diff --git a/Lang/0815/00DESCRIPTION b/Lang/0815/00DESCRIPTION index 836363472e..53327ee7f6 100644 --- a/Lang/0815/00DESCRIPTION +++ b/Lang/0815/00DESCRIPTION @@ -1,9 +1,9 @@ {{language|0815}} -'''0815''' is an esoteric programming language designed and implemented between December 2012 and January 2013 by [[Paulo Jorente]] +'''0815''' is an esoteric programming language designed and implemented between December 2012 and January 2013 by [[Paulo Jorente]]. ==See also== * [http://esolangs.org/wiki/0815 0815 Esolangs] – 0815 on Esolangs -* [http://pjorente.pj.funpic.de/poncho/esolang/ 0815 page] – features specs, programs and an interpreter. +* [http://paulo-jorente.de/poncho/esolang/0815 0815 page] – features specs, programs and an interpreter. [[Category:Esoteric_Languages]] \ No newline at end of file diff --git a/Lang/0815/Averages-Arithmetic-mean b/Lang/0815/Averages-Arithmetic-mean new file mode 120000 index 0000000000..07f9d30c36 --- /dev/null +++ b/Lang/0815/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/0815 \ No newline at end of file diff --git a/Lang/0815/Sum-of-squares b/Lang/0815/Sum-of-squares new file mode 120000 index 0000000000..1788a50c04 --- /dev/null +++ b/Lang/0815/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/0815 \ No newline at end of file diff --git a/Lang/360-Assembly/00DESCRIPTION b/Lang/360-Assembly/00DESCRIPTION index d10d4b2ac3..d3a26430c9 100644 --- a/Lang/360-Assembly/00DESCRIPTION +++ b/Lang/360-Assembly/00DESCRIPTION @@ -16,4 +16,4 @@ themselves in popular use to all assembly-language dialects on the System/360 an its descendants. The 360 assembly was introduced with the System/360 in 1964. ==Wikipedia article== -http://en.wikipedia.org/wiki/IBM_Basic_assembly_language_and_successors \ No newline at end of file +[[wp:IBM_Basic_assembly_language_and_successors|IBM Basic assembly language and successors]] \ No newline at end of file diff --git a/Lang/360-Assembly/100-doors b/Lang/360-Assembly/100-doors new file mode 120000 index 0000000000..6f3c851cf9 --- /dev/null +++ b/Lang/360-Assembly/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/A+B b/Lang/360-Assembly/A+B new file mode 120000 index 0000000000..e6c8bfe1de --- /dev/null +++ b/Lang/360-Assembly/A+B @@ -0,0 +1 @@ +../../Task/A+B/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Ackermann-function b/Lang/360-Assembly/Ackermann-function new file mode 120000 index 0000000000..e15181ac04 --- /dev/null +++ b/Lang/360-Assembly/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Arithmetic-Integer b/Lang/360-Assembly/Arithmetic-Integer new file mode 120000 index 0000000000..c64aea927a --- /dev/null +++ b/Lang/360-Assembly/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Arithmetic-geometric-mean b/Lang/360-Assembly/Arithmetic-geometric-mean new file mode 120000 index 0000000000..0f819e5fba --- /dev/null +++ b/Lang/360-Assembly/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Arrays b/Lang/360-Assembly/Arrays new file mode 120000 index 0000000000..4c3d579fe8 --- /dev/null +++ b/Lang/360-Assembly/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Averages-Arithmetic-mean b/Lang/360-Assembly/Averages-Arithmetic-mean new file mode 120000 index 0000000000..61d641811f --- /dev/null +++ b/Lang/360-Assembly/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Averages-Simple-moving-average b/Lang/360-Assembly/Averages-Simple-moving-average new file mode 120000 index 0000000000..25d527df2f --- /dev/null +++ b/Lang/360-Assembly/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Binary-digits b/Lang/360-Assembly/Binary-digits new file mode 120000 index 0000000000..ac298c2227 --- /dev/null +++ b/Lang/360-Assembly/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Catalan-numbers b/Lang/360-Assembly/Catalan-numbers new file mode 120000 index 0000000000..77f4260b22 --- /dev/null +++ b/Lang/360-Assembly/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Chinese-remainder-theorem b/Lang/360-Assembly/Chinese-remainder-theorem new file mode 120000 index 0000000000..42f5fa69bf --- /dev/null +++ b/Lang/360-Assembly/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Count-the-coins b/Lang/360-Assembly/Count-the-coins new file mode 120000 index 0000000000..24685dfc91 --- /dev/null +++ b/Lang/360-Assembly/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Evaluate-binomial-coefficients b/Lang/360-Assembly/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..4d2d6cb026 --- /dev/null +++ b/Lang/360-Assembly/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Factors-of-a-Mersenne-number b/Lang/360-Assembly/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..6a635338e7 --- /dev/null +++ b/Lang/360-Assembly/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Function-definition b/Lang/360-Assembly/Function-definition new file mode 120000 index 0000000000..bb7ec19835 --- /dev/null +++ b/Lang/360-Assembly/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Hailstone-sequence b/Lang/360-Assembly/Hailstone-sequence new file mode 120000 index 0000000000..84496b6ba8 --- /dev/null +++ b/Lang/360-Assembly/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Horners-rule-for-polynomial-evaluation b/Lang/360-Assembly/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..4ffc66358e --- /dev/null +++ b/Lang/360-Assembly/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Include-a-file b/Lang/360-Assembly/Include-a-file new file mode 120000 index 0000000000..134f2215e0 --- /dev/null +++ b/Lang/360-Assembly/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Leap-year b/Lang/360-Assembly/Leap-year new file mode 120000 index 0000000000..f6a457ad14 --- /dev/null +++ b/Lang/360-Assembly/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Long-multiplication b/Lang/360-Assembly/Long-multiplication new file mode 120000 index 0000000000..5ce37c21e8 --- /dev/null +++ b/Lang/360-Assembly/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-Continue b/Lang/360-Assembly/Loops-Continue new file mode 120000 index 0000000000..d5b27740db --- /dev/null +++ b/Lang/360-Assembly/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-Downward-for b/Lang/360-Assembly/Loops-Downward-for new file mode 120000 index 0000000000..63f5bc5a5c --- /dev/null +++ b/Lang/360-Assembly/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-For b/Lang/360-Assembly/Loops-For new file mode 120000 index 0000000000..d7f91eccec --- /dev/null +++ b/Lang/360-Assembly/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-For-with-a-specified-step b/Lang/360-Assembly/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..8c1ed99d2b --- /dev/null +++ b/Lang/360-Assembly/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-N-plus-one-half b/Lang/360-Assembly/Loops-N-plus-one-half new file mode 120000 index 0000000000..03322e5d52 --- /dev/null +++ b/Lang/360-Assembly/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-Nested b/Lang/360-Assembly/Loops-Nested new file mode 120000 index 0000000000..d05cbad41b --- /dev/null +++ b/Lang/360-Assembly/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Matrix-multiplication b/Lang/360-Assembly/Matrix-multiplication new file mode 120000 index 0000000000..cff4346bfb --- /dev/null +++ b/Lang/360-Assembly/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Multiplication-tables b/Lang/360-Assembly/Multiplication-tables new file mode 120000 index 0000000000..b0902653ee --- /dev/null +++ b/Lang/360-Assembly/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/N-queens-problem b/Lang/360-Assembly/N-queens-problem new file mode 120000 index 0000000000..21c61c526b --- /dev/null +++ b/Lang/360-Assembly/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Pangram-checker b/Lang/360-Assembly/Pangram-checker new file mode 120000 index 0000000000..7b6b3c3537 --- /dev/null +++ b/Lang/360-Assembly/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Prime-decomposition b/Lang/360-Assembly/Prime-decomposition new file mode 120000 index 0000000000..640ef5e9c1 --- /dev/null +++ b/Lang/360-Assembly/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Reduced-row-echelon-form b/Lang/360-Assembly/Reduced-row-echelon-form new file mode 120000 index 0000000000..2667f4ec12 --- /dev/null +++ b/Lang/360-Assembly/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Sorting-algorithms-Quicksort b/Lang/360-Assembly/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..c73e40b6d2 --- /dev/null +++ b/Lang/360-Assembly/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/String-case b/Lang/360-Assembly/String-case new file mode 120000 index 0000000000..fefea3c989 --- /dev/null +++ b/Lang/360-Assembly/String-case @@ -0,0 +1 @@ +../../Task/String-case/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Sum-of-squares b/Lang/360-Assembly/Sum-of-squares new file mode 120000 index 0000000000..83dde9dd36 --- /dev/null +++ b/Lang/360-Assembly/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Temperature-conversion b/Lang/360-Assembly/Temperature-conversion new file mode 120000 index 0000000000..e3c6ac1f55 --- /dev/null +++ b/Lang/360-Assembly/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Towers-of-Hanoi b/Lang/360-Assembly/Towers-of-Hanoi new file mode 120000 index 0000000000..8f9dd0fd19 --- /dev/null +++ b/Lang/360-Assembly/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Zig-zag-matrix b/Lang/360-Assembly/Zig-zag-matrix new file mode 120000 index 0000000000..f720f5e840 --- /dev/null +++ b/Lang/360-Assembly/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/360-Assembly \ No newline at end of file diff --git a/Lang/80386-Assembly/00DESCRIPTION b/Lang/80386-Assembly/00DESCRIPTION index ef755eace2..e9fba32460 100644 --- a/Lang/80386-Assembly/00DESCRIPTION +++ b/Lang/80386-Assembly/00DESCRIPTION @@ -1,2 +1,4 @@ {{language}}{{assembler language}}{{stub}} -80386 assembly is assembly for the Intel 80386 the predecessor of the 80486 it is an early 16/32 bit Intel processor Wikipedia has a page on it [https://en.wikipedia.org/wiki/Intel_80386] on their is an example code \ No newline at end of file +80386 assembly is assembly for the Intel 80386 the predecessor of the 80486 it is an early 16/32 bit Intel processor Wikipedia has a page on it [https://en.wikipedia.org/wiki/Intel_80386] on their is an example code + +[[category: x86 Assembly]] \ No newline at end of file diff --git a/Lang/8086-Assembly/00DESCRIPTION b/Lang/8086-Assembly/00DESCRIPTION index 16e1928b2b..e65ae40d39 100644 --- a/Lang/8086-Assembly/00DESCRIPTION +++ b/Lang/8086-Assembly/00DESCRIPTION @@ -1 +1,3 @@ -{{Stub}}{{language}}{{assembler language}}[[Category:Assembly]]8086 Assembly is the assembly language used by the Intel 8086 processor. This processor was used for the first time in the IBM PC, and in its various clones. The 8086 gave birth, starting with the 80186 processor, to the X86 family, that nowadays is the most used processor family in desktop computers. All the 32 and 64 bit processors from this family are able to operate in a 8086 compatibility mode, for backward compatibility with legacy software and running very low-level code (like the BIOS). For the evolution of this assembly implementation to 32 bits, see [[X86 assembly]]. \ No newline at end of file +{{Stub}}{{language}}{{assembler language}}[[Category:Assembly]]8086 Assembly is the assembly language used by the Intel 8086 processor. This processor was used for the first time in the IBM PC, and in its various clones. The 8086 gave birth, starting with the 80186 processor, to the X86 family, that nowadays is the most used processor family in desktop computers. All the 32 and 64 bit processors from this family are able to operate in a 8086 compatibility mode, for backward compatibility with legacy software and running very low-level code (like the BIOS). For the evolution of this assembly implementation to 32 bits, see [[X86 assembly]]. + +[[category: x86 Assembly]] \ No newline at end of file diff --git a/Lang/ABAP/Arrays b/Lang/ABAP/Arrays new file mode 120000 index 0000000000..fe4c93f72a --- /dev/null +++ b/Lang/ABAP/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Balanced-brackets b/Lang/ABAP/Balanced-brackets new file mode 120000 index 0000000000..6f28d04cd3 --- /dev/null +++ b/Lang/ABAP/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Break-OO-privacy b/Lang/ABAP/Break-OO-privacy new file mode 120000 index 0000000000..2a5082ba8a --- /dev/null +++ b/Lang/ABAP/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Collections b/Lang/ABAP/Collections new file mode 120000 index 0000000000..3e1063b080 --- /dev/null +++ b/Lang/ABAP/Collections @@ -0,0 +1 @@ +../../Task/Collections/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Evaluate-binomial-coefficients b/Lang/ABAP/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..0b3b8d8e9c --- /dev/null +++ b/Lang/ABAP/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Even-or-odd b/Lang/ABAP/Even-or-odd new file mode 120000 index 0000000000..c7dc7da38b --- /dev/null +++ b/Lang/ABAP/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/ABAP \ No newline at end of file diff --git a/Lang/ABAP/FizzBuzz b/Lang/ABAP/FizzBuzz new file mode 120000 index 0000000000..9084fc393e --- /dev/null +++ b/Lang/ABAP/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Generate-lower-case-ASCII-alphabet b/Lang/ABAP/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..516b6798cb --- /dev/null +++ b/Lang/ABAP/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Hailstone-sequence b/Lang/ABAP/Hailstone-sequence new file mode 120000 index 0000000000..ced89da742 --- /dev/null +++ b/Lang/ABAP/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/ABAP \ No newline at end of file diff --git a/Lang/ABAP/List-comprehensions b/Lang/ABAP/List-comprehensions new file mode 120000 index 0000000000..da11fc6598 --- /dev/null +++ b/Lang/ABAP/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Ludic-numbers b/Lang/ABAP/Ludic-numbers new file mode 120000 index 0000000000..105437c21f --- /dev/null +++ b/Lang/ABAP/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Regular-expressions b/Lang/ABAP/Regular-expressions new file mode 120000 index 0000000000..079b933a2e --- /dev/null +++ b/Lang/ABAP/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Show-the-epoch b/Lang/ABAP/Show-the-epoch new file mode 120000 index 0000000000..e6fd1ed572 --- /dev/null +++ b/Lang/ABAP/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Sieve-of-Eratosthenes b/Lang/ABAP/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..27c30a346b --- /dev/null +++ b/Lang/ABAP/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/ABAP \ No newline at end of file diff --git a/Lang/ABAP/String-concatenation b/Lang/ABAP/String-concatenation new file mode 120000 index 0000000000..8d126296d0 --- /dev/null +++ b/Lang/ABAP/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/ABAP \ No newline at end of file diff --git a/Lang/ABAP/URL-decoding b/Lang/ABAP/URL-decoding new file mode 120000 index 0000000000..c02f11194c --- /dev/null +++ b/Lang/ABAP/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/ABAP \ No newline at end of file diff --git a/Lang/ABAP/XML-DOM-serialization b/Lang/ABAP/XML-DOM-serialization new file mode 120000 index 0000000000..5a9b1d4f7d --- /dev/null +++ b/Lang/ABAP/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/ABAP \ No newline at end of file diff --git a/Lang/ALGOL-60/00DESCRIPTION b/Lang/ALGOL-60/00DESCRIPTION index e246651bcd..6f0071b0f6 100644 --- a/Lang/ALGOL-60/00DESCRIPTION +++ b/Lang/ALGOL-60/00DESCRIPTION @@ -1,4 +1,5 @@ {{stub}}{{language|bnf=http://www.masswerk.at/algol60/syntax.txt}} ==See also== *[[wp:ALGOL|ALGOL 60 on Wikipedia]] -*[[ALGOL 68]] \ No newline at end of file +*[[ALGOL 68]] +*[[ALGOL W]] \ No newline at end of file diff --git a/Lang/ALGOL-68/00DESCRIPTION b/Lang/ALGOL-68/00DESCRIPTION index 25aef9e3ca..0fd2841a32 100644 --- a/Lang/ALGOL-68/00DESCRIPTION +++ b/Lang/ALGOL-68/00DESCRIPTION @@ -90,10 +90,21 @@ not too much else is required. Examples: |} ===Example of different program representations=== At the time when ALGOL 68 was defined some predominant computers had -36 bit words, and 6 bit character sets. Hence it was desirable that -ALGOL 68 should be able to run on machines with only uppercase. Hence -the official spec provided for different representations of the same -program. Example: +24 or 36 bit words, with 6 bit character sets. Hence it was desirable that +ALGOL 68 should be able to run on machines with only uppercase. +The official spec provided for different representations of the same +program. Quote stropping (enclosing the bold words in single quotes) +and Point stropping (preceeding the bold words with a dot) +were used. A variant of Point stropping called RES stropping was also defined. +In RES stropping some language-defined bold words are not preceded by a dot. +A pragmatic comment may have been required to indicate which +stropping convention was to be used, as in some of the examples below. +Upper stropping (representing the bold words by upper case and +non-bold words in lower case) was introduced by Algol 68R. Upper stropping +is used by Algol 68RS and is one of the options for Algol 68G. +Rutgers ALGOL 68 uses quote stropping. Most of the samples +on Rosetta Code use Upper stropping. +Example: {|border="1" style="border-collapse: collapse; border: 5px double grey;" align="center" || Algol68 as typically published ¢ bold/underline typeface ¢ @@ -113,7 +124,7 @@ program. Example: 'do' sum sq+:=i↑2 'od' -|| Code for a 7-bit/ascii compiler +|| 7-bit/ascii compiler .PR UPPER .PR MODE XINT = INT; XINT sum sq:=0; @@ -122,7 +133,7 @@ program. Example: DO sum sq+:=i**2 OD -|| Code for a 6-bits/byte compiler +|| 6-bits/byte compiler .PR POINT .PR .MODE .XINT = .INT; .XINT SUM SQ:=0; @@ -131,7 +142,7 @@ program. Example: .DO SUM SQ .PLUSAB I .UP 2 .OD -|| Algol68 using RES stropping +|| RES stropping .PR RES .PR mode .xint = int; .xint sum sq:=0; @@ -140,6 +151,15 @@ program. Example: do sum sq+:=i↑2 od +|| Upper stropping + # upper case = bold # + MODE XINT = INT; + XINT sum sq:=0; + FOR i WHILE + sum sq /= 70*70 + DO + sum sq PLUSAB i UP 2 + OD |} == Coercion (casting) == @@ -241,6 +261,10 @@ t |} For more details about Primaries and Secondaries refer to [[Operator_precedence#ALGOL_68|Operator precedence]]. +==See also== +*[[Web 68]] +*[[ALGOL 60]] +*[[ALGOL W]] == Code Specimen == {{language programming paradigm|Concurrent}} {{language programming paradigm|Imperative}} \ No newline at end of file diff --git a/Lang/ALGOL-68/ABC-Problem b/Lang/ALGOL-68/ABC-Problem new file mode 120000 index 0000000000..ffa9c84cdb --- /dev/null +++ b/Lang/ALGOL-68/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/AKS-test-for-primes b/Lang/ALGOL-68/AKS-test-for-primes new file mode 120000 index 0000000000..9295affcc7 --- /dev/null +++ b/Lang/ALGOL-68/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Almost-prime b/Lang/ALGOL-68/Almost-prime new file mode 120000 index 0000000000..65ae9bf05a --- /dev/null +++ b/Lang/ALGOL-68/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Arbitrary-precision-integers--included- b/Lang/ALGOL-68/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..c68ab1bec6 --- /dev/null +++ b/Lang/ALGOL-68/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Arithmetic-geometric-mean b/Lang/ALGOL-68/Arithmetic-geometric-mean new file mode 120000 index 0000000000..f8015e83d8 --- /dev/null +++ b/Lang/ALGOL-68/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Averages-Median b/Lang/ALGOL-68/Averages-Median new file mode 120000 index 0000000000..4bd97332d1 --- /dev/null +++ b/Lang/ALGOL-68/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Balanced-brackets b/Lang/ALGOL-68/Balanced-brackets new file mode 120000 index 0000000000..21c8de0af3 --- /dev/null +++ b/Lang/ALGOL-68/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/CRC-32 b/Lang/ALGOL-68/CRC-32 new file mode 120000 index 0000000000..239675f86a --- /dev/null +++ b/Lang/ALGOL-68/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/CSV-data-manipulation b/Lang/ALGOL-68/CSV-data-manipulation new file mode 120000 index 0000000000..9207093665 --- /dev/null +++ b/Lang/ALGOL-68/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Call-a-foreign-language-function b/Lang/ALGOL-68/Call-a-foreign-language-function new file mode 120000 index 0000000000..1db8f7e986 --- /dev/null +++ b/Lang/ALGOL-68/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Comma-quibbling b/Lang/ALGOL-68/Comma-quibbling new file mode 120000 index 0000000000..977ee0e5ae --- /dev/null +++ b/Lang/ALGOL-68/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Continued-fraction b/Lang/ALGOL-68/Continued-fraction new file mode 120000 index 0000000000..ccf03e7277 --- /dev/null +++ b/Lang/ALGOL-68/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Count-in-factors b/Lang/ALGOL-68/Count-in-factors new file mode 120000 index 0000000000..ac2ab8e64d --- /dev/null +++ b/Lang/ALGOL-68/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Delegates b/Lang/ALGOL-68/Delegates new file mode 120000 index 0000000000..e02e620e0c --- /dev/null +++ b/Lang/ALGOL-68/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Doubly-linked-list-Traversal b/Lang/ALGOL-68/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..394aec05b5 --- /dev/null +++ b/Lang/ALGOL-68/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Empty-string b/Lang/ALGOL-68/Empty-string new file mode 120000 index 0000000000..ab6b3db48f --- /dev/null +++ b/Lang/ALGOL-68/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/File-modification-time b/Lang/ALGOL-68/File-modification-time new file mode 120000 index 0000000000..b6d68ff700 --- /dev/null +++ b/Lang/ALGOL-68/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Find-limit-of-recursion b/Lang/ALGOL-68/Find-limit-of-recursion new file mode 120000 index 0000000000..282351a48a --- /dev/null +++ b/Lang/ALGOL-68/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Gray-code b/Lang/ALGOL-68/Gray-code new file mode 120000 index 0000000000..6ac0fbdc7d --- /dev/null +++ b/Lang/ALGOL-68/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Harshad-or-Niven-series b/Lang/ALGOL-68/Harshad-or-Niven-series new file mode 120000 index 0000000000..3e5e2d273c --- /dev/null +++ b/Lang/ALGOL-68/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Hello-world-Line-printer b/Lang/ALGOL-68/Hello-world-Line-printer new file mode 120000 index 0000000000..1b13ef8cf3 --- /dev/null +++ b/Lang/ALGOL-68/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Integer-overflow b/Lang/ALGOL-68/Integer-overflow new file mode 120000 index 0000000000..c3c07cd11b --- /dev/null +++ b/Lang/ALGOL-68/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Josephus-problem b/Lang/ALGOL-68/Josephus-problem new file mode 120000 index 0000000000..25a6e76bc3 --- /dev/null +++ b/Lang/ALGOL-68/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Least-common-multiple b/Lang/ALGOL-68/Least-common-multiple new file mode 120000 index 0000000000..0cce523556 --- /dev/null +++ b/Lang/ALGOL-68/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Letter-frequency b/Lang/ALGOL-68/Letter-frequency new file mode 120000 index 0000000000..b958f3ce2a --- /dev/null +++ b/Lang/ALGOL-68/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Linear-congruential-generator b/Lang/ALGOL-68/Linear-congruential-generator new file mode 120000 index 0000000000..fc52a29369 --- /dev/null +++ b/Lang/ALGOL-68/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Longest-string-challenge b/Lang/ALGOL-68/Longest-string-challenge new file mode 120000 index 0000000000..eb27a2a535 --- /dev/null +++ b/Lang/ALGOL-68/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/MD5 b/Lang/ALGOL-68/MD5 new file mode 120000 index 0000000000..3e10599a1e --- /dev/null +++ b/Lang/ALGOL-68/MD5 @@ -0,0 +1 @@ +../../Task/MD5/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Metaprogramming b/Lang/ALGOL-68/Metaprogramming new file mode 120000 index 0000000000..5350662d0a --- /dev/null +++ b/Lang/ALGOL-68/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Modular-exponentiation b/Lang/ALGOL-68/Modular-exponentiation new file mode 120000 index 0000000000..c5af5e071f --- /dev/null +++ b/Lang/ALGOL-68/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Modular-inverse b/Lang/ALGOL-68/Modular-inverse new file mode 120000 index 0000000000..ee90cf6ff2 --- /dev/null +++ b/Lang/ALGOL-68/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Multifactorial b/Lang/ALGOL-68/Multifactorial new file mode 120000 index 0000000000..8ed5c64a3d --- /dev/null +++ b/Lang/ALGOL-68/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/One-of-n-lines-in-a-file b/Lang/ALGOL-68/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..790f480ac6 --- /dev/null +++ b/Lang/ALGOL-68/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Parsing-RPN-to-infix-conversion b/Lang/ALGOL-68/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..ba79cec5d0 --- /dev/null +++ b/Lang/ALGOL-68/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Phrase-reversals b/Lang/ALGOL-68/Phrase-reversals new file mode 120000 index 0000000000..be4598251f --- /dev/null +++ b/Lang/ALGOL-68/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Polymorphism b/Lang/ALGOL-68/Polymorphism new file mode 120000 index 0000000000..73cef899ae --- /dev/null +++ b/Lang/ALGOL-68/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Program-name b/Lang/ALGOL-68/Program-name new file mode 120000 index 0000000000..8306354f52 --- /dev/null +++ b/Lang/ALGOL-68/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/RSA-code b/Lang/ALGOL-68/RSA-code new file mode 120000 index 0000000000..3d00e4b094 --- /dev/null +++ b/Lang/ALGOL-68/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Runge-Kutta-method b/Lang/ALGOL-68/Runge-Kutta-method new file mode 120000 index 0000000000..3d96c62861 --- /dev/null +++ b/Lang/ALGOL-68/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Heapsort b/Lang/ALGOL-68/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..8eb94ff2f4 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Pancake-sort b/Lang/ALGOL-68/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..df7660c18b --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sorting-algorithms-Radix-sort b/Lang/ALGOL-68/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..d77167c0d8 --- /dev/null +++ b/Lang/ALGOL-68/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Temperature-conversion b/Lang/ALGOL-68/Temperature-conversion new file mode 120000 index 0000000000..4aae7c5f25 --- /dev/null +++ b/Lang/ALGOL-68/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/00DESCRIPTION b/Lang/ALGOL-W/00DESCRIPTION index fbd35eb835..c03423d718 100644 --- a/Lang/ALGOL-W/00DESCRIPTION +++ b/Lang/ALGOL-W/00DESCRIPTION @@ -3,7 +3,7 @@ |strength=strong |safety=safe |express=explicit -|compat=structural +|compat=nominative |checking=both |LCT=yes}} Algol W is a successor to [[wp:Algol 60|Algol 60]] closely based on A @@ -27,6 +27,9 @@ aw2c correctly compiles Tony Marsland's computer [[wp:chess|chess]] player and Hendrik Boom's [http://mtn-host.prjek.net/projects/a68h/ A68H] [[Algol 68]] compiler. +==See also== +*[[ALGOL 60]] +*[[ALGOL 68]] == Code Specimen == {{language programming paradigm|Concurrent}} {{stub}} \ No newline at end of file diff --git a/Lang/ALGOL-W/100-doors b/Lang/ALGOL-W/100-doors new file mode 120000 index 0000000000..954c02976a --- /dev/null +++ b/Lang/ALGOL-W/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/A+B b/Lang/ALGOL-W/A+B new file mode 120000 index 0000000000..4231b03087 --- /dev/null +++ b/Lang/ALGOL-W/A+B @@ -0,0 +1 @@ +../../Task/A+B/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/ABC-Problem b/Lang/ALGOL-W/ABC-Problem new file mode 120000 index 0000000000..ae1a0587c7 --- /dev/null +++ b/Lang/ALGOL-W/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Assertions b/Lang/ALGOL-W/Assertions new file mode 120000 index 0000000000..5c0f8ceba2 --- /dev/null +++ b/Lang/ALGOL-W/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Averages-Arithmetic-mean b/Lang/ALGOL-W/Averages-Arithmetic-mean new file mode 120000 index 0000000000..ba937d8c51 --- /dev/null +++ b/Lang/ALGOL-W/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Averages-Root-mean-square b/Lang/ALGOL-W/Averages-Root-mean-square new file mode 120000 index 0000000000..660112a456 --- /dev/null +++ b/Lang/ALGOL-W/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Binary-digits b/Lang/ALGOL-W/Binary-digits new file mode 120000 index 0000000000..886ebfed71 --- /dev/null +++ b/Lang/ALGOL-W/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Case-sensitivity-of-identifiers b/Lang/ALGOL-W/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..3b105677dc --- /dev/null +++ b/Lang/ALGOL-W/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Character-codes b/Lang/ALGOL-W/Character-codes new file mode 120000 index 0000000000..2f999b77ac --- /dev/null +++ b/Lang/ALGOL-W/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Comma-quibbling b/Lang/ALGOL-W/Comma-quibbling new file mode 120000 index 0000000000..5dab56cd9f --- /dev/null +++ b/Lang/ALGOL-W/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Conditional-structures b/Lang/ALGOL-W/Conditional-structures new file mode 120000 index 0000000000..e48e47aa28 --- /dev/null +++ b/Lang/ALGOL-W/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Copy-a-string b/Lang/ALGOL-W/Copy-a-string new file mode 120000 index 0000000000..4a449ab936 --- /dev/null +++ b/Lang/ALGOL-W/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Create-a-two-dimensional-array-at-runtime b/Lang/ALGOL-W/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..688743f68e --- /dev/null +++ b/Lang/ALGOL-W/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Determine-if-a-string-is-numeric b/Lang/ALGOL-W/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..c15b4df3f0 --- /dev/null +++ b/Lang/ALGOL-W/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Digital-root b/Lang/ALGOL-W/Digital-root new file mode 120000 index 0000000000..e53284508b --- /dev/null +++ b/Lang/ALGOL-W/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Dot-product b/Lang/ALGOL-W/Dot-product new file mode 120000 index 0000000000..2590fb3bb5 --- /dev/null +++ b/Lang/ALGOL-W/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Empty-program b/Lang/ALGOL-W/Empty-program new file mode 120000 index 0000000000..3ce91cbd53 --- /dev/null +++ b/Lang/ALGOL-W/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Entropy b/Lang/ALGOL-W/Entropy new file mode 120000 index 0000000000..dd7b4f6540 --- /dev/null +++ b/Lang/ALGOL-W/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Evaluate-binomial-coefficients b/Lang/ALGOL-W/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..9b5be748a0 --- /dev/null +++ b/Lang/ALGOL-W/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Even-or-odd b/Lang/ALGOL-W/Even-or-odd new file mode 120000 index 0000000000..30f1e1edcf --- /dev/null +++ b/Lang/ALGOL-W/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Factorial b/Lang/ALGOL-W/Factorial new file mode 120000 index 0000000000..01c77fb141 --- /dev/null +++ b/Lang/ALGOL-W/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/FizzBuzz b/Lang/ALGOL-W/FizzBuzz new file mode 120000 index 0000000000..7dc22afc16 --- /dev/null +++ b/Lang/ALGOL-W/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Function-definition b/Lang/ALGOL-W/Function-definition new file mode 120000 index 0000000000..defddbebcd --- /dev/null +++ b/Lang/ALGOL-W/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Greatest-common-divisor b/Lang/ALGOL-W/Greatest-common-divisor new file mode 120000 index 0000000000..917e358372 --- /dev/null +++ b/Lang/ALGOL-W/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Greatest-element-of-a-list b/Lang/ALGOL-W/Greatest-element-of-a-list new file mode 120000 index 0000000000..053195a692 --- /dev/null +++ b/Lang/ALGOL-W/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Hello-world-Text b/Lang/ALGOL-W/Hello-world-Text new file mode 120000 index 0000000000..b2ac78fddf --- /dev/null +++ b/Lang/ALGOL-W/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Integer-comparison b/Lang/ALGOL-W/Integer-comparison new file mode 120000 index 0000000000..b056aab0f7 --- /dev/null +++ b/Lang/ALGOL-W/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Least-common-multiple b/Lang/ALGOL-W/Least-common-multiple new file mode 120000 index 0000000000..a17aa34bbd --- /dev/null +++ b/Lang/ALGOL-W/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Literals-Floating-point b/Lang/ALGOL-W/Literals-Floating-point new file mode 120000 index 0000000000..2b055c4570 --- /dev/null +++ b/Lang/ALGOL-W/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Literals-String b/Lang/ALGOL-W/Literals-String new file mode 120000 index 0000000000..5dbf9dd034 --- /dev/null +++ b/Lang/ALGOL-W/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Logical-operations b/Lang/ALGOL-W/Logical-operations new file mode 120000 index 0000000000..e8edad6a93 --- /dev/null +++ b/Lang/ALGOL-W/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loop-over-multiple-arrays-simultaneously b/Lang/ALGOL-W/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..1d5393884b --- /dev/null +++ b/Lang/ALGOL-W/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loops-Do-while b/Lang/ALGOL-W/Loops-Do-while new file mode 120000 index 0000000000..a93e333758 --- /dev/null +++ b/Lang/ALGOL-W/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loops-Downward-for b/Lang/ALGOL-W/Loops-Downward-for new file mode 120000 index 0000000000..22845dae11 --- /dev/null +++ b/Lang/ALGOL-W/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loops-For b/Lang/ALGOL-W/Loops-For new file mode 120000 index 0000000000..6119bf8da2 --- /dev/null +++ b/Lang/ALGOL-W/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loops-For-with-a-specified-step b/Lang/ALGOL-W/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..62ca3c4cd9 --- /dev/null +++ b/Lang/ALGOL-W/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loops-Infinite b/Lang/ALGOL-W/Loops-Infinite new file mode 120000 index 0000000000..af50df9a8c --- /dev/null +++ b/Lang/ALGOL-W/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loops-N-plus-one-half b/Lang/ALGOL-W/Loops-N-plus-one-half new file mode 120000 index 0000000000..ad9101d821 --- /dev/null +++ b/Lang/ALGOL-W/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Loops-While b/Lang/ALGOL-W/Loops-While new file mode 120000 index 0000000000..68a19ca6f0 --- /dev/null +++ b/Lang/ALGOL-W/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Magic-squares-of-odd-order b/Lang/ALGOL-W/Magic-squares-of-odd-order new file mode 120000 index 0000000000..9aad245b8a --- /dev/null +++ b/Lang/ALGOL-W/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Multiplication-tables b/Lang/ALGOL-W/Multiplication-tables new file mode 120000 index 0000000000..cf1047dc45 --- /dev/null +++ b/Lang/ALGOL-W/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Mutual-recursion b/Lang/ALGOL-W/Mutual-recursion new file mode 120000 index 0000000000..c216cc9515 --- /dev/null +++ b/Lang/ALGOL-W/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Non-decimal-radices-Convert b/Lang/ALGOL-W/Non-decimal-radices-Convert new file mode 120000 index 0000000000..fafa9c4b73 --- /dev/null +++ b/Lang/ALGOL-W/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Null-object b/Lang/ALGOL-W/Null-object new file mode 120000 index 0000000000..1114cc3088 --- /dev/null +++ b/Lang/ALGOL-W/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Quaternion-type b/Lang/ALGOL-W/Quaternion-type new file mode 120000 index 0000000000..9f1593930d --- /dev/null +++ b/Lang/ALGOL-W/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Roman-numerals-Decode b/Lang/ALGOL-W/Roman-numerals-Decode new file mode 120000 index 0000000000..22e94bd34b --- /dev/null +++ b/Lang/ALGOL-W/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Short-circuit-evaluation b/Lang/ALGOL-W/Short-circuit-evaluation new file mode 120000 index 0000000000..dfaf878ec5 --- /dev/null +++ b/Lang/ALGOL-W/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sieve-of-Eratosthenes b/Lang/ALGOL-W/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..331ea9fce4 --- /dev/null +++ b/Lang/ALGOL-W/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Singly-linked-list-Element-definition b/Lang/ALGOL-W/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..0f6773c9d7 --- /dev/null +++ b/Lang/ALGOL-W/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Singly-linked-list-Element-insertion b/Lang/ALGOL-W/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..918e7e47a7 --- /dev/null +++ b/Lang/ALGOL-W/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Singly-linked-list-Traversal b/Lang/ALGOL-W/Singly-linked-list-Traversal new file mode 120000 index 0000000000..f51fd0957e --- /dev/null +++ b/Lang/ALGOL-W/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sorting-algorithms-Bubble-sort b/Lang/ALGOL-W/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..fdbe7edb85 --- /dev/null +++ b/Lang/ALGOL-W/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sorting-algorithms-Cocktail-sort b/Lang/ALGOL-W/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..d88d538db8 --- /dev/null +++ b/Lang/ALGOL-W/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Standard-deviation b/Lang/ALGOL-W/Standard-deviation new file mode 120000 index 0000000000..745c6dedc7 --- /dev/null +++ b/Lang/ALGOL-W/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/String-case b/Lang/ALGOL-W/String-case new file mode 120000 index 0000000000..a70c653bfb --- /dev/null +++ b/Lang/ALGOL-W/String-case @@ -0,0 +1 @@ +../../Task/String-case/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sum-and-product-of-an-array b/Lang/ALGOL-W/Sum-and-product-of-an-array new file mode 120000 index 0000000000..671d6a8c8b --- /dev/null +++ b/Lang/ALGOL-W/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sum-of-squares b/Lang/ALGOL-W/Sum-of-squares new file mode 120000 index 0000000000..62fd8f0791 --- /dev/null +++ b/Lang/ALGOL-W/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Tic-tac-toe b/Lang/ALGOL-W/Tic-tac-toe new file mode 120000 index 0000000000..5abb694502 --- /dev/null +++ b/Lang/ALGOL-W/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Towers-of-Hanoi b/Lang/ALGOL-W/Towers-of-Hanoi new file mode 120000 index 0000000000..5bf422a247 --- /dev/null +++ b/Lang/ALGOL-W/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Trabb-Pardo-Knuth-algorithm b/Lang/ALGOL-W/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..bb039e7ee3 --- /dev/null +++ b/Lang/ALGOL-W/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Trigonometric-functions b/Lang/ALGOL-W/Trigonometric-functions new file mode 120000 index 0000000000..fb9e7d7b71 --- /dev/null +++ b/Lang/ALGOL-W/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Twelve-statements b/Lang/ALGOL-W/Twelve-statements new file mode 120000 index 0000000000..c43cc50944 --- /dev/null +++ b/Lang/ALGOL-W/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Variables b/Lang/ALGOL-W/Variables new file mode 120000 index 0000000000..6942cfae1c --- /dev/null +++ b/Lang/ALGOL-W/Variables @@ -0,0 +1 @@ +../../Task/Variables/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Vector-products b/Lang/ALGOL-W/Vector-products new file mode 120000 index 0000000000..87cbee3477 --- /dev/null +++ b/Lang/ALGOL-W/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/ALGOL-W \ No newline at end of file diff --git a/Lang/APL/00DESCRIPTION b/Lang/APL/00DESCRIPTION index 2252da77e4..4dcccc8786 100644 --- a/Lang/APL/00DESCRIPTION +++ b/Lang/APL/00DESCRIPTION @@ -1,4 +1,8 @@ -{{stub}}{{language|APL +{{language|APL |checking=dynamic}}{{language programming paradigm|functional}} -APL is an array oriented interactive programming language and integrated development environment. \ No newline at end of file +APL (A Programming Language) is an [[wp:Array_programming|array oriented]], [[Functional_programming|functional]], interactive programming language created and developed by [[wp:Kenneth_E._Iverson|Kenneth Iverson]] in the 1960's. It uses a large range of special graphic symbols to represent functions and operators, giving very concise code.[[wp:APL_(programming_language)|APL Wikipedia Entry]] It influenced many other programming languages such as [[J]] and [[Mathematica]]. + +== References == + + \ No newline at end of file diff --git a/Lang/APL/Conways-Game-of-Life b/Lang/APL/Conways-Game-of-Life new file mode 120000 index 0000000000..0fa0988c59 --- /dev/null +++ b/Lang/APL/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/APL \ No newline at end of file diff --git a/Lang/APL/Dot-product b/Lang/APL/Dot-product new file mode 120000 index 0000000000..b79c37a734 --- /dev/null +++ b/Lang/APL/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/APL \ No newline at end of file diff --git a/Lang/APL/Sparkline-in-unicode b/Lang/APL/Sparkline-in-unicode new file mode 120000 index 0000000000..34a42ed439 --- /dev/null +++ b/Lang/APL/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/APL \ No newline at end of file diff --git a/Lang/APL/User-input-Text b/Lang/APL/User-input-Text new file mode 120000 index 0000000000..46ab634670 --- /dev/null +++ b/Lang/APL/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/Conways-Game-of-Life b/Lang/ARM-Assembly/Conways-Game-of-Life new file mode 120000 index 0000000000..8439994b7e --- /dev/null +++ b/Lang/ARM-Assembly/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Hello-world-Text b/Lang/ARM-Assembly/Hello-world-Text new file mode 120000 index 0000000000..b0d310ec40 --- /dev/null +++ b/Lang/ARM-Assembly/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Loops-Infinite b/Lang/ARM-Assembly/Loops-Infinite new file mode 120000 index 0000000000..9978b848d4 --- /dev/null +++ b/Lang/ARM-Assembly/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Luhn-test-of-credit-card-numbers b/Lang/ARM-Assembly/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..4aff5bbe5b --- /dev/null +++ b/Lang/ARM-Assembly/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/ARM-Assembly \ No newline at end of file diff --git a/Lang/ATS/00DESCRIPTION b/Lang/ATS/00DESCRIPTION index 15be069a9e..59c50c8a35 100644 --- a/Lang/ATS/00DESCRIPTION +++ b/Lang/ATS/00DESCRIPTION @@ -24,7 +24,7 @@ * [[Imperative programming]]. The novel and unique approach to imperative programming in ATS is firmly rooted in the paradigm of programming with theorem-proving. The type system of ATS allows many features considered dangerous in other languages (e.g., explicit pointer arithmetic and explicit memory allocation/deallocation) to be safely supported in ATS, making ATS a viable programming langauge for low-level systems programming. -* [[Concurrent programming]]. ATS, equipped with a multicore-safe implementation of [[garbage collection]], can support multithreaded programming through the use of pthreads. The availability of linear types for tracking and safely manipulating resources provides a effective means to constructing reliable programs that can take advantage of multicore architectures. +* [[Concurrent programming]]. ATS can support multithreaded programming through safe use of pthreads. The availability of linear types for tracking and safely manipulating resources provides an effective approach to constructing reliable programs that can take great advantage of multicore architectures. * [[Modular programming]]. The module system of ATS is largely infuenced by that of [[Modula-3]], which is both simple and general as well as effective in supporting large scale programming. diff --git a/Lang/ATS/Factorial b/Lang/ATS/Factorial new file mode 120000 index 0000000000..20c857d6d7 --- /dev/null +++ b/Lang/ATS/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/ATS \ No newline at end of file diff --git a/Lang/ATS/N-queens-problem b/Lang/ATS/N-queens-problem new file mode 120000 index 0000000000..f992fc5ea4 --- /dev/null +++ b/Lang/ATS/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/ATS \ No newline at end of file diff --git a/Lang/AWK/00DESCRIPTION b/Lang/AWK/00DESCRIPTION index fd06d8b1db..fc87255dc6 100644 --- a/Lang/AWK/00DESCRIPTION +++ b/Lang/AWK/00DESCRIPTION @@ -21,10 +21,9 @@ A few decades later, Kernighan continues to maintain the [[nawk|reference implem ==Links== *[http://leaf.dragonflybsd.org/cgi/web-man?command=awk§ion=1 awk(1) manual page], short and brief +*[https://www.gnu.org/software/gawk/ gawk] GNU awk [https://www.gnu.org/software/gawk/manual/ manual] *[[wp:AWK (programming language)|AWK in Wikipedia]] *[http://awk.info AWK Community Portal] ==Online-Execution== -* [http://www.compileonline.com/execute_awk_online.php compileonline.com] - gawk 4.1.0 (2013) -* [http://codingground.tutorialspoint.com/ codingground.tutorialspoint.com] - gawk 4.1.0 (2013) -* [http://ideone.com ideone.com] - gawk 3.1.6 (2007), mawk 1.3.3 (Nov 1996) \ No newline at end of file +* [http://ideone.com ideone.com] - gawk, mawk (both are kept up to date) \ No newline at end of file diff --git a/Lang/AWK/Abundant,-deficient-and-perfect-number-classifications b/Lang/AWK/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..d1e7da4faf --- /dev/null +++ b/Lang/AWK/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/AWK \ No newline at end of file diff --git a/Lang/AWK/Aliquot-sequence-classifications b/Lang/AWK/Aliquot-sequence-classifications new file mode 120000 index 0000000000..80bd813dcd --- /dev/null +++ b/Lang/AWK/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/AWK \ No newline at end of file diff --git a/Lang/AWK/Amicable-pairs b/Lang/AWK/Amicable-pairs new file mode 120000 index 0000000000..77d51c19cc --- /dev/null +++ b/Lang/AWK/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/AWK \ No newline at end of file diff --git a/Lang/AWK/Equilibrium-index b/Lang/AWK/Equilibrium-index new file mode 120000 index 0000000000..c3388760fb --- /dev/null +++ b/Lang/AWK/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/AWK \ No newline at end of file diff --git a/Lang/AWK/Evolutionary-algorithm b/Lang/AWK/Evolutionary-algorithm new file mode 120000 index 0000000000..2f01c8a171 --- /dev/null +++ b/Lang/AWK/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/AWK \ No newline at end of file diff --git a/Lang/AWK/HTTP b/Lang/AWK/HTTP new file mode 120000 index 0000000000..c81783815a --- /dev/null +++ b/Lang/AWK/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/AWK \ No newline at end of file diff --git a/Lang/AWK/Hickerson-series-of-almost-integers b/Lang/AWK/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..fdb6ea4aa6 --- /dev/null +++ b/Lang/AWK/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/AWK \ No newline at end of file diff --git a/Lang/AWK/Horners-rule-for-polynomial-evaluation b/Lang/AWK/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..5c437794de --- /dev/null +++ b/Lang/AWK/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/AWK \ No newline at end of file diff --git a/Lang/AWK/Quine b/Lang/AWK/Quine new file mode 120000 index 0000000000..677bbe55f8 --- /dev/null +++ b/Lang/AWK/Quine @@ -0,0 +1 @@ +../../Task/Quine/AWK \ No newline at end of file diff --git a/Lang/AWK/Tree-traversal b/Lang/AWK/Tree-traversal new file mode 120000 index 0000000000..6b25a2a70a --- /dev/null +++ b/Lang/AWK/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/AWK \ No newline at end of file diff --git a/Lang/AWK/Van-der-Corput-sequence b/Lang/AWK/Van-der-Corput-sequence new file mode 120000 index 0000000000..34c9bec433 --- /dev/null +++ b/Lang/AWK/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/AWK \ No newline at end of file diff --git a/Lang/Ada/CSV-data-manipulation b/Lang/Ada/CSV-data-manipulation new file mode 120000 index 0000000000..651a57879e --- /dev/null +++ b/Lang/Ada/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Ada \ No newline at end of file diff --git a/Lang/Ada/Stern-Brocot-sequence b/Lang/Ada/Stern-Brocot-sequence new file mode 120000 index 0000000000..6872d80d5b --- /dev/null +++ b/Lang/Ada/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Ada \ No newline at end of file diff --git a/Lang/Agda/Reverse-a-string b/Lang/Agda/Reverse-a-string new file mode 120000 index 0000000000..9ddd9863da --- /dev/null +++ b/Lang/Agda/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Agda \ No newline at end of file diff --git a/Lang/AmigaE/00DESCRIPTION b/Lang/AmigaE/00DESCRIPTION index 69e564f55b..328fee8dc0 100644 --- a/Lang/AmigaE/00DESCRIPTION +++ b/Lang/AmigaE/00DESCRIPTION @@ -6,7 +6,7 @@ Do not confuse [[E]] with AmigaE. Amiga E was born in 1993, E in 1997. Unluckily, they share the same name, and since Amiga E is the most popular (as far as I know, unique...!) implementation of E, and since Amiga E has some features that bind it to ''Amiga family'', the name AmigaE seems reasonable, even though HOPL reports it as E. -The language was designed by Wouter von Oortmerssen, also the perpetrator of [[FALSE]]. +The language was designed by Wouter van Oortmerssen, also the perpetrator of [[FALSE]]. ==See Also== * [[wp:Amiga E|Wikipedia: AmigaE]] \ No newline at end of file diff --git a/Lang/AppleScript/A+B b/Lang/AppleScript/A+B new file mode 120000 index 0000000000..a0586fd1d3 --- /dev/null +++ b/Lang/AppleScript/A+B @@ -0,0 +1 @@ +../../Task/A+B/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/ABC-Problem b/Lang/AppleScript/ABC-Problem new file mode 120000 index 0000000000..d1a7b8c6ba --- /dev/null +++ b/Lang/AppleScript/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Ackermann-function b/Lang/AppleScript/Ackermann-function new file mode 120000 index 0000000000..15e8383b5a --- /dev/null +++ b/Lang/AppleScript/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Character-codes b/Lang/AppleScript/Character-codes new file mode 120000 index 0000000000..fea566957d --- /dev/null +++ b/Lang/AppleScript/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Copy-a-string b/Lang/AppleScript/Copy-a-string new file mode 120000 index 0000000000..b9bc53c9cd --- /dev/null +++ b/Lang/AppleScript/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Empty-string b/Lang/AppleScript/Empty-string new file mode 120000 index 0000000000..debe5c5850 --- /dev/null +++ b/Lang/AppleScript/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Even-or-odd b/Lang/AppleScript/Even-or-odd new file mode 120000 index 0000000000..c8e51d6146 --- /dev/null +++ b/Lang/AppleScript/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Guess-the-number b/Lang/AppleScript/Guess-the-number new file mode 120000 index 0000000000..f502cba143 --- /dev/null +++ b/Lang/AppleScript/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Guess-the-number-With-feedback b/Lang/AppleScript/Guess-the-number-With-feedback new file mode 120000 index 0000000000..c7afff15f8 --- /dev/null +++ b/Lang/AppleScript/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Guess-the-number-With-feedback--player- b/Lang/AppleScript/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..c862cd20d9 --- /dev/null +++ b/Lang/AppleScript/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Happy-numbers b/Lang/AppleScript/Happy-numbers new file mode 120000 index 0000000000..bb9fbded1d --- /dev/null +++ b/Lang/AppleScript/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Levenshtein-distance b/Lang/AppleScript/Levenshtein-distance new file mode 120000 index 0000000000..31a3cd487c --- /dev/null +++ b/Lang/AppleScript/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Loops-Break b/Lang/AppleScript/Loops-Break new file mode 120000 index 0000000000..a951266284 --- /dev/null +++ b/Lang/AppleScript/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Loops-Downward-for b/Lang/AppleScript/Loops-Downward-for new file mode 120000 index 0000000000..2f57706dce --- /dev/null +++ b/Lang/AppleScript/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Loops-Foreach b/Lang/AppleScript/Loops-Foreach new file mode 120000 index 0000000000..11f75f77c6 --- /dev/null +++ b/Lang/AppleScript/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Read-entire-file b/Lang/AppleScript/Read-entire-file new file mode 120000 index 0000000000..511e15a8ef --- /dev/null +++ b/Lang/AppleScript/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Shell-one-liner b/Lang/AppleScript/Shell-one-liner new file mode 120000 index 0000000000..3eda091c17 --- /dev/null +++ b/Lang/AppleScript/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/String-comparison b/Lang/AppleScript/String-comparison new file mode 120000 index 0000000000..188831dfe6 --- /dev/null +++ b/Lang/AppleScript/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Strip-a-set-of-characters-from-a-string b/Lang/AppleScript/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..1b46775d5a --- /dev/null +++ b/Lang/AppleScript/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Tic-tac-toe b/Lang/AppleScript/Tic-tac-toe new file mode 120000 index 0000000000..80213223c0 --- /dev/null +++ b/Lang/AppleScript/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/URL-decoding b/Lang/AppleScript/URL-decoding new file mode 120000 index 0000000000..d780eeea53 --- /dev/null +++ b/Lang/AppleScript/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/URL-encoding b/Lang/AppleScript/URL-encoding new file mode 120000 index 0000000000..71f5cfb12b --- /dev/null +++ b/Lang/AppleScript/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/00DESCRIPTION b/Lang/Applesoft-BASIC/00DESCRIPTION index 7e8548dc93..5d976ad7f2 100644 --- a/Lang/Applesoft-BASIC/00DESCRIPTION +++ b/Lang/Applesoft-BASIC/00DESCRIPTION @@ -5,4 +5,5 @@ ==See Also== * [[wp:Applesoft BASIC|Wikipedia: Applesoft BASIC]] -* [http://www.landsnail.com/a2ref.htm Apple II Programmer's Reference] from ][ In a Mac, via [http://www.landsnail.com/ Landsnail.com] \ No newline at end of file +* [http://www.landsnail.com/a2ref.htm Apple II Programmer's Reference] from ][ In a Mac, via [http://www.landsnail.com/ Landsnail.com] +* [http://www.hoist-point.com/applesoft_basic_tutorial.htm AppleSoft BASIC tutorial for absolute beginners] \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Create-a-two-dimensional-array-at-runtime b/Lang/Applesoft-BASIC/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..ffdb6a91fc --- /dev/null +++ b/Lang/Applesoft-BASIC/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Identity-matrix b/Lang/Applesoft-BASIC/Identity-matrix new file mode 120000 index 0000000000..18232d9463 --- /dev/null +++ b/Lang/Applesoft-BASIC/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/AspectJ/History-variables b/Lang/AspectJ/History-variables new file mode 120000 index 0000000000..47cca43a24 --- /dev/null +++ b/Lang/AspectJ/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/AspectJ \ No newline at end of file diff --git a/Lang/Assembly/Least-common-multiple b/Lang/Assembly/Least-common-multiple new file mode 120000 index 0000000000..be1e5fc53c --- /dev/null +++ b/Lang/Assembly/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Assembly \ No newline at end of file diff --git a/Lang/AutoHotkey/Maximum-triangle-path-sum b/Lang/AutoHotkey/Maximum-triangle-path-sum new file mode 120000 index 0000000000..9201dba7de --- /dev/null +++ b/Lang/AutoHotkey/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoIt/Bitmap-Bresenhams-line-algorithm b/Lang/AutoIt/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..397f6d6663 --- /dev/null +++ b/Lang/AutoIt/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Execute-a-system-command b/Lang/AutoIt/Execute-a-system-command new file mode 120000 index 0000000000..89c3fe1532 --- /dev/null +++ b/Lang/AutoIt/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Generate-lower-case-ASCII-alphabet b/Lang/AutoIt/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..ece3cbc292 --- /dev/null +++ b/Lang/AutoIt/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Hello-world-Newline-omission b/Lang/AutoIt/Hello-world-Newline-omission new file mode 120000 index 0000000000..7a2fef239b --- /dev/null +++ b/Lang/AutoIt/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Hello-world-Web-server b/Lang/AutoIt/Hello-world-Web-server new file mode 120000 index 0000000000..4112eb2388 --- /dev/null +++ b/Lang/AutoIt/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Read-entire-file b/Lang/AutoIt/Read-entire-file new file mode 120000 index 0000000000..92a327ac4b --- /dev/null +++ b/Lang/AutoIt/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Repeat-a-string b/Lang/AutoIt/Repeat-a-string new file mode 120000 index 0000000000..f28c0fd8a8 --- /dev/null +++ b/Lang/AutoIt/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Sockets b/Lang/AutoIt/Sockets new file mode 120000 index 0000000000..eb83bb6e16 --- /dev/null +++ b/Lang/AutoIt/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/AutoIt \ No newline at end of file diff --git a/Lang/BASIC/Constrained-random-points-on-a-circle b/Lang/BASIC/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..382b262611 --- /dev/null +++ b/Lang/BASIC/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Conways-Game-of-Life b/Lang/BASIC/Conways-Game-of-Life new file mode 120000 index 0000000000..4a3c1fe98c --- /dev/null +++ b/Lang/BASIC/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Create-a-two-dimensional-array-at-runtime b/Lang/BASIC/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..1f8e4d27c5 --- /dev/null +++ b/Lang/BASIC/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Day-of-the-week b/Lang/BASIC/Day-of-the-week new file mode 120000 index 0000000000..6f2b84d6c4 --- /dev/null +++ b/Lang/BASIC/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Euler-method b/Lang/BASIC/Euler-method new file mode 120000 index 0000000000..792ef3ac32 --- /dev/null +++ b/Lang/BASIC/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Forest-fire b/Lang/BASIC/Forest-fire new file mode 120000 index 0000000000..d577ab5e56 --- /dev/null +++ b/Lang/BASIC/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Matrix-multiplication b/Lang/BASIC/Matrix-multiplication new file mode 120000 index 0000000000..c88f8ec6fd --- /dev/null +++ b/Lang/BASIC/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Bitmap-Midpoint-circle-algorithm b/Lang/BASIC256/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..4b615e921b --- /dev/null +++ b/Lang/BASIC256/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Hello-world-Newbie b/Lang/BASIC256/Hello-world-Newbie new file mode 120000 index 0000000000..619e05f479 --- /dev/null +++ b/Lang/BASIC256/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/BASIC256 \ No newline at end of file diff --git a/Lang/BBC-BASIC/Catamorphism b/Lang/BBC-BASIC/Catamorphism new file mode 120000 index 0000000000..4e88f7ba6f --- /dev/null +++ b/Lang/BBC-BASIC/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Iterated-digits-squaring b/Lang/BBC-BASIC/Iterated-digits-squaring new file mode 120000 index 0000000000..bd5c438666 --- /dev/null +++ b/Lang/BBC-BASIC/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Zero-to-the-zero-power b/Lang/BBC-BASIC/Zero-to-the-zero-power new file mode 120000 index 0000000000..5151efaa27 --- /dev/null +++ b/Lang/BBC-BASIC/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/BBC-BASIC \ No newline at end of file diff --git a/Lang/Batch-File/00DESCRIPTION b/Lang/Batch-File/00DESCRIPTION index bea7157500..1bcc82760d 100644 --- a/Lang/Batch-File/00DESCRIPTION +++ b/Lang/Batch-File/00DESCRIPTION @@ -1 +1,3 @@ -{{language|Batch File}}'''Batch files''' are the scripting languages for [[Microsoft]] command line shells, such as [[MS-DOS]], COMMAND.EXE, and CMD.EXE. They typically have either the .BAT or .CMD extension. \ No newline at end of file +{{language|Batch File}}'''Batch files''' are the scripting languages for [[Microsoft]] command line shells, such as [[MS-DOS]], COMMAND.EXE, and CMD.EXE. They typically have either the .BAT or .CMD extension. + +The "batch files" written in the Batch File language are not to be confused with the "bash scripts" written in the [[bash | bash programming language]] for the [[UNIX Shell]]. \ No newline at end of file diff --git a/Lang/Batch-File/Balanced-brackets b/Lang/Batch-File/Balanced-brackets new file mode 120000 index 0000000000..c79f4f4825 --- /dev/null +++ b/Lang/Batch-File/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Bitmap-Midpoint-circle-algorithm b/Lang/Batch-File/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..ede9296abc --- /dev/null +++ b/Lang/Batch-File/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Bulls-and-cows b/Lang/Batch-File/Bulls-and-cows new file mode 120000 index 0000000000..18553e5c9c --- /dev/null +++ b/Lang/Batch-File/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Calendar b/Lang/Batch-File/Calendar new file mode 120000 index 0000000000..860a1b8ecd --- /dev/null +++ b/Lang/Batch-File/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Comma-quibbling b/Lang/Batch-File/Comma-quibbling new file mode 120000 index 0000000000..f4b28d6e2f --- /dev/null +++ b/Lang/Batch-File/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Count-occurrences-of-a-substring b/Lang/Batch-File/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..6abc6e0ba9 --- /dev/null +++ b/Lang/Batch-File/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/DNS-query b/Lang/Batch-File/DNS-query new file mode 120000 index 0000000000..ce007c15dd --- /dev/null +++ b/Lang/Batch-File/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Day-of-the-week b/Lang/Batch-File/Day-of-the-week new file mode 120000 index 0000000000..bd3fb0c85a --- /dev/null +++ b/Lang/Batch-File/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Detect-division-by-zero b/Lang/Batch-File/Detect-division-by-zero new file mode 120000 index 0000000000..d92e3edcf8 --- /dev/null +++ b/Lang/Batch-File/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Digital-root b/Lang/Batch-File/Digital-root new file mode 120000 index 0000000000..55d5d27842 --- /dev/null +++ b/Lang/Batch-File/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Draw-a-clock b/Lang/Batch-File/Draw-a-clock new file mode 120000 index 0000000000..403d56a517 --- /dev/null +++ b/Lang/Batch-File/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Empty-directory b/Lang/Batch-File/Empty-directory new file mode 120000 index 0000000000..f7d48b0168 --- /dev/null +++ b/Lang/Batch-File/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Equilibrium-index b/Lang/Batch-File/Equilibrium-index new file mode 120000 index 0000000000..e6cd7c6859 --- /dev/null +++ b/Lang/Batch-File/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Fractran b/Lang/Batch-File/Fractran new file mode 120000 index 0000000000..2392bf313d --- /dev/null +++ b/Lang/Batch-File/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/I-before-E-except-after-C b/Lang/Batch-File/I-before-E-except-after-C new file mode 120000 index 0000000000..6a9e744f29 --- /dev/null +++ b/Lang/Batch-File/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Integer-comparison b/Lang/Batch-File/Integer-comparison new file mode 120000 index 0000000000..86e5325ecf --- /dev/null +++ b/Lang/Batch-File/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Josephus-problem b/Lang/Batch-File/Josephus-problem new file mode 120000 index 0000000000..35ad118b2b --- /dev/null +++ b/Lang/Batch-File/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Leap-year b/Lang/Batch-File/Leap-year new file mode 120000 index 0000000000..1cfc67d40f --- /dev/null +++ b/Lang/Batch-File/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Least-common-multiple b/Lang/Batch-File/Least-common-multiple new file mode 120000 index 0000000000..4ab5357965 --- /dev/null +++ b/Lang/Batch-File/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Long-multiplication b/Lang/Batch-File/Long-multiplication new file mode 120000 index 0000000000..e147ef10b1 --- /dev/null +++ b/Lang/Batch-File/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Loops-Downward-for b/Lang/Batch-File/Loops-Downward-for new file mode 120000 index 0000000000..f8278b7e73 --- /dev/null +++ b/Lang/Batch-File/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Loops-For-with-a-specified-step b/Lang/Batch-File/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..9369be1bd6 --- /dev/null +++ b/Lang/Batch-File/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Loops-Foreach b/Lang/Batch-File/Loops-Foreach new file mode 120000 index 0000000000..b96ad2877d --- /dev/null +++ b/Lang/Batch-File/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Luhn-test-of-credit-card-numbers b/Lang/Batch-File/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..2c1b7bdba4 --- /dev/null +++ b/Lang/Batch-File/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Mad-Libs b/Lang/Batch-File/Mad-Libs new file mode 120000 index 0000000000..ad2a45b666 --- /dev/null +++ b/Lang/Batch-File/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Menu b/Lang/Batch-File/Menu new file mode 120000 index 0000000000..954934c013 --- /dev/null +++ b/Lang/Batch-File/Menu @@ -0,0 +1 @@ +../../Task/Menu/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Middle-three-digits b/Lang/Batch-File/Middle-three-digits new file mode 120000 index 0000000000..d27b3b0749 --- /dev/null +++ b/Lang/Batch-File/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Modular-inverse b/Lang/Batch-File/Modular-inverse new file mode 120000 index 0000000000..1ef3c5cbc5 --- /dev/null +++ b/Lang/Batch-File/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Multiplication-tables b/Lang/Batch-File/Multiplication-tables new file mode 120000 index 0000000000..97293e8345 --- /dev/null +++ b/Lang/Batch-File/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Nth b/Lang/Batch-File/Nth new file mode 120000 index 0000000000..8b2eda3188 --- /dev/null +++ b/Lang/Batch-File/Nth @@ -0,0 +1 @@ +../../Task/Nth/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Number-names b/Lang/Batch-File/Number-names new file mode 120000 index 0000000000..b3b9474f83 --- /dev/null +++ b/Lang/Batch-File/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Number-reversal-game b/Lang/Batch-File/Number-reversal-game new file mode 120000 index 0000000000..d6960876d7 --- /dev/null +++ b/Lang/Batch-File/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Old-lady-swallowed-a-fly b/Lang/Batch-File/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..f62bb097d6 --- /dev/null +++ b/Lang/Batch-File/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/One-dimensional-cellular-automata b/Lang/Batch-File/One-dimensional-cellular-automata new file mode 120000 index 0000000000..7678f8f43e --- /dev/null +++ b/Lang/Batch-File/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Pangram-checker b/Lang/Batch-File/Pangram-checker new file mode 120000 index 0000000000..e155b2391e --- /dev/null +++ b/Lang/Batch-File/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Pascals-triangle b/Lang/Batch-File/Pascals-triangle new file mode 120000 index 0000000000..70598d55b1 --- /dev/null +++ b/Lang/Batch-File/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Penneys-game b/Lang/Batch-File/Penneys-game new file mode 120000 index 0000000000..49350e0ac1 --- /dev/null +++ b/Lang/Batch-File/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Phrase-reversals b/Lang/Batch-File/Phrase-reversals new file mode 120000 index 0000000000..d81d3243f9 --- /dev/null +++ b/Lang/Batch-File/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Pick-random-element b/Lang/Batch-File/Pick-random-element new file mode 120000 index 0000000000..acb3571bdb --- /dev/null +++ b/Lang/Batch-File/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Reverse-words-in-a-string b/Lang/Batch-File/Reverse-words-in-a-string new file mode 120000 index 0000000000..69ec0d791e --- /dev/null +++ b/Lang/Batch-File/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Roman-numerals-Decode b/Lang/Batch-File/Roman-numerals-Decode new file mode 120000 index 0000000000..423d28ab7c --- /dev/null +++ b/Lang/Batch-File/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Roman-numerals-Encode b/Lang/Batch-File/Roman-numerals-Encode new file mode 120000 index 0000000000..a36a067b8e --- /dev/null +++ b/Lang/Batch-File/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Search-a-list b/Lang/Batch-File/Search-a-list new file mode 120000 index 0000000000..3948075412 --- /dev/null +++ b/Lang/Batch-File/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Short-circuit-evaluation b/Lang/Batch-File/Short-circuit-evaluation new file mode 120000 index 0000000000..b604a85639 --- /dev/null +++ b/Lang/Batch-File/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Sorting-algorithms-Pancake-sort b/Lang/Batch-File/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..89658edde2 --- /dev/null +++ b/Lang/Batch-File/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Speech-synthesis b/Lang/Batch-File/Speech-synthesis new file mode 120000 index 0000000000..d1f951dac5 --- /dev/null +++ b/Lang/Batch-File/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Stable-marriage-problem b/Lang/Batch-File/Stable-marriage-problem new file mode 120000 index 0000000000..66aa03dd58 --- /dev/null +++ b/Lang/Batch-File/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/String-matching b/Lang/Batch-File/String-matching new file mode 120000 index 0000000000..ae4d8e1598 --- /dev/null +++ b/Lang/Batch-File/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Terminal-control-Dimensions b/Lang/Batch-File/Terminal-control-Dimensions new file mode 120000 index 0000000000..de8121f4be --- /dev/null +++ b/Lang/Batch-File/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Terminal-control-Ringing-the-terminal-bell b/Lang/Batch-File/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..2a80a7cb26 --- /dev/null +++ b/Lang/Batch-File/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Tic-tac-toe b/Lang/Batch-File/Tic-tac-toe new file mode 120000 index 0000000000..ab472a0e61 --- /dev/null +++ b/Lang/Batch-File/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Towers-of-Hanoi b/Lang/Batch-File/Towers-of-Hanoi new file mode 120000 index 0000000000..ebe9dc5876 --- /dev/null +++ b/Lang/Batch-File/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Walk-a-directory-Non-recursively b/Lang/Batch-File/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..5572461ac3 --- /dev/null +++ b/Lang/Batch-File/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Write-to-Windows-event-log b/Lang/Batch-File/Write-to-Windows-event-log new file mode 120000 index 0000000000..275ce56696 --- /dev/null +++ b/Lang/Batch-File/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Yin-and-yang b/Lang/Batch-File/Yin-and-yang new file mode 120000 index 0000000000..35acc29cb6 --- /dev/null +++ b/Lang/Batch-File/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Batch-File \ No newline at end of file diff --git a/Lang/Befunge/00DESCRIPTION b/Lang/Befunge/00DESCRIPTION index 3a3f1ea033..055fe26193 100644 --- a/Lang/Befunge/00DESCRIPTION +++ b/Lang/Befunge/00DESCRIPTION @@ -1,13 +1,14 @@ {{language|Befunge}} -'''Befunge''' is an esoteric programming language invented by Chris Pressey in 1993. It is unusual for having a two-dimensional toroidal code space. Commands are single characters. The instruction pointer can move up, down, left, and right across the source. The original specification is known as Befunge-93, which was later updated with additional features as Befunge-98. +'''Befunge''' is an esoteric programming language invented by Chris Pressey in 1993. It is unusual for having a two-dimensional toroidal code space. Commands are single characters, and the instruction pointer can move up, down, left, and right across the source. One of the original goals of the language was to be as hard to compile as possible. -Befunge was the first of a family of languages referred to as "Funges". In addition to the "normal" 2-dimensional layout, there is a 1-dimension variant called '''Unefunge''', a 3-dimensional variant called '''Trefunge''', and an ''N''-dimensional variant called '''Nefunge'''. +In the latter part of the 90s, several attempts were made to extend the language, with mutually incompatible versions proposed in '96, '97 and '98. It was at this time that the idea of variant dimensions were introduced, with '''Unefunge''' (one-dimensional), '''Trefunge''' (three-dimensional) and '''Nefunge''' (''N''-dimensional) - the general language class then being refered to as a '''Funge'''. + +The '96 and '97 versions are now largely considered abandoned, and while '''Funge-98''' did gain a certain amount of tranction, it has never been as widely adopted as the original '''Befunge-93'''. Being considerably more complex than the original, it is often deemed "too complicated" and sometimes even "too normal". ==See also== +* [http://github.com/catseye/Befunge-93/blob/master/doc/Befunge-93.markdown Befunge-93 Specification] +* [http://github.com/catseye/Funge-98/blob/master/doc/funge98.markdown Funge-98 Specification] * [[wp:Esoteric programming language#Funges|Funges on Wikipedia]] * [[eso:Befunge|Befunge on Esolangs]] -* [http://catseye.tc/projects/befunge93/doc/befunge93.html Befunge-93 Documentation] (broken in some browsers) -** [http://web.archive.org/web/20080625030023/http://catseye.tc/projects/befunge93/doc/befunge93.html Web Archive copy of the above] -* [http://quadium.net/funge/spec98.html Funge-98 Final Specification] [[Category:Esoteric Languages]] \ No newline at end of file diff --git a/Lang/Befunge/Almost-prime b/Lang/Befunge/Almost-prime new file mode 120000 index 0000000000..c6f2baab0e --- /dev/null +++ b/Lang/Befunge/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Binary-digits b/Lang/Befunge/Binary-digits new file mode 120000 index 0000000000..c23ed58b67 --- /dev/null +++ b/Lang/Befunge/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Befunge \ No newline at end of file diff --git a/Lang/Befunge/CSV-to-HTML-translation b/Lang/Befunge/CSV-to-HTML-translation new file mode 120000 index 0000000000..011cc88f08 --- /dev/null +++ b/Lang/Befunge/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Catalan-numbers b/Lang/Befunge/Catalan-numbers new file mode 120000 index 0000000000..f4d1b6392c --- /dev/null +++ b/Lang/Befunge/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Colour-bars-Display b/Lang/Befunge/Colour-bars-Display new file mode 120000 index 0000000000..c589bfcbb7 --- /dev/null +++ b/Lang/Befunge/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Count-in-factors b/Lang/Befunge/Count-in-factors new file mode 120000 index 0000000000..f537276604 --- /dev/null +++ b/Lang/Befunge/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Count-in-octal b/Lang/Befunge/Count-in-octal new file mode 120000 index 0000000000..33ef3619eb --- /dev/null +++ b/Lang/Befunge/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Deal-cards-for-FreeCell b/Lang/Befunge/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..2b7b1c55a9 --- /dev/null +++ b/Lang/Befunge/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Digital-root b/Lang/Befunge/Digital-root new file mode 120000 index 0000000000..41350fd632 --- /dev/null +++ b/Lang/Befunge/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Discordian-date b/Lang/Befunge/Discordian-date new file mode 120000 index 0000000000..252ef3c094 --- /dev/null +++ b/Lang/Befunge/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Draw-a-sphere b/Lang/Befunge/Draw-a-sphere new file mode 120000 index 0000000000..f7b59f2a43 --- /dev/null +++ b/Lang/Befunge/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Even-or-odd b/Lang/Befunge/Even-or-odd new file mode 120000 index 0000000000..5bf8f48532 --- /dev/null +++ b/Lang/Befunge/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Find-the-last-Sunday-of-each-month b/Lang/Befunge/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..67f7133497 --- /dev/null +++ b/Lang/Befunge/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Floyds-triangle b/Lang/Befunge/Floyds-triangle new file mode 120000 index 0000000000..b6fdbec180 --- /dev/null +++ b/Lang/Befunge/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Generate-Chess960-starting-position b/Lang/Befunge/Generate-Chess960-starting-position new file mode 120000 index 0000000000..8d510911f5 --- /dev/null +++ b/Lang/Befunge/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Generate-lower-case-ASCII-alphabet b/Lang/Befunge/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..d79af11678 --- /dev/null +++ b/Lang/Befunge/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Harshad-or-Niven-series b/Lang/Befunge/Harshad-or-Niven-series new file mode 120000 index 0000000000..0f36090026 --- /dev/null +++ b/Lang/Befunge/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Holidays-related-to-Easter b/Lang/Befunge/Holidays-related-to-Easter new file mode 120000 index 0000000000..d62ceb9c80 --- /dev/null +++ b/Lang/Befunge/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Integer-overflow b/Lang/Befunge/Integer-overflow new file mode 120000 index 0000000000..374853ba46 --- /dev/null +++ b/Lang/Befunge/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Integer-sequence b/Lang/Befunge/Integer-sequence new file mode 120000 index 0000000000..7cefc35629 --- /dev/null +++ b/Lang/Befunge/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Josephus-problem b/Lang/Befunge/Josephus-problem new file mode 120000 index 0000000000..7c7a93b65e --- /dev/null +++ b/Lang/Befunge/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Last-Friday-of-each-month b/Lang/Befunge/Last-Friday-of-each-month new file mode 120000 index 0000000000..2b525ba061 --- /dev/null +++ b/Lang/Befunge/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Leap-year b/Lang/Befunge/Leap-year new file mode 120000 index 0000000000..55d7649b86 --- /dev/null +++ b/Lang/Befunge/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Linear-congruential-generator b/Lang/Befunge/Linear-congruential-generator new file mode 120000 index 0000000000..47c803a49f --- /dev/null +++ b/Lang/Befunge/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Loop-over-multiple-arrays-simultaneously b/Lang/Befunge/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..ec2be3b6df --- /dev/null +++ b/Lang/Befunge/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Loops-For-with-a-specified-step b/Lang/Befunge/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..c4e984ddd5 --- /dev/null +++ b/Lang/Befunge/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Magic-squares-of-odd-order b/Lang/Befunge/Magic-squares-of-odd-order new file mode 120000 index 0000000000..e8ecae3bb2 --- /dev/null +++ b/Lang/Befunge/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Mandelbrot-set b/Lang/Befunge/Mandelbrot-set new file mode 120000 index 0000000000..4ad53e3fa1 --- /dev/null +++ b/Lang/Befunge/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Maze-generation b/Lang/Befunge/Maze-generation new file mode 120000 index 0000000000..7a2c17905a --- /dev/null +++ b/Lang/Befunge/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Middle-three-digits b/Lang/Befunge/Middle-three-digits new file mode 120000 index 0000000000..2fe5790572 --- /dev/null +++ b/Lang/Befunge/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Narcissist b/Lang/Befunge/Narcissist new file mode 120000 index 0000000000..2f66829a46 --- /dev/null +++ b/Lang/Befunge/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Nth b/Lang/Befunge/Nth new file mode 120000 index 0000000000..ffa7331f60 --- /dev/null +++ b/Lang/Befunge/Nth @@ -0,0 +1 @@ +../../Task/Nth/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Old-lady-swallowed-a-fly b/Lang/Befunge/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..a0857efad8 --- /dev/null +++ b/Lang/Befunge/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Pascals-triangle b/Lang/Befunge/Pascals-triangle new file mode 120000 index 0000000000..8f00e85129 --- /dev/null +++ b/Lang/Befunge/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Pernicious-numbers b/Lang/Befunge/Pernicious-numbers new file mode 120000 index 0000000000..568455a955 --- /dev/null +++ b/Lang/Befunge/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Program-termination b/Lang/Befunge/Program-termination new file mode 120000 index 0000000000..e0d5ca45b8 --- /dev/null +++ b/Lang/Befunge/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Roman-numerals-Encode b/Lang/Befunge/Roman-numerals-Encode new file mode 120000 index 0000000000..42544cc68f --- /dev/null +++ b/Lang/Befunge/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Sierpinski-carpet b/Lang/Befunge/Sierpinski-carpet new file mode 120000 index 0000000000..98f3f69acf --- /dev/null +++ b/Lang/Befunge/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Sierpinski-triangle b/Lang/Befunge/Sierpinski-triangle new file mode 120000 index 0000000000..9a333c20d6 --- /dev/null +++ b/Lang/Befunge/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Sum-of-a-series b/Lang/Befunge/Sum-of-a-series new file mode 120000 index 0000000000..e7b6263953 --- /dev/null +++ b/Lang/Befunge/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Temperature-conversion b/Lang/Befunge/Temperature-conversion new file mode 120000 index 0000000000..023d527048 --- /dev/null +++ b/Lang/Befunge/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Terminal-control-Clear-the-screen b/Lang/Befunge/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..6b32c8a983 --- /dev/null +++ b/Lang/Befunge/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Terminal-control-Coloured-text b/Lang/Befunge/Terminal-control-Coloured-text new file mode 120000 index 0000000000..af5654cc3d --- /dev/null +++ b/Lang/Befunge/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Terminal-control-Cursor-positioning b/Lang/Befunge/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..633c68160e --- /dev/null +++ b/Lang/Befunge/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Terminal-control-Display-an-extended-character b/Lang/Befunge/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..7be394d323 --- /dev/null +++ b/Lang/Befunge/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Terminal-control-Hiding-the-cursor b/Lang/Befunge/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..50a594fb54 --- /dev/null +++ b/Lang/Befunge/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Terminal-control-Inverse-video b/Lang/Befunge/Terminal-control-Inverse-video new file mode 120000 index 0000000000..814f0fb152 --- /dev/null +++ b/Lang/Befunge/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Befunge \ No newline at end of file diff --git a/Lang/Befunge/The-Twelve-Days-of-Christmas b/Lang/Befunge/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..4630e2ff95 --- /dev/null +++ b/Lang/Befunge/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Tic-tac-toe b/Lang/Befunge/Tic-tac-toe new file mode 120000 index 0000000000..26ae303387 --- /dev/null +++ b/Lang/Befunge/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Yin-and-yang b/Lang/Befunge/Yin-and-yang new file mode 120000 index 0000000000..e8ef4b5a7a --- /dev/null +++ b/Lang/Befunge/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Zero-to-the-zero-power b/Lang/Befunge/Zero-to-the-zero-power new file mode 120000 index 0000000000..a4ab7e6ec6 --- /dev/null +++ b/Lang/Befunge/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Zig-zag-matrix b/Lang/Befunge/Zig-zag-matrix new file mode 120000 index 0000000000..0e97b9f40b --- /dev/null +++ b/Lang/Befunge/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Befunge \ No newline at end of file diff --git a/Lang/Bracmat/00DESCRIPTION b/Lang/Bracmat/00DESCRIPTION index e5a937026c..23c45f4a56 100644 --- a/Lang/Bracmat/00DESCRIPTION +++ b/Lang/Bracmat/00DESCRIPTION @@ -10,10 +10,10 @@ |strength=weak |tags=bracmat }} -Bracmat is an interpreted programming language that is developed by Bart Jongejan, starting in 1986. Originally it was designed as a Computer Algebra system, but it has shown its merits in natural language processing as well. Bracmat has been used in the field of General Relativity for the algebraic computation of Ricci tensors from given space-time metrics, for the implementation of a dialogue-manager in virtual world project that allowed a user to communicate with software agents in plain English and with gestures, for the analysis of texts in a "Controlled Language"-project and for automatic error correction of hundreds of [[HTML]] pages. Bracmat has also shown its utility in some real-world applications: for example to identify persons, companies etc. in pre-tagged texts that must be anonymised. The to date most advanced application of Bracmat is as workflow planner and executor. Instead of letting the user choose between software tools, which the user may not know very well, the planner asks the user to specify what kind of output she wants. With this information the planner computes all (not necessarily sequential) combinations of tools and their parameter settings that combine into workflows that are guaranteed to produce the specified output from the given input. The computed list is condensed into a short format that highlights the differences between the workflows for the user and leaves out all that is of less importance. +Bracmat is an interpreted programming language for symbolic computation. Originally (in the eighties) it was designed as a Computer Algebra system, but it has shown its merits in natural language processing as well. Bracmat has been used in the field of General Relativity for the algebraic computation of Ricci tensors from given space-time metrics, for the implementation of a dialogue-manager in virtual world project that allowed a user to communicate with software agents in plain English and with gestures, for the analysis of texts in a "Controlled Language"-project and for automatic error correction of hundreds of [[HTML]] pages. Bracmat has also shown its utility in some real-world applications: for example to identify persons, companies etc. in pre-tagged texts that must be anonymised. The to date most advanced application of Bracmat is as workflow planner and executor. Instead of letting the user choose between software tools, which the user may not know very well, the planner asks the user to specify what kind of output she wants. With this information the planner computes all (not necessarily sequential) combinations of tools and their parameter settings that combine into workflows that are guaranteed to produce the specified output from the given input. The computed list is condensed into a short format that highlights the differences between the workflows for the user and leaves out all that is of less importance. -Bracmat's strength is [[pattern matching]], in strings as well as in tree structures. +Bracmat is almost unique in the combination of on the one hand allowing associative [[pattern matching]], in strings as well as in tree structures, and on the other hand allowing expression evaluation during a match operation. Bracmat is inspired by [[SNOBOL4]] (pattern matching, success/failure), by [[Lisp]] (Bracmat programs are made of the same stuff as Bracmat data), by [[Prolog]] (backtracking) and a little bit by [[object-oriented]] languages. The first implementation was for an ARM based computer. The ARM processor's 4-bit condition code selector on every instruction were the inspiration for Bracmat's flags ~ [ ! !! ` @ % > < # / ? that can be set on any node in an expression. For example, the ! and ? flags turn a symbol into a variable. When flags are combined, care has been taken that the semantics of a combination of flags is close to a combination of the semantics of each flag. -The Bracmat-interpreter is written in Standard [[C]] and can be compiled for many platforms, such as Epoc, [[Windows]], [[Mac OS]], [[Linux]] and [[Unix]]. The compiled code measures about 130 KB (statically linked), depending on the platform. The runtime is not very memory hungry, as compared to e.g. [[Java]]. \ No newline at end of file +The Bracmat-interpreter is written in Standard [[C]] and can be compiled for many platforms, such as Epoc, [[Windows]], [[Mac OS]] (including OS X), [[Linux]] and [[Unix]]. The compiled code measures about 130 KB (statically linked), depending on the platform. The runtime is not very memory hungry, as compared to e.g. [[Java]]. Bracmat can be compiled for 32 and 64 bit systems. \ No newline at end of file diff --git a/Lang/Bracmat/Abundant,-deficient-and-perfect-number-classifications b/Lang/Bracmat/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..c08cf96112 --- /dev/null +++ b/Lang/Bracmat/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/CSV-to-HTML-translation b/Lang/Bracmat/CSV-to-HTML-translation new file mode 120000 index 0000000000..52b4f9b5a3 --- /dev/null +++ b/Lang/Bracmat/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Create-an-HTML-table b/Lang/Bracmat/Create-an-HTML-table new file mode 120000 index 0000000000..e38cd31848 --- /dev/null +++ b/Lang/Bracmat/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Ethiopian-multiplication b/Lang/Bracmat/Ethiopian-multiplication new file mode 120000 index 0000000000..1d07b4aa22 --- /dev/null +++ b/Lang/Bracmat/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Exceptions b/Lang/Bracmat/Exceptions new file mode 120000 index 0000000000..a0b5e45628 --- /dev/null +++ b/Lang/Bracmat/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Guess-the-number b/Lang/Bracmat/Guess-the-number new file mode 120000 index 0000000000..1efa49c69d --- /dev/null +++ b/Lang/Bracmat/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Hofstadter-Conway-$10,000-sequence b/Lang/Bracmat/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..24170b68ba --- /dev/null +++ b/Lang/Bracmat/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Horners-rule-for-polynomial-evaluation b/Lang/Bracmat/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..83d1ee3c68 --- /dev/null +++ b/Lang/Bracmat/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Jensens-Device b/Lang/Bracmat/Jensens-Device new file mode 120000 index 0000000000..3f6189afea --- /dev/null +++ b/Lang/Bracmat/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Modular-inverse b/Lang/Bracmat/Modular-inverse new file mode 120000 index 0000000000..6eb319d7c7 --- /dev/null +++ b/Lang/Bracmat/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Nth-root b/Lang/Bracmat/Nth-root new file mode 120000 index 0000000000..cb148a9dea --- /dev/null +++ b/Lang/Bracmat/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Sort-an-array-of-composite-structures b/Lang/Bracmat/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..b1acc63bc2 --- /dev/null +++ b/Lang/Bracmat/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/User-input-Text b/Lang/Bracmat/User-input-Text new file mode 120000 index 0000000000..664168ae7c --- /dev/null +++ b/Lang/Bracmat/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Bracmat \ No newline at end of file diff --git a/Lang/Brainf---/Hello-world-Newline-omission b/Lang/Brainf---/Hello-world-Newline-omission new file mode 120000 index 0000000000..5ebf4b7c93 --- /dev/null +++ b/Lang/Brainf---/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Brainf--- \ No newline at end of file diff --git a/Lang/Brainf---/Towers-of-Hanoi b/Lang/Brainf---/Towers-of-Hanoi new file mode 120000 index 0000000000..efbc46c24b --- /dev/null +++ b/Lang/Brainf---/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Brainf--- \ No newline at end of file diff --git a/Lang/Brainf---/Write-language-name-in-3D-ASCII b/Lang/Brainf---/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..46a87484a3 --- /dev/null +++ b/Lang/Brainf---/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Brainf--- \ No newline at end of file diff --git a/Lang/Burlesque/Empty-string b/Lang/Burlesque/Empty-string new file mode 120000 index 0000000000..f667388b5f --- /dev/null +++ b/Lang/Burlesque/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Middle-three-digits b/Lang/Burlesque/Middle-three-digits new file mode 120000 index 0000000000..b6846163fc --- /dev/null +++ b/Lang/Burlesque/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Reverse-words-in-a-string b/Lang/Burlesque/Reverse-words-in-a-string new file mode 120000 index 0000000000..283fe10700 --- /dev/null +++ b/Lang/Burlesque/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Substring b/Lang/Burlesque/Substring new file mode 120000 index 0000000000..15148eaa42 --- /dev/null +++ b/Lang/Burlesque/Substring @@ -0,0 +1 @@ +../../Task/Substring/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Substring-Top-and-tail b/Lang/Burlesque/Substring-Top-and-tail new file mode 120000 index 0000000000..8c98066949 --- /dev/null +++ b/Lang/Burlesque/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Burlesque \ No newline at end of file diff --git a/Lang/Burlesque/Zero-to-the-zero-power b/Lang/Burlesque/Zero-to-the-zero-power new file mode 120000 index 0000000000..7eca3d6875 --- /dev/null +++ b/Lang/Burlesque/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Burlesque \ No newline at end of file diff --git a/Lang/C++/00DESCRIPTION b/Lang/C++/00DESCRIPTION index c10caeb0cf..cf522cf3f3 100644 --- a/Lang/C++/00DESCRIPTION +++ b/Lang/C++/00DESCRIPTION @@ -22,8 +22,9 @@ If you can't find an implementation for your task in the C++ category below, ple * '''C++98''' is the version of C++ standardized by ISO in 1998. It is the most commonly used and supported version of the language. The term "C++" usually refers to C++98. * '''C++03''' is a minor improvement to C++98, standardized by ISO in 2003. * '''TR1''' (Technical Report 1) is a proposal for extensions to the C++ standard library. It was published in 2007. Many of its proposals made it into C++11. Many compilers support it, but put its headers in a different directory. -* '''C++11''' (formerly called '''C++0x''') is a significant improvement, adding many new language features and libraries. It was standardized by ISO in 2011. Most of its features are available in [[GCC]] [http://gcc.gnu.org/projects/cxx0x.html] and [[Clang]] [http://clang.llvm.org/cxx_status.html]. +* '''C++11''' (formerly called '''C++0x''' and sometimes '''C++1x''') is a significant improvement, adding many new language features and libraries. It was standardized by ISO in 2011. Most of its features are available in [[GCC]] [http://gcc.gnu.org/projects/cxx0x.html] and [[Clang]] [http://clang.llvm.org/cxx_status.html]. * '''C++14''' (formerly called '''C++1y''') is a minor improvement to C++11, standardized by ISO in 2014. Most of its features are available in [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [http://gcc.gnu.org/projects/cxx1y.html]. +* '''C++17''' (or '''C++1z''') is informal name of future standard which will become in 2017, but many of its features are already published and supported by several compilers. {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} diff --git a/Lang/C++/Active-object b/Lang/C++/Active-object new file mode 120000 index 0000000000..f77eb1097d --- /dev/null +++ b/Lang/C++/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/C++ \ No newline at end of file diff --git a/Lang/C++/Atomic-updates b/Lang/C++/Atomic-updates new file mode 120000 index 0000000000..04098f6451 --- /dev/null +++ b/Lang/C++/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/C++ \ No newline at end of file diff --git a/Lang/C++/Bitmap-Flood-fill b/Lang/C++/Bitmap-Flood-fill new file mode 120000 index 0000000000..105f8a2b47 --- /dev/null +++ b/Lang/C++/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/C++ \ No newline at end of file diff --git a/Lang/C++/Call-a-function b/Lang/C++/Call-a-function new file mode 120000 index 0000000000..a1d7518c19 --- /dev/null +++ b/Lang/C++/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/C++ \ No newline at end of file diff --git a/Lang/C++/Checkpoint-synchronization b/Lang/C++/Checkpoint-synchronization new file mode 120000 index 0000000000..a9b644c7bc --- /dev/null +++ b/Lang/C++/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/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..0391837058 --- /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++/Constrained-genericity b/Lang/C++/Constrained-genericity new file mode 120000 index 0000000000..01de367515 --- /dev/null +++ b/Lang/C++/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/C++ \ No newline at end of file diff --git a/Lang/C++/Doubly-linked-list-Definition b/Lang/C++/Doubly-linked-list-Definition new file mode 120000 index 0000000000..692f998d98 --- /dev/null +++ b/Lang/C++/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/C++ \ No newline at end of file diff --git a/Lang/C++/Doubly-linked-list-Element-definition b/Lang/C++/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..2b0688dcf7 --- /dev/null +++ b/Lang/C++/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/C++ \ No newline at end of file diff --git a/Lang/C++/Doubly-linked-list-Element-insertion b/Lang/C++/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..7f354580d8 --- /dev/null +++ b/Lang/C++/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/C++ \ No newline at end of file diff --git a/Lang/C++/Doubly-linked-list-Traversal b/Lang/C++/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..85de29665e --- /dev/null +++ b/Lang/C++/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/C++ \ No newline at end of file diff --git a/Lang/C++/Draw-a-cuboid b/Lang/C++/Draw-a-cuboid new file mode 120000 index 0000000000..7f3ff814eb --- /dev/null +++ b/Lang/C++/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/C++ \ No newline at end of file diff --git a/Lang/C++/Empty-directory b/Lang/C++/Empty-directory new file mode 120000 index 0000000000..1d6c55a8aa --- /dev/null +++ b/Lang/C++/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/C++ \ No newline at end of file diff --git a/Lang/C++/Galton-box-animation b/Lang/C++/Galton-box-animation new file mode 120000 index 0000000000..7bd95af04b --- /dev/null +++ b/Lang/C++/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/C++ \ No newline at end of file diff --git a/Lang/C++/Harshad-or-Niven-series b/Lang/C++/Harshad-or-Niven-series new file mode 120000 index 0000000000..fbc2954f1e --- /dev/null +++ b/Lang/C++/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/C++ \ No newline at end of file diff --git a/Lang/C++/Heronian-triangles b/Lang/C++/Heronian-triangles new file mode 120000 index 0000000000..26c873be50 --- /dev/null +++ b/Lang/C++/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/C++ \ No newline at end of file diff --git a/Lang/C++/Integer-overflow b/Lang/C++/Integer-overflow new file mode 120000 index 0000000000..723566b157 --- /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++/Inverted-index b/Lang/C++/Inverted-index new file mode 120000 index 0000000000..fe0260a4ac --- /dev/null +++ b/Lang/C++/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/C++ \ No newline at end of file diff --git a/Lang/C++/Monte-Carlo-methods b/Lang/C++/Monte-Carlo-methods new file mode 120000 index 0000000000..3b2c1d1833 --- /dev/null +++ b/Lang/C++/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/C++ \ No newline at end of file diff --git a/Lang/C++/Nth b/Lang/C++/Nth new file mode 120000 index 0000000000..b6fbe05130 --- /dev/null +++ b/Lang/C++/Nth @@ -0,0 +1 @@ +../../Task/Nth/C++ \ No newline at end of file diff --git a/Lang/C++/Parsing-RPN-to-infix-conversion b/Lang/C++/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..ee21d3ae18 --- /dev/null +++ b/Lang/C++/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/C++ \ No newline at end of file diff --git a/Lang/C++/Self-referential-sequence b/Lang/C++/Self-referential-sequence new file mode 120000 index 0000000000..a0af7593e0 --- /dev/null +++ b/Lang/C++/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/C++ \ No newline at end of file diff --git a/Lang/C++/Sequence-of-primes-by-Trial-Division b/Lang/C++/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..160036485c --- /dev/null +++ b/Lang/C++/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/C++ \ No newline at end of file diff --git a/Lang/C++/Set-puzzle b/Lang/C++/Set-puzzle new file mode 120000 index 0000000000..2421c00dbe --- /dev/null +++ b/Lang/C++/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/C++ \ No newline at end of file diff --git a/Lang/C++/Singly-linked-list-Traversal b/Lang/C++/Singly-linked-list-Traversal new file mode 120000 index 0000000000..bc003fe392 --- /dev/null +++ b/Lang/C++/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/C++ \ No newline at end of file diff --git a/Lang/C++/Sockets b/Lang/C++/Sockets new file mode 120000 index 0000000000..24ad9e8e89 --- /dev/null +++ b/Lang/C++/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/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..0baa0ba2e9 --- /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++/Stern-Brocot-sequence b/Lang/C++/Stern-Brocot-sequence new file mode 120000 index 0000000000..f68a6323a8 --- /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-comparison b/Lang/C++/String-comparison new file mode 120000 index 0000000000..2fb6cfb595 --- /dev/null +++ b/Lang/C++/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/C++ \ No newline at end of file diff --git a/Lang/C++/Synchronous-concurrency b/Lang/C++/Synchronous-concurrency new file mode 120000 index 0000000000..5a41569eb9 --- /dev/null +++ b/Lang/C++/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/C++ \ No newline at end of file diff --git a/Lang/C++/Ternary-logic b/Lang/C++/Ternary-logic new file mode 120000 index 0000000000..0dc526331c --- /dev/null +++ b/Lang/C++/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/C++ \ No newline at end of file diff --git a/Lang/C++/Textonyms b/Lang/C++/Textonyms new file mode 120000 index 0000000000..1b22df04c3 --- /dev/null +++ b/Lang/C++/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/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..3a653255ef --- /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..f8d651b095 --- /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-sharp/00DESCRIPTION b/Lang/C-sharp/00DESCRIPTION index f9abd37fde..17083312b1 100644 --- a/Lang/C-sharp/00DESCRIPTION +++ b/Lang/C-sharp/00DESCRIPTION @@ -15,7 +15,7 @@ '''C#''' is an [[object-oriented language|object-oriented programming language]] developed by Microsoft as part of their .NET initiative, and later approved as a standard by [[wp:ECMA|ECMA]] and [[ISO]]. C# has a procedural, [[object-oriented language|object-oriented]] syntax based on [[C++]] that includes aspects of several other programming languages (most notably [[Delphi]] and [[Java]]) with a particular emphasis on simplification (fewer symbolic requirements than [[C++]], fewer declarative requirements than [[Java]]). ==Citations== -*[[wp:C_sharp|Wikipedia:C#]] +*[[wp:C_Sharp_(programming_language)|Wikipedia:C#]] {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} diff --git a/Lang/C-sharp/AKS-test-for-primes b/Lang/C-sharp/AKS-test-for-primes new file mode 120000 index 0000000000..59eb71bffa --- /dev/null +++ b/Lang/C-sharp/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Count-the-coins b/Lang/C-sharp/Count-the-coins new file mode 120000 index 0000000000..55b5d2e2b7 --- /dev/null +++ b/Lang/C-sharp/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Seven-sided-dice-from-five-sided-dice b/Lang/C-sharp/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..2dfa820da7 --- /dev/null +++ b/Lang/C-sharp/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/C-sharp \ No newline at end of file diff --git a/Lang/C/00DESCRIPTION b/Lang/C/00DESCRIPTION index ccc5e68a4b..a13bdf35b5 100644 --- a/Lang/C/00DESCRIPTION +++ b/Lang/C/00DESCRIPTION @@ -19,10 +19,10 @@ C has since spread to many other [[:Category:Platforms|platforms]], and is now o ==Versions== * '''K&R C''' was the first widely-used form of C. It was originally documented in ''The C Programming Language'', published in 1978. It is named for the authors, Brian Kernighan and Dennis Ritchie (also the language's creator). Code in this style is virtually nonexistent today. -* '''C89''' (often called '''[[ANSI]] C''') is the version of C standardized by ANSI in 1989. It is the most commonly used and supported version of the language. The term "C" usually refers to C89 or C90. -* '''C90''' (often called '''[[ISO]] C''') is a minor improvement to C89, standardized by ISO in 1990. Most C compilers support it by default. -* '''C99''' is a significant improvement, adopting many features of [[C++]] and standardizing common compiler extensions. It was standardized by ISO in 1999, and by ANSI in 2000. It is not completely supported by many, if any, compilers, but most of its features are available in [[GCC]]. [http://gcc.gnu.org/c99status.html] -* '''C11''' is the current standard, published in December 2011. Some of its features are available in GCC. [http://gcc.gnu.org/gcc-4.6/changes.html#c] +* '''C89''' (often called '''[[ANSI]] C''') is the version of C standardized by ANSI in 1989. It is the most commonly used and supported version of the language. +* '''C90''' (often called '''[[ISO]] C''') is identical to C89, republished by ISO in 1990. +* '''C99''' is a significant improvement, adopting many features of [[C++]] and standardizing common compiler extensions. It was standardized by ISO in 1999, and by ANSI in 2000. It is primarily supported by commercial C compilers, but most of its features are available in [[Clang]] [[GCC]]. [http://gcc.gnu.org/c99status.html] +* '''C11''' is the current standard, published in December 2011. It is the default for [[GCC]] as of version 5.1. ==Citation== *[[wp:C_%28programming_language%29|Wikipedia:C (programming language)]] diff --git a/Lang/C/Empty-string b/Lang/C/Empty-string deleted file mode 120000 index c3476a092f..0000000000 --- a/Lang/C/Empty-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Empty-string/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..e6a332c5ee --- /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/Find-the-last-Sunday-of-each-month b/Lang/C/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..8b4fd5b784 --- /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/COBOL/Extend-your-language b/Lang/COBOL/Extend-your-language new file mode 120000 index 0000000000..cdc126430b --- /dev/null +++ b/Lang/COBOL/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/COBOL \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/100-doors b/Lang/Cache-ObjectScript/100-doors new file mode 120000 index 0000000000..5b24659271 --- /dev/null +++ b/Lang/Cache-ObjectScript/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Variables b/Lang/Cache-ObjectScript/Variables new file mode 120000 index 0000000000..7999e783ab --- /dev/null +++ b/Lang/Cache-ObjectScript/Variables @@ -0,0 +1 @@ +../../Task/Variables/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Chapel/Conways-Game-of-Life b/Lang/Chapel/Conways-Game-of-Life new file mode 120000 index 0000000000..84a9c89df7 --- /dev/null +++ b/Lang/Chapel/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Langtons-ant b/Lang/Chapel/Langtons-ant new file mode 120000 index 0000000000..9bdf46a589 --- /dev/null +++ b/Lang/Chapel/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Monty-Hall-problem b/Lang/Chapel/Monty-Hall-problem new file mode 120000 index 0000000000..0055dde2c0 --- /dev/null +++ b/Lang/Chapel/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Chapel \ No newline at end of file diff --git a/Lang/Chapel/Solve-the-no-connection-puzzle b/Lang/Chapel/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..75f9bce49f --- /dev/null +++ b/Lang/Chapel/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Chapel \ No newline at end of file diff --git a/Lang/Clojure/9-billion-names-of-God-the-integer b/Lang/Clojure/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..759b96b661 --- /dev/null +++ b/Lang/Clojure/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Abundant,-deficient-and-perfect-number-classifications b/Lang/Clojure/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..0140b1a44b --- /dev/null +++ b/Lang/Clojure/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Averages-Mean-angle b/Lang/Clojure/Averages-Mean-angle new file mode 120000 index 0000000000..d24f5a2cf2 --- /dev/null +++ b/Lang/Clojure/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Bitmap-Midpoint-circle-algorithm b/Lang/Clojure/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..3197523626 --- /dev/null +++ b/Lang/Clojure/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Call-a-foreign-language-function b/Lang/Clojure/Call-a-foreign-language-function new file mode 120000 index 0000000000..ededbc8ca5 --- /dev/null +++ b/Lang/Clojure/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Cholesky-decomposition b/Lang/Clojure/Cholesky-decomposition new file mode 120000 index 0000000000..e374976a47 --- /dev/null +++ b/Lang/Clojure/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Currying b/Lang/Clojure/Currying new file mode 120000 index 0000000000..7384b862d9 --- /dev/null +++ b/Lang/Clojure/Currying @@ -0,0 +1 @@ +../../Task/Currying/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Deal-cards-for-FreeCell b/Lang/Clojure/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..624d84e2b6 --- /dev/null +++ b/Lang/Clojure/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Clojure/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..e0b4a30868 --- /dev/null +++ b/Lang/Clojure/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Flipping-bits-game b/Lang/Clojure/Flipping-bits-game new file mode 120000 index 0000000000..20e9405b9a --- /dev/null +++ b/Lang/Clojure/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Clojure \ No newline at end of file diff --git a/Lang/Clojure/HTTPS-Authenticated b/Lang/Clojure/HTTPS-Authenticated new file mode 120000 index 0000000000..7f8f14a4d5 --- /dev/null +++ b/Lang/Clojure/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Josephus-problem b/Lang/Clojure/Josephus-problem new file mode 120000 index 0000000000..09b116fea0 --- /dev/null +++ b/Lang/Clojure/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Keyboard-input-Keypress-check b/Lang/Clojure/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..cce6710918 --- /dev/null +++ b/Lang/Clojure/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Clojure/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..0a5eed23e4 --- /dev/null +++ b/Lang/Clojure/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Keyboard-macros b/Lang/Clojure/Keyboard-macros new file mode 120000 index 0000000000..b4d75df9d1 --- /dev/null +++ b/Lang/Clojure/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Parametrized-SQL-statement b/Lang/Clojure/Parametrized-SQL-statement new file mode 120000 index 0000000000..e333a34051 --- /dev/null +++ b/Lang/Clojure/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Permutations-by-swapping b/Lang/Clojure/Permutations-by-swapping new file mode 120000 index 0000000000..15348ad6a1 --- /dev/null +++ b/Lang/Clojure/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Phrase-reversals b/Lang/Clojure/Phrase-reversals new file mode 120000 index 0000000000..78eaafca64 --- /dev/null +++ b/Lang/Clojure/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Runtime-evaluation-In-an-environment b/Lang/Clojure/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..d7d5206842 --- /dev/null +++ b/Lang/Clojure/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sparkline-in-unicode b/Lang/Clojure/Sparkline-in-unicode new file mode 120000 index 0000000000..4831c39f7c --- /dev/null +++ b/Lang/Clojure/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Table-creation-Postal-addresses b/Lang/Clojure/Table-creation-Postal-addresses new file mode 120000 index 0000000000..d249688bbc --- /dev/null +++ b/Lang/Clojure/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Visualize-a-tree b/Lang/Clojure/Visualize-a-tree new file mode 120000 index 0000000000..47ffb8d97b --- /dev/null +++ b/Lang/Clojure/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/CRC-32 b/Lang/CoffeeScript/CRC-32 new file mode 120000 index 0000000000..f432d5acdc --- /dev/null +++ b/Lang/CoffeeScript/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Five-weekends b/Lang/CoffeeScript/Five-weekends new file mode 120000 index 0000000000..789f92fb18 --- /dev/null +++ b/Lang/CoffeeScript/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Generate-lower-case-ASCII-alphabet b/Lang/CoffeeScript/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..094f4137ac --- /dev/null +++ b/Lang/CoffeeScript/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/MD5-Implementation b/Lang/CoffeeScript/MD5-Implementation new file mode 120000 index 0000000000..81a68cf3ef --- /dev/null +++ b/Lang/CoffeeScript/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Map-range b/Lang/CoffeeScript/Map-range new file mode 120000 index 0000000000..8547009576 --- /dev/null +++ b/Lang/CoffeeScript/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Show-the-epoch b/Lang/CoffeeScript/Show-the-epoch new file mode 120000 index 0000000000..29184636f2 --- /dev/null +++ b/Lang/CoffeeScript/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/XML-XPath b/Lang/CoffeeScript/XML-XPath new file mode 120000 index 0000000000..03a0264119 --- /dev/null +++ b/Lang/CoffeeScript/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/CoffeeScript \ No newline at end of file diff --git a/Lang/ColdFusion/Integer-comparison b/Lang/ColdFusion/Integer-comparison new file mode 120000 index 0000000000..bc60b0c99f --- /dev/null +++ b/Lang/ColdFusion/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/String-comparison b/Lang/ColdFusion/String-comparison new file mode 120000 index 0000000000..63238dce86 --- /dev/null +++ b/Lang/ColdFusion/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/ColdFusion \ No newline at end of file diff --git a/Lang/Common-Lisp/Abundant,-deficient-and-perfect-number-classifications b/Lang/Common-Lisp/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..2780952cca --- /dev/null +++ b/Lang/Common-Lisp/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Call-a-function b/Lang/Common-Lisp/Call-a-function new file mode 120000 index 0000000000..d7550c5ee0 --- /dev/null +++ b/Lang/Common-Lisp/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Create-an-HTML-table b/Lang/Common-Lisp/Create-an-HTML-table new file mode 120000 index 0000000000..9e9f8cdd25 --- /dev/null +++ b/Lang/Common-Lisp/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Empty-program b/Lang/Common-Lisp/Empty-program new file mode 120000 index 0000000000..8e0733132c --- /dev/null +++ b/Lang/Common-Lisp/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Fast-Fourier-transform b/Lang/Common-Lisp/Fast-Fourier-transform new file mode 120000 index 0000000000..c880087c24 --- /dev/null +++ b/Lang/Common-Lisp/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Fibonacci-word b/Lang/Common-Lisp/Fibonacci-word new file mode 120000 index 0000000000..c420dc38ff --- /dev/null +++ b/Lang/Common-Lisp/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Fractal-tree b/Lang/Common-Lisp/Fractal-tree new file mode 120000 index 0000000000..edafb1cca1 --- /dev/null +++ b/Lang/Common-Lisp/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/GUI-component-interaction b/Lang/Common-Lisp/GUI-component-interaction new file mode 120000 index 0000000000..bd4f0e2f30 --- /dev/null +++ b/Lang/Common-Lisp/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Handle-a-signal b/Lang/Common-Lisp/Handle-a-signal new file mode 120000 index 0000000000..f7289b68c5 --- /dev/null +++ b/Lang/Common-Lisp/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Hello-world-Newbie b/Lang/Common-Lisp/Hello-world-Newbie new file mode 120000 index 0000000000..bf8644bc2a --- /dev/null +++ b/Lang/Common-Lisp/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Iterated-digits-squaring b/Lang/Common-Lisp/Iterated-digits-squaring new file mode 120000 index 0000000000..8c47236aeb --- /dev/null +++ b/Lang/Common-Lisp/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Jump-anywhere b/Lang/Common-Lisp/Jump-anywhere new file mode 120000 index 0000000000..567567c7d9 --- /dev/null +++ b/Lang/Common-Lisp/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Largest-int-from-concatenated-ints b/Lang/Common-Lisp/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..b51f10aeeb --- /dev/null +++ b/Lang/Common-Lisp/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Left-factorials b/Lang/Common-Lisp/Left-factorials new file mode 120000 index 0000000000..9e413fd166 --- /dev/null +++ b/Lang/Common-Lisp/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Lucas-Lehmer-test b/Lang/Common-Lisp/Lucas-Lehmer-test new file mode 120000 index 0000000000..cfeef2e804 --- /dev/null +++ b/Lang/Common-Lisp/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Make-directory-path b/Lang/Common-Lisp/Make-directory-path new file mode 120000 index 0000000000..43669e2e37 --- /dev/null +++ b/Lang/Common-Lisp/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Metronome b/Lang/Common-Lisp/Metronome new file mode 120000 index 0000000000..e23843cae0 --- /dev/null +++ b/Lang/Common-Lisp/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Parallel-calculations b/Lang/Common-Lisp/Parallel-calculations new file mode 120000 index 0000000000..0732c6412a --- /dev/null +++ b/Lang/Common-Lisp/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Pi b/Lang/Common-Lisp/Pi new file mode 120000 index 0000000000..ae629f41e7 --- /dev/null +++ b/Lang/Common-Lisp/Pi @@ -0,0 +1 @@ +../../Task/Pi/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Priority-queue b/Lang/Common-Lisp/Priority-queue new file mode 120000 index 0000000000..daac3be7d1 --- /dev/null +++ b/Lang/Common-Lisp/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Quaternion-type b/Lang/Common-Lisp/Quaternion-type new file mode 120000 index 0000000000..dd7bafa7e8 --- /dev/null +++ b/Lang/Common-Lisp/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Quickselect-algorithm b/Lang/Common-Lisp/Quickselect-algorithm new file mode 120000 index 0000000000..5ba11df16c --- /dev/null +++ b/Lang/Common-Lisp/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Read-a-configuration-file b/Lang/Common-Lisp/Read-a-configuration-file new file mode 120000 index 0000000000..d2daf80647 --- /dev/null +++ b/Lang/Common-Lisp/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Record-sound b/Lang/Common-Lisp/Record-sound new file mode 120000 index 0000000000..c6c81c5604 --- /dev/null +++ b/Lang/Common-Lisp/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Runge-Kutta-method b/Lang/Common-Lisp/Runge-Kutta-method new file mode 120000 index 0000000000..ee99c84235 --- /dev/null +++ b/Lang/Common-Lisp/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Semordnilap b/Lang/Common-Lisp/Semordnilap new file mode 120000 index 0000000000..9de23da834 --- /dev/null +++ b/Lang/Common-Lisp/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Simulate-input-Mouse b/Lang/Common-Lisp/Simulate-input-Mouse new file mode 120000 index 0000000000..b4607e1b9d --- /dev/null +++ b/Lang/Common-Lisp/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Bead-sort b/Lang/Common-Lisp/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..5e0e3c51fe --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Terminal-control-Clear-the-screen b/Lang/Common-Lisp/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..ddc90d95e4 --- /dev/null +++ b/Lang/Common-Lisp/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Terminal-control-Display-an-extended-character b/Lang/Common-Lisp/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..35bfacc770 --- /dev/null +++ b/Lang/Common-Lisp/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Terminal-control-Hiding-the-cursor b/Lang/Common-Lisp/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..7ca7ec0574 --- /dev/null +++ b/Lang/Common-Lisp/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Terminal-control-Preserve-screen b/Lang/Common-Lisp/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..388d51911c --- /dev/null +++ b/Lang/Common-Lisp/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Terminal-control-Ringing-the-terminal-bell b/Lang/Common-Lisp/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..f763a5fb4d --- /dev/null +++ b/Lang/Common-Lisp/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Terminal-control-Unicode-output b/Lang/Common-Lisp/Terminal-control-Unicode-output new file mode 120000 index 0000000000..9c85e54d8a --- /dev/null +++ b/Lang/Common-Lisp/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Unicode-strings b/Lang/Common-Lisp/Unicode-strings new file mode 120000 index 0000000000..6e3adaeaec --- /dev/null +++ b/Lang/Common-Lisp/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Vampire-number b/Lang/Common-Lisp/Vampire-number new file mode 120000 index 0000000000..0b3ef4f73b --- /dev/null +++ b/Lang/Common-Lisp/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Visualize-a-tree b/Lang/Common-Lisp/Visualize-a-tree new file mode 120000 index 0000000000..704d84f4a1 --- /dev/null +++ b/Lang/Common-Lisp/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Write-language-name-in-3D-ASCII b/Lang/Common-Lisp/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..f1c6b9f29a --- /dev/null +++ b/Lang/Common-Lisp/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Common-Lisp \ No newline at end of file diff --git a/Lang/Coq/Variadic-function b/Lang/Coq/Variadic-function new file mode 120000 index 0000000000..391626fb92 --- /dev/null +++ b/Lang/Coq/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Coq \ No newline at end of file diff --git a/Lang/D/Textonyms b/Lang/D/Textonyms new file mode 120000 index 0000000000..b6588325ea --- /dev/null +++ b/Lang/D/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/D \ No newline at end of file diff --git a/Lang/DCL/A+B b/Lang/DCL/A+B new file mode 120000 index 0000000000..cbef1fc75e --- /dev/null +++ b/Lang/DCL/A+B @@ -0,0 +1 @@ +../../Task/A+B/DCL \ No newline at end of file diff --git a/Lang/DCL/Arithmetic-Integer b/Lang/DCL/Arithmetic-Integer new file mode 120000 index 0000000000..b15561702e --- /dev/null +++ b/Lang/DCL/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/DCL \ No newline at end of file diff --git a/Lang/DCL/Catamorphism b/Lang/DCL/Catamorphism new file mode 120000 index 0000000000..bcde40cf1d --- /dev/null +++ b/Lang/DCL/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/DCL \ No newline at end of file diff --git a/Lang/DCL/Check-that-file-exists b/Lang/DCL/Check-that-file-exists new file mode 120000 index 0000000000..4bd3ffac42 --- /dev/null +++ b/Lang/DCL/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/DCL \ No newline at end of file diff --git a/Lang/DCL/Comma-quibbling b/Lang/DCL/Comma-quibbling new file mode 120000 index 0000000000..e48306e4df --- /dev/null +++ b/Lang/DCL/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/DCL \ No newline at end of file diff --git a/Lang/DCL/Command-line-arguments b/Lang/DCL/Command-line-arguments new file mode 120000 index 0000000000..7fa4ffea96 --- /dev/null +++ b/Lang/DCL/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/DCL \ No newline at end of file diff --git a/Lang/DCL/Count-in-factors b/Lang/DCL/Count-in-factors new file mode 120000 index 0000000000..0b2a438761 --- /dev/null +++ b/Lang/DCL/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/DCL \ No newline at end of file diff --git a/Lang/DCL/Count-in-octal b/Lang/DCL/Count-in-octal new file mode 120000 index 0000000000..5aeae10e51 --- /dev/null +++ b/Lang/DCL/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/DCL \ No newline at end of file diff --git a/Lang/DCL/Digital-root b/Lang/DCL/Digital-root new file mode 120000 index 0000000000..3b2dcea40e --- /dev/null +++ b/Lang/DCL/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/DCL \ No newline at end of file diff --git a/Lang/DCL/Even-or-odd b/Lang/DCL/Even-or-odd new file mode 120000 index 0000000000..63fc304587 --- /dev/null +++ b/Lang/DCL/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/DCL \ No newline at end of file diff --git a/Lang/DCL/File-input-output b/Lang/DCL/File-input-output new file mode 120000 index 0000000000..b30d6bfb69 --- /dev/null +++ b/Lang/DCL/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/DCL \ No newline at end of file diff --git a/Lang/DCL/Fork b/Lang/DCL/Fork new file mode 120000 index 0000000000..80a2faed83 --- /dev/null +++ b/Lang/DCL/Fork @@ -0,0 +1 @@ +../../Task/Fork/DCL \ No newline at end of file diff --git a/Lang/DCL/Generic-swap b/Lang/DCL/Generic-swap new file mode 120000 index 0000000000..6ac91c51c9 --- /dev/null +++ b/Lang/DCL/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/DCL \ No newline at end of file diff --git a/Lang/DCL/Greatest-element-of-a-list b/Lang/DCL/Greatest-element-of-a-list new file mode 120000 index 0000000000..d042fdcac0 --- /dev/null +++ b/Lang/DCL/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/DCL \ No newline at end of file diff --git a/Lang/DCL/Guess-the-number b/Lang/DCL/Guess-the-number new file mode 120000 index 0000000000..c318f3cdf7 --- /dev/null +++ b/Lang/DCL/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/DCL \ No newline at end of file diff --git a/Lang/DCL/Guess-the-number-With-feedback b/Lang/DCL/Guess-the-number-With-feedback new file mode 120000 index 0000000000..e6ac473fd0 --- /dev/null +++ b/Lang/DCL/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/DCL \ No newline at end of file diff --git a/Lang/DCL/Hailstone-sequence b/Lang/DCL/Hailstone-sequence new file mode 120000 index 0000000000..767fdcfca4 --- /dev/null +++ b/Lang/DCL/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/DCL \ No newline at end of file diff --git a/Lang/DCL/Hamming-numbers b/Lang/DCL/Hamming-numbers new file mode 120000 index 0000000000..4ad8115196 --- /dev/null +++ b/Lang/DCL/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/DCL \ No newline at end of file diff --git a/Lang/DCL/Happy-numbers b/Lang/DCL/Happy-numbers new file mode 120000 index 0000000000..91f536a478 --- /dev/null +++ b/Lang/DCL/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/DCL \ No newline at end of file diff --git a/Lang/DCL/Hello-world-Text b/Lang/DCL/Hello-world-Text new file mode 120000 index 0000000000..9ac5db64a8 --- /dev/null +++ b/Lang/DCL/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/DCL \ No newline at end of file diff --git a/Lang/DCL/Integer-comparison b/Lang/DCL/Integer-comparison new file mode 120000 index 0000000000..ba925228e0 --- /dev/null +++ b/Lang/DCL/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/DCL \ No newline at end of file diff --git a/Lang/DCL/Integer-sequence b/Lang/DCL/Integer-sequence new file mode 120000 index 0000000000..4242dc78c7 --- /dev/null +++ b/Lang/DCL/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/DCL \ No newline at end of file diff --git a/Lang/DCL/Jump-anywhere b/Lang/DCL/Jump-anywhere new file mode 120000 index 0000000000..6e2ae79824 --- /dev/null +++ b/Lang/DCL/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/DCL \ No newline at end of file diff --git a/Lang/DCL/Keyboard-input-Flush-the-keyboard-buffer b/Lang/DCL/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..74dc64ee09 --- /dev/null +++ b/Lang/DCL/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/DCL \ No newline at end of file diff --git a/Lang/DCL/Literals-Integer b/Lang/DCL/Literals-Integer new file mode 120000 index 0000000000..d58453438c --- /dev/null +++ b/Lang/DCL/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/DCL \ No newline at end of file diff --git a/Lang/DCL/Loops-Infinite b/Lang/DCL/Loops-Infinite new file mode 120000 index 0000000000..72d8bb8951 --- /dev/null +++ b/Lang/DCL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/DCL \ No newline at end of file diff --git a/Lang/DCL/Middle-three-digits b/Lang/DCL/Middle-three-digits new file mode 120000 index 0000000000..982c5d0265 --- /dev/null +++ b/Lang/DCL/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/DCL \ No newline at end of file diff --git a/Lang/DCL/Multiplication-tables b/Lang/DCL/Multiplication-tables new file mode 120000 index 0000000000..6d620c13ca --- /dev/null +++ b/Lang/DCL/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/DCL \ No newline at end of file diff --git a/Lang/DCL/Read-a-configuration-file b/Lang/DCL/Read-a-configuration-file new file mode 120000 index 0000000000..5392443f00 --- /dev/null +++ b/Lang/DCL/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/DCL \ No newline at end of file diff --git a/Lang/DCL/Read-a-file-line-by-line b/Lang/DCL/Read-a-file-line-by-line new file mode 120000 index 0000000000..db6c21f4b9 --- /dev/null +++ b/Lang/DCL/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/DCL \ No newline at end of file diff --git a/Lang/DCL/Repeat-a-string b/Lang/DCL/Repeat-a-string new file mode 120000 index 0000000000..45af04f9b6 --- /dev/null +++ b/Lang/DCL/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/DCL \ No newline at end of file diff --git a/Lang/DCL/Semiprime b/Lang/DCL/Semiprime new file mode 120000 index 0000000000..6ec0a7b2cc --- /dev/null +++ b/Lang/DCL/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/DCL \ No newline at end of file diff --git a/Lang/DCL/Sleep b/Lang/DCL/Sleep new file mode 120000 index 0000000000..d27e289d8a --- /dev/null +++ b/Lang/DCL/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/DCL \ No newline at end of file diff --git a/Lang/DCL/Spiral-matrix b/Lang/DCL/Spiral-matrix new file mode 120000 index 0000000000..8addd99e4b --- /dev/null +++ b/Lang/DCL/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/DCL \ No newline at end of file diff --git a/Lang/DCL/String-concatenation b/Lang/DCL/String-concatenation new file mode 120000 index 0000000000..810148d5e6 --- /dev/null +++ b/Lang/DCL/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/DCL \ No newline at end of file diff --git a/Lang/DCL/String-matching b/Lang/DCL/String-matching new file mode 120000 index 0000000000..b9e331af10 --- /dev/null +++ b/Lang/DCL/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/DCL \ No newline at end of file diff --git a/Lang/DCL/System-time b/Lang/DCL/System-time new file mode 120000 index 0000000000..c81cf157d3 --- /dev/null +++ b/Lang/DCL/System-time @@ -0,0 +1 @@ +../../Task/System-time/DCL \ No newline at end of file diff --git a/Lang/DCL/Walk-a-directory-Non-recursively b/Lang/DCL/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..955c7b382b --- /dev/null +++ b/Lang/DCL/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/DCL \ No newline at end of file diff --git a/Lang/Dart/Loops-N-plus-one-half b/Lang/Dart/Loops-N-plus-one-half new file mode 120000 index 0000000000..babe60d296 --- /dev/null +++ b/Lang/Dart/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Dart \ No newline at end of file diff --git a/Lang/Dart/Palindrome-detection b/Lang/Dart/Palindrome-detection new file mode 120000 index 0000000000..35512e77a5 --- /dev/null +++ b/Lang/Dart/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Dart \ No newline at end of file diff --git a/Lang/Delphi/Gaussian-elimination b/Lang/Delphi/Gaussian-elimination new file mode 120000 index 0000000000..a0e2a4db4c --- /dev/null +++ b/Lang/Delphi/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Haversine-formula b/Lang/Delphi/Haversine-formula new file mode 120000 index 0000000000..1cc4386739 --- /dev/null +++ b/Lang/Delphi/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Identity-matrix b/Lang/Delphi/Identity-matrix new file mode 120000 index 0000000000..c8a29c3683 --- /dev/null +++ b/Lang/Delphi/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Pascals-triangle b/Lang/Delphi/Pascals-triangle new file mode 120000 index 0000000000..f4d1a41ad2 --- /dev/null +++ b/Lang/Delphi/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Polymorphic-copy b/Lang/Delphi/Polymorphic-copy new file mode 120000 index 0000000000..0e3aeab1c3 --- /dev/null +++ b/Lang/Delphi/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/Delphi \ No newline at end of file diff --git a/Lang/Eiffel/Anagrams b/Lang/Eiffel/Anagrams new file mode 120000 index 0000000000..d15e7e4abc --- /dev/null +++ b/Lang/Eiffel/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Anagrams-Deranged-anagrams b/Lang/Eiffel/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..058e942787 --- /dev/null +++ b/Lang/Eiffel/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Bulls-and-cows b/Lang/Eiffel/Bulls-and-cows new file mode 120000 index 0000000000..c6b59401da --- /dev/null +++ b/Lang/Eiffel/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Comma-quibbling b/Lang/Eiffel/Comma-quibbling new file mode 120000 index 0000000000..798aa5e055 --- /dev/null +++ b/Lang/Eiffel/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Comments b/Lang/Eiffel/Comments new file mode 120000 index 0000000000..6d72187223 --- /dev/null +++ b/Lang/Eiffel/Comments @@ -0,0 +1 @@ +../../Task/Comments/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Cut-a-rectangle b/Lang/Eiffel/Cut-a-rectangle new file mode 120000 index 0000000000..18905a9bbb --- /dev/null +++ b/Lang/Eiffel/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Even-or-odd b/Lang/Eiffel/Even-or-odd new file mode 120000 index 0000000000..06e3ad55d1 --- /dev/null +++ b/Lang/Eiffel/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Eiffel/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..facfe38fca --- /dev/null +++ b/Lang/Eiffel/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Hailstone-sequence b/Lang/Eiffel/Hailstone-sequence new file mode 120000 index 0000000000..9674c818da --- /dev/null +++ b/Lang/Eiffel/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Hofstadter-Conway-$10,000-sequence b/Lang/Eiffel/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..428735ae15 --- /dev/null +++ b/Lang/Eiffel/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Integer-comparison b/Lang/Eiffel/Integer-comparison new file mode 120000 index 0000000000..30759fe835 --- /dev/null +++ b/Lang/Eiffel/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Josephus-problem b/Lang/Eiffel/Josephus-problem new file mode 120000 index 0000000000..b49b00acfd --- /dev/null +++ b/Lang/Eiffel/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Knapsack-problem-0-1 b/Lang/Eiffel/Knapsack-problem-0-1 new file mode 120000 index 0000000000..23ae31bdb1 --- /dev/null +++ b/Lang/Eiffel/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Knapsack-problem-Continuous b/Lang/Eiffel/Knapsack-problem-Continuous new file mode 120000 index 0000000000..6cae0e5535 --- /dev/null +++ b/Lang/Eiffel/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Knapsack-problem-Unbounded b/Lang/Eiffel/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..93d66ae24d --- /dev/null +++ b/Lang/Eiffel/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/LZW-compression b/Lang/Eiffel/LZW-compression new file mode 120000 index 0000000000..d72ab23f77 --- /dev/null +++ b/Lang/Eiffel/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Middle-three-digits b/Lang/Eiffel/Middle-three-digits new file mode 120000 index 0000000000..d8de52c8f4 --- /dev/null +++ b/Lang/Eiffel/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Mutual-recursion b/Lang/Eiffel/Mutual-recursion new file mode 120000 index 0000000000..b9c23d845c --- /dev/null +++ b/Lang/Eiffel/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/One-dimensional-cellular-automata b/Lang/Eiffel/One-dimensional-cellular-automata new file mode 120000 index 0000000000..9f37a96b2a --- /dev/null +++ b/Lang/Eiffel/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/One-of-n-lines-in-a-file b/Lang/Eiffel/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..88c822ca75 --- /dev/null +++ b/Lang/Eiffel/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Pernicious-numbers b/Lang/Eiffel/Pernicious-numbers new file mode 120000 index 0000000000..3c8d973d5d --- /dev/null +++ b/Lang/Eiffel/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Price-fraction b/Lang/Eiffel/Price-fraction new file mode 120000 index 0000000000..8303fb7bb5 --- /dev/null +++ b/Lang/Eiffel/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Primality-by-trial-division b/Lang/Eiffel/Primality-by-trial-division new file mode 120000 index 0000000000..074e2c3246 --- /dev/null +++ b/Lang/Eiffel/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Self-referential-sequence b/Lang/Eiffel/Self-referential-sequence new file mode 120000 index 0000000000..068fb41393 --- /dev/null +++ b/Lang/Eiffel/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sequence-of-primes-by-Trial-Division b/Lang/Eiffel/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..6ae4aadc2f --- /dev/null +++ b/Lang/Eiffel/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Singleton b/Lang/Eiffel/Singleton new file mode 120000 index 0000000000..4bc0aed9a9 --- /dev/null +++ b/Lang/Eiffel/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Heapsort b/Lang/Eiffel/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..de7ee50d80 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Radix-sort b/Lang/Eiffel/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..f44ed09c18 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Text-processing-1 b/Lang/Eiffel/Text-processing-1 new file mode 120000 index 0000000000..c42ddb39ed --- /dev/null +++ b/Lang/Eiffel/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Text-processing-2 b/Lang/Eiffel/Text-processing-2 new file mode 120000 index 0000000000..41ea986713 --- /dev/null +++ b/Lang/Eiffel/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Text-processing-Max-licenses-in-use b/Lang/Eiffel/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..e37c3dae01 --- /dev/null +++ b/Lang/Eiffel/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/The-Twelve-Days-of-Christmas b/Lang/Eiffel/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..ecc5bd0a77 --- /dev/null +++ b/Lang/Eiffel/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Truncatable-primes b/Lang/Eiffel/Truncatable-primes new file mode 120000 index 0000000000..1250086d42 --- /dev/null +++ b/Lang/Eiffel/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Twelve-statements b/Lang/Eiffel/Twelve-statements new file mode 120000 index 0000000000..65c349ec38 --- /dev/null +++ b/Lang/Eiffel/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Vampire-number b/Lang/Eiffel/Vampire-number new file mode 120000 index 0000000000..7ee618cee7 --- /dev/null +++ b/Lang/Eiffel/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Zero-to-the-zero-power b/Lang/Eiffel/Zero-to-the-zero-power new file mode 120000 index 0000000000..9b0310c078 --- /dev/null +++ b/Lang/Eiffel/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Eiffel \ No newline at end of file diff --git a/Lang/Elena/00DESCRIPTION b/Lang/Elena/00DESCRIPTION index 42d4540b35..c737720fc5 100644 --- a/Lang/Elena/00DESCRIPTION +++ b/Lang/Elena/00DESCRIPTION @@ -11,13 +11,13 @@ == Overview == -ELENA is a general-purpose, object-oriented, polymorphic language with late binding. It features multiple dispatching, context-dependent roles, dynamic inheritance and group object support. +ELENA is a general-purpose, object-oriented, polymorphic language with late binding. It features message dispatching / manipulation, dynamic object mutation, a script engine / interpreter and group object support. -The language treats any program as a set of objects (class instances). The program flow is a process of interaction between objects by sending each other messages. A message may have attached information (a message parameter). An object may react on message if it has an appropriate message handler (a method). If the object reacts on the message it is treated as successful otherwise unsuccessful. In its turn the method may send messages to other objects and so on until the flow reaches the method written by external tools (meta method). If the message is unsuccessful the flow is considered to be broken. It's possible to declare alternative flow which are executed if previous ones are broken. The method has only one input parameter and one output parameter (the method may return itself). +Any program or library consists of modules containing classes and symbols. -Every object may be formed up with other objects characterizing its internal state. They in turn may be formed with others and so on until meta objects which internal states are considered as raw data. +The main way to interact with objects in ELENA is sending a message. The message name is structured and consists of a verb, a signature and a parameter counter. The verb defines a message action, for example read or write some data. There are only limited set of possible verbs. The signature is user defined and describes the message parameters. If the signature is not provided the message is considered to be generic and can be qualified (by dispatching). -All referring entities in the language are objects. A variable is a reference to the object allocated in the program heap. The literal and numeric constants are references to the objects allocated in the static memory. +If the object wants to handle the message it has to contain the method with the same name. If no method mapping was found the flow is considered to be broken and the control goes to the next alternative flow (exception handler) or the program is stopped. It is possible to declare generic handler which will be called for all incoming messages. == Namespaces == diff --git a/Lang/Elena/100-doors b/Lang/Elena/100-doors new file mode 120000 index 0000000000..18cf0d7347 --- /dev/null +++ b/Lang/Elena/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Elena \ No newline at end of file diff --git a/Lang/Elena/24-game b/Lang/Elena/24-game new file mode 120000 index 0000000000..55d0680ea6 --- /dev/null +++ b/Lang/Elena/24-game @@ -0,0 +1 @@ +../../Task/24-game/Elena \ No newline at end of file diff --git a/Lang/Elena/GUI-component-interaction b/Lang/Elena/GUI-component-interaction new file mode 120000 index 0000000000..dc042033d4 --- /dev/null +++ b/Lang/Elena/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Elena \ No newline at end of file diff --git a/Lang/Elena/Simple-windowed-application b/Lang/Elena/Simple-windowed-application new file mode 120000 index 0000000000..3394091036 --- /dev/null +++ b/Lang/Elena/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Elena \ No newline at end of file diff --git a/Lang/Elena/String-append b/Lang/Elena/String-append new file mode 120000 index 0000000000..af161571e4 --- /dev/null +++ b/Lang/Elena/String-append @@ -0,0 +1 @@ +../../Task/String-append/Elena \ No newline at end of file diff --git a/Lang/Elena/String-case b/Lang/Elena/String-case new file mode 120000 index 0000000000..f04e673c4c --- /dev/null +++ b/Lang/Elena/String-case @@ -0,0 +1 @@ +../../Task/String-case/Elena \ No newline at end of file diff --git a/Lang/Elena/String-comparison b/Lang/Elena/String-comparison new file mode 120000 index 0000000000..1400539849 --- /dev/null +++ b/Lang/Elena/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Elena \ No newline at end of file diff --git a/Lang/Elena/String-concatenation b/Lang/Elena/String-concatenation new file mode 120000 index 0000000000..e5525e5a1c --- /dev/null +++ b/Lang/Elena/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Elena \ No newline at end of file diff --git a/Lang/Elena/String-interpolation--included- b/Lang/Elena/String-interpolation--included- new file mode 120000 index 0000000000..632bd9cdc9 --- /dev/null +++ b/Lang/Elena/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Elena \ No newline at end of file diff --git a/Lang/Elena/String-prepend b/Lang/Elena/String-prepend new file mode 120000 index 0000000000..d40b0b9761 --- /dev/null +++ b/Lang/Elena/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Elena \ No newline at end of file diff --git a/Lang/Elixir/00DESCRIPTION b/Lang/Elixir/00DESCRIPTION index 391ae5b1b2..7075e16e09 100644 --- a/Lang/Elixir/00DESCRIPTION +++ b/Lang/Elixir/00DESCRIPTION @@ -1,4 +1,20 @@ {{stub}} {{language |site=http://elixir-lang.org}} -{{implementation|Erlang}} \ No newline at end of file +{{implementation|Erlang}} +Elixir is a dynamic, functional language designed for building scalable and maintainable applications. + +Elixir leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web development and the embedded software domain. + +Platform features +* Scalability +* Fault-tolerance + +Language features +* Functional programming +* Extensibility and DSLs + +Tooling features +* A growing ecosystem +* Interactive development +* Erlang compatible \ No newline at end of file diff --git a/Lang/Elixir/A+B b/Lang/Elixir/A+B new file mode 120000 index 0000000000..f978ff5e4f --- /dev/null +++ b/Lang/Elixir/A+B @@ -0,0 +1 @@ +../../Task/A+B/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Align-columns b/Lang/Elixir/Align-columns new file mode 120000 index 0000000000..213cf1282d --- /dev/null +++ b/Lang/Elixir/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Anagrams b/Lang/Elixir/Anagrams new file mode 120000 index 0000000000..51dd6c21dd --- /dev/null +++ b/Lang/Elixir/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Anonymous-recursion b/Lang/Elixir/Anonymous-recursion new file mode 120000 index 0000000000..c6ffa1a23b --- /dev/null +++ b/Lang/Elixir/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Arithmetic-Integer b/Lang/Elixir/Arithmetic-Integer new file mode 120000 index 0000000000..5aae1536bc --- /dev/null +++ b/Lang/Elixir/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Arithmetic-geometric-mean b/Lang/Elixir/Arithmetic-geometric-mean new file mode 120000 index 0000000000..5747b78619 --- /dev/null +++ b/Lang/Elixir/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Array-concatenation b/Lang/Elixir/Array-concatenation new file mode 120000 index 0000000000..62a79c4166 --- /dev/null +++ b/Lang/Elixir/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Associative-array-Creation b/Lang/Elixir/Associative-array-Creation new file mode 120000 index 0000000000..58a65b14e2 --- /dev/null +++ b/Lang/Elixir/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Associative-array-Iteration b/Lang/Elixir/Associative-array-Iteration new file mode 120000 index 0000000000..284a3095a1 --- /dev/null +++ b/Lang/Elixir/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Average-loop-length b/Lang/Elixir/Average-loop-length new file mode 120000 index 0000000000..67c9641241 --- /dev/null +++ b/Lang/Elixir/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Averages-Mode b/Lang/Elixir/Averages-Mode new file mode 120000 index 0000000000..0aaed6ae10 --- /dev/null +++ b/Lang/Elixir/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Binary-digits b/Lang/Elixir/Binary-digits new file mode 120000 index 0000000000..cb1bccde6e --- /dev/null +++ b/Lang/Elixir/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Bitwise-operations b/Lang/Elixir/Bitwise-operations new file mode 120000 index 0000000000..78007c9f63 --- /dev/null +++ b/Lang/Elixir/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Boolean-values b/Lang/Elixir/Boolean-values new file mode 120000 index 0000000000..260ffaa2da --- /dev/null +++ b/Lang/Elixir/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Elixir \ No newline at end of file diff --git a/Lang/Elixir/CRC-32 b/Lang/Elixir/CRC-32 new file mode 120000 index 0000000000..5c25f29e4e --- /dev/null +++ b/Lang/Elixir/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Caesar-cipher b/Lang/Elixir/Caesar-cipher new file mode 120000 index 0000000000..d765684ad7 --- /dev/null +++ b/Lang/Elixir/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Catalan-numbers b/Lang/Elixir/Catalan-numbers new file mode 120000 index 0000000000..9fca4611f4 --- /dev/null +++ b/Lang/Elixir/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Catalan-numbers-Pascals-triangle b/Lang/Elixir/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..415ebba8a9 --- /dev/null +++ b/Lang/Elixir/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Catamorphism b/Lang/Elixir/Catamorphism new file mode 120000 index 0000000000..dd2d7129e9 --- /dev/null +++ b/Lang/Elixir/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Character-codes b/Lang/Elixir/Character-codes new file mode 120000 index 0000000000..c73b8c151e --- /dev/null +++ b/Lang/Elixir/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Check-that-file-exists b/Lang/Elixir/Check-that-file-exists new file mode 120000 index 0000000000..62dd6dffe2 --- /dev/null +++ b/Lang/Elixir/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Chinese-remainder-theorem b/Lang/Elixir/Chinese-remainder-theorem new file mode 120000 index 0000000000..29bbb2dcf1 --- /dev/null +++ b/Lang/Elixir/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Circles-of-given-radius-through-two-points b/Lang/Elixir/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..ed76c1f9c8 --- /dev/null +++ b/Lang/Elixir/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Closest-pair-problem b/Lang/Elixir/Closest-pair-problem new file mode 120000 index 0000000000..52a5b5afd6 --- /dev/null +++ b/Lang/Elixir/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Combinations b/Lang/Elixir/Combinations new file mode 120000 index 0000000000..de74b1a5c0 --- /dev/null +++ b/Lang/Elixir/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Combinations-with-repetitions b/Lang/Elixir/Combinations-with-repetitions new file mode 120000 index 0000000000..93fb1a66a5 --- /dev/null +++ b/Lang/Elixir/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Comma-quibbling b/Lang/Elixir/Comma-quibbling new file mode 120000 index 0000000000..4a611c7955 --- /dev/null +++ b/Lang/Elixir/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Copy-a-string b/Lang/Elixir/Copy-a-string new file mode 120000 index 0000000000..ee5cbbcd24 --- /dev/null +++ b/Lang/Elixir/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Count-in-factors b/Lang/Elixir/Count-in-factors new file mode 120000 index 0000000000..f4717ec02e --- /dev/null +++ b/Lang/Elixir/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Count-in-octal b/Lang/Elixir/Count-in-octal new file mode 120000 index 0000000000..0210d9a9fe --- /dev/null +++ b/Lang/Elixir/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Count-occurrences-of-a-substring b/Lang/Elixir/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..d2eaaee7cf --- /dev/null +++ b/Lang/Elixir/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Count-the-coins b/Lang/Elixir/Count-the-coins new file mode 120000 index 0000000000..4872439e1a --- /dev/null +++ b/Lang/Elixir/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Date-format b/Lang/Elixir/Date-format new file mode 120000 index 0000000000..c46cefde9d --- /dev/null +++ b/Lang/Elixir/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Day-of-the-week b/Lang/Elixir/Day-of-the-week new file mode 120000 index 0000000000..dcaff8906e --- /dev/null +++ b/Lang/Elixir/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Delete-a-file b/Lang/Elixir/Delete-a-file new file mode 120000 index 0000000000..d1fa93ebf9 --- /dev/null +++ b/Lang/Elixir/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Detect-division-by-zero b/Lang/Elixir/Detect-division-by-zero new file mode 120000 index 0000000000..5f80e5cbea --- /dev/null +++ b/Lang/Elixir/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Determine-if-a-string-is-numeric b/Lang/Elixir/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..d607d3705b --- /dev/null +++ b/Lang/Elixir/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Digital-root b/Lang/Elixir/Digital-root new file mode 120000 index 0000000000..5ad84659dc --- /dev/null +++ b/Lang/Elixir/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Digital-root-Multiplicative-digital-root b/Lang/Elixir/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..b47bbbe9c2 --- /dev/null +++ b/Lang/Elixir/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Dinesmans-multiple-dwelling-problem b/Lang/Elixir/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..0eb32b2d7a --- /dev/null +++ b/Lang/Elixir/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Documentation b/Lang/Elixir/Documentation new file mode 120000 index 0000000000..4cbfd2459a --- /dev/null +++ b/Lang/Elixir/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Dot-product b/Lang/Elixir/Dot-product new file mode 120000 index 0000000000..6d4d123705 --- /dev/null +++ b/Lang/Elixir/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Draw-a-cuboid b/Lang/Elixir/Draw-a-cuboid new file mode 120000 index 0000000000..d7d1089c4e --- /dev/null +++ b/Lang/Elixir/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Dutch-national-flag-problem b/Lang/Elixir/Dutch-national-flag-problem new file mode 120000 index 0000000000..28acb9ce3a --- /dev/null +++ b/Lang/Elixir/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Empty-directory b/Lang/Elixir/Empty-directory new file mode 120000 index 0000000000..953e999d60 --- /dev/null +++ b/Lang/Elixir/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Empty-program b/Lang/Elixir/Empty-program new file mode 120000 index 0000000000..e1c7956a55 --- /dev/null +++ b/Lang/Elixir/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Entropy b/Lang/Elixir/Entropy new file mode 120000 index 0000000000..22be4b4d04 --- /dev/null +++ b/Lang/Elixir/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Enumerations b/Lang/Elixir/Enumerations new file mode 120000 index 0000000000..6119a6f430 --- /dev/null +++ b/Lang/Elixir/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Environment-variables b/Lang/Elixir/Environment-variables new file mode 120000 index 0000000000..da19a25e80 --- /dev/null +++ b/Lang/Elixir/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Equilibrium-index b/Lang/Elixir/Equilibrium-index new file mode 120000 index 0000000000..81051963c3 --- /dev/null +++ b/Lang/Elixir/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Ethiopian-multiplication b/Lang/Elixir/Ethiopian-multiplication new file mode 120000 index 0000000000..8150ab025f --- /dev/null +++ b/Lang/Elixir/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Euler-method b/Lang/Elixir/Euler-method new file mode 120000 index 0000000000..8ff1e7d916 --- /dev/null +++ b/Lang/Elixir/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Evaluate-binomial-coefficients b/Lang/Elixir/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..82b20cd8db --- /dev/null +++ b/Lang/Elixir/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Even-or-odd b/Lang/Elixir/Even-or-odd new file mode 120000 index 0000000000..ce9c1ad390 --- /dev/null +++ b/Lang/Elixir/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Events b/Lang/Elixir/Events new file mode 120000 index 0000000000..313be20db8 --- /dev/null +++ b/Lang/Elixir/Events @@ -0,0 +1 @@ +../../Task/Events/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Evolutionary-algorithm b/Lang/Elixir/Evolutionary-algorithm new file mode 120000 index 0000000000..d711366fa9 --- /dev/null +++ b/Lang/Elixir/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Elixir/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..661d69136d --- /dev/null +++ b/Lang/Elixir/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Exponentiation-operator b/Lang/Elixir/Exponentiation-operator new file mode 120000 index 0000000000..81d7c2bdb2 --- /dev/null +++ b/Lang/Elixir/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Factors-of-an-integer b/Lang/Elixir/Factors-of-an-integer new file mode 120000 index 0000000000..12c4abdf4a --- /dev/null +++ b/Lang/Elixir/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Fibonacci-n-step-number-sequences b/Lang/Elixir/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..4b50e59b64 --- /dev/null +++ b/Lang/Elixir/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Fibonacci-sequence b/Lang/Elixir/Fibonacci-sequence new file mode 120000 index 0000000000..66661512e6 --- /dev/null +++ b/Lang/Elixir/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Fibonacci-word b/Lang/Elixir/Fibonacci-word new file mode 120000 index 0000000000..5e7645a785 --- /dev/null +++ b/Lang/Elixir/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Fibonacci-word-fractal b/Lang/Elixir/Fibonacci-word-fractal new file mode 120000 index 0000000000..050d9b29d1 --- /dev/null +++ b/Lang/Elixir/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Elixir \ No newline at end of file diff --git a/Lang/Elixir/File-input-output b/Lang/Elixir/File-input-output new file mode 120000 index 0000000000..008c9242df --- /dev/null +++ b/Lang/Elixir/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Elixir \ No newline at end of file diff --git a/Lang/Elixir/File-size b/Lang/Elixir/File-size new file mode 120000 index 0000000000..52933ed290 --- /dev/null +++ b/Lang/Elixir/File-size @@ -0,0 +1 @@ +../../Task/File-size/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Filter b/Lang/Elixir/Filter new file mode 120000 index 0000000000..574b1792c8 --- /dev/null +++ b/Lang/Elixir/Filter @@ -0,0 +1 @@ +../../Task/Filter/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Find-common-directory-path b/Lang/Elixir/Find-common-directory-path new file mode 120000 index 0000000000..ce30031071 --- /dev/null +++ b/Lang/Elixir/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Find-the-last-Sunday-of-each-month b/Lang/Elixir/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..2e0510ea07 --- /dev/null +++ b/Lang/Elixir/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Find-the-missing-permutation b/Lang/Elixir/Find-the-missing-permutation new file mode 120000 index 0000000000..2341bbbcea --- /dev/null +++ b/Lang/Elixir/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Five-weekends b/Lang/Elixir/Five-weekends new file mode 120000 index 0000000000..5ee7305eee --- /dev/null +++ b/Lang/Elixir/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Floyds-triangle b/Lang/Elixir/Floyds-triangle new file mode 120000 index 0000000000..7d864c317b --- /dev/null +++ b/Lang/Elixir/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Fork b/Lang/Elixir/Fork new file mode 120000 index 0000000000..7308685c06 --- /dev/null +++ b/Lang/Elixir/Fork @@ -0,0 +1 @@ +../../Task/Fork/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Formatted-numeric-output b/Lang/Elixir/Formatted-numeric-output new file mode 120000 index 0000000000..acb5d1019c --- /dev/null +++ b/Lang/Elixir/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Forward-difference b/Lang/Elixir/Forward-difference new file mode 120000 index 0000000000..5b50140fe8 --- /dev/null +++ b/Lang/Elixir/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Function-composition b/Lang/Elixir/Function-composition new file mode 120000 index 0000000000..eced76c0e9 --- /dev/null +++ b/Lang/Elixir/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Function-definition b/Lang/Elixir/Function-definition new file mode 120000 index 0000000000..9c38a0ef78 --- /dev/null +++ b/Lang/Elixir/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Gamma-function b/Lang/Elixir/Gamma-function new file mode 120000 index 0000000000..52b9c05dbd --- /dev/null +++ b/Lang/Elixir/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Generate-lower-case-ASCII-alphabet b/Lang/Elixir/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..5e005752c7 --- /dev/null +++ b/Lang/Elixir/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Generic-swap b/Lang/Elixir/Generic-swap new file mode 120000 index 0000000000..45032353ae --- /dev/null +++ b/Lang/Elixir/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Gray-code b/Lang/Elixir/Gray-code new file mode 120000 index 0000000000..efa321c0cf --- /dev/null +++ b/Lang/Elixir/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Greatest-common-divisor b/Lang/Elixir/Greatest-common-divisor new file mode 120000 index 0000000000..79fe79cf79 --- /dev/null +++ b/Lang/Elixir/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Greatest-element-of-a-list b/Lang/Elixir/Greatest-element-of-a-list new file mode 120000 index 0000000000..308a93752f --- /dev/null +++ b/Lang/Elixir/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Greatest-subsequential-sum b/Lang/Elixir/Greatest-subsequential-sum new file mode 120000 index 0000000000..0c6b239c3a --- /dev/null +++ b/Lang/Elixir/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Guess-the-number-With-feedback--player- b/Lang/Elixir/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..3460f4c8b4 --- /dev/null +++ b/Lang/Elixir/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Hamming-numbers b/Lang/Elixir/Hamming-numbers new file mode 120000 index 0000000000..c06dcb5910 --- /dev/null +++ b/Lang/Elixir/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Happy-numbers b/Lang/Elixir/Happy-numbers new file mode 120000 index 0000000000..00882052d2 --- /dev/null +++ b/Lang/Elixir/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Harshad-or-Niven-series b/Lang/Elixir/Harshad-or-Niven-series new file mode 120000 index 0000000000..09504fa5c2 --- /dev/null +++ b/Lang/Elixir/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Hash-from-two-arrays b/Lang/Elixir/Hash-from-two-arrays new file mode 120000 index 0000000000..39d9b3767c --- /dev/null +++ b/Lang/Elixir/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Hash-join b/Lang/Elixir/Hash-join new file mode 120000 index 0000000000..16d1875b72 --- /dev/null +++ b/Lang/Elixir/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Haversine-formula b/Lang/Elixir/Haversine-formula new file mode 120000 index 0000000000..4ec14fb760 --- /dev/null +++ b/Lang/Elixir/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Hello-world-Standard-error b/Lang/Elixir/Hello-world-Standard-error new file mode 120000 index 0000000000..86061b30c5 --- /dev/null +++ b/Lang/Elixir/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Here-document b/Lang/Elixir/Here-document new file mode 120000 index 0000000000..f2052555e3 --- /dev/null +++ b/Lang/Elixir/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Heronian-triangles b/Lang/Elixir/Heronian-triangles new file mode 120000 index 0000000000..e1cbd28563 --- /dev/null +++ b/Lang/Elixir/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Higher-order-functions b/Lang/Elixir/Higher-order-functions new file mode 120000 index 0000000000..c71fc2b935 --- /dev/null +++ b/Lang/Elixir/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Holidays-related-to-Easter b/Lang/Elixir/Holidays-related-to-Easter new file mode 120000 index 0000000000..8ac01b70d8 --- /dev/null +++ b/Lang/Elixir/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Horners-rule-for-polynomial-evaluation b/Lang/Elixir/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..569026bc17 --- /dev/null +++ b/Lang/Elixir/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Elixir \ No newline at end of file diff --git a/Lang/Elixir/I-before-E-except-after-C b/Lang/Elixir/I-before-E-except-after-C new file mode 120000 index 0000000000..a47bef5f36 --- /dev/null +++ b/Lang/Elixir/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Identity-matrix b/Lang/Elixir/Identity-matrix new file mode 120000 index 0000000000..524db120c1 --- /dev/null +++ b/Lang/Elixir/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Increment-a-numerical-string b/Lang/Elixir/Increment-a-numerical-string new file mode 120000 index 0000000000..facc4eaa69 --- /dev/null +++ b/Lang/Elixir/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Input-loop b/Lang/Elixir/Input-loop new file mode 120000 index 0000000000..2c269b7368 --- /dev/null +++ b/Lang/Elixir/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Integer-comparison b/Lang/Elixir/Integer-comparison new file mode 120000 index 0000000000..372b2b3f80 --- /dev/null +++ b/Lang/Elixir/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Integer-sequence b/Lang/Elixir/Integer-sequence new file mode 120000 index 0000000000..b58fead01e --- /dev/null +++ b/Lang/Elixir/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Interactive-programming b/Lang/Elixir/Interactive-programming new file mode 120000 index 0000000000..8e4fa9d9e6 --- /dev/null +++ b/Lang/Elixir/Interactive-programming @@ -0,0 +1 @@ +../../Task/Interactive-programming/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Jensens-Device b/Lang/Elixir/Jensens-Device new file mode 120000 index 0000000000..28a0a275f0 --- /dev/null +++ b/Lang/Elixir/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Josephus-problem b/Lang/Elixir/Josephus-problem new file mode 120000 index 0000000000..a33b2dee19 --- /dev/null +++ b/Lang/Elixir/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Kaprekar-numbers b/Lang/Elixir/Kaprekar-numbers new file mode 120000 index 0000000000..e27cd9a346 --- /dev/null +++ b/Lang/Elixir/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Knapsack-problem-Continuous b/Lang/Elixir/Knapsack-problem-Continuous new file mode 120000 index 0000000000..f872d9adaf --- /dev/null +++ b/Lang/Elixir/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Knuth-shuffle b/Lang/Elixir/Knuth-shuffle new file mode 120000 index 0000000000..aa7ed3e5a7 --- /dev/null +++ b/Lang/Elixir/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Elixir \ No newline at end of file diff --git a/Lang/Elixir/LZW-compression b/Lang/Elixir/LZW-compression new file mode 120000 index 0000000000..ccb88d7c3c --- /dev/null +++ b/Lang/Elixir/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Langtons-ant b/Lang/Elixir/Langtons-ant new file mode 120000 index 0000000000..10b9e4504f --- /dev/null +++ b/Lang/Elixir/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Largest-int-from-concatenated-ints b/Lang/Elixir/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..6012ffbd76 --- /dev/null +++ b/Lang/Elixir/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Last-Friday-of-each-month b/Lang/Elixir/Last-Friday-of-each-month new file mode 120000 index 0000000000..9aa1f69ad6 --- /dev/null +++ b/Lang/Elixir/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Last-letter-first-letter b/Lang/Elixir/Last-letter-first-letter new file mode 120000 index 0000000000..44abb954c5 --- /dev/null +++ b/Lang/Elixir/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Leap-year b/Lang/Elixir/Leap-year new file mode 120000 index 0000000000..30d544633a --- /dev/null +++ b/Lang/Elixir/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Least-common-multiple b/Lang/Elixir/Least-common-multiple new file mode 120000 index 0000000000..4b0383ba29 --- /dev/null +++ b/Lang/Elixir/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Left-factorials b/Lang/Elixir/Left-factorials new file mode 120000 index 0000000000..f05645487e --- /dev/null +++ b/Lang/Elixir/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Letter-frequency b/Lang/Elixir/Letter-frequency new file mode 120000 index 0000000000..e4fc3a962a --- /dev/null +++ b/Lang/Elixir/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Levenshtein-distance b/Lang/Elixir/Levenshtein-distance new file mode 120000 index 0000000000..5d96329dcd --- /dev/null +++ b/Lang/Elixir/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Linear-congruential-generator b/Lang/Elixir/Linear-congruential-generator new file mode 120000 index 0000000000..57c5f6609c --- /dev/null +++ b/Lang/Elixir/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Literals-Floating-point b/Lang/Elixir/Literals-Floating-point new file mode 120000 index 0000000000..2e75f4f493 --- /dev/null +++ b/Lang/Elixir/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Literals-Integer b/Lang/Elixir/Literals-Integer new file mode 120000 index 0000000000..93281841ee --- /dev/null +++ b/Lang/Elixir/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Literals-String b/Lang/Elixir/Literals-String new file mode 120000 index 0000000000..61750f7582 --- /dev/null +++ b/Lang/Elixir/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Logical-operations b/Lang/Elixir/Logical-operations new file mode 120000 index 0000000000..9785fc870c --- /dev/null +++ b/Lang/Elixir/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Longest-common-subsequence b/Lang/Elixir/Longest-common-subsequence new file mode 120000 index 0000000000..1aaac1c444 --- /dev/null +++ b/Lang/Elixir/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loop-over-multiple-arrays-simultaneously b/Lang/Elixir/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..f7d77e98ca --- /dev/null +++ b/Lang/Elixir/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-Break b/Lang/Elixir/Loops-Break new file mode 120000 index 0000000000..1e1cdab26f --- /dev/null +++ b/Lang/Elixir/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-Continue b/Lang/Elixir/Loops-Continue new file mode 120000 index 0000000000..4e8bcd119c --- /dev/null +++ b/Lang/Elixir/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-Do-while b/Lang/Elixir/Loops-Do-while new file mode 120000 index 0000000000..bc11464f1a --- /dev/null +++ b/Lang/Elixir/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-Downward-for b/Lang/Elixir/Loops-Downward-for new file mode 120000 index 0000000000..2dd82af927 --- /dev/null +++ b/Lang/Elixir/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-For b/Lang/Elixir/Loops-For new file mode 120000 index 0000000000..98942170ca --- /dev/null +++ b/Lang/Elixir/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-For-with-a-specified-step b/Lang/Elixir/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..c1d2dc77f6 --- /dev/null +++ b/Lang/Elixir/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-Foreach b/Lang/Elixir/Loops-Foreach new file mode 120000 index 0000000000..be1c10b612 --- /dev/null +++ b/Lang/Elixir/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-Infinite b/Lang/Elixir/Loops-Infinite new file mode 120000 index 0000000000..963379a141 --- /dev/null +++ b/Lang/Elixir/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-N-plus-one-half b/Lang/Elixir/Loops-N-plus-one-half new file mode 120000 index 0000000000..61a61cb451 --- /dev/null +++ b/Lang/Elixir/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-Nested b/Lang/Elixir/Loops-Nested new file mode 120000 index 0000000000..249cd6d342 --- /dev/null +++ b/Lang/Elixir/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Loops-While b/Lang/Elixir/Loops-While new file mode 120000 index 0000000000..6f760084b5 --- /dev/null +++ b/Lang/Elixir/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Lucas-Lehmer-test b/Lang/Elixir/Lucas-Lehmer-test new file mode 120000 index 0000000000..e6a4eccdb9 --- /dev/null +++ b/Lang/Elixir/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Ludic-numbers b/Lang/Elixir/Ludic-numbers new file mode 120000 index 0000000000..c6d9779a18 --- /dev/null +++ b/Lang/Elixir/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Luhn-test-of-credit-card-numbers b/Lang/Elixir/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..9abc31dbdf --- /dev/null +++ b/Lang/Elixir/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Magic-squares-of-odd-order b/Lang/Elixir/Magic-squares-of-odd-order new file mode 120000 index 0000000000..59f32a0699 --- /dev/null +++ b/Lang/Elixir/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Make-directory-path b/Lang/Elixir/Make-directory-path new file mode 120000 index 0000000000..5660fa687f --- /dev/null +++ b/Lang/Elixir/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Map-range b/Lang/Elixir/Map-range new file mode 120000 index 0000000000..bb3f0f82f4 --- /dev/null +++ b/Lang/Elixir/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Matrix-transposition b/Lang/Elixir/Matrix-transposition new file mode 120000 index 0000000000..89c284d77d --- /dev/null +++ b/Lang/Elixir/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Maximum-triangle-path-sum b/Lang/Elixir/Maximum-triangle-path-sum new file mode 120000 index 0000000000..9caafafb5f --- /dev/null +++ b/Lang/Elixir/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Maze-generation b/Lang/Elixir/Maze-generation new file mode 120000 index 0000000000..4932d5ce48 --- /dev/null +++ b/Lang/Elixir/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Middle-three-digits b/Lang/Elixir/Middle-three-digits new file mode 120000 index 0000000000..86de2aefa2 --- /dev/null +++ b/Lang/Elixir/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Monte-Carlo-methods b/Lang/Elixir/Monte-Carlo-methods new file mode 120000 index 0000000000..5eacd75ac4 --- /dev/null +++ b/Lang/Elixir/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Monty-Hall-problem b/Lang/Elixir/Monty-Hall-problem new file mode 120000 index 0000000000..3a3b7933e2 --- /dev/null +++ b/Lang/Elixir/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Morse-code b/Lang/Elixir/Morse-code new file mode 120000 index 0000000000..24938f2493 --- /dev/null +++ b/Lang/Elixir/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Move-to-front-algorithm b/Lang/Elixir/Move-to-front-algorithm new file mode 120000 index 0000000000..b574074975 --- /dev/null +++ b/Lang/Elixir/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Multifactorial b/Lang/Elixir/Multifactorial new file mode 120000 index 0000000000..8b18386bc6 --- /dev/null +++ b/Lang/Elixir/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Multiple-distinct-objects b/Lang/Elixir/Multiple-distinct-objects new file mode 120000 index 0000000000..9eac0c580a --- /dev/null +++ b/Lang/Elixir/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Multiplication-tables b/Lang/Elixir/Multiplication-tables new file mode 120000 index 0000000000..0886793339 --- /dev/null +++ b/Lang/Elixir/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Multisplit b/Lang/Elixir/Multisplit new file mode 120000 index 0000000000..57d3b9a166 --- /dev/null +++ b/Lang/Elixir/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Elixir \ No newline at end of file diff --git a/Lang/Elixir/N-queens-problem b/Lang/Elixir/N-queens-problem new file mode 120000 index 0000000000..8b0508328a --- /dev/null +++ b/Lang/Elixir/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Narcissistic-decimal-number b/Lang/Elixir/Narcissistic-decimal-number new file mode 120000 index 0000000000..84fa9e54cf --- /dev/null +++ b/Lang/Elixir/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Non-decimal-radices-Convert b/Lang/Elixir/Non-decimal-radices-Convert new file mode 120000 index 0000000000..91fdccba76 --- /dev/null +++ b/Lang/Elixir/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Non-decimal-radices-Input b/Lang/Elixir/Non-decimal-radices-Input new file mode 120000 index 0000000000..117ff725c2 --- /dev/null +++ b/Lang/Elixir/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Non-decimal-radices-Output b/Lang/Elixir/Non-decimal-radices-Output new file mode 120000 index 0000000000..4927636a1c --- /dev/null +++ b/Lang/Elixir/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Nth b/Lang/Elixir/Nth new file mode 120000 index 0000000000..96ec933845 --- /dev/null +++ b/Lang/Elixir/Nth @@ -0,0 +1 @@ +../../Task/Nth/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Nth-root b/Lang/Elixir/Nth-root new file mode 120000 index 0000000000..e39f7c30ff --- /dev/null +++ b/Lang/Elixir/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Null-object b/Lang/Elixir/Null-object new file mode 120000 index 0000000000..ae899b5f2c --- /dev/null +++ b/Lang/Elixir/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Numerical-integration b/Lang/Elixir/Numerical-integration new file mode 120000 index 0000000000..f3431d3e43 --- /dev/null +++ b/Lang/Elixir/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Elixir \ No newline at end of file diff --git a/Lang/Elixir/One-dimensional-cellular-automata b/Lang/Elixir/One-dimensional-cellular-automata new file mode 120000 index 0000000000..cce0827240 --- /dev/null +++ b/Lang/Elixir/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Ordered-words b/Lang/Elixir/Ordered-words new file mode 120000 index 0000000000..5248aec583 --- /dev/null +++ b/Lang/Elixir/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Pangram-checker b/Lang/Elixir/Pangram-checker new file mode 120000 index 0000000000..898e519e44 --- /dev/null +++ b/Lang/Elixir/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Pascals-triangle b/Lang/Elixir/Pascals-triangle new file mode 120000 index 0000000000..23ac5b1623 --- /dev/null +++ b/Lang/Elixir/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Permutation-test b/Lang/Elixir/Permutation-test new file mode 120000 index 0000000000..4a70c6e92e --- /dev/null +++ b/Lang/Elixir/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Permutations b/Lang/Elixir/Permutations new file mode 120000 index 0000000000..a9134822c7 --- /dev/null +++ b/Lang/Elixir/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Permutations-Derangements b/Lang/Elixir/Permutations-Derangements new file mode 120000 index 0000000000..233933a0d2 --- /dev/null +++ b/Lang/Elixir/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Permutations-by-swapping b/Lang/Elixir/Permutations-by-swapping new file mode 120000 index 0000000000..d134804417 --- /dev/null +++ b/Lang/Elixir/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Pernicious-numbers b/Lang/Elixir/Pernicious-numbers new file mode 120000 index 0000000000..135c923582 --- /dev/null +++ b/Lang/Elixir/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Phrase-reversals b/Lang/Elixir/Phrase-reversals new file mode 120000 index 0000000000..1fa448cf9f --- /dev/null +++ b/Lang/Elixir/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Pi b/Lang/Elixir/Pi new file mode 120000 index 0000000000..5c97fb9ac3 --- /dev/null +++ b/Lang/Elixir/Pi @@ -0,0 +1 @@ +../../Task/Pi/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Power-set b/Lang/Elixir/Power-set new file mode 120000 index 0000000000..1d6321a905 --- /dev/null +++ b/Lang/Elixir/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Price-fraction b/Lang/Elixir/Price-fraction new file mode 120000 index 0000000000..32efac5e54 --- /dev/null +++ b/Lang/Elixir/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Primality-by-trial-division b/Lang/Elixir/Primality-by-trial-division new file mode 120000 index 0000000000..6fcee3a255 --- /dev/null +++ b/Lang/Elixir/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Prime-decomposition b/Lang/Elixir/Prime-decomposition new file mode 120000 index 0000000000..41ca118316 --- /dev/null +++ b/Lang/Elixir/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Problem-of-Apollonius b/Lang/Elixir/Problem-of-Apollonius new file mode 120000 index 0000000000..9725e28b3f --- /dev/null +++ b/Lang/Elixir/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Program-termination b/Lang/Elixir/Program-termination new file mode 120000 index 0000000000..dbd33e89d4 --- /dev/null +++ b/Lang/Elixir/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Pythagorean-triples b/Lang/Elixir/Pythagorean-triples new file mode 120000 index 0000000000..161cca129e --- /dev/null +++ b/Lang/Elixir/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Queue-Definition b/Lang/Elixir/Queue-Definition new file mode 120000 index 0000000000..6a814fb203 --- /dev/null +++ b/Lang/Elixir/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Range-expansion b/Lang/Elixir/Range-expansion new file mode 120000 index 0000000000..58ce91658e --- /dev/null +++ b/Lang/Elixir/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Range-extraction b/Lang/Elixir/Range-extraction new file mode 120000 index 0000000000..5af6edc22b --- /dev/null +++ b/Lang/Elixir/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Read-a-file-line-by-line b/Lang/Elixir/Read-a-file-line-by-line new file mode 120000 index 0000000000..aee39dbf65 --- /dev/null +++ b/Lang/Elixir/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Read-entire-file b/Lang/Elixir/Read-entire-file new file mode 120000 index 0000000000..5b14493763 --- /dev/null +++ b/Lang/Elixir/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Regular-expressions b/Lang/Elixir/Regular-expressions new file mode 120000 index 0000000000..013b3aba64 --- /dev/null +++ b/Lang/Elixir/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Remove-duplicate-elements b/Lang/Elixir/Remove-duplicate-elements new file mode 120000 index 0000000000..34f546ccd6 --- /dev/null +++ b/Lang/Elixir/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Return-multiple-values b/Lang/Elixir/Return-multiple-values new file mode 120000 index 0000000000..a59c6f2390 --- /dev/null +++ b/Lang/Elixir/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Roman-numerals-Decode b/Lang/Elixir/Roman-numerals-Decode new file mode 120000 index 0000000000..f17ccc32dc --- /dev/null +++ b/Lang/Elixir/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Roman-numerals-Encode b/Lang/Elixir/Roman-numerals-Encode new file mode 120000 index 0000000000..314b821ec9 --- /dev/null +++ b/Lang/Elixir/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Roots-of-a-function b/Lang/Elixir/Roots-of-a-function new file mode 120000 index 0000000000..d7ec11390f --- /dev/null +++ b/Lang/Elixir/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Roots-of-a-quadratic-function b/Lang/Elixir/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..b5b67b4074 --- /dev/null +++ b/Lang/Elixir/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Rot-13 b/Lang/Elixir/Rot-13 new file mode 120000 index 0000000000..ffca569b04 --- /dev/null +++ b/Lang/Elixir/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Run-length-encoding b/Lang/Elixir/Run-length-encoding new file mode 120000 index 0000000000..810de1c4a8 --- /dev/null +++ b/Lang/Elixir/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Search-a-list b/Lang/Elixir/Search-a-list new file mode 120000 index 0000000000..892549a700 --- /dev/null +++ b/Lang/Elixir/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Set b/Lang/Elixir/Set new file mode 120000 index 0000000000..02764e35d5 --- /dev/null +++ b/Lang/Elixir/Set @@ -0,0 +1 @@ +../../Task/Set/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Seven-sided-dice-from-five-sided-dice b/Lang/Elixir/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..355d4cecf6 --- /dev/null +++ b/Lang/Elixir/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Shell-one-liner b/Lang/Elixir/Shell-one-liner new file mode 120000 index 0000000000..e223a8bf32 --- /dev/null +++ b/Lang/Elixir/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sierpinski-carpet b/Lang/Elixir/Sierpinski-carpet new file mode 120000 index 0000000000..ffe874148f --- /dev/null +++ b/Lang/Elixir/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sierpinski-triangle b/Lang/Elixir/Sierpinski-triangle new file mode 120000 index 0000000000..a2124722ce --- /dev/null +++ b/Lang/Elixir/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sieve-of-Eratosthenes b/Lang/Elixir/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..4e72816ef2 --- /dev/null +++ b/Lang/Elixir/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sort-an-array-of-composite-structures b/Lang/Elixir/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..8738837f75 --- /dev/null +++ b/Lang/Elixir/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sort-an-integer-array b/Lang/Elixir/Sort-an-integer-array new file mode 120000 index 0000000000..9993404dea --- /dev/null +++ b/Lang/Elixir/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sort-disjoint-sublist b/Lang/Elixir/Sort-disjoint-sublist new file mode 120000 index 0000000000..26558b7cc7 --- /dev/null +++ b/Lang/Elixir/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sort-stability b/Lang/Elixir/Sort-stability new file mode 120000 index 0000000000..debb39759e --- /dev/null +++ b/Lang/Elixir/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Bead-sort b/Lang/Elixir/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..696c0a9a70 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Bogosort b/Lang/Elixir/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..2e90a477e3 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Bubble-sort b/Lang/Elixir/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..55bcb6fdb6 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Cocktail-sort b/Lang/Elixir/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..595bb49311 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Counting-sort b/Lang/Elixir/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..4aaf7053ef --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Gnome-sort b/Lang/Elixir/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..a708c43907 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Insertion-sort b/Lang/Elixir/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..1b9696c29e --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Merge-sort b/Lang/Elixir/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..49cbc53537 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Pancake-sort b/Lang/Elixir/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..2ac965f9e2 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Quicksort b/Lang/Elixir/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..bf787221cd --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Radix-sort b/Lang/Elixir/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..29322a9178 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sorting-algorithms-Selection-sort b/Lang/Elixir/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..b48f588b05 --- /dev/null +++ b/Lang/Elixir/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Spiral-matrix b/Lang/Elixir/Spiral-matrix new file mode 120000 index 0000000000..c1cb4c1424 --- /dev/null +++ b/Lang/Elixir/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Stack b/Lang/Elixir/Stack new file mode 120000 index 0000000000..9b5e0461a9 --- /dev/null +++ b/Lang/Elixir/Stack @@ -0,0 +1 @@ +../../Task/Stack/Elixir \ No newline at end of file diff --git a/Lang/Elixir/String-append b/Lang/Elixir/String-append new file mode 120000 index 0000000000..3f361c451a --- /dev/null +++ b/Lang/Elixir/String-append @@ -0,0 +1 @@ +../../Task/String-append/Elixir \ No newline at end of file diff --git a/Lang/Elixir/String-comparison b/Lang/Elixir/String-comparison new file mode 120000 index 0000000000..968977a5bf --- /dev/null +++ b/Lang/Elixir/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Elixir \ No newline at end of file diff --git a/Lang/Elixir/String-prepend b/Lang/Elixir/String-prepend new file mode 120000 index 0000000000..6c765d4a5e --- /dev/null +++ b/Lang/Elixir/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Substring b/Lang/Elixir/Substring new file mode 120000 index 0000000000..5725ca9078 --- /dev/null +++ b/Lang/Elixir/Substring @@ -0,0 +1 @@ +../../Task/Substring/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Substring-Top-and-tail b/Lang/Elixir/Substring-Top-and-tail new file mode 120000 index 0000000000..4f62f24f6b --- /dev/null +++ b/Lang/Elixir/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sudoku b/Lang/Elixir/Sudoku new file mode 120000 index 0000000000..f28a6c8170 --- /dev/null +++ b/Lang/Elixir/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sum-and-product-of-an-array b/Lang/Elixir/Sum-and-product-of-an-array new file mode 120000 index 0000000000..ec0d9cfc4c --- /dev/null +++ b/Lang/Elixir/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sum-digits-of-an-integer b/Lang/Elixir/Sum-digits-of-an-integer new file mode 120000 index 0000000000..25c18e7908 --- /dev/null +++ b/Lang/Elixir/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sum-multiples-of-3-and-5 b/Lang/Elixir/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..1a57e1e9f8 --- /dev/null +++ b/Lang/Elixir/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sum-of-a-series b/Lang/Elixir/Sum-of-a-series new file mode 120000 index 0000000000..cc165d2ef0 --- /dev/null +++ b/Lang/Elixir/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Sum-of-squares b/Lang/Elixir/Sum-of-squares new file mode 120000 index 0000000000..edf78a6457 --- /dev/null +++ b/Lang/Elixir/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Symmetric-difference b/Lang/Elixir/Symmetric-difference new file mode 120000 index 0000000000..5ba67dcb3f --- /dev/null +++ b/Lang/Elixir/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Elixir \ No newline at end of file diff --git a/Lang/Elixir/System-time b/Lang/Elixir/System-time new file mode 120000 index 0000000000..8efa8b5745 --- /dev/null +++ b/Lang/Elixir/System-time @@ -0,0 +1 @@ +../../Task/System-time/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Temperature-conversion b/Lang/Elixir/Temperature-conversion new file mode 120000 index 0000000000..4a41c2060c --- /dev/null +++ b/Lang/Elixir/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Elixir \ No newline at end of file diff --git a/Lang/Elixir/The-Twelve-Days-of-Christmas b/Lang/Elixir/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..2a44c5d955 --- /dev/null +++ b/Lang/Elixir/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Time-a-function b/Lang/Elixir/Time-a-function new file mode 120000 index 0000000000..ea84ed6f5e --- /dev/null +++ b/Lang/Elixir/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Top-rank-per-group b/Lang/Elixir/Top-rank-per-group new file mode 120000 index 0000000000..a3f2d8912b --- /dev/null +++ b/Lang/Elixir/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Towers-of-Hanoi b/Lang/Elixir/Towers-of-Hanoi new file mode 120000 index 0000000000..f68919434f --- /dev/null +++ b/Lang/Elixir/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Trigonometric-functions b/Lang/Elixir/Trigonometric-functions new file mode 120000 index 0000000000..83ec667f5d --- /dev/null +++ b/Lang/Elixir/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Elixir \ No newline at end of file diff --git a/Lang/Elixir/URL-decoding b/Lang/Elixir/URL-decoding new file mode 120000 index 0000000000..53c7cf9434 --- /dev/null +++ b/Lang/Elixir/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Elixir \ No newline at end of file diff --git a/Lang/Elixir/URL-encoding b/Lang/Elixir/URL-encoding new file mode 120000 index 0000000000..8d6a24ed4d --- /dev/null +++ b/Lang/Elixir/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Elixir \ No newline at end of file diff --git a/Lang/Elixir/User-input-Text b/Lang/Elixir/User-input-Text new file mode 120000 index 0000000000..1781be9463 --- /dev/null +++ b/Lang/Elixir/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Van-der-Corput-sequence b/Lang/Elixir/Van-der-Corput-sequence new file mode 120000 index 0000000000..b9e912c8e9 --- /dev/null +++ b/Lang/Elixir/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Variadic-function b/Lang/Elixir/Variadic-function new file mode 120000 index 0000000000..4e4bc5cb46 --- /dev/null +++ b/Lang/Elixir/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Verify-distribution-uniformity-Naive b/Lang/Elixir/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..eec6315036 --- /dev/null +++ b/Lang/Elixir/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Word-wrap b/Lang/Elixir/Word-wrap new file mode 120000 index 0000000000..b522ed4b98 --- /dev/null +++ b/Lang/Elixir/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Elixir \ No newline at end of file diff --git a/Lang/Elixir/World-Cup-group-stage b/Lang/Elixir/World-Cup-group-stage new file mode 120000 index 0000000000..c89fe99e04 --- /dev/null +++ b/Lang/Elixir/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Write-language-name-in-3D-ASCII b/Lang/Elixir/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..9c8acd9d4b --- /dev/null +++ b/Lang/Elixir/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Y-combinator b/Lang/Elixir/Y-combinator new file mode 120000 index 0000000000..3575c44a38 --- /dev/null +++ b/Lang/Elixir/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Zero-to-the-zero-power b/Lang/Elixir/Zero-to-the-zero-power new file mode 120000 index 0000000000..de7af1035e --- /dev/null +++ b/Lang/Elixir/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Zig-zag-matrix b/Lang/Elixir/Zig-zag-matrix new file mode 120000 index 0000000000..0e934bfca2 --- /dev/null +++ b/Lang/Elixir/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Elixir \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Dot-product b/Lang/Emacs-Lisp/Dot-product new file mode 120000 index 0000000000..2711d3b153 --- /dev/null +++ b/Lang/Emacs-Lisp/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Even-or-odd b/Lang/Emacs-Lisp/Even-or-odd new file mode 120000 index 0000000000..7c9aa71c01 --- /dev/null +++ b/Lang/Emacs-Lisp/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Fibonacci-sequence b/Lang/Emacs-Lisp/Fibonacci-sequence new file mode 120000 index 0000000000..be274546c7 --- /dev/null +++ b/Lang/Emacs-Lisp/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/HTTP b/Lang/Emacs-Lisp/HTTP new file mode 120000 index 0000000000..b2c2f0bb00 --- /dev/null +++ b/Lang/Emacs-Lisp/HTTP @@ -0,0 +1 @@ +../../Task/HTTP/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Hello-world-Newline-omission b/Lang/Emacs-Lisp/Hello-world-Newline-omission new file mode 120000 index 0000000000..0cb5768de8 --- /dev/null +++ b/Lang/Emacs-Lisp/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Hello-world-Standard-error b/Lang/Emacs-Lisp/Hello-world-Standard-error new file mode 120000 index 0000000000..659a815430 --- /dev/null +++ b/Lang/Emacs-Lisp/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Horners-rule-for-polynomial-evaluation b/Lang/Emacs-Lisp/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..64be7b340e --- /dev/null +++ b/Lang/Emacs-Lisp/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Hostname b/Lang/Emacs-Lisp/Hostname new file mode 120000 index 0000000000..c25bdfc804 --- /dev/null +++ b/Lang/Emacs-Lisp/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Include-a-file b/Lang/Emacs-Lisp/Include-a-file new file mode 120000 index 0000000000..927d26437e --- /dev/null +++ b/Lang/Emacs-Lisp/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Integer-comparison b/Lang/Emacs-Lisp/Integer-comparison new file mode 120000 index 0000000000..a591422c6c --- /dev/null +++ b/Lang/Emacs-Lisp/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Multiple-regression b/Lang/Emacs-Lisp/Multiple-regression new file mode 120000 index 0000000000..372eeb0a99 --- /dev/null +++ b/Lang/Emacs-Lisp/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Phrase-reversals b/Lang/Emacs-Lisp/Phrase-reversals new file mode 120000 index 0000000000..35c5f135e7 --- /dev/null +++ b/Lang/Emacs-Lisp/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Polynomial-regression b/Lang/Emacs-Lisp/Polynomial-regression new file mode 120000 index 0000000000..d04c73aa23 --- /dev/null +++ b/Lang/Emacs-Lisp/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Regular-expressions b/Lang/Emacs-Lisp/Regular-expressions new file mode 120000 index 0000000000..410595b8cf --- /dev/null +++ b/Lang/Emacs-Lisp/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Reverse-words-in-a-string b/Lang/Emacs-Lisp/Reverse-words-in-a-string new file mode 120000 index 0000000000..befae09595 --- /dev/null +++ b/Lang/Emacs-Lisp/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Send-email b/Lang/Emacs-Lisp/Send-email new file mode 120000 index 0000000000..fe8501fec7 --- /dev/null +++ b/Lang/Emacs-Lisp/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sockets b/Lang/Emacs-Lisp/Sockets new file mode 120000 index 0000000000..5704b58272 --- /dev/null +++ b/Lang/Emacs-Lisp/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/String-append b/Lang/Emacs-Lisp/String-append new file mode 120000 index 0000000000..5d906ff7ce --- /dev/null +++ b/Lang/Emacs-Lisp/String-append @@ -0,0 +1 @@ +../../Task/String-append/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/String-concatenation b/Lang/Emacs-Lisp/String-concatenation new file mode 120000 index 0000000000..d8ea274498 --- /dev/null +++ b/Lang/Emacs-Lisp/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/String-matching b/Lang/Emacs-Lisp/String-matching new file mode 120000 index 0000000000..58eaebbc96 --- /dev/null +++ b/Lang/Emacs-Lisp/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/String-prepend b/Lang/Emacs-Lisp/String-prepend new file mode 120000 index 0000000000..cd7411bd9e --- /dev/null +++ b/Lang/Emacs-Lisp/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Emacs-Lisp/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..ae8d13de8e --- /dev/null +++ b/Lang/Emacs-Lisp/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Substring-Top-and-tail b/Lang/Emacs-Lisp/Substring-Top-and-tail new file mode 120000 index 0000000000..c69ea7656b --- /dev/null +++ b/Lang/Emacs-Lisp/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sum-digits-of-an-integer b/Lang/Emacs-Lisp/Sum-digits-of-an-integer new file mode 120000 index 0000000000..4d8ac806b7 --- /dev/null +++ b/Lang/Emacs-Lisp/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sum-multiples-of-3-and-5 b/Lang/Emacs-Lisp/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..3ec24f2097 --- /dev/null +++ b/Lang/Emacs-Lisp/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sum-of-a-series b/Lang/Emacs-Lisp/Sum-of-a-series new file mode 120000 index 0000000000..65182dc580 --- /dev/null +++ b/Lang/Emacs-Lisp/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sum-of-squares b/Lang/Emacs-Lisp/Sum-of-squares new file mode 120000 index 0000000000..27b5761a6d --- /dev/null +++ b/Lang/Emacs-Lisp/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/System-time b/Lang/Emacs-Lisp/System-time new file mode 120000 index 0000000000..8650af27d6 --- /dev/null +++ b/Lang/Emacs-Lisp/System-time @@ -0,0 +1 @@ +../../Task/System-time/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Abundant,-deficient-and-perfect-number-classifications b/Lang/Erlang/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..3b4617c5cd --- /dev/null +++ b/Lang/Erlang/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Almost-prime b/Lang/Erlang/Almost-prime new file mode 120000 index 0000000000..c462544554 --- /dev/null +++ b/Lang/Erlang/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Amicable-pairs b/Lang/Erlang/Amicable-pairs new file mode 120000 index 0000000000..c43961dea0 --- /dev/null +++ b/Lang/Erlang/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Catamorphism b/Lang/Erlang/Catamorphism new file mode 120000 index 0000000000..d3d50ff8f9 --- /dev/null +++ b/Lang/Erlang/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Combinations-and-permutations b/Lang/Erlang/Combinations-and-permutations new file mode 120000 index 0000000000..ff0a7d18bf --- /dev/null +++ b/Lang/Erlang/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Factors-of-a-Mersenne-number b/Lang/Erlang/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..16acfacbcf --- /dev/null +++ b/Lang/Erlang/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Generate-lower-case-ASCII-alphabet b/Lang/Erlang/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..a3f6f1aafb --- /dev/null +++ b/Lang/Erlang/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Erlang \ No newline at end of file diff --git a/Lang/Erlang/I-before-E-except-after-C b/Lang/Erlang/I-before-E-except-after-C new file mode 120000 index 0000000000..7c40a08076 --- /dev/null +++ b/Lang/Erlang/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Longest-increasing-subsequence b/Lang/Erlang/Longest-increasing-subsequence new file mode 120000 index 0000000000..06177ed225 --- /dev/null +++ b/Lang/Erlang/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Mandelbrot-set b/Lang/Erlang/Mandelbrot-set new file mode 120000 index 0000000000..7b0ab8f79e --- /dev/null +++ b/Lang/Erlang/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Matrix-multiplication b/Lang/Erlang/Matrix-multiplication new file mode 120000 index 0000000000..205abc54f6 --- /dev/null +++ b/Lang/Erlang/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Number-names b/Lang/Erlang/Number-names new file mode 120000 index 0000000000..779cc36242 --- /dev/null +++ b/Lang/Erlang/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Quickselect-algorithm b/Lang/Erlang/Quickselect-algorithm new file mode 120000 index 0000000000..09bbe45185 --- /dev/null +++ b/Lang/Erlang/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Semiprime b/Lang/Erlang/Semiprime new file mode 120000 index 0000000000..90eb5b7b55 --- /dev/null +++ b/Lang/Erlang/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Terminal-control-Clear-the-screen b/Lang/Erlang/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..a95b709cef --- /dev/null +++ b/Lang/Erlang/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Erlang \ No newline at end of file diff --git a/Lang/Excel/00DESCRIPTION b/Lang/Excel/00DESCRIPTION index 60e1826780..8a20480e53 100644 --- a/Lang/Excel/00DESCRIPTION +++ b/Lang/Excel/00DESCRIPTION @@ -1,2 +1,2 @@ -{{stub}}{{language}} -'''Excel''' isn't actual language, but certain problems can be solved using it. \ No newline at end of file +{{stub}}{{np language}} +[[wp:Microsoft_Excel|Excel]] is a [[wp:Spreadsheet|spreadsheet]] program from [[wp:Microsoft_Office|Microsoft Office]] suite applications. Excel provides calculations, [[wp:Spreadsheet#Cell_reference|cell referencing]], and illustration of data sheets by using its ''functions'', ''formulas'', ''graphs'', etc. Hence, even though Excel is not a programming application/language, it can be used to solve certain programming related tasks. \ No newline at end of file diff --git a/Lang/Excel/Greatest-common-divisor b/Lang/Excel/Greatest-common-divisor new file mode 120000 index 0000000000..b09f8cc905 --- /dev/null +++ b/Lang/Excel/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Excel \ No newline at end of file diff --git a/Lang/Excel/Nth-root b/Lang/Excel/Nth-root new file mode 120000 index 0000000000..79c498bc97 --- /dev/null +++ b/Lang/Excel/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Excel \ No newline at end of file diff --git a/Lang/F-Sharp/Priority-queue b/Lang/F-Sharp/Priority-queue new file mode 120000 index 0000000000..0a6c7d3e72 --- /dev/null +++ b/Lang/F-Sharp/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/F-Sharp \ No newline at end of file diff --git a/Lang/Factor/Seven-sided-dice-from-five-sided-dice b/Lang/Factor/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..b205b2e135 --- /dev/null +++ b/Lang/Factor/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Factor \ No newline at end of file diff --git a/Lang/Factor/Verify-distribution-uniformity-Naive b/Lang/Factor/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..0b7bc2d848 --- /dev/null +++ b/Lang/Factor/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Factor \ No newline at end of file diff --git a/Lang/Felix/Continued-fraction b/Lang/Felix/Continued-fraction new file mode 120000 index 0000000000..230cddf028 --- /dev/null +++ b/Lang/Felix/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Felix \ No newline at end of file diff --git a/Lang/Forth/00DESCRIPTION b/Lang/Forth/00DESCRIPTION index 5411b5384c..601c00414f 100644 --- a/Lang/Forth/00DESCRIPTION +++ b/Lang/Forth/00DESCRIPTION @@ -10,4 +10,4 @@ Where not otherwise specified, examples conform to the 1994 [[ANSI]] Standard, a ==Citations== * [[wp:Forth_%28programming_language%29|Wikipedia:Forth (programming language)]] -* [http://www.forthfreak.net/dpans/dpansf.htm Index to the ANS Forth words] \ No newline at end of file +* [http://lars.nocrew.org/dpans/dpansf.htm Index to the ANS Forth words] \ No newline at end of file diff --git a/Lang/Forth/AKS-test-for-primes b/Lang/Forth/AKS-test-for-primes new file mode 120000 index 0000000000..48a6b9a07b --- /dev/null +++ b/Lang/Forth/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Forth \ No newline at end of file diff --git a/Lang/Forth/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Forth/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..6ac3a90675 --- /dev/null +++ b/Lang/Forth/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Forth \ No newline at end of file diff --git a/Lang/Forth/Assertions b/Lang/Forth/Assertions new file mode 120000 index 0000000000..5738f90797 --- /dev/null +++ b/Lang/Forth/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Forth \ No newline at end of file diff --git a/Lang/Forth/Break-OO-privacy b/Lang/Forth/Break-OO-privacy new file mode 120000 index 0000000000..7f9a408b00 --- /dev/null +++ b/Lang/Forth/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Forth \ No newline at end of file diff --git a/Lang/Forth/Constrained-genericity b/Lang/Forth/Constrained-genericity new file mode 120000 index 0000000000..db82c2e0c0 --- /dev/null +++ b/Lang/Forth/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Forth \ No newline at end of file diff --git a/Lang/Forth/Delegates b/Lang/Forth/Delegates new file mode 120000 index 0000000000..9c25ebd08e --- /dev/null +++ b/Lang/Forth/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Forth \ No newline at end of file diff --git a/Lang/Forth/Flatten-a-list b/Lang/Forth/Flatten-a-list new file mode 120000 index 0000000000..b138a5ef89 --- /dev/null +++ b/Lang/Forth/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Forth \ No newline at end of file diff --git a/Lang/Forth/Generate-lower-case-ASCII-alphabet b/Lang/Forth/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..f3a9e7cc4c --- /dev/null +++ b/Lang/Forth/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Forth \ No newline at end of file diff --git a/Lang/Forth/Generator-Exponential b/Lang/Forth/Generator-Exponential new file mode 120000 index 0000000000..4547aecc56 --- /dev/null +++ b/Lang/Forth/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Forth \ No newline at end of file diff --git a/Lang/Forth/IBAN b/Lang/Forth/IBAN new file mode 120000 index 0000000000..625a37d6d3 --- /dev/null +++ b/Lang/Forth/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Forth \ No newline at end of file diff --git a/Lang/Forth/Inheritance-Multiple b/Lang/Forth/Inheritance-Multiple new file mode 120000 index 0000000000..24ec79d711 --- /dev/null +++ b/Lang/Forth/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/Forth \ No newline at end of file diff --git a/Lang/Forth/Jump-anywhere b/Lang/Forth/Jump-anywhere new file mode 120000 index 0000000000..7a134276f0 --- /dev/null +++ b/Lang/Forth/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Forth \ No newline at end of file diff --git a/Lang/Forth/Knapsack-problem-0-1 b/Lang/Forth/Knapsack-problem-0-1 new file mode 120000 index 0000000000..7fe668060c --- /dev/null +++ b/Lang/Forth/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Forth \ No newline at end of file diff --git a/Lang/Forth/Multiple-distinct-objects b/Lang/Forth/Multiple-distinct-objects new file mode 120000 index 0000000000..e8497b6750 --- /dev/null +++ b/Lang/Forth/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Forth \ No newline at end of file diff --git a/Lang/Forth/One-of-n-lines-in-a-file b/Lang/Forth/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..808f033e23 --- /dev/null +++ b/Lang/Forth/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Forth \ No newline at end of file diff --git a/Lang/Forth/Rep-string b/Lang/Forth/Rep-string new file mode 120000 index 0000000000..7363057273 --- /dev/null +++ b/Lang/Forth/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Forth \ No newline at end of file diff --git a/Lang/Forth/Respond-to-an-unknown-method-call b/Lang/Forth/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..53c1da3bca --- /dev/null +++ b/Lang/Forth/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Forth \ No newline at end of file diff --git a/Lang/Forth/Safe-addition b/Lang/Forth/Safe-addition new file mode 120000 index 0000000000..62fd3c7e4c --- /dev/null +++ b/Lang/Forth/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Forth \ No newline at end of file diff --git a/Lang/Forth/Send-an-unknown-method-call b/Lang/Forth/Send-an-unknown-method-call new file mode 120000 index 0000000000..57b0ba51eb --- /dev/null +++ b/Lang/Forth/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Forth \ No newline at end of file diff --git a/Lang/Forth/Seven-sided-dice-from-five-sided-dice b/Lang/Forth/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..888b157388 --- /dev/null +++ b/Lang/Forth/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Forth \ No newline at end of file diff --git a/Lang/Forth/Singleton b/Lang/Forth/Singleton new file mode 120000 index 0000000000..872411af4f --- /dev/null +++ b/Lang/Forth/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Forth \ No newline at end of file diff --git a/Lang/Forth/String-append b/Lang/Forth/String-append new file mode 120000 index 0000000000..02b6a9ecfb --- /dev/null +++ b/Lang/Forth/String-append @@ -0,0 +1 @@ +../../Task/String-append/Forth \ No newline at end of file diff --git a/Lang/Forth/Strip-a-set-of-characters-from-a-string b/Lang/Forth/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..b9e490c43a --- /dev/null +++ b/Lang/Forth/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Forth \ No newline at end of file diff --git a/Lang/Forth/Temperature-conversion b/Lang/Forth/Temperature-conversion new file mode 120000 index 0000000000..c22aeccbee --- /dev/null +++ b/Lang/Forth/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Forth \ No newline at end of file diff --git a/Lang/Forth/Verify-distribution-uniformity-Naive b/Lang/Forth/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..b724c6e79b --- /dev/null +++ b/Lang/Forth/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Forth \ No newline at end of file diff --git a/Lang/Fortran/00DESCRIPTION b/Lang/Fortran/00DESCRIPTION index 3562d91fc6..0aa8ae19a5 100644 --- a/Lang/Fortran/00DESCRIPTION +++ b/Lang/Fortran/00DESCRIPTION @@ -6,9 +6,9 @@ |gc=no |LCT=yes |tags=fortran -|bnf=http://fortran.comsci.us/syntax/statement/index.html}}{{language programming paradigm|Imperative}} +|bnf=http://fortran.comsci.us/syntax/statement/index.html}}{{language programming paradigm|Imperative}}{{Language programming paradigm|Procedural}}{{Language programming paradigm|Object-oriented}} Fortran is the oldest programming language still in widespread use. The language has evolved considerably since it was first released in 1957. Fortran was original developed for scientific and engineering applications, and remains especially suited to numeric computation and scientific computing. By convention, versions before Fortran 90 are spelled with all uppercase letters (e.g. FORTRAN 66, FORTRAN 77), while starting with Fortran 90, the mixed case spelling is used (i.e. Fortran 90, Fortran 95, Fortran 2003 and Fortran 2008). The most recent standard is Fortran 2008 (ISO/IEC 1539-1:2010). FORTRAN 77, being quite old, lacks almost everything one expects from a modern programming language. It uses a fixed-length line and column oriented line format which was motivated by punch cards. Due to its age, and since FORTRAN compilers generally gave very good performance for numerical code, a lot of code, especially scientific code, was written in FORTRAN. Also, for quite a while there was no free Fortran 90 compiler, which also caused a lot of FORTRAN 77 code to be written even quite some time after Fortran 90 was standardized. Because of the large body of code written in FORTRAN 77 it remains relevant today. Indeed, every modern Fortran compiler still accepts FORTRAN 77 code. -Fortran 90 was a major revision of the language. It introduced a new free-form source code format, modern programming language features like modules, pointers and user-defined types, an improved type system for built-in types and superiour built-in array handling. Newer Fortran standards (Fortran 2003 and Fortran 2008) added further modern features, like support for object oriented programming, inheritance, polymorphism, parallel processing, and interoperability with the C programming language. \ No newline at end of file +Fortran 90 was a major revision of the language. It introduced a new free-form source code format, modern programming language features like modules, pointers and user-defined types, an improved type system for built-in types and superiour built-in array handling. Newer Fortran standards (Fortran 2003 and Fortran 2008) added further modern features, like support for [[object oriented programming]], [[inheritance]], [[polymorphism]], [[parallel processing]], and [[interoperability]] with the C programming language. \ No newline at end of file diff --git a/Lang/Fortran/AKS-test-for-primes b/Lang/Fortran/AKS-test-for-primes new file mode 120000 index 0000000000..f46317c48e --- /dev/null +++ b/Lang/Fortran/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Abstract-type b/Lang/Fortran/Abstract-type new file mode 120000 index 0000000000..41be494622 --- /dev/null +++ b/Lang/Fortran/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Abundant,-deficient-and-perfect-number-classifications b/Lang/Fortran/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..06059754e8 --- /dev/null +++ b/Lang/Fortran/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Accumulator-factory b/Lang/Fortran/Accumulator-factory new file mode 120000 index 0000000000..36a0a37371 --- /dev/null +++ b/Lang/Fortran/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Aliquot-sequence-classifications b/Lang/Fortran/Aliquot-sequence-classifications new file mode 120000 index 0000000000..e1c40eb8be --- /dev/null +++ b/Lang/Fortran/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Amicable-pairs b/Lang/Fortran/Amicable-pairs new file mode 120000 index 0000000000..98eba959b3 --- /dev/null +++ b/Lang/Fortran/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Averages-Mean-time-of-day b/Lang/Fortran/Averages-Mean-time-of-day new file mode 120000 index 0000000000..ad0894ce73 --- /dev/null +++ b/Lang/Fortran/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Calendar b/Lang/Fortran/Calendar new file mode 120000 index 0000000000..94fab520bd --- /dev/null +++ b/Lang/Fortran/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Call-a-foreign-language-function b/Lang/Fortran/Call-a-foreign-language-function new file mode 120000 index 0000000000..70fc320d1b --- /dev/null +++ b/Lang/Fortran/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Call-a-function-in-a-shared-library b/Lang/Fortran/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..beba116d1f --- /dev/null +++ b/Lang/Fortran/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Classes b/Lang/Fortran/Classes new file mode 120000 index 0000000000..46896a3bd7 --- /dev/null +++ b/Lang/Fortran/Classes @@ -0,0 +1 @@ +../../Task/Classes/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Detect-division-by-zero b/Lang/Fortran/Detect-division-by-zero new file mode 120000 index 0000000000..c9b1ae6382 --- /dev/null +++ b/Lang/Fortran/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Empty-string b/Lang/Fortran/Empty-string new file mode 120000 index 0000000000..9119b181ba --- /dev/null +++ b/Lang/Fortran/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Hello-world-Line-printer b/Lang/Fortran/Hello-world-Line-printer new file mode 120000 index 0000000000..aefef09e3f --- /dev/null +++ b/Lang/Fortran/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Fortran \ No newline at end of file diff --git a/Lang/Fortran/JSON b/Lang/Fortran/JSON new file mode 120000 index 0000000000..1840bc68f2 --- /dev/null +++ b/Lang/Fortran/JSON @@ -0,0 +1 @@ +../../Task/JSON/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Least-common-multiple b/Lang/Fortran/Least-common-multiple new file mode 120000 index 0000000000..991a313e35 --- /dev/null +++ b/Lang/Fortran/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ludic-numbers b/Lang/Fortran/Ludic-numbers new file mode 120000 index 0000000000..55a267ebee --- /dev/null +++ b/Lang/Fortran/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Mad-Libs b/Lang/Fortran/Mad-Libs new file mode 120000 index 0000000000..1fbcf35daa --- /dev/null +++ b/Lang/Fortran/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Magic-squares-of-odd-order b/Lang/Fortran/Magic-squares-of-odd-order new file mode 120000 index 0000000000..80808cdd31 --- /dev/null +++ b/Lang/Fortran/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Natural-sorting b/Lang/Fortran/Natural-sorting new file mode 120000 index 0000000000..7f6f957b43 --- /dev/null +++ b/Lang/Fortran/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Pernicious-numbers b/Lang/Fortran/Pernicious-numbers new file mode 120000 index 0000000000..068d6c225f --- /dev/null +++ b/Lang/Fortran/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Pick-random-element b/Lang/Fortran/Pick-random-element new file mode 120000 index 0000000000..3962dd1f61 --- /dev/null +++ b/Lang/Fortran/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Random-number-generator--included- b/Lang/Fortran/Random-number-generator--included- new file mode 120000 index 0000000000..5d41c113ae --- /dev/null +++ b/Lang/Fortran/Random-number-generator--included- @@ -0,0 +1 @@ +../../Task/Random-number-generator--included-/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Remove-lines-from-a-file b/Lang/Fortran/Remove-lines-from-a-file new file mode 120000 index 0000000000..3fbd0aa83b --- /dev/null +++ b/Lang/Fortran/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Reverse-words-in-a-string b/Lang/Fortran/Reverse-words-in-a-string new file mode 120000 index 0000000000..eb58812f2b --- /dev/null +++ b/Lang/Fortran/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sequence-of-primes-by-Trial-Division b/Lang/Fortran/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..02d60e2b83 --- /dev/null +++ b/Lang/Fortran/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Fortran \ No newline at end of file diff --git a/Lang/Fortran/String-append b/Lang/Fortran/String-append new file mode 120000 index 0000000000..3be1b1cee6 --- /dev/null +++ b/Lang/Fortran/String-append @@ -0,0 +1 @@ +../../Task/String-append/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sutherland-Hodgman-polygon-clipping b/Lang/Fortran/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..a3075c031e --- /dev/null +++ b/Lang/Fortran/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Text-processing-1 b/Lang/Fortran/Text-processing-1 new file mode 120000 index 0000000000..5c3b32e7bd --- /dev/null +++ b/Lang/Fortran/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Text-processing-2 b/Lang/Fortran/Text-processing-2 new file mode 120000 index 0000000000..10107cd885 --- /dev/null +++ b/Lang/Fortran/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Ulam-spiral--for-primes- b/Lang/Fortran/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..f10047c579 --- /dev/null +++ b/Lang/Fortran/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Undefined-values b/Lang/Fortran/Undefined-values new file mode 120000 index 0000000000..95b96bd293 --- /dev/null +++ b/Lang/Fortran/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Vigen-re-cipher b/Lang/Fortran/Vigen-re-cipher new file mode 120000 index 0000000000..1b5fb3bc24 --- /dev/null +++ b/Lang/Fortran/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Fortran \ No newline at end of file diff --git a/Lang/Frege/FizzBuzz b/Lang/Frege/FizzBuzz new file mode 120000 index 0000000000..e2345e302c --- /dev/null +++ b/Lang/Frege/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Frege \ No newline at end of file diff --git a/Lang/Frink/Almost-prime b/Lang/Frink/Almost-prime new file mode 120000 index 0000000000..dae495389b --- /dev/null +++ b/Lang/Frink/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Frink \ No newline at end of file diff --git a/Lang/Frink/Higher-order-functions b/Lang/Frink/Higher-order-functions new file mode 120000 index 0000000000..af6a7350c8 --- /dev/null +++ b/Lang/Frink/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Frink \ No newline at end of file diff --git a/Lang/Frink/Host-introspection b/Lang/Frink/Host-introspection new file mode 120000 index 0000000000..85ad494026 --- /dev/null +++ b/Lang/Frink/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/Frink \ No newline at end of file diff --git a/Lang/Frink/Input-loop b/Lang/Frink/Input-loop new file mode 120000 index 0000000000..690b5bf5fb --- /dev/null +++ b/Lang/Frink/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Frink \ No newline at end of file diff --git a/Lang/Frink/Iterated-digits-squaring b/Lang/Frink/Iterated-digits-squaring new file mode 120000 index 0000000000..b5a380614f --- /dev/null +++ b/Lang/Frink/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Frink \ No newline at end of file diff --git a/Lang/Frink/Reverse-words-in-a-string b/Lang/Frink/Reverse-words-in-a-string new file mode 120000 index 0000000000..9ead316821 --- /dev/null +++ b/Lang/Frink/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Frink \ No newline at end of file diff --git a/Lang/Frink/Set b/Lang/Frink/Set new file mode 120000 index 0000000000..1800ca37c6 --- /dev/null +++ b/Lang/Frink/Set @@ -0,0 +1 @@ +../../Task/Set/Frink \ No newline at end of file diff --git a/Lang/GW-BASIC/100-doors b/Lang/GW-BASIC/100-doors new file mode 120000 index 0000000000..1c0cd96d10 --- /dev/null +++ b/Lang/GW-BASIC/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/99-Bottles-of-Beer b/Lang/GW-BASIC/99-Bottles-of-Beer new file mode 120000 index 0000000000..dd219cfda2 --- /dev/null +++ b/Lang/GW-BASIC/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Arrays b/Lang/GW-BASIC/Arrays new file mode 120000 index 0000000000..737dc1d0d1 --- /dev/null +++ b/Lang/GW-BASIC/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Loops-Break b/Lang/GW-BASIC/Loops-Break new file mode 120000 index 0000000000..1b35aefc89 --- /dev/null +++ b/Lang/GW-BASIC/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/00DESCRIPTION b/Lang/Gambas/00DESCRIPTION index 1801824bc0..3bfe141f2a 100644 --- a/Lang/Gambas/00DESCRIPTION +++ b/Lang/Gambas/00DESCRIPTION @@ -11,4 +11,5 @@ Gambas is a free development environment based on a [[Basic]] interpreter with object extensions, a bit like Visual Basic™ (but it is NOT a clone !). -With Gambas, you can quickly design your program [[GUI]] with QT or GTK+, access [[MySQL]], [[PostgreSQL]], Firebird, ODBC and [[SQLite]] databases, pilot KDE applications with DCOP, translate your program into any language, create network applications easily, make 3D [[OpenGL]] applications, make CGI web applications, and so on... \ No newline at end of file +With Gambas, you can quickly design your program [[GUI]] with QT or GTK+, access [[MySQL]], [[PostgreSQL]], Firebird, ODBC and [[SQLite]] databases, pilot KDE applications with DCOP, translate your program into any language, create network applications easily, make 3D [[OpenGL]] applications, make CGI web applications, and so on... +[http://www.papdan.com/seo-services-search-engine-optimisation.php Melbourne SEO Services] | [http://www.papdan.com/ Melbourne Web Developer] | [http://www.usapropertyinvestors.com.au USA Property Investment] | [http://www.phillro.com.au/p/industrial-2/airless-spray-packages-2/ Airless Spray] \ No newline at end of file diff --git a/Lang/Gema/Reverse-words-in-a-string b/Lang/Gema/Reverse-words-in-a-string new file mode 120000 index 0000000000..4e29712325 --- /dev/null +++ b/Lang/Gema/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Gema \ No newline at end of file diff --git a/Lang/Go/00DESCRIPTION b/Lang/Go/00DESCRIPTION index 838664d138..026db41f29 100644 --- a/Lang/Go/00DESCRIPTION +++ b/Lang/Go/00DESCRIPTION @@ -22,7 +22,7 @@ Not to be confused with [[:Category:Go!|Go!]] *[[wp:Go (programming language)|Go in Wikipedia]] * [http://tour.golang.org/ Go Tour and Tutorial] * [http://golang.org/doc/devel/release.html Release History] -** Release Notes: [http://golang.org/doc/go1.3 1.3], [http://golang.org/doc/go1.2 1.2], [http://golang.org/doc/go1.1 1.1], [http://golang.org/doc/go1 1.0] +** Release Notes: [http://golang.org/doc/go1.4 1.4], [http://golang.org/doc/go1.3 1.3], [http://golang.org/doc/go1.2 1.2], [http://golang.org/doc/go1.1 1.1], [http://golang.org/doc/go1 1.0] * [http://golang.org/ref/spec Go language specification] * [http://golang.org/pkg/ Go standard library documentation] * [http://go-lang.cat-v.org/ Go Language Resources] \ No newline at end of file diff --git a/Lang/Go/Morse-code b/Lang/Go/Morse-code new file mode 120000 index 0000000000..ba07747ad0 --- /dev/null +++ b/Lang/Go/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Go \ No newline at end of file diff --git a/Lang/Go/Old-lady-swallowed-a-fly b/Lang/Go/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..c47fac54b6 --- /dev/null +++ b/Lang/Go/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Go \ No newline at end of file diff --git a/Lang/Go/Plot-coordinate-pairs b/Lang/Go/Plot-coordinate-pairs new file mode 120000 index 0000000000..ad70948f56 --- /dev/null +++ b/Lang/Go/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Go \ No newline at end of file diff --git a/Lang/Groovy/Conways-Game-of-Life b/Lang/Groovy/Conways-Game-of-Life new file mode 120000 index 0000000000..8bba59dc0a --- /dev/null +++ b/Lang/Groovy/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Longest-common-subsequence b/Lang/Groovy/Longest-common-subsequence new file mode 120000 index 0000000000..ba3e5f9fe3 --- /dev/null +++ b/Lang/Groovy/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Send-email b/Lang/Groovy/Send-email new file mode 120000 index 0000000000..1f90e4cc6a --- /dev/null +++ b/Lang/Groovy/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/Groovy \ No newline at end of file diff --git a/Lang/Groovy/URL-encoding b/Lang/Groovy/URL-encoding new file mode 120000 index 0000000000..3a3e57da31 --- /dev/null +++ b/Lang/Groovy/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Groovy \ No newline at end of file diff --git a/Lang/HLA/00DESCRIPTION b/Lang/HLA/00DESCRIPTION index 163b52623f..a3aef2cae0 100644 --- a/Lang/HLA/00DESCRIPTION +++ b/Lang/HLA/00DESCRIPTION @@ -10,4 +10,6 @@ High Level Assembler (HLA) is a front-end for several x86 assemblers developed by Randall Hyde. It allows the use of higher-level language constructs to aid both beginners and advanced assembly developers. It fully supports advanced data types and object-oriented assembly language programming. It uses a syntax loosely based on several high-level languages (HLL), such as Pascal, Ada, Modula-2, and C++, to allow the creation of readable assembly language programs, and to allow HLL programmers to learn HLA as rapidly as possible. ==See Also== -* [[wp:High Level Assembly|Wikipedia: High Level Assembly]] \ No newline at end of file +* [[wp:High Level Assembly|Wikipedia: High Level Assembly]] + +[[category: assembly]] \ No newline at end of file diff --git a/Lang/Haskell/Averages-Mean-time-of-day b/Lang/Haskell/Averages-Mean-time-of-day new file mode 120000 index 0000000000..bf6b5b63f4 --- /dev/null +++ b/Lang/Haskell/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Bitcoin-public-point-to-address b/Lang/Haskell/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..7164fc9bcc --- /dev/null +++ b/Lang/Haskell/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Catalan-numbers-Pascals-triangle b/Lang/Haskell/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..03aa9039f0 --- /dev/null +++ b/Lang/Haskell/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Combinations-and-permutations b/Lang/Haskell/Combinations-and-permutations new file mode 120000 index 0000000000..fd10850322 --- /dev/null +++ b/Lang/Haskell/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Guess-the-number-With-feedback--player- b/Lang/Haskell/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..c6bb6a49f3 --- /dev/null +++ b/Lang/Haskell/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Here-document b/Lang/Haskell/Here-document new file mode 120000 index 0000000000..83b3041248 --- /dev/null +++ b/Lang/Haskell/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Hickerson-series-of-almost-integers b/Lang/Haskell/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..4ef21ee30c --- /dev/null +++ b/Lang/Haskell/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Haskell \ No newline at end of file diff --git a/Lang/Haskell/MD4 b/Lang/Haskell/MD4 new file mode 120000 index 0000000000..abfe57a537 --- /dev/null +++ b/Lang/Haskell/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Make-directory-path b/Lang/Haskell/Make-directory-path new file mode 120000 index 0000000000..69a538bf4e --- /dev/null +++ b/Lang/Haskell/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Parse-an-IP-Address b/Lang/Haskell/Parse-an-IP-Address new file mode 120000 index 0000000000..c03b70b399 --- /dev/null +++ b/Lang/Haskell/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Percolation-Site-percolation b/Lang/Haskell/Percolation-Site-percolation new file mode 120000 index 0000000000..198c2b6e78 --- /dev/null +++ b/Lang/Haskell/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Pig-the-dice-game b/Lang/Haskell/Pig-the-dice-game new file mode 120000 index 0000000000..18b6114d2c --- /dev/null +++ b/Lang/Haskell/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Pig-the-dice-game-Player b/Lang/Haskell/Pig-the-dice-game-Player new file mode 120000 index 0000000000..918530e4c7 --- /dev/null +++ b/Lang/Haskell/Pig-the-dice-game-Player @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game-Player/Haskell \ No newline at end of file diff --git a/Lang/Haskell/RIPEMD-160 b/Lang/Haskell/RIPEMD-160 new file mode 120000 index 0000000000..236c652b8d --- /dev/null +++ b/Lang/Haskell/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Haskell \ No newline at end of file diff --git a/Lang/Haskell/SHA-256 b/Lang/Haskell/SHA-256 new file mode 120000 index 0000000000..4922c134ff --- /dev/null +++ b/Lang/Haskell/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Set-puzzle b/Lang/Haskell/Set-puzzle new file mode 120000 index 0000000000..2d90e47deb --- /dev/null +++ b/Lang/Haskell/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Solve-the-no-connection-puzzle b/Lang/Haskell/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..e38bd18ad8 --- /dev/null +++ b/Lang/Haskell/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Haskell \ No newline at end of file diff --git a/Lang/Haskell/State-name-puzzle b/Lang/Haskell/State-name-puzzle new file mode 120000 index 0000000000..66a237a7a3 --- /dev/null +++ b/Lang/Haskell/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Textonyms b/Lang/Haskell/Textonyms new file mode 120000 index 0000000000..7bf9e8e323 --- /dev/null +++ b/Lang/Haskell/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Haskell \ No newline at end of file diff --git a/Lang/Haskell/The-Twelve-Days-of-Christmas b/Lang/Haskell/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..9e17534306 --- /dev/null +++ b/Lang/Haskell/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Ulam-spiral--for-primes- b/Lang/Haskell/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..7cea2fd98f --- /dev/null +++ b/Lang/Haskell/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Haskell \ No newline at end of file diff --git a/Lang/J/00DESCRIPTION b/Lang/J/00DESCRIPTION index 8d48f2ec70..a4c5cf1794 100644 --- a/Lang/J/00DESCRIPTION +++ b/Lang/J/00DESCRIPTION @@ -16,7 +16,7 @@ {{language programming paradigm|Reflective}} {{language programming paradigm|Tacit}} -== the J language == +== The J language == J is a notational programming language designed for interactive use. @@ -29,6 +29,8 @@ Object-module and imperative techniques are supported, but not required. The J programming language was designed and developed by [http://en.wikipedia.org/wiki/Kenneth_E._Iverson Ken Iverson] and Roger Hui. It is a closely related successor to [[APL]], also by Iverson which itself was a successor to the notation Ken Iverson used to teach his classes about computers in the 1950s.
+The notation draws heavily from concepts of [[wp:Abstract algebra|Abstract algebra]] and [[wp:Tensor calculus|Tensor calculus]], simplified for describing computer architecture and design to a pragmatic business audience. (The ideas themselves are simple, but for some reason the topics scare most teachers.) + == Reading J == J is meant to be read with the aid of a computer. J sentences are single lines and trying variations and simplifications of an expression is common practice. The first step in understanding any J sentence is to understand the data you started with and the data which resulted. When learning how a J sentence works, you can also try simpler sentences with the same data or perhaps related data. When trying to understand contexts that use large data structures, it can often be wise to investigate small, representative samples until you understand how the code works. @@ -72,7 +74,7 @@ The language represents capabilities of hardware. For example, if language did n Discussion of the goals of the J community on RC and general guidelines for presenting J solutions takes place at [[J/HouseStyle|House Style]]. -== Jers on RosettaCode == +== Jedi on RosettaCode == *[[User:Roger_Hui|Roger Hui]]: [[Special:Contributions/Roger_Hui|contributions]], [[j:RogerHui|J wiki]] *[[User:TBH|Tracy Harms]]: [[Special:Contributions/TBH|contributions]], [[j:TracyHarms|J wiki]] *[[User:DanBron|Dan Bron]]: [[Special:Contributions/DanBron|contributions]], [[j:DanBron|J wiki]] @@ -84,10 +86,12 @@ Discussion of the goals of the J community on RC and general guidelines for pres *[[User:VZC|VZC]]: [[Special:Contributions/VZC|contributions]] *[[User:Bathala|Alex 'bathala' Rufon]]: [[Special:Contributions/Bathala|contributions]], [[j:bathala|J wiki]] *[[User:Lambertdw|David Lambert]]:[[Special:Contributions/Lambertdw|contributions]] +*[[User:JimTheriot|JimTheriot]]: [[Special:Contributions/JimTheriot|contributions]] +*[[User:DevonMcC|Devon McCormick]]: [[Special:Contributions/DevonMcC|contributions]] -== try me == +== Try me == -Want to try one of those cryptic J lines you see peppered through RC? Try pasting it into the [http://erxz.com:10080/ web interface for buubot '''(broken link)'''] (a [[Perl]] IRC bot which has a J evaluation mode: just prefix your line with '''''jeval'''''). +Want to try one of those cryptic J lines you see peppered through RC? Try pasting it into this [http://joebo.github.io/j-emscripten/ browser-based implementation of J]. If you want to be a bit more interactive, and get some guidance from J gurus, you can join the actual J IRC channel on Freenode, #jsoftware. Buubot and several other J eval bots run there. If you don't have an IRC client you can try [http://webchat.freenode.net/?randomnick=1&channels=jsoftware freenode's web interface] (or just [http://webchat.freenode.net/?channels=jsoftware&randomnick=1 give it a quick spin]). More [[j:Community/IRC|details about the J IRC community]] is available. diff --git a/Lang/J/Active-object b/Lang/J/Active-object new file mode 120000 index 0000000000..846094f4b9 --- /dev/null +++ b/Lang/J/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/J \ No newline at end of file diff --git a/Lang/J/Canny-edge-detector b/Lang/J/Canny-edge-detector new file mode 120000 index 0000000000..a61a4bd58e --- /dev/null +++ b/Lang/J/Canny-edge-detector @@ -0,0 +1 @@ +../../Task/Canny-edge-detector/J \ No newline at end of file diff --git a/Lang/J/DNS-query b/Lang/J/DNS-query new file mode 120000 index 0000000000..a35c9d77e4 --- /dev/null +++ b/Lang/J/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/J \ No newline at end of file diff --git a/Lang/J/Make-directory-path b/Lang/J/Make-directory-path new file mode 120000 index 0000000000..4d3f928a96 --- /dev/null +++ b/Lang/J/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/J \ No newline at end of file diff --git a/Lang/J/Visualize-a-tree b/Lang/J/Visualize-a-tree new file mode 120000 index 0000000000..d6353cb684 --- /dev/null +++ b/Lang/J/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/J \ No newline at end of file diff --git a/Lang/J/Vogels-approximation-method b/Lang/J/Vogels-approximation-method new file mode 120000 index 0000000000..1cd14d69eb --- /dev/null +++ b/Lang/J/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/J \ No newline at end of file diff --git a/Lang/Jacquard-Loom/00DESCRIPTION b/Lang/Jacquard-Loom/00DESCRIPTION index 2a7b789441..d6c7119dcc 100644 --- a/Lang/Jacquard-Loom/00DESCRIPTION +++ b/Lang/Jacquard-Loom/00DESCRIPTION @@ -3,4 +3,4 @@ The Jacquard loom is a mechanical loom, invented by Joseph Marie Jacquard, that simplifies the process of manufacturing patterned textiles by using punched cards to control the patterning sequence. -Tasks in this category use patterns to solve programming related tasks on the loom. \ No newline at end of file +Tasks in this category use patterns to solve programming-related tasks on the loom. \ No newline at end of file diff --git a/Lang/Java/AKS-test-for-primes b/Lang/Java/AKS-test-for-primes new file mode 120000 index 0000000000..5f7031bd01 --- /dev/null +++ b/Lang/Java/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Java \ No newline at end of file diff --git a/Lang/Java/Almost-prime b/Lang/Java/Almost-prime new file mode 120000 index 0000000000..54e37b0f81 --- /dev/null +++ b/Lang/Java/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Java \ No newline at end of file diff --git a/Lang/Java/Textonyms b/Lang/Java/Textonyms new file mode 120000 index 0000000000..83fc394563 --- /dev/null +++ b/Lang/Java/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Java \ No newline at end of file diff --git a/Lang/Java/Voronoi-diagram b/Lang/Java/Voronoi-diagram new file mode 120000 index 0000000000..395d3b9c11 --- /dev/null +++ b/Lang/Java/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Java \ No newline at end of file diff --git a/Lang/JavaScript/Abundant,-deficient-and-perfect-number-classifications b/Lang/JavaScript/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..cb8ef603b9 --- /dev/null +++ b/Lang/JavaScript/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Averages-Mean-angle b/Lang/JavaScript/Averages-Mean-angle new file mode 120000 index 0000000000..1ca77e2fc9 --- /dev/null +++ b/Lang/JavaScript/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Call-an-object-method b/Lang/JavaScript/Call-an-object-method new file mode 120000 index 0000000000..18ad23df2f --- /dev/null +++ b/Lang/JavaScript/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Catalan-numbers-Pascals-triangle b/Lang/JavaScript/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..b8e2ee8653 --- /dev/null +++ b/Lang/JavaScript/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Comments b/Lang/JavaScript/Comments new file mode 120000 index 0000000000..30921d778a --- /dev/null +++ b/Lang/JavaScript/Comments @@ -0,0 +1 @@ +../../Task/Comments/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Equilibrium-index b/Lang/JavaScript/Equilibrium-index new file mode 120000 index 0000000000..a6bbbb9c38 --- /dev/null +++ b/Lang/JavaScript/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Fibonacci-word b/Lang/JavaScript/Fibonacci-word new file mode 120000 index 0000000000..943ed5e55e --- /dev/null +++ b/Lang/JavaScript/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Find-the-last-Sunday-of-each-month b/Lang/JavaScript/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..07045aca13 --- /dev/null +++ b/Lang/JavaScript/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Gaussian-elimination b/Lang/JavaScript/Gaussian-elimination new file mode 120000 index 0000000000..4486427bda --- /dev/null +++ b/Lang/JavaScript/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Harshad-or-Niven-series b/Lang/JavaScript/Harshad-or-Niven-series new file mode 120000 index 0000000000..4d1ab96d7a --- /dev/null +++ b/Lang/JavaScript/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Image-convolution b/Lang/JavaScript/Image-convolution new file mode 120000 index 0000000000..b7b5b61ede --- /dev/null +++ b/Lang/JavaScript/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Literals-String b/Lang/JavaScript/Literals-String new file mode 120000 index 0000000000..0676fd8684 --- /dev/null +++ b/Lang/JavaScript/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Narcissistic-decimal-number b/Lang/JavaScript/Narcissistic-decimal-number new file mode 120000 index 0000000000..f28ec56315 --- /dev/null +++ b/Lang/JavaScript/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Nth b/Lang/JavaScript/Nth new file mode 120000 index 0000000000..15238d49b9 --- /dev/null +++ b/Lang/JavaScript/Nth @@ -0,0 +1 @@ +../../Task/Nth/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Parsing-RPN-calculator-algorithm b/Lang/JavaScript/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..aee5e723bb --- /dev/null +++ b/Lang/JavaScript/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Partial-function-application b/Lang/JavaScript/Partial-function-application new file mode 120000 index 0000000000..969a642dcf --- /dev/null +++ b/Lang/JavaScript/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Percentage-difference-between-images b/Lang/JavaScript/Percentage-difference-between-images new file mode 120000 index 0000000000..3ef94e8cb9 --- /dev/null +++ b/Lang/JavaScript/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Phrase-reversals b/Lang/JavaScript/Phrase-reversals new file mode 120000 index 0000000000..c1e844e325 --- /dev/null +++ b/Lang/JavaScript/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Return-multiple-values b/Lang/JavaScript/Return-multiple-values new file mode 120000 index 0000000000..29666431d9 --- /dev/null +++ b/Lang/JavaScript/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Reverse-words-in-a-string b/Lang/JavaScript/Reverse-words-in-a-string new file mode 120000 index 0000000000..83bab01e2b --- /dev/null +++ b/Lang/JavaScript/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Roots-of-unity b/Lang/JavaScript/Roots-of-unity new file mode 120000 index 0000000000..16993ebab6 --- /dev/null +++ b/Lang/JavaScript/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/S-Expressions b/Lang/JavaScript/S-Expressions new file mode 120000 index 0000000000..00938c1737 --- /dev/null +++ b/Lang/JavaScript/S-Expressions @@ -0,0 +1 @@ +../../Task/S-Expressions/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Sequence-of-non-squares b/Lang/JavaScript/Sequence-of-non-squares new file mode 120000 index 0000000000..e35c7009dc --- /dev/null +++ b/Lang/JavaScript/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Set b/Lang/JavaScript/Set new file mode 120000 index 0000000000..f51f302f17 --- /dev/null +++ b/Lang/JavaScript/Set @@ -0,0 +1 @@ +../../Task/Set/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Short-circuit-evaluation b/Lang/JavaScript/Short-circuit-evaluation new file mode 120000 index 0000000000..817d1c5b90 --- /dev/null +++ b/Lang/JavaScript/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Speech-synthesis b/Lang/JavaScript/Speech-synthesis new file mode 120000 index 0000000000..1a65a115fb --- /dev/null +++ b/Lang/JavaScript/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Temperature-conversion b/Lang/JavaScript/Temperature-conversion new file mode 120000 index 0000000000..d824cf5498 --- /dev/null +++ b/Lang/JavaScript/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Test-a-function b/Lang/JavaScript/Test-a-function new file mode 120000 index 0000000000..38d2b0ad1a --- /dev/null +++ b/Lang/JavaScript/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Word-wrap b/Lang/JavaScript/Word-wrap new file mode 120000 index 0000000000..95ad6055c8 --- /dev/null +++ b/Lang/JavaScript/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/JavaScript \ No newline at end of file diff --git a/Lang/Joy/Flatten-a-list b/Lang/Joy/Flatten-a-list new file mode 120000 index 0000000000..a01517f6a5 --- /dev/null +++ b/Lang/Joy/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Joy \ No newline at end of file diff --git a/Lang/Julia/AKS-test-for-primes b/Lang/Julia/AKS-test-for-primes new file mode 120000 index 0000000000..d3c7d5ffb6 --- /dev/null +++ b/Lang/Julia/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Julia \ No newline at end of file diff --git a/Lang/Julia/Abundant,-deficient-and-perfect-number-classifications b/Lang/Julia/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..c1feac6fff --- /dev/null +++ b/Lang/Julia/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Julia \ No newline at end of file diff --git a/Lang/Julia/Aliquot-sequence-classifications b/Lang/Julia/Aliquot-sequence-classifications new file mode 120000 index 0000000000..6a4ad0c2c0 --- /dev/null +++ b/Lang/Julia/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Julia \ No newline at end of file diff --git a/Lang/Julia/Amicable-pairs b/Lang/Julia/Amicable-pairs new file mode 120000 index 0000000000..806af67e99 --- /dev/null +++ b/Lang/Julia/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Julia \ No newline at end of file diff --git a/Lang/Julia/Arithmetic-Rational b/Lang/Julia/Arithmetic-Rational new file mode 120000 index 0000000000..72cd22644c --- /dev/null +++ b/Lang/Julia/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Julia \ No newline at end of file diff --git a/Lang/Julia/Arithmetic-geometric-mean b/Lang/Julia/Arithmetic-geometric-mean new file mode 120000 index 0000000000..f3133f4d18 --- /dev/null +++ b/Lang/Julia/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Julia \ No newline at end of file diff --git a/Lang/Julia/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Julia/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..64b8f20732 --- /dev/null +++ b/Lang/Julia/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap b/Lang/Julia/Bitmap new file mode 120000 index 0000000000..907f2b2c1a --- /dev/null +++ b/Lang/Julia/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-Bresenhams-line-algorithm b/Lang/Julia/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..325ecb6cc7 --- /dev/null +++ b/Lang/Julia/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-Histogram b/Lang/Julia/Bitmap-Histogram new file mode 120000 index 0000000000..492365386d --- /dev/null +++ b/Lang/Julia/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-Read-a-PPM-file b/Lang/Julia/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..f27c16fa12 --- /dev/null +++ b/Lang/Julia/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-Write-a-PPM-file b/Lang/Julia/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..4556c26499 --- /dev/null +++ b/Lang/Julia/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Brownian-tree b/Lang/Julia/Brownian-tree new file mode 120000 index 0000000000..19e43815df --- /dev/null +++ b/Lang/Julia/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Julia \ No newline at end of file diff --git a/Lang/Julia/CRC-32 b/Lang/Julia/CRC-32 new file mode 120000 index 0000000000..eb69d1d34f --- /dev/null +++ b/Lang/Julia/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Julia \ No newline at end of file diff --git a/Lang/Julia/CSV-data-manipulation b/Lang/Julia/CSV-data-manipulation new file mode 120000 index 0000000000..e3ef3b0269 --- /dev/null +++ b/Lang/Julia/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Julia \ No newline at end of file diff --git a/Lang/Julia/CSV-to-HTML-translation b/Lang/Julia/CSV-to-HTML-translation new file mode 120000 index 0000000000..f641a724fe --- /dev/null +++ b/Lang/Julia/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Julia \ No newline at end of file diff --git a/Lang/Julia/Carmichael-3-strong-pseudoprimes b/Lang/Julia/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..eb1c25c2d1 --- /dev/null +++ b/Lang/Julia/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Julia \ No newline at end of file diff --git a/Lang/Julia/Case-sensitivity-of-identifiers b/Lang/Julia/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..3292ecb38c --- /dev/null +++ b/Lang/Julia/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Julia \ No newline at end of file diff --git a/Lang/Julia/Catamorphism b/Lang/Julia/Catamorphism new file mode 120000 index 0000000000..eaa7dbf291 --- /dev/null +++ b/Lang/Julia/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Julia \ No newline at end of file diff --git a/Lang/Julia/Cholesky-decomposition b/Lang/Julia/Cholesky-decomposition new file mode 120000 index 0000000000..50a015fcb3 --- /dev/null +++ b/Lang/Julia/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Julia \ No newline at end of file diff --git a/Lang/Julia/Circles-of-given-radius-through-two-points b/Lang/Julia/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..b02eb138d9 --- /dev/null +++ b/Lang/Julia/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Julia \ No newline at end of file diff --git a/Lang/Julia/Combinations-and-permutations b/Lang/Julia/Combinations-and-permutations new file mode 120000 index 0000000000..066bae4a92 --- /dev/null +++ b/Lang/Julia/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Julia \ No newline at end of file diff --git a/Lang/Julia/Command-line-arguments b/Lang/Julia/Command-line-arguments new file mode 120000 index 0000000000..07f0512f1e --- /dev/null +++ b/Lang/Julia/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Julia \ No newline at end of file diff --git a/Lang/Julia/Comments b/Lang/Julia/Comments new file mode 120000 index 0000000000..84e9dfa9b9 --- /dev/null +++ b/Lang/Julia/Comments @@ -0,0 +1 @@ +../../Task/Comments/Julia \ No newline at end of file diff --git a/Lang/Julia/Compound-data-type b/Lang/Julia/Compound-data-type new file mode 120000 index 0000000000..6ba25aa070 --- /dev/null +++ b/Lang/Julia/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Julia \ No newline at end of file diff --git a/Lang/Julia/Constrained-random-points-on-a-circle b/Lang/Julia/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..45f37f34a3 --- /dev/null +++ b/Lang/Julia/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Julia \ No newline at end of file diff --git a/Lang/Julia/Copy-a-string b/Lang/Julia/Copy-a-string new file mode 120000 index 0000000000..df319b9df8 --- /dev/null +++ b/Lang/Julia/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Count-in-factors b/Lang/Julia/Count-in-factors new file mode 120000 index 0000000000..7d27041cec --- /dev/null +++ b/Lang/Julia/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Julia \ No newline at end of file diff --git a/Lang/Julia/Count-in-octal b/Lang/Julia/Count-in-octal new file mode 120000 index 0000000000..d167c8cd52 --- /dev/null +++ b/Lang/Julia/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Julia \ No newline at end of file diff --git a/Lang/Julia/Count-occurrences-of-a-substring b/Lang/Julia/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..a97edd6967 --- /dev/null +++ b/Lang/Julia/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Julia \ No newline at end of file diff --git a/Lang/Julia/Create-a-file b/Lang/Julia/Create-a-file new file mode 120000 index 0000000000..1f964c1daa --- /dev/null +++ b/Lang/Julia/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Create-a-two-dimensional-array-at-runtime b/Lang/Julia/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..577506b07d --- /dev/null +++ b/Lang/Julia/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Julia \ No newline at end of file diff --git a/Lang/Julia/Date-format b/Lang/Julia/Date-format new file mode 120000 index 0000000000..67bf28ce08 --- /dev/null +++ b/Lang/Julia/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Julia \ No newline at end of file diff --git a/Lang/Julia/Day-of-the-week b/Lang/Julia/Day-of-the-week new file mode 120000 index 0000000000..b323a81c8d --- /dev/null +++ b/Lang/Julia/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Julia \ No newline at end of file diff --git a/Lang/Julia/Detect-division-by-zero b/Lang/Julia/Detect-division-by-zero new file mode 120000 index 0000000000..4e481fc16f --- /dev/null +++ b/Lang/Julia/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Julia \ No newline at end of file diff --git a/Lang/Julia/Determine-if-a-string-is-numeric b/Lang/Julia/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..385ab457a8 --- /dev/null +++ b/Lang/Julia/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Julia \ No newline at end of file diff --git a/Lang/Julia/Digital-root b/Lang/Julia/Digital-root new file mode 120000 index 0000000000..28241a8fe8 --- /dev/null +++ b/Lang/Julia/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Julia \ No newline at end of file diff --git a/Lang/Julia/Digital-root-Multiplicative-digital-root b/Lang/Julia/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..6ddc305dfd --- /dev/null +++ b/Lang/Julia/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Julia \ No newline at end of file diff --git a/Lang/Julia/Dutch-national-flag-problem b/Lang/Julia/Dutch-national-flag-problem new file mode 120000 index 0000000000..a15b6a5715 --- /dev/null +++ b/Lang/Julia/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Julia \ No newline at end of file diff --git a/Lang/Julia/Empty-program b/Lang/Julia/Empty-program new file mode 120000 index 0000000000..b42701df3c --- /dev/null +++ b/Lang/Julia/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Julia \ No newline at end of file diff --git a/Lang/Julia/Empty-string b/Lang/Julia/Empty-string new file mode 120000 index 0000000000..94ac54f4ea --- /dev/null +++ b/Lang/Julia/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Evaluate-binomial-coefficients b/Lang/Julia/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..36c829d334 --- /dev/null +++ b/Lang/Julia/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/Julia \ No newline at end of file diff --git a/Lang/Julia/Execute-a-system-command b/Lang/Julia/Execute-a-system-command new file mode 120000 index 0000000000..8c95f58752 --- /dev/null +++ b/Lang/Julia/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Julia \ No newline at end of file diff --git a/Lang/Julia/Fibonacci-n-step-number-sequences b/Lang/Julia/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..a302a8cc8a --- /dev/null +++ b/Lang/Julia/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Julia \ No newline at end of file diff --git a/Lang/Julia/File-modification-time b/Lang/Julia/File-modification-time new file mode 120000 index 0000000000..0c4e596b11 --- /dev/null +++ b/Lang/Julia/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Julia \ No newline at end of file diff --git a/Lang/Julia/Find-common-directory-path b/Lang/Julia/Find-common-directory-path new file mode 120000 index 0000000000..4ba35043c4 --- /dev/null +++ b/Lang/Julia/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Julia \ No newline at end of file diff --git a/Lang/Julia/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Julia/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..d331f15773 --- /dev/null +++ b/Lang/Julia/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Julia \ No newline at end of file diff --git a/Lang/Julia/Find-limit-of-recursion b/Lang/Julia/Find-limit-of-recursion new file mode 120000 index 0000000000..3f6ed9b99d --- /dev/null +++ b/Lang/Julia/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Julia \ No newline at end of file diff --git a/Lang/Julia/Find-the-last-Sunday-of-each-month b/Lang/Julia/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..ff6ea7b142 --- /dev/null +++ b/Lang/Julia/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Julia \ No newline at end of file diff --git a/Lang/Julia/Find-the-missing-permutation b/Lang/Julia/Find-the-missing-permutation new file mode 120000 index 0000000000..e3fe9c3f56 --- /dev/null +++ b/Lang/Julia/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Julia \ No newline at end of file diff --git a/Lang/Julia/First-class-functions b/Lang/Julia/First-class-functions new file mode 120000 index 0000000000..3c53bf37b8 --- /dev/null +++ b/Lang/Julia/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Julia \ No newline at end of file diff --git a/Lang/Julia/Five-weekends b/Lang/Julia/Five-weekends new file mode 120000 index 0000000000..94866703d4 --- /dev/null +++ b/Lang/Julia/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Julia \ No newline at end of file diff --git a/Lang/Julia/Formatted-numeric-output b/Lang/Julia/Formatted-numeric-output new file mode 120000 index 0000000000..d625380233 --- /dev/null +++ b/Lang/Julia/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Julia \ No newline at end of file diff --git a/Lang/Julia/Four-bit-adder b/Lang/Julia/Four-bit-adder new file mode 120000 index 0000000000..bec3446bc1 --- /dev/null +++ b/Lang/Julia/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Julia \ No newline at end of file diff --git a/Lang/Julia/Generate-Chess960-starting-position b/Lang/Julia/Generate-Chess960-starting-position new file mode 120000 index 0000000000..32f0f95423 --- /dev/null +++ b/Lang/Julia/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Julia \ No newline at end of file diff --git a/Lang/Julia/Grayscale-image b/Lang/Julia/Grayscale-image new file mode 120000 index 0000000000..528693544e --- /dev/null +++ b/Lang/Julia/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/Julia \ No newline at end of file diff --git a/Lang/Julia/Greatest-subsequential-sum b/Lang/Julia/Greatest-subsequential-sum new file mode 120000 index 0000000000..b5b035b37e --- /dev/null +++ b/Lang/Julia/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Julia \ No newline at end of file diff --git a/Lang/Julia/Guess-the-number-With-feedback--player- b/Lang/Julia/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..e82ee882ca --- /dev/null +++ b/Lang/Julia/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Julia \ No newline at end of file diff --git a/Lang/Julia/Handle-a-signal b/Lang/Julia/Handle-a-signal new file mode 120000 index 0000000000..d7bb8fd49d --- /dev/null +++ b/Lang/Julia/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Julia \ No newline at end of file diff --git a/Lang/Julia/Heronian-triangles b/Lang/Julia/Heronian-triangles new file mode 120000 index 0000000000..4f4a72acdf --- /dev/null +++ b/Lang/Julia/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Julia \ No newline at end of file diff --git a/Lang/Julia/Hickerson-series-of-almost-integers b/Lang/Julia/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..21630baf25 --- /dev/null +++ b/Lang/Julia/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Julia \ No newline at end of file diff --git a/Lang/Julia/Hofstadter-Figure-Figure-sequences b/Lang/Julia/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..6d1b589f8c --- /dev/null +++ b/Lang/Julia/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/Julia \ No newline at end of file diff --git a/Lang/Julia/Host-introspection b/Lang/Julia/Host-introspection new file mode 120000 index 0000000000..8c1a7bae9b --- /dev/null +++ b/Lang/Julia/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/Julia \ No newline at end of file diff --git a/Lang/Julia/Hostname b/Lang/Julia/Hostname new file mode 120000 index 0000000000..f7931a5730 --- /dev/null +++ b/Lang/Julia/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Julia \ No newline at end of file diff --git a/Lang/Julia/Integer-overflow b/Lang/Julia/Integer-overflow new file mode 120000 index 0000000000..9d7e47f26d --- /dev/null +++ b/Lang/Julia/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Julia \ No newline at end of file diff --git a/Lang/Julia/Jensens-Device b/Lang/Julia/Jensens-Device new file mode 120000 index 0000000000..e43d4fd36b --- /dev/null +++ b/Lang/Julia/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Julia \ No newline at end of file diff --git a/Lang/Julia/Knapsack-problem-0-1 b/Lang/Julia/Knapsack-problem-0-1 new file mode 120000 index 0000000000..bded0d40be --- /dev/null +++ b/Lang/Julia/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Julia \ No newline at end of file diff --git a/Lang/Julia/Knapsack-problem-Bounded b/Lang/Julia/Knapsack-problem-Bounded new file mode 120000 index 0000000000..49650883b1 --- /dev/null +++ b/Lang/Julia/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/Julia \ No newline at end of file diff --git a/Lang/Julia/Knapsack-problem-Continuous b/Lang/Julia/Knapsack-problem-Continuous new file mode 120000 index 0000000000..465d007eb6 --- /dev/null +++ b/Lang/Julia/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Julia \ No newline at end of file diff --git a/Lang/Julia/Knuth-shuffle b/Lang/Julia/Knuth-shuffle new file mode 120000 index 0000000000..bf752b86ac --- /dev/null +++ b/Lang/Julia/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Julia \ No newline at end of file diff --git a/Lang/Julia/Knuths-algorithm-S b/Lang/Julia/Knuths-algorithm-S new file mode 120000 index 0000000000..fc9a3fe796 --- /dev/null +++ b/Lang/Julia/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Julia \ No newline at end of file diff --git a/Lang/Julia/Largest-int-from-concatenated-ints b/Lang/Julia/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..5ea663dc41 --- /dev/null +++ b/Lang/Julia/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Julia \ No newline at end of file diff --git a/Lang/Julia/Last-Friday-of-each-month b/Lang/Julia/Last-Friday-of-each-month new file mode 120000 index 0000000000..f2777b39ce --- /dev/null +++ b/Lang/Julia/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Julia \ No newline at end of file diff --git a/Lang/Julia/Linear-congruential-generator b/Lang/Julia/Linear-congruential-generator new file mode 120000 index 0000000000..e4b30049d5 --- /dev/null +++ b/Lang/Julia/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Julia \ No newline at end of file diff --git a/Lang/Julia/List-comprehensions b/Lang/Julia/List-comprehensions new file mode 120000 index 0000000000..d88c3d4d0c --- /dev/null +++ b/Lang/Julia/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Julia \ No newline at end of file diff --git a/Lang/Julia/Logical-operations b/Lang/Julia/Logical-operations new file mode 120000 index 0000000000..87aab336f0 --- /dev/null +++ b/Lang/Julia/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-Break b/Lang/Julia/Loops-Break new file mode 120000 index 0000000000..05acc19375 --- /dev/null +++ b/Lang/Julia/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-Continue b/Lang/Julia/Loops-Continue new file mode 120000 index 0000000000..5ca975bea0 --- /dev/null +++ b/Lang/Julia/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-Do-while b/Lang/Julia/Loops-Do-while new file mode 120000 index 0000000000..a3bcbe9807 --- /dev/null +++ b/Lang/Julia/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-For b/Lang/Julia/Loops-For new file mode 120000 index 0000000000..e505c98a86 --- /dev/null +++ b/Lang/Julia/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-Infinite b/Lang/Julia/Loops-Infinite new file mode 120000 index 0000000000..295dce3a59 --- /dev/null +++ b/Lang/Julia/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-Nested b/Lang/Julia/Loops-Nested new file mode 120000 index 0000000000..f25265c84b --- /dev/null +++ b/Lang/Julia/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-While b/Lang/Julia/Loops-While new file mode 120000 index 0000000000..e9b2f54095 --- /dev/null +++ b/Lang/Julia/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Julia \ No newline at end of file diff --git a/Lang/Julia/Ludic-numbers b/Lang/Julia/Ludic-numbers new file mode 120000 index 0000000000..1733b20f6c --- /dev/null +++ b/Lang/Julia/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Julia \ No newline at end of file diff --git a/Lang/Julia/Luhn-test-of-credit-card-numbers b/Lang/Julia/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..a43eccd3c2 --- /dev/null +++ b/Lang/Julia/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Julia \ No newline at end of file diff --git a/Lang/Julia/MD4 b/Lang/Julia/MD4 new file mode 120000 index 0000000000..ab0051dd70 --- /dev/null +++ b/Lang/Julia/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Julia \ No newline at end of file diff --git a/Lang/Julia/MD5 b/Lang/Julia/MD5 new file mode 120000 index 0000000000..1b667de7ba --- /dev/null +++ b/Lang/Julia/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Julia \ No newline at end of file diff --git a/Lang/Julia/Man-or-boy-test b/Lang/Julia/Man-or-boy-test new file mode 120000 index 0000000000..e662212588 --- /dev/null +++ b/Lang/Julia/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Julia \ No newline at end of file diff --git a/Lang/Julia/Monty-Hall-problem b/Lang/Julia/Monty-Hall-problem new file mode 120000 index 0000000000..d4dfc78cd4 --- /dev/null +++ b/Lang/Julia/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Julia \ No newline at end of file diff --git a/Lang/Julia/Multifactorial b/Lang/Julia/Multifactorial new file mode 120000 index 0000000000..caa79acdad --- /dev/null +++ b/Lang/Julia/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Julia \ No newline at end of file diff --git a/Lang/Julia/Multiplication-tables b/Lang/Julia/Multiplication-tables new file mode 120000 index 0000000000..d7ece1d4e7 --- /dev/null +++ b/Lang/Julia/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Julia \ No newline at end of file diff --git a/Lang/Julia/Narcissistic-decimal-number b/Lang/Julia/Narcissistic-decimal-number new file mode 120000 index 0000000000..8b098da38e --- /dev/null +++ b/Lang/Julia/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Julia \ No newline at end of file diff --git a/Lang/Julia/Non-continuous-subsequences b/Lang/Julia/Non-continuous-subsequences new file mode 120000 index 0000000000..2e3a8798c9 --- /dev/null +++ b/Lang/Julia/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Julia \ No newline at end of file diff --git a/Lang/Julia/Non-decimal-radices-Output b/Lang/Julia/Non-decimal-radices-Output new file mode 120000 index 0000000000..fedc0db61e --- /dev/null +++ b/Lang/Julia/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Julia \ No newline at end of file diff --git a/Lang/Julia/Nth b/Lang/Julia/Nth new file mode 120000 index 0000000000..69f4d91711 --- /dev/null +++ b/Lang/Julia/Nth @@ -0,0 +1 @@ +../../Task/Nth/Julia \ No newline at end of file diff --git a/Lang/Julia/Number-names b/Lang/Julia/Number-names new file mode 120000 index 0000000000..e25df48c29 --- /dev/null +++ b/Lang/Julia/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Julia \ No newline at end of file diff --git a/Lang/Julia/One-dimensional-cellular-automata b/Lang/Julia/One-dimensional-cellular-automata new file mode 120000 index 0000000000..84f8564cfa --- /dev/null +++ b/Lang/Julia/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Julia \ No newline at end of file diff --git a/Lang/Julia/One-of-n-lines-in-a-file b/Lang/Julia/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..3eda6c78d1 --- /dev/null +++ b/Lang/Julia/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Order-disjoint-list-items b/Lang/Julia/Order-disjoint-list-items new file mode 120000 index 0000000000..f966317a4c --- /dev/null +++ b/Lang/Julia/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Julia \ No newline at end of file diff --git a/Lang/Julia/Order-two-numerical-lists b/Lang/Julia/Order-two-numerical-lists new file mode 120000 index 0000000000..3e64c1031d --- /dev/null +++ b/Lang/Julia/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Julia \ No newline at end of file diff --git a/Lang/Julia/Ordered-words b/Lang/Julia/Ordered-words new file mode 120000 index 0000000000..0d217d6bb7 --- /dev/null +++ b/Lang/Julia/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Julia \ No newline at end of file diff --git a/Lang/Julia/Pangram-checker b/Lang/Julia/Pangram-checker new file mode 120000 index 0000000000..4914729d2c --- /dev/null +++ b/Lang/Julia/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Julia \ No newline at end of file diff --git a/Lang/Julia/Penneys-game b/Lang/Julia/Penneys-game new file mode 120000 index 0000000000..5ba2e45969 --- /dev/null +++ b/Lang/Julia/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Julia \ No newline at end of file diff --git a/Lang/Julia/Permutation-test b/Lang/Julia/Permutation-test new file mode 120000 index 0000000000..06a1536120 --- /dev/null +++ b/Lang/Julia/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Julia \ No newline at end of file diff --git a/Lang/Julia/Permutations b/Lang/Julia/Permutations new file mode 120000 index 0000000000..ec6a5e5506 --- /dev/null +++ b/Lang/Julia/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Julia \ No newline at end of file diff --git a/Lang/Julia/Permutations-Rank-of-a-permutation b/Lang/Julia/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..7c57878a46 --- /dev/null +++ b/Lang/Julia/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Julia \ No newline at end of file diff --git a/Lang/Julia/Pernicious-numbers b/Lang/Julia/Pernicious-numbers new file mode 120000 index 0000000000..cca41ba131 --- /dev/null +++ b/Lang/Julia/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Julia \ No newline at end of file diff --git a/Lang/Julia/Phrase-reversals b/Lang/Julia/Phrase-reversals new file mode 120000 index 0000000000..b678ec54ea --- /dev/null +++ b/Lang/Julia/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Julia \ No newline at end of file diff --git a/Lang/Julia/Pig-the-dice-game b/Lang/Julia/Pig-the-dice-game new file mode 120000 index 0000000000..7a65a56c9b --- /dev/null +++ b/Lang/Julia/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Julia \ No newline at end of file diff --git a/Lang/Julia/Playing-cards b/Lang/Julia/Playing-cards new file mode 120000 index 0000000000..2e4d97a8d4 --- /dev/null +++ b/Lang/Julia/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Julia \ No newline at end of file diff --git a/Lang/Julia/Polynomial-long-division b/Lang/Julia/Polynomial-long-division new file mode 120000 index 0000000000..bef09a6283 --- /dev/null +++ b/Lang/Julia/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/Julia \ No newline at end of file diff --git a/Lang/Julia/Price-fraction b/Lang/Julia/Price-fraction new file mode 120000 index 0000000000..34654c2ad5 --- /dev/null +++ b/Lang/Julia/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Julia \ No newline at end of file diff --git a/Lang/Julia/Primality-by-trial-division b/Lang/Julia/Primality-by-trial-division new file mode 120000 index 0000000000..8567cb5be5 --- /dev/null +++ b/Lang/Julia/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Julia \ No newline at end of file diff --git a/Lang/Julia/Priority-queue b/Lang/Julia/Priority-queue new file mode 120000 index 0000000000..b2dd1017e5 --- /dev/null +++ b/Lang/Julia/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Julia \ No newline at end of file diff --git a/Lang/Julia/Probabilistic-choice b/Lang/Julia/Probabilistic-choice new file mode 120000 index 0000000000..79719f9079 --- /dev/null +++ b/Lang/Julia/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Julia \ No newline at end of file diff --git a/Lang/Julia/Problem-of-Apollonius b/Lang/Julia/Problem-of-Apollonius new file mode 120000 index 0000000000..31ccab6a8a --- /dev/null +++ b/Lang/Julia/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/Julia \ No newline at end of file diff --git a/Lang/Julia/Program-name b/Lang/Julia/Program-name new file mode 120000 index 0000000000..e9b16d0f3b --- /dev/null +++ b/Lang/Julia/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Julia \ No newline at end of file diff --git a/Lang/Julia/Pythagorean-triples b/Lang/Julia/Pythagorean-triples new file mode 120000 index 0000000000..fcc234f5cd --- /dev/null +++ b/Lang/Julia/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Julia \ No newline at end of file diff --git a/Lang/Julia/Queue-Definition b/Lang/Julia/Queue-Definition new file mode 120000 index 0000000000..981162c078 --- /dev/null +++ b/Lang/Julia/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Julia \ No newline at end of file diff --git a/Lang/Julia/RIPEMD-160 b/Lang/Julia/RIPEMD-160 new file mode 120000 index 0000000000..35cf63f872 --- /dev/null +++ b/Lang/Julia/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Julia \ No newline at end of file diff --git a/Lang/Julia/Random-number-generator--device- b/Lang/Julia/Random-number-generator--device- new file mode 120000 index 0000000000..785ac1c11a --- /dev/null +++ b/Lang/Julia/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Julia \ No newline at end of file diff --git a/Lang/Julia/Range-extraction b/Lang/Julia/Range-extraction new file mode 120000 index 0000000000..a7b148334e --- /dev/null +++ b/Lang/Julia/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Julia \ No newline at end of file diff --git a/Lang/Julia/Ranking-methods b/Lang/Julia/Ranking-methods new file mode 120000 index 0000000000..91242599c4 --- /dev/null +++ b/Lang/Julia/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Julia \ No newline at end of file diff --git a/Lang/Julia/Remove-lines-from-a-file b/Lang/Julia/Remove-lines-from-a-file new file mode 120000 index 0000000000..fb7e90c87d --- /dev/null +++ b/Lang/Julia/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Rep-string b/Lang/Julia/Rep-string new file mode 120000 index 0000000000..f54fd02fe6 --- /dev/null +++ b/Lang/Julia/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Roman-numerals-Decode b/Lang/Julia/Roman-numerals-Decode new file mode 120000 index 0000000000..6357611df3 --- /dev/null +++ b/Lang/Julia/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Julia \ No newline at end of file diff --git a/Lang/Julia/Roman-numerals-Encode b/Lang/Julia/Roman-numerals-Encode new file mode 120000 index 0000000000..653bbe26d0 --- /dev/null +++ b/Lang/Julia/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Julia \ No newline at end of file diff --git a/Lang/Julia/Roots-of-a-function b/Lang/Julia/Roots-of-a-function new file mode 120000 index 0000000000..166fce97e0 --- /dev/null +++ b/Lang/Julia/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Julia \ No newline at end of file diff --git a/Lang/Julia/Roots-of-a-quadratic-function b/Lang/Julia/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..087645696a --- /dev/null +++ b/Lang/Julia/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/Julia \ No newline at end of file diff --git a/Lang/Julia/SHA-1 b/Lang/Julia/SHA-1 new file mode 120000 index 0000000000..7baffeba6c --- /dev/null +++ b/Lang/Julia/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Julia \ No newline at end of file diff --git a/Lang/Julia/SHA-256 b/Lang/Julia/SHA-256 new file mode 120000 index 0000000000..47bec43404 --- /dev/null +++ b/Lang/Julia/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Julia \ No newline at end of file diff --git a/Lang/Julia/Secure-temporary-file b/Lang/Julia/Secure-temporary-file new file mode 120000 index 0000000000..38d2f4777d --- /dev/null +++ b/Lang/Julia/Secure-temporary-file @@ -0,0 +1 @@ +../../Task/Secure-temporary-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Sequence-of-primes-by-Trial-Division b/Lang/Julia/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..278c833a5c --- /dev/null +++ b/Lang/Julia/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Julia \ No newline at end of file diff --git a/Lang/Julia/Set-consolidation b/Lang/Julia/Set-consolidation new file mode 120000 index 0000000000..07c62a117e --- /dev/null +++ b/Lang/Julia/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Julia \ No newline at end of file diff --git a/Lang/Julia/Show-the-epoch b/Lang/Julia/Show-the-epoch new file mode 120000 index 0000000000..f09058b9b6 --- /dev/null +++ b/Lang/Julia/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Julia \ No newline at end of file diff --git a/Lang/Julia/Sieve-of-Eratosthenes b/Lang/Julia/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..c237011891 --- /dev/null +++ b/Lang/Julia/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Julia \ No newline at end of file diff --git a/Lang/Julia/Sort-an-array-of-composite-structures b/Lang/Julia/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..90433094a8 --- /dev/null +++ b/Lang/Julia/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/Julia \ No newline at end of file diff --git a/Lang/Julia/Sort-disjoint-sublist b/Lang/Julia/Sort-disjoint-sublist new file mode 120000 index 0000000000..2d21ca2ef8 --- /dev/null +++ b/Lang/Julia/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Julia \ No newline at end of file diff --git a/Lang/Julia/Sort-using-a-custom-comparator b/Lang/Julia/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..1f4d98e0e1 --- /dev/null +++ b/Lang/Julia/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Bead-sort b/Lang/Julia/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..4a3f8dd3f4 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Bogosort b/Lang/Julia/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..5c74ce4621 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Bubble-sort b/Lang/Julia/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..2043b2327a --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Cocktail-sort b/Lang/Julia/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..895d25b8e6 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Gnome-sort b/Lang/Julia/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..a720634b4e --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Merge-sort b/Lang/Julia/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..22b4899108 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Pancake-sort b/Lang/Julia/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..803b87915a --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Selection-sort b/Lang/Julia/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..52d17a13c0 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sorting-algorithms-Sleep-sort b/Lang/Julia/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..065075a8f3 --- /dev/null +++ b/Lang/Julia/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Sparkline-in-unicode b/Lang/Julia/Sparkline-in-unicode new file mode 120000 index 0000000000..add849f874 --- /dev/null +++ b/Lang/Julia/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/Julia \ No newline at end of file diff --git a/Lang/Julia/Spiral-matrix b/Lang/Julia/Spiral-matrix new file mode 120000 index 0000000000..e318845799 --- /dev/null +++ b/Lang/Julia/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Julia \ No newline at end of file diff --git a/Lang/Julia/Standard-deviation b/Lang/Julia/Standard-deviation new file mode 120000 index 0000000000..7f2281f0b6 --- /dev/null +++ b/Lang/Julia/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Julia \ No newline at end of file diff --git a/Lang/Julia/Stem-and-leaf-plot b/Lang/Julia/Stem-and-leaf-plot new file mode 120000 index 0000000000..03bfa259e1 --- /dev/null +++ b/Lang/Julia/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Julia \ No newline at end of file diff --git a/Lang/Julia/Strip-a-set-of-characters-from-a-string b/Lang/Julia/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..0af2540f7c --- /dev/null +++ b/Lang/Julia/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Strip-comments-from-a-string b/Lang/Julia/Strip-comments-from-a-string new file mode 120000 index 0000000000..9c58aee02d --- /dev/null +++ b/Lang/Julia/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Julia/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..4b2cc8f4a1 --- /dev/null +++ b/Lang/Julia/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Symmetric-difference b/Lang/Julia/Symmetric-difference new file mode 120000 index 0000000000..e7da253ee1 --- /dev/null +++ b/Lang/Julia/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Julia \ No newline at end of file diff --git a/Lang/Julia/System-time b/Lang/Julia/System-time new file mode 120000 index 0000000000..399e536e52 --- /dev/null +++ b/Lang/Julia/System-time @@ -0,0 +1 @@ +../../Task/System-time/Julia \ No newline at end of file diff --git a/Lang/Julia/Terminal-control-Coloured-text b/Lang/Julia/Terminal-control-Coloured-text new file mode 120000 index 0000000000..3e3f6ff9d6 --- /dev/null +++ b/Lang/Julia/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Julia \ No newline at end of file diff --git a/Lang/Julia/Terminal-control-Ringing-the-terminal-bell b/Lang/Julia/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..10afa1d073 --- /dev/null +++ b/Lang/Julia/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Julia \ No newline at end of file diff --git a/Lang/Julia/Terminal-control-Unicode-output b/Lang/Julia/Terminal-control-Unicode-output new file mode 120000 index 0000000000..2e0702f3a0 --- /dev/null +++ b/Lang/Julia/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Julia \ No newline at end of file diff --git a/Lang/Julia/Textonyms b/Lang/Julia/Textonyms new file mode 120000 index 0000000000..8c386ee5cb --- /dev/null +++ b/Lang/Julia/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Julia \ No newline at end of file diff --git a/Lang/Julia/Tokenize-a-string b/Lang/Julia/Tokenize-a-string new file mode 120000 index 0000000000..7996ab8d7f --- /dev/null +++ b/Lang/Julia/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Julia \ No newline at end of file diff --git a/Lang/Julia/Truncatable-primes b/Lang/Julia/Truncatable-primes new file mode 120000 index 0000000000..365a7f952c --- /dev/null +++ b/Lang/Julia/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Julia \ No newline at end of file diff --git a/Lang/Julia/Twelve-statements b/Lang/Julia/Twelve-statements new file mode 120000 index 0000000000..002ac8b341 --- /dev/null +++ b/Lang/Julia/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Julia \ No newline at end of file diff --git a/Lang/Julia/URL-decoding b/Lang/Julia/URL-decoding new file mode 120000 index 0000000000..f72b9558dc --- /dev/null +++ b/Lang/Julia/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Julia \ No newline at end of file diff --git a/Lang/Julia/URL-encoding b/Lang/Julia/URL-encoding new file mode 120000 index 0000000000..cba1b595ac --- /dev/null +++ b/Lang/Julia/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Julia \ No newline at end of file diff --git a/Lang/Julia/User-input-Text b/Lang/Julia/User-input-Text new file mode 120000 index 0000000000..11c7bc993d --- /dev/null +++ b/Lang/Julia/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Julia \ No newline at end of file diff --git a/Lang/Julia/Vampire-number b/Lang/Julia/Vampire-number new file mode 120000 index 0000000000..2945b85af4 --- /dev/null +++ b/Lang/Julia/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Julia \ No newline at end of file diff --git a/Lang/Julia/Van-der-Corput-sequence b/Lang/Julia/Van-der-Corput-sequence new file mode 120000 index 0000000000..118704284b --- /dev/null +++ b/Lang/Julia/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Julia \ No newline at end of file diff --git a/Lang/Julia/Variable-length-quantity b/Lang/Julia/Variable-length-quantity new file mode 120000 index 0000000000..c0d88f0e2b --- /dev/null +++ b/Lang/Julia/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/Julia \ No newline at end of file diff --git a/Lang/Julia/Vector-products b/Lang/Julia/Vector-products new file mode 120000 index 0000000000..f1b49cd99e --- /dev/null +++ b/Lang/Julia/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Julia \ No newline at end of file diff --git a/Lang/Julia/Vigen-re-cipher b/Lang/Julia/Vigen-re-cipher new file mode 120000 index 0000000000..2870348e80 --- /dev/null +++ b/Lang/Julia/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Julia \ No newline at end of file diff --git a/Lang/Julia/Vigen-re-cipher-Cryptanalysis b/Lang/Julia/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..1e7f9476cf --- /dev/null +++ b/Lang/Julia/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Julia \ No newline at end of file diff --git a/Lang/Julia/Vogels-approximation-method b/Lang/Julia/Vogels-approximation-method new file mode 120000 index 0000000000..3336216041 --- /dev/null +++ b/Lang/Julia/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Julia \ No newline at end of file diff --git a/Lang/Julia/Web-scraping b/Lang/Julia/Web-scraping new file mode 120000 index 0000000000..63d1261517 --- /dev/null +++ b/Lang/Julia/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Julia \ No newline at end of file diff --git a/Lang/Julia/Zero-to-the-zero-power b/Lang/Julia/Zero-to-the-zero-power new file mode 120000 index 0000000000..c0a054fbde --- /dev/null +++ b/Lang/Julia/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Julia \ No newline at end of file diff --git a/Lang/Julia/Zig-zag-matrix b/Lang/Julia/Zig-zag-matrix new file mode 120000 index 0000000000..98a684ab53 --- /dev/null +++ b/Lang/Julia/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Julia \ No newline at end of file diff --git a/Lang/K/Tokenize-a-string b/Lang/K/Tokenize-a-string new file mode 120000 index 0000000000..95e254e65b --- /dev/null +++ b/Lang/K/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/K \ No newline at end of file diff --git a/Lang/Kotlin/Color-of-a-screen-pixel b/Lang/Kotlin/Color-of-a-screen-pixel new file mode 120000 index 0000000000..2edb6eca2c --- /dev/null +++ b/Lang/Kotlin/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/FizzBuzz b/Lang/Kotlin/FizzBuzz new file mode 120000 index 0000000000..0ea9cffde2 --- /dev/null +++ b/Lang/Kotlin/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Hello-world-Text b/Lang/Kotlin/Hello-world-Text new file mode 120000 index 0000000000..8b141418a0 --- /dev/null +++ b/Lang/Kotlin/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Largest-int-from-concatenated-ints b/Lang/Kotlin/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..65bd0acf6e --- /dev/null +++ b/Lang/Kotlin/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Read-entire-file b/Lang/Kotlin/Read-entire-file new file mode 120000 index 0000000000..c5c8a499e8 --- /dev/null +++ b/Lang/Kotlin/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Repeat-a-string b/Lang/Kotlin/Repeat-a-string new file mode 120000 index 0000000000..5574e2e2e5 --- /dev/null +++ b/Lang/Kotlin/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Semordnilap b/Lang/Kotlin/Semordnilap new file mode 120000 index 0000000000..7cf743e01b --- /dev/null +++ b/Lang/Kotlin/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sierpinski-triangle-Graphical b/Lang/Kotlin/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..b4274d54ec --- /dev/null +++ b/Lang/Kotlin/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Tokenize-a-string b/Lang/Kotlin/Tokenize-a-string new file mode 120000 index 0000000000..08ff0929db --- /dev/null +++ b/Lang/Kotlin/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Kotlin \ No newline at end of file diff --git a/Lang/LOLCODE/Towers-of-Hanoi b/Lang/LOLCODE/Towers-of-Hanoi new file mode 120000 index 0000000000..429a5b4afb --- /dev/null +++ b/Lang/LOLCODE/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/LOLCODE \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Circles-of-given-radius-through-two-points b/Lang/Liberty-BASIC/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..b96e2d44ae --- /dev/null +++ b/Lang/Liberty-BASIC/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Comma-quibbling b/Lang/Liberty-BASIC/Comma-quibbling new file mode 120000 index 0000000000..9a12ba020e --- /dev/null +++ b/Lang/Liberty-BASIC/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Draw-a-cuboid b/Lang/Liberty-BASIC/Draw-a-cuboid new file mode 120000 index 0000000000..efe8117412 --- /dev/null +++ b/Lang/Liberty-BASIC/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Entropy b/Lang/Liberty-BASIC/Entropy new file mode 120000 index 0000000000..bf373cbf9b --- /dev/null +++ b/Lang/Liberty-BASIC/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Magic-squares-of-odd-order b/Lang/Liberty-BASIC/Magic-squares-of-odd-order new file mode 120000 index 0000000000..5bcb09318c --- /dev/null +++ b/Lang/Liberty-BASIC/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Old-lady-swallowed-a-fly b/Lang/Liberty-BASIC/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..8d11a4523c --- /dev/null +++ b/Lang/Liberty-BASIC/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/One-of-n-lines-in-a-file b/Lang/Liberty-BASIC/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..4314fc0616 --- /dev/null +++ b/Lang/Liberty-BASIC/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Program-name b/Lang/Liberty-BASIC/Program-name new file mode 120000 index 0000000000..31298b9863 --- /dev/null +++ b/Lang/Liberty-BASIC/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Reverse-words-in-a-string b/Lang/Liberty-BASIC/Reverse-words-in-a-string new file mode 120000 index 0000000000..40669f35ff --- /dev/null +++ b/Lang/Liberty-BASIC/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Runge-Kutta-method b/Lang/Liberty-BASIC/Runge-Kutta-method new file mode 120000 index 0000000000..8ad0b3b78f --- /dev/null +++ b/Lang/Liberty-BASIC/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/SHA-1 b/Lang/Liberty-BASIC/SHA-1 new file mode 120000 index 0000000000..23d6235e7f --- /dev/null +++ b/Lang/Liberty-BASIC/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Seven-sided-dice-from-five-sided-dice b/Lang/Liberty-BASIC/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..9852f92910 --- /dev/null +++ b/Lang/Liberty-BASIC/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sort-stability b/Lang/Liberty-BASIC/Sort-stability new file mode 120000 index 0000000000..494a6de169 --- /dev/null +++ b/Lang/Liberty-BASIC/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sorting-algorithms-Comb-sort b/Lang/Liberty-BASIC/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..3638b40deb --- /dev/null +++ b/Lang/Liberty-BASIC/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Sorting-algorithms-Shell-sort b/Lang/Liberty-BASIC/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..46b93295f1 --- /dev/null +++ b/Lang/Liberty-BASIC/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Verify-distribution-uniformity-Naive b/Lang/Liberty-BASIC/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..78cb14c769 --- /dev/null +++ b/Lang/Liberty-BASIC/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Limbo/Gray-code b/Lang/Limbo/Gray-code new file mode 120000 index 0000000000..9e3f906849 --- /dev/null +++ b/Lang/Limbo/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Levenshtein-distance b/Lang/Limbo/Levenshtein-distance new file mode 120000 index 0000000000..4ccd2bd3ff --- /dev/null +++ b/Lang/Limbo/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Limbo \ No newline at end of file diff --git a/Lang/Logo/Day-of-the-week b/Lang/Logo/Day-of-the-week new file mode 120000 index 0000000000..7c658ed654 --- /dev/null +++ b/Lang/Logo/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Logo \ No newline at end of file diff --git a/Lang/Logo/Even-or-odd b/Lang/Logo/Even-or-odd new file mode 120000 index 0000000000..861717cf1d --- /dev/null +++ b/Lang/Logo/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Logo \ No newline at end of file diff --git a/Lang/Logo/Last-Friday-of-each-month b/Lang/Logo/Last-Friday-of-each-month new file mode 120000 index 0000000000..0a2c9bcfa9 --- /dev/null +++ b/Lang/Logo/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Logo \ No newline at end of file diff --git a/Lang/Logo/Middle-three-digits b/Lang/Logo/Middle-three-digits new file mode 120000 index 0000000000..1ac4c27d79 --- /dev/null +++ b/Lang/Logo/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Logo \ No newline at end of file diff --git a/Lang/Logo/Old-lady-swallowed-a-fly b/Lang/Logo/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..32ae52ef47 --- /dev/null +++ b/Lang/Logo/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Logo \ No newline at end of file diff --git a/Lang/Logo/Quine b/Lang/Logo/Quine new file mode 120000 index 0000000000..fc16c39b96 --- /dev/null +++ b/Lang/Logo/Quine @@ -0,0 +1 @@ +../../Task/Quine/Logo \ No newline at end of file diff --git a/Lang/Logtalk/Call-an-object-method b/Lang/Logtalk/Call-an-object-method new file mode 120000 index 0000000000..e04921bd85 --- /dev/null +++ b/Lang/Logtalk/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Currying b/Lang/Logtalk/Currying new file mode 120000 index 0000000000..bc066213ae --- /dev/null +++ b/Lang/Logtalk/Currying @@ -0,0 +1 @@ +../../Task/Currying/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/IBAN b/Lang/Logtalk/IBAN new file mode 120000 index 0000000000..07ffaed4ba --- /dev/null +++ b/Lang/Logtalk/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Include-a-file b/Lang/Logtalk/Include-a-file new file mode 120000 index 0000000000..3fb1d6ae4c --- /dev/null +++ b/Lang/Logtalk/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Logtalk \ No newline at end of file diff --git a/Lang/Logtalk/Sieve-of-Eratosthenes b/Lang/Logtalk/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..bbfe6edf88 --- /dev/null +++ b/Lang/Logtalk/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Logtalk \ No newline at end of file diff --git a/Lang/Lua/Function-prototype b/Lang/Lua/Function-prototype new file mode 120000 index 0000000000..89c36c9e13 --- /dev/null +++ b/Lang/Lua/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Lua \ No newline at end of file diff --git a/Lang/Lua/Harshad-or-Niven-series b/Lang/Lua/Harshad-or-Niven-series new file mode 120000 index 0000000000..3d8be078f6 --- /dev/null +++ b/Lang/Lua/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Lua \ No newline at end of file diff --git a/Lang/Lua/Haversine-formula b/Lang/Lua/Haversine-formula new file mode 120000 index 0000000000..4617a7c154 --- /dev/null +++ b/Lang/Lua/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Lua \ No newline at end of file diff --git a/Lang/Lua/Maximum-triangle-path-sum b/Lang/Lua/Maximum-triangle-path-sum new file mode 120000 index 0000000000..1063cb76ed --- /dev/null +++ b/Lang/Lua/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Lua \ No newline at end of file diff --git a/Lang/Lua/Morse-code b/Lang/Lua/Morse-code new file mode 120000 index 0000000000..a92ffa33b7 --- /dev/null +++ b/Lang/Lua/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Lua \ No newline at end of file diff --git a/Lang/Lua/Pinstripe-Display b/Lang/Lua/Pinstripe-Display new file mode 120000 index 0000000000..5d748cbfec --- /dev/null +++ b/Lang/Lua/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Lua \ No newline at end of file diff --git a/Lang/Lua/Voronoi-diagram b/Lang/Lua/Voronoi-diagram new file mode 120000 index 0000000000..85e1ea6f65 --- /dev/null +++ b/Lang/Lua/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Lua \ No newline at end of file diff --git a/Lang/Lua/Zhang-Suen-thinning-algorithm b/Lang/Lua/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..4eeba27f6b --- /dev/null +++ b/Lang/Lua/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Lua \ No newline at end of file diff --git a/Lang/MATLAB/Canny-edge-detector b/Lang/MATLAB/Canny-edge-detector new file mode 120000 index 0000000000..e31e0e66ee --- /dev/null +++ b/Lang/MATLAB/Canny-edge-detector @@ -0,0 +1 @@ +../../Task/Canny-edge-detector/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Count-the-coins b/Lang/MATLAB/Count-the-coins new file mode 120000 index 0000000000..75bb08801a --- /dev/null +++ b/Lang/MATLAB/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Levenshtein-distance b/Lang/MATLAB/Levenshtein-distance new file mode 120000 index 0000000000..62f3cd7479 --- /dev/null +++ b/Lang/MATLAB/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sequence-of-primes-by-Trial-Division b/Lang/MATLAB/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..f835c2f209 --- /dev/null +++ b/Lang/MATLAB/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Zero-to-the-zero-power b/Lang/MATLAB/Zero-to-the-zero-power new file mode 120000 index 0000000000..02c15b9e12 --- /dev/null +++ b/Lang/MATLAB/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/MATLAB \ No newline at end of file diff --git a/Lang/Maple/99-Bottles-of-Beer b/Lang/Maple/99-Bottles-of-Beer new file mode 120000 index 0000000000..5db72c8b56 --- /dev/null +++ b/Lang/Maple/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Maple \ No newline at end of file diff --git a/Lang/Maple/Guess-the-number b/Lang/Maple/Guess-the-number new file mode 120000 index 0000000000..0be9ff29cd --- /dev/null +++ b/Lang/Maple/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Maple \ No newline at end of file diff --git a/Lang/Maple/Guess-the-number-With-feedback b/Lang/Maple/Guess-the-number-With-feedback new file mode 120000 index 0000000000..3b24ab5b17 --- /dev/null +++ b/Lang/Maple/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Maple \ No newline at end of file diff --git a/Lang/Maple/Haversine-formula b/Lang/Maple/Haversine-formula new file mode 120000 index 0000000000..16bbeeb4a3 --- /dev/null +++ b/Lang/Maple/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Maple \ No newline at end of file diff --git a/Lang/Maple/JSON b/Lang/Maple/JSON new file mode 120000 index 0000000000..846925764f --- /dev/null +++ b/Lang/Maple/JSON @@ -0,0 +1 @@ +../../Task/JSON/Maple \ No newline at end of file diff --git a/Lang/Maple/Roots-of-unity b/Lang/Maple/Roots-of-unity new file mode 120000 index 0000000000..da728a0c74 --- /dev/null +++ b/Lang/Maple/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Maple \ No newline at end of file diff --git a/Lang/Maple/Semiprime b/Lang/Maple/Semiprime new file mode 120000 index 0000000000..7b8db4c41d --- /dev/null +++ b/Lang/Maple/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Maple \ No newline at end of file diff --git a/Lang/Mathematica/Aliquot-sequence-classifications b/Lang/Mathematica/Aliquot-sequence-classifications new file mode 120000 index 0000000000..b54bcd26d0 --- /dev/null +++ b/Lang/Mathematica/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Append-a-record-to-the-end-of-a-text-file b/Lang/Mathematica/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..72bc309969 --- /dev/null +++ b/Lang/Mathematica/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Atomic-updates b/Lang/Mathematica/Atomic-updates new file mode 120000 index 0000000000..4d93b5cd6c --- /dev/null +++ b/Lang/Mathematica/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Bitmap-PPM-conversion-through-a-pipe b/Lang/Mathematica/Bitmap-PPM-conversion-through-a-pipe new file mode 120000 index 0000000000..8a2ac5cdd6 --- /dev/null +++ b/Lang/Mathematica/Bitmap-PPM-conversion-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Bitmap-Read-an-image-through-a-pipe b/Lang/Mathematica/Bitmap-Read-an-image-through-a-pipe new file mode 120000 index 0000000000..aa4737c20d --- /dev/null +++ b/Lang/Mathematica/Bitmap-Read-an-image-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-Read-an-image-through-a-pipe/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Canny-edge-detector b/Lang/Mathematica/Canny-edge-detector new file mode 120000 index 0000000000..e63211e15b --- /dev/null +++ b/Lang/Mathematica/Canny-edge-detector @@ -0,0 +1 @@ +../../Task/Canny-edge-detector/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Circles-of-given-radius-through-two-points b/Lang/Mathematica/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..57911afd60 --- /dev/null +++ b/Lang/Mathematica/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Colour-pinstripe-Display b/Lang/Mathematica/Colour-pinstripe-Display new file mode 120000 index 0000000000..0570013e4a --- /dev/null +++ b/Lang/Mathematica/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Deal-cards-for-FreeCell b/Lang/Mathematica/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..1f50777041 --- /dev/null +++ b/Lang/Mathematica/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Deepcopy b/Lang/Mathematica/Deepcopy new file mode 120000 index 0000000000..3ab889f62b --- /dev/null +++ b/Lang/Mathematica/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Delegates b/Lang/Mathematica/Delegates new file mode 120000 index 0000000000..24be59a1e6 --- /dev/null +++ b/Lang/Mathematica/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Generate-Chess960-starting-position b/Lang/Mathematica/Generate-Chess960-starting-position new file mode 120000 index 0000000000..071e49382d --- /dev/null +++ b/Lang/Mathematica/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Here-document b/Lang/Mathematica/Here-document new file mode 120000 index 0000000000..1d148ea39f --- /dev/null +++ b/Lang/Mathematica/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Honeycombs b/Lang/Mathematica/Honeycombs new file mode 120000 index 0000000000..dfd5685ae8 --- /dev/null +++ b/Lang/Mathematica/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Integer-overflow b/Lang/Mathematica/Integer-overflow new file mode 120000 index 0000000000..d612a98965 --- /dev/null +++ b/Lang/Mathematica/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Last-letter-first-letter b/Lang/Mathematica/Last-letter-first-letter new file mode 120000 index 0000000000..33daf02563 --- /dev/null +++ b/Lang/Mathematica/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Narcissist b/Lang/Mathematica/Narcissist new file mode 120000 index 0000000000..5a7f40aa6f --- /dev/null +++ b/Lang/Mathematica/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Narcissistic-decimal-number b/Lang/Mathematica/Narcissistic-decimal-number new file mode 120000 index 0000000000..001426697d --- /dev/null +++ b/Lang/Mathematica/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Old-lady-swallowed-a-fly b/Lang/Mathematica/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..3b08ec6086 --- /dev/null +++ b/Lang/Mathematica/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Order-disjoint-list-items b/Lang/Mathematica/Order-disjoint-list-items new file mode 120000 index 0000000000..2ac40b5890 --- /dev/null +++ b/Lang/Mathematica/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Parsing-RPN-calculator-algorithm b/Lang/Mathematica/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..90861269b3 --- /dev/null +++ b/Lang/Mathematica/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Parsing-Shunting-yard-algorithm b/Lang/Mathematica/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..4d79cc7d57 --- /dev/null +++ b/Lang/Mathematica/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Pinstripe-Display b/Lang/Mathematica/Pinstripe-Display new file mode 120000 index 0000000000..de3f06d4a6 --- /dev/null +++ b/Lang/Mathematica/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/RSA-code b/Lang/Mathematica/RSA-code new file mode 120000 index 0000000000..0b1c3cff64 --- /dev/null +++ b/Lang/Mathematica/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Respond-to-an-unknown-method-call b/Lang/Mathematica/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..91e8ceaedd --- /dev/null +++ b/Lang/Mathematica/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Runtime-evaluation b/Lang/Mathematica/Runtime-evaluation new file mode 120000 index 0000000000..e9872e3a9f --- /dev/null +++ b/Lang/Mathematica/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/SQL-based-authentication b/Lang/Mathematica/SQL-based-authentication new file mode 120000 index 0000000000..f1c7a4c907 --- /dev/null +++ b/Lang/Mathematica/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Solve-the-no-connection-puzzle b/Lang/Mathematica/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..bc8605dcd2 --- /dev/null +++ b/Lang/Mathematica/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Take-notes-on-the-command-line b/Lang/Mathematica/Take-notes-on-the-command-line new file mode 120000 index 0000000000..fb6f38a949 --- /dev/null +++ b/Lang/Mathematica/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Window-creation-X11 b/Lang/Mathematica/Window-creation-X11 new file mode 120000 index 0000000000..216e6dd2ef --- /dev/null +++ b/Lang/Mathematica/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Mathematica \ No newline at end of file diff --git a/Lang/Mercury/Delete-a-file b/Lang/Mercury/Delete-a-file new file mode 120000 index 0000000000..f3047d1fab --- /dev/null +++ b/Lang/Mercury/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Quaternion-type b/Lang/Mercury/Quaternion-type new file mode 120000 index 0000000000..34fd045795 --- /dev/null +++ b/Lang/Mercury/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Terminal-control-Unicode-output b/Lang/Mercury/Terminal-control-Unicode-output new file mode 120000 index 0000000000..0823e61f4f --- /dev/null +++ b/Lang/Mercury/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Tree-traversal b/Lang/Mercury/Tree-traversal new file mode 120000 index 0000000000..d473baf308 --- /dev/null +++ b/Lang/Mercury/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Zero-to-the-zero-power b/Lang/Mercury/Zero-to-the-zero-power new file mode 120000 index 0000000000..62bbf9b02b --- /dev/null +++ b/Lang/Mercury/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Mercury \ No newline at end of file diff --git a/Lang/Metafont/Inverted-syntax b/Lang/Metafont/Inverted-syntax new file mode 120000 index 0000000000..7aaab489f5 --- /dev/null +++ b/Lang/Metafont/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Metafont \ No newline at end of file diff --git a/Lang/Modula-3/Environment-variables b/Lang/Modula-3/Environment-variables new file mode 120000 index 0000000000..3fc6b5d3aa --- /dev/null +++ b/Lang/Modula-3/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Include-a-file b/Lang/Modula-3/Include-a-file new file mode 120000 index 0000000000..b17be9fadb --- /dev/null +++ b/Lang/Modula-3/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Singly-linked-list-Element-definition b/Lang/Modula-3/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..fd92eafd98 --- /dev/null +++ b/Lang/Modula-3/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Modula-3 \ No newline at end of file diff --git a/Lang/Modula-3/Singly-linked-list-Element-insertion b/Lang/Modula-3/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..16a3683e3e --- /dev/null +++ b/Lang/Modula-3/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Modula-3 \ No newline at end of file diff --git a/Lang/Moonscript/Y-combinator b/Lang/Moonscript/Y-combinator new file mode 120000 index 0000000000..a799475eb3 --- /dev/null +++ b/Lang/Moonscript/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Moonscript \ No newline at end of file diff --git a/Lang/Neko/00DESCRIPTION b/Lang/Neko/00DESCRIPTION index 68f4febe69..053221edf9 100644 --- a/Lang/Neko/00DESCRIPTION +++ b/Lang/Neko/00DESCRIPTION @@ -1,6 +1,6 @@ {{stub}} {{language -|exec=interpreted +|exec=bytecode |gc=yes |checking=dynamic |site=http://nekovm.org/ diff --git a/Lang/Neko/Copy-a-string b/Lang/Neko/Copy-a-string new file mode 120000 index 0000000000..4ad28247c6 --- /dev/null +++ b/Lang/Neko/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Neko \ No newline at end of file diff --git a/Lang/Neko/FizzBuzz b/Lang/Neko/FizzBuzz new file mode 120000 index 0000000000..16d07a90a3 --- /dev/null +++ b/Lang/Neko/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Neko \ No newline at end of file diff --git a/Lang/Neko/Inheritance-Single b/Lang/Neko/Inheritance-Single new file mode 120000 index 0000000000..c7ce9ebe9f --- /dev/null +++ b/Lang/Neko/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Neko \ No newline at end of file diff --git a/Lang/Nemerle/Ackermann-function b/Lang/Nemerle/Ackermann-function new file mode 120000 index 0000000000..ec0fe3db8b --- /dev/null +++ b/Lang/Nemerle/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Nemerle \ No newline at end of file diff --git a/Lang/NetRexx/Short-circuit-evaluation b/Lang/NetRexx/Short-circuit-evaluation new file mode 120000 index 0000000000..4ca45f1f24 --- /dev/null +++ b/Lang/NetRexx/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/NetRexx \ No newline at end of file diff --git a/Lang/NewLISP/Call-a-foreign-language-function b/Lang/NewLISP/Call-a-foreign-language-function new file mode 120000 index 0000000000..7a7d0fd30e --- /dev/null +++ b/Lang/NewLISP/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Empty-directory b/Lang/NewLISP/Empty-directory new file mode 120000 index 0000000000..cad807eef5 --- /dev/null +++ b/Lang/NewLISP/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/IBAN b/Lang/NewLISP/IBAN new file mode 120000 index 0000000000..726a23c208 --- /dev/null +++ b/Lang/NewLISP/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Integer-comparison b/Lang/NewLISP/Integer-comparison new file mode 120000 index 0000000000..9cda5c42e2 --- /dev/null +++ b/Lang/NewLISP/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Middle-three-digits b/Lang/NewLISP/Middle-three-digits new file mode 120000 index 0000000000..de9fad1110 --- /dev/null +++ b/Lang/NewLISP/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Palindrome-detection b/Lang/NewLISP/Palindrome-detection new file mode 120000 index 0000000000..d7abe3c957 --- /dev/null +++ b/Lang/NewLISP/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Pick-random-element b/Lang/NewLISP/Pick-random-element new file mode 120000 index 0000000000..4636692816 --- /dev/null +++ b/Lang/NewLISP/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Quine b/Lang/NewLISP/Quine new file mode 120000 index 0000000000..d6d2792dd9 --- /dev/null +++ b/Lang/NewLISP/Quine @@ -0,0 +1 @@ +../../Task/Quine/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Temperature-conversion b/Lang/NewLISP/Temperature-conversion new file mode 120000 index 0000000000..3dc43a9c3f --- /dev/null +++ b/Lang/NewLISP/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Terminal-control-Clear-the-screen b/Lang/NewLISP/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..d49772d3c3 --- /dev/null +++ b/Lang/NewLISP/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/NewLISP \ No newline at end of file diff --git a/Lang/OCaml/Modular-exponentiation b/Lang/OCaml/Modular-exponentiation new file mode 120000 index 0000000000..2d77962845 --- /dev/null +++ b/Lang/OCaml/Modular-exponentiation @@ -0,0 +1 @@ +../../Task/Modular-exponentiation/OCaml \ No newline at end of file diff --git a/Lang/Oberon-2/Amicable-pairs b/Lang/Oberon-2/Amicable-pairs new file mode 120000 index 0000000000..43ea0dbbad --- /dev/null +++ b/Lang/Oberon-2/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Day-of-the-week b/Lang/Oberon-2/Day-of-the-week new file mode 120000 index 0000000000..04e8686218 --- /dev/null +++ b/Lang/Oberon-2/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Oberon-2 \ No newline at end of file diff --git a/Lang/Objeck/00DESCRIPTION b/Lang/Objeck/00DESCRIPTION index b26ec9f064..6bed07cf68 100644 --- a/Lang/Objeck/00DESCRIPTION +++ b/Lang/Objeck/00DESCRIPTION @@ -9,8 +9,8 @@ |LCT=yes}} {{language programming paradigm|Object-oriented}}{{language programming paradigm|functional}} -The '''Objeck Programming Language''' is an [[object-oriented]] computing language with [[functional programming|functional]] features. The language has ties with [[C sharp|C#]], [[Scheme]] and indirectly [[Ruby]]. In this language all data types, except for higher-order functions, are treated as objects. The language contains all of the basic features of a general-purpose (Turing complete) programming language with an emphasis placed on OOP simplicity. +The '''Objeck Programming Language''' is an [[object-oriented]] computing language with [[functional programming|functional]] features. The language has ties with [[Java]] and [[Scheme]]. In this language all data types, except for higher-order functions, are treated as objects. -The programming environment consists of an optimizing compiler, virtual machine with associated [[Garbage collection|garbage collector]] and [[JIT]] compiler along with a command-line debugger. The compiler emits binary [[bytecode]] that is executed by the runtime system. The runtime system has the ability to translate the bytecode into AMD64 or IA-32 machine code on the fly. +The programming environment consists of an optimizing compiler, command-line debugger and virtual machine with associated [[Garbage collection|garbage collector]] and [[JIT]] compiler. The compiler emits binary [[bytecode]] that is executed by the runtime system. The runtime system has the ability to translate the bytecode into AMD64 or IA-32 executable machine code on the fly. For more information check out the [http://www.objeck.org/docs/objeck_lang.pdf Programmer's Guide] or this YouTube [https://www.youtube.com/watch?v=IUaQYdw02TU video]. The language can be [http://sourceforge.net/projects/objeck-lang/files/ obtained] from the main project homepage. Also, check out the IRC channel #objeck on freenode.net. \ No newline at end of file diff --git a/Lang/Objeck/ABC-Problem b/Lang/Objeck/ABC-Problem new file mode 120000 index 0000000000..3ebf42e555 --- /dev/null +++ b/Lang/Objeck/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Objeck \ No newline at end of file diff --git a/Lang/Objeck/AKS-test-for-primes b/Lang/Objeck/AKS-test-for-primes new file mode 120000 index 0000000000..75ddfc2bf3 --- /dev/null +++ b/Lang/Objeck/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Ackermann-function b/Lang/Objeck/Ackermann-function new file mode 120000 index 0000000000..8b788f9d95 --- /dev/null +++ b/Lang/Objeck/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Doubly-linked-list-Element-definition b/Lang/Objeck/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..70149d7344 --- /dev/null +++ b/Lang/Objeck/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Doubly-linked-list-Element-insertion b/Lang/Objeck/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..68150d7db1 --- /dev/null +++ b/Lang/Objeck/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Rep-string b/Lang/Objeck/Rep-string new file mode 120000 index 0000000000..6f3c60f6db --- /dev/null +++ b/Lang/Objeck/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Runge-Kutta-method b/Lang/Objeck/Runge-Kutta-method new file mode 120000 index 0000000000..dba1b0df45 --- /dev/null +++ b/Lang/Objeck/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Objeck \ No newline at end of file diff --git a/Lang/Objective-C/Constrained-genericity b/Lang/Objective-C/Constrained-genericity new file mode 120000 index 0000000000..e7952c5a41 --- /dev/null +++ b/Lang/Objective-C/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Parametric-polymorphism b/Lang/Objective-C/Parametric-polymorphism new file mode 120000 index 0000000000..094bb1526a --- /dev/null +++ b/Lang/Objective-C/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Objective-C \ No newline at end of file diff --git a/Lang/PARI-GP/00DESCRIPTION b/Lang/PARI-GP/00DESCRIPTION index 74f2bf636c..12cf8c2691 100644 --- a/Lang/PARI-GP/00DESCRIPTION +++ b/Lang/PARI-GP/00DESCRIPTION @@ -17,7 +17,7 @@ PARI/GP is a widely used computer algebra system designed for fast computations PARI/GP is composed of two parts: a [[C]] library called PARI and an interface, gp, to this library. GP scripts are concise, easy to write, and resemble mathematical language. (Terminology: the scripting language of gp is called GP.) -PARI was written by Henri Cohen and others at Université Bordeaux I and is now maintained by Karim Belabas. gp was originally written by Dominique Bernardi, then maintained and enhanced by Karim Belabas and Ilya Zakharevich, and finally rewritten by Bill Alombert. +PARI was written by Henri Cohen and others at Université Bordeaux I and is now maintained by Karim Belabas. gp was originally written by Dominique Bernardi, then maintained and enhanced by Karim Belabas and Ilya Zakharevich, and finally rewritten by Bill Allombert. == Using PARI/GP == PARI/GP can be downloaded at its official website's [http://pari.math.u-bordeaux.fr/download.html download page]. @@ -40,6 +40,7 @@ The most common way to use PARI is through the gp calculator, using its own scri * [http://go.helms-net.de/sw/paritty/pari_tty_einf_en.html Pari-tty] * [http://www.skalatan.de/pariguide/ pariGUIde] * [https://github.com/baruchel/vim-notebook vim-notebook] +* [https://github.com/jdemeyer/pari_jupyter Jupyter kernel] If you want to write a program rather than script a calculator, many languages are supported: * [[C]]: PARI is written in C, so it's very easy to either write your own programs or extend gp using C. diff --git a/Lang/PARI-GP/Abundant,-deficient-and-perfect-number-classifications b/Lang/PARI-GP/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..43bf8be3e0 --- /dev/null +++ b/Lang/PARI-GP/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Associative-array-Creation b/Lang/PARI-GP/Associative-array-Creation new file mode 120000 index 0000000000..e4589b373e --- /dev/null +++ b/Lang/PARI-GP/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Associative-array-Iteration b/Lang/PARI-GP/Associative-array-Iteration new file mode 120000 index 0000000000..8ad2d22c13 --- /dev/null +++ b/Lang/PARI-GP/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Day-of-the-week b/Lang/PARI-GP/Day-of-the-week new file mode 120000 index 0000000000..0f7eaaf8b8 --- /dev/null +++ b/Lang/PARI-GP/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Extensible-prime-generator b/Lang/PARI-GP/Extensible-prime-generator new file mode 120000 index 0000000000..5f6ebc30cf --- /dev/null +++ b/Lang/PARI-GP/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Heronian-triangles b/Lang/PARI-GP/Heronian-triangles new file mode 120000 index 0000000000..a3843a0455 --- /dev/null +++ b/Lang/PARI-GP/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Holidays-related-to-Easter b/Lang/PARI-GP/Holidays-related-to-Easter new file mode 120000 index 0000000000..ff6eb745f0 --- /dev/null +++ b/Lang/PARI-GP/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Hostname b/Lang/PARI-GP/Hostname new file mode 120000 index 0000000000..856c84600f --- /dev/null +++ b/Lang/PARI-GP/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Integer-overflow b/Lang/PARI-GP/Integer-overflow new file mode 120000 index 0000000000..a489df46f4 --- /dev/null +++ b/Lang/PARI-GP/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Sequence-of-primes-by-Trial-Division b/Lang/PARI-GP/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..cd737dc6ab --- /dev/null +++ b/Lang/PARI-GP/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/Balanced-brackets b/Lang/PHP/Balanced-brackets new file mode 120000 index 0000000000..1a378d5508 --- /dev/null +++ b/Lang/PHP/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/PHP \ No newline at end of file diff --git a/Lang/PHP/Convert-decimal-number-to-rational b/Lang/PHP/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..00a74ad4f1 --- /dev/null +++ b/Lang/PHP/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/PHP \ No newline at end of file diff --git a/Lang/PHP/IBAN b/Lang/PHP/IBAN new file mode 120000 index 0000000000..bb8daaea71 --- /dev/null +++ b/Lang/PHP/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/PHP \ No newline at end of file diff --git a/Lang/PHP/Josephus-problem b/Lang/PHP/Josephus-problem new file mode 120000 index 0000000000..1f83b2f536 --- /dev/null +++ b/Lang/PHP/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/PHP \ No newline at end of file diff --git a/Lang/PHP/Maze-generation b/Lang/PHP/Maze-generation new file mode 120000 index 0000000000..5e26d65e31 --- /dev/null +++ b/Lang/PHP/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/PHP \ No newline at end of file diff --git a/Lang/PHP/Modular-inverse b/Lang/PHP/Modular-inverse new file mode 120000 index 0000000000..815988643a --- /dev/null +++ b/Lang/PHP/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/PHP \ No newline at end of file diff --git a/Lang/PHP/Named-parameters b/Lang/PHP/Named-parameters new file mode 120000 index 0000000000..671981399e --- /dev/null +++ b/Lang/PHP/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/PHP \ No newline at end of file diff --git a/Lang/PHP/Number-reversal-game b/Lang/PHP/Number-reversal-game new file mode 120000 index 0000000000..7982107d97 --- /dev/null +++ b/Lang/PHP/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/PHP \ No newline at end of file diff --git a/Lang/PHP/Sequence-of-non-squares b/Lang/PHP/Sequence-of-non-squares new file mode 120000 index 0000000000..ef1df4eee6 --- /dev/null +++ b/Lang/PHP/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/PHP \ No newline at end of file diff --git a/Lang/PHP/Standard-deviation b/Lang/PHP/Standard-deviation new file mode 120000 index 0000000000..d3369f76f4 --- /dev/null +++ b/Lang/PHP/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/PHP \ No newline at end of file diff --git a/Lang/PHP/Ternary-logic b/Lang/PHP/Ternary-logic new file mode 120000 index 0000000000..92854a4724 --- /dev/null +++ b/Lang/PHP/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/PHP \ No newline at end of file diff --git a/Lang/PHP/Vigen-re-cipher b/Lang/PHP/Vigen-re-cipher new file mode 120000 index 0000000000..973ee0e5cf --- /dev/null +++ b/Lang/PHP/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/PHP \ No newline at end of file diff --git a/Lang/PL-I/AKS-test-for-primes b/Lang/PL-I/AKS-test-for-primes new file mode 120000 index 0000000000..9b8ddee912 --- /dev/null +++ b/Lang/PL-I/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Associative-array-Creation b/Lang/PL-I/Associative-array-Creation new file mode 120000 index 0000000000..04de3e36d7 --- /dev/null +++ b/Lang/PL-I/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Iterated-digits-squaring b/Lang/PL-I/Iterated-digits-squaring new file mode 120000 index 0000000000..96c4993a7f --- /dev/null +++ b/Lang/PL-I/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/PL-I \ No newline at end of file diff --git a/Lang/PL-I/LZW-compression b/Lang/PL-I/LZW-compression new file mode 120000 index 0000000000..286d987e10 --- /dev/null +++ b/Lang/PL-I/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Maximum-triangle-path-sum b/Lang/PL-I/Maximum-triangle-path-sum new file mode 120000 index 0000000000..977ea97940 --- /dev/null +++ b/Lang/PL-I/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Narcissistic-decimal-number b/Lang/PL-I/Narcissistic-decimal-number new file mode 120000 index 0000000000..8b469e2beb --- /dev/null +++ b/Lang/PL-I/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Pernicious-numbers b/Lang/PL-I/Pernicious-numbers new file mode 120000 index 0000000000..e89be6b946 --- /dev/null +++ b/Lang/PL-I/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Phrase-reversals b/Lang/PL-I/Phrase-reversals new file mode 120000 index 0000000000..e2aac5b1c6 --- /dev/null +++ b/Lang/PL-I/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Probabilistic-choice b/Lang/PL-I/Probabilistic-choice new file mode 120000 index 0000000000..124c9b867f --- /dev/null +++ b/Lang/PL-I/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Gnome-sort b/Lang/PL-I/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..795b3a7800 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/PL-I \ No newline at end of file diff --git a/Lang/PL-SQL/Ackermann-function b/Lang/PL-SQL/Ackermann-function new file mode 120000 index 0000000000..7d250331a8 --- /dev/null +++ b/Lang/PL-SQL/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/PL-SQL \ No newline at end of file diff --git a/Lang/PL-SQL/Ludic-numbers b/Lang/PL-SQL/Ludic-numbers new file mode 120000 index 0000000000..ddaeac8136 --- /dev/null +++ b/Lang/PL-SQL/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/PL-SQL \ No newline at end of file diff --git a/Lang/PL-SQL/Rot-13 b/Lang/PL-SQL/Rot-13 new file mode 120000 index 0000000000..054411aeee --- /dev/null +++ b/Lang/PL-SQL/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/PL-SQL \ No newline at end of file diff --git a/Lang/PL-pgSQL/Exceptions b/Lang/PL-pgSQL/Exceptions new file mode 120000 index 0000000000..4193fda165 --- /dev/null +++ b/Lang/PL-pgSQL/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/PL-pgSQL \ No newline at end of file diff --git a/Lang/Pascal/Averages-Simple-moving-average b/Lang/Pascal/Averages-Simple-moving-average new file mode 120000 index 0000000000..db6e3da318 --- /dev/null +++ b/Lang/Pascal/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Evolutionary-algorithm b/Lang/Pascal/Evolutionary-algorithm new file mode 120000 index 0000000000..f59c82a754 --- /dev/null +++ b/Lang/Pascal/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Langtons-ant b/Lang/Pascal/Langtons-ant new file mode 120000 index 0000000000..c79dc050e2 --- /dev/null +++ b/Lang/Pascal/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Long-multiplication b/Lang/Pascal/Long-multiplication new file mode 120000 index 0000000000..ea51cda12b --- /dev/null +++ b/Lang/Pascal/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Loops-Nested b/Lang/Pascal/Loops-Nested new file mode 120000 index 0000000000..bb7ef2ecbe --- /dev/null +++ b/Lang/Pascal/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Mad-Libs b/Lang/Pascal/Mad-Libs new file mode 120000 index 0000000000..ff0bddfed5 --- /dev/null +++ b/Lang/Pascal/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Modular-inverse b/Lang/Pascal/Modular-inverse new file mode 120000 index 0000000000..728fd2e999 --- /dev/null +++ b/Lang/Pascal/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Natural-sorting b/Lang/Pascal/Natural-sorting new file mode 120000 index 0000000000..99b57bf629 --- /dev/null +++ b/Lang/Pascal/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Pig-the-dice-game b/Lang/Pascal/Pig-the-dice-game new file mode 120000 index 0000000000..3dc22ecf37 --- /dev/null +++ b/Lang/Pascal/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sequence-of-primes-by-Trial-Division b/Lang/Pascal/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..e060241407 --- /dev/null +++ b/Lang/Pascal/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Temperature-conversion b/Lang/Pascal/Temperature-conversion new file mode 120000 index 0000000000..ef38be8043 --- /dev/null +++ b/Lang/Pascal/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Ulam-spiral--for-primes- b/Lang/Pascal/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..c49894200d --- /dev/null +++ b/Lang/Pascal/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Unix-ls b/Lang/Pascal/Unix-ls new file mode 120000 index 0000000000..7e59cc12a8 --- /dev/null +++ b/Lang/Pascal/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Write-language-name-in-3D-ASCII b/Lang/Pascal/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..0a5b318676 --- /dev/null +++ b/Lang/Pascal/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Zero-to-the-zero-power b/Lang/Pascal/Zero-to-the-zero-power new file mode 120000 index 0000000000..a2f0d4cf9d --- /dev/null +++ b/Lang/Pascal/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Pascal \ No newline at end of file diff --git a/Lang/Pentium-Assembly/00DESCRIPTION b/Lang/Pentium-Assembly/00DESCRIPTION index 95309450b0..d66474f514 100644 --- a/Lang/Pentium-Assembly/00DESCRIPTION +++ b/Lang/Pentium-Assembly/00DESCRIPTION @@ -1 +1,3 @@ -{{language}}{{assembler language}}{{stub}} \ No newline at end of file +{{language}}{{assembler language}}{{stub}} + +[[category: x86 Assembly]] \ No newline at end of file diff --git a/Lang/Perl-6/GUI-component-interaction b/Lang/Perl-6/GUI-component-interaction new file mode 120000 index 0000000000..34e494177d --- /dev/null +++ b/Lang/Perl-6/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Integer-overflow b/Lang/Perl-6/Integer-overflow new file mode 120000 index 0000000000..2415f13599 --- /dev/null +++ b/Lang/Perl-6/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Update-a-configuration-file b/Lang/Perl-6/Update-a-configuration-file new file mode 120000 index 0000000000..6bd979ad72 --- /dev/null +++ b/Lang/Perl-6/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/Break-OO-privacy b/Lang/Perl/Break-OO-privacy new file mode 120000 index 0000000000..a2458074a2 --- /dev/null +++ b/Lang/Perl/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Perl \ No newline at end of file diff --git a/Lang/Perl/Check-Machin-like-formulas b/Lang/Perl/Check-Machin-like-formulas new file mode 120000 index 0000000000..6849912c2c --- /dev/null +++ b/Lang/Perl/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/Perl \ No newline at end of file diff --git a/Lang/Perl/Haversine-formula b/Lang/Perl/Haversine-formula new file mode 120000 index 0000000000..e05da72155 --- /dev/null +++ b/Lang/Perl/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Perl \ No newline at end of file diff --git a/Lang/Perl/Magic-squares-of-odd-order b/Lang/Perl/Magic-squares-of-odd-order new file mode 120000 index 0000000000..dbd74dfd0c --- /dev/null +++ b/Lang/Perl/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Perl \ No newline at end of file diff --git a/Lang/Perl/Make-directory-path b/Lang/Perl/Make-directory-path new file mode 120000 index 0000000000..2417f96629 --- /dev/null +++ b/Lang/Perl/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Perl \ No newline at end of file diff --git a/Lang/Perl/Penneys-game b/Lang/Perl/Penneys-game new file mode 120000 index 0000000000..7db894760a --- /dev/null +++ b/Lang/Perl/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Perl \ No newline at end of file diff --git a/Lang/Perl/Polynomial-regression b/Lang/Perl/Polynomial-regression new file mode 120000 index 0000000000..f61d8f5564 --- /dev/null +++ b/Lang/Perl/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Perl \ No newline at end of file diff --git a/Lang/Perl/Sequence-of-primes-by-Trial-Division b/Lang/Perl/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..a58e7888f0 --- /dev/null +++ b/Lang/Perl/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Perl \ No newline at end of file diff --git a/Lang/PicoLisp/Abundant,-deficient-and-perfect-number-classifications b/Lang/PicoLisp/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..7ab2476c7b --- /dev/null +++ b/Lang/PicoLisp/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Amicable-pairs b/Lang/PicoLisp/Amicable-pairs new file mode 120000 index 0000000000..7ac0d48b70 --- /dev/null +++ b/Lang/PicoLisp/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Left-factorials b/Lang/PicoLisp/Left-factorials new file mode 120000 index 0000000000..5aa49a50e7 --- /dev/null +++ b/Lang/PicoLisp/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Longest-increasing-subsequence b/Lang/PicoLisp/Longest-increasing-subsequence new file mode 120000 index 0000000000..4b7d650c0e --- /dev/null +++ b/Lang/PicoLisp/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Maximum-triangle-path-sum b/Lang/PicoLisp/Maximum-triangle-path-sum new file mode 120000 index 0000000000..d9688e20d5 --- /dev/null +++ b/Lang/PicoLisp/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Reverse-words-in-a-string b/Lang/PicoLisp/Reverse-words-in-a-string new file mode 120000 index 0000000000..3328ac3e84 --- /dev/null +++ b/Lang/PicoLisp/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Zero-to-the-zero-power b/Lang/PicoLisp/Zero-to-the-zero-power new file mode 120000 index 0000000000..38ac735755 --- /dev/null +++ b/Lang/PicoLisp/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/PicoLisp \ No newline at end of file diff --git a/Lang/PostScript/00DESCRIPTION b/Lang/PostScript/00DESCRIPTION index 96287d2476..14f4460eb4 100644 --- a/Lang/PostScript/00DESCRIPTION +++ b/Lang/PostScript/00DESCRIPTION @@ -1,9 +1,11 @@ {{language|PostScript}} -'''PostScript''' is a concatenative dynamically typed language with abundant meta language facilites. It allows definition of new control structures at run time, allows reflection and reification of stack, scopes, and even continuations. With Display PostScript, the language even has facilities for multi-threaded execution. Since the language is based on stack, it is suitable for combinator based programming, and all the higher order combinators (initiated by joy language) is applicable in postscript. The language also allows a form of proto-type based object orientated programming using dictionaries. See {{libheader|initlib}} for implemention of higher order combinators. +'''PostScript''' is a concatenative dynamically typed language with abundant meta language facilities. It allows definition of new control structures at run time, allows reflection and reification of stack, scopes, and even continuations. With Display PostScript, the language even has facilities for multi-threaded execution. Since the language is based on stack, it is suitable for combinator based programming, and all the higher order combinators (initiated by joy language) is applicable in postscript. The language also allows a form of prototype based object orientated programming using dictionaries. See {{libheader|initlib}} for implementation of higher order combinators. -'''PostScript''' originated as a printer definition language invented by the founders of '''Adobe'''. The language was necessitated by the increasing demands of printing and rendering jobs on the computers of the 70s. These tasks were therefore pushed to the printers themselves, with the result that printers now had chips and built in interpreters for PostScript. With the growth of printing complexity, some printers ended up having even more powerful processors than the master systems themselves. +'''PostScript''' originated as a printer definition language invented by the founders of '''Adobe'''. The language was necessitated by the increasing demands of printing and rendering jobs on the computers of the 1970s. These tasks were therefore pushed to the printers themselves, with the result that printers now had chips and built in interpreters for PostScript. With the growth of printing complexity, some printers ended up having even more powerful processors than the master systems themselves. -Although now almost displaced by the '''Portable Document Format''' (PDF), also developed by Adobe, PostScript's USP lies in it's being a '''Turing complete''' language with support for the basic data types and fundamental structures and concepts of Computer Science. Many interpreters and viewers of PostScript are available, some even for free. Although primarily a language suited for 2D graphics, PostScript is complete as a language and able to hadle normal computation tasks. +Although now almost displaced by the '''Portable Document Format''' (PDF), also developed by Adobe, PostScript's USP lies in it's being a '''Turing complete''' language with support for the basic data types and fundamental structures and concepts of Computer Science. Many interpreters and viewers of PostScript are available, some even for free. Although primarily a language suited for 2D graphics, PostScript is complete as a language and able to handle normal computation tasks. + +''(does "USP" mean "unique selling proposition"?)'' ==See Also== *[http://logand.com/sw/wps/index.html WPS - PostScript interpreter written in JavaScript.] diff --git a/Lang/PowerShell/ABC-Problem b/Lang/PowerShell/ABC-Problem new file mode 120000 index 0000000000..7246edf5d4 --- /dev/null +++ b/Lang/PowerShell/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Abundant,-deficient-and-perfect-number-classifications b/Lang/PowerShell/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..1393a0c734 --- /dev/null +++ b/Lang/PowerShell/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Arithmetic-geometric-mean b/Lang/PowerShell/Arithmetic-geometric-mean new file mode 120000 index 0000000000..a868d13c6b --- /dev/null +++ b/Lang/PowerShell/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Compile-time-calculation b/Lang/PowerShell/Compile-time-calculation new file mode 120000 index 0000000000..69fac6a548 --- /dev/null +++ b/Lang/PowerShell/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Count-in-factors b/Lang/PowerShell/Count-in-factors new file mode 120000 index 0000000000..fdabc302d2 --- /dev/null +++ b/Lang/PowerShell/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Count-occurrences-of-a-substring b/Lang/PowerShell/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..2291888677 --- /dev/null +++ b/Lang/PowerShell/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Detect-division-by-zero b/Lang/PowerShell/Detect-division-by-zero new file mode 120000 index 0000000000..9d05b49a42 --- /dev/null +++ b/Lang/PowerShell/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Dot-product b/Lang/PowerShell/Dot-product new file mode 120000 index 0000000000..ed80b663a1 --- /dev/null +++ b/Lang/PowerShell/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Empty-directory b/Lang/PowerShell/Empty-directory new file mode 120000 index 0000000000..8449959fed --- /dev/null +++ b/Lang/PowerShell/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Empty-string b/Lang/PowerShell/Empty-string new file mode 120000 index 0000000000..0e7730de2c --- /dev/null +++ b/Lang/PowerShell/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Entropy b/Lang/PowerShell/Entropy new file mode 120000 index 0000000000..9b63f371f4 --- /dev/null +++ b/Lang/PowerShell/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Equilibrium-index b/Lang/PowerShell/Equilibrium-index new file mode 120000 index 0000000000..a8448ee3b5 --- /dev/null +++ b/Lang/PowerShell/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Euler-method b/Lang/PowerShell/Euler-method new file mode 120000 index 0000000000..fc924bfd60 --- /dev/null +++ b/Lang/PowerShell/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Evaluate-binomial-coefficients b/Lang/PowerShell/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..07b93758a2 --- /dev/null +++ b/Lang/PowerShell/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Even-or-odd b/Lang/PowerShell/Even-or-odd new file mode 120000 index 0000000000..384ef195d5 --- /dev/null +++ b/Lang/PowerShell/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Find-the-missing-permutation b/Lang/PowerShell/Find-the-missing-permutation new file mode 120000 index 0000000000..067f08b3e4 --- /dev/null +++ b/Lang/PowerShell/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Five-weekends b/Lang/PowerShell/Five-weekends new file mode 120000 index 0000000000..156f901da8 --- /dev/null +++ b/Lang/PowerShell/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Flatten-a-list b/Lang/PowerShell/Flatten-a-list new file mode 120000 index 0000000000..a71270fdfa --- /dev/null +++ b/Lang/PowerShell/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Function-composition b/Lang/PowerShell/Function-composition new file mode 120000 index 0000000000..39b97597e2 --- /dev/null +++ b/Lang/PowerShell/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Handle-a-signal b/Lang/PowerShell/Handle-a-signal new file mode 120000 index 0000000000..70051f044e --- /dev/null +++ b/Lang/PowerShell/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Hello-world-Newbie b/Lang/PowerShell/Hello-world-Newbie new file mode 120000 index 0000000000..1f1a59f6b0 --- /dev/null +++ b/Lang/PowerShell/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Hello-world-Newline-omission b/Lang/PowerShell/Hello-world-Newline-omission new file mode 120000 index 0000000000..b06e3602ce --- /dev/null +++ b/Lang/PowerShell/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Higher-order-functions b/Lang/PowerShell/Higher-order-functions new file mode 120000 index 0000000000..86009ea722 --- /dev/null +++ b/Lang/PowerShell/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Horners-rule-for-polynomial-evaluation b/Lang/PowerShell/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..36b100f8f8 --- /dev/null +++ b/Lang/PowerShell/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Identity-matrix b/Lang/PowerShell/Identity-matrix new file mode 120000 index 0000000000..319134d258 --- /dev/null +++ b/Lang/PowerShell/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Josephus-problem b/Lang/PowerShell/Josephus-problem new file mode 120000 index 0000000000..3657b08ee7 --- /dev/null +++ b/Lang/PowerShell/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Least-common-multiple b/Lang/PowerShell/Least-common-multiple new file mode 120000 index 0000000000..ee0ad30450 --- /dev/null +++ b/Lang/PowerShell/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Left-factorials b/Lang/PowerShell/Left-factorials new file mode 120000 index 0000000000..531aa97fa0 --- /dev/null +++ b/Lang/PowerShell/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Linear-congruential-generator b/Lang/PowerShell/Linear-congruential-generator new file mode 120000 index 0000000000..c2a8d433d6 --- /dev/null +++ b/Lang/PowerShell/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Matrix-arithmetic b/Lang/PowerShell/Matrix-arithmetic new file mode 120000 index 0000000000..85c469b55e --- /dev/null +++ b/Lang/PowerShell/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Matrix-multiplication b/Lang/PowerShell/Matrix-multiplication new file mode 120000 index 0000000000..457df4d76e --- /dev/null +++ b/Lang/PowerShell/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Matrix-transposition b/Lang/PowerShell/Matrix-transposition new file mode 120000 index 0000000000..9284bd3bf1 --- /dev/null +++ b/Lang/PowerShell/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Middle-three-digits b/Lang/PowerShell/Middle-three-digits new file mode 120000 index 0000000000..6875f8f7af --- /dev/null +++ b/Lang/PowerShell/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Modular-inverse b/Lang/PowerShell/Modular-inverse new file mode 120000 index 0000000000..11e1e02d44 --- /dev/null +++ b/Lang/PowerShell/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Move-to-front-algorithm b/Lang/PowerShell/Move-to-front-algorithm new file mode 120000 index 0000000000..bb8893db19 --- /dev/null +++ b/Lang/PowerShell/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Nth b/Lang/PowerShell/Nth new file mode 120000 index 0000000000..14a3e11c86 --- /dev/null +++ b/Lang/PowerShell/Nth @@ -0,0 +1 @@ +../../Task/Nth/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Nth-root b/Lang/PowerShell/Nth-root new file mode 120000 index 0000000000..e4fb2ad34a --- /dev/null +++ b/Lang/PowerShell/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Old-lady-swallowed-a-fly b/Lang/PowerShell/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..285eed1969 --- /dev/null +++ b/Lang/PowerShell/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Order-disjoint-list-items b/Lang/PowerShell/Order-disjoint-list-items new file mode 120000 index 0000000000..26fd4279a5 --- /dev/null +++ b/Lang/PowerShell/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Permutations b/Lang/PowerShell/Permutations new file mode 120000 index 0000000000..381ddcab6c --- /dev/null +++ b/Lang/PowerShell/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Permutations-by-swapping b/Lang/PowerShell/Permutations-by-swapping new file mode 120000 index 0000000000..a0d869ca11 --- /dev/null +++ b/Lang/PowerShell/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Phrase-reversals b/Lang/PowerShell/Phrase-reversals new file mode 120000 index 0000000000..f5146d8346 --- /dev/null +++ b/Lang/PowerShell/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Power-set b/Lang/PowerShell/Power-set new file mode 120000 index 0000000000..dbd9271579 --- /dev/null +++ b/Lang/PowerShell/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Prime-decomposition b/Lang/PowerShell/Prime-decomposition new file mode 120000 index 0000000000..5b99ec8e6b --- /dev/null +++ b/Lang/PowerShell/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Program-name b/Lang/PowerShell/Program-name new file mode 120000 index 0000000000..9de3488c42 --- /dev/null +++ b/Lang/PowerShell/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Pythagorean-triples b/Lang/PowerShell/Pythagorean-triples new file mode 120000 index 0000000000..f8138dc0ab --- /dev/null +++ b/Lang/PowerShell/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Queue-Usage b/Lang/PowerShell/Queue-Usage new file mode 120000 index 0000000000..c339a14d81 --- /dev/null +++ b/Lang/PowerShell/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Range-expansion b/Lang/PowerShell/Range-expansion new file mode 120000 index 0000000000..795ccc963c --- /dev/null +++ b/Lang/PowerShell/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Range-extraction b/Lang/PowerShell/Range-extraction new file mode 120000 index 0000000000..43eeb059c6 --- /dev/null +++ b/Lang/PowerShell/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Remove-lines-from-a-file b/Lang/PowerShell/Remove-lines-from-a-file new file mode 120000 index 0000000000..e0fb054980 --- /dev/null +++ b/Lang/PowerShell/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Return-multiple-values b/Lang/PowerShell/Return-multiple-values new file mode 120000 index 0000000000..30e26640f9 --- /dev/null +++ b/Lang/PowerShell/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Reverse-words-in-a-string b/Lang/PowerShell/Reverse-words-in-a-string new file mode 120000 index 0000000000..0b14f5bf49 --- /dev/null +++ b/Lang/PowerShell/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Roman-numerals-Decode b/Lang/PowerShell/Roman-numerals-Decode new file mode 120000 index 0000000000..e7991e918a --- /dev/null +++ b/Lang/PowerShell/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Roman-numerals-Encode b/Lang/PowerShell/Roman-numerals-Encode new file mode 120000 index 0000000000..76046c6260 --- /dev/null +++ b/Lang/PowerShell/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Runge-Kutta-method b/Lang/PowerShell/Runge-Kutta-method new file mode 120000 index 0000000000..258d4642a2 --- /dev/null +++ b/Lang/PowerShell/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Search-a-list b/Lang/PowerShell/Search-a-list new file mode 120000 index 0000000000..671cad2466 --- /dev/null +++ b/Lang/PowerShell/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sequence-of-primes-by-Trial-Division b/Lang/PowerShell/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..c55fd5e874 --- /dev/null +++ b/Lang/PowerShell/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sort-an-array-of-composite-structures b/Lang/PowerShell/Sort-an-array-of-composite-structures new file mode 120000 index 0000000000..72f18fc5f4 --- /dev/null +++ b/Lang/PowerShell/Sort-an-array-of-composite-structures @@ -0,0 +1 @@ +../../Task/Sort-an-array-of-composite-structures/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sort-disjoint-sublist b/Lang/PowerShell/Sort-disjoint-sublist new file mode 120000 index 0000000000..4af85d51a5 --- /dev/null +++ b/Lang/PowerShell/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Gnome-sort b/Lang/PowerShell/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..5b6525afa1 --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Heapsort b/Lang/PowerShell/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..affea1bd0b --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Sorting-algorithms-Insertion-sort b/Lang/PowerShell/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..1db1c19d9d --- /dev/null +++ b/Lang/PowerShell/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/String-append b/Lang/PowerShell/String-append new file mode 120000 index 0000000000..78dce38d7f --- /dev/null +++ b/Lang/PowerShell/String-append @@ -0,0 +1 @@ +../../Task/String-append/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/String-comparison b/Lang/PowerShell/String-comparison new file mode 120000 index 0000000000..2f2b7b0372 --- /dev/null +++ b/Lang/PowerShell/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/String-prepend b/Lang/PowerShell/String-prepend new file mode 120000 index 0000000000..4f33b8590d --- /dev/null +++ b/Lang/PowerShell/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Strip-whitespace-from-a-string-Top-and-tail b/Lang/PowerShell/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..4daa9f10b5 --- /dev/null +++ b/Lang/PowerShell/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Substring-Top-and-tail b/Lang/PowerShell/Substring-Top-and-tail new file mode 120000 index 0000000000..b9cabcb73f --- /dev/null +++ b/Lang/PowerShell/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Temperature-conversion b/Lang/PowerShell/Temperature-conversion new file mode 120000 index 0000000000..dd1ba34cf9 --- /dev/null +++ b/Lang/PowerShell/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Time-a-function b/Lang/PowerShell/Time-a-function new file mode 120000 index 0000000000..8f6cef77ba --- /dev/null +++ b/Lang/PowerShell/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Towers-of-Hanoi b/Lang/PowerShell/Towers-of-Hanoi new file mode 120000 index 0000000000..f6fc7bc70b --- /dev/null +++ b/Lang/PowerShell/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Vector-products b/Lang/PowerShell/Vector-products new file mode 120000 index 0000000000..a4cb2cafce --- /dev/null +++ b/Lang/PowerShell/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Word-wrap b/Lang/PowerShell/Word-wrap new file mode 120000 index 0000000000..bc15166e8c --- /dev/null +++ b/Lang/PowerShell/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/PowerShell \ No newline at end of file diff --git a/Lang/Prolog/Amicable-pairs b/Lang/Prolog/Amicable-pairs new file mode 120000 index 0000000000..48cc6c2bd7 --- /dev/null +++ b/Lang/Prolog/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Conditional-structures b/Lang/Prolog/Conditional-structures new file mode 120000 index 0000000000..058d146b14 --- /dev/null +++ b/Lang/Prolog/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Entropy b/Lang/Prolog/Entropy new file mode 120000 index 0000000000..70f41a2d61 --- /dev/null +++ b/Lang/Prolog/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Literals-String b/Lang/Prolog/Literals-String new file mode 120000 index 0000000000..4c0510d4c9 --- /dev/null +++ b/Lang/Prolog/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Sockets b/Lang/Prolog/Sockets new file mode 120000 index 0000000000..18f2977b8f --- /dev/null +++ b/Lang/Prolog/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Prolog \ No newline at end of file diff --git a/Lang/Pure-Data/Ackermann-function b/Lang/Pure-Data/Ackermann-function new file mode 120000 index 0000000000..737379be2a --- /dev/null +++ b/Lang/Pure-Data/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Pure-Data \ No newline at end of file diff --git a/Lang/Pure-Data/Draw-a-cuboid b/Lang/Pure-Data/Draw-a-cuboid new file mode 120000 index 0000000000..dedc6d0398 --- /dev/null +++ b/Lang/Pure-Data/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Pure-Data \ No newline at end of file diff --git a/Lang/Pure-Data/Loops-Infinite b/Lang/Pure-Data/Loops-Infinite new file mode 120000 index 0000000000..6135f2d300 --- /dev/null +++ b/Lang/Pure-Data/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Pure-Data \ No newline at end of file diff --git a/Lang/PureBasic/9-billion-names-of-God-the-integer b/Lang/PureBasic/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..3105c8ebe9 --- /dev/null +++ b/Lang/PureBasic/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/ABC-Problem b/Lang/PureBasic/ABC-Problem new file mode 120000 index 0000000000..1df9b09af2 --- /dev/null +++ b/Lang/PureBasic/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/AKS-test-for-primes b/Lang/PureBasic/AKS-test-for-primes new file mode 120000 index 0000000000..c518924349 --- /dev/null +++ b/Lang/PureBasic/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Convert-decimal-number-to-rational b/Lang/PureBasic/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..cc13796f20 --- /dev/null +++ b/Lang/PureBasic/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Entropy b/Lang/PureBasic/Entropy new file mode 120000 index 0000000000..0d1ad5786e --- /dev/null +++ b/Lang/PureBasic/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Fibonacci-word b/Lang/PureBasic/Fibonacci-word new file mode 120000 index 0000000000..48b828cc87 --- /dev/null +++ b/Lang/PureBasic/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/I-before-E-except-after-C b/Lang/PureBasic/I-before-E-except-after-C new file mode 120000 index 0000000000..0296934e14 --- /dev/null +++ b/Lang/PureBasic/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/IBAN b/Lang/PureBasic/IBAN new file mode 120000 index 0000000000..58f54ce59a --- /dev/null +++ b/Lang/PureBasic/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Integer-overflow b/Lang/PureBasic/Integer-overflow new file mode 120000 index 0000000000..765f5798f4 --- /dev/null +++ b/Lang/PureBasic/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Iterated-digits-squaring b/Lang/PureBasic/Iterated-digits-squaring new file mode 120000 index 0000000000..b6395a4f1c --- /dev/null +++ b/Lang/PureBasic/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/JSON b/Lang/PureBasic/JSON new file mode 120000 index 0000000000..fecdb66d5e --- /dev/null +++ b/Lang/PureBasic/JSON @@ -0,0 +1 @@ +../../Task/JSON/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Josephus-problem b/Lang/PureBasic/Josephus-problem new file mode 120000 index 0000000000..3b5ba00808 --- /dev/null +++ b/Lang/PureBasic/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Jump-anywhere b/Lang/PureBasic/Jump-anywhere new file mode 120000 index 0000000000..81d457d8fe --- /dev/null +++ b/Lang/PureBasic/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Rep-string b/Lang/PureBasic/Rep-string new file mode 120000 index 0000000000..f2602f6551 --- /dev/null +++ b/Lang/PureBasic/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Reverse-words-in-a-string b/Lang/PureBasic/Reverse-words-in-a-string new file mode 120000 index 0000000000..dd7a913ee4 --- /dev/null +++ b/Lang/PureBasic/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Temperature-conversion b/Lang/PureBasic/Temperature-conversion new file mode 120000 index 0000000000..c034c465e3 --- /dev/null +++ b/Lang/PureBasic/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Word-wrap b/Lang/PureBasic/Word-wrap new file mode 120000 index 0000000000..850929a8ae --- /dev/null +++ b/Lang/PureBasic/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Write-language-name-in-3D-ASCII b/Lang/PureBasic/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..c884865057 --- /dev/null +++ b/Lang/PureBasic/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/PureBasic \ No newline at end of file diff --git a/Lang/Python/Bitcoin-public-point-to-address b/Lang/Python/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..92b287f7de --- /dev/null +++ b/Lang/Python/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Python \ No newline at end of file diff --git a/Lang/Python/Execute-SNUSP b/Lang/Python/Execute-SNUSP new file mode 120000 index 0000000000..27987f73c3 --- /dev/null +++ b/Lang/Python/Execute-SNUSP @@ -0,0 +1 @@ +../../Task/Execute-SNUSP/Python \ No newline at end of file diff --git a/Lang/Python/Metronome b/Lang/Python/Metronome new file mode 120000 index 0000000000..d935f78afd --- /dev/null +++ b/Lang/Python/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Python \ No newline at end of file diff --git a/Lang/Python/QR-decomposition b/Lang/Python/QR-decomposition new file mode 120000 index 0000000000..9195383c82 --- /dev/null +++ b/Lang/Python/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Python \ No newline at end of file diff --git a/Lang/Python/Sequence-of-primes-by-Trial-Division b/Lang/Python/Sequence-of-primes-by-Trial-Division new file mode 120000 index 0000000000..d4211e67e9 --- /dev/null +++ b/Lang/Python/Sequence-of-primes-by-Trial-Division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-Trial-Division/Python \ No newline at end of file diff --git a/Lang/Python/Thieles-interpolation-formula b/Lang/Python/Thieles-interpolation-formula new file mode 120000 index 0000000000..a47769f90d --- /dev/null +++ b/Lang/Python/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Python \ No newline at end of file diff --git a/Lang/Q/FizzBuzz b/Lang/Q/FizzBuzz new file mode 120000 index 0000000000..89d8433731 --- /dev/null +++ b/Lang/Q/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Q \ No newline at end of file diff --git a/Lang/Q/Greatest-element-of-a-list b/Lang/Q/Greatest-element-of-a-list new file mode 120000 index 0000000000..2c5fd8beca --- /dev/null +++ b/Lang/Q/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Q \ No newline at end of file diff --git a/Lang/Q/Higher-order-functions b/Lang/Q/Higher-order-functions new file mode 120000 index 0000000000..d6dd03deb0 --- /dev/null +++ b/Lang/Q/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Q \ No newline at end of file diff --git a/Lang/Q/Read-entire-file b/Lang/Q/Read-entire-file new file mode 120000 index 0000000000..28b05f82e7 --- /dev/null +++ b/Lang/Q/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Q \ No newline at end of file diff --git a/Lang/Q/Tokenize-a-string b/Lang/Q/Tokenize-a-string new file mode 120000 index 0000000000..09eefc1346 --- /dev/null +++ b/Lang/Q/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Q \ No newline at end of file diff --git a/Lang/R/Caesar-cipher b/Lang/R/Caesar-cipher new file mode 120000 index 0000000000..093a4d4941 --- /dev/null +++ b/Lang/R/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/R \ No newline at end of file diff --git a/Lang/R/Generate-lower-case-ASCII-alphabet b/Lang/R/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..c7c8f8d88b --- /dev/null +++ b/Lang/R/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/R \ No newline at end of file diff --git a/Lang/R/Guess-the-number-With-feedback b/Lang/R/Guess-the-number-With-feedback new file mode 120000 index 0000000000..e11d66d7ec --- /dev/null +++ b/Lang/R/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/R \ No newline at end of file diff --git a/Lang/R/Heronian-triangles b/Lang/R/Heronian-triangles new file mode 120000 index 0000000000..bc1b477ac8 --- /dev/null +++ b/Lang/R/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/R \ No newline at end of file diff --git a/Lang/R/Runge-Kutta-method b/Lang/R/Runge-Kutta-method new file mode 120000 index 0000000000..9fcf7417a5 --- /dev/null +++ b/Lang/R/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/R \ No newline at end of file diff --git a/Lang/REBOL/Anonymous-recursion b/Lang/REBOL/Anonymous-recursion new file mode 120000 index 0000000000..5c9e13cbb0 --- /dev/null +++ b/Lang/REBOL/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/REBOL \ No newline at end of file diff --git a/Lang/REXX/00DESCRIPTION b/Lang/REXX/00DESCRIPTION index 26aa4ce196..7c96a0776a 100644 --- a/Lang/REXX/00DESCRIPTION +++ b/Lang/REXX/00DESCRIPTION @@ -8,23 +8,25 @@ |checking=dynamic |parampass=value}} {{Wikipedia|REXX}} -REXX (REstructured eXtended eXecutor) is an interpreted programming language which was developed at IBM. It is a structured high-level programming language which was designed to be both easy to learn and easy to read. Both proprietary and open source interpreters for REXX are available on a wide range of computing platforms, and compilers are available for IBM mainframes. +REXX (REstructured eXtended eXecutor) is an interpreted programming language which was developed at IBM.   It is a structured high-level programming language which was designed to be both easy to learn and easy to read.   Both proprietary and open source interpreters for REXX are available on a wide range of computing platforms, and compilers are available for IBM mainframes. -* '''[[wp:AREXX|AREXX]]''' is a classic REXX implementation (with extensions) for the AmigaOS, given in bundle since AmigaOS 2. (Regina REXX has specific support for the extended functions that were introduced in AREXX.) ARexx was written in 1987 by William S. Hawes. +* '''[[wp:ARexx|ARexx]]''' is a classic REXX implementation (with extensions) for the AmigaOS, given in bundle since AmigaOS 2.   (Regina REXX has specific support for the extended functions that were introduced in ARexx.)   ARexx was written in 1987 by William S. Hawes. * '''[[Brexx]]''' a classic REXX written by Vassilis N. Vlachoudis, it is free and it's open source and available under the GNU General Public License. * '''[[CRX REXX]]''' (Compact REXX) is a classic REXX first written by Dr. Brian Marks. -* '''[[CTC REXX]]''' is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation, a license is required to use this product. This version of REXX can only be used under PC/SPF and it's panels. +* '''[[CTC REXX]]''' is a classic REXX that is bundled with PC/SPF and written by Command Technology Corporation, a license is required to use this product.   This version of REXX can only be used under PC/SPF and it's panels.   PC/SPF resembles the IBM program product SPF (which has other names and versions). -* '''[[KEXX]]''' is a subset of REXX that is bundled with KEDIT and written by Mansfield Software Group, Inc., a license is required to use this product. KEXX only executes under the KEDIT licensed product. +* '''[[KEXX]]''' is a subset of REXX that is bundled with KEDIT and written by Mansfield Software Group, Inc., a license is required to use this product.   KEXX only executes under the KEDIT licensed product.   KEDIT is an XEDIT clone (an editor from IBM for VM/CMS program products). -* '''[[MVS/TSO REXX]]''' is IBM's implementation of classic REXX, a license is required to use the operating system, '''MVS''' and '''TSO''' are used here as generic references. +* '''[[MVS/TSO REXX]]''' is IBM's implementation of classic REXX, a license is required to use the product as well as the operating system it runs under;   '''MVS''' and '''TSO''' are used here as generic references. * '''[[MVS/TSO REXX compiler]]''' is an IBM implementation of classic REXX, a license is required to use this product as well as the operating system it runs under. -* '''[[NetRexx|NetRexx]]''' is IBM's variant of the REXX programming language to run on the Java virtual machine. It supports a classic REXX syntax, with no reserved keywords, along with considerable additions to support Object-oriented programming in a manner compatible with Java's object model, yet can be used as both a compiled and an interpreted language, with an option of using only data types native to the JVM or the NetRexx runtime package. The syntax and object model of NetRexx differ from Object REXX. +* '''[[NetRexx|NetRexx]]''' is IBM's variant of the REXX programming language to run on the Java virtual machine.   It supports a classic REXX syntax, with no reserved keywords, along with considerable additions to support Object-oriented programming in a manner compatible with Java's object model, yet can be used as both a compiled and an interpreted language, with an option of using only data types native to the JVM or the NetRexx run-time package.   The syntax and object model of NetRexx differ from Object REXX. + +* '''[https://en.wikipedia.org/wiki/Object_REXX Object REXX]''' is/was an object-oriented scripting language initially produced by IBM for OS/2.   It is a follow-on to and a significant extension of the "Classic Rexx" language originally created for the CMS component of VM/SP and later ported to MVS, OS/2 and PC DOS.   OS/2 version of IBM Object REXX is deeply integrated with SOM.   On October 12, 2004, IBM released Object REXX as open source software, giving rise to Open Object Rexx (ooREXX). * '''[[ooRexx|ooRexx]]''' (Open Object Rexx) is an implementation of [[wp:Object REXX|Object REXX]], which is REXX with OO features (some REXX programs are compatible). @@ -32,27 +34,29 @@ * '''[[OS/400 REXX]]''' is an IBM implementation of classic REXX, a license is required to use this product as well as the operating system it runs under. -* '''[[PC/REXX]]''' is the first classic REXX implented outside of IBM mainframes, intended for IBM DOS and MS DOS. Written by Mansfield Software Group, Inc., REXX was bundled with KEDIT, a license is required to use this product. +* '''[[PC/REXX]]''' is the first classic REXX implemented outside of IBM mainframes, intended for IBM DOS and MS DOS.   Written by Mansfield Software Group, Inc., REXX was bundled with KEDIT, a license is required to use this product. * '''[[Personal REXX]]''' is a classic REXX that is intended for IBM DOS and MS DOS, written by a Quercus Systems, a license is required to use this product. -* '''[[Regina REXX]]''' is an implementation first created by Anders Christensen and now maintained by others, notably Mark Hessling. Regina REXX runs on more different platforms than any other REXX, too many to name here. +* '''Portable REXX'''   (see the   '''R4 REXX'''   entry, below). + +* '''[[Regina REXX]]''' is an implementation first created by Anders Christensen (in 1992) and now maintained by others, notably Mark Hessling.   Regina REXX runs on more different platforms than any other REXX, too many to name here.   It can be downloaded freely. -* '''[[Reginald REXX]]''' is a REXX developed by Jeff Glatt. It can be downloaded freely. +* '''[[Reginald REXX]]''' is a REXX developed by Jeff Glatt.   It can be downloaded freely. * '''[[REXX/imc]]''' a classic REXX developed by Ian M. Collier (imc) for Linux/Unix. -* '''[[ROO oo-REXX]]''' an object-oriented REXX delveloped by Keith Watts of Kilowatt Software, Inc. It can be downloaded freely. '''ROO''' is also known as '''ROO!'''. +* '''[[ROO oo-REXX]]''' an object-oriented REXX developed by Keith Watts of Kilowatt Software, Inc.     It can be downloaded freely.   '''ROO''' is also known as '''ROO!'''. -* '''[[R4 REXX]]''' a classic REXX developed by Keith Watts of Kilowatt Software, Inc. It was also known as Portable REXX. It can be downloaded freely. +* '''[[R4 REXX]]''' a classic REXX developed by Keith Watts of Kilowatt Software, Inc.     It was also known as '''Portable REXX'''.   It can be downloaded freely. -* '''[["T/REXX, a REXX compiler for CMS]]''' is an implementation of classic REXX written by Lundin and Woodruff (according to Wikipedia). +* '''[[T/REXX, a REXX compiler for CMS]]''' is an implementation of classic REXX written by Lundin and Woodruff (according to Wikipedia). -* '''[[VM/CMS REXX]]''' is an IBM implementation of classic REXX that was first implemented in the early 1980s. A license is required to use this product as well as the operating system that it runs under. This was the original implementation of REXX written by Mike Cowlishaw of IBM (circa 1979). +* '''[[VM/CMS REXX]]''' is an IBM implementation of classic REXX that was first implemented in the early 1980s.   A license is required to use this product as well as the operating system that it runs under.   This was the original implementation of REXX written (circa 1979) by Mike Cowlishaw of IBM. * '''[[VM/CMS REXX compiler]]''' is an IBM implementation of classic REXX, a license is required to use this product as well as the operating system it runs under. -
[Most of the entries were entered mostly from memory and apologies are offered for not knowing more about what wording should be used; the IBM operating systems or Program Products that run REXX are numerous and varied. Their complete (official) names would fill a pagefull. Some of the REXXes are no longer sold nor available for downloading or purchase, others are no longer maintained. Naming of names is being avoided (especially those licensed products for sale), and it is hoped that this is seen that no products nor vendors are being endorsed, appraised, or critiqued.] -- [[User:Gerard Schildberger|Gerard Schildberger]] 09:28, 1 July 2012 (UTC) +
[Most of the entries were entered mostly from memory and apologies are offered for not knowing more about what wording should be used; the IBM operating systems or Program Products that run REXX are numerous and varied.   Their complete (official) names would fill a pageful.   Some of the REXXes are no longer sold nor available for downloading or purchase, others are no longer maintained.   Naming of names is being avoided (especially those licensed products for sale), and it is hoped that this is seen that no products nor vendors are being endorsed, appraised, or critiqued.]   -- [[User:Gerard Schildberger|Gerard Schildberger]] 09:28, 1 July 2012 (UTC) ===External Links=== * [http://sourceforge.net/projects/brexx/ Brexx interpreter] diff --git a/Lang/REXX/Abundant,-deficient-and-perfect-number-classifications b/Lang/REXX/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..62bdf9cd82 --- /dev/null +++ b/Lang/REXX/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/REXX \ No newline at end of file diff --git a/Lang/REXX/Call-a-foreign-language-function b/Lang/REXX/Call-a-foreign-language-function new file mode 120000 index 0000000000..0c23594762 --- /dev/null +++ b/Lang/REXX/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/REXX \ No newline at end of file diff --git a/Lang/REXX/Call-a-function-in-a-shared-library b/Lang/REXX/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..bd72af696c --- /dev/null +++ b/Lang/REXX/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/REXX \ No newline at end of file diff --git a/Lang/REXX/Deal-cards-for-FreeCell b/Lang/REXX/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..48a5267335 --- /dev/null +++ b/Lang/REXX/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/REXX \ No newline at end of file diff --git a/Lang/REXX/Determine-if-only-one-instance-is-running b/Lang/REXX/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..bf2168312e --- /dev/null +++ b/Lang/REXX/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/REXX \ No newline at end of file diff --git a/Lang/REXX/File-modification-time b/Lang/REXX/File-modification-time new file mode 120000 index 0000000000..ba708e4752 --- /dev/null +++ b/Lang/REXX/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/REXX \ No newline at end of file diff --git a/Lang/REXX/Image-noise b/Lang/REXX/Image-noise new file mode 120000 index 0000000000..6b6155fdf9 --- /dev/null +++ b/Lang/REXX/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/REXX \ No newline at end of file diff --git a/Lang/REXX/Ranking-methods b/Lang/REXX/Ranking-methods new file mode 120000 index 0000000000..11020b3120 --- /dev/null +++ b/Lang/REXX/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/REXX \ No newline at end of file diff --git a/Lang/REXX/Terminal-control-Hiding-the-cursor b/Lang/REXX/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..7e3a690fe2 --- /dev/null +++ b/Lang/REXX/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/REXX \ No newline at end of file diff --git a/Lang/REXX/Update-a-configuration-file b/Lang/REXX/Update-a-configuration-file new file mode 120000 index 0000000000..8a55d6d44b --- /dev/null +++ b/Lang/REXX/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/REXX \ No newline at end of file diff --git a/Lang/REXX/Yin-and-yang b/Lang/REXX/Yin-and-yang new file mode 120000 index 0000000000..9914bcaca1 --- /dev/null +++ b/Lang/REXX/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/REXX \ No newline at end of file diff --git a/Lang/Racket/Append-a-record-to-the-end-of-a-text-file b/Lang/Racket/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..9eb667df3f --- /dev/null +++ b/Lang/Racket/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Racket \ No newline at end of file diff --git a/Lang/Racket/Bitwise-IO b/Lang/Racket/Bitwise-IO new file mode 120000 index 0000000000..77679965bd --- /dev/null +++ b/Lang/Racket/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Racket \ No newline at end of file diff --git a/Lang/Racket/Hello-world-Newbie b/Lang/Racket/Hello-world-Newbie new file mode 120000 index 0000000000..892e678adc --- /dev/null +++ b/Lang/Racket/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Racket \ No newline at end of file diff --git a/Lang/Racket/Integer-overflow b/Lang/Racket/Integer-overflow new file mode 120000 index 0000000000..2a0827387e --- /dev/null +++ b/Lang/Racket/Integer-overflow @@ -0,0 +1 @@ +../../Task/Integer-overflow/Racket \ No newline at end of file diff --git a/Lang/Racket/Machine-code b/Lang/Racket/Machine-code new file mode 120000 index 0000000000..9f447fbfc8 --- /dev/null +++ b/Lang/Racket/Machine-code @@ -0,0 +1 @@ +../../Task/Machine-code/Racket \ No newline at end of file diff --git a/Lang/Racket/Rendezvous b/Lang/Racket/Rendezvous new file mode 120000 index 0000000000..c3143ce658 --- /dev/null +++ b/Lang/Racket/Rendezvous @@ -0,0 +1 @@ +../../Task/Rendezvous/Racket \ No newline at end of file diff --git a/Lang/Racket/Simulate-input-Mouse b/Lang/Racket/Simulate-input-Mouse new file mode 120000 index 0000000000..fb49691c34 --- /dev/null +++ b/Lang/Racket/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Racket \ No newline at end of file diff --git a/Lang/Racket/Textonyms b/Lang/Racket/Textonyms new file mode 120000 index 0000000000..d06782808b --- /dev/null +++ b/Lang/Racket/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Racket \ No newline at end of file diff --git a/Lang/Racket/Use-another-language-to-call-a-function b/Lang/Racket/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..42d37b52fd --- /dev/null +++ b/Lang/Racket/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Racket \ No newline at end of file diff --git a/Lang/RapidQ/Include-a-file b/Lang/RapidQ/Include-a-file new file mode 120000 index 0000000000..8fabc7be2f --- /dev/null +++ b/Lang/RapidQ/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Reverse-a-string b/Lang/RapidQ/Reverse-a-string new file mode 120000 index 0000000000..ef88df7b6d --- /dev/null +++ b/Lang/RapidQ/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Rot-13 b/Lang/RapidQ/Rot-13 new file mode 120000 index 0000000000..b59f2aaa01 --- /dev/null +++ b/Lang/RapidQ/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/RapidQ \ No newline at end of file diff --git a/Lang/Refal/00DESCRIPTION b/Lang/Refal/00DESCRIPTION index ac95bf6da2..1ced3a802e 100644 --- a/Lang/Refal/00DESCRIPTION +++ b/Lang/Refal/00DESCRIPTION @@ -1,3 +1,4 @@ {{stub}} +Refal stands for REcursive Functions Algorithmic Language, it's a functional programming language suited to symbolic and textual manipulation. {{language |site=http://www.refal.net/index_e.htm}} \ No newline at end of file diff --git a/Lang/Ruby/Call-a-function b/Lang/Ruby/Call-a-function new file mode 120000 index 0000000000..5e6488b0ea --- /dev/null +++ b/Lang/Ruby/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Compare-sorting-algorithms-performance b/Lang/Ruby/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..b5f49e977f --- /dev/null +++ b/Lang/Ruby/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Ulam-spiral--for-primes- b/Lang/Ruby/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..b6da66b748 --- /dev/null +++ b/Lang/Ruby/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Circles-of-given-radius-through-two-points b/Lang/Run-BASIC/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..302344f16b --- /dev/null +++ b/Lang/Run-BASIC/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Generate-lower-case-ASCII-alphabet b/Lang/Run-BASIC/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..1bbf772a9e --- /dev/null +++ b/Lang/Run-BASIC/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/HTTPS-Authenticated b/Lang/Run-BASIC/HTTPS-Authenticated new file mode 120000 index 0000000000..30827bfba8 --- /dev/null +++ b/Lang/Run-BASIC/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Left-factorials b/Lang/Run-BASIC/Left-factorials new file mode 120000 index 0000000000..d897f6d5d1 --- /dev/null +++ b/Lang/Run-BASIC/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Stair-climbing-puzzle b/Lang/Run-BASIC/Stair-climbing-puzzle new file mode 120000 index 0000000000..af23444e09 --- /dev/null +++ b/Lang/Run-BASIC/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Voronoi-diagram b/Lang/Run-BASIC/Voronoi-diagram new file mode 120000 index 0000000000..2edf76a007 --- /dev/null +++ b/Lang/Run-BASIC/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/00DESCRIPTION b/Lang/Rust/00DESCRIPTION index f983988e48..ce935fc36e 100644 --- a/Lang/Rust/00DESCRIPTION +++ b/Lang/Rust/00DESCRIPTION @@ -11,18 +11,17 @@ |hopl id=1558 }} -Rust is a work-in-progress general purpose, multi-paradigm, systems programming language sponsored by Mozilla. Its goal is to provide a fast, practical, concurrent language with zero-cost abstractions and strong memory safety. It employs a unique model of ownership to eliminate data races. +Rust is a general purpose, multi-paradigm, systems programming language sponsored by Mozilla. Its goal is to provide a fast, practical, concurrent language with zero-cost abstractions and strong memory safety. It employs a unique model of ownership to eliminate data races. == Features == From the official website: -* algebraic data types -* apattern matching -* closures -* type inference * zero-cost abstractions +* move semantics * guaranteed memory safety -* optional garbage collection -* concurrency without data races +* threads without data races +* trait-based generics +* pattern matching +* type inference * minimal runtime * efficient C bindings diff --git a/Lang/Rust/Address-of-a-variable b/Lang/Rust/Address-of-a-variable new file mode 120000 index 0000000000..94c6dd9a1d --- /dev/null +++ b/Lang/Rust/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Rust \ No newline at end of file diff --git a/Lang/Rust/Aliquot-sequence-classifications b/Lang/Rust/Aliquot-sequence-classifications new file mode 120000 index 0000000000..5f9a4b3d6c --- /dev/null +++ b/Lang/Rust/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Rust \ No newline at end of file diff --git a/Lang/Rust/Amicable-pairs b/Lang/Rust/Amicable-pairs new file mode 120000 index 0000000000..18d7ee7a3f --- /dev/null +++ b/Lang/Rust/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Rust \ No newline at end of file diff --git a/Lang/Rust/Apply-a-callback-to-an-array b/Lang/Rust/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..338f208d49 --- /dev/null +++ b/Lang/Rust/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Rust \ No newline at end of file diff --git a/Lang/Rust/Arrays b/Lang/Rust/Arrays new file mode 120000 index 0000000000..51ca52588c --- /dev/null +++ b/Lang/Rust/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Rust \ No newline at end of file diff --git a/Lang/Rust/Assertions b/Lang/Rust/Assertions new file mode 120000 index 0000000000..b10f9a07b9 --- /dev/null +++ b/Lang/Rust/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/Rust \ No newline at end of file diff --git a/Lang/Rust/Averages-Median b/Lang/Rust/Averages-Median new file mode 120000 index 0000000000..c399515a2e --- /dev/null +++ b/Lang/Rust/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Rust \ No newline at end of file diff --git a/Lang/Rust/Balanced-brackets b/Lang/Rust/Balanced-brackets new file mode 120000 index 0000000000..4e19886e23 --- /dev/null +++ b/Lang/Rust/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Rust \ No newline at end of file diff --git a/Lang/Rust/Character-codes b/Lang/Rust/Character-codes new file mode 120000 index 0000000000..65a464a287 --- /dev/null +++ b/Lang/Rust/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Rust \ No newline at end of file diff --git a/Lang/Rust/Enforced-immutability b/Lang/Rust/Enforced-immutability new file mode 120000 index 0000000000..e8b395b919 --- /dev/null +++ b/Lang/Rust/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Rust \ No newline at end of file diff --git a/Lang/Rust/Execute-Brain---- b/Lang/Rust/Execute-Brain---- new file mode 120000 index 0000000000..c81814a30b --- /dev/null +++ b/Lang/Rust/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Rust \ No newline at end of file diff --git a/Lang/Rust/Execute-a-system-command b/Lang/Rust/Execute-a-system-command new file mode 120000 index 0000000000..d18833b15a --- /dev/null +++ b/Lang/Rust/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Rust \ No newline at end of file diff --git a/Lang/Rust/Function-definition b/Lang/Rust/Function-definition new file mode 120000 index 0000000000..425088e427 --- /dev/null +++ b/Lang/Rust/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Rust \ No newline at end of file diff --git a/Lang/Rust/Generic-swap b/Lang/Rust/Generic-swap new file mode 120000 index 0000000000..1140a57709 --- /dev/null +++ b/Lang/Rust/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Rust \ No newline at end of file diff --git a/Lang/Rust/Greatest-element-of-a-list b/Lang/Rust/Greatest-element-of-a-list new file mode 120000 index 0000000000..3b7a70b5bc --- /dev/null +++ b/Lang/Rust/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Rust \ No newline at end of file diff --git a/Lang/Rust/Greatest-subsequential-sum b/Lang/Rust/Greatest-subsequential-sum new file mode 120000 index 0000000000..3e1367aa8d --- /dev/null +++ b/Lang/Rust/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Rust \ No newline at end of file diff --git a/Lang/Rust/Here-document b/Lang/Rust/Here-document new file mode 120000 index 0000000000..48cb7dd835 --- /dev/null +++ b/Lang/Rust/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Rust \ No newline at end of file diff --git a/Lang/Rust/Higher-order-functions b/Lang/Rust/Higher-order-functions new file mode 120000 index 0000000000..2505074e58 --- /dev/null +++ b/Lang/Rust/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Rust \ No newline at end of file diff --git a/Lang/Rust/Hofstadter-Q-sequence b/Lang/Rust/Hofstadter-Q-sequence new file mode 120000 index 0000000000..05037e8eb1 --- /dev/null +++ b/Lang/Rust/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Include-a-file b/Lang/Rust/Include-a-file new file mode 120000 index 0000000000..ac55c3ef59 --- /dev/null +++ b/Lang/Rust/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Rust \ No newline at end of file diff --git a/Lang/Rust/Iterated-digits-squaring b/Lang/Rust/Iterated-digits-squaring new file mode 120000 index 0000000000..b646365aff --- /dev/null +++ b/Lang/Rust/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Rust \ No newline at end of file diff --git a/Lang/Rust/Knights-tour b/Lang/Rust/Knights-tour new file mode 120000 index 0000000000..1121e5c902 --- /dev/null +++ b/Lang/Rust/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Rust \ No newline at end of file diff --git a/Lang/Rust/Leap-year b/Lang/Rust/Leap-year new file mode 120000 index 0000000000..1a942a650c --- /dev/null +++ b/Lang/Rust/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Rust \ No newline at end of file diff --git a/Lang/Rust/Logical-operations b/Lang/Rust/Logical-operations new file mode 120000 index 0000000000..4fd4a4d658 --- /dev/null +++ b/Lang/Rust/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-Do-while b/Lang/Rust/Loops-Do-while new file mode 120000 index 0000000000..90a285336f --- /dev/null +++ b/Lang/Rust/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-For b/Lang/Rust/Loops-For new file mode 120000 index 0000000000..9df39e919d --- /dev/null +++ b/Lang/Rust/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-Foreach b/Lang/Rust/Loops-Foreach new file mode 120000 index 0000000000..2bf2919ff4 --- /dev/null +++ b/Lang/Rust/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Rust \ No newline at end of file diff --git a/Lang/Rust/Maximum-triangle-path-sum b/Lang/Rust/Maximum-triangle-path-sum new file mode 120000 index 0000000000..3b73133565 --- /dev/null +++ b/Lang/Rust/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Rust \ No newline at end of file diff --git a/Lang/Rust/Null-object b/Lang/Rust/Null-object new file mode 120000 index 0000000000..e99f22a928 --- /dev/null +++ b/Lang/Rust/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Rust \ No newline at end of file diff --git a/Lang/Rust/Numerical-integration b/Lang/Rust/Numerical-integration new file mode 120000 index 0000000000..df871657f5 --- /dev/null +++ b/Lang/Rust/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Rust \ No newline at end of file diff --git a/Lang/Rust/Range-expansion b/Lang/Rust/Range-expansion new file mode 120000 index 0000000000..9b9078feee --- /dev/null +++ b/Lang/Rust/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Rust \ No newline at end of file diff --git a/Lang/Rust/Remove-lines-from-a-file b/Lang/Rust/Remove-lines-from-a-file new file mode 120000 index 0000000000..e6c6f40d73 --- /dev/null +++ b/Lang/Rust/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Rust \ No newline at end of file diff --git a/Lang/Rust/Repeat-a-string b/Lang/Rust/Repeat-a-string new file mode 120000 index 0000000000..35e94110c2 --- /dev/null +++ b/Lang/Rust/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Rust \ No newline at end of file diff --git a/Lang/Rust/Return-multiple-values b/Lang/Rust/Return-multiple-values new file mode 120000 index 0000000000..5fae0e065d --- /dev/null +++ b/Lang/Rust/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Rust \ No newline at end of file diff --git a/Lang/Rust/Reverse-words-in-a-string b/Lang/Rust/Reverse-words-in-a-string new file mode 120000 index 0000000000..dd2e149873 --- /dev/null +++ b/Lang/Rust/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Rust \ No newline at end of file diff --git a/Lang/Rust/Search-a-list b/Lang/Rust/Search-a-list new file mode 120000 index 0000000000..37d978e654 --- /dev/null +++ b/Lang/Rust/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Rust \ No newline at end of file diff --git a/Lang/Rust/Sequence-of-non-squares b/Lang/Rust/Sequence-of-non-squares new file mode 120000 index 0000000000..8157580752 --- /dev/null +++ b/Lang/Rust/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Rust \ No newline at end of file diff --git a/Lang/Rust/Set b/Lang/Rust/Set new file mode 120000 index 0000000000..6cc2021fc9 --- /dev/null +++ b/Lang/Rust/Set @@ -0,0 +1 @@ +../../Task/Set/Rust \ No newline at end of file diff --git a/Lang/Rust/Show-the-epoch b/Lang/Rust/Show-the-epoch new file mode 120000 index 0000000000..c1d4874100 --- /dev/null +++ b/Lang/Rust/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Rust \ No newline at end of file diff --git a/Lang/Rust/Sockets b/Lang/Rust/Sockets new file mode 120000 index 0000000000..6e930865ce --- /dev/null +++ b/Lang/Rust/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Rust \ No newline at end of file diff --git a/Lang/Rust/String-comparison b/Lang/Rust/String-comparison new file mode 120000 index 0000000000..1e16071a1a --- /dev/null +++ b/Lang/Rust/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Rust \ No newline at end of file diff --git a/Lang/Rust/String-matching b/Lang/Rust/String-matching new file mode 120000 index 0000000000..be69ebb787 --- /dev/null +++ b/Lang/Rust/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Rust \ No newline at end of file diff --git a/Lang/Rust/Synchronous-concurrency b/Lang/Rust/Synchronous-concurrency new file mode 120000 index 0000000000..1c57e334ee --- /dev/null +++ b/Lang/Rust/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Rust \ No newline at end of file diff --git a/Lang/Rust/Walk-a-directory-Non-recursively b/Lang/Rust/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..c40cc6b3cb --- /dev/null +++ b/Lang/Rust/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Rust \ No newline at end of file diff --git a/Lang/Rust/Walk-a-directory-Recursively b/Lang/Rust/Walk-a-directory-Recursively new file mode 120000 index 0000000000..4062d5587b --- /dev/null +++ b/Lang/Rust/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Rust \ No newline at end of file diff --git a/Lang/SAS/00DESCRIPTION b/Lang/SAS/00DESCRIPTION index e01909eae8..d73bcd09d3 100644 --- a/Lang/SAS/00DESCRIPTION +++ b/Lang/SAS/00DESCRIPTION @@ -4,4 +4,4 @@ }} {{implementation|SQL}}{{stub}} -SAS is a [[proprietary]] statistical analysis language. \ No newline at end of file +SAS is a proprietary statistical analysis language. \ No newline at end of file diff --git a/Lang/SNOBOL4/Execute-a-Markov-algorithm b/Lang/SNOBOL4/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..7a928f217a --- /dev/null +++ b/Lang/SNOBOL4/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/SNOBOL4 \ No newline at end of file diff --git a/Lang/SNUSP/Sorting-algorithms-Sleep-sort b/Lang/SNUSP/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..2b0ad6058b --- /dev/null +++ b/Lang/SNUSP/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/SNUSP \ No newline at end of file diff --git a/Lang/SQL/Averages-Arithmetic-mean b/Lang/SQL/Averages-Arithmetic-mean new file mode 120000 index 0000000000..d4a3df6a65 --- /dev/null +++ b/Lang/SQL/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/SQL \ No newline at end of file diff --git a/Lang/SQL/Conways-Game-of-Life b/Lang/SQL/Conways-Game-of-Life new file mode 120000 index 0000000000..258ba190f7 --- /dev/null +++ b/Lang/SQL/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/SQL \ No newline at end of file diff --git a/Lang/SQL/Greatest-common-divisor b/Lang/SQL/Greatest-common-divisor new file mode 120000 index 0000000000..11474dedbe --- /dev/null +++ b/Lang/SQL/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/SQL \ No newline at end of file diff --git a/Lang/SQL/Literals-String b/Lang/SQL/Literals-String new file mode 120000 index 0000000000..473554027a --- /dev/null +++ b/Lang/SQL/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/SQL \ No newline at end of file diff --git a/Lang/SQL/Standard-deviation b/Lang/SQL/Standard-deviation new file mode 120000 index 0000000000..acd1ea1bbd --- /dev/null +++ b/Lang/SQL/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/SQL \ No newline at end of file diff --git a/Lang/SQL/The-Twelve-Days-of-Christmas b/Lang/SQL/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..8df98736d7 --- /dev/null +++ b/Lang/SQL/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/SQL \ No newline at end of file diff --git a/Lang/SQL/Zero-to-the-zero-power b/Lang/SQL/Zero-to-the-zero-power new file mode 120000 index 0000000000..f737bb6e97 --- /dev/null +++ b/Lang/SQL/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/SQL \ No newline at end of file diff --git a/Lang/Scala/Average-loop-length b/Lang/Scala/Average-loop-length new file mode 120000 index 0000000000..198062c8d1 --- /dev/null +++ b/Lang/Scala/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Scala \ No newline at end of file diff --git a/Lang/Scala/Circles-of-given-radius-through-two-points b/Lang/Scala/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..0c44e0fe9b --- /dev/null +++ b/Lang/Scala/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Scala \ No newline at end of file diff --git a/Lang/Scala/Currying b/Lang/Scala/Currying new file mode 120000 index 0000000000..1f6909021d --- /dev/null +++ b/Lang/Scala/Currying @@ -0,0 +1 @@ +../../Task/Currying/Scala \ No newline at end of file diff --git a/Lang/Scala/Dragon-curve b/Lang/Scala/Dragon-curve new file mode 120000 index 0000000000..0f293aeda4 --- /dev/null +++ b/Lang/Scala/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Scala \ No newline at end of file diff --git a/Lang/Scala/Five-weekends b/Lang/Scala/Five-weekends new file mode 120000 index 0000000000..d9bcfceb27 --- /dev/null +++ b/Lang/Scala/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Scala \ No newline at end of file diff --git a/Lang/Scala/Fractran b/Lang/Scala/Fractran new file mode 120000 index 0000000000..e7c71e91e4 --- /dev/null +++ b/Lang/Scala/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Scala \ No newline at end of file diff --git a/Lang/Scala/Heronian-triangles b/Lang/Scala/Heronian-triangles new file mode 120000 index 0000000000..6158105a38 --- /dev/null +++ b/Lang/Scala/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Scala \ No newline at end of file diff --git a/Lang/Scala/Left-factorials b/Lang/Scala/Left-factorials new file mode 120000 index 0000000000..5c55894565 --- /dev/null +++ b/Lang/Scala/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Scala \ No newline at end of file diff --git a/Lang/Scala/Magic-squares-of-odd-order b/Lang/Scala/Magic-squares-of-odd-order new file mode 120000 index 0000000000..4ef738485f --- /dev/null +++ b/Lang/Scala/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/Scala \ No newline at end of file diff --git a/Lang/Scala/Modular-inverse b/Lang/Scala/Modular-inverse new file mode 120000 index 0000000000..9d6fb525c6 --- /dev/null +++ b/Lang/Scala/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Scala \ No newline at end of file diff --git a/Lang/Scala/Parsing-RPN-calculator-algorithm b/Lang/Scala/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..67e7775034 --- /dev/null +++ b/Lang/Scala/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Scala \ No newline at end of file diff --git a/Lang/Scala/Ray-casting-algorithm b/Lang/Scala/Ray-casting-algorithm new file mode 120000 index 0000000000..3e5ac35578 --- /dev/null +++ b/Lang/Scala/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/Scala \ No newline at end of file diff --git a/Lang/Scala/SHA-1 b/Lang/Scala/SHA-1 new file mode 120000 index 0000000000..b2c60cbeca --- /dev/null +++ b/Lang/Scala/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Scala \ No newline at end of file diff --git a/Lang/Scala/Trabb-Pardo-Knuth-algorithm b/Lang/Scala/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..2344d3a219 --- /dev/null +++ b/Lang/Scala/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Scala \ No newline at end of file diff --git a/Lang/Scheme/ABC-Problem b/Lang/Scheme/ABC-Problem new file mode 120000 index 0000000000..6ec037e955 --- /dev/null +++ b/Lang/Scheme/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Abundant,-deficient-and-perfect-number-classifications b/Lang/Scheme/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..349733bf5b --- /dev/null +++ b/Lang/Scheme/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Scheme \ No newline at end of file diff --git a/Lang/Scheme/JSON b/Lang/Scheme/JSON new file mode 120000 index 0000000000..3a4d4969f5 --- /dev/null +++ b/Lang/Scheme/JSON @@ -0,0 +1 @@ +../../Task/JSON/Scheme \ No newline at end of file diff --git a/Lang/Scheme/SHA-1 b/Lang/Scheme/SHA-1 new file mode 120000 index 0000000000..9af147a7f3 --- /dev/null +++ b/Lang/Scheme/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Scheme \ No newline at end of file diff --git a/Lang/Scilab/Loops-Break b/Lang/Scilab/Loops-Break new file mode 120000 index 0000000000..365d8e1fe7 --- /dev/null +++ b/Lang/Scilab/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-Continue b/Lang/Scilab/Loops-Continue new file mode 120000 index 0000000000..0543ab5a15 --- /dev/null +++ b/Lang/Scilab/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-Do-while b/Lang/Scilab/Loops-Do-while new file mode 120000 index 0000000000..7bf7a98245 --- /dev/null +++ b/Lang/Scilab/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-Downward-for b/Lang/Scilab/Loops-Downward-for new file mode 120000 index 0000000000..de2ffce3ee --- /dev/null +++ b/Lang/Scilab/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-For b/Lang/Scilab/Loops-For new file mode 120000 index 0000000000..b2c94bddbf --- /dev/null +++ b/Lang/Scilab/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-For-with-a-specified-step b/Lang/Scilab/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..81565eb3f8 --- /dev/null +++ b/Lang/Scilab/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-Foreach b/Lang/Scilab/Loops-Foreach new file mode 120000 index 0000000000..7821634d1f --- /dev/null +++ b/Lang/Scilab/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-Infinite b/Lang/Scilab/Loops-Infinite new file mode 120000 index 0000000000..9f5424d34e --- /dev/null +++ b/Lang/Scilab/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-N-plus-one-half b/Lang/Scilab/Loops-N-plus-one-half new file mode 120000 index 0000000000..3ed00b8a3a --- /dev/null +++ b/Lang/Scilab/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-Nested b/Lang/Scilab/Loops-Nested new file mode 120000 index 0000000000..2dc09ffb6e --- /dev/null +++ b/Lang/Scilab/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Loops-While b/Lang/Scilab/Loops-While new file mode 120000 index 0000000000..0ed8890ddd --- /dev/null +++ b/Lang/Scilab/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Multiplication-tables b/Lang/Scilab/Multiplication-tables new file mode 120000 index 0000000000..0a8204309c --- /dev/null +++ b/Lang/Scilab/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Scilab \ No newline at end of file diff --git a/Lang/Seed7/Generate-lower-case-ASCII-alphabet b/Lang/Seed7/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..5af01e15a6 --- /dev/null +++ b/Lang/Seed7/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Make-directory-path b/Lang/Seed7/Make-directory-path new file mode 120000 index 0000000000..d0f2d06a24 --- /dev/null +++ b/Lang/Seed7/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Seed7 \ No newline at end of file diff --git a/Lang/Self/00DESCRIPTION b/Lang/Self/00DESCRIPTION index fc604dbf65..856070bf64 100644 --- a/Lang/Self/00DESCRIPTION +++ b/Lang/Self/00DESCRIPTION @@ -3,7 +3,7 @@ |LCT=no }} -'''Self''' is an [[object-oriented]] programming language based on the concept of prototypes. It was used primarily as an experimental test system for language design in the 1980s and 1990s; however, as of July of 2006, Self is still being actively developed as part of the Klein project which is a Self virtual machine written entirely in Self. The latest major version is 4.3, which was released in July 2006. +'''Self''' is an [[object-oriented]] programming language based on the concept of prototypes. It was used primarily as an experimental test system for language design in the 1980s and 1990s; however, as of May 2015, Self is still being developed and maintained as an open source project. The latest major version is 4.5.0, which was released in January 2014. ==Citations== * [[wp:Self_%28programming_language%29|Wikipedia:Self (programming language)]] \ No newline at end of file diff --git a/Lang/Self/A+B b/Lang/Self/A+B new file mode 120000 index 0000000000..b4520e391a --- /dev/null +++ b/Lang/Self/A+B @@ -0,0 +1 @@ +../../Task/A+B/Self \ No newline at end of file diff --git a/Lang/Self/Arrays b/Lang/Self/Arrays new file mode 120000 index 0000000000..30f811f416 --- /dev/null +++ b/Lang/Self/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Self \ No newline at end of file diff --git a/Lang/Self/Empty-string b/Lang/Self/Empty-string new file mode 120000 index 0000000000..3b6a0b61f8 --- /dev/null +++ b/Lang/Self/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Self \ No newline at end of file diff --git a/Lang/Self/Factorial b/Lang/Self/Factorial new file mode 120000 index 0000000000..6d72f5b865 --- /dev/null +++ b/Lang/Self/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Self \ No newline at end of file diff --git a/Lang/Self/Greatest-element-of-a-list b/Lang/Self/Greatest-element-of-a-list new file mode 120000 index 0000000000..40c6a0d0d7 --- /dev/null +++ b/Lang/Self/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Self \ No newline at end of file diff --git a/Lang/Self/Guess-the-number b/Lang/Self/Guess-the-number new file mode 120000 index 0000000000..8ee450ccbb --- /dev/null +++ b/Lang/Self/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Self \ No newline at end of file diff --git a/Lang/Self/Inheritance-Multiple b/Lang/Self/Inheritance-Multiple new file mode 120000 index 0000000000..bb2634ed3f --- /dev/null +++ b/Lang/Self/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/Self \ No newline at end of file diff --git a/Lang/Self/Inheritance-Single b/Lang/Self/Inheritance-Single new file mode 120000 index 0000000000..975f3b8225 --- /dev/null +++ b/Lang/Self/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Self \ No newline at end of file diff --git a/Lang/Self/Logical-operations b/Lang/Self/Logical-operations new file mode 120000 index 0000000000..04f8b790ff --- /dev/null +++ b/Lang/Self/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Self \ No newline at end of file diff --git a/Lang/Self/Loops-Foreach b/Lang/Self/Loops-Foreach new file mode 120000 index 0000000000..e7121d747d --- /dev/null +++ b/Lang/Self/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Self \ No newline at end of file diff --git a/Lang/Self/Loops-Infinite b/Lang/Self/Loops-Infinite new file mode 120000 index 0000000000..613334deda --- /dev/null +++ b/Lang/Self/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Self \ No newline at end of file diff --git a/Lang/Self/Polymorphism b/Lang/Self/Polymorphism new file mode 120000 index 0000000000..69c0d8bbbb --- /dev/null +++ b/Lang/Self/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Self \ No newline at end of file diff --git a/Lang/Self/Reverse-a-string b/Lang/Self/Reverse-a-string new file mode 120000 index 0000000000..e1e21b0544 --- /dev/null +++ b/Lang/Self/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Self \ No newline at end of file diff --git a/Lang/Self/The-Twelve-Days-of-Christmas b/Lang/Self/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..35ad3a445a --- /dev/null +++ b/Lang/Self/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Self \ No newline at end of file diff --git a/Lang/Self/Tokenize-a-string b/Lang/Self/Tokenize-a-string new file mode 120000 index 0000000000..3f2a85ee3e --- /dev/null +++ b/Lang/Self/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Self \ No newline at end of file diff --git a/Lang/Squirrel/Comments b/Lang/Squirrel/Comments new file mode 120000 index 0000000000..d549ed2774 --- /dev/null +++ b/Lang/Squirrel/Comments @@ -0,0 +1 @@ +../../Task/Comments/Squirrel \ No newline at end of file diff --git a/Lang/TI-83-BASIC/00DESCRIPTION b/Lang/TI-83-BASIC/00DESCRIPTION index 09126e654f..edb711d646 100644 --- a/Lang/TI-83-BASIC/00DESCRIPTION +++ b/Lang/TI-83-BASIC/00DESCRIPTION @@ -1,6 +1,6 @@ {{stub}}{{language|TI-83 BASIC |tags=ti83b}} -'''TI-83 BASIC''' or '''TI-BASIC''' is the high-level language used on TI-83 and TI-83+ calculators (aside from the assembly which is also on the calculator). TI-83 BASIC is the older brother of [[TI-89 BASIC]]. One of the main complaints with TI-83 BASIC is that there is no native function that tells time, this feature was added in TI-89 BASIC. The language itself, however, is a powerful language capable of many things; nested loops and string manipulation among others. Many students create small programs on their calculators to help them through tests and homework. One popular example is a quadratic formula program. TI-83 BASIC is not affiliated with [[BASIC]] and is not as similar to it as the name would suggest. Someone who has experience writing code in [[C]] or [[C++]] should have no trouble working with this language. +'''TI-83 BASIC''' or '''TI-BASIC''' is the high-level language used on TI-83/84/+/SE calculators (aside from the assembly which is also on the calculator). TI-83 BASIC is the older brother of [[TI-89 BASIC]]. One of the main complaints with TI-83 BASIC is that there is no native function that tells time, this feature was added in the TI-84+. The language itself, however, is a powerful language capable of many things; nested loops and string manipulation among others. Many students create small programs on their calculators to help them through tests and homework. One popular example is a quadratic formula program. TI-83 BASIC is not affiliated with [[BASIC]] and is not as similar to it as the name would suggest. Someone who has experience writing code in [[C]] or [[C++]] should have no trouble working with this language. ==See Also== * [[wp:TI-BASIC|Wikipedia: TI-BASIC]] diff --git a/Lang/TI-83-BASIC/Arithmetic-geometric-mean b/Lang/TI-83-BASIC/Arithmetic-geometric-mean new file mode 120000 index 0000000000..312362d183 --- /dev/null +++ b/Lang/TI-83-BASIC/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Averages-Arithmetic-mean b/Lang/TI-83-BASIC/Averages-Arithmetic-mean new file mode 120000 index 0000000000..fe2f87faee --- /dev/null +++ b/Lang/TI-83-BASIC/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Create-a-two-dimensional-array-at-runtime b/Lang/TI-83-BASIC/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..d08572d90e --- /dev/null +++ b/Lang/TI-83-BASIC/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Empty-program b/Lang/TI-83-BASIC/Empty-program new file mode 120000 index 0000000000..29700b99fb --- /dev/null +++ b/Lang/TI-83-BASIC/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Evaluate-binomial-coefficients b/Lang/TI-83-BASIC/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..e584818c56 --- /dev/null +++ b/Lang/TI-83-BASIC/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Even-or-odd b/Lang/TI-83-BASIC/Even-or-odd new file mode 120000 index 0000000000..64479550a1 --- /dev/null +++ b/Lang/TI-83-BASIC/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Factors-of-a-Mersenne-number b/Lang/TI-83-BASIC/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..f1abb0d07c --- /dev/null +++ b/Lang/TI-83-BASIC/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Gaussian-elimination b/Lang/TI-83-BASIC/Gaussian-elimination new file mode 120000 index 0000000000..4bd84c1bfd --- /dev/null +++ b/Lang/TI-83-BASIC/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Hello-world-Text b/Lang/TI-83-BASIC/Hello-world-Text new file mode 120000 index 0000000000..993891e0fa --- /dev/null +++ b/Lang/TI-83-BASIC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Hickerson-series-of-almost-integers b/Lang/TI-83-BASIC/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..5136bee0c7 --- /dev/null +++ b/Lang/TI-83-BASIC/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Integer-comparison b/Lang/TI-83-BASIC/Integer-comparison new file mode 120000 index 0000000000..7f21bbe2c3 --- /dev/null +++ b/Lang/TI-83-BASIC/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Loops-For-with-a-specified-step b/Lang/TI-83-BASIC/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..cfe3a54861 --- /dev/null +++ b/Lang/TI-83-BASIC/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Loops-Nested b/Lang/TI-83-BASIC/Loops-Nested new file mode 120000 index 0000000000..3d2fd82f0a --- /dev/null +++ b/Lang/TI-83-BASIC/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Pangram-checker b/Lang/TI-83-BASIC/Pangram-checker new file mode 120000 index 0000000000..0487fe44cb --- /dev/null +++ b/Lang/TI-83-BASIC/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Prime-decomposition b/Lang/TI-83-BASIC/Prime-decomposition new file mode 120000 index 0000000000..e2158de9a7 --- /dev/null +++ b/Lang/TI-83-BASIC/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Random-number-generator--included- b/Lang/TI-83-BASIC/Random-number-generator--included- new file mode 120000 index 0000000000..e14f1bf676 --- /dev/null +++ b/Lang/TI-83-BASIC/Random-number-generator--included- @@ -0,0 +1 @@ +../../Task/Random-number-generator--included-/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/String-concatenation b/Lang/TI-83-BASIC/String-concatenation new file mode 120000 index 0000000000..b488f3f992 --- /dev/null +++ b/Lang/TI-83-BASIC/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/A+B b/Lang/TI-89-BASIC/A+B new file mode 120000 index 0000000000..3bc203992f --- /dev/null +++ b/Lang/TI-89-BASIC/A+B @@ -0,0 +1 @@ +../../Task/A+B/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TI-89-BASIC/Roots-of-a-quadratic-function b/Lang/TI-89-BASIC/Roots-of-a-quadratic-function new file mode 120000 index 0000000000..bee0bb35ce --- /dev/null +++ b/Lang/TI-89-BASIC/Roots-of-a-quadratic-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-quadratic-function/TI-89-BASIC \ No newline at end of file diff --git a/Lang/TXR/00DESCRIPTION b/Lang/TXR/00DESCRIPTION index e908b2ce73..739386c444 100644 --- a/Lang/TXR/00DESCRIPTION +++ b/Lang/TXR/00DESCRIPTION @@ -28,7 +28,7 @@ In TXR Lisp, the @ character has more "meta" piled on top of it: @(do ...) directive which contains nothing but TXR Lisp forms. Also, TXR Lisp evaluation is available from program invocation via the -e and -p options. -The second unusual feature in TXR Lisp is that the "tokens" in the pattern matching language are essentially themselves Lisp symbols and expressions. These "tokens" are used to create a block-structured language. This is quite odd. For instance a construct might begin with a @(collect :vars (foo)). This is a Lisp expression with interior structure, but to the parser of the pattern language, it's also basically just a token, like a giant keyword. IT begins a collect clause, and is followed by some optional material which may just be literal text, and must be terminated by the @(end) directive: another token-expression entity. +The second unusual feature in TXR is that the "tokens" in the pattern matching language are essentially themselves Lisp symbols and expressions. These "tokens" are used to create a block-structured language. This is quite odd. For instance a construct might begin with a @(collect :vars (foo)). This is a Lisp expression with interior structure, but to the parser of the pattern language, it's also basically just a token, like a giant keyword. IT begins a collect clause, and is followed by some optional material which may just be literal text, and must be terminated by the @(end) directive: another token-expression entity. === Dual Personality === diff --git a/Lang/TXR/CSV-data-manipulation b/Lang/TXR/CSV-data-manipulation new file mode 120000 index 0000000000..e4085e7baf --- /dev/null +++ b/Lang/TXR/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/TXR \ No newline at end of file diff --git a/Lang/TXR/Classes b/Lang/TXR/Classes new file mode 120000 index 0000000000..7be5f9c56a --- /dev/null +++ b/Lang/TXR/Classes @@ -0,0 +1 @@ +../../Task/Classes/TXR \ No newline at end of file diff --git a/Lang/TXR/Combinations-with-repetitions b/Lang/TXR/Combinations-with-repetitions new file mode 120000 index 0000000000..d2d2c2cd6e --- /dev/null +++ b/Lang/TXR/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/TXR \ No newline at end of file diff --git a/Lang/TXR/Compound-data-type b/Lang/TXR/Compound-data-type new file mode 120000 index 0000000000..7edc0e89e0 --- /dev/null +++ b/Lang/TXR/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/TXR \ No newline at end of file diff --git a/Lang/TXR/Extend-your-language b/Lang/TXR/Extend-your-language new file mode 120000 index 0000000000..5a87f8650a --- /dev/null +++ b/Lang/TXR/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/TXR \ No newline at end of file diff --git a/Lang/TXR/Reverse-words-in-a-string b/Lang/TXR/Reverse-words-in-a-string new file mode 120000 index 0000000000..e3f6974acf --- /dev/null +++ b/Lang/TXR/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/TXR \ No newline at end of file diff --git a/Lang/Tcl/Abundant,-deficient-and-perfect-number-classifications b/Lang/Tcl/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..44287035ea --- /dev/null +++ b/Lang/Tcl/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Aliquot-sequence-classifications b/Lang/Tcl/Aliquot-sequence-classifications new file mode 120000 index 0000000000..3998fa1fa5 --- /dev/null +++ b/Lang/Tcl/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Heronian-triangles b/Lang/Tcl/Heronian-triangles new file mode 120000 index 0000000000..8beb61d5d5 --- /dev/null +++ b/Lang/Tcl/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Solve-a-Numbrix-puzzle b/Lang/Tcl/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..f582f3c84e --- /dev/null +++ b/Lang/Tcl/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Stern-Brocot-sequence b/Lang/Tcl/Stern-Brocot-sequence new file mode 120000 index 0000000000..8fee44566f --- /dev/null +++ b/Lang/Tcl/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Textonyms b/Lang/Tcl/Textonyms new file mode 120000 index 0000000000..7ec66a8e9c --- /dev/null +++ b/Lang/Tcl/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Ulam-spiral--for-primes- b/Lang/Tcl/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..c28ade197f --- /dev/null +++ b/Lang/Tcl/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Tcl \ No newline at end of file diff --git a/Lang/UNIX-Shell/Binary-search b/Lang/UNIX-Shell/Binary-search new file mode 120000 index 0000000000..fc264eac65 --- /dev/null +++ b/Lang/UNIX-Shell/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Count-occurrences-of-a-substring b/Lang/UNIX-Shell/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..03a8b7fd71 --- /dev/null +++ b/Lang/UNIX-Shell/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Count-the-coins b/Lang/UNIX-Shell/Count-the-coins new file mode 120000 index 0000000000..291083876f --- /dev/null +++ b/Lang/UNIX-Shell/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Old-lady-swallowed-a-fly b/Lang/UNIX-Shell/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..5f62512dba --- /dev/null +++ b/Lang/UNIX-Shell/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/UNIX-Shell \ No newline at end of file diff --git a/Lang/UserRPL/00DESCRIPTION b/Lang/UserRPL/00DESCRIPTION index 4d3d27c049..4e402524ea 100644 --- a/Lang/UserRPL/00DESCRIPTION +++ b/Lang/UserRPL/00DESCRIPTION @@ -1 +1,3 @@ -{{stub}}{{language}} \ No newline at end of file +{{stub}}{{language}} + +{{merge language | RPL }} \ No newline at end of file diff --git a/Lang/VBA/Factors-of-an-integer b/Lang/VBA/Factors-of-an-integer new file mode 120000 index 0000000000..2e48dd7934 --- /dev/null +++ b/Lang/VBA/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/VBA \ No newline at end of file diff --git a/Lang/VBA/Problem-of-Apollonius b/Lang/VBA/Problem-of-Apollonius new file mode 120000 index 0000000000..697e1431e7 --- /dev/null +++ b/Lang/VBA/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/VBA \ No newline at end of file diff --git a/Lang/VBScript/Almost-prime b/Lang/VBScript/Almost-prime new file mode 120000 index 0000000000..fb1b282850 --- /dev/null +++ b/Lang/VBScript/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Arithmetic-geometric-mean b/Lang/VBScript/Arithmetic-geometric-mean new file mode 120000 index 0000000000..64a7b38baa --- /dev/null +++ b/Lang/VBScript/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Associative-array-Iteration b/Lang/VBScript/Associative-array-Iteration new file mode 120000 index 0000000000..1fc8448674 --- /dev/null +++ b/Lang/VBScript/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Averages-Arithmetic-mean b/Lang/VBScript/Averages-Arithmetic-mean new file mode 120000 index 0000000000..ff73df2e58 --- /dev/null +++ b/Lang/VBScript/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Averages-Pythagorean-means b/Lang/VBScript/Averages-Pythagorean-means new file mode 120000 index 0000000000..3a9bb703b2 --- /dev/null +++ b/Lang/VBScript/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Balanced-brackets b/Lang/VBScript/Balanced-brackets new file mode 120000 index 0000000000..3f14d2b484 --- /dev/null +++ b/Lang/VBScript/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Best-shuffle b/Lang/VBScript/Best-shuffle new file mode 120000 index 0000000000..9c28419408 --- /dev/null +++ b/Lang/VBScript/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Binary-search b/Lang/VBScript/Binary-search new file mode 120000 index 0000000000..8f0076273f --- /dev/null +++ b/Lang/VBScript/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/VBScript \ No newline at end of file diff --git a/Lang/VBScript/CSV-data-manipulation b/Lang/VBScript/CSV-data-manipulation new file mode 120000 index 0000000000..574ee7575f --- /dev/null +++ b/Lang/VBScript/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/VBScript \ No newline at end of file diff --git a/Lang/VBScript/CSV-to-HTML-translation b/Lang/VBScript/CSV-to-HTML-translation new file mode 120000 index 0000000000..40e9ff35c5 --- /dev/null +++ b/Lang/VBScript/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Catalan-numbers b/Lang/VBScript/Catalan-numbers new file mode 120000 index 0000000000..27bce48fa2 --- /dev/null +++ b/Lang/VBScript/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Character-codes b/Lang/VBScript/Character-codes new file mode 120000 index 0000000000..301fa4a2ed --- /dev/null +++ b/Lang/VBScript/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Combinations b/Lang/VBScript/Combinations new file mode 120000 index 0000000000..4ebbaa96ca --- /dev/null +++ b/Lang/VBScript/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Comma-quibbling b/Lang/VBScript/Comma-quibbling new file mode 120000 index 0000000000..ba9d11448a --- /dev/null +++ b/Lang/VBScript/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Count-in-factors b/Lang/VBScript/Count-in-factors new file mode 120000 index 0000000000..f379fa4a72 --- /dev/null +++ b/Lang/VBScript/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Count-in-octal b/Lang/VBScript/Count-in-octal new file mode 120000 index 0000000000..4653dd443f --- /dev/null +++ b/Lang/VBScript/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Count-occurrences-of-a-substring b/Lang/VBScript/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..411fa90144 --- /dev/null +++ b/Lang/VBScript/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Count-the-coins b/Lang/VBScript/Count-the-coins new file mode 120000 index 0000000000..9c6eb8c841 --- /dev/null +++ b/Lang/VBScript/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Create-a-file b/Lang/VBScript/Create-a-file new file mode 120000 index 0000000000..06f5014296 --- /dev/null +++ b/Lang/VBScript/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Create-an-HTML-table b/Lang/VBScript/Create-an-HTML-table new file mode 120000 index 0000000000..c6de80eac6 --- /dev/null +++ b/Lang/VBScript/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/VBScript \ No newline at end of file diff --git a/Lang/VBScript/DNS-query b/Lang/VBScript/DNS-query new file mode 120000 index 0000000000..3cd5e86f72 --- /dev/null +++ b/Lang/VBScript/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Date-format b/Lang/VBScript/Date-format new file mode 120000 index 0000000000..f1da00985e --- /dev/null +++ b/Lang/VBScript/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Day-of-the-week b/Lang/VBScript/Day-of-the-week new file mode 120000 index 0000000000..fa5bd96523 --- /dev/null +++ b/Lang/VBScript/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Detect-division-by-zero b/Lang/VBScript/Detect-division-by-zero new file mode 120000 index 0000000000..1f2dfe9476 --- /dev/null +++ b/Lang/VBScript/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Digital-root b/Lang/VBScript/Digital-root new file mode 120000 index 0000000000..5296aa718a --- /dev/null +++ b/Lang/VBScript/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Dot-product b/Lang/VBScript/Dot-product new file mode 120000 index 0000000000..ed1a7e6111 --- /dev/null +++ b/Lang/VBScript/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Dutch-national-flag-problem b/Lang/VBScript/Dutch-national-flag-problem new file mode 120000 index 0000000000..aac1ab69c1 --- /dev/null +++ b/Lang/VBScript/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Empty-directory b/Lang/VBScript/Empty-directory new file mode 120000 index 0000000000..e3b3032a19 --- /dev/null +++ b/Lang/VBScript/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Equilibrium-index b/Lang/VBScript/Equilibrium-index new file mode 120000 index 0000000000..35b86193a3 --- /dev/null +++ b/Lang/VBScript/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Evaluate-binomial-coefficients b/Lang/VBScript/Evaluate-binomial-coefficients new file mode 120000 index 0000000000..e921673cc2 --- /dev/null +++ b/Lang/VBScript/Evaluate-binomial-coefficients @@ -0,0 +1 @@ +../../Task/Evaluate-binomial-coefficients/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Even-or-odd b/Lang/VBScript/Even-or-odd new file mode 120000 index 0000000000..556a1eea6e --- /dev/null +++ b/Lang/VBScript/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Execute-a-system-command b/Lang/VBScript/Execute-a-system-command new file mode 120000 index 0000000000..6ef48bd585 --- /dev/null +++ b/Lang/VBScript/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Exponentiation-operator b/Lang/VBScript/Exponentiation-operator new file mode 120000 index 0000000000..cb14ef87d9 --- /dev/null +++ b/Lang/VBScript/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Factors-of-a-Mersenne-number b/Lang/VBScript/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..48b9ea8197 --- /dev/null +++ b/Lang/VBScript/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Fibonacci-n-step-number-sequences b/Lang/VBScript/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..54afe30dad --- /dev/null +++ b/Lang/VBScript/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Filter b/Lang/VBScript/Filter new file mode 120000 index 0000000000..9e3c485f2d --- /dev/null +++ b/Lang/VBScript/Filter @@ -0,0 +1 @@ +../../Task/Filter/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Generate-lower-case-ASCII-alphabet b/Lang/VBScript/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..7520c587be --- /dev/null +++ b/Lang/VBScript/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Greatest-element-of-a-list b/Lang/VBScript/Greatest-element-of-a-list new file mode 120000 index 0000000000..94ea2ddce7 --- /dev/null +++ b/Lang/VBScript/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Hailstone-sequence b/Lang/VBScript/Hailstone-sequence new file mode 120000 index 0000000000..79b584617f --- /dev/null +++ b/Lang/VBScript/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Hamming-numbers b/Lang/VBScript/Hamming-numbers new file mode 120000 index 0000000000..c1007147c2 --- /dev/null +++ b/Lang/VBScript/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Happy-numbers b/Lang/VBScript/Happy-numbers new file mode 120000 index 0000000000..0933fd62e0 --- /dev/null +++ b/Lang/VBScript/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Harshad-or-Niven-series b/Lang/VBScript/Harshad-or-Niven-series new file mode 120000 index 0000000000..1c2aa7ba00 --- /dev/null +++ b/Lang/VBScript/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Hash-join b/Lang/VBScript/Hash-join new file mode 120000 index 0000000000..a2539d0a60 --- /dev/null +++ b/Lang/VBScript/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Hofstadter-Figure-Figure-sequences b/Lang/VBScript/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..4ac560d605 --- /dev/null +++ b/Lang/VBScript/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Hofstadter-Q-sequence b/Lang/VBScript/Hofstadter-Q-sequence new file mode 120000 index 0000000000..0cf6dda1d1 --- /dev/null +++ b/Lang/VBScript/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Horners-rule-for-polynomial-evaluation b/Lang/VBScript/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..1db840a1fa --- /dev/null +++ b/Lang/VBScript/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Hostname b/Lang/VBScript/Hostname new file mode 120000 index 0000000000..98b4c8ae74 --- /dev/null +++ b/Lang/VBScript/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/VBScript \ No newline at end of file diff --git a/Lang/VBScript/IBAN b/Lang/VBScript/IBAN new file mode 120000 index 0000000000..c5d147229f --- /dev/null +++ b/Lang/VBScript/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Identity-matrix b/Lang/VBScript/Identity-matrix new file mode 120000 index 0000000000..3290073c75 --- /dev/null +++ b/Lang/VBScript/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Iterated-digits-squaring b/Lang/VBScript/Iterated-digits-squaring new file mode 120000 index 0000000000..ba6ff438bf --- /dev/null +++ b/Lang/VBScript/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Josephus-problem b/Lang/VBScript/Josephus-problem new file mode 120000 index 0000000000..6230eb303c --- /dev/null +++ b/Lang/VBScript/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Largest-int-from-concatenated-ints b/Lang/VBScript/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..cca7de29db --- /dev/null +++ b/Lang/VBScript/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Leap-year b/Lang/VBScript/Leap-year new file mode 120000 index 0000000000..106af756ac --- /dev/null +++ b/Lang/VBScript/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Least-common-multiple b/Lang/VBScript/Least-common-multiple new file mode 120000 index 0000000000..ea57bc993f --- /dev/null +++ b/Lang/VBScript/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Letter-frequency b/Lang/VBScript/Letter-frequency new file mode 120000 index 0000000000..997a3ff66d --- /dev/null +++ b/Lang/VBScript/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Longest-string-challenge b/Lang/VBScript/Longest-string-challenge new file mode 120000 index 0000000000..44dbec2e4e --- /dev/null +++ b/Lang/VBScript/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Ludic-numbers b/Lang/VBScript/Ludic-numbers new file mode 120000 index 0000000000..2c9b71bcf8 --- /dev/null +++ b/Lang/VBScript/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Mad-Libs b/Lang/VBScript/Mad-Libs new file mode 120000 index 0000000000..bd9531e071 --- /dev/null +++ b/Lang/VBScript/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Magic-squares-of-odd-order b/Lang/VBScript/Magic-squares-of-odd-order new file mode 120000 index 0000000000..8ddede3ec8 --- /dev/null +++ b/Lang/VBScript/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Matrix-multiplication b/Lang/VBScript/Matrix-multiplication new file mode 120000 index 0000000000..616c512e47 --- /dev/null +++ b/Lang/VBScript/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Matrix-transposition b/Lang/VBScript/Matrix-transposition new file mode 120000 index 0000000000..e98f736d6f --- /dev/null +++ b/Lang/VBScript/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Maximum-triangle-path-sum b/Lang/VBScript/Maximum-triangle-path-sum new file mode 120000 index 0000000000..a71fe7a4cb --- /dev/null +++ b/Lang/VBScript/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Menu b/Lang/VBScript/Menu new file mode 120000 index 0000000000..3381bbf490 --- /dev/null +++ b/Lang/VBScript/Menu @@ -0,0 +1 @@ +../../Task/Menu/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Middle-three-digits b/Lang/VBScript/Middle-three-digits new file mode 120000 index 0000000000..7eed9f0d2f --- /dev/null +++ b/Lang/VBScript/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Move-to-front-algorithm b/Lang/VBScript/Move-to-front-algorithm new file mode 120000 index 0000000000..8052c7c3ff --- /dev/null +++ b/Lang/VBScript/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Multifactorial b/Lang/VBScript/Multifactorial new file mode 120000 index 0000000000..8618ca946a --- /dev/null +++ b/Lang/VBScript/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Multisplit b/Lang/VBScript/Multisplit new file mode 120000 index 0000000000..e3c2da0905 --- /dev/null +++ b/Lang/VBScript/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Narcissistic-decimal-number b/Lang/VBScript/Narcissistic-decimal-number new file mode 120000 index 0000000000..8ef6dd9096 --- /dev/null +++ b/Lang/VBScript/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/VBScript \ No newline at end of file diff --git a/Lang/VBScript/One-of-n-lines-in-a-file b/Lang/VBScript/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..a630aad383 --- /dev/null +++ b/Lang/VBScript/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Order-two-numerical-lists b/Lang/VBScript/Order-two-numerical-lists new file mode 120000 index 0000000000..6ac62308cf --- /dev/null +++ b/Lang/VBScript/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Ordered-words b/Lang/VBScript/Ordered-words new file mode 120000 index 0000000000..b9e2ffd75d --- /dev/null +++ b/Lang/VBScript/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Parse-an-IP-Address b/Lang/VBScript/Parse-an-IP-Address new file mode 120000 index 0000000000..cde9a031f3 --- /dev/null +++ b/Lang/VBScript/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Pascals-triangle b/Lang/VBScript/Pascals-triangle new file mode 120000 index 0000000000..b7f3c5adf8 --- /dev/null +++ b/Lang/VBScript/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Perfect-numbers b/Lang/VBScript/Perfect-numbers new file mode 120000 index 0000000000..4808051273 --- /dev/null +++ b/Lang/VBScript/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Pernicious-numbers b/Lang/VBScript/Pernicious-numbers new file mode 120000 index 0000000000..108e0a4b75 --- /dev/null +++ b/Lang/VBScript/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Phrase-reversals b/Lang/VBScript/Phrase-reversals new file mode 120000 index 0000000000..dab8b00e33 --- /dev/null +++ b/Lang/VBScript/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Pick-random-element b/Lang/VBScript/Pick-random-element new file mode 120000 index 0000000000..092a231450 --- /dev/null +++ b/Lang/VBScript/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Power-set b/Lang/VBScript/Power-set new file mode 120000 index 0000000000..3c3330c83b --- /dev/null +++ b/Lang/VBScript/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Price-fraction b/Lang/VBScript/Price-fraction new file mode 120000 index 0000000000..e4a1c759e4 --- /dev/null +++ b/Lang/VBScript/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Primality-by-trial-division b/Lang/VBScript/Primality-by-trial-division new file mode 120000 index 0000000000..1f54b54e63 --- /dev/null +++ b/Lang/VBScript/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Prime-decomposition b/Lang/VBScript/Prime-decomposition new file mode 120000 index 0000000000..b624fc459b --- /dev/null +++ b/Lang/VBScript/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Probabilistic-choice b/Lang/VBScript/Probabilistic-choice new file mode 120000 index 0000000000..1dcd8ba183 --- /dev/null +++ b/Lang/VBScript/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Pythagorean-triples b/Lang/VBScript/Pythagorean-triples new file mode 120000 index 0000000000..285e5f1b31 --- /dev/null +++ b/Lang/VBScript/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Range-extraction b/Lang/VBScript/Range-extraction new file mode 120000 index 0000000000..7b7b825586 --- /dev/null +++ b/Lang/VBScript/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Read-a-configuration-file b/Lang/VBScript/Read-a-configuration-file new file mode 120000 index 0000000000..8ec26acb80 --- /dev/null +++ b/Lang/VBScript/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Read-a-file-line-by-line b/Lang/VBScript/Read-a-file-line-by-line new file mode 120000 index 0000000000..fd1a460d7a --- /dev/null +++ b/Lang/VBScript/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Read-a-specific-line-from-a-file b/Lang/VBScript/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..e67641a670 --- /dev/null +++ b/Lang/VBScript/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Regular-expressions b/Lang/VBScript/Regular-expressions new file mode 120000 index 0000000000..b7db288d8a --- /dev/null +++ b/Lang/VBScript/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Remove-duplicate-elements b/Lang/VBScript/Remove-duplicate-elements new file mode 120000 index 0000000000..651548212b --- /dev/null +++ b/Lang/VBScript/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Remove-lines-from-a-file b/Lang/VBScript/Remove-lines-from-a-file new file mode 120000 index 0000000000..96e2363832 --- /dev/null +++ b/Lang/VBScript/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Rep-string b/Lang/VBScript/Rep-string new file mode 120000 index 0000000000..3ca0196437 --- /dev/null +++ b/Lang/VBScript/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/VBScript \ No newline at end of file diff --git a/Lang/VBScript/SEDOLs b/Lang/VBScript/SEDOLs new file mode 120000 index 0000000000..fb6261cca6 --- /dev/null +++ b/Lang/VBScript/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Search-a-list b/Lang/VBScript/Search-a-list new file mode 120000 index 0000000000..8088dcee30 --- /dev/null +++ b/Lang/VBScript/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Self-describing-numbers b/Lang/VBScript/Self-describing-numbers new file mode 120000 index 0000000000..a0faf7ba19 --- /dev/null +++ b/Lang/VBScript/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Semordnilap b/Lang/VBScript/Semordnilap new file mode 120000 index 0000000000..c02e52b064 --- /dev/null +++ b/Lang/VBScript/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Send-email b/Lang/VBScript/Send-email new file mode 120000 index 0000000000..29b986ec58 --- /dev/null +++ b/Lang/VBScript/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sierpinski-triangle b/Lang/VBScript/Sierpinski-triangle new file mode 120000 index 0000000000..7805543b7b --- /dev/null +++ b/Lang/VBScript/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sorting-algorithms-Quicksort b/Lang/VBScript/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..e4223c804c --- /dev/null +++ b/Lang/VBScript/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sorting-algorithms-Selection-sort b/Lang/VBScript/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..e0f77774c9 --- /dev/null +++ b/Lang/VBScript/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Spiral-matrix b/Lang/VBScript/Spiral-matrix new file mode 120000 index 0000000000..9fcf3aee19 --- /dev/null +++ b/Lang/VBScript/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Standard-deviation b/Lang/VBScript/Standard-deviation new file mode 120000 index 0000000000..dcb31fb0c1 --- /dev/null +++ b/Lang/VBScript/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/VBScript \ No newline at end of file diff --git a/Lang/VBScript/String-append b/Lang/VBScript/String-append new file mode 120000 index 0000000000..644eb5b606 --- /dev/null +++ b/Lang/VBScript/String-append @@ -0,0 +1 @@ +../../Task/String-append/VBScript \ No newline at end of file diff --git a/Lang/VBScript/String-matching b/Lang/VBScript/String-matching new file mode 120000 index 0000000000..1320164ae6 --- /dev/null +++ b/Lang/VBScript/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/VBScript \ No newline at end of file diff --git a/Lang/VBScript/String-prepend b/Lang/VBScript/String-prepend new file mode 120000 index 0000000000..a86ed51f8a --- /dev/null +++ b/Lang/VBScript/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Strip-a-set-of-characters-from-a-string b/Lang/VBScript/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..1b02e917aa --- /dev/null +++ b/Lang/VBScript/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Strip-comments-from-a-string b/Lang/VBScript/Strip-comments-from-a-string new file mode 120000 index 0000000000..77f7b35c8a --- /dev/null +++ b/Lang/VBScript/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Strip-control-codes-and-extended-characters-from-a-string b/Lang/VBScript/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..80ebff19ef --- /dev/null +++ b/Lang/VBScript/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Strip-whitespace-from-a-string-Top-and-tail b/Lang/VBScript/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..3af6afd55e --- /dev/null +++ b/Lang/VBScript/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Substring-Top-and-tail b/Lang/VBScript/Substring-Top-and-tail new file mode 120000 index 0000000000..ced40401d0 --- /dev/null +++ b/Lang/VBScript/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sum-and-product-of-an-array b/Lang/VBScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..a4120e1ebb --- /dev/null +++ b/Lang/VBScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sum-multiples-of-3-and-5 b/Lang/VBScript/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..162cf3ca09 --- /dev/null +++ b/Lang/VBScript/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sum-of-squares b/Lang/VBScript/Sum-of-squares new file mode 120000 index 0000000000..1017fddf36 --- /dev/null +++ b/Lang/VBScript/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Temperature-conversion b/Lang/VBScript/Temperature-conversion new file mode 120000 index 0000000000..0537b5093d --- /dev/null +++ b/Lang/VBScript/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Text-processing-1 b/Lang/VBScript/Text-processing-1 new file mode 120000 index 0000000000..0016a994c7 --- /dev/null +++ b/Lang/VBScript/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Text-processing-2 b/Lang/VBScript/Text-processing-2 new file mode 120000 index 0000000000..7569d59af7 --- /dev/null +++ b/Lang/VBScript/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/VBScript \ No newline at end of file diff --git a/Lang/VBScript/The-Twelve-Days-of-Christmas b/Lang/VBScript/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..bf9622c0c8 --- /dev/null +++ b/Lang/VBScript/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Towers-of-Hanoi b/Lang/VBScript/Towers-of-Hanoi new file mode 120000 index 0000000000..67c73febf7 --- /dev/null +++ b/Lang/VBScript/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Trabb-Pardo-Knuth-algorithm b/Lang/VBScript/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..a21c6d8469 --- /dev/null +++ b/Lang/VBScript/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Truncatable-primes b/Lang/VBScript/Truncatable-primes new file mode 120000 index 0000000000..920cefbfb4 --- /dev/null +++ b/Lang/VBScript/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Truncate-a-file b/Lang/VBScript/Truncate-a-file new file mode 120000 index 0000000000..3e279816ae --- /dev/null +++ b/Lang/VBScript/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Ulam-spiral--for-primes- b/Lang/VBScript/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..df12d063d2 --- /dev/null +++ b/Lang/VBScript/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Update-a-configuration-file b/Lang/VBScript/Update-a-configuration-file new file mode 120000 index 0000000000..d23b47b5fd --- /dev/null +++ b/Lang/VBScript/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Vigen-re-cipher b/Lang/VBScript/Vigen-re-cipher new file mode 120000 index 0000000000..a46622066a --- /dev/null +++ b/Lang/VBScript/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Walk-a-directory-Non-recursively b/Lang/VBScript/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..2e64095583 --- /dev/null +++ b/Lang/VBScript/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Web-scraping b/Lang/VBScript/Web-scraping new file mode 120000 index 0000000000..ebeed50097 --- /dev/null +++ b/Lang/VBScript/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Word-wrap b/Lang/VBScript/Word-wrap new file mode 120000 index 0000000000..69ecc9e5f5 --- /dev/null +++ b/Lang/VBScript/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Write-to-Windows-event-log b/Lang/VBScript/Write-to-Windows-event-log new file mode 120000 index 0000000000..28fdba32cf --- /dev/null +++ b/Lang/VBScript/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/VBScript \ No newline at end of file diff --git a/Lang/VBScript/XML-XPath b/Lang/VBScript/XML-XPath new file mode 120000 index 0000000000..0e83929c62 --- /dev/null +++ b/Lang/VBScript/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Zeckendorf-number-representation b/Lang/VBScript/Zeckendorf-number-representation new file mode 120000 index 0000000000..af8d5ffc7b --- /dev/null +++ b/Lang/VBScript/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Zero-to-the-zero-power b/Lang/VBScript/Zero-to-the-zero-power new file mode 120000 index 0000000000..376dc7bade --- /dev/null +++ b/Lang/VBScript/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Zig-zag-matrix b/Lang/VBScript/Zig-zag-matrix new file mode 120000 index 0000000000..29266f39bb --- /dev/null +++ b/Lang/VBScript/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/VBScript \ No newline at end of file diff --git a/Lang/Verilog/A+B b/Lang/Verilog/A+B new file mode 120000 index 0000000000..6fdcc5fd91 --- /dev/null +++ b/Lang/Verilog/A+B @@ -0,0 +1 @@ +../../Task/A+B/Verilog \ No newline at end of file diff --git a/Lang/Verilog/Four-bit-adder b/Lang/Verilog/Four-bit-adder new file mode 120000 index 0000000000..ae6d75cc03 --- /dev/null +++ b/Lang/Verilog/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Verilog \ No newline at end of file diff --git a/Lang/Vim-Script/Y-combinator b/Lang/Vim-Script/Y-combinator new file mode 120000 index 0000000000..c4a2606624 --- /dev/null +++ b/Lang/Vim-Script/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Vim-Script \ No newline at end of file diff --git a/Lang/Visual-Basic/Factors-of-a-Mersenne-number b/Lang/Visual-Basic/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..ad241ae154 --- /dev/null +++ b/Lang/Visual-Basic/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Function-definition b/Lang/Visual-Basic/Function-definition new file mode 120000 index 0000000000..2e6691189e --- /dev/null +++ b/Lang/Visual-Basic/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Terminal-control-Dimensions b/Lang/Visual-Basic/Terminal-control-Dimensions new file mode 120000 index 0000000000..905da4552c --- /dev/null +++ b/Lang/Visual-Basic/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Prolog/FizzBuzz b/Lang/Visual-Prolog/FizzBuzz new file mode 120000 index 0000000000..ebfd9dc9c2 --- /dev/null +++ b/Lang/Visual-Prolog/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Visual-Prolog \ No newline at end of file diff --git a/Lang/Whitespace/00DESCRIPTION b/Lang/Whitespace/00DESCRIPTION index a85f14cdf9..6d27343d2b 100644 --- a/Lang/Whitespace/00DESCRIPTION +++ b/Lang/Whitespace/00DESCRIPTION @@ -5,4 +5,6 @@ |hopl=no |LCT=no }} -Whitespace is a language in which non whitespace characters are ignored; only spaces, tabs and newlines are considered syntax. \ No newline at end of file +Whitespace is a language in which non whitespace characters are ignored; only spaces, tabs and newlines are considered syntax. + +[[Category:Esoteric_Languages]] \ No newline at end of file diff --git a/Lang/X86-Assembly/Guess-the-number b/Lang/X86-Assembly/Guess-the-number new file mode 120000 index 0000000000..898c696ff0 --- /dev/null +++ b/Lang/X86-Assembly/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Linear-congruential-generator b/Lang/X86-Assembly/Linear-congruential-generator new file mode 120000 index 0000000000..be5efd470a --- /dev/null +++ b/Lang/X86-Assembly/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Sierpinski-carpet b/Lang/X86-Assembly/Sierpinski-carpet new file mode 120000 index 0000000000..17302e5a54 --- /dev/null +++ b/Lang/X86-Assembly/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/X86-Assembly \ No newline at end of file diff --git a/Lang/XSLT/99-Bottles-of-Beer b/Lang/XSLT/99-Bottles-of-Beer new file mode 120000 index 0000000000..fb3915f739 --- /dev/null +++ b/Lang/XSLT/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Execute-HQ9+ b/Lang/XSLT/Execute-HQ9+ new file mode 120000 index 0000000000..01a54ed39b --- /dev/null +++ b/Lang/XSLT/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Knights-tour b/Lang/XSLT/Knights-tour new file mode 120000 index 0000000000..77a22fef0a --- /dev/null +++ b/Lang/XSLT/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/XSLT \ No newline at end of file diff --git a/Lang/Z80-Assembly/Greatest-common-divisor b/Lang/Z80-Assembly/Greatest-common-divisor new file mode 120000 index 0000000000..964e041970 --- /dev/null +++ b/Lang/Z80-Assembly/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Z80-Assembly \ No newline at end of file diff --git a/Lang/Z80-Assembly/Loops-For b/Lang/Z80-Assembly/Loops-For new file mode 120000 index 0000000000..1898cb1147 --- /dev/null +++ b/Lang/Z80-Assembly/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Z80-Assembly \ No newline at end of file diff --git a/Task/100-doors/00DESCRIPTION b/Task/100-doors/00DESCRIPTION index 930a516fe1..dbb453f3dd 100644 --- a/Task/100-doors/00DESCRIPTION +++ b/Task/100-doors/00DESCRIPTION @@ -3,7 +3,7 @@ You make 100 [[task feature::Rosetta Code:multiple passes|passes]] by the doors. The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it). The second time you only visit every 2nd door (door #2, #4, #6, ...). The third time, every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door. -Question: What state are the doors in after the last pass? Which are open, which are closed? [http://www.techinterview.org/Puzzles/fog0000000079.html] +Question: What state are the doors in after the last pass? Which are open, which are closed? '''[[task feature::Rosetta Code:extra credit|Alternate]]:''' As noted in this page's [[Talk:100 doors|discussion page]], the only doors that remain open are whose numbers are perfect squares of integers. diff --git a/Task/100-doors/360-Assembly/100-doors.360 b/Task/100-doors/360-Assembly/100-doors.360 new file mode 100644 index 0000000000..b35318ac3f --- /dev/null +++ b/Task/100-doors/360-Assembly/100-doors.360 @@ -0,0 +1,38 @@ +* 100 doors 13/08/2015 +HUNDOOR CSECT + USING HUNDOOR,R12 + LR R12,R15 + LA R6,0 + LA R8,1 step 1 + LA R9,100 +LOOPI BXH R6,R8,ELOOPI do ipass=1 to 100 (R6) + LR R7,R6 + SR R7,R6 + LR R10,R6 step ipass + LA R11,100 +LOOPJ BXH R7,R10,ELOOPJ do idoor=ipass to 100 by ipass (R7) + LA R5,DOORS-1 + AR R5,R7 + XI 0(R5),X'01' doors(idoor)=not(doors(idoor)) +NEXTJ B LOOPJ +ELOOPJ B LOOPI +ELOOPI LA R10,BUFFER R10 address of the buffer + LA R5,DOORS R5 address of doors item + LA R6,1 idoor=1 (R6) + LA R9,100 loop counter +LOOPN CLI 0(R5),X'01' if doors(idoor)=1 + BNE NEXTN + XDECO R6,XDEC idoor to decimal + MVC 0(4,R10),XDEC+8 move decimal to buffer + LA R10,4(R10) +NEXTN LA R6,1(R6) idoor=idoor+1 + LA R5,1(R5) + BCT R9,LOOPN loop +ELOOPN XPRNT BUFFER,80 +RETURN XR R15,R15 + BR R14 +DOORS DC 100X'00' +BUFFER DC CL80' ' +XDEC DS CL12 + YREGS + END HUNDOOR diff --git a/Task/100-doors/ALGOL-W/100-doors.alg b/Task/100-doors/ALGOL-W/100-doors.alg new file mode 100644 index 0000000000..047ec93a35 --- /dev/null +++ b/Task/100-doors/ALGOL-W/100-doors.alg @@ -0,0 +1,32 @@ +begin + % find the first few squares via the unoptimised door flipping method % + + integer doorMax; + doorMax := 100; + + begin + % need to start a new block so the array can have variable bounds % + + % array of doors - door( i ) is true if open, false if closed % + logical array door( 1 :: doorMax ); + + % set all doors to closed % + for i := 1 until doorMax do door( i ) := false; + + % repeatedly flip the doors % + for i := 1 until doorMax + do begin + for j := i step j until doorMax + do begin + door( j ) := not door( j ) + end + end; + + % display the results % + i_w := 1; % set integer field width % + s_w := 1; % and separator width % + for i := 1 until doorMax do if door( i ) then writeon( i ) + + end + +end. diff --git a/Task/100-doors/APL/100-doors.apl b/Task/100-doors/APL/100-doors.apl new file mode 100644 index 0000000000..84d670d4d8 --- /dev/null +++ b/Task/100-doors/APL/100-doors.apl @@ -0,0 +1,2 @@ +doors←{100⍴((⍵-1)⍴0),1} +≠⌿⊃doors¨ ⍳100 diff --git a/Task/100-doors/Befunge/100-doors-1.bf b/Task/100-doors/Befunge/100-doors-1.bf new file mode 100644 index 0000000000..7f06b23d19 --- /dev/null +++ b/Task/100-doors/Befunge/100-doors-1.bf @@ -0,0 +1,3 @@ +>"d">:00p1-:>:::9%\9/9+g2%!\:9v +$.v_^#!$::$_^#`"c":+g00p+9/9\%< +::<_@#`$:\*:+55:+1p27g1g+9/9\%9 diff --git a/Task/100-doors/Befunge/100-doors-2.bf b/Task/100-doors/Befunge/100-doors-2.bf new file mode 100644 index 0000000000..0827813833 --- /dev/null +++ b/Task/100-doors/Befunge/100-doors-2.bf @@ -0,0 +1 @@ +1+:::*.9`#@_ diff --git a/Task/100-doors/Befunge/100-doors.bf b/Task/100-doors/Befunge/100-doors-3.bf similarity index 100% rename from Task/100-doors/Befunge/100-doors.bf rename to Task/100-doors/Befunge/100-doors-3.bf diff --git a/Task/100-doors/Cache-ObjectScript/100-doors-1.cos b/Task/100-doors/Cache-ObjectScript/100-doors-1.cos new file mode 100644 index 0000000000..b7a0bd7cd3 --- /dev/null +++ b/Task/100-doors/Cache-ObjectScript/100-doors-1.cos @@ -0,0 +1,12 @@ + for i=1:1:100 { + set doors(i) = 0 + } + for i=1:1:100 { + for door=i:i:100 { + Set doors(door)='doors(door) + } + } + for i = 1:1:100 + { + if doors(i)=1 write i_": open",! + } diff --git a/Task/100-doors/Cache-ObjectScript/100-doors-2.cos b/Task/100-doors/Cache-ObjectScript/100-doors-2.cos new file mode 100644 index 0000000000..a35a76906d --- /dev/null +++ b/Task/100-doors/Cache-ObjectScript/100-doors-2.cos @@ -0,0 +1,10 @@ +1: open +4: open +9: open +16: open +25: open +36: open +49: open +64: open +81: open +100: open diff --git a/Task/100-doors/Clojure/100-doors-3.clj b/Task/100-doors/Clojure/100-doors-3.clj index 0ef6ba4ae7..63f5be1883 100644 --- a/Task/100-doors/Clojure/100-doors-3.clj +++ b/Task/100-doors/Clojure/100-doors-3.clj @@ -1,9 +1,9 @@ -(defn doors [] - (reduce (fn [doors idx] (assoc doors idx true)) - (into [] (repeat 100 false)) - (map #(dec (* % %)) (range 1 11)))) - -(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n)) +(defn open-doors [] + (->> (for [step (range 1 101), occ (range step 101 step)] occ) + frequencies + (filter (comp odd? val)) + (map first) + sort)) (defn print-open-doors [] (println diff --git a/Task/100-doors/Clojure/100-doors-4.clj b/Task/100-doors/Clojure/100-doors-4.clj new file mode 100644 index 0000000000..0ef6ba4ae7 --- /dev/null +++ b/Task/100-doors/Clojure/100-doors-4.clj @@ -0,0 +1,11 @@ +(defn doors [] + (reduce (fn [doors idx] (assoc doors idx true)) + (into [] (repeat 100 false)) + (map #(dec (* % %)) (range 1 11)))) + +(defn open-doors [] (for [[d n] (map vector (doors) (iterate inc 1)) :when d] n)) + +(defn print-open-doors [] + (println + "Open doors after 100 passes:" + (apply str (interpose ", " (open-doors))))) diff --git a/Task/100-doors/Clojure/100-doors-5.clj b/Task/100-doors/Clojure/100-doors-5.clj new file mode 100644 index 0000000000..1d289b73fd --- /dev/null +++ b/Task/100-doors/Clojure/100-doors-5.clj @@ -0,0 +1,6 @@ +(defn open-doors [] (->> (iterate inc 1) (map #(* % %)) (take-while #(<= % 100)))) + +(defn print-open-doors [] + (println + "Open doors after 100 passes:" + (apply str (interpose ", " (open-doors))))) diff --git a/Task/100-doors/Common-Lisp/100-doors-2.lisp b/Task/100-doors/Common-Lisp/100-doors-2.lisp index 973d3f0b46..40b440d0cf 100644 --- a/Task/100-doors/Common-Lisp/100-doors-2.lisp +++ b/Task/100-doors/Common-Lisp/100-doors-2.lisp @@ -1,7 +1,7 @@ (define-modify-macro toggle () not) (defun 100-doors () - (let ((doors (make-array 100 :initial-element nil))) + (let ((doors (make-array 100))) (dotimes (i 100) (loop for j from i below 100 by (1+ i) do (toggle (svref doors j)))) diff --git a/Task/100-doors/Common-Lisp/100-doors-3.lisp b/Task/100-doors/Common-Lisp/100-doors-3.lisp index dfec970db4..7d2e52d87e 100644 --- a/Task/100-doors/Common-Lisp/100-doors-3.lisp +++ b/Task/100-doors/Common-Lisp/100-doors-3.lisp @@ -1,23 +1,13 @@ -(defun perfect-square-list (n) - "Generates a list of perfect squares from 0 up to n" - (loop for i from 1 to (isqrt n) collect (expt i 2))) - -(defun print-doors (doors) - "Pretty prints the doors list" - (format T "~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%" doors)) - -(defun open-door (doors num open) - "Sets door at num to open" - (setf (nth (- num 1) doors) open)) - -(defun visit-all (doors vlist open) - "Visits and opens all the doors indicated in vlist" - (dolist (dn vlist doors) - (open-door doors dn open))) - -(defun start2 (&optional (size 100)) - "Start the program" - (print-doors - (visit-all (make-list size :initial-element '\#) - (perfect-square-list size) - '_))) +(defun toggle (w m z) + (loop for a in w for n from 1 to z + collect (if (zerop (mod n m)) (not a) a))) + +(defun doors (z &optional (w (make-list z)) (n 1)) + (if (> n z) w (doors z (toggle w n z) (1+ n)))) + +> (doors 100) +(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL + NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL + NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL + NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T + NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T) diff --git a/Task/100-doors/Common-Lisp/100-doors-4.lisp b/Task/100-doors/Common-Lisp/100-doors-4.lisp index b791c006f2..e10efb7d66 100644 --- a/Task/100-doors/Common-Lisp/100-doors-4.lisp +++ b/Task/100-doors/Common-Lisp/100-doors-4.lisp @@ -1,5 +1,6 @@ -(let ((i 0)) - (mapcar (lambda (x) - (if (zerop (mod (sqrt (incf i)) 1)) - "_" "#")) - (make-list 100))) +(defun 100-doors () + (let ((doors (make-array 100))) + (dotimes (i 10) + (setf (svref doors (* i i)) t)) + (dotimes (i 100) + (format t "door ~a: ~:[closed~;open~]~%" (1+ i) (svref doors i))))) diff --git a/Task/100-doors/Common-Lisp/100-doors-5.lisp b/Task/100-doors/Common-Lisp/100-doors-5.lisp new file mode 100644 index 0000000000..dfec970db4 --- /dev/null +++ b/Task/100-doors/Common-Lisp/100-doors-5.lisp @@ -0,0 +1,23 @@ +(defun perfect-square-list (n) + "Generates a list of perfect squares from 0 up to n" + (loop for i from 1 to (isqrt n) collect (expt i 2))) + +(defun print-doors (doors) + "Pretty prints the doors list" + (format T "~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%" doors)) + +(defun open-door (doors num open) + "Sets door at num to open" + (setf (nth (- num 1) doors) open)) + +(defun visit-all (doors vlist open) + "Visits and opens all the doors indicated in vlist" + (dolist (dn vlist doors) + (open-door doors dn open))) + +(defun start2 (&optional (size 100)) + "Start the program" + (print-doors + (visit-all (make-list size :initial-element '\#) + (perfect-square-list size) + '_))) diff --git a/Task/100-doors/Common-Lisp/100-doors-6.lisp b/Task/100-doors/Common-Lisp/100-doors-6.lisp new file mode 100644 index 0000000000..b791c006f2 --- /dev/null +++ b/Task/100-doors/Common-Lisp/100-doors-6.lisp @@ -0,0 +1,5 @@ +(let ((i 0)) + (mapcar (lambda (x) + (if (zerop (mod (sqrt (incf i)) 1)) + "_" "#")) + (make-list 100))) diff --git a/Task/100-doors/Eiffel/100-doors-1.e b/Task/100-doors/Eiffel/100-doors-1.e index d3e090614a..3284376ef2 100644 --- a/Task/100-doors/Eiffel/100-doors-1.e +++ b/Task/100-doors/Eiffel/100-doors-1.e @@ -1,7 +1,7 @@ note description: "100 Doors problem" - date: "07-AUG-2011" - revision: "1.0" + date: "08-JUL-2015" + revision: "1.1" class APPLICATION @@ -11,54 +11,82 @@ create feature {NONE} -- Initialization - doors: LINKED_LIST [DOOR] - -- A set of doors - once - create Result.make + make + -- Main application routine. + do + initialize_closed_doors + toggle_doors + output_door_states end - make - -- Run application. - local - count, i: INTEGER +feature -- Access + + doors: ARRAYED_LIST [DOOR] + -- A set of doors (self-initialized to capacity of `max_door_count'). + attribute + create Result.make (max_door_count) + end + +feature -- Basic Operations + + initialize_closed_doors + -- Initialize all `doors'. do - --initialize doors - count := 100 - from - i := 1 - until - i > count - loop - doors.extend (create {DOOR}.make (i, false)) - i := i + 1 + across min_door_count |..| max_door_count as ic_address_list loop + doors.extend (create {DOOR}.make_closed (ic_address_list.item)) end + ensure + has_all_closed_doors: across doors as ic_doors_list all not ic_doors_list.item.is_open end + end - -- toggle doors - from - i := 1 - until - i > count - loop - across - doors as this - loop - if this.item.address \\ i = 0 then - this.item.open := not this.item.open - end - end -- across doors - i := i + 1 - end -- for i - - -- print results - doors.do_all (agent (door: DOOR) - do - if door.open then - io.put_string ("Door " + door.address.out + " is open.") - elseif not door.open then - io.put_string ("Door " + door.address.out + " is closed.") + toggle_doors + -- Toggle all `doors'. + do + across min_door_count |..| max_door_count as ic_addresses_list loop + across doors as ic_doors_list loop + if is_door_to_toggle (ic_doors_list.item.address, ic_addresses_list.item) then + ic_doors_list.item.toggle_door end - io.put_new_line - end) - end -- make + end + end + end + + output_door_states + -- Output the state of all `doors'. + do + doors.do_all (agent door_state_out) + end + +feature -- Status Report + + is_door_to_toggle (a_door_address, a_index_address: like {DOOR}.address): BOOLEAN + -- Is the door at `a_door_address' needing to be toggled, when compared to `a_index_address'? + do + Result := a_door_address \\ a_index_address = 0 + ensure + only_modulus_zero: Result = (a_door_address \\ a_index_address = 0) + end + +feature -- Outputs + + door_state_out (a_door: DOOR) + -- Output the state of `a_door'. + do + print ("Door " + a_door.address.out + " is ") + if a_door.is_open then + print ("open.") + else + print ("closed.") + end + io.new_line + end + +feature {DOOR} -- Constants + + min_door_count: INTEGER = 1 + -- Minimum number of doors. + + max_door_count: INTEGER = 100 + -- Maximum number of doors. -end -- APPLICATION +end diff --git a/Task/100-doors/Eiffel/100-doors-2.e b/Task/100-doors/Eiffel/100-doors-2.e index b009c03553..95f6f09b26 100644 --- a/Task/100-doors/Eiffel/100-doors-2.e +++ b/Task/100-doors/Eiffel/100-doors-2.e @@ -1,44 +1,77 @@ note description: "A door with an address and an open or closed state." - date: "07-AUG-2011" - revision: "1.0" + date: "08-JUL-2015" + revision: "1.1" class DOOR create + make_closed, make -feature -- initialization +feature {NONE} -- initialization - make (addr: INTEGER; status: BOOLEAN) - -- create door with address and status + make_closed (a_address: INTEGER) + -- Initialize Current {DOOR} at `a_address' and state of `Is_closed'. require - valid_address: addr /= '%U' - valid_status: status /= '%U' + positive: a_address >= {APPLICATION}.min_door_count and a_address >= Min_door_count do - address := addr - open := status + make (a_address, Is_closed) ensure - address_set: address = addr - status_set: open = status + closed: is_open = Is_closed + end + + make (a_address: INTEGER; a_status: BOOLEAN) + -- Initialize Current {DOOR} with `a_address' and `a_status', denoting position and `is_open' or `Is_closed'. + require + positive: a_address >= {APPLICATION}.min_door_count and a_address >= Min_door_count + do + address := a_address + is_open := a_status + ensure + address_set: address = a_address + status_set: is_open = a_status end feature -- access address: INTEGER + -- `address' of Current {DOOR}. - open: BOOLEAN assign set_open + is_open: BOOLEAN assign set_open + -- `is_open' (or not) status of Current {DOOR}. -feature -- mutators +feature -- Setters - set_open (status: BOOLEAN) - require - valid_status: status /= '%U' + set_open (a_status: BOOLEAN) + -- Set `status' with `a_status' do - open := status + is_open := a_status ensure - open_updated: open = status + open_updated: is_open = a_status end +feature {APPLICATION} -- Basic Operations + + toggle_door + -- Toggle Current {DOOR} from `is_open' to not `is_open'. + do + is_open := not is_open + ensure + toggled: is_open /= old is_open + end + +feature {NONE} -- Implementation: Constants + + Is_closed: BOOLEAN = False + -- State of being not `is_open'. + + Min_door_count: INTEGER = 1 + -- Minimum door count. + +invariant + one_or_more: address >= 1 + consistency: is_open implies not Is_closed + end diff --git a/Task/100-doors/Elena/100-doors.elena b/Task/100-doors/Elena/100-doors.elena new file mode 100644 index 0000000000..9affe761fe --- /dev/null +++ b/Task/100-doors/Elena/100-doors.elena @@ -0,0 +1,21 @@ +#define system. +#define system'routines. +#define extensions. + +#symbol program= +[ + #var Doors := Array new:100 set &every: (&index:n) [ false ]. + + 0 till:100 &doEach: i + [ + i till:100 &by:(i + 1) &doEach: j + [ + Doors@j := Doors@j not. + ]. + ]. + + 0 till:100 &doEach: i + [ + console writeLine:"Door #":(i + 1):" :":(Doors@i iif:"Open":"Closed"). + ]. +]. diff --git a/Task/100-doors/GW-BASIC/100-doors.gw-basic b/Task/100-doors/GW-BASIC/100-doors.gw-basic new file mode 100644 index 0000000000..cc17a68ae0 --- /dev/null +++ b/Task/100-doors/GW-BASIC/100-doors.gw-basic @@ -0,0 +1,10 @@ +10 DIM A(100) +20 FOR OFFSET = 1 TO 100 +30 FOR I = 0 TO 100 STEP OFFSET +40 A(I) = A(I) + 1 +50 NEXT I +60 NEXT OFFSET +70 ' Print "opened" doors +80 FOR I = 1 TO 100 +90 IF A(I) MOD 2 = 1 THEN PRINT I +100 NEXT I diff --git a/Task/100-doors/Julia/100-doors-1.julia b/Task/100-doors/Julia/100-doors-1.julia index 35148bded1..6a4b4a18ee 100644 --- a/Task/100-doors/Julia/100-doors-1.julia +++ b/Task/100-doors/Julia/100-doors-1.julia @@ -3,5 +3,5 @@ for a = 1:100, b in a:a:100 doors[b] = !doors[b] end for a = 1:100 - println("Door $a is " * (doors[a] ? "open" : "close")) + println("Door $a is " * (doors[a] ? "open." : "closed.")) end diff --git a/Task/100-doors/Julia/100-doors-2.julia b/Task/100-doors/Julia/100-doors-2.julia index 4da27443f8..c0aa20d831 100644 --- a/Task/100-doors/Julia/100-doors-2.julia +++ b/Task/100-doors/Julia/100-doors-2.julia @@ -1 +1 @@ -for i = 1:10 println("Door $(i^2) is open") end +for i = 1:10 println("Door $(i^2) is open.") end diff --git a/Task/100-doors/NetRexx/100-doors-1.netrexx b/Task/100-doors/NetRexx/100-doors-1.netrexx index b70175888a..b479628cc0 100644 --- a/Task/100-doors/NetRexx/100-doors-1.netrexx +++ b/Task/100-doors/NetRexx/100-doors-1.netrexx @@ -1,5 +1,5 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols binary +options replace format comments java crossref symbols binary True = Rexx(1 == 1) False = Rexx(\True) diff --git a/Task/100-doors/NetRexx/100-doors-2.netrexx b/Task/100-doors/NetRexx/100-doors-2.netrexx index 6cf57a1565..9c2e357805 100644 --- a/Task/100-doors/NetRexx/100-doors-2.netrexx +++ b/Task/100-doors/NetRexx/100-doors-2.netrexx @@ -1,5 +1,5 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols binary +options replace format comments java crossref symbols binary True = (1 == 1) False = \True diff --git a/Task/100-doors/Perl-6/100-doors-1.pl6 b/Task/100-doors/Perl-6/100-doors-1.pl6 index 39431637ce..b005f4d7cc 100644 --- a/Task/100-doors/Perl-6/100-doors-1.pl6 +++ b/Task/100-doors/Perl-6/100-doors-1.pl6 @@ -1,5 +1,5 @@ my @doors = False xx 101; -($_ = !$_ for @doors[0, * + $_ ...^ * > 100]) for 1..100; +(.=not for @doors[0, $_ ... 100]) for 1..100; say "Door $_ is ", [ @doors[$_] ] for 1..100; diff --git a/Task/100-doors/Rust/100-doors-1.rust b/Task/100-doors/Rust/100-doors-1.rust index 5f84be178f..64414e1adc 100644 --- a/Task/100-doors/Rust/100-doors-1.rust +++ b/Task/100-doors/Rust/100-doors-1.rust @@ -1,14 +1,13 @@ -// rust 1.0.0-alpha -#![feature(core)] -use std::iter::{range_step_inclusive}; fn main() { - let mut door_open = [false; 100]; - for pass in (1us..101) { - for door in range_step_inclusive(pass, 100, pass) { - door_open[door - 1] = !door_open[door - 1]; + let mut door_open = [false; 100]; + for pass in (1..101) { + let mut door = pass; + while door <= 100 { + door_open[door - 1] = !door_open[door - 1]; + door += pass; + } + } + for (i, &is_open) in door_open.iter().enumerate() { + println!("Door {} is {}.", i + 1, if is_open {"open"} else {"closed"}); } - } - for (i, state) in door_open.iter().enumerate() { - println!("Door {} is {}.", i + 1, if *state {"open"} else {"closed"}); - } } diff --git a/Task/100-doors/Rust/100-doors-2.rust b/Task/100-doors/Rust/100-doors-2.rust index 032c9a25aa..1a5371ce3a 100644 --- a/Task/100-doors/Rust/100-doors-2.rust +++ b/Task/100-doors/Rust/100-doors-2.rust @@ -1,9 +1,9 @@ -// rust 0.8 - fn main() { - for i in std::iter::range_inclusive(1,100) { - let x = (i as f64).pow(&0.5); - let state = if x == x.round() {"open"} else {"closed"}; - println!("Door {} is {}", i, state); - } + let squares: Vec<_> = (1..10+1).map(|n| n*n).collect(); + let is_square = |num| squares.binary_search(&num).is_ok(); + + for i in 1..100+1 { + let state = if is_square(i) {"open"} else {"closed"}; + println!("Door {} is {}", i, state); + } } diff --git a/Task/24-game/Batch-File/24-game.bat b/Task/24-game/Batch-File/24-game.bat index d3ff85cd53..41dad929ea 100644 --- a/Task/24-game/Batch-File/24-game.bat +++ b/Task/24-game/Batch-File/24-game.bat @@ -1,83 +1,150 @@ -@echo off +@set @dummy=0 /* + ::24.bat :: ::Batch file implemetnation of the 24 Game where a player is given four random ::digits n, where 1 <= n <= 9, and needs to provide a simple arithmetic ::operation that does evaluate to 24. :: -::Note: [1]This implementation does not evaluate brackets -:: [2]This implementation does not keep remainders since batch language -:: has no support for floating point calculations +::Please open the Batch File Directly to play... + +@echo off +setlocal enabledelayedexpansion +title The 24 Game Batch File cls +echo. echo The 24 Game echo. echo Given four digits, provide a simple arithmetic expression echo that evaluates to 24 using +,-,*,/. echo. -echo Enter 'SHOW' to show the digits or 'EXIT' to end the game. +echo Reminders (Please read): echo. +echo 1. Type 'new' (NO quotes) - Fresh digits +echo 2. Type 'show' (NO quotes) - Show digits +echo 3. Type 'exit' (NO quotes) - Quit game +echo 4. Combining two digits as one number is NOT allowed. +echo 5. Use each digit only ONCE in expressions. +echo 6. Use ONLY the Parentheses as the groupting symbols. +echo 7. Do not make any digit Negative. +echo. +echo Why do someone wants to not follow the reminders? To trick me, right? ;) +echo. +pause +:NEW set TRY=0 ::Get four random digits -set /a "DIGIT_1=%RANDOM% %%9 + 1" -set /a "DIGIT_2=%RANDOM% %%9 + 1" -set /a "DIGIT_3=%RANDOM% %%9 + 1" -set /a "DIGIT_4=%RANDOM% %%9 + 1" +set /a "DIGIT_1=%RANDOM%%%9+1" +set /a "DIGIT_2=%RANDOM%%%9+1" +set /a "DIGIT_3=%RANDOM%%%9+1" +set /a "DIGIT_4=%RANDOM%%%9+1" +cls +echo. +echo The 24 Game +echo. goto SHOW ::Main Program Loop :MAIN set /a TRY+=1 +set ANSWER= set "TMP_DIGIT_1=%DIGIT_1%" set "TMP_DIGIT_2=%DIGIT_2%" set "TMP_DIGIT_3=%DIGIT_3%" set "TMP_DIGIT_4=%DIGIT_4%" -::Promt for an answer and trim answer string +::Prompt for an answer +echo. set /p ANSWER="Try %TRY%: " -set "ANSWER=%ANSWER: =%" +::Determine if the player inputs a "good" try (input validation...) +if /i "!ANSWER!"=="NEW" goto NEW +if /i "!ANSWER!"=="SHOW" goto SHOW +if /i "!ANSWER!"=="EXIT" goto ABORT -if /i "%ANSWER%"=="SHOW" goto SHOW -if /i "%ANSWER%"=="EXIT" goto ABORT -if "%ANSWER:~6,1%"=="" goto ERROR_MISSING_CHARS: +set ANSWER=!ANSWER: =! +set DIGITS_USED=0&set COUNTER=0 -::Determine if each digits has ben used once in the input equation -set DIGITS_USED=0 -set COUNTER=0 :LOOP -call set CURR_DIGIT=%%ANSWER:~%COUNTER%,1%% -if %CURR_DIGIT%==%TMP_DIGIT_1% (set "TMP_DIGIT_1=" & set /a "DIGITS_USED+=1") -if %CURR_DIGIT%==%TMP_DIGIT_2% (set "TMP_DIGIT_2=" & set /a "DIGITS_USED+=2") -if %CURR_DIGIT%==%TMP_DIGIT_3% (set "TMP_DIGIT_3=" & set /a "DIGITS_USED+=4") -if %CURR_DIGIT%==%TMP_DIGIT_4% (set "TMP_DIGIT_4=" & set /a "DIGITS_USED+=8") -set /a "COUNTER+=2" -if not "%COUNTER%"=="8" goto LOOP -if not "%DIGITS_USED%"=="15" goto ERROR_INCORRECT_INPUT +set CURR_DIGIT=!ANSWER:~%COUNTER%,1! +if "!CURR_DIGIT!"=="%TMP_DIGIT_1%" (set "TMP_DIGIT_1=X"&goto NEXTCHARSCAN1) +if "!CURR_DIGIT!"=="%TMP_DIGIT_2%" (set "TMP_DIGIT_2=X"&goto NEXTCHARSCAN1) +if "!CURR_DIGIT!"=="%TMP_DIGIT_3%" (set "TMP_DIGIT_3=X"&goto NEXTCHARSCAN1) +if "!CURR_DIGIT!"=="%TMP_DIGIT_4%" (set "TMP_DIGIT_4=X"&goto NEXTCHARSCAN1) +if "!CURR_DIGIT!"=="" goto ALMOST +if "!CURR_DIGIT!"==")" goto SCANMORE +if "!CURR_DIGIT!"=="(" goto SCANMORE +if "!CURR_DIGIT!"=="+" goto NEXTCHARSCAN2 +if "!CURR_DIGIT!"=="-" goto DONTALLOWNEGATIVES +if "!CURR_DIGIT!"=="*" goto NEXTCHARSCAN2 +if "!CURR_DIGIT!"=="/" goto NEXTCHARSCAN2 +goto ERROR_ICHAR_FOUND -::Calculate and evaluate result -set /a "RESULT=%ANSWER%" -if "%RESULT%"=="24" goto END +:NEXTCHARSCAN1 +set /a NEXT=%COUNTER%+1 +set NEXT_CHAR=!ANSWER:~%NEXT%,1! +for /l %%w in (1,1,9) do ( +if "!NEXT_CHAR!"=="%%w" goto ERROR_POSITION +) +goto :SCANMORE +:DONTALLOWNEGATIVES +set /a NEXT=%COUNTER%-1 +if "%NEXT%"=="-1" goto ERROR_NEGA +set NEXT_CHAR=!ANSWER:~%NEXT%,1! +for /l %%z in (1,1,9) do ( +if "!NEXT_CHAR!"=="%%z" goto NEXTCHARSCAN2 +) +if "!NEXT_CHAR!"=="(" goto ERROR_NEGA +if "!NEXT_CHAR!"==")" goto NEXTCHARSCAN2 +goto ERROR_NEGA +:NEXTCHARSCAN2 +set /a NEXT=%COUNTER%+1 +set NEXT_CHAR=!ANSWER:~%NEXT%,1! +for %%y in (+,-,/) do ( +if "!NEXT_CHAR!"=="%%y" goto ERROR_TRICK +) +:SCANMORE +set /a "COUNTER+=1"&goto LOOP -echo Invalid input [Bad result: Expected 24, Received %RESULT%] -goto MAIN - -:ERROR_MISSING_CHARS -echo Invalid input [insufficient number of characters] -goto MAIN +:ALMOST +if not "%TMP_DIGIT_1%%TMP_DIGIT_2%%TMP_DIGIT_3%%TMP_DIGIT_4%"=="XXXX" goto ERROR_CHARS +::(SIGH) Input passed... Now, calculate and evaluate result +set "RESULT=" +for /f "usebackq delims=" %%x in (`cscript //nologo //e:jscript "%~f0" "%ANSWER%" 2^>nul`) do set RESULT=%%x +::Wait... Input is STILL erroneous??? +if "%RESULT%"=="" goto ERROR_SYNTAX +::YES!!! Correct Expression??? +if "%RESULT%"=="24" goto END -:ERROR_INCORRECT_INPUT -echo Invalid input [incorrect digits] -goto MAIN +::The Outputs +echo Wrong Answer [%RESULT% is not equal to 24.]&goto MAIN +:ERROR_CHARS +echo Invalid input [Please use all the digits above ONCE.]&goto MAIN +:ERROR_ICHAR_FOUND +echo Invalid input [An invalid character is found... C'mon...]&goto MAIN +:ERROR_SYNTAX +echo Invalid input [Syntax Error... Please answer seriously... I'm begging you...]&goto MAIN +:ERROR_POSITION +echo Invalid input [Sorry, digit concatenation is not allowed.]&goto MAIN +:ERROR_TRICK +echo Invalid input [Are you Playing the Game Seriously?]&goto MAIN +:ERROR_NEGA +echo Invalid input [Do not Make any Digit Negative.]&goto MAIN :SHOW -echo Given digits: %DIGIT_1% %DIGIT_2% %DIGIT_3% %DIGIT_4% -goto MAIN - +echo Given digits: %DIGIT_1% %DIGIT_2% %DIGIT_3% %DIGIT_4%&goto MAIN :END -echo Correct input [Congratulations!] - +echo Correct Input [Congratulations^^!] +echo. +echo Press any char key for a new game, or close this window to exit... +pause>nul +goto NEW :ABORT echo. +exit +::*/ + +WScript.echo(eval(WScript.arguments(0))); diff --git a/Task/24-game/Elena/24-game.elena b/Task/24-game/Elena/24-game.elena new file mode 100644 index 0000000000..8c436af44c --- /dev/null +++ b/Task/24-game/Elena/24-game.elena @@ -0,0 +1,173 @@ +#define system. +#define system'routines. +#define system'collections. +#define system'dynamic. +#define extensions. + +#class ExpressionTree +{ + #field theTree. + + #constructor new : aLiteral + [ + #var aLevel := Integer new:0. + + aLiteral run &each: ch + [ + #var node := Dynamic new. + + ch => + #43 ? [ node set &level:(aLevel + 1) set &operation:%add. ] // + + #45 ? [ node set &level:(aLevel + 1) set &operation:%subtract. ] // - + #42 ? [ node set &level:(aLevel + 2) set &operation:%multiply. ] // * + #47 ? [ node set &level:(aLevel + 2) set &operation:%divide. ] // / + #40 ? [ aLevel += 10. ^ $self. ] // ( + #41 ? [ aLevel -= 10. ^ $self. ] // ) + ! [ + node set &leaf:(ch literal toReal) set &level:((aLevel + 3)). + ]. + + ($nil == theTree) + ? [ theTree := node. ] + ! [ + (theTree level >= node level) + ? [ + node set &left:theTree set &right:$nil. + + theTree := node. + ] + ! [ + #var aTop := theTree. + #loop (($nil != aTop right)and:[aTop right level < node level] ) + ? [ aTop := aTop right. ]. + + node set &left:(aTop right) set &right:$nil. + + aTop set &right:node. + ]. + ]. + ]. + ] + + #method eval : aNode + [ + (aNode if &leaf) + ? [ ^ aNode leaf. ] + ! [ + #var aLeft := $self eval:(aNode left). + #var aRight := $self eval:(aNode right). + + ^ aLeft::(aNode operation) eval:aRight. + ] + ] + + #method value + <= eval:theTree. + + #method readLeaves : aList &at:aNode + [ + ($nil == aNode) + ? [ #throw InvalidArgumentException new. ]. + + (aNode if &leaf) + ? [ aList += aNode leaf. ] + ! [ + $self readLeaves:aList &at:(aNode left). + $self readLeaves:aList &at:(aNode right). + ]. + ] + + #method readLeaves : aList + <= readLeaves:aList &at:theTree. +} + +#class TwentyFourGame +{ + #field theNumbers. + + #constructor new + [ + $self newPuzzle. + ] + + #method newPuzzle + [ + theNumbers := ( + 1 + randomGenerator eval:9, + 1 + randomGenerator eval:9, + 1 + randomGenerator eval:9, + 1 + randomGenerator eval:9). + ] + + #method help + [ + console + writeLine:"------------------------------- Instructions ------------------------------" + writeLine:"Four digits will be displayed." + writeLine:"Enter an equation using all of those four digits that evaluates to 24" + writeLine:"Only * / + - operators and () are allowed" + writeLine:"Digits can only be used once, but in any order you need." + writeLine:"Digits cannot be combined - i.e.: 12 + 12 when given 1,2,2,1 is not allowed" + writeLine:"Submit a blank line to skip the current puzzle." + writeLine:"Type 'q' to quit" + writeLine + writeLine:"Example: given 2 3 8 2, answer should resemble 8*3-(2-2)" + writeLine:"------------------------------- --------------------------------------------". + ] + + #method prompt + [ + theNumbers run &each: n [ console writeLiteral:n:" ". ]. + + console write:": ". + ] + + #method resolve : aLine + [ + #var exp := ExpressionTree new:aLine. + + #var Leaves := ArrayList new. + exp readLeaves:Leaves. + + (Leaves ascendant equal &indexable:(theNumbers ascendant)) + ! [ console writeLine:"Invalid input. Enter an equation using all of those four digits. Try again.". ^ $self. ]. + + #var aResult := exp value. + (aResult == 24) + ? [ + console writeLine:"Good work. ":aLine:"=":aResult. + + $self newPuzzle. + ] + ! [ console writeLine:"Incorrect. ":aLine:"=":aResult. ]. + ] +} + +#class(extension) gameOp +{ + #method playRound : aLine + [ + (aLine == "q") + ? [ ^ false. ] + ! [ + (aLine == "") + ? [ console writeLine:"Skipping this puzzle". self newPuzzle. ] + ! [ + self resolve:aLine + | if &Error: e + [ + console writeLine:"An error occurred. Check your input and try again.". + ]. + ]. + + ^ true. + ]. + ] +} + +#symbol program = +[ + #var aGame := TwentyFourGame new help. + + #loop (aGame prompt playRound:(console readLine)) ? []. +]. diff --git a/Task/9-billion-names-of-God-the-integer/Clojure/9-billion-names-of-god-the-integer.clj b/Task/9-billion-names-of-God-the-integer/Clojure/9-billion-names-of-god-the-integer.clj new file mode 100644 index 0000000000..4eea269b70 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Clojure/9-billion-names-of-god-the-integer.clj @@ -0,0 +1,19 @@ +(defn nine-billion-names [row column] + (cond (<= row 0) 0 + (<= column 0) 0 + (< row column) 0 + (= row 1) 1 + :else (let [addend (nine-billion-names (dec row) (dec column)) + augend (nine-billion-names (- row column) column)] + (+ addend augend)))) + +(defn print-row [row] + (doseq [x (range 1 (inc row))] + (print (nine-billion-names row x) \space)) + (println)) + +(defn print-triangle [rows] + (doseq [x (range 1 (inc rows))] + (print-row x))) + +(print-triangle 25) diff --git a/Task/9-billion-names-of-God-the-integer/PureBasic/9-billion-names-of-god-the-integer.purebasic b/Task/9-billion-names-of-God-the-integer/PureBasic/9-billion-names-of-god-the-integer.purebasic new file mode 100644 index 0000000000..2debe2e96d --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/PureBasic/9-billion-names-of-god-the-integer.purebasic @@ -0,0 +1,68 @@ +Define.i nMax=25, n, k +Dim pfx.s(1) + +Procedure.s Sigma(sx.s, sums.s) + Define.i i, v1, v2, r + Define.s s, sa + sums=ReverseString(sums) : s=ReverseString(sx) + For i=1 To Len(s)*Bool(Len(s)>Len(sums))+Len(sums)*Bool(Len(sums)>=Len(s)) + v1=Val(Mid(s,i,1)) + v2=Val(Mid(sums,i,1)) + r+v1+v2 + sa+Str(r%10) + r/10 + Next i + If r : sa+Str(r%10) : EndIf + ProcedureReturn ReverseString(sa) +EndProcedure + +Procedure.i Adr(row.i,col.i) + ProcedureReturn ((row-1)*row/2+col)*Bool(row>0 And col>0) +EndProcedure + +Procedure Triangle(row.i,Array pfx.s(1)) + Define.i n,k + Define.s zs + nMax=row + ReDim pfx(Adr(nMax,nMax)) + For n=1 To nMax + For k=1 To n + If k>n : pfx(Adr(n,k))="0" : Continue : EndIf + If n=k : pfx(Adr(n,k))="1" : Continue : EndIf + If k<=n/2 + zs="" + zs=Sigma(pfx(Adr(n-k,k)),zs) + zs=Sigma(pfx(Adr(n-1,k-1)),zs) + pfx(Adr(n,k))=zs + Else + pfx(Adr(n,k))=pfx(Adr(n-1,k-1)) + EndIf + Next k + Next n +EndProcedure + +Procedure.s sum(row.i, Array pfx.s(1)) + Define.s s + Triangle(row, pfx()) + For n=1 To row + s=Sigma(pfx(Adr(row,n)),s) + Next n + ProcedureReturn RSet(Str(row),5,Chr(32))+" : "+s +EndProcedure + +OpenConsole() + +Triangle(nMax, pfx()) +For n=1 To nMax + Print(Space(((nMax*4-1)-(n*4-1))/2)) + For k=1 To n + Print(RSet(pfx(Adr(n,k)),3,Chr(32))+Space(1)) + Next k + PrintN("") +Next n +PrintN("") +PrintN(sum(23,pfx())) +PrintN(sum(123,pfx())) +PrintN(sum(1234,pfx())) +PrintN(sum(12345,pfx())) +Input() 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 index b953b64d23..d47d43180a 100644 --- 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 @@ -1,52 +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*/ +/*REXX program generates & shows a number triangle for partitions of a number.*/ +numeric digits 400 /*be able to handle larger numbers. */ +parse arg N .; if N=='' then N=25 /*N specified? 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────────────────────────*/ +if N==N+0 then say ' G('aN"):" G(N) /*just for well formed numbers.*/ + say 'partitions('aN"):" partitions(aN) /*do it the easy way*/ +exit /*stick a fork in it, we're all 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.*/ +!.4.2=2; do j=1 for aN%2; !.j.j=1; end /*j*/ /*gen 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 $ + do t=1 for 1+build; #.=1 /*gen triangle once or twice ···*/ + do r=1 for aN; #.2=r%2 /*#.2 is a shortcut calculation.*/ + do c=3 to r-2; #.c=gen#(r,c); end /*c*/ + L=length(mx); p=0; __= /*__ will be a row (line) of triangle.*/ + do cc=1 for r /*only sum the last row of numbers. */ + p=p+#.cc /*add the last row of the triangle. */ + if \build then iterate /*should we skip building the triangle?*/ + mx=max(mx,#.cc) /*used to build the symmetric numbers. */ + __=__ right(#.cc,L) /*construct a row (or line) of triangle*/ + end /*cc*/ + if t==1 then iterate /*Is this the 1st time through? No show*/ + say center(strip(__), 2+(aN-1)*(length(mx)+1)) + end /*r*/ /* [↑] center the row of the triangle.*/ + end /*t*/ +return p /*return with the 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 number 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 the calculated number*/ + end /* [↑] right half of triangle*/ +$=1 /* [↓] left " " " */ + do q=2 for y-1; 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) /*recurse.*/ + end /*q*/ +!.x.y=$; return $ /*use memoization; return with number.*/ +/*──────────────────────────────────PARTITIONS subroutine─────────────────────*/ +partitions: procedure expose @.; parse arg n; if @.n\==0 then return @.n /*◄─┐*/ +$=0 /*Already known? Then return value►───┘*/ + do k=1 for n; _=n-(k*3-1)*k%2; if _<0 then leave + if @._==0 then x=partitions(_) /* [◄] recursive call.*/ + else x=@._ /*value already known. */ + _=_-k; if _<0 then y=0 /*recursive call ►────┐*/ + else if @._==0 then y=partitions(_) /*◄──┘*/ + else y=@._ + if k//2 then $=$+x+y /*utilize this method if K is odd. */ + else $=$2x-y /* " " " " " " even. */ + end /*k*/ /* [↑] Euler's recursive function. */ +@.n=$; return $ /*use memoization; return with number.*/ diff --git a/Task/99-Bottles-of-Beer/D/99-bottles-of-beer-3.d b/Task/99-Bottles-of-Beer/D/99-bottles-of-beer-3.d new file mode 100644 index 0000000000..f2b9b4796c --- /dev/null +++ b/Task/99-Bottles-of-Beer/D/99-bottles-of-beer-3.d @@ -0,0 +1,21 @@ +module bottles; + +template BeerSong(int Bottles) +{ + static if (Bottles == 1) + { + enum BeerSong = "1 bottle of beer on the wall\n" ~ + "1 bottle of beer\ntake it down, pass it around\n" ~ " + no more bottles of beer on the wall\n"; + } + else + { + enum BeerSong = Bottles.stringof ~ " bottles of beer on the wall\n" ~ + Bottles.stringof ~ " bottles of beer\ntake it down, pass it around\n" ~ + BeerSong!(Bottles-1); + } +} + +pragma(msg,BeerSong!99); + +void main(){} diff --git a/Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer.e b/Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer-1.e similarity index 100% rename from Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer.e rename to Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer-1.e diff --git a/Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer-2.e b/Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer-2.e new file mode 100644 index 0000000000..da956ccc6d --- /dev/null +++ b/Task/99-Bottles-of-Beer/Eiffel/99-bottles-of-beer-2.e @@ -0,0 +1,22 @@ + output_lyrics + -- Output the lyrics to 99-bottles-of-beer. + local + l_bottles: LINKED_LIST [INTEGER] + do + create l_bottles.make + across (1 |..| 99) as ic loop l_bottles.force (ic.item) end + across l_bottles.new_cursor.reversed as ic_bottles loop + print (ic_bottles.item) + print (" bottles of beer on the wall, ") + print (ic_bottles.item) + print (" bottles of beer.%N") + print ("Take one down, pass it around, ") + if ic_bottles.item > 1 then + print (ic_bottles.item) + print (" bottles of beer on the wall.%N%N") + end + end + print ("1 bottle of beer on the wall.%N") + print ("No more bottles of beer on the wall, no more bottles of beer.%N") + print ("Go to the store and buy some more, 99 bottles of beer on the wall.%N") + end diff --git a/Task/99-Bottles-of-Beer/Fexl/99-bottles-of-beer.fexl b/Task/99-Bottles-of-Beer/Fexl/99-bottles-of-beer.fexl index 50fbca6461..69e11d538d 100644 --- a/Task/99-Bottles-of-Beer/Fexl/99-bottles-of-beer.fexl +++ b/Task/99-Bottles-of-Beer/Fexl/99-bottles-of-beer.fexl @@ -1,16 +1,16 @@ \suffix=(\n eq n 1 "" "s") -\sing_count=(\n put n put " " put "bottle" put (suffix n) put " of beer") -\sing_line1=(\n sing_count n put " on the wall" nl) +\sing_count=(\n put [n " bottle" (suffix n) " of beer"]) +\sing_line1=(\n sing_count n say " on the wall") \sing_line2=(\n sing_count n nl) -\sing= - (@\loop\n - le n 0 (); - sing_line1 n - sing_line2 n - say "Take one down, pass it around" - \n=(- n 1) - sing_line1 n - nl - loop n - ) +\sing== + (\n + le n 0 (); + sing_line1 n + sing_line2 n + say "Take one down, pass it around" + \n=(- n 1) + sing_line1 n + nl + sing n + ) sing 3 diff --git a/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer.fth b/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-1.fth similarity index 100% rename from Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer.fth rename to Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-1.fth diff --git a/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-2.fth b/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-2.fth new file mode 100644 index 0000000000..36a3defd7c --- /dev/null +++ b/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-2.fth @@ -0,0 +1,36 @@ +: bottles ( n -- ) \ select the right grammar based on 'n' + dup + case + 1 of ." One more bottle " drop endof + 0 of ." No more bottles " drop endof + . ." bottles " \ default case + endcase ; + +\ create punctuation with delay for artistic effect +: , [char] , emit 100 ms ; +: . [char] . emit 300 ms ; + +\ create the words to write the program +: of ." of " ; +: beer ." beer " ; +: on ." on " ; +: the ." the " ; +: wall ." wall" ; +: take ." take " ; +: one ." one " ; +: down ." down" ; +: pass ." pass " ; +: it ." it " ; +: around ." around" ; + +\ who said Forth is write only? +: beers ( n -- ) \ USAGE: 99 beers + 1 swap + cr + do + I bottles of beer on the wall , cr + I bottles of beer , cr + take one down , pass it around , cr + I 1- bottles of beer on the wall . cr + cr + -1 +loop ; diff --git a/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-3.fth b/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-3.fth new file mode 100644 index 0000000000..9b6606860a --- /dev/null +++ b/Task/99-Bottles-of-Beer/Forth/99-bottles-of-beer-3.fth @@ -0,0 +1,12 @@ +2 beers +2 bottles of beer on the wall, +2 bottles of beer , +take one down, pass it around, +One more bottle of beer on the wall. + +One more bottle of beer on the wall, +One more bottle of beer , +take one down, pass it around, +No more bottles of beer on the wall. + + ok diff --git a/Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer-3.f b/Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer-3.f new file mode 100644 index 0000000000..29d14f3912 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Fortran/99-bottles-of-beer-3.f @@ -0,0 +1,132 @@ +module song_typedefs + implicit none + + private ! all + public :: TBottles + + type, abstract :: TContainer + integer :: quantity + contains + ! deferred method i.e. abstract method = must be overridden in extended type + procedure(take_one), deferred, pass :: take_one + procedure(show_quantity), deferred, pass :: show_quantity + end type TContainer + + + abstract interface + subroutine take_one(this) + import TContainer + implicit none + class(TContainer) :: this + end subroutine take_one + subroutine show_quantity(this) + import TContainer + implicit none + class(TContainer) :: this + end subroutine show_quantity + end interface + + ! extended derived type + type, extends(TContainer) :: TBottles + contains + procedure, pass :: take_one => take_one_bottle + procedure, pass :: show_quantity => show_bottles + final :: finalize_bottles + end type TBottles + + contains + + subroutine show_bottles(this) + implicit none + class(TBottles) :: this + ! integer :: show_bottles + character(len=*), parameter :: bw0 = "No more bottles of beer on the wall," + character(len=*), parameter :: bwx = "bottles of beer on the wall," + character(len=*), parameter :: bw1 = "bottle of beer on the wall," + character(len=*), parameter :: bb0 = "no more bottles of beer." + character(len=*), parameter :: bbx = "bottles of beer." + character(len=*), parameter :: bb1 = "bottle of beer." + character(len=*), parameter :: fmtxdd = "(I2,1X,A28,1X,I2,1X,A16)" + character(len=*), parameter :: fmtxd = "(I1,1X,A28,1X,I1,1X,A16)" + character(len=*), parameter :: fmt1 = "(I1,1X,A27,1X,I1,1X,A15)" + character(len=*), parameter :: fmt0 = "(A36,1X,A24)" + + select case (this % quantity) + case (10:) + write(*,fmtxdd) this % quantity, bwx, this % quantity, bbx + case (2:9) + write(*,fmtxd) this % quantity, bwx, this % quantity, bbx + case (1) + write(*,fmt1) this % quantity, bw1, this % quantity, bb1 + case (0) + write(*,*) + write(*,fmt0) bw0, bb0 + case default + write(*,*)"Warning! Number of bottles exception, error 42. STOP" + stop + end select + ! show_bottles = this % quantity + end subroutine show_bottles + + subroutine take_one_bottle(this) ! bind(c, name='take_one_bottle') + implicit none + class(TBottles) :: this + ! integer :: take_one_bottle + character(len=*), parameter :: t1 = "Take one down and pass it around," + character(len=*), parameter :: remx = "bottles of beer on the wall." + character(len=*), parameter :: rem1 = "bottle of beer on the wall." + character(len=*), parameter :: rem0 = "no more bottles of beer on the wall." + character(len=*), parameter :: fmtx = "(A33,1X,I2,1X,A28)" + character(len=*), parameter :: fmt1 = "(A33,1X,I2,1X,A27)" + character(len=*), parameter :: fmt0 = "(A33,1X,A36)" + + this % quantity = this % quantity -1 + + select case (this%quantity) + case (2:) + write(*,fmtx) t1, this%quantity, remx + case (1) + write(*,fmt1) t1, this%quantity, rem1 + case (0) + write(*,fmt0) t1, rem0 + case (-1) + write(*,'(A66)') "Go to the store and buy some more, 99 bottles of beer on the wall." + case default + write(*,*)"Warning! Number of bottles exception, error 42. STOP" + stop + end select + + end subroutine take_one_bottle + + subroutine finalize_bottles(bottles) + implicit none + type(TBottles) :: bottles + ! here can be more code + end subroutine finalize_bottles + +end module song_typedefs + +!----------------------------------------------------------------------- +!Main program +!----------------------------------------------------------------------- +program bottles_song + use song_typedefs + implicit none + integer, parameter :: MAGIC_NUMBER = 99 + type(TBottles), target :: BTLS + + BTLS = TBottles(MAGIC_NUMBER) + + call make_song(BTLS) + + contains + + subroutine make_song(bottles) + type(TBottles) :: bottles + do while(bottles%quantity >= 0) + call bottles%show_quantity() + call bottles%take_one() + enddo + end subroutine make_song + +end program bottles_song diff --git a/Task/99-Bottles-of-Beer/GW-BASIC/99-bottles-of-beer.gw-basic b/Task/99-Bottles-of-Beer/GW-BASIC/99-bottles-of-beer.gw-basic new file mode 100644 index 0000000000..b0cb43b351 --- /dev/null +++ b/Task/99-Bottles-of-Beer/GW-BASIC/99-bottles-of-beer.gw-basic @@ -0,0 +1,6 @@ +10 FOR BOTTLES = 99 TO 1 STEP -1 +20 PRINT BOTTLES " bottles of beer on the wall" +30 PRINT BOTTLES " bottles of beer" +40 PRINT "Take one down, pass it around" +50 PRINT BOTTLES-1 " bottles of beer on the wall" +60 NEXT BOTTLES diff --git a/Task/99-Bottles-of-Beer/Kotlin/99-bottles-of-beer.kotlin b/Task/99-Bottles-of-Beer/Kotlin/99-bottles-of-beer.kotlin index 4b1da88360..612c8220d4 100644 --- a/Task/99-Bottles-of-Beer/Kotlin/99-bottles-of-beer.kotlin +++ b/Task/99-Bottles-of-Beer/Kotlin/99-bottles-of-beer.kotlin @@ -1,11 +1,8 @@ -fun main(args : Array) { - var i = 99 - while (i > 0) { - - System.out?.println("${i} bottles of beer on the wall") - System.out?.println("${i} bottles of beer") - System.out?.println("Take one down, pass it around") - i--; - } - System.out?.println("0 bottles of beer on the wall") +fun main(args: Array) { + for (i in 99.downTo(1)) { + println("${i} bottles of beer on the wall") + println("${i} bottles of beer") + println("Take one down, pass it around") + } + println("No more bottles of beer on the wall!") } diff --git a/Task/99-Bottles-of-Beer/Maple/99-bottles-of-beer.maple b/Task/99-Bottles-of-Beer/Maple/99-bottles-of-beer.maple new file mode 100644 index 0000000000..046e763cac --- /dev/null +++ b/Task/99-Bottles-of-Beer/Maple/99-bottles-of-beer.maple @@ -0,0 +1,5 @@ +seq( printf( "%d %s of beer on the wall,\n%d %s of beer.\nTake one down, pass it around,\n%d %s of beer on the wall.\n\n", + i, `if`( i<>1, "bottles", "bottle" ), + i, `if`( i<>1, "bottles", "bottle" ), + i-1, `if`( i-1<>1, "bottles", "bottle") ), +i = 99..1, -1 ); diff --git a/Task/99-Bottles-of-Beer/OCaml/99-bottles-of-beer-3.ocaml b/Task/99-Bottles-of-Beer/OCaml/99-bottles-of-beer-3.ocaml new file mode 100644 index 0000000000..42378a3beb --- /dev/null +++ b/Task/99-Bottles-of-Beer/OCaml/99-bottles-of-beer-3.ocaml @@ -0,0 +1,26 @@ +(* A basic "Writer" monoid with emit *) +module Writer = struct + type 'a t = 'a * string + let ( >>= ) (x,s) f = let (y,s') = f x in (y, s ^ s') + let return x = (x,"") + let emit (x,s) = print_string s; x +end + +(* Utility functions for handling strings and grammar *) +let line s = (String.capitalize s) ^ ".\n" +let count = function 0 -> "no more" | n -> string_of_int n +let plural = function 1 -> "" | _ -> "s" +let specify = function 1 -> "it" | _ -> "one" +let bottles n = count n ^ " bottle" ^ plural n ^ " of beer" + +(* Actions, expressed as an int * string, for Writer *) +let report n = (n, line (bottles n ^ " on the wall, " ^ bottles n)) +let take n = (n-1, "Take " ^ specify n ^ " down and pass it around") +let summary n = (n, ", " ^ bottles n ^ " on the wall.\n\n") +let shop = (99, "Go to the store and buy some more") + +let rec verse state = + Writer.(state >>= report >>= function 0 -> shop >>= summary (* ends here *) + | n -> take n >>= summary |> verse) +let sing start = + Writer.(emit (verse (return start))) diff --git a/Task/99-Bottles-of-Beer/OCaml/99-bottles-of-beer-4.ocaml b/Task/99-Bottles-of-Beer/OCaml/99-bottles-of-beer-4.ocaml new file mode 100644 index 0000000000..6ab1346499 --- /dev/null +++ b/Task/99-Bottles-of-Beer/OCaml/99-bottles-of-beer-4.ocaml @@ -0,0 +1,11 @@ +# sing 2;; +2 bottles of beer on the wall, 2 bottles of beer. +Take one down and pass it around, 1 bottle of beer on the wall. + +1 bottle of beer on the wall, 1 bottle of beer. +Take it down and pass it around, no more bottles of beer on the wall. + +No more bottles of beer on the wall, no more bottles of beer. +Go to the store and buy some more, 99 bottles of beer on the wall. + +- : int = 99 diff --git a/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-1.pl6 b/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-1.pl6 index 6661f5fcad..5032af8e15 100644 --- a/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-1.pl6 +++ b/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-1.pl6 @@ -1,13 +1,13 @@ my $b = 99; -sub b($b) { - "$b bottle{'s'.substr($b == 1)} of beer"; +repeat while --$b { + say "{b $b} on the wall"; + say "{b $b}"; + say "Take one down, pass it around"; + say "{b $b-1} on the wall"; + say ""; } -repeat while --$b { - .say for "&b($b) on the wall", - b($b), - 'Take one down, pass it around', - "&b($b-1) on the wall", - ''; +sub b($b) { + "$b bottle{'s' if $b != 1} of beer"; } diff --git a/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-2.pl6 b/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-2.pl6 index 443b15a573..3cadb30ac6 100644 --- a/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-2.pl6 +++ b/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-2.pl6 @@ -1,19 +1,18 @@ -#= Sings a verse about a certian number of beers, possibly on a wall. +for 99...1 -> $bottles { + sing $bottles, :wall; + sing $bottles; + say "Take one down, pass it around"; + sing $bottles - 1, :wall; + say ""; +} + +#| Prints a verse about a certain number of beers, possibly on a wall. sub sing( Int $number, #= Number of bottles of beer. - Bool $has_wall = False #= Mention that the beers are on a wall? + Bool :$wall, #= Mention that the beers are on a wall? ) { - my $quantity = $number == 0 ?? "No more" !! $number; - my $plural = $number == 1 ?? "" !! "s"; - my $wall = $has_wall ?? " on the wall" !! ""; - return "{$quantity} bottle{$plural} of beer{$wall}" -} - -for 99...1 -> $bottles { - .say for - sing($bottles, True), - sing($bottles), - "Take one down, pass it around", - sing($bottles-1, True), - ""; + my $quantity = $number == 0 ?? "No more" !! $number; + my $plural = $number == 1 ?? "" !! "s"; + my $location = $wall ?? " on the wall" !! ""; + say "$quantity bottle$plural of beer$location" } diff --git a/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-3.pl6 b/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-3.pl6 index 61d6168c78..6474334a2c 100644 --- a/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-3.pl6 +++ b/Task/99-Bottles-of-Beer/Perl-6/99-bottles-of-beer-3.pl6 @@ -1,11 +1,11 @@ -my @quantities = (99 ... 1), 'No more', 99; -my @bottles = 'bottles' xx 98, 'bottle', 'bottles' xx 2; -my @actions = 'Take one down, pass it around' xx 99, +my @quantities = flat (99 ... 1), 'No more', 99; +my @bottles = flat 'bottles' xx 98, 'bottle', 'bottles' xx 2; +my @actions = flat 'Take one down, pass it around' xx 99, 'Go to the store, buy some more'; for @quantities Z @bottles Z @actions Z @quantities[1 .. *] Z @bottles[1 .. *] - -> $a, $b, $c, $d, $e { + -> ($a, $b, $c, $d, $e) { say "$a $b of beer on the wall"; say "$a $b of beer"; say $c; diff --git a/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust b/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust index 189f945b3e..8615008e94 100644 --- a/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust +++ b/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust @@ -1,16 +1,13 @@ -use std::iter::range_step_inclusive; - trait Bottles { fn bottles_of_beer(&self) -> Self; fn on_the_wall(&self); } -impl Bottles for isize { - - fn bottles_of_beer(&self) -> isize { +impl Bottles for u32 { + fn bottles_of_beer(&self) -> u32 { match *self { - 1 => print!("{} bottle of beer", self), 0 => print!("No bottles of beer"), + 1 => print!("{} bottle of beer", self), _ => print!("{} bottles of beer", self) } *self // return a number for chaining @@ -22,7 +19,7 @@ impl Bottles for isize { } fn main() { - for i in range_step_inclusive(99is, 1, -1) { + for i in (1..100).rev() { i.bottles_of_beer().on_the_wall(); i.bottles_of_beer(); println!("\nTake one down, pass it around..."); diff --git a/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql index 538c9a4edd..50eedd9843 100644 --- a/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql +++ b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-1.sql @@ -1,9 +1,9 @@ select - ( 100 - level ) || ' bottle' || case 100 - level when 1 then '' else 's' end || ' of beer on the wall' + ( 100 - level ) || ' bottle' || case when level != 99 then 's' end || ' of beer on the wall' || chr(10) - || ( 100 - level ) || ' bottle' || case 100 - level when 1 then '' else 's' end || ' of beer' + || ( 100 - level ) || ' bottle' || case when level != 99 then 's' end || ' of beer' || chr(10) || 'Take one down, pass it around' || chr(10) - || ( 99 - level ) || ' bottle' || case 99 - level when 1 then '' else 's' end || ' of beer on the wall' + || ( 99 - level ) || ' bottle' || case when level != 98 then 's' end || ' of beer on the wall' from dual connect by level <= 99; diff --git a/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-4.sql b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-4.sql new file mode 100644 index 0000000000..999d56c8a8 --- /dev/null +++ b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-4.sql @@ -0,0 +1,32 @@ +/*These statements work in PostgreSQL (tested in 9.3)*/ + +SELECT generate_series || ' bottles of beer on the wall' || chr(10) || +generate_series || ' bottles of beer' || chr(10) || +'Take one down, pass it around' || chr(10) || +coalesce(lead(generate_series) OVER (ORDER BY generate_series DESC),0) || ' bottles of beer on the wall' +FROM generate_series(1,100) +ORDER BY generate_series DESC; + +/*The next statement takes also into account the grammaticalt support for "1 bottle of beer".*/ + +SELECT generate_series || ' bottle' || CASE WHEN generate_series>1 THEN 's' ELSE '' END || ' of beer on the wall' || chr(10) || +generate_series || ' bottle' || CASE WHEN generate_series>1 THEN 's' ELSE '' END || ' of beer' || chr(10) || +'Take one down, pass it around' || chr(10) || +coalesce(lead(generate_series) OVER (ORDER BY generate_series DESC),0) || ' bottle' || CASE WHEN coalesce(lead(generate_series) OVER (ORDER BY generate_series DESC),0) <>1 THEN 's' ELSE '' END || ' of beer on the wall' +FROM generate_series(1,100) +ORDER BY generate_series DESC; + +/*The next statement uses recursive query.*/ + +WITH RECURSIVE t(n) AS ( + VALUES (1) + UNION ALL + SELECT n+1 FROM t WHERE n < 100 +) +SELECT n || ' bottle' || CASE WHEN n>1 THEN 's' ELSE '' END || ' of beer on the wall' || chr(10) || +n || ' bottle' || CASE WHEN n>1 THEN 's' ELSE '' END || ' of beer' || chr(10) || +'Take one down, pass it around' || chr(10) || +coalesce(lead(n) OVER (ORDER BY n DESC),0) || ' bottle' || +CASE WHEN coalesce(lead(n) OVER (ORDER BY n DESC),0) <>1 THEN 's' ELSE '' END || ' of beer on the wall' +FROM t +ORDER BY n DESC; diff --git a/Task/99-Bottles-of-Beer/Scheme/99-bottles-of-beer.ss b/Task/99-Bottles-of-Beer/Scheme/99-bottles-of-beer.ss index f05d51e6a0..b467fd6042 100644 --- a/Task/99-Bottles-of-Beer/Scheme/99-bottles-of-beer.ss +++ b/Task/99-Bottles-of-Beer/Scheme/99-bottles-of-beer.ss @@ -1,7 +1,12 @@ -(define (bottles x) - (format #t "~a bottles of beer on the wall~%" x) - (format #t "~a bottles of beer~%" x) - (format #t "Take one down, pass it around~%") - (format #t "~a bottles of beer on the wall~%" (- x 1)) - (if (> (- x 1) 0) - (bottles (- x 1)))) +(define (sing) + (define (sing-to-x n) + (if (> n -1) + (begin + (display n) + (display "bottles of beer on the wall") + (newline) + (display "Take one down, pass it around") + (newline) + (sing-to-x (- n 1))) + (display "would you wanna me to sing it again?"))) + (sing-to-x 99)) diff --git a/Task/99-Bottles-of-Beer/XSLT/99-bottles-of-beer.xslt b/Task/99-Bottles-of-Beer/XSLT/99-bottles-of-beer.xslt new file mode 100644 index 0000000000..1479eec45f --- /dev/null +++ b/Task/99-Bottles-of-Beer/XSLT/99-bottles-of-beer.xslt @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Take one down, pass it around + + + + + + + + + + + + + + + on the wall + + + bottle + + s + of beer + + + + + diff --git a/Task/A+B/360-Assembly/a+b.360 b/Task/A+B/360-Assembly/a+b.360 new file mode 100644 index 0000000000..013b95ab57 --- /dev/null +++ b/Task/A+B/360-Assembly/a+b.360 @@ -0,0 +1,21 @@ +* A+B 29/08/2015 +APLUSB CSECT + USING APLUSB,R12 + LR R12,R15 + OPEN (MYDATA,INPUT) +LOOP GET MYDATA,PG read a single record + XDECI R4,PG input A + XDECI R5,PG+12 input B + AR R4,R5 A+B + XDECO R4,PG+24 edit A+B + XPRNT PG,36 print A+B + B LOOP repeat +ATEND CLOSE MYDATA +RETURN XR R15,R15 + BR R14 + LTORG +MYDATA DCB LRECL=24,RECFM=FT,EODAD=ATEND,DDNAME=MYFILE +PG DS CL24 record + DC CL12' ' + YREGS + END APLUSB diff --git a/Task/A+B/ALGOL-W/a+b.alg b/Task/A+B/ALGOL-W/a+b.alg new file mode 100644 index 0000000000..50c2932706 --- /dev/null +++ b/Task/A+B/ALGOL-W/a+b.alg @@ -0,0 +1,5 @@ +begin + integer a, b; + read( a, b ); + write( a + b ) +end. diff --git a/Task/A+B/AppleScript/a+b.applescript b/Task/A+B/AppleScript/a+b.applescript new file mode 100644 index 0000000000..69a882d9a8 --- /dev/null +++ b/Task/A+B/AppleScript/a+b.applescript @@ -0,0 +1,7 @@ +on run argv + try + return ((first item of argv) as integer) + (second item of argv) as integer + on error + return "Usage with -1000 <= a,b <= 1000: " & tab & " A+B.scpt a b" + end try +end run diff --git a/Task/A+B/C++/a+b-1.cpp b/Task/A+B/C++/a+b-1.cpp index 119b27f180..09526fb0bb 100644 --- a/Task/A+B/C++/a+b-1.cpp +++ b/Task/A+B/C++/a+b-1.cpp @@ -1,7 +1,7 @@ // Standard input-output streams #include using namespace std; -void main() +int main() { int a, b; cin >> a >> b; diff --git a/Task/A+B/Clojure/a+b-3.clj b/Task/A+B/Clojure/a+b-3.clj new file mode 100644 index 0000000000..121ed14ac1 --- /dev/null +++ b/Task/A+B/Clojure/a+b-3.clj @@ -0,0 +1,3 @@ +(println (+ (read) (read))) +3 4 +7 diff --git a/Task/A+B/Clojure/a+b-4.clj b/Task/A+B/Clojure/a+b-4.clj new file mode 100644 index 0000000000..c4f7dcd78c --- /dev/null +++ b/Task/A+B/Clojure/a+b-4.clj @@ -0,0 +1,4 @@ +(let [ints (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") )] + (println (reduce + ints))) +3 4 +=>7 diff --git a/Task/A+B/Clojure/a+b-5.clj b/Task/A+B/Clojure/a+b-5.clj new file mode 100644 index 0000000000..acbaa35815 --- /dev/null +++ b/Task/A+B/Clojure/a+b-5.clj @@ -0,0 +1,4 @@ +(println (reduce + (map #(Integer/parseInt %) (clojure.string/split (read-line) #"\s") ))) + +3 4 +=>7 diff --git a/Task/A+B/DCL/a+b.dcl b/Task/A+B/DCL/a+b.dcl new file mode 100644 index 0000000000..d98987dd46 --- /dev/null +++ b/Task/A+B/DCL/a+b.dcl @@ -0,0 +1,4 @@ +$ read sys$command line +$ a = f$element( 0, " ", line ) +$ b = f$element( 1, " ", line ) +$ write sys$output a + b diff --git a/Task/A+B/Eiffel/a+b.e b/Task/A+B/Eiffel/a+b-1.e similarity index 100% rename from Task/A+B/Eiffel/a+b.e rename to Task/A+B/Eiffel/a+b-1.e diff --git a/Task/A+B/Eiffel/a+b-2.e b/Task/A+B/Eiffel/a+b-2.e new file mode 100644 index 0000000000..9032093b45 --- /dev/null +++ b/Task/A+B/Eiffel/a+b-2.e @@ -0,0 +1,20 @@ + make + -- Run application. + note + synopsis: "[ + The specification implies command line input stream and also + implies a range for both `A' and `B' (e.g. (-1000 <= A,B <= +1000)). + To test in Eiffel Studio workbench, one can set Execution Parameters + of "2 2", where the expected output is 4. One may also create other + test Execution Parameters where the inputs are out-of-bounds and + confirm the failure. + ]" + do + if attached {INTEGER} argument (1).to_integer as a and then + attached {INTEGER} argument (2).to_integer as b and then + (a >= -1000 and b >= -1000 and a <= 1000 and b <= 1000) then + print (a + b) + else + print ("Either argument 1 or 2 is out-of-bounds. Ensure: (-1000 <= A,B <= +1000)") + end + end diff --git a/Task/A+B/Ela/a+b.ela b/Task/A+B/Ela/a+b.ela index 541697631e..e9b39c1ac7 100644 --- a/Task/A+B/Ela/a+b.ela +++ b/Task/A+B/Ela/a+b.ela @@ -1,3 +1,7 @@ -open console list string read +open monad io string list -readn() |> string.split " " |> map readStr |> sum +a'b() = do + str <- readStr + putStrLn <| show <| sum <| map gread <| string.split " " <| str + +a'b() ::: IO diff --git a/Task/A+B/Elena/a+b.elena b/Task/A+B/Elena/a+b.elena index 45307430a9..789a47618e 100644 --- a/Task/A+B/Elena/a+b.elena +++ b/Task/A+B/Elena/a+b.elena @@ -6,6 +6,5 @@ #var A := Integer new. #var B := Integer new. - consoleEx readLine:A:B. - consoleEx writeLine:(A + B). + console readLine:A:B writeLine:(A + B). ]. diff --git a/Task/A+B/Elixir/a+b.elixir b/Task/A+B/Elixir/a+b.elixir new file mode 100644 index 0000000000..1c1d25dd90 --- /dev/null +++ b/Task/A+B/Elixir/a+b.elixir @@ -0,0 +1,6 @@ +IO.gets("Enter your first integer: ") + |> String.replace(~r/\n/,"") + |> String.split(" ", trim: true) + |> Enum.map(&(String.to_integer(&1))) + |> Enum.reduce(&(&1 + &2)) + |> IO.inspect diff --git a/Task/A+B/Haskell/a+b.hs b/Task/A+B/Haskell/a+b.hs index e6a8348f58..9dd7b76fd8 100644 --- a/Task/A+B/Haskell/a+b.hs +++ b/Task/A+B/Haskell/a+b.hs @@ -1 +1 @@ -main = getLine >>= print . sum . map read . words +main = print . sum . map read . words =<< getLine diff --git a/Task/A+B/Java/a+b-4.java b/Task/A+B/Java/a+b-4.java new file mode 100644 index 0000000000..aaebb7623e --- /dev/null +++ b/Task/A+B/Java/a+b-4.java @@ -0,0 +1,14 @@ +grammar aplusb ; + +options { + language = Java; +} + +aplusb : (WS* e1=Num WS+ e2=Num NEWLINE {System.out.println($e1.text + " + " + $e2.text + " = " + (Integer.parseInt($e1.text) + Integer.parseInt($e2.text)));})+ + ; +Num : '-'?('0'..'9')+ + ; +WS : (' ' | '\t') + ; +NEWLINE : WS* '\r'? '\n' + ; diff --git a/Task/A+B/NetRexx/a+b.netrexx b/Task/A+B/NetRexx/a+b.netrexx index 2045bdde49..3aed753c65 100644 --- a/Task/A+B/NetRexx/a+b.netrexx +++ b/Task/A+B/NetRexx/a+b.netrexx @@ -1,6 +1,6 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols binary +options replace format comments java symbols binary parse ask a b . say a '+' b '=' a + b diff --git a/Task/A+B/Perl-6/a+b-1.pl6 b/Task/A+B/Perl-6/a+b-1.pl6 new file mode 100644 index 0000000000..b2bd52e81d --- /dev/null +++ b/Task/A+B/Perl-6/a+b-1.pl6 @@ -0,0 +1 @@ +say [+] get.words diff --git a/Task/A+B/Perl-6/a+b-2.pl6 b/Task/A+B/Perl-6/a+b-2.pl6 new file mode 100644 index 0000000000..1ca776638f --- /dev/null +++ b/Task/A+B/Perl-6/a+b-2.pl6 @@ -0,0 +1 @@ +$*IN.get.words.reduce(* + *).say diff --git a/Task/A+B/Perl-6/a+b-3.pl6 b/Task/A+B/Perl-6/a+b-3.pl6 new file mode 100644 index 0000000000..8d02852753 --- /dev/null +++ b/Task/A+B/Perl-6/a+b-3.pl6 @@ -0,0 +1,2 @@ +my ($a,$b) = $*IN.get.split(" "); +say $a + $b; diff --git a/Task/A+B/Perl-6/a+b.pl6 b/Task/A+B/Perl-6/a+b.pl6 deleted file mode 100644 index 7217cd2042..0000000000 --- a/Task/A+B/Perl-6/a+b.pl6 +++ /dev/null @@ -1 +0,0 @@ -say [+] .words for lines diff --git a/Task/A+B/Rust/a+b.rust b/Task/A+B/Rust/a+b.rust index bf6a14d01a..147cda922a 100644 --- a/Task/A+B/Rust/a+b.rust +++ b/Task/A+B/Rust/a+b.rust @@ -1,15 +1,17 @@ -// -*- rust v0.9 -*- -use std::os; +// rustc -V +// rustc 1.2.0-nightly (0cc99f9cc 2015-05-17) (built 2015-05-18) + +use std::io; +use std::str::FromStr; fn main() { - let args : ~[~str] = os::args(); - let mut values = 0; - - for i in args.iter(){ - match from_str::(i.to_str()) { - Some(valid_int) => values += valid_int, - None => () - } - } - println(values.to_str()); + let mut line = String::new(); + io::stdin().read_line(&mut line).unwrap(); + + let result = line.trim() + .split(' ') + .map(|x| isize::from_str(x).unwrap()) + .fold(0, |sum, x| sum + x); + + println!("{}", result); } diff --git a/Task/A+B/Scala/a+b-3.scala b/Task/A+B/Scala/a+b-3.scala new file mode 100644 index 0000000000..42b430e4f3 --- /dev/null +++ b/Task/A+B/Scala/a+b-3.scala @@ -0,0 +1 @@ +println(readLine().split(" ").filter(_.length>0).map(_.toInt).sum) diff --git a/Task/A+B/Self/a+b.self b/Task/A+B/Self/a+b.self new file mode 100644 index 0000000000..e4c105592d --- /dev/null +++ b/Task/A+B/Self/a+b.self @@ -0,0 +1 @@ +((stdin readLine splitOn: ' ') mapBy: [|:e| e asInteger]) sum printLine. diff --git a/Task/A+B/TI-83-BASIC/a+b.ti-83 b/Task/A+B/TI-83-BASIC/a+b.ti-83 new file mode 100644 index 0000000000..4e418b8727 --- /dev/null +++ b/Task/A+B/TI-83-BASIC/a+b.ti-83 @@ -0,0 +1,2 @@ +:Prompt A,B +:Disp A+B diff --git a/Task/A+B/TI-89-BASIC/a+b.ti-89 b/Task/A+B/TI-89-BASIC/a+b.ti-89 new file mode 100644 index 0000000000..19afdba68b --- /dev/null +++ b/Task/A+B/TI-89-BASIC/a+b.ti-89 @@ -0,0 +1,2 @@ +:aplusb(a,b) +:a+b diff --git a/Task/A+B/Verilog/a+b.v b/Task/A+B/Verilog/a+b.v new file mode 100644 index 0000000000..80e1c639a1 --- /dev/null +++ b/Task/A+B/Verilog/a+b.v @@ -0,0 +1,19 @@ +module TEST; + + reg signed [11:0] y; + + initial begin + y= sum(2, 2); + y= sum(3, 2); + y= sum(-3, 2); + end + + function signed [11:0] sum; + input signed [10:0] a, b; + begin + sum= a + b; + $display("%d + %d = %d",a,b,sum); + end + endfunction + +endmodule diff --git a/Task/ABC-Problem/ALGOL-68/abc-problem.alg b/Task/ABC-Problem/ALGOL-68/abc-problem.alg new file mode 100644 index 0000000000..524af00c33 --- /dev/null +++ b/Task/ABC-Problem/ALGOL-68/abc-problem.alg @@ -0,0 +1,80 @@ +# determine whether we can spell words with a set of blocks # + +# construct the list of blocks # +[][]STRING 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" ) + ); + +# Returns TRUE if we can spell the word using the blocks, FALSE otherwise # +# Returns TRUE for an empty string # +PROC can spell = ( STRING word, [][]STRING blocks )BOOL: + BEGIN + + # construct a set of flags to indicate whether the blocks are used # + # or not # + [ 1 LWB blocks : 1 UPB blocks ]BOOL used; + FOR block pos FROM LWB used TO UPB used + DO + used[ block pos ] := FALSE + OD; + + # initialliy assume we can spell the word # + BOOL result := TRUE; + + # check we can spell the word with the set of blocks # + FOR word pos FROM LWB word TO UPB word WHILE result + DO + CHAR c = IF is lower( word[ word pos ] ) + THEN to upper( word[ word pos ] ) + ELSE word[ word pos ] + FI; + + # look through the unused blocks for the current letter # + BOOL found := FALSE; + FOR block pos FROM 1 LWB blocks TO 1 UPB blocks + WHILE NOT found + DO + IF ( c = blocks[ block pos ][ 1 ][ 1 ] + OR c = blocks[ block pos ][ 2 ][ 1 ] + ) + AND NOT used[ block pos ] + THEN + # found an unused block with the required letter # + found := TRUE; + used[ block pos ] := TRUE + FI + OD; + + result := found + + OD; + + result + END; # can spell # + + +main: ( + + # test the can spell procedure # + PROC test can spell = ( STRING word, [][]STRING blocks )VOID: + write( ( ( "can spell: """ + + word + + """ -> " + + IF can spell( word, blocks ) THEN "yes" ELSE "no" FI + ) + , newline + ) + ); + + test can spell( "A", blocks ); + test can spell( "BaRK", blocks ); + test can spell( "BOOK", blocks ); + test can spell( "TREAT", blocks ); + test can spell( "COMMON", blocks ); + test can spell( "SQUAD", blocks ); + test can spell( "CONFUSE", blocks ) + +) diff --git a/Task/ABC-Problem/ALGOL-W/abc-problem.alg b/Task/ABC-Problem/ALGOL-W/abc-problem.alg new file mode 100644 index 0000000000..c0166056bb --- /dev/null +++ b/Task/ABC-Problem/ALGOL-W/abc-problem.alg @@ -0,0 +1,81 @@ +% determine whether we can spell words with a set of blocks % +begin + % Returns true if we can spell the word using the blocks, % + % false otherwise % + % As strings are fixed length in Algol W, the length of the string is % + % passed as a separate parameter % + logical procedure canSpell ( string(20) value word + ; integer value wordLength + ) ; + begin + + % convert a character to upper-case % + % assumes the letters are contiguous in the character set % + % as in ASCII and Unicode - not correct for EBCDIC % + string(1) procedure toUpper( string(1) value c ) ; + if c < "a" or c > "z" then c + else code( ( decode( c ) - decode( "a" ) ) + + decode( "A" ) + ) ; + + logical spellable; + integer wordPos, blockPos; + string(20) letters1, letters2; + + % make local copies the faces so we can remove the used blocks % + letters1 := face1; + letters2 := face2; + + % check we can spell the word with the set of blocks % + spellable := true; + wordPos := 0; + while wordPos < wordLength and spellable do begin + string(1) letter; + letter := toUpper( word( wordPos // 1 ) ); + if letter not = " " then begin + spellable := false; + blockPos := 0; + while blockPos < 20 and not spellable do begin + if letter = letters1( blockPos // 1 ) + or letter = letters2( blockPos // 1 ) + then begin + % found the letter - remove the used block from the % + % remaining blocks % + letters1( blockPos // 1 ) := " "; + letters2( blockPos // 1 ) := " "; + spellable := true + end; + blockPos := blockPos + 1 + end + end; + wordPos := wordPos + 1; + end; + + spellable + end canSpell ; + + % the letters available on the faces of the blocks % + string(20) face1, face2; + face1 := "BXDCNGRTQFJHVAOEFLPZ"; + face2 := "OKQPATEGDSWUINBRSYCM"; + + begin + % test the can spell procedure % + procedure testCanSpell ( string(20) value word + ; integer value wordLength + ) ; + write( if canSpell( word, wordLength ) then "can " else "cannot" + , " spell """ + , word + , """" + ); + + testCanSpell( "a", 1 ); + testCanSpell( "bark", 4 ); + testCanSpell( "BOOK", 4 ); + testCanSpell( "treat", 5 ); + testCanSpell( "commoN", 6 ); + testCanSpell( "Squad", 5 ); + testCanSpell( "confuse", 7 ) + end +end. diff --git a/Task/ABC-Problem/AppleScript/abc-problem.applescript b/Task/ABC-Problem/AppleScript/abc-problem.applescript new file mode 100644 index 0000000000..1c6047df28 --- /dev/null +++ b/Task/ABC-Problem/AppleScript/abc-problem.applescript @@ -0,0 +1,27 @@ +set blocks to {"bo", "xk", "dq", "cp", "na", "gt", "re", "tg", "qd", "fs", "jw", "hu", "vi", "an", "ob", "er", "fs", "ly", "pc", "zm"} + +canMakeWordWithBlocks("a", blocks) +canMakeWordWithBlocks("bark", blocks) +canMakeWordWithBlocks("book", blocks) +canMakeWordWithBlocks("treat", blocks) +canMakeWordWithBlocks("common", blocks) +canMakeWordWithBlocks("squad", blocks) +canMakeWordWithBlocks("confuse", blocks) + +on canMakeWordWithBlocks(theString, constBlocks) + copy constBlocks to theBlocks + if theString = "" then return true + set i to 1 + repeat + if i > (count theBlocks) then exit repeat + if character 1 of theString is in item i of theBlocks then + set item i of theBlocks to missing value + set theBlocks to strings of theBlocks + if canMakeWordWithBlocks(rest of characters of theString as string, theBlocks) then + return true + end if + end if + set i to i + 1 + end repeat + return false +end canMakeWordWithBlocks diff --git a/Task/ABC-Problem/C-sharp/abc-problem-1.cs b/Task/ABC-Problem/C-sharp/abc-problem-1.cs new file mode 100644 index 0000000000..5fefe3e240 --- /dev/null +++ b/Task/ABC-Problem/C-sharp/abc-problem-1.cs @@ -0,0 +1,30 @@ +using System; +using System.IO; +// Needed for the method. +using System.Text.RegularExpressions; +using System.Collections.Generic; + +void Main() +{ + string blocks = "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" + }; + + foreach(var word in words) + { + Console.WriteLine("{0}: {1}", word, CheckWord(blocks, word)); + } +} + +bool CheckWord(string blocks, string word) +{ + for(int i = 0; i < word.Length; ++i) + { + int length = blocks.Length; + Regex rgx = new Regex("([a-z]"+word[i]+"|"+word[i]+"[a-z])", RegexOptions.IgnoreCase); + blocks = rgx.Replace(blocks, "", 1); + if(blocks.Length == length) return false; + } + return true; +} diff --git a/Task/ABC-Problem/C-sharp/abc-problem.cs b/Task/ABC-Problem/C-sharp/abc-problem-2.cs similarity index 100% rename from Task/ABC-Problem/C-sharp/abc-problem.cs rename to Task/ABC-Problem/C-sharp/abc-problem-2.cs diff --git a/Task/ABC-Problem/J/abc-problem-3.j b/Task/ABC-Problem/J/abc-problem-3.j index 56e3992269..99b0cf6d30 100644 --- a/Task/ABC-Problem/J/abc-problem-3.j +++ b/Task/ABC-Problem/J/abc-problem-3.j @@ -1,3 +1,4 @@ delElem=: {~<@<@< uppc=:(-32*96&<*.123&>)&.(3&u:) reduc=: ] delElem 1 i.~e."0 1 +forms=: (1 - '' -: (reduc L:0/ :: (a:"_)@(<"0@],<@[))&uppc) L:0 diff --git a/Task/ABC-Problem/J/abc-problem-6.j b/Task/ABC-Problem/J/abc-problem-6.j new file mode 100644 index 0000000000..0a0212b75b --- /dev/null +++ b/Task/ABC-Problem/J/abc-problem-6.j @@ -0,0 +1,14 @@ + Blocks canform 0{::ExampleWords +1 + word +A + need +2 + relevant +NA +AN + candidates +ANA +ANN +AAA +AAN diff --git a/Task/ABC-Problem/JavaScript/abc-problem-1.js b/Task/ABC-Problem/JavaScript/abc-problem-1.js new file mode 100644 index 0000000000..c1fca996a0 --- /dev/null +++ b/Task/ABC-Problem/JavaScript/abc-problem-1.js @@ -0,0 +1,37 @@ +var blocks = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM"; + +function CheckWord(blocks, word) { + // Makes sure that word only contains letters. + if(word !== /([a-z]*)/i.exec(word)[1]) return false; + // Loops through each character to see if a block exists. + for(var i = 0; i < word.length; ++i) + { + // Gets the ith character. + var letter = word.charAt(i); + // Stores the length of the blocks to determine if a block was removed. + var length = blocks.length; + // The regexp gets constructed by eval to allow more browsers to use the function. + var reg = eval("/([a-z]"+letter+"|"+letter+"[a-z])/i"); + // This does the same as above, but some browsers do not support... + //var reg = new RegExp("([a-z]"+letter+"|"+letter+"[a-z])", "i"); + // Removes all occurrences of the match. + blocks = blocks.replace(reg, ""); + // If the length did not change then a block did not exist. + if(blocks.length === length) return false; + } + // If every character has passed then return true. + return true; +}; + +var words = [ + "A", + "BARK", + "BOOK", + "TREAT", + "COMMON", + "SQUAD", + "CONFUSE" +]; + +for(var i = 0;iPrint("\"\": ")->PrintLine(CanMakeWord("", blocks)); + IO.Console->Print("A: ")->PrintLine(CanMakeWord("A", blocks)); + IO.Console->Print("BARK: ")->PrintLine(CanMakeWord("BARK", blocks)); + IO.Console->Print("book: ")->PrintLine(CanMakeWord("book", blocks)); + IO.Console->Print("treat: ")->PrintLine(CanMakeWord("treat", blocks)); + IO.Console->Print("COMMON: ")->PrintLine(CanMakeWord("COMMON", blocks)); + IO.Console->Print("SQuAd: ")->PrintLine(CanMakeWord("SQuAd", blocks)); + IO.Console->Print("CONFUSE: ")->PrintLine(CanMakeWord("CONFUSE", blocks)); + } + + function : CanMakeWord(word : String, blocks : String[]) ~ Bool { + if(word->Size() = 0) { + return true; + }; + + c := word->Get(0)->ToUpper(); + for(i := 0; i < blocks->Size(); i++;) { + b := blocks[i]; + if(<>(b->Get(0)->ToUpper() <> c & b->Get(1)->ToUpper() <> c)) { + Swap(0, i, blocks); + new_word := word->SubString(1, word->Size() - 1); + new_blocks := String->New[blocks->Size() - 1]; + Runtime->Copy(new_blocks, 0, blocks, 1, blocks->Size() - 1); + if(CanMakeWord(new_word, new_blocks)) { + return true; + }; + Swap(0, i, blocks); + }; + }; + + return false; + } + + function : native : Swap(i : Int, j : Int, arr : String[]) ~ Nil { + tmp := arr[i]; + arr[i] := arr[j]; + arr[j] := tmp; + } +} diff --git a/Task/ABC-Problem/Perl-6/abc-problem.pl6 b/Task/ABC-Problem/Perl-6/abc-problem.pl6 index 0f331a2891..fd9c9b4fa3 100644 --- a/Task/ABC-Problem/Perl-6/abc-problem.pl6 +++ b/Task/ABC-Problem/Perl-6/abc-problem.pl6 @@ -1,6 +1,6 @@ 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; + can-spell-word $word.uc.comb.list, @regex; } multi can-spell-word([$head,*@tail], @regex) { @@ -8,7 +8,7 @@ multi can-spell-word([$head,*@tail], @regex) { if $head ~~ $re { return True unless @tail; return False if @regex == 1; - return True if can-spell-word @tail, @regex.grep: * !=== $re; + return True if can-spell-word @tail, list @regex.grep: * !=== $re; } } False; diff --git a/Task/ABC-Problem/PowerShell/abc-problem.psh b/Task/ABC-Problem/PowerShell/abc-problem.psh new file mode 100644 index 0000000000..9fd301dcac --- /dev/null +++ b/Task/ABC-Problem/PowerShell/abc-problem.psh @@ -0,0 +1,117 @@ +<# +.Synopsis + ABC Problem +.DESCRIPTION + 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 + blocks = "BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM" + 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: + >>> 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 + + Using the examples below you can either see just the value or + status and the values using the verbose switch + +.EXAMPLE + test-blocks -testword confuse + +.EXAMPLE + test-blocks -testword confuse -verbose + +#> + +function test-blocks +{ + [CmdletBinding()] + # [OutputType([int])] + Param + ( + # word to test against blocks + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true)] + $testword + + ) + + $word = $testword + + #define array of blocks + [System.Collections.ArrayList]$blockarray = "BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM" + + #send word to chararray + $chararray = $word.ToCharArray() + $chars = $chararray + + #get the character count + $charscount = $chars.count + + #get the initial count of the blocks + $blockcount = $blockarray.Count + + #find out how many blocks should be left from the difference + #of the blocks and characters in the word - 1 letter/1 block + $correctblockcount = $blockcount - $charscount + + #loop through the characters in the word + foreach ($char in $chars) + { + + #loop through the blocks + foreach ($block in $blockarray) + { + + #check the current character against each letter on the current block + #and break if found so the array can reload + if ($char -in $block[0] -or $char -in $block[1]) + { + + write-verbose "match for letter - $char - removing block $block" + $blockarray.Remove($block) + break + + } + + } + + } + #get final count of blocks left in array to determine if the word was + #correctly made + $finalblockcount = $blockarray.count + if ($finalblockcount -ne $correctblockcount) + { + write-verbose "$word : $false " + return $false + } + else + { + write-verbose "$word : $true " + return $true + } + +} + +#loop all the words and pass them to the function +$wordlist = "a", "bark", "book", "treat", "common", "squad", "confuse" +foreach ($word in $wordlist) +{ + test-blocks -testword $word -Verbose +} diff --git a/Task/ABC-Problem/Prolog/abc-problem.pro b/Task/ABC-Problem/Prolog/abc-problem-1.pro similarity index 100% rename from Task/ABC-Problem/Prolog/abc-problem.pro rename to Task/ABC-Problem/Prolog/abc-problem-1.pro diff --git a/Task/ABC-Problem/Prolog/abc-problem-2.pro b/Task/ABC-Problem/Prolog/abc-problem-2.pro new file mode 100644 index 0000000000..6b02f606d9 --- /dev/null +++ b/Task/ABC-Problem/Prolog/abc-problem-2.pro @@ -0,0 +1,18 @@ +:- use_module([ library(chr), + abathslib(protelog/composer) ]). + +:- chr_constraint blocks, block/1, letter/1, word_built. + +can_build_word(Word) :- + maplist(block, [(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)]), + maplist(letter) <- string_chars <- string_lower(Word), %% using the `composer` module + word_built, + !. + +'take letter and block' @ letter(L), block((A,B)) <=> L == A ; L == B | true. +'fail if letters remain' @ word_built, letter(_) <=> false. + +%% These rules, removing remaining constraints from the store, are just cosmetic: +'clean up blocks' @ word_built \ block(_) <=> true. +'word was built' @ word_built <=> true. diff --git a/Task/ABC-Problem/Prolog/abc-problem-3.pro b/Task/ABC-Problem/Prolog/abc-problem-3.pro new file mode 100644 index 0000000000..6779165b18 --- /dev/null +++ b/Task/ABC-Problem/Prolog/abc-problem-3.pro @@ -0,0 +1,14 @@ +?- can_build_word("A"). +true. +?- can_build_word("BARK"). +true. +?- can_build_word("BOOK"). +false. +?- can_build_word("TREAT"). +true. +?- can_build_word("COMMON"). +false. +?- can_build_word("SQUAD"). +true. +?- can_build_word("CONFUSE"). +true. diff --git a/Task/ABC-Problem/PureBasic/abc-problem-1.purebasic b/Task/ABC-Problem/PureBasic/abc-problem-1.purebasic new file mode 100644 index 0000000000..e05892c1a0 --- /dev/null +++ b/Task/ABC-Problem/PureBasic/abc-problem-1.purebasic @@ -0,0 +1,32 @@ +EnableExplicit +#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM " + +Procedure.s can_make_word(word.s) + Define.s letters = #LETTERS, buffer + Define.i index1, index2 + Define.b match + For index1=1 To Len(word) + index2=1 : match=#False + Repeat + buffer=StringField(letters,index2,Space(1)) + If FindString(buffer,Mid(word,index1,1),1,#PB_String_NoCase) + letters=RemoveString(letters,buffer+Chr(32),0,1,1) + match=#True + Break + EndIf + index2+1 + Until index2>CountString(letters,Space(1)) + If Not match : ProcedureReturn word+#TAB$+"FALSE" : EndIf + Next + ProcedureReturn word+#TAB$+"TRUE" +EndProcedure + +OpenConsole() +PrintN(can_make_word("a")) +PrintN(can_make_word("BaRK")) +PrintN(can_make_word("BOoK")) +PrintN(can_make_word("TREAt")) +PrintN(can_make_word("cOMMON")) +PrintN(can_make_word("SqUAD")) +PrintN(can_make_word("COnFUSE")) +Input() diff --git a/Task/ABC-Problem/PureBasic/abc-problem-2.purebasic b/Task/ABC-Problem/PureBasic/abc-problem-2.purebasic new file mode 100644 index 0000000000..cdda3b84bb --- /dev/null +++ b/Task/ABC-Problem/PureBasic/abc-problem-2.purebasic @@ -0,0 +1,21 @@ +Define.i +#LETTERS = "BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM " + +Macro test(t) + Print(t+#TAB$+#TAB$+"= ") : If can_make_word(t) : PrintN("True") : Else : PrintN("False") : EndIf +EndMacro + +Procedure.s residue(s$,n.i) + ProcedureReturn Left(s$,Int(n/3)*3)+Mid(s$,Int(n/3)*3+4) +EndProcedure + +Procedure.b can_make_word(word$,letters$=#LETTERS) + n=FindString(letters$,Left(word$,1),1,#PB_String_NoCase) + If Len(word$) And n : ProcedureReturn can_make_word(Mid(word$,2),residue(letters$,n)) : EndIf + If Not Len(word$) : ProcedureReturn #True : Else : ProcedureReturn #False : EndIf +EndProcedure + +OpenConsole() +test("a") : test("BaRK") : test("BOoK") : test("TREAt") +test("cOMMON") : test("SqUAD") : test("COnFUSE") +Input() diff --git a/Task/ABC-Problem/REXX/abc-problem-1.rexx b/Task/ABC-Problem/REXX/abc-problem-1.rexx index 4e78f30afe..b5152e475b 100644 --- a/Task/ABC-Problem/REXX/abc-problem-1.rexx +++ b/Task/ABC-Problem/REXX/abc-problem-1.rexx @@ -1,24 +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.*/ +/*REXX program determines if words can be spelt from a pool of toy blocks. */ +list= 'A bark bOOk treat common squaD conFuse' /*words can be in 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 a list of seven words*/ + call spell word(list,k) /*display if word can be spelt (or not)*/ + end /*k*/ /* [↑] tests each word in the list. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +spell: procedure expose blocks; arg x; p.=0 /*uppercase word to be spelt. */ +parse upper var blocks theBlocks; L=length(x) /*uppercase the block letters.*/ + /* [↓] try to spell the word.*/ + do try=1 for L; z=theBlocks /*use a fresh copy of Z blocks*/ + do n=1 for L; y=substr(x,n,1) /*attempt another block letter*/ + p.n=pos(y,z,1+p.n); if p.n==0 then iterate try /*not found? Try again.*/ + z=overlay(' ',z,p.n) /*mutate block ───► a onesy.*/ + do k=1 for words(blocks) /*scrub block pool (not 1s). */ + if length(word(z,k))==1 then z=delword(z,k,1) /*single char? Delete.*/ + end /*k*/ /* [↑] elide any onesy block.*/ + if n==L then leave try /*was the last letter spelt? */ + end /*n*/ /* [↑] end of a block attempt*/ + end /*try*/ /* [↑] end of "TRY" permute. */ -say right(ox,30) right(word("can't can", (n==L)+1), 6) 'be spelt.' -return n==L /*also, return the flag.*/ +say right(arg(1),30) right(word("can't can", (n==L)+1), 6) 'be spelt.' +return diff --git a/Task/ABC-Problem/Rust/abc-problem.rust b/Task/ABC-Problem/Rust/abc-problem.rust index 7ae452408a..ebc29201a6 100644 --- a/Task/ABC-Problem/Rust/abc-problem.rust +++ b/Task/ABC-Problem/Rust/abc-problem.rust @@ -1,33 +1,29 @@ -#![feature(core, unicode)] -extern crate core; -extern crate unicode; - -use core::iter::repeat; -use core::str::StrExt; -use unicode::char::CharExt; +use std::iter::repeat; 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 + let c = word.chars().nth(index).unwrap().to_uppercase().next().unwrap(); + for i in 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()); + return rec_can_make_word(word.chars().count() - 1, word, blocks, + &mut repeat(false).take(blocks.len()).collect::>()); } 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())) - } + 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 { + println!("{} -> {}", word, can_make_word(word, &blocks)) + } } diff --git a/Task/ABC-Problem/Scheme/abc-problem.ss b/Task/ABC-Problem/Scheme/abc-problem.ss new file mode 100644 index 0000000000..9a9f4a9025 --- /dev/null +++ b/Task/ABC-Problem/Scheme/abc-problem.ss @@ -0,0 +1,41 @@ +(define *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))) + +(define (exists p? li) + (and (not (null? li)) + (or (p? (car li)) + (exists p? (cdr li))))) + +(define (remove-one x li) + (cond + ((null? li) '()) + ((equal? (car li) x) (cdr li)) + (else (cons (car li) (remove-one x (cdr li)))))) + +(define (can-make-list? li blocks) + (or (null? li) + (exists + (lambda (block) + (and + (member (char-upcase (car li)) block) + (can-make-list? (cdr li) (remove-one block blocks)))) + blocks))) + +(define (can-make-word? word) + (can-make-list? (string->list word) *blocks*)) + + +(define *words* + '("A" "Bark" "book" "TrEaT" "COMMON" "squaD" "CONFUSE")) + +(for-each + (lambda (word) + (display (if (can-make-word? word) + " Can make word: " + "Cannot make word: ")) + (display word) + (newline)) + *words*) diff --git a/Task/AKS-test-for-primes/00DESCRIPTION b/Task/AKS-test-for-primes/00DESCRIPTION index 9b1322f542..c709f6e5bf 100644 --- a/Task/AKS-test-for-primes/00DESCRIPTION +++ b/Task/AKS-test-for-primes/00DESCRIPTION @@ -15,6 +15,8 @@ For example, trying p=3: :And all the coefficients are divisible by 3 so 3 is prime. +{{alertbox|#ffe4e4|'''Note:'''
This task is '''not''' the AKS primality test. It is an inefficient exponential time algorithm discovered in the late 1600s and used as an introductory lemma in the AKS derivation.}} + ;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. @@ -22,9 +24,6 @@ For example, trying p=3: # 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/ALGOL-68/aks-test-for-primes.alg b/Task/AKS-test-for-primes/ALGOL-68/aks-test-for-primes.alg new file mode 100644 index 0000000000..9483422a08 --- /dev/null +++ b/Task/AKS-test-for-primes/ALGOL-68/aks-test-for-primes.alg @@ -0,0 +1,86 @@ +BEGIN +COMMENT + Mathematical preliminaries. + + First note that the homogeneous polynomial (a+b)^n is symmetrical + (to see this just swap the variables a and b). Therefore its + coefficients need be calculated only to that of (ab)^{n/2} for even + n or (ab)^{(n-1)/2} for odd n. + + Second, the coefficients are the binomial coefficients C(n,k) where + the coefficient of a^k b^(n-k) is C(n,k) = n! / k! (k-1)!. This + leads to an immediate and relatively efficient implementation for + which we do not need to compute n! before dividing by k! and (k-1)! + but, rather cancel common factors as we go along. Further, the + well-known symmetry identity C(n,k) = C(n, n-k) allows a + significant reduction in computational effort. + + Third, (x-1)^n is the value of (a + b)^n when a=x and b = -1. The + powers of -1 alternate between +1 and -1 so we may as well compute + (x+1)^n and negate every other coefficient when printing. +COMMENT + PR precision=300 PR + MODE LLI = LONG LONG INT; CO For brevity CO + PROC choose = (INT n, k) LLI : + BEGIN + LLI result := 1; + INT sym k := (k >= n%2 | n-k | k); CO Use symmetry CO + IF sym k > 0 THEN + FOR i FROM 0 TO sym k-1 + DO + result TIMESAB (n-i); + result OVERAB (i+1) + OD + FI; + result + END; + PROC coefficients = (INT n) [] LLI : + BEGIN + [0:n] LLI a; + FOR i FROM 0 TO n%2 + DO + a[i] := a[n-i] := choose (n, i) CO Use symmetry CO + OD; + a + END; +COMMENT + First print the polynomials (x-1)^n, remembering to alternate signs + and to tidy up the constant term, the x^1 term and the x^n term. + This means we must treat (x-1)^0 and (x-1)^1 specially +COMMENT + FOR n FROM 0 TO 7 + DO + [0:n] LLI a := coefficients (n); + printf (($"(x-1)^", g(0), " = "$, n)); + CASE n+1 IN + printf (($g(0)l$, a[0])), + printf (($"x - ", g(0)l$, a[1])) + OUT + printf (($"x^", g(0)$, n)); + FOR i TO n-2 + DO + printf (($xax, g(0), "x^", g(0)$, (ODD i | "-" | "+"), a[i], n-i)) + OD; + printf (($xax, g(0), "x"$, (ODD (n-1) | "-" | "+"), a[n-1])); + printf (($xaxg(0)l$, (ODD n | "-" | "+"), a[n])) + ESAC +OD; +COMMENT + Finally, for the "AKS" portion of the task, the sign of the + coefficient has no effect on its divisibility by p so, once again, + we may as well use the positive coefficients. Symmetry clearly + reduces the necessary number of tests by a factor of two. +COMMENT + PROC is prime = (INT n) BOOL : + BEGIN + BOOL prime := TRUE; + FOR i FROM 1 TO n%2 WHILE prime DO prime := choose (n, i) MOD n = 0 OD; + prime + END; + print ("Primes < 50 are "); + FOR n FROM 2 TO 50 DO (is prime (n) | printf (($g(0)x$, n)) ) OD; + print (newline); + print ("And just to show off, the primes between 900 and 1000 are "); + FOR n FROM 900 TO 1000 DO IF is prime (n) THEN printf (($g(0)x$, n)) FI OD; + print (newline) +END diff --git a/Task/AKS-test-for-primes/C-sharp/aks-test-for-primes.cs b/Task/AKS-test-for-primes/C-sharp/aks-test-for-primes.cs new file mode 100644 index 0000000000..80b0711b7c --- /dev/null +++ b/Task/AKS-test-for-primes/C-sharp/aks-test-for-primes.cs @@ -0,0 +1,53 @@ +using System; + public class AksTest + { + static long[] c = new long[100]; + + static void Main(string[] args) + { + for (int n = 0; n < 10; n++) { + coef(n); + Console.Write("(x-1)^" + n + " = "); + show(n); + Console.WriteLine(""); + } + Console.Write("Primes:"); + for (int n = 1; n <= 63; n++) + if (is_prime(n)) + Console.Write(n + " "); + + Console.WriteLine('\n'); + Console.ReadLine(); + } + + static void coef(int n) + { + int i, j; + + if (n < 0 || n > 63) System.Environment.Exit(0);// gracefully deal with range issue + + for (c[i = 0] = 1L; i < n; c[0] = -c[0], i++) + for (c[1 + (j = i)] = 1L; j > 0; j--) + c[j] = c[j - 1] - c[j]; + } + + static bool is_prime(int n) + { + int i; + + coef(n); + c[0] += 1; + c[i = n] -= 1; + + while (i-- != 0 && (c[i] % n) == 0) ; + + return i < 0; + } + + static void show(int n) + { + do { + Console.Write("+" + c[n] + "x^" + n); + }while (n-- != 0); + } + } diff --git a/Task/AKS-test-for-primes/Forth/aks-test-for-primes.fth b/Task/AKS-test-for-primes/Forth/aks-test-for-primes.fth new file mode 100644 index 0000000000..78cd84269e --- /dev/null +++ b/Task/AKS-test-for-primes/Forth/aks-test-for-primes.fth @@ -0,0 +1,25 @@ +: coeffs ( u -- nu ... n0 ) \ coefficients of (x-1)^u + 1 swap 1+ dup 1 ?do over over i - i */ negate swap loop drop ; + +: prime? ( u -- f ) + dup 2 < if drop false exit then + dup >r coeffs 1+ + \ if not prime, this loop consumes at most half the coefficients, otherwise all + begin dup 1 <> while + r@ mod 0= while + repeat then rdrop + dup 1 = >r + begin 1 = until + r> ; + +: .monom ( u1 u2 -- ) + dup 0> if [char] + emit then 0 .r ?dup if ." x^" . else space then ; +: .poly ( u -- ) + dup >r coeffs 0 r> 1+ 0 ?do + tuck swap .monom 1+ + loop ; + +: main + 11 0 ?do i . ." : " i .poly cr loop cr + 50 1 ?do i prime? if i . then loop + cr ; diff --git a/Task/AKS-test-for-primes/Fortran/aks-test-for-primes.f b/Task/AKS-test-for-primes/Fortran/aks-test-for-primes.f new file mode 100644 index 0000000000..5bc2c2d561 --- /dev/null +++ b/Task/AKS-test-for-primes/Fortran/aks-test-for-primes.f @@ -0,0 +1,138 @@ +program aks + implicit none + + ! Coefficients of polynomial expansion + integer(kind=16), dimension(:), allocatable :: coeffs + integer(kind=16) :: n + ! Character variable for I/O + character(len=40) :: tmp + + ! Point #2 + do n = 0, 7 + write(tmp, *) n + call polynomial_expansion(n, coeffs) + write(*, fmt='(A)', advance='no') '(x - 1)^'//trim(adjustl(tmp))//' =' + call print_polynom(coeffs) + end do + + ! Point #4 + do n = 2, 35 + if (is_prime(n)) write(*, '(I4)', advance='no') n + end do + write(*, *) + + ! Point #5 + do n = 2, 124 + if (is_prime(n)) write(*, '(I4)', advance='no') n + end do + write(*, *) + + if (allocated(coeffs)) deallocate(coeffs) +contains + ! Calculate coefficients of (x - 1)^n using binomial theorem + subroutine polynomial_expansion(n, coeffs) + integer(kind=16), intent(in) :: n + integer(kind=16), dimension(:), allocatable, intent(out) :: coeffs + integer(kind=16) :: i, j + + if (allocated(coeffs)) deallocate(coeffs) + + allocate(coeffs(n + 1)) + + do i = 1, n + 1 + coeffs(i) = binomial(n, i - 1)*(-1)**(n - i - 1) + end do + end subroutine + + ! Calculate binomial coefficient using recurrent relation, as calculation + ! using factorial overflows too quickly. + function binomial(n, k) result (res) + integer(kind=16), intent(in) :: n, k + integer(kind=16) :: res + integer(kind=16) :: i + + if (k == 0) then + res = 1 + return + end if + + res = 1 + do i = 0, k - 1 + res = res*(n - i)/(i + 1) + end do + end function + + ! Outputs polynomial with given coefficients + subroutine print_polynom(coeffs) + integer(kind=16), dimension(:), allocatable, intent(in) :: coeffs + integer(kind=4) :: i, p + character(len=40) :: cbuf, pbuf + logical(kind=1) :: non_zero + + if (.not. allocated(coeffs)) return + + non_zero = .false. + + do i = 1, size(coeffs) + if (coeffs(i) .eq. 0) cycle + + p = i - 1 + write(cbuf, '(I40)') abs(coeffs(i)) + write(pbuf, '(I40)') p + + if (non_zero) then + if (coeffs(i) .gt. 0) then + write(*, fmt='(A)', advance='no') ' + ' + else + write(*, fmt='(A)', advance='no') ' - ' + endif + else + if (coeffs(i) .gt. 0) then + write(*, fmt='(A)', advance='no') ' ' + else + write(*, fmt='(A)', advance='no') ' - ' + endif + endif + + if (p .eq. 0) then + write(*, fmt='(A)', advance='no') trim(adjustl(cbuf)) + elseif (p .eq. 1) then + if (coeffs(i) .eq. 1) then + write(*, fmt='(A)', advance='no') 'x' + else + write(*, fmt='(A)', advance='no') trim(adjustl(cbuf))//'x' + end if + else + if (coeffs(i) .eq. 1) then + write(*, fmt='(A)', advance='no') 'x^'//trim(adjustl(pbuf)) + else + write(*, fmt='(A)', advance='no') & + trim(adjustl(cbuf))//'x^'//trim(adjustl(pbuf)) + end if + end if + non_zero = .true. + end do + + write(*, *) + end subroutine + + ! Test if n is prime using AKS test. Point #3. + function is_prime(n) result (res) + integer(kind=16), intent (in) :: n + logical(kind=1) :: res + integer(kind=16), dimension(:), allocatable :: coeffs + integer(kind=16) :: i + + call polynomial_expansion(n, coeffs) + coeffs(1) = coeffs(1) + 1 + coeffs(n + 1) = coeffs(n + 1) - 1 + + res = .true. + + do i = 1, n + 1 + res = res .and. (mod(coeffs(i), n) == 0) + end do + + if (allocated(coeffs)) deallocate(coeffs) + end function +end program aks diff --git a/Task/AKS-test-for-primes/Java/aks-test-for-primes.java b/Task/AKS-test-for-primes/Java/aks-test-for-primes.java new file mode 100644 index 0000000000..b7ea1a286b --- /dev/null +++ b/Task/AKS-test-for-primes/Java/aks-test-for-primes.java @@ -0,0 +1,52 @@ +public class AksTest +{ + static Long[] c = new Long[100]; + + public static void main(String[] args) + { + for (int n = 0; n < 10; n++) { + coef(n); + System.out.print("(x-1)^" + n + " = "); + show(n); + System.out.println(""); + } + + System.out.print("Primes:"); + for (int n = 1; n <= 63; n++) + if (is_prime(n)) + System.out.printf(" %d", n); + + System.out.println('\n'); + } + + static void coef(int n) + { + int i, j; + + if (n < 0 || n > 63) System.exit(0); // gracefully deal with range issue + + for (c[i=0] = 1l; i < n; c[0] = -c[0], i++) + for (c[1 + (j=i)] = 1l; j > 0; j--) + c[j] = c[j-1] - c[j]; + } + + static boolean is_prime(int n) + { + int i; + + coef(n); + c[0] += 1; + c[i=n] -= 1; + + while (i-- != 0 && (c[i] % n) == 0); + + return i < 0; + } + + static void show(int n) + { + do { + System.out.print("+" + c[n] + "x^"+ n); + }while (n-- != 0); + } +} 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-1.js similarity index 100% rename from Task/AKS-test-for-primes/JavaScript/aks-test-for-primes.js rename to Task/AKS-test-for-primes/JavaScript/aks-test-for-primes-1.js diff --git a/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes-2.js b/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes-2.js new file mode 100644 index 0000000000..b2fe7e4cfc --- /dev/null +++ b/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes-2.js @@ -0,0 +1,23 @@ +function pascal(n) { + var cs = []; if (n) while (n--) coef(); return coef + function coef() { + if (cs.length === 0) return cs = [1]; + for (var t=[1,1], i=cs.length-1; i; i-=1) t.splice( 1, 0, cs[i-1]+cs[i] ); return cs = t + } +} + +function show(cs) { + for (var s='', sgn=true, i=0, deg=cs.length-1; i<=deg; sgn=!sgn, i+=1) { + s += ' ' + (sgn ? '+' : '-') + cs[i] + (e => e==0 ? '' : e==1 ? 'x' : 'x' + e + '')(deg-i) + } + return '(x-1)' + deg + ' =' + s; +} + +function isPrime(cs) { + var deg=cs.length-1; return cs.slice(1, deg).every( function(c) { return c % deg === 0 } ) +} + +var coef=pascal(); for (var i=0; i<=7; i+=1) document.write(show(coef()), '
') + +document.write('
Primes: '); +for (var coef=pascal(2), n=2; n<=50; n+=1) if (isPrime(coef())) document.write(' ', n) diff --git a/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes-3.js b/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes-3.js new file mode 100644 index 0000000000..42fbb953cb --- /dev/null +++ b/Task/AKS-test-for-primes/JavaScript/aks-test-for-primes-3.js @@ -0,0 +1,22 @@ +function coef(n) { + for (var c=[1], i=0; i0 ? ' +' : ' ') + cs[n] + (n==0 ? '' : n==1 ? 'x' :'x'+n+''); while (n--) + return s +} + +function isPrime(n) { + var cs=coef(n), i=n-1; while (i-- && cs[i]%n == 0); + return i < 1 +} + +for (var n=0; n<=7; n++) document.write('(x-1)',n,' = ', show(coef(n)), '
') + +document.write('
Primes: '); +for (var n=2; n<=50; n++) if (isPrime(n)) document.write(' ', n) diff --git a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-1.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-1.julia new file mode 100644 index 0000000000..714332c76b --- /dev/null +++ b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-1.julia @@ -0,0 +1,12 @@ +function polycoefs(n::Int64) + pc = typeof(n)[] + if n < 0 + return pc + end + sgn = one(n) + for k in n:-1:0 + push!(pc, sgn*binomial(n, k)) + sgn = -sgn + end + return pc +end diff --git a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.julia new file mode 100644 index 0000000000..1cc9df25e6 --- /dev/null +++ b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.julia @@ -0,0 +1,27 @@ +function stringpoly(n::Int64) + if n < 0 + return "" + end + st = @sprintf "(x - 1)^{%d} & = & " n + for (i, c) in enumerate(polycoefs(n)) + if i == 1 + op = "" + ac = c + elseif c < 0 + op = "-" + ac = abs(c) + else + op = "+" + ac = abs(c) + end + p = n + 1 - i + if p == 0 + st *= @sprintf " %s %d\\\\" op ac + elseif ac == 1 + st *= @sprintf " %s x^{%d}" op p + else + st *= @sprintf " %s %dx^{%d}" op ac p + end + end + return st +end diff --git a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-3.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-3.julia new file mode 100644 index 0000000000..a0f749937f --- /dev/null +++ b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-3.julia @@ -0,0 +1,11 @@ +function isaksprime(n::Int64) + if n < 2 + return false + end + for c in polycoefs(n)[2:(end-1)] + if c%n != 0 + return false + end + end + return true +end diff --git a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-4.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-4.julia new file mode 100644 index 0000000000..ddac5cdfdc --- /dev/null +++ b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-4.julia @@ -0,0 +1,18 @@ +println("") +println("\\begin{array}{lcl}") +for i in 0:10 + println(stringpoly(i)) +end +println("\\end{array}") +println("\n") + +L = 50 +print("AKS primes less than ", L, ": ") +sep = "" +for i in 1:L + if isaksprime(i) + print(sep, i) + sep = ", " + end +end +println() diff --git a/Task/AKS-test-for-primes/Objeck/aks-test-for-primes.objeck b/Task/AKS-test-for-primes/Objeck/aks-test-for-primes.objeck new file mode 100644 index 0000000000..824341367a --- /dev/null +++ b/Task/AKS-test-for-primes/Objeck/aks-test-for-primes.objeck @@ -0,0 +1,57 @@ +class AksTest { + @c : static : Int[]; + + function : Main(args : String[]) ~ Nil { + @c := Int->New[100]; + + for(n := 0; n < 10; n++;) { + Coef(n); + "(x-1)^ {$n} = "->Print(); + Show(n); + '\n'->Print(); + }; + + "\nPrimes:"->PrintLine(); + for(n := 2; n <= 63; n++;) { + if(IsPrime(n)) { + " {$n}"->Print(); + }; + }; + '\n'->Print(); + } + + function : native : Coef(n : Int) ~ Nil { + i := 0; j := 0; + + if (n < 0 | n > 63) { + Runtime->Exit(0); + }; + + for(@c[0] := 1; i < n; i++;) { + j := i; + for(@c[1 + j] := 1; j > 0; j--;) { + @c[j] := @c[j-1] - @c[j]; + }; + @c[0] := @c[0] * -1; + }; + } + + function : native : IsPrime(n : Int) ~ Bool { + Coef(n); + @c[0] += 1; @c[n] -= 1; + + i:=n; + while (i <> 0 & (@c[i] % n) = 0) { + i--; + }; + + return i = 0; + } + + function : Show(n : Int) ~ Nil { + do { + value := @c[n]; + "+{$value}x^{$n}"->Print(); + } while (n-- <> 0); + } +} diff --git a/Task/AKS-test-for-primes/PL-I/aks-test-for-primes.pli b/Task/AKS-test-for-primes/PL-I/aks-test-for-primes.pli new file mode 100644 index 0000000000..f5057c51b1 --- /dev/null +++ b/Task/AKS-test-for-primes/PL-I/aks-test-for-primes.pli @@ -0,0 +1,135 @@ +AKS: procedure options (main, reorder); /* 16 September 2015, derived from Fortran */ + + /* Coefficients of polynomial expansion */ + declare coeffs(*) fixed (31) controlled; + declare n fixed(3); + + + /* Point #2 */ + do n = 0 to 7; + call polynomial_expansion(n, coeffs); + put edit ( '(x - 1)^', trim(n), ' =' ) (a); + call print_polynomial (coeffs); + end; + + /* Point #4 */ + put skip; + do n = 2 to 35; + if is_prime(n) then put edit ( trim (n) ) (x(1), a); + end; + + /* Point #5 */ + put skip; + do n = 2 to 97; + if is_prime(n) then put edit ( trim (n) ) (x(1), a); + end; + put skip; + + + + /* Calculate coefficients of (x - 1)^n using binomial theorem */ +polynomial_expansion: procedure (n, coeffs); + declare n fixed binary; + declare coeffs (*) fixed (31) controlled; + declare i fixed binary; + + if allocation(coeffs) > 0 then free coeffs; + allocate coeffs (n+1); + + do i = 1 to n + 1; + coeffs(i) = binomial(n, i - 1); + if iand(n - i - 1, 1) = 1 then coeffs(i) = -coeffs(i); + end; + end polynomial_expansion; + + /* Calculate binomial coefficient using recurrent relation, as calculation */ + /* using factorial overflows too quickly. */ +binomial: procedure (n, k) returns (fixed(31)); + declare (n, k) fixed; + declare i fixed; + declare result fixed (31) initial (n); + + if k = 0 then return (1); + + do i = 1 to k - 1; + result = (result*(n - i))/(i + 1); + end; + return (result); + end binomial; + + /* Outputs polynomial with given coefficients */ +print_polynomial: procedure (coeffs); + declare coeffs (*) fixed (31) controlled; + declare ( i, p ) fixed binary; + declare non_zero bit (1) aligned; + declare (true initial ('1'b), false initial ('0'b)) bit (1); + + if allocation(coeffs) = 0 then return; + + non_zero = false; + + do i = 1 to hbound(coeffs); + if coeffs(i) = 0 then iterate; + + p = i - 1; + + if non_zero then + do; + if coeffs(i) > 0 then + put edit ( ' + ' ) (a); + else + put edit ( ' - ' ) (a); + end; + else + do; + if coeffs(i) > 0 then + put edit ( ' ' ) (a); + else + put edit ( ' - ' ) (a); + end; + + if p = 0 then + put edit ( trim(abs(coeffs(i))) ) (a); + else if p = 1 then + do; + if coeffs(i) = 1 then + put edit ( 'x' ) (a); + else + put edit ( trim(abs(coeffs(i))), 'x' ) (a); + end; + else + do; + if coeffs(i) = 1 then + put edit ( 'x^', trim(p) ) (a); + else + put edit ( trim(abs(coeffs(i)) ), 'x^', trim(p)) (a); + end; + + non_zero = true; + end; + + put skip; + end print_polynomial; + + /* Test if n is prime using AKS test. Point #3. */ +is_prime: procedure (n) returns (bit (1)); + declare n fixed (15); + declare result bit (1) aligned; + declare coeffs (*) fixed (31) controlled; + declare i fixed binary; + + call polynomial_expansion(n, coeffs); + coeffs(1) = coeffs(1) + 1; + coeffs(n + 1) = coeffs(n + 1) - 1; + + result = '1'b; + + do i = 1 to n + 1; + result = result & (mod(coeffs(i), n) = 0); + end; + + if allocation(coeffs) > 0 then free coeffs; + return (result); + end is_prime; + +end AKS; 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-1.pl similarity index 100% rename from Task/AKS-test-for-primes/Perl/aks-test-for-primes.pl rename to Task/AKS-test-for-primes/Perl/aks-test-for-primes-1.pl diff --git a/Task/AKS-test-for-primes/Perl/aks-test-for-primes-2.pl b/Task/AKS-test-for-primes/Perl/aks-test-for-primes-2.pl new file mode 100644 index 0000000000..4be23657b4 --- /dev/null +++ b/Task/AKS-test-for-primes/Perl/aks-test-for-primes-2.pl @@ -0,0 +1,4 @@ +use ntheory ":all"; +# Uncomment next line to see the r and s values used. Set to 2 for more detail. +# prime_set_config(verbose => 1); +say join(" ", grep { is_aks_prime($_) } 1_000_000_000 .. 1_000_000_100); diff --git a/Task/AKS-test-for-primes/PureBasic/aks-test-for-primes.purebasic b/Task/AKS-test-for-primes/PureBasic/aks-test-for-primes.purebasic new file mode 100644 index 0000000000..0908f0ee06 --- /dev/null +++ b/Task/AKS-test-for-primes/PureBasic/aks-test-for-primes.purebasic @@ -0,0 +1,43 @@ +EnableExplicit +Define vzr.b = -1, vzc.b = ~vzr, nMAX.i = 10, n , k + +Procedure coeff(nRow.i, Array pd.i(2)) + Define.i n, k + For n=1 To nRow + For k=0 To n + If k=0 Or k=n : pd(n,k)=1 : Continue : EndIf + pd(n,k)=pd(n-1,k-1)+pd(n-1,k) + Next + Next +EndProcedure + +Procedure.b isPrime(n.i, Array pd.i(2)) + Define.i m + For m=1 To n-1 + If Not pd(n,m) % n = 0 : ProcedureReturn #False : EndIf + Next + ProcedureReturn #True +EndProcedure + +Dim pd.i(nMAX,nMAX) +pd(0,0)=1 : coeff(nMAX, pd()) +OpenConsole() + +For n=0 To nMAX + Print(RSet(Str(n),3,Chr(32))+": ") + If vzr : Print("+") : Else : Print("-") : EndIf + For k=0 To n + If k>0 : If vzc : Print("+") : Else : Print("-") : EndIf : vzc = ~vzc : EndIf + Print(RSet(Str(pd(n,k)),3,Chr(32))+Space(3)) + Next + PrintN("") + vzr = ~vzr : vzc = ~vzr +Next +PrintN("") + +nMAX=50 : Dim pd.i(nMAX,nMAX) +Print("Primes n<=50 : ") : coeff(nMAX, pd()) +For n=2 To 50 + If isPrime(n,pd()) : Print(Str(n)+Space(2)) : EndIf +Next +Input() 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 index da7833f1ec..69ad8f5ca7 100644 --- 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 @@ -1,20 +1,16 @@ -def expand_x_1(p): - ex = [1] - for i in range(p): - ex.append(ex[-1] * -(p-i) / (i+1)) - return ex[::-1] +def expand_x_1(n): +# This version uses a generator and thus less computations + c =1 + for i in range(n/2+1): + c = c*(n-i)/(i+1) + yield c -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]) +def aks(p): + if p==2: + return True - -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)]) + for i in expand_x_1(p): + if i % p: +# we stop without computing all possible solutions + return False + return True 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 index 4e7140c616..da7833f1ec 100644 --- 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 @@ -1,15 +1,20 @@ -print(''' -{| class="wikitable" style="text-align:left;" -|+ Polynomial Expansions and AKS prime test -|- -! p -! (x-1)^p -|-''') +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('! %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('|}') + 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-3.py b/Task/AKS-test-for-primes/Python/aks-test-for-primes-3.py new file mode 100644 index 0000000000..4e7140c616 --- /dev/null +++ b/Task/AKS-test-for-primes/Python/aks-test-for-primes-3.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/REXX/aks-test-for-primes-2.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx index 49977af5a2..f93378cb28 100644 --- a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx @@ -1,42 +1,40 @@ -/*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.*/ +/*REXX pgm calculates primes via the Agrawal-Kayal-Saxena (AKS) primality test*/ +parse arg Z .; if Z=='' then Z=200 /*Z not specified? Then use default.*/ +OZ=Z; tell=Z<0; Z=abs(Z) /*Is Z negative? Then show expression.*/ +numeric digits max(9,Z%3) /*define a dynamic # of decimal digits.*/ +$.0='-'; $.1="+"; @.=1 /*$.x: sign char; default coefficients.*/ +#= /*define list of prime numbers (so far)*/ + do p=3 for Z; pm=p-1; pp=p+1 /*PM & PP: used as a coding convenience*/ + do m=2 for pp%2-1; mm=m-1 /*calculate coefficients for a power. */ + @.p.m=@.pm.mm + @.pm.m; h=pp-m /*calculate left side of coefficients*/ + @.p.h=@.p.m /* " right " " " */ + end /*m*/ /* [↑] The M DO loop creates both */ + end /*p*/ /* sides in the same loop, saving */ + /* a bunch of execution time. */ +if tell then say '(x-1)^0: 1' /*possibly display the first expression*/ + /* [↓] test for primality by division.*/ + do n=2 for Z; nh=n%2; d=n-1 /*create expressions; find the primes.*/ + do k=3 to nh while @.n.k//d==0 /*are coefficients divisible by N-1 ? */ + end /*k*/ /* [↑] skip the 1st & 2nd coefficients*/ + /* [↓] multiple THEN─IF faster than &s*/ + if d\==1 then if d\==4 then if k>nh then #=# d /*add number to prime list.*/ + if \tell then iterate /*Don't tell? Don't show expressions.*/ + y='(x-1)^'d": " /*define first part of the expression. */ + s=1 /*S: is the sign indicator (-1│+1).*/ + do j=n to 2 by -1 /*create the higher powers first. */ + if j==2 then xp='x' /*if power=1, then don't show the power*/ + else xp='x^' || (j-1) /* ··· else show power with ^ */ + if j==n then y=y xp /*no sign (+│-) for the 1st expression.*/ + else y=y $.s @.n.j'∙'xp /*build the expression with sign (+|-).*/ + s=\s /*flip the sign for the next expression*/ + end /*j*/ /* [↑] the sign (now) is either 0 │ 1,*/ + /* and is displayed either - │ + */ + say y $.s 1 /*just show the first N expressions, */ + end /*n*/ /* [↑] ··· but only for negative Z. */ + say /* [↓] Has Z a leading + ? Then show.*/ +is="isn't"; if Z==word(. #,words(#)+1) then is='is' /*is or isn't a prime.*/ +if left(OZ,1)=='+' then say Z is 'prime.' /*tell if OZ has a +. */ + else say 'primes:' # /*display prime # list. */ +say /* [↓] size of big 'un.*/ +say 'Found ' words(#) ' primes and the largest coefficient has' , + length(@.pm.h) "decimal digits." /*stick a fork in it, we're all done. */ diff --git a/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust b/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust index c60dccf84d..11e268bfce 100644 --- a/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust +++ b/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust @@ -1,38 +1,32 @@ -//Rust 1.0.0-alpha -#![feature(core)] -extern crate core; - -use core::iter::repeat; +use std::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 + 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], |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) - } + if p < 2 { + false + } else { + let c = aks_coefficients(p); + (1 .. (c.len() - 1) / 2 + 1).all(|i| (c[i] % (p as i64)) == 0) + } } fn main() { - for i in 0us..8 { + for i in 0..8 { println!("{}: {:?}", i, aks_coefficients(i)); } - for i in (1us..51).filter(|&: &i| is_prime(i)) { - print!("{} ", i); + for i in (1..51).filter(|&i| is_prime(i)) { + print!("{} ", i); } } diff --git a/Task/Abstract-type/Eiffel/abstract-type.e b/Task/Abstract-type/Eiffel/abstract-type-1.e similarity index 100% rename from Task/Abstract-type/Eiffel/abstract-type.e rename to Task/Abstract-type/Eiffel/abstract-type-1.e diff --git a/Task/Abstract-type/Eiffel/abstract-type-2.e b/Task/Abstract-type/Eiffel/abstract-type-2.e new file mode 100644 index 0000000000..30b375bc7c --- /dev/null +++ b/Task/Abstract-type/Eiffel/abstract-type-2.e @@ -0,0 +1,61 @@ +note + title: "Prototype Person" + description: "Abstract notion of a {PERSON}." + synopsis: "[ + Abstract Data Types as represented by any Eiffel class, fully or partially implemented, are + not just about the attribute and routine features of the class (deferred or implemented). + The class and each feature may also have specification rules expressed as preconditions, + post-conditions, and class invariants. Other assertion contracts may be applied to fully + implemented features as well. + + In the example below, while `age' is deferred (i.e. "abstract"), we have coded a rule which + states that any caller of `age' must only do so after a `birth_date' has been defined and + attached to that feature. Failing to do so will cause a contract violation. Moreover, the + class invariant makes two strong assertions that must always hold for any implemented version + of {PERSON}: The `birth_date' (if attached--that is--not Void or null) must be in the past + and never in the future. Also, if "Years" are used to represent the age, the calculation of + `age' must always agree with "current year - birth year = age". + + This form of Abstract Data Type specification has very clear advantages in that not only + must client code or descendents conform statically, implementing what is deferred, but they + must also obey the rules of the assertions dynamically in a polymorphic run-time situation. + ]" + +deferred class + PERSON + +feature -- Access + + first_name, + last_name, + middle_name, + suffix: STRING + + birth_date: detachable DATE + -- Date-of-Birth for Current {PERSON}. + deferred + end + +feature -- Basic Operations + + age: NATURAL_64 + -- Age of Current {PERSON} in some undefined units. + require + has_birth_date: attached birth_date + deferred + end + + age_units: STRING + -- Unit-of-Measure (UOM) of `age'. + attribute + Result := year_unit_string + end + + year_unit_string: STRING = "Years" + +invariant + not_future: attached birth_date as al_birth_date implies al_birth_date < (create {DATE}.make_now) + accurate_age: attached birth_date as al_birth_date and then age > 0 and then age_units.same_string (year_unit_string) + implies ((create {DATE}.make_now).year - al_birth_date.year) = age + +end diff --git a/Task/Abstract-type/Forth/abstract-type.fth b/Task/Abstract-type/Forth/abstract-type-1.fth similarity index 100% rename from Task/Abstract-type/Forth/abstract-type.fth rename to Task/Abstract-type/Forth/abstract-type-1.fth diff --git a/Task/Abstract-type/Forth/abstract-type-2.fth b/Task/Abstract-type/Forth/abstract-type-2.fth new file mode 100644 index 0000000000..76aeda71d5 --- /dev/null +++ b/Task/Abstract-type/Forth/abstract-type-2.fth @@ -0,0 +1,3 @@ +include FMS-SI.f + +The FMS object extension uses duck typing and so has no need for abstract types. diff --git a/Task/Abstract-type/Fortran/abstract-type.f b/Task/Abstract-type/Fortran/abstract-type.f new file mode 100644 index 0000000000..1f915ae204 --- /dev/null +++ b/Task/Abstract-type/Fortran/abstract-type.f @@ -0,0 +1,16 @@ + ! abstract derived type + type, abstract :: TFigure + real(rdp) :: area + contains + ! deferred method i.e. abstract method = must be overridden in extended type + procedure(calculate_area), deferred, pass :: calculate_area + end type TFigure + ! only declaration of the abstract method/procedure for TFigure type + abstract interface + function calculate_area(this) + import TFigure !imports TFigure type from host scoping unit and makes it accessible here + implicit none + class(TFigure) :: this + real(rdp) :: calculate_area + end function calculate_area + end interface diff --git a/Task/Abstract-type/NetRexx/abstract-type.netrexx b/Task/Abstract-type/NetRexx/abstract-type.netrexx index f9badd6873..56be02438e 100644 --- a/Task/Abstract-type/NetRexx/abstract-type.netrexx +++ b/Task/Abstract-type/NetRexx/abstract-type.netrexx @@ -1,5 +1,5 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols binary +options replace format comments java crossref symbols binary -- ----------------------------------------------------------------------------- class RCAbstractType public final diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/00DESCRIPTION b/Task/Abundant,-deficient-and-perfect-number-classifications/00DESCRIPTION index ae3b02930b..e0f267b3d9 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/00DESCRIPTION +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/00DESCRIPTION @@ -14,4 +14,3 @@ Calculate how many of the integers 1 to 20,000 inclusive are in each of the thre * [[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/AWK/abundant,-deficient-and-perfect-number-classifications.awk b/Task/Abundant,-deficient-and-perfect-number-classifications/AWK/abundant,-deficient-and-perfect-number-classifications.awk new file mode 100644 index 0000000000..38e2d676c0 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/AWK/abundant,-deficient-and-perfect-number-classifications.awk @@ -0,0 +1,36 @@ +#!/bin/gawk -f +function sumprop(num, i,sum,root) { +if (num == 1) return 0 +sum=1 +root=sqrt(num) +for ( i=2; i < root; i++) { + if (num % i == 0 ) + { + sum = sum + i + num/i + } + } +if (num % root == 0) + { + sum = sum + root + } +return sum +} + +BEGIN{ +limit = 20000 +abundant = 0 +defiecient =0 +perfect = 0 + +for (j=1; j < limit+1; j++) + { + sump = sumprop(j) + if (sump < j) deficient = deficient + 1 + if (sump == j) perfect = perfect + 1 + if (sump > j) abundant = abundant + 1 + } +print "For 1 through " limit +print "Perfect: " perfect +print "Abundant: " abundant +print "Deficient: " deficient +} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Bracmat/abundant,-deficient-and-perfect-number-classifications.bracmat b/Task/Abundant,-deficient-and-perfect-number-classifications/Bracmat/abundant,-deficient-and-perfect-number-classifications.bracmat new file mode 100644 index 0000000000..27c9bd8572 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Bracmat/abundant,-deficient-and-perfect-number-classifications.bracmat @@ -0,0 +1,73 @@ +( clk$:?t0 +& ( multiples + = prime multiplicity + . !arg:(?prime.?multiplicity) + & !multiplicity:0 + & 1 + | !prime^!multiplicity*(.!multiplicity) + + multiples$(!prime.-1+!multiplicity) + ) +& ( P + = primeFactors prime exp poly S + . !arg^1/67:?primeFactors + & ( !primeFactors:?^1/67&0 + | 1:?poly + & whl + ' ( !primeFactors:%?prime^?exp*?primeFactors + & !poly*multiples$(!prime.67*!exp):?poly + ) + & -1+!poly+1:?poly + & 1:?S + & ( !poly + : ? + + (#%@?s*?&!S+!s:?S&~) + + ? + | 1/2*!S + ) + ) + ) +& 0:?deficient:?perfect:?abundant +& 0:?n +& whl + ' ( 1+!n:~>20000:?n + & P$!n + : ( !n&1+!abundant:?abundant + ) + ) +& out$(deficient !deficient perfect !perfect abundant !abundant) +& clk$:?t1 +& out$(flt$(!t1+-1*!t0,2) sec) +& clk$:?t2 +& ( P + = f h S + . 0:?f + & 0:?S + & whl + ' ( 1+!f:?f + & !f^2:~>!n + & ( !arg*!f^-1:~/:?g + & !S+!f:?S + & ( !g:~!f&!S+!g:?S + | + ) + | + ) + ) + & 1/2*!S + ) +& 0:?deficient:?perfect:?abundant +& 0:?n +& whl + ' ( 1+!n:~>20000:?n + & P$!n + : ( !n&1+!abundant:?abundant + ) + ) +& out$(deficient !deficient perfect !perfect abundant !abundant) +& clk$:?t3 +& out$(flt$(!t3+-1*!t2,2) sec) +); diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Clojure/abundant,-deficient-and-perfect-number-classifications-1.clj b/Task/Abundant,-deficient-and-perfect-number-classifications/Clojure/abundant,-deficient-and-perfect-number-classifications-1.clj new file mode 100644 index 0000000000..4be683eb68 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Clojure/abundant,-deficient-and-perfect-number-classifications-1.clj @@ -0,0 +1,17 @@ +(defn pad-class + [n] + (let [divs (filter #(zero? (mod n %)) (range 1 n)) + divs-sum (reduce + divs)] + (cond + (< divs-sum n) :deficient + (= divs-sum n) :perfect + (> divs-sum n) :abundant))) + +(def pad-classes (map pad-class (map inc (range)))) + +(defn count-classes + [n] + (let [classes (take n pad-classes)] + {:perfect (count (filter #(= % :perfect) classes)) + :abundant (count (filter #(= % :abundant) classes)) + :deficient (count (filter #(= % :deficient) classes))})) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Clojure/abundant,-deficient-and-perfect-number-classifications-2.clj b/Task/Abundant,-deficient-and-perfect-number-classifications/Clojure/abundant,-deficient-and-perfect-number-classifications-2.clj new file mode 100644 index 0000000000..144d74897d --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Clojure/abundant,-deficient-and-perfect-number-classifications-2.clj @@ -0,0 +1,4 @@ +(count-classes 20000) +;=> {:perfect 4, +; :abundant 4953, +; :deficient 15043} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Common-Lisp/abundant,-deficient-and-perfect-number-classifications.lisp b/Task/Abundant,-deficient-and-perfect-number-classifications/Common-Lisp/abundant,-deficient-and-perfect-number-classifications.lisp new file mode 100644 index 0000000000..605162c5bf --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Common-Lisp/abundant,-deficient-and-perfect-number-classifications.lisp @@ -0,0 +1,18 @@ +(defun number-class (n) + (let ((divisor-sum (sum-divisors n))) + (cond ((< divisor-sum n) :deficient) + ((= divisor-sum n) :perfect) + ((> divisor-sum n) :abundant)))) + +(defun sum-divisors (n) + (loop :for i :from 1 :to (/ n 2) + :when (zerop (mod n i)) + :sum i)) + +(defun classification () + (loop :for n :from 1 :to 20000 + :for class := (number-class n) + :count (eq class :deficient) :into deficient + :count (eq class :perfect) :into perfect + :count (eq class :abundant) :into abundant + :finally (return (values deficient perfect abundant)))) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications.erl b/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications.erl new file mode 100644 index 0000000000..d0e48c4358 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications.erl @@ -0,0 +1,31 @@ +-module(properdivs). +-export([divs/1,sumdivs/1,class/1]). + +divs(0) -> []; +divs(1) -> []; +divs(N) -> lists:sort(divisors(1,N)). + +divisors(1,N) -> + [1] ++ divisors(2,N,math:sqrt(N)). + +divisors(K,_N,Q) when K > Q -> []; +divisors(K,N,_Q) when N rem K =/= 0 -> + [] ++ divisors(K+1,N,math:sqrt(N)); +divisors(K,N,_Q) when K * K == N -> + [K] ++ divisors(K+1,N,math:sqrt(N)); +divisors(K,N,_Q) -> + [K, N div K] ++ divisors(K+1,N,math:sqrt(N)). + +sumdivs(N) -> lists:sum(divs(N)). + +class(Limit) -> class(0,0,0,sumdivs(2),2,Limit). + +class(D,P,A,_Sum,Acc,L) when Acc > L +1-> + io:format("Deficient: ~w, Perfect: ~w, Abundant: ~w~n", [D,P,A]); + +class(D,P,A,Sum,Acc,L) when Acc < Sum -> + class(D,P,A+1,sumdivs(Acc+1),Acc+1,L); +class(D,P,A,Sum,Acc,L) when Acc == Sum -> + class(D,P+1,A,sumdivs(Acc+1),Acc+1,L); +class(D,P,A,Sum,Acc,L) when Acc > Sum -> + class(D+1,P,A,sumdivs(Acc+1),Acc+1,L). diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Fortran/abundant,-deficient-and-perfect-number-classifications.f b/Task/Abundant,-deficient-and-perfect-number-classifications/Fortran/abundant,-deficient-and-perfect-number-classifications.f new file mode 100644 index 0000000000..d101b646f2 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Fortran/abundant,-deficient-and-perfect-number-classifications.f @@ -0,0 +1,38 @@ + MODULE FACTORSTUFF !This protocol evades the need for multiple parameters, or COMMON, or one shapeless main line... +Concocted by R.N.McLean, MMXV. + INTEGER LOTS !The span.. + PARAMETER (LOTS = 20000)!Nor is computer storage infinite. + INTEGER KNOWNSUM(LOTS) !Calculate these once. + CONTAINS !Assistants. + SUBROUTINE PREPARESUMF !Initialise the KNOWNSUM array. +Convert the Sieve of Eratoshenes to have each slot contain the sum of the proper divisors of its slot number. +Changes to instead count the number of factors, or prime factors, etc. would be simple enough. + INTEGER F !A factor for numbers such as 2F, 3F, 4F, 5F, ... + KNOWNSUM(1) = 0 !Proper divisors of N do not include N. + KNOWNSUM(2:LOTS) = 1 !So, although 1 divides all N without remainder, 1 is excluded for itself. + DO F = 2,LOTS/2 !Step through all the possible divisors of numbers not exceeding LOTS. + FORALL(I = F + F:LOTS:F) KNOWNSUM(I) = KNOWNSUM(I) + F !And augment each corresponding slot. + END DO !Different divisors can hit the same slot. For instance, 6 by 2 and also by 3. + END SUBROUTINE PREPARESUMF !Could alternatively generate all products of prime numbers. + PURE INTEGER FUNCTION SIGN3(N) !Returns -1, 0, +1 according to the sign of N. +Confounded by the intrinsic function SIGN distinguishing only two states: < 0 from >= 0. NOT three-way. + INTEGER, INTENT(IN):: N !The number. + IF (N) 1,2,3 !A three-way result calls for a three-way test. + 1 SIGN3 = -1 !Negative. + RETURN + 2 SIGN3 = 0 !Zero. + RETURN + 3 SIGN3 = +1 !Positive. + END FUNCTION SIGN3 !Rather basic. + END MODULE FACTORSTUFF !Enough assistants. + PROGRAM THREEWAYS !Classify N against the sum of proper divisors of N, for N up to 20,000. + USE FACTORSTUFF !This should help. + INTEGER I !Stepper. + INTEGER TEST(LOTS) !Assesses the three states in one pass. + WRITE (6,*) "Inspecting sums of proper divisors for 1 to",LOTS + CALL PREPARESUMF !Values for every N up to the search limit will be called for at least once. + FORALL(I = 1:LOTS) TEST(I) = SIGN3(KNOWNSUM(I) - I) !How does KnownSum(i) compare to i? + WRITE (6,*) "Deficient",COUNT(TEST .LT. 0) !This means one pass through the array + WRITE (6,*) "Perfect! ",COUNT(TEST .EQ. 0) !For each of three types. + WRITE (6,*) "Abundant ",COUNT(TEST .GT. 0) !Alternatively, make one pass with three counts. + END !Done. diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-1.js b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-1.js new file mode 100644 index 0000000000..edeeb32f9b --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-1.js @@ -0,0 +1,5 @@ +for (var dpa=[1,0,0], n=2; n<=20000; n+=1) { + for (var ds=0, d=1, e=n/2+1; d' ) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-2.js b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-2.js new file mode 100644 index 0000000000..d3dba24cc9 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-2.js @@ -0,0 +1,6 @@ +for (var dpa=[1,0,0], n=2; n<=20000; n+=1) { + for (var ds=1, d=2, e=Math.sqrt(n); d' ) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-3.js b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-3.js new file mode 100644 index 0000000000..8fb7d53ff2 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/JavaScript/abundant,-deficient-and-perfect-number-classifications-3.js @@ -0,0 +1,48 @@ +function primes(t) { + var ps = {2:true, 3:true} + next: for (var n=5, i=2; n<=t; n+=i, i=6-i) { + var s = Math.sqrt( n ) + for ( var p in ps ) { + if ( p > s ) break + if ( n % p ) continue + continue next + } + ps[n] = true + } + return ps +} + +function factorize(f, t) { + var cs = {}, ps = primes(t) + for (var n=f; n<=t; n++) if (!ps[n]) cs[n] = factors(n) + return cs + function factors(n) { + for ( var p in ps ) if ( n % p == 0 ) break + var ts = {} + ts[p] = 1 + if ( ps[n /= p] ) { + if ( !ts[n]++ ) ts[n]=1 + } + else { + var fs = cs[n] + if ( !fs ) fs = cs[n] = factors(n) + for ( var e in fs ) ts[e] = fs[e] + (e==p) + } + return ts + } +} + +function pContrib(p, e) { + for (var pc=1, n=1, i=1; i<=e; i+=1) pc+=n*=p; + return pc +} + +for (var dpa=[1,0,0], t=20000, cs=factorize(2,t), n=2; n<=t; n+=1) { + var ds=1, fs=cs[n] + if (fs) { + for (var p in fs) ds *= pContrib(p, fs[p]) + ds -= n + } + dpa[ds' ) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Julia/abundant,-deficient-and-perfect-number-classifications-1.julia b/Task/Abundant,-deficient-and-perfect-number-classifications/Julia/abundant,-deficient-and-perfect-number-classifications-1.julia new file mode 100644 index 0000000000..30f26de223 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Julia/abundant,-deficient-and-perfect-number-classifications-1.julia @@ -0,0 +1,17 @@ +function pcontrib(p::Int64, a::Int64) + n = one(p) + pcon = one(p) + for i in 1:a + n *= p + pcon += n + end + return pcon +end + +function divisorsum(n::Int64) + dsum = one(n) + for (p, a) in factor(n) + dsum *= pcontrib(p, a) + end + dsum -= n +end diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Julia/abundant,-deficient-and-perfect-number-classifications-2.julia b/Task/Abundant,-deficient-and-perfect-number-classifications/Julia/abundant,-deficient-and-perfect-number-classifications-2.julia new file mode 100644 index 0000000000..5d4776cc18 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Julia/abundant,-deficient-and-perfect-number-classifications-2.julia @@ -0,0 +1,17 @@ +const L = 2*10^4 +iclasslabel = ["Deficient", "Perfect", "Abundant"] +iclass = zeros(Int64, 3) +iclass[1] = one(Int64) #by convention 1 is deficient + +for n in 2:L + if isprime(n) + iclass[1] += 1 + else + iclass[sign(divisorsum(n)-n)+2] += 1 + end +end + +println("Classification of integers from 1 to ", L) +for i in 1:3 + println(" ", iclasslabel[i], ", ", iclass[i]) +end diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/PARI-GP/abundant,-deficient-and-perfect-number-classifications.pari b/Task/Abundant,-deficient-and-perfect-number-classifications/PARI-GP/abundant,-deficient-and-perfect-number-classifications.pari new file mode 100644 index 0000000000..f33c6212e7 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/PARI-GP/abundant,-deficient-and-perfect-number-classifications.pari @@ -0,0 +1,10 @@ +classify(k)= +{ + my(v=[0,0,0],t); + for(n=1,k, + t=sigma(n,-1); + if(t<2,v[1]++,t>2,v[3]++,v[2]++) + ); + v; +} +classify(20000) 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 index 0bc967dad3..d66fb4c8c3 100644 --- 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 @@ -1,11 +1,214 @@ +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 - tdpa = array[0..2] of LongWord; // 0 = deficient,1= perfect,2 = abundant + 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; -.. -in function Check - // SumOfProperDivs + +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; - //in Pascal boolean true == 1/false == 0 + 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(Max:10,' upper limit'); + writeln(DpaCnt[0]:10,' deficient'); + writeln(DpaCnt[1]:10,' perfect'); + writeln(DpaCnt[2]:10,' abundant'); + writeln(DpaCnt[2]/Max:14:10,' ratio abundant/upper Limit '); + writeln(DpaCnt[0]/Max:14:10,' ratio abundant/upper Limit '); + 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/Abundant,-deficient-and-perfect-number-classifications/PicoLisp/abundant,-deficient-and-perfect-number-classifications.l b/Task/Abundant,-deficient-and-perfect-number-classifications/PicoLisp/abundant,-deficient-and-perfect-number-classifications.l new file mode 100644 index 0000000000..f25dcd64f0 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/PicoLisp/abundant,-deficient-and-perfect-number-classifications.l @@ -0,0 +1,42 @@ +(de accud (Var Key) + (if (assoc Key (val Var)) + (con @ (inc (cdr @))) + (push Var (cons Key 1)) ) + Key ) +(de factor-sum (N) + (if (=1 N) + 0 + (let + (R NIL + D 2 + L (1 2 2 . (4 2 4 2 4 6 2 6 .)) + M (sqrt N) + N1 N + S 1 ) + (while (>= M D) + (if (=0 (% N1 D)) + (setq M + (sqrt (setq N1 (/ N1 (accud 'R D)))) ) + (inc 'D (pop 'L)) ) ) + (accud 'R N1) + (for I R + (one D) + (one M) + (for J (cdr I) + (setq M (* M (car I))) + (inc 'D M) ) + (setq S (* S D)) ) + (- S N) ) ) ) +(bench + (let + (A 0 + D 0 + P 0 ) + (for I 20000 + (setq @@ (factor-sum I)) + (cond + ((< @@ I) (inc 'D)) + ((= @@ I) (inc 'P)) + ((> @@ I) (inc 'A)) ) ) + (println D P A) ) ) +(bye) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications.psh b/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications.psh new file mode 100644 index 0000000000..f53d6699e6 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/PowerShell/abundant,-deficient-and-perfect-number-classifications.psh @@ -0,0 +1,27 @@ +new-variable deficient -value 0 +new-variable perfect -value 0 +new-variable abundant -value 0 +new-variable sum + +for($i=1;$i -le 20000;$i++){ + $sum=0 + for($n=1;$n -le [System.Math]::Floor([System.Math]::Sqrt($i));$n++){ + if($i%$n -eq 0){ + $sum+=($i/$n) + if($i/$n -ne $n) {$sum+=$n} + } + } + $sum-=$i + if($sum -lt $i){ + $deficient++ + } + elseif($sum -eq $i){ + $perfect++ + } else { + $abundant++ + } +} + +Write-Host "Deficient = $deficient" +Write-Host "Perfect = $perfect" +Write-Host "Abundant = $abundant" diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications.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.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/REXX/abundant,-deficient-and-perfect-number-classifications-1.rexx b/Task/Abundant,-deficient-and-perfect-number-classifications/REXX/abundant,-deficient-and-perfect-number-classifications-1.rexx new file mode 100644 index 0000000000..e4c26a1d94 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/REXX/abundant,-deficient-and-perfect-number-classifications-1.rexx @@ -0,0 +1,24 @@ +/*REXX pgm counts the number of abundant/deficient/perfect numbers in a range.*/ +parse arg low high . /*get optional args from C.L. */ +high=word(high low 20000,1); low=word(low 1,1) /*get the LOW and HIGH values.*/ +say center('integers from ' low " to " high, 45, "═") +!.=0 /*define all types of sums to zero. */ + do j=low to high; $=sigma(j) /*find the sigma for an integer range. */ + if $j then !.a=!.a+1 /* " " abundant " */ + else !.p=!.p+1 /* " " perfect " */ + end /*j*/ + +say ' the number of perfect numbers: ' right(!.p, length(high)) +say ' the number of abundant numbers: ' right(!.a, length(high)) +say ' the number of deficient numbers: ' right(!.d, length(high)) +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sigma: procedure; parse arg x; if x<2 then return 0; odd=x//2 /*odd? */ +s=1 /* [↓] only use EVEN or ODD integers.*/ + do j=2+odd by 1+odd while j*jj then !.a=!.a+1 /* " " abundant " */ + else !.p=!.p+1 /* " " perfect " */ + end /*j*/ + +say ' the number of perfect numbers: ' right(!.p, length(high)) +say ' the number of abundant numbers: ' right(!.a, length(high)) +say ' the number of deficient numbers: ' right(!.d, length(high)) +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +iSqrt: procedure; parse arg x; q=1; r=0; do while q<=x; q=q*4; end + do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do; x=_; r=r+q; end + end /*while ···*/ +return r +/*────────────────────────────────────────────────────────────────────────────*/ +sigma: procedure; parse arg x; if x<5 then return max(0,x-1); sqX=iSqrt(x) +s=1; odd=x//2 /* [↓] only use EVEN or ODD integers.*/ + do j=2+odd by 1+odd to sqX /*divide by all integers up to √ x */ + if x//j==0 then s=s+j+ x%j /*add the two divisors to (sigma) sum. */ + end /*j*/ /* [↑] % is the REXX integer division*/ + /* [↓] adjust for a square. ___*/ +if sqx*sqx==x then s=s-j /*Was X a square? If so, subtract √ x */ +return s /*return (sigma) sum of the divisors. */ diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/REXX/abundant,-deficient-and-perfect-number-classifications-3.rexx b/Task/Abundant,-deficient-and-perfect-number-classifications/REXX/abundant,-deficient-and-perfect-number-classifications-3.rexx new file mode 100644 index 0000000000..f8136ed195 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/REXX/abundant,-deficient-and-perfect-number-classifications-3.rexx @@ -0,0 +1,50 @@ +Call time 'R' +cnt.=0 +Do x=1 To 20000 + pd=proper_divisors(x) + sumpd=sum(pd) + Select + When xhi Then Do + list.npd=x + hi=npd + End + When npd=hi Then + list.hi=list.hi x + Otherwise + Nop + End + End + +Say 'In the range 1 - 20000' +Say format(cnt.abundant ,5) 'numbers are abundant ' +Say format(cnt.perfect ,5) 'numbers are perfect ' +Say format(cnt.deficient,5) 'numbers are deficient ' +Say time('E') 'seconds elapsed' +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/Abundant,-deficient-and-perfect-number-classifications/Racket/abundant,-deficient-and-perfect-number-classifications.rkt b/Task/Abundant,-deficient-and-perfect-number-classifications/Racket/abundant,-deficient-and-perfect-number-classifications.rkt index bf3832ad49..234a8e355c 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Racket/abundant,-deficient-and-perfect-number-classifications.rkt +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Racket/abundant,-deficient-and-perfect-number-classifications.rkt @@ -1,26 +1,14 @@ #lang racket -(require "proper-divisors.rkt") -(define SCOPE 20000) +(require math) +(define (proper-divisors n) (drop-right (divisors n) 1)) +(define classes '(deficient perfect abundant)) +(define (classify n) + (list-ref classes (add1 (sgn (- (apply + (proper-divisors n)) n))))) -(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 #< $j} {return 1} + return -1 +} + +proc classify {k} { + lassign [ProperDivisors $k] p ;# we only care about the first part of the result + dict get { + 1 abundant + 0 perfect + -1 deficient + } [cmp $k $p] +} + +puts "Classifying the integers in \[1, 20_000\]:" +set classes {} ;# this will be a dict + +for {set i 1} {$i <= 20000} {incr i} { + set class [classify $i] + dict incr classes $class +} + +# using [lsort] to order the dictionary by value: +foreach {kind count} [lsort -stride 2 -index 1 -integer $classes] { + puts "$kind: $count" +} diff --git a/Task/Accumulator-factory/C++/accumulator-factory-3.cpp b/Task/Accumulator-factory/C++/accumulator-factory-3.cpp new file mode 100644 index 0000000000..15d26be1c8 --- /dev/null +++ b/Task/Accumulator-factory/C++/accumulator-factory-3.cpp @@ -0,0 +1,21 @@ +struct CumulantBase_ +{ + virtual ~CumulantBase_(); + virtual std::ostream& Write(std::ostream& dst) const = 0; +}; + +template struct Cumulant_ : CumulantBase_ +{ + T_ val_; + Cumulant_(const T_& val) : val_(val) {} + std::ostream& Write(std::ostream& dst) const override + { + return dst << val_; + } +}; + +struct Accumulator_ +{ + std::unique_ptr val_; + template Accumulator_(const T_& val) { Set(val); } + template void Set(const T_& val) { val_.reset(new Cumulant_(val)); } diff --git a/Task/Accumulator-factory/C++/accumulator-factory-4.cpp b/Task/Accumulator-factory/C++/accumulator-factory-4.cpp new file mode 100644 index 0000000000..739fb84b7c --- /dev/null +++ b/Task/Accumulator-factory/C++/accumulator-factory-4.cpp @@ -0,0 +1,29 @@ +// still inside struct Accumulator_ + // various operator() implementations provide a de facto multimethod + Accumulator_& operator()(int more) + { + if (auto i = CoerceInt(*val_)) + Set(+i + more); + else if (auto d = CoerceDouble(*val_)) + Set(+d + more); + else + THROW("Accumulate(int) failed"); + return *this; + } + Accumulator_& operator()(double more) + { + if (auto d = CoerceDouble(*val_)) + Set(+d + more); + else + THROW("Accumulate(double) failed"); + return *this; + } + Accumulator_& operator()(const String_& more) + { + if (auto s = CoerceString(*val_)) + Set(+s + more); + else + THROW("Accumulate(string) failed"); + return *this; + } +}; diff --git a/Task/Accumulator-factory/C++/accumulator-factory-5.cpp b/Task/Accumulator-factory/C++/accumulator-factory-5.cpp new file mode 100644 index 0000000000..7893d522ff --- /dev/null +++ b/Task/Accumulator-factory/C++/accumulator-factory-5.cpp @@ -0,0 +1,21 @@ +// recognize cumulants by type +boost::optional CoerceInt(const CumulantBase_& c) +{ + if (auto p = dynamic_cast*>(&c)) + return p->val_; + return boost::optional(); +} +boost::optional CoerceDouble(const CumulantBase_& c) +{ + if (auto p = dynamic_cast*>(&c)) + return p->val_; + if (auto i = CoerceInt(c)) + return boost::optional(i); + return boost::optional(); +} +boost::optional CoerceString(const CumulantBase_& c) +{ + if (auto p = dynamic_cast*>(&c)) + return p->val_; + return boost::optional(); +} diff --git a/Task/Accumulator-factory/C++/accumulator-factory-6.cpp b/Task/Accumulator-factory/C++/accumulator-factory-6.cpp new file mode 100644 index 0000000000..e0e88383ba --- /dev/null +++ b/Task/Accumulator-factory/C++/accumulator-factory-6.cpp @@ -0,0 +1,4 @@ +std::ostream& operator<<(std::ostream& dst, const Accumulator_& acc) +{ + return acc.val_->Write(dst); +} diff --git a/Task/Accumulator-factory/Fortran/accumulator-factory-1.f b/Task/Accumulator-factory/Fortran/accumulator-factory-1.f new file mode 100644 index 0000000000..275dc347d3 --- /dev/null +++ b/Task/Accumulator-factory/Fortran/accumulator-factory-1.f @@ -0,0 +1,20 @@ +#define foo(type,g,nn) \ +typex function g(i);\ +typex i,s,n;\ +data s,n/0,nn/;\ +s=s+i;\ +g=s+n;\ +end + + foo(real,x,1) + foo(integer,y,3) + + program acc + real x, temp + integer y, itemp + temp = x(5.0) + print *, x(2.3) + itemp = y(5) + print *, y(2) + stop + end diff --git a/Task/Accumulator-factory/Fortran/accumulator-factory-2.f b/Task/Accumulator-factory/Fortran/accumulator-factory-2.f new file mode 100644 index 0000000000..1faf371f4b --- /dev/null +++ b/Task/Accumulator-factory/Fortran/accumulator-factory-2.f @@ -0,0 +1,79 @@ +module modAcc +implicit none +private +integer, public, parameter :: KRL = selected_real_kind(14) + +type, public :: AccType + real(KRL), private :: dn, dsum + complex(KRL), private :: fn, fsum + integer, private :: jn, jsum, icod + contains + procedure, private :: initd, initf, initi + generic, public :: init => initd, initf, initi + procedure, private :: dfun, ffun, jfun + generic, public :: fun => dfun, jfun, ffun +end type AccType + + +contains + +subroutine initd(self, dd) + class(AccType), intent(inout) :: self + real(KRL), intent(in) :: dd + self%dn = dd + self%icod = 1 +end subroutine initd + +subroutine initf(self, ff) + class(AccType), intent(inout) :: self + complex(KRL), intent(in) :: ff + self%fn = ff + self%icod = 2 +end subroutine initf + +subroutine initi(self, jj) + class(AccType), intent(inout) :: self + integer, intent(in) :: jj + self%jn = jj + self%icod = 3 +end subroutine initi + +real(KRL) function dfun(self, di) + class(AccType), intent(inout) :: self + real(KRL), intent(in) :: di + self%dsum = self%dsum + di + dfun = self%dn + self%dsum +end function dfun + + +complex(KRL) function ffun(self, fi) + class(AccType), intent(inout) :: self + complex(KRL), intent(in) :: fi + self%fsum = self%fsum + fi + ffun = self%fn + self%fsum +end function ffun + + +integer function jfun(self, ji) + class(AccType), intent(inout) :: self + integer, intent(in) :: ji + self%jsum = self%jsum + ji + jfun = self%jn + self%jsum +end function jfun + +end module modAcc + + +program test + use modAcc + implicit none + type(AccType) :: x, y + integer :: itemp + real(KRL) :: temp + call x%init(1.0_KRL) + temp = x%fun(5.0_KRL) + call y%init(3) + print *, x%fun(2.3_KRL) + itemp = y%fun(5) + print *, y%fun(2) +end program test diff --git a/Task/Accumulator-factory/Rust/accumulator-factory.rust b/Task/Accumulator-factory/Rust/accumulator-factory.rust index 651e5f3188..51a75a7504 100644 --- a/Task/Accumulator-factory/Rust/accumulator-factory.rust +++ b/Task/Accumulator-factory/Rust/accumulator-factory.rust @@ -1,19 +1,20 @@ -#![feature(unboxed_closures)] +// rustc -V +// rustc 1.2.0-nightly (0cc99f9cc 2015-05-17) (built 2015-05-18) use std::ops::Add; -use std::ops::FnMut; -fn accumulator_factory<'a, T>(n: T) -> Box T + 'a> - where T: Add + Copy + 'a { +fn foo(n: Num) -> Box Num> + where Num: Add + Copy + 'static { let mut acc = n; - Box::new (move |&mut: i: T| { + Box::new(move |i: Num| { acc = acc + i; acc }) } fn main() { - let mut acc = accumulator_factory(10f64); - println!("{}", acc(12f64)); - println!("{}", acc(12f64)); + let mut x = foo(1.); + x(5.); + foo(3.); + println!("{}", x(2.3)); } diff --git a/Task/Ackermann-function/00DESCRIPTION b/Task/Ackermann-function/00DESCRIPTION index a0c1132e36..5a999940ce 100644 --- a/Task/Ackermann-function/00DESCRIPTION +++ b/Task/Ackermann-function/00DESCRIPTION @@ -1,6 +1,6 @@ -The '''[[wp:Ackermann function|Ackermann function]]''' is a classic recursive example in computer science. -It is a function that grows very quickly (in its value and in the size of its call tree). -It is defined as follows: +The '''[[wp:Ackermann function|Ackermann function]]''' is a classic example of a recursive function, notable especially because it is not a [[wp:Primitive_recursive_function|primitive recursive function]]. It grows very quickly in value, as does the size of its call tree. + +The Ackermann function is usually defined as follows: : A(m, n) = \begin{cases} @@ -13,7 +13,5 @@ It is defined as follows: Its arguments are never negative and it always terminates. Write a function which returns the value of A(m, n). Arbitrary precision is preferred (since the function grows so quickly), but not required. -Interestingly enough, the Ackermann function is one of the very few known examples of function that can ''only'' be implemented recursively. It is impossible to implement it with just for loops and other control flow commands. See this [http://youtube.com/watch?v=i7sm9dzFtEI computerphile episode] for more information. - ;See also: * [[wp:Conway_chained_arrow_notation#Ackermann_function|Conway chained arrow notation]] for the Ackermann function. diff --git a/Task/Ackermann-function/360-Assembly/ackermann-function.360 b/Task/Ackermann-function/360-Assembly/ackermann-function.360 new file mode 100644 index 0000000000..719afe3af3 --- /dev/null +++ b/Task/Ackermann-function/360-Assembly/ackermann-function.360 @@ -0,0 +1,77 @@ +* Ackermann function 07/09/2015 +ACKERMAN CSECT + USING ACKERMAN,R12 r12 : base register + LR R12,R15 establish base register + ST R14,SAVER14A save r14 + LA R4,0 m=0 +LOOPM CH R4,=H'3' do m=0 to 3 + BH ELOOPM + LA R5,0 n=0 +LOOPN CH R5,=H'8' do n=0 to 8 + BH ELOOPN + LR R1,R4 m + LR R2,R5 n + BAL R14,ACKER r1=acker(m,n) + XDECO R1,PG+19 + XDECO R4,XD + MVC PG+10(2),XD+10 + XDECO R5,XD + MVC PG+13(2),XD+10 + XPRNT PG,44 print buffer + LA R5,1(R5) n=n+1 + B LOOPN +ELOOPN LA R4,1(R4) m=m+1 + B LOOPM +ELOOPM L R14,SAVER14A restore r14 + BR R14 return to caller +SAVER14A DS F static save r14 +PG DC CL44'Ackermann(xx,xx) = xxxxxxxxxxxx' +XD DS CL12 +ACKER CNOP 0,4 function r1=acker(r1,r2) + LR R3,R1 save argument r1 in r3 + LR R9,R10 save stackptr (r10) in r9 temp + LA R1,STACKLEN amount of storage required + GETMAIN RU,LV=(R1) allocate storage for stack + USING STACK,R10 make storage addressable + LR R10,R1 establish stack addressability + ST R14,SAVER14B save previous r14 + ST R9,SAVER10B save previous r10 + LR R1,R3 restore saved argument r1 +START ST R1,M stack m + ST R2,N stack n +IF1 C R1,=F'0' if m<>0 + BNE IF2 then goto if2 + LR R11,R2 n + LA R11,1(R11) return n+1 + B EXIT +IF2 C R2,=F'0' else if m<>0 + BNE IF3 then goto if3 + BCTR R1,0 m=m-1 + LA R2,1 n=1 + BAL R14,ACKER r1=acker(m) + LR R11,R1 return acker(m-1,1) + B EXIT +IF3 BCTR R2,0 n=n-1 + BAL R14,ACKER r1=acker(m,n-1) + LR R2,R1 acker(m,n-1) + L R1,M m + BCTR R1,0 m=m-1 + BAL R14,ACKER r1=acker(m-1,acker(m,n-1)) + LR R11,R1 return acker(m-1,1) +EXIT L R14,SAVER14B restore r14 + L R9,SAVER10B restore r10 temp + LA R0,STACKLEN amount of storage to free + FREEMAIN A=(R10),LV=(R0) free allocated storage + LR R1,R11 value returned + LR R10,R9 restore r10 + BR R14 return to caller + LTORG + DROP R12 base no longer needed +STACK DSECT dynamic area +SAVER14B DS F saved r14 +SAVER10B DS F saved r10 +M DS F m +N DS F n +STACKLEN EQU *-STACK + YREGS + END ACKERMAN diff --git a/Task/Ackermann-function/AppleScript/ackermann-function.applescript b/Task/Ackermann-function/AppleScript/ackermann-function.applescript new file mode 100644 index 0000000000..21cc254552 --- /dev/null +++ b/Task/Ackermann-function/AppleScript/ackermann-function.applescript @@ -0,0 +1,5 @@ +on ackermann(m, n) + if m is equal to 0 then return n + 1 + if n is equal to 0 then return ackermann(m - 1, 1) + return ackermann(m - 1, ackermann(m, n - 1)) +end ackermann diff --git a/Task/Ackermann-function/Befunge/ackermann-function-1.bf b/Task/Ackermann-function/Befunge/ackermann-function-1.bf new file mode 100644 index 0000000000..5a8e5993c1 --- /dev/null +++ b/Task/Ackermann-function/Befunge/ackermann-function-1.bf @@ -0,0 +1,3 @@ +&>&>vvg0>#0\#-:#1_1v +@v:\00p>:#^_$1+\:#^_$. diff --git a/Task/Ackermann-function/Befunge/ackermann-function.bf b/Task/Ackermann-function/Befunge/ackermann-function-2.bf similarity index 100% rename from Task/Ackermann-function/Befunge/ackermann-function.bf rename to Task/Ackermann-function/Befunge/ackermann-function-2.bf diff --git a/Task/Ackermann-function/Eiffel/ackermann-function.e b/Task/Ackermann-function/Eiffel/ackermann-function.e index 07730f3a3b..5b9e4e0d74 100644 --- a/Task/Ackermann-function/Eiffel/ackermann-function.e +++ b/Task/Ackermann-function/Eiffel/ackermann-function.e @@ -1,6 +1,15 @@ note description: "Example of Ackerman function" - URI: "http://rosettacode.org/wiki/Ackermann_function" + synopsis: "[ + The EIS link below (in Eiffel Studio) will launch in either an in-IDE browser or + and external browser (your choice). The protocol informs Eiffel Studio about what + program to use to open the `src' reference, which can be URI, PDF, or DOC. See + second EIS for more information. + ]" + EIS: "name=Ackermann_function", "protocol=URI", "tag=rosetta_code", + "src=http://rosettacode.org/wiki/Ackermann_function" + EIS: "name=eis_protocols", "protocol=URI", "tag=eiffel_docs", + "src=https://docs.eiffel.com/book/eiffelstudio/protocols" class APPLICATION diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index 34ccffe5c9..6ceae5c6ee 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -15,11 +15,11 @@ #symbol program = [ - control forrange &int:0 &int:3 &do: (&int:i) + 0 to:3 &doEach: (:i) [ - control forrange &int:0 &int:5 &do: (&int:j) + 0 to:5 &doEach: (:j) [ - consoleEx writeLine:"A(":i:",":j:")=":(ackermann:i:j). + console writeLine:"A(":i:",":j:")=":(ackermann:i:j). ]. ]. diff --git a/Task/Ackermann-function/Erlang/ackermann-function.erl b/Task/Ackermann-function/Erlang/ackermann-function.erl index 0a79c28ecb..8d9a6091d8 100644 --- a/Task/Ackermann-function/Erlang/ackermann-function.erl +++ b/Task/Ackermann-function/Erlang/ackermann-function.erl @@ -1,9 +1,9 @@ --module(ack). --export([main/1, ack/2]). +-module(ackermann). +-export([ackermann/2]). -main( [A, B] ) -> - io:fwrite( "~p~n",[ack(erlang:list_to_integer(A), erlang:list_to_integer(B))] ). - -ack(0,N) -> N + 1; -ack(M,0) -> ack(M-1, 1); -ack(M,N) -> ack(M-1,ack(M,N-1)). +ackermann(0, N) -> + N+1; +ackermann(M, 0) -> + ackermann(M-1, 1); +ackermann(M, N) when M > 0 andalso N > 0 -> + ackermann(M-1, ackermann(M, N-1)). diff --git a/Task/Ackermann-function/Nemerle/ackermann-function-1.nemerle b/Task/Ackermann-function/Nemerle/ackermann-function-1.nemerle new file mode 100644 index 0000000000..24b44f4066 --- /dev/null +++ b/Task/Ackermann-function/Nemerle/ackermann-function-1.nemerle @@ -0,0 +1,20 @@ +using System; +using Nemerle.IO; + + +def ackermann(m, n) { + def A = ackermann; + match(m, n) { + | (0, n) => n + 1 + | (m, 0) when m > 0 => A(m - 1, 1) + | (m, n) when m > 0 && n > 0 => A(m - 1, A(m, n - 1)) + | _ => throw Exception("invalid inputs"); + } +} + + +for(mutable m = 0; m < 4; m++) { + for(mutable n = 0; n < 5; n++) { + print("ackermann($m, $n) = $(ackermann(m, n))\n"); + } +} diff --git a/Task/Ackermann-function/Nemerle/ackermann-function-2.nemerle b/Task/Ackermann-function/Nemerle/ackermann-function-2.nemerle new file mode 100644 index 0000000000..f1599c8c5c --- /dev/null +++ b/Task/Ackermann-function/Nemerle/ackermann-function-2.nemerle @@ -0,0 +1,6 @@ +def ackermann(m, n) { + | (0, n) => n + 1 + | (m, 0) when m > 0 => ackermann(m - 1, 1) + | (m, n) when m > 0 && n > 0 => ackermann(m - 1, ackermann(m, n - 1)) + | _ => throw Exception("invalid inputs"); +} diff --git a/Task/Ackermann-function/Nemerle/ackermann-function-3.nemerle b/Task/Ackermann-function/Nemerle/ackermann-function-3.nemerle new file mode 100644 index 0000000000..ab056dc65b --- /dev/null +++ b/Task/Ackermann-function/Nemerle/ackermann-function-3.nemerle @@ -0,0 +1,9 @@ +def ackermann = { + def A(m, n) { + | (0, n) => n + 1 + | (m, 0) when m > 0 => A(m - 1, 1) + | (m, n) when m > 0 && n > 0 => A(m - 1, A(m, n - 1)) + | _ => throw Exception("invalid inputs"); + } + A +} diff --git a/Task/Ackermann-function/Objeck/ackermann-function.objeck b/Task/Ackermann-function/Objeck/ackermann-function.objeck new file mode 100644 index 0000000000..7a3d22e0d6 --- /dev/null +++ b/Task/Ackermann-function/Objeck/ackermann-function.objeck @@ -0,0 +1,30 @@ +class Ackermann { + function : Main(args : String[]) ~ Nil { + for(m := 0; m <= 3; ++m;) { + for(n := 0; n <= 4; ++n;) { + a := Ackermann(m, n); + if(a > 0) { + "Ackermann({$m}, {$n}) = {$a}"->PrintLine(); + }; + }; + }; + } + + function : Ackermann(m : Int, n : Int) ~ Int { + if(m > 0) { + if (n > 0) { + return Ackermann(m - 1, Ackermann(m, n - 1)); + } + else if (n = 0) { + return Ackermann(m - 1, 1); + }; + } + else if(m = 0) { + if(n >= 0) { + return n + 1; + }; + }; + + return -1; + } +} diff --git a/Task/Ackermann-function/PL-SQL/ackermann-function.sql b/Task/Ackermann-function/PL-SQL/ackermann-function.sql new file mode 100644 index 0000000000..2c701602e2 --- /dev/null +++ b/Task/Ackermann-function/PL-SQL/ackermann-function.sql @@ -0,0 +1,21 @@ +DECLARE + + FUNCTION ackermann(pi_m IN NUMBER, + pi_n IN NUMBER) RETURN NUMBER IS + BEGIN + IF pi_m = 0 THEN + RETURN pi_n + 1; + ELSIF pi_n = 0 THEN + RETURN ackermann(pi_m - 1, 1); + ELSE + RETURN ackermann(pi_m - 1, ackermann(pi_m, pi_n - 1)); + END IF; + END ackermann; + +BEGIN + FOR n IN 0 .. 6 LOOP + FOR m IN 0 .. 3 LOOP + dbms_output.put_line('A(' || m || ',' || n || ') = ' || ackermann(m, n)); + END LOOP; + END LOOP; +END; diff --git a/Task/Ackermann-function/Perl/ackermann-function-5.pl b/Task/Ackermann-function/Perl/ackermann-function-5.pl new file mode 100644 index 0000000000..43d5497aaf --- /dev/null +++ b/Task/Ackermann-function/Perl/ackermann-function-5.pl @@ -0,0 +1,34 @@ +use strict; +use warnings; +use Math::BigInt; + +use constant two => Math::BigInt->new(2); + +sub ack { + my $n = pop; + while( @_ ) { + my $m = pop; + if( $m > 3 ) { + push @_, (--$m) x $n; + push @_, reverse 3 .. --$m; + $n = 13; + } elsif( $m == 3 ) { + if( $n < 29 ) { + $n = ( 1 << ( $n + 3 ) ) - 3; + } else { + $n = two ** ( $n + 3 ) - 3; + } + } elsif( $m == 2 ) { + $n = 2 * $n + 3; + } elsif( $m >= 0 ) { + $n = $n + $m + 1; + } else { + die "negative m!"; + } + } + $n; +} + +print "ack(3,4) is ", ack(3,4), "\n"; +print "ack(4,1) is ", ack(4,1), "\n"; +print "ack(4,2) has ", length(ack(4,2)), " digits\n"; diff --git a/Task/Ackermann-function/Pure-Data/ackermann-function.pure b/Task/Ackermann-function/Pure-Data/ackermann-function.pure new file mode 100644 index 0000000000..7fd130742e --- /dev/null +++ b/Task/Ackermann-function/Pure-Data/ackermann-function.pure @@ -0,0 +1,45 @@ +#N canvas 741 265 450 436 10; +#X obj 83 111 t b l; +#X obj 115 163 route 0; +#X obj 115 185 + 1; +#X obj 83 380 f; +#X obj 161 186 swap; +#X obj 161 228 route 0; +#X obj 161 250 - 1; +#X obj 161 208 pack; +#X obj 115 314 t f f; +#X msg 161 272 \$1 1; +#X obj 115 142 t l; +#X obj 207 250 swap; +#X obj 273 271 - 1; +#X obj 207 272 t f f; +#X obj 207 298 - 1; +#X obj 207 360 pack; +#X obj 239 299 pack; +#X obj 83 77 inlet; +#X obj 83 402 outlet; +#X connect 0 0 3 0; +#X connect 0 1 10 0; +#X connect 1 0 2 0; +#X connect 1 1 4 0; +#X connect 2 0 8 0; +#X connect 3 0 18 0; +#X connect 4 0 7 0; +#X connect 4 1 7 1; +#X connect 5 0 6 0; +#X connect 5 1 11 0; +#X connect 6 0 9 0; +#X connect 7 0 5 0; +#X connect 8 0 3 1; +#X connect 8 1 15 1; +#X connect 9 0 10 0; +#X connect 10 0 1 0; +#X connect 11 0 13 0; +#X connect 11 1 12 0; +#X connect 12 0 16 1; +#X connect 13 0 14 0; +#X connect 13 1 16 0; +#X connect 14 0 15 0; +#X connect 15 0 10 0; +#X connect 16 0 10 0; +#X connect 17 0 0 0; diff --git a/Task/Ackermann-function/REXX/ackermann-function-1.rexx b/Task/Ackermann-function/REXX/ackermann-function-1.rexx index 30e4659fb6..84ebc21c4f 100644 --- a/Task/Ackermann-function/REXX/ackermann-function-1.rexx +++ b/Task/Ackermann-function/REXX/ackermann-function-1.rexx @@ -1,25 +1,25 @@ -/*REXX program calculates/shows some values for the Ackermann function. */ - - /*Note: the Ackermann function (as implemented) is */ - /* higly recursive and is limited by the */ - /* biggest number that can have "1" added to */ - /* a number (successfully, accurately). */ +/*REXX program calculates and displays some values for the Ackermann function.*/ +/* ╔════════════════════════════════════════════════════════════════════════╗ + ║ Note: the Ackermann function (as implemented here) utilizes deep ║ + ║ recursive and is limited by the largest number that can have ║ + ║ "1" (unity) added to a number (successfully and accurately). ║ + ╚════════════════════════════════════════════════════════════════════════╝ */ high=24 - do j=0 to 3; say - do k=0 to high%(max(1,j)) - call Ackermann_tell j,k - end /*k*/ - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ACKERMANN_TELL subroutine───────────*/ -ackermann_tell: parse arg mm,nn; calls=0 /*display an echo message.*/ -nnn=right(nn,length(high)) -say 'Ackermann('mm","nnn')='right(ackermann(mm,nn),high), - left('',12) 'calls='right(calls,high) + do j=0 to 3; say + do k=0 to high%(max(1,j)) + call Ackermann_tell j,k + end /*k*/ + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────ACKERMANN_TELL subroutine─────────────────*/ +ackermann_tell: parse arg mm,nn; calls=0 /*display an echo message. */ +#=right(nn,length(high)) +say 'Ackermann('mm","#')='right(ackermann(mm,nn),high), + left('',12) 'calls='right(calls,high) return -/*──────────────────────────────────ACKERMANN subroutine────────────────*/ -ackermann: procedure expose calls /*compute the Ackerman function. */ +/*──────────────────────────────────ACKERMANN subroutine──────────────────────*/ +ackermann: procedure expose calls /*compute value of Ackermann function.*/ parse arg m,n; calls=calls+1 -if m==0 then return n+1 -if n==0 then return ackermann(m-1,1) - return ackermann(m-1,ackermann(m,n-1)) +if m==0 then return n+1 +if n==0 then return ackermann(m-1,1) + return ackermann(m-1,ackermann(m,n-1)) diff --git a/Task/Ackermann-function/REXX/ackermann-function-2.rexx b/Task/Ackermann-function/REXX/ackermann-function-2.rexx index 072ea29706..0ff1d7ddc5 100644 --- a/Task/Ackermann-function/REXX/ackermann-function-2.rexx +++ b/Task/Ackermann-function/REXX/ackermann-function-2.rexx @@ -1,19 +1,19 @@ -/*REXX program calculates/shows some values for the Ackermann function. */ +/*REXX program calculates and displays some values for the Ackermann function.*/ high=24 - do j=0 to 3; say - do k=0 to high%(max(1,j)) - call Ackermann_tell j,k - end /*k*/ - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ACKERMANN_TELL subroutine───────────*/ -ackermann_tell: parse arg mm,nn; calls=0 /*display an echo message.*/ -nnn=right(nn,length(high)) -say 'Ackermann('mm","nnn')='right(ackermann(mm,nn),high), - left('',12) 'calls='right(calls,10) + do j=0 to 3; say + do k=0 to high%(max(1,j)) + call Ackermann_tell j,k + end /*k*/ + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────ACKERMANN_TELL subroutine─────────────────*/ +ackermann_tell: parse arg mm,nn; calls=0 /*display an echo message.*/ +#=right(nn,length(high)) +say 'Ackermann('mm","#')='right(ackermann(mm,nn),high), + left('',12) 'calls='right(calls,high) return -/*──────────────────────────────────ACKERMANN subroutine────────────────*/ -ackermann: procedure expose calls /*compute the Ackerman function. */ +/*──────────────────────────────────ACKERMANN subroutine──────────────────────*/ +ackermann: procedure expose calls /*compute value of Ackermann function.*/ parse arg m,n; calls=calls+1 if m==0 then return n+1 if n==0 then return ackermann(m-1,1) diff --git a/Task/Ackermann-function/REXX/ackermann-function-3.rexx b/Task/Ackermann-function/REXX/ackermann-function-3.rexx index d4cecef861..10d1b991c7 100644 --- a/Task/Ackermann-function/REXX/ackermann-function-3.rexx +++ b/Task/Ackermann-function/REXX/ackermann-function-3.rexx @@ -1,36 +1,36 @@ -/*REXX program calculates/shows some values for the Ackermann function. */ +/*REXX program calculates and displays some values for the Ackermann function.*/ high=24 -numeric digits 100 /*have REXX to use up to 100 digit integers.*/ +numeric digits 100 /*have REXX to use up to 100 digit integers.*/ - /*When REXX raises a number to a power (via */ - /* the ** operator), the power must be an */ - /* integer (positive, zero, or negative). */ + /*When REXX raises a number to a power (via */ + /* the ** operator), the power must be an */ + /* integer (positive, zero, or negative). */ - do j=0 to 4; say /*Ackermann(5,1) is a bit impractical to calc.*/ - do k=0 to high%(max(1,j)) - call Ackermann_tell j,k - if j==4 & k==2 then leave /*no sense in going overboard.*/ - end /*k*/ + do j=0 to 4; say /*Ackermann(5,1) is a bit impractical to calc.*/ + do k=0 to high%(max(1,j)) + call Ackermann_tell j,k + if j==4 & k==2 then leave /*there's no sense in going overboard. */ + end /*k*/ end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ACKERMANN_TELL subroutine───────────*/ -ackermann_tell: parse arg mm,nn; calls=0 /*display an echo message.*/ -nnn=right(nn,length(high)) -say 'Ackermann('mm","nnn')='right(ackermann(mm,nn),high), - left('',12) 'calls='right(calls,10) +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────ACKERMANN_TELL subroutine─────────────────*/ +ackermann_tell: parse arg mm,nn; calls=0 /*display an echo message.*/ +#=right(nn,length(high)) +say 'Ackermann('mm","#')='right(ackermann(mm,nn),high), + left('',12) 'calls='right(calls,high) return -/*──────────────────────────────────ACKERMANN subroutine────────────────*/ -ackermann: procedure expose calls /*compute the Ackerman function. */ +/*──────────────────────────────────ACKERMANN subroutine──────────────────────*/ +ackermann: procedure expose calls /*compute value of Ackermann function.*/ parse arg m,n; calls=calls+1 -if m==0 then return n+1 -if m==1 then return n+2 -if m==2 then return n+n+3 -if m==3 then return 2**(n+3)-3 -if m==4 then do; a=2 - do (n+3)-1 /*ugh!*/ - a=2**a - end - return a-3 - end -if n==0 then return ackermann(m-1,1) - return ackermann(m-1,ackermann(m,n-1)) +if m==0 then return n+1 +if m==1 then return n+2 +if m==2 then return n+n+3 +if m==3 then return 2**(n+3)-3 +if m==4 then do; a=2 /* [↓] Ugh! ··· and more ughs. */ + do (n+3)-1 /*This is where the heavy lifting is. */ + a=2**a + end + return a-3 + end +if n==0 then return ackermann(m-1,1) + return ackermann(m-1,ackermann(m,n-1)) diff --git a/Task/Ackermann-function/Rust/ackermann-function-1.rust b/Task/Ackermann-function/Rust/ackermann-function-1.rust index cea988c48a..81455e177b 100644 --- a/Task/Ackermann-function/Rust/ackermann-function-1.rust +++ b/Task/Ackermann-function/Rust/ackermann-function-1.rust @@ -1,15 +1,14 @@ - // works for Rust 0.9 -fn main() { - let a: int = ack(3, 4); // 125 - println!("{}", a.to_str()); +fn ack(m: isize, n: isize) -> isize { + if m == 0 { + n + 1 + } else if n == 0 { + ack(m - 1, 1) + } else { + ack(m - 1, ack(m, n - 1)) + } } -fn ack(m: int, n: int) -> int { - if m == 0 { - n + 1 - } else if n == 0 { - ack(m - 1, 1) - } else { - ack(m - 1, ack(m, n - 1)) - } +fn main() { + let a = ack(3, 4); + println!("{}", a); // 125 } diff --git a/Task/Active-Directory-Connect/Racket/active-directory-connect-1.rkt b/Task/Active-Directory-Connect/Racket/active-directory-connect-1.rkt new file mode 100644 index 0000000000..3cf49b683f --- /dev/null +++ b/Task/Active-Directory-Connect/Racket/active-directory-connect-1.rkt @@ -0,0 +1,3 @@ +#lang racket +(require net/ldap) +(ldap-authenticate "ldap.somewhere.com" 389 "uid=username,ou=people,dc=somewhere,dc=com" password) diff --git a/Task/Active-Directory-Connect/Racket/active-directory-connect.rkt b/Task/Active-Directory-Connect/Racket/active-directory-connect-2.rkt similarity index 100% rename from Task/Active-Directory-Connect/Racket/active-directory-connect.rkt rename to Task/Active-Directory-Connect/Racket/active-directory-connect-2.rkt diff --git a/Task/Active-object/C++/active-object.cpp b/Task/Active-object/C++/active-object.cpp new file mode 100644 index 0000000000..0798f804c2 --- /dev/null +++ b/Task/Active-object/C++/active-object.cpp @@ -0,0 +1,89 @@ +#include +#include +#include +#include +#include +#include + +using namespace std::chrono_literals; + +class Integrator +{ + public: + using clock_type = std::chrono::high_resolution_clock; + using dur_t = std::chrono::duration; + using func_t = double(*)(double); + + explicit Integrator(func_t f = nullptr); + ~Integrator(); + void input(func_t new_input); + double output() { return integrate(); } + + private: + std::atomic_flag continue_; + std::mutex mutex; + std::thread worker; + + func_t func; + double state = 0; + //Improves precision by reducing sin result error on large values + clock_type::time_point const beginning = clock_type::now(); + clock_type::time_point t_prev = beginning; + + void do_work(); + double integrate(); +}; + +Integrator::Integrator(func_t f) : func(f) +{ + continue_.test_and_set(); + worker = std::thread(&Integrator::do_work, this); +} + +Integrator::~Integrator() +{ + continue_.clear(); + worker.join(); +} + +void Integrator::input(func_t new_input) +{ + integrate(); + std::lock_guard lock(mutex); + func = new_input; +} + +void Integrator::do_work() +{ + while(continue_.test_and_set()) { + integrate(); + std::this_thread::sleep_for(1ms); + } +} + +double Integrator::integrate() +{ + std::lock_guard lock(mutex); + auto now = clock_type::now(); + dur_t start = t_prev - beginning; + dur_t fin = now - beginning; + if(func) + state += (func(start.count()) + func(fin.count())) * (fin - start).count() / 2; + t_prev = now; + return state; +} + +double sine(double time) +{ + constexpr double PI = 3.1415926535897932; + return std::sin(2 * PI * 0.5 * time); +} + +int main() +{ + Integrator foo(sine); + std::this_thread::sleep_for(2s); + foo.input(nullptr); + std::this_thread::sleep_for(500ms); + std::cout << foo.output(); +} diff --git a/Task/Active-object/J/active-object-1.j b/Task/Active-object/J/active-object-1.j new file mode 100644 index 0000000000..d5a62204c9 --- /dev/null +++ b/Task/Active-object/J/active-object-1.j @@ -0,0 +1,24 @@ +coclass 'activeobject' +require'dates' + +create=:setinput NB. constructor + +T=:3 :0 + if. nc<'T0' do. T0=:tsrep 6!:0'' end. + 0.001*(tsrep 6!:0'')-T0 +) + +F=:G=:0: +Zero=:0 + +setinput=:3 :0 + zero=. getoutput'' + '`F ignore'=: y,_:`'' + G=: F f.d._1 + Zero=: zero-G T '' + getoutput'' +) + +getoutput=:3 :0 + Zero+G T'' +) diff --git a/Task/Active-object/J/active-object-2.j b/Task/Active-object/J/active-object-2.j new file mode 100644 index 0000000000..f0208aa075 --- /dev/null +++ b/Task/Active-object/J/active-object-2.j @@ -0,0 +1,17 @@ +cocurrent 'testrig' + +delay=: 6!:3 + +object=: conew 'activeobject' +setinput__object 1&o.@o.`'' +smoutput (T__object,getoutput__object) '' + +delay 2 + +smoutput (T__object,getoutput__object) '' +setinput__object 0:`'' +smoutput (T__object,getoutput__object) '' + +delay 0.5 + +smoutput (T__object,getoutput__object) '' diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena index 942d66e752..0109cb4cfe 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena @@ -1,8 +1,8 @@ #define system. +#define extensions. -#class Extender +#class Extender :: BaseExtender { - #field theObject. #field theField. #constructor new : anObject @@ -16,20 +16,18 @@ [ theField := aValue. ] - - #method => theObject. } #symbol program = [ #var anObject := 234. - // adding a field + // extending an object with a field anObject := Extender new:anObject. anObject set &foo:"bar". - console << anObject << ".foo=" << anObject foo. + console writeLine:anObject:".foo=":(anObject foo). console readChar. ]. diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Forth/add-a-variable-to-a-class-instance-at-runtime.fth b/Task/Add-a-variable-to-a-class-instance-at-runtime/Forth/add-a-variable-to-a-class-instance-at-runtime.fth new file mode 100644 index 0000000000..c4694a3439 --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Forth/add-a-variable-to-a-class-instance-at-runtime.fth @@ -0,0 +1,29 @@ +include FMS-SI.f +include FMS-SILib.f + + +\ FMS doesn't have the ability to add instance variables +\ or methods at run time. But it is very simple to add any number of +\ objects of any type to a single object at run time. The added +\ objects are then accessible via an index number. + +:class foo + object-list inst-objects \ a dynamically growable object container + :m add: ( obj -- ) inst-objects add: ;m + :m at: ( idx -- obj ) inst-objects at: ;m +;class + +foo foo1 + +: main + heap> string foo1 add: + heap> fvar foo1 add: + + s" Now is the time " 0 foo1 at: !: + 3.14159e 1 foo1 at: !: + + 0 foo1 at: p: \ send the print message to indexed object 0 + 1 foo1 at: p: \ send the print message to indexed object 1 +; + +main \ => Now is the time 3.14159 diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Perl-6/add-a-variable-to-a-class-instance-at-runtime-3.pl6 b/Task/Add-a-variable-to-a-class-instance-at-runtime/Perl-6/add-a-variable-to-a-class-instance-at-runtime-3.pl6 index 214fd5c523..9162cf6e47 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Perl-6/add-a-variable-to-a-class-instance-at-runtime-3.pl6 +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Perl-6/add-a-variable-to-a-class-instance-at-runtime-3.pl6 @@ -1,4 +1,4 @@ -use MONKEY_TYPING; +use MONKEY-TYPING; augment class Int { method answer { "Life, the Universe, and Everything" } } diff --git a/Task/Address-of-a-variable/Rust/address-of-a-variable-1.rust b/Task/Address-of-a-variable/Rust/address-of-a-variable-1.rust new file mode 100644 index 0000000000..a58eafe675 --- /dev/null +++ b/Task/Address-of-a-variable/Rust/address-of-a-variable-1.rust @@ -0,0 +1,3 @@ +let var: u32 = 1; +let raw: *const u32 = &var; +println!("address of var: {:?}", raw); diff --git a/Task/Address-of-a-variable/Rust/address-of-a-variable-2.rust b/Task/Address-of-a-variable/Rust/address-of-a-variable-2.rust new file mode 100644 index 0000000000..9b1bed0267 --- /dev/null +++ b/Task/Address-of-a-variable/Rust/address-of-a-variable-2.rust @@ -0,0 +1,5 @@ +let address: usize = 0x7ffc8f303130; +unsafe { + let val = *(address as *const usize); + println!("value at {}: {:?}", address, val); +} diff --git a/Task/Address-of-a-variable/Rust/address-of-a-variable-3.rust b/Task/Address-of-a-variable/Rust/address-of-a-variable-3.rust new file mode 100644 index 0000000000..78261501f5 --- /dev/null +++ b/Task/Address-of-a-variable/Rust/address-of-a-variable-3.rust @@ -0,0 +1,3 @@ +unsafe { + *(0x7ffc8f303130 as *mut usize) = 1; +} diff --git a/Task/Align-columns/Elixir/align-columns.elixir b/Task/Align-columns/Elixir/align-columns.elixir new file mode 100644 index 0000000000..fb4f2508d6 --- /dev/null +++ b/Task/Align-columns/Elixir/align-columns.elixir @@ -0,0 +1,35 @@ +defmodule Align do + def columns(text, alignment) do + fieldsbyrow = String.split(text, "\n", trim: true) + |> Enum.map(fn line -> String.split(line, "$", trim: true) end) + maxfields = Enum.map(fieldsbyrow, fn field -> length(field) end) |> Enum.max + colwidths = Enum.map(fieldsbyrow, fn field -> field ++ List.duplicate("", maxfields - length(field)) end) + |> List.zip + |> Enum.map(fn column -> + Tuple.to_list(column) |> Enum.map(fn col-> String.length(col) end) |> Enum.max + end) + Enum.each(fieldsbyrow, fn row -> + Enum.zip(row, colwidths) + |> Enum.map(fn {field, width} -> adjust(field, width, alignment) end) + |> Enum.join(" ") |> IO.puts + end) + end + + defp adjust(field, width, :Left), do: String.ljust(field, width) + defp adjust(field, width, :Right), do: String.rjust(field, width) + defp adjust(field, width, _), do: :string.centre(String.to_char_list(field), width) +end + +text = """ +Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +are$delineated$by$a$single$'dollar'$character,$write$a$program +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ +column$are$separated$by$at$least$one$space. +Further,$allow$for$each$word$in$a$column$to$be$either$left$ +justified,$right$justified,$or$center$justified$within$its$column. +""" + +Enum.each([:Left, :Right, :Center], fn alignment -> + IO.puts "\n# #{alignment} Column-aligned output:" + Align.columns(text, alignment) +end) diff --git a/Task/Align-columns/Erlang/align-columns.erl b/Task/Align-columns/Erlang/align-columns.erl index aebb153caa..844ebe2f8b 100644 --- a/Task/Align-columns/Erlang/align-columns.erl +++ b/Task/Align-columns/Erlang/align-columns.erl @@ -36,33 +36,3 @@ prepare_line(Words_line, Words_length, Alignment) -> Zipped = lists:zip (All_words, Words_length), [ apply(string, Alignment, [Word, Length + 1, $\s]) || {Word, Length} <- Zipped]. - -=== Output - - -1> c(align_columns). -{ok,align_columns} -2> align_columns:align_center(). - Given a text file of many lines where fields within a line - are delineated by a single 'dollar' character, write a program - that aligns each column of fields by ensuring that words in each - column are separated by at least one space. - Further, allow for each word in a column to be either left -justified, right justified, or center justified within its column. -ok -3> align_columns:align_left(). -Given a text file of many lines where fields within a line -are delineated by a single 'dollar' character, write a program -that aligns each column of fields by ensuring that words in each -column are separated by at least one space. -Further, allow for each word in a column to be either left -justified, right justified, or center justified within its column. -ok -4> align_columns:align_right(). - Given a text file of many lines where fields within a line - are delineated by a single 'dollar' character, write a program - that aligns each column of fields by ensuring that words in each - column are separated by at least one space. - Further, allow for each word in a column to be either left - justified, right justified, or center justified within its column. -ok diff --git a/Task/Align-columns/Python/align-columns-3.py b/Task/Align-columns/Python/align-columns-3.py new file mode 100644 index 0000000000..ac4daedcdb --- /dev/null +++ b/Task/Align-columns/Python/align-columns-3.py @@ -0,0 +1,18 @@ +''' +cat <<'EOF' > align_columns.dat +Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +are$delineated$by$a$single$'dollar'$character,$write$a$program +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ +column$are$separated$by$at$least$one$space. +Further,$allow$for$each$word$in$a$column$to$be$either$left$ +justified,$right$justified,$or$center$justified$within$its$column. +EOF +''' + +for align in '<^>': + rows = [ line.strip().split('$') for line in open('align_columns.dat') ] + fmts = [ '{:%s%d}' % (align, max( len(row[i]) if i < len(row) else 0 for row in rows )) + for i in range(max(map(len, rows))) ] + for row in rows: + print(' '.join(fmts).format(*(row + [''] * len(fmts)))) + print('') diff --git a/Task/Align-columns/Ruby/align-columns.rb b/Task/Align-columns/Ruby/align-columns.rb index cf0a0b8845..e08cfd8b00 100644 --- a/Task/Align-columns/Ruby/align-columns.rb +++ b/Task/Align-columns/Ruby/align-columns.rb @@ -1,15 +1,13 @@ -J2justifier = {'L' => :ljust, - 'R' => :rjust, - 'C' => :center} +J2justifier = {Left: :ljust, Right: :rjust, Center: :center} =begin Justify columns of textual tabular input where the record separator is the newline and the field separator is a 'dollar' character. -justification can be L, R, or C; (Left, Right, or Centered). +justification can be Symbol; (:Left, :Right, or :Center). Return the justified output as a string =end -def aligner(infile, justification = 'L') +def aligner(infile, justification = :Left) fieldsbyrow = infile.map {|line| line.strip.split('$')} # pad to same number of fields per record maxfields = fieldsbyrow.map(&:length).max @@ -38,8 +36,8 @@ def aligner(infile, justification = 'L') justified,$right$justified,$or$center$justified$within$its$column. END -for align in %w{Left Right Center} +for align in [:Left, :Right, :Center] infile = StringIO.new(textinfile) puts "\n# %s Column-aligned output:" % align - puts aligner(infile, align[0..0]) + puts aligner(infile, align) end diff --git a/Task/Align-columns/Rust/align-columns.rust b/Task/Align-columns/Rust/align-columns.rust index b8e58fc179..773be13ba7 100644 --- a/Task/Align-columns/Rust/align-columns.rust +++ b/Task/Align-columns/Rust/align-columns.rust @@ -1,53 +1,46 @@ -#![feature(core)] -extern crate core; - -use core::iter::repeat; -use core::str::StrExt; -use std::iter::Extend; +use std::iter::{Extend, repeat}; enum AlignmentType { Left, Center, Right } fn get_column_widths(text: &str) -> Vec { - let mut widths = Vec::new(); - for line in text.lines().map(|s| s.trim_matches(' ').trim_right_matches('$')) { - let mut lens = line.split('$').map(|s| s.char_len()); - let mut idx = 0; - for len in lens { - if idx < widths.len() { - widths[idx] = std::cmp::max(widths[idx], len); - } - else { - widths.push(len); - } - idx += 1; - } - } - widths + let mut widths = Vec::new(); + for line in text.lines().map(|s| s.trim_matches(' ').trim_right_matches('$')) { + let lens = line.split('$').map(|s| s.chars().count()); + for (idx, len) in lens.enumerate() { + if idx < widths.len() { + widths[idx] = std::cmp::max(widths[idx], len); + } + else { + widths.push(len); + } + } + } + widths } fn align_columns(text: &str, alignment: AlignmentType) -> String { - let widths = get_column_widths(text); - let mut result = String::new(); - for line in text.lines().map(|s| s.trim_matches(' ').trim_right_matches('$')) { - for (s, w) in line.split('$').zip(widths.iter()) { - let blank_count = w - s.char_len(); - let (pre, post) = match alignment { - AlignmentType::Left => (0, blank_count), - AlignmentType::Center => (blank_count / 2, (blank_count + 1) / 2), - AlignmentType::Right => (blank_count, 0), - }; - result.extend(repeat(' ').take(pre)); - result.push_str(s); - result.extend(repeat(' ').take(post)); - result.push(' '); - } - result.push_str("\n"); - } - result + let widths = get_column_widths(text); + let mut result = String::new(); + for line in text.lines().map(|s| s.trim_matches(' ').trim_right_matches('$')) { + for (s, w) in line.split('$').zip(widths.iter()) { + let blank_count = w - s.chars().count(); + let (pre, post) = match alignment { + AlignmentType::Left => (0, blank_count), + AlignmentType::Center => (blank_count / 2, (blank_count + 1) / 2), + AlignmentType::Right => (blank_count, 0), + }; + result.extend(repeat(' ').take(pre)); + result.push_str(s); + result.extend(repeat(' ').take(post)); + result.push(' '); + } + result.push_str("\n"); + } + result } fn main() { - let text = r#"Given$a$text$file$of$many$lines,$where$fields$within$a$line$ + let text = r#"Given$a$text$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. diff --git a/Task/Align-columns/TUSCRIPT/align-columns.tu b/Task/Align-columns/TUSCRIPT/align-columns.tu index b22236f941..c7450354bf 100644 --- a/Task/Align-columns/TUSCRIPT/align-columns.tu +++ b/Task/Align-columns/TUSCRIPT/align-columns.tu @@ -12,7 +12,7 @@ SET nix=SPLIT (exampletext,":$:",c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12) LOOP l1=1,12 SET colum=CONCAT ("c",l1) SET newcolum=CONCAT ("new",l1) -SET @newcolum="", length=MAX LENGTH (@colum), space=length+2 +SET @newcolum="", length=MAX LENGTH (@colum), space=length+2 LOOP n,l2=@colum SET newcell=CENTER (l2,space) SET @newcolum=APPEND (@newcolum,"~",newcell) diff --git a/Task/Aliquot-sequence-classifications/AWK/aliquot-sequence-classifications.awk b/Task/Aliquot-sequence-classifications/AWK/aliquot-sequence-classifications.awk new file mode 100644 index 0000000000..82a0ecfd00 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/AWK/aliquot-sequence-classifications.awk @@ -0,0 +1,66 @@ +#!/bin/gawk -f +function sumprop(num, i,sum,root) { +if (num == 1) return 0 +sum=1 +root=sqrt(num) +for ( i=2; i < root; i++) { + if (num % i == 0 ) + { + sum = sum + i + num/i + } + } +if (num % root == 0) + { + sum = sum + root + } +return sum +} +function class(k, oldk,newk,seq){ +# first term +oldk = k +seq = " " +# second term +newk = sumprop(oldk) +oldk = newk +seq = seq " " newk +if (newk == 0) return "terminating " seq +if (newk == k) return "perfect " seq +# third term +newk = sumprop(oldk) +oldk = newk +seq = seq " " newk +if (newk == 0) return "terminating " seq +if (newk == k) return "amicable " seq +for (t=4; t<17; t++) { +newk = sumprop(oldk) +seq = seq " " newk +if (newk == 0) return "terminating " seq +if (newk == k) return "sociable (period " t-1 ") "seq +if (newk == oldk) return "aspiring " seq +if (index(seq," " newk " ") > 0) return "cyclic (at " newk ") " seq +if (newk > 140737488355328) return "non-terminating (term > 140737488355328) " seq +oldk = newk +} +return "non-terminating (after 16 terms) " seq +} +BEGIN{ +print "Number classification sequence" +for (j=1; j < 11; j++) + { + print j,class(j)} + print 11,class(11) + print 12,class(12) + print 28,class(28) + print 496,class(496) + print 220,class(220) + print 1184,class(1184) + print 12496,class(12496) + print 1264460,class(1264460) + print 790,class(790) + print 909,class(909) + print 562,class(562) + print 1064,class(1064) + print 1488,class(1488) + print 15355717786080,class(15355717786080) + +} diff --git a/Task/Aliquot-sequence-classifications/Fortran/aliquot-sequence-classifications.f b/Task/Aliquot-sequence-classifications/Fortran/aliquot-sequence-classifications.f new file mode 100644 index 0000000000..0c02683489 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Fortran/aliquot-sequence-classifications.f @@ -0,0 +1,123 @@ + MODULE FACTORSTUFF !This protocol evades the need for multiple parameters, or COMMON, or one shapeless main line... +Concocted by R.N.McLean, MMXV. +c INTEGER*4 I4LIMIT +c PARAMETER (I4LIMIT = 2147483647) + INTEGER*8 TOOBIG !Some bounds. + PARAMETER (TOOBIG = 2**47) !Computer arithmetic is not with real numbers. + INTEGER LOTS !Nor is computer storage infinite. + PARAMETER (LOTS = 10000) !So there can't be all that many of these. + INTEGER*8 KNOWNSUM(LOTS) !If multiple references are expected, it is worthwhile calculating these. + CONTAINS !Assistants. + INTEGER*8 FUNCTION SUMF(N) !Sum of the proper divisors of N. + INTEGER*8 N !The number in question. + INTEGER*8 F,F2 !Candidate factor, and its square. + INTEGER*8 S,INC,BOOST !Assistants. + IF (N.LE.LOTS) THEN !If we're within reach, + SUMF = KNOWNSUM(N) !The result is to hand. + ELSE !Otherwise, some on-the-spot effort ensues. +Could use SUMF in place of S, but some compilers have been confused by such usage. + S = 1 !1 is always a factor of N, but N is deemed not proper. + F = 1 !Prepare a crude search for factors. + INC = 1 !One by plodding one. + IF (MOD(N,2) .EQ. 1) INC = 2!Ah, but an odd number cannot have an even number as a divisor. + 1 F = F + INC !So half the time we can doubleplod. + F2 = F*F !Up to F2 < N rather than F < SQRT(N) and worries over inexact arithmetic. + IF (F2 .LT. N) THEN !F2 = N handled below. + IF (MOD(N,F) .EQ. 0) THEN !Does F divide N? + BOOST = F + N/F !Yes. The divisor and its counterpart. + IF (S .GT. TOOBIG - BOOST) GO TO 666 !Would their augmentation cause an overflow? + S = S + BOOST !No, so count in the two divisors just discovered. + END IF !So much for a divisor discovered. + GO TO 1 !Try for another. + END IF !So much for N = p*q style factors. + IF (F2 .EQ. N) THEN !Special case: N may be a perfect square, not necessarily of a prime number. + IF (S .GT. TOOBIG - F) GO TO 666 !It is. And it too might cause overflow. + S = S + F !But if not, count F once only. + END IF !All done. + SUMF = S !This is the result. + END IF !Whichever way obtained, + RETURN !Done. +Cannot calculate the sum, because it exceeds the INTEGER*8 limit. + 666 SUMF = -666 !An expression of dismay that the caller will notice. + END FUNCTION SUMF !Alternatively, find the prime factors, and combine them... + SUBROUTINE PREPARESUMF !Initialise the KNOWNSUM array. +Convert the Sieve of Eratoshenes to have each slot contain the sum of the proper divisors of its slot number. +Changes to instead count the number of factors, or prime factors, etc. would be simple enough. + INTEGER*8 F !A factor for numbers such as 2F, 3F, 4F, 5F, ... + KNOWNSUM(1) = 0 !Proper divisors of N do not include N. + KNOWNSUM(2:LOTS) = 1 !So, although 1 divides all N without remainder, 1 is excluded for itself. + DO F = 2,LOTS/2 !Step through all the possible divisors of numbers not exceeding LOTS. + FORALL(I = F + F:LOTS:F) KNOWNSUM(I) = KNOWNSUM(I) + F !And augment each corresponding slot. + END DO !Different divisors can hit the same slot. For instance, 6 by 2 and also by 3. + END SUBROUTINE PREPARESUMF !Could alternatively generate all products of prime numbers. + SUBROUTINE CLASSIFY(N) !Traipse along the SumF trail. + INTEGER*8 N !The starter. + INTEGER ROPE !The size of my memory is not so great.. + PARAMETER(ROPE = 16) !Indeed, this is strictly limited. + INTEGER*8 TRAIL(ROPE) !But the numbers can be large. + INTEGER*8 SF !The working sum of proper divisors. + INTEGER I,L !Indices, merely. + CHARACTER*28 THIS !A perfect scratchpad for remarks. + L = 1 !Every journey starts with its first step. + TRAIL(1) = N !Which is this. + SF = N !Syncopation. + 10 SF = SUMF(SF) !Step onwards. + IF (SF .LT. 0) THEN !Trouble? + WRITE (THIS,11) L,"overflows!" !Yes. Too big a number. + 11 FORMAT ("After ",I0,", ",A) !Describe the situation. + CALL REPORT(ADJUSTR(THIS)) !And give the report. + ELSE IF (SF .EQ. 0) THEN !Otherwise, a finish? + WRITE (THIS,11) L,"terminates!" !Yay! + CALL REPORT(ADJUSTR(THIS)) !This sequence is finished. + ELSE IF (ANY(TRAIL(1:L) .EQ. SF)) THEN !Otherwise, is there an echo somewhere? + IF (L .EQ. 1) THEN !Yes! + CALL REPORT("Perfect!") !Are we at the start? + ELSE IF (L .EQ. 2) THEN !Or perhaps not far along. + CALL REPORT("Amicable:") !These are held special. + ELSE !Otherwise, we've wandered further along. + I = MINLOC(ABS(TRAIL(1:L) - SF),DIM=1) !Damnit, re-scan the array to finger the first matching element. + IF (I .EQ. 1) THEN !If all the way back to the start, + WRITE (THIS,12) L !Then there are this many elements in the sociable ring. + 12 FORMAT ("Sociable ",I0,":") !Computers are good at counting. + CALL REPORT(ADJUSTR(THIS)) !So, perform an added service. + ELSE IF (I .EQ. L) THEN !Perhaps we've hit a perfect number! + CALL REPORT("Aspiring:") !A cycle of length one. + ELSE !But otherwise, + WRITE (THIS,13) L - I + 1,SF !A longer cycle. Amicable, or sociable. + 13 FORMAT ("Cyclic end ",I0,", to ",I0,":") !Name the flashback value too. + CALL REPORT(ADJUSTR(THIS)) !Thus. + END IF !So much for cycles. + END IF !So much for finding an echo. + ELSE !Otherwise, nothing special has happened. + IF (L .GE. ROPE) THEN !So, how long is a piece of string? + WRITE (THIS,11) L,"non-terminating?" !Not long enough! + CALL REPORT(ADJUSTR(THIS)) !So we give up. + ELSE !But if there is more scope, + L = L + 1 !Advance one more step. + TRAIL(L) = SF !Save the latest result. + GO TO 10 !And try for the next. + END IF !So much for continuing. + END IF !So much for the classification. + RETURN !Finished. + CONTAINS !Not quite. + SUBROUTINE REPORT(WHAT) !There is this service routine. + CHARACTER*(*) WHAT !Whatever the length of the text, the FORMAT's A28 shows 28 characters, right-aligned. + WRITE (6,1) WHAT,TRAIL(1:L)!Mysteriously, a fresh line after every twelve elements. + 1 FORMAT (A28,1X,12(I0:",")) !And obviously, the : signifies "do not print what follows unless there is another number to go. + END SUBROUTINE REPORT !That was easy. + END SUBROUTINE CLASSIFY !Enough. + END MODULE FACTORSTUFF !Enough assistants. + PROGRAM CLASSIFYTHEM !Report on the nature of the sequence N, Sumf(N), Sumf(Sumf(N)), etc. + USE FACTORSTUFF !This should help. + INTEGER*8 I,N !Steppers. + INTEGER*8 THIS(14) !A testing collection. + DATA THIS/11,12,28,496,220,1184,12496,1264460,790,909, !Old-style continuation character in column six. + 1 562,1064,1488,15355717786080/ !Monster value far exceeds the INTEGER*4 limit + CALL PREPARESUMF !Prepare for 1:LOTS, even though this test run will use only a few. + DO I = 1,10 !As specified, the first ten integers. + CALL CLASSIFY(I) + END DO + DO I = 1,SIZE(THIS) !Now for the specified list. + CALL CLASSIFY(THIS(I)) + END DO + END !Done. diff --git a/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-1.julia b/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-1.julia new file mode 100644 index 0000000000..6bc1af7615 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-1.julia @@ -0,0 +1,24 @@ +function aliquotclassifier{T<:Integer}(n::T) + a = T[n] + b = divisorsum(a[end]) + len = 1 + while len < 17 && !(b in a) && 0 < b && b < 2^47+1 + push!(a, b) + b = divisorsum(a[end]) + len += 1 + end + if b in a + 1 < len || return ("Perfect", a) + if b == a[1] + 2 < len || return ("Amicable", a) + return ("Sociable", a) + elseif b == a[end] + return ("Aspiring", a) + else + return ("Cyclic", push!(a, b)) + end + end + push!(a, b) + b != 0 || return ("Terminating", a) + return ("Non-terminating", a) +end diff --git a/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-2.julia b/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-2.julia new file mode 100644 index 0000000000..2c8a9350b9 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-2.julia @@ -0,0 +1,17 @@ +function pcontrib{T<:Integer}(p::T, a::T) + n = one(T) + pcon = one(T) + for i in 1:a + n *= p + pcon += n + end + return pcon +end + +function divisorsum{T<:Integer}(n::T) + dsum = one(T) + for (p, a) in factor(n) + dsum *= pcontrib(p, a) + end + dsum -= n +end diff --git a/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-3.julia b/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-3.julia new file mode 100644 index 0000000000..2969255cbd --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-3.julia @@ -0,0 +1,6 @@ +println("Classification Tests:") +tests = [1:12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488] +for i in tests + (class, a) = aliquotclassifier(i) + println(@sprintf("%8d => ", i), @sprintf("%16s, ", class), a) +end diff --git a/Task/Aliquot-sequence-classifications/Mathematica/aliquot-sequence-classifications.math b/Task/Aliquot-sequence-classifications/Mathematica/aliquot-sequence-classifications.math new file mode 100644 index 0000000000..09b5594bb4 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Mathematica/aliquot-sequence-classifications.math @@ -0,0 +1,19 @@ +seq[n_] := + NestList[If[# == 0, 0, + DivisorSum[#, # &, Function[div, div != #]]] &, n, 16]; +class[seq_] := + Which[Length[seq] < 2, "Non-terminating", MemberQ[seq, 0], + "Terminating", seq[[1]] == seq[[2]], "Perfect", + Length[seq] > 2 && seq[[1]] == seq[[3]], "Amicable", + Length[seq] > 3 && MemberQ[seq[[4 ;;]], seq[[1]]], "Sociable", + MatchQ[class[Rest[seq]], "Perfect" | "Aspiring"], "Aspiring", + MatchQ[class[Rest[seq]], "Amicable" | "Sociable" | "Cyclic"], + "Cyclic", True, "Non-terminating"]; +notate[seq_] := + Which[seq == {}, {}, + MemberQ[Rest[seq], + seq[[1]]], {Prepend[TakeWhile[Rest[seq], # != seq[[1]] &], + seq[[1]]]}, True, Prepend[notate[Rest[seq]], seq[[1]]]]; +Print[{#, class[seq[#]], notate[seq[#]] /. {0} -> 0}] & /@ {1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, + 562, 1064, 1488, 15355717786080}; diff --git a/Task/Aliquot-sequence-classifications/Perl-6/aliquot-sequence-classifications.pl6 b/Task/Aliquot-sequence-classifications/Perl-6/aliquot-sequence-classifications.pl6 index 98f75eaf93..1505c05114 100644 --- a/Task/Aliquot-sequence-classifications/Perl-6/aliquot-sequence-classifications.pl6 +++ b/Task/Aliquot-sequence-classifications/Perl-6/aliquot-sequence-classifications.pl6 @@ -13,13 +13,13 @@ multi quality ($,$n) { "cyclic-$n" } sub aliquotidian ($x) { my %seen; - my @seq := $x, &propdivsum ... *; + my @seq = $x, &propdivsum ... *; for 0..16 -> $to { - my $this = @seq[$to] or return "$x terminating [@seq[^$to]]"; + my $this = @seq[$to] or return "$x\tterminating\t[@seq[^$to]]"; last if $this > 140737488355328; if %seen{$this}:exists { my $from = %seen{$this}; - return "$x &quality($from, $to-$from) [@seq[^$to]]"; + return "$x\t&quality($from, $to-$from)\t[@seq[^$to]]"; } %seen{$this} = $to; } @@ -27,7 +27,7 @@ sub aliquotidian ($x) { } -aliquotidian($_).say for +aliquotidian($_).say for flat 1..10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, diff --git a/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx b/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx index ae16429c73..0a9274b5e1 100644 --- a/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx +++ b/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx @@ -1,62 +1,63 @@ -/*REXX pgm classifies various positive integers for aliquot sequences. */ -parse arg low high L /*get optional arguments*/ +/*REXX program classifies various positive integers for aliquot sequences. */ +parse arg low high L /*get some 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. */ +if L='' then L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 +big=2**47; NTlimit=16+1 /*seq. non─terminating limit. */ +numeric digits max(9, 1+length(big)) /*be able to handle // oper.*/ +#.=.; #.0=0; #.1=0 /*#. are 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.*/ + do n=low to high /*process (probably) some low numbers. */ + call classify_aliquot n /*call a subroutine to classify number.*/ + end /*n*/ /* [↑] process a range of integers. */ 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. */ +b.=0 /* [↓] ensure one number of each class*/ + do q=1 until b.sociable \== 0 /*the only one that has to be counted. */ + call classify_aliquot -q /*the minus (-) sign indicates ¬ tell. */ + _=what; upper _; b._=b._+1 /*bump the counter for this seq. class.*/ + if b._==1 then call show_class q,$ /*show the first occurrence only.*/ + end /*q*/ /* [↑] process 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.*/ + do i=1 for words(L) /*L is a list of "special numbers". */ + call classify_aliquot word(L,i) /*call a subroutine to classify number.*/ + end /*i*/ /* [↑] process a list of integers. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +classify_aliquot: parse arg a 1 aa; a=abs(a) /*get what number is to be used.*/ +if #.a\==. then s=#.a /*Was this number been summed before? */ + else s=sigma(a) /*No, then classify number the hard way*/ +#.a=s; $=s /*define sum of the proper divisors. */ +what='terminating' /*assume this kind of classification. */ +c.=0; c.s=1 /*clear all cyclic sequences; set 1st.*/ +if $==a then what='perfect' /*check for a "perfect" number. */ + else do t=1 while s\==0 /*loop until sum isn't 0 or > big.*/ + m=word($, words($)) /*obtain the last number in sequence. */ + if #.m==. then s=sigma(m) /*if not defined, then sum proper divs.*/ + else s=#.m /*use the previously found integer. */ + 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 the integer sequence.*/ + if s==a & t>3 then do; what='sociable' ; leave; end + if c.s & m\==0 then do; what='cyclic' ; leave; end + c.s=1 /*assign another possible cyclic number*/ + /* [↓] Rosetta Code task's limit: >16 */ + if t>NTlimit then do; what='non-terminating'; leave; end + if s>big then do; what='NON-TERMINATING'; leave; end + 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 (AliquotType, Vec) { + let limit = 1i64 << 47; //140737488355328 + let mut terms = Some(num).into_iter().collect::>(); + for i in 0..16 { + let n = terms[i]; + let divsum = (1..(n + 1) / 2 + 1).filter(|&x| n % x == 0 && n != x).fold(0, |sum, x| sum + x); + let classification = if divsum == 0 { + Some(AliquotType::Terminating) + } + else if divsum > limit { + Some(AliquotType::NonTerminating) + } + else if let Some(prev_idx) = terms.iter().position(|&x| x == divsum) { + let cycle_len = terms.len() - prev_idx; + Some(if prev_idx == 0 { + match cycle_len { + 1 => AliquotType::Perfect, + 2 => AliquotType::Amicable, + _ => AliquotType::Sociable + } + } + else { + if cycle_len == 1 {AliquotType::Aspiring} else {AliquotType::Cyclic} + }) + } + else { + None + }; + terms.push(divsum); + if let Some(result) = classification { + return (result, terms); + } + } + (AliquotType::NonTerminating, terms) +} + +fn main() { + let nums = [1i64, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488/*, 15355717786080*/]; + for num in &nums { + println!("{} {:?}", num, classify_aliquot(*num)); + } +} diff --git a/Task/Aliquot-sequence-classifications/Tcl/aliquot-sequence-classifications.tcl b/Task/Aliquot-sequence-classifications/Tcl/aliquot-sequence-classifications.tcl new file mode 100644 index 0000000000..4cb434db3b --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Tcl/aliquot-sequence-classifications.tcl @@ -0,0 +1,73 @@ +proc ProperDivisors {n} { + if {$n == 1} {return 0} + 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 + } + } + } + list $sum $divs +} + +proc al_iter {n} { + yield [info coroutine] + while {$n} { + yield $n + lassign [ProperDivisors $n] n + } + yield 0 + return -code break +} + +proc al_classify {n} { + coroutine iter al_iter $n + set items {} + try { + set type "non-terminating" + while {[llength $items] < 16} { + set i [iter] + if {$i == 0} { + set type "terminating" + } + set ix [lsearch -exact $items $i] + set items [linsert $items 0 $i] + switch $ix { + -1 { continue } + 0 { throw RESULT "perfect" } + 1 { throw RESULT "amicable" } + default { throw RESULT "sociable" } + } + } + } trap {RESULT} {type} { + rename iter {} + set map { + perfect aspiring + amicable cyclic + sociable cyclic + } + if {$ix != [llength $items]-2} { + set type [dict get $map $type] + } + } + list $type [lreverse $items] +} + +for {set i 1} {$i <= 10} {incr i} { + puts [format "%8d -> %-16s : %s" $i {*}[al_classify $i]] +} + +foreach i {11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 } { + puts [format "%8d -> %-16s : %s" $i {*}[al_classify $i]] +} + +;# stretch goal .. let's time it: +set i 15355717786080 +puts [time { + puts [format "%8d -> %-16s : %s" $i {*}[al_classify $i]] +}] diff --git a/Task/Almost-prime/ALGOL-68/almost-prime.alg b/Task/Almost-prime/ALGOL-68/almost-prime.alg new file mode 100644 index 0000000000..cc6c5b91de --- /dev/null +++ b/Task/Almost-prime/ALGOL-68/almost-prime.alg @@ -0,0 +1,41 @@ +BEGIN + INT examples=10, classes=5; + MODE SEMIPRIME = STRUCT ([examples]INT data, INT count); + [classes]SEMIPRIME semi primes; + PROC num facs = (INT n) INT : +COMMENT + Return number of not necessarily distinct prime factors of n. + Not very efficient for large n ... +COMMENT + BEGIN + INT tf := 2, residue := n, count := 1; + WHILE tf < residue DO + INT remainder = residue MOD tf; + ( remainder = 0 | count +:= 1; residue %:= tf | tf +:= 1 ) + OD; + count + END; + PROC update table = (REF []SEMIPRIME table, INT i) BOOL : +COMMENT + Add i to the appropriate row of the table, if any, unless that row + is already full. Return a BOOL which is TRUE when all of the table + is full. +COMMENT + BEGIN + INT k := num facs(i); + IF k <= classes + THEN + INT c = 1 + count OF table[k]; + ( c <= examples | (data OF table[k])[c] := i; count OF table[k] := c ) + FI; + INT sum := 0; + FOR i TO classes DO sum +:= count OF table[i] OD; + sum < classes * examples + END; + FOR i TO classes DO count OF semi primes[i] := 0 OD; + FOR i FROM 2 WHILE update table (semi primes, i) DO SKIP OD; + FOR i TO classes + DO + printf (($"k = ", d, ":", n(examples)(xg(0))l$, i, data OF semi primes[i])) + OD +END diff --git a/Task/Almost-prime/Befunge/almost-prime.bf b/Task/Almost-prime/Befunge/almost-prime.bf new file mode 100644 index 0000000000..68fc63420b --- /dev/null +++ b/Task/Almost-prime/Befunge/almost-prime.bf @@ -0,0 +1,6 @@ +1>::48*"= k",,,,02p.":",01v +|^ v0!`\*:g40:2g03g`*#v_ 1`03g+02g->| +F@>/03g1+03p>vpv+1\.:,*48 < +P#|!\g40%g40:<4>:9`>#v_\1^| +|^>#!1#`+#50#:^#+1,+5>#5$<| diff --git a/Task/Almost-prime/Erlang/almost-prime.erl b/Task/Almost-prime/Erlang/almost-prime.erl new file mode 100644 index 0000000000..837468d390 --- /dev/null +++ b/Task/Almost-prime/Erlang/almost-prime.erl @@ -0,0 +1,24 @@ +-module(factors). +-export([factors/1,kfactors/0,kfactors/2]). + +factors(N) -> + factors(N,2,[]). + +factors(1,_,Acc) -> Acc; +factors(N,K,Acc) when N rem K == 0 -> + factors(N div K,K, [K|Acc]); +factors(N,K,Acc) -> + factors(N,K+1,Acc). + +kfactors() -> kfactors(10,5,1,1,[]). +kfactors(N,K) -> kfactors(N,K,1,1,[]). +kfactors(_Tn,Tk,_N,K,_Acc) when K == Tk+1 -> io:fwrite("Done! "); +kfactors(Tn,Tk,N,K,Acc) when length(Acc) == Tn -> + io:format("K: ~w ~w ~n", [K, Acc]), + kfactors(Tn,Tk,2,K+1,[]); + +kfactors(Tn,Tk,N,K,Acc) -> + case length(factors(N)) of K -> + kfactors(Tn,Tk, N+1,K, Acc ++ [ N ] ); + _ -> + kfactors(Tn,Tk, N+1,K, Acc) end. diff --git a/Task/Almost-prime/Frink/almost-prime.frink b/Task/Almost-prime/Frink/almost-prime.frink new file mode 100644 index 0000000000..03ef633fc1 --- /dev/null +++ b/Task/Almost-prime/Frink/almost-prime.frink @@ -0,0 +1,17 @@ +for k = 1 to 5 +{ + n=2 + count = 0 + print["k=$k:"] + do + { + if length[factorFlat[n]] == k + { + print[" $n"] + count = count + 1 + } + n = n + 1 + } while count < 10 + + println[] +} diff --git a/Task/Almost-prime/Haskell/almost-prime.hs b/Task/Almost-prime/Haskell/almost-prime-1.hs similarity index 100% rename from Task/Almost-prime/Haskell/almost-prime.hs rename to Task/Almost-prime/Haskell/almost-prime-1.hs diff --git a/Task/Almost-prime/Haskell/almost-prime-2.hs b/Task/Almost-prime/Haskell/almost-prime-2.hs new file mode 100644 index 0000000000..9b7a9c5a84 --- /dev/null +++ b/Task/Almost-prime/Haskell/almost-prime-2.hs @@ -0,0 +1,27 @@ +primes = 2:3:[n | n <- [5,7..], foldr (\p r-> p*p > n || rem n p > 0 && r) + True (drop 1 primes)] + +merge aa@(a:as) bb@(b:bs) + | a < b = a:merge as bb + | otherwise = b:merge aa bs + +-- n-th item is all k-primes not divisible by any of the first n primes +notdivs k = f primes $ kprimes (k-1) where + f (p:ps) s = map (p*) s : f ps (filter ((/=0).(`mod`p)) s) + +kprimes k + | k == 1 = primes + | otherwise = f (head ndk) (tail ndk) (tail $ map (^k) primes) where + ndk = notdivs k + -- tt is the thresholds for merging in next sequence + -- it is equal to "map head seqs", but don't do that + f aa@(a:as) seqs tt@(t:ts) + | a < t = a : f as seqs tt + | otherwise = f (merge aa $ head seqs) (tail seqs) ts + +main = do + -- next line is for task requirement: + mapM_ (\x->print (x, take 10 $ kprimes x)) [1 .. 5] + + putStrLn "\n10000th to 10100th 500-amost primes:" + mapM_ print $ take 100 $ drop 10000 $ kprimes 500 diff --git a/Task/Almost-prime/Java/almost-prime.java b/Task/Almost-prime/Java/almost-prime.java new file mode 100644 index 0000000000..46460dcedf --- /dev/null +++ b/Task/Almost-prime/Java/almost-prime.java @@ -0,0 +1,28 @@ +public class AlmostPrime +{ + public static void main(String args[]) + { + for (int k = 1; k <= 5; k++) { + System.out.print("k = " + k + ":"); + + for (int i = 2, c = 0; c < 10; i++) + if (kprime(i, k)) { + System.out.print(" " + i); + c++; + } + + System.out.println(""); + } + } + + public static boolean kprime(int n, int k) + { + int f = 0; + for (int p = 2; f < k && p*p <= n; p++) + while (0 == n % p){ + n /= p; + f++; + } + return f + ((n > 1)?1:0) == k; + } +} diff --git a/Task/Almost-prime/REXX/almost-prime.rexx b/Task/Almost-prime/REXX/almost-prime.rexx new file mode 100644 index 0000000000..f3c43280a4 --- /dev/null +++ b/Task/Almost-prime/REXX/almost-prime.rexx @@ -0,0 +1,28 @@ +/*REXX program computes & displays N numbers of the first K k─almost primes.*/ +parse arg N K . /*get optional arguments from the C.L. */ +if N=='' then N=10 /*N not specified? Then use default.*/ +if K=='' then K= 5; w=length(k) /*K " " " " " */ + /*W: is the width of K, used for output*/ + do m=1 for K; $=2**m; fir=$ /*generate & assign 1st k─almost prime.*/ + #=1; if #==N then leave /*#: k─almost primes; Enough are found?*/ + #=2; $=$ 3*(2**(m-1)) /*generate & append 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; $=$ j /*bump K─almost counter; append it to $*/ + end /*j*/ /* [↑] generate N k─almost primes.*/ + say right(m,w)"─almost ("N') primes:' $ /*displays " " " " */ + end /*m*/ /* [↑] display a line for each K-prime*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +#factr: procedure; parse arg x 1 z /*defines X and Z to the argument. */ + do f=0 while z//2==0; z=z%2; end /*÷ by 2s.*/ + do f=f while z//3==0; z=z%3; end /*÷ " 3s.*/ + do f=f while z//5==0; z=z%5; end /*÷ " 5s.*/ +j=5 + do y=0 by 2; j=j+2+y//4 /*insure J isn't divisible by three. */ + parse var j '' -1 _ /*obtain the right─most decimal digit. */ + if _==5 then iterate /*fast check for divisible by five. */ + if j>z then leave /*is number reduced to the smallest # ?*/ + do f=f+1 while z//j==0; z=z%j; end; f=f-1 /*÷ by Js.*/ + end /*y*/ /* [↑] find all the factors in X. */ +return max(f,1) /*if prime (f==0), then return 1. */ diff --git a/Task/Almost-prime/Rust/almost-prime.rust b/Task/Almost-prime/Rust/almost-prime.rust index 4ff84b9ee4..3e4d80a2bb 100644 --- a/Task/Almost-prime/Rust/almost-prime.rust +++ b/Task/Almost-prime/Rust/almost-prime.rust @@ -1,39 +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 +fn is_kprime(n: u32, k: u32) -> bool { + let mut primes = 0; + let mut f = 2; + 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, + k: u32, + n: u32, } 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) - } + type Item = u32; + 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 kprime_generator(k: u32) -> KPrimeGen { + KPrimeGen {k: k, n: 1} } fn main() { - for k in 1us..6 { - println!("{}: {:?}", k, kprime_generator(k).take(10).collect::>()); - } + for k in 1..6 { + println!("{}: {:?}", k, kprime_generator(k).take(10).collect::>()); + } } diff --git a/Task/Almost-prime/VBScript/almost-prime.vb b/Task/Almost-prime/VBScript/almost-prime.vb new file mode 100644 index 0000000000..005f1d5331 --- /dev/null +++ b/Task/Almost-prime/VBScript/almost-prime.vb @@ -0,0 +1,54 @@ +For k = 1 To 5 + count = 0 + increment = 1 + WScript.StdOut.Write "K" & k & ": " + Do Until count = 10 + If PrimeFactors(increment) = k Then + WScript.StdOut.Write increment & " " + count = count + 1 + End If + increment = increment + 1 + Loop + WScript.StdOut.WriteLine +Next + +Function PrimeFactors(n) + PrimeFactors = 0 + arrP = Split(ListPrimes(n)," ") + divnum = n + Do Until divnum = 1 + For i = 0 To UBound(arrP)-1 + If divnum = 1 Then + Exit For + ElseIf divnum Mod arrP(i) = 0 Then + divnum = divnum/arrP(i) + PrimeFactors = PrimeFactors + 1 + End If + Next + Loop +End Function + +Function IsPrime(n) + If n = 2 Then + IsPrime = True + ElseIf n <= 1 Or n Mod 2 = 0 Then + IsPrime = False + Else + IsPrime = True + For i = 3 To Int(Sqr(n)) Step 2 + If n Mod i = 0 Then + IsPrime = False + Exit For + End If + Next + End If +End Function + +Function ListPrimes(n) + ListPrimes = "" + For i = 1 To n + If IsPrime(i) Then + ListPrimes = ListPrimes & i & " " + End If + Next +End Function diff --git a/Task/Amb/Elena/amb.elena b/Task/Amb/Elena/amb.elena index 6c94cd7cb5..e1f0736977 100644 --- a/Task/Amb/Elena/amb.elena +++ b/Task/Amb/Elena/amb.elena @@ -1,125 +1,74 @@ #define system. +#define system'routines. #define extensions. #define extensions'routines. -// --- Joinable -- - #symbol joinable = (:aFormer:aLater) - [ (aFormer @ (aFormer length - 1)) == (aLater @ 0) ]. - -// --- Activatora --- + [ (aFormer@(aFormer length - 1)) == (aLater@0) ]. -#class(role)Activator2 +#symbol dispatcher = { - #method eval : anArray + eval : anArray &func2:aFunction [ - ^ self eval:(anArray@0):(anArray@1). + ^ aFunction eval:(anArray@0):(anArray@1). ] -} -#class(role)Activator3 -{ - #method eval : anArray + eval : anArray &func3:aFunction [ - ^ self eval:(anArray@0):(anArray@1):(anArray@2). + ^ aFunction eval:(anArray@0):(anArray@1):(anArray@2). ] -} -#class(role)Activator4 -{ - #method eval : anArray + eval : anArray &func4:aFunction [ - ^ self eval:(anArray@0):(anArray@1):(anArray@2):(anArray@3). + ^ aFunction eval:(anArray@0):(anArray@1):(anArray@2):(anArray@3). ] -} -#class(role)Activator5 -{ - #method eval : anArray + eval : anArray &func5:aFunction [ - ^ self eval:(anArray@0):(anArray@1):(anArray@2):(anArray@3):(anArray@4). + ^ aFunction 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 + #constructor new &args:Arguments [ - 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). + theCombinator := SequentialEnumerator new &args:Arguments. ] #method seek : aCondition [ theCombinator reset. - control while:[ theCombinator next ] &do: + theCombinator seek &each: v [ - aCondition~theRole eval:(theCombinator get) ? - [ #break nil. ]. + ^ aCondition cast:%eval &to:dispatcher &with:v. ]. ] #method do : aFunction [ #var aResult := theCombinator get. - nil != aResult - ? [ aFunction~theRole eval:aResult. ] + (nil != aResult) + ? [ aFunction cast:%eval &to:dispatcher &with: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. + for &args:Arguments + = AmbValueCollection new &args:Arguments. }. -// --- 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") + for &args:("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". ]. + do: (:a:b:c:d) [ console writeLine:a:" ":b:" ":c:" ":d. ] + | if &InvalidArgumentError: e [ console writeLine:"AMB is angry". ]. ]. diff --git a/Task/Amb/Perl-6/amb-2.pl6 b/Task/Amb/Perl-6/amb-2.pl6 index d5d5695a94..16c2c2dd70 100644 --- a/Task/Amb/Perl-6/amb-2.pl6 +++ b/Task/Amb/Perl-6/amb-2.pl6 @@ -4,15 +4,19 @@ sub amb($var,*@a) { }]"; } +sub joins ($word1, $word2) { + substr($word1,*-1,1) eq substr($word2,0,1) +} + '' ~~ 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-2.pl b/Task/Amb/Perl/amb-2.pl index 1323079790..da5d46cbfb 100644 --- a/Task/Amb/Perl/amb-2.pl +++ b/Task/Amb/Perl/amb-2.pl @@ -1,40 +1,27 @@ +#!/usr/bin/perl + use strict; use warnings; +use feature 'say'; +use re 'eval'; -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; - } - } +sub amb ($@) { + my $var = shift; + join ' || ', map { "(?{ $var = '$_' })" } @_; } -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); +sub joins { + substr(shift,-1,1) eq substr(shift,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"; -}); +my ($a,$b,$c,$d); +'' =~ m/ + (??{ amb '$a', qw[the that a] }) + (??{ amb '$b', qw[frog elephant thing] }) + (??{ amb '$c', qw[walked treaded grows] }) + (??{ amb '$d', qw[slowly quickly] }) + (?(?{ joins($b, $c) })|(*FAIL)) + (?(?{ joins($a, $b) })|(*FAIL)) + (?(?{ joins($c, $d) })|(*FAIL)) + (?{ say "$a $b $c $d" }) +/x; diff --git a/Task/Amb/Perl/amb-3.pl b/Task/Amb/Perl/amb-3.pl new file mode 100644 index 0000000000..1323079790 --- /dev/null +++ b/Task/Amb/Perl/amb-3.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/Ruby/amb.rb b/Task/Amb/Ruby/amb.rb index 8b13f0bf76..dfa5336791 100644 --- a/Task/Amb/Ruby/amb.rb +++ b/Task/Amb/Ruby/amb.rb @@ -1,3 +1,5 @@ +require "continuation" + class Amb class ExhaustedError < RuntimeError; end diff --git a/Task/Amicable-pairs/AWK/amicable-pairs.awk b/Task/Amicable-pairs/AWK/amicable-pairs.awk new file mode 100644 index 0000000000..bf53b0d347 --- /dev/null +++ b/Task/Amicable-pairs/AWK/amicable-pairs.awk @@ -0,0 +1,28 @@ +#!/bin/awk -f +function sumprop(num, i,sum,root) { +if (num < 2) return 0 +sum=1 +root=sqrt(num) +for ( i=2; i < root; i++) { + if (num % i == 0 ) + { + sum = sum + i + num/i + } + } + if (num % root == 0) + { + sum = sum + root + } + return sum + } + +BEGIN{ +limit=20000 +print "Amicable pairs < ",limit +for (n=1; n < limit+1; n++) + { + m=sumprop(n) + if (n == sumprop(m) && n < m) print n,m + } +} +} diff --git a/Task/Amicable-pairs/C/amicable-pairs.c b/Task/Amicable-pairs/C/amicable-pairs.c index ae528a648e..fce6cce9f7 100644 --- a/Task/Amicable-pairs/C/amicable-pairs.c +++ b/Task/Amicable-pairs/C/amicable-pairs.c @@ -5,37 +5,52 @@ 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; + 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 + // only sieve within lower half , the modification starts at 2*p + for (uint p = 2; p+p <= top; p++) { + if (divsum[p] > 1) { + divsum[p] -= p;// subtract number itself from divisor sum ('proper') + 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]; + + //counter where n is not a*p with a = ?*p, useful for most p. + //think of p>31 seldom divisions or p>sqrt(top) than no division is needed + //n = 2*p, so the prime itself is left unchanged => k=p-1 + uint k= p-1; + for (uint n = p+p; n <= top; n += p) { + uint s=1+pows[1]; + k--; + // search the right power only if needed + if ( k==0) { + for (uint i = 2; i < x && !(n%pows[i]); s += pows[i++]); + k = p; } + divsum[n] *= s; + } + } + + //now correct the upper half + for (uint p = (top >> 1)+1; p <= top; p++) { + if (divsum[p] > 1){ + divsum[p] -= p;} + } + + uint cnt = 0; + 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); + cnt++;} + } + printf("\nTop %u count : %u\n",top,cnt); + return 0; } diff --git a/Task/Amicable-pairs/Erlang/amicable-pairs-1.erl b/Task/Amicable-pairs/Erlang/amicable-pairs-1.erl new file mode 100644 index 0000000000..d6cad31724 --- /dev/null +++ b/Task/Amicable-pairs/Erlang/amicable-pairs-1.erl @@ -0,0 +1,35 @@ +-module(properdivs). +-export([amicable/1,divs/1,sumdivs/1]). + +amicable(Limit) -> amicable(Limit,[],3,2). + +amicable(Limit,List,_Current,Acc) when Acc >= Limit -> List; +amicable(Limit,List,Current,Acc) when Current =< Acc/2 -> + amicable(Limit,List,Acc,Acc+1); +amicable(Limit,List,Current,Acc) -> + CS = sumdivs(Current), + AS = sumdivs(Acc), + if + CS == Acc andalso AS == Current andalso Acc =/= Current -> + io:format("A: ~w, B: ~w, ~nL: ~w~w~n", [Current,Acc,divs(Current),divs(Acc)]), + NL = List ++ [{Current,Acc}], + amicable(Limit,NL,Acc+1,Acc+1); + true -> + amicable(Limit,List,Current-1,Acc) end. + +divs(0) -> []; +divs(1) -> []; +divs(N) -> lists:sort(divisors(1,N)). + +divisors(1,N) -> + [1] ++ divisors(2,N,math:sqrt(N)). + +divisors(K,_N,Q) when K > Q -> []; +divisors(K,N,_Q) when N rem K =/= 0 -> + [] ++ divisors(K+1,N,math:sqrt(N)); +divisors(K,N,_Q) when K * K == N -> + [K] ++ divisors(K+1,N,math:sqrt(N)); +divisors(K,N,_Q) -> + [K, N div K] ++ divisors(K+1,N,math:sqrt(N)). + +sumdivs(N) -> lists:sum(divs(N)). diff --git a/Task/Amicable-pairs/Erlang/amicable-pairs-2.erl b/Task/Amicable-pairs/Erlang/amicable-pairs-2.erl new file mode 100644 index 0000000000..076d4dff0a --- /dev/null +++ b/Task/Amicable-pairs/Erlang/amicable-pairs-2.erl @@ -0,0 +1,7 @@ +friendly(Limit) -> + List = [{X,properdivs:sumdivs(X)} || X <- lists:seq(3,Limit)], + Final = [ X || + X <- lists:seq(3,Limit), + X == properdivs:sumdivs(proplists:get_value(X,List)) + andalso X =/= proplists:get_value(X,List)], + io:format("L: ~w~n", [Final]). diff --git a/Task/Amicable-pairs/Erlang/amicable-pairs-3.erl b/Task/Amicable-pairs/Erlang/amicable-pairs-3.erl new file mode 100644 index 0000000000..ed46e6ed74 --- /dev/null +++ b/Task/Amicable-pairs/Erlang/amicable-pairs-3.erl @@ -0,0 +1,19 @@ +friendly(Limit) -> + List = [{X,properdivs:sumdivs(X)} || X <- lists:seq(3,Limit)], + Final = [ X || X <- lists:seq(3,Limit), X == properdivs:sumdivs(proplists:get_value(X,List)) + andalso X =/= proplists:get_value(X,List)], + findfriendlies(Final,[]). + + +findfriendlies(List,Acc) when length(List) =< 0 -> Acc; +findfriendlies(List,Acc) -> + A = lists:nth(1,List), + AS = sumdivs(A), + B = lists:nth(2,List), + BS = sumdivs(B), + if + AS == B andalso BS == A -> + {_,BL} = lists:split(2,List), + findfriendlies(BL,Acc++[{A,B}]); + true -> false + end. diff --git a/Task/Amicable-pairs/Fortran/amicable-pairs.f b/Task/Amicable-pairs/Fortran/amicable-pairs.f new file mode 100644 index 0000000000..b8c7a686fd --- /dev/null +++ b/Task/Amicable-pairs/Fortran/amicable-pairs.f @@ -0,0 +1,66 @@ + MODULE FACTORSTUFF !This protocol evades the need for multiple parameters, or COMMON, or one shapeless main line... +Concocted by R.N.McLean, MMXV. + INTEGER LOTS,ILIMIT !Some bounds. + PARAMETER (ILIMIT = 2147483647) !Computer arithmetic is not with real numbers. + PARAMETER (LOTS = 22000) !Nor is computer storage infinite. + INTEGER KNOWNSUM(LOTS) !Calculate these once as multiple references are expected. + CONTAINS !Assistants. + INTEGER FUNCTION SUMF(N) !Sum of the proper divisors of N. + INTEGER N !The number in question. + INTEGER S,F,F2,INC,BOOST !Assistants. + IF (N.LE.LOTS) THEN !If we're within reach, + SUMF = KNOWNSUM(N) !The result is to hand. + ELSE !Otherwise, some on-the-spot effort ensues. +Could use SUMF in place of S, but some compilers have been confused by such usage. + S = 1 !1 is always a factor of N, but N is deemed not. + F = 1 !Prepare a crude search for factors. + INC = 1 !One by plodding one. + IF (MOD(N,2) .EQ. 1) INC = 2!Ah, but an odd number cannot have an even number as a divisor. + 1 F = F + INC !So half the time we can doubleplod. + F2 = F*F !Up to F2 < N rather than F < SQRT(N) and worries over inexact arithmetic. + IF (F2 .LT. N) THEN !F2 = N handled below. + IF (MOD(N,F) .EQ. 0) THEN !Does F divide N? + BOOST = F + N/F !Yes. The divisor and its counterpart. + IF (S .GT. ILIMIT - BOOST) GO TO 666 !Would their augmentation cause an overflow? + S = S + BOOST !No, so count in the two divisors just discovered. + END IF !So much for a divisor discovered. + GO TO 1 !Try for another. + END IF !So much for the horde. + IF (F2 .EQ. N) THEN !Special case: N may be a perfect square, not necessarily of a prime number. + IF (S .GT. ILIMIT - F) GO TO 666 !It is. And it too might cause overflow. + S = S + F !But if not, count F once only. + END IF !All done. + SUMF = S !This is the result. + END IF !Whichever way obtained, + RETURN !Done. +Cannot calculate the sum, because it exceeds the integer limit. + 666 SUMF = -666 !An expression of dismay that the caller will notice. + END FUNCTION SUMF !Alternatively, find the prime factors, and combine them... + SUBROUTINE PREPARESUMF !Initialise the KNOWNSUM array. +Convert the Sieve of Eratoshenes to have each slot contain the sum of the proper divisors of its slot number. +Changes to instead count the number of factors, or prime factors, etc. would be simple enough. + INTEGER F !A factor for numbers such as 2F, 3F, 4F, 5F, ... + KNOWNSUM(1) = 0 !Proper divisors of N do not include N. + KNOWNSUM(2:LOTS) = 1 !So, although 1 is a proper divisor of all N, 1 is excluded for itself. + DO F = 2,LOTS/2 !Step through all the possible divisors of numbers not exceeding LOTS. + FOR ALL(I = F + F:LOTS:F) KNOWNSUM(I) = KNOWNSUM(I) + F !And augment each corresponding slot. + END DO !Different divisors can hit the same slot. For instance, 6 by 2 and also by 3. + END SUBROUTINE PREPARESUMF !Could alternatively generate all products of prime numbers. + END MODULE FACTORSTUFF !Enough assistants. + PROGRAM AMICABLE !Seek N such that SumF(SumF(N)) = N, for N up to 20,000. + USE FACTORSTUFF !This should help. + INTEGER I,N !Steppers. + INTEGER S1,S2 !Sums of factors. + CALL PREPARESUMF !Values for every N up to the search limit will be called for at least once. +c WRITE (6,66) (I,KNOWNSUM(I), I = 1,48) +c 66 FORMAT (10(I3,":",I5,"|")) + DO N = 2,20000 !Step through the specified search space. + S1 = SUMF(N) !Only even numbers appear in the results, but check every one anyway. + IF (S1 .EQ. N) THEN !Catch a tight loop. + WRITE (6,*) "Perfect!!",N !Self amicable! Would otherwise appear as Amicable! n,n. + ELSE IF (S1 .GT. N) THEN !Look for a pair going upwards only. + S2 = SUMF(S1) !Since otherwise each would appear twice. + IF (S2.EQ.N) WRITE (6,*) "Amicable!",N,S1 !Aha! + END IF !So much for that candidate. + END DO !On to the next. + END !Done. diff --git a/Task/Amicable-pairs/J/amicable-pairs-2.j b/Task/Amicable-pairs/J/amicable-pairs-2.j index c21dc963a9..a48b14a6c8 100644 --- a/Task/Amicable-pairs/J/amicable-pairs-2.j +++ b/Task/Amicable-pairs/J/amicable-pairs-2.j @@ -1,4 +1,4 @@ - 1+0 20000 #:I.,() 1+i.20000 + 1 + 0 20000 #: I. ,() 1 + i.20000 220 284 1184 1210 2620 2924 diff --git a/Task/Amicable-pairs/Julia/amicable-pairs-1.julia b/Task/Amicable-pairs/Julia/amicable-pairs-1.julia new file mode 100644 index 0000000000..30f26de223 --- /dev/null +++ b/Task/Amicable-pairs/Julia/amicable-pairs-1.julia @@ -0,0 +1,17 @@ +function pcontrib(p::Int64, a::Int64) + n = one(p) + pcon = one(p) + for i in 1:a + n *= p + pcon += n + end + return pcon +end + +function divisorsum(n::Int64) + dsum = one(n) + for (p, a) in factor(n) + dsum *= pcontrib(p, a) + end + dsum -= n +end diff --git a/Task/Amicable-pairs/Julia/amicable-pairs-2.julia b/Task/Amicable-pairs/Julia/amicable-pairs-2.julia new file mode 100644 index 0000000000..a988c80acb --- /dev/null +++ b/Task/Amicable-pairs/Julia/amicable-pairs-2.julia @@ -0,0 +1,12 @@ +const L = 2*10^4 +acnt = 0 + +println("Amicable pairs not greater than ", L) + +for i in 2:L + !isprime(i) || continue + j = divisorsum(i) + j < i && divisorsum(j) == i || continue + acnt += 1 + println(@sprintf("%4d", acnt), " => ", j, ", ", i) +end diff --git a/Task/Amicable-pairs/Oberon-2/amicable-pairs.oberon-2 b/Task/Amicable-pairs/Oberon-2/amicable-pairs.oberon-2 new file mode 100644 index 0000000000..38b5b1a9c2 --- /dev/null +++ b/Task/Amicable-pairs/Oberon-2/amicable-pairs.oberon-2 @@ -0,0 +1,38 @@ +MODULE AmicablePairs; +IMPORT + Out; +CONST + max = 20000; + +VAR + i,j: INTEGER; + pd: ARRAY max + 1 OF LONGINT; + +PROCEDURE ProperDivisorsSum(n: LONGINT): LONGINT; +VAR + i,sum: LONGINT; +BEGIN + sum := 0; + IF n > 1 THEN + INC(sum,1);i := 2; + WHILE (i < n) DO + IF (n MOD i) = 0 THEN INC(sum,i) END; + INC(i) + END + END; + RETURN sum +END ProperDivisorsSum; + +BEGIN + FOR i := 0 TO max DO + pd[i] := ProperDivisorsSum(i) + END; + + FOR i := 2 TO max DO + FOR j := i + 1 TO max DO + IF (pd[i] = j) & (pd[j] = i) THEN + Out.Char('[');Out.Int(i,0);Out.Char(',');Out.Int(j,0);Out.Char("]");Out.Ln + END + END + END +END AmicablePairs. diff --git a/Task/Amicable-pairs/Pascal/amicable-pairs-1.pascal b/Task/Amicable-pairs/Pascal/amicable-pairs-1.pascal index a823986e1c..77b321cdf8 100644 --- a/Task/Amicable-pairs/Pascal/amicable-pairs-1.pascal +++ b/Task/Amicable-pairs/Pascal/amicable-pairs-1.pascal @@ -1,232 +1,89 @@ -program AmicablePairs; + Program SumOfFactors; uses crt; {Perpetrated by R.N.McLean, December MCMXCV} +//{$DEFINE ShowOverflow} {$IFDEF FPC} - {$MODE DELPHI} - {$H+} -{$ELSE} - {$APPTYPE CONSOLE} + {$MODE DELPHI}//tested with lots = 524*1000*1000 takes 75 secs generating KnownSum {$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; + var outf: text; + const Limit = 2147483647; + const lots = 20000; {This should be much bigger, but problems apply.} + var KnownSum: array[1..lots] of longint; + Function SumF(N: Longint): Longint; + var f,f2,s,ulp: longint; + Begin + if n <= lots then SumF:=KnownSum[N] {Hurrah!} + else + begin {This is really crude...} + s:=1; {1 is always a factor, but N is not.} + f:=2; + f2:=f*f; + while f2 < N do + begin + if N mod f = 0 then + begin {We have a divisor, and its friend.} + ulp:=f + (N div f); + if s > Limit - ulp then begin SumF:=-666; exit; end; + s:=s + ulp; + end; + f:=f + 1; + f2:=f*f; + end; + if f2 = N then {A perfect square gets its factor in once only.} + if s <= Limit - f then s:=s + f + else begin SumF:=-667; exit; end; + SumF:=s; + end; + End; + var i,j,l,sf,fs: LongInt; + const enuff = 666; {Only so much sociability.} + var trail: array[0..enuff] of longint; + BEGIN + ClrScr; + WriteLn('Chasing Chains of Sums of Factors of Numbers.'); + for i:=1 to lots do KnownSum[i]:=1; {Sigh. KnownSum:=1;} - //sieving - j := 1; - p := 2*j+1; - repeat - if Esieve^[j] = #1 then +{start summing every divisor } + for i:=2 to lots do 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; + j:=i + i; + While j <= lots do {Sigh. For j:=i + i:Lots:i do KnownSum[j]:=KnownSum[j] + i;} + begin + KnownSum[j]:=KnownSum[j] + i; + j:=j + i; + end; 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; + {Enough preparation.} + Assign(outf,'Factors.txt'); ReWrite(Outf); + WriteLn(Outf,'Chasing Chains of Sums of Factors of Numbers.'); -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 + for i:=2 to lots do {Search.} begin - r := IdxS/IDxI; - writeln(i+1:4,IdxI:16,IDxS:16,' ratio ',r:10:7); - IF r < 1 then + l:=0; + sf:=SumF(i); + while (sf > i) and (l < enuff) do begin - writeln(i); - readln; - halt; + l:=l + 1; + trail[l]:=sf; + sf:=SumF(sf); 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; + if l >= enuff then writeln('Rope ran out! ',i); +{$IFDEF ShowOverflow} + if sf < 0 then writeln('Overflow with ',i); +{$ENDIF} + if i = sf then {A loop?} + begin {Yes. Reveal its members.} + trail[0]:=i; {The first.} + if l = 0 then write('Perfect!! ') + else if l = 1 then write('Amicable! ') + else write('Sociable: '); + for j:=0 to l do Write(Trail[j],','); + WriteLn; + if l = 0 then write(outf,'Perfect!! ') + else if l = 1 then write(outf,'Amicable! ') + else write(outf,'Sociable: '); + for j:=0 to l do write(outf,Trail[j],','); + WriteLn(outf); 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. + Close (outf); + END. diff --git a/Task/Amicable-pairs/Pascal/amicable-pairs-2.pascal b/Task/Amicable-pairs/Pascal/amicable-pairs-2.pascal index cf9651d404..a823986e1c 100644 --- a/Task/Amicable-pairs/Pascal/amicable-pairs-2.pascal +++ b/Task/Amicable-pairs/Pascal/amicable-pairs-2.pascal @@ -1,210 +1,232 @@ 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} + {$H+} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} - uses sysutils; const -//MAX = 20000; -{$IFDEF UNIX} MAX = 524*1000*1000;{$ELSE}MAX = 499*1000*1000;{$ENDIF} + MAX = 20000; +//MAX = 20*1000*1000; type tValue = LongWord; tpValue = ^tValue; tPower = array[0..31] of tValue; tIndex = record idxI, - idxS : tValue; + idxS : Uint64; 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; + //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 Init; +procedure Su_append(n,factor:tValue;var su:string); var - i : LongInt; + q,p : tValue; begin - DivSumField[0]:= 0; - For i := 1 to MAX do - DivSumField[i]:= 1; + 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: tValue); -//Only for output, normally a factorication would do +procedure ProperDivs(n: Uint64); +//output of prime factorization var - su,so : string; - i,q : tValue; + su : string; + primNo : tValue; + p: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,']'); + 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 : double; + r_max,r_min,r : double; begin - r := 1.0; + r_max := 1.0; + r_min := 16.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 + with Indices[i] do + begin r := IdxS/IDxI; - IF cnt < 20 then + writeln(i+1:4,IdxI:16,IDxS:16,' ratio ',r:10:7); + IF r < 1 then begin - ProperDivs(IdxI); - ProperDivs(IdxS); + writeln(i); + readln; + halt; 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 + if r_max < r then + r_max := r + else + if r_min > r then + r_min := r; + IF cnt < 20 then begin - With indices[n] do - begin - idxI := i; - idxS := s; - end; - inc(n); + ProperDivs(IdxI); + ProperDivs(IdxS); end; end; - inc(DpaCnt[Ord(s>=i)-Ord(s<=i)+1]); - end; - result := n; + writeln(' min ratio ',r_min:12:10); writeln(' max ratio ',r_max:12:10); end; -Procedure CalcPotfactor(prim:tValue); -//PowerFac[k] = (prim^(k+1)-1)/(prim-1) == Sum (i=1..k) prim^i +procedure SumOFProperDiv(n: tValue;var SumOfProperDivs:tValue); +// calculated by prime factorization var - k: tValue; - Pot, //== prim^k - PFac : Int64; + i,q, primNo, Prime,pot : tValue; + SumOfDivs: tValue; 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; + i := N; + SumOfDivs := 1; + primNo := 0; + Prime := Primes[0]; + q := i DIV Prime; repeat - i := power[result]; - Inc(i); - IF i < p then - BREAK - else + 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 - i := 0; - power[result] := 0; - inc(result); + prime := i; + q := 1; end; - until false; - power[result] := i; + until i = 1; + SumOfProperDivs := SumOfDivs - N; end; -function Sieve(prim: tValue):tValue; -//simple version +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 - actNumber : tValue; + i,s,k,n : tValue; + idx : nativeInt; begin - while prim <= MAX do + n := 0; + idx := 3; + For i := 2 to MAX do begin - InitPW(prim); - //actNumber = actual number = n*prim - //power == n to base prim - actNumber := prim; - while actNumber < MAX do + //must be divisble by 2 or 3 ( n < High(tValue) < 1e14 ) + IF DIV23[idx] = 0 then begin - DivSumField[actNumber] := DivSumField[actNumber] *PowerFac[NextPotCnt(prim)]; - inc(actNumber,prim); + 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; - //next prime - repeat - inc(prim); - until (DivSumField[prim] = 1); + dec(idx); + IF idx < 0 then + idx := high(DIV23); end; - result := prim; + result := n; end; var - T2,T1,T0: TDatetime; + T2,T1: TDatetime; APcnt: tValue; - begin - T0:= time; - Init; - Sieve(2); + InitPrimes; T1:= time; - APCnt := Check; + 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} + {$IFNDEF UNIX} readln;{$ENDIF} end. diff --git a/Task/Amicable-pairs/Pascal/amicable-pairs-3.pascal b/Task/Amicable-pairs/Pascal/amicable-pairs-3.pascal new file mode 100644 index 0000000000..18968035b7 --- /dev/null +++ b/Task/Amicable-pairs/Pascal/amicable-pairs-3.pascal @@ -0,0 +1,241 @@ +program AmicPair; +{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; + +type + tValue = LongWord; + tpValue = ^tValue; + tDivSum = array[0..0] of tValue;// evil, but dynamic arrays are slower + tpDivSum = ^tDivSum; + tPower = array[0..31] of tValue; + tIndex = record + idxI, + idxS : tValue; + end; +var + power, + PowerFac : tPower; + ds : array of tValue; + Indices : array[0..511] of tIndex; + DivSumField : tpDivSum; + MAX : tValue; + +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 + n := 0; + For i := 1 to MAX do + begin + //s = sum of proper divs (I) == sum of divs (I) - I + s := DivSumField^[i]; + IF (s <=MAX) AND (s>i) AND (DivSumField^[s]= i)then + begin + With indices[n] do + begin + idxI := i; + idxS := s; + end; + inc(n); + end; + end; + result := n; +end; + +Procedure CalcPotfactor(prim:tValue); +//PowerFac[k] = (prim^(k+1)-1)/(prim-1) == Sum (i=0..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; +//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; + +procedure Sieve(prim: tValue); +var + actNumber,idx : tValue; +begin + //sieve with "small" primes + while prim*prim <= MAX do + begin + InitPW(prim); + Begin + //actNumber = actual number = n*prim + actNumber := prim; + idx := prim; + while actNumber <= MAX do + begin + dec(idx); + IF idx > 0 then + DivSumField^[actNumber] *= PowerFac[0] + else + Begin + DivSumField^[actNumber] *= PowerFac[NextPotCnt(prim)+1]; + idx := Prim; + end; + inc(actNumber,prim); + end; + end; + //next prime + repeat + inc(prim); + until DivSumField^[prim]= 1;//(DivSumField[prim] = 1); + end; + + //sieve with "big" primes, only one factor is possible + while 2*prim <= MAX do + begin + InitPW(prim); + Begin + actNumber := prim; + idx := PowerFac[0]; + while actNumber <= MAX do + begin + DivSumField^[actNumber] *= idx; + inc(actNumber,prim); + end; + end; + repeat + inc(prim); + until DivSumField^[prim]= 1; + end; + + For idx := 2 to MAX do + dec(DivSumField^[idx],idx); +end; + +var + T2,T1,T0: TDatetime; + APcnt: tValue; + i: NativeInt; +begin + MAX := 20000; + IF ParamCount > 0 then + MAX := StrToInt(ParamStr(1)); + setlength(ds,MAX); + DivSumField := @ds[0]; + T0:= time; + For i := 1 to 1 do + Begin + Init; + Sieve(2); + end; + T1:= time; + + APCnt := Check; + T2:= time; + AmPairOutput(APCnt); + writeln(APCnt,' amicable pairs til ',MAX); + 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)); + setlength(ds,0); + {$IFNDEF UNIX} + readln; + {$ENDIF} +end. diff --git a/Task/Amicable-pairs/PicoLisp/amicable-pairs.l b/Task/Amicable-pairs/PicoLisp/amicable-pairs.l new file mode 100644 index 0000000000..f54cb5f610 --- /dev/null +++ b/Task/Amicable-pairs/PicoLisp/amicable-pairs.l @@ -0,0 +1,36 @@ +(de accud (Var Key) + (if (assoc Key (val Var)) + (con @ (inc (cdr @))) + (push Var (cons Key 1)) ) + Key ) +(de factor-sum (N) + (if (=1 N) + 0 + (let + (R NIL + D 2 + L (1 2 2 . (4 2 4 2 4 6 2 6 .)) + M (sqrt N) + N1 N + S 1 ) + (while (>= M D) + (if (=0 (% N1 D)) + (setq M + (sqrt (setq N1 (/ N1 (accud 'R D)))) ) + (inc 'D (pop 'L)) ) ) + (accud 'R N1) + (for I R + (one D) + (one M) + (for J (cdr I) + (setq M (* M (car I))) + (inc 'D M) ) + (setq S (* S D)) ) + (- S N) ) ) ) +(bench + (for I 20000 + (let X (factor-sum I) + (and + (< I X) + (= I (factor-sum X)) + (println I X) ) ) ) ) diff --git a/Task/Amicable-pairs/Prolog/amicable-pairs-1.pro b/Task/Amicable-pairs/Prolog/amicable-pairs-1.pro new file mode 100644 index 0000000000..3de48170cf --- /dev/null +++ b/Task/Amicable-pairs/Prolog/amicable-pairs-1.pro @@ -0,0 +1,33 @@ +divisor(N, Divisor) :- + UpperBound is round(sqrt(N)), + between(1, UpperBound, D), + 0 is N mod D, + ( + Divisor = D + ; + LargerDivisor is N/D, + LargerDivisor =\= D, + Divisor = LargerDivisor + ). + +proper_divisor(N, D) :- + divisor(N, D), + D =\= N. + +assoc_num_divsSum_in_range(Low, High, Assoc) :- + findall( Num-DivSum, + ( between(Low, High, Num), + aggregate_all( sum(D), + proper_divisor(Num, D), + DivSum )), + Pairs ), + list_to_assoc(Pairs, Assoc). + +get_amicable_pair(Assoc, M-N) :- + gen_assoc(M, Assoc, N), + M < N, + get_assoc(N, Assoc, M). + +amicable_pairs_under_20000(Pairs) :- + assoc_num_divsSum_in_range(1,20000, Assoc), + findall(P, get_amicable_pair(Assoc, P), Pairs). diff --git a/Task/Amicable-pairs/Prolog/amicable-pairs-2.pro b/Task/Amicable-pairs/Prolog/amicable-pairs-2.pro new file mode 100644 index 0000000000..b65a57b88c --- /dev/null +++ b/Task/Amicable-pairs/Prolog/amicable-pairs-2.pro @@ -0,0 +1,2 @@ +?- amicable_pairs_under_20000(R). +R = [220-284, 1184-1210, 2620-2924, 5020-5564, 6232-6368, 10744-10856, 12285-14595, 17296-18416]. diff --git a/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx b/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx index a981b1f3b8..5adbef2791 100644 --- a/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx +++ b/Task/Amicable-pairs/REXX/amicable-pairs-2.rexx @@ -1,28 +1,30 @@ -/*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.*/ +/*REXX program finds and displays all amicable pairs up to a given number. */ +parse arg H .; if H=='' then H=20000 /*get optional arguments (high limit).*/ +w=length(H) ; low=220 /*W: used for columnar output alignment*/ +@.=. /* [↑] LOW is lowest amicable number. */ + do k=low for H-low; _=sigma(k) /*generate sigma sums for a range of #s*/ + if _>=low then @.k=_ /*only keep the pertinent sigma sums. */ + end /*k*/ /* [↑] process a range of integers. */ +#=0 /*number of amicable pairs found so far*/ + do m=low to H; n=@.m /*start the search at the lowest number*/ + if n==. then iterate /*if not pertinent, then ignore the #.*/ + if m==@.n then do /*If equal, might be an amicable number*/ + if m==n then iterate /*skip any perfect numbers. */ + #=#+1 /*bump amicable pair counter.*/ + say right(m,w) ' and ' right(n,w) " are an amicable pair." + m=n /*start M (DO index) from N.*/ + end + end /*m*/ 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*j1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end;end + return r +/*────────────────────────────────────────────────────────────────────────────*/ +sigma: procedure; parse arg x; od=x//2 /*use either EVEN or ODD integers. */ +s=1 /*set initial sigma sum to unity. ___*/ + do j=2+od by 1+od to iSqrt(x) /*divide by all integers up to the √ x */ + if x//j==0 then s=s + j + x%j /*add the two divisors to the sum. */ + end /*j*/ /* [↑] % is REXX integer division. */ +return s /*return the sum of the divisors. */ diff --git a/Task/Amicable-pairs/REXX/amicable-pairs-5.rexx b/Task/Amicable-pairs/REXX/amicable-pairs-5.rexx new file mode 100644 index 0000000000..4632a279a3 --- /dev/null +++ b/Task/Amicable-pairs/REXX/amicable-pairs-5.rexx @@ -0,0 +1,30 @@ +/*REXX program finds and displays all amicable pairs up to a given number. */ +parse arg H .; if H=='' then H=20000 /*get optional arguments (high limit).*/ +w=length(H) ; low=220 /*W: used for columnar output alignment*/ +x=220 34765731 6232 87633 284 12285 10856 36939357 6368 5684679 /*S minimums.*/ +y=220 34765731 6232 69615 220 12285 10744 34765731 6232 5357625 /*D minimums.*/ + do i=0 for 10; $.i=word(x,i+1); L.i=word(y,i+1); end /*minimum amicable #s.*/ +#=0 /*number of amicable pairs found so far*/ +@.= /* [↑] LOW is lowest amicable number. */ + do k=low for H-low /*generate sigma sums for a range of #s*/ + parse var k '' -1 D /*obtain last decimal digit of K. */ + if k<$.D then iterate /*if no need to compute, then skip it. */ + od=k//2 /*OD: set to unity if K is odd.*/ + z=k; r=0; q=1; do while q<=z; q=q*4; end /*R will be iSqrt of Z*/ + do while q>1; q=q%4; _=z-r-q; r=r%2; if _>=0 then do;z=_;r=r+q; end;end + s=1 /*set initial sigma sum to unity. ___*/ + do j=2+od by 1+od to r /*divide by all integers up to the √ K */ + if k//j==0 then s=s+ j + k%j /*add the two divisors to the sum. */ + end /*j*/ /* [↑] % is REXX integer division. */ + if s u32 { + (1..val/2+1).filter(|n| val % n == 0) + .fold(0, |sum, n| sum + n) +} + +fn main() { + let iter = (1..20_000).map(|i| (i, sum_of_divisors(i))) + .filter(|&(i, div_sum)| i > div_sum); + + for (i, sum1) in iter { + if sum_of_divisors(sum1) == i { + println!("{} {}", i, sum1); + } + } +} diff --git a/Task/Anagrams-Deranged-anagrams/Eiffel/anagrams-deranged-anagrams.e b/Task/Anagrams-Deranged-anagrams/Eiffel/anagrams-deranged-anagrams.e new file mode 100644 index 0000000000..2b8645da00 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Eiffel/anagrams-deranged-anagrams.e @@ -0,0 +1,124 @@ +class + ANAGRAMS_DERANGED + +create + make + +feature + + make + -- Longest deranged anagram. + local + deranged_anagrams: LINKED_LIST [STRING] + count: INTEGER + do + read_wordlist + across + words as wo + loop + deranged_anagrams := check_list_for_deranged (wo.item) + if not deranged_anagrams.is_empty and deranged_anagrams [1].count > count then + count := deranged_anagrams [1].count + end + wo.item.wipe_out + wo.item.append (deranged_anagrams) + end + across + words as wo + loop + across + wo.item as w + loop + if w.item.count = count then + io.put_string (w.item + "%T") + io.new_line + end + end + end + end + + original_list: STRING = "unixdict.txt" + +feature {NONE} + + check_list_for_deranged (list: LINKED_LIST [STRING]): LINKED_LIST [STRING] + -- Deranged anagrams in 'list'. + do + create Result.make + across + 1 |..| list.count as i + loop + across + (i.item + 1) |..| list.count as j + loop + if check_for_deranged (list [i.item], list [j.item]) then + Result.extend (list [i.item]) + Result.extend (list [j.item]) + end + end + end + end + + check_for_deranged (a, b: STRING): BOOLEAN + -- Are 'a' and 'b' deranged anagrams? + local + n: INTEGER + do + across + 1 |..| a.count as i + loop + if a [i.item] = b [i.item] then + n := n + 1 + end + end + Result := n = 0 + end + + read_wordlist + -- Hashtable 'words' with alphabetically sorted Strings used as key. + local + l_file: PLAIN_TEXT_FILE + sorted: STRING + empty_list: LINKED_LIST [STRING] + do + create l_file.make_open_read_write (original_list) + l_file.read_stream (l_file.count) + wordlist := l_file.last_string.split ('%N') + l_file.close + create words.make (wordlist.count) + across + wordlist as w + loop + create empty_list.make + sorted := sort_letters (w.item) + words.put (empty_list, sorted) + if attached words.at (sorted) as ana then + ana.extend (w.item) + end + end + end + + wordlist: LIST [STRING] + + sort_letters (word: STRING): STRING + --Alphabetically sorted. + local + letters: SORTED_TWO_WAY_LIST [STRING] + do + create letters.make + create Result.make_empty + across + 1 |..| word.count as i + loop + letters.extend (word.at (i.item).out) + end + across + letters as s + loop + Result.append (s.item) + end + end + + words: HASH_TABLE [LINKED_LIST [STRING], STRING] + +end diff --git a/Task/Anagrams-Deranged-anagrams/J/anagrams-deranged-anagrams.j b/Task/Anagrams-Deranged-anagrams/J/anagrams-deranged-anagrams.j index a10727688c..24336c4507 100644 --- a/Task/Anagrams-Deranged-anagrams/J/anagrams-deranged-anagrams.j +++ b/Task/Anagrams-Deranged-anagrams/J/anagrams-deranged-anagrams.j @@ -1,4 +1,4 @@ - #words=: <;._2 ] 1!:1 <'unixdict.txt' + #words=: 'b' freads 'unixdict.txt' 25104 #anagrams=: (#~ 1 < #@>) () words 1303 diff --git a/Task/Anagrams/Eiffel/anagrams.e b/Task/Anagrams/Eiffel/anagrams.e new file mode 100644 index 0000000000..757700b4b9 --- /dev/null +++ b/Task/Anagrams/Eiffel/anagrams.e @@ -0,0 +1,87 @@ +class + ANAGRAMS + +create + make + +feature + + make + -- Set of Anagrams, containing most words. + local + count: INTEGER + do + read_wordlist + across + words as wo + loop + if wo.item.count > count then + count := wo.item.count + end + end + across + words as wo + loop + if wo.item.count = count then + across + wo.item as list + loop + io.put_string (list.item + "%T") + end + io.new_line + end + end + end + + original_list: STRING = "unixdict.txt" + +feature {NONE} + + read_wordlist + -- Preprocessed wordlist for finding Anagrams. + local + l_file: PLAIN_TEXT_FILE + sorted: STRING + empty_list: LINKED_LIST [STRING] + do + create l_file.make_open_read_write (original_list) + l_file.read_stream (l_file.count) + wordlist := l_file.last_string.split ('%N') + l_file.close + create words.make (wordlist.count) + across + wordlist as w + loop + create empty_list.make + sorted := sort_letters (w.item) + words.put (empty_list, sorted) + if attached words.at (sorted) as ana then + ana.extend (w.item) + end + end + end + + wordlist: LIST [STRING] + + sort_letters (word: STRING): STRING + --Sorted in alphabetical order. + local + letters: SORTED_TWO_WAY_LIST [STRING] + do + create letters.make + create Result.make_empty + across + 1 |..| word.count as i + loop + letters.extend (word.at (i.item).out) + end + across + letters as s + loop + Result.append (s.item) + end + end + + words: HASH_TABLE [LINKED_LIST [STRING], STRING] + +end diff --git a/Task/Anagrams/Elena/anagrams.elena b/Task/Anagrams/Elena/anagrams.elena index 2e7259d070..1e7666349c 100644 --- a/Task/Anagrams/Elena/anagrams.elena +++ b/Task/Anagrams/Elena/anagrams.elena @@ -1,36 +1,34 @@ #define system. -#define system'collections. #define system'routines. +#define system'io. +#define system'collections. #define extensions. -#define extensions'text. +#define extensions'routines. -// --- Normalized --- - -#symbol Normalized = (:aLiteral) -[ - ^ Summing new:(String new) foreach:(arrayControl sort:(literalControl toArray:aLiteral)) literal. -]. - -// --- Program --- +#class(extension) op +{ + #method normalized + = self toArray ascendant summarize:(String new) literal. +} #symbol program = [ #var aDictionary := Dictionary new. - textFileControl forEachLine:"unixdict.txt" &do: aWord + File new &path:"unixdict.txt" run &eachLine: aWord [ - #var aKey := Normalized:aWord. - #var anItem := aDictionary getAt &key:aKey. - nil == anItem ? + #var aKey := aWord normalized. + #var anItem := aDictionary@aKey. + ($nil == anItem) ? [ - anItem := List new. - aDictionary set &key:aKey &value:anItem. + anItem := ArrayList new. + aDictionary@aKey := anItem. ]. anItem += aWord. ]. - listControl sort:aDictionary &with: (:aFormer:aLater) [ aFormer value length > aLater value length ]. - - controlEx foreach:aDictionary &top:20 &do: aPair [ consoleEx writeLine:(aPair value) ]. + aDictionary array_list + sort: (:aFormer:aLater) [ aFormer length > aLater length ] + top:20 run &each: aPair [ console writeLine:aPair ]. ]. diff --git a/Task/Anagrams/Elixir/anagrams-1.elixir b/Task/Anagrams/Elixir/anagrams-1.elixir new file mode 100644 index 0000000000..850868ad4d --- /dev/null +++ b/Task/Anagrams/Elixir/anagrams-1.elixir @@ -0,0 +1,32 @@ +defmodule Anagrams do + def find(file) do + {:ok, body} = File.read(file) + body + |> String.split("\n",trim: true) + |> Enum.map(&(String.split(&1,"",trim: true))) + |> sort(%{}) + |> Enum.group_by(fn {_,v} -> length(v) end) + |> Enum.max_by(&(&1)) + |> print() + end + + def sort([],m), do: m + def sort([word|words],m) do + s = Enum.sort(word) + if Dict.has_key?(m,s) do + m = Map.put(m,s, [word|Dict.get(m,s)]) + else + m = Map.put(m,s,[word]) + end + sort(words,m) + end + + def print({_,y}) do + Enum.map(y, fn {_,e} -> Enum.map(e, &(Enum.join(&1,""))) + |> Enum.sort + |> Enum.join(" ") end) + |> Enum.join("\n") + |> IO.puts + end +end +Anagrams.find("unixdict.txt") diff --git a/Task/Anagrams/Elixir/anagrams-2.elixir b/Task/Anagrams/Elixir/anagrams-2.elixir new file mode 100644 index 0000000000..9a99627ea7 --- /dev/null +++ b/Task/Anagrams/Elixir/anagrams-2.elixir @@ -0,0 +1,17 @@ +File.stream!("unixdict.txt") + |> Stream.map(&(String.strip(&1))) + |> Stream.map(&({&1,&1 + |> String.split("",trim: true) + |> Enum.sort + |> Enum.join})) + |> Enum.to_list + |> Enum.group_by(fn {_,y} -> y end) + |> Dict.values + |> Enum.group_by(&(length(&1))) + |> Enum.max_by(&(&1)) + |> elem(1) + |> Stream.map(fn n -> Stream.map(n, fn {y,_} -> y end) + |> Enum.sort + |> Enum.join(" ") end) + |> Enum.join("\n") + |> IO.puts diff --git a/Task/Anagrams/Julia/anagrams.julia b/Task/Anagrams/Julia/anagrams.julia index 535da9806d..07e236c335 100644 --- a/Task/Anagrams/Julia/anagrams.julia +++ b/Task/Anagrams/Julia/anagrams.julia @@ -6,7 +6,7 @@ function anagram(wordlist) hash = Dict() ; ananum = 0 for word in wordlist sorted = CharString(sort(collect(word.data))) - hash[sorted] = [ get(hash, sorted, {}), word ] + hash[sorted] = [ get(hash, sorted, []), word ] ananum = max(length(hash[sorted]), ananum) end collect(values(filter((x,y)-> length(y) == ananum, hash))) diff --git a/Task/Anagrams/REXX/anagrams-1.rexx b/Task/Anagrams/REXX/anagrams-1.rexx index 807a6c2688..4768141a96 100644 --- a/Task/Anagrams/REXX/anagrams-1.rexx +++ b/Task/Anagrams/REXX/anagrams-1.rexx @@ -1,30 +1,30 @@ -/*REXX program finds words with the largest set of anagrams (same size).*/ -iFID='unixdict.txt' /*input file identifier, # words.*/ -hc=; !.=; #.=0; w=0; words=0; most=0 /*initialize some REXX variables.*/ - /* [↓] read entire file by line.*/ - do recs=0 while lines(iFID)\==0 /*Got data? Then read a record.*/ - x=space(linein(iFID),0) /*pick off a word from the input.*/ - L=length(x); if L<3 then iterate /*onesies and twosies can't win. */ - if \datatype(x,'M') then iterate /*filter out nonanagramable words*/ - words=words+1 /*count of (useable) words. */ - z=sortA(x) /*sort the letters in the word. */ - !.z=!.z x; #.z=#.z+1 /*append it to !.z, bump the ctr.*/ - if #.z>most then do; hc=z; most=#.z; if L>w then w=L; iterate; end - if #.z==most then hc=hc z /*append sorted word─►max anagram*/ - end /*recs*/ /*hc◄─list of high count anagrams.*/ -say '──────────────────────────────' recs 'words in the dictionary file: ' iFID +/*REXX program finds words with the largest set of anagrams (of the same size)*/ +iFID='unixdict.txt' /*the dictionary input File IDentifier.*/ +$=; !.=; #.=0; w=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ + /* [↓] read the entire file (by lines)*/ + do while lines(iFID)\==0 /*Got any data? Then read a record. */ + @=space(linein(iFID),0) /*pick off a word from the input line. */ + L=length(@); if L<3 then iterate /*onesies and twosies words can't win. */ + if \datatype(@,'M') then iterate /*ignore any non─anagramable words. */ + uw=uw+1 /*count of the (useable) words in file.*/ + z=sortA(@) /*sort the letters in the word. */ + !.z=!.z @; #.z=#.z+1 /*append it to !.z; bump the counter. */ + if #.z>most then do; $=z; most=#.z; if L>w then w=L; iterate; end + if #.z==most then $=$ z /*append the sorted word──◄ max anagram*/ + end /*while*/ /*$ ►── list of high count anagrams. */ +say '─────────────────────────' uw 'useable words in the dictionary file: ' iFID say - do m=1 for words(hc); z=subword(hc,m,1) /*high count anagrams*/ - say ' ' left(subword(!.z,1,1),w) ' [anagrams: ' subword(!.z,2)"]" - end /*m*/ /* W is the maximum width word. */ + do m=1 for words($); z=subword($,m,1) /*high count of anagrams.*/ + say ' ' left(subword(!.z,1,1),w) ' [anagrams: ' subword(!.z,2)"]" + end /*m*/ /*W is the maximum width of any word.*/ say -say '───── Found' words(hc) "words (each of which have" #.z-1 'anagrams).' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SORTA subroutine────────────────────*/ -sortA: procedure; arg char +1 xx _. /*get 1st letter of arg, _.=null.*/ -_.char=char /*no need to concatenate 1st char*/ - /*[↓] put letters alphabetically.*/ - do length(xx); parse var xx char +1 xx; _.char=_.char||char; end - /*reassemble word, sorted letters*/ -return _.a||_.b||_.c||_.d||_.e||_.f||_.g||_.h||_.i||_.j||_.k||_.l||_.m||, - _.n||_.o||_.p||_.q||_.r||_.s||_.t||_.u||_.v||_.w||_.x||_.y||_.z +say '───── Found' words($) "words (each of which have" #.z-1 'anagrams).' +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────SORTA subroutine──────────────────────────*/ +sortA: procedure; arg char +1 xx,@. /*get the first letter of arg; @.=null*/ +@.char=char /*no need to concatenate the first char*/ + /*[↓] sort/put letters alphabetically.*/ + do length(xx); parse var xx char +1 xx; @.char=@.char || char; end + /*reassemble word with sorted letters. */ +return @.a||@.b||@.c||@.d||@.e||@.f||@.g||@.h||@.i||@.j||@.k||@.l||@.m||, + @.n||@.o||@.p||@.q||@.r||@.s||@.t||@.u||@.v||@.w||@.x||@.y||@.z diff --git a/Task/Anagrams/REXX/anagrams-2.rexx b/Task/Anagrams/REXX/anagrams-2.rexx index 2aa4ce2b6b..591e7450c8 100644 --- a/Task/Anagrams/REXX/anagrams-2.rexx +++ b/Task/Anagrams/REXX/anagrams-2.rexx @@ -1,28 +1,28 @@ -/*REXX program finds words with the largest set of anagrams (same size).*/ -iFID='unixdict.txt' /*input file identifier, # words.*/ -hc=; !.=; #.=0; w=0; words=0; most=0 /*initialize some REXX variables.*/ - /* [↓] read entire file by line.*/ - do recs=0 while lines(iFID)\==0 /*Got data? Then read a record.*/ - x=space(linein(iFID),0) /*pick off a word from the input.*/ - L=length(x); if L<3 then iterate /*onesies and twosies can't win. */ - if \datatype(x,'M') then iterate /*filter out nonanagramable words*/ - words=words+1 /*count of (useable) words. */ - parse upper var x y +1 u _. /*get uppercase X & nullify "_." */ - xx='?'y; _.xx=y /*get 1st letter (special case).*/ - /*[↓] put letters alphabetically.*/ - do length(u); parse var u y +1 u; xx='?'y; _.xx=_.xx||y; end - /*reassemble word, sorted letters*/ - z=_.?a||_.?b||_.?c||_.?d||_.?e||_.?f||_.?g||_.?h||_.?i||_.?j||_.?k||_.?l||_.?m||, - _.?n||_.?o||_.?p||_.?q||_.?r||_.?s||_.?t||_.?u||_.?v||_.?w||_.?x||_.?y||_.?z - !.z=!.z x; #.z=#.z+1 /*append it to !.z, bump the ctr.*/ - if #.z>most then do; hc=z; most=#.z; if L>w then w=L; iterate; end - if #.z==most then hc=hc z /*append sorted word─►hc anagrams*/ - end /*recs*/ /*hc◄─list of high count anagrams*/ -say '──────────────────────────────' recs 'words in the dictionary file: ' iFID +/*REXX program finds words with the largest set of anagrams (of the same size)*/ +iFID='unixdict.txt' /*the dictionary input File IDentifier.*/ +$=; !.=; #.=0; ww=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ + /* [↓] read the entire file (by lines)*/ + do while lines(iFID)\==0 /*Got any data? Then read a record. */ + @=space(linein(iFID),0) /*pick off a word from the input line. */ + LL=length(@); if LL<3 then iterate /*onesies and twosies (words) can't win*/ + if \datatype(@,'M') then iterate /*ignore any non─anagramable words. */ + uw=uw+1 /*count of the (useable) words in file.*/ + parse upper var @ _ +1 xx @. /*get uppercase @ and nullify @. */ + @._=_ /*get the first letter (special case). */ + /*[↓] sort/put letters alphabetically.*/ + do LL-1; parse var xx _ +1 xx; @._=@._||_; end /*get rest of word.*/ + /*reassemble word with sorted letters. */ + zz=@.a||@.b||@.c||@.d||@.e||@.f||@.g||@.h||@.i||@.j||@.k||@.l||@.m||, + @.n||@.o||@.p||@.q||@.r||@.s||@.t||@.u||@.v||@.w||@.x||@.y||@.z + !.zz=!.zz @; #.zz=#.zz+1 /*append it to !.zz; bump the counter.*/ + if #.zz>most then do; $=zz; most=#.zz; if LL>ww then ww=LL; iterate; end + if #.zz==most then $=$ zz /*append the sorted word──◄ $ anagrams.*/ + end /*while*/ +say '─────────────────────────' uw 'useable words in the dictionary file: ' iFID say - do m=1 for words(hc); z=subword(hc,m,1) /*high count anagrams*/ - say ' ' left(subword(!.z,1,1),w) ' [anagrams: ' subword(!.z,2)"]" - end /*m*/ /* W is the maximum width word. */ + do m=1 for words($); z=subword($,m,1) /*high count of anagrams.*/ + say ' ' left(subword(!.z,1,1),ww) ' [anagrams: ' subword(!.z,2)"]" + end /*m*/ /*WW is the maximum width of any word.*/ say -say '───── Found' words(hc) "words (each of which have" #.z-1 'anagrams).' - /*stick a fork in it, we're done.*/ +say '───── Found' words($) "words (each of which have" #.z-1 'anagrams).' + /*stick a fork in it, we're all done. */ diff --git a/Task/Anagrams/REXX/anagrams-3.rexx b/Task/Anagrams/REXX/anagrams-3.rexx index e7f411ea0f..7ed192ca90 100644 --- a/Task/Anagrams/REXX/anagrams-3.rexx +++ b/Task/Anagrams/REXX/anagrams-3.rexx @@ -1,28 +1,28 @@ -/*REXX program finds words with the largest set of anagrams (same size).*/ -iFID='unixdict.txt' /*input file identifier, # words.*/ -hc=; !.=; #.=0; ww=0; words=0; most=0 /*initialize some REXX variables.*/ - /* [↓] read entire file by line.*/ - do recs=0 while lines(iFID)\==0 /*Got data? Then read a record.*/ - @=space(linein(iFID),0) /*pick off a word from the input.*/ - LL=length(@); if LL<3 then iterate /*onesies and twosies can't win. */ - if \datatype(@,'M') then iterate /*exclude non-anagramable words. */ - words=words+1 /*count of (useable) words. */ - parse upper var @ _ +1 xx _. /*get uppercase @ & nullify "_." */ - _._=_ /*get 1st letter (special case).*/ - /*[↓] put letters alphabetically.*/ - do LL-1; parse var xx _ +1 xx; _._=_._||_; end /*rest of word.*/ - /*reassemble word, sorted letters*/ - zz=_.a||_.b||_.c||_.d||_.e||_.f||_.g||_.h||_.i||_.j||_.k||_.l||_.m||, - _.n||_.o||_.p||_.q||_.r||_.s||_.t||_.u||_.v||_.w||_.x||_.y||_.z - !.zz=!.zz @; #.zz=#.zz+1 /*append it to !.zz, bump the ctr.*/ - if #.zz>most then do; hc=zz; most=#.zz; if LL>ww then ww=LL; iterate; end - if #.zz==most then hc=hc zz /*append sorted word─►hc anagrams*/ - end /*recs*/ /*this loop can't have 1-letter vars.*/ -say '──────────────────────────────' recs 'words in the dictionary file: ' iFID +/*REXX program finds words with the largest set of anagrams (of the same size)*/ +iFID='unixdict.txt' /*the dictionary input File IDentifier.*/ +$=; !.=; #.=0; ww=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ + /* [↓] read the entire file (by lines)*/ + do while lines(iFID)\==0 /*Got any data? Then read a record. */ + @=space(linein(iFID),0) /*pick off a word from the input line. */ + LL=length(@); if LL<3 then iterate /*onesies and twosies (words) can't win*/ + if \datatype(@,'M') then iterate /*ignore any non─anagramable words. */ + uw=uw+1 /*count of the (useable) words in file.*/ + parse upper var @ _ +1 xx '' @. /*get uppercase @ and nullify @. */ + @._=_ /*get the first letter (special case). */ + /*[↓] sort/put letters alphabetically.*/ + do LL-1; parse var xx _ +1 xx; @._=@._||_; end /*get rest of word.*/ + /*reassemble word with sorted letters. */ + zz=@.a||@.b||@.c||@.d||@.e||@.f||@.g||@.h||@.i||@.j||@.k||@.l||@.m||, + @.n||@.o||@.p||@.q||@.r||@.s||@.t||@.u||@.v||@.w||@.x||@.y||@.z + !.zz=!.zz @; #.zz=#.zz+1 /*append it to !.zz; bump the counter.*/ + if #.zz>most then do; $=zz; most=#.zz; if LL>ww then ww=LL; iterate; end + if #.zz==most then $=$ zz /*append the sorted word──► $ anagrams.*/ + end /*while*/ +say '─────────────────────────' uw 'useable words in the dictionary file: ' iFID say - do m=1 for words(hc); z=subword(hc,m,1) /*high count anagrams*/ - say ' ' left(subword(!.z,1,1),ww) ' [anagrams: ' subword(!.z,2)"]" - end /*m*/ /* WW is the maximum width word. */ + do m=1 for words($); z=subword($,m,1) /*high count of anagrams.*/ + say ' ' left(subword(!.z,1,1),ww) ' [anagrams: ' subword(!.z,2)"]" + end /*m*/ /*WW is the maximum width of any word.*/ say -say '───── Found' words(hc) "words (each of which have" #.z-1 'anagrams).' - /*stick a fork in it, we're done.*/ +say '───── Found' words($) "words (each of which have" #.z-1 'anagrams).' + /*stick a fork in it, we're all done. */ diff --git a/Task/Anagrams/REXX/anagrams-5.rexx b/Task/Anagrams/REXX/anagrams-5.rexx index ce7bb7b83e..baa6d99a7b 100644 --- a/Task/Anagrams/REXX/anagrams-5.rexx +++ b/Task/Anagrams/REXX/anagrams-5.rexx @@ -5,7 +5,7 @@ say 'u=' u say 'L=' L _.= do k=1 for L /*keep truckin' for L chars. */ - y = substr(u,k,1) /*get the next character in U. */ + parse var u =(k) y +1 /*get Kth character in U string. */ xx = '?'y /*assign a prefixed char to XX. */ _.xx = _.xx || y /*append it to all the Y chars.*/ end /*do k*/ /*U now has the first char gone.*/ diff --git a/Task/Anagrams/Rust/anagrams.rust b/Task/Anagrams/Rust/anagrams.rust index e323f34020..84faf495fc 100644 --- a/Task/Anagrams/Rust/anagrams.rust +++ b/Task/Anagrams/Rust/anagrams.rust @@ -1,27 +1,27 @@ -use std::collections::hashmap::{HashMap, Occupied, Vacant}; -use std::io::File; -use std::io::BufferedReader; +use std::collections::HashMap; +use std::collections::hash_map::Entry::*; +use std::fs::File; +use std::io::{BufRead,BufReader}; use std::cmp; fn sort_string(string: &str) -> String { - let mut chars = string.chars().collect::>(); - chars.sort(); - String::from_chars(chars.as_slice()) + let mut chars = string.chars().collect::>(); + chars.sort(); + chars.into_iter().collect() } fn main () { - let path = Path::new("unixdict.txt"); - let mut file = BufferedReader::new(File::open(&path)); - let mut map = HashMap::new(); - for line in file.lines().map(|s| s.unwrap()) { - let s = line.as_slice().trim(); - match map.entry(sort_string(s)) { - Vacant(entry) => { entry.set(vec![s.into_string()]); }, - Occupied(mut entry) => { entry.get_mut().push(s.into_string()); } - } - } - let max_length = map.values().fold(0, |s, v| cmp::max(s, v.len())); - for v in map.values().filter(|&v| v.len() == max_length) { - println!("{}", v.connect(" ")) - } + let file = BufReader::new(File::open("unixdict.txt").unwrap()); + let mut map = HashMap::new(); + for line in file.lines() { + let s: String = line.unwrap().trim().into(); + match map.entry(sort_string(&s)) { + Vacant(entry) => { entry.insert(vec![s]); }, + Occupied(mut entry) => { entry.get_mut().push(s); } + } + } + let max_length = map.values().fold(0, |s, v| cmp::max(s, v.len())); + for v in map.values().filter(|&v| v.len() == max_length) { + println!("{}", v.join(" ")) + } } diff --git a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena index d662a8511a..a4ff364c13 100644 --- a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena +++ b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena @@ -1,18 +1,19 @@ #define system. +#define extensions. #symbol fibo = (:n) [ - n < 0 - ? [ #throw InvalidArgumentException new:"Must be non negative". ]. + (n < 0) + ? [ #throw InvalidArgumentException new &message:"Must be non negative". ]. ^ { eval:n [ ^ (n > 1) ? [ ($self:(n - 2)) + ($self:(n - 1)) ] ! [ n ]. ] }:n. ]. #symbol program = [ - control forrange &int:-1 &int:10 &do: (&int:i) + -1 to:10 &doEach: (:i) [ - console << "fib(" << i << ")=". + console writeLiteral:"fib(":i:")=". console writeLine:(fibo:i) | if &InvalidArgumentError: e [ diff --git a/Task/Anonymous-recursion/Elixir/anonymous-recursion.elixir b/Task/Anonymous-recursion/Elixir/anonymous-recursion.elixir new file mode 100644 index 0000000000..afe7a989f3 --- /dev/null +++ b/Task/Anonymous-recursion/Elixir/anonymous-recursion.elixir @@ -0,0 +1,13 @@ +fib = fn f -> ( + fn x -> if x == 0, do: 0, else: (if x == 1, do: 1, else: f.(x - 1) + f.(x - 2)) end + ) +end + +y = fn x -> ( + fn f -> f.(f) + end).( + fn g -> x.(fn z ->(g.(g)).(z) end) + end) +end + +IO.inspect y.(&(fib.(&1))).(40) diff --git a/Task/Anonymous-recursion/J/anonymous-recursion-3.j b/Task/Anonymous-recursion/J/anonymous-recursion-3.j new file mode 100644 index 0000000000..457c090047 --- /dev/null +++ b/Task/Anonymous-recursion/J/anonymous-recursion-3.j @@ -0,0 +1 @@ +basis ` ($: @: g) @. test diff --git a/Task/Anonymous-recursion/J/anonymous-recursion-4.j b/Task/Anonymous-recursion/J/anonymous-recursion-4.j new file mode 100644 index 0000000000..08a96958e5 --- /dev/null +++ b/Task/Anonymous-recursion/J/anonymous-recursion-4.j @@ -0,0 +1 @@ +basis @: (g^:test^:_) diff --git a/Task/Anonymous-recursion/JavaScript/anonymous-recursion-1.js b/Task/Anonymous-recursion/JavaScript/anonymous-recursion-1.js index b0d573f6f9..820a33fdf6 100644 --- a/Task/Anonymous-recursion/JavaScript/anonymous-recursion-1.js +++ b/Task/Anonymous-recursion/JavaScript/anonymous-recursion-1.js @@ -1,11 +1,7 @@ function fibo(n) { - if (n < 0) - throw "Argument cannot be negative"; - else - return (function(n) { - if (n < 2) - return 1; - else - return arguments.callee(n-1) + arguments.callee(n-2); - })(n); + if (n < 0) { throw "Argument cannot be negative"; } + + return (function(n) { + return (n < 2) ? 1 : arguments.callee(n-1) + arguments.callee(n-2); + })(n); } diff --git a/Task/Anonymous-recursion/JavaScript/anonymous-recursion-2.js b/Task/Anonymous-recursion/JavaScript/anonymous-recursion-2.js index 5686788567..96921f5d9e 100644 --- a/Task/Anonymous-recursion/JavaScript/anonymous-recursion-2.js +++ b/Task/Anonymous-recursion/JavaScript/anonymous-recursion-2.js @@ -1,11 +1,7 @@ function fibo(n) { - if (n < 0) - throw "Argument cannot be negative"; - else - return (function fib(n) { - if (n < 2) - return 1; - else - return fib(n-1) + fib(n-2); - })(n); + if (n < 0) { throw "Argument cannot be negative"; } + + return (function fib(n) { + return (n < 2) ? 1 : fib(n-1) + fib(n-2); + })(n); } diff --git a/Task/Anonymous-recursion/REBOL/anonymous-recursion.rebol b/Task/Anonymous-recursion/REBOL/anonymous-recursion.rebol new file mode 100644 index 0000000000..b49b77ec42 --- /dev/null +++ b/Task/Anonymous-recursion/REBOL/anonymous-recursion.rebol @@ -0,0 +1 @@ +fib: func [n /f][ do f: func [m] [ either m < 2 [m][(f m - 1) + f m - 2]] n] 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 index 93a68243a4..25489e8a27 100644 --- 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 @@ -1,119 +1,73 @@ -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; +import static java.lang.Integer.parseInt; +import static java.nio.file.StandardOpenOption.APPEND; +import static java.util.Arrays.asList; +import static java.util.Arrays.stream; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; + import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Stream; 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(); - } + static class Record { + private final String account; + private final String password; + private final int uid; + private final int gid; + private final List gecos; + private final String directory; + private final String shell; + + public Record(String account, String password, int uid, int gid, List gecos, String directory, String shell) { + this.account = requireNonNull(account); + this.password = requireNonNull(password); + this.uid = uid; + this.gid = gid; + this.gecos = requireNonNull(gecos); + this.directory = requireNonNull(directory); + this.shell = requireNonNull(shell); } - - 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(); - } - } + + @Override + public String toString() { + return account + ':' + password + ':' + uid + ':' + gid + ':' + gecos.stream().collect(joining(",")) + ':' + directory + ':' + shell; } - + + public static Record parse(String text) { + String[] tokens = text.split(":"); + return new Record( + tokens[0], + tokens[1], + parseInt(tokens[2]), + parseInt(tokens[3]), + asList(tokens[4].split(",")), + tokens[5], + tokens[6]); + } + } + + public static void main(String[] args) throws IOException { + String[] rawData = { + "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", + "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash", + "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" + }; + + List records = stream(rawData).map(Record::parse).collect(toList()); + + Path tmp = Paths.get("_rosetta", ".passwd"); + Files.createDirectories(tmp.getParent()); + Files.write(tmp, (Iterable)records.stream().limit(2).map(Record::toString)::iterator); + + Files.write(tmp, asList(records.get(2).toString()), APPEND); + + try(Stream lines = Files.lines(tmp)) { + lines.map(Record::parse).forEach(System.out::println); + } + } } diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Mathematica/append-a-record-to-the-end-of-a-text-file.math b/Task/Append-a-record-to-the-end-of-a-text-file/Mathematica/append-a-record-to-the-end-of-a-text-file.math new file mode 100644 index 0000000000..fdee8de838 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Mathematica/append-a-record-to-the-end-of-a-text-file.math @@ -0,0 +1,17 @@ +data = <|"account" -> "xyz", "password" -> "x", "UID" -> 1003, + "GID" -> 1000, "fullname" -> "X Yz", "office" -> "Room 1003", + "extension" -> "(234)555-8913", "homephone" -> "(234)555-0033", + "email" -> "xyz@rosettacode.org", "directory" -> "/home/xyz", + "shell" -> "/bin/bash"|>; +asString[data_] := + StringRiffle[ + ToString /@ + Insert[data /@ {"account", "password", "UID", "GID", "directory", + "shell"}, + StringRiffle[ + data /@ {"fullname", "office", "extension", "homephone", + "email"}, ","], 5], ":"]; +fname = FileNameJoin[{$TemporaryDirectory, "testfile"}]; +str = OpenWrite[fname]; (* Use OpenAppend if file exists *) +Close[str]; +Print["Appended record: " <> asString[data]]; diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Racket/append-a-record-to-the-end-of-a-text-file.rkt b/Task/Append-a-record-to-the-end-of-a-text-file/Racket/append-a-record-to-the-end-of-a-text-file.rkt new file mode 100644 index 0000000000..4a7100c93d --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Racket/append-a-record-to-the-end-of-a-text-file.rkt @@ -0,0 +1,36 @@ +#lang racket + +(define sample1 + '("jsmith" "x" 1001 1000 + ("Joe Smith" "Room 1007" "(234)555-8917" "(234)555-0077" "jsmith@rosettacode.org") + "/home/jsmith" "/bin/bash")) + +(define sample2 + '("jdoe" "x" 1002 1000 + ("Jane Doe" "Room 1004" "(234)555-8914" "(234)555-0044" "jdoe@rosettacode.org") + "/home/jdoe" "/bin/bash")) + +(define sample3 + '("xyz" "x" 1003 1000 + ("X Yz" "Room 1003" "(234)555-8913" "(234)555-0033" "xyz@rosettacode.org") + "/home/xyz" "/bin/bash")) + +(define passwd-file "sexpr-passwd") + +(define (write-passwds mode . ps) + (with-output-to-file passwd-file #:exists mode + (λ() (for ([p (in-list ps)]) (printf "~s\n" p))))) + +(define (lookup username) + (with-input-from-file passwd-file + (λ() (for/first ([p (in-producer read eof)] + #:when (equal? username (car p))) + p)))) + +(printf "Creating file with two sample records.\n") +(write-passwds 'replace sample1 sample2) + +(printf "Appending third sample.\n") +(write-passwds 'append sample3) + +(printf "Looking up xyz in current file:\n=> ~s\n" (lookup "xyz")) 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 index 103ae63e8a..ba82b79b3d 100644 --- 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 @@ -1,14 +1,14 @@ Gecos = Struct.new :fullname, :office, :extension, :homephone, :email class Gecos def to_s - "%s,%s,%s,%s,%s" % [fullname, office, extension, homephone, email] + "%s,%s,%s,%s,%s" % to_a 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(':') + to_a.join(':') end end diff --git a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena index 913597444c..40672f3f6d 100644 --- a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena +++ b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena @@ -1,11 +1,10 @@ #define system. +#define system'routines. #symbol PrintSecondPower = (:n) [ console writeLine:(n * n) ]. #symbol program = [ - #var anArray := (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). - - control foreach:anArray &do:PrintSecondPower. + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) run &each:PrintSecondPower. ]. diff --git a/Task/Apply-a-callback-to-an-array/REXX/apply-a-callback-to-an-array.rexx b/Task/Apply-a-callback-to-an-array/REXX/apply-a-callback-to-an-array.rexx index 3c812a7402..30e005e6af 100644 --- a/Task/Apply-a-callback-to-an-array/REXX/apply-a-callback-to-an-array.rexx +++ b/Task/Apply-a-callback-to-an-array/REXX/apply-a-callback-to-an-array.rexx @@ -1,29 +1,26 @@ -/*REXX program to apply a callback to a stemmed (REXX) array. */ - a.=; b.= - a.0= 0 - a.1= 1 - a.2= 2 - a.3= 3 - a.4= 4 - a.5= 5 - a.6= 6 - a.7= 7 - a.8= 8 - a.9= 9 -a.10=10 - -call listab 'before' -call bangit 'a','b' /*factorialize the A array, store results in B */ -call listab ' after' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────BANGIT subroutine───────────────────*/ -bangit: do i=0 - _=value(arg(1)'.'i); if _=='' then return - call value arg(2)'.'i,fact(_) +/*REXX pgm applies a callback to an array (using factorials for demonstration)*/ +a.=; b.=; a.0 = 0 + a.1 = 1 + a.2 = 2 + a.3 = 3 + a.4 = 4 + a.5 = 5 + a.6 = 6 + a.7 = 7 + a.8 = 8 + a.9 = 9 + a.10 = 10 +call listAB 'before' +call bangit 'a','b' /*factorialize the A array, store results───►B.*/ +call listAB ' after' +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +bangit: do i=0; _=value(arg(1)'.'i); if _=='' then return + call value arg(2)'.'i, fact(_) end /*i*/ -/*──────────────────────────────────FACT subroutine─────────────────────*/ -fact: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! -/*──────────────────────────────────LISTAB subroutine───────────────────*/ -listab: do j=0 while a.j\==''; say arg(1) 'a.'j"="a.j; end /*j*/ -say; do k=0 while b.k\==''; say arg(1) 'b.'k"="b.k; end /*k*/ +/*────────────────────────────────────────────────────────────────────────────*/ +fact: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! +/*────────────────────────────────────────────────────────────────────────────*/ +listAB: do j=0 while a.j\==''; say arg(1) 'a.'j"="a.j; end /*j*/; say + do k=0 while b.k\==''; say arg(1) 'b.'k"="b.k; end /*k*/ return diff --git a/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rust b/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rust new file mode 100644 index 0000000000..8e67a487bf --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Rust/apply-a-callback-to-an-array.rust @@ -0,0 +1,9 @@ +fn echo(n: &i32) { + println!("{}", n); +} + +fn main() { + let a: [i32; 5]; + a = [1, 2, 3, 4, 5]; + let _: Vec<_> = a.into_iter().map(echo).collect(); +} diff --git a/Task/Arbitrary-precision-integers--included-/ALGOL-68/arbitrary-precision-integers--included-.alg b/Task/Arbitrary-precision-integers--included-/ALGOL-68/arbitrary-precision-integers--included-.alg new file mode 100644 index 0000000000..491e082f36 --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/ALGOL-68/arbitrary-precision-integers--included-.alg @@ -0,0 +1,40 @@ +BEGIN +COMMENT + The task specifies + + "Strictly speaking, this should not be solved by fixed-precision + numeric libraries where the precision has to be manually set to a + large value; although if this is the only recourse then it may be + used with a note explaining that the precision must be set manually + to a large enough value." + + Now one should always speak strictly, especially to animals and + small children and, strictly speaking, Algol 68 Genie requires that + a non-default numeric precision for a LONG LONG INT be specified by + "precision=" either in a source code PRAGMAT + or as a command line argument. However, that specification need + not be made manually. This snippet of code outputs an appropriate + PRAGMAT + + printf (($gg(0)xgl$, "PR precision=", + ENTIER (1.0 + log (5) * 4^(3^(2))), "PR")); + + and the technique shown in the "Call a foreign-language function" + task used to write, compile and run an Algol 68 program in which + the precision is programmatically determined. + + The default stack size on this machine is also inadequate but twice + the default is sufficient. The PRAGMAT below can be machine + generated with + + printf (($gg(0)xgl$, "PR stack=", 2 * system stack size, "PR")); + +COMMENT + PR precision=183231 PR + PR stack=16777216 PR + INT digits = ENTIER (1.0 + log (5) * 4^(3^(2))), exponent = 4^(3^2); + LONG LONG INT big = LONG LONG 5^exponent; + printf (($gxg(0)l$, " First 20 digits:", big % LONG LONG 10 ^ (digits - 20))); + printf (($gxg(0)l$, " Last 20 digits:", big MOD LONG LONG 10 ^ 20)); + printf (($gxg(0)l$, "Number of digits:", digits)) +END diff --git a/Task/Arbitrary-precision-integers--included-/Standard-ML/arbitrary-precision-integers--included-.ml b/Task/Arbitrary-precision-integers--included-/Standard-ML/arbitrary-precision-integers--included--1.ml similarity index 100% rename from Task/Arbitrary-precision-integers--included-/Standard-ML/arbitrary-precision-integers--included-.ml rename to Task/Arbitrary-precision-integers--included-/Standard-ML/arbitrary-precision-integers--included--1.ml diff --git a/Task/Arbitrary-precision-integers--included-/Standard-ML/arbitrary-precision-integers--included--2.ml b/Task/Arbitrary-precision-integers--included-/Standard-ML/arbitrary-precision-integers--included--2.ml new file mode 100644 index 0000000000..2e1320c71b --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Standard-ML/arbitrary-precision-integers--included--2.ml @@ -0,0 +1,48 @@ +fun + ntol (0, x) = if len x < 1 then [0] else x + | (n, x) = ntol (n div 10, (n mod 10) :: x) + | n = ntol (n, []) +and + powers_of_10 9 = 1000000000 + | 8 = 100000000 + | 7 = 10000000 + | 6 = 1000000 + | 5 = 100000 + | 4 = 10000 + | 3 = 1000 + | 2 = 100 + | 1 = 10 + | 0 = 1 +and + size (c, 0) = c + | (c, n > 9999999999) = size (c + 10, trunc (n / 10000000000)) + | (c, n) = size (c + 1, trunc (n / 10)) + | n = size ( 0, trunc (n / 10)) +and + makeVisible L = map (fn x = if int x then chr (x + 48) else x) L +and + log10 (n, 0, x) = ston ` implode ` makeVisible ` rev x + | (n, c, x) = + let val n' = n^10; + val size_n' = size n' + in + log10 (n' / powers_of_10 size_n', c - 1, size_n' :: x) + end + | (n, c) = + let + val size_n = size n + in + log10 (n / 10^size_n, c, #"." :: rev (ntol size_n) @ []) + end +; +val fourThreeTwo = 4^3^2; +val fiveFourThreeTwo = 5^fourThreeTwo; + +val digitCount = trunc (log10(5,6) * fourThreeTwo + 0.5); +print "Count = "; println digitCount; + +val end20 = fiveFourThreeTwo mod (10^20); +print "End 20 = "; println end20; + +val top20 = fiveFourThreeTwo div (10^(digitCount - 20)); +print "Top 20 = "; println top20; diff --git a/Task/Arena-storage-pool/C++/arena-storage-pool-2.cpp b/Task/Arena-storage-pool/C++/arena-storage-pool-2.cpp index 078d16ab78..431a5f049b 100644 --- a/Task/Arena-storage-pool/C++/arena-storage-pool-2.cpp +++ b/Task/Arena-storage-pool/C++/arena-storage-pool-2.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include @@ -28,7 +28,7 @@ Pool* pool::cur = 0; Pool::Pool(std::size_type size): memory(static_cast(::operator new(size))), free(memory), - end(memory)) + end(memory + size)) { prev = cur; cur = this; diff --git a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx index 2cf9a24144..067037b1a5 100644 --- a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx +++ b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx @@ -1,23 +1,23 @@ -/*REXX program to show how to support math functions for complex numbers*/ -x = '(5,3i)' /*this little piggy uses "I" (or "i") ···*/ -y = '( .5, 6j)' /*this little piggy uses "J" (or "j") ···*/ +/*REXX pgm demonstrates how to support some math functions for complex numbers*/ +x = '(5,3i)' /*define X ─── can use I i J or j */ +y = "( .5, 6j)" /*define Y " " " " " " " */ -sum = Cadd(x,y) ; say ' addition: ' x " + " y ' = ' sum -dif = Csub(x,y) ; say ' subtraction: ' x " + " y ' = ' dif -prod = Cmul(x,y) ; say 'multiplication: ' x " * " y ' = ' prod -quot = Cdiv(x,y) ; say ' division: ' x " ÷ " y ' = ' quot -inv = Cinv(x) ; say ' inverse: ' x " = " inv -cnjX = Ccnj(x) ; say ' conjugate of: ' x " = " cnjX -negX = Cneg(x) ; say ' negation of: ' x " = " negX -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────one─liners──────────────────────────────────────────────*/ -Ccnj: procedure; arg a ',' b,c ',' d; call Cg; r1=a; r2=-b; return Cr() -Cadd: procedure; arg a ',' b,c ',' d; call Cg; r1=a+c; r2=b+d; return Cr() -Csub: procedure; arg a ',' b,c ',' d; call Cg; r1=a-c; r2=b-d; return Cr() -Cmul: procedure; arg a ',' b,c ',' d; call Cg; r1=a*c-b*d; r2=b*c+a*d; return Cr() -Cdiv: procedure; arg a ',' b,c ',' d; call Cg;_=c*c+d*d;r1=(a*c+b*d)/_;r2=(b*c-a*d)/_;return Cr() -Cdej: return word(translate(arg(1), , '{[(JI)]}') 0, 1) -Cg: a=Cdej(a); b=Cdej(b); c=Cdej(c); d=Cdej(d); return +say ' addition: ' x " + " y ' = ' Cadd(x,y) +say ' subtraction: ' x " - " y ' = ' Csub(x,y) +say 'multiplication: ' x " * " y ' = ' Cmul(x,y) +say ' division: ' x " ÷ " y ' = ' Cdiv(x,y) +say ' inverse: ' x " = " Cinv(x,y) +say ' conjugate of: ' x " = " Conj(x,y) +say ' negation of: ' x " = " Cneg(x,y) +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ +Conj: procedure; arg a ',' b,c ',' d; call C#; return C$( a, -b) +Cadd: procedure; arg a ',' b,c ',' d; call C#; return C$(a+c, b+d) +Csub: procedure; arg a ',' b,c ',' d; call C#; return C$(a-c, b-d) +Cmul: procedure; arg a ',' b,c ',' d; call C#; return C$(ac-bd, bc+ad) +Cdiv: procedure; arg a ',' b,c ',' d; call C#; return C$((ac+bd)/s, (bc-ad)/s) Cinv: return Cdiv(1, arg(1)) Cneg: return Cmul(arg(1), -1) -Cr: _='['r1; if r2\=0 then _=_','r2"j"; return _']' +C_: arg __; return word(translate(__, , '{[(JI)]}') 0, 1) /*get # or 0*/ +C#: a=C_(a);b=C_(b);c=C_(c);d=C_(d);ac=a*c;ad=a*d;bc=b*c;bd=b*d;s=c*c+d*d;return +C$: parse arg r,c;_='['r; if c\=0 then _=_','c"j"; return _']' /*uses j*/ diff --git a/Task/Arithmetic-Complex/Ruby/arithmetic-complex-3.rb b/Task/Arithmetic-Complex/Ruby/arithmetic-complex-3.rb new file mode 100644 index 0000000000..40f958f8e9 --- /dev/null +++ b/Task/Arithmetic-Complex/Ruby/arithmetic-complex-3.rb @@ -0,0 +1,4 @@ +require "cmath" +CMath.sqrt(-9) #=> 0+3.0i +CMath.acos(0+3.0i) #=> (1.5707963267948966-1.8184464592320668i) +#etc diff --git a/Task/Arithmetic-Complex/Rust/arithmetic-complex.rust b/Task/Arithmetic-Complex/Rust/arithmetic-complex.rust index dffc2ea40f..7bcab4df1c 100644 --- a/Task/Arithmetic-Complex/Rust/arithmetic-complex.rust +++ b/Task/Arithmetic-Complex/Rust/arithmetic-complex.rust @@ -1,16 +1,16 @@ extern crate num; - -use num::complex::Cmplx; +use num::complex::Complex; fn main() { - let a = Cmplx::new(-4.0, 5.0); - let b = Cmplx::new(1.0, 1.0); + // two valid forms of definition + let a = Complex {re:-4.0, im: 5.0}; + let b = Complex::new(1.0, 1.0); - println!("a = {}", a); - println!("b = {}", b); - println!("a + b = {}", a + b); - println!("a * b = {}", a * b); - println!("1 / a = {}", Cmplx::new(1.0, 0.0) / a); - println!("-a = {}", -a); - println!("conj a = {}", a.conj()); + println!(" a = {}", a); + println!(" b = {}", b); + println!(" a + b = {}", a + b); + println!(" a * b = {}", a * b); + println!(" 1 / a = {}", a.inv()); + println!(" -a = {}", -a); + println!("conj(a) = {}", a.conj()); } diff --git a/Task/Arithmetic-Integer/00DESCRIPTION b/Task/Arithmetic-Integer/00DESCRIPTION index 8db20921a2..0d641d39be 100644 --- a/Task/Arithmetic-Integer/00DESCRIPTION +++ b/Task/Arithmetic-Integer/00DESCRIPTION @@ -1,5 +1,6 @@ {{basic data operation}} [[Category:Simple]] -Get two integers from the user, and then output the sum, difference, product, integer quotient and remainder of those numbers. Don't include error handling. +Get two integers from the user, and then output the sum, difference, product, integer quotient and remainder of those numbers. +Don't include error handling. For quotient, indicate how it rounds (e.g. towards 0, towards negative infinity, etc.). For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different. diff --git a/Task/Arithmetic-Integer/360-Assembly/arithmetic-integer.360 b/Task/Arithmetic-Integer/360-Assembly/arithmetic-integer.360 new file mode 100644 index 0000000000..f66a361651 --- /dev/null +++ b/Task/Arithmetic-Integer/360-Assembly/arithmetic-integer.360 @@ -0,0 +1,39 @@ +* Arithmetic/Integer 04/09/2015 +ARITHINT CSECT + USING ARITHINT,R12 + LR R12,R15 +ADD L R1,A + A R1,B r1=a+b + XDECO R1,BUF + MVI BUF,C'+' + XPRNT BUF,12 +SUB L R1,A + S R1,B r1=a-b + XDECO R1,BUF + MVI BUF,C'-' + XPRNT BUF,12 +MUL L R1,A + M R0,B r0r1=a*b + XDECO R1,BUF so r1 has the lower part + MVI BUF,C'*' + XPRNT BUF,12 +DIV L R0,A + SRDA R0,32 to shift the sign + D R0,B r1=a/b and r0 has the remainder + XDECO R1,BUF so r1 has quotient + MVI BUF,C'/' + XPRNT BUF,12 +MOD L R0,A + SRDA R0,32 to shift the sign + D R0,B r1=a/b and r0 has the remainder + XDECO R0,BUF so r0 has the remainder + MVI BUF,C'R' + XPRNT BUF,12 +RETURN XR R15,R15 + BR R14 + CNOP 0,4 +A DC F'53' +B DC F'11' +BUF DC CL12' ' + YREGS + END ARITHINT diff --git a/Task/Arithmetic-Integer/Ada/arithmetic-integer.ada b/Task/Arithmetic-Integer/Ada/arithmetic-integer.ada index 9eb691c312..3bf26272a4 100644 --- a/Task/Arithmetic-Integer/Ada/arithmetic-integer.ada +++ b/Task/Arithmetic-Integer/Ada/arithmetic-integer.ada @@ -12,7 +12,9 @@ begin Put_Line("a+b = " & Integer'Image(A + B)); Put_Line("a-b = " & Integer'Image(A - B)); Put_Line("a*b = " & Integer'Image(A * B)); - Put_Line("a/b = " & Integer'Image(A / B) & ", remainder " & Integer'Image(A mod B)); + Put_Line("a/b = " & Integer'Image(A / B)); + Put_Line("a mod b = " & Integer'Image(A mod B)); -- Sign matches B + Put_Line("remainder of a/b = " & Integer'Image(A rem B)); -- Sign matches A Put_Line("a**b = " & Integer'Image(A ** B)); end Integer_Arithmetic; diff --git a/Task/Arithmetic-Integer/DCL/arithmetic-integer.dcl b/Task/Arithmetic-Integer/DCL/arithmetic-integer.dcl new file mode 100644 index 0000000000..d7d328fa11 --- /dev/null +++ b/Task/Arithmetic-Integer/DCL/arithmetic-integer.dcl @@ -0,0 +1,8 @@ +$ inquire a "Enter first number" +$ a = f$integer( a ) +$ inquire b "Enter second number" +$ b = f$integer( b ) +$ write sys$output "a + b = ", a + b +$ write sys$output "a - b = ", a - b +$ write sys$output "a * b = ", a * b +$ write sys$output "a / b = ", a / b ! truncates down diff --git a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena index 42ee66cfa1..2212245642 100644 --- a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena +++ b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena @@ -6,12 +6,12 @@ #symbol program = [ - #var(type:int) a := consoleEx readLine:(Integer new) int. - #var(type:int)b := consoleEx readLine:(Integer new) int. + #var a := console readLine:(Integer new). + #var b := console readLine:(Integer new). - consoleEx writeLine:a:" + ": b:" = ":(a + b). - consoleEx writeLine:a:" - ": b:" = ":(a - b). - consoleEx writeLine:a:" * ": b:" = ":(a * b). - consoleEx writeLine:a:" / ": b:" = ":(a / b). // truncates towards 0 - consoleEx writeLine:a:" %% ":b:" = ":(a mod:b). // matches sign of first operand + console writeLine:a:" + ": b:" = ":(a + b). + console writeLine:a:" - ": b:" = ":(a - b). + console writeLine:a:" * ": b:" = ":(a * b). + console writeLine:a:" / ": b:" = ":(a / b). // truncates towards 0 + console writeLine:a:" % ":b:" = ":(a mod:b). // matches sign of first operand ]. diff --git a/Task/Arithmetic-Integer/Elixir/arithmetic-integer.elixir b/Task/Arithmetic-Integer/Elixir/arithmetic-integer.elixir new file mode 100644 index 0000000000..3b402c361b --- /dev/null +++ b/Task/Arithmetic-Integer/Elixir/arithmetic-integer.elixir @@ -0,0 +1,15 @@ +# Function to remove line breaks and convert string to int +get_int = fn msg -> IO.gets(msg) |> String.strip |> String.to_integer end + +# Get user input +a = get_int.("Enter your first integer: ") +b = get_int.("Enter your second integer: ") + +IO.puts "Elixir Integer Arithmetic:\n" +IO.puts "Sum: #{a + b}" +IO.puts "Difference: #{a - b}" +IO.puts "Product: #{a * b}" +IO.puts "True Division: #{a / b}" # Float +IO.puts "Division: #{div(a,b)}" # Truncated Towards 0 +IO.puts "Remainder: #{rem(a,b)}" # Sign from first digit +IO.puts "Exponent: #{:math.pow(a,b)}" # Float, using Erlang's :math diff --git a/Task/Arithmetic-Integer/Factor/arithmetic-integer.factor b/Task/Arithmetic-Integer/Factor/arithmetic-integer.factor new file mode 100644 index 0000000000..b8f74e2c70 --- /dev/null +++ b/Task/Arithmetic-Integer/Factor/arithmetic-integer.factor @@ -0,0 +1,17 @@ +USING: combinators io kernel math math.functions math.order +math.parser prettyprint ; + +"a=" "b=" [ write readln string>number ] bi@ +{ + [ + "sum: " write . ] + [ - "difference: " write . ] + [ * "product: " write . ] + [ / "quotient: " write . ] + [ /i "integer quotient: " write . ] + [ rem "remainder: " write . ] + [ mod "modulo: " write . ] + [ max "maximum: " write . ] + [ min "minimum: " write . ] + [ gcd "gcd: " write . drop ] + [ lcm "lcm: " write . ] +} 2cleave diff --git a/Task/Arithmetic-Integer/NetRexx/arithmetic-integer.netrexx b/Task/Arithmetic-Integer/NetRexx/arithmetic-integer.netrexx index 62a72145e2..f58547fdb4 100644 --- a/Task/Arithmetic-Integer/NetRexx/arithmetic-integer.netrexx +++ b/Task/Arithmetic-Integer/NetRexx/arithmetic-integer.netrexx @@ -1,6 +1,6 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols binary +options replace format comments java crossref symbols binary say "enter 2 integer values separated by blanks" parse ask a b diff --git a/Task/Arithmetic-Integer/REXX/arithmetic-integer.rexx b/Task/Arithmetic-Integer/REXX/arithmetic-integer.rexx index 8b734b7286..452bcd96a1 100644 --- a/Task/Arithmetic-Integer/REXX/arithmetic-integer.rexx +++ b/Task/Arithmetic-Integer/REXX/arithmetic-integer.rexx @@ -1,26 +1,24 @@ -/*REXX pgm gets 2 integers from the C.L. or via prompt, shows some opers*/ -numeric digits 20 /*all numbers are rounded at ··· */ - /*··· the 20th significant digit.*/ -parse arg x y . /*maybe the integers are on C.L.?*/ -if y=='' then do /*nope, then prompt user for 'em.*/ - say "─────Enter two integer values (separated by blanks):" - parse pull x y . - end - do 2 /*show A with B, then B with A.*/ - say /*show blank line for eyeballing.*/ +/*REXX pgm gets 2 integers from the C,L. or via prompt; shows some operations.*/ +numeric digits 20 /*#s are round at 20th significant dig.*/ +parse arg x y . /*maybe the integers are on the C.L. */ - call show 'addition' , "+", x+y - call show 'subtraction' , "-", x-y - call show 'multiplication', "*", x*y - call show 'int division' , "%", x%y, ' [rounds down]' - call show 'real division' , "/", x/y - call show 'div remainder' , "//", x//y, ' [sign from 1st operand]' - call show 'power' , "**", x**y + do while \datatype(x,'W') | \datatype(y,'W') /*both X and Y must be ints.*/ + say "─────Enter two integer values (separated by blanks):" + parse pull x y . /*accept two items from command line. */ + end /*while ··· */ + /* [↓] perform this DO loop twice. */ + do j=1 for 2 /*show A oper B, then B oper A.*/ + call show 'addition' , "+", x+y + call show 'subtraction' , "-", x-y + call show 'multiplication' , "*", x*y + call show 'int division' , "%", x%y, ' [rounds down]' + call show 'real division' , "/", x/y + call show 'division remainder', "//", x//y, ' [sign from 1st operand]' + call show 'power' , "**", x**y - parse value x y with y x /*swap the two values & do again.*/ - end /*2*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SHOW subroutine─────────────────────*/ -show: parse arg what,oper,value,comment -say right(what,25)' ' x center(oper,4) y ' ───► ' value comment -return + parse value x y with y x /*swap the two values and perform again*/ + if j==1 then say copies('═', 79) /*display a fence after the 1st round. */ + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +show: parse arg c,o,#,?; say right(c,25)' ' x center(o,4) y ' ───► ' # ?; return diff --git a/Task/Arithmetic-Integer/Rust/arithmetic-integer.rust b/Task/Arithmetic-Integer/Rust/arithmetic-integer.rust index e01ae1105c..f572e245f9 100644 --- a/Task/Arithmetic-Integer/Rust/arithmetic-integer.rust +++ b/Task/Arithmetic-Integer/Rust/arithmetic-integer.rust @@ -1,14 +1,13 @@ -use std::io; +use std::env; fn main() { - #![allow(unstable)] // Currently required whilst Rust 1.0 is finalised - let a: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap(); - let b: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap(); + let args: Vec<_> = env::args().collect(); + let a = args[1].parse::().unwrap(); + let b = args[2].parse::().unwrap(); - let sum = a + b; - println!("a + b = {0}" , sum); - println!("a - b = {0}" , a - b); - println!("a * b = {0}" , a * b); - println!("quotient of a / b = {0}" , a / b); // truncates towards 0 - println!("remainder of a / b = {0}" , a % b); // same sign as first operand + println!("sum: {}", a + b); + println!("difference: {}", a - b); + println!("product: {}", a * b); + println!("integer quotient: {}", a / b); // truncates towards zero + println!("remainder: {}", a % b); // same sign as first operand } diff --git a/Task/Arithmetic-Rational/Julia/arithmetic-rational.julia b/Task/Arithmetic-Rational/Julia/arithmetic-rational.julia new file mode 100644 index 0000000000..0806369652 --- /dev/null +++ b/Task/Arithmetic-Rational/Julia/arithmetic-rational.julia @@ -0,0 +1,24 @@ +function isperfect{T<:Integer}(n::T) + !isprime(n) || return false + tal = 1//n + hi = isqrt(n) + if hi^2 == n + tal += 1//hi + hi -= 1 + end + for i in 2:hi + (d, r) = divrem(n, i) + if r == 0 + tal += (1//i + 1//d) + end + end + return tal == 1//1 +end + +lo = 2 +hi = 2^19 +println("Searching for perfect numbers from ", lo, " to ", hi, ".") +for i in 2:2^19 + isperfect(i) || continue + println(@sprintf("%8d", i)) +end diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena new file mode 100644 index 0000000000..37c77114ac --- /dev/null +++ b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena @@ -0,0 +1,330 @@ +#define system. +#define system'routines. +#define extensions. + +#class Token +{ + #field theValue. + #field theLevel. + + #constructor new &level:aLevel + [ + theValue := String new. + theLevel := aLevel + 9. + ] + + #method level = theLevel. + + #method append : aChar + [ + theValue += aChar. + ] + + #method number = theValue value toReal. +} + +#class Node +{ + #field theLeft. + #field theRight. + #field theLevel. + + #constructor new &level:aLevel + [ + theLevel := aLevel. + ] + + #method level = theLevel. + + #method left = theLeft. + + #method right = theRight. + + #method set &left:anObject [ theLeft := anObject. ] + + #method set &right:anObject [ theRight := anObject. ] +} + +#class SummaryNode :: Node +{ + #constructor new &level:aLevel + <= %new &level:(aLevel + 1). + + #method number = theLeft number + theRight number. +} + +#class DifferenceNode :: Node +{ + #constructor new &level:aLevel + <= %new &level:(aLevel + 1). + + #method number = theLeft number - theRight number. +} + +#class ProductNode :: Node +{ + #constructor new &level:aLevel + <= %new &level:(aLevel + 2). + + #method number = theLeft number * theRight number. +} + +#class FractionNode :: Node +{ + #constructor new &level:aLevel + <= %new &level:(aLevel + 2). + + #method number = theLeft number / theRight number. +} + +#class Expression +{ + #field theLevel. + #field theTop. + + #constructor new &level:aLevel + [ + theLevel := aLevel. + ] + + #method top = theTop. + + #method set &top:aNode [ theTop := aNode. ] + + #method right = theTop. + + #method set &right:aNode [ theTop := aNode. ] + + #method level = theLevel. + + #method number => theTop. +} + +// --- States --- + +#symbol operatorState = (:ch) +[ + ch => + #40 ? [ // ( + self new &bracket goto &start. + ] + ! [ + self new &token append:ch goto &token. + ]. +]. + +#symbol tokenState = (:ch) +[ + ch => + #41 ? [ // ) + self close &bracket goto &token. + ] + #42 ? [ // * + self new &product goto &operator. + ] + #43 ? [ // + + self new &summary goto &operator. + ] + #45 ? [ // - + self new &difference goto &operator. + ] + #47 ? // / + [ + self new &fraction goto &operator. + ] + ! [ + self append:ch. + ]. +]. + +#symbol startState = (:ch) +[ + ch => + #40 ? [ // ( + self new &bracket goto &start. + ] + #45 ? [ // - + self new &token append &literal:"0" new &difference goto &operator. + ] + ! [ + self new &token append:ch goto &token. + ]. +]. + +#class Scope +{ + #field theState. + #field theLevel. + #field theParser. + #field theToken. + #field theExpression. + + #constructor new &parser:aParser + [ + theState := startState. + theLevel := 0. + theExpression := Expression new &level:0. + theParser := aParser. + ] + + #method new &token + [ + theToken := theParser append &token &expression:theExpression &level:theLevel. + ] + + #method new &summary + [ + theToken := nil. + + theParser append &summary &expression:theExpression &level:theLevel. + ] + + #method new &difference + [ + theToken := nil. + + theParser append &difference &expression:theExpression &level:theLevel. + ] + + #method new &product + [ + theToken := nil. + + theParser append &product &expression:theExpression &level:theLevel. + ] + + #method new &fraction + [ + theToken := nil. + + theParser append &fraction &expression:theExpression &level:theLevel. + ] + + #method new &bracket + [ + theToken := nil. + + theLevel := theLevel + 10. + + theParser append &subexpression &expression:theExpression &level:theLevel. + ] + + #method close &bracket + [ + (theLevel < 10) + ? [ #throw InvalidArgumentException new &message:"Invalid expression". ]. + + theLevel := theLevel - 10. + ] + + #method append:ch + [ + ((ch >= 48) and:(ch < 58)) + ? [ theToken append:ch. ] + ! [ #throw InvalidArgumentException new &message:"Invalid expression". ]. + ] + + #method append &literal:aLiteral + [ + aLiteral run &each: ch [ self append:ch. ]. + ] + + #method goto &start + [ + theState := startState. + ] + + #method goto &token + [ + theState := tokenState. + ] + + #method goto &operator + [ + theState := operatorState. + ] + + #method number => theExpression. + + #method => theState. +} + +#class Parser +{ + #method append &token &expression:anExpression &level:aLevel + [ + #var aToken := Token new &level:aLevel. + + anExpression set &top:($self append &last:(anExpression top) &new:aToken). + + ^ aToken. + ] + + #method append &summary &expression:anExpression &level:aLevel + [ + anExpression set &top:($self append &last:(anExpression top) &new:(SummaryNode new &level:aLevel)). + ] + + #method append &difference &expression:anExpression &level:aLevel + [ + anExpression set &top:($self append &last:(anExpression top) &new:(DifferenceNode new &level:aLevel)). + ] + + #method append &product &expression:anExpression &level:aLevel + [ + anExpression set &top:($self append &last:(anExpression top) &new:(ProductNode new &level:aLevel)). + ] + + #method append &fraction &expression:anExpression &level:aLevel + [ + anExpression set &top:($self append &last:(anExpression top) &new:(FractionNode new &level:aLevel)). + ] + + #method append &subexpression &expression:anExpression &level:aLevel + [ + anExpression set &top:($self append &last:(anExpression top) &new:(Expression new &level:aLevel)). + ] + + #method append &last:aLastNode &new:aNewNode + [ + ($nil == aLastNode) + ? [ ^ aNewNode. ]. + + (aNewNode level <= aLastNode level) + ? [ aNewNode set &left:aLastNode. ^ aNewNode. ]. + + #var aParent := aLastNode. + #var aCurrent := aLastNode right. + #loop (($nil != aCurrent) and:[ aNewNode level > aCurrent level ]) ? + [ aParent := aCurrent. aCurrent := aCurrent right. ]. + + ($nil == aCurrent) + ? [ aParent set &right:aNewNode. ] + ! [ aNewNode set &left:aCurrent. aParent set &right:aNewNode. ]. + + ^ aLastNode. + ] + + #method run : aText + [ + #var aScope := Scope new &parser:$self. + + aText run &each: ch [ aScope eval:ch. ]. + + ^ aScope number. + ] +} + +#symbol program = +[ + #var aText := String new. + #var aParser := Parser new. + + [ (aText << console readLine) length > 0] doWhile: + [ + console writeLine:"=" :(aParser run:aText) + | if &Error:e [ + console writeLine:"Invalid Expression". + ]. + ]. +]. diff --git a/Task/Arithmetic-evaluation/Haskell/arithmetic-evaluation.hs b/Task/Arithmetic-evaluation/Haskell/arithmetic-evaluation.hs index c8545adb5b..301404b8a4 100644 --- a/Task/Arithmetic-evaluation/Haskell/arithmetic-evaluation.hs +++ b/Task/Arithmetic-evaluation/Haskell/arithmetic-evaluation.hs @@ -1,5 +1,7 @@ -import Text.ParserCombinators.Parsec -import Text.ParserCombinators.Parsec.Expr +import Text.Parsec +import Text.Parsec.Expr +import Text.Parsec.Combinator +import Data.Functor data Exp = Num Int | Add Exp Exp @@ -8,22 +10,20 @@ data Exp = Num Int | Div Exp Exp expr = buildExpressionParser table factor + where table = [[op "*" (Mul) AssocLeft, op "/" (Div) AssocLeft] + ,[op "+" (Add) AssocLeft, op "-" (Sub) AssocLeft]] + op s f assoc = Infix (f <$ string s) assoc + factor = (between `on` char) '(' ')' expr + <|> (Num . read <$> many1 digit) + on f g = \x y -> f (g x) (g y) -table = [[op "*" (Mul) AssocLeft, op "/" (Div) AssocLeft] - ,[op "+" (Add) AssocLeft, op "-" (Sub) AssocLeft]] - where op s f assoc = Infix (do string s; return f) assoc +eval :: Num a => Exp -> a +eval e = case e of + Num x -> fromIntegral x + Add a b -> eval a + eval b + Sub a b -> eval a - eval b + Mul a b -> eval a * eval b + Div a b -> eval a `div` eval b -factor = do char '(' ; x <- expr ; char ')' - return x - <|> do ds <- many1 digit - return $ Num (read ds) - -evaluate (Num x) = fromIntegral x -evaluate (Add a b) = (evaluate a) + (evaluate b) -evaluate (Sub a b) = (evaluate a) - (evaluate b) -evaluate (Mul a b) = (evaluate a) * (evaluate b) -evaluate (Div a b) = (evaluate a) `div` (evaluate b) - -solution exp = case parse expr [] exp of - Right expr -> evaluate expr - Left _ -> error "Did not parse" +solution :: Num a => String -> a +solution = either (const (error "Did not parse")) eval . parse expr "" diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Julia/arithmetic-geometric-mean-calculate-pi.julia b/Task/Arithmetic-geometric-mean-Calculate-Pi/Julia/arithmetic-geometric-mean-calculate-pi.julia new file mode 100644 index 0000000000..e346905f89 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Julia/arithmetic-geometric-mean-calculate-pi.julia @@ -0,0 +1,34 @@ +function agm_step{T<:FloatingPoint}(x::T, y::T) + (0.5*(x + y), sqrt(x*y)) +end + +function approx_pi_step{T<:FloatingPoint,U<:Integer}(x::T, y::T, z::T, n::U) + (a, g) = agm_step(x, y) + k = n + 1 + s = z + 2^(k+1)*(a^2 - g^2) + return (a, g, s, k) +end + +function approx_pi{T<:FloatingPoint}(a::T, g::T, s::T) + 4a^2/(1 - s) +end + +prec = 512 +set_bigfloat_precision(prec) +println("Approximating pi using ", prec, "-bit floats.") +println(" k Error Result") +a = big(1.0) +g = a/sqrt(big(2.0)) +s = big(0.0) +k = 0 +oldagpi = big(0.0) +for i in 1:100 + (a, g, s, k) = approx_pi_step(a, g, s, k) + agpi = approx_pi(a, g, s) + 2eps(agpi) < abs(agpi-oldagpi) || break + oldagpi = agpi + err = pi - agpi + print(@sprintf(" %2d ", i)) + print(@sprintf(" %9.1e", err)) + println(@sprintf(" %.60e", agpi)) +end 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 index 055f17fbd4..d57f67151c 100644 --- 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 @@ -1,21 +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. */ +/*REXX program calculates the value of pi using the AGM algorithm. */ +parse arg d .; if d=='' then d=500 /*D not specified? Then use default. */ +numeric digits d+5 /*set the numeric decimal 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 */ + do j=1 until a==old; old=a /*keep calculating until no more 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 the 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) +pi=a**2/z /*display the computed value of pi. */ +numeric digits d /*set the numeric decimal digits to D.*/ +say pi/1 /*display the computed value of pi. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ 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 index f01480f22b..1fd1dc97ab 100644 --- 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 @@ -1,24 +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. */ +/*REXX program calculates value of pi using the AGM algorithm (running digits)*/ +parse arg d .; if d=='' then d=500 /*D not specified? Then use default. */ +numeric digits d+5 /*set the numeric decimal 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) + do j=1 until a==old; old=a /*keep calculating until no more 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 the final calculation. */ + many=compare(a,old) /*how many accurate digits computed? */ + if many==0 then many=d /*adjust for the very last time. */ + say right('iteration' j,20) right(many,9) "digits" /*show digits.*/ + end /*j*/ /* [↑] stop if A equals OLD. */ +say /*display a blank line for a separator.*/ +pi=a**2/z /*display the computed value of pi. */ +numeric digits d /*set the numeric decimal digits to D.*/ +say pi/1 /*display the computed value of pi. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Arithmetic-geometric-mean/360-Assembly/arithmetic-geometric-mean.360 b/Task/Arithmetic-geometric-mean/360-Assembly/arithmetic-geometric-mean.360 new file mode 100644 index 0000000000..a7ca7d1b68 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/360-Assembly/arithmetic-geometric-mean.360 @@ -0,0 +1,91 @@ +AGM CSECT + USING AGM,R13 +SAVEAREA B STM-SAVEAREA(R15) + DC 17F'0' + DC CL8'AGM' +STM STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 + ZAP A,K a=1 + ZAP PWL8,K + MP PWL8,K + DP PWL8,=P'2' + ZAP PWL8,PWL8(7) + BAL R14,SQRT + ZAP G,PWL8 g=sqrt(1/2) +WHILE1 EQU * while a!=g + ZAP PWL8,A + SP PWL8,G + CP PWL8,=P'0' (a-g)!=0 + BE EWHILE1 + ZAP PWL8,A + AP PWL8,G + DP PWL8,=P'2' + ZAP AN,PWL8(7) an=(a+g)/2 + ZAP PWL8,A + MP PWL8,G + BAL R14,SQRT + ZAP G,PWL8 g=sqrt(a*g) + ZAP A,AN a=an + B WHILE1 +EWHILE1 EQU * + ZAP PWL8,A + UNPK ZWL16,PWL8 + MVC CWL16,ZWL16 + OI CWL16+15,X'F0' + MVI CWL16,C'+' + CP PWL8,=P'0' + BNM *+8 + MVI CWL16,C'-' + MVC CWL80+0(15),CWL16 + MVC CWL80+9(1),=C'.' /k (15-6=9) + XPRNT CWL80,80 display a + L R13,4(0,R13) + LM R14,R12,12(R13) + XR R15,R15 + BR R14 + DS 0F +K DC PL8'1000000' 10^6 +A DS PL8 +G DS PL8 +AN DS PL8 +* ****** SQRT ******************* +SQRT CNOP 0,4 function sqrt(x) + ZAP X,PWL8 + ZAP X0,=P'0' x0=0 + ZAP X1,=P'1' x1=1 +WHILE2 EQU * while x0!=x1 + ZAP PWL8,X0 + SP PWL8,X1 + CP PWL8,=P'0' (x0-x1)!=0 + BE EWHILE2 + ZAP X0,X1 x0=x1 + ZAP PWL16,X + DP PWL16,X1 + ZAP XW,PWL16(8) xw=x/x1 + ZAP PWL8,X1 + AP PWL8,XW + DP PWL8,=P'2' + ZAP PWL8,PWL8(7) + ZAP X2,PWL8 x2=(x1+xw)/2 + ZAP X1,X2 x1=x2 + B WHILE2 +EWHILE2 EQU * + ZAP PWL8,X1 return x1 + BR R14 + DS 0F +X DS PL8 +X0 DS PL8 +X1 DS PL8 +X2 DS PL8 +XW DS PL8 +* end SQRT +PWL8 DC PL8'0' +PWL16 DC PL16'0' +CWL80 DC CL80' ' +CWL16 DS CL16 +ZWL16 DS ZL16 + LTORG + YREGS + END AGM diff --git a/Task/Arithmetic-geometric-mean/ALGOL-68/arithmetic-geometric-mean.alg b/Task/Arithmetic-geometric-mean/ALGOL-68/arithmetic-geometric-mean.alg new file mode 100644 index 0000000000..f52f1d546f --- /dev/null +++ b/Task/Arithmetic-geometric-mean/ALGOL-68/arithmetic-geometric-mean.alg @@ -0,0 +1,23 @@ +BEGIN + PROC agm = (LONG REAL x, y) LONG REAL : + BEGIN + IF x < LONG 0.0 OR y < LONG 0.0 THEN -LONG 1.0 + ELIF x + y = LONG 0.0 THEN LONG 0.0 CO Edge cases CO + ELSE + LONG REAL a := x, g := y; + LONG REAL epsilon := a + g; + LONG REAL next a := (a + g) / LONG 2.0, next g := long sqrt (a * g); + LONG REAL next epsilon := ABS (a - g); + WHILE next epsilon < epsilon + DO + print ((epsilon, " ", next epsilon, newline)); + epsilon := next epsilon; + a := next a; g := next g; + next a := (a + g) / LONG 2.0; next g := long sqrt (a * g); + next epsilon := ABS (a - g) + OD; + a + FI + END; + printf (($l(-35,33)l$, agm (LONG 1.0, LONG 1.0 / long sqrt (LONG 2.0)))) +END diff --git a/Task/Arithmetic-geometric-mean/Elixir/arithmetic-geometric-mean.elixir b/Task/Arithmetic-geometric-mean/Elixir/arithmetic-geometric-mean.elixir new file mode 100644 index 0000000000..1a5b456720 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Elixir/arithmetic-geometric-mean.elixir @@ -0,0 +1,8 @@ +defmodule ArithhGeom do + def mean(a,g,tol) when abs(a-g) <= tol, do: a + def mean(a,g,tol) when abs(a-g) > tol do + mean((a+g)/2,:math.pow(a*g, 0.5),tol) + end +end + +IO.puts ArithhGeom.mean(1,1/:math.sqrt(2),0.0000000001) diff --git a/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-4.j b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-4.j new file mode 100644 index 0000000000..9ea888a54c --- /dev/null +++ b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-4.j @@ -0,0 +1,30 @@ +DP=:101 + +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 +) + +ln=: DP&$: : (4 : 0) " 0 + assert. 0:) (x:!.0 y)%2x^m + if. x<-:#":t do. t=. (1+x) round t end. + ln2=. 2*+/1r3 (^%]) 1+2*i.>.0.5*(%3)^.0.5*0.1^x+>.10^.1>.m + lnr=. 2*+/t (^%]) 1+2*i.>.0.5*(|t)^.0.5*0.1^x + lnr + m * ln2 +) + +exp=: DP&$: : (4 : 0) " 0 + m=. <.0.5+y%^.2 + xm=. x+>.m*10^.2 + d=. (x:!.0 y)-m*xm ln 2 + if. xm<-:#":d do. d=. xm round d end. + e=. 0.1^xm + n=. e (>i.1:) a (^%!@]) i.>.a^.e [ a=. |y-m*^.2 + (2x^m) * 1++/*/\d%1+i.n +) diff --git a/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-5.j b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-5.j new file mode 100644 index 0000000000..00a705847b --- /dev/null +++ b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-5.j @@ -0,0 +1,7 @@ +fmt=:[: ;:inv DP&$: : (4 :0)&.> + x{.deb (x*2j1)":y +) + +root=: ln@] exp@% [ + +epsilon=: 1r9^DP diff --git a/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-6.j b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-6.j new file mode 100644 index 0000000000..d109b7595c --- /dev/null +++ b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-6.j @@ -0,0 +1,8 @@ + fmt sqrt 2 +1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641572 + fmt *~sqrt 2 +2.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 + fmt epsilon +0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000418 + fmt 2 root 2 +1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641572 diff --git a/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-7.j b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-7.j new file mode 100644 index 0000000000..5f604601ef --- /dev/null +++ b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-7.j @@ -0,0 +1,2 @@ +geomean=: */ root~ # +geomean2=: [: sqrt */ diff --git a/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-8.j b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-8.j new file mode 100644 index 0000000000..08851742af --- /dev/null +++ b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-8.j @@ -0,0 +1,4 @@ + fmt geomean 3 5 +3.872983346207416885179265399782399610832921705291590826587573766113483091936979033519287376858673517 + fmt geomean2 3 5 +3.872983346207416885179265399782399610832921705291590826587573766113483091936979033519287376858673517 diff --git a/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-9.j b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-9.j new file mode 100644 index 0000000000..620d1cb422 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/J/arithmetic-geometric-mean-9.j @@ -0,0 +1,9 @@ + fmt (mean, geomean2)^:(epsilon <&| -/)^:a: 1,%sqrt 2 +1.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 0.707106781186547524400844362104849039284835937688474036588339868995366239231053519425193767163820786 +0.853553390593273762200422181052424519642417968844237018294169934497683119615526759712596883581910393 0.840896415253714543031125476233214895040034262356784510813226085974924754953902239814324004199292536 +0.847224902923494152615773828642819707341226115600510764553698010236303937284714499763460443890601464 0.847201266746891460403631453693352397963981013612000500823295747923488191871327668107581434542353536 +0.847213084835192806509702641168086052652603564606255632688496879079896064578021083935520939216477500 0.847213084752765366704298051779902070392110656059452583317776227659438896688518556753569298762449381 +0.847213084793979086607000346473994061522357110332854108003136553369667480633269820344545118989463440 0.847213084793979086605997900490389211440534858586261300461413929971399281619068666682569108141224710 +0.847213084793979086606499123482191636481445984459557704232275241670533381126169243513557113565344075 0.847213084793979086606499123482191636481445836194326665888883503648934628542100275932846717790147361 +0.847213084793979086606499123482191636481445910326942185060579372659734004834134759723201915677745718 0.847213084793979086606499123482191636481445910326942185060579372659734004834134759723198672311476741 +0.847213084793979086606499123482191636481445910326942185060579372659734004834134759723200293994611229 0.847213084793979086606499123482191636481445910326942185060579372659734004834134759723200293994611229 diff --git a/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia b/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia new file mode 100644 index 0000000000..c7b230d474 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia @@ -0,0 +1,29 @@ +function agm{T<:FloatingPoint,U<:Integer}(x::T, y::T, e::U=5) + 0 < y && 0 < y && 0 < e || throw(DomainError()) + err = e*eps(x) + (g, a) = extrema([x, y]) + while err < (a - g) + ap = a + a = 0.5*(a + g) + g = sqrt(ap*g) + end + return a +end + +x = 1.0 +y = 1.0/sqrt(2.0) + +println("Using literal-precision float numbers:") +println(" agm(", x, ",", y, ") = ", agm(x, y)) + +println() +println("Using half-precision float numbers:") +x = float16(x) +y = float16(y) +println(" agm(", x, ",", y, ") = ", agm(x, y)) + +println() +println("Using ", get_bigfloat_precision(), "-bit float numbers:") +x = BigFloat(1.0) +y = x/sqrt(BigFloat(2.0)) +println(" agm(", x, ",", y, ") = \n ", agm(x, y)) diff --git a/Task/Arithmetic-geometric-mean/PowerShell/arithmetic-geometric-mean.psh b/Task/Arithmetic-geometric-mean/PowerShell/arithmetic-geometric-mean.psh new file mode 100644 index 0000000000..b7bbe830ca --- /dev/null +++ b/Task/Arithmetic-geometric-mean/PowerShell/arithmetic-geometric-mean.psh @@ -0,0 +1,14 @@ +function agm ([Double]$a, [Double]$g) { + [Double]$eps = 1E-15 + [Double]$a1 = [Double]$g1 = 0 + while([Math]::Abs($a - $g) -gt $eps) { + $a1, $g1 = $a, $g + $a = ($a1 + $g1)/2 + $g = [Math]::Sqrt($a1*$g1) + } + [pscustomobject]@{ + a = "$a" + g = "$g" + } +} +agm 1 (1/[Math]::Sqrt(2)) diff --git a/Task/Arithmetic-geometric-mean/REXX/arithmetic-geometric-mean.rexx b/Task/Arithmetic-geometric-mean/REXX/arithmetic-geometric-mean.rexx index 67ae0c5893..360ef88915 100644 --- a/Task/Arithmetic-geometric-mean/REXX/arithmetic-geometric-mean.rexx +++ b/Task/Arithmetic-geometric-mean/REXX/arithmetic-geometric-mean.rexx @@ -1,29 +1,30 @@ -/*REXX program calculates AGM (arithmetric-geometric mean) of 2 numbers.*/ -parse arg a b digs . /*obtain numbers from the command line.*/ -if digs=='' then digs=100 /*no DIGS specified? Then use default.*/ -numeric digits digs /*Now, REXX will use lots of digits. */ -if a=='' then a=1 /*no A specified? Then use default. */ -if b=='' then b=1/sqrt(2) /*no B specified? " " " */ -say '1st # =' a -say '2nd # =' b -say ' AGM =' agm(a,b)/1 /*divide by 1; goes from 105──►100 digs*/ -say ' AGM =' agm(a,b)/1 /*dividing by 1 normalizes the REXX num*/ -exit /*stick a fork in it, we're done.*/ -/*────────────────────────────AGM subroutine────────────────────────────*/ -agm: procedure: parse arg x,y; if x=y then return x /*equality case.*/ -if y=0 then return 0; if x=0 then return .5*y /*two "0" cases.*/ -numeric digits digits()+5 /*add 5 more digs to ensure convergence*/ -!='1e-' || (digits()-1); _x=x+1 +/*REXX program calculates the AGM (arithmetic─geometric mean) of two numbers.*/ +parse arg a b digs . /*obtain optional numbers from the C.L.*/ +if digs=='' | digs==',' then digs=100 /*No DIGS specified? Then use default.*/ +numeric digits digs /*REXX will use lots of decimal digits.*/ +if a=='' | a==',' then a=1 /*No A specified? Then use default.*/ +if b=='' | b==',' then b=1/sqrt(2) /*No B specified? " " " */ +say '1st # =' a /*display the A value. */ +say '2nd # =' b /* " " B " */ +say ' AGM =' agm(a, b) /* " " AGM " */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +agm: procedure: parse arg x,y; if x=y then return x /*equality case?*/ + if y=0 then return 0 /*is Y zero? */ + if x=0 then return y/2 /* " X " */ + d=digits(); numeric digits d+5 /*add 5 more digs to ensure convergence*/ + tiny='1e-' || (digits()-1); /*construct a pretty tiny REXX number. */ + ox=x+1 + do while ox\=x & abs(ox)>tiny; ox=x; oy=y + x=(ox+oy)/2; y=sqrt(ox*oy) + end /*while ··· */ - do while _x\=x & abs(_x)>!; _x=x; _y=y; x=(_x+_y)*.5 - y=sqrt(_x*_y) - end /*while*/ -return x -/*────────────────────────────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 scientific; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 + numeric digits d /*restore numeric digits to original.*/ + return x/1 /*normalize X to the new digits. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Arithmetic-geometric-mean/Rust/arithmetic-geometric-mean.rust b/Task/Arithmetic-geometric-mean/Rust/arithmetic-geometric-mean.rust index 919af0b3e6..f2ef20f883 100644 --- a/Task/Arithmetic-geometric-mean/Rust/arithmetic-geometric-mean.rust +++ b/Task/Arithmetic-geometric-mean/Rust/arithmetic-geometric-mean.rust @@ -1,16 +1,11 @@ -// http://rosettacode.org/wiki/Arithmetric-geometric_mean // Accepts two command line arguments // cargo run --name agm arg1 arg2 -use std::num; - -#[cfg(not(test))] fn main () { - let args = std::os::args(); - let args = args.as_slice(); + let mut args = std::env::args(); - let x = from_str::(args[1].as_slice()).unwrap() ; - let y = from_str::(args[2].as_slice()).unwrap() ; + let x = args.nth(1).expect("First argument not specified.").parse::().unwrap(); + let y = args.next().expect("Second argument not specified.").parse::().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); @@ -26,12 +21,11 @@ fn agm (x: f32, y: f32) -> f32 { if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { - a1 = (a + g) / 2f32; + a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; - if num::abs( a - g) < e { return a; } + if (a - g).abs() < e { return a; } } } - } diff --git a/Task/Arithmetic-geometric-mean/TI-83-BASIC/arithmetic-geometric-mean.ti-83 b/Task/Arithmetic-geometric-mean/TI-83-BASIC/arithmetic-geometric-mean.ti-83 new file mode 100644 index 0000000000..b4e191be71 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/TI-83-BASIC/arithmetic-geometric-mean.ti-83 @@ -0,0 +1,6 @@ +1→A:1/sqrt(2)→G +While abs(A-G)>e-15 +(A+G)/2→B +sqrt(AG)→G:B→A +End +A diff --git a/Task/Arithmetic-geometric-mean/VBScript/arithmetic-geometric-mean.vb b/Task/Arithmetic-geometric-mean/VBScript/arithmetic-geometric-mean.vb new file mode 100644 index 0000000000..23712fe71f --- /dev/null +++ b/Task/Arithmetic-geometric-mean/VBScript/arithmetic-geometric-mean.vb @@ -0,0 +1,10 @@ +Function agm(a,g) + Do Until a = tmp_a + tmp_a = a + a = (a + g)/2 + g = Sqr(tmp_a * g) + Loop + agm = a +End Function + +WScript.Echo agm(1,1/Sqr(2)) diff --git a/Task/Array-concatenation/00DESCRIPTION b/Task/Array-concatenation/00DESCRIPTION index 7294dcbf0a..c5fb502a19 100644 --- a/Task/Array-concatenation/00DESCRIPTION +++ b/Task/Array-concatenation/00DESCRIPTION @@ -1 +1,2 @@ -Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it. +Show how to concatenate two arrays in your language. +If this is as simple as array1 + array2, so be it. diff --git a/Task/Array-concatenation/00META.yaml b/Task/Array-concatenation/00META.yaml index 32d20151af..ffee6c0d57 100644 --- a/Task/Array-concatenation/00META.yaml +++ b/Task/Array-concatenation/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Data Structures diff --git a/Task/Array-concatenation/Elena/array-concatenation.elena b/Task/Array-concatenation/Elena/array-concatenation.elena index a013070804..81a9217c2e 100644 --- a/Task/Array-concatenation/Elena/array-concatenation.elena +++ b/Task/Array-concatenation/Elena/array-concatenation.elena @@ -1,3 +1,4 @@ +#define system. #define extensions. #symbol program = @@ -5,5 +6,5 @@ #var a := (1,2,3). #var b := (4,5). - consoleEx writeLine:"(":a:") + (":b:") = (":(a + b):")". + console writeLine:"(":a:") + (":b:") = (":(a + b):")". ]. diff --git a/Task/Array-concatenation/Elixir/array-concatenation.elixir b/Task/Array-concatenation/Elixir/array-concatenation.elixir new file mode 100644 index 0000000000..7748f061f3 --- /dev/null +++ b/Task/Array-concatenation/Elixir/array-concatenation.elixir @@ -0,0 +1,6 @@ +iex(1)> [1, 2, 3] ++ [4, 5, 6] +[1, 2, 3, 4, 5, 6] +iex(2)> Enum.concat([[1, [2], 3], [4], [5, 6]]) +[1, [2], 3, 4, 5, 6] +iex(3)> Enum.concat([1..3, [4,5,6], 7..9]) +[1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Array-concatenation/JavaScript/array-concatenation.js b/Task/Array-concatenation/JavaScript/array-concatenation.js index b6cc4cdcc1..5f1f3034c3 100644 --- a/Task/Array-concatenation/JavaScript/array-concatenation.js +++ b/Task/Array-concatenation/JavaScript/array-concatenation.js @@ -1,4 +1,3 @@ -var - a = [1,2,3], - b = [4,5,6], - c = a.concat(b); // [1,2,3,4,5,6] +var a = [1,2,3], + b = [4,5,6], + c = a.concat(b); //=> [1,2,3,4,5,6] diff --git a/Task/Array-concatenation/NetRexx/array-concatenation.netrexx b/Task/Array-concatenation/NetRexx/array-concatenation.netrexx index d2a8c76859..bd017280c8 100644 --- a/Task/Array-concatenation/NetRexx/array-concatenation.netrexx +++ b/Task/Array-concatenation/NetRexx/array-concatenation.netrexx @@ -1,5 +1,5 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols nobinary +options replace format comments java crossref nobinary cymru = [ 'Ogof Ffynnon Ddu', 'Ogof Draenen' ] diff --git a/Task/Array-concatenation/Perl-6/array-concatenation.pl6 b/Task/Array-concatenation/Perl-6/array-concatenation.pl6 index 0ed14befaf..f23db7bf62 100644 --- a/Task/Array-concatenation/Perl-6/array-concatenation.pl6 +++ b/Task/Array-concatenation/Perl-6/array-concatenation.pl6 @@ -1,8 +1,8 @@ -# the comma ',' can be used to concatenate arrays: -sub concatenateArrays(@a, @b) { - @a, @b +# the prefix:<|> operator (called "slip") can be used to interpolate arrays into a list: +sub cat-arrays(@a, @b) { + |@a, |@b } my @a1 = (1,2,3); my @a2 = (2,3,4); -concatenateArrays(@a1,@a2).join(", ").say; +cat-arrays(@a1,@a2).join(", ").say; diff --git a/Task/Array-concatenation/Ruby/array-concatenation.rb b/Task/Array-concatenation/Ruby/array-concatenation-1.rb similarity index 100% rename from Task/Array-concatenation/Ruby/array-concatenation.rb rename to Task/Array-concatenation/Ruby/array-concatenation-1.rb diff --git a/Task/Array-concatenation/Ruby/array-concatenation-2.rb b/Task/Array-concatenation/Ruby/array-concatenation-2.rb new file mode 100644 index 0000000000..f505881cf7 --- /dev/null +++ b/Task/Array-concatenation/Ruby/array-concatenation-2.rb @@ -0,0 +1,4 @@ +# concat multiple arrays: +[arr1,arr2,arr3].flatten(1) +# ignore nil: +[arr1,arr2,arr3].compact.flatten(1) diff --git a/Task/Arrays/360-Assembly/arrays.360 b/Task/Arrays/360-Assembly/arrays.360 new file mode 100644 index 0000000000..5abb8983e6 --- /dev/null +++ b/Task/Arrays/360-Assembly/arrays.360 @@ -0,0 +1,30 @@ +* Arrays 04/09/2015 +ARRAYS PROLOG +* we use TA array with 1 as origin. So TA(1) to TA(20) +* ta(i)=ta(j) + L R1,J j + BCTR R1,0 -1 + SLA R1,2 r1=(j-1)*4 (*4 by shift left) + L R0,TA(R1) load r0 with ta(j) + L R1,I i + BCTR R1,0 -1 + SLA R1,2 r1=(i-1)*4 (*4 by shift left) + ST R0,TA(R1) store r0 to ta(i) + EPILOG +* Array of 20 integers (32 bits) (4 bytes) +TA DS 20F +* Initialized array of 10 integers (32 bits) +TB DC 10F'0' +* Initialized array of 10 integers (32 bits) +TC DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10' +* Array of 10 integers (16 bits) +TD DS 10H +* Array of 10 strings of 8 characters (initialized) +TE DC 10CL8' ' +* Array of 10 double precision floating point reals (64 bits) +TF DS 10D +* +I DC F'2' +J DC F'4' + YREGS + END ARRAYS diff --git a/Task/Arrays/ABAP/arrays.abap b/Task/Arrays/ABAP/arrays.abap new file mode 100644 index 0000000000..959905f9b5 --- /dev/null +++ b/Task/Arrays/ABAP/arrays.abap @@ -0,0 +1,13 @@ +TYPES: tty_int TYPE STANDARD TABLE OF i + WITH NON-UNIQUE DEFAULT KEY. + +DATA(itab) = VALUE tty_int( ( 1 ) + ( 2 ) + ( 3 ) ). + +INSERT 4 INTO TABLE itab. +APPEND 5 TO itab. +DELETE itab INDEX 1. + +cl_demo_output=>display( itab ). +cl_demo_output=>display( itab[ 2 ] ). diff --git a/Task/Arrays/Elena/arrays-1.elena b/Task/Arrays/Elena/arrays-1.elena index ffe20e4ffd..2f60eb4e09 100644 --- a/Task/Arrays/Elena/arrays-1.elena +++ b/Task/Arrays/Elena/arrays-1.elena @@ -1,3 +1 @@ - #var anArray := (1, 2, 3). - - system'console writeLine:(anArray@1). + #var aStaticArray := (1, 2, 3). diff --git a/Task/Arrays/Elena/arrays-2.elena b/Task/Arrays/Elena/arrays-2.elena index 9b96ec3462..b69959e9cc 100644 --- a/Task/Arrays/Elena/arrays-2.elena +++ b/Task/Arrays/Elena/arrays-2.elena @@ -1,4 +1,4 @@ - #var anArray := system'Array new &length:5. - anArray setAt:0:2. - - system'console writeLine:(anArray@0). + #var anArray := system'Array new &length:3. + anArray@0 := 1. + anArray@1 := 2. + anArray@2 := 3. diff --git a/Task/Arrays/Elena/arrays-3.elena b/Task/Arrays/Elena/arrays-3.elena new file mode 100644 index 0000000000..76e5f28de0 --- /dev/null +++ b/Task/Arrays/Elena/arrays-3.elena @@ -0,0 +1,4 @@ + #var(type:intarray,size:3)aStackAllocatedArray. + aStackAllocatedArray@0 := 1. + aStackAllocatedArray@1 := 2. + aStackAllocatedArray@2 := 3. diff --git a/Task/Arrays/Elena/arrays-4.elena b/Task/Arrays/Elena/arrays-4.elena new file mode 100644 index 0000000000..c95883669a --- /dev/null +++ b/Task/Arrays/Elena/arrays-4.elena @@ -0,0 +1,6 @@ + #var aDynamicArray := ArrayList new. + aDynamicArray += 1. + aDynamicArray += 2. + aDynamicArray += 4. + + aDynamicArray@2 := 3. diff --git a/Task/Arrays/Elena/arrays-5.elena b/Task/Arrays/Elena/arrays-5.elena new file mode 100644 index 0000000000..a7542b22a3 --- /dev/null +++ b/Task/Arrays/Elena/arrays-5.elena @@ -0,0 +1,3 @@ + system'console writeLine:(anArray@0). + system'console writeLine:(aStackAllocatedArray@1). + system'console writeLine:(aDynamicArray@2). diff --git a/Task/Arrays/GW-BASIC/arrays.gw-basic b/Task/Arrays/GW-BASIC/arrays.gw-basic new file mode 100644 index 0000000000..2fd97ccbfb --- /dev/null +++ b/Task/Arrays/GW-BASIC/arrays.gw-basic @@ -0,0 +1,8 @@ +10 DATA 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 +20 DIM A(9) ' Array with size 10 (9 is maximum subscript), all elements are set to 0 +30 FOR I = 0 TO 9 +40 READ A(I) ' Initialize by reading data +50 NEXT I +60 PRINT A(4) ' Get 4th element of array +70 A(4) = 400 ' Set 4th element of array +80 PRINT A(4) diff --git a/Task/Arrays/JavaScript/arrays.js b/Task/Arrays/JavaScript/arrays.js index 61eb7749ce..d3189374bc 100644 --- a/Task/Arrays/JavaScript/arrays.js +++ b/Task/Arrays/JavaScript/arrays.js @@ -11,9 +11,12 @@ var myArray2 = new Array("Item1","Item2"); var myArray3 = ["Item1", "Item2"]; // Assign a value to member [2] (length is now 3) -myArray[2] = 5; +myArray3[2] = 5; var x = myArray[2] + myArray.length; // 8 +// You can also add a member to an array with the push function (length is now 4) +myArray3.push('Test'); + // Elisions are supported, but are buggy in some implementations var y = [0,1,,]; // length 3, or 4 in buggy implementations diff --git a/Task/Arrays/NetRexx/arrays.netrexx b/Task/Arrays/NetRexx/arrays.netrexx index cb159c3c87..2a99df959a 100644 --- a/Task/Arrays/NetRexx/arrays.netrexx +++ b/Task/Arrays/NetRexx/arrays.netrexx @@ -1,5 +1,5 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols nobinary +options replace format comments java crossref symbols nobinary array = int[10] array[0] = 42 diff --git a/Task/Arrays/PHP/arrays-1.php b/Task/Arrays/PHP/arrays-1.php index 321a55f67c..332ce5aac6 100644 --- a/Task/Arrays/PHP/arrays-1.php +++ b/Task/Arrays/PHP/arrays-1.php @@ -1,2 +1,3 @@ $NumberArray = array(0, 1, 2, 3, 4, 5, 6); $LetterArray = array("a", "b", "c", "d", "e", "f"); +$simpleForm = ['apple', 'orange']; diff --git a/Task/Arrays/PHP/arrays-10.php b/Task/Arrays/PHP/arrays-10.php index 1d2d0181bf..434f9c3f9d 100644 --- a/Task/Arrays/PHP/arrays-10.php +++ b/Task/Arrays/PHP/arrays-10.php @@ -1 +1 @@ -$BlankArray = array(); +echo $CustomKeyArray["b"]; // Returns C diff --git a/Task/Arrays/PHP/arrays-11.php b/Task/Arrays/PHP/arrays-11.php index ed3cfc61e0..1d2d0181bf 100644 --- a/Task/Arrays/PHP/arrays-11.php +++ b/Task/Arrays/PHP/arrays-11.php @@ -1 +1 @@ -$BlankArray[] = "Not Blank Anymore"; +$BlankArray = array(); diff --git a/Task/Arrays/PHP/arrays-12.php b/Task/Arrays/PHP/arrays-12.php index 2bb5dcc57d..ed3cfc61e0 100644 --- a/Task/Arrays/PHP/arrays-12.php +++ b/Task/Arrays/PHP/arrays-12.php @@ -1 +1 @@ -$AssignArray["CertainKey"] = "Value"; +$BlankArray[] = "Not Blank Anymore"; diff --git a/Task/Arrays/PHP/arrays-13.php b/Task/Arrays/PHP/arrays-13.php new file mode 100644 index 0000000000..2bb5dcc57d --- /dev/null +++ b/Task/Arrays/PHP/arrays-13.php @@ -0,0 +1 @@ +$AssignArray["CertainKey"] = "Value"; diff --git a/Task/Arrays/PHP/arrays-3.php b/Task/Arrays/PHP/arrays-3.php index ae03e97e10..e588f4b9fc 100644 --- a/Task/Arrays/PHP/arrays-3.php +++ b/Task/Arrays/PHP/arrays-3.php @@ -1,2 +1,3 @@ -echo $NumberArray[5]; // Returns 5 -echo $LetterArray[5]; // Returns f +$arr = ['apple', 'orange']; +array_push($arr, 'pear'); +print implode(',', $arr); // Returns apple,orange,pear diff --git a/Task/Arrays/PHP/arrays-4.php b/Task/Arrays/PHP/arrays-4.php index dbec29fa5b..ae03e97e10 100644 --- a/Task/Arrays/PHP/arrays-4.php +++ b/Task/Arrays/PHP/arrays-4.php @@ -1 +1,2 @@ -echo $MultiArray[1][5]; // 2 +echo $NumberArray[5]; // Returns 5 +echo $LetterArray[5]; // Returns f diff --git a/Task/Arrays/PHP/arrays-5.php b/Task/Arrays/PHP/arrays-5.php index 86f04db73b..dbec29fa5b 100644 --- a/Task/Arrays/PHP/arrays-5.php +++ b/Task/Arrays/PHP/arrays-5.php @@ -1 +1 @@ -print_r($MultiArray); +echo $MultiArray[1][5]; // 2 diff --git a/Task/Arrays/PHP/arrays-6.php b/Task/Arrays/PHP/arrays-6.php index 701458228c..86f04db73b 100644 --- a/Task/Arrays/PHP/arrays-6.php +++ b/Task/Arrays/PHP/arrays-6.php @@ -1,34 +1 @@ -Array( - 0 => array( - 0 => 0 - 1 => 0 - 2 => 0 - 3 => 0 - 4 => 0 - 5 => 0 - ) - 1 => array( - 0 => 1 - 1 => 1 - 2 => 1 - 3 => 1 - 4 => 1 - 5 => 1 - ) - 2 => array( - 0 => 2 - 1 => 2 - 2 => 2 - 3 => 2 - 4 => 2 - 5 => 2 - ) - 3 => array( - 0 => 3 - 1 => 3 - 2 => 3 - 3 => 3 - 4 => 3 - 5 => 3 - ) -) +print_r($MultiArray); diff --git a/Task/Arrays/PHP/arrays-7.php b/Task/Arrays/PHP/arrays-7.php index 26108d73e7..701458228c 100644 --- a/Task/Arrays/PHP/arrays-7.php +++ b/Task/Arrays/PHP/arrays-7.php @@ -1 +1,34 @@ -$StartIndexAtOne = array(1 => "A", "B", "C", "D"); +Array( + 0 => array( + 0 => 0 + 1 => 0 + 2 => 0 + 3 => 0 + 4 => 0 + 5 => 0 + ) + 1 => array( + 0 => 1 + 1 => 1 + 2 => 1 + 3 => 1 + 4 => 1 + 5 => 1 + ) + 2 => array( + 0 => 2 + 1 => 2 + 2 => 2 + 3 => 2 + 4 => 2 + 5 => 2 + ) + 3 => array( + 0 => 3 + 1 => 3 + 2 => 3 + 3 => 3 + 4 => 3 + 5 => 3 + ) +) diff --git a/Task/Arrays/PHP/arrays-8.php b/Task/Arrays/PHP/arrays-8.php index cb1ec1e873..26108d73e7 100644 --- a/Task/Arrays/PHP/arrays-8.php +++ b/Task/Arrays/PHP/arrays-8.php @@ -1 +1 @@ -$CustomKeyArray = array("d" => "A", "c" => "B", "b" =>"C", "a" =>"D"); +$StartIndexAtOne = array(1 => "A", "B", "C", "D"); diff --git a/Task/Arrays/PHP/arrays-9.php b/Task/Arrays/PHP/arrays-9.php index 434f9c3f9d..cb1ec1e873 100644 --- a/Task/Arrays/PHP/arrays-9.php +++ b/Task/Arrays/PHP/arrays-9.php @@ -1 +1 @@ -echo $CustomKeyArray["b"]; // Returns C +$CustomKeyArray = array("d" => "A", "c" => "B", "b" =>"C", "a" =>"D"); diff --git a/Task/Arrays/Rust/arrays-1.rust b/Task/Arrays/Rust/arrays-1.rust new file mode 100644 index 0000000000..5e4b1c6541 --- /dev/null +++ b/Task/Arrays/Rust/arrays-1.rust @@ -0,0 +1,3 @@ +let a = [1, 2, 3]; // immutable array +let mut m = [1, 2, 3]; // mutable array +let zeroes = [0; 200]; // creates an array of 200 zeroes diff --git a/Task/Arrays/Rust/arrays-2.rust b/Task/Arrays/Rust/arrays-2.rust new file mode 100644 index 0000000000..e1daf6a37a --- /dev/null +++ b/Task/Arrays/Rust/arrays-2.rust @@ -0,0 +1,5 @@ +let a = [1, 2, 3]; +a.len(); +for e in a.iter() { + e; +} diff --git a/Task/Arrays/Rust/arrays-3.rust b/Task/Arrays/Rust/arrays-3.rust new file mode 100644 index 0000000000..c035c5a7e0 --- /dev/null +++ b/Task/Arrays/Rust/arrays-3.rust @@ -0,0 +1,2 @@ +let names = ["Graydon", "Brian", "Niko"]; +names[1]; // second element diff --git a/Task/Arrays/Rust/arrays-4.rust b/Task/Arrays/Rust/arrays-4.rust new file mode 100644 index 0000000000..a5c121934f --- /dev/null +++ b/Task/Arrays/Rust/arrays-4.rust @@ -0,0 +1 @@ +let v = vec![1, 2, 3]; diff --git a/Task/Arrays/Rust/arrays-5.rust b/Task/Arrays/Rust/arrays-5.rust new file mode 100644 index 0000000000..8482df8c9c --- /dev/null +++ b/Task/Arrays/Rust/arrays-5.rust @@ -0,0 +1,3 @@ +let mut v = vec![1, 2, 3]; +v.push(4); +v.len(); // 4 diff --git a/Task/Arrays/Self/arrays-1.self b/Task/Arrays/Self/arrays-1.self new file mode 100644 index 0000000000..23713a4d73 --- /dev/null +++ b/Task/Arrays/Self/arrays-1.self @@ -0,0 +1 @@ +vector copySize: 100 diff --git a/Task/Arrays/Self/arrays-2.self b/Task/Arrays/Self/arrays-2.self new file mode 100644 index 0000000000..b86b018968 --- /dev/null +++ b/Task/Arrays/Self/arrays-2.self @@ -0,0 +1 @@ +vector copySize: 100 FillingWith: anObject diff --git a/Task/Arrays/Self/arrays-3.self b/Task/Arrays/Self/arrays-3.self new file mode 100644 index 0000000000..31e220859b --- /dev/null +++ b/Task/Arrays/Self/arrays-3.self @@ -0,0 +1 @@ +(1 & 'Hello' & 2.0 & someObject) asVector diff --git a/Task/Arrays/Self/arrays-4.self b/Task/Arrays/Self/arrays-4.self new file mode 100644 index 0000000000..5b473d28a8 --- /dev/null +++ b/Task/Arrays/Self/arrays-4.self @@ -0,0 +1,9 @@ +|v| +"creates an vector that holds up to 20 elements" +v: vector copySize: 20. +"access the first element" +v first printLine. +"access the 10th element" +(v at: 9) printLine. +"put 100 as second value" +vat: 1 Put: 100. diff --git a/Task/Arrays/Self/arrays-5.self b/Task/Arrays/Self/arrays-5.self new file mode 100644 index 0000000000..053cc9baa9 --- /dev/null +++ b/Task/Arrays/Self/arrays-5.self @@ -0,0 +1,3 @@ +v do: [:each | each printLine]. +v copy mapBy: [:each | each squared]. +v copy filterBy: [:each | each > 10]. diff --git a/Task/Arrays/Self/arrays-6.self b/Task/Arrays/Self/arrays-6.self new file mode 100644 index 0000000000..7484e5af79 --- /dev/null +++ b/Task/Arrays/Self/arrays-6.self @@ -0,0 +1,11 @@ +|s| +"creates a new sequence" +s: sequence copyRemoveAll. +"add an element" +s addLast: 'Hello'. +"access the first element" +s first printLine. +"remove the first element" +s removeFirst. +"Check size" +s size printLine. diff --git a/Task/Arrays/TI-83-BASIC/arrays-3.ti-83 b/Task/Arrays/TI-83-BASIC/arrays-3.ti-83 new file mode 100644 index 0000000000..609104c576 --- /dev/null +++ b/Task/Arrays/TI-83-BASIC/arrays-3.ti-83 @@ -0,0 +1,4 @@ +20→dim(L1) +DelVar L1 +5→dim(∟MYLIST) +DelVar ∟MYLIST diff --git a/Task/Arrays/TI-83-BASIC/arrays-4.ti-83 b/Task/Arrays/TI-83-BASIC/arrays-4.ti-83 new file mode 100644 index 0000000000..5ca1b774d2 --- /dev/null +++ b/Task/Arrays/TI-83-BASIC/arrays-4.ti-83 @@ -0,0 +1,3 @@ +[[11,21,31,41][12,22,32,42][13,23,33,43]]→[A] +Disp [A](1,3) +0→[A](4,2) diff --git a/Task/Arrays/TI-83-BASIC/arrays-5.ti-83 b/Task/Arrays/TI-83-BASIC/arrays-5.ti-83 new file mode 100644 index 0000000000..0ddffdea37 --- /dev/null +++ b/Task/Arrays/TI-83-BASIC/arrays-5.ti-83 @@ -0,0 +1,2 @@ +{5,5}→dim([A]) +DelVar [A] diff --git a/Task/Arrays/Visual-Basic-.NET/arrays.visual b/Task/Arrays/Visual-Basic-.NET/arrays.visual index da50171596..7044a73611 100644 --- a/Task/Arrays/Visual-Basic-.NET/arrays.visual +++ b/Task/Arrays/Visual-Basic-.NET/arrays.visual @@ -1,31 +1,31 @@ - 'Example of array of 10 int types: - Dim numbers As Integer() = New Integer(0) {} - 'Example of array of 4 string types: - Dim words As String() = {"hello", "world", "from", "mars"} - 'You can also declare the size of the array and initialize the values at the same time: - Dim more_numbers As Integer() = New Integer(2) {21, 14, 63} +'Example of array of 10 int types: +Dim numbers As Integer() = New Integer(0) {} +'Example of array of 4 string types: +Dim words As String() = {"hello", "world", "from", "mars"} +'You can also declare the size of the array and initialize the values at the same time: +Dim more_numbers As Integer() = New Integer(2) {21, 14, 63} - 'For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration. - 'The following creates a 3x2 int matrix - Dim number_matrix As Integer(,) = New Integer(2, 1) {} +'For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration. +'The following creates a 3x2 int matrix +Dim number_matrix As Integer(,) = New Integer(2, 1) {} - 'As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces. - Dim string_matrix As String(,) = {{"I", "swam"}, {"in", "the"}, {"freezing", "water"}} - 'or - Dim funny_matrix As String(,) = New String(1, 1) {{"clowns", "are"}, {"not", "funny"}} +'As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces. +Dim string_matrix As String(,) = {{"I", "swam"}, {"in", "the"}, {"freezing", "water"}} +'or +Dim funny_matrix As String(,) = New String(1, 1) {{"clowns", "are"}, {"not", "funny"}} - Dim array As Integer() = New Integer(9) {} - array(0) = 1 - array(1) = 3 - Console.WriteLine(array(0)) +Dim array As Integer() = New Integer(9) {} +array(0) = 1 +array(1) = 3 +Console.WriteLine(array(0)) - 'Dynamic - Imports System - Imports System.Collections.Generic - Dim list As New List(Of Integer)() - list.Add(1) - list.Add(3) - list(0) = 2 - Console.WriteLine(list(0)) +'Dynamic +Imports System +Imports System.Collections.Generic +Dim list As New List(Of Integer)() +list.Add(1) +list.Add(3) +list(0) = 2 +Console.WriteLine(list(0)) diff --git a/Task/Assertions/ALGOL-W/assertions.alg b/Task/Assertions/ALGOL-W/assertions.alg new file mode 100644 index 0000000000..39e015fe7e --- /dev/null +++ b/Task/Assertions/ALGOL-W/assertions.alg @@ -0,0 +1,6 @@ +begin + integer a; + a := 43; + assert a = 42; + write( "this won't appear" ) +end. diff --git a/Task/Assertions/Forth/assertions.fth b/Task/Assertions/Forth/assertions.fth new file mode 100644 index 0000000000..c11546d5b2 --- /dev/null +++ b/Task/Assertions/Forth/assertions.fth @@ -0,0 +1,4 @@ +variable a +: assert a @ 42 <> throw ; + +41 a ! assert diff --git a/Task/Assertions/Rust/assertions.rust b/Task/Assertions/Rust/assertions.rust new file mode 100644 index 0000000000..0036190fa6 --- /dev/null +++ b/Task/Assertions/Rust/assertions.rust @@ -0,0 +1,3 @@ +let x = 42; +assert!(x == 42); +assert_eq!(x, 42); diff --git a/Task/Associative-array-Creation/Elena/associative-array-creation.elena b/Task/Associative-array-Creation/Elena/associative-array-creation.elena index d86acd5ebb..9505edb516 100644 --- a/Task/Associative-array-Creation/Elena/associative-array-creation.elena +++ b/Task/Associative-array-Creation/Elena/associative-array-creation.elena @@ -1,3 +1,4 @@ +#define system. #define system'collections. // --- Program --- @@ -6,8 +7,9 @@ [ // 1. Create #var aMap := Dictionary new. - aMap set &key:"key" &value:"foox". - aMap set &key:"key2" &value:"foo2". - aMap set &key:"key" &value:"foo". - + aMap@"key" := "foox". + aMap@"key" := "foo". + aMap@"key2":= "foo2". + aMap@"key3":= "foo3". + aMap@"key4":= "foo4". ]. diff --git a/Task/Associative-array-Creation/Elixir/associative-array-creation.elixir b/Task/Associative-array-Creation/Elixir/associative-array-creation.elixir new file mode 100644 index 0000000000..db3a54960e --- /dev/null +++ b/Task/Associative-array-Creation/Elixir/associative-array-creation.elixir @@ -0,0 +1,19 @@ +defmodule RC do + def dict_create(dict_impl \\ Map) do + d = dict_impl.new #=> creates an empty Dict + d1 = Dict.put(d,:foo,1) + d2 = Dict.put(d1,:bar,2) + print_vals(d2) + print_vals(Dict.put(d2,:foo,3)) + end + + defp print_vals(d) do + IO.inspect d + Enum.each(d, fn {k,v} -> IO.puts "#{k}: #{v}" end) + end +end + +IO.puts "< create Map.new >" +RC.dict_create +IO.puts "\n< create HashDict.new >" +RC.dict_create(HashDict) diff --git a/Task/Associative-array-Creation/Haskell/associative-array-creation-1.hs b/Task/Associative-array-Creation/Haskell/associative-array-creation-1.hs index 722f7709cb..a98bc29d40 100644 --- a/Task/Associative-array-Creation/Haskell/associative-array-creation-1.hs +++ b/Task/Associative-array-Creation/Haskell/associative-array-creation-1.hs @@ -2,4 +2,4 @@ import Data.Map dict = fromList [("key1","val1"), ("key2","val2")] -ans = Data.Map.lookup "key2" dict -- evaluates to "val2" +ans = Data.Map.lookup "key2" dict -- evaluates to Just "val2" diff --git a/Task/Associative-array-Creation/JavaScript/associative-array-creation-1.js b/Task/Associative-array-Creation/JavaScript/associative-array-creation-1.js index 9841fd5e92..245d1edf85 100644 --- a/Task/Associative-array-Creation/JavaScript/associative-array-creation-1.js +++ b/Task/Associative-array-Creation/JavaScript/associative-array-creation-1.js @@ -1,13 +1,21 @@ var assoc = {}; + assoc['foo'] = 'bar'; assoc['another-key'] = 3; -assoc.thirdKey = 'we can also do this!'; // dot notation can be used if the property name - // is a valid identifier -assoc[2] = 'the index here is the string "2"'; -assoc[null] = 'this also works'; -assoc[(function(){return 'expr';})()] = 'Can use expressions too'; +// dot notation can be used if the property name is a valid identifier +assoc.thirdKey = 'we can also do this!'; +assoc[2] = "the index here is the string '2'"; + +//using JavaScript's object literal notation +var assoc = { + foo: 'bar', + 'another-key': 3 //the key can either be enclosed by quotes or not +}; + +//iterating keys for (var key in assoc) { + // hasOwnProperty() method ensures the property isn't inherited if (assoc.hasOwnProperty(key)) { alert('key:"' + key + '", value:"' + assoc[key] + '"'); } diff --git a/Task/Associative-array-Creation/JavaScript/associative-array-creation-2.js b/Task/Associative-array-Creation/JavaScript/associative-array-creation-2.js index 1c0a6fcc57..5ecc55159b 100644 --- a/Task/Associative-array-Creation/JavaScript/associative-array-creation-2.js +++ b/Task/Associative-array-Creation/JavaScript/associative-array-creation-2.js @@ -1,4 +1,22 @@ -var assoc = { - foo: 'bar', - 'another-key': 3 //the key can either be enclosed by quotes or not -}; +var map = new Map(), + fn = function () {}, + obj = {}; + +map.set(fn, 123); +map.set(obj, 'abc'); +map.set('key', 'val'); +map.set(3, x => x + x); + +map.get(fn); //=> 123 +map.get(function () {}); //=> undefined because not the same function +map.get(obj); //=> 'abc' +map.get({}); //=> undefined because not the same object +map.get('key'); //=> 'val' +map.get(3); //=> (x => x + x) + +map.size; //=> 4 + +//iterating using ES6 for..of syntax +for (var key of map.keys()) { + console.log(key + ' => ' + map.get(key)); +} diff --git a/Task/Associative-array-Creation/NetRexx/associative-array-creation.netrexx b/Task/Associative-array-Creation/NetRexx/associative-array-creation.netrexx index fcbfe3e662..6f8a402028 100644 --- a/Task/Associative-array-Creation/NetRexx/associative-array-creation.netrexx +++ b/Task/Associative-array-Creation/NetRexx/associative-array-creation.netrexx @@ -1,6 +1,6 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols +options replace format comments java crossref symbols key0 = '0' key1 = 'key0' diff --git a/Task/Associative-array-Creation/PARI-GP/associative-array-creation-1.pari b/Task/Associative-array-Creation/PARI-GP/associative-array-creation-1.pari new file mode 100644 index 0000000000..effdc67ffd --- /dev/null +++ b/Task/Associative-array-Creation/PARI-GP/associative-array-creation-1.pari @@ -0,0 +1 @@ +M = Map(); diff --git a/Task/Associative-array-Creation/PARI-GP/associative-array-creation-2.pari b/Task/Associative-array-Creation/PARI-GP/associative-array-creation-2.pari new file mode 100644 index 0000000000..bac1fe5844 --- /dev/null +++ b/Task/Associative-array-Creation/PARI-GP/associative-array-creation-2.pari @@ -0,0 +1,6 @@ +mapput(M, "key", "value"); +mapput(M, 17, "different value"); +mapput(M, "key2", Pi); +mapget(M, "key2") \\ returns Pi +mapisdefined(M, "key3") \\ returns 0 +mapdelete(M, "key2"); diff --git a/Task/Associative-array-Creation/PHP/associative-array-creation-1.php b/Task/Associative-array-Creation/PHP/associative-array-creation-1.php index e77595cfbf..0123bbcf91 100644 --- a/Task/Associative-array-Creation/PHP/associative-array-creation-1.php +++ b/Task/Associative-array-Creation/PHP/associative-array-creation-1.php @@ -1,11 +1,21 @@ $array = array(); +$array = []; // Simpler form of array initialization $array['foo'] = 'bar'; $array['bar'] = 'foo'; echo($array['foo']); // bar echo($array['moo']); // Undefined index -//alternative (inline) way +// Alternative (inline) way $array2 = array('fruit' => 'apple', 'price' => 12.96, 'colour' => 'green'); + +// Another alternative (simpler) way +$array2 = ['fruit' => 'apple', + 'price' => 12.96, + 'colour' => 'green']; + +// Check if key exists in the associative array +echo(isset($array['foo'])); // Faster, but returns false if the value of the element is set to null +echo(array_key_exists('foo', $array)); // Slower, but returns true if the value of the element is null diff --git a/Task/Associative-array-Creation/PL-I/associative-array-creation.pli b/Task/Associative-array-Creation/PL-I/associative-array-creation.pli new file mode 100644 index 0000000000..ceda79c816 --- /dev/null +++ b/Task/Associative-array-Creation/PL-I/associative-array-creation.pli @@ -0,0 +1,49 @@ +*process source xref attributes or(!); + assocarr: Proc Options(main); + Dcl 1 aa, + 2 an Bin Fixed(31) Init(0), + 2 pairs(100), + 3 key Char(10) Var, + 3 val Char(10) Var; + Dcl hi Char(10) Value((high(10))); + Dcl i Bin Fixed(31); + Dcl k Char(10) Var; + + Call aadd('1','spam'); + Call aadd('2','eggs'); + Call aadd('3','foo'); + Call aadd('2','spam'); + Call aadd('4','spam'); + + Put Skip(' '); + Put Edit('Iterate over keys')(Skip,a); + Do i=1 To an; + k=key(i); + Put Edit('>'!!k!!'< => >'!!aacc(k)!!'<')(Skip,a); + End; + + aadd: Proc(k,v); + Dcl (k,v) Char(*) Var; + If aacc(k)^=hi Then + Put Edit('Key >',k,'< would be a duplicate, not added.') + (Skip,a,a,a); + Else Do; + an+=1; + key(an)=k; + val(an)=v; + Put Edit('added >'!!k!!'< -> '!!v!!'<')(Skip,a); + End; + End; + + aacc: Proc(k) Returns(Char(10) Var); + Dcl k Char(*) Var; + Dcl v Char(10) Var; + Dcl i Bin Fixed(31); + Do i=1 To an; + If key(i)=k Then + Return(val(i)); + End; + Return(hi); + End; + + End; diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena index bb3a5a30ae..65dcb765ab 100644 --- a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena +++ b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena @@ -1,5 +1,7 @@ #define system. #define system'collections. +#define system'routines. +#define extensions. // --- Program --- @@ -7,13 +9,12 @@ [ // 1. Create #var aMap := Dictionary new. - aMap set &key:"key" &value:"foox". - aMap set &key:"key" &value:"foo". - aMap set &key:"key2" &value:"foo2". - aMap set &key:"key3" &value:"foo3". - aMap set &key:"key4" &value:"foo4". + aMap@"key" := "foox". + aMap@"key2":= "foo2". + aMap@"key3":= "foo3". + aMap@"key4":= "foo4". // Enumerate - control foreach:aMap &do: aKeyValue - [ console write:(aKeyValue key) write:" : " writeLine:(aKeyValue value) ]. + aMap run &each: aKeyValue + [ console writeLine:(aKeyValue key):" : ":aKeyValue ]. ]. diff --git a/Task/Associative-array-Iteration/Elixir/associative-array-iteration.elixir b/Task/Associative-array-Iteration/Elixir/associative-array-iteration.elixir new file mode 100644 index 0000000000..c1f172c244 --- /dev/null +++ b/Task/Associative-array-Iteration/Elixir/associative-array-iteration.elixir @@ -0,0 +1,18 @@ +defmodule RC do + def test_iterate(dict_impl \\ Map) do + d = dict_impl.new |> Dict.put(:foo,1) |> Dict.put(:bar,2) + print_vals(d) + end + + defp print_vals(d) do + IO.inspect d + Enum.each(d, fn {k,v} -> IO.puts "#{k}: #{v}" end) + Enum.each(Dict.keys(d), fn key -> IO.inspect key end) + Enum.each(Dict.values(d), fn value -> IO.inspect value end) + end +end + +IO.puts "< iterate Map >" +RC.test_iterate +IO.puts "\n< iterate HashDict >" +RC.test_iterate(HashDict) diff --git a/Task/Associative-array-Iteration/JavaScript/associative-array-iteration.js b/Task/Associative-array-Iteration/JavaScript/associative-array-iteration.js new file mode 100644 index 0000000000..c0f44cf1e5 --- /dev/null +++ b/Task/Associative-array-Iteration/JavaScript/associative-array-iteration.js @@ -0,0 +1,18 @@ +var myhash = {}; //a new, empty object +myhash["hello"] = 3; +myhash.world = 6; //obj.name is equivalent to obj["name"] for certain values of name +myhash["!"] = 9; + +//iterate using for..in loop +for (var key in myhash) { + //ensure key is in object and not in prototype + if (myhash.hasOwnProperty(key)) { + console.log("Key is: " + key + '. Value is: ' + myhash[key]); + } +} + +//iterate using ES5.1 Object.keys() and Array.prototype.Map() +var keys = Object.keys(); //get Array of object keys (doesn't get prototype keys) +keys.map(function (key) { + console.log("Key is: " + key + '. Value is: ' + myhash[key]); +}); diff --git a/Task/Associative-array-Iteration/NetRexx/associative-array-iteration.netrexx b/Task/Associative-array-Iteration/NetRexx/associative-array-iteration.netrexx index f106174905..0c811a6cd2 100644 --- a/Task/Associative-array-Iteration/NetRexx/associative-array-iteration.netrexx +++ b/Task/Associative-array-Iteration/NetRexx/associative-array-iteration.netrexx @@ -1,5 +1,5 @@ /* NetRexx */ -options replace format comments java crossref savelog symbols +options replace format comments java crossref symbols surname = 'Unknown' -- default value surname['Fred'] = 'Bloggs' diff --git a/Task/Associative-array-Iteration/PARI-GP/associative-array-iteration-1.pari b/Task/Associative-array-Iteration/PARI-GP/associative-array-iteration-1.pari new file mode 100644 index 0000000000..556e911cae --- /dev/null +++ b/Task/Associative-array-Iteration/PARI-GP/associative-array-iteration-1.pari @@ -0,0 +1 @@ +keys = Vec(M); diff --git a/Task/Associative-array-Iteration/PARI-GP/associative-array-iteration-2.pari b/Task/Associative-array-Iteration/PARI-GP/associative-array-iteration-2.pari new file mode 100644 index 0000000000..5d19f7e630 --- /dev/null +++ b/Task/Associative-array-Iteration/PARI-GP/associative-array-iteration-2.pari @@ -0,0 +1,3 @@ +for(i=1,#keys, + print(keys[i]," ",mapget(M,keys[i])) +) diff --git a/Task/Associative-array-Iteration/Rust/associative-array-iteration.rust b/Task/Associative-array-Iteration/Rust/associative-array-iteration.rust index 404f6d6d96..7b2973e8df 100644 --- a/Task/Associative-array-Iteration/Rust/associative-array-iteration.rust +++ b/Task/Associative-array-Iteration/Rust/associative-array-iteration.rust @@ -1,16 +1,17 @@ use std::collections::HashMap; + fn main() { - let mut squares = HashMap::new(); - squares.insert("one", 1i32); - squares.insert("two", 4); - squares.insert("three", 9); - for key in squares.keys() { - println!("Key {}", key); - } - for value in squares.values() { - println!("Value {}", value); - } - for (key, value) in squares.iter() { - println!("{} => {}", key, value); - } + let mut squares = HashMap::new(); + squares.insert("one", 1); + squares.insert("two", 4); + squares.insert("three", 9); + for key in squares.keys() { + println!("Key {}", key); + } + for value in squares.values() { + println!("Value {}", value); + } + for (key, value) in squares.iter() { + println!("{} => {}", key, value); + } } diff --git a/Task/Associative-array-Iteration/VBScript/associative-array-iteration.vb b/Task/Associative-array-Iteration/VBScript/associative-array-iteration.vb new file mode 100644 index 0000000000..9f39b6846a --- /dev/null +++ b/Task/Associative-array-Iteration/VBScript/associative-array-iteration.vb @@ -0,0 +1,12 @@ +'instantiate the dictionary object +Set dict = CreateObject("Scripting.Dictionary") + +'populate the dictionary or hash table +dict.Add 1,"larry" +dict.Add 2,"curly" +dict.Add 3,"moe" + +'iterate key and value pairs +For Each key In dict.Keys + WScript.StdOut.WriteLine key & " - " & dict.Item(key) +Next diff --git a/Task/Atomic-updates/C++/atomic-updates.cpp b/Task/Atomic-updates/C++/atomic-updates.cpp new file mode 100644 index 0000000000..c78fa3d0b6 --- /dev/null +++ b/Task/Atomic-updates/C++/atomic-updates.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +constexpr int bucket_count = 15; + +void equalizer(array& buckets, + array& bucket_mutex) { + random_device rd; + mt19937 gen(rd()); + uniform_int_distribution<> dist_bucket(0, bucket_count - 1); + + while (true) { + int from = dist_bucket(gen); + int to = dist_bucket(gen); + if (from != to) { + lock_guard lock_first(bucket_mutex[min(from, to)]); + lock_guard lock_second(bucket_mutex[max(from, to)]); + int diff = buckets[from] - buckets[to]; + int amount = abs(diff / 2); + if (diff < 0) { + swap(from, to); + } + buckets[from] -= amount; + buckets[to] += amount; + } + } +} + +void randomizer(array& buckets, + array& bucket_mutex) { + random_device rd; + mt19937 gen(rd()); + uniform_int_distribution<> dist_bucket(0, bucket_count - 1); + + while (true) { + int from = dist_bucket(gen); + int to = dist_bucket(gen); + if (from != to) { + lock_guard lock_first(bucket_mutex[min(from, to)]); + lock_guard lock_second(bucket_mutex[max(from, to)]); + uniform_int_distribution<> dist_amount(0, buckets[from]); + int amount = dist_amount(gen); + buckets[from] -= amount; + buckets[to] += amount; + } + } +} + +void print_buckets(const array& buckets) { + int total = 0; + for (const int& bucket : buckets) { + total += bucket; + cout << setw(3) << bucket << ' '; + } + cout << "= " << setw(3) << total << endl; +} + +int main() { + random_device rd; + mt19937 gen(rd()); + uniform_int_distribution<> dist(0, 99); + + array buckets; + array bucket_mutex; + for (int& bucket : buckets) { + bucket = dist(gen); + } + print_buckets(buckets); + + thread t_eq(equalizer, ref(buckets), ref(bucket_mutex)); + thread t_rd(randomizer, ref(buckets), ref(bucket_mutex)); + + while (true) { + this_thread::sleep_for(chrono::seconds(1)); + for (mutex& mutex : bucket_mutex) { + mutex.lock(); + } + print_buckets(buckets); + for (mutex& mutex : bucket_mutex) { + mutex.unlock(); + } + } + return 0; +} diff --git a/Task/Atomic-updates/Mathematica/atomic-updates.math b/Task/Atomic-updates/Mathematica/atomic-updates.math new file mode 100644 index 0000000000..18a03d0b8f --- /dev/null +++ b/Task/Atomic-updates/Mathematica/atomic-updates.math @@ -0,0 +1,21 @@ +transfer[bucks_, src_, dest_, n_] := + ReplacePart[ + bucks, {src -> Max[bucks[[src]] - n, 0], + dest -> bucks[[dest]] + Min[bucks[[src]], n]}]; +DistributeDefinitions[transfer]; +SetSharedVariable[bucks, comp]; +bucks = RandomInteger[10, 20]; +comp = True; +Print["Original sum: " <> IntegerString[Plus @@ bucks]]; +Print[Dynamic["Current sum: " <> IntegerString[Plus @@ bucks]]]; +WaitAll[{ParallelSubmit[ + While[True, While[! comp, Null]; comp = False; + Module[{a = RandomInteger[{1, 20}], b = RandomInteger[{1, 20}]}, + bucks = transfer[bucks, Max[a, b], Min[a, b], + Floor[Abs[bucks[[a]] - bucks[[b]]]/2]]]; comp = True]], + ParallelSubmit[ + While[True, While[! comp, Null]; comp = False; + Module[{src = RandomInteger[{1, 20}], + dest = RandomInteger[{1, 20}]}, + bucks = transfer[bucks, src, dest, + RandomInteger[{1, bucks[[src]]}]]]; comp = True]]}]; diff --git a/Task/Atomic-updates/PicoLisp/atomic-updates.l b/Task/Atomic-updates/PicoLisp/atomic-updates.l index 916d3b438d..6b5f91a3e8 100644 --- a/Task/Atomic-updates/PicoLisp/atomic-updates.l +++ b/Task/Atomic-updates/PicoLisp/atomic-updates.l @@ -21,39 +21,40 @@ (de pickBucket () (db 'key '+Bucket (rand 1 *Buckets)) ) +# Create process +(de process (QuadFunction) + (unless (fork) + (seed *Pid) # Ensure local random sequence + (loop + (let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2' + (unless (== B1 B2) # Found two different ones? + (dbSync) # Atomic DB operation + (let (V1 (; B1 val) V2 (; B2 val)) # Get current values + (QuadFunction B1 V1 B2 V2) ) + (commit 'upd) ) ) ) ) ) # Close transaction + # First process -(unless (fork) - (seed *Pid) # Ensure local random sequence - (loop - (let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2' - (dbSync) # Atomic DB operation - (let (V1 (; B1 val) V2 (; B2 val)) # Get current values - (cond - ((> V1 V2) - (dec> B1 'val) # Make them closer to equal - (inc> B2 'val) ) - ((> V2 V1) - (dec> B2 'val) - (inc> B1 'val) ) ) ) - (commit 'upd) ) ) ) # Close transaction +(process + (quote (B1 V1 B2 V2) + (cond + ((> V1 V2) + (dec> B1 'val) # Make them closer to equal + (inc> B2 'val) ) + ((> V2 V1) + (dec> B2 'val) + (inc> B1 'val) ) ) ) ) # Second process -(unless (fork) - (seed *Pid) # Ensure local random sequence - (loop - (let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2' - (unless (== B1 B2) # Found two different ones? - (dbSync) # Atomic DB operation - (let (V1 (; B1 val) V2 (; B2 val)) # Get current values - (cond - ((> V1 V2 0) - (inc> B1 'val) # Redistribute them - (dec> B2 'val) ) - ((> V2 V1 0) - (inc> B2 'val) - (dec> B1 'val) ) ) ) - (commit 'upd) ) ) ) ) # Close transaction +(process + (quote (B1 V1 B2 V2) + (cond + ((> V1 V2 0) + (inc> B1 'val) # Redistribute them + (dec> B2 'val) ) + ((> V2 V1 0) + (inc> B2 'val) + (dec> B1 'val) ) ) ) ) # Third process (unless (fork) diff --git a/Task/Average-loop-length/Elixir/average-loop-length.elixir b/Task/Average-loop-length/Elixir/average-loop-length.elixir new file mode 100644 index 0000000000..b059950f51 --- /dev/null +++ b/Task/Average-loop-length/Elixir/average-loop-length.elixir @@ -0,0 +1,28 @@ +defmodule RC do + def factorial(0), do: 1 + def factorial(n), do: Enum.reduce(1..n, 1, &(&1 * &2)) + + def loop_length(n), do: loop_length(n, HashSet.new) + + defp loop_length(n, set) do + r = :random.uniform(n) + if Set.member?(set, r), do: Set.size(set), + else: loop_length(n, Set.put(set, r)) + end + + def task(runs) do + IO.puts " N average analytical (error) " + IO.puts "=== ========= ========== =========" + Enum.each(1..20, fn n -> + sum_of_runs = Enum.reduce(1..runs, 0, fn _,sum -> sum + loop_length(n) end) + avg = sum_of_runs / runs + analytical = Enum.reduce(1..n, 0, fn i,sum -> + sum + (factorial(n) / :math.pow(n, i) / factorial(n-i)) + end) + :io.format "~3w ~9.4f ~9.4f (~6.2f%)~n", [n, avg, analytical, abs(avg/analytical - 1)*100] + end) + end +end + +runs = 100_000 +RC.task(runs) diff --git a/Task/Average-loop-length/REXX/average-loop-length.rexx b/Task/Average-loop-length/REXX/average-loop-length.rexx index 6308b61663..c5f870c50b 100644 --- a/Task/Average-loop-length/REXX/average-loop-length.rexx +++ b/Task/Average-loop-length/REXX/average-loop-length.rexx @@ -1,38 +1,37 @@ -/*REXX pgm computes avg loop length mapping a random field 1..N to 1..N*/ -parse arg runs tests seed . -if runs ==',' | runs =='' then runs = 40 /*num of runs. */ -if tests ==',' | tests =='' then tests = 1000000 /*num of trials.*/ -if seed\==',' & seed\=='' then call random ,,seed /*repeatability?*/ -numeric digits 100000; !.=0; !.0=1 /*be able to calculate !(25000).*/ -numeric digits max(9,length(!(runs))) /*set NUMERIC digits for !(runs).*/ -say right( runs, 24) 'runs' /*display # of runs we're using*/ -say right( tests, 24) 'tests' /* " " " tests " " */ -say right( digits(), 24) 'digits' /* " " " digits " " */ +/*REXX pgm computes average loop length mapping a random field 1..N ───► 1..N */ +parse arg runs tests seed . /*obtain optional arguments from C.L. */ +if runs ==',' | runs =='' then runs = 40 /*number of runs. */ +if tests ==',' | tests =='' then tests= 1000000 /* " " trials. */ +if seed\==',' & seed\=='' then call random ,,seed /*RAND repeatability?*/ +numeric digits 100000; !.=0; !.0=1 /*be able to calculate 25,000! */ +numeric digits max(9,length(!(runs))) /*set the NUMERIC DIGITS for !(runs). */ +say right( runs, 24) 'runs' /*display number of runs we're using.*/ +say right( tests, 24) 'tests' /* " " " tests " " */ +say right( digits(), 24) 'digits' /* " " " digits " " */ say -say ' N average exact % error' /*headers & pad.*/ -h= ' ─── ───────── ───────── ─────────'; say h; pad=left('',3) - - do #=1 for runs; ##=right(#,9) /*## is used for indenting output*/ - avg = fmtD(exact(#)) /*use 4 digits past decimal point*/ - exa = fmtD(exper(#)) /* " " " " " " */ - err = fmtD(abs(exa-avg)*100/avg) /* " " " " " " */ - say ## pad exa pad avg pad err /*display a line of statistics. */ - end /*#*/ -say h /*display the final header bar. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────! subroutine────────────────────────*/ -!: procedure expose !.; parse arg z; if !.z\==0 then return !.z -!=1; do j=1 for z; !=!*j; !.j=!; end; return ! -/*──────────────────────────────────EXACT subroutine────────────────────*/ -exact: parse arg x; s=0; do j=1 for x; s=s+!(x)/!(x-j)/x**j; end; return s -/*──────────────────────────────────EXPER subroutine────────────────────*/ -exper: parse arg n -k=0; do tests; $.=0 /*repeat TESTS times, reset FOUND*/ - do n; r=random(1,n); if $.r then leave - $.r=1; k=k+1 /*bump the ctr. */ - end /*n*/ - end /*tests*/ -return k/tests -/*──────────────────────────────────FMTD subroutine─────────────────────*/ -fmtD: parse arg y,d; d=word(d 4,1); y=format(y,,d); parse var y w '.' f -if f=0 then return w || left('',d+1); return y +say ' N average exact % error' /*◄──title,header►───┐*/ +h= ' ─── ───────── ───────── ─────────'; pad=left('',3) /*◄──────┘*/ +say h + do #=1 for runs; ##=right(#,9) /*## is used for indenting the output.*/ + avg=fmtD(exact(#)) /*use four digits past decimal point. */ + exa=fmtD(exper(#)) /* " " " " " " */ + err=fmtD(abs(exa-avg)*100/avg) /* " " " " " " */ + say ## pad exa pad avg pad err /*display a line of statistics to term.*/ + end /*#*/ +say h /*display the final header (some bars).*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +!: procedure expose !.; parse arg z; if !.z\==0 then return !.z + !=1; do j=1 for z; !=!*j; !.j=!; end; /*factorial*/ return ! +/*────────────────────────────────────────────────────────────────────────────*/ +exact: parse arg x; s=0; do j=1 for x; s=s+!(x)/!(x-j)/x**j; end; return s +/*────────────────────────────────────────────────────────────────────────────*/ +exper: parse arg n; k=0; do tests; $.=0 /*do it TESTS times.*/ + do n; r=random(1,n); if $.r then leave + $.r=1; k=k+1 /*bump the counter. */ + end /*n*/ + end /*tests*/ + return k/tests +/*────────────────────────────────────────────────────────────────────────────*/ +fmtD: parse arg y,d; d=word(d 4,1); y=format(y,,d); parse var y w '.' f + if f=0 then return w || left('', d+1); return y diff --git a/Task/Average-loop-length/Scala/average-loop-length.scala b/Task/Average-loop-length/Scala/average-loop-length.scala new file mode 100644 index 0000000000..10eda602c8 --- /dev/null +++ b/Task/Average-loop-length/Scala/average-loop-length.scala @@ -0,0 +1,37 @@ +import scala.util.Random + +object AverageLoopLength extends App { + + val factorial: Stream[Double] = 1 #:: factorial.zip(Stream.from(1)).map(n => n._2 * factorial(n._2 - 1)) + + def expected(n: Int) = (for (i <- 1 to n) yield factorial(n) / Math.pow(n, i) / factorial(n - i)).sum + + def trial(n: Int):Double = { + var count = 0 + var x = 1 + var bits = 0 + + while ((bits & x) == 0) { + count = count + 1 + bits = bits | x + x = 1 << Random.nextInt(n) + } + count + } + + def tested(n: Int, times: Int) = (for (i <- 1 to times) yield trial(n)).sum / times + + val results = for (n <- 1 to 20; + avg = tested(n, 1000000); + theory = expected(n) + ) yield (n, avg, theory, (avg / theory - 1) * 100) + + + println("n avg exp diff") + println("------------------------------------") + results foreach { n => { + println(f"${n._1}%2d ${n._2}%2.6f ${n._3}%2.6f ${n._4}%2.3f%%") + } + } + +} diff --git a/Task/Averages-Arithmetic-mean/0815/averages-arithmetic-mean.0815 b/Task/Averages-Arithmetic-mean/0815/averages-arithmetic-mean.0815 new file mode 100644 index 0000000000..7663a7ae4a --- /dev/null +++ b/Task/Averages-Arithmetic-mean/0815/averages-arithmetic-mean.0815 @@ -0,0 +1,4 @@ +{x{+=<:2:x/%<:d:~$<:01:~><:02:~><:03:~><:04:~><:05:~><:06:~><:07:~><:08: +~><:09:~><:0a:~><:0b:~><:0c:~><:0d:~><:0e:~><:0f:~><:10:~><:11:~><:12:~> +<:13:~><:14:~><:15:~><:16:~><:17:~><:18:~><:19:~><:ffffffffffffffff:~>{x +{+>}:8f:{&={+>{~>&=x<:ffffffffffffffff:/#:8f:{{=<:19:x/% diff --git a/Task/Averages-Arithmetic-mean/360-Assembly/averages-arithmetic-mean.360 b/Task/Averages-Arithmetic-mean/360-Assembly/averages-arithmetic-mean.360 new file mode 100644 index 0000000000..eb994c61b5 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/360-Assembly/averages-arithmetic-mean.360 @@ -0,0 +1,27 @@ +AVGP CSECT + USING AVGP,12 + LR 12,15 + SR 3,3 i=0 + SR 6,6 sum=0 +LOOP CH 3,=AL2(NN-T-1) for i=1 to nn + BH ENDLOOP + L 2,T(3) t(i) + MH 2,=H'100' scaling factor=2 + AR 6,2 sum=sum+t(i) + LA 3,4(3) next i + B LOOP +ENDLOOP LR 5,6 sum + LA 4,0 + D 4,NN sum/nn + XDECO 5,Z edit binary + MVC U,Z+10 descale + MVI Z+10,C'.' + MVC Z+11(2),U + XPRNT Z,80 output + XR 15,15 + BR 14 +T DC F'10',F'9',F'8',F'7',F'6',F'5',F'4',F'3',F'2',F'1' +NN DC A((NN-T)/4) +Z DC CL80' ' +U DS CL2 + END AVGP diff --git a/Task/Averages-Arithmetic-mean/ALGOL-W/averages-arithmetic-mean.alg b/Task/Averages-Arithmetic-mean/ALGOL-W/averages-arithmetic-mean.alg new file mode 100644 index 0000000000..33ece8703e --- /dev/null +++ b/Task/Averages-Arithmetic-mean/ALGOL-W/averages-arithmetic-mean.alg @@ -0,0 +1,22 @@ +begin + % procedure to find the mean of the elements of a vector. % + % As the procedure can't find the bounds of the array for itself, % + % we pass them in lb and ub % + real procedure mean ( real array vector ( * ) + ; integer value lb + ; integer value ub + ) ; + begin + real sum; + assert( ub > lb ); % terminate the program if there are no elements % + sum := 0; + for i := lb until ub do sum := sum + vector( i ); + sum / ( ( ub + 1 ) - lb ) + end mean ; + + % test the mean procedure by finding the mean of 1.1, 2.2, 3.3, 4.4, 5.5 % + real array numbers ( 1 :: 5 ); + for i := 1 until 5 do numbers( i ) := i + ( i / 10 ); + r_format := "A"; r_w := 10; r_d := 2; % set fixed point output % + write( mean( numbers, 1, 5 ) ); +end. diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index c01bddc2cc..fe3354484a 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -1,32 +1,27 @@ #define system. -#define system'routines. +#define extensions. -// --- Sum --- - -#class MeanAction : BasePattern +#class(extension)op { - #field theValue. - #field theCount. - - #constructor new + #method average [ - theValue := Real new. - theCount := Integer new. - ] + #var aSum := Real new. + #var aCount := Integer new:0. - #method evaluate : aValue - [ - theCount += 1. + #var anEnumerator := self enumerator. - theValue += aValue. - ] + #loop (anEnumerator next)? + [ + aSum += anEnumerator get. + aCount += 1. + ]. - #method value = theValue / theCount. + ^ aSum / aCount. + ] } -// --- Program --- - #symbol program = [ - console writeLine:(MeanAction new foreach:(1, 2, 3, 4, 5, 6, 7, 8) value). + #var anArray := (1, 2, 3, 4, 5, 6, 7, 8). + console writeLine:"Arithmetic mean of {":anArray:"} is ":(anArray average). ]. diff --git a/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean.l b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-1.l similarity index 100% rename from Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean.l rename to Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-1.l diff --git a/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-2.l b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-2.l new file mode 100644 index 0000000000..19fadd4efd --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Emacs-Lisp/averages-arithmetic-mean-2.l @@ -0,0 +1,2 @@ +(setq x '[1 2 3 4]) +(string-to-number (calc-eval (format "vmean(%s)" x))) diff --git a/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx b/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx index fddfdee535..cef807d928 100644 --- a/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx +++ b/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx @@ -1,22 +1,22 @@ -/*REXX pgm finds the averages/arithmetic mean of several lists (vectors)*/ - @.1 = 10 9 8 7 6 5 4 3 2 1 - @.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11 - @.3 = '10 20 30 40 50 -100 4.7 -11e2' - @.4 = '1 2 3 4 five 6 7 8 9 10.1. ±2' - @.5 = 'World War I & World War II' - @.6 = +/*REXX program finds the averages/arithmetic mean of several lists (vectors).*/ + @.1 = 10 9 8 7 6 5 4 3 2 1 + @.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11 + @.3 = '10 20 30 40 50 -100 4.7 -11e2' + @.4 = '1 2 3 4 five 6 7 8 9 10.1. ±2' + @.5 = 'World War I & World War II' + @.6 = /*a null value. */ do j=1 for 6 - say 'numbers = ' @.j; say 'average = ' avg(@.j); say copies('═',60) + say 'numbers = ' @.j; say "average = " avg(@.j); say copies('═',60) end /*t*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────AVG subroutine──────────────────────*/ -avg: procedure; parse arg x; w=words(x); s=0; $=left('',20) -if w==0 then return 'N/A: ───[null vector.]' +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +avg: procedure; parse arg x; #=words(x); $=0 /*#: number of items. */ +if #==0 then return 'N/A: ───[null vector.]' /*No words? Return N/A*/ - do k=1 for w; _=word(x,k) - if datatype(_,'N') then do; s=s+_; iterate; end - say $ '***error!*** non-numeric: ' _; w=w-1 /*adjust W*/ - end /*k*/ + do k=1 for #; _=word(x,k) /*obtain a number.*/ + if datatype(_,'N') then do; $=$+_; iterate; end /*if numeric, add.*/ + say left('',20) "***error!*** non-numeric: " _; #=#-1 /*error; adjust #.*/ + end /*k*/ -if w==0 then return 'N/A: ───[no numeric values.]' -return s/max(1,w) +if #==0 then return 'N/A: ───[no numeric values.]' /*No nums? Return N/A.*/ +return $/max(1,#) /*return the average. */ diff --git a/Task/Averages-Arithmetic-mean/Rust/averages-arithmetic-mean.rust b/Task/Averages-Arithmetic-mean/Rust/averages-arithmetic-mean.rust index 14dfeeaea1..6283016058 100644 --- a/Task/Averages-Arithmetic-mean/Rust/averages-arithmetic-mean.rust +++ b/Task/Averages-Arithmetic-mean/Rust/averages-arithmetic-mean.rust @@ -1,15 +1,15 @@ fn sum(arr: &[f64]) -> f64 { - return arr.iter().fold(0.0, |p,q| p + *q); + arr.iter().fold(0.0, |p,&q| p + q) } fn mean(arr: &[f64]) -> f64 { - return sum(arr) / arr.len() as f64; + sum(arr) / arr.len() as f64 } fn main() { let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0]; - println!("mean of {}: {}", v, mean(v)); + println!("mean of {:?}: {:?}", v, mean(v)); let w = &[]; - println!("mean of {}: {}", w, mean(w)); + println!("mean of {:?}: {:?}", w, mean(w)); } diff --git a/Task/Averages-Arithmetic-mean/SQL/averages-arithmetic-mean.sql b/Task/Averages-Arithmetic-mean/SQL/averages-arithmetic-mean.sql new file mode 100644 index 0000000000..eb8bd3dab7 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/SQL/averages-arithmetic-mean.sql @@ -0,0 +1,5 @@ +create table "numbers" ("datapoint" integer); + +insert into "numbers" select rownum from tab; + +select sum("datapoint")/count(*) from "numbers"; diff --git a/Task/Averages-Arithmetic-mean/TI-83-BASIC/averages-arithmetic-mean.ti-83 b/Task/Averages-Arithmetic-mean/TI-83-BASIC/averages-arithmetic-mean.ti-83 new file mode 100644 index 0000000000..23847806c4 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/TI-83-BASIC/averages-arithmetic-mean.ti-83 @@ -0,0 +1 @@ +Mean(Ans diff --git a/Task/Averages-Arithmetic-mean/VBScript/averages-arithmetic-mean.vb b/Task/Averages-Arithmetic-mean/VBScript/averages-arithmetic-mean.vb new file mode 100644 index 0000000000..3201a0e9e1 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/VBScript/averages-arithmetic-mean.vb @@ -0,0 +1,11 @@ +Function mean(arr) + size = UBound(arr) + 1 + mean = 0 + For i = 0 To UBound(arr) + mean = mean + arr(i) + Next + mean = mean/size +End Function + +'Example +WScript.Echo mean(Array(3,1,4,1,5,9)) diff --git a/Task/Averages-Mean-angle/Clojure/averages-mean-angle-1.clj b/Task/Averages-Mean-angle/Clojure/averages-mean-angle-1.clj new file mode 100644 index 0000000000..cf03ef24ec --- /dev/null +++ b/Task/Averages-Mean-angle/Clojure/averages-mean-angle-1.clj @@ -0,0 +1,12 @@ +(defn mean-fn + [k coll] + (let [n (count coll) + trig (get {:sin #(Math/sin %) :cos #(Math/cos %)} k)] + (* (/ 1 n) (reduce + (map trig coll))))) + +(defn mean-angle + [degrees] + (let [radians (map #(Math/toRadians %) degrees) + a (mean-fn :sin radians) + b (mean-fn :cos radians)] + (Math/toDegrees (Math/atan2 a b)))) diff --git a/Task/Averages-Mean-angle/Clojure/averages-mean-angle-2.clj b/Task/Averages-Mean-angle/Clojure/averages-mean-angle-2.clj new file mode 100644 index 0000000000..2723af0d9a --- /dev/null +++ b/Task/Averages-Mean-angle/Clojure/averages-mean-angle-2.clj @@ -0,0 +1,8 @@ +(mean-angle [350 10]) +;=> -1.614809932057922E-15 + +(mean-angle [90 180 270 360]) +;=> -90.0 + +(mean-angle [10 20 30]) +;=> 19.999999999999996 diff --git a/Task/Averages-Mean-angle/J/averages-mean-angle-1.j b/Task/Averages-Mean-angle/J/averages-mean-angle-1.j index 00f37b5218..2a883f44d7 100644 --- a/Task/Averages-Mean-angle/J/averages-mean-angle-1.j +++ b/Task/Averages-Mean-angle/J/averages-mean-angle-1.j @@ -1 +1 @@ -avgAngleD=: (_1 { [: (**|)&.+.@(+/ % #)&.(*.inv) 1,.])&.(1r180p1&*) +avgAngleD=: 360|(_1 { [: (**|)&.+.@(+/ % #)&.(*.inv) 1,.])&.(1r180p1&*) diff --git a/Task/Averages-Mean-angle/J/averages-mean-angle-2.j b/Task/Averages-Mean-angle/J/averages-mean-angle-2.j index 7d2fd083f5..b1d8731344 100644 --- a/Task/Averages-Mean-angle/J/averages-mean-angle-2.j +++ b/Task/Averages-Mean-angle/J/averages-mean-angle-2.j @@ -3,4 +3,4 @@ toComplex=: *.inv NB. maps integer pairs mean=: +/ % # NB. calculate arithmetic mean roundComplex=: (* * |)&.+. NB. discard an extraneous least significant bit of precision from a complex value whose magnitude is in the vicinity of 1 avgAngleR=: _1 { [: roundComplex@mean&.toComplex 1 ,. ] NB. calculate average angle in radians -avgAngleD=: avgAngleR&.rfd +avgAngleD=: 360|avgAngleR&.rfd NB. calculate average angle in degrees diff --git a/Task/Averages-Mean-angle/J/averages-mean-angle-3.j b/Task/Averages-Mean-angle/J/averages-mean-angle-3.j index 885df3edfe..9125ef0137 100644 --- a/Task/Averages-Mean-angle/J/averages-mean-angle-3.j +++ b/Task/Averages-Mean-angle/J/averages-mean-angle-3.j @@ -4,3 +4,7 @@ 0 avgAngleD 10 20 30 20 + avgAngleD 20 350 +5 + avgAngleD 10 340 +355 diff --git a/Task/Averages-Mean-angle/JavaScript/averages-mean-angle.js b/Task/Averages-Mean-angle/JavaScript/averages-mean-angle.js new file mode 100644 index 0000000000..e139007ef2 --- /dev/null +++ b/Task/Averages-Mean-angle/JavaScript/averages-mean-angle.js @@ -0,0 +1,18 @@ +function sum(a) { + s = 0; + for (var i in a) s += a[i]; + return s; +} + +function degToRad(a) { + return Math.PI/180*a; +} + +function meanAngleDeg(a) { + return 180/Math.PI*Math.atan2(sum(a.map(degToRad).map(Math.sin))/a.length,sum(a.map(degToRad).map(Math.cos))/a.length); +} + +var a = [350, 10], b = [90, 180, 270, 360], c =[10, 20, 30]; +console.log(meanAngleDeg(a)); +console.log(meanAngleDeg(b)); +console.log(meanAngleDeg(c)); diff --git a/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx b/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx index f99093ee21..f94e708a77 100644 --- a/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx +++ b/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx @@ -1,56 +1,57 @@ -/*REXX program computes the mean angle (angles expressed in degrees). */ -numeric digits 50 /*use fifty digits of precision, */ - showDig=10 /*··· but only display 10 digits.*/ +/*REXX program computes the mean angle (the angles expressed in degrees). */ +numeric digits 50 /*use 50 decimal digits of precision,*/ + showDig=10 /* but only display ten decimal digits.*/ # = 350 10 ; say showit(#, meanAngleD(#) ) # = 90 180 270 360 ; say showit(#, meanAngleD(#) ) # = 10 20 30 ; say showit(#, meanAngleD(#) ) -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────MEANANGD subroutine─────────────────*/ -meanAngleD: procedure; parse arg x; numeric digits digits()+digits()%4 -_sin=0; _cos=0; n=words(x); do j=1 for n; !=d2r(word(x,j)) - _sin = _sin + sin(!) - _cos = _cos + cos(!) - end /*j*/ -return r2d(atan2(_sin/n, _cos/n)) -/*─────────────────────────────one─line subroutines──────────────────────────────────────────*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────subroutines──────────────────────────────────────────────*/ .sinCos: arg z,_,i; x=x*x; do k=2 by 2 until p=z; p=z; _=-_*x/(k*(k+i)); z=z+_; end; return z $fuzz: return min(arg(1), max(1, digits() - arg(2) ) ) -acos: procedure; parse arg x; return pi() * .5 - asin(x) +acos: procedure; parse arg x; return pi() * .5 - asin(x) atan: parse arg x; if abs(x)=1 then return pi()*.25 * sign(x); return asin(x/sqrt(1 + x*x)) d2d: return arg(1) // 360 -d2r: return r2r(d2d(arg(1)) / 180 * pi() ) -r2d: return d2d((r2r(arg(1)) / pi()) * 180) -r2r: return arg(1) // (pi() * 2) +d2r: return r2r(d2d(arg(1)) / 180 * pi() ) +r2d: return d2d((r2r(arg(1)) / pi()) * 180) +r2r: return arg(1) // (pi() * 2) p: return word(arg(1), 1) pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862;return pi -/*───────────────────────────────────ASIN subroutine────────────────────*/ -asin: procedure; parse arg x 1 z 1 o 1 p; xx=x*x + +asin: procedure; parse arg x 1 z 1 o 1 p; xx=x*x if xx>=.5 then return sign(x) * acos(sqrt(1-xx)) - do j=2 by 2 until p=z; p=z; o=o*xx*(j-1)/j; z=z+o/(j+1); end - return z /* [↑] compute until no noise.*/ -/*───────────────────────────────────ATAN2 subroutine───────────────────*/ + do j=2 by 2 until p=z; p=z; o=o*xx*(j-1)/j; z=z+o/(j+1); end + return z /* [↑] compute until no more noise. */ + atan2: procedure; parse arg y,x; call pi; s=sign(y) select - when x=0 then z=s * pi * .5 - when x<0 then if y=0 then z=pi; else z=s*(pi-abs(atan(y/x))) + when x=0 then z=s * pi * .5 + when x<0 then if y=0 then z=pi; else z=s*(pi-abs(atan(y/x))) otherwise z=s * atan(y/x) end /*select*/; return z -/*───────────────────────────────────COS subroutine─────────────────────*/ -cos: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3) - a=abs(x); if a=0 then return 1; if a=pi then return -1 - if a=pi*.5 | a=pi*1.5 then return 0; if a=pi/3 then return .5 - if a=pi*2/3 then return -.5; return .sinCos(1, 1, -1) -/*───────────────────────────────────SHOWIT subroutine──────────────────*/ + +cos: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(6, 3) + a=abs(x); if a=0 then return 1; if a=pi then return -1 + if a=pi*.5 | a=pi*1.5 then return 0; if a=pi/3 then return .5 + if a=pi*2/3 then return -.5; return .sinCos(1, 1, -1) + + +meanAngleD: procedure; parse arg x; numeric digits digits()+digits()%4 + _sin=0; _cos=0; n=words(x); do j=1 for n; !=d2r(word(x,j)) + _sin=_sin + sin(!) + _cos=_cos + cos(!) + end /*j*/ + return r2d(atan2(_sin/n, _cos/n)) + showit: procedure expose showDig; numeric digits showDig; parse arg a,mA return left('angles='a,30) 'mean angle=' format(mA,,showDig,0)/1 -/*───────────────────────────────────COS subroutine─────────────────────*/ + sin: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3) if x=pi*.5 then return 1; if x==pi*1.5 then return -1 if abs(x)=pi | x=0 then return 0; return .sinCos(x, x, +1) -/*───────────────────────────────────SQRT subroutine────────────────────*/ -sqrt: procedure; parse arg x,i; if x=0 then return 0; d=digits(); m.=11 - if x<0 then i='i'; numeric digits 11; numeric form; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2 - do j=0 while p>9; m.j=p; p=p%2+1; end /*j*/ - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k - g=.5*(g+x/g); end /*k*/; numeric digits d; return g/1 + +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Averages-Mean-time-of-day/Fortran/averages-mean-time-of-day.f b/Task/Averages-Mean-time-of-day/Fortran/averages-mean-time-of-day.f new file mode 100644 index 0000000000..9928c2e53e --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Fortran/averages-mean-time-of-day.f @@ -0,0 +1,70 @@ +program mean_time_of_day + implicit none + integer(kind=4), parameter :: dp = kind(0.0d0) + + type time_t + integer(kind=4) :: hours, minutes, seconds + end type + + character(len=8), dimension(4), parameter :: times = & + (/ '23:00:17', '23:40:20', '00:12:45', '00:17:19' /) + real(kind=dp), dimension(size(times)) :: angles + real(kind=dp) :: mean + + angles = time_to_angle(str_to_time(times)) + mean = mean_angle(angles) + if (mean < 0) mean = 360 + mean + + write(*, fmt='(I2.2, '':'', I2.2, '':'', I2.2)') angle_to_time(mean) +contains + real(kind=dp) function mean_angle(angles) + real(kind=dp), dimension(:), intent (in) :: angles + real(kind=dp) :: x, y + + x = sum(sin(radians(angles)))/size(angles) + y = sum(cos(radians(angles)))/size(angles) + + mean_angle = degrees(atan2(x, y)) + end function + + elemental real(kind=dp) function radians(angle) + real(kind=dp), intent (in) :: angle + real(kind=dp), parameter :: pi = 4d0*atan(1d0) + radians = angle/180*pi + end function + + elemental real(kind=dp) function degrees(angle) + real(kind=dp), intent (in) :: angle + real(kind=dp), parameter :: pi = 4d0*atan(1d0) + degrees = 180*angle/pi + end function + + elemental type(time_t) function str_to_time(str) + character(len=*), intent (in) :: str + ! Assuming time in format hh:mm:ss + read(str, fmt='(I2, 1X, I2, 1X, I2)') str_to_time + end function + + elemental real(kind=dp) function time_to_angle(time) result (res) + type(time_t), intent (in) :: time + + real(kind=dp) :: seconds + real(kind=dp), parameter :: seconds_in_day = 24*60*60 + + seconds = time%seconds + 60*time%minutes + 60*60*time%hours + res = 360*seconds/seconds_in_day + end function + + elemental type(time_t) function angle_to_time(angle) + real(kind=dp), intent (in) :: angle + + real(kind=dp) :: seconds + real(kind=dp), parameter :: seconds_in_day = 24*60*60 + + seconds = seconds_in_day*angle/360d0 + angle_to_time%hours = int(seconds/60d0/60d0) + seconds = mod(seconds, 60d0*60d0) + angle_to_time%minutes = int(seconds/60d0) + angle_to_time%seconds = mod(seconds, 60d0) + end function +end program diff --git a/Task/Averages-Mean-time-of-day/Haskell/averages-mean-time-of-day.hs b/Task/Averages-Mean-time-of-day/Haskell/averages-mean-time-of-day.hs new file mode 100644 index 0000000000..4ccb20f00a --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Haskell/averages-mean-time-of-day.hs @@ -0,0 +1,27 @@ +import Data.Complex (cis, phase) +import Data.List.Split (splitOn) +import Text.Printf (printf) + +timeToRadians :: String -> Float +timeToRadians time = + let hours:minutes:seconds:_ = splitOn ":" time + s = fromIntegral (read seconds :: Int) + m = fromIntegral (read minutes :: Int) + h = fromIntegral (read hours :: Int) + in (2*pi)*(h+ (m + s/60.0 )/60.0 )/24.0 + +radiansToTime :: Float -> String +radiansToTime r = + let tau = pi*2 + (_,fDay) = properFraction (r / tau) :: (Int, Float) + fDayPositive = if fDay < 0 then 1.0+fDay else fDay + (hours, fHours) = properFraction $ 24.0 * fDayPositive + (minutes, fMinutes) = properFraction $ 60.0 * fHours + seconds = 60.0 * fMinutes + in printf "%0d" (hours::Int) ++ ":" ++ printf "%0d" (minutes::Int) ++ ":" ++ printf "%0.0f" (seconds::Float) + +meanAngle :: [Float] -> Float +meanAngle = phase . sum . map cis + +main :: IO () +main = putStrLn $ radiansToTime $ meanAngle $ map timeToRadians ["23:00:17", "23:40:20", "00:12:45", "00:17:19"] diff --git a/Task/Averages-Median/ALGOL-68/averages-median.alg b/Task/Averages-Median/ALGOL-68/averages-median.alg new file mode 100644 index 0000000000..6c96006024 --- /dev/null +++ b/Task/Averages-Median/ALGOL-68/averages-median.alg @@ -0,0 +1,65 @@ +INT max_elements = 1000000; + +# Return the k-th smallest item in array x of length len # +PROC quick_select = (INT k, REF[]REAL x) REAL: + BEGIN + + PROC swap = (INT a, b) VOID: + BEGIN + REAL t = x[a]; + x[a] := x[b]; x[b] := t + END; + + INT left := 1, right := UPB x; + INT pos, i; + REAL pivot; + + WHILE left < right DO + pivot := x[k]; + swap (k, right); + pos := left; + FOR i FROM left TO right DO + IF x[i] < pivot THEN + swap (i, pos); + pos +:= 1 + FI + OD; + swap (right, pos); + IF pos = k THEN break FI; + IF pos < k THEN left := pos + 1 + ELSE right := pos - 1 + FI + OD; +break: + SKIP; + x[k] + END; + + # Initialize random length REAL array with random doubles # + INT length = ENTIER (next random * max_elements); + [length]REAL x; + FOR i TO length DO + x[i] := (next random * 1e6 - 0.5e6) + OD; + + REAL median := + IF NOT ODD length THEN + # Even number of elements, median is average of middle two # + (quick_select (length % 2, x) + quick_select(length % 2 - 1, x)) / 2 + ELSE + # select middle element # + quick_select(length % 2, x) + FI; + + # Sanity testing of median # + INT less := 0, more := 0, eq := 0; + FOR i TO length DO + IF x[i] < median THEN less +:= 1 + ELIF x[i] > median THEN more +:= 1 + ELSE eq +:= 1 + FI + OD; + print (("length: ", whole (length,0), new line, "median: ", median, new line, + "<: ", whole (less,0), new line, + ">: ", whole (more, 0), new line, + "=: ", whole (eq, 0), new line)) diff --git a/Task/Averages-Median/Elena/averages-median.elena b/Task/Averages-Median/Elena/averages-median.elena index 8923f97b31..837821c0a2 100644 --- a/Task/Averages-Median/Elena/averages-median.elena +++ b/Task/Averages-Median/Elena/averages-median.elena @@ -1,25 +1,31 @@ #define system. #define system'routines. +#define system'math. #define extensions. -#define extensions'math. -#symbol median = (:anArray) -[ - #var aSorted := arrayControl sort:(anArray~indexable array). +#class(extension) op +{ + #method median + [ + #var aSorted := self ascendant. - #var aLen := aSorted length. - ^ aLen => - 0 ? [ nil ] - ! [ - #var aMiddleIndex := aLen / 2. - ^ (modulus:aLen:2) => - 0 ? [ (aSorted@(aMiddleIndex - 1) + aSorted@aMiddleIndex) / 2 ] - ! [ aSorted@aMiddleIndex ]. - ]. -]. + #var aLen := aSorted length. + (aLen == 0) + ? [ ^ nil. ] + ! [ + #var aMiddleIndex := aLen / 2. + (aLen mod:2 == 0) + ? [ ^ (aSorted@(aMiddleIndex - 1) + aSorted@aMiddleIndex) / 2. ] + ! [ ^ aSorted@aMiddleIndex. ]. + ]. + ] +} #symbol program = [ - consoleEx writeLine:(median:(4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r)). - consoleEx writeLine:(median:(4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r)). + #var a1 := (4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r). + #var a2 := (4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r). + + console writeLine:"median of (":a1:") is ":(a1 median). + console writeLine:"median of (":a2:") is ":(a2 median). ]. diff --git a/Task/Averages-Median/Rust/averages-median.rust b/Task/Averages-Median/Rust/averages-median.rust new file mode 100644 index 0000000000..c6b1b27739 --- /dev/null +++ b/Task/Averages-Median/Rust/averages-median.rust @@ -0,0 +1,15 @@ +fn median(mut xs: Vec) -> f64 { + // sort in ascending order, panic on f64::NaN + xs.sort_by(|x,y| x.partial_cmp(y).unwrap() ); + let n = xs.len(); + if n % 2 == 0 { + (xs[n/2] + xs[n/2 + 1]) / 2.0 + } else { + xs[n/2] + } +} + +fn main() { + let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.]; + println!("{:?}", median(nums)) +} diff --git a/Task/Averages-Mode/Elena/averages-mode.elena b/Task/Averages-Mode/Elena/averages-mode.elena index f33d3a233d..0b67b5178f 100644 --- a/Task/Averages-Mode/Elena/averages-mode.elena +++ b/Task/Averages-Mode/Elena/averages-mode.elena @@ -3,39 +3,35 @@ #define system'collections. #define extensions. -// Averages/Mode - -#symbol mode = (:anArray) -[ - #var aCountMap := Dictionary new &default:0. - control foreach:anArray &do: anItem +#class(extension) op +{ + #method mode [ - aCountMap set &key:anItem &value:(aCountMap getAt &key:anItem + 1). - ]. - - listControl sort:aCountMap &with: (:p:n) - [ p value > n value ]. + #var aCountMap := Dictionary new &default:0. + self run &each: anItem + [ + aCountMap@anItem := aCountMap@anItem + 1. + ]. - #var aResult := List new. + aCountMap := aCountMap array_list sort:(:p:n) [ p > n ]. - #var aMax := aCountMap First value. - control foreach:aCountMap &do: anItem - [ - aMax == anItem value - ? [ aResult += anItem key. ]. - ]. + #var aMax := aCountMap firstMember. - ^ listControl toArray:aResult. -]. + ^ aCountMap + filter &each:kv [ aMax safeEqual:kv ] + select &each:kv [ kv key ] + toArray. + ] +} #symbol program = [ #var anArray1 := (1, 1, 2, 4, 4). #var anArray2 := (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17). + #var anArray3 := (1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"). - #var aMode1 := mode:anArray1. - #var aMode2 := mode:anArray2. - - consoleEx writeLine:"mode of (":anArray1:") is (":aMode1:")". - consoleEx writeLine:"mode of (":anArray2:") is (":aMode2:")". + console + writeLine:"mode of (":anArray1:") is (":(anArray1 mode):")" + writeLine:"mode of (":anArray2:") is (":(anArray2 mode):")" + writeLine:"mode of (":anArray3:") is (":(anArray3 mode):")". ]. diff --git a/Task/Averages-Mode/Elixir/averages-mode.elixir b/Task/Averages-Mode/Elixir/averages-mode.elixir new file mode 100644 index 0000000000..4277247750 --- /dev/null +++ b/Task/Averages-Mode/Elixir/averages-mode.elixir @@ -0,0 +1,14 @@ +defmodule Average do + def mode(list) do + gb = Enum.group_by(list, &(&1)) + max = Enum.map(gb, fn {_,val} -> length(val) end) |> Enum.max + for {key,val} <- gb, length(val)==max, do: key + end +end + +lists = [[3,1,4,1,5,9,2,6,5,3,5,8,9], + [1, 2, "qwe", "asd", 1, 2, "qwe", "asd", 2, "qwe"]] +Enum.each(lists, fn list -> + IO.puts "mode: #{inspect list}" + IO.puts " => #{inspect Average.mode(list)}" +end) diff --git a/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx b/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx index d596c23098..4bc9d89e74 100644 --- a/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx +++ b/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx @@ -1,68 +1,57 @@ -/*REXX program to compute/show Pythagorean means [Amean, Gmean, Hmean].*/ -parse arg n . /*maybe get an optional argument.*/ -if n=='' then n=10 /*None specified? Assume default*/ - /*══════════════════compute Amean [Arithmetic mean]*/ -sum=0; do j=1 for n - @.j=j /*populate the stemmed array @. */ - sum=sum+@.j /*compute the sum of all elements*/ - end /*j*/ -Amean=sum/n /*calculate the Amean. */ -say 'Amean =' Amean /*show and tell Amean. */ - /*══════════════════compute Gmean [Geometric mean].*/ -prod=1; do k=1 for n - prod=prod*@.k /*comp. product of all elements. */ - end /*k*/ -Gmean=iroot(prod,n) /*calculate the Gmean. */ -say 'Gmean =' Gmean /*show and tell Gmean. */ - /*══════════════════compute Hmean [Harmonic mean]. */ -rsum=0; do m=1 for n - rsum=rsum+1/@.m /*compute the sum of reciprocals.*/ - end /*m*/ -Hmean=n/rsum /*calculate the Hmean. */ -say 'Hmean =' Hmean /*show and tell Hmean. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────IROOT subroutine────────────────────*/ -iroot: procedure; arg x 1 ox,y 1 oy /*get both args, and also a copy.*/ -if x=0 | x=1 then return x /*handle special case of 0 & 1. */ -if y=0 then return 1 /*handle special case of root 0. */ -if y=1 then return x /*handle special case of root 1. */ -if x<0 & y//2==0 then do /*check for illegal combination. */ - say; say '*** error! *** (from IROOT):'; say - say 'root' y "can't be even if 1st argument is < 0." - say; return '[n/a]' /*return a not applicable.*/ +/*REXX program to compute and display Pythagorean means [Amean, Gmean, Hmean].*/ +parse arg n . /*obtain the optional argument from CL.*/ +if n=='' then n=10 /*None specified? Then assume default.*/ +sum=0 /*░░░░░░░░░░░░░░░░░░compute Amean [Arithmetic mean]░░░░░░*/ + do a=1 for n /*populate the array and calculate sum.*/ + @.a=a /*populate the stemmed array @. */ + sum=sum + @.a /*compute the sum of all the elements. */ + end /*a*/ +Amean=sum/n /*calculate the arithmetic mean. */ +say 'Amean =' Amean /*display " " " */ +prod=1 /*░░░░░░░░░░░░░░░░░░compute Gmean [Geometric mean]░░░░░░░*/ + do g=1 for n + prod=prod * @.g /*compute the product of all elements. */ + end /*g*/ +Gmean=Iroot(prod,n) /*calculate the geometric mean. */ +say 'Gmean =' Gmean /*display " " " */ +rsum=0 /*░░░░░░░░░░░░░░░░░░compute Hmean [Harmonic mean]░░░░░░░░*/ + do r=1 for n + rsum=rsum + 1/@.r /*compute the sum of the reciprocals. */ + end /*r*/ +Hmean=n/rsum /*calculate the harmonic mean. */ +say 'Hmean =' Hmean /*display " " " */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +Iroot: procedure; arg x 1 ox, y 1 oy /*get both args, and also a copy of X&Y*/ +if x=0 | x=1 then return x /*handle special case of zero and unity*/ +if y=0 then return 1 /* " " " " a zero root.*/ +if y=1 then return x /* " " " " a unity root.*/ +if x<0 & y//2==0 then do /*check for an illegal combination. */ + say; say '*** error! *** (from Iroot):'; say + say 'root' y "can't be even if first argument is < 0." + say; return '[n/a]' /*return a "not applicable" text.*/ end -x=abs(x) /*use the absolute value for X. */ -y=abs(y) /*use the absolute value for root*/ -digO=digits() /*save original accuracy (digits)*/ -a=digO+5 /*use an extra 5 digs (accuracy).*/ -g=(x+1)/y**y /*use this as the 1st guesstimate*/ -m=y-1 /*use this as a fast [root-1]. */ -numeric fuzz 3 /*3 fuzz digits for comparisons. */ -d=5 /*start with 5 digits accuracy. When the */ - /*DIGITS is large, CPU time is wasted on */ - /*large accuracies when the guess isn't */ - /*close to the final answer. It's best to*/ - /*take baby steps before going full bore */ - /*throttle and putting the pedal to the */ - /*metal, getting it in high gear, and */ - /*then turning the volume all the way up. */ +x=abs(x); y=abs(y); m=y-1 /*use the absolute value for X and Y. */ +digO=digits() /*save original accuracy (decimal digs)*/ +a=digO+5 /*use an extra five digs " " */ +g=(x+1)/y**y /*use this as the first guesstimate. */ +numeric fuzz 3 /*use three fuzz digits for comparisons*/ +d=5 /*Start with 5 digits accuracy. When the digits is large, */ + /*CPU time is wasted when the guess isn't close to the root.*/ - do forever /* ◄─────────────────┐ keep plugging as digs increases*/ - d=min(d+d,a) /* │ limit the digits to orig digs+5*/ - numeric digits d /* │ keep increasing the accuracy. */ - old=0 /* │ define old (guess). */ - /* │ */ - do forever /* ◄────────────┐ │ keep plugging at the Yth root.*/ - _=(m*g**y+x)/y/g**m /* │ │ this is the nitty-gritty stuff.*/ - if _=g | _=old then leave /* │ │ are we close enough yet ? */ - old=g /* │ │ save guess in old (guess). */ - g=_ /* │ │ set Guess to what's been calc. */ - end /*forever ►────────────┘ │ */ - /* │ */ - if d==a then leave /* │ are we at the desired accuracy?*/ - end /*forever ►───────────────┘ */ + do forever /* ◄──────────────────┐ keep plugging as digits are increased*/ + d=min(d+d,a) /* │ limit the digits to original digs+5. */ + numeric digits d /* │ keep increasing the accuracy. */ + old=. /* │ define the old (guess). */ + /* │ */ + do forever /* ◄─────────────┐ │ keep plugging at the Yth root. */ + _=(m*g**y+x)/y/g**m /* │ │ this is the nitty─gritty stuff. */ + if _=g | _=old then leave /* │ │ are we close enough yet ? */ + old=g; g=_ /* │ │ save guess to old); set new guess. */ + end /*forever ►─────────────┘ │ */ + /* │ */ + if d==a then leave /* │ are we at the desired accuracy ? */ + end /*forever ►────────────────┘ */ -_=g*sign(ox) /*adjust for the sign of orig X. */ -if oy<0 then _=1/_ /*adjust for negative root. */ -numeric digits digO /*restore the original digits. */ -return _/1 /*normalize result to orig digits*/ +_=g*sign(ox); if oy<0 then _=1/_ /*adjust for original X sing; neg. root*/ +numeric digits digO; return _/1 /*normalize to original decimal digits.*/ diff --git a/Task/Averages-Pythagorean-means/VBScript/averages-pythagorean-means.vb b/Task/Averages-Pythagorean-means/VBScript/averages-pythagorean-means.vb new file mode 100644 index 0000000000..e087a2174d --- /dev/null +++ b/Task/Averages-Pythagorean-means/VBScript/averages-pythagorean-means.vb @@ -0,0 +1,27 @@ +Function arithmetic_mean(arr) + sum = 0 + For i = 0 To UBound(arr) + sum = sum + arr(i) + Next + arithmetic_mean = sum / (UBound(arr)+1) +End Function + +Function geometric_mean(arr) + product = 1 + For i = 0 To UBound(arr) + product = product * arr(i) + Next + geometric_mean = product ^ (1/(UBound(arr)+1)) +End Function + +Function harmonic_mean(arr) + sum = 0 + For i = 0 To UBound(arr) + sum = sum + (1/arr(i)) + Next + harmonic_mean = (UBound(arr)+1) / sum +End Function + +WScript.StdOut.WriteLine arithmetic_mean(Array(1,2,3,4,5,6,7,8,9,10)) +WScript.StdOut.WriteLine geometric_mean(Array(1,2,3,4,5,6,7,8,9,10)) +WScript.StdOut.WriteLine harmonic_mean(Array(1,2,3,4,5,6,7,8,9,10)) diff --git a/Task/Averages-Root-mean-square/ALGOL-W/averages-root-mean-square.alg b/Task/Averages-Root-mean-square/ALGOL-W/averages-root-mean-square.alg new file mode 100644 index 0000000000..24d7e96c31 --- /dev/null +++ b/Task/Averages-Root-mean-square/ALGOL-W/averages-root-mean-square.alg @@ -0,0 +1,21 @@ +begin + % computes the root-mean-square of an array of numbers with % + % the specified lower bound (lb) and upper bound (ub) % + real procedure rms( real array numbers ( * ) + ; integer value lb + ; integer value ub + ) ; + begin + real sum; + sum := 0; + for i := lb until ub do sum := sum + ( numbers(i) * numbers(i) ); + sqrt( sum / ( ( ub - lb ) + 1 ) ) + end rms ; + + % test the rms procedure with the numbers 1 to 10 % + real array testNumbers( 1 :: 10 ); + for i := 1 until 10 do testNumbers(i) := i; + r_format := "A"; r_w := 10; r_d := 4; % set fixed point output % + write( "rms of 1 .. 10: ", rms( testNumbers, 1, 10 ) ); + +end. diff --git a/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-2.l b/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-2.l index 5795de2d6f..aeb75d7723 100644 --- a/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-2.l +++ b/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-2.l @@ -3,4 +3,4 @@ (sqrt (/ (apply '+ (cl-map 'list '* nums nums)) (length nums)))) -(rms '(1 2 3 4 5 6 7 8 9 10)) +(rms (number-sequence 1 10)) diff --git a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-2.julia b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-2.julia index 881332dcfd..a7ee4b2c4f 100644 --- a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-2.julia +++ b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-2.julia @@ -1 +1 @@ -sqrt(sum(x -> x*x, A) / length(A)) +sqrt(mean(A.^2.)) diff --git a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-3.julia b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-3.julia index 1eeb684f14..881332dcfd 100644 --- a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-3.julia +++ b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-3.julia @@ -1,7 +1 @@ -function rms(A) - s = 0.0 - for a in A - s += a*a - end - return sqrt(s / length(A)) -end +sqrt(sum(x -> x*x, A) / length(A)) diff --git a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-4.julia b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-4.julia index f133058c5a..1eeb684f14 100644 --- a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-4.julia +++ b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-4.julia @@ -1 +1,7 @@ -norm(A) / sqrt(length(A)) +function rms(A) + s = 0.0 + for a in A + s += a*a + end + return sqrt(s / length(A)) +end diff --git a/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-5.julia b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-5.julia new file mode 100644 index 0000000000..f133058c5a --- /dev/null +++ b/Task/Averages-Root-mean-square/Julia/averages-root-mean-square-5.julia @@ -0,0 +1 @@ +norm(A) / sqrt(length(A)) diff --git a/Task/Averages-Root-mean-square/REXX/averages-root-mean-square.rexx b/Task/Averages-Root-mean-square/REXX/averages-root-mean-square.rexx index 2c66552434..3a9d3df5ef 100644 --- a/Task/Averages-Root-mean-square/REXX/averages-root-mean-square.rexx +++ b/Task/Averages-Root-mean-square/REXX/averages-root-mean-square.rexx @@ -1,16 +1,18 @@ -/*REXX program computes the root mean square of a series of numbers. */ -parse arg n . /*get the argument (maybe). */ -if n=='' then n=10 /*Not specified? Then assume 10.*/ -numeric digits 50 /*let's go a little overboard. */ -sum=0 /*sum of numbers squared (so far)*/ - do j=1 for n /*step through N integers. */ - sum=sum+j**2 /*sum the squares of the integers*/ +/*REXX program computes and displays the root mean square of a number sequence*/ +parse arg n . /*obtain the optional argument from CL.*/ +if n=='' then n=10 /*Not specified? Then use the default.*/ +numeric digits 50 /*go a little overboard on decimal digs*/ +sum=0 /*the sum of numbers squared (so far).*/ + do j=1 for n /*process each of the N integers. */ + sum=sum+j**2 /*sum the squares of the integers. */ end /*j*/ -rms=sqrt(sum/n) /*divide by N, then get SQRT. */ -say 'root mean square for 1──►'n "is" rms /*display it.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SQRT subroutine─────────────────────────*/ -sqrt: procedure; parse arg x;if x=0 then return 0;d=digits();numeric digits 11 -numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2 -p=d+d%4+2; m.=11; do j=0 while p>9; m.j=p; p=p%2+1; end; do k=j+5 to 0 by -1 -if m.k>11 then numeric digits m.k;g=.5*(g+x/g);end;numeric digits d;return g/1 +rms=sqrt(sum/n) /*divide by N, then calculate the SQRT.*/ +say 'root mean square for 1──►'n "is" rms /*display the RMS. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Averages-Simple-moving-average/360-Assembly/averages-simple-moving-average.360 b/Task/Averages-Simple-moving-average/360-Assembly/averages-simple-moving-average.360 new file mode 100644 index 0000000000..c10842e9f9 --- /dev/null +++ b/Task/Averages-Simple-moving-average/360-Assembly/averages-simple-moving-average.360 @@ -0,0 +1,88 @@ +* Averages/Simple moving average 26/08/2015 +AVGSMA CSECT + USING AVGSMA,R12 + LR R12,R15 + ST R14,SAVER14 + ZAP II,=P'0' ii=0 + LA R7,1 + LH R3,NA + SRA R3,1 na/2 +LOOPA CR R7,R3 do i=1 to na/2 + BH ELOOPA + AP II,=P'1000' ii=ii+1000 + LR R1,R7 i + MH R1,=H'6' + LA R4,A-6(R1) + MVC 0(6,R4),II a(i)=ii + LH R1,NA na + SR R1,R7 -i + MH R1,=H'6' + LA R4,A(R1) + MVC 0(6,R4),II a(na+1-i)=ii + LA R7,1(R7) + B LOOPA +ELOOPA XPRNT =CL30' n sma3 sma5 ',30 + XPRNT =CL30' ----- ----------- -----------',30 + LA R7,1 i=1 +LOOP CH R7,NA do i=1 to na + BH RETURN + STH R7,N n=i + XDECO R7,C i + MVC BUF+1(5),C+7 + MVC P,=H'3' p=3 + BAL R14,SMA + MVC C(13),EDMASK + ED C(13),SS sma(3,i) + MVC BUF+7(11),C+2 + MVC P,=H'5' p=5 + BAL R14,SMA + MVC C(13),EDMASK + ED C(13),SS sma(5,i) + MVC BUF+19(11),C+2 + XPRNT BUF,30 output i,sma3,sma5 + LA R7,1(R7) + B LOOP +* ***** sub sma(p,n) returns(PL6) +SMA LH R5,N + SH R5,P + A R5,=F'1' ia=n-p+1 + C R5,=F'1' + BH OKIA + LA R5,1 ia=1 +OKIA LH R6,NA ib=na + CH R6,N + BL OKIB + LH R6,N ib=n +OKIB ZAP II,=P'0' ii=0 + ZAP SS,=P'0' ss=0 + LR R3,R5 k=ia +LOOPK CR R3,R6 do k=ia to ib + BH ELOOPK + AP II,=P'1' ii=ii+1 + LR R1,R3 + MH R1,=H'6' + LA R4,A-6(R1) + MVC C(6),0(R4) ss=ss+a(k) + AP SS,C(6) + LA R3,1(R3) + B LOOPK +ELOOPK ZAP C,SS + DP C,II + ZAP SS,C(10) ss=ss/ii + BR R14 +RETURN L R14,SAVER14 restore caller address + XR R15,R15 + BR R14 +SAVER14 DS F +NN EQU 10 +NA DC AL2(NN) +A DS (NN)PL6 +II DS PL6 +SS DS PL6 +P DS H +N DS H +C DS CL16 +BUF DC CL30' ' buffer +EDMASK DC X'4020202020202021204B202020' CL13 + YREGS + END AVGSMA diff --git a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena index c7483737b9..9c5aa7267f 100644 --- a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena +++ b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena @@ -29,7 +29,7 @@ aCount := thePeriod. ]. - #var aSum := Summing new:(Real new &int:0) foreach:theList. + #var aSum := theList summarize:(Real new &int:0). ^ aSum / aCount. ]. @@ -41,15 +41,15 @@ #var SMA3 := SMA new:3. #var SMA5 := SMA new:5. - control forrange &int:1 &int:5 &do: (&int:i) + 1 to:5 &doEach: (:i) [ - consoleEx writeLine:"sma3 + " :i :" = ": (SMA3 += i). - consoleEx writeLine:"sma5 + " :i :" = ": (SMA5 += i). + console write:"sma3 + " :i :" = ": (SMA3 += i) &paddingRight:30 &with:#32. + console writeLine:"sma5 + " :i :" = ": (SMA5 += i). ]. - control forrange &int:5 &int:1 &do: (&int:i) + 5 to:1 &doEach: (:i) [ - consoleEx writeLine:"sma3 + " :i :" = ": (SMA3 += i). - consoleEx writeLine:"sma5 + " :i :" = ": (SMA5 += i). + console write:"sma3 + " :i :" = ": (SMA3 += i) &paddingRight:30 &with:#32. + console writeLine:"sma5 + " :i :" = ": (SMA5 += i). ]. ]. diff --git a/Task/Averages-Simple-moving-average/Pascal/averages-simple-moving-average.pascal b/Task/Averages-Simple-moving-average/Pascal/averages-simple-moving-average.pascal new file mode 100644 index 0000000000..08fb633b9e --- /dev/null +++ b/Task/Averages-Simple-moving-average/Pascal/averages-simple-moving-average.pascal @@ -0,0 +1,78 @@ +program sma; +type + tsma = record + smaValue : array of double; + smaAverage, + smaSumOld, + smaSumNew, + smaRezActLength : double; + smaActLength, + smaLength, + smaPos :NativeInt; + smaIsntFull: boolean; + end; + +procedure smaInit(var sma:tsma;p: NativeUint); +Begin + with sma do + Begin + setlength(smaValue,0); + setlength(smaValue,p); + smaLength:= p; + smaActLength := 0; + smaAverage:= 0.0; + smaSumOld := 0.0; + smaSumNew := 0.0; + smaPos := p-1; + smaIsntFull := true + end; +end; + +function smaAddValue(var sma:tsma;v: double):double; +Begin + with sma do + Begin + IF smaIsntFull then + Begin + inc(smaActLength); + smaRezActLength := 1/smaActLength; + smaIsntFull := smaActLength < smaLength ; + end; + smaSumOld := smaSumOld+v-smaValue[smaPos]; + smaValue[smaPos] := v; + smaSumNew := smaSumNew+v; + + smaPos := smaPos-1; + if smaPos < 0 then + begin + smaSumOld:= smaSumNew; + smaSumNew:= 0.0; + smaPos := smaLength-1; + end; + smaAverage := smaSumOld *smaRezActLength; + smaAddValue:= smaAverage; + end; +end; + +var + sma3,sma5:tsma; + i : LongInt; +begin + smaInit(sma3,3); + smaInit(sma5,5); + For i := 1 to 5 do + Begin + write('Inserting ',i,' into sma3 ',smaAddValue(sma3,i):0:4); + writeln(' Inserting ',i,' into sma5 ',smaAddValue(sma5,i):0:4); + end; + For i := 5 downto 1 do + Begin + write('Inserting ',i,' into sma3 ',smaAddValue(sma3,i):0:4); + writeln(' Inserting ',i,' into sma5 ',smaAddValue(sma5,i):0:4); + end; + //speed test + smaInit(sma3,3); + For i := 1 to 100000000 do + smaAddValue(sma3,i); + writeln('100''000''000 insertions ',sma3.smaAverage:0:4); +end. diff --git a/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx b/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx index dc73d270de..7aa911cfe6 100644 --- a/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx +++ b/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx @@ -1,24 +1,26 @@ -/*REXX program illustrates simple moving average using a simple list. */ -parse arg p q n . /*get some arguments (maybe). */ -if p=='' then p=3 /*the 1st period (default: 3).*/ -if q=='' then q=5 /* " 2nd " " 5 */ -if n=='' then n=10 /*number of items in the list.*/ -@.=0 /*define stemmed array, init 0*/ -/*──────────────────────────────────────────build 1st half of the list. */ - do j=1 for n%2; @.j=j; end /* ··· increasing values.*/ -/*──────────────────────────────────────────build 2nd half of the list. */ - do k=n%2 to 1 by -1; @.j=k; j=j+1; end /* ··· decreasing values.*/ -/*──────────────────────────────────────────perform a simple moving avg.*/ +/*REXX program illustrates simple moving average using a constructed list. */ +parse arg p q n . /*get optional arguments from the C.L. */ +if p=='' then p=3 /*the 1st period (the default is: 3).*/ +if q=='' then q=5 /* " 2nd " " " " 5).*/ +if n=='' then n=10 /*the number of items in the list. */ +@.=0 /*define array with initial zero values*/ + /* [↓] build 1st half of list*/ + do j=1 for n%2; @.j=j; end /* ··· increasing values.*/ + /* [↓] build 2nd half of list*/ + do k=n%2 to 1 by -1; @.j=k; j=j+1; end /* ··· decreasing values.*/ + say ' ' " SMA with " ' SMA with ' say ' number ' " period" p' ' ' period' q say ' ──────── ' "──────────" '──────────' - do m=1 for n - say center(@.m,10) left(sma(p,m),11) left(sma(q,m),11) - end /*m*/ /* [↑] show simple moving avg.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SMA subroutine──────────────────────*/ -sma: procedure expose @.; parse arg p,j; s=0; i=0 - do k=max(1,j-p+1) to j+p for p while k<=j; i=i+1 - s=s+@.k - end /*k*/ + + /* [↓] perform a simple moving average*/ + do m=1 for n + say center(@.m, 10) left(sma(p,m), 11) left(sma(q,m), 11) + end /*m*/ /* [↑] show a simple moving average.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sma: procedure expose @.; parse arg p,j; s=0; i=0 + do k=max(1,j-p+1) to j+p for p while k<=j; i=i+1 + s=s+@.k + end /*k*/ return s/i diff --git a/Task/Balanced-brackets/ABAP/balanced-brackets.abap b/Task/Balanced-brackets/ABAP/balanced-brackets.abap new file mode 100644 index 0000000000..3d0f94e4c1 --- /dev/null +++ b/Task/Balanced-brackets/ABAP/balanced-brackets.abap @@ -0,0 +1,95 @@ +CLASS lcl_balanced_brackets DEFINITION. + PUBLIC SECTION. + CLASS-METHODS: + class_constructor, + + are_brackets_balanced + IMPORTING + seq TYPE string + RETURNING + VALUE(r_are_brackets_balanced) TYPE abap_bool, + + get_random_brackets_seq + IMPORTING + n TYPE i + RETURNING + VALUE(r_bracket_seq) TYPE string. + + PRIVATE SECTION. + CLASS-DATA: random_int TYPE REF TO cl_abap_random_int. + + CLASS-METHODS: + _split_string + IMPORTING + i_text TYPE string + RETURNING + VALUE(r_chars) TYPE stringtab, + + _rand_bool + RETURNING + VALUE(r_bool) TYPE i. +ENDCLASS. + +CLASS lcl_balanced_brackets IMPLEMENTATION. + METHOD class_constructor. + random_int = cl_abap_random_int=>create( seed = CONV #( sy-uzeit ) + min = 0 + max = 1 ). + ENDMETHOD. + + METHOD are_brackets_balanced. + DATA: open_bracket_count TYPE i. + + DATA(chars) = _split_string( seq ). + + r_are_brackets_balanced = abap_false. + + LOOP AT chars ASSIGNING FIELD-SYMBOL(). + IF = ']' AND open_bracket_count = 0. + RETURN. + ENDIF. + + IF = ']'. + open_bracket_count = open_bracket_count - 1. + ENDIF. + + IF = '['. + open_bracket_count = open_bracket_count + 1. + ENDIF. + ENDLOOP. + + IF open_bracket_count > 0. + RETURN. + ENDIF. + + r_are_brackets_balanced = abap_true. + ENDMETHOD. + + METHOD get_random_brackets_seq. + DATA(itab) = VALUE stringtab( FOR i = 1 THEN i + 1 WHILE i <= n + ( COND #( WHEN _rand_bool( ) = 0 THEN '[' + ELSE ']' ) ) ). + r_bracket_seq = concat_lines_of( itab ). + ENDMETHOD. + + METHOD _rand_bool. + r_bool = random_int->get_next( ). + ENDMETHOD. + + METHOD _split_string. + DATA: off TYPE i VALUE 0. + + DO strlen( i_text ) TIMES. + INSERT i_text+off(1) INTO TABLE r_chars. + off = off + 1. + ENDDO. + ENDMETHOD. +ENDCLASS. + +START-OF-SELECTION. + DO 10 TIMES. + DATA(seq) = lcl_balanced_brackets=>get_random_brackets_seq( 10 ). + cl_demo_output=>write( |{ seq } => { COND string( WHEN lcl_balanced_brackets=>are_brackets_balanced( seq ) = abap_true THEN 'OK' + ELSE 'NOT OK' ) }| ). + ENDDO. + cl_demo_output=>display( ). diff --git a/Task/Balanced-brackets/ALGOL-68/balanced-brackets.alg b/Task/Balanced-brackets/ALGOL-68/balanced-brackets.alg new file mode 100644 index 0000000000..5826669045 --- /dev/null +++ b/Task/Balanced-brackets/ALGOL-68/balanced-brackets.alg @@ -0,0 +1,63 @@ +# generates a string of random opening and closing brackets. The number of # +# each type of brackets is speccified in length # +PROC get brackets = ( INT length ) STRING: + BEGIN + INT result length = length * 2; + [ 1 : result length ]CHAR result; + # initialise the brackets to all open brackets # + FOR char pos TO result length DO result[ char pos ] := "[" OD; + # set half of the brackets to close brackets # + INT close count := 0; + WHILE close count < length + DO + INT random pos = 1 + ENTIER ( next random * result length ); + IF result[ random pos ] = "[" + THEN + close count +:= 1; + result[ random pos ] := "]" + FI + OD; + result + END # get brackets # ; + +# returns TRUE if the brackets string contains a correctly nested sequence # +# of brackets, FALSE otherwise # +PROC check brackets = ( STRING brackets ) BOOL: + BEGIN + INT depth := 0; + FOR char pos FROM LWB brackets TO UPB brackets + WHILE + IF brackets[ char pos ] = "[" + THEN + depth +:= 1 + ELSE + depth -:= 1 + FI; + depth >= 0 + DO + SKIP + OD; + # depth will be 0 if we reached the end of the string and it was # + # correct, non-0 otherwise # + depth = 0 + END # check brackets # ; + +# procedure to test check brackets # +PROC test check brackets = ( STRING brackets ) VOID: + print( ( ( brackets + + ": " + + IF check brackets( brackets ) THEN "ok" ELSE "not ok" FI + ) + , newline + ) + ) ; + +# test the bracket generation and checking PROCs # +test check brackets( get brackets( 0 ) ); +FOR length TO 12 +DO + TO 2 + DO + test check brackets( get brackets( length ) ) + OD +OD diff --git a/Task/Balanced-brackets/Batch-File/balanced-brackets.bat b/Task/Balanced-brackets/Batch-File/balanced-brackets.bat new file mode 100644 index 0000000000..891627f336 --- /dev/null +++ b/Task/Balanced-brackets/Batch-File/balanced-brackets.bat @@ -0,0 +1,63 @@ +:: Balanced Brackets Task from Rosetta Code Wiki +:: Batch File Implementation + +@echo off +setlocal enabledelayedexpansion + +::The Main Thing... +set numofpairs=10 +set howmanystrings=10 +cls +for /l %%. in (1,1,%howmanystrings%) do ( + call :generate + call :checkforbalance +) +echo.&pause&exit /b +::/The Main Thing. + +::Generate strings of brackets... +:generate + set i=0&set j=%numofpairs%&set samp= + set /a toss=%random%%%2 + set put1=[&set put2=] + if %toss%==1 (set put1=]&set put2=[) + for /l %%x in (1,1,%numofpairs%) do ( + set samp=!samp!%put1% + ) + :add + if not %i%==%numofpairs% ( + set /a rnd=%random%%%%j%+1 + set /a oppos=%j%-!rnd! + ::A new trick for substitution of delayed variables... + for /f "tokens=1-2" %%A in ("!rnd! !oppos!") do ( + set str1=!samp:~-%%A! + set str2=!samp:~0,%%B! + ) + set samp=!str2!%put2%!str1! + set /a "j+=1","i+=1" + goto :add + ) +goto :EOF +::/Generate strings of brackets. + +::Check for Balance... +::Uses Markov Algorithm. +:checkforbalance +set "changes=!samp!" +:check_loop +if "!changes!"=="" goto itsbal +if "!input!"=="!changes!" goto notbal + +set input=!changes! +set "changes=!input:[]=!" +goto check_loop + +:itsbal +echo. +echo %samp% is Balanced. +goto :EOF +:notbal +echo. +echo %samp% is NOT Balanced. +goto :EOF +::/Check for Balance. diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index 9aa5068604..1e9b113859 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -2,40 +2,42 @@ #define system'routines. #define extensions. -// --- RandomBrackets --- - -#symbol randomBrackets = (:aLength) -[ - ^ (0 == aLength) - ? [ emptyLiteralValue ] - ! [ - #var aBrackets := arrayControl new &length:(aLength int) &each: i[ CharValue new &short:91 ] + arrayControl new &length:(aLength int) &each: i[ CharValue new &short:93 ]. - - randomControl randomize:(aLength * 2) &array:aBrackets. - - ^ Summing new:(String new) foreach:aBrackets literal. - ]. -]. - -#symbol isBalanced = (:aLiteral) -[ - #var aCounter := Integer new:0. - - control foreach:aLiteral &until: aChar [ aCounter append:(aChar => "[" ? [ 1 ] "]" ? [ -1 ]) < 0 ]. +#symbol randomBrackets = +{ + new : aLength + = (0 == aLength) + ? [ emptyLiteralValue ] + ! [ + #var aBrackets := + Array new &length:(aLength int) set &every: (&index:i) [ #91 ] + + + Array new &length:(aLength int) set &every: (&index:i)[ #93 ]. + + aBrackets randomize:(aLength * 2). + + ^ aBrackets summarize:(String new) literal. + ]. +}. + +#class(extension)op +{ + #method isBalanced + [ + #var aCounter := Integer new:0. - ^ (0 == aCounter). -]. + self seek &each:aChar [ (aCounter += (aChar => #91 ? [ 1 ] #93 ? [ -1 ])) < 0 ]. -// --- Program --- + ^ (0 == aCounter). + ] +} #symbol program = [ - control forrange &int:0 &int:9 &do: (&int:aLength) + 0 to:9 &doEach: (:aLength) [ - #var anStr := randomBrackets:aLength. - #var balanced := isBalanced:anStr. + #var anStr := randomBrackets new:aLength. - consoleEx writeLine:"""":anStr:"""":(balanced => true ? [ " is balanced" ] false ? [ " is not balanced" ]). + console writeLine:"""":anStr:"""":((anStr isBalanced) => true ? [ " is balanced" ] false ? [ " is not balanced" ]). ]. console readChar. diff --git a/Task/Balanced-brackets/J/balanced-brackets-2.j b/Task/Balanced-brackets/J/balanced-brackets-2.j index 8cb613b3d3..6a55000c8e 100644 --- a/Task/Balanced-brackets/J/balanced-brackets-2.j +++ b/Task/Balanced-brackets/J/balanced-brackets-2.j @@ -1,4 +1,4 @@ - (,&' ' , ('bad';'OK') {::~ checkBalanced)"1 genBracketPairs i. 10 + (, ' ' , ('bad';'OK') {::~ checkBalanced)"1 genBracketPairs i. 10 OK ][ bad ][[] bad diff --git a/Task/Balanced-brackets/Julia/balanced-brackets-1.julia b/Task/Balanced-brackets/Julia/balanced-brackets-1.julia index 8241f68701..6bac68cc9c 100644 --- a/Task/Balanced-brackets/Julia/balanced-brackets-1.julia +++ b/Task/Balanced-brackets/Julia/balanced-brackets-1.julia @@ -7,6 +7,6 @@ function balanced(str) i == 0 ? true : false end -brackets(n) = CharString(shuffle([("[]"^n)...])) +brackets(n) = join(shuffle([("[]"^n)...])) -print(map(x -> (x, balanced(x)), [brackets(i) for i = 0:8])) +map(x -> (x, balanced(x)), [brackets(i) for i = 0:8]) diff --git a/Task/Balanced-brackets/PHP/balanced-brackets.php b/Task/Balanced-brackets/PHP/balanced-brackets.php new file mode 100644 index 0000000000..cbd657ac7c --- /dev/null +++ b/Task/Balanced-brackets/PHP/balanced-brackets.php @@ -0,0 +1,33 @@ +#!/usr/bin/php + xx $n).pick(*).join; +my $s = (<[ ]> xx $n).flat.pick(*).join; say "$s {balanced($s) ?? "is" !! "is not"} well-balanced" diff --git a/Task/Balanced-brackets/Perl-6/balanced-brackets-3.pl6 b/Task/Balanced-brackets/Perl-6/balanced-brackets-3.pl6 index 1e5da3a4b7..9e2552ad64 100644 --- a/Task/Balanced-brackets/Perl-6/balanced-brackets-3.pl6 +++ b/Task/Balanced-brackets/Perl-6/balanced-brackets-3.pl6 @@ -5,4 +5,4 @@ sub balanced($_ is copy) { my $n = prompt "Number of bracket pairs: "; my $s = <[ ]>.roll($n*2).join; -say "$s is", ' not' xx not balanced($s)), " well-balanced"; +say "$s is", ' not' x not balanced($s), " well-balanced"; diff --git a/Task/Balanced-brackets/Perl-6/balanced-brackets-4.pl6 b/Task/Balanced-brackets/Perl-6/balanced-brackets-4.pl6 index e5599d6aff..4468b7b922 100644 --- a/Task/Balanced-brackets/Perl-6/balanced-brackets-4.pl6 +++ b/Task/Balanced-brackets/Perl-6/balanced-brackets-4.pl6 @@ -1,5 +1,5 @@ grammar BalBrack { token TOP { '[' * ']' } } my $n = prompt "Number of bracket pairs: "; -my $s = ('[' xx $n, ']' xx $n).pick(*).join; +my $s = ('[' xx $n, ']' xx $n).flat.pick(*).join; say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced"; diff --git a/Task/Balanced-brackets/REXX/balanced-brackets-1.rexx b/Task/Balanced-brackets/REXX/balanced-brackets-1.rexx index 5f3acdb5e0..8d28138848 100644 --- a/Task/Balanced-brackets/REXX/balanced-brackets-1.rexx +++ b/Task/Balanced-brackets/REXX/balanced-brackets-1.rexx @@ -1,40 +1,38 @@ -/*REXX program to check for balanced brackets [] */ -@.=0 -yesno.0 = left('',40) 'unbalanced' -yesno.1 = 'balanced' +/*REXX program checks for balanced (square) brackets [ ] */ +@.=0; yesNo.0=left('',40) 'unbalanced' /*forty +1 leading blanks.*/ + yesNo.1= 'balanced' +q= ; call checkBal q; say yesNo.result q +q= '[][][][[]]' ; call checkBal q; say yesNo.result q +q= '[][][][[]]][' ; call checkBal q; say yesNo.result q +q= '[' ; call checkBal q; say yesNo.result q +q= ']' ; call checkBal q; say yesNo.result q +q= '[]' ; call checkBal q; say yesNo.result q +q= '][' ; call checkBal q; say yesNo.result q +q= '][][' ; call checkBal q; say yesNo.result q +q= '[[]]' ; call checkBal q; say yesNo.result q +q= '[[[[[[[]]]]]]]' ; call checkBal q; say yesNo.result q +q= '[[[[[]]]][]' ; call checkBal q; say yesNo.result q +q= '[][]' ; call checkBal q; say yesNo.result q +q= '[]][[]' ; call checkBal q; say yesNo.result q +q= ']]][[[[]' ; call checkBal q; say yesNo.result q -q='[][][][[]]' ; call checkBal q; say yesno.result q -q='[][][][[]]][' ; call checkBal q; say yesno.result q -q='[' ; call checkBal q; say yesno.result q -q=']' ; call checkBal q; say yesno.result q -q='[]' ; call checkBal q; say yesno.result q -q='][' ; call checkBal q; say yesno.result q -q='][][' ; call checkBal q; say yesno.result q -q='[[]]' ; call checkBal q; say yesno.result q -q='[[[[[[[]]]]]]]' ; call checkBal q; say yesno.result q -q='[[[[[]]]][]' ; call checkBal q; say yesno.result q -q='[][]' ; call checkBal q; say yesno.result q -q='[]][[]' ; call checkBal q; say yesno.result q -q=']]][[[[]' ; call checkBal q; say yesno.result q - - do j=1 for 40 - q=translate(rand(random(1,8)),'[]',01) - call checkBal q; if result=='-1' then iterate - say yesno.result q - end -exit -/*───────────────────────────────────PAND subroutine────────────────────*/ -pand: p=random(0,1); return p || \p -/*───────────────────────────────────RAND subroutine────────────────────*/ -rand: pp=pand(); pp=pand()pp; pp=copies(pp,arg(1)) - i=random(2,length(pp)); pp=left(pp,i-1)substr(pp,i) -return pp -/*───────────────────────────────────CHECKBAL subroutine────────────────*/ -checkBal: procedure expose @.; arg y /*check for balanced brackets [] */ -nest=0; if @.y then return '-1' /*already done this expression ? */ -@.y=1 /*indicate expression processed. */ - do j=1 for length(y); _=substr(y,j,1) /*pick off character.*/ - if _=='[' then nest=nest+1 - else do; nest=nest-1; if nest<0 then return 0; end - end /*j*/ -return nest==0 + do j=1 for 40 + q=translate(rand(random(1, 8)), '[]', 01) + call checkBal q; if result==-1 then iterate /*skip if duplicated.*/ + say yesNo.result q /*display the result.*/ + end /*j*/ /* [↑] generate 40 random "Q" strings.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +?: ?=random(0,1); return ? || \? +/*────────────────────────────────────────────────────────────────────────────*/ +rand: ??=copies(?()?(), arg(1)); _=random(2, length(??)) + return left(??, _-1)substr(??, _) +/*────────────────────────────────────────────────────────────────────────────*/ +checkBal: procedure expose @.; parse arg y /*get the "bracket" expression. */ + if @.y then return -1 /*already done this expression ? */ + @.y=1 /*indicate expression processed. */ + !=0; do j=1 for length(y); _=substr(y,j,1) /*get a char.*/ + if _=='[' then !=!+1 /*bump nest #*/ + else do; !=!-1; if !<0 then return 0; end + end /*j*/ + return !==0 /* [↑] "!" is the nested counter.*/ diff --git a/Task/Balanced-brackets/REXX/balanced-brackets-3.rexx b/Task/Balanced-brackets/REXX/balanced-brackets-3.rexx index 86bb17a118..9bdc0f5e8a 100644 --- a/Task/Balanced-brackets/REXX/balanced-brackets-3.rexx +++ b/Task/Balanced-brackets/REXX/balanced-brackets-3.rexx @@ -1,58 +1,23 @@ -/*REXX program to check for balanced brackets [ ] */ -count=0 -nested=0 -yesno.0 = left('',40) 'unbalanced' -yesno.1 = 'balanced' -q='' ; call checkBal q; say yesno.result q -q='[][][][[]]' ; call checkBal q; say yesno.result q -q='[][][][[]]][' ; call checkBal q; say yesno.result q -q='[' ; call checkBal q; say yesno.result q -q=']' ; call checkBal q; say yesno.result q -q='[]' ; call checkBal q; say yesno.result q -q='][' ; call checkBal q; say yesno.result q -q='][][' ; call checkBal q; say yesno.result q -q='[[]]' ; call checkBal q; say yesno.result q -q='[[[[[[[]]]]]]]' ; call checkBal q; say yesno.result q -q='[[[[[]]]][]' ; call checkBal q; say yesno.result q -q='[][]' ; call checkBal q; say yesno.result q -q='[]][[]' ; call checkBal q; say yesno.result q -q=']]][[[[]' ; call checkBal q; say yesno.result q -call teller -count=0 -nested=0 - do j=1 /*generate lots of permutations. */ - q=translate(strip(x2b(d2x(j)),'L',0),"][",01) /*convert──►[].*/ - if countstr(']',q)\==countstr('[',q) then iterate /*compliant?*/ +/*REXX program checks for numerous generated balanced (square) brackets [ ] */ +bals=0 +#=0; do j=1 until length(q)>20 /*generate lots of bracket permutations*/ + q=translate(strip(x2b(d2x(j)),'L',0),"][",01) /*convert ──► []*/ + if countStr(']',q)\==countstr('[',q) then iterate /*is compliant? */ call checkBal q - if length(q)>20 then leave /*done all 20-char possibilities?*/ - end -/*───────────────────────────────────TELLER subroutine──────────────────*/ -teller: say -say count " expressions were checked, " nested ' were balanced, ', - count-nested " were unbalanced." -return -/*───────────────────────────────────CHECKBAL subroutine────────────────*/ -checkBal: procedure expose nested count; parse arg y; count=count+1 -nest=0 - do j=1 for length(y); _=substr(y,j,1) /*pick off character.*/ - select - when _=='[' then nest=nest+1 /*opening bracket ...*/ - when _==']' then do; nest=nest-1; if nest<0 then leave; end - otherwise nop /*ignore any chaff. */ - end /*select*/ - end /*j*/ -nested=nested + (nest==0) -return nest==0 -/* ┌──────────────────────────────────────────────────────────────────┐ - │ COUNTSTR counts the number of occurances of a string (or char)│ - │ within another string (haystack) without overlap. If either arg │ - │ is null, 0 (zero) is returned. To make the subroutine case │ - │ insensative, change the PARSE ARG ... statement to ARG ... │ - │ Example: yyy = 'The quick brown fox jumped over the lazy dog.' │ - │ zz = countstr('o',yyy) /*ZZ will be set to 4 */ │ - │ Note that COUNTSTR is also a built-in function of the newer │ - │ REXX interpreters, and the result should be identical. Checks │ - │ could be added to validate if 2 or 3 arguments are passed. │ - └──────────────────────────────────────────────────────────────────┘ */ -countstr: procedure; parse arg n,h,s; if s=='' then s=1; w=length(n) - do r=0 until _==0; _=pos(n,h,s); s=_+w; end; return r + end /*j*/ /*have all 20─character possibilities? */ +say +say # " expressions were checked, " bals ' were balanced, ' , + #-bals " were unbalanced." +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +checkBal: procedure expose # bals; parse arg y; #=#+1 /*bump count.*/ +!=0 + do j=1 for length(y) + if substr(y,j,1)=='[' then !=!+1 + else do; !=!-1; if !<0 then leave; end + end /*j*/ +bals=bals + (!==0) +return !==0 +/*────────────────────────────────────────────────────────────────────────────*/ +countStr: procedure; parse arg n,h,s; if s=='' then s=1; w=length(n) + do r=0 until _==0; _=pos(n,h,s); s=_+w; end; return r diff --git a/Task/Balanced-brackets/Rust/balanced-brackets.rust b/Task/Balanced-brackets/Rust/balanced-brackets.rust new file mode 100644 index 0000000000..07f272c968 --- /dev/null +++ b/Task/Balanced-brackets/Rust/balanced-brackets.rust @@ -0,0 +1,40 @@ +extern crate rand; + +trait Balanced { + /// Returns true if the brackets are balanced + fn is_balanced(&self) -> bool; +} + +impl<'a> Balanced for str { + fn is_balanced(&self) -> bool { + let mut count = 0; + + for bracket in self.chars() { + let change = match bracket { + '[' => 1, + ']' => -1, + _ => panic!("Strings should only contain brackets") + }; + + count += change; + if count < 0 { return false; } + } + + count == 0 + } +} + +/// Generates random brackets +fn generate_brackets(num: usize) -> String { + use rand::random; + + (0..num).map(|_| if random() { '[' } else { ']' }).collect() +} + +fn main() { + for i in (0..10) { + let brackets = generate_brackets(i); + + println!("{} {}", brackets, brackets.is_balanced()) + } +} diff --git a/Task/Balanced-brackets/VBScript/balanced-brackets.vb b/Task/Balanced-brackets/VBScript/balanced-brackets.vb new file mode 100644 index 0000000000..8a458a26f4 --- /dev/null +++ b/Task/Balanced-brackets/VBScript/balanced-brackets.vb @@ -0,0 +1,36 @@ +For n = 1 To 10 + sequence = Generate_Sequence(n) + WScript.Echo sequence & " is " & Check_Balance(sequence) & "." +Next + +Function Generate_Sequence(n) + For i = 1 To n + j = Round(Rnd()) + If j = 0 Then + Generate_Sequence = Generate_Sequence & "[" + Else + Generate_Sequence = Generate_Sequence & "]" + End If + Next +End Function + +Function Check_Balance(s) + Set Stack = CreateObject("System.Collections.Stack") + For i = 1 To Len(s) + char = Mid(s,i,1) + If i = 1 Or char = "[" Then + Stack.Push(char) + ElseIf Stack.Count <> 0 Then + If char = "]" And Stack.Peek = "[" Then + Stack.Pop + End If + Else + Stack.Push(char) + End If + Next + If Stack.Count > 0 Then + Check_Balance = "Not Balanced" + Else + Check_Balance = "Balanced" + End If +End Function diff --git a/Task/Balanced-ternary/ATS/balanced-ternary.ats b/Task/Balanced-ternary/ATS/balanced-ternary.ats index fdad9a32e4..21f123cd8e 100644 --- a/Task/Balanced-ternary/ATS/balanced-ternary.ats +++ b/Task/Balanced-ternary/ATS/balanced-ternary.ats @@ -61,12 +61,12 @@ loop{n:nat} // if isneqz(inp) then let - val c = inp.head + val c = inp.head() val d = (case- c of '+' => P | '0' => Z | '-' => N): btd // end of [val] in - loop (inp.tail, list_cons(d, ds)) + loop (inp.tail(), list_cons(d, ds)) end // end of [then] else ds // end of [else] // diff --git a/Task/Balanced-ternary/REXX/balanced-ternary.rexx b/Task/Balanced-ternary/REXX/balanced-ternary.rexx index 349ef0920a..43f51aa9aa 100644 --- a/Task/Balanced-ternary/REXX/balanced-ternary.rexx +++ b/Task/Balanced-ternary/REXX/balanced-ternary.rexx @@ -1,55 +1,56 @@ -/*REXX pgm converts decimal ◄───► balanced ternary; also performs arith.*/ -numeric digits 10000 /*handle almost any size numbers.*/ -Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by sub.*/ -Bo = '-436' ; Bbt = d2bt(Bo) ; @ = '(decimal)' -Co = '+-++-' ; Cbt = Co ; @@ = 'balanced ternary =' +/*REXX pgm converts decimal ◄───► balanced ternary; also performs arithmetic.*/ +numeric digits 10000 /*be able to handle gihugic numbers. */ +Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by subroutine*/ +Bo = '-436' ; Bbt = d2bt(Bo) ; @ = '(decimal)' +Co = '+-++-' ; Cbt = Co ; @@ = 'balanced ternary =' call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt say; $bt = btMul(Abt,btSub(Bbt,Cbt)) - call btshow '[a*(b-c)]', $bt -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────BT2D subroutine─────────────────────*/ -d2bt: procedure; parse arg x 1; p=0; $.='-'; $.1='+'; $.0=0; #= -x=x/1 - do until x==0; _=(x//(3**(p+1)))%3**p - if _==2 then _=-1; if _=-2 then _=1 - x=x-_*(3**p); p=p+1; #=$._ || # - end /*until*/ -return # -/*──────────────────────────────────BT2D subroutine─────────────────────*/ -bt2d: procedure; parse arg x; r=reverse(x); #=0; $.=-1; $.0=0; _='+'; $._=1 - do j=1 for length(x); _=substr(r,j,1); #=#+$._*3**(j-1); end -return # -/*──────────────────────────────────BTADD subroutine────────────────────*/ -btAdd: procedure; parse arg x,y; rx=reverse(x); ry=reverse(y); carry=0 -$.='-'; $.0=0; $.1='+'; @.=0; _='-'; @._=-1; _="+"; @._=1; #= - - do j=1 for max(length(x),length(y)) - x_=substr(rx,j,1); xn=@.x_ - y_=substr(ry,j,1); yn=@.y_ - s=xn+yn+carry ; carry=0 - if s== 2 then do; s=-1; carry= 1; end - if s== 3 then do; s= 0; carry= 1; end - if s==-2 then do; s= 1; carry=-1; end - #=$.s || # - end /*j*/ -if carry\==0 then #=$.carry || #; return btNorm(#) -/*──────────────────────────────────BTMUL subroutine────────────────────*/ -btMul: procedure; parse arg x,y; if x==0 | y==0 then return 0; S=1 -x=btNorm(x); y=btNorm(y) /*handle: 0-xxx values.*/ -if left(x,1)=='-' then do; x=btNeg(x); S=-S; end /*positate.*/ -if left(y,1)=='-' then do; y=btNeg(y); S=-S; end /*positate.*/ -if length(y)>length(x) then parse value x y with y x /*optimize.*/ + call btShow '[a*(b-c)]', $bt +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +d2bt: procedure; parse arg x 1; p=0; $.='-'; $.1='+'; $.0=0; #= + x=x/1 + do until x==0; _=(x//(3**(p+1)))%3**p + if _== 2 then _= -1 + if _== -2 then _= 1 + x=x-_*(3**p); p=p+1; #=$._ || # + end /*until ···*/ + return # +/*────────────────────────────────────────────────────────────────────────────*/ +bt2d: procedure; parse arg x; r=reverse(x); #=0; $.=-1; $.0=0; _='+'; $._=1 + do j=1 for length(x); _=substr(r,j,1); #=#+$._*3**(j-1); end + return # +/*────────────────────────────────────────────────────────────────────────────*/ +btAdd: procedure; parse arg x,y; rx=reverse(x); ry=reverse(y); carry=0 + @.=0 ; _='-'; @._=-1; _="+"; @._=1 + $.='-'; $.0=0; $.1='+' + #=; do j=1 for max(length(x),length(y)) + x_=substr(rx,j,1); xn=@.x_ + y_=substr(ry,j,1); yn=@.y_ + s=xn+yn+carry ; carry= 0 + if s== 2 then do; s=-1; carry= 1; end + if s== 3 then do; s= 0; carry= 1; end + if s==-2 then do; s= 1; carry=-1; end + #=$.s || # + end /*j*/ + if carry\==0 then #=$.carry||#; return btNorm(#) +/*────────────────────────────────────────────────────────────────────────────*/ +btMul: procedure; parse arg x,y; if x==0 | y==0 then return 0; S=1 +x=btNorm(x); y=btNorm(y) /*handle: 0-xxx values.*/ +if left(x,1)=='-' then do; x=btNeg(x); S=-S; end /*positate.*/ +if left(y,1)=='-' then do; y=btNeg(y); S=-S; end /*positate.*/ +if length(y)>length(x) then parse value x y with y x /*optimize.*/ P=0 - do until y==0 /*keep adding 'til done*/ - P=btAdd(P,x) /*multiple the hard way*/ - y=btSub(y,'+') /*subtract 1 from Y. */ - end /*until*/ -if S==-1 then P=btNeg(P) /*adjust product sign. */ -return P /*return the product P.*/ -/*───────────────────────────────one-line subroutines───────────────────*/ -btNeg: return translate(arg(1), '-+', "+-") /*negate the bal_tern #*/ -btNorm: _=strip(arg(1),'L',0); if _=='' then _=0; return _ /*normalize*/ -btSub: return btAdd(arg(1), btNeg(arg(2))) /*subtract two BT args.*/ + do until y==0 /*keep adding 'til done*/ + P=btAdd(P,x) /*multiple the hard way*/ + y=btSub(y,'+') /*subtract 1 from Y.*/ + end /*until*/ +if S==-1 then P=btNeg(P) /*adjust product sign. */ +return P /*return the product P.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +btNeg: return translate(arg(1), '-+', "+-") /*negate the bal_tern #*/ +btNorm: _=strip(arg(1),'L',0); if _=='' then _=0; return _ /*normalize a #*/ +btSub: return btAdd(arg(1), btNeg(arg(2))) /*subtract two BT args.*/ btShow: say center(arg(1),9) right(arg(2),20) @@ right(bt2d(arg(2)),9) @; return diff --git a/Task/Benfords-law/AWK/benfords-law.awk b/Task/Benfords-law/AWK/benfords-law.awk index 52417f3b5d..48aa0d165e 100644 --- a/Task/Benfords-law/AWK/benfords-law.awk +++ b/Task/Benfords-law/AWK/benfords-law.awk @@ -6,8 +6,8 @@ BEGIN { } print("digit expected observed deviation") for (i=1; i<=9; i++) { - expected = log10(i+1) - log10(i) - actual = arr[i] / n + 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)) } diff --git a/Task/Benfords-law/Julia/benfords-law.julia b/Task/Benfords-law/Julia/benfords-law.julia index 0ad27c7f0a..fc2bde47c9 100644 --- a/Task/Benfords-law/Julia/benfords-law.julia +++ b/Task/Benfords-law/Julia/benfords-law.julia @@ -2,4 +2,4 @@ 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])] +benford(l) = [Number[1:9;] ben(l) log10(1.+1./[1:9;])] diff --git a/Task/Bernoulli-numbers/00DESCRIPTION b/Task/Bernoulli-numbers/00DESCRIPTION index 3f30f6a737..44976b1d42 100644 --- a/Task/Bernoulli-numbers/00DESCRIPTION +++ b/Task/Bernoulli-numbers/00DESCRIPTION @@ -5,7 +5,7 @@ * 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). +** 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: diff --git a/Task/Bernoulli-numbers/Maple/bernoulli-numbers.maple b/Task/Bernoulli-numbers/Maple/bernoulli-numbers.maple index 7ddf77c3ec..3d99fbc72a 100644 --- a/Task/Bernoulli-numbers/Maple/bernoulli-numbers.maple +++ b/Task/Bernoulli-numbers/Maple/bernoulli-numbers.maple @@ -1,11 +1 @@ -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); +print(select(n->n[2]<>0,[seq([n,bernoulli(n,1)],n=0..60)])); diff --git a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx index 4e70243af7..a6006e4c0d 100644 --- a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx +++ b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx @@ -1,53 +1,52 @@ -/*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#.*/ +/*REXX program calculates a number of Bernoulli numbers expressed as fractions*/ +parse arg N .; if N=='' then N=60 /*Not specified? Then use the default.*/ +!.=0; w=max(length(N),4); Nw=N+N%5 /*used for aligning (output) fractions.*/ +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 the numbers from 0 ──► N. */ + b=bern(#); if b==0 then iterate /*calculate Bernoulli number, skip if 0*/ + indent=max(0, nW-pos('/', b)) /*calculate alignment (indentation). */ + say right(#,w) left('',indent) b /*display the indented Bernoulli number*/ + end /*#*/ /* [↑] align the Bernoulli fractions. */ +exit /*stick a fork in it, we're all 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 numbers up to X, */ + do j=2 to x by 2; jp=j+1; d=j+j /* ··· and set some shortcut vars.*/ + if d>digits() then numeric digits d /*increase the decimal digits 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 fraction.*/ + an=comb(jp,k)*bn /*use COMBination for the next term. */ + $lcm=lcm(sd,ad) /*use Least Common Denominator function*/ + sn=$lcm%sd*sn; sd=$lcm /*calculate the current numerator. */ + an=$lcm%ad*an; ad=$lcm /* " " next " */ + sn=sn+an /* " " current " */ + end /*k*/ /* [↑] calculate the SN/SD sequence.*/ + sn=-sn /*adjust the sign for the numerator. */ + sd=sd*jp /*calculate the denominator. */ + if sn\==1 then do; _=gcd(sn, sd) /*get the Greatest Common Denominator.*/ + sn=sn%_; sd=sd%_ /*reduce the numerator and denominator.*/ + end /* [↑] done with the reduction(s). */ + @.j=sn'/'sd /*save the result for the next round. */ + end /*j*/ /* [↑] done calculating Bernoulli #'s.*/ 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-y0\55+\:2%68>*#<+#8\#62#%/#2:_$>:#,_$@ diff --git a/Task/Binary-digits/C++/binary-digits.cpp b/Task/Binary-digits/C++/binary-digits-1.cpp similarity index 100% rename from Task/Binary-digits/C++/binary-digits.cpp rename to Task/Binary-digits/C++/binary-digits-1.cpp diff --git a/Task/Binary-digits/C++/binary-digits-2.cpp b/Task/Binary-digits/C++/binary-digits-2.cpp new file mode 100644 index 0000000000..a728562a75 --- /dev/null +++ b/Task/Binary-digits/C++/binary-digits-2.cpp @@ -0,0 +1,14 @@ +#include +#include +void printBits(int n) { // Use int like most programming languages. + int iExp = 0; // Bit-length + while (n >> iExp) ++iExp; // Could use template + for (int at = iExp - 1; at >= 0; at--) // Reverse iter from the bit-length to 0 - msb is at end + std::cout << std::bitset<32>(n)[at]; // Show 1's, show lsb, hide leading zeros + std::cout << '\n'; +} +int main(int argc, char* argv[]) { + printBits(5); + printBits(50); + printBits(9000); +} // for testing with n=0 printBits<32>(0); diff --git a/Task/Binary-digits/C++/binary-digits-3.cpp b/Task/Binary-digits/C++/binary-digits-3.cpp new file mode 100644 index 0000000000..411105fe87 --- /dev/null +++ b/Task/Binary-digits/C++/binary-digits-3.cpp @@ -0,0 +1,8 @@ +#include +int main(int argc, char* argv[]) { + unsigned int in[] = {5, 50, 9000}; // Use int like most programming languages + for (int i = 0; i < 3; i++) // Use all inputs + for (int at = 31; at >= 0; at--) // reverse iteration from the max bit-length to 0, because msb is at the end + if (int b = (in[i] >> at)) // skip leading zeros. Start output when significant bits are set + std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num +} diff --git a/Task/Binary-digits/C++/binary-digits-4.cpp b/Task/Binary-digits/C++/binary-digits-4.cpp new file mode 100644 index 0000000000..d4a1ee0cc0 --- /dev/null +++ b/Task/Binary-digits/C++/binary-digits-4.cpp @@ -0,0 +1,7 @@ +#include +int main(int argc, char* argv[]) { // Usage: program.exe 5 50 9000 + for (int i = 1; i < argc; i++) // argv[0] is program name + for (int at = 31; at >= 0; at--) // reverse iteration from the max bit-length to 0, because msb is at the end + if (int b = (atoi(argv[i]) >> at)) // skip leading zeros + std::cout << ('0' + b & 1) << (!at ? "\n": ""); // '0' or '1'. Add EOL if last bit of num +} diff --git a/Task/Binary-digits/Elena/binary-digits.elena b/Task/Binary-digits/Elena/binary-digits.elena index 0a7e068b3b..196aa484d9 100644 --- a/Task/Binary-digits/Elena/binary-digits.elena +++ b/Task/Binary-digits/Elena/binary-digits.elena @@ -1,11 +1,11 @@ #define system. +#define system'routines. #define extensions. -// --- Program --- - #symbol program = [ - console writeLine:(convertor toLiteral:5 &base:2). - console writeLine:(convertor toLiteral:50 &base:2). - console writeLine:(convertor toLiteral:9000 &base:2). + (5,50,9000) run &each: n + [ + console writeLine:(n toLiteral &base:2). + ]. ]. diff --git a/Task/Binary-digits/Elixir/binary-digits-1.elixir b/Task/Binary-digits/Elixir/binary-digits-1.elixir new file mode 100644 index 0000000000..bb96e5a12b --- /dev/null +++ b/Task/Binary-digits/Elixir/binary-digits-1.elixir @@ -0,0 +1 @@ +IO.puts Integer.to_string(5,2) diff --git a/Task/Binary-digits/Elixir/binary-digits-2.elixir b/Task/Binary-digits/Elixir/binary-digits-2.elixir new file mode 100644 index 0000000000..a2d49651be --- /dev/null +++ b/Task/Binary-digits/Elixir/binary-digits-2.elixir @@ -0,0 +1 @@ +5 |> Integer.to_string(2) |> IO.puts diff --git a/Task/Binary-digits/Elixir/binary-digits-3.elixir b/Task/Binary-digits/Elixir/binary-digits-3.elixir new file mode 100644 index 0000000000..448add711b --- /dev/null +++ b/Task/Binary-digits/Elixir/binary-digits-3.elixir @@ -0,0 +1 @@ +[5,50,9000] |> Enum.map(fn n -> IO.puts Integer.to_string(n,2) end) diff --git a/Task/Binary-digits/Euphoria/binary-digits.euphoria b/Task/Binary-digits/Euphoria/binary-digits-1.euphoria similarity index 100% rename from Task/Binary-digits/Euphoria/binary-digits.euphoria rename to Task/Binary-digits/Euphoria/binary-digits-1.euphoria diff --git a/Task/Binary-digits/Euphoria/binary-digits-2.euphoria b/Task/Binary-digits/Euphoria/binary-digits-2.euphoria new file mode 100644 index 0000000000..f78a552487 --- /dev/null +++ b/Task/Binary-digits/Euphoria/binary-digits-2.euphoria @@ -0,0 +1,16 @@ +include std/math.e +include std/convert.e + +function Bin(integer n, sequence s = "") + if n > 0 then + return Bin(floor(n/2),(mod(n,2) + #30) & s) + end if + if length(s) = 0 then + return to_integer("0") + end if + return to_integer(s) +end function + +printf(1, "%d\n", Bin(5)) +printf(1, "%d\n", Bin(50)) +printf(1, "%d\n", Bin(9000)) diff --git a/Task/Binary-search/Fortran/binary-search-3.f b/Task/Binary-search/Fortran/binary-search-3.f new file mode 100644 index 0000000000..ea7942d6ab --- /dev/null +++ b/Task/Binary-search/Fortran/binary-search-3.f @@ -0,0 +1,20 @@ + INTEGER FUNCTION FINDI(X,A,N) !Binary chopper. Find i such that X = A(i) +Careful: it is surprisingly difficult to make this neat, due to vexations when N = 0 or 1. + REAL X,A(*) !Where is X in array A(1:N)? + INTEGER N !The count. + INTEGER L,R,P !Fingers. + L = 0 !Establish outer bounds, to search A(L+1:R-1). + R = N + 1 !L = first - 1; R = last + 1. + 1 P = (R - L)/2 !Probe point. Beware INTEGER overflow with (L + R)/2. + IF (P.LE.0) GO TO 5 !Aha! Nowhere!! The span is empty. + P = P + L !Convert an offset from L to an array index. + IF (X - A(P)) 3,4,2 !Compare to the probe point. + 2 L = P !A(P) < X. Shift the left bound up: X follows A(P). + GO TO 1 !Another chop. + 3 R = P !X < A(P). Shift the right bound down: X precedes A(P). + GO TO 1 !Try again. + 4 FINDI = P !A(P) = X. So, X is found, here! + RETURN !Done. +Curse it! + 5 FINDI = -L !X is not found. Insert it at L + 1, i.e. at A(1 - FINDI). + END FUNCTION FINDI !A's values need not be all different, merely in order. diff --git a/Task/Binary-search/Fortran/binary-search-4.f b/Task/Binary-search/Fortran/binary-search-4.f new file mode 100644 index 0000000000..f10593e1b0 --- /dev/null +++ b/Task/Binary-search/Fortran/binary-search-4.f @@ -0,0 +1,20 @@ + INTEGER FUNCTION FINDI(X,A,N) !Binary chopper. Find i such that X = A(i) +Careful: it is surprisingly difficult to make this neat, due to vexations when N = 0 or 1. + REAL X,A(*) !Where is X in array A(1:N)? + INTEGER N !The count. + INTEGER L,R,P !Fingers. + L = 0 !Establish outer bounds, to search A(L+1:R-1). + R = N + 1 !L = first - 1; R = last + 1. + GO TO 1 !Hop to it. + 2 L = P !A(P) < X. Shift the left bound up: X follows A(P). + 1 P = (R - L)/2 !Probe point. Beware INTEGER overflow with (L + R)/2. + IF (P.LE.0) GO TO 5 !Aha! Nowhere!! The span is empty. + P = P + L !Convert an offset from L to an array index. + IF (X - A(P)) 3,4,2 !Compare to the probe point. + 3 R = P !X < A(P). Shift the right bound down: X precedes A(P). + GO TO 1 !Try again. + 4 FINDI = P !A(P) = X. So, X is found, here! + RETURN !Done. +Curse it! + 5 FINDI = -L !X is not found. Insert it at L + 1, i.e. at A(1 - FINDI). + END FUNCTION FINDI !A's values need not be all different, merely in order. diff --git a/Task/Binary-search/Java/binary-search-1.java b/Task/Binary-search/Java/binary-search-1.java index 6d7bb6f14f..31cad26c88 100644 --- a/Task/Binary-search/Java/binary-search-1.java +++ b/Task/Binary-search/Java/binary-search-1.java @@ -5,7 +5,7 @@ public static int binarySearch(int[] nums, int check){ int hi = nums.length - 1; int lo = 0; while(hi >= lo){ - guess = lo + ((hi - lo) / 2); + int guess = lo + ((hi - lo) / 2); if(nums[guess] > check){ hi = guess - 1; }else if(nums[guess] < check){ diff --git a/Task/Binary-search/JavaScript/binary-search-1.js b/Task/Binary-search/JavaScript/binary-search-1.js index 9db7dd951f..4c149b0096 100644 --- a/Task/Binary-search/JavaScript/binary-search-1.js +++ b/Task/Binary-search/JavaScript/binary-search-1.js @@ -1,11 +1,13 @@ function binary_search_recursive(a, value, lo, hi) { - if (hi < lo) - return null; - var mid = Math.floor((lo+hi)/2); - if (a[mid] > value) - return binary_search_recursive(a, value, lo, mid-1); - else if (a[mid] < value) - return binary_search_recursive(a, value, mid+1, hi); - else - return mid; + if (hi < lo) { return null; } + + var mid = Math.floor((lo + hi) / 2); + + if (a[mid] > value) { + return binary_search_recursive(a, value, lo, mid - 1); + } + if (a[mid] < value) { + return binary_search_recursive(a, value, mid + 1, hi); + } + return mid; } diff --git a/Task/Binary-search/JavaScript/binary-search-2.js b/Task/Binary-search/JavaScript/binary-search-2.js index b2ba949fff..4318bd9b6e 100644 --- a/Task/Binary-search/JavaScript/binary-search-2.js +++ b/Task/Binary-search/JavaScript/binary-search-2.js @@ -1,14 +1,17 @@ function binary_search_iterative(a, value) { - lo = 0; - hi = a.length - 1; - while (lo <= hi) { - var mid = Math.floor((lo+hi)/2); - if (a[mid] > value) - hi = mid - 1; - else if (a[mid] < value) - lo = mid + 1; - else - return mid; + var mid, lo = 0, + hi = a.length - 1; + + while (lo <= hi) { + mid = Math.floor((lo + hi) / 2); + + if (a[mid] > value) { + hi = mid - 1; + } else if (a[mid] < value) { + lo = mid + 1; + } else { + return mid; } - return null; + } + return null; } diff --git a/Task/Binary-search/Perl/binary-search-1.pl b/Task/Binary-search/Perl/binary-search-1.pl index 1d9f4e117d..4671b81c4d 100644 --- a/Task/Binary-search/Perl/binary-search-1.pl +++ b/Task/Binary-search/Perl/binary-search-1.pl @@ -1,11 +1,11 @@ sub binary_search { my ($array_ref, $value, $left, $right) = @_; while ($left <= $right) { - my $middle = int(($right + $left) / 2); - if ($array_ref->[$middle] == $value) { - return 1; - } - if ($value < $array_ref->[$middle]) { + my $middle = int(($right + $left) >> 1); + return 1 if ($array_ref->[$middle] == $value); + if ($value == $array_ref->[$middle]) { + return middle; + } elsif ($value < $array_ref->[$middle]) { $right = $middle - 1; } else { $left = $middle + 1; diff --git a/Task/Binary-search/Perl/binary-search-2.pl b/Task/Binary-search/Perl/binary-search-2.pl index aa4ecb82fc..7d31f28a7c 100644 --- a/Task/Binary-search/Perl/binary-search-2.pl +++ b/Task/Binary-search/Perl/binary-search-2.pl @@ -1,13 +1,11 @@ sub binary_search { my ($array_ref, $value, $left, $right) = @_; - if ($right < $left) { - return 0; - } - my $middle = int(($right + $left) / 2); - if ($array_ref->[$middle] == $value) { - return 1; - } - if ($value < $array_ref->[$middle]) { + return 0 if ($right < $left); + my $middle = int(($right + $left) >> 1); + return 1 if ($array_ref->[$middle] == $value); + if ($value == $array_ref->[$middle]) { + return middle; + } elsif ($value < $array_ref->[$middle]) { binary_search($array_ref, $value, $left, $middle - 1); } else { binary_search($array_ref, $value, $middle + 1, $right); diff --git a/Task/Binary-search/Ruby/binary-search-1.rb b/Task/Binary-search/Ruby/binary-search-1.rb index 070f3987d8..9c6e6cba4a 100644 --- a/Task/Binary-search/Ruby/binary-search-1.rb +++ b/Task/Binary-search/Ruby/binary-search-1.rb @@ -1,10 +1,12 @@ class Array def binary_search(val, low=0, high=(length - 1)) return nil if high < low - mid = (low + high) / 2 - case - when self[mid] > val then binary_search(val, low, mid-1) - when self[mid] < val then binary_search(val, mid+1, high) + mid = (low + high) >> 1 + case var <=> self[mid] + when -1 + binary_search(val, low, mid - 1) + when 1 + binary_search(val, mid + 1, high) else mid end end diff --git a/Task/Binary-search/Ruby/binary-search-2.rb b/Task/Binary-search/Ruby/binary-search-2.rb index a9f8d2d223..1a77e72306 100644 --- a/Task/Binary-search/Ruby/binary-search-2.rb +++ b/Task/Binary-search/Ruby/binary-search-2.rb @@ -2,11 +2,14 @@ class Array def binary_search_iterative(val) low, high = 0, length - 1 while low <= high - mid = (low + high) / 2 - case - when self[mid] > val then high = mid - 1 - when self[mid] < val then low = mid + 1 - else return mid + mid = (low + high) >> 1 + case var <=> self[mid] + when 1 + low = mid + 1 + when -1 + high = mid - 1 + else + return mid end end nil diff --git a/Task/Binary-search/Rust/binary-search.rust b/Task/Binary-search/Rust/binary-search.rust index 96f15fa1af..4a4bd8563e 100644 --- a/Task/Binary-search/Rust/binary-search.rust +++ b/Task/Binary-search/Rust/binary-search.rust @@ -1,17 +1,17 @@ -fn binary_search(haystack: ~[int], needle: int) -> int { - let mut low = 0; - let mut high = haystack.len() as int - 1; - - if high == 0 { return -1 } - - while low <= high { - // avoid overflow - let mid = low + (high - low) / 2; - - if haystack[mid] > needle { high = mid - 1 } - else if haystack[mid] < needle { low = mid + 1 } - else { return mid } +fn bin_search(sar : &[T], v : &T) -> Option { + let mut lowi=0; + let mut highi=sar.len(); + loop { + if lowi>=highi { + return None; + } + let mi=lowi+(highi-lowi)/2; + if sar[mi].lt(v) { + lowi=mi+1; + } else if sar[mi].gt(v) { + highi=mi; + } else { + return Some(mi); + } } - - return -1; } diff --git a/Task/Binary-search/UNIX-Shell/binary-search-1.sh b/Task/Binary-search/UNIX-Shell/binary-search-1.sh new file mode 100644 index 0000000000..3b4fff2fe7 --- /dev/null +++ b/Task/Binary-search/UNIX-Shell/binary-search-1.sh @@ -0,0 +1,11 @@ +#!/bin/ksh +# This should work on any clone of Bourne Shell, ksh is the fastest. + +value=$1; [ -z "$value" ] && exit +array=() +size=0 + +while IFS= read -r line; do + size=$(($size + 1)) + array[${#array[*]}]=$line +done diff --git a/Task/Binary-search/UNIX-Shell/binary-search-2.sh b/Task/Binary-search/UNIX-Shell/binary-search-2.sh new file mode 100644 index 0000000000..faba8b3821 --- /dev/null +++ b/Task/Binary-search/UNIX-Shell/binary-search-2.sh @@ -0,0 +1,15 @@ +left=0 +right=$(($size - 1)) +while [ $left -le $right ] ; do + mid=$((($left + $right) >> 1)) +# echo "$left $mid(${array[$mid]}) $right" + if [ $value -eq ${array[$mid]} ] ; then + echo $mid + exit + elif [ $value -lt ${array[$mid]} ]; then + right=$(($mid - 1)) + else + left=$((mid + 1)) + fi +done +echo 'ERROR 404 : NOT FOUND' diff --git a/Task/Binary-search/UNIX-Shell/binary-search-3.sh b/Task/Binary-search/UNIX-Shell/binary-search-3.sh new file mode 100644 index 0000000000..f80055cb17 --- /dev/null +++ b/Task/Binary-search/UNIX-Shell/binary-search-3.sh @@ -0,0 +1 @@ + No code yet diff --git a/Task/Binary-search/VBScript/binary-search.vb b/Task/Binary-search/VBScript/binary-search.vb new file mode 100644 index 0000000000..fc18dfe54b --- /dev/null +++ b/Task/Binary-search/VBScript/binary-search.vb @@ -0,0 +1,27 @@ +Function binary_search(arr,value,lo,hi) + If hi < lo Then + binary_search = 0 + Else + middle=Int((hi+lo)/2) + If value < arr(middle) Then + binary_search = binary_search(arr,value,lo,middle-1) + ElseIf value > arr(middle) Then + binary_search = binary_search(arr,value,middle+1,hi) + Else + binary_search = middle + Exit Function + End If + End If +End Function + +'Tesing the function. +num_range = Array(2,3,5,6,8,10,11,15,19,20) +n = CInt(WScript.Arguments(0)) +idx = binary_search(num_range,n,LBound(num_range),UBound(num_range)) +If idx > 0 Then + WScript.StdOut.Write n & " found at index " & idx + WScript.StdOut.WriteLine +Else + WScript.StdOut.Write n & " not found" + WScript.StdOut.WriteLine +End If diff --git a/Task/Binary-strings/Forth/binary-strings-1.fth b/Task/Binary-strings/Forth/binary-strings-1.fth index e0f90e0512..51ec7bdb7d 100644 --- a/Task/Binary-strings/Forth/binary-strings-1.fth +++ b/Task/Binary-strings/Forth/binary-strings-1.fth @@ -1,8 +1,96 @@ -create cstr1 ," A sample string" -create cstr2 ," another string" -create buf 256 allot - -cstr1 count buf place -s" and " buf +place -cstr2 count buf +place -buf count type \ A sample string and another string +\ Rosetta Code Binary Strings Demo in Forth +\ Portions of this code are found at http://forth.sourceforge.net/mirror/toolbelt-ext/index.html + +\ String words created in this code: +\ STR< STR> STR= COMPARESTR SUBSTR STRPAD CLEARSTR +\ ="" =" STRING: MAXLEN REPLACE-CHAR COPYSTR WRITESTR +\ ," APPEND-CHAR STRING, PLACE CONCAT APPEND C+! ENDSTR +\ COUNT STRLEN + +: STRLEN ( addr -- length) c@ ; \ alias the "character fetch" operator + +: COUNT ( addr -- addr+1 length) \ returns the address+1 and the length byte on the stack + dup strlen swap 1+ swap ; + +: ENDSTR ( str -- addr) \ calculate the address at the end of a string + COUNT + ; + +: C+! ( n addr -- ) \ primitive: increment a byte at addr by n + DUP C@ ROT + SWAP C! ; + +: APPEND ( addr1 length addr2 -- ) \ Append addr1 length to addr2 + 2dup 2>r endstr swap move 2r> c+! ; + +: CONCAT ( string1 string2 -- ) \ concatenate counted string1 to counted string2 + >r COUNT R> APPEND ; + +: PLACE ( addr1 len addr2 -- ) \ addr1 and length, placed at addr2 as counted string + 2dup 2>r 1+ swap move 2r> c! ; + +: STRING, ( addr len -- ) \ compile a string at the next available memory (called 'HERE') + here over 1+ allot place ; + +: APPEND-CHAR ( char string -- ) \ append char to string + dup >r count dup 1+ r> c! + c! ; + +: ," [CHAR] " PARSE STRING, ; \ Parse input stream until '"' and compile into memory + + +: WRITESTR ( string -- ) \ output a counted string with a carriage return + count type CR ; + +: COPYSTR ( string1 string3 -- ) \ String cloning and copying COPYSTR + >r count r> PLACE ; + +: REPLACE-CHAR ( char1 char2 string -- ) \ replace all char2 with char1 in string + count \ get string's address and length + BOUNDS \ calc start and end addr of string for do-loop + DO \ do a loop from start address to end address + I C@ OVER = \ fetch the char at loop index compare to CHAR2 + IF + OVER I C! \ if its equal, store CHAR1 into the index address + THEN + LOOP + 2drop ; \ drop the chars off the stack + + + 256 constant maxlen \ max size of byte counted string in this example + +: string: CREATE maxlen ALLOT ; \ simple string variable constructor + + +: =" ( string -- ) \ String variable assignment operator (compile time only) + [char] " PARSE ROT PLACE ; + +: ="" ( string -- ) 0 swap c! ; \ empty a string, set count to zero + + +: clearstr ( string -- ) \ erase a string variables contents, fill with 0 + maxlen erase ; + + + string: strpad \ general purpose storage buffer + +: substr ( string1 start length -- strpad) \ Extract a substring of string and return an output string + strpad ="" \ clear strpad + >r \ push the length + + \ calc the new start addr + r> strpad append \ pop the length and append to strpad + strpad ; \ return the address of strpad. + + +\ COMPARE takes the 4 inputs from the stack (addr1 len1 addr2 len2 ) +\ and returns a flag for equal (0) , less-than (1) or greater-than (-1) on the stack + + : comparestr ( string1 string2 -- flag) \ adapt for use with counted strings + count rot count compare ; + +\ now it's simple to make new operators + : STR= ( string1 string2 -- flag) + comparestr 0= ; + + : STR> ( string1 string2 -- flag) + comparestr -1 = ; + + : STR< ( string1 string2 -- flag) + comparestr 1 = ; diff --git a/Task/Binary-strings/Forth/binary-strings-2.fth b/Task/Binary-strings/Forth/binary-strings-2.fth index 1f13f36649..2445052cd2 100644 --- a/Task/Binary-strings/Forth/binary-strings-2.fth +++ b/Task/Binary-strings/Forth/binary-strings-2.fth @@ -1,6 +1,124 @@ -: empty? ( str len -- ? ) nip 0= ; -: +c ( c str len -- ) + c! ; -: replace-bytes ( from to str len -- ) - bounds do - over i c@ = if dup i c! then - loop 2drop ; +\ Rosetta Code Binary String tasks Console Tests + +\ 1. String creation and destruction (when needed and if there's no garbage collection or similar mechanism) + +\ RAW Forth can manually create a binary string with the C, operator +\ C, takes a byte off the stack and writes it into the next available memory address +\ 'binary_string' drops it's data address on the stack. Nothing more. + +HEX ok + create binary_string 9 c, 1 c, 2 c, 3 c, 4 c, 5 c, + 0A c, 0B c, 0C c, 0FF c, \ 1st byte is length +ok + +\ test what we created using the DUMP utility + binary_string count dump +25EC:7365 01 02 03 04 05 0A 0B 0C FF 04 44 55 4D 50 00 20 ..........DUMP. +ok + + +\ create static string variables using our constructor ok + string: buffer1 ok + string: buffer2 ok + +DECIMAL ok + +\ 2. String assignment + +\ create string constants with assignments(static, counted strings) ok + create string1 ," Now is the time for all good men to come to the aid" + create string2 ," Right now!" ok + +\ assign text to string variables with syntacic sugar + buffer1 =" This text will go into the memory allocated for buffer1" ok + buffer2 ="" ok + +\ or use S" and PLACE + S" The rain in Spain..." buffer2 PLACE ok + +\ Test the assignments + string2 writestr Right now! + ok + string1 writestr Now is the time for all good men to come to the aid + ok + buffer1 writestr This text will go into the memory allocated for buffer1 + ok + buffer2 writestr The rain in Spain... + ok + + +\ destroy string contents. Fill string with zero + buffer1 clearstr ok + buffer1 40 dump +25EC:7370 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ +25EC:7380 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ +25EC:7390 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + ok + +\ 3. String comparison. ( the '.' prints the top of the stack in these examples) + buffer1 buffer2 STR= . ( should be 0 FALSE flag) -1 ok + buffer1 =" ABCDEFG" ok + buffer2 =" ABCDEFG" ok + + buffer1 buffer2 STR= . ( should be -1, TRUE flag) -1 ok + string1 buffer1 str> . ( should be 0) 0 ok + string1 buffer1 str< . ( should be -1) -1 ok + + +\ 4. String cloning and copying + string1 buffer1 COPYSTR ok + + string1 writestr Now is the time for all good men to come to the aid ok + buffer1 writestr Now is the time for all good men to come to the aid ok + + + +\ 5. Check if a string is empty + buffer1 len . 55 ok + buffer1 ="" \ assign null string ok + buffer1 len . 0 ok + + + +\ 6. Append a byte to a string + buffer2 =" Append this" ok + buffer2 writestr Append this + ok + char ! buffer2 APPEND-CHAR ok + buffer2 writestr Append this! + ok +hex ok + 0A buffer2 APPEND-CHAR \ append a raw carriage return ok + 0D buffer2 APPEND-CHAR \ append a raw line-feed ok + ok + buffer2 writestr Append this! + + ok +\ we see the extra line before OK so Appending binary chars worked + + decimal ok + +\ 7. Extract a substring from a string. Result placed in a temp buffer automagically + + string1 writestr Now is the time for all good men to come to the aid ok + + string1 5 11 substr writestr is the time ok + + +\ 8. Replace every occurrence of a byte (or a string) in a string with another string +\ BL is a system constant for "Blank" ie the space character (HEX 020) + + buffer1 =" This*string*is*full*of*stars*" ok + ok + BL char * buffer1 REPLACE-CHAR ok + buffer1 writestr This string is full of stars + ok + + +\ 9. Join strings + buffer1 =" James " ok + buffer2 =" Alexander" ok + buffer2 buffer1 CONCAT ok + ok + buffer1 writestr James Alexander + ok diff --git a/Task/Binary-strings/J/binary-strings-5.j b/Task/Binary-strings/J/binary-strings-5.j index 1f067bf642..e6929eb563 100644 --- a/Task/Binary-strings/J/binary-strings-5.j +++ b/Task/Binary-strings/J/binary-strings-5.j @@ -1,2 +1,2 @@ - name1= 'example' - name2= name1 + name1=: 'example' + name2=: name1 diff --git a/Task/Bitcoin-public-point-to-address/Haskell/bitcoin-public-point-to-address.hs b/Task/Bitcoin-public-point-to-address/Haskell/bitcoin-public-point-to-address.hs new file mode 100644 index 0000000000..1c7fc09e79 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Haskell/bitcoin-public-point-to-address.hs @@ -0,0 +1,20 @@ +import Numeric (showIntAtBase) +import Data.List (unfoldr) +import Data.Binary (Word8) +import Crypto.Hash.SHA256 as S (hash) +import Crypto.Hash.RIPEMD160 as R (hash) +import Data.ByteString (unpack, pack) + +publicPointToAddress :: Integer -> Integer -> String +publicPointToAddress x y = + let toBytes x = reverse $ unfoldr (\b -> if b == 0 then Nothing else Just (fromIntegral $ b `mod` 256, b `div` 256)) x + ripe = 0 : unpack (R.hash $ S.hash $ pack $ 4 : toBytes x ++ toBytes y) + ripe_checksum = take 4 $ unpack $ S.hash $ S.hash $ pack ripe + addressAsList = ripe ++ ripe_checksum + address = foldl (\v b -> v * 256 + fromIntegral b) 0 addressAsList + base58Digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + in showIntAtBase 58 (base58Digits !!) address "" + +main = print $ publicPointToAddress + 0x50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352 + 0x2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6 diff --git a/Task/Bitcoin-public-point-to-address/Python/bitcoin-public-point-to-address.py b/Task/Bitcoin-public-point-to-address/Python/bitcoin-public-point-to-address.py new file mode 100644 index 0000000000..bcd2ab0b2c --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Python/bitcoin-public-point-to-address.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 + +import binascii +import functools +import hashlib + +digits58 = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' + +def b58(n): + return b58(n//58) + digits58[n%58:n%58+1] if n else b'' + +def public_point_to_address(x, y): + c = b'\x04' + binascii.unhexlify(x) + binascii.unhexlify(y) + r = hashlib.new('ripemd160') + r.update(hashlib.sha256(c).digest()) + c = b'\x00' + r.digest() + d = hashlib.sha256(hashlib.sha256(c).digest()).digest() + return b58(functools.reduce(lambda n, b: n<<8|b, c + d[:4])) + +if __name__ == '__main__': + print(public_point_to_address( + b'50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352', + b'2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6')) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.autoit b/Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.autoit new file mode 100644 index 0000000000..60a2debaef --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/AutoIt/bitmap-bresenhams-line-algorithm.autoit @@ -0,0 +1,23 @@ +Local $var = drawBresenhamLine(2, 3, 2, 6) + +Func drawBresenhamLine($iX0, $iY0, $iX1, $iY1) + Local $iDx = Abs($iX1 - $iX0) + Local $iSx = $iX0 < $iX1 ? 1 : -1 + Local $iDy = Abs($iY1 - $iY0) + Local $iSy = $iY0 < $iY1 ? 1 : -1 + Local $iErr = ($iDx > $iDy ? $iDx : -$iDy) / 2, $e2 + + While $iX0 <= $iX1 + ConsoleWrite("plot( $x=" & $iX0 & ", $y=" & $iY0 & " )" & @LF) + If ($iX0 = $iX1) And ($iY0 = $iY1) Then Return + $e2 = $iErr + If ($e2 > -$iDx) Then + $iErr -= $iDy + $iX0 += $iSx + EndIf + If ($e2 < $iDy) Then + $iErr += $iDx + $iY0 += $iSy + EndIf + WEnd +EndFunc ;==>drawBresenhamLine diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia b/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia new file mode 100644 index 0000000000..d5fae39810 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia @@ -0,0 +1,23 @@ +function line(img, x0::Int, y0::Int, x1::Int, y1::Int, col) + dx = int(abs(x1-x0)) + dy = int(abs(y1-y0)) + + sx = x0dy ? dx : -dy)/2 + + while true + @inbounds img[x0,y0]=col + if (x0==x1 && y0==y1); break; end + e2 = err; + if e2 > -dx + err -= dy + x0 += sx + end + if e2 < dy + err += dx + y0 += sy + end + end +end diff --git a/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-1.rexx b/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-1.rexx index a665e53ed3..a2a311cae6 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-1.rexx +++ b/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-1.rexx @@ -1,43 +1,42 @@ -/*REXX program plots/draws line(s) using the Bresenham's line algorithm.*/ -@.='·' /*fill the array with middle─dots*/ -parse arg data /*allow data point specifications*/ -if data='' then data= '(1,8) (8,16) (16,8) (8,1) (1,8)' /*rhombus*/ -data=translate(data,,'()[]{}/,:;') /*elide chaff from data points. */ - /* [↓] data pt pairs ──► !.array.*/ - do points=1 while data\='' /*put data points into an array. */ - parse var data x y data; !.points=x y /*extract line segments.*/ - if points==1 then do; minX=x; maxX=x; minY=y; maxY=y; end /*1st case*/ - minX=min(minX,x); maxX=max(maxX,x); minY=min(minY,y); maxY=max(maxY,y) - end /*points*/ /* [↑] data points pairs in !. */ +/*REXX program plots/draws line segments using the Bresenham's line algorithm.*/ +@.='·' /*fill the array with middle─dots chars*/ +parse arg data /*allow the data point specifications. */ +if data='' then data= '(1,8) (8,16) (16,8) (8,1) (1,8)' /*◄────rhombus.*/ +data=translate(data,,'()[]{}/,:;') /*elide chaff from the data points. */ + /* [↓] data point pairs ───► !.array. */ + do points=1 while data\='' /*put the data points into an array (!)*/ + parse var data x y data; !.points=x y /*extract the line segments. */ + if points==1 then do; minX=x; maxX=x; minY=y; maxY=y; end /*1st case.*/ + minX=min(minX,x); maxX=max(maxX,x); minY=min(minY,y); maxY=max(maxY,y) + end /*points*/ /* [↑] data points pairs in array !. */ -border=2 /*border=extra space around plot.*/ -minX=minX-border*2; maxX=maxX+border*2 /*min,max X for the plot display.*/ -minY=minY-border ; maxY=maxY+border /* " " Y " " " " */ - do x=minX to maxX; @.x.0='─'; end /*draw dash from left──► right.*/ - do y=minY to maxY; @.0.y='│'; end /*draw pipe from lowest──►highest*/ -@.0.0='┼' /*define the plot's axis point. */ - do seg=2 to points-1; _=seg-1 /*obtain the X,Y line coördinates*/ - call draw_line !._, !.seg /*draw (plot) a line segment. */ - end /*seg*/ /* [↑] drawing the line segments*/ - /* [↓] display the plot to term.*/ - do y=maxY to minY by -1; _= /*display plot one line at a time*/ - do x=minX to maxX /*traipse throught the X axis. */ - _=_ || @.x.y /*construct a "line" of the plot.*/ - end /*x*/ /*(a line is a "row" of points.) */ - say _ /*display a "line" of the plot. */ - end /*y*/ /* [↑] all done ploting the pts.*/ -exit /*stick a fork in it, we're done.*/ -/*────────────────────────────────DRAW_LINE subroutine──────────────────*/ -draw_line: procedure expose @.; parse arg x y,xf yf; plotChar='Θ' -dx=abs(xf-x); if x -dy then do; err=err-dy; x=x+sx; end - if err2 < dx then do; err=err+dx; y=y+sy; end +err=dx-dy /*calculate error between adjustments. */ + do forever; @.x.y=plotChar /*plot the points until it's complete. */ + if x=xf & y=yf then return /*are the plot points at the finish? */ + err2=err+err /*addition is faster than: err*2. */ + if err2 > -dy then do; err=err-dy; x=x+sx; end + if err2 < dx then do; err=err+dx; y=y+sy; end end /*forever*/ -return diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Scala/bitmap-bresenhams-line-algorithm.scala b/Task/Bitmap-Bresenhams-line-algorithm/Scala/bitmap-bresenhams-line-algorithm.scala index 4896181acb..0b4cb5aaae 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Scala/bitmap-bresenhams-line-algorithm.scala +++ b/Task/Bitmap-Bresenhams-line-algorithm/Scala/bitmap-bresenhams-line-algorithm.scala @@ -15,7 +15,7 @@ object BitmapOps { if (e2 +#include +#include + +using namespace cv; +using namespace std; + +class FloodFillAlgorithm { +public: + FloodFillAlgorithm(Mat* image) : + image(image) { + } + virtual ~FloodFillAlgorithm(); + + void flood(Point startPoint, Scalar tgtColor, Scalar loDiff); + void flood(Point startPoint, Mat* tgtMat); + +protected: + Mat* image; +private: + bool insideImage(Point p); +}; + +#endif /* PROCESSING_FLOODFILLALGORITHM_H_ */ diff --git a/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp b/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp new file mode 100644 index 0000000000..3518acceab --- /dev/null +++ b/Task/Bitmap-Flood-fill/C++/bitmap-flood-fill-2.cpp @@ -0,0 +1,43 @@ +#include "FloodFillAlgorithm.h" + +FloodFillAlgorithm::~FloodFillAlgorithm() { +} + +void FloodFillAlgorithm::flood(Point startPoint, Scalar tgtColor, Scalar loDiff) { + floodFill(*image, startPoint, tgtColor, 0, loDiff); +} + +void FloodFillAlgorithm::flood(Point startPoint, Mat* tgtMat) { + if (!insideImage(startPoint)) + return; + + Vec3b srcColor = image->at(startPoint); + + if (image->at(startPoint) == srcColor) { + + queue pointQueue; + pointQueue.push(startPoint); + + while (!pointQueue.empty()) { + Point p = pointQueue.front(); + pointQueue.pop(); + + if (insideImage(p)) { + + if ((image->at(p) == srcColor)) { + image->at(p) = tgtMat->at(p); + + pointQueue.push(Point(p.x + 1, p.y)); + pointQueue.push(Point(p.x - 1, p.y)); + pointQueue.push(Point(p.x, p.y + 1)); + pointQueue.push(Point(p.x, p.y - 1)); + } + } + + } + } +} + +bool FloodFillAlgorithm::insideImage(Point p) { + return (p.x >= 0) && (p.x < image->size().width) && (p.y >= 0) && (p.y < image->size().height); +} diff --git a/Task/Bitmap-Histogram/Julia/bitmap-histogram.julia b/Task/Bitmap-Histogram/Julia/bitmap-histogram.julia new file mode 100644 index 0000000000..549e8d8a3a --- /dev/null +++ b/Task/Bitmap-Histogram/Julia/bitmap-histogram.julia @@ -0,0 +1,15 @@ +using Color, Images, FixedPointNumbers + +ima = imread("bitmap_histogram_in.jpg") +imb = convert(Image{Gray{Ufixed8}}, ima) + +# calculate histogram +a = map(x->x.val.i, imb.data) +(nothing, h) = hist(reshape(a, length(a)), -1:typemax(Uint8)) + +g = float(imb.data) +b = g .> median(g) +fill!(imb, Gray(0.0)) +imb[b] = Gray(1.0) + +imwrite(imb, "bitmap_histogram_out.png") diff --git a/Task/Bitmap-Midpoint-circle-algorithm/BASIC256/bitmap-midpoint-circle-algorithm.basic256 b/Task/Bitmap-Midpoint-circle-algorithm/BASIC256/bitmap-midpoint-circle-algorithm.basic256 new file mode 100644 index 0000000000..bacbdc429a --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/BASIC256/bitmap-midpoint-circle-algorithm.basic256 @@ -0,0 +1,39 @@ +fastgraphics +clg +color red +call DrawCircle(150,100,100) +refresh +color blue +call DrawCircle(200,200,50) +refresh + + #Function DrawCircle + #1st param = X-coord of center + #2nd param = Y-coord of center + #3rd param = radius +Function DrawCircle(x0,y0,radius) + x=radius + y=0 + decisionOver2=1-x + + while x>=y + plot( x + x0, y + y0) + plot( y + x0, x + y0) + plot(-x + x0, y + y0) + plot(-y + x0, x + y0) + plot(-x + x0, -y + y0) + plot(-y + x0, -x + y0) + plot( x + x0, -y + y0) + plot( y + x0, -x + y0) + + y++ + + if decisionOver2<=0 then + decisionOver2+=2*y+1 + else + x-- + decisionOver2+=2*(y-x)+1 + end if + end while + return 0 +End Function diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat b/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat new file mode 100644 index 0000000000..45665a2733 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Batch-File/bitmap-midpoint-circle-algorithm.bat @@ -0,0 +1,72 @@ +@echo off +setlocal enabledelayedexpansion + + %== Initializations ==% +set width=50 +set height=30 + +set /a allowance=height+2 +mode %width%,%allowance% +echo Rendering... + +set "outp=" +for /l %%i in (1,1,%height%) do ( + for /l %%j in (1,1,%width%) do ( + set "c[%%i][%%j]= " + ) +) + + %== Set the parameters for making circle ==% +call :DrawCircle 20 20 10 +call :DrawCircle 10 30 15 + + %== Output result ==% +for /l %%i in (1,1,%height%) do ( + for /l %%j in (1,1,%width%) do ( + set "outp=!outp!!c[%%i][%%j]!" + ) +) +cls +echo !outp! +pause>nul +exit /b + + %== The main function ==% +:DrawCircle + set x0=%1 + set y0=%2 + set radius=%3 + + set x=!radius! + set y=0 + set /a decisionOver2 = 1 - !x! + + :circle_loop + if !x! geq !y! ( + set /a "hor=x + x0","ver=y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=y + x0","ver=x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-x + x0","ver=y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-y + x0","ver=x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-x + x0","ver=-y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=-y + x0","ver=-x + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=x + x0","ver=-y + y0" + set "c[!hor!][!ver!]=Û" + set /a "hor=y + x0","ver=-x + y0" + set "c[!hor!][!ver!]=Û" + + set /a y+=1 + if !decisionOver2! leq 0 ( + set /a "decisionOver2 = !decisionOver2! + (2 * y^) + 1" + ) else ( + set /a x-=1 + set /a "decisionOver2 = !decisionOver2! + 2 * (y - x^) + 1" + ) + goto circle_loop + ) +goto :EOF diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Clojure/bitmap-midpoint-circle-algorithm-1.clj b/Task/Bitmap-Midpoint-circle-algorithm/Clojure/bitmap-midpoint-circle-algorithm-1.clj new file mode 100644 index 0000000000..241572a36f --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Clojure/bitmap-midpoint-circle-algorithm-1.clj @@ -0,0 +1,26 @@ +(defn draw-circle [draw-function x0 y0 radius] + (letfn [(put [x y m] + (let [x+ (+ x0 x) + x- (- x0 x) + y+ (+ y0 y) + y- (- y0 y) + x0y+ (+ x0 y) + x0y- (- x0 y) + xy0+ (+ y0 x) + xy0- (- y0 x)] + (draw-function x+ y+) + (draw-function x+ y-) + (draw-function x- y+) + (draw-function x- y-) + (draw-function x0y+ xy0+) + (draw-function x0y+ xy0-) + (draw-function x0y- xy0+) + (draw-function x0y- xy0-) + (let [[y m] (if (pos? m) + [(dec y) (- m (* 8 y))] + [y m])] + (when (<= x y) + (put (inc x) + y + (+ m 4 (* 8 x)))))))] + (put 0 radius (- 5 (* 4 radius))))) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Clojure/bitmap-midpoint-circle-algorithm-2.clj b/Task/Bitmap-Midpoint-circle-algorithm/Clojure/bitmap-midpoint-circle-algorithm-2.clj new file mode 100644 index 0000000000..a4e755551b --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Clojure/bitmap-midpoint-circle-algorithm-2.clj @@ -0,0 +1,10 @@ +(let [circle-points (atom [])] + (letfn [(draw-fn [x y] + (swap! circle-points #(conj % [x y])))] + (draw-circle draw-fn 10 10 7)) + (let [empty-grid (vec (repeat 20 (vec (repeat 20 " ")))) + grid (reduce (fn [grid xy] (assoc-in grid xy "x")) + empty-grid + @circle-points)] + (doseq [line grid] + (println (clojure.string/join line))))) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/REXX/bitmap-midpoint-circle-algorithm.rexx b/Task/Bitmap-Midpoint-circle-algorithm/REXX/bitmap-midpoint-circle-algorithm.rexx index a5ed2b3f8b..48607a0130 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/REXX/bitmap-midpoint-circle-algorithm.rexx +++ b/Task/Bitmap-Midpoint-circle-algorithm/REXX/bitmap-midpoint-circle-algorithm.rexx @@ -1,43 +1,43 @@ -/*REXX pgm plots 3 circles using midpoint/Bresenham's circle algorithm. */ -@. = '·' /*fill the array with middle-dots*/ -minX=0; maxX=0; minY=0; maxY=0 /*initialize minimums & maximums.*/ -call drawCircle 0, 0, 8, '#' /*plot 1st circle with pound char*/ -call drawCircle 0, 0, 11, '$' /* " 2nd " " dollar " */ -call drawCircle 0, 0, 19, '@' /* " 3rd " " commer. at*/ -border=2 /*BORDER: shows N extra grid pts*/ -minX=minX-border*2; maxX=maxX+border*2 /*adjust min&max X to show border*/ -minY=minY-border ; maxY=maxY+border /* " " " Y " " " */ -if @.0.0==@. then @.0.0='┼' /*maybe define plot's axis origin*/ - /* [↓] define horizontal grid. */ - do gx=minX to maxX; if @.gx.0==@. then @.gx.0='─'; end /*gx*/ - do gy=minY to maxY; if @.0.gy==@. then @.0.gy='│'; end /*gy*/ - /* [↑] define the vertical grid.*/ - do y=maxY by -1 to minY; aRow= /* [↓] draw grid from top to bot.*/ - do x=minX to maxX /* [↓] " " " left──►right*/ - aRow=aRow || @.x.y /*build a grid row, char by char.*/ - end /*x*/ /* [↑] a grid row should be done*/ - say aRow /*display signal row of the grid.*/ +/*REXX program plots three circles using midpoint/Bresenham's circle algorithm*/ +@. = '·' /*fill the array with middle─dots char.*/ +minX=0; maxX=0; minY=0; maxY=0 /*initialize the minimums and maximums.*/ +call drawCircle 0, 0, 8, '#' /*plot 1st circle with pound character.*/ +call drawCircle 0, 0, 11, '$' /* " 2nd " " dollar " */ +call drawCircle 0, 0, 19, '@' /* " 3rd " " commercial at. */ +border=2 /*BORDER: shows N extra grid points.*/ +minX=minX-border*2; maxX=maxX+border*2 /*adjust min and max X to show border*/ +minY=minY-border ; maxY=maxY+border /* " " " " Y " " " */ +if @.0.0==@. then @.0.0='┼' /*maybe define the plot's axis origin. */ + /*define the plot's horizontal grid──┐ */ + do h=minX to maxX; if @.h.0==@. then @.h.0='─'; end /* ◄───────────┘ */ + do v=minY to maxY; if @.0.v==@. then @.0.v='│'; end /* ◄──────────┐ */ + /*define the plot's vertical grid───┘ */ + do y=maxY by -1 to minY; aRow= /* [↓] draw grid from top ──► bottom.*/ + do x=minX to maxX /* [↓] " " " left ──► right. */ + aRow=aRow || @.x.y /*build a grid row, one char at a time.*/ + end /*x*/ /* [↑] a grid row should be finished. */ + say aRow /*display a single row of the grid. */ end /*y*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────DRAWCIRCLE subroutine──────────────*/ -drawCircle: procedure expose @. minX maxX minY maxY -parse arg xx,yy,r,plotChar; f=1-r; fx=1; fy=-2*r; y=r +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +drawCircle: procedure expose @. minX maxX minY maxY /* [↓] Y is defined as R*/ +parse arg xx,yy,r 1 y,plotChar; f=1-r; fx=1; fy=-2*r /*get the X,Y coördinates*/ - do x=0 while x=0 then do; y=y-1; fy=fy+2; f=f+fy; end - fx=fx+2; f=f+fx - call plotPoint xx+x, yy+y, plotChar - call plotPoint xx+y, yy+x, plotChar - call plotPoint xx+y, yy-x, plotChar - call plotPoint xx+x, yy-y, plotChar - call plotPoint xx-y, yy+x, plotChar - call plotPoint xx-x, yy+y, plotChar - call plotPoint xx-x, yy-y, plotChar - call plotPoint xx-y, yy-x, plotChar - end /*x*/ /* [↑] place plot points ══► plot*/ + do x=0 while x=0 then do; y=y-1; fy=fy+2; f=f+fy; end /*▒*/ + fx=fx+2; f=f+fx /*▒*/ + call plotPoint xx+x, yy+y /*▒*/ + call plotPoint xx+y, yy+x /*▒*/ + call plotPoint xx+y, yy-x /*▒*/ + call plotPoint xx+x, yy-y /*▒*/ + call plotPoint xx-y, yy+x /*▒*/ + call plotPoint xx-x, yy+y /*▒*/ + call plotPoint xx-x, yy-y /*▒*/ + call plotPoint xx-y, yy-x /*▒*/ + end /*x*/ /* [↑] place plot points ══► plot.▒▒▒▒▒▒▒▒▒▒▒▒▒*/ return -/*──────────────────────────────────PLOTPOINT subroutine────────────────*/ -plotPoint: procedure expose @. minX maxX minY maxY -parse arg xx,yy,@.xx.yy; minX=min(minX,xx); maxX=max(maxX,xx) - minY=min(minY,yy); maxY=max(maxY,yy) +/*────────────────────────────────────────────────────────────────────────────*/ +plotPoint: parse arg c,r; @.c.r=plotChar /*assign a character to be plotted.*/ +minX=min(minX,c); maxX=max(maxX,c) /*find the minimum and maximum X. */ +minY=min(minY,r); maxY=max(maxY,r) /* " " " " " Y. */ return diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe.go b/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe.go new file mode 100644 index 0000000000..08a2664e3e --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/Go/bitmap-ppm-conversion-through-a-pipe.go @@ -0,0 +1,59 @@ +package main + +// Files required to build supporting package raster are found in: +// * Bitmap +// * Write a PPM file + +import ( + "fmt" + "math/rand" + "os/exec" + "raster" +) + +func main() { + b := raster.NewBitmap(400, 300) + // a little extravagant, this draws a design of dots and lines + b.FillRgb(0xc08040) + for i := 0; i < 2000; i++ { + b.SetPxRgb(rand.Intn(400), rand.Intn(300), 0x804020) + } + for x := 0; x < 400; x++ { + for y := 240; y < 245; y++ { + b.SetPxRgb(x, y, 0x804020) + } + for y := 260; y < 265; y++ { + b.SetPxRgb(x, y, 0x804020) + } + } + for y := 0; y < 300; y++ { + for x := 80; x < 85; x++ { + b.SetPxRgb(x, y, 0x804020) + } + for x := 95; x < 100; x++ { + b.SetPxRgb(x, y, 0x804020) + } + } + + // pipe logic + c := exec.Command("cjpeg", "-outfile", "pipeout.jpg") + pipe, err := c.StdinPipe() + if err != nil { + fmt.Println(err) + return + } + err = c.Start() + if err != nil { + fmt.Println(err) + return + } + err = b.WritePpmTo(pipe) + if err != nil { + fmt.Println(err) + return + } + err = pipe.Close() + if err != nil { + fmt.Println(err) + } +} diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-1.math b/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-1.math new file mode 100644 index 0000000000..d194d92cf6 --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-1.math @@ -0,0 +1,6 @@ +convert[img_, out_] := + Module[{pipe = + StartProcess[{"WolframKernel", "-noinit", "-noprompt", "-run", + "Export[\"out.jpg\",ImportString[InputString[],\"PPM\"]]"}]}, + WriteString[pipe, ExportString[Image[Graphics[]], "PPM"]]; + Close[pipe];]; diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-2.math b/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-2.math new file mode 100644 index 0000000000..c4ad95af34 --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/Mathematica/bitmap-ppm-conversion-through-a-pipe-2.math @@ -0,0 +1,15 @@ +let print_jpeg ~img ?(quality=96) () = + let cmd = Printf.sprintf "cjpeg -quality %d" quality in + (* + let cmd = Printf.sprintf "ppmtojpeg -quality %d" quality in + let cmd = Printf.sprintf "convert ppm:- -quality %d jpg:-" quality in + *) + let ic, oc = Unix.open_process cmd in + output_ppm ~img ~oc; + try + while true do + let c = input_char ic in + print_char c + done + with End_of_file -> () +;; diff --git a/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia b/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia new file mode 100644 index 0000000000..8f57b7b6fa --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia @@ -0,0 +1,13 @@ +using Color, Images, FixedPointNumbers + +const M_RGB_Y = reshape(Color.M_RGB_XYZ[2,:], 3) + +function rgb2gray(img::Image) + g = red(img)*M_RGB_Y[1] + green(img)*M_RGB_Y[2] + blue(img)*M_RGB_Y[3] + g = clamp(g, 0.0, 1.0) + return grayim(g) +end + +ima = imread("bitmap_read_ppm_in.ppm") +imb = convert(Image{Gray{Ufixed8}}, ima) +imwrite(imb, "bitmap_read_ppm_out.png") diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Mathematica/bitmap-read-an-image-through-a-pipe.math b/Task/Bitmap-Read-an-image-through-a-pipe/Mathematica/bitmap-read-an-image-through-a-pipe.math new file mode 100644 index 0000000000..417ea1c7ed --- /dev/null +++ b/Task/Bitmap-Read-an-image-through-a-pipe/Mathematica/bitmap-read-an-image-through-a-pipe.math @@ -0,0 +1 @@ +Export["out.bmp", ImportString[InputString[], "PPM"]]; diff --git a/Task/Bitmap-Write-a-PPM-file/J/bitmap-write-a-ppm-file-2.j b/Task/Bitmap-Write-a-PPM-file/J/bitmap-write-a-ppm-file-2.j index d7b33df89e..e1315e22ad 100644 --- a/Task/Bitmap-Write-a-PPM-file/J/bitmap-write-a-ppm-file-2.j +++ b/Task/Bitmap-Write-a-PPM-file/J/bitmap-write-a-ppm-file-2.j @@ -1,4 +1,5 @@ NB. create 10 by 10 block of magenta pixels in top right quadrant of a 300 wide by 600 high green image - myimg=: ((145 + pixellist) ; 255 0 255) setPixels 0 255 0 makeRGB 600 200 + pixellist=: >,{;~i.10 + myimg=: ((150 + pixellist) ; 255 0 255) setPixels 0 255 0 makeRGB 600 300 myimg writeppm jpath '~temp/myimg.ppm' -360015 +540015 diff --git a/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-1.julia b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-1.julia new file mode 100644 index 0000000000..340df5a80e --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-1.julia @@ -0,0 +1,15 @@ +using Color, Images, FixedPointNumbers + +w = 70 +h = 50 + +a = zeros(RGB{Ufixed8}, h, w) +img = Image(a) + +img["x", 10:40, "y", 5:35] = color("skyblue") +for i in 45:65, j in (i-25):40 + img["x", i, "y", j] = color("sienna1") +end + +imwrite(img, "bitmap_write.ppm") +imwrite(img, "bitmap_write.png") diff --git a/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-2.julia b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-2.julia new file mode 100644 index 0000000000..a1d1a76ae9 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-2.julia @@ -0,0 +1,16 @@ +function writeppm(fn::String, a::Image) + outf = open(fn, "w") + (w, h) = size(a.pic) + write(outf, "P6\n") + write(outf, @sprintf "%d %d\n" w h) + write(outf, @sprintf "%d\n" 255) + for i in 1:h + for j in 1:w + c = color(a, j, i) + write(outf, c.r) + write(outf, c.g) + write(outf, c.b) + end + end + close(outf) +end diff --git a/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-3.julia b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-3.julia new file mode 100644 index 0000000000..1408852623 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file-3.julia @@ -0,0 +1,18 @@ +w = 500 +h = 300 +a = Image(w, h) + +purple = Color(0xff, 0, 0xff) +green = Color(0, 0xff, 0) +white = Color(0xff, 0xff, 0xff) + +fill!(a, green) +for i in 20:220, j in 10:100 + splat!(a, i, j, purple) +end +for i in 180:400, j in 80:200 + splat!(a, i, j, white) +end + +fn = "bitmap_write.ppm" +writeppm(fn, a) diff --git a/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust b/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust index 10a6e9950f..f6bce11508 100644 --- a/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust +++ b/Task/Bitmap-Write-a-PPM-file/Rust/bitmap-write-a-ppm-file.rust @@ -1,70 +1,69 @@ -use std::vec::from_elem; -use std::path::posix::{Path}; -use std::io::File; +use std::path::Path; +use std::io::Write; +use std::fs::File; pub struct RGB { - r: u8 - ,g: u8 - ,b: u8 + r: u8, + g: u8, + b: u8, } pub struct PPM { - height: uint - ,width: uint - ,data: ~[u8] + height: u32, + width: u32, + data: Vec, } impl PPM { - pub fn new(height: uint, width: uint) -> PPM { - let size = 3 * height * width; - let buffer = from_elem(size, 0u8); - PPM{height: height, width: width, data: buffer} - } - - fn buffer_size(&self) -> uint { - 3 * self.height * self.width - } + pub fn new(height: u32, width: u32) -> PPM { + let size = 3 * height * width; + let buffer = vec![0; size as usize]; + PPM { height: height, width: width, data: buffer } + } - fn get_offset(&self, x: uint, y: uint) -> Option { - let offset = (y * self.width * 3) + (x * 3); - if(offset < self.buffer_size()){ - Some(offset) - }else{ - None + fn buffer_size(&self) -> u32 { + 3 * self.height * self.width } - } - pub fn get_pixel(&self, x: uint, y: uint) -> Option { - match self.get_offset(x, y) { - Some(offset) => { - let r = self.data[offset]; - let g = self.data[offset + 1]; - let b = self.data[offset + 2]; - Some(RGB{r, g, b}) - }, - None => None + fn get_offset(&self, x: u32, y: u32) -> Option { + let offset = (y * self.width * 3) + (x * 3); + if offset < self.buffer_size() { + Some(offset as usize) + } else { + None + } } - } - pub fn set_pixel(&mut self, x: uint, y: uint, color: RGB) -> bool { - match self.get_offset(x, y) { - Some(offset) => { - self.data[offset] = color.r; - self.data[offset + 1] = color.g; - self.data[offset + 2] = color.b; - true - }, - None => false + pub fn get_pixel(&self, x: u32, y: u32) -> Option { + match self.get_offset(x, y) { + Some(offset) => { + let r = self.data[offset]; + let g = self.data[offset + 1]; + let b = self.data[offset + 2]; + Some(RGB {r: r, g: g, b: b}) + }, + None => None + } } - } - pub fn write_file(&self, filename: &str) -> bool { - let path = Path::new(filename); - let mut file = File::create(&path); - let header = format!("P6 {} {} 255\n", self.width, self.height); - file.write(header.as_bytes()); - file.write(self.data); - true - } + pub fn set_pixel(&mut self, x: u32, y: u32, color: RGB) -> bool { + match self.get_offset(x, y) { + Some(offset) => { + self.data[offset] = color.r; + self.data[offset + 1] = color.g; + self.data[offset + 2] = color.b; + true + }, + None => false + } + } + pub fn write_file(&self, filename: &str) -> std::io::Result<()> { + let path = Path::new(filename); + let mut file = try!(File::create(&path)); + let header = format!("P6 {} {} 255\n", self.width, self.height); + try!(file.write(header.as_bytes())); + try!(file.write(&self.data)); + Ok(()) + } } diff --git a/Task/Bitmap/Julia/bitmap-1.julia b/Task/Bitmap/Julia/bitmap-1.julia new file mode 100644 index 0000000000..4a420d9e5b --- /dev/null +++ b/Task/Bitmap/Julia/bitmap-1.julia @@ -0,0 +1,36 @@ +using Color, Images, FixedPointNumbers + +function hexify(pxl::RGB) + p = reinterpret(Uint8, [pxl.r, pxl.g, pxl.b]) + join(map(x->hex(x, 2), p)) +end + +function showimagehex(a::Image) + s = " " + for i in 1:height(a) + for j in 1:width(a) + s *= " "*hexify(a["x", j, "y", i]) + end + s *= "\n " + end + return s +end + +w = 5 +h = 7 +cback = RGB(1, 0, 1) +cfore = RGB(0, 1, 0) + +a = Array(RGB{Ufixed8}, h, w) +img = Image(a) + +println("Uninitialized image:") +println(showimagehex(img)) + +fill!(img, cback) +println("Image filled with background color:") +println(showimagehex(img)) + +img["x", 2, "y", 3] = cfore +println("Image with a pixel set for foreground color:") +println(showimagehex(img)) diff --git a/Task/Bitmap/Julia/bitmap-2.julia b/Task/Bitmap/Julia/bitmap-2.julia new file mode 100644 index 0000000000..f7afb43f48 --- /dev/null +++ b/Task/Bitmap/Julia/bitmap-2.julia @@ -0,0 +1,10 @@ +type Color + r::Uint8 + g::Uint8 + b::Uint8 +end + +type Image + pic::Array{Color,2} +end +Image(w::Int, h::Int) = Image(Array(Color, w, h)) diff --git a/Task/Bitmap/Julia/bitmap-3.julia b/Task/Bitmap/Julia/bitmap-3.julia new file mode 100644 index 0000000000..d6047428e1 --- /dev/null +++ b/Task/Bitmap/Julia/bitmap-3.julia @@ -0,0 +1 @@ +Base.fill!(a::Image, c::Color) = Base.fill!(a.pic, c) diff --git a/Task/Bitmap/Julia/bitmap-4.julia b/Task/Bitmap/Julia/bitmap-4.julia new file mode 100644 index 0000000000..ecf10317be --- /dev/null +++ b/Task/Bitmap/Julia/bitmap-4.julia @@ -0,0 +1,4 @@ +function splat!(a::Image, x::Int, y::Int, c::Color) + a.pic[x, y] = c + nothing +end diff --git a/Task/Bitmap/Julia/bitmap-5.julia b/Task/Bitmap/Julia/bitmap-5.julia new file mode 100644 index 0000000000..6c6e8f7f25 --- /dev/null +++ b/Task/Bitmap/Julia/bitmap-5.julia @@ -0,0 +1,3 @@ +function color(a::Image, x::Int, y::Int) + a.pic[x, y] +end diff --git a/Task/Bitmap/Julia/bitmap-6.julia b/Task/Bitmap/Julia/bitmap-6.julia new file mode 100644 index 0000000000..3ee62aa801 --- /dev/null +++ b/Task/Bitmap/Julia/bitmap-6.julia @@ -0,0 +1,21 @@ +function showpixel(a::Image, x::Int, y::Int) + c = color(a, x, y) + hex(c.r, 2)*hex(c.g, 2)*hex(c.b, 2) +end + +w = 5 +h = 7 +a = Image(w, h) + +purple = Color(0xff, 0, 0xff) +green = Color(0, 0xff, 0) + +fill!(a, purple) +splat!(a, 2, 3, green) + +for i in 1:h + for j in 1:w + print(showpixel(a, j, i), " ") + end + println() +end diff --git a/Task/Bitmap/Perl-6/bitmap.pl6 b/Task/Bitmap/Perl-6/bitmap.pl6 index f13339f627..e5f1f66533 100644 --- a/Task/Bitmap/Perl-6/bitmap.pl6 +++ b/Task/Bitmap/Perl-6/bitmap.pl6 @@ -1,16 +1,14 @@ -class Pixel { has Int ($.R, $.G, $.B) } +class Pixel { has UInt ($.R, $.G, $.B) } class Bitmap { - has Int ($.width, $.height); - has Pixel @.data; + has UInt ($.width, $.height); + has Pixel @!data; method fill(Pixel $p) { - for ^$!width X ^$!height -> $i, $j { - self.pixel($i, $j) = $p.clone; - } + @!data = $p.clone xx ($!width*$!height) } method pixel( - $i where ^self.width, - $j where ^self.height + $i where ^$!width, + $j where ^$!height --> Pixel ) is rw { @!data[$i*$!height + $j] } diff --git a/Task/Bitwise-IO/Python/bitwise-io-1.py b/Task/Bitwise-IO/Python/bitwise-io-1.py index 31d155993f..10dd423ebf 100644 --- a/Task/Bitwise-IO/Python/bitwise-io-1.py +++ b/Task/Bitwise-IO/Python/bitwise-io-1.py @@ -5,7 +5,10 @@ def __init__(self, f): self.out = f def __del__(self): - self.flush() + try: + self.flush() + except ValueError: # I/O operation on closed file + pass def writebit(self, bit): if self.bcount == 8 : diff --git a/Task/Bitwise-IO/Racket/bitwise-io.rkt b/Task/Bitwise-IO/Racket/bitwise-io.rkt new file mode 100644 index 0000000000..05ec380389 --- /dev/null +++ b/Task/Bitwise-IO/Racket/bitwise-io.rkt @@ -0,0 +1,59 @@ +#lang racket + +(require racket/fixnum) + +(define (make-bit-writer file) + (define o (open-output-file file #:exists 'truncate)) + (define b+len (cons 0 0)) + (define (write-some-bits! n len) + (if (<= 8 len) + (begin (write-byte (fxand n #xFF) o) + (write-some-bits! (fxrshift n 8) (- len 8))) + (set! b+len (cons n len)))) + (define write-bits + (case-lambda + [(n) (if (eof-object? n) + (begin (when (positive? (cdr b+len)) (write-byte (car b+len) o)) + (close-output-port o)) + (write-bits n (integer-length n)))] + [(n nbits) + (when (< nbits (integer-length n)) + (error 'write-bits "integer bigger than number of bits")) + (write-some-bits! (fxior (car b+len) (fxlshift n (cdr b+len))) + (+ (cdr b+len) nbits))])) + write-bits) + +(define (make-bit-reader file) + (define i (open-input-file file)) + (define b+len (cons 0 0)) + (define (read-some-bits wanted n len) + (if (<= wanted len) + (begin0 (fxand n (sub1 (expt 2 wanted))) + (set! b+len (cons (fxrshift n wanted) (- len wanted)))) + (read-some-bits wanted (+ n (fxlshift (read-byte i) len)) (+ len 8)))) + (define (read-bits n) + (if (eof-object? n) + (close-input-port i) + (read-some-bits n (car b+len) (cdr b+len)))) + read-bits) + +(define (crunch str file) + (define out (make-bit-writer file)) + (for ([b (in-bytes (string->bytes/utf-8 str))]) (out b 7)) + (out eof)) + +(define (decrunch file) + (define in (make-bit-reader file)) + (define bs (for/list ([i (in-range (quotient (* 8 (file-size file)) 7))]) + (in 7))) + (in eof) + (bytes->string/utf-8 (list->bytes bs))) + +(define orig + (string-append "This is an ascii string that will be" + " crunched, written, read and expanded.")) + +(crunch orig "crunched.out") + +(printf "Decrunched string ~aequal to original.\n" + (if (equal? orig (decrunch "crunched.out")) "" "NOT ")) diff --git a/Task/Bitwise-operations/Elena/bitwise-operations.elena b/Task/Bitwise-operations/Elena/bitwise-operations.elena index e3309784b5..a8c27f3e83 100644 --- a/Task/Bitwise-operations/Elena/bitwise-operations.elena +++ b/Task/Bitwise-operations/Elena/bitwise-operations.elena @@ -1,20 +1,20 @@ #define system. #define extensions. -#symbol bitwiseTest = (:x:y) -[ - console write:x write:" and " write:y write:" = " writeLine:(x and:y). - console write:x write:" or " write:y write:" = " writeLine:(x or:y). - console write:x write:" xor " write:y write:" = " writeLine:(x xor:y). - console write:"not " write:x write:" = " writeLine:(x not). - console write:x write:" shr " write:y write:" = " writeLine:(x shift &index:(y int)). - console write:x write:" shl " write:y write:" = " writeLine:(x shift &index:(y negative int)). -]. +#class(extension) testOp +{ + #method bitwiseTest : y + [ + console writeLine:self:" and ":y:" = ":(self and:y). + console writeLine:self:" or ":y:" = ":(self or:y). + console writeLine:self:" xor ":y:" = ":(self xor:y). + console writeLine:"not ":self:" = ":(self not). + console writeLine:self:" shr ":y:" = ":(self shift &index:y). + console writeLine:self:" shl ":y:" = ":(self shift &index:(y negative)). + ] +} #symbol program = [ - #var a := consoleEx readLine:(Integer new). - #var b := consoleEx readLine:(Integer new). - - bitwiseTest:a:b. + console readLine:(Integer new) bitwiseTest:(console readLine:(Integer new)). ]. diff --git a/Task/Bitwise-operations/Elixir/bitwise-operations.elixir b/Task/Bitwise-operations/Elixir/bitwise-operations.elixir new file mode 100644 index 0000000000..69da1b0d65 --- /dev/null +++ b/Task/Bitwise-operations/Elixir/bitwise-operations.elixir @@ -0,0 +1,22 @@ +defmodule Bitwise_operation do + use Bitwise + + def test(a \\ 255, b \\ 170, c \\ 2) do + IO.puts "Bitwise function:" + IO.puts "band(#{a}, #{b}) = #{band(a, b)}" + IO.puts "bor(#{a}, #{b}) = #{bor(a, b)}" + IO.puts "bxor(#{a}, #{b}) = #{bxor(a, b)}" + IO.puts "bnot(#{a}) = #{bnot(a)}" + IO.puts "bsl(#{a}, #{c}) = #{bsl(a, c)}" + IO.puts "bsr(#{a}, #{c}) = #{bsr(a, c)}" + IO.puts "\nBitwise as operator:" + IO.puts "#{a} &&& #{b} = #{a &&& b}" + IO.puts "#{a} ||| #{b} = #{a ||| b}" + IO.puts "#{a} ^^^ #{b} = #{a ^^^ b}" + IO.puts "~~~#{a} = #{~~~a}" + IO.puts "#{a} <<< #{c} = #{a <<< c}" + IO.puts "#{a} >>> #{c} = #{a >>> c}" + end +end + +Bitwise_operation.test diff --git a/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 b/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 index 7eb25564d9..0d6151252e 100644 --- a/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 +++ b/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 @@ -2,7 +2,7 @@ constant MAXINT = uint.Range.max; constant BITS = MAXINT.base(2).chars; # define rotate ops for the fun of it -multi sub infix:<⥁>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).rotate(b).reverse] } +multi sub infix:<⥁>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).list.rotate(b).reverse] } multi sub infix:<⥀>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).reverse.rotate(b)] } sub int-bits (Int $a, Int $b) { diff --git a/Task/Bitwise-operations/Rust/bitwise-operations.rust b/Task/Bitwise-operations/Rust/bitwise-operations.rust index 27aed31b08..d8d4d321be 100644 --- a/Task/Bitwise-operations/Rust/bitwise-operations.rust +++ b/Task/Bitwise-operations/Rust/bitwise-operations.rust @@ -1,12 +1,12 @@ fn main() { let a: u8 = 105; let b: u8 = 91; - println!("a = {:0>8t}", a); - println!("b = {:0>8t}", b); - println!("a | b = {:0>8t}", a | b); - println!("a & b = {:0>8t}", a & b); - println!("a ^ b = {:0>8t}", a ^ b); - println!("!a = {:0>8t}", !a); - println!("a << 3 = {:0>8t}", a >> 3); - println!("a >> 3 = {:0>8t}", a << 3); + println!("a = {:0>8b}", a); + println!("b = {:0>8b}", b); + println!("a | b = {:0>8b}", a | b); + println!("a & b = {:0>8b}", a & b); + println!("a ^ b = {:0>8b}", a ^ b); + println!("!a = {:0>8b}", !a); + println!("a << 3 = {:0>8b}", a << 3); + println!("a >> 3 = {:0>8b}", a >> 3); } diff --git a/Task/Boolean-values/Elixir/boolean-values-1.elixir b/Task/Boolean-values/Elixir/boolean-values-1.elixir new file mode 100644 index 0000000000..1068d54a57 --- /dev/null +++ b/Task/Boolean-values/Elixir/boolean-values-1.elixir @@ -0,0 +1,6 @@ +iex(1)> true === :true +true +iex(2)> false === :false +true +iex(3)> true === 1 +false diff --git a/Task/Boolean-values/Elixir/boolean-values-2.elixir b/Task/Boolean-values/Elixir/boolean-values-2.elixir new file mode 100644 index 0000000000..77b6bb90fe --- /dev/null +++ b/Task/Boolean-values/Elixir/boolean-values-2.elixir @@ -0,0 +1,4 @@ +iex(4)> nil === :nil +true +iex(5)> nil === false +false diff --git a/Task/Box-the-compass/REXX/box-the-compass.rexx b/Task/Box-the-compass/REXX/box-the-compass.rexx index 817957c82a..9e3b4d32d7 100644 --- a/Task/Box-the-compass/REXX/box-the-compass.rexx +++ b/Task/Box-the-compass/REXX/box-the-compass.rexx @@ -1,32 +1,29 @@ -/*REXX program boxes the compass (from º headings ───> 32 point set). */ +/*REXX program "boxes the compass" (from º headings ───► a 32 point set).*/ +parse arg # /*allow a º heading to be specified.*/ +if #='' then #= 0 16.87 16.88 33.75 50.62 50.63 67.5 84.37 84.38 101.25 118.12, + 118.13 135 151.87 151.88 168.75 185.62 185.63 202.5 219.37, + 219.38 236.25 253.12 253.13 270 286.87 286.88 303.75 320.62, + 320.63 337.5 354.37 354.38 /* [↑] use default in degrees.*/ -headings=0 16.87 16.88 33.75 50.62 50.63 67.5 84.37 84.38 101.25 118.12, - 118.13 135 151.87 151.88 168.75 185.62 185.63 202.5 219.37, - 219.38 236.25 253.12 253.13 270 286.87 286.88 303.75 320.62, - 320.63 337.5 354.37 354.38 /*some sample compass headings. */ +points= 'n nbe n-ne nebn ne nebe e-ne ebn e ebs e-se sebe se sebs s-se sbe', + 's sbw s-sw swbs sw swbw w-sw wbs w wbn w-nw nwbw nw nwbn n-nw nbw' -points='n nbe n-ne nebn ne nebe e-ne ebn e ebs e-se sebe se sebs s-se sbe', - 's sbw s-sw swbs sw swbw w-sw wbs w wbn w-nw nwbw nw nwbn n-nw nbw' +dirs= 'north south east west' /*define cardinal compass directions.*/ + /* [↓] choose a degree (°) glyph. */ +if 4=='f4'x then degSym='a1'x /*is this system an EBCDIC system? */ + else degSym='f8'x /*although 'a7'x looks better: ° vs º*/ + /*─────────────────────────── f8 a7*/ +say right(degSym'heading',30) center('compass heading',20) +say right( '────────',30) copies('─' ,20) -dirs='north south east west' -@ebcdic= 1=='f1'x -if @ebcdic then degSym='a1'x - else degSym='f8'x /*although, 'a7'x looks better, */ - /*see line 1 (above).*/ -say right(degSym'heading',30) center('compass heading',20) -say right( '────────',30) copies('─' ,20) - - do j=1 for words(headings) - x=word(headings,j) - say right(format(x,,2)degSym,30-1) ' ' boxHeading(x) + do j=1 for words(#); x=word(#,j) /*get one of the degree headings*/ + say right(format(x,,2)degSym,30-1) ' ' boxHeading(x) end /*j*/ -exit -/*─────────────────────────────────────BOXHEADING subroutine────────────*/ -boxHeading: _=arg(1)//360; if _<0 then _=360-_ /*normalize the heading.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +boxHeading: _=arg(1)//360; if _<0 then _=360-_ /*normalize the heading.*/ _=word(points,trunc(max(1,(_/11.25+1.5)//33))) - do k=1 for words(dirs); d=word(dirs,k) - _=changestr(left(d,1),_,d) - end /*k*/ -return changestr('b',_," by ") - /*next statement is ignored. */ -return upper(changestr('b',_," by "),1) /*capitalizes the 1st letter.*/ + do k=1 for words(dirs); d=word(dirs,k) + _=changestr(left(d,1), _, d) + end /*k*/ +return changestr('b', _, " by ") /*expand "b" ──► "by"*/ diff --git a/Task/Break-OO-privacy/ABAP/break-oo-privacy.abap b/Task/Break-OO-privacy/ABAP/break-oo-privacy.abap new file mode 100644 index 0000000000..d24554bd6e --- /dev/null +++ b/Task/Break-OO-privacy/ABAP/break-oo-privacy.abap @@ -0,0 +1,41 @@ +class friendly_class definition deferred. + +class my_class definition friends friendly_class . + + public section. + methods constructor. + + private section. + data secret type char30. + +endclass. + +class my_class implementation . + + method constructor. + secret = 'a password'. " Instantiate secret. + endmethod. + +endclass. + +class friendly_class definition create public . + + public section. + methods return_secret + returning value(r_secret) type char30. + +endclass. + +class friendly_class implementation. + + method return_secret. + + data lr_my_class type ref to my_class. + + create object lr_my_class. " Instantiate my_class + + write lr_my_class->secret. " Here's the privacy violation. + + endmethod. + +endclass. diff --git a/Task/Break-OO-privacy/Forth/break-oo-privacy.fth b/Task/Break-OO-privacy/Forth/break-oo-privacy.fth new file mode 100644 index 0000000000..c457e5915a --- /dev/null +++ b/Task/Break-OO-privacy/Forth/break-oo-privacy.fth @@ -0,0 +1,17 @@ +include FMS-SI.f + +99 value x \ create a global variable named x + +:class foo + ivar x \ this x is private to the class foo + :m init: 10 x ! ;m \ constructor + :m print x ? ;m +;class + +foo f1 \ instantiate a foo object +f1 print \ 10 + +x . \ 99 x is a globally scoped name + +50 .. f1.x ! \ use the dot parser to access the private x without a message +f1 print \ 50 diff --git a/Task/Break-OO-privacy/Perl/break-oo-privacy.pl b/Task/Break-OO-privacy/Perl/break-oo-privacy.pl new file mode 100644 index 0000000000..1dfe87fd80 --- /dev/null +++ b/Task/Break-OO-privacy/Perl/break-oo-privacy.pl @@ -0,0 +1,15 @@ +package Foo; +sub new { + my $class = shift; + my $self = { _bar => 'I am ostensibly private' }; + return bless $self, $class; +} + +sub get_bar { + my $self = shift; + return $self->{_bar}; +} + +package main; +my $foo = Foo->new(); +print "$_\n" for $foo->get_bar(), $foo->{_bar}; diff --git a/Task/Break-OO-privacy/Scala/break-oo-privacy.scala b/Task/Break-OO-privacy/Scala/break-oo-privacy.scala index 6fe708bd5f..8e88eeb0ee 100644 --- a/Task/Break-OO-privacy/Scala/break-oo-privacy.scala +++ b/Task/Break-OO-privacy/Scala/break-oo-privacy.scala @@ -1,22 +1,13 @@ -class Example { - private var _name: String = null - - def this(name: String) { - this() - _name = name - } - - override def toString = "Hello, I am " + _name +class Example(private var name: String) { + override def toString = s"Hello, I am $name" } object BreakPrivacy extends App { - val foo: Example = new Example("Erik") - for (f <- classOf[Example].getDeclaredFields - if f.getName == "_name" - ) { - f.setAccessible(true) - println(f.get(foo)) - f.set(foo, "Edith") - println(foo) - } + val field = classOf[Example].getDeclaredField("name") + field.setAccessible(true) + + val foo = new Example("Erik") + println(field.get(foo)) + field.set(foo, "Edith") + println(foo) } diff --git a/Task/Brownian-tree/Julia/brownian-tree.julia b/Task/Brownian-tree/Julia/brownian-tree.julia new file mode 100644 index 0000000000..3b4b0196a4 --- /dev/null +++ b/Task/Brownian-tree/Julia/brownian-tree.julia @@ -0,0 +1,43 @@ +using Color, Images, FixedPointNumbers + +const W = 512 +const W0 = W>>1 +const H = 512 +const H0 = H>>1 +const N = iceil(1.0*W*H) +const SIDESTICK = false + + +function motecolor(x::Int, y::Int) + h = clamp(180*(atan2(y-H0, x-W0)/pi + 1.0), 0.0, 360.0) + return HSV(h, 0.5, 0.5) +end + +img = Image(zeros(RGB{Ufixed8}, H, W)) +img["x", W0, "y", H0] = RGB(1, 1, 1) +isfree = trues(W, H) +isfree[W0, H0] = false +for i in 1:N + x = rand(1:W) + y = rand(1:H) + isfree[x, y] || continue + mc = motecolor(x, y) + for j in 1:10^3 + xp = x + rand(-1:1) + yp = y + rand(-1:1) + iscontained = 0 < xp <= W && 0 < yp <= H + if iscontained && isfree[xp, yp] + x = xp + y = yp + continue + else + if SIDESTICK || (iscontained && !isfree[xp, yp]) + isfree[x, y] = false + img["x", x, "y", y] = mc + end + break + end + end +end + +imwrite(img, "brownian_tree.png") diff --git a/Task/Bulls-and-cows-Player/Prolog/bulls-and-cows-player-1.pro b/Task/Bulls-and-cows-Player/Prolog/bulls-and-cows-player-1.pro index cd7a55deac..a4917c590b 100644 --- a/Task/Bulls-and-cows-Player/Prolog/bulls-and-cows-player-1.pro +++ b/Task/Bulls-and-cows-Player/Prolog/bulls-and-cows-player-1.pro @@ -38,7 +38,7 @@ tirage(L, Ms) :- digits(Digits), - % The guess continas only this numbers + % The guess contains only this numbers Ms ins 0..Digits, all_different(Ms), diff --git a/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx b/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx index 65fcd8db72..58f5340608 100644 --- a/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx +++ b/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx @@ -1,63 +1,60 @@ -/*REXX pgm plays Bulls & Cows game with CBLFs (Carbon Based Life Forms).*/ -call gen@ /*generate all the possibilities.*/ -call # /*get the first guess for game. */ +/*REXX program plays Bulls & Cows game with CBLFs (Carbon Based Life Forms).*/ +call gen@ /*generate all the possibilities. */ +call # /*get the first guess for the game. */ do tries=1 until #()<2 | bull==4; say call prompter - do ?=L to H /*traipse through the whole list.*/ - if @.?==. then iterate /*was this already eliminated ? */ - call bull# ?,g /*obtain the bulls & cows count. */ - if bull\==bulls | cow\==cows then @.?=. /*eliminate it*/ + do ?=L to H /*traipse through the whole list. */ + if @.?==. then iterate /*was this choice already eliminated ? */ + call bull# ?,g /*obtain the bulls and cows count. */ + if bull\==bulls | cow\==cows then @.?=. /*eliminate choice.*/ end /*?*/ call # end /*tries*/ -if #==0 then do; call sayErr "At least one of your responses was invalid."; exit; end -pad=left('',9) -say; say pad " ┌─────────────────────────────────────────────────┐" - say pad " │ │" - say pad " │ Your secret Bulls and Cows number is: " g " │" - say pad " │ │" - say pad " └─────────────────────────────────────────────────┘"; say -say tries 'tries.' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one─liner subroutines───────────────*/ -#: #=0; do k=L to H; if @.k==. then iterate; #=#+1; g=k; end; return # -gen@: @.=.; L=1234; H=9876; do j=L to H; if genOK() then @.j=j; end; return -genOK: if pos(0,j)\==0 then return 0; return \rep() -rep: do k=1 for 3; if pos(substr(j,k,1),j,k+1)\==0 then return 1; end; return 0 -sayErr: say; say pad '***error!*** ' em arg(1); return -/*──────────────────────────────────BULL# subroutine────────────────────*/ -bull#: parse arg n,q; L=length(n); bulls=0; cows=0 /*init. some vars*/ +if #==0 then do; call serr "At least one of your responses was invalid."; exit; end +say; say " ╔═════════════════════════════════════════════════╗" + say " ║ ║" + say " ║ Your secret Bulls and Cows number is: " g " ║" + say " ║ ║" + say " ╚═════════════════════════════════════════════════╝"; say +say tries 'tries.' +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ +#: #=0; do k=L to H; if @.k==. then iterate; #=#+1; g=k; end; return # +gen@: @.=.; L=1234; H=9876; do j=L to H; if genOK() then @.j=j; end; return +genOK: if pos(0,j)\==0 then return 0; return \rep() +rep: do k=1 for 3; if pos(substr(j,k,1),j,k+1)\==0 then return 1; end; return 0 +serr: say; say pad '***error!*** ' ! arg(1); return +/*────────────────────────────────────────────────────────────────────────────*/ +bull#: parse arg n,q; L=length(n); bulls=0; cows=0 /*initialize some vars.*/ + do j=1 for L; if substr(n,j,1)\==substr(q,j,1) then iterate + bulls=bulls+1 /*bump the bull counter. */ + q=overlay(.,q,j) /*disallow this for a cow count.*/ + end /*j*/ /* [↑] bull count═══════════════*/ - do j=1 for L; if substr(n,j,1)\==substr(q,j,1) then iterate - bulls=bulls+1 /*bump the bull count. */ - q=overlay(.,q,j) /*disallow this for a cow count. */ - end /*j*/ /* [↑] bull count───────────────*/ - - do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate - cows=cows+1 /*bump the cow count. */ - q=translate(q,,_) /*this allows for multiple digits*/ - end /*k*/ /* [↑] cow count───────────────*/ -return -/*──────────────────────────────────PROMPTER subroutine─────────────────*/ -prompter: pad='─────' /*define PAD chars for messages. */ + do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate + cows=cows+1 /*bump the cow counter. */ + q=translate(q,,_) /*this allows for multiple digits*/ + end /*k*/ /* [↑] cow count═══════════════*/ + return +/*────────────────────────────────────────────────────────────────────────────*/ +prompter: pad='─────' /*define PAD characters for messages.*/ do forever; say - say pad "How many bulls and cows were guessed with " g '? [─── or QUIT]' - pull x 1 bull cow _ . /*PULL capitalizes the args.*/ - if abbrev('QUIT',x,1) then exit /*user wants to quit playing*/ + say pad "How many bulls and cows were guessed with " g '? [─── or QUIT]' + pull x 1 bull cow _ . /*PULL capitalizes the arguments.*/ + if abbrev('QUIT',x,1) then exit /*the user wants to quit playing.*/ select - when bull=='' then em="no numbers were entered." - when cow =='' then em="not enough numbers were entered." - when _\=='' then em="too many numbers entered: " x - when \datatype(bull,'W') then em="1st number (bulls) not an integer: " bull - when \datatype(cow ,'W') then em="2nd number (cows) not an integer: " cow - when bull <0 | bull >4 then em="1st number (bulls) not 0──►4: " bull - when cow <0 | cow >4 then em="2nd number (cows) not 0──►4: " cow - when bull + cow > 4 then em="sum of bulls and cows can't be > 4: " x - otherwise em= + when bull=='' then != "no numbers were entered." + when cow =='' then != "not enough numbers were entered." + when _\=='' then != "too many numbers entered: " x + when \datatype(bull,'W') then != "1st number (bulls) not an integer: " bull + when \datatype(cow ,'W') then != "2nd number (cows) not an integer: " cow + when bull <0 | bull >4 then != "1st number (bulls) not 0──►4: " bull + when cow <0 | cow >4 then != "2nd number (cows) not 0──►4: " cow + when bull + cow > 4 then != "sum of bulls and cows can't be > 4: " x + otherwise != end /*select*/ - if em\=='' then do; call sayErr; iterate; end /*prompt user again.*/ - bull=bull/1; cow=cow/1 /*normalize the two answers. */ - return /*we've got two kosher numbers. */ + if !\=='' then do; call serr; iterate; end /*prompt the user again.*/ + bull=bull/1; cow=cow/1; return /*normalize 2 bulls & cows #s; return.*/ end /*forever*/ diff --git a/Task/Bulls-and-cows/Batch-File/bulls-and-cows.bat b/Task/Bulls-and-cows/Batch-File/bulls-and-cows.bat new file mode 100644 index 0000000000..672ba85448 --- /dev/null +++ b/Task/Bulls-and-cows/Batch-File/bulls-and-cows.bat @@ -0,0 +1,119 @@ +:: +::Bulls and Cows Task from Rosetta Code Wiki +::Batch File Implementation +:: +::Directly OPEN the Batch File to play... +:: + +@echo off +title Bulls and Cows Game +setlocal enabledelayedexpansion + +::GENERATING THE CODE TO BE GUESSED BY PLAYER... +:begin +set list=123456789 +set cnt=1 +set code= +set tries=0 +:gen +set /a mod=10-%cnt% +set /a rnd=%random%%%%mod% +set pick=!list:~%rnd%,1! +set code=%code%%pick% +set list=!list:%pick%=! +if %cnt%==4 ( + set c1=%code:~0,1%&set c2=%code:~1,1%&set c3=%code:~2,1%&set c4=%code:~3,1% + goto :start +) +set /a cnt+=1 +goto :gen +::/GENERATING THE CODE TO BE GUESSED BY PLAYER... + +::GAME DISPLAY +:start +cls +echo. +echo Bulls and Cows Game +echo Batch File Implementation +echo. +echo NOTE: Please MAXIMIZE this command window. +echo. +echo Gameplay: +echo. +echo I have generated a 4-digit code from digit 1-9 WITHOUT duplication. +echo Your objective is to guess it. If your guess is equal to my code, +echo then you WIN. If not, I will score your guess: +echo. +echo ** A score of one BULL is accumulated for each digit that equals +echo the CORRESPONDING digit in my code. +echo. +echo ** A score of one COW is accumulated for each digit that appears +echo in your guess, but in the WRONG position. +echo. +echo Now, start guessing^^! +echo. +:game +echo. +set /p guess=Your Guess: +::/GAME DISPLAY + +::INPUT VALIDATION +if !guess! gtr 9876 (echo Please input a valid guess.&goto :game) +if !guess! lss 1234 (echo Please input a valid guess.&goto :game) +set i1=%guess:~0,1%&set i2=%guess:~1,1%&set i3=%guess:~2,1%&set i4=%guess:~3,1% +set chk=1 +:cycle +set /a tmp1=%chk%+1 +for /l %%a in (%tmp1%,1,4) do ( + if !i%chk%!==!i%%a! ( + echo Please input a valid guess.&goto :game + ) +) +if %chk%==3 ( + goto :score +) +set /a chk+=1 +goto :cycle +::/INPUT VALIDATION + +::SCORING +:score +set /a tries+=1 +if %guess%==%code% (goto :won) +set cow=0 +set bull=0 +for /l %%a in (1,1,4) do ( + if !i%%a!==!c%%a! ( + set /a bull+=1 + ) else ( + set "entrycow=%%a" + call :scorecow + ) +) +set guess= +echo BULLS=%bull% COWS=%cow% +goto :game + +:scorecow +set nums=1 2 3 4 +set put=!nums:%entrycow%=! +for %%b in (%put%) do ( + if !c%%b!==!i%entrycow%! ( + set /a cow+=1 + goto :EOF + ) +) +goto :EOF +::/SCORING + +::ALREADY WON! +:won +echo. +echo. +echo After %tries% Tries, YOU CRACKED IT^^! My code is %code%. +echo. +set /p opt=Play again?(Y/N) +if /i "!opt!"=="y" (call :begin) +if /i "!opt!"=="n" (exit/b) +goto :won +::/ALREADY WON! diff --git a/Task/Bulls-and-cows/Eiffel/bulls-and-cows.e b/Task/Bulls-and-cows/Eiffel/bulls-and-cows.e new file mode 100644 index 0000000000..c86f9516fd --- /dev/null +++ b/Task/Bulls-and-cows/Eiffel/bulls-and-cows.e @@ -0,0 +1,112 @@ +class + BULLS_AND_COWS + +create + execute + +feature + + execute + -- Initiate game. + do + io.put_string ("Let's play bulls and cows.%N") + create answer.make_empty + play + end + +feature {NONE} + + play + -- Plays bulls ans cows. + local + count, seed: INTEGER + guess: STRING + do + from + until + seed > 0 + loop + io.put_string ("Enter a positive integer.%NYour play will be generated from it.%N") + io.read_integer + seed := io.last_integer + end + generate_answer (seed) + io.put_string ("Your game has been created.%N Try to guess the four digit number.%N") + create guess.make_empty + from + until + guess ~ answer + loop + io.put_string ("Guess: ") + io.read_line + guess := io.last_string + if guess.count = 4 and guess.is_natural and not guess.has ('0') then + io.put_string (score (guess) + "%N") + count := count + 1 + else + io.put_string ("Your input does not have the correct format.") + end + end + io.put_string ("Congratulations! You won with " + count.out + " guesses.") + end + + answer: STRING + + generate_answer (s: INTEGER) + -- Answer with 4-digits between 1 and 9 stored in 'answer'. + require + positive_seed: s > 0 + local + random: RANDOM + ran: INTEGER + do + create random.set_seed (s) + from + until + answer.count = 4 + loop + ran := (random.double_item * 10).floor + if ran > 0 and not answer.has_substring (ran.out) then + answer.append (ran.out) + end + random.forth + end + ensure + answer_not_void: answer /= Void + correct_length: answer.count = 4 + end + + score (g: STRING): STRING + -- Score for the guess 'g' depending on 'answer'. + require + same_length: answer.count = g.count + local + k: INTEGER + a, ge: STRING + do + Result := "" + a := answer.twin + ge := g.twin + across + 1 |..| a.count as c + loop + if a [c.item] ~ ge [c.item] then + Result := Result + "BULL " + a [c.item] := ' ' + ge [c.item] := ' ' + end + end + across + 1 |..| a.count as c + loop + if a [c.item] /= ' ' then + k := ge.index_of (a [c.item], 1) + if k > 0 then + Result := Result + "COW " + ge [k] := ' ' + end + end + end + end + +end diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index db1e0f1436..34a1ea299b 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -10,17 +10,17 @@ #constructor new [ // generate secret number - #var aRandomNumbers := randomControl randomize:9 &array:(1,2,3,4,5,6,7,8,9). + #var aRandomNumbers := (1,2,3,4,5,6,7,8,9) randomize:9. - theNumbers := arrayControl Subarray:aRandomNumbers &from:0 &length:4. + theNumbers := aRandomNumbers Subarray &index:0 &length:4. theAttempt := Integer new:1. ] #method ask [ - #var aRow := consoleEx write:"Your Guess #":theAttempt:" ?" readLine. + #var aRow := console writeLiteral:"Your Guess #":theAttempt:" ?" readLine. - ^ literalControl toArray:aRow. + ^ aRow toArray. ] #method proceed : aGuess @@ -31,18 +31,18 @@ (aGuess length != 4) ? [ aBulls << -1. ] ! [ - control forrange &int:0 &int:3 &do: (&int:i) + 0 to:3 &doEach: (:i) [ #var ch := aGuess@i. - #var aNumber := convertor toInt:(ch literal). + #var aNumber := ch literal toInt. // check range - (aNumber > 0)and:(aNumber < 10) + ((aNumber > 0)and:(aNumber < 10)) ! [ #throw InvalidArgumentException new. ]. // check duplicates - #var duplicate := arrayControl seek:aGuess &until: x [ (x == ch)and:[ x equal &reference:ch not ] ]. - nil != duplicate ? + #var duplicate := aGuess seek &each: x [ (x == ch)and:[ x equal &reference:ch not ] ]. + (nil != duplicate) ? [ #throw InvalidArgumentException new. ]. @@ -50,23 +50,23 @@ (aNumber == (theNumbers@i)) ? [ aBulls += 1. ] ! [ - arrayControl ifExist:aNumber &in:theNumbers + (theNumbers ifExists:aNumber) ? [ aCows += 1. ]. ]. ] - | ifFailed: + | if &Error: e [ aBulls << -1. ]. ]. ^ aBulls => - -1 ? [ consoleEx writeLine:"Not a valid guess.". ^ true. ] - 4 ? [ consoleEx writeLine:"Congratulations! You have won!". ^ false. ] + -1 ? [ console writeLine:"Not a valid guess.". ^ true. ] + 4 ? [ console writeLine:"Congratulations! You have won!". ^ false. ] ! [ theAttempt += 1. - consoleEx writeLine:"Your Score is " : aBulls : " bulls and " : aCows : " cows". + console writeLine:"Your Score is " : aBulls : " bulls and " : aCows : " cows". ^ true. ]. @@ -77,5 +77,5 @@ [ #var aGameMaster := GameMaster new. - control while:[ aGameMaster proceed:(aGameMaster ask) ]. + [ aGameMaster proceed:(aGameMaster ask) ] doWhile. ]. diff --git a/Task/Bulls-and-cows/Julia/bulls-and-cows-2.julia b/Task/Bulls-and-cows/Julia/bulls-and-cows-2.julia index d3ed5f648f..9663d50472 100644 --- a/Task/Bulls-and-cows/Julia/bulls-and-cows-2.julia +++ b/Task/Bulls-and-cows/Julia/bulls-and-cows-2.julia @@ -1,6 +1,6 @@ function bullsandcows () bulls = cows = turns = 0 - result = (s = {} ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s)) + result = (s = [] ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s)) println("A game of bulls and cows!") while (bulls != 4) print("Your guess? ") diff --git a/Task/Bulls-and-cows/Rust/bulls-and-cows.rust b/Task/Bulls-and-cows/Rust/bulls-and-cows.rust index 8aafc2dab7..31e347b6d5 100644 --- a/Task/Bulls-and-cows/Rust/bulls-and-cows.rust +++ b/Task/Bulls-and-cows/Rust/bulls-and-cows.rust @@ -1,77 +1,82 @@ use std::io; -use std::rand::{task_rng, Rng}; +use rand::{Rng,thread_rng}; -static NUMBER_OF_DIGITS: uint = 4; +extern crate rand; -static DIGITS: [char, ..9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9']; +const NUMBER_OF_DIGITS: usize = 4; + +static DIGITS: [char; 9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9']; fn generate_digits() -> Vec { - let mut temp_digits = Vec::from_slice(DIGITS); - task_rng().shuffle(temp_digits.as_mut_slice()); - return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect(); + let mut temp_digits: Vec<_> = (&DIGITS[..]).into(); + thread_rng().shuffle(&mut temp_digits); + return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect(); } -fn parse_guess_string(guess: &String) -> Result, String> { - let chars: Vec = guess.as_slice().chars().collect(); +fn parse_guess_string(guess: &str) -> Result, String> { + let chars: Vec = (&guess).chars().collect(); - if !chars.iter().all(|c| DIGITS.contains(c)) { - return Err("only digits, please".to_string()); - } + if !chars.iter().all(|c| DIGITS.contains(c)) { + return Err("only digits, please".to_string()); + } - if chars.len() != NUMBER_OF_DIGITS { - return Err(format!("you need to guess with {:u} digits", NUMBER_OF_DIGITS)); - } + if chars.len() != NUMBER_OF_DIGITS { + return Err(format!("you need to guess with {} digits", NUMBER_OF_DIGITS)); + } - let mut uniques: Vec = chars.clone(); - uniques.dedup(); - if uniques.len() != chars.len() { - return Err("no duplicates, please".to_string()); - } + let mut uniques: Vec = chars.clone(); + uniques.dedup(); + if uniques.len() != chars.len() { + return Err("no duplicates, please".to_string()); + } - return Ok(chars); + return Ok(chars); } -fn calculate_score(given_digits: &Vec, guessed_digits: &Vec) -> (uint, uint) { - let mut bulls = 0; - let mut cows = 0; - for i in range(0, NUMBER_OF_DIGITS) { - let pos: Option = guessed_digits.iter().position(|&a| -> bool {a == given_digits[i]}); - match pos { - None => (), - Some(p) if p == i => bulls += 1, - Some(_) => cows += 1 +fn calculate_score(given_digits: &[char], guessed_digits: &[char]) -> (usize, usize) { + let mut bulls = 0; + let mut cows = 0; + for i in 0..NUMBER_OF_DIGITS { + let pos: Option = guessed_digits.iter().position(|&a| -> bool {a == given_digits[i]}); + match pos { + None => (), + Some(p) if p == i => bulls += 1, + Some(_) => cows += 1 + } } - } - return (bulls, cows); + return (bulls, cows); } fn main() { - let mut reader = io::stdin(); - - loop { - let given_digits = generate_digits(); - println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS); + let reader = io::stdin(); loop { + let given_digits = generate_digits(); + println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS); - let guess_string = reader.read_line().unwrap().as_slice().trim().to_string(); + loop { + let guess_string: String = { + let mut buf = String::new(); + reader.read_line(&mut buf).unwrap(); + buf.trim().into() + }; - let digits_maybe = parse_guess_string(&guess_string); - match digits_maybe { - Err(msg) => { - println!("{}", msg); - continue; - }, - Ok(guess_digits) => { - match calculate_score(&given_digits, &guess_digits) { - (NUMBER_OF_DIGITS, _) => { - println!("you win!"); - break; - }, - (bulls, cows) => println!("bulls: {:u}, cows: {:u}", bulls, cows) - } + let digits_maybe = parse_guess_string(&guess_string); + match digits_maybe { + Err(msg) => { + println!("{}", msg); + continue; + }, + Ok(guess_digits) => { + match calculate_score(&given_digits, &guess_digits) { + (NUMBER_OF_DIGITS, _) => { + println!("you win!"); + break; + }, + (bulls, cows) => println!("bulls: {}, cows: {}", bulls, cows) + } + } + } } - } } - } } diff --git a/Task/CRC-32/ALGOL-68/crc-32.alg b/Task/CRC-32/ALGOL-68/crc-32.alg new file mode 100644 index 0000000000..6e949b4d94 --- /dev/null +++ b/Task/CRC-32/ALGOL-68/crc-32.alg @@ -0,0 +1,54 @@ +[0:255]BITS crc_table; +BOOL crc_table_computed := FALSE; + +PROC make_crc_table = VOID: + BEGIN + INT n, k; + FOR n FROM 0 TO 255 DO + BITS c := BIN n; + FOR k TO 8 DO + c := IF 32 ELEM c THEN + 16redb88320 XOR (c SHR 1) + ELSE + c SHR 1 + FI + OD; + crc_table[n] := c + OD; + crc_table_computed := TRUE + END; + +PROC update_crc = (BITS crc, STRING buf) BITS: + BEGIN + BITS c := crc XOR 16rffffffff; + INT n; + + IF NOT crc_table_computed THEN make_crc_table FI; + FOR n TO UPB buf DO + c := crc_table[ABS ((c XOR BIN ABS buf[n]) AND 16rff)] XOR (c SHR 8) + OD ; + c XOR 16rffffffff + END; + + PROC hex = (BITS x) STRING : + BEGIN + PROC hexdig = (BITS x) CHAR: REPR (IF ABS x ≤ 9 THEN ABS x + ABS "0" + ELSE ABS x - 10 + ABS "a" + FI); + STRING h := ""; + IF x = 16r0 THEN + h := "0" + ELSE + BITS n := x; + WHILE h := hexdig (n AND 16rf) + h; n ≠ 16r0 DO + n := n SHR 4 + OD + FI; + h + END; + +PROC crc = (STRING buf) BITS: + update_crc(16r0, buf); + +STRING s = "The quick brown fox jumps over the lazy dog"; +print(("CRC32 OF ", s, " is: ", hex (crc (s)), newline)) diff --git a/Task/CRC-32/CoffeeScript/crc-32-1.coffee b/Task/CRC-32/CoffeeScript/crc-32-1.coffee new file mode 100644 index 0000000000..e5d113f74e --- /dev/null +++ b/Task/CRC-32/CoffeeScript/crc-32-1.coffee @@ -0,0 +1,13 @@ +crc32 = do -> + table = + for n in [0..255] + for [0..7] + if n & 1 + n = 0xEDB88320 ^ n >>> 1 + else + n >>>= 1 + n + (str, crc = -1) -> + for c in str + crc = crc >>> 8 ^ table[(crc ^ c.charCodeAt 0) & 255] + (crc ^ -1) >>> 0 diff --git a/Task/CRC-32/CoffeeScript/crc-32-2.coffee b/Task/CRC-32/CoffeeScript/crc-32-2.coffee new file mode 100644 index 0000000000..ce9184d7ce --- /dev/null +++ b/Task/CRC-32/CoffeeScript/crc-32-2.coffee @@ -0,0 +1 @@ +console.log (crc32 'The quick brown fox jumps over the lazy dog').toString 16 diff --git a/Task/CRC-32/CoffeeScript/crc-32-3.coffee b/Task/CRC-32/CoffeeScript/crc-32-3.coffee new file mode 100644 index 0000000000..d330329024 --- /dev/null +++ b/Task/CRC-32/CoffeeScript/crc-32-3.coffee @@ -0,0 +1 @@ +414fa339 diff --git a/Task/CRC-32/Elixir/crc-32.elixir b/Task/CRC-32/Elixir/crc-32.elixir new file mode 100644 index 0000000000..153a9b0975 --- /dev/null +++ b/Task/CRC-32/Elixir/crc-32.elixir @@ -0,0 +1,7 @@ +defmodule Test do + def crc32(str) do + IO.puts :erlang.crc32(str) |> Integer.to_string(16) + end +end + +Test.crc32("The quick brown fox jumps over the lazy dog") diff --git a/Task/CRC-32/Julia/crc-32.julia b/Task/CRC-32/Julia/crc-32.julia new file mode 100644 index 0000000000..ed17de8403 --- /dev/null +++ b/Task/CRC-32/Julia/crc-32.julia @@ -0,0 +1,32 @@ +function crc32(crc::Int, str::ASCIIString) + table = zeros(Uint32, 256) + + for i=0:255 + temp = i + + for j=0:7 + if temp & 1 == 1 + temp >>= 1 + temp $= 0xedb88320 + else + temp >>= 1 + end + end + + table[i + 1] = temp + end + + crc $= 0xffffffff + + for i in map(Uint32, collect(str)) + crc = (crc >> 8) $ table[(crc & 0xff) $ i + 1] + end + + crc $ 0xffffffff +end + +str = "The quick brown fox jumps over the lazy dog" +crc = crc32(0, str) +assert(crc == 0x414fa339) +println("Message: ", str) +println("Checksum: ", hex(crc)) diff --git a/Task/CRC-32/REXX/crc-32.rexx b/Task/CRC-32/REXX/crc-32.rexx index 50da774811..5cdc2c3122 100644 --- a/Task/CRC-32/REXX/crc-32.rexx +++ b/Task/CRC-32/REXX/crc-32.rexx @@ -1,37 +1,37 @@ -/*REXX program computes the CRC-32 (32 bit Cylic Redundancy Check), */ -/* checksum for a given string [as described in ISO 3309, ITU-T V.42].*/ -/*──────────────────────────────────────────────────────────────────────*/ -call show 'The quick brown fox jumps over the lazy dog' /*1st str*/ -call show 'Generate CRC32 Checksum For Byte Array Example' /*2nd str*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────CRC_32 subroutine───────────────────*/ -CRC_32: procedure; parse arg !,$ /*2nd arg: repeated─invocations.*/ - /* [↓] build 8─bit indexed table*/ - do i=0 for 256; z=d2c(i) /* one byte at a time. */ - r=right(z, 4, '0'x) /*insure the "R" is 32 bits. */ +/*REXX program computes the CRC─32 (32 bit Cyclic Redundancy Check) checksum*/ +/*─────────────────for a given string [as described in ISO 3309, ITU─T V.42].*/ - do j=0 for 8 /*handle each bit of rightmost 8.*/ - rb=x2b(c2x(r)) /*convert char ──► hex ──► binary*/ - _=right(rb,1) /*remember right-most bit for IF.*/ - r=x2c(b2x(0 || left(rb, 31))) /*shift it right (unsigned) 1 bit*/ - if _\==0 then r=bitxor(r, 'edb88320'x) /*bit XOR grunt─work.*/ +call show 'The quick brown fox jumps over the lazy dog' /*1st string.*/ +call show 'Generate CRC32 Checksum For Byte Array Example' /*2nd " */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +CRC_32: procedure; parse arg !,$ /*2nd arg: it has repeated─invocations.*/ + /* [↓] build an 8─bit indexed table,*/ + do i=0 for 256; z=d2c(i) /* one byte at a time.*/ + r=right(z, 4, '0'x) /*insure the "R" is thirty-two bits.*/ + + do j=0 for 8 /*handle each bit of rightmost 8 bits. */ + rb=x2b(c2x(r)) /*convert character ──► hex ──► binary.*/ + _=right(rb,1) /*remember the right─most bit for IF. */ + r=x2c(b2x(0 || left(rb, 31))) /*shift it right (an unsigned) 1 bit.*/ + if _\==0 then r=bitxor(r, 'edb88320'x) /*this is bit XOR grunt─work.*/ end /*j*/ - !.z=r /*assign to an 8─bit index table.*/ + !.z=r /*assign to an eight─bit index table. */ end /*i*/ -$=bitxor(word($ '0000000'x,1),'ffFFffFF'x) /*use user's CRC or default.*/ - do k=1 for length(!) /*start crunching the input data.*/ +$=bitxor(word($ '0000000'x,1),'ffFFffFF'x) /*use the user's CRC or a default.*/ + do k=1 for length(!) /*start crunching the input data. */ ?=bitxor(right($, 1), substr(!, k, 1)) $=bitxor('0'x || left($, 3), !.?) end /*k*/ -return $ /*return with da money to invoker*/ -/*──────────────────────────────────SHOW subroutine─────────────────────*/ -show: procedure; parse arg Xstring; numeric digits 12; say; say -checksum=CRC_32(Xstring) /*invoke CRC_32 to create a CRC*/ -checksum=bitxor(checksum,'ffFFffFF'x) /*final convolution for checksum.*/ +return $ /*return with da money to the invoker. */ +/*────────────────────────────────────────────────────────────────────────────*/ +show: procedure; parse arg Xstring; numeric digits 12; say; say +checksum=CRC_32(Xstring) /*invoke CRC_32 to create a CRC.*/ +checksum=bitxor(checksum,'ffFFffFF'x) /*final convolution for checksum.*/ say center(' input string [length of' length(Xstring) "bytes] ", 79, '═') -say Xstring /*show the string on its own line*/ -say /* ↓↓↓↓↓↓↓↓↓↓↓↓ is 15 blanks.*/ -say 'hex CRC-32 checksum =' c2x(checksum) left('', 15), - "dec CRC-32 checksum =" c2d(checksum) /*show CRC-32 in hex & dec.*/ +say Xstring /*show the string on its own line*/ +say /*↓↓↓↓↓↓↓↓↓↓↓↓ is fifteen blanks*/ +say 'hex CRC-32 checksum =' c2x(checksum) left('', 15), + "dec CRC-32 checksum =" c2d(checksum) /*show the CRC-32 in hex and dec.*/ return diff --git a/Task/CSV-data-manipulation/ALGOL-68/csv-data-manipulation.alg b/Task/CSV-data-manipulation/ALGOL-68/csv-data-manipulation.alg new file mode 100644 index 0000000000..749c7da413 --- /dev/null +++ b/Task/CSV-data-manipulation/ALGOL-68/csv-data-manipulation.alg @@ -0,0 +1,88 @@ +# count occurrances of a char in string # +PROC char count = (CHAR c, STRING str) INT: + BEGIN + INT count := 0; + FOR i TO UPB str DO + IF c = str[i] THEN count +:= 1 + FI + OD; + count + END; + +# split string on separator # +PROC char split = (STRING str, CHAR sep) FLEX[]STRING : + BEGIN + INT strlen := UPB str, cnt := 0; + INT len, p; + INT start := 1; + [char count (sep, str) + 1] STRING list; + WHILE start <= strlen ANDF char in string (sep, p, str[start:]) DO + p +:= start - 1; + list[cnt +:= 1] := str[start:p-1]; + start := p + 1 + OD; + IF cnt = 0 THEN list[cnt +:= 1] := str + ELIF start <= UPB str + 1 THEN list[cnt +:= 1] := str[start:] + FI; + list + END; + +PROC join = ([]STRING words, STRING sep) STRING: + IF UPB words > 0 THEN + STRING str := words [1]; + FOR i FROM 2 TO UPB words DO + str +:= sep + words[i] + OD; + str + ELSE + "" + FI; + +# read a line from file # +PROC readline = (REF FILE f) STRING: + BEGIN + STRING line; + get (f, line); new line (f); + line + END; + +# Add one item to tuple # +OP +:= = (REF FLEX[]STRING tuple, STRING item) VOID: + BEGIN + [UPB tuple+1]STRING new; + new[:UPB tuple] := tuple; + new[UPB new] := item; + tuple := new + END; + +# convert signed number TO INT # +OP TOINT = (STRING str) INT: + BEGIN + INT n := 0, sign := 1; + FOR i TO UPB str WHILE sign /= 0 DO + IF is digit (str[i]) THEN n := n * 10 + ABS str[i] - ABS "0" + ELIF i = 1 AND str[i] = "-" THEN sign := -1 + ELIF i /= 1 OR str[i] /= "+" THEN sign := 0 + FI + OD; + n * sign + END; + +OP STR = (INT i) STRING: whole (i,0); + +# The main program # +FILE foo; +open (foo, "CSV_data_manipulation.data", stand in channel); +FLEX[0]STRING header := char split (readline (foo), ","); +header +:= "SUM"; +print ((join (header, ","), new line)); +WHILE NOT end of file (foo) DO + FLEX[0]STRING fields := char split (readline (foo), ","); + INT sum := 0; + FOR i TO UPB fields DO + sum +:= TOINT fields[i] + OD; + fields +:= STR sum; + print ((join (fields, ","), new line)) +OD; +close (foo) diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.ada b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.ada new file mode 100644 index 0000000000..66d0814c1a --- /dev/null +++ b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-1.ada @@ -0,0 +1,19 @@ +package CSV is + + type Row(<>) is tagged private; + + function Line(S: String; Separator: Character := ',') return Row; + function Next(R: in out Row) return Boolean; + -- if there is still an item in R, Next advances to it and returns True + function Item(R: Row) return String; + -- after calling R.Next i times, this returns the i'th item (if any) + +private + type Row(Length: Natural) is tagged record + Str: String(1 .. Length); + Fst: Positive; + Lst: Natural; + Nxt: Positive; + Sep: Character; + end record; +end CSV; diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.ada b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.ada new file mode 100644 index 0000000000..d3be3a211f --- /dev/null +++ b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-2.ada @@ -0,0 +1,24 @@ +package body CSV is + + function Line(S: String; Separator: Character := ',') + return Row is + (Length => S'Length, Str => S, + Fst => S'First, Lst => S'Last, Nxt => S'First, Sep => Separator); + + function Item(R: Row) return String is + (R.Str(R.Fst .. R.Lst)); + + function Next(R: in out Row) return Boolean is + Last: Natural := R.Nxt; + begin + R.Fst := R.Nxt; + while Last <= R.Str'Last and then R.Str(Last) /= R.Sep loop + -- find Separator + Last := Last + 1; + end loop; + R.Lst := Last - 1; + R.Nxt := Last + 1; + return (R.Fst <= R.Str'Last); + end Next; + +end CSV; diff --git a/Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.ada b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.ada new file mode 100644 index 0000000000..f402572d3f --- /dev/null +++ b/Task/CSV-data-manipulation/Ada/csv-data-manipulation-3.ada @@ -0,0 +1,19 @@ +with CSV, Ada.Text_IO; use Ada.Text_IO; + +procedure CSV_Data_Manipulation is + Header: String := Get_Line; +begin + Put_Line(Header & ", SUM"); + while not End_Of_File loop + declare + R: CSV.Row := CSV.Line(Get_Line); + Sum: Integer := 0; + begin + while R.Next loop + Sum := Sum + Integer'Value(R.Item); + Put(R.Item & ","); + end loop; + Put_Line(Integer'Image(Sum)); + end; + end loop; +end CSV_Data_Manipulation; diff --git a/Task/CSV-data-manipulation/Common-Lisp/csv-data-manipulation.lisp b/Task/CSV-data-manipulation/Common-Lisp/csv-data-manipulation.lisp index f1f6ddfdc4..e654cbc197 100644 --- a/Task/CSV-data-manipulation/Common-Lisp/csv-data-manipulation.lisp +++ b/Task/CSV-data-manipulation/Common-Lisp/csv-data-manipulation.lisp @@ -1,4 +1,4 @@ -(defun csv_to_nested_list (filename seperator) +(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 @@ -13,23 +13,23 @@ First line is assumed to be a comment (as no comment syntax is specified)." ;; throw away first line, which is assumed to be a comment (cdr list)))) -(defun calc_sums (nested_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))) + (loop for sublist in nested-list collect (apply #'+ sublist))) -(defun list_to_csv (nested_list) +(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)))))) + (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) +(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) + (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 + (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/Go/csv-data-manipulation.go b/Task/CSV-data-manipulation/Go/csv-data-manipulation.go index cf94c2bade..d6adc29b82 100644 --- a/Task/CSV-data-manipulation/Go/csv-data-manipulation.go +++ b/Task/CSV-data-manipulation/Go/csv-data-manipulation.go @@ -2,78 +2,57 @@ 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") + rows := readSample() + appendSum(rows) + writeChanges(rows) +} - // Exit on error. +func readSample() [][]string { + f, err := os.Open("sample.csv") if err != nil { - log.Fatal("Error opening sample csv file:", err) + log.Fatal(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") + rows, err := csv.NewReader(f).ReadAll() + f.Close() if err != nil { - log.Fatal("Error creating output file:", err) + log.Fatal(err) } - defer outputFile.Close() + return rows +} - csvWriter := csv.NewWriter(outputFile) - defer csvWriter.Flush() +func appendSum(rows [][]string) { + rows[0] = append(rows[0], "SUM") + for i := 1; i < len(rows); i++ { + rows[i] = append(rows[i], sum(rows[i])) + } +} - // For each row in the data. - for i := 0; ; i++ { - record, err := csvReader.Read() - if err == io.EOF { - break - } +func sum(row []string) string { + sum := 0 + for _, s := range row { + x, err := strconv.Atoi(s) 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) + return "NA" } + sum += x + } + return strconv.Itoa(sum) +} - // Write modified record to disk. - err = csvWriter.Write(record) - if err != nil { - log.Fatal("Error writing record to output file:", err) - } +func writeChanges(rows [][]string) { + f, err := os.Create("output.csv") + if err != nil { + log.Fatal(err) + } + err = csv.NewWriter(f).WriteAll(rows) + f.Close() + if err != nil { + log.Fatal(err) } } diff --git a/Task/CSV-data-manipulation/Java/csv-data-manipulation-3.java b/Task/CSV-data-manipulation/Java/csv-data-manipulation-3.java new file mode 100644 index 0000000000..a683df216b --- /dev/null +++ b/Task/CSV-data-manipulation/Java/csv-data-manipulation-3.java @@ -0,0 +1,31 @@ +public static void main(String[] args) throws IOException { + + // 1st, config the CSV reader with line separator + CsvParserSettings settings = new CsvParserSettings(); + settings.getFormat().setLineSeparator("\n"); + + // 2nd, config the CSV reader with row processor attaching the bean definition + BeanListProcessor rowProcessor = new BeanListProcessor(Employee.class); + settings.setRowProcessor(rowProcessor); + + // 3rd, creates a CSV parser with the configs + CsvParser parser = new CsvParser(settings); + + // 4th, parse all rows from the CSF file into the list of beans you defined + parser.parse(new FileReader("/examples/employees.csv")); + List resolvedBeans = rowProcessor.getBeans(); + + // 5th, Store, Delete duplicates, Re-arrange the words in specific order + // ...... + + // 6th, Write the listed of processed employee beans out to a CSV file. + CsvWriterSettings writerSettings = new CsvWriterSettings(); + + // 6.1 Creates a BeanWriterProcessor that handles annotated fields in the Employee class. + writerSettings.setRowWriterProcessor(new BeanWriterProcessor(Employee.class)); + + // 6.2 persistent the employee beans to a CSV file. + CsvWriter writer = new CsvWriter(new FileWriter("/examples/processed_employees.csv"), writerSettings); + writer.processRecords(resolvedBeans); + writer.writeRows(new ArrayList>()); + } diff --git a/Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia b/Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia new file mode 100644 index 0000000000..f79aca6fee --- /dev/null +++ b/Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia @@ -0,0 +1,14 @@ +ifn = "csv_data_manipulation_in.dat" +ofn = "csv_data_manipulation_out.dat" + +ifile = open(ifn, "r") +(a, h) = readcsv(ifile, Int, header=true) +close(ifile) + +a = hcat(a, sum(a, 2)) +h = hcat(h, "SUM") +a = vcat(h, a) + +ofile = open(ofn, "w") +writecsv(ofile, a) +close(ofile) diff --git a/Task/CSV-data-manipulation/TXR/csv-data-manipulation.txr b/Task/CSV-data-manipulation/TXR/csv-data-manipulation.txr new file mode 100644 index 0000000000..7fa44fc012 --- /dev/null +++ b/Task/CSV-data-manipulation/TXR/csv-data-manipulation.txr @@ -0,0 +1,11 @@ +@(coll)@{name /[^,]+/}@(end) +@(collect :vars (value sum)) +@ (bind sum 0) +@ (coll)@{value /[^,]+/}@(set sum @(+ sum (int-str value)))@(end) +@(end) +@(output) +@ (rep)@name,@(last)SUM@(end) +@ (repeat) +@ (rep)@value,@(last)@sum@(end) +@ (end) +@(end) diff --git a/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vb b/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vb new file mode 100644 index 0000000000..da5502ec55 --- /dev/null +++ b/Task/CSV-data-manipulation/VBScript/csv-data-manipulation.vb @@ -0,0 +1,35 @@ +'Instatiate FSO. +Set objFSO = CreateObject("Scripting.FileSystemObject") +'Open the CSV file for reading. The file is in the same folder as the script and named csv_sample.csv. +Set objInCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",1,False) +'Set header status to account for the first line as the column headers. +IsHeader = True +'Initialize the var for the output string. +OutTxt = "" +'Read each line of the file. +Do Until objInCSV.AtEndOfStream + line = objInCSV.ReadLine + If IsHeader Then + OutTxt = OutTxt & line & ",SUM" & vbCrLf + IsHeader = False + Else + OutTxt = OutTxt & line & "," & AddElements(line) & vbCrLf + End If +Loop +'Close the file. +objInCSV.Close +'Open the same file for writing. +Set objOutCSV = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\csv_sample.csv",2,True) +'Write the var OutTxt to the file overwriting existing contents. +objOutCSV.Write OutTxt +'Close the file. +objOutCSV.Close +Set objFSO = Nothing + +'Routine to add each element in a row. +Function AddElements(s) + arr = Split(s,",") + For i = 0 To UBound(arr) + AddElements = AddElements + CInt(arr(i)) + Next +End Function diff --git a/Task/CSV-to-HTML-translation/Befunge/csv-to-html-translation-1.bf b/Task/CSV-to-HTML-translation/Befunge/csv-to-html-translation-1.bf new file mode 100644 index 0000000000..479b480e21 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Befunge/csv-to-html-translation-1.bf @@ -0,0 +1,9 @@ +#!,#:< "" \0 +55 + v >0>::65*1+`\"~"`!*#v_4-5v > +v>#^~^" + RETURN + else + html "" + RETURN + end if + end if + r2 = sqr((x1-x2)^2+(y1-y2)^2)/2 'half distance between points + if rPoints are too far apart (";2*r2;") - there are no circles of radius ";r + RETURN + end if + + 'else, calculate two centers + cx=(x1+x2)/2 'middle point + cy=(y1+y2)/2 + 'should move from middle point along perpendicular by dd2 + dd2=sqr(r^2-r2^2) 'perpendicular distance + dx1=x2-cx 'vector to middle point + dy1=y2-cy + dx = 0-dy1/r2*dd2 'perpendicular: + dy = dx1/r2*dd2 'rotate and scale + html "" 'two points, with (+) + html "" 'and (-) +RETURN 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 index fc5787a302..ee6c2e400a 100644 --- 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 @@ -1,58 +1,58 @@ use std::fmt; +#[derive(Clone,Copy)] 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() - } +fn distance (p1: Point, p2: Point) -> f64 { + ((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt() } -impl fmt::Show for Point { // a Point become printable in console +impl fmt::Display for Point { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "({:.4f}, {:.4f})", self.x, self.y) + write!(f, "({:.4}, {:.4})", 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 describe_circle(p1: Point, p2: Point, r: f64) { + let sep = distance(p1, p2); + + if sep == 0. { + if r == 0. { + println!("No circles can be drawn through {}", p1); + } else { + println!("Infinitely many circles can be drawn through {}", p1); + } + } else if sep == 2.0 * r { + println!("Given points are opposite ends of a diameter of the circle with center ({:.4},{:.4}) and r {:.4}", + (p1.x+p2.x) / 2.0, (p1.y+p2.y) / 2.0, r); + } else if sep > 2.0 * r { + println!("Given points are farther away from each other than a diameter of a circle with r {:.4}", r); + } else { + let mirror_dist = (r.powi(2) - (sep / 2.0).powi(2)).sqrt(); + + println!("Two circles are possible."); + println!("Circle C1 with center ({:.4}, {:.4}), r {:.4} and Circle C2 with center ({:.4}, {:.4}), r {:.4}", + ((p1.x + p2.x) / 2.0) + mirror_dist * (p1.y-p2.y)/sep, (p1.y+p2.y) / 2.0 + mirror_dist*(p2.x-p1.x)/sep, + r, + (p1.x+p2.x) / 2.0 - mirror_dist*(p1.y-p2.y)/sep, (p1.y+p2.y) / 2.0 - mirror_dist*(p2.x-p1.x)/sep, r); + } } 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); - } + let points: Vec<(Point, Point)> = vec![ + (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }), + (Point { x: 0.0000, y: 2.0000 }, Point { x: 0.0000, y: 0.0000 }), + (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 }), + (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }), + (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 }) + ]; + let radii: Vec = vec![2.0, 1.0, 2.0, 0.5, 0.0]; + + for (p, r) in points.into_iter().zip(radii.into_iter()) { + println!("\nPoints: ({}, {}), Radius: {:.4}", p.0, p.1, r); + describe_circle(p.0, p.1, r); + } } diff --git a/Task/Circles-of-given-radius-through-two-points/Scala/circles-of-given-radius-through-two-points.scala b/Task/Circles-of-given-radius-through-two-points/Scala/circles-of-given-radius-through-two-points.scala new file mode 100644 index 0000000000..34ec951847 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Scala/circles-of-given-radius-through-two-points.scala @@ -0,0 +1,55 @@ +import org.scalatest.FunSuite +import math._ + +case class V2(x: Double, y: Double) { + val distance = hypot(x, y) + def /(other: V2) = V2((x+other.x) / 2.0, (y+other.y) / 2.0) + def -(other: V2) = V2(x-other.x,y-other.y) + override def equals(other: Any) = other match { + case p: V2 => abs(x-p.x) < 0.0001 && abs(y-p.y) < 0.0001 + case _ => false + } + override def toString = f"($x%.4f, $y%.4f)" +} + +case class Circle(center: V2, radius: Double) + +class PointTest extends FunSuite { + println(" p1 p2 r result") + Seq( + (V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0, Seq(Circle(V2(1.8631, 1.9742), 2.0), Circle(V2(-0.8632, -0.7521), 2.0))), + (V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0, Seq(Circle(V2(0.0, 1.0), 1.0))), + (V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0, "coincident points yields infinite circles"), + (V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5, "radius is less then the distance between points"), + (V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0, "radius of zero yields no circles") + ) foreach { v => + print(s"${v._1} ${v._2} ${v._3}: ") + circles(v._1, v._2, v._3) match { + case Right(list) => println(list mkString ",") + assert(list === v._4) + case Left(error) => println(error) + assert(error === v._4) + } + } + + def circles(p1: V2, p2: V2, radius: Double) = if (radius == 0.0) { + Left("radius of zero yields no circles") + } else if (p1 == p2) { + Left("coincident points yields infinite circles") + } else if (radius * 2 < (p1-p2).distance) { + Left("radius is less then the distance between points") + } else { + Right(circlesThruPoints(p1, p2, radius)) + } ensuring { result => + result.isLeft || result.right.get.nonEmpty + } + + def circlesThruPoints(p1: V2, p2: V2, radius: Double): Seq[Circle] = { + val diff = p2 - p1 + val d = pow(pow(radius, 2) - pow(diff.distance / 2, 2), 0.5) + val mid = p1 / p2 + Seq( + Circle(V2(mid.x - d * diff.y / diff.distance, mid.y + d * diff.x / diff.distance), abs(radius)), + Circle(V2(mid.x + d * diff.y / diff.distance, mid.y - d * diff.x / diff.distance), abs(radius))).distinct + } +} diff --git a/Task/Classes/C/classes.c b/Task/Classes/C/classes.c index 0d98c78fc9..8e7765378c 100644 --- a/Task/Classes/C/classes.c +++ b/Task/Classes/C/classes.c @@ -1,3 +1,5 @@ +#include + typedef struct sMyClass { int variable; @@ -5,15 +7,14 @@ typedef struct sMyClass MyClass MyClass_new() { - MyClass pthis = malloc( sizeof(struct sMyClass) ); - //memset(pthis, 0, sizeof(struct sMyClass) ); + MyClass pthis = malloc(sizeof *pthis); pthis->variable = 0; return pthis; } void MyClass_delete(MyClass* pthis) { - if(pthis && *pthis) + if (pthis) { free(*pthis); *pthis = NULL; diff --git a/Task/Classes/Forth/classes-7.fth b/Task/Classes/Forth/classes-7.fth new file mode 100644 index 0000000000..ebe0433718 --- /dev/null +++ b/Task/Classes/Forth/classes-7.fth @@ -0,0 +1,31 @@ +include FMS-SI.f + +:class foo \ begin class foo definition + ivar x \ declare an instance variable named x + :m put ( n -- ) x ! ;m \ a method/message definition + :m init: 10 self put ;m \ the constructor method + :m print x ? ;m \ a print method for x +;class \ end class foo definition + +foo f1 \ instantiate a foo object, in the dictionary, named f1 +f1 print \ 10 send the print message to object f1 +20 f1 put \ send a message with one parameter to the object +f1 print \ 20 + + +: bar \ bar is a normal Forth function definition + heap> foo \ instantiate a nameless object in the heap + dup print + 30 over put + dup print + foo {: f :} + f print + 30 f put + f print + f calculate_circle_area + procedure, pass :: get_circle_diameter + final :: finalize_circle + end type TCircle + + ! extended derived type + type, extends(TShape) :: TRectangle + type(TPoint) :: A,B,C,D + contains + procedure, pass :: calculate_area => calculate_rectangle_area + final :: finalize_rectangle + end type TRectangle + + ! extended derived type + type, extends(TRectangle) :: TSquare + contains + procedure, pass :: calculate_area => calculate_square_area + final :: finalize_square + end type TSquare + + contains + + ! finalization subroutines for each type + ! They called recursively, i.e. finalize_rectangle + ! will be called after finalize_square subroutine + subroutine finalize_circle(x) + type(TCircle), intent(inout) :: x + write(*,*) "Deleting TCircle object" + end subroutine finalize_circle + + subroutine finalize_rectangle(x) + type(TRectangle), intent(inout) :: x + write(*,*) "Deleting also TRectangle object" + end subroutine finalize_rectangle + + subroutine finalize_square(x) + type(TSquare), intent(inout) :: x + write(*,*) "Deleting TSquare object" + end subroutine finalize_square + + function calculate_circle_area(this) + implicit none + class(TCircle) :: this + real(rdp) :: calculate_circle_area + this%area = pi * this%radius**2 + calculate_circle_area = this%area + end function calculate_circle_area + + function calculate_rectangle_area(this) + implicit none + class(TRectangle) :: this + real(rdp) :: calculate_rectangle_area + ! here could be more code + this%area = 1 + calculate_rectangle_area = this%area + end function calculate_rectangle_area + + function calculate_square_area(this) + implicit none + class(TSquare) :: this + real(rdp) :: calculate_square_area + ! here could be more code + this%area = 1 + calculate_square_area = this%area + end function calculate_square_area + + function get_circle_diameter(this) + implicit none + class(TCircle) :: this + real(rdp) :: get_circle_diameter + this % diameter = 2.0_rdp * this % radius + get_circle_diameter = this % diameter + end function get_circle_diameter + +end module typedefs_module + +!----------------------------------------------------------------------- +!Main program +!----------------------------------------------------------------------- +program rosetta_class + use accuracy_module + use typedefs_module + implicit none + + ! we need this subroutine in order to show the finalization + call test_types() + + contains + + subroutine test_types() + implicit none + ! declare object of type TPoint + type(TPoint), target :: point + ! declare object of type TCircle + type(TCircle),target :: circle + ! declare object of type TSquare + type(TSquare),target :: square + + ! declare pointers + class(TPoint), pointer :: ppo + class(TCircle), pointer :: pci + class(TSquare), pointer :: psq + + !constructor + point = TPoint(5.d0,5.d0) + ppo => point + write(*,*) "x=",point%x,"y=",point%y + + pci => circle + + pci % radius = 1 + write(*,*) pci % radius + ! write(*,*) pci % diameter !No,it is a PRIVATE component + write(*,*) pci % get_circle_diameter() + write(*,*) pci % calculate_area() + write(*,*) pci % area + + psq => square + + write(*,*) psq % area + write(*,*) psq % calculate_area() + write(*,*) psq % area + end subroutine test_types + +end program rosetta_class diff --git a/Task/Classes/JavaScript/classes.js b/Task/Classes/JavaScript/classes-1.js similarity index 100% rename from Task/Classes/JavaScript/classes.js rename to Task/Classes/JavaScript/classes-1.js diff --git a/Task/Classes/JavaScript/classes-2.js b/Task/Classes/JavaScript/classes-2.js new file mode 100644 index 0000000000..b590772fd2 --- /dev/null +++ b/Task/Classes/JavaScript/classes-2.js @@ -0,0 +1,77 @@ +class Car { + /** + * A few brands of cars + * @type {string[]} + */ + static brands = ['Mazda', 'Volvo']; + + /** + * Weight of car + * @type {number} + */ + weight = 1000; + + /** + * Brand of car + * @type {string} + */ + brand; + + /** + * Price of car + * @type {number} + */ + price; + + /** + * @param {string} brand - car brand + * @param {number} weight - mass of car + */ + constructor(brand, weight) { + if (brand) this.brand = brand; + if (weight) this.weight = weight + } + + /** + * Drive + * @param distance - distance to drive + */ + drive(distance = 10) { + console.log(`A ${this.brand} ${this.constructor.name} drove ${distance}cm`); + } + + /** + * Formatted stats string + */ + get formattedStats() { + let out = + `Type: ${this.constructor.name.toLowerCase()}` + + `\nBrand: ${this.brand}` + + `\nWeight: ${this.weight}`; + + if (this.size) out += `\nSize: ${this.size}`; + + return out + } +} + +class Truck extends Car { + /** + * Size of truck + * @type {number} + */ + size; + + /** + * @param {string} brand - car brand + * @param {number} size - size of car + */ + constructor(brand, size) { + super(brand, 2000); + if (size) this.size = size; + } +} + +let myTruck = new Truck('Volvo', 2); +console.log(myTruck.formattedStats); +myTruck.drive(40); diff --git a/Task/Classes/TXR/classes.txr b/Task/Classes/TXR/classes.txr new file mode 100644 index 0000000000..921d923b55 --- /dev/null +++ b/Task/Classes/TXR/classes.txr @@ -0,0 +1,24 @@ +(defstruct shape () + cached-area + + (:init (self) + (put-line `@self is born!`)) + + (:fini (self) + (put-line `@self says goodbye!`)) + + (:method area (self) + (or self.cached-area + (set self.cached-area self.(calc-area))))) + +(defstruct circle shape + (radius 1.0) + + (:method calc-area (self) + (* %pi% self.radius self.radius))) + +(defstruct square shape + (length 1.0) + + (:method calc-area (self) + (* self.length self.length))) diff --git a/Task/Closest-pair-problem/Elixir/closest-pair-problem.elixir b/Task/Closest-pair-problem/Elixir/closest-pair-problem.elixir new file mode 100644 index 0000000000..c55ab39a89 --- /dev/null +++ b/Task/Closest-pair-problem/Elixir/closest-pair-problem.elixir @@ -0,0 +1,24 @@ +defmodule Closest_pair do + def bruteForce([p0,p1|_] = points) do + pnts = List.to_tuple(points) + minDist = distance(p0, p1) + n = tuple_size(pnts) + {minDistance, minPoints} = Enum.reduce(0..n-2, {minDist, [0,1]}, fn i,{mD,mP} -> + Enum.reduce(i+1..n-1, {mD,mP}, fn j,{md,mp} -> + dist = distance(elem(pnts,i), elem(pnts,j)) + if dist < md, do: {dist, [i,j]}, else: {md,mp} + end) + end) + {:math.sqrt(minDistance), minPoints} + end + + defp distance({p0x,p0y}, {p1x,p1y}) do + (p1x - p0x) * (p1x - p0x) + (p1y - p0y) * (p1y - p0y) + end +end + +data = [{0.654682, 0.925557}, {0.409382, 0.619391}, {0.891663, 0.888594}, {0.716629, 0.996200}, + {0.477721, 0.946355}, {0.925092, 0.818220}, {0.624291, 0.142924}, {0.211332, 0.221507}, + {0.293786, 0.691701}, {0.839186, 0.728260}] + +IO.inspect Closest_pair.bruteForce(data) diff --git a/Task/Closest-pair-problem/JavaScript/closest-pair-problem.js b/Task/Closest-pair-problem/JavaScript/closest-pair-problem-1.js similarity index 100% rename from Task/Closest-pair-problem/JavaScript/closest-pair-problem.js rename to Task/Closest-pair-problem/JavaScript/closest-pair-problem-1.js diff --git a/Task/Closest-pair-problem/JavaScript/closest-pair-problem-2.js b/Task/Closest-pair-problem/JavaScript/closest-pair-problem-2.js new file mode 100644 index 0000000000..a5ff7541b7 --- /dev/null +++ b/Task/Closest-pair-problem/JavaScript/closest-pair-problem-2.js @@ -0,0 +1,131 @@ +var Point = function(x, y) { + this.x = x; + this.y = y; +}; +Point.prototype.getX = function() { + return this.x; +}; +Point.prototype.getY = function() { + return this.y; +}; + +var mergeSort = function mergeSort(points, comp) { + if(points.length < 2) return points; + + + var n = points.length, + i = 0, + j = 0, + leftN = Math.floor(n / 2), + rightN = leftN; + + + var leftPart = mergeSort( points.slice(0, leftN), comp), + rightPart = mergeSort( points.slice(rightN), comp ); + + var sortedPart = []; + + while((i < leftPart.length) && (j < rightPart.length)) { + if(comp(leftPart[i], rightPart[j]) < 0) { + sortedPart.push(leftPart[i]); + i += 1; + } + else { + sortedPart.push(rightPart[j]); + j += 1; + } + } + while(i < leftPart.length) { + sortedPart.push(leftPart[i]); + i += 1; + } + while(j < rightPart.length) { + sortedPart.push(rightPart[j]); + j += 1; + } + return sortedPart; +}; + +var closestPair = function _closestPair(Px, Py) { + if(Px.length < 2) return { distance: Infinity, pair: [ new Point(0, 0), new Point(0, 0) ] }; + if(Px.length < 3) { + //find euclid distance + var d = Math.sqrt( Math.pow(Math.abs(Px[1].x - Px[0].x), 2) + Math.pow(Math.abs(Px[1].y - Px[0].y), 2) ); + return { + distance: d, + pair: [ Px[0], Px[1] ] + }; + } + + var n = Px.length, + leftN = Math.floor(n / 2), + rightN = leftN; + + var Xl = Px.slice(0, leftN), + Xr = Px.slice(rightN), + Xm = Xl[leftN - 1], + Yl = [], + Yr = []; + //separate Py + for(var i = 0; i < Py.length; i += 1) { + if(Py[i].x <= Xm.x) + Yl.push(Py[i]); + else + Yr.push(Py[i]); + } + + var dLeft = _closestPair(Xl, Yl), + dRight = _closestPair(Xr, Yr); + + var minDelta = dLeft.distance, + closestPair = dLeft.pair; + if(dLeft.distance > dRight.distance) { + minDelta = dRight.distance; + closestPair = dRight.pair; + } + + + //filter points around Xm within delta (minDelta) + var closeY = []; + for(i = 0; i < Py.length; i += 1) { + if(Math.abs(Py[i].x - Xm.x) < minDelta) closeY.push(Py[i].x); + } + //find min within delta. 8 steps max + for(i = 0; i < closeY.length; i += 1) { + for(var j = i + 1; j < Math.min( (i + 8), closeY.length ); j += 1) { + var d = Math.sqrt( Math.pow(Math.abs(closeY[j].x - closeY[i].x), 2) + Math.pow(Math.abs(closeY[j].y - closeY[i].y), 2) ); + if(d < minDelta) { + minDelta = d; + closestPair = [ closeY[i], closeY[j] ] + } + } + } + + return { + distance: minDelta, + pair: closestPair + }; +}; + + +var points = [ + new Point(0.748501, 4.09624), + new Point(3.00302, 5.26164), + new Point(3.61878, 9.52232), + new Point(7.46911, 4.71611), + new Point(5.7819, 2.69367), + new Point(2.34709, 8.74782), + new Point(2.87169, 5.97774), + new Point(6.33101, 0.463131), + new Point(7.46489, 4.6268), + new Point(1.45428, 0.087596) +]; + +var Px = mergeSort(points, function(a, b) { + return (a.x < b.x)? -1 : ( (a.x > b.x)? 1 : 0 ); +}); +var Py = mergeSort(points, function(a, b) { + return (a.y < b.y)? -1 : ( (a.y > b.y)? 1 : 0 ); +}); + +console.log( closestPair(Px, Py) ); diff --git a/Task/Closest-pair-problem/Perl-6/closest-pair-problem.pl6 b/Task/Closest-pair-problem/Perl-6/closest-pair-problem.pl6 index b87c283417..db1eb030a2 100644 --- a/Task/Closest-pair-problem/Perl-6/closest-pair-problem.pl6 +++ b/Task/Closest-pair-problem/Perl-6/closest-pair-problem.pl6 @@ -15,7 +15,7 @@ sub dist-squared($a,$b) { sub closest_pair_simple(@arr is copy) { return Inf if @arr < 2; - my ($a, $b, $d) = @arr[0,1], dist-squared(|@arr[0,1]); + my ($a, $b, $d) = flat @arr[0,1], dist-squared(|@arr[0,1]); while @arr { my $p = pop @arr; for @arr -> $l { diff --git a/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx b/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx index 72295d045e..f5114b9de1 100644 --- a/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx +++ b/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx @@ -1,32 +1,33 @@ -/*REXX program solves the closest pair of points problem in 2 dimensions*/ -parse arg N low high seed . /*get optional arguments from CL.*/ -if N=='' | N==',' then N=100 /*N not specified? Use default.*/ +/*REXX program solves the closest pair of points problem in two dimensions. */ +parse arg N low high seed . /*obtain optional arguments from the CL*/ +if N=='' | N==',' then N=100 /*N not specified? Then use default.*/ if low=='' | low==',' then low=0 if high=='' | high==',' then high=20000 -if seed\==''& seed\==',' then call random ,,seed /*seed for repeatable.*/ +if seed\==''& seed\==',' then call random ,,seed /*seed for RANDOM repeatable*/ w=length(high); w=w + (w//2==0) - /*╔══════════════════════╗*/ do j=1 for N /*gen N random pts.*/ - /*║ generate N points. ║*/ @x.j=random(low,high) /*random X.*/ - /*╚══════════════════════╝*/ @y.j=random(low,high) /* " Y.*/ + /*╔══════════════════════╗*/ do j=1 for N /*generate N random points. */ + /*║ generate N points. ║*/ @x.j=random(low,high) /*a random X. */ + /*╚══════════════════════╝*/ @y.j=random(low,high) /*" " Y. */ end /*j*/ A=1; B=2 -minDD=(@x.A-@x.B)**2 + (@y.A-@y.B)**2 /*distance between 1st two points*/ +minDD=(@x.A-@x.B)**2 + (@y.A-@y.B)**2 /*distance between first two points. */ - do j=1 for N-1 /*find min distance between a ···*/ - do k=j+1 to N /*point and all the other points.*/ + do j=1 for N-1 /*find minimum distance between a ··· */ + do k=j+1 to N /* ··· point and all the other points.*/ dd=(@x.j - @x.k)**2 + (@y.j - @y.k)**2 if dd\=0 then if dd9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end -numeric digits d; return g/1 +say _ center("x",w,'═')" " center('y',w,"═") ' is: ' sqrt(abs(minDD)) +say left('', length(_)-1) '['right(@x.A, w)"," right(@y.A, w)"]" +say left('', length(_)-1) '['right(@x.B, w)"," right(@y.B, w)"]" +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Closures-Value-capture/Delphi/closures-value-capture.delphi b/Task/Closures-Value-capture/Delphi/closures-value-capture.delphi index 6dad738f4f..594177ec1d 100644 --- a/Task/Closures-Value-capture/Delphi/closures-value-capture.delphi +++ b/Task/Closures-Value-capture/Delphi/closures-value-capture.delphi @@ -1,19 +1,27 @@ program Project1; type - TFuncIntResult = reference to function : integer; + TFuncIntResult = reference to function: Integer; -var - Funcs : array [0..9] of TFuncIntResult; - i : integer; +// use function that returns anonymous method to avoid capturing the loop variable +function CreateFunc(i: Integer): TFuncIntResult; +begin + Result := + function: Integer + begin + Result := i * i; + end; +end; +var + Funcs: array[0..9] of TFuncIntResult; + i: integer; begin - // Create 10 anonymous functions + // create 10 anonymous functions for i := Low(Funcs) to High(Funcs) do - Funcs[i] := function() : integer begin Result := i*i; end; + Funcs[i] := CreateFunc(i); // call all 10 functions for i := Low(Funcs) to High(Funcs) do - writeln( Funcs[i]() ); - + Writeln(Funcs[i]()); end. diff --git a/Task/Closures-Value-capture/Racket/closures-value-capture-1.rkt b/Task/Closures-Value-capture/Racket/closures-value-capture-1.rkt index 90874c61ba..456484ab55 100644 --- a/Task/Closures-Value-capture/Racket/closures-value-capture-1.rkt +++ b/Task/Closures-Value-capture/Racket/closures-value-capture-1.rkt @@ -1,3 +1,3 @@ #lang racket -(map (λ(f) (f)) - (for/list ([i 10]) (λ () (* i i)))) +(define functions (for/list ([i 10]) (λ() (* i i)))) +(map (λ(f) (f)) functions) diff --git a/Task/Closures-Value-capture/Rust/closures-value-capture.rust b/Task/Closures-Value-capture/Rust/closures-value-capture.rust index ef171bd5d6..4dfd3acf78 100644 --- a/Task/Closures-Value-capture/Rust/closures-value-capture.rust +++ b/Task/Closures-Value-capture/Rust/closures-value-capture.rust @@ -1,4 +1,4 @@ fn main() { - let fs: ~[proc() -> uint] = range(0u,10).map(|i| {proc() i*i}).collect(); - println!("7th val: {}", fs[7]()); + let fs: Vec<_> = (0..10).map(|i| {move || i*i} ).collect(); + println!("7th val: {}", fs[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 index 7b183257b5..d1f0faf220 100644 --- a/Task/Closures-Value-capture/Scheme/closures-value-capture-1.ss +++ b/Task/Closures-Value-capture/Scheme/closures-value-capture-1.ss @@ -4,7 +4,7 @@ (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 '())) +(define list-of-functions (build-list-of-functions 10 1 '())) (map (lambda (f) (f)) list-of-functions) diff --git a/Task/Closures-Value-capture/Scheme/closures-value-capture-2.ss b/Task/Closures-Value-capture/Scheme/closures-value-capture-2.ss index 1e275f67a9..d41b750074 100644 --- a/Task/Closures-Value-capture/Scheme/closures-value-capture-2.ss +++ b/Task/Closures-Value-capture/Scheme/closures-value-capture-2.ss @@ -1,2 +1,2 @@ -(1 4 9 16 25 36 49 64 81 100) +'(1 4 9 16 25 36 49 64 81) 81 diff --git a/Task/Closures-Value-capture/Scheme/closures-value-capture-3.ss b/Task/Closures-Value-capture/Scheme/closures-value-capture-3.ss new file mode 100644 index 0000000000..a8517e1afa --- /dev/null +++ b/Task/Closures-Value-capture/Scheme/closures-value-capture-3.ss @@ -0,0 +1,6 @@ +(define list-of-functions (map (lambda (x) (lambda () (* x x))) (iota 0 1 10))) + +; print the result +(display + (map (lambda (n) (n)) list-of-functions) +(newline) diff --git a/Task/Collections/ABAP/collections.abap b/Task/Collections/ABAP/collections.abap new file mode 100644 index 0000000000..bef974eeaa --- /dev/null +++ b/Task/Collections/ABAP/collections.abap @@ -0,0 +1,18 @@ +REPORT z_test_rosetta_collection. + +CLASS lcl_collection DEFINITION CREATE PUBLIC. + + PUBLIC SECTION. + METHODS: start. +ENDCLASS. + +CLASS lcl_collection IMPLEMENTATION. + METHOD start. + DATA(itab) = VALUE int4_table( ( 1 ) ( 2 ) ( 3 ) ). + + cl_demo_output=>display( itab ). + ENDMETHOD. +ENDCLASS. + +START-OF-SELECTION. + NEW lcl_collection( )->start( ). diff --git a/Task/Collections/JavaScript/collections-1.js b/Task/Collections/JavaScript/collections-1.js index 9b6f1dfb34..086362a6bb 100644 --- a/Task/Collections/JavaScript/collections-1.js +++ b/Task/Collections/JavaScript/collections-1.js @@ -2,4 +2,4 @@ var array = []; array.push('abc'); array.push(123); array.push(new MyClass); -alert( array[2] ); +console.log( array[2] ); diff --git a/Task/Collections/JavaScript/collections-2.js b/Task/Collections/JavaScript/collections-2.js index b44f8a4b2d..bbe7f21b40 100644 --- a/Task/Collections/JavaScript/collections-2.js +++ b/Task/Collections/JavaScript/collections-2.js @@ -1,5 +1,5 @@ -var map = {}; -map['foo'] = 'xyz'; //equivalent to: map.foo = 'xyz'; -map['bar'] = new MyClass; //equivalent to: map.bar = new MyClass; -map['1x; ~~:-b'] = 'text'; //no equivalent -alert( map['1x; ~~:-b'] ); +var obj = {}; +obj['foo'] = 'xyz'; //equivalent to: obj.foo = 'xyz'; +obj['bar'] = new MyClass; //equivalent to: obj.bar = new MyClass; +obj['1x; ~~:-b'] = 'text'; //no equivalent +console.log(obj['1x; ~~:-b']); diff --git a/Task/Collections/PARI-GP/collections-1.pari b/Task/Collections/PARI-GP/collections-1.pari index 9f466035e7..e2a6777891 100644 --- a/Task/Collections/PARI-GP/collections-1.pari +++ b/Task/Collections/PARI-GP/collections-1.pari @@ -6,3 +6,4 @@ m = matrix(1,1); s = Set(v); l = List(v); vs = vectorsmall(0); +M = Map() diff --git a/Task/Collections/PARI-GP/collections-2.pari b/Task/Collections/PARI-GP/collections-2.pari index 5d446db9c1..467e117789 100644 --- a/Task/Collections/PARI-GP/collections-2.pari +++ b/Task/Collections/PARI-GP/collections-2.pari @@ -1,3 +1,4 @@ listput(l, "hello world") v=concat(v, [1,2,3]); v=concat(v, 4); +mapput(M, "key", "value"); diff --git a/Task/Collections/Perl-6/collections-1.pl6 b/Task/Collections/Perl-6/collections-1.pl6 index 1a82f22906..c10d850614 100644 --- a/Task/Collections/Perl-6/collections-1.pl6 +++ b/Task/Collections/Perl-6/collections-1.pl6 @@ -3,14 +3,14 @@ my @array = 1,2,3; @array.push: 4,5,6; # Hash -my %hash = a => 1, b => 2; +my %hash = 'a' => 1, 'b' => 2; %hash = 3,4; -%hash.push: e => 5, f => 6; +%hash.push: 'e' => 5, 'f' => 6; -# KeySet -my $s = KeySet.new: ; +# SetHash +my $s = SetHash.new: ; $s ∪= ; -# KeyBag -my $b = KeyBag.new: ; -$b.push: ; +# BagHash +my $b = BagHash.new: ; +$b ⊎= ; diff --git a/Task/Collections/Perl-6/collections-2.pl6 b/Task/Collections/Perl-6/collections-2.pl6 index 2e78e92ec9..36a71e40d1 100644 --- a/Task/Collections/Perl-6/collections-2.pl6 +++ b/Task/Collections/Perl-6/collections-2.pl6 @@ -8,4 +8,4 @@ my $newset = $set ∪ ; # Bag my $bag = bag ; -my $newbag = $bag ∪ ; +my $newbag = $bag ⊎ ; diff --git a/Task/Color-of-a-screen-pixel/Kotlin/color-of-a-screen-pixel.kotlin b/Task/Color-of-a-screen-pixel/Kotlin/color-of-a-screen-pixel.kotlin new file mode 100644 index 0000000000..bb2c27b458 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Kotlin/color-of-a-screen-pixel.kotlin @@ -0,0 +1,12 @@ +import java.awt.Color +import java.awt.MouseInfo +import java.awt.Robot + +fun getMouseColor(): Color { + val location = MouseInfo.getPointerInfo().getLocation() + return getColorAt(location.x, location.y) +} + +fun getColorAt(x: Int, y: Int): Color { + return Robot().getPixelColor(x, y) +} diff --git a/Task/Colour-bars-Display/Befunge/colour-bars-display.bf b/Task/Colour-bars-Display/Befunge/colour-bars-display.bf new file mode 100644 index 0000000000..dc8f0a7dac --- /dev/null +++ b/Task/Colour-bars-Display/Befunge/colour-bars-display.bf @@ -0,0 +1,6 @@ +$:55+%#v_:1-"P"%55+/3g^ +39*,,,~@>48*,1-:#v_$"m[" diff --git a/Task/Colour-bars-Display/PHP/colour-bars-display-1.php b/Task/Colour-bars-Display/PHP/colour-bars-display-1.php index c21aa2e734..427057a5c0 100644 --- a/Task/Colour-bars-Display/PHP/colour-bars-display-1.php +++ b/Task/Colour-bars-Display/PHP/colour-bars-display-1.php @@ -1,12 +1,12 @@ {408, 408}] diff --git a/Task/Combinations-and-permutations/Erlang/combinations-and-permutations.erl b/Task/Combinations-and-permutations/Erlang/combinations-and-permutations.erl new file mode 100644 index 0000000000..13775a10b0 --- /dev/null +++ b/Task/Combinations-and-permutations/Erlang/combinations-and-permutations.erl @@ -0,0 +1,44 @@ + %% @author Salvador Tamarit + +-module(combinations_permutations). + +-export([test/0]). + +perm(N, K) -> + product(lists:seq(N - K + 1, N)). + +comb(N, K) -> + perm(N, K) div product(lists:seq(1, K)). + +product(List) -> + lists:foldl(fun(N, Acc) -> N * Acc end, 1, List). + +test() -> + io:format("\nA sample of permutations from 1 to 12:\n"), + [show_perm({N, N div 3}) || N <- lists:seq(1, 12)], + io:format("\nA sample of combinations from 10 to 60:\n"), + [show_comb({N, N div 3}) || N <- lists:seq(10, 60, 10)], + io:format("\nA sample of permutations from 5 to 15000:\n"), + [show_perm({N, N div 3}) || N <- [5,50,500,1000,5000,15000]], + io:format("\nA sample of combinations from 100 to 1000:\n"), + [show_comb({N, N div 3}) || N <- lists:seq(100, 1000, 100)], + ok. + +show_perm({N, K}) -> + show_gen(N, K, "perm", fun perm/2). + +show_comb({N, K}) -> + show_gen(N, K, "comb", fun comb/2). + +show_gen(N, K, StrFun, Fun) -> + io:format("~s(~p, ~p) = ~s\n",[StrFun, N, K, show_big(Fun(N, K), 40)]). + +show_big(N, Limit) -> + StrN = integer_to_list(N), + case length(StrN) < Limit of + true -> + StrN; + false -> + {Shown, Hidden} = lists:split(Limit, StrN), + io_lib:format("~s... (~p more digits)", [Shown, length(Hidden)]) + end. diff --git a/Task/Combinations-and-permutations/Haskell/combinations-and-permutations.hs b/Task/Combinations-and-permutations/Haskell/combinations-and-permutations.hs new file mode 100644 index 0000000000..b0038fceb7 --- /dev/null +++ b/Task/Combinations-and-permutations/Haskell/combinations-and-permutations.hs @@ -0,0 +1,37 @@ +perm :: Integer -> Integer -> Integer +perm n k = product [n-k+1..n] + +comb :: Integer -> Integer -> Integer +comb n k = perm n k `div` product [1..k] + +main :: IO () +main = do + let showBig maxlen b = + let st = show b + stlen = length st + in if stlen < maxlen then st else take maxlen st ++ "... (" ++ show (stlen-maxlen) ++ " more digits)" + + let showPerm pr = + putStrLn $ "perm(" ++ show n ++ "," ++ show k ++ ") = " ++ showBig 40 (perm n k) + where n = fst pr + k = snd pr + + let showComb pr = + putStrLn $ "comb(" ++ show n ++ "," ++ show k ++ ") = " ++ showBig 40 (comb n k) + where n = fst pr + k = snd pr + + putStrLn "A sample of permutations from 1 to 12:" + mapM_ showPerm [(n, n `div` 3) | n <- [1..12] ] + + putStrLn "" + putStrLn "A sample of combinations from 10 to 60:" + mapM_ showComb [(n, n `div` 3) | n <- [10,20..60] ] + + putStrLn "" + putStrLn "A sample of permutations from 5 to 15000:" + mapM_ showPerm [(n, n `div` 3) | n <- [5,50,500,1000,5000,15000] ] + + putStrLn "" + putStrLn "A sample of combinations from 100 to 1000:" + mapM_ showComb [(n, n `div` 3) | n <- [100,200..1000] ] diff --git a/Task/Combinations-and-permutations/J/combinations-and-permutations-1.j b/Task/Combinations-and-permutations/J/combinations-and-permutations-1.j index c6b4481312..7fdb99e17e 100644 --- a/Task/Combinations-and-permutations/J/combinations-and-permutations-1.j +++ b/Task/Combinations-and-permutations/J/combinations-and-permutations-1.j @@ -1,2 +1,2 @@ C=: ! -P=: (<: * (*/@}. 1+i.))"0 +P=: (%&!&x:~ * <:)"0 diff --git a/Task/Combinations-and-permutations/Julia/combinations-and-permutations-1.julia b/Task/Combinations-and-permutations/Julia/combinations-and-permutations-1.julia new file mode 100644 index 0000000000..7ef61366b1 --- /dev/null +++ b/Task/Combinations-and-permutations/Julia/combinations-and-permutations-1.julia @@ -0,0 +1,10 @@ +function Base.binomial{T<:FloatingPoint}(n::T, k::T) + exp(lfact(n) - lfact(n - k) - lfact(k)) +end + +function Base.factorial{T<:FloatingPoint}(n::T, k::T) + exp(lfact(n) - lfact(k)) +end + +⊞{T<:Real}(n::T, k::T) = binomial(n, k) +⊠{T<:Real}(n::T, k::T) = factorial(n, n-k) diff --git a/Task/Combinations-and-permutations/Julia/combinations-and-permutations-2.julia b/Task/Combinations-and-permutations/Julia/combinations-and-permutations-2.julia new file mode 100644 index 0000000000..eff290c5cc --- /dev/null +++ b/Task/Combinations-and-permutations/Julia/combinations-and-permutations-2.julia @@ -0,0 +1,52 @@ +function picknk{T<:Integer}(lo::T, hi::T) + n = rand(lo:hi) + k = rand(1:n) + return (n, k) +end + +nsamp = 10 + +print("Tests of the combinations (⊞) and permutations (⊠) operators for ") +println("integer values.") +println() +lo, hi = 1, 12 +print(nsamp, " samples of n ⊠ k with n in [", lo, ", ", hi, "] ") +println("and k in [1, n].") +for i in 1:nsamp + (n, k) = picknk(lo, hi) + println(@sprintf " %2d ⊠ %2d = %18d" n k n ⊠ k) +end + +lo, hi = 10, 60 +println() +print(nsamp, " samples of n ⊞ k with n in [", lo, ", ", hi, "] ") +println("and k in [1, n].") +for i in 1:nsamp + (n, k) = picknk(lo, hi) + println(@sprintf " %2d ⊞ %2d = %18d" n k n ⊞ k) +end + +println() +print("Tests of the combinations (⊞) and permutations (⊠) operators for ") +println("(big) float values.") +println() +lo, hi = 5, 15000 +print(nsamp, " samples of n ⊠ k with n in [", lo, ", ", hi, "] ") +println("and k in [1, n].") +for i in 1:nsamp + (n, k) = picknk(lo, hi) + n = BigFloat(n) + k = BigFloat(k) + println(@sprintf " %7.1f ⊠ %7.1f = %10.6e" n k n ⊠ k) +end + +lo, hi = 100, 1000 +println() +print(nsamp, " samples of n ⊞ k with n in [", lo, ", ", hi, "] ") +println("and k in [1, n].") +for i in 1:nsamp + (n, k) = picknk(lo, hi) + n = BigFloat(n) + k = BigFloat(k) + println(@sprintf " %7.1f ⊞ %7.1f = %10.6e" n k n ⊞ k) +end diff --git a/Task/Combinations-and-permutations/Perl-6/combinations-and-permutations.pl6 b/Task/Combinations-and-permutations/Perl-6/combinations-and-permutations.pl6 index 6b0e49fe9e..48778067e3 100644 --- a/Task/Combinations-and-permutations/Perl-6/combinations-and-permutations.pl6 +++ b/Task/Combinations-and-permutations/Perl-6/combinations-and-permutations.pl6 @@ -32,7 +32,7 @@ for 10, 20 ... 60 -> $n { say "C($n, $p) = ", C($n, $p); } -say; +say ''; say "Floating point approximations:"; for 5, 50, 500, 1000, 5000, 15000 -> $n { my $p = $n div 3; diff --git a/Task/Combinations-and-permutations/REXX/combinations-and-permutations.rexx b/Task/Combinations-and-permutations/REXX/combinations-and-permutations.rexx index 4c74d830af..6a76dc4bcd 100644 --- a/Task/Combinations-and-permutations/REXX/combinations-and-permutations.rexx +++ b/Task/Combinations-and-permutations/REXX/combinations-and-permutations.rexx @@ -1,46 +1,44 @@ -/*REXX program to compute a sampling of combinations and permutations. */ -numeric digits 100 /*use hundred digits of precision*/ +/*REXX program to compute and show a sampling of combinations and permutations*/ +numeric digits 100 /*use 100 decimal 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*/ + do j=1 for 12 /*show all permutations from 1 ──► 12.*/ + _=; do k=1 for j /*step through all J permutations. */ + _=_ 'P('j","k')='perm(j,k)" " /*add an extra blank between numbers. */ + end /*k*/ + say strip(_) /*show the permutations horizontally. */ 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. */ + 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 numbers. */ end /*k*/ - say strip(_) /*show a horizontal line of COMBs*/ + say strip(_) /*show the combinations horizontally. */ end /*j*/ say -numeric digits 20 /*force floating point for big #s*/ +numeric digits 20 /*force floating point for big numbers.*/ - 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*/ + do j=5 to 15000 by 1000 /*show a few permutations, big numbers.*/ + _=; do k=1 to j for 5 by j%10 /*step through some J permutations. */ + _=_ 'P('j","k')='perm(j,k)" " /*add an extra blank between numbers. */ + end /*k*/ + say strip(_) /*show the permutations horizontally. */ 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*/ + do j=100 to 1000 by 100 /*show a few combinations, big numbers.*/ + _=; do k= 1 to j by j%5 /*step through some combinations. */ + _=_ 'C('j","k')='comb(j,k)" " /*add an extra blank between numbers. */ + end /*k*/ + say strip(_) /*show the combinations horizontally. */ 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-yx then return 0 /*oops-say, too big a chunk. */ +if x=y then return 1 /*X things are the same as chunk size.*/ +if x-y IO.inspect x end) + +IO.puts "\nExtra credit: #{length(RC.comb_rep(3, Enum.to_list(1..10)))}" diff --git a/Task/Combinations-with-repetitions/J/combinations-with-repetitions-2.j b/Task/Combinations-with-repetitions/J/combinations-with-repetitions-2.j index 73927e7224..09a41720f0 100644 --- a/Task/Combinations-with-repetitions/J/combinations-with-repetitions-2.j +++ b/Task/Combinations-with-repetitions/J/combinations-with-repetitions-2.j @@ -12,5 +12,5 @@ ├─────┼─────┤ │plain│plain│ └─────┴─────┘ - #3 rcomb i.10 NB. ways to choose 3 items from 10 with replacement + #3 rcomb i.10 NB. ways to choose 3 items from 10 with repetitions 220 diff --git a/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions.rexx b/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions.rexx index b43e62ed79..162891ee9f 100644 --- a/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions.rexx +++ b/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions.rexx @@ -1,29 +1,23 @@ -/*REXX program shows combination sets for X things taken Y at a time*/ -parse arg x y symbols x2 y2 symbols2 . /*get optional arguments from CL.*/ -if x=='' | x==',' then x= 3 /*X not specified? Use default.*/ -if y=='' | y==',' then y= 2 /*Y " " " " */ -if x2=='' | x2==',' then x2=-10 /*X2 " " " " */ -if y2=='' | y2==',' then y2= 3 /*Y2 " " " " */ -if symbols =='' then symbols ='iced jam plain' /*symbol table words.*/ -if symbols2=='' then symbols2=symbols /*symbol2 " " */ -call RcombN x, y, symbols /*1st part of Rosetta Code task. */ -call RcombN x2, y2, symbols2 /*2nd " " " " " */ -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────RCOMBN subroutine────────────────*/ -RcombN: procedure; parse arg x,y,syms; tell=x>0; x=abs(x); base=x+1 -syms=translate(syms,,',') /*separate the symbols from list.*/ -say "────────────" abs(x) 'doughnut selection taken' y "at a time:" - do i=1 for words(syms); $.i=word(syms,i); end -@.=1 /* [↓] maybe show combinations.*/ - do #=1; if tell then do; L=; do d=1 for y /*a comb.*/ - _=@.d; L=L $._ - end /*d*/ ; say L - end - @.y=@.y+1; if @.y==base then if .RcombN(y-1) then leave - end /*#*/ -say "────────────" # 'combinations.'; say; say; say -return # -.RcombN: procedure expose @. y base; parse arg d; if d==0 then return 1 -p=@.d+1; if p==base then return .RcombN(d-1); do u=d to y; @.u=p - end /*u*/ -return 0 +/*REXX program displays combination sets for X things taken Y at a time.*/ +call RcombN 3, 2, 'iced,jam,plain' /*The 1st part of Rosetta Code task. */ +call RcombN -10, 3, 'Iced,jam,plain' /* " 2nd " " " " " */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +RcombN: procedure; parse arg x,y,syms; tell=x>0; x=abs(x); z=x+1 +syms=translate(syms,,',') /*separate symbols*/ +say "────────────" x 'doughnut selection taken' y "at a time:" + + do i=1 for words(syms); $.i=word(syms,i) /*assign symbols. */ + end /*i*/ +@.=1 /*assign @ default*/ + do #=1; if tell then call show /*display combos? */ + @.y=@.y+1; if @.y==z then if .(y-1) then leave /* ◄─── recursive.*/ + end /*#*/ + +say "────────────" # 'combinations.'; say; say; say +return +/*────────────────────────────────────────────────────────────────────────────*/ +.: procedure expose @. y z; parse arg ?; if ?==0 then return 1; p=@.?+1 + if p==z then return .(?-1); do i=? to y; @.i=p; end; return 0 +/*────────────────────────────────────────────────────────────────────────────*/ +show: L=; do c=1 for y; _=@.c; L=L $._; end; say L; return diff --git a/Task/Combinations-with-repetitions/TXR/combinations-with-repetitions-1.txr b/Task/Combinations-with-repetitions/TXR/combinations-with-repetitions-1.txr new file mode 100644 index 0000000000..b207144daf --- /dev/null +++ b/Task/Combinations-with-repetitions/TXR/combinations-with-repetitions-1.txr @@ -0,0 +1 @@ +txr -p "(rcomb '(iced jam plain) 2)" diff --git a/Task/Combinations-with-repetitions/TXR/combinations-with-repetitions-2.txr b/Task/Combinations-with-repetitions/TXR/combinations-with-repetitions-2.txr new file mode 100644 index 0000000000..2349474af6 --- /dev/null +++ b/Task/Combinations-with-repetitions/TXR/combinations-with-repetitions-2.txr @@ -0,0 +1 @@ +txr -p "(length-list (rcomb '(0 1 2 3 4 5 6 7 8 9) 3))" diff --git a/Task/Combinations/Clojure/combinations.clj b/Task/Combinations/Clojure/combinations-1.clj similarity index 100% rename from Task/Combinations/Clojure/combinations.clj rename to Task/Combinations/Clojure/combinations-1.clj diff --git a/Task/Combinations/Clojure/combinations-2.clj b/Task/Combinations/Clojure/combinations-2.clj new file mode 100644 index 0000000000..5869a89775 --- /dev/null +++ b/Task/Combinations/Clojure/combinations-2.clj @@ -0,0 +1,11 @@ +(defn combinations + "Generate the combinations of n elements from a list of [0..m)" + [m n] + (let [xs (range m)] + (loop [i (int 0) res #{#{}}] + (if (== i n) + res + (recur (+ 1 i) + (set (for [x xs r res + :when (not-any? #{x} r)] + (conj r x)))))))) diff --git a/Task/Combinations/Eiffel/combinations-1.e b/Task/Combinations/Eiffel/combinations-1.e index 652e772e5e..a34966eef4 100644 --- a/Task/Combinations/Eiffel/combinations-1.e +++ b/Task/Combinations/Eiffel/combinations-1.e @@ -1,71 +1,88 @@ class COMBINATIONS + create make + feature - make(n, k:INTEGER) + + make (n, k: INTEGER) require - n_positive: n>0 - k_positive: k>0 - k_smaller_equal: k<=n + n_positive: n > 0 + k_positive: k > 0 + k_smaller_equal: k <= n do create set.make set.extend ("") create sol.make - sol:=solve(set,k,n-k) - sol:= conv_sol(n, sol) + sol := solve (set, k, n - k) + sol := convert_solution (n, sol) ensure - correct_num_of_sol: num_of_comb(n,k)= sol.count + correct_num_of_sol: num_of_comb (n, k) = sol.count end - set: LINKED_LIST[STRING] - sol: LINKED_LIST[STRING] - conv_sol(n: INTEGER; solution: LINKED_LIST[STRING]):LINKED_LIST[STRING] - local - i,j: INTEGER - temp: STRING - do - create temp.make (n) - from - i:=1 - until - i>solution.count - loop + sol: LINKED_LIST [STRING] + +feature {None} + + set: LINKED_LIST [STRING] + + convert_solution (n: INTEGER; solution: LINKED_LIST [STRING]): LINKED_LIST [STRING] + -- strings of 'k' digits between 1 and 'n' + local + i, j: INTEGER + temp: STRING + do + create temp.make (n) from - j:= 1 + i := 1 until - j> n + i > solution.count loop - if solution[i].at (j)= '1' then - temp.append (j.out) + from + j := 1 + until + j > n + loop + if solution [i].at (j) = '1' then + temp.append (j.out) + end + j := j + 1 end - j:= j+1 + solution [i].deep_copy (temp) + temp.wipe_out + i := i + 1 end - solution[i].deep_copy( temp) - temp.wipe_out - i:= i+1 + Result := solution end - Result:= solution - end - solve(seta: LINKED_LIST[STRING];one,zero: INTEGER): LINKED_LIST[STRING] + solve (seta: LINKED_LIST [STRING]; one, zero: INTEGER): LINKED_LIST [STRING] + -- list of strings with a number of 'one' 1s and 'zero' 0, standig for wether the corresponing digit is taken or not. local - new_P1, new_P0: LINKED_LIST[STRING] + new_P1, new_P0: LINKED_LIST [STRING] do create new_P1.make create new_P0.make - if one > 0 then - new_P1.deep_copy(seta) - across new_P1 as P1 loop new_P1.item.append ("1") end - new_P1:=solve(new_P1, one-1, zero) - end + if one > 0 then + new_P1.deep_copy (seta) + across + new_P1 as P1 + loop + new_P1.item.append ("1") + end + new_P1 := solve (new_P1, one - 1, zero) + end if zero > 0 then - new_P0.deep_copy(seta) - across new_P0 as P0 loop new_P0.item.append ("0") end - new_P0:=solve(new_P0, one, zero-1) + new_P0.deep_copy (seta) + across + new_P0 as P0 + loop + new_P0.item.append ("0") + end + new_P0 := solve (new_P0, one, zero - 1) end - if one=0 and zero= 0 then - Result:= seta + if one = 0 and zero = 0 then + Result := seta else create Result.make Result.fill (new_p0) @@ -73,24 +90,25 @@ feature end end - num_of_comb (n,k:INTEGER):INTEGER - --- used for contracts + num_of_comb (n, k: INTEGER): INTEGER + -- number of 'k' sized combinations out of 'n'. local upper, lower, m, l: INTEGER do - upper:= 1 - lower:= 1 - m:= n - l:= k + upper := 1 + lower := 1 + m := n + l := k from until - m IO.inspect x end) diff --git a/Task/Combinations/J/combinations-1.j b/Task/Combinations/J/combinations-1.j index cf86f6b0c2..585f21feb0 100644 --- a/Task/Combinations/J/combinations-1.j +++ b/Task/Combinations/J/combinations-1.j @@ -1,5 +1 @@ -comb1=: dyad define - c=. 1 {.~ - d=. 1+y-x - z=. i.1 0 - for_j. (d-1+y)+/&i.d do. z=. (c#j) ,. z{~;(-c){.&.>:y)+.0=x do. i.(x<:y),x else. (0,.x comb&.<: y),1+x comb y-1 end. -) + 3 comb 5 +0 1 2 +0 1 3 +0 1 4 +0 2 3 +0 2 4 +0 3 4 +1 2 3 +1 2 4 +1 3 4 +2 3 4 diff --git a/Task/Combinations/J/combinations-3.j b/Task/Combinations/J/combinations-3.j index 13e4c36a64..cf86f6b0c2 100644 --- a/Task/Combinations/J/combinations-3.j +++ b/Task/Combinations/J/combinations-3.j @@ -1 +1,5 @@ -combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~) +comb1=: dyad define + c=. 1 {.~ - d=. 1+y-x + z=. i.1 0 + for_j. (d-1+y)+/&i.d do. z=. (c#j) ,. z{~;(-c){.&.>:y)+.0=x do. i.(x<:y),x else. (0,.x combr&.<: y),1+x combr y-1 end. +) diff --git a/Task/Combinations/J/combinations-5.j b/Task/Combinations/J/combinations-5.j new file mode 100644 index 0000000000..13e4c36a64 --- /dev/null +++ b/Task/Combinations/J/combinations-5.j @@ -0,0 +1 @@ +combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~) diff --git a/Task/Combinations/Python/combinations-2.py b/Task/Combinations/Python/combinations-2.py index 0a723e39a5..59a48d13b9 100644 --- a/Task/Combinations/Python/combinations-2.py +++ b/Task/Combinations/Python/combinations-2.py @@ -1,6 +1,4 @@ def comb(m, lst): - if m == 0: - return [[]] - else: - return [[x] + suffix for i, x in enumerate(lst) - for suffix in comb(m - 1, lst[i + 1:])] + if m == 0: return [[]] + return [[x] + suffix for i, x in enumerate(lst) + for suffix in comb(m - 1, lst[i + 1:])] diff --git a/Task/Combinations/VBScript/combinations.vb b/Task/Combinations/VBScript/combinations.vb new file mode 100644 index 0000000000..0c2448175d --- /dev/null +++ b/Task/Combinations/VBScript/combinations.vb @@ -0,0 +1,40 @@ +Function Dec2Bin(n) + q = n + Dec2Bin = "" + Do Until q = 0 + Dec2Bin = CStr(q Mod 2) & Dec2Bin + q = Int(q / 2) + Loop + Dec2Bin = Right("00000" & Dec2Bin,6) +End Function + +Sub Combination(n,k) + Dim arr() + ReDim arr(n-1) + For h = 0 To n-1 + arr(h) = h + 1 + Next + Set list = CreateObject("System.Collections.Arraylist") + For i = 1 To 2^n + bin = Dec2Bin(i) + c = 0 + tmp_combo = "" + If Len(Replace(bin,"0","")) = k Then + For j = Len(bin) To 1 Step -1 + If CInt(Mid(bin,j,1)) = 1 Then + tmp_combo = tmp_combo & arr(c) & "," + End If + c = c + 1 + Next + list.Add Mid(tmp_combo,1,(k*2)-1) + End If + Next + list.Sort + For l = 0 To list.Count-1 + WScript.StdOut.Write list(l) + WScript.StdOut.WriteLine + Next +End Sub + +'Testing with n = 5 / k = 3 +Call Combination(5,3) diff --git a/Task/Comma-quibbling/ALGOL-68/comma-quibbling.alg b/Task/Comma-quibbling/ALGOL-68/comma-quibbling.alg new file mode 100644 index 0000000000..f9d22ccde9 --- /dev/null +++ b/Task/Comma-quibbling/ALGOL-68/comma-quibbling.alg @@ -0,0 +1,77 @@ +# returns a string ( assumed to be of space-separated words ) with the words # +# separated by ", ", except for the last which is separated from the rest by # +# " and ". The list is enclosed by braces # +PROC to list = ( STRING words ) STRING: + BEGIN + # count the number of words # + INT word count := 0; + BOOL in word := FALSE; + FOR char pos FROM LWB words TO UPB words + DO + IF NOT is upper( words[ char pos ] ) + THEN + # not an upper-case letter, possibly a word has been ended # + in word := FALSE + ELSE + # not a delimitor, possibly the start of a word # + IF NOT in word + THEN + # we are starting a new word # + word count +:= 1; + in word := TRUE + FI + FI + OD; + + # format the result # + STRING result := "{"; + in word := FALSE; + INT word number := 0; + FOR char pos FROM LWB words TO UPB words + DO + IF NOT is upper( words[ char pos ] ) + THEN + # not an upper-case letter, possibly a word has been ended # + in word := FALSE + ELSE + # not a delimitor, possibly the start of a word # + IF NOT in word + THEN + # we are starting a new word # + word number +:= 1; + in word := TRUE; + IF word number > 1 + THEN + # second or subsequent word - need a separator # + result +:= IF word number = word count + THEN # final word # + " and " + ELSE # non-final word # + ", " + FI + FI + FI; + # add the character to the result # + result +:= words[ char pos ] + FI + OD; + + result + "}" + END # to list # ; + + + # procedure to test the to list PROC # + PROC test to list = ( STRING words ) VOID: + print( ( ( words + + ": " + + to list( words ) + ) + , newline + ) + ); + + # test the to list PROC # + test to list( "" ); + test to list( "ABC" ); + test to list( "ABC DEF" ); + test to list( "ABC DEF G H" ) diff --git a/Task/Comma-quibbling/ALGOL-W/comma-quibbling.alg b/Task/Comma-quibbling/ALGOL-W/comma-quibbling.alg new file mode 100644 index 0000000000..640a772919 --- /dev/null +++ b/Task/Comma-quibbling/ALGOL-W/comma-quibbling.alg @@ -0,0 +1,107 @@ +begin + + % returns a list of the words contained in wordString, separated by ", ", % + % except for the last which is separated from the rest by " and ". % + % The words are enclosed by braces % + string(256) procedure toList ( string(256) value words ) ; + begin + string(256) list; + integer wordCount, wordNumber, listPos; + logical inWord; + + % returns true if ch is an upper-case letter, false otherwise % + % assumes the letters are consecutive in the character set % + % (as in ascii) would not be correct if the character set was % + % ebcdic (as in the original implementations of Algol W) % + logical procedure isUpper ( string(1) value ch ) ; ch >= "A" and ch <= "Z" ; + + % adds a character to the result % + procedure addChar( string(1) value ch ) ; + begin + list( listPos // 1 ) := ch; + listPos := listPos + 1; + end addChar ; + + % adds a string to the result % + procedure addString( string(256) value str + ; integer value len + ) ; + for strPos := 0 until len - 1 do addChar( str( strPos // 1 ) ); + + % count the number of words % + + wordCount := 0; + inWord := false; + for charPos := 0 until 255 + do begin + if isUpper( words( charPos // 1 ) ) then begin + % not an upper-case letter, possibly a word has been ended % + inWord := false + end + else begin + % not a delimitor, possibly the start of a word % + if not inWord then begin + % we are starting a new word % + wordCount := wordCount + 1; + inWord := true + end if_not_inWord + end + end for_charPos; + + % format the result % + + list := ""; + listPos := 0; + inWord := false; + wordNumber := 0; + + addChar( "{" ); + + for charPos := 0 until 255 + do begin + if not isUpper( words( charPos // 1 ) ) then begin + % not an upper-case letter, possibly a word has been ended % + inWord := false + end + else begin + % not a delimitor, possibly the start of a word % + if not inWord then begin + % we are starting a new word % + wordNumber := wordNumber + 1; + inWord := true; + if wordNumber > 1 then begin + % second or subsequent word - need a separator % + if wordNumber = wordCount then addString( " and ", 5 ) % final word % + else addString( ", ", 2 ) % non-final word % + end + end; + % add the character to the result % + addChar( words( charPos // 1 ) ) + end + end for_charPos ; + + addChar( "}" ); + + list + end toList ; + + + % procedure to test the toList procedure % + procedure testToList ( string(256) value words ) ; + begin + string(256) list; + list := toList( words ); + write( s_w := 0 + , words( 0 // 32 ) + , ": " + , list( 0 // 32 ) + ) + end testToList ; + + % test the toList procedure % + testToList( "" ); + testToList( "ABC" ); + testToList( "ABC DEF" ); + testToList( "ABC DEF G H" ); + +end. diff --git a/Task/Comma-quibbling/Batch-File/comma-quibbling.bat b/Task/Comma-quibbling/Batch-File/comma-quibbling.bat new file mode 100644 index 0000000000..361c93cf74 --- /dev/null +++ b/Task/Comma-quibbling/Batch-File/comma-quibbling.bat @@ -0,0 +1,41 @@ +@echo off +setlocal enabledelayedexpansion + +::THE MAIN THING... +echo. +set inp=[] +call :quibble +set inp=["ABC"] +call :quibble +set inp=["ABC","DEF"] +call :quibble +set inp=["ABC","DEF","G","H"] +call :quibble +echo. +pause +exit /b +::/THE MAIN THING... + +::THE FUNCTION +:quibble +set cont=0 +set proc=%inp:[=% +set proc=%proc:]=% + +for %%x in (%proc%) do ( + set /a cont+=1 + set x=%%x + set str!cont!=!x:"=! +) +set /a bef=%cont%-1 +set output=%str1% +if %cont%==2 (set output=%str1% and %str2%) +if %cont% gtr 2 ( + for /l %%y in (2,1,%bef%) do ( + set output=!output!^, !str%%y! + ) + set output=!output! and !str%cont%! +) +echo {!output!} +goto :EOF +::/THE FUNCTION diff --git a/Task/Comma-quibbling/DCL/comma-quibbling.dcl b/Task/Comma-quibbling/DCL/comma-quibbling.dcl new file mode 100644 index 0000000000..e795c04f0b --- /dev/null +++ b/Task/Comma-quibbling/DCL/comma-quibbling.dcl @@ -0,0 +1,36 @@ +$ list = "[]" +$ gosub comma_quibbling +$ write sys$output return_string +$ +$ list = "[""ABC""]" +$ gosub comma_quibbling +$ write sys$output return_string +$ +$ list = "[""ABC"", ""DEF""]" +$ gosub comma_quibbling +$ write sys$output return_string +$ +$ list = "[""ABC"", ""DEF"", ""G"", ""H""]" +$ gosub comma_quibbling +$ write sys$output return_string +$ +$ exit +$ +$ comma_quibbling: +$ list = list - "[" - "]" +$ return_string = "{}" +$ if list .eqs. "" then $ return +$ return_string = "{" + f$element( 0, ",", list ) - """" - """" +$ if f$locate( ",", list ) .eq. f$length( list ) then $ goto done2 +$ i = 1 +$ loop: +$ word = f$element( i, ",", list ) - """" - """" +$ if word .eqs. "," then $ goto done1 +$ return_string = return_string - "^" + "^," + word +$ i = i + 1 +$ goto loop +$ done1: +$ return_string = f$element( 0, "^", return_string ) + " and" + ( f$element( 1, "^", return_string ) - "," ) +$ done2: +$ return_string = return_string + "}" +$ return diff --git a/Task/Comma-quibbling/Eiffel/comma-quibbling.e b/Task/Comma-quibbling/Eiffel/comma-quibbling.e new file mode 100644 index 0000000000..0f9e67e5bc --- /dev/null +++ b/Task/Comma-quibbling/Eiffel/comma-quibbling.e @@ -0,0 +1,47 @@ +class + APPLICATION + +create + make + +feature + + make + -- Test of the feature comma_quibbling. + local + l: LINKED_LIST [STRING] + do + create l.make + io.put_string (comma_quibbling (l) + "%N") + l.extend ("ABC") + io.put_string (comma_quibbling (l) + "%N") + l.extend ("DEF") + io.put_string (comma_quibbling (l) + "%N") + l.extend ("G") + l.extend ("H") + io.put_string (comma_quibbling (l) + "%N") + end + + comma_quibbling (l: LINKED_LIST [STRING]): STRING + -- Elements of 'l' seperated by a comma or an and where appropriate. + require + l_not_void: l /= Void + do + create Result.make_empty + Result.extend ('{') + if l.is_empty then + Result.append ("}") + elseif l.count = 1 then + Result.append (l [1] + "}") + else + Result.append (l [1]) + across + 2 |..| (l.count - 1) as c + loop + Result.append (", " + l [c.item]) + end + Result.append (" and " + l [l.count] + "}") + end + end + +end diff --git a/Task/Comma-quibbling/Elixir/comma-quibbling.elixir b/Task/Comma-quibbling/Elixir/comma-quibbling.elixir new file mode 100644 index 0000000000..f6f921a4d0 --- /dev/null +++ b/Task/Comma-quibbling/Elixir/comma-quibbling.elixir @@ -0,0 +1,16 @@ +defmodule RC do + def generate( list ), do: "{#{ generate_content(list) }}" + + defp generate_content( [] ), do: "" + defp generate_content( [x] ), do: x + defp generate_content( [x1, x2] ), do: "#{x1} and #{x2}" + defp generate_content( xs ) do + [last, second_to_last | t] = Enum.reverse( xs ) + with_commas = for x <- t, do: x <> "," + Enum.join(Enum.reverse([last, "and", second_to_last | with_commas]), " ") + end +end + +Enum.each([[], ["ABC"], ["ABC", "DEF"], ["ABC", "DEF", "G", "H"]], fn list -> + IO.inspect RC.generate(list) +end) diff --git a/Task/Comma-quibbling/Liberty-BASIC/comma-quibbling.liberty b/Task/Comma-quibbling/Liberty-BASIC/comma-quibbling.liberty new file mode 100644 index 0000000000..1e1127f2dc --- /dev/null +++ b/Task/Comma-quibbling/Liberty-BASIC/comma-quibbling.liberty @@ -0,0 +1,44 @@ +do + read in$ + if in$ ="END" then wait + w =wordCount( in$) + select case w + case 0 + o$ ="{}" + case 1 + o$ ="{" +in$ +"}" + case 2 + o$ ="{" +word$( in$, 1) +" and " +word$( in$, 2) +"}" + case else + o$ ="{" + o$ =o$ +word$( in$, 1) + for k =2 to w -1 + o$ =o$ +", " +word$( in$, k) + next k + o$ =o$ +" and " +word$( in$, w) +"}" + end select + if w =1 then + print "'"; in$; "'"; " held "; w; " word. "; tab( 30); o$ + else + print "'"; in$; "'"; " held "; w; " words. "; tab( 30); o$ + end if + loop until 0 + + wait + + function wordCount( IN$) + wordCount =1 + for i =1 to len( IN$) + if mid$( IN$, i, 1) =" " then wordCount =wordCount +1 + next i + end function + + end + + data "" 'No input words. + data "ABC" 'One input word. + data "ABC DEF" 'Two words. + data "ABC DEF G" 'Three words. + data "ABC DEF G H" 'Four words. + + data "END" 'Sentinel for EOD. diff --git a/Task/Comma-quibbling/VBScript/comma-quibbling.vb b/Task/Comma-quibbling/VBScript/comma-quibbling.vb new file mode 100644 index 0000000000..5e2ccae3fc --- /dev/null +++ b/Task/Comma-quibbling/VBScript/comma-quibbling.vb @@ -0,0 +1,27 @@ +Function Quibble(s) + arr = Split(s,",") + If s = "" Then + Quibble = "{}" + ElseIf UBound(arr) = 0 Then + Quibble = "{" & arr(0) & "}" + Else + Quibble = "{" + For i = 0 To UBound(arr) + If i = UBound(arr) - 1 Then + Quibble = Quibble & arr(i) & " and " & arr(i + 1) & "}" + Exit For + Else + Quibble = Quibble & arr(i) & ", " + End If + Next + End If +End Function + +WScript.StdOut.Write Quibble("") +WScript.StdOut.WriteLine +WScript.StdOut.Write Quibble("ABC") +WScript.StdOut.WriteLine +WScript.StdOut.Write Quibble("ABC,DEF") +WScript.StdOut.WriteLine +WScript.StdOut.Write Quibble("ABC,DEF,G,H") +WScript.StdOut.WriteLine diff --git a/Task/Command-line-arguments/DCL/command-line-arguments.dcl b/Task/Command-line-arguments/DCL/command-line-arguments.dcl new file mode 100644 index 0000000000..44a6cba8ad --- /dev/null +++ b/Task/Command-line-arguments/DCL/command-line-arguments.dcl @@ -0,0 +1,5 @@ +$ i = 1 +$ loop: +$ write sys$output "the value of P''i' is ", p'i +$ i = i + 1 +$ if i .le. 8 then $ goto loop diff --git a/Task/Command-line-arguments/Julia/command-line-arguments.julia b/Task/Command-line-arguments/Julia/command-line-arguments.julia new file mode 100644 index 0000000000..c9bde08773 --- /dev/null +++ b/Task/Command-line-arguments/Julia/command-line-arguments.julia @@ -0,0 +1,6 @@ +prog = basename(Base.source_path()) + +println(prog, "'s command-line arguments are:") +for s in ARGS + println(" ", s) +end diff --git a/Task/Command-line-arguments/Rust/command-line-arguments-1.rust b/Task/Command-line-arguments/Rust/command-line-arguments-1.rust index 5a053037d1..225d9656c3 100644 --- a/Task/Command-line-arguments/Rust/command-line-arguments-1.rust +++ b/Task/Command-line-arguments/Rust/command-line-arguments-1.rust @@ -1,5 +1,6 @@ -use std::os; +use std::env; fn main(){ - println!("{:?}", os::args()); + let args: Vec<_> = env::args().collect(); + println!("{:?}", args); } diff --git a/Task/Command-line-arguments/Rust/command-line-arguments-2.rust b/Task/Command-line-arguments/Rust/command-line-arguments-2.rust index 51f063e956..b9a5acaa15 100644 --- a/Task/Command-line-arguments/Rust/command-line-arguments-2.rust +++ b/Task/Command-line-arguments/Rust/command-line-arguments-2.rust @@ -1,2 +1,2 @@ ./program -c "alpha beta" -h "gamma" -~[~"./args", ~"-c", ~"alpha beta", ~"-h", ~"gamma"] +["./program", "-c", "alpha beta", "-h", "gamma"] diff --git a/Task/Comments/4D/comments.4d b/Task/Comments/4D/comments.4d index 31151ddee3..16fb1cef17 100644 --- a/Task/Comments/4D/comments.4d +++ b/Task/Comments/4D/comments.4d @@ -1 +1,2 @@ -`Comments in 4th Dimension begin with the accent character and extend to the end of the line. +`Comments in 4th Dimension begin with the accent character and extend to the end of the line (until 4D version 2004). +// This is a comment starting from 4D v11 and newer. Accent character is replaced by // diff --git a/Task/Comments/Eiffel/comments.e b/Task/Comments/Eiffel/comments.e new file mode 100644 index 0000000000..7a77b47038 --- /dev/null +++ b/Task/Comments/Eiffel/comments.e @@ -0,0 +1 @@ +-- inline comment, continues until new line diff --git a/Task/Comments/J/comments.j b/Task/Comments/J/comments.j index a0f2046039..1c5b28c515 100644 --- a/Task/Comments/J/comments.j +++ b/Task/Comments/J/comments.j @@ -9,3 +9,5 @@ Note 'example' Another way to record multi-line comments as text is to use 'Note', which is actually a simple program that makes it clearer when defined text is used only to provide comment. ) + +'A simple string which is not used is legal, and will be discarded' diff --git a/Task/Comments/JavaScript/comments-1.js b/Task/Comments/JavaScript/comments-1.js new file mode 100644 index 0000000000..436477fb7b --- /dev/null +++ b/Task/Comments/JavaScript/comments-1.js @@ -0,0 +1 @@ +n = n + 1; // This is a comment diff --git a/Task/Comments/JavaScript/comments-2.js b/Task/Comments/JavaScript/comments-2.js new file mode 100644 index 0000000000..546894d1b7 --- /dev/null +++ b/Task/Comments/JavaScript/comments-2.js @@ -0,0 +1 @@ +// This is a valid comment // with a "nested" comment diff --git a/Task/Comments/JavaScript/comments-3.js b/Task/Comments/JavaScript/comments-3.js new file mode 100644 index 0000000000..ba806c6259 --- /dev/null +++ b/Task/Comments/JavaScript/comments-3.js @@ -0,0 +1,6 @@ +/* This is +a multi line +comment +// with a "nested" comment +and another line in the comment +*/ diff --git a/Task/Comments/Julia/comments.julia b/Task/Comments/Julia/comments.julia new file mode 100644 index 0000000000..a1242a052a --- /dev/null +++ b/Task/Comments/Julia/comments.julia @@ -0,0 +1,7 @@ +# single line + +#= +Multi- +line +comment +=# diff --git a/Task/Comments/Squirrel/comments.nut b/Task/Comments/Squirrel/comments.nut new file mode 100644 index 0000000000..858c66937f --- /dev/null +++ b/Task/Comments/Squirrel/comments.nut @@ -0,0 +1,7 @@ +//this is a single line comment + +#this is also a single line comment + +/* + this is a multi-line comment +*/ diff --git a/Task/Compare-sorting-algorithms-performance/Ruby/compare-sorting-algorithms-performance.rb b/Task/Compare-sorting-algorithms-performance/Ruby/compare-sorting-algorithms-performance.rb new file mode 100644 index 0000000000..110aa6f1fa --- /dev/null +++ b/Task/Compare-sorting-algorithms-performance/Ruby/compare-sorting-algorithms-performance.rb @@ -0,0 +1,93 @@ +class Array + def radix_sort(base=10) # negative value is inapplicable. + ary = dup + rounds = (Math.log(ary.max)/Math.log(base)).ceil + rounds.times do |i| + buckets = Array.new(base){[]} + base_i = base**i + ary.each do |n| + digit = (n/base_i) % base + buckets[digit] << n + end + ary = buckets.flatten + end + ary + end + + def quick_sort + return self if size <= 1 + pivot = sample + g = group_by{|x| x<=>pivot} + g.default = [] + g[-1].quick_sort + g[0] + g[1].quick_sort + end + + def shell_sort + inc = size / 2 + while inc > 0 + (inc...size).each do |i| + value = self[i] + while i >= inc and self[i - inc] > value + self[i] = self[i - inc] + i -= inc + end + self[i] = value + end + inc = (inc == 2 ? 1 : (inc * 5.0 / 11).to_i) + end + self + end + + def insertion_sort + (1...size).each do |i| + value = self[i] + j = i - 1 + while j >= 0 and self[j] > value + self[j+1] = self[j] + j -= 1 + end + self[j+1] = value + end + self + end + + def bubble_sort + (1...size).each do |i| + (0...size-i).each do |j| + self[j], self[j+1] = self[j+1], self[j] if self[j] > self[j+1] + end + end + self + end +end + +data_size = [1000, 10000, 100000, 1000000] +data = [] +data_size.each do |size| + ary = *1..size + data << [ [1]*size, ary, ary.shuffle, ary.reverse ] +end +data = data.transpose + +data_type = ["set to all ones", "ascending sequence", "randomly shuffled", "descending sequence"] +print "Array size: " +puts data_size.map{|size| "%9d" % size}.join + +data.each_with_index do |arys,i| + puts "\nData #{data_type[i]}:" + [:sort, :radix_sort, :quick_sort, :shell_sort, :insertion_sort, :bubble_sort].each do |m| + printf "%20s ", m + flag = true + arys.each do |ary| + if flag + t0 = Time.now + ary.dup.send(m) + printf " %7.3f", (t1 = Time.now - t0) + flag = false if t1 > 2 + else + print " --.---" + end + end + puts + end +end diff --git a/Task/Compile-time-calculation/Haskell/compile-time-calculation-1.hs b/Task/Compile-time-calculation/Haskell/compile-time-calculation-1.hs new file mode 100644 index 0000000000..7821e713b2 --- /dev/null +++ b/Task/Compile-time-calculation/Haskell/compile-time-calculation-1.hs @@ -0,0 +1,7 @@ +module Factorial where +import Language.Haskell.TH.Syntax + +fact n = product [1..n] + +factQ :: Integer -> Q Exp +factQ = lift . fact diff --git a/Task/Compile-time-calculation/Haskell/compile-time-calculation-2.hs b/Task/Compile-time-calculation/Haskell/compile-time-calculation-2.hs new file mode 100644 index 0000000000..237771e0a1 --- /dev/null +++ b/Task/Compile-time-calculation/Haskell/compile-time-calculation-2.hs @@ -0,0 +1,4 @@ +{-# LANGUAGE TemplateHaskell #-} +import Factorial + +main = print $(factQ 10) diff --git a/Task/Compile-time-calculation/Haskell/compile-time-calculation.hs b/Task/Compile-time-calculation/Haskell/compile-time-calculation.hs deleted file mode 100644 index 527ffd3984..0000000000 --- a/Task/Compile-time-calculation/Haskell/compile-time-calculation.hs +++ /dev/null @@ -1,5 +0,0 @@ -{-# LANGUAGE QuasiQuotes, TemplateHaskell #-} - -fact n = product [1..n] - -main = print $([|fact 10|]) diff --git a/Task/Compile-time-calculation/PowerShell/compile-time-calculation.psh b/Task/Compile-time-calculation/PowerShell/compile-time-calculation.psh new file mode 100644 index 0000000000..74ae4582a9 --- /dev/null +++ b/Task/Compile-time-calculation/PowerShell/compile-time-calculation.psh @@ -0,0 +1,14 @@ +function fact([BigInt]$n){ + if($n -ge ([BigInt]::Zero)) { + $fact = [BigInt]::One + ([BigInt]::One)..$n | foreach{ + $fact = [BigInt]::Multiply($fact, $_) + } + $fact + + } else { + Write-Error "$n is lower than 0" + } +} +"$((Measure-Command {$fact = fact 10}).TotalSeconds) Seconds" +$fact diff --git a/Task/Compound-data-type/JavaScript/compound-data-type.js b/Task/Compound-data-type/JavaScript/compound-data-type.js index b5fe6df70a..d230c54507 100644 --- a/Task/Compound-data-type/JavaScript/compound-data-type.js +++ b/Task/Compound-data-type/JavaScript/compound-data-type.js @@ -1 +1,18 @@ +//using object literal syntax var point = {x : 1, y : 2}; + +//using constructor +var Point = function (x, y) { + this.x = x; + this.y = y; +}; +point = new Point(1, 2); + +//using ES6 class syntax +class Point { + constructor(x, y) { + this.x = x; + this.y = y; + } +} +point = new Point(1, 2); diff --git a/Task/Compound-data-type/Julia/compound-data-type-1.julia b/Task/Compound-data-type/Julia/compound-data-type-1.julia new file mode 100644 index 0000000000..6234a7c31c --- /dev/null +++ b/Task/Compound-data-type/Julia/compound-data-type-1.julia @@ -0,0 +1,4 @@ +type Point{T<:Real} + x::T + y::T +end diff --git a/Task/Compound-data-type/Julia/compound-data-type-2.julia b/Task/Compound-data-type/Julia/compound-data-type-2.julia new file mode 100644 index 0000000000..596735b274 --- /dev/null +++ b/Task/Compound-data-type/Julia/compound-data-type-2.julia @@ -0,0 +1,4 @@ +==(u::Point, v::Point) = (u.x == v.x) & (u.y == v.y) +-(u::Point) = Point(-u.x, -u.y) ++(u::Point, v::Point) = Point(u.x + v.x, u.y + v.y) +-(u::Point, v::Point) = Point(u.x - v.x, u.y - v.y) diff --git a/Task/Compound-data-type/Julia/compound-data-type-3.julia b/Task/Compound-data-type/Julia/compound-data-type-3.julia new file mode 100644 index 0000000000..29b702b609 --- /dev/null +++ b/Task/Compound-data-type/Julia/compound-data-type-3.julia @@ -0,0 +1,14 @@ +a = Point(1, 2) +b = Point(3, 7) +c = Point(2, 4) + +println("a = ", a) +println("b = ", b) +println("c = ", c) + +println("a + b = ", a+b) +println("-a + b = ", -a+b) +println("a - b = ", a-b) +println("a + b + c = ", a+b+c) +println("a == c ", a == c) +println("a + a == c ", a + a == c) diff --git a/Task/Compound-data-type/TXR/compound-data-type-1.txr b/Task/Compound-data-type/TXR/compound-data-type-1.txr new file mode 100644 index 0000000000..132921678f --- /dev/null +++ b/Task/Compound-data-type/TXR/compound-data-type-1.txr @@ -0,0 +1 @@ +(defstruct point nil (x 0) (y 0)) diff --git a/Task/Compound-data-type/TXR/compound-data-type-2.txr b/Task/Compound-data-type/TXR/compound-data-type-2.txr new file mode 100644 index 0000000000..4be0e69930 --- /dev/null +++ b/Task/Compound-data-type/TXR/compound-data-type-2.txr @@ -0,0 +1 @@ +(defstruct point nil x y) diff --git a/Task/Compound-data-type/TXR/compound-data-type-3.txr b/Task/Compound-data-type/TXR/compound-data-type-3.txr new file mode 100644 index 0000000000..ac802c627c --- /dev/null +++ b/Task/Compound-data-type/TXR/compound-data-type-3.txr @@ -0,0 +1,3 @@ +(new point) ;; -> #S(point x 0 y 0) +(new point x 1) ;; -> #S(point x 1 y 0) +(new point x 1 y 1) ;; -> #S(point x 1 y 1) diff --git a/Task/Compound-data-type/TXR/compound-data-type-4.txr b/Task/Compound-data-type/TXR/compound-data-type-4.txr new file mode 100644 index 0000000000..6c674ed527 --- /dev/null +++ b/Task/Compound-data-type/TXR/compound-data-type-4.txr @@ -0,0 +1 @@ +(defstruct (point x y) nil (x 0) (y 0)) diff --git a/Task/Compound-data-type/TXR/compound-data-type-5.txr b/Task/Compound-data-type/TXR/compound-data-type-5.txr new file mode 100644 index 0000000000..3ade4fb586 --- /dev/null +++ b/Task/Compound-data-type/TXR/compound-data-type-5.txr @@ -0,0 +1 @@ +(new (point 3 4)) -> #S(point x 3 y 4) diff --git a/Task/Compound-data-type/TXR/compound-data-type-6.txr b/Task/Compound-data-type/TXR/compound-data-type-6.txr new file mode 100644 index 0000000000..27d46c45a2 --- /dev/null +++ b/Task/Compound-data-type/TXR/compound-data-type-6.txr @@ -0,0 +1,3 @@ +(defun displace-point-destructively (p delta) + (inc p.x delta.x) + (inc p.y delta.y)) diff --git a/Task/Concurrent-computing/Rust/concurrent-computing.rust b/Task/Concurrent-computing/Rust/concurrent-computing.rust index 26e4980e70..59e637e9ee 100644 --- a/Task/Concurrent-computing/Rust/concurrent-computing.rust +++ b/Task/Concurrent-computing/Rust/concurrent-computing.rust @@ -1,15 +1,18 @@ -use std::io::timer::sleep; -use std::rand::{task_rng, Rng}; +extern crate rand; +use std::thread; +use rand::thread_rng; +use rand::distributions::{Range, IndependentSample}; fn main() { - let mut rng = task_rng(); - for word in "Enjoy Rosetta Code".words() { - let local_word = word.to_string(); - let snooze_time = rng.gen_range::(0, 1000); - - spawn(proc() { - sleep(snooze_time); - println!("{}", local_word); - }); - } + let mut rng = thread_rng(); + let rng_range = Range::new(0u32, 100); + for word in "Enjoy Rosetta Code".split_whitespace() { + let snooze_time = rng_range.ind_sample(&mut rng); + let local_word = word.to_owned(); + std::thread::spawn(move || { + thread::sleep_ms(snooze_time); + println!("{}", local_word); + }); + } + thread::sleep_ms(1000); } diff --git a/Task/Conditional-structures/ALGOL-W/conditional-structures.alg b/Task/Conditional-structures/ALGOL-W/conditional-structures.alg new file mode 100644 index 0000000000..3134ed8a3a --- /dev/null +++ b/Task/Conditional-structures/ALGOL-W/conditional-structures.alg @@ -0,0 +1,32 @@ +begin + integer a, b, c; + + a := 1; b := 2; c := 3; + + % algol W has the traditional Algol if-the-else statement % + % there is no "elseif" contraction % + if a = b + then write( "a = b" ) + else if a = c + then write( "a = c" ) + else write( "a is ", a ); + + % if-then-else can also be used in an expression % + write( if a < 4 then "lt 4" else "ge 4" ); + + % algol W also has a "case" statement, an integer expression is used to % + % select the statement to execute. If the expression evaluates to 1, % + % the first statement is executed, if 2, the second is executed etc. % + % If the expression is less than 1 or greater than the number of % + % statements, a run time error occurs % + case a + b of + begin write( "a + b is one" ) + ; write( "a + b is two" ) + ; write( "a + b is three" ) + ; write( "a + b is four" ) + end; + + % there is also an expression form of the case: % + write( case c - a of ( "one", "two", "three", "four" ) ) + +end. diff --git a/Task/Conditional-structures/JavaScript/conditional-structures-4.js b/Task/Conditional-structures/JavaScript/conditional-structures-4.js new file mode 100644 index 0000000000..365111a4e7 --- /dev/null +++ b/Task/Conditional-structures/JavaScript/conditional-structures-4.js @@ -0,0 +1,10 @@ +function takeWhile(lst, fnTest) { + 'use strict'; + var varHead = lst.length ? lst[0] : null; + + return varHead ? ( + fnTest(varHead) ? [varHead].concat( + takeWhile(lst.slice(1), fnTest) + ) : [] + ) : []; +} diff --git a/Task/Conditional-structures/Prolog/conditional-structures-1.pro b/Task/Conditional-structures/Prolog/conditional-structures-1.pro new file mode 100644 index 0000000000..760321321d --- /dev/null +++ b/Task/Conditional-structures/Prolog/conditional-structures-1.pro @@ -0,0 +1 @@ +go :- write('Hello, World!'), nl. diff --git a/Task/Conditional-structures/Prolog/conditional-structures-2.pro b/Task/Conditional-structures/Prolog/conditional-structures-2.pro new file mode 100644 index 0000000000..542761e6d8 --- /dev/null +++ b/Task/Conditional-structures/Prolog/conditional-structures-2.pro @@ -0,0 +1,6 @@ +fact(foo). +fact(bar). +fact(baz). + +go :- fact(booger). +go :- fact(bar). diff --git a/Task/Conditional-structures/Prolog/conditional-structures-3.pro b/Task/Conditional-structures/Prolog/conditional-structures-3.pro new file mode 100644 index 0000000000..8ceff211bc --- /dev/null +++ b/Task/Conditional-structures/Prolog/conditional-structures-3.pro @@ -0,0 +1,8 @@ +fact(X) :- + ( X = foo + ; X = bar + ; X = baz ). + +go :- + ( fact(booger) + ; fact(bar) ). diff --git a/Task/Conditional-structures/Prolog/conditional-structures-4.pro b/Task/Conditional-structures/Prolog/conditional-structures-4.pro new file mode 100644 index 0000000000..ecd50d3025 --- /dev/null +++ b/Task/Conditional-structures/Prolog/conditional-structures-4.pro @@ -0,0 +1,7 @@ +fact(X) :- + ( X = bar -> write('You got me!'), nl + ; write(X), write(' is not right!'), nl, fail ). + +go :- + ( fact(booger) + ; fact(bar) ). diff --git a/Task/Conjugate-transpose/REXX/conjugate-transpose.rexx b/Task/Conjugate-transpose/REXX/conjugate-transpose.rexx index 5f1d6cc189..4c73c5bd66 100644 --- a/Task/Conjugate-transpose/REXX/conjugate-transpose.rexx +++ b/Task/Conjugate-transpose/REXX/conjugate-transpose.rexx @@ -1,88 +1,87 @@ -/*REXX pgm performs a conjugate transpose on a complex square matrix.*/ +/*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.*/ +M.=0 /*Matrix has all elements equal to 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*/ + 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*/ +call showCmat 'M' ,N /*display a nicely 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*/ +call conjCmat 'MH', "M" ,N /*conjugate the M matrix ───► MH */ +call showCmat 'MH' ,N /*display a nicely 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) +call multCmat 'M', 'MH', 'MMH', N /*multiple the 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 all done. */ +/*──────────────────────────────────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) +/*────────────────────────────────────────────────────────────────────────────*/ +conjCmat: parse 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*/ - 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 + end /*r*/ + return +/*────────────────────────────────────────────────────────────────────────────*/ +isHermitian: parse 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: parse 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: parse 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: parse 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: parse arg matX,rows,cols; if cols=='' then cols=rows; @@=left('',6) + say; say center('matrix' matX,79,'─'); call normCmat matX,rows,cols + do r=1 to rows; _= + do c=1 to cols; _=_ @@ left(value(matX'.'r"."c),9); end + say _ + end /*r*/ + say; return +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Constrained-genericity/C++/constrained-genericity.cpp b/Task/Constrained-genericity/C++/constrained-genericity.cpp new file mode 100644 index 0000000000..d25ed1d5cc --- /dev/null +++ b/Task/Constrained-genericity/C++/constrained-genericity.cpp @@ -0,0 +1,33 @@ +template //Detection helper struct +struct can_eat //Detects presence of non-const member function void eat() +{ + private: + template struct SFINAE {}; + template static char Test(SFINAE*); + template static int Test(...); + public: + static constexpr bool value = sizeof(Test(0)) == sizeof(char); +}; + +struct potato +{ void eat(); }; + +struct brick +{}; + +template +class FoodBox +{ + //Using static assertion to prohibit non-edible types + static_assert(can_eat::value, "Only edible items are allowed in foodbox"); + + //Rest of class definition +}; + +int main() +{ + FoodBox lunch; + + //Following leads to compile-time error + //FoodBox practical_joke; +} diff --git a/Task/Constrained-genericity/Forth/constrained-genericity.fth b/Task/Constrained-genericity/Forth/constrained-genericity.fth new file mode 100644 index 0000000000..c33cc4ee7f --- /dev/null +++ b/Task/Constrained-genericity/Forth/constrained-genericity.fth @@ -0,0 +1,61 @@ +include FMS-SI.f +include FMS-SILib.f + +: (where) ( class-xt where-dfa -- flag ) + swap >body { where-dfa class-dfa } + begin + class-dfa ['] object >body <> + while + class-dfa where-dfa = if true exit then + class-dfa sfa @ to class-dfa + repeat false ; + +: where ( class-xt "classname" -- flag ) + ' >body state @ + if postpone literal postpone (where) + else (where) + then ; immediate + +:class Eatable + :m eat cr ." successful eat" ;m +;class + +\ FoodBox is defined without using eat in any way. +:class FoodBox + object-list eatable-types + :m fill: { n class-xt -- } + class-xt where Eatable + if n 0 do class-xt eatable-types xtadd: loop + else ." not an eatable type " + then ;m + :m get ( -- obj ) eatable-types ;m +;class + +: test ( obj -- ) \ send the eat message to each object in the object-list + begin dup each: + while eat + repeat drop ; + +FoodBox fb +3 ' Eatable fb fill: \ fill the object-list with 3 objects of class Eatable +fb get test +successful eat +successful eat +successful eat + +FoodBox fb1 +5 ' object fb1 fill: \ => not an eatable type + +:class apple > : NSObject +@end diff --git a/Task/Constrained-random-points-on-a-circle/BASIC/constrained-random-points-on-a-circle-1.basic b/Task/Constrained-random-points-on-a-circle/BASIC/constrained-random-points-on-a-circle-1.basic new file mode 100644 index 0000000000..9196a187a8 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/BASIC/constrained-random-points-on-a-circle-1.basic @@ -0,0 +1,8 @@ + MODE 8 + ORIGIN 640, 512 + FOR i% = 1 TO 1000 + x% = RND(31)-16 + y% = RND(31)-16 + r = SQR(x%^2 + y%^2) + IF r >= 10 IF r <= 15 PLOT x%*2, y%*2 + NEXT diff --git a/Task/Constrained-random-points-on-a-circle/BASIC/constrained-random-points-on-a-circle-2.basic b/Task/Constrained-random-points-on-a-circle/BASIC/constrained-random-points-on-a-circle-2.basic new file mode 100644 index 0000000000..91eaf28e49 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/BASIC/constrained-random-points-on-a-circle-2.basic @@ -0,0 +1,60 @@ +'Free Basic version .9 + +#define Intrange(f,l) int(Rnd*(((l)+1)-(f))+(f)) + +Type pair + As Integer x,y +End Type + +Operator =(a As pair,b As pair) As Integer +Return a.x=b.x And a.y=b.y +End Operator + +Function NotInArray(a() As pair,n As pair) As Integer + For z As Integer=Lbound(a) To Ubound(a) + If a(z)=n Then Return 0 + Next z + Return -1 +End Function + +Redim As pair pts(0) +Dim As Integer x,y,counter +Do + counter=counter+1 + x=IntRange(-20,20) + y=IntRange(-20,20) + var root=Sqr(x*x+y*y) + If 10<= root And root<=15 Then + If NotInArray(pts(),Type(x,y)) Then + Redim Preserve pts(1 To Ubound(pts)+1) + pts(Ubound(pts))=Type(x,y) + End If + End If +Loop Until counter=100000 + +'============== Plot to Console ====================== + +dim as integer yres=hiword(width) +dim as integer xres=loword(width) + +#define map(a,b,x,c,d) ((d)-(c))*((x)-(a))/((b)-(a))+(c) +#define _X(num) int( map(0,xres,(num),0,loword(width))) +#define _Y(num) int( map(0,yres,(num),0,hiword(width))) + +counter=0 +For n As Integer=Lbound(pts) To Ubound(pts) + counter=counter+1 + if counter <=100 then + var xpos=map(-20,20,pts(n).x,0,xres) + var ypos=map(-20,20,pts(n).y,0,yres) + locate _Y(ypos),_X(xpos) + print "*" + end if +Next n + +print +locate 1,1 +Print "Total number of points "; counter +print "Total number plotted ";100 +print "done" +Sleep diff --git a/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle-1.elixir b/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle-1.elixir new file mode 100644 index 0000000000..3bf7c039eb --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle-1.elixir @@ -0,0 +1,21 @@ +defmodule Random do + defp generate_point(0, _, _, set), do: set + defp generate_point(n, f, range, set) do + point = {x,y} = {f.(), f.()} + if x*x + y*y in range and not Set.member?(set, point), + do: generate_point(n-1, f, range, Set.put(set, point)), + else: generate_point(n, f, range, set) + end + def circle do + f = fn -> :rand.uniform(31) - 16 end + points = generate_point(100, f, 10*10..15*15, HashSet.new) + for x <- -15..15 do + for y <- -15..15 do + IO.write if Set.member?(points, {x,y}), do: "x", else: " " + end + IO.puts "" + end + end +end + +Random.circle diff --git a/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle-2.elixir b/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle-2.elixir new file mode 100644 index 0000000000..93c17e2ec1 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle-2.elixir @@ -0,0 +1,17 @@ +defmodule Constrain do + defp precalculate(range, condition) do + for x <- range, y <- range, x*x + y*y in condition, do: {x,y} + end + + def circle do + range = -15..15 + all_points = precalculate(range, 10*10..15*15) + IO.puts length(all_points) + points = Enum.shuffle(all_points) |> Enum.take(100) + Enum.each(-15..15, fn x -> + IO.puts Enum.map(range, fn y -> if Enum.member?(points, {x,y}), do: "o ", else: " " end) + end) + end +end + +Constrain.circle diff --git a/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle.elixir b/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle.elixir deleted file mode 100644 index b484c918c5..0000000000 --- a/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle.elixir +++ /dev/null @@ -1,30 +0,0 @@ -defmodule Random do - def init() do - :random.seed(:erlang.now()) - end - def generate_point() do - x = :random.uniform(31) - 16 - y = :random.uniform(31) - 16 - if 10*10 <= x*x + y*y and x*x + y*y <= 15*15 do - {x, y} - else - generate_point() - end - end - def circle() do - points = for _ <- 1..100, do: generate_point() - for x <- -15..15 do - for y <- -15..15 do - if Enum.member?(points, {x, y}) do - IO.write "x" - else - IO.write " " - end - end - IO.puts "" - end - end -end - -Random.init() -Random.circle() diff --git a/Task/Constrained-random-points-on-a-circle/Julia/constrained-random-points-on-a-circle.julia b/Task/Constrained-random-points-on-a-circle/Julia/constrained-random-points-on-a-circle.julia new file mode 100644 index 0000000000..263e9c2ac0 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Julia/constrained-random-points-on-a-circle.julia @@ -0,0 +1,18 @@ +const LO = 10 +const HI = 15 +const GOAL = 100 + +canvas = falses(2HI+1, 2HI+1) +i = 0 + +while i < GOAL + x = rand(-HI:HI) + y = rand(-HI:HI) + LO^2-1 < x^2 + y^2 < HI^2+1 || continue + i += 1 + canvas[x+HI+1, y+HI+1] = true +end + +for i in 1:(2HI+1) + println(" ", join(map(j -> j ? "\u25cf " : " ", canvas[i,:]))) +end diff --git a/Task/Constrained-random-points-on-a-circle/Perl-6/constrained-random-points-on-a-circle-1.pl6 b/Task/Constrained-random-points-on-a-circle/Perl-6/constrained-random-points-on-a-circle-1.pl6 index 69eca96fc0..abd2a925a3 100644 --- a/Task/Constrained-random-points-on-a-circle/Perl-6/constrained-random-points-on-a-circle-1.pl6 +++ b/Task/Constrained-random-points-on-a-circle/Perl-6/constrained-random-points-on-a-circle-1.pl6 @@ -1,12 +1,12 @@ my @range = -15..16; -my @points = gather for @range X @range -> $x, $y { +my @points = gather for @range X @range -> ($x, $y) { take [$x,$y] if 10 <= sqrt($x*$x+$y*$y) <= 15 } my @samples = @points.roll(100); # or .pick(100) to get distinct points # format and print my %matrix; -for @range X @range -> $x, $y { %matrix{$y}{$x} = ' ' } +for @range X @range -> ($x, $y) { %matrix{$y}{$x} = ' ' } %matrix{$_[1]}{$_[0]} = '*' for @samples; %matrix{$_}{@range}.join(' ').say for @range; diff --git a/Task/Constrained-random-points-on-a-circle/Perl-6/constrained-random-points-on-a-circle-2.pl6 b/Task/Constrained-random-points-on-a-circle/Perl-6/constrained-random-points-on-a-circle-2.pl6 index b25aed61ac..2a80a2c7c4 100644 --- a/Task/Constrained-random-points-on-a-circle/Perl-6/constrained-random-points-on-a-circle-2.pl6 +++ b/Task/Constrained-random-points-on-a-circle/Perl-6/constrained-random-points-on-a-circle-2.pl6 @@ -1,5 +1,5 @@ (say ~.map: { $_ // ' ' } for my @matrix) given do -> [$x, $y] { @matrix[$x][$y] = '*' } for pick 100, do - for ^32 X ^32 -> $x, $y { + for ^32 X ^32 -> ($x, $y) { [$x,$y] when 100..225 given [+] ($x,$y X- 15) X** 2; } diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx index c5463160fc..d2d7c5098d 100644 --- a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx @@ -1,28 +1,26 @@ -/*REXX program gens 100 random points in an annulus: 10 ≤ √(x²+y²) ≤ 15 */ -parse arg points low high . /*allow parms from command line. */ +/*REXX program generates 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */ +parse arg points low high . /*obtain optional args from the C.L. */ if points=='' then points=100 -if low=='' then low=10; low2= low**2 /*define a square shortcut.*/ -if high=='' then high=15; high2=high**2 /* " " " " */ +if low=='' then low=10; low2= low**2 /*define a shortcut for square.*/ +if high=='' then high=15; high2=high**2 /* " " " " " */ $= - do x=-high; x2=x*x /*gen all possible annulus points*/ + do x=-high; x2=x*x /*generate all possible annulus points.*/ if x<0 & x2>high2 then iterate if x>0 & x2>high2 then leave - do y=-high; y2=y*y; s=x2+y2 + do y=-high; s=x2+y*y if (y<0 & s>high2) | s0 & s>high2 then leave - $=$ x','y /*add a point-set to the $ list. */ + $=$ x','y /*add a point─set to the $ list. */ end /*y*/ end /*x*/ -plotChar='O'; minY=high2; maxY=-minY; ap=words($); field.= +plotChar='Θ'; minY=high2; maxY=-minY; ap=words($); @.= - do j=1 for points /*"draw" the x,y points [char O].*/ - parse value word($,random(1,ap)) with x ',' y /*pick random point.*/ - field.y=overlay(plotChar, field.y, x+high+1) /*"draw: the point. */ - minY=min(minY,y); maxY=max(maxY,y) /*plot restricting. */ + do j=1 for points /*define the x,y points [character O].*/ + parse value word($,random(1,ap)) with x ',' y /*pick a random point.*/ + @.y=overlay(plotChar, @.y, x+high+1) /*define: the point. */ + minY=min(minY,y); maxY=max(maxY,y) /*plot restricting. */ end /*j*/ - - do y=minY to maxY /*display the annulus to screen. */ - if field\=='' then say field.y /*Not blank? Then display it. */ - end /*y*/ - /*stick a fork in it, we're done.*/ + /* [↓] only show displayable section. */ + do y=minY to maxY; say @.y; end /*display the annulus to the terminal. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx index daa5938b87..aee38fc1cf 100644 --- a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx @@ -1,28 +1,26 @@ -/*REXX program gens 100 random points in an annulus: 10 ≤ √(x²+y²) ≤ 15 */ -parse arg points low high . /*allow parms from command line. */ +/*REXX program generates 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */ +parse arg points low high . /*obtain optional args from the C.L. */ if points=='' then points=100 -if low=='' then low=10; low2= low**2 /*define a square shortcut.*/ -if high=='' then high=15; high2=high**2 /* " " " " */ +if low=='' then low=10; low2= low**2 /*define a square shortcut.*/ +if high=='' then high=15; high2=high**2 /* " " " " */ $= - do x=-high; x2=x*x /*gen all possible annulus points*/ + do x=-high; x2=x*x /*generate all possible annulus points.*/ if x<0 & x2>high2 then iterate if x>0 & x2>high2 then leave - do y=-high; y2=y*y; s=x2+y2 + do y=-high; s=x2+y*y if (y<0 & s>high2) | s0 & s>high2 then leave - $=$ x','y /*add a point-set to the $ list. */ + $=$ x','y /*add a point─set to the $ list. */ end /*y*/ end /*x*/ -plotChar='O'; minY=high2; maxY=-minY; ap=words($); field.= +plotChar='Θ'; minY=high2; maxY=-minY; ap=words($); @.= - do j=1 for points /*"draw" the x,y points [char O].*/ - parse value word($,random(1,ap)) with x ',' y /*pick random point.*/ - field.y=overlay(plotChar, field.y, 2*x+2*high+1) /*"draw: the point. */ - minY=min(minY,y); maxY=max(maxY,y) /*plot restricting. */ + do j=1 for points /*define the x,y points [character Θ].*/ + parse value word($,random(1,ap)) with x ',' y /*pick a random point.*/ + @.y=overlay(plotChar, @.y, 2*x+2*high+1) /*define: the point. */ + minY=min(minY,y); maxY=max(maxY,y) /*plot restricting. */ end /*j*/ - - do y=minY to maxY /*display the annulus to screen. */ - if field\=='' then say field.y /*Not blank? Then display it. */ - end /*y*/ - /*stick a fork in it, we're done.*/ + /* [↓] only show displayable section. */ + do y=minY to maxY; say @.y; end /*display the annulus to the terminal. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-2.rb b/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-2.rb index 85d31e089c..c4ca9c14ec 100644 --- a/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-2.rb +++ b/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-2.rb @@ -1,10 +1,8 @@ r2 = 10*10..15*15 range = (-15..15).to_a -points = range.product(range).each_with_object([]) do |(i,j), pt| - pt << [i,j] if r2.cover?(i*i + j*j) -end +points = range.product(range).select {|i,j| r2.cover?(i*i + j*j)} puts "Precalculate: #{points.size}" pt = Hash.new(" ") -points.sample(100).each{|i,j| pt[[i,j]] = " o"} +points.sample(100).each{|ij| pt[ij] = " o"} puts range.map{|i| range.map{|j| pt[[i,j]]}.join} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-1.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-1.j index 773b6c248a..3bd0c8b846 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-1.j +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-1.j @@ -1 +1 @@ -cf=. }:@:({:"1@:((, <.)@%@-/@] ::]^:(<_) (, <.)) %&x:&>/) +cf=: _1 1 ,@}. (, <.)@%@-/ ::]^:a:@(, <.)@(%&x:/) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-10.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-10.j new file mode 100644 index 0000000000..e95f8e4cf9 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-10.j @@ -0,0 +1,4 @@ + r2cf each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 +┌───┬─┬─────┬─────┬───┬─────────────────────────────────┬─────────┐ +│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│_2 25 1 2│ +└───┴─┴─────┴─────┴───┴─────────────────────────────────┴─────────┘ diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-5.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-5.j index 38bde9faa9..d23c14b672 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-5.j +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-5.j @@ -1,33 +1 @@ -coclass'cf' -create =: dyad def 'EMPTY [ N =: x , y' -destroy =: codestroy -r2cf =: monad define - if. 0 (= {:) N do. _ return. end. - RV =. <.@:(%/) N - N =: ({. , |/)@:|. N - RV -) - -cocurrent'base' -CF =: conew'cf' - -Until =: conjunction def 'u^:(-.@:v)^:_' - -(,. }.@:}:@:((,r2cf__CF)Until(_-:{:))@:(8[create__CF/)&.>)1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 -Note 'Output' -┌─────────────────┬─────────────────────────────────┐ -│1 2 │0 2 │ -├─────────────────┼─────────────────────────────────┤ -│3 1 │3 │ -├─────────────────┼─────────────────────────────────┤ -│23 8 │2 1 7 │ -├─────────────────┼─────────────────────────────────┤ -│13 11 │1 5 2 │ -├─────────────────┼─────────────────────────────────┤ -│22 7 │3 7 │ -├─────────────────┼─────────────────────────────────┤ -│14142136 10000000│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│ -├─────────────────┼─────────────────────────────────┤ -│_151 77 │_2 25 1 2 │ -└─────────────────┴─────────────────────────────────┘ -) +r2cf=:1 1{."1@}.({:,(0,{:)#:{.)^:(*@{:)^:a: diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-6.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-6.j index 6069e8e7f2..3110f2b2a8 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-6.j +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-6.j @@ -1,13 +1,20 @@ - f =: 3 : 0 -a =. {.y -b =. {:y -out=. <. a%b -while. b > 1 do. -'a b' =. b; b|a -out=. out , <. a%b -end. -) - f each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 -┌───┬─┬─────┬─────┬───┬───────────────────────────────────┬─────────┐ -│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 _│_2 25 1 2│ -└───┴─┴─────┴─────┴───┴───────────────────────────────────┴─────────┘ + ((":@{.,'/',":@{:),': ',":@r2cf)@>1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77;14142 10000;141421 100000;1414214 1000000;14142136 10000000;31 10;314 100;3142 1000;31428 10000;314285 100000;3142857 1000000;31428571 10000000;314285714 100000000 +1/2: 0 2 +3/1: 3 +23/8: 2 1 7 +13/11: 1 5 2 +22/7: 3 7 +14142136/10000000: 1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 +_151/77: _2 25 1 2 +14142/10000: 1 2 2 2 2 2 1 1 29 +141421/100000: 1 2 2 2 2 2 2 3 1 1 3 1 7 2 +1414214/1000000: 1 2 2 2 2 2 2 2 3 6 1 2 1 12 +14142136/10000000: 1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 +31/10: 3 10 +314/100: 3 7 7 +3142/1000: 3 7 23 1 2 +31428/10000: 3 7 357 +314285/100000: 3 7 2857 +3142857/1000000: 3 7 142857 +31428571/10000000: 3 7 476190 3 +314285714/100000000: 3 7 7142857 diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-7.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-7.j new file mode 100644 index 0000000000..38bde9faa9 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-7.j @@ -0,0 +1,33 @@ +coclass'cf' +create =: dyad def 'EMPTY [ N =: x , y' +destroy =: codestroy +r2cf =: monad define + if. 0 (= {:) N do. _ return. end. + RV =. <.@:(%/) N + N =: ({. , |/)@:|. N + RV +) + +cocurrent'base' +CF =: conew'cf' + +Until =: conjunction def 'u^:(-.@:v)^:_' + +(,. }.@:}:@:((,r2cf__CF)Until(_-:{:))@:(8[create__CF/)&.>)1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 +Note 'Output' +┌─────────────────┬─────────────────────────────────┐ +│1 2 │0 2 │ +├─────────────────┼─────────────────────────────────┤ +│3 1 │3 │ +├─────────────────┼─────────────────────────────────┤ +│23 8 │2 1 7 │ +├─────────────────┼─────────────────────────────────┤ +│13 11 │1 5 2 │ +├─────────────────┼─────────────────────────────────┤ +│22 7 │3 7 │ +├─────────────────┼─────────────────────────────────┤ +│14142136 10000000│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2│ +├─────────────────┼─────────────────────────────────┤ +│_151 77 │_2 25 1 2 │ +└─────────────────┴─────────────────────────────────┘ +) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-8.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-8.j new file mode 100644 index 0000000000..e6272eed31 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-8.j @@ -0,0 +1,13 @@ +f =: 3 : 0 + a =. {.y + b =. {:y + out=. <. a%b + while. b > 1 do. + 'a b' =. b; b|a + out=. out , <. a%b + end. +) + f each 1 2;3 1;23 8;13 11;22 7;14142136 10000000;_151 77 +┌───┬─┬─────┬─────┬───┬───────────────────────────────────┬─────────┐ +│0 2│3│2 1 7│1 5 2│3 7│1 2 2 2 2 2 2 2 2 2 6 1 2 4 1 1 2 _│_2 25 1 2│ +└───┴─┴─────┴─────┴───┴───────────────────────────────────┴─────────┘ diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-9.j b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-9.j new file mode 100644 index 0000000000..b0b4355286 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/J/continued-fraction-arithmetic-construct-from-rational-number-9.j @@ -0,0 +1,8 @@ +r2cf=:3 :0 + 'n1 n2'=. y + r=.'' + while.n2 do. + 'n1 t1 n2'=. n2,(0,n2)#:n1 + r=.r,t1 + end. +) diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/REXX/continued-fraction-arithmetic-construct-from-rational-number.rexx b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/REXX/continued-fraction-arithmetic-construct-from-rational-number.rexx index 7840e9810e..466bb30fce 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/REXX/continued-fraction-arithmetic-construct-from-rational-number.rexx +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/REXX/continued-fraction-arithmetic-construct-from-rational-number.rexx @@ -49,12 +49,12 @@ pi: return, /*a bit of overkill, but hey !! */ /*─────────────────────────────SERR subroutine──────────────────────────*/ serr: say; say '***error!***'; say; say arg(1); say; exit /*─────────────────────────────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: if x<0 then call sqrtErr; numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ /*─────────────────────────────MAXFACT subroutine───────────────────────*/ $maxFact: procedure; parse arg x 1 _x,y; y=10**(digits()-1); b=0; h=1 a=1; g=0; do while a<=y & g<=y; n=trunc(_x); _=a; a=n*a+b; b=_; _=g diff --git a/Task/Continued-fraction/ALGOL-68/continued-fraction.alg b/Task/Continued-fraction/ALGOL-68/continued-fraction.alg new file mode 100644 index 0000000000..fdf384ff9a --- /dev/null +++ b/Task/Continued-fraction/ALGOL-68/continued-fraction.alg @@ -0,0 +1,25 @@ +PROC cf = (INT steps, PROC (INT) INT a, PROC (INT) INT b) REAL: +BEGIN + REAL result; + result := 0; + FOR n FROM steps BY -1 TO 1 DO + result := b(n) / (a(n) + result) + OD; + a(0) + result +END; + +PROC asqr2 = (INT n) INT: (n = 0 | 1 | 2); +PROC bsqr2 = (INT n) INT: 1; + +PROC anap = (INT n) INT: (n = 0 | 2 | n); +PROC bnap = (INT n) INT: (n = 1 | 1 | n - 1); + +PROC api = (INT n) INT: (n = 0 | 3 | 6); +PROC bpi = (INT n) INT: (n = 1 | 1 | (2 * n - 1) ** 2); + +INT precision = 10000; + +print (("Precision: ", precision, newline)); +print (("Sqr(2): ", cf(precision, asqr2, bsqr2), newline)); +print (("Napier: ", cf(precision, anap, bnap), newline)); +print (("Pi: ", cf(precision, api, bpi))) diff --git a/Task/Continued-fraction/Felix/continued-fraction.felix b/Task/Continued-fraction/Felix/continued-fraction.felix new file mode 100644 index 0000000000..ffdab5dd1c --- /dev/null +++ b/Task/Continued-fraction/Felix/continued-fraction.felix @@ -0,0 +1,27 @@ +fun pi (n:int) : (double*double) => + let a = match n with | 0 => 3.0 | _ => 6.0 endmatch in + let b = pow(2.0 * n.double - 1.0, 2.0) in + (a,b); + +fun sqrt_2 (n:int) : (double*double) => + let a = match n with | 0 => 1.0 | _ => 2.0 endmatch in + let b = 1.0 in + (a,b); + +fun napier (n:int) : (double*double) => + let a = match n with | 0 => 2.0 | _ => n.double endmatch in + let b = match n with | 1 => 1.0 | _ => (n.double - 1.0) endmatch in + (a,b); + +fun cf_iter (steps:int) (f:int -> double*double) = { + var acc = 0.0; + for var n in steps downto 0 do + var a, b = f(n); + acc = if (n > 0) then (b / (a + acc)) else (acc + a); + done + return acc; +} + +println$ cf_iter 200 sqrt_2; // => 1.41421 +println$ cf_iter 200 napier; // => 2.71818 +println$ cf_iter 1000 pi; // => 3.14159 diff --git a/Task/Continued-fraction/Perl-6/continued-fraction-2.pl6 b/Task/Continued-fraction/Perl-6/continued-fraction-2.pl6 index 7051b62d31..7ed0856b98 100644 --- a/Task/Continued-fraction/Perl-6/continued-fraction-2.pl6 +++ b/Task/Continued-fraction/Perl-6/continued-fraction-2.pl6 @@ -1,9 +1,7 @@ -sub infix:<⚬>(&f, &g) { -> $x { &f(&g($x)) } } -sub continued-fraction(@a, @b, $x = Inf) { - map { .($x) }, - [\⚬] map { @a[$_] + @b[$_] / * }, 0 .. * +sub continued-fraction(@a, @b) { + map { .(Inf) }, [\o] map { @a[$_] + @b[$_] / * }, ^Inf } -printf "√2 ≈ %.9f\n", continued-fraction((1, 2 xx *), (1 xx *))[10]; -printf "e ≈ %.9f\n", continued-fraction((2, 1 .. *), (1, 1 .. *))[10]; -printf "π ≈ %.9f\n", continued-fraction((3, 6 xx *), ((1, 3, 5 ... *) X** 2))[100]; +printf "√2 ≈ %.9f\n", continued-fraction((1, |(2 xx *)), (1 xx *))[10]; +printf "e ≈ %.9f\n", continued-fraction((2, |(1 .. *)), (1, |(1 .. *)))[10]; +printf "π ≈ %.9f\n", continued-fraction((3, |(6 xx *)), ((1, 3, 5 ... *) X** 2))[100]; diff --git a/Task/Convert-decimal-number-to-rational/PHP/convert-decimal-number-to-rational.php b/Task/Convert-decimal-number-to-rational/PHP/convert-decimal-number-to-rational.php new file mode 100644 index 0000000000..86e2f91794 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/PHP/convert-decimal-number-to-rational.php @@ -0,0 +1,32 @@ +function asRational($val, $tolerance = 1.e-6) +{ + if ($val == (int) $val) { + // integer + return $val; + } + + $h1=1; + $h2=0; + $k1=0; + $k2=1; + $b = 1 / $val; + + do { + $b = 1 / $b; + $a = floor($b); + $aux = $h1; + $h1 = $a * $h1 + $h2; + $h2 = $aux; + $aux = $k1; + $k1 = $a * $k1 + $k2; + $k2 = $aux; + $b = $b - $a; + } while (abs($val-$h1/$k1) > $val * $tolerance); + + return $h1.'/'.$k1; +} + +echo asRational(1/5)."\n"; // "1/5" +echo asRational(1/4)."\n"; // "1/4" +echo asRational(1/3)."\n"; // "1/3" +echo asRational(5)."\n"; // "5" diff --git a/Task/Convert-decimal-number-to-rational/PureBasic/convert-decimal-number-to-rational.purebasic b/Task/Convert-decimal-number-to-rational/PureBasic/convert-decimal-number-to-rational.purebasic new file mode 100644 index 0000000000..b5e552deec --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/PureBasic/convert-decimal-number-to-rational.purebasic @@ -0,0 +1,24 @@ +Procedure.i ggT(a.i, b.i) + Define t.i : If a < b : Swap a, b : EndIf + While a%b : t=a : a=b : b=t%a : Wend : ProcedureReturn b +EndProcedure + +Procedure.s Dec2Rat(dn.d) + Define nk$, gt.i, res$ + nk$=Trim(StringField(StrD(dn),2,"."),"0") + gt=ggT(Val(nk$),Int(Pow(10.0,Len(nk$)))) + res$=Str(Val(nk$)/gt)+"/"+Str(Int(Pow(10.0,Len(nk$)))/gt) + ProcedureReturn res$ +EndProcedure + +OpenConsole() +Define d.d +Repeat + Read.d d : If Not (d>0.0 And d<1.0) : Break : EndIf + Print(LSet(StrD(d),15," ")+" -> "+#TAB$+Dec2Rat(d)+#CRLF$) +ForEver +Input() : End + +DataSection + Data.d 0.9054054,0.518518,0.75,0.0 +EndDataSection 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 index af8d8c7b19..f30d48bc50 100644 --- 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 @@ -1,27 +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*/ +/*REXX pgm converts a rational fraction [n/m] or nnn.ddd to it's lowest terms*/ +numeric digits 10 /*use ten decimal digits of precision. */ +parse arg orig 1 n.1 '/' n.2; if n.2='' then n.2=1 /*get fraction. */ +if n.1='' then call er 'no argument specified.' /*tell error msg*/ + + do j=1 to 2; if \datatype(n.j,'N') then call er "argument isn't numeric:" n.j + end /*j*/ /* [↑} validate arguments: n.1 n.2 */ + +if n.2=0 then call er "divisor can't be zero." /*Whoa! Dividing by zero! */ +say 'old =' space(orig) /*display original fraction*/ +say 'new =' rat(n.1/n.2) /*display the result──►term*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +er: say; say '***error!***'; say; say arg(1); say; exit 13 +/*────────────────────────────────────────────────────────────────────────────*/ +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 display the number divided by 1*/ + return b'/'h /*display proper (or improper) fraction*/ diff --git a/Task/Conways-Game-of-Life/APL/conways-game-of-life.apl b/Task/Conways-Game-of-Life/APL/conways-game-of-life.apl new file mode 100644 index 0000000000..4608da8255 --- /dev/null +++ b/Task/Conways-Game-of-Life/APL/conways-game-of-life.apl @@ -0,0 +1,25 @@ + ∇LIFE[⎕]∇ +[0] NG←LIFE CG;W +[1] W←CG+(¯1⊖CG)+(1⊖CG)+(¯1⌽CG)+(1⌽CG) +[2] W←W+(1⊖1⌽CG)+(¯1⊖1⌽CG)+(1⊖¯1⌽CG)+(¯1⊖¯1⌽CG) +[3] NG←(3=W)+(CG∧4=W) + ∇ + RP←5 5⍴0 0 0 0 0 0 0 1 1 0 0 1 1 0 0 0 0 1 0 0 + RP +0 0 0 0 0 +0 0 1 1 0 +0 1 1 0 0 +0 0 1 0 0 +0 0 0 0 0 + LIFE RP +0 0 0 0 0 +0 1 1 1 0 +0 1 0 0 0 +0 1 1 0 0 +0 0 0 0 0 + LIFE LIFE RP +0 0 1 0 0 +0 1 1 0 0 +1 0 0 1 0 +0 1 1 0 0 +0 0 0 0 0 diff --git a/Task/Conways-Game-of-Life/ARM-Assembly/conways-game-of-life.arm b/Task/Conways-Game-of-Life/ARM-Assembly/conways-game-of-life.arm new file mode 100644 index 0000000000..e139996e39 --- /dev/null +++ b/Task/Conways-Game-of-Life/ARM-Assembly/conways-game-of-life.arm @@ -0,0 +1,96 @@ + .string "PRG" + + lcd_ptr .req r4 + active_fb .req r5 + inactive_fb .req r6 + offset_r .req r7 + backup_fb .req r8 + + @ start + push {r4-r10, r12, lr} + + ldr lcd_ptr, =0xC0000000 @ address of the LCD controller + adr offset_r, offsets + ldrh r0, [offset_r, #6] @ 0xffff is already in memory because -1 is in the offsets table + str r0, [lcd_ptr, #0x200] @ set up paletted colors: 1 is black, 0 is white + + ldr r2, [lcd_ptr, #0x18] @ load lcd configuration + bic r2, #14 + orr r2, #6 @ Set color mode to 8 bpp, paletted + str r2, [lcd_ptr, #0x18] + + ldr backup_fb, [lcd_ptr, #0x10] @ Save address of OS framebuffer + + @ allocate a buffer for game state / framebuffer + ldr r0, =153600 @ 320 * 240 * 2 + add r0, #8 + svc #5 @ malloc + push {r0} + orr inactive_fb, r0, #7 + add inactive_fb, #1 + add active_fb, inactive_fb, #76800 + + @ fill buffer with random ones and zeroes + ldr r10, =76800 + mov r9, #0 +1: subs r10, r10, #1 + strb r9, [active_fb, r10] @ zero other framebuffer + svc #206 @ rand syscall + and r0, r0, #1 + strb r0, [inactive_fb, r10] + bne 1b + + @ set first and last rows to zero + mov r2, #320 + mov r1, #0 + mov r0, inactive_fb + push {r1,r2} + svc #7 @ memset + pop {r1,r2} + ldr r3, =76480 + add r0, r0, r3 + svc #7 + + @ beginning of main loop, swap framebuffers +3: ldr r0, =76480 @ 320 * 239 + str inactive_fb, [lcd_ptr, #0x10] + mov inactive_fb, active_fb + ldr active_fb, [lcd_ptr, #0x10] + + @ per-pixel loop +2: mov r1, #16 @ 8 * 2 + mov r2, #0 + sub r0, #1 + + @ loop to count up neighboring living cells +1: subs r1, #2 + ldrsh r3, [offset_r, r1] @ cant use lsl #1 + add r3, r3, r0 + ldrb r3, [active_fb, r3] + add r2, r2, r3 + bne 1b @ at end of loop, r1 and r3 can be discarded + + @ decides whether the cell should live or die based on neighbors + ldrb r1, [active_fb, r0] + add r2, r2, r1 + teq r2, #3 + moveq r1, #1 + teqne r2, #4 + movne r1, #0 + strb r1, [inactive_fb, r0] + teq r0, #320 + bne 2b + + @ checks if the escape key is pressed + ldr r0, =0x900E001C + ldr r1, [r0] + tst r1, #0x80 + beq 3b + + str backup_fb, [lcd_ptr, #0x10] @ restores OS framebuffer + + pop {r0} + svc #6 @ free buffer + pop {r4-r10, r12, pc} +offsets: + .hword -321, -320, -319, -1, 1, 319, 320, 321 diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-1.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-1.basic new file mode 100644 index 0000000000..f28433510b --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-1.basic @@ -0,0 +1,8 @@ +# Conway's_Game_of_Life + +X = 59 : Y = 35 : H = 4 + +fastgraphics +graphsize X*H,Y*H + +dim c(X,Y) : dim cn(X,Y) : dim cl(X,Y) diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-2.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-2.basic new file mode 100644 index 0000000000..408b2663f8 --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-2.basic @@ -0,0 +1,64 @@ +# Thunderbird methuselah +c[X/2-1,Y/3+1] = 1 : c[X/2,Y/3+1] = 1 : c[X/2+1,Y/3+1] = 1 +c[X/2,Y/3+3] = 1 : c[X/2,Y/3+4] = 1 : c[X/2,Y/3+5] = 1 + +s = 0 +do + color black + rect 0,0,graphwidth,graphheight + alive = 0 : stable = 1 + s = s + 1 + for y = 0 to Y-1 + for x = 0 to X-1 + xm1 = (x-1+X)%X : xp1 = (x+1+X)%X + ym1 = (y-1+Y)%Y : yp1 = (y+1+Y)%Y + cn[x,y] = c[xm1,y] + c[xp1,y] + cn[x,y] = c[xm1,ym1] + c[x,ym1] + c[xp1,ym1] + cn[x,y] + cn[x,y] = c[xm1,yp1] + c[x,yp1] + c[xp1,yp1] + cn[x,y] + if c[x,y] = 1 then + if cn[x,y] < 2 or cn[x,y] > 3 then + cn[x,y] = 0 + else + cn[x,y] = 1 + alive = alive + 1 + end if + else + if cn[x,y] = 3 then + cn[x,y] = 1 + alive = alive + 1 + else + cn[x,y] = 0 + end if + end if + if c[x,y] then + if cn[x,y] then + if cl[x,y] then color purple # adult + if not cl[x,y] then color green # newborn + else + if cl[x,y] then color red # old + if not cl[x,y] then color yellow # shortlived + end if + rect x*H,y*H,H,H + end if + next x + next y + refresh + pause 0.06 + # Copy arrays + for i = 0 to X-1 + for j = 0 to Y-1 + if cl[i,j]<>cn[i,j] then stable = 0 + cl[i,j] = c[i,j] + c[i,j] = cn[i,j] + next j + next i +until not alive or stable + +if not alive then + print "Died in "+s+" iterations" + color black + rect 0,0,graphwidth,graphheight + refresh +else + print "Stabilized in "+(s-2)+" iterations" +end if diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-3.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-3.basic new file mode 100644 index 0000000000..9e2ac60ef1 --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-3.basic @@ -0,0 +1,35 @@ + dx% = 64 + dy% = 64 + DIM old&(dx%+1,dy%+1), new&(dx%+1,dy%+1) + VDU 23,22,dx%*4;dy%*4;16,16,16,0 + OFF + + REM Set blinker: + old&(50,50) = 1 : old&(50,51) = 1 : old&(50,52) = 1 + REM Set glider: + old&(5,7) = 1 : old&(6,7) = 1 : old&(7,7) = 1 : old&(7,6) = 1 : old&(6,5) = 1 + + REM Draw initial grid: + FOR X% = 1 TO dx% + FOR Y% = 1 TO dy% + IF old&(X%,Y%) GCOL 11 ELSE GCOL 4 + PLOT 69, X%*8-6, Y%*8-4 + NEXT + NEXT X% + + REM Run: + GCOL 4,0 + REPEAT + FOR X% = 1 TO dx% + FOR Y% = 1 TO dy% + S% = old&(X%-1,Y%) + old&(X%,Y%-1) + old&(X%-1,Y%-1) + old&(X%+1,Y%-1) + \ + \ old&(X%+1,Y%) + old&(X%,Y%+1) + old&(X%-1,Y%+1) + old&(X%+1,Y%+1) + O% = old&(X%,Y%) + N% = -(S%=3 OR (O%=1 AND S%=2)) + new&(X%,Y%) = N% + IF N%<>O% PLOT X%*8-6, Y%*8-4 + NEXT + NEXT X% + SWAP old&(), new&() + WAIT 30 + UNTIL FALSE diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-4.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-4.basic new file mode 100644 index 0000000000..d810d2e1d9 --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-4.basic @@ -0,0 +1,164 @@ +'FreeBASIC Conway's Game of Life +'May 2015 +' + grid = 300 '480 by 480 + gridy = grid + gridx = grid + pointsize = 5 'pixels + steps = 10 + +press$ = "" + + red = 4 'red is color 6 + white = 15 'color + black = 0 'color + + 'color 0 normaly is black + 'color 1 normaly is dark blue + 'color 2 normaly is green + bot = 35 'this is 35 lines from the top of the page + dim old( grid + 10, grid +10), new( grid +10, grid +10) + +'Set blinker: + ' old( 160, 160) =1: old( 160, 170) =1 : old( 160, 180) =1 + +'Set blinker: + ' old( 160, 20) =1: old( 160, 30) =1 : old( 160, 40) =1 + +'Set blinker: + ' old( 20, 20) =1: old( 20, 30) =1 : old( 20, 40) =1 + +'Set glider: + ' old( 50, 70) =1: old( 60, 70) =1: old( 70, 70) =1 + ' old( 70, 60) =1: old( 60, 50) =1 + +' http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life +' Thunderbird methuselah +'X = 59 : Y = 35 : H = 4 +'c[X/2-1,Y/3+1] = 1 : c[X/2,Y/3+1] = 1 : c[X/2+1,Y/3+1] = 1 +'c[X/2,Y/3+3] = 1 : c[X/2,Y/3+4] = 1 : c[X/2,Y/3+5] = 1 + +'xb = 59 : yb = 35 +' old( Xb/2-1,Yb/3+1) =1: old(Xb/2,Yb/3+1) =1: old(Xb/2+1,Yb/3+1) =1 +' old( Xb/2,Yb/3+3) =1: old(Xb/2,Yb/3+4) =1 :old(Xb/2,Yb/3+5) = 1 +'r-pentomino +' old( 150,140) =1: old( 160,140) =1 +' old( 140,150) =1 :old( 150,150) =1 +' old( 150,160) =1 + +'Die Hard around 150 generations +' old( 150,140) =1: old(160,140) =1 : old(160,150) =1 +' old( 200,150) =1: old(210,150) =1 : old(210,130) = 1 : old(220,150) = 1 + +'Acorn around 450 generations +' it looks like this: +' 0X +' 000X +' XX00XXX + old( 180,200) =1 + old( 200,210) =1 + old( 170,220) =1 :old( 180,220) =1 : old( 210,220) =1 : old( 220,220) =1 : old( + +230,220) =1 + +Screen 20 'Resolution 800x600 with at least 256 colors + +color white +line (10,10)-(gridx,gridy),,B 'box from top left to bottom right + +Locate bot, 1 'Use a standard place on the bottom of the page +color white +print " Welcome to Conway's Game of Life" +Print " Using a consrained playing field (300x300), the Acorn seed runs" +print " for about 450 generations before it becomes stable (or stale)." +print " Enter any key to start" +beep +sleep + +Do ' flush the key input buffer + press$ = Inkey +Loop Until press$ = "" +print " " + +'Draw initial grid + for x = 10 to gridX step steps + for y = 10 to gridY step steps + color white 'old(x,y) + if old(x,y) = 1 then circle (x, y), pointsize,,,,, F + next y + next x +' +Locate bot, 1 +color white +print " Welcome to Conway's Game of Life" +Print " Using a consrained playing field, the Acorn seed runs for " +print " about 450 generations before it becomes stable (or stale)." +color red +print " Enter spacebar to continue or pause, ESC to stop" +sleep +' +Do ' flush the key input buffer + press$ = Inkey +Loop Until press$ = "" + + do + press$ = INKEY + gen = gen + 1 + locate bot+5,1 + color white + print " Gen = "; gen + for x = 10 to gridX step steps + for y = 10 to gridY step steps + 'find number of live Moore neighbours + neighbours = old( x - steps, y - steps) +old( x , y - steps) + neighbours = neighbours + old( x + steps, y -steps) + neighbours = neighbours + old( x - steps, y) + old( x + steps, y) + neighbours = neighbours + old( x - steps, y + steps) + neighbours = neighbours + old( x, y + steps) +old( x + steps, y + steps) + was =old( x, y) + if was =0 then + if neighbours =3 then N =1 else N =0 + else + if neighbours =3 or neighbours =2 then N =1 else N =0 + end if + new( x, y) = N + if n = 2 then color white + if n = 1 then color red + if n = 0 then color black + circle (x, y), pointsize,,,,, F + if press$ = CHR$(27) goto 10 + if press$ = " " then + sleep + Do ' flush the key input buffer + press$ = Inkey + Loop Until press$ = "" + press$ = INKEY + endif + next y + next x +color white +line (10,10)-(gridx,gridy),,B 'box from top left to bottom right +locate bot,1 +' +'t = timer +'do +'loop until timer > t + .2 + +sleep 70 ' might not be slow enough +' + for x =10 to gridX step steps + for y =10 to gridY step steps + old( x, y) =new( x, y) + next y + next x + +LOOP ' UNTIL press$ = CHR$(27) 'return to do loop up top until "esc" key is pressed. + +10 +color white +locate bot+3,1 +print " " 'clear instructions +locate bot+6,1 +Print " Press any key to exit " +sleep +End diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-5.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-5.basic new file mode 100644 index 0000000000..e1f236d310 --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-5.basic @@ -0,0 +1,68 @@ + nomainwin + + gridX = 20 + gridY = gridX + + mult =500 /gridX + pointSize =360 /gridX + + dim old( gridX +1, gridY +1), new( gridX +1, gridY +1) + +'Set blinker: + old( 16, 16) =1: old( 16, 17) =1 : old( 16, 18) =1 + +'Set glider: + old( 5, 7) =1: old( 6, 7) =1: old( 7, 7) =1 + old( 7, 6) =1: old( 6, 5) =1 + + WindowWidth =570 + WindowHeight =600 + + open "Conway's 'Game of Life'." for graphics_nsb_nf as #w + + #w "trapclose [quit]" + #w "down ; size "; pointSize + #w "fill black" + +'Draw initial grid + for x = 1 to gridX + for y = 1 to gridY + '#w "color "; int( old( x, y) *256); " 0 255" + if old( x, y) <>0 then #w "color red" else #w "color darkgray" + #w "set "; x *mult +20; " "; y *mult +20 + next y + next x +' ______________________________________________________________________________ +'Run + do + for x =1 to gridX + for y =1 to gridY + 'find number of live Moore neighbours + neighbours =old( x -1, y -1) +old( x, y -1) +old( x +1, y -1)+_ + old( x -1, y) +old( x +1, y )+_ + old( x -1, y +1) +old( x, y +1) +old( x +1, y +1) + was =old( x, y) + if was =0 then + if neighbours =3 then N =1 else N =0 + else + if neighbours =3 or neighbours =2 then N =1 else N =0 + end if + new( x, y) = N + '#w "color "; int( N /8 *256); " 0 255" + if N <>0 then #w "color red" else #w "color darkgray" + #w "set "; x *mult +20; " "; y *mult +20 + next y + next x + scan +'swap + for x =1 to gridX + for y =1 to gridY + old( x, y) =new( x, y) + next y + next x +'Re-run until interrupted... + loop until FALSE +'User shutdown received + [quit] + close #w + end diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-6.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-6.basic new file mode 100644 index 0000000000..3cbea8d8cb --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-6.basic @@ -0,0 +1,56 @@ +EnableExplicit +Define.i x, y ,Xmax ,Ymax ,N +Xmax = 13 : Ymax = 20 +Dim world.i(Xmax+1,Ymax+1) +Dim Nextworld.i(Xmax+1,Ymax+1) + +; Glider test +;------------------------------------------ + world(1,1)=1 : world(1,2)=0 : world(1,3)=0 + world(2,1)=0 : world(2,2)=1 : world(2,3)=1 + world(3,1)=1 : world(3,2)=1 : world(3,3)=0 +;------------------------------------------ + +OpenConsole() +EnableGraphicalConsole(1) +ClearConsole() +Print("Press any key to interrupt") +Repeat + ConsoleLocate(0,2) + PrintN(LSet("", Xmax+2, "-")) + ;---------- endless world --------- + For y = 1 To Ymax + world(0,y)=world(Xmax,y) + world(Xmax+1,y)=world(1,y) + Next + For x = 1 To Xmax + world(x,0)=world(x,Ymax) + world(x,Ymax+1)=world(x,1) + Next + world(0 ,0 )=world(Xmax,Ymax) + world(Xmax+1,Ymax+1)=world(1 ,1 ) + world(Xmax+1,0 )=world(1 ,Ymax) + world( 0,Ymax+1)=world(Xmax,1 ) + ;---------- endless world --------- + For y = 1 To Ymax + Print("|") + For x = 1 To Xmax + Print(Chr(32+world(x,y)*3)) + N = world(x-1,y-1)+world(x-1,y)+world(x-1,y+1)+world(x,y-1) + N + world(x,y+1)+world(x+1,y-1)+world(x+1,y)+world(x+1,y+1) + If (world(x,y) And (N = 2 Or N = 3))Or (world(x,y)=0 And N = 3) + Nextworld(x,y)=1 + Else + Nextworld(x,y)=0 + EndIf + Next + PrintN("|") + Next + PrintN(LSet("", Xmax+2, "-")) + Delay(100) + ;Swap world() , Nextworld() ;PB <4.50 + CopyArray(Nextworld(), world());PB =>4.50 + Dim Nextworld.i(Xmax+1,Ymax+1) +Until Inkey() <> "" + +PrintN("Press any key to exit"): Repeat: Until Inkey() <> "" diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-7.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-7.basic new file mode 100644 index 0000000000..00c941336f --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-7.basic @@ -0,0 +1,21 @@ + PROGRAM:CONWAY +:While 1 +:For(X,2,9,1) +:For(Y,2,17,1) +:If [A](Y,X) +:Then +:Output(X-1,Y-1,"X") +:Else +:Output(X-1,Y-1," ") +:End +:[A](Y-1,X-1)+[A](Y,X-1)+[A](Y+1,X-1)+[A](Y-1,X)+[A](Y+1,X)+[A](Y-1,X+1)+[A](Y,X+1)+[A](Y+1,X+1)→N +:If ([A](Y,X) and (N=2 or N=3)) or (not([A](Y,X)) and N=3) +:Then +:1→[B](Y,X) +:Else +:0→[B](Y,X) +:End +:End +:End +:[B]→[A] +:End diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-8.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-8.basic new file mode 100644 index 0000000000..b6f27a46b2 --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-8.basic @@ -0,0 +1,6 @@ +PROGRAM:PIC2LIFE +:For(I,0,17,1) +:For(J,0,9,1) +:pxl-Test(J,I)→[A](I+1,J+1) +:End +:End diff --git a/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-9.basic b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-9.basic new file mode 100644 index 0000000000..3e6839ffc6 --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC/conways-game-of-life-9.basic @@ -0,0 +1,76 @@ +Define life(pattern) = Prgm + Local x,y,nt,count,save,xl,yl,xh,yh + Define nt(y,x) = when(pxlTest(y,x), 1, 0) + + {}→save + setGraph("Axes", "Off")→save[1] + setGraph("Grid", "Off")→save[2] + setGraph("Labels", "Off")→save[3] + FnOff + PlotOff + ClrDraw + + If pattern = "blinker" Then + 36→yl + 40→yh + 78→xl + 82→xh + PxlOn 36,80 + PxlOn 38,80 + PxlOn 40,80 + ElseIf pattern = "glider" Then + 30→yl + 40→yh + 76→xl + 88→xh + PxlOn 38,76 + PxlOn 36,78 + PxlOn 36,80 + PxlOn 38,80 + PxlOn 40,80 + ElseIf pattern = "r" Then + 38-5*2→yl + 38+5*2→yh + 80-5*2→xl + 80+5*2→xh + PxlOn 38,78 + PxlOn 36,82 + PxlOn 36,80 + PxlOn 38,80 + PxlOn 40,80 + EndIf + + While getKey() = 0 + © Expand upper-left corner to whole cell + For y,yl,yh,2 + For x,xl,xh,2 + If pxlTest(y,x) Then + PxlOn y+1,x + PxlOn y+1,x+1 + PxlOn y, x+1 + Else + PxlOff y+1,x + PxlOff y+1,x+1 + PxlOff y, x+1 + EndIf + EndFor + EndFor + + © Compute next generation + For y,yl,yh,2 + For x,xl,xh,2 + nt(y-1,x-1) + nt(y-1,x) + nt(y-1,x+2) + nt(y,x-1) + nt(y+1,x+2) + nt(y+2,x-1) + nt(y+2,x+1) + nt(y+2,x+2) → count + If count = 3 Then + PxlOn y,x + ElseIf count ≠ 2 Then + PxlOff y,x + EndIf + EndFor + EndFor + EndWhile + + © Restore changed options + setGraph("Axes", save[1]) + setGraph("Grid", save[2]) + setGraph("Labels", save[3]) +EndPrgm diff --git a/Task/Conways-Game-of-Life/C++/conways-game-of-life.cpp b/Task/Conways-Game-of-Life/C++/conways-game-of-life.cpp index f57130d334..35c53aa600 100644 --- a/Task/Conways-Game-of-Life/C++/conways-game-of-life.cpp +++ b/Task/Conways-Game-of-Life/C++/conways-game-of-life.cpp @@ -1,204 +1,186 @@ +#include +#include #include -#define HEIGHT 4 -#define WIDTH 4 +#include -struct Shape { -public: - char xCoord; - char yCoord; - char height; - char width; - char **figure; -}; - -struct Glider : public Shape { - static const char GLIDER_SIZE = 3; - Glider( char x , char y ); - ~Glider(); -}; +typedef unsigned char byte; -struct Blinker : public Shape { - static const char BLINKER_HEIGHT = 3; - static const char BLINKER_WIDTH = 1; - Blinker( char x , char y ); - ~Blinker(); -}; - -class GameOfLife { +class world { public: - GameOfLife( Shape sh ); - void print(); - void update(); - char getState( char state , char xCoord , char yCoord , bool toggle); - void iterate(unsigned int iterations); + world( int x, int y ) : _wid( x ), _hei( y ) { + int s = _wid * _hei * sizeof( byte ); + _cells = new byte[s]; + memset( _cells, 0, s ); + } + ~world() { + delete [] _cells; + } + int wid() const { + return _wid; + } + int hei() const { + return _hei; + } + byte at( int x, int y ) const { + return _cells[x + y * _wid]; + } + void set( int x, int y, byte c ) { + _cells[x + y * _wid] = c; + } + void swap( world* w ) { + memcpy( _cells, w->_cells, _wid * _hei * sizeof( byte ) ); + } private: - char world[HEIGHT][WIDTH]; - char otherWorld[HEIGHT][WIDTH]; - bool toggle; - Shape shape; + int _wid, _hei; + byte* _cells; }; - -GameOfLife::GameOfLife( Shape sh ) : - shape(sh) , - toggle(true) -{ - for ( char i = 0; i < HEIGHT; i++ ) { - for ( char j = 0; j < WIDTH; j++ ) { - world[i][j] = '.'; - } +class rule { +public: + rule( world* w ) : wrd( w ) { + wid = wrd->wid(); + hei = wrd->hei(); + wrdT = new world( wid, hei ); } - for ( char i = shape.yCoord; i - shape.yCoord < shape.height; i++ ) { - for ( char j = shape.xCoord; j - shape.xCoord < shape.width; j++ ) { - if ( i < HEIGHT && j < WIDTH ) { - world[i][j] = - shape.figure[ i - shape.yCoord ][j - shape.xCoord ]; - } - } + ~rule() { + if( wrdT ) delete wrdT; } -} - -void GameOfLife::print() { - if ( toggle ) { - for ( char i = 0; i < HEIGHT; i++ ) { - for ( char j = 0; j < WIDTH; j++ ) { - std::cout << world[i][j]; - } - std::cout << std::endl; - } - } else { - for ( char i = 0; i < HEIGHT; i++ ) { - for ( char j = 0; j < WIDTH; j++ ) { - std::cout << otherWorld[i][j]; - } - std::cout << std::endl; - } + bool hasLivingCells() { + for( int y = 0; y < hei; y++ ) + for( int x = 0; x < wid; x++ ) + if( wrd->at( x, y ) ) return true; + std::cout << "*** All cells are dead!!! ***\n\n"; + return false; } - for ( char i = 0; i < WIDTH; i++ ) { - std::cout << '='; + void swapWrds() { + wrd->swap( wrdT ); } - std::cout << std::endl; -} - -void GameOfLife::update() { - if (toggle) { - for ( char i = 0; i < HEIGHT; i++ ) { - for ( char j = 0; j < WIDTH; j++ ) { - otherWorld[i][j] = - GameOfLife::getState(world[i][j] , i , j , toggle); - } - } - toggle = !toggle; - } else { - for ( char i = 0; i < HEIGHT; i++ ) { - for ( char j = 0; j < WIDTH; j++ ) { - world[i][j] = - GameOfLife::getState(otherWorld[i][j] , i , j , toggle); - } - } - toggle = !toggle; + void setRuleB( std::vector& birth ) { + _birth = birth; } -} - -char GameOfLife::getState( char state, char yCoord, char xCoord, bool toggle ) { - char neighbors = 0; - if ( toggle ) { - for ( char i = yCoord - 1; i <= yCoord + 1; i++ ) { - for ( char j = xCoord - 1; j <= xCoord + 1; j++ ) { - if ( i == yCoord && j == xCoord ) { - continue; - } - if ( i > -1 && i < HEIGHT && j > -1 && j < WIDTH ) { - if ( world[i][j] == 'X' ) { - neighbors++; - } + void setRuleS( std::vector& stay ) { + _stay = stay; + } + void applyRules() { + int n; + for( int y = 0; y < hei; y++ ) { + for( int x = 0; x < wid; x++ ) { + n = neighbours( x, y ); + if( wrd->at( x, y ) ) { + wrdT->set( x, y, inStay( n ) ? 1 : 0 ); + } else { + wrdT->set( x, y, inBirth( n ) ? 1 : 0 ); } } } - } else { - for ( char i = yCoord - 1; i <= yCoord + 1; i++ ) { - for ( char j = xCoord - 1; j <= xCoord + 1; j++ ) { - if ( i == yCoord && j == xCoord ) { - continue; - } - if ( i > -1 && i < HEIGHT && j > -1 && j < WIDTH ) { - if ( otherWorld[i][j] == 'X' ) { - neighbors++; - } - } + } +private: + int neighbours( int xx, int yy ) { + int n = 0, nx, ny; + for( int y = -1; y < 2; y++ ) { + for( int x = -1; x < 2; x++ ) { + if( !x && !y ) continue; + nx = ( wid + xx + x ) % wid; + ny = ( hei + yy + y ) % hei; + n += wrd->at( nx, ny ) > 0 ? 1 : 0; } } + return n; } - if (state == 'X') { - return ( neighbors > 1 && neighbors < 4 ) ? 'X' : '.'; + bool inStay( int n ) { + return( _stay.end() != find( _stay.begin(), _stay.end(), n ) ); } - else { - return ( neighbors == 3 ) ? 'X' : '.'; + bool inBirth( int n ) { + return( _birth.end() != find( _birth.begin(), _birth.end(), n ) ); } -} - -void GameOfLife::iterate( unsigned int iterations ) { - for ( int i = 0; i < iterations; i++ ) { - print(); - update(); + int wid, hei; + world *wrd, *wrdT; + std::vector _stay, _birth; +}; +class cellular { +public: + cellular( int w, int h ) : rl( 0 ) { + wrd = new world( w, h ); } -} - -Glider::Glider( char x , char y ) { - xCoord = x; - yCoord = y; - height = GLIDER_SIZE; - width = GLIDER_SIZE; - figure = new char*[GLIDER_SIZE]; - for ( char i = 0; i < GLIDER_SIZE; i++ ) { - figure[i] = new char[GLIDER_SIZE]; - } - for ( char i = 0; i < GLIDER_SIZE; i++ ) { - for ( char j = 0; j < GLIDER_SIZE; j++ ) { - figure[i][j] = '.'; - } + ~cellular() { + if( rl ) delete rl; + delete wrd; } - figure[0][1] = 'X'; - figure[1][2] = 'X'; - figure[2][0] = 'X'; - figure[2][1] = 'X'; - figure[2][2] = 'X'; -} + void start( int r ) { + rl = new rule( wrd ); + gen = 1; + std::vector t; + switch( r ) { + case 1: // conway + t.push_back( 2 ); t.push_back( 3 ); rl->setRuleS( t ); + t.clear(); t.push_back( 3 ); rl->setRuleB( t ); + break; + case 2: // amoeba + t.push_back( 1 ); t.push_back( 3 ); t.push_back( 5 ); t.push_back( 8 ); rl->setRuleS( t ); + t.clear(); t.push_back( 3 ); t.push_back( 5 ); t.push_back( 7 ); rl->setRuleB( t ); + break; + case 3: // life34 + t.push_back( 3 ); t.push_back( 4 ); rl->setRuleS( t ); + rl->setRuleB( t ); + break; + case 4: // maze + t.push_back( 1 ); t.push_back( 2 ); t.push_back( 3 ); t.push_back( 4 ); t.push_back( 5 ); rl->setRuleS( t ); + t.clear(); t.push_back( 3 ); rl->setRuleB( t ); + break; + } -Glider::~Glider() { - for ( char i = 0; i < GLIDER_SIZE; i++ ) { - delete[] figure[i]; + /* just for test - shoud read from a file */ + /* GLIDER */ + wrd->set( 6, 1, 1 ); wrd->set( 7, 2, 1 ); + wrd->set( 5, 3, 1 ); wrd->set( 6, 3, 1 ); + wrd->set( 7, 3, 1 ); + /* BLINKER */ + wrd->set( 1, 3, 1 ); wrd->set( 2, 3, 1 ); + wrd->set( 3, 3, 1 ); + /******************************************/ + generation(); } - delete[] figure; -} - -Blinker::Blinker( char x , char y ) { - xCoord = x; - yCoord = y; - height = BLINKER_HEIGHT; - width = BLINKER_WIDTH; - figure = new char*[BLINKER_HEIGHT]; - for ( char i = 0; i < BLINKER_HEIGHT; i++ ) { - figure[i] = new char[BLINKER_WIDTH]; - } - for ( char i = 0; i < BLINKER_HEIGHT; i++ ) { - for ( char j = 0; j < BLINKER_WIDTH; j++ ) { - figure[i][j] = 'X'; +private: + void display() { + system( "cls" ); + int wid = wrd->wid(), + hei = wrd->hei(); + std::cout << "+" << std::string( wid, '-' ) << "+\n"; + for( int y = 0; y < hei; y++ ) { + std::cout << "|"; + for( int x = 0; x < wid; x++ ) { + if( wrd->at( x, y ) ) std::cout << "#"; + else std::cout << "."; + } + std::cout << "|\n"; } + std::cout << "+" << std::string( wid, '-' ) << "+\n"; + std::cout << "Generation: " << gen << "\n\nPress [RETURN] for the next generation..."; + std::cin.get(); } -} - -Blinker::~Blinker() { - for ( char i = 0; i < BLINKER_HEIGHT; i++ ) { - delete[] figure[i]; + void generation() { + do { + display(); + rl->applyRules(); + rl->swapWrds(); + gen++; + } + while ( rl->hasLivingCells() ); } - delete[] figure; -} + rule* rl; + world* wrd; + int gen; +}; -int main() { - Glider glider(0,0); - GameOfLife gol(glider); - gol.iterate(5); - Blinker blinker(1,0); - GameOfLife gol2(blinker); - gol2.iterate(4); +int main( int argc, char* argv[] ) { + cellular c( 20, 12 ); + std::cout << "\n\t*** CELLULAR AUTOMATA ***" << "\n\n Which one you want to run?\n\n\n"; + std::cout << " [1]\tConway's Life\n [2]\tAmoeba\n [3]\tLife 34\n [4]\tMaze\n\n > "; + int o; + do { + std::cin >> o; + } + while( o < 1 || o > 4 ); + std::cin.ignore(); + c.start( o ); + return system( "pause" ); } diff --git a/Task/Conways-Game-of-Life/Chapel/conways-game-of-life.chapel b/Task/Conways-Game-of-Life/Chapel/conways-game-of-life.chapel new file mode 100644 index 0000000000..2a26b5bc69 --- /dev/null +++ b/Task/Conways-Game-of-Life/Chapel/conways-game-of-life.chapel @@ -0,0 +1,66 @@ +config const gridHeight: int = 3; +config const gridWidth: int = 3; + +enum State { dead = 0, alive = 1 }; + +class ConwaysGameofLife { + + var gridDomain: domain(2); + var computeDomain: subdomain( gridDomain ); + var grid: [gridDomain] int; + + proc ConwaysGameofLife( height: int, width: int ) { + this.gridDomain = {0..#height+2, 0..#width+2}; + this.computeDomain = this.gridDomain.expand( -1 ); + } + + proc step(){ + + var tempGrid: [this.computeDomain] State; + forall (i,j) in this.computeDomain { + var isAlive = this.grid[i,j] == State.alive; + var numAlive = (+ reduce this.grid[ i-1..i+1, j-1..j+1 ]) - if isAlive then 1 else 0; + tempGrid[i,j] = if ( (2 == numAlive && isAlive) || numAlive == 3 ) then State.alive else State.dead ; + } + + this.grid[this.computeDomain] = tempGrid; + + } + + proc this( i: int, j: int ) ref : State { + return this.grid[i,j]; + } + + proc prettyPrint(): string { + var str: string; + for i in this.gridDomain.dim(1) { + if i == 0 || i == gridDomain.dim(1).last { + for j in this.gridDomain.dim(2) { + str += "-"; + } + } else { + for j in this.gridDomain.dim(2) { + if j == 0 || j == this.gridDomain.dim(2).last { + str += "|"; + } else { + str += if this.grid[i,j] == State.alive then "#" else " "; + } + } + } + str += "\n"; + } + return str; + } + +} + +proc main{ + var game = new ConwaysGameofLife( gridHeight, gridWidth ); + game[gridHeight/2 + 1, gridWidth/2 ] = State.alive; + game[gridHeight/2 + 1, gridWidth/2 + 1 ] = State.alive; + game[gridHeight/2 + 1, gridWidth/2 + 2 ] = State.alive; + for i in 1..3 { + writeln( game.prettyPrint() ); + game.step(); + } +} diff --git a/Task/Conways-Game-of-Life/Groovy/conways-game-of-life.groovy b/Task/Conways-Game-of-Life/Groovy/conways-game-of-life.groovy new file mode 100644 index 0000000000..1a726c75db --- /dev/null +++ b/Task/Conways-Game-of-Life/Groovy/conways-game-of-life.groovy @@ -0,0 +1,104 @@ +class GameOfLife { + + int generations + int dimensions + def board + + GameOfLife(generations = 5, dimensions = 5) { + this.generations = generations + this.dimensions = dimensions + this.board = createBlinkerBoard() + } + + static def createBlinkerBoard() { + [ + [].withDefault{0}, + [0,0,1].withDefault{0}, + [0,0,1].withDefault{0}, + [0,0,1].withDefault{0} + ].withDefault{[]} + } + + static def createGliderBoard() { + [ + [].withDefault{0}, + [0,0,1].withDefault{0}, + [0,0,0,1].withDefault{0}, + [0,1,1,1].withDefault{0} + ].withDefault{[]} + } + + static def getValue(board, point) { + def x,y + (x,y) = point + if(x < 0 || y < 0) { + return 0 + } + board[x][y] ? 1 : 0 + } + + static def countNeighbors(board, point) { + def x,y + (x,y) = point + def neighbors = 0 + neighbors += getValue(board, [x-1,y-1]) + neighbors += getValue(board, [x-1,y]) + neighbors += getValue(board, [x-1,y+1]) + neighbors += getValue(board, [x,y-1]) + neighbors += getValue(board, [x,y+1]) + neighbors += getValue(board, [x+1,y-1]) + neighbors += getValue(board, [x+1,y]) + neighbors += getValue(board, [x+1,y+1]) + neighbors + } + + static def conwaysRule(currentValue, neighbors) { + def newValue = 0 + if(neighbors == 3 || (currentValue && neighbors == 2)) { + newValue = 1 + } + newValue + } + + static def createNextGeneration(currentBoard, dimensions) { + def newBoard = [].withDefault{[].withDefault{0}} + (0..(dimensions-1)).each { row -> + (0..(dimensions-1)).each { column -> + def point = [row, column] + def currentValue = getValue(currentBoard, point) + def neighbors = countNeighbors(currentBoard, point) + newBoard[row][column] = conwaysRule(currentValue, neighbors) + } + } + newBoard + } + + static def printBoard(generationCount, board, dimensions) { + println "Generation ${generationCount}" + println '*' * 80 + (0..(dimensions-1)).each { row -> + (0..(dimensions-1)).each { column -> + print board[row][column] ? 'X' : '.' + } + print System.getProperty('line.separator') + } + println '' + } + + def start() { + (1..generations).each { generation -> + printBoard(generation, this.board, this.dimensions) + this.board = createNextGeneration(this.board, this.dimensions) + } + } + +} + +// Blinker +def game = new GameOfLife() +game.start() + +// Glider +game = new GameOfLife(10, 10) +game.board = game.createGliderBoard() +game.start() diff --git a/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j b/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j index 0e8a5d3e72..a2e9763af1 100644 --- a/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j +++ b/Task/Conways-Game-of-Life/J/conways-game-of-life-1.j @@ -1,4 +1,4 @@ pad=: 0,0,~0,.0,.~] -life=: (_3 _3 (+/ e. 3+0,4&{)@,;._3 ])@pad +life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@pad NB. the above could also be a one-line solution: -life=: (_3 _3 (+/ e. 3+0,4&{)@,;._3 ])@(0,0,~0,.0,.~]) +life=: (3 3 (+/ e. 3+0,4&{)@,;._3 ])@(0,0,~0,.0,.~]) diff --git a/Task/Conways-Game-of-Life/J/conways-game-of-life-3.j b/Task/Conways-Game-of-Life/J/conways-game-of-life-3.j new file mode 100644 index 0000000000..5a1a22d240 --- /dev/null +++ b/Task/Conways-Game-of-Life/J/conways-game-of-life-3.j @@ -0,0 +1 @@ + blocks=: (2 2$2) ((7 u:' ▗▖▄▝▐▞▟▘▚▌▙▀▜▛█') {~ #.@,);._3 >.&.-:@$ {. ] diff --git a/Task/Conways-Game-of-Life/JavaScript/conways-game-of-life-3.js b/Task/Conways-Game-of-Life/JavaScript/conways-game-of-life-3.js new file mode 100644 index 0000000000..808ae87aab --- /dev/null +++ b/Task/Conways-Game-of-Life/JavaScript/conways-game-of-life-3.js @@ -0,0 +1,41 @@ +const _ = require('lodash'); + +/////////////////// +// LODASH IMPORT // +/////////////////// + +// import all lodash functions to the main namespace, but isNaN not to cause conflicts +_.each(_.keys(_), k => global[k === 'isNaN' ? '_isNaN' : k] = _[k]); + +/////////////// +// FUNCTIONS // +/////////////// +const WORLD_WIDTH = 3, + WORLD_HEIGHT = 3, + displayWorld = (world) => console.log(map(world, x => x.join(' ')).join('\n') + '\n'), + + aliveNeighbours = (world, x, y) => chain(range(-1, 2)) + .reduce((acc, i) => acc.concat(map(range(-1, 2), ii => [i, ii])), []) + .reject(partial(isEqual, [0, 0])) + .map(i => { + try { + return world[x + i[0]][y + i[1]]; + } catch (err) { + return null; + } + }) + .compact() + .value() + .length, + + isAlive = (cell, numAliveNeighbours) => (cell === 1 && inRange(numAliveNeighbours, 2, 4)) || (cell === 0 && numAliveNeighbours === 3) ? 1 : 0, + updateWorld = (world) => map(world, (row, rowidx) => map(row, (cell, colidx) => isAlive(cell, aliveNeighbours(world, rowidx, colidx)))); + + +// let world = map(range(WORLD_WIDTH), partial(ary(map, 2), range(WORLD_HEIGHT), partial(random, 0, 1, false))); +let world = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]; + +setInterval(() => { + world = updateWorld(world) + displayWorld(world); +}, 1000); diff --git a/Task/Conways-Game-of-Life/REXX/conways-game-of-life-1.rexx b/Task/Conways-Game-of-Life/REXX/conways-game-of-life-1.rexx index 664cc119d2..d912bc3d5f 100644 --- a/Task/Conways-Game-of-Life/REXX/conways-game-of-life-1.rexx +++ b/Task/Conways-Game-of-Life/REXX/conways-game-of-life-1.rexx @@ -1,53 +1,48 @@ /*REXX program displays Conway's game of life, it stops after N repeats.*/ signal on halt /*handle cell growth interruptus.*/ -parse arg peeps '(' generations rows cols bare! life! clearScreen repeats - blank = 'BLANK' /*the "name" for blank*/ -generations = p(generations 100) /*#generations allowed*/ - rows = p(rows 3) /*number of cell rows.*/ - cols = p(cols 3) /* " " " cols.*/ - bare! = pickChar(bare! blank) /*an empty cell thingy*/ -clearScreen = p(clearScreen 0) /*1 = clear the screen*/ - life! = pickChar(life! '☼') /*looks like an ameba.*/ - repeats = p(repeats 2) /*stop if 2 repeats.*/ -fents=max(linesize()-1,cols) /*fence width shown after display*/ -#repeats=0; $.=bare! /*the universe is new, and barren*/ +parse arg peeps '(' rows cols empty life! clearScreen repeats generations + rows = p(rows 3) /*the maximum number of cell rows*/ + cols = p(cols 3) /* " " " " " cols*/ + emp = pickChar(empty 'blank') /*an empty cell character (glyph)*/ + clearScr = p(clearScreen 0) /*1 indicates to clear the screen*/ +clearscr=1 +clearscr=0 + life! = pickChar(life! '☼') /*the gylph looks like an ameba. */ + reps = p(repeats 2) /*stop if there are 2 repeats.*/ +generations = p(generations 100) /*number of generations allowed. */ +usw=max(linesize()-1,cols) /*usable screen width for display*/ +#reps=0; $.=emp /*the universe is new, and barren*/ gens=abs(generations) /*use this for convenience. */ -x=space(peeps) /*remove superfluous spaces. */ -if x=='' then x='2,1 2,2 2,3' /* [↓] process the cells given.*/ - do while x\==''; parse var x _ x; parse var _ r ',' c . - $.r.c=life!; rows=max(rows,r); cols=max(cols,c) - end /*while*/ -life=0; !.=0; call showCells /*show initial state of the cells*/ -/*─────────────────────────────────────watch cell colony grow/live/die. */ - do life=1 for gens; @.=bare! - do r=1 for rows - do c=1 for cols; ??=$.r.c; n=neighbors() - if ??==bare! then do; if n==3 then ??=life!; end - else if n<2 | n>3 then ??=bare! - @.r.c=?? - end /*c*/ - end /*r*/ - call assign$ /*assign alternate cells ──► real*/ - if generations>0 | life==gens then call showCells - end /*life*/ -/*─────────────────────────────────────stop watching the universe (life)*/ -halt: cycles=life-1; if cycles\==gens then say 'REXX program interrupted.' -exit /*stick a fork in it, we're done.*/ +x=space(peeps); upper x /*elide superfluous spaces; upper*/ +if x=='' then x='BLINKER' /*if none specified, use BLINKER.*/ +if x=='BLINKER' then x='2,1 2,2 2,3' +if x=='GLIDER' then x='48,11 48,12 48,13 49,13 50,12' +if x=='OCTAGON' then x='1,5 1,6 2,4 2,7 3,3 3,8 4,2 4,9 5,2 5,9 6,3 6,8 7,4 7,7 8,5 8,6' +call assign. /*assign the initial state cells.*/ +call showCells /*show initial state of the cells*/ + /* [↓] cell colony grow/live/die*/ + do life=1 for gens; call assign@ /*construct the next generation. */ + if generations>0 | life==gens then call showCells /*display it?*/ + end /*life*/ +fin: exit /*stick a fork in it, we're done.*/ /*───────────────────────────────SHOWCELLS subroutine───────────────────*/ -showCells: if clearScreen then 'CLS' /* ◄─── change this for your OS.*/ +showCells: if clearScr then 'CLS' /* ◄─── change this for your OS.*/ call showRows /*show the rows in proper order. */ -say right(copies('═',fents)life,fents) /*show&tell for a bunch of cells.*/ -if _=='' then exit /*if no life, then stop the run. */ -if !._ then #repeats=#repeats+1 /*we detected a repeated pattern.*/ +say right(copies('▒',usw) life,usw) /*show fence between generations.*/ +if _=='' then call fin /*if no life, then stop the run.*/ +if !._ then #reps=#reps+1 /*we detected a repeated pattern.*/ !._=1 /*existence state & compare later*/ -if repeats\==0 & #repeats<=repeats then return /*so far, so good.*/ -say '"Life" repeated itself' repeats "times, program is stopping." -exit /*stick a fork in it, we're done.*/ +if reps\==0 & #reps<=reps then return /*so far, so good regarding reps.*/ +say; say ' "Life" repeated itself' reps "times, simulation has ended." +call fin /*stick a fork in it, we're done.*/ /*───────────────────────────────1─liner subroutines───────────────────────────────────────────────────────────────────────*/ -$: parse arg _row,_col; return $._row._col==life! -assign$: do r=1 for rows; do c=1 for cols; $.r.c=@.r.c; end; end; return -err: say;say;say center(' error! ',max(40,linesize()%2),"*");say;do j=1 for arg();say arg(j);say;end;say;exit 13 -neighbors: return $(r-1,c-1)+$(r-1,c)+$(r-1,c+1)+$(r,c-1)+$(r,c+1)+$(r+1,c-1)+$(r+1,c)+$(r+1,c+1) +$: parse arg _row,_col; return $._row._col==life! +assign$: do r=1 for rows; do c=1 for cols; $.r.c=@.r.c; end; end; return +assign.: do while x\==''; parse var x r ',' c x; $.r.c=life!; rows=max(rows,r); cols=max(cols,c); end; life=0; !.=0; return +assign?: ?=$.r.c; n=neighbors(); if ?==emp then do;if n==3 then ?=life!; end; else if n<2 | n>3 then ?=emp; @.r.c=?; return +assign@: @.=emp; do r=1 for rows; do c=1 for cols; call assign?; end; end; call assign$; return +halt: say; say 'REXX program halted.'; say; exit 0 +neighbors: rm=r-1; rp=r+1; cm=c-1; cp=c+1; return $(rm,cm)+$(rm,c)+$(rm,cp)+$(r,cm)+$(r,cp)+$(rp,cm)+$(rp,c)+$(rp,cp) p: return word(arg(1),1) -pickChar: _=p(arg(1));if translate(_)==blank then _=' ';if length(_)==3 then _=d2c(_);if length(_)==2 then _=x2c(_);return _ -showRows: _=; do r=rows by -1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T'); say z; _=_||z; end; return +pickChar: _=p(arg(1)); arg u .; if u=='BLANK' then _=' '; L=length(_); if L==3 then _=d2c(_);if L==2 then _=x2c(_); return _ +showRows: _=; do r=rows by -1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T',emp); say z; _=_||z; end; return diff --git a/Task/Conways-Game-of-Life/SQL/conways-game-of-life.sql b/Task/Conways-Game-of-Life/SQL/conways-game-of-life.sql new file mode 100644 index 0000000000..40cf54847d --- /dev/null +++ b/Task/Conways-Game-of-Life/SQL/conways-game-of-life.sql @@ -0,0 +1,116 @@ +-- save these lines in a file called +-- setupworld.sql + +-- turn off feedback for cleaner display + +set feedback off + +-- 3 x 3 world + +-- alive has coordinates of living cells + +drop table alive; + +create table alive (x number,y number); + +-- three alive up the middle +-- * +-- * +-- * + +insert into alive values (2,1); +insert into alive values (2,2); +insert into alive values (2,3); + +commit; + +-- save these lines in a file called +newgeneration.sql + +-- adjact contains one row for each pair of +-- coordinates that is adjacent to a living cell + +drop table adjacent; + +create table adjacent (x number,y number); + +-- add row for each of the 8 adjacent squares + +insert into adjacent select x-1,y-1 from alive; +insert into adjacent select x-1,y from alive; +insert into adjacent select x-1,y+1 from alive; +insert into adjacent select x,y-1 from alive; +insert into adjacent select x,y+1 from alive; +insert into adjacent select x+1,y-1 from alive; +insert into adjacent select x+1,y from alive; +insert into adjacent select x+1,y+1 from alive; + +commit; + +-- delete rows for squares that are outside the world + +delete from adjacent where x<1 or y<1 or x>3 or y>3; + +commit; + +-- table counts is the number of live cells +-- adjacent to that point + +drop table counts; + +create table counts as +select x,y,count(*) n +from adjacent a +group by x,y; + +-- C N new C +-- 1 0,1 -> 0 # Lonely +-- 1 4,5,6,7,8 -> 0 # Overcrowded +-- 1 2,3 -> 1 # Lives +-- 0 3 -> 1 # It takes three to give birth! +-- 0 0,1,2,4,5,6,7,8 -> 0 # Barren + +-- delete the ones who die + +delete from alive a +where +((a.x,a.y) not in (select x,y from counts)) or +((select c.n from counts c where a.x=c.x and a.y=c.y) in +(1,4,5,6,7,8)); + +-- insert the ones that are born + +insert into alive a +select x,y from counts c +where c.n=3 and +((c.x,c.y) not in (select x,y from alive)); + +commit; + +-- create output table + +drop table output; + +create table output as +select rownum y,' ' x1,' ' x2,' ' x3 +from dba_tables where rownum < 4; + +update output set x1='*' +where (1,y) in +(select x,y from alive); + +update output set x2='*' +where (2,y) in +(select x,y from alive); + +update output set x3='*' +where (3,y) in +(select x,y from alive); + +commit + +-- output configuration + +select x1||x2||x3 WLD +from output +order by y desc; diff --git a/Task/Copy-a-string/ALGOL-W/copy-a-string.alg b/Task/Copy-a-string/ALGOL-W/copy-a-string.alg new file mode 100644 index 0000000000..24bae16956 --- /dev/null +++ b/Task/Copy-a-string/ALGOL-W/copy-a-string.alg @@ -0,0 +1,9 @@ +begin + % strings are (fixed length) values in algol W. Assignment makes a copy % + string(10) a, copyOfA; + a := "some text"; + copyOfA := a; + % assignment to a will not change copyOfA % + a := "new value"; + write( a, copyOfA ) +end. diff --git a/Task/Copy-a-string/AppleScript/copy-a-string.applescript b/Task/Copy-a-string/AppleScript/copy-a-string.applescript new file mode 100644 index 0000000000..acc0b2d3a6 --- /dev/null +++ b/Task/Copy-a-string/AppleScript/copy-a-string.applescript @@ -0,0 +1,2 @@ +set src to "Hello" +set dst to src diff --git a/Task/Copy-a-string/Elixir/copy-a-string.elixir b/Task/Copy-a-string/Elixir/copy-a-string.elixir new file mode 100644 index 0000000000..8702ca9cf2 --- /dev/null +++ b/Task/Copy-a-string/Elixir/copy-a-string.elixir @@ -0,0 +1,2 @@ +src = "Hello" +dst = src diff --git a/Task/Copy-a-string/Julia/copy-a-string.julia b/Task/Copy-a-string/Julia/copy-a-string.julia new file mode 100644 index 0000000000..f0cb1f83f0 --- /dev/null +++ b/Task/Copy-a-string/Julia/copy-a-string.julia @@ -0,0 +1,8 @@ +s = "Rosetta Code" +t = s + +println("s = \"", s, "\" and, after \"t = s\", t = \"", t, "\"") + +s = "Julia at "*s + +println("s = \"", s, "\" and, after this change, t = \"", t, "\"") diff --git a/Task/Copy-a-string/Neko/copy-a-string.neko b/Task/Copy-a-string/Neko/copy-a-string.neko new file mode 100644 index 0000000000..ddceda62b4 --- /dev/null +++ b/Task/Copy-a-string/Neko/copy-a-string.neko @@ -0,0 +1,2 @@ +var src = "Hello" +var dst = src diff --git a/Task/Count-in-factors/00DESCRIPTION b/Task/Count-in-factors/00DESCRIPTION index 54435421cf..e716b205be 100644 --- a/Task/Count-in-factors/00DESCRIPTION +++ b/Task/Count-in-factors/00DESCRIPTION @@ -1,5 +1,5 @@ Write a program which counts up from 1, displaying each number as the multiplication of its prime factors. For the purpose of this task, 1 may be shown as itself. -For examle, 2 is prime, so it would be shown as itself. 6 is not prime; it would be shown as 2\times3. Likewise, 2144 is not prime; it would be shown as 2\times2\times2\times2\times2\times67. +For example, 2 is prime, so it would be shown as itself. 6 is not prime; it would be shown as 2\times3. Likewise, 2144 is not prime; it would be shown as 2\times2\times2\times2\times2\times67. c.f. [[Prime decomposition]] diff --git a/Task/Count-in-factors/ALGOL-68/count-in-factors.alg b/Task/Count-in-factors/ALGOL-68/count-in-factors.alg new file mode 100644 index 0000000000..d8f510f5da --- /dev/null +++ b/Task/Count-in-factors/ALGOL-68/count-in-factors.alg @@ -0,0 +1,36 @@ +OP +:= = (REF FLEX []INT a, INT b) VOID: + BEGIN + [⌈a + 1] INT c; + c[:⌈a] := a; + c[⌈a+1:] := b; + a := c + END; + + +PROC factorize = (INT nn) []INT: + BEGIN + IF nn = 1 THEN (1) + ELSE + INT k := 2, n := nn; + FLEX[0]INT result; + WHILE n > 1 DO + WHILE n MOD k = 0 DO + result +:= k; + n := n % k + OD; + k +:= 1 + OD; + result + FI + END; + +FLEX[0]INT factors; +FOR i TO 22 DO + factors := factorize (i); + print ((whole (i, 0), " = ")); + FOR j TO UPB factors DO + (j /= 1 | print (" × ")); + print ((whole (factors[j], 0))) + OD; + print ((new line)) +OD diff --git a/Task/Count-in-factors/Befunge/count-in-factors.bf b/Task/Count-in-factors/Befunge/count-in-factors.bf new file mode 100644 index 0000000000..e45cb6ed38 --- /dev/null +++ b/Task/Count-in-factors/Befunge/count-in-factors.bf @@ -0,0 +1,4 @@ +1>>>>:.48*"=",,::1-#v_.v +$<<<^_@#-"e":+1,+55$2<<< +v4_^#-1:/.:g00_00g1+>>0v +>8*"x",,:00g%!^!%g00:p0< diff --git a/Task/Count-in-factors/DCL/count-in-factors.dcl b/Task/Count-in-factors/DCL/count-in-factors.dcl new file mode 100644 index 0000000000..f1c0c16a51 --- /dev/null +++ b/Task/Count-in-factors/DCL/count-in-factors.dcl @@ -0,0 +1,44 @@ +$ close /nolog primes +$ on control_y then $ goto clean +$ +$ n = 1 +$ outer_loop: +$ x = n +$ open primes primes.txt +$ +$ loop1: +$ read /end_of_file = prime primes prime +$ prime = f$integer( prime ) +$ loop2: +$ t = x / prime +$ if t * prime .eq. x +$ then +$ if f$type( factorization ) .eqs. "" +$ then +$ factorization = f$string( prime ) +$ else +$ factorization = factorization + "*" + f$string( prime ) +$ endif +$ if t .eq. 1 then $ goto done +$ x = t +$ goto loop2 +$ else +$ goto loop1 +$ endif +$ prime: +$ if f$type( factorization ) .eqs. "" +$ then +$ factorization = f$string( x ) +$ else +$ factorization = factorization + "*" + f$string( x ) +$ endif +$ done: +$ write sys$output f$fao( "!4SL = ", n ), factorization +$ delete /symbol factorization +$ close primes +$ n = n + 1 +$ if n .le. 2144 then $ goto outer_loop +$ exit +$ +$ clean: +$ close /nolog primes diff --git a/Task/Count-in-factors/Eiffel/count-in-factors.e b/Task/Count-in-factors/Eiffel/count-in-factors.e index be90caa806..42bd6f598d 100644 --- a/Task/Count-in-factors/Eiffel/count-in-factors.e +++ b/Task/Count-in-factors/Eiffel/count-in-factors.e @@ -2,32 +2,63 @@ class COUNT_IN_FACTORS feature - display_factor(p: INTEGER) - --- uses the feature factor (Task: prime decomposition) - require - p_positive: p>0 - local - i,j:INTEGER - factors: ARRAY[INTEGER] - do - create factors.make_empty - from - i:= 1 - until - i>p - loop - io.put_string ("%N" + i.out + " ") - factors:= factor(i) - io.put_string (factors[1].out) + + display_factor (p: INTEGER) + -- Factors of all integers up to 'p'. + require + p_positive: p > 0 + local + factors: ARRAY [INTEGER] + do + across + 1 |..| p as c + loop + io.new_line + io.put_string (c.item.out + "%T") + factors := factor (c.item) + across + factors as f + loop + io.put_integer (f.item) + if f.is_last = False then + io.put_string (" x ") + end + end + end + end + + + factor (p: INTEGER): ARRAY [INTEGER] + -- Prime decomposition of 'p'. + require + p_positive: p > 0 + local + div, i, next, rest: INTEGER + do + create Result.make_empty + if p = 1 then + Result.force (1, 1) + end + div := 2 + next := 3 + rest := p from - j:= 2 + i := 1 until - j> factors.count + rest = 1 loop - io.put_string (" x " + factors[j].out) - j:= j +1 + from + until + rest \\ div /= 0 + loop + Result.force (div, i) + rest := (rest / div).floor + i := i + 1 + end + div := next + next := next + 2 end - i:= i+1 + ensure + is_divisor: across Result as r all p \\ r.item = 0 end end - end end diff --git a/Task/Count-in-factors/Elixir/count-in-factors.elixir b/Task/Count-in-factors/Elixir/count-in-factors.elixir new file mode 100644 index 0000000000..adfbdb571b --- /dev/null +++ b/Task/Count-in-factors/Elixir/count-in-factors.elixir @@ -0,0 +1,12 @@ +defmodule RC do + def factor(n), do: factor(n, 2, []) + + def factor(n, i, fact) when n < i*i, do: Enum.reverse([n|fact]) + def factor(n, i, fact) do + if rem(n,i)==0, do: factor(div(n,i), i, [i|fact]), + else: factor(n, i+1, fact) + end +end + +Enum.each(1..20, fn n -> + IO.puts "#{n}: #{Enum.join(RC.factor(n)," x ")}" end) diff --git a/Task/Count-in-factors/Julia/count-in-factors.julia b/Task/Count-in-factors/Julia/count-in-factors.julia new file mode 100644 index 0000000000..1a169172fa --- /dev/null +++ b/Task/Count-in-factors/Julia/count-in-factors.julia @@ -0,0 +1,20 @@ +function factor_print{T<:Integer}(n::T) + const SEP = " \u00d7 " + -2 < n || return "-1"*SEP*factor_print(-n) + if isprime(n) || n < 2 + return string(n) + end + a = T[] + for (k, v) in factor(n) + append!(a, k*ones(T, v)) + end + sort!(a) + join(a, SEP) +end + +lo = -4 +hi = 40 +println("Factor print ", lo, " to ", hi) +for i in lo:hi + println(@sprintf("%5d = ", i), factor_print(i)) +end diff --git a/Task/Count-in-factors/Perl-6/count-in-factors-1.pl6 b/Task/Count-in-factors/Perl-6/count-in-factors-1.pl6 index 0ffa9a58c8..8d90b940bd 100644 --- a/Task/Count-in-factors/Perl-6/count-in-factors-1.pl6 +++ b/Task/Count-in-factors/Perl-6/count-in-factors-1.pl6 @@ -1,4 +1,4 @@ -constant @primes = grep &is-prime, 2, (3, 5, 7 ... *); +constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime; multi factors(1) { 1 } multi factors(Int $remainder is copy) { diff --git a/Task/Count-in-factors/PowerShell/count-in-factors.psh b/Task/Count-in-factors/PowerShell/count-in-factors.psh new file mode 100644 index 0000000000..5bbb00031d --- /dev/null +++ b/Task/Count-in-factors/PowerShell/count-in-factors.psh @@ -0,0 +1,32 @@ +function eratosthenes ($n) { + if($n -ge 1){ + $prime = @(1..($n+1) | foreach{$true}) + $prime[1] = $false + $m = [Math]::Floor([Math]::Sqrt($n)) + for($i = 2; $i -le $m; $i++) { + if($prime[$i]) { + for($j = $i*$i; $j -le $n; $j += $i) { + $prime[$j] = $false + } + } + } + 1..$n | where{$prime[$_]} + } else { + "$n must be equal or greater than 1" + } +} +function prime-decomposition ($n) { + $array = eratosthenes $n + $prime = @() + foreach($p in $array) { + while($n%$p -eq 0) { + $n /= $p + $prime += @($p) + } + } + $prime +} +$OFS = " x " +"$(prime-decomposition 2144)" +"$(prime-decomposition 100)" +"$(prime-decomposition 12)" diff --git a/Task/Count-in-factors/REXX/count-in-factors-1.rexx b/Task/Count-in-factors/REXX/count-in-factors-1.rexx new file mode 100644 index 0000000000..1fc76f5e73 --- /dev/null +++ b/Task/Count-in-factors/REXX/count-in-factors-1.rexx @@ -0,0 +1,34 @@ +/*REXX program lists the prime factors of a specified integer (or a range).*/ +@.=left('',8); @.0='{unity} '; @.1='[prime] '; X='x' /*some tags and literals.*/ +parse arg low high . /*get optional arguments from the C.L. */ +if low=='' then do;low=1;high=40; end /*No LOW & HIGH? Then use the default.*/ +if high=='' then high=low; tell=high>0 /*No HIGH? " " " " */ +w=length(high); high=abs(high) /*get maximum width for pretty output. */ +numeric digits max(9,w+1) /*maybe bump the precision of numbers. */ +#=0 /*the number of primes found (so far). */ + do n=low to high; f=factr(n) /*process a single number or a range.*/ + p=words(translate(f,,'x')) -(n==1) /*P: is the number of prime factors. */ + if p==1 then #=#+1 /*bump the primes counter (exclude N=1)*/ + if tell then say right(n,w) '=' @.p space(f,0) /*show if prime, factors*/ + end /*n*/ +say +say right(#,w) ' primes found.' /*display the number of primes found. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +factr: procedure; parse arg z 1 n,$; if z<2 then return z + do while z// 2==0; $=$ 'x 2' ; z=z% 2; end /*maybe add factor of 2 */ + do while z// 3==0; $=$ 'x 3' ; z=z% 3; end /* " " " " 3 */ + do while z// 5==0; $=$ 'x 5' ; z=z% 5; end /* " " " " 5 */ + do while z// 7==0; $=$ 'x 7' ; z=z% 7; end /* " " " " 7 */ + + do j=11 by 6 while j<=z /*insure that J isn't divisible by 3.*/ + parse var j '' -1 _ /*get the last decimal digit of J. */ + if _\==5 then do while z//j==0; $=$ 'x' j; z=z%j; end /*maybe reduce.*/ + if _ ==3 then iterate /*if next number will be ÷ by 3, skip.*/ + if j*j>n then leave /*are we higher than the √ N ? */ + y=j+2 + do while z//y==0; $=$ 'x' y; z=z%y; end + end /*j*/ + +if z==1 then z= /*if residual is unity, then nullify it*/ +return strip( strip( $ 'x' z), , 'x') /*elide a possible leading (extra) "x".*/ diff --git a/Task/Count-in-factors/REXX/count-in-factors-2.rexx b/Task/Count-in-factors/REXX/count-in-factors-2.rexx new file mode 100644 index 0000000000..9a088c14a5 --- /dev/null +++ b/Task/Count-in-factors/REXX/count-in-factors-2.rexx @@ -0,0 +1,37 @@ +/*REXX program lists the prime factors of a specified integer (or a range).*/ +@.=left('',8); @.0='{unity} '; @.1='[prime] '; X='x' /*some tags and literals.*/ +parse arg low high . /*get optional arguments from the C.L. */ +if low=='' then do;low=1;high=40; end /*No LOW & HIGH? Then use the default.*/ +if high=='' then high=low; tell=high>0 /*No HIGH? " " " " */ +w=length(high); high=abs(high) /*get maximum width for pretty output. */ +numeric digits max(9,w+1) /*maybe bump the precision of numbers. */ +#=0 /*the number of primes found (so far). */ + do n=low to high; f=factr(n) /*process a single number or a range.*/ + p=words(translate(f,,'x')) -(n==1) /*P: is the number of prime factors. */ + if p==1 then #=#+1 /*bump the primes counter (exclude N=1)*/ + if tell then say right(n,w) '=' @.p space(f,0) /*show if prime, factors*/ + end /*n*/ +say +say right(#,w) ' primes found.' /*display the number of primes found. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +factr: procedure; parse arg z 1 n,$; if z<2 then return z + do while z// 2==0; $=$ 'x 2' ; z=z% 2; end /*maybe add factor of 2 */ + do while z// 3==0; $=$ 'x 3' ; z=z% 3; end /* " " " " 3 */ + do while z// 5==0; $=$ 'x 5' ; z=z% 5; end /* " " " " 5 */ + do while z// 7==0; $=$ 'x 7' ; z=z% 7; end /* " " " " 7 */ + t=z; r=0; q=1; do while q<=t; q=q*4; end /*R will be iSqrt of Z*/ + + do while q>1; q=q%4; _=t-r-q; r=r%2; if _>=0 then do; t=_; r=r+q; end + end /*while ···*/ /* [↑] compute the integer SQRT of Z. */ + + do j=11 by 6 to r while j<=z /*insure that J isn't divisible by 3.*/ + parse var j '' -1 _ /*get the last decimal digit of J. */ + if _\==5 then do while z//j==0; $=$ 'x' j; z=z%j; end /*maybe reduce*/ + if _ ==3 then iterate /*if next number will be ÷ by 3, skip.*/ + y=j+2 + do while z//y==0; $=$ 'x' y; z=z%y; end /*maybe reduce*/ + end /*j*/ + +if z==1 then z= /*if residual is unity, then nullify it*/ +return strip( strip( $ 'x' z), , 'x') /*elide a possible leading (extra) "x".*/ diff --git a/Task/Count-in-factors/REXX/count-in-factors.rexx b/Task/Count-in-factors/REXX/count-in-factors.rexx deleted file mode 100644 index 5d38b2330d..0000000000 --- a/Task/Count-in-factors/REXX/count-in-factors.rexx +++ /dev/null @@ -1,41 +0,0 @@ -/*REXX program lists the prime factors of a specified integer (or range)*/ -@.=left('',8); @.0='{unity} '; @.1='[prime] ' /*unity & prime tags.*/ -parse arg low high . /*get the argument(s) from the CL*/ -if low=='' then do;low=1;high=40;end /*No LOW&HIGH? Then use default.*/ -if high=='' then high=low; oHigh=high /*No HIGH? Then use the LOW.*/ -w=length(high); high=abs(high) /*get max width for pretty tell. */ -numeric digits max(9,w+1) /*maybe bump precision of numbers*/ -blanks=1 /*1=allow spaces around the "x".*/ -primes=0 /*number of primes detected. */ - do n=low to high /*process single number | a range*/ - y=factr(n); /*squish (or not) the blanks. */ - #=words(translate(y,,'x')) - (n==1) /*# of prime factors. */ - if #==1 then primes=primes+1 /*bump primes counter (exclude 1)*/ - if high\==oHigh then iterate /*only show factors if HIGH is >0*/ - say right(n,w) '=' @.# space(y,blanks) /*prime flag, factors.*/ - end /*n*/ /*if BLANKS=0, no spaces around X*/ -say -say right(primes,w) ' primes found.' /*display number of primes found.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FACTR subroutine────────────────────*/ -factr: procedure; parse arg x; x=abs(x); z=x /*insure X is positive.*/ -if x<2 then return x /*handle a couple special cases. */ -list= /*nullify the list (empty string)*/ - /* [↓] process some low primes. */ - do j=2 to 5; if j\==4 then call .buildF; end /*factorize, put──►list*/ - j=5 /*start where we left off (five).*/ - do y=0 by 2; j=j+2+y//4 /*insure it's not divisible by 3.*/ - if right(j,1)==5 then iterate /*fast check for divisible by 5.*/ - if j>z then leave /*number reduced to a small 'un? */ - if j*j>x then leave /*are we higher than the √X ? */ - call .buildF /*add a prime factor to list (J).*/ - end /*y*/ - -if z==1 then z= /*if residual is = 1, nullify it.*/ -return strip(strip(list 'x' z),,"x") /*elide a possible leading "x". */ -/*──────────────────────────────────.BUILDF subroutine──────────────────*/ -.buildF: do while z//j==0 /*keep dividing until it hurts. */ - list=list 'x' j /*add number to the list (J). */ - z=z%j /*do an integer divide. */ - end /*while*/ -return diff --git a/Task/Count-in-factors/VBScript/count-in-factors.vb b/Task/Count-in-factors/VBScript/count-in-factors.vb new file mode 100644 index 0000000000..bd322e473b --- /dev/null +++ b/Task/Count-in-factors/VBScript/count-in-factors.vb @@ -0,0 +1,59 @@ +Function CountFactors(n) + If n = 1 Then + CountFactors = 1 + Else + arrP = Split(ListPrimes(n)," ") + Set arrList = CreateObject("System.Collections.ArrayList") + divnum = n + Do Until divnum = 1 + 'The -1 is to account for the null element of arrP + For i = 0 To UBound(arrP)-1 + If divnum = 1 Then + Exit For + ElseIf divnum Mod arrP(i) = 0 Then + divnum = divnum/arrP(i) + arrList.Add arrP(i) + End If + Next + Loop + arrList.Sort + For i = 0 To arrList.Count - 1 + If i = arrList.Count - 1 Then + CountFactors = CountFactors & arrList(i) + Else + CountFactors = CountFactors & arrList(i) & " * " + End If + Next + End If +End Function + +Function IsPrime(n) + If n = 2 Then + IsPrime = True + ElseIf n <= 1 Or n Mod 2 = 0 Then + IsPrime = False + Else + IsPrime = True + For i = 3 To Int(Sqr(n)) Step 2 + If n Mod i = 0 Then + IsPrime = False + Exit For + End If + Next + End If +End Function + +Function ListPrimes(n) + ListPrimes = "" + For i = 1 To n + If IsPrime(i) Then + ListPrimes = ListPrimes & i & " " + End If + Next +End Function + +'Testing the fucntions. +WScript.StdOut.Write "2 = " & CountFactors(2) +WScript.StdOut.WriteLine +WScript.StdOut.Write "2144 = " & CountFactors(2144) +WScript.StdOut.WriteLine diff --git a/Task/Count-in-octal/Befunge/count-in-octal.bf b/Task/Count-in-octal/Befunge/count-in-octal.bf new file mode 100644 index 0000000000..dcf6e6e615 --- /dev/null +++ b/Task/Count-in-octal/Befunge/count-in-octal.bf @@ -0,0 +1 @@ +:0\55+\:8%68>*#<+#8\#68#%/#8:_$>:#,_$1+:0`!#@_ diff --git a/Task/Count-in-octal/DCL/count-in-octal.dcl b/Task/Count-in-octal/DCL/count-in-octal.dcl new file mode 100644 index 0000000000..3b6e9c2327 --- /dev/null +++ b/Task/Count-in-octal/DCL/count-in-octal.dcl @@ -0,0 +1,5 @@ +$ i = 0 +$ loop: +$ write sys$output f$fao( "!OL", i ) +$ i = i + 1 +$ goto loop diff --git a/Task/Count-in-octal/Elixir/count-in-octal.elixir b/Task/Count-in-octal/Elixir/count-in-octal.elixir new file mode 100644 index 0000000000..19bcf09142 --- /dev/null +++ b/Task/Count-in-octal/Elixir/count-in-octal.elixir @@ -0,0 +1 @@ +Stream.iterate(1,&(&1+1)) |> Enum.each(&IO.puts Integer.to_string(&1,8)) diff --git a/Task/Count-in-octal/Julia/count-in-octal.julia b/Task/Count-in-octal/Julia/count-in-octal.julia new file mode 100644 index 0000000000..db6e753ceb --- /dev/null +++ b/Task/Count-in-octal/Julia/count-in-octal.julia @@ -0,0 +1,4 @@ +for i in one(Int64):typemax(Int64) + print(oct(i), " ") + sleep(0.1) +end diff --git a/Task/Count-in-octal/Rust/count-in-octal.rust b/Task/Count-in-octal/Rust/count-in-octal.rust index 6cedd7178e..bfe6a306b0 100644 --- a/Task/Count-in-octal/Rust/count-in-octal.rust +++ b/Task/Count-in-octal/Rust/count-in-octal.rust @@ -1,9 +1,5 @@ -// rust 0.9-pre - -use std::uint; - fn main() { - for i in range(uint::min_value, uint::max_value) { + for i in 0..std::usize::MAX { println!("{:o}", i); } } diff --git a/Task/Count-in-octal/VBScript/count-in-octal.vb b/Task/Count-in-octal/VBScript/count-in-octal.vb new file mode 100644 index 0000000000..9a6359e2a2 --- /dev/null +++ b/Task/Count-in-octal/VBScript/count-in-octal.vb @@ -0,0 +1,3 @@ +For i = 0 To 20 + WScript.StdOut.WriteLine Oct(i) +Next diff --git a/Task/Count-occurrences-of-a-substring/Batch-File/count-occurrences-of-a-substring.bat b/Task/Count-occurrences-of-a-substring/Batch-File/count-occurrences-of-a-substring.bat new file mode 100644 index 0000000000..c8d7d30a66 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Batch-File/count-occurrences-of-a-substring.bat @@ -0,0 +1,21 @@ +@echo off +setlocal enabledelayedexpansion + + ::Main +call :countString "the three truths","th" +call :countString "ababababab","abab" +pause>nul +exit /b + ::/Main + + ::Procedure +:countString + set input=%~1 + set cnt=0 + + :count_loop + set trimmed=!input:*%~2=! + if "!trimmed!"=="!input!" (echo.!cnt!&goto :EOF) + set input=!trimmed! + set /a cnt+=1 + goto count_loop diff --git a/Task/Count-occurrences-of-a-substring/Elixir/count-occurrences-of-a-substring.elixir b/Task/Count-occurrences-of-a-substring/Elixir/count-occurrences-of-a-substring.elixir new file mode 100644 index 0000000000..129a767069 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Elixir/count-occurrences-of-a-substring.elixir @@ -0,0 +1,15 @@ +countSubstring = fn(_, "") -> 0 + (str, sub) -> length(String.split(str, sub)) - 1 end + +data = [ {"the three truths", "th"}, + {"ababababab", "abab"}, + {"abaabba*bbaba*bbab", "a*b"}, + {"abaabba*bbaba*bbab", "a"}, + {"abaabba*bbaba*bbab", " "}, + {"abaabba*bbaba*bbab", ""}, + {"", "a"}, + {"", ""} ] + +Enum.each(data, fn{str, sub} -> + IO.puts countSubstring.(str, sub) +end) diff --git a/Task/Count-occurrences-of-a-substring/Erlang/count-occurrences-of-a-substring-1.erl b/Task/Count-occurrences-of-a-substring/Erlang/count-occurrences-of-a-substring-1.erl index 77065064f3..ab0fc6432d 100644 --- a/Task/Count-occurrences-of-a-substring/Erlang/count-occurrences-of-a-substring-1.erl +++ b/Task/Count-occurrences-of-a-substring/Erlang/count-occurrences-of-a-substring-1.erl @@ -4,6 +4,10 @@ -module(substrings). -export([main/2]). +%% String and Sub exhausted, count a match and present result +match([], [], _OrigSub, Acc) -> + Acc+1; + %% String exhausted, present result match([], _Sub, _OrigSub, Acc) -> Acc; diff --git a/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring.js b/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring.js index dd96fa6666..12bfd99303 100644 --- a/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring.js +++ b/Task/Count-occurrences-of-a-substring/JavaScript/count-occurrences-of-a-substring.js @@ -1,3 +1,4 @@ function countSubstring(str, subStr){ - return str.match(new RegExp(subStr, "g")).length + var matches=str.match(new RegExp(subStr, "g")); + return matches?matches.length:0; } diff --git a/Task/Count-occurrences-of-a-substring/Julia/count-occurrences-of-a-substring.julia b/Task/Count-occurrences-of-a-substring/Julia/count-occurrences-of-a-substring.julia new file mode 100644 index 0000000000..0063bced3b --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Julia/count-occurrences-of-a-substring.julia @@ -0,0 +1,14 @@ +ts = ["the three truths", "ababababab"] +tsub = ["th", "abab"] + +println("Test of non-overlapping substring counts.") +for i in 1:length(ts) + print(ts[i], " (", tsub[i], ") => ") + println(length(matchall(Regex(tsub[i]), ts[i]))) +end +println() +println("Test of overlapping substring counts.") +for i in 1:length(ts) + print(ts[i], " (", tsub[i], ") => ") + println(length(matchall(Regex(tsub[i]), ts[i], true))) +end diff --git a/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-1.psh b/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-1.psh new file mode 100644 index 0000000000..8312af449c --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-1.psh @@ -0,0 +1 @@ +[regex]::Matches("the three truths", "th").count diff --git a/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-2.psh b/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-2.psh new file mode 100644 index 0000000000..ac20bd15a5 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/PowerShell/count-occurrences-of-a-substring-2.psh @@ -0,0 +1 @@ +[regex]::Matches("ababababab","abab").count diff --git a/Task/Count-occurrences-of-a-substring/REXX/count-occurrences-of-a-substring.rexx b/Task/Count-occurrences-of-a-substring/REXX/count-occurrences-of-a-substring.rexx index 39ee54a226..e5e753b90a 100644 --- a/Task/Count-occurrences-of-a-substring/REXX/count-occurrences-of-a-substring.rexx +++ b/Task/Count-occurrences-of-a-substring/REXX/count-occurrences-of-a-substring.rexx @@ -1,16 +1,30 @@ -/*REXX program counts occurrences of a substring (with no overlap). */ -bag = "the three truths" - x = "th" - say left(bag,30) left(x,15) 'found' countstr(bag,x) -bag = "ababababab" - x = "abab" - say left(bag,30) left(x,15) 'found' countstr(bag,x) -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────COUNTSTR subroutine──────────────*/ -countstr: procedure; parse arg haystack, needle, startAt -if startAt=='' then startAt=1; width=length(needle) - - do k=0 until _==0; _=pos(needle,haystack,startAt) - startAt = _ + width - end /*k*/ -return k +/*REXX pgm counts the occurrences of a (non─overlapping) substring in a string*/ +w=. /*max. width so far.*/ +bag='the three truths' ; x='th' ; call showResult +bag='ababababab' ; x='abab' ; call showResult +bag='aaaabacad' ; x='aa' ; call showResult +bag='abaabba*bbaba*bbab' ; x='a*b' ; call showResult +bag='abaabba*bbaba*bbab' ; x=' ' ; call showResult +bag= ; x='a' ; call showResult +bag= ; x= ; call showResult +bag='catapultcatalog' ; x='cat' ; call showResult +bag='aaaaaaaaaaaaaa' ; x='aa' ; call showResult +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +countstr: procedure; parse arg haystack,needle,start /*get the arguments.*/ +if start=='' then start=1; width=length(needle) + do $=0 until p==0; p=pos(needle,haystack,start) + start=p+width /*prevent overlaps. */ + end /*$*/ +return $ /*return the count. */ +/*────────────────────────────────────────────────────────────────────────────*/ +showResult: _= '═' /*the char (double bar) used in title. */ +if w==. then do; w=30; n=w%2 /*W: width of largest haystack; N=½W */ + say center('haystack',w ) center('needle',n ) center('count',5 ) + say center('' ,w,_) center('' ,n,_) center('' ,5,_) + end + /* [↓] handle showing of null strings.*/ +if bag=='' then bag=' (null)' +if x=='' then x=' (null)' +say left(bag,w) left(x,n) center(countstr(bag,x),5) /*display the result.*/ +return diff --git a/Task/Count-occurrences-of-a-substring/Ruby/count-occurrences-of-a-substring.rb b/Task/Count-occurrences-of-a-substring/Ruby/count-occurrences-of-a-substring.rb index 7e6d5f12bc..b0fa2a84d7 100644 --- a/Task/Count-occurrences-of-a-substring/Ruby/count-occurrences-of-a-substring.rb +++ b/Task/Count-occurrences-of-a-substring/Ruby/count-occurrences-of-a-substring.rb @@ -1,8 +1,6 @@ def countSubstrings str, subStr - return str.scan(subStr).length + str.scan(subStr).length end -irb(main):001:0> "the three truths".scan("th").length -=> 3 -irb(main):002:0> "ababababab".scan("abab").length -=> 2 +p countSubstrings "the three truths", "th" #=> 3 +p countSubstrings "ababababab", "abab" #=> 2 diff --git a/Task/Count-occurrences-of-a-substring/UNIX-Shell/count-occurrences-of-a-substring.sh b/Task/Count-occurrences-of-a-substring/UNIX-Shell/count-occurrences-of-a-substring.sh new file mode 100644 index 0000000000..195e0b5d0e --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/UNIX-Shell/count-occurrences-of-a-substring.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +function countString(){ + input=$1 + cnt=0 + + until [ "${input/$2/}" == "$input" ]; do + input=${input/$2/} + let cnt+=1 + done + echo $cnt +} + +countString "the three truths" "th" +countString "ababababab" "abab" diff --git a/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring.vb b/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring.vb new file mode 100644 index 0000000000..f0406be57b --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/VBScript/count-occurrences-of-a-substring.vb @@ -0,0 +1,16 @@ +Function CountSubstring(str,substr) + CountSubstring = 0 + For i = 1 To Len(str) + If Len(str) >= Len(substr) Then + If InStr(i,str,substr) Then + CountSubstring = CountSubstring + 1 + i = InStr(i,str,substr) + Len(substr) - 1 + End If + Else + Exit For + End If + Next +End Function + +WScript.StdOut.Write CountSubstring("the three truths","th") & vbCrLf +WScript.StdOut.Write CountSubstring("ababababab","abab") & vbCrLf diff --git a/Task/Count-the-coins/360-Assembly/count-the-coins.360 b/Task/Count-the-coins/360-Assembly/count-the-coins.360 new file mode 100644 index 0000000000..3ea5ebadff --- /dev/null +++ b/Task/Count-the-coins/360-Assembly/count-the-coins.360 @@ -0,0 +1,59 @@ +* count the coins 04/09/2015 +COINS CSECT + USING COINS,R12 + LR R12,R15 + L R8,AMOUNT npenny=amount + L R4,AMOUNT + SRDA R4,32 + D R4,=F'5' + LR R9,R5 nnickle=amount/5 + L R4,AMOUNT + SRDA R4,32 + D R4,=F'10' + LR R10,R5 ndime=amount/10 + L R4,AMOUNT + SRDA R4,32 + D R4,=F'25' + LR R11,R5 nquarter=amount/25 + SR R1,R1 count=0 + SR R4,R4 p=0 +LOOPP CR R4,R8 do p=0 to npenny + BH ELOOPP + SR R5,R5 n=0 +LOOPN CR R5,R9 do n=0 to nnickle + BH ELOOPN + SR R6,R6 +LOOPD CR R6,R10 do d=0 to ndime + BH ELOOPD + SR R7,R7 q=0 +LOOPQ CR R7,R11 do q=0 to nquarter + BH ELOOPQ + LR R3,R5 n + MH R3,=H'5' + LR R2,R4 p + AR R2,R3 + LR R3,R6 d + MH R3,=H'10' + AR R2,R3 + LR R3,R7 q + MH R3,=H'25' + AR R2,R3 s=p+n*5+d*10+q*25 + C R2,=F'100' if s=100 + BNE NOTOK + LA R1,1(R1) count=count+1 +NOTOK LA R7,1(R7) q=q+1 + B LOOPQ +ELOOPQ LA R6,1(R6) d=d+1 + B LOOPD +ELOOPD LA R5,1(R5) n=n+1 + B LOOPN +ELOOPN LA R4,1(R4) p=p+1 + B LOOPP +ELOOPP XDECO R1,PG+0 edit count + XPRNT PG,12 print count + XR R15,R15 + BR R14 +AMOUNT DC F'100' start value in cents +PG DS CL12 + YREGS + END COINS diff --git a/Task/Count-the-coins/C-sharp/count-the-coins.cs b/Task/Count-the-coins/C-sharp/count-the-coins.cs new file mode 100644 index 0000000000..222a361f11 --- /dev/null +++ b/Task/Count-the-coins/C-sharp/count-the-coins.cs @@ -0,0 +1,21 @@ + // Adapted from http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/ + class Program + { + static long Count(int[] C, int m, int n) + { + var table = new long[n + 1]; + table[0] = 1; + for (int i = 0; i < m; i++) + for (int j = C[i]; j <= n; j++) + table[j] += table[j - C[i]]; + return table[n]; + } + static void Main(string[] args) + { + var C = new int[] { 1, 5, 10, 25 }; + int m = C.Length; + int n = 100; + Console.WriteLine(Count(C, m, n)); //242 + Console.ReadLine(); + } + } diff --git a/Task/Count-the-coins/Elixir/count-the-coins.elixir b/Task/Count-the-coins/Elixir/count-the-coins.elixir new file mode 100644 index 0000000000..eb1c528bea --- /dev/null +++ b/Task/Count-the-coins/Elixir/count-the-coins.elixir @@ -0,0 +1,24 @@ +defmodule Coins do + def find(coins,lim) do + vals = Enum.into(0..lim,Map.new,&{&1,0}) |> Dict.put(0,1) + count(coins,lim,vals) + |> Dict.values + |> Enum.max + |> IO.inspect + end + + defp count([],_,vals), do: vals + defp count([coin|coins],lim,vals) do + count(coins,lim,ways(coin,coin,lim,vals)) + end + + defp ways(num,_coin,lim,vals) when num > lim, do: vals + defp ways(num, coin,lim,vals) do + ways(num+1,coin,lim,ad(coin,num,vals)) + end + + defp ad(a,b,c), do: Dict.put(c,b,c[b]+c[b-a]) +end + +Coins.find([1,5,10,25],100) +Coins.find([1,5,10,25,50,100],100_000) diff --git a/Task/Count-the-coins/JavaScript/count-the-coins-5.js b/Task/Count-the-coins/JavaScript/count-the-coins-5.js new file mode 100644 index 0000000000..12e49df156 --- /dev/null +++ b/Task/Count-the-coins/JavaScript/count-the-coins-5.js @@ -0,0 +1,6 @@ +var amount=100, coin=[1,5,10,25] +var t=[1]; for (t[amount]=0, a=1; a= 0, @now [$coin,*@later]) { @cache[$n][+@later] //= ways($n - $coin, @now) + ways($n, @later); } multi ways($,@) { 0 } - ways($amount, @coins.sort(-*)); # sort descending + ways($amount, @coins.sort(-*).list); # sort descending } say ways-to-make-change 1_00, [1,5,10,25]; diff --git a/Task/Count-the-coins/Perl-6/count-the-coins-2.pl6 b/Task/Count-the-coins/Perl-6/count-the-coins-2.pl6 index 9c0ff996db..f32cc567ab 100644 --- a/Task/Count-the-coins/Perl-6/count-the-coins-2.pl6 +++ b/Task/Count-the-coins/Perl-6/count-the-coins-2.pl6 @@ -1,6 +1,6 @@ sub ways-to-make-change-slowly(\n, @coins) { my @table = [1 xx @coins], [0 xx @coins] xx n; - for 1..n X ^@coins -> \i, \j { + for 1..n X ^@coins -> (\i, \j) { my \c = @coins[j]; @table[i][j] = [+] @table[i - c][j ] // 0, diff --git a/Task/Count-the-coins/REXX/count-the-coins-1.rexx b/Task/Count-the-coins/REXX/count-the-coins-1.rexx index 2d33e55871..0e1bbbfe15 100644 --- a/Task/Count-the-coins/REXX/count-the-coins-1.rexx +++ b/Task/Count-the-coins/REXX/count-the-coins-1.rexx @@ -1,21 +1,31 @@ -/*REXX program makes change from some amount with various specie (coins)*/ -parse arg N $ /*obtain optional args from C.L. */ -if N='' then N=100 /*Not specified? Use $1 default.*/ -if $='' then $=1 5 10 25 /*Use penny/nickel/dime/quarter ?*/ -coins=words($) /*count number of coins specified*/ - do j=1 for coins /*create a fast way of accessing.*/ - $.j=word($,j) /*define a stemmed array element.*/ - end /*j*/ - -say 'with an amount of ' N " cents, there are " kaChing(N, coins) -say 'ways to make change with coins of the following denominations: ' $ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────KACHING subroutine──────────────────*/ -kaChing: procedure expose $.; parse arg a,k /*sub is recursive. */ -if a==0 then return 1 /*unroll special case*/ -if k==1 then return 1 /* " " " */ -if k==2 then f=1 /*handle special case*/ - else f=kaChing(a, k-1) /*recurse the amount.*/ -if a==$.k then return f + 1 /*handle special case*/ -if a <$.k then return f /* " " " */ - return f + kaChing(a-$.k, k) /*use diminished $. */ +/*REXX program counts the ways to make change with coins from an given amount.*/ +numeric digits 20 /*be able to handle large amounts of $.*/ +parse arg N $ /*obtain optional arguments from the CL*/ +if N='' | N=',' then N=100 /*Not specified? Then Use $1 (≡100¢).*/ +if $='' | $=',' then $=1 5 10 25 /*Use penny/nickel/dime/quarter default*/ +if left(N,1)=='$' then N=100*substr(N,2) /*amount was specified in dollars.*/ +coins=words($) /*the number of coins specified. */ +NN=N; do j=1 for coins /*create a fast way of accessing specie*/ + _=word($,j) /*define an array element for the coin.*/ + if _=='1/2' then _=.5 /*an alternate spelling of a half-cent.*/ + if _=='1/4' then _=.25 /* " " " " " quarter-¢.*/ + $.j=_ /*assign the value to a particular coin*/ + end /*j*/ +_=n//100; cnt=' cents' /* [↓] Is amount in whole $'s*/ +if _=0 then do; NN='$'||(NN%100); cnt=; end /*show amount in dollars, ¬ ¢.*/ +say 'with an amount of ' commas(NN)cnt", there are " commas(kaChing(N,coins)) +say 'ways to make change with coins of the following denominations: ' $ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M") + e=verify(n,#'0',,verify(n,#"0.",'M'))-4 + do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _ +/*────────────────────────────────────────────────────────────────────────────*/ +kaChing: procedure expose $.; parse arg a,k /*this function is recursive.*/ +if a==0 then return 1 /*unroll for a special case. */ +if k==1 then return 1 /* " " " " " */ +if k==2 then f=1 /*handle this special case. */ + else f=kaChing(a, k-1) /*count, recurse the amount. */ +if a==$.k then return f + 1 /*handle this special case. */ +if a <$.k then return f /* " " " " */ + return f + kaChing(a-$.k, k) /*use a diminished amount ($)*/ diff --git a/Task/Count-the-coins/REXX/count-the-coins-2.rexx b/Task/Count-the-coins/REXX/count-the-coins-2.rexx index 1fc2d16141..5b79377a44 100644 --- a/Task/Count-the-coins/REXX/count-the-coins-2.rexx +++ b/Task/Count-the-coins/REXX/count-the-coins-2.rexx @@ -1,24 +1,32 @@ -/*REXX program makes change from some amount with various specie (coins)*/ -numeric digits 20 /*be able to handle large amounts*/ -parse arg N $ /*obtain optional args from C.L. */ -if N='' then N=100 /*Not specified? Use $1 default.*/ -if $='' then $=1 5 10 25 /*Use penny/nickel/dime/quarter ?*/ -coins=words($) /*count number of coins specified*/ -!.=. /*used for memoization for A & K.*/ - do j=1 for coins /*create a fast way of accessing.*/ - $.j=word($,j) /*define a stemmed array element.*/ - end /*j*/ - -say 'with an amount of ' N " cents, there are " kaChing(N, coins) -say 'ways to make change with coins of the following denominations: ' $ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────KACHING subroutine──────────────────*/ -kaChing: procedure expose $. !.; parse arg a,k /*sub is recursive. */ -if a==0 then return 1 /*unroll special case*/ -if k==1 then return 1 /* " " " */ -if k==2 then f=1 /*handle special case*/ - else f=kaChing(a,k-1) /*recurse the amount.*/ -if !.a.k\==. then return !.a.k /*found A & K before?*/ -if a==$.k then do; !.a.k=f+1; return f+1; end /*handle special case*/ -if a <$.k then do; !.a.k=f; return f; end /* " " " */ -!.a.k=f + kaChing(a-$.k, k); return !.a.k /*compute,set,return.*/ +/*REXX program counts the ways to make change with coins from an given amount.*/ +numeric digits 20 /*be able to handle large amounts of $.*/ +parse arg N $ /*obtain optional arguments from the CL*/ +if N='' | N=',' then N=100 /*Not specified? Then Use $1 (≡100¢).*/ +if $='' | $=',' then $=1 5 10 25 /*Use penny/nickel/dime/quarter default*/ +if left(N,1)=='$' then N=100*substr(N,2) /*amount was specified in dollars.*/ +coins=words($) /*the number of coins specified. */ +!.=.; NN=N; do j=1 for coins /*create a fast way of accessing specie*/ + _=word($,j) /*define an array element for the coin.*/ + if _=='1/2' then _=.5 /*an alternate spelling of a half-cent.*/ + if _=='1/4' then _=.25 /* " " " " " quarter-¢.*/ + $.j=_ /*assign the value to a particular coin*/ + end /*j*/ +_=n//100; cnt=' cents' /* [↓] Is amount in whole $'s*/ +if _=0 then do; NN='$'||(NN%100); cnt=; end /*show amount in dollars, ¬ ¢.*/ +say 'with an amount of ' commas(NN)cnt", there are " commas(kaChing(N,coins)) +say 'ways to make change with coins of the following denominations: ' $ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M") + e=verify(n,#'0',,verify(n,#"0.",'M'))-4 + do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _ +/*────────────────────────────────────────────────────────────────────────────*/ +kaChing: procedure expose $. !.; parse arg a,k /*function is recursive. */ +if !.a.k\==. then return !.a.k /*found this A & K before? */ +if a==0 then return 1 /*unroll for a special case*/ +if k==1 then return 1 /* " " " " " */ +if k==2 then f=1 /*handle this special case.*/ + else f=kaChing(a, k-1) /*count, recurse the amount*/ +if a==$.k then do; !.a.k=f+1; return !.a.k; end /*handle this special case.*/ +if a <$.k then do; !.a.k=f ; return f ; end /* " " " " */ +!.a.k=f + kaChing(a-$.k, k) ; return !.a.k /*compute, define, return. */ diff --git a/Task/Count-the-coins/REXX/count-the-coins-3.rexx b/Task/Count-the-coins/REXX/count-the-coins-3.rexx new file mode 100644 index 0000000000..f240ae22db --- /dev/null +++ b/Task/Count-the-coins/REXX/count-the-coins-3.rexx @@ -0,0 +1,53 @@ +/*REXX program counts the ways to make change with coins from an given amount.*/ +numeric digits 20 /*be able to handle large amounts of $.*/ +parse arg N $ /*obtain optional arguments from the CL*/ +if N='' | N=',' then N='$1' /*Not specified? Then Use $1 (≡100¢).*/ +if $='' | $=',' then $=1 5 10 25 /*Use penny/nickel/dime/quarter default*/ +X=N /*save original for possible error msgs*/ +if left(N,1)=='$' then do /*the amount has a leading dollar sign.*/ + _=substr(N,2) /*amount was specified in dollars. */ + if \isNum(_) then call ser "amount isn't numeric: " N + N=100*_ /*change amount (in $) ───► cents (¢).*/ + end +max$=10**digits() /*the maximum amount this pgm can have.*/ +if \isNum(N) then call ser X " amount isn't numeric." +if N=0 then call ser X " amount can't be zero." +if N<0 then call ser X " amount can't be negative." +if N>max$ then call ser X " amount can't be greater than " max$'.' +coins=words($); !.=.; NN=N; p=0 /*#coins specified; coins; amount; prev*/ +@.=0 /*verify a coin was only specified once*/ + do j=1 for coins /*create a fast way of accessing specie*/ + _=word($,j); ?=_ ' coin' /*define an array element for the coin.*/ + if _=='1/2' then _=.5 /*an alternate spelling of a half-cent.*/ + if _=='1/4' then _=.25 /* " " " " " quarter-¢.*/ + if \isNum(_) then call ser ? "coin value isn't numeric." + if _<0 then call ser ? "coin value can't be negative." + if _<=0 then call ser ? "coin value can't be zero." + if @._ then call ser ? "coin was already specified." + if _

N then call ser ? "coin must be less or equal to amount:" X + @._=1; p=_ /*signify coin was specified; set prev.*/ + $.j=_ /*assign the value to a particular coin*/ + end /*j*/ +_=n//100; cnt=' cents' /* [↓] Is amount in whole $'s*/ +if _=0 then do; NN='$'||(NN%100); cnt=; end /*show amount in dollars, ¬ ¢.*/ +say 'with an amount of ' commas(NN)cnt", there are " commas(kaChing(N,coins)) +say 'ways to make change with coins of the following denominations: ' $ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +isNum: return datatype(arg(1), 'N') /*return 1 if arg is numeric, 0 if not.*/ +ser: say; say '***error!***'; say; say arg(1); say; exit 13 /*error msg.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M") + e=verify(n,#'0',,verify(n,#"0.",'M'))-4 + do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _ +/*────────────────────────────────────────────────────────────────────────────*/ +kaChing: procedure expose $. !.; parse arg a,k /*function is recursive. */ +if !.a.k\==. then return !.a.k /*found this A & K before? */ +if a==0 then return 1 /*unroll for a special case*/ +if k==1 then return 1 /* " " " " " */ +if k==2 then f=1 /*handle this special case.*/ + else f=kaChing(a, k-1) /*count, recurse the amount*/ +if a==$.k then do; !.a.k=f+1; return !.a.k; end /*handle this special case.*/ +if a <$.k then do; !.a.k=f ; return f ; end /* " " " " */ +!.a.k=f + kaChing(a-$.k, k) ; return !.a.k /*compute, define, return. */ diff --git a/Task/Count-the-coins/Scala/count-the-coins.scala b/Task/Count-the-coins/Scala/count-the-coins-1.scala similarity index 100% rename from Task/Count-the-coins/Scala/count-the-coins.scala rename to Task/Count-the-coins/Scala/count-the-coins-1.scala diff --git a/Task/Count-the-coins/Scala/count-the-coins-2.scala b/Task/Count-the-coins/Scala/count-the-coins-2.scala new file mode 100644 index 0000000000..694ed7eb64 --- /dev/null +++ b/Task/Count-the-coins/Scala/count-the-coins-2.scala @@ -0,0 +1,8 @@ +def count(target: Int, coins: List[Int]): Int = { + if (target == 0) 1 + else if (coins.isEmpty || target < 0) 0 + else count(target, coins.tail) + count(target - coins.head, coins) +} + + +count(100, List(25, 10, 5, 1)) diff --git a/Task/Count-the-coins/UNIX-Shell/count-the-coins-1.sh b/Task/Count-the-coins/UNIX-Shell/count-the-coins-1.sh new file mode 100644 index 0000000000..e2b32aae9a --- /dev/null +++ b/Task/Count-the-coins/UNIX-Shell/count-the-coins-1.sh @@ -0,0 +1,13 @@ +function count_change { + local -i amount=$1 coin j + local ways=(1) + shift + for coin; do + for (( j=coin; j <= amount; j++ )); do + let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0} + done + done + echo "${ways[amount]}" +} +count_change 100 25 10 5 1 +count_change 100000 100 50 25 10 5 1 diff --git a/Task/Count-the-coins/UNIX-Shell/count-the-coins-2.sh b/Task/Count-the-coins/UNIX-Shell/count-the-coins-2.sh new file mode 100644 index 0000000000..e4b9892745 --- /dev/null +++ b/Task/Count-the-coins/UNIX-Shell/count-the-coins-2.sh @@ -0,0 +1,14 @@ +function count_change { + typeset -i amount=$1 coin j + typeset ways + set -A ways 1 + shift + for coin; do + for (( j=coin; j <= amount; j++ )); do + let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0} + done + done + echo "${ways[amount]}" +} +count_change 100 25 10 5 1 +count_change 100000 100 50 25 10 5 1 diff --git a/Task/Count-the-coins/UNIX-Shell/count-the-coins-3.sh b/Task/Count-the-coins/UNIX-Shell/count-the-coins-3.sh new file mode 100644 index 0000000000..3bb7e06ae4 --- /dev/null +++ b/Task/Count-the-coins/UNIX-Shell/count-the-coins-3.sh @@ -0,0 +1,16 @@ +function count_change { + typeset -i amount=$1 coin j + typeset ways + set -A ways 1 + shift + for coin; do + let j=coin + while (( j <= amount )); do + let ways[j]=${ways[j]:-0}+${ways[j-coin]:-0} + let j+=1 + done + done + echo "${ways[amount]}" +} +count_change 100 25 10 5 1 +# (optional task exceeds a subscript limit in ksh88) diff --git a/Task/Count-the-coins/UNIX-Shell/count-the-coins-4.sh b/Task/Count-the-coins/UNIX-Shell/count-the-coins-4.sh new file mode 100644 index 0000000000..e814f9ecc9 --- /dev/null +++ b/Task/Count-the-coins/UNIX-Shell/count-the-coins-4.sh @@ -0,0 +1,15 @@ +if [ $# -lt 2 ]; then + set ${1-100} 25 10 5 1 +fi +amount=$1 +shift +ways_0=1 +for coin in "$@"; do + j=$coin + while [ $j -le $amount ]; do + d=`expr $j - $coin` + eval "ways_$j=\`expr \${ways_$j-0} + \${ways_$d-0}\`" + j=`expr $j + 1` + done +done +eval "echo \$ways_$amount" diff --git a/Task/Count-the-coins/VBScript/count-the-coins.vb b/Task/Count-the-coins/VBScript/count-the-coins.vb new file mode 100644 index 0000000000..409c376f09 --- /dev/null +++ b/Task/Count-the-coins/VBScript/count-the-coins.vb @@ -0,0 +1,20 @@ +Function count(coins,m,n) + ReDim table(n+1) + table(0) = 1 + i = 0 + Do While i < m + j = coins(i) + Do While j <= n + table(j) = table(j) + table(j - coins(i)) + j = j + 1 + Loop + i = i + 1 + Loop + count = table(n) +End Function + +'testing +arr = Array(1,5,10,25) +m = UBound(arr) + 1 +n = 100 +WScript.StdOut.WriteLine count(arr,m,n) diff --git a/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION b/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION index b0d6478dbd..1cb379e3d7 100644 --- a/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION +++ b/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION @@ -1,3 +1,4 @@ +{{omit from|Axe}} {{omit from|AWK|not OO}} {{omit from|BASIC|not OO}} {{omit from|C|not OO}} diff --git a/Task/Create-a-file/AWK/create-a-file.awk b/Task/Create-a-file/AWK/create-a-file.awk index 754ca46545..4a3f7fdc7d 100644 --- a/Task/Create-a-file/AWK/create-a-file.awk +++ b/Task/Create-a-file/AWK/create-a-file.awk @@ -1,5 +1,8 @@ BEGIN { printf "" > "output.txt" - # try to create the file in the root (for *nix-like systems) + close("output.txt") printf "" > "/output.txt" + close("/output.txt") + system("mkdir docs") + system("mkdir /docs") } diff --git a/Task/Create-a-file/Julia/create-a-file.julia b/Task/Create-a-file/Julia/create-a-file.julia new file mode 100644 index 0000000000..9448f4efc1 --- /dev/null +++ b/Task/Create-a-file/Julia/create-a-file.julia @@ -0,0 +1,12 @@ +# many I/O functions have UNIX names + +touch("output.txt") +mkdir("docs") + +# probably don't have permission +try + touch("/output.txt") + mkdir("/docs") +catch e + warn(e) +end diff --git a/Task/Create-a-file/VBScript/create-a-file.vb b/Task/Create-a-file/VBScript/create-a-file.vb new file mode 100644 index 0000000000..3dca9a5df6 --- /dev/null +++ b/Task/Create-a-file/VBScript/create-a-file.vb @@ -0,0 +1,9 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") + +'current directory +objFSO.CreateFolder(".\docs") +objFSO.CreateTextFile(".\docs\output.txt") + +'root directory +objFSO.CreateFolder("\docs") +objFSO.CreateTextFile("\docs\output.txt") diff --git a/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-W/create-a-two-dimensional-array-at-runtime.alg b/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-W/create-a-two-dimensional-array-at-runtime.alg new file mode 100644 index 0000000000..17a50b7f20 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-W/create-a-two-dimensional-array-at-runtime.alg @@ -0,0 +1,22 @@ +begin + integer dimension1UpperBound, dimension2UpperBound; + write( "upper bound for dimension 1: " ); + read( dimension1UpperBound ); + write( "upper bound for dimension 2: " ); + read( dimension2UpperBound ); + + begin + % we start a new block because declarations must precede statements % + % and variables in array bounds must be from outside the block % + integer array matrix ( 1 :: dimension1UpperBound + , 1 :: dimension2UpperBound + ); + % set the first element - the program will crash if the user input % + % upper bounds less than 1 % + matrix( 1, 1 ) := 3; + % write it % + write( matrix( 1, 1 ) ); + % the array is automatically deleted when the block ends % + end + +end. diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Applesoft-BASIC/create-a-two-dimensional-array-at-runtime.applesoft b/Task/Create-a-two-dimensional-array-at-runtime/Applesoft-BASIC/create-a-two-dimensional-array-at-runtime.applesoft new file mode 100644 index 0000000000..cec3313822 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Applesoft-BASIC/create-a-two-dimensional-array-at-runtime.applesoft @@ -0,0 +1,7 @@ +10 INPUT "ENTER TWO INTEGERS:"; X%, Y% +20 DIM A%(X% - 1, Y% - 1) +30 X% = RND(1) * X% +40 Y% = RND(1) * Y% +50 A%(X%, Y%) = -32767 +60 PRINT A%(X%, Y%) +70 CLEAR diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime.basic new file mode 100644 index 0000000000..58d8c59637 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime.basic @@ -0,0 +1,6 @@ + CLS + INPUT a, b 'inputs need to be separated by commas + DIM array (1 TO a, 1 TO b) + array(1,1) = 42 + PRINT array(1,1) + ERASE array diff --git a/Task/Create-a-two-dimensional-array-at-runtime/JavaScript/create-a-two-dimensional-array-at-runtime.js b/Task/Create-a-two-dimensional-array-at-runtime/JavaScript/create-a-two-dimensional-array-at-runtime.js index 1ef50ac024..ee349f1226 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/JavaScript/create-a-two-dimensional-array-at-runtime.js +++ b/Task/Create-a-two-dimensional-array-at-runtime/JavaScript/create-a-two-dimensional-array-at-runtime.js @@ -1,28 +1,17 @@ -var w = parseInt( get_input("Enter a width:") ); -var w = parseInt( get_input("Enter a height:") ); +var width = Number(prompt("Enter width: ")); +var height = Number(prompt("Enter height: ")); -// create the 2-D array -var a = new Array(h); -for (var i = 0; i < h; i++) - a[i] = new Array(w); +//make 2D array +var arr = new Array(height); -a[0][0] = 'foo'; -WScript.Echo('a[0][0] = ' + a[0][0]); +for (var i = 0; i < h; i++) { + arr[i] = new Array(width); +} -a = null; +//set value of element +a[0][0] = 'foo'; +//print value of element +console.log('arr[0][0] = ' + arr[0][0]); -function get_input(prompt) { - output(prompt); - try { - return WScript.StdIn.readLine(); - } catch(e) { - return readline(); - } -} -function output(prompt) { - try { - return WScript.echo(prompt); - } catch(e) { - return print(prompt); - } -} +//cleanup array +arr = void(0); diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia b/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia new file mode 100644 index 0000000000..9a12897b97 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia @@ -0,0 +1,38 @@ +julia> "Inspired by Python's `input` function." + function input(prompt::AbstractString="") + print(prompt) + chomp(readline()) + end +input (generic function with 2 methods) + +julia> n = parse(Int, input("Upper bound for dimension 1: ")) # parse as `Int` +Upper bound for dimension 1: 5 +5 + +julia> m = parse(Int, input("Upper bound for dimension 2: ")) +Upper bound for dimension 2: 5 +5 + +julia> x = rand(n, m) # create an n·m random matrix +5x5 Array{Float64,2}: + 0.80217 0.422318 0.594049 0.45547 0.208822 + 0.0533981 0.304858 0.0276755 0.797732 0.828796 + 0.522506 0.563856 0.216759 0.865961 0.034306 + 0.792363 0.815744 0.868697 0.42509 0.588946 + 0.112034 0.539611 0.674581 0.508299 0.939373 + +julia> x[3, 3] # overloads `getindex` generic function +0.21675944652281487 + +julia> x[3, 3] = 5 # overloads `setindex!` generic function +5 + +julia> x::Matirx # `Matrix{T}` is an alias for `Array{T, 2}` +5x5 Array{Float64,2}: + 0.80217 0.422318 0.594049 0.45547 0.208822 + 0.0533981 0.304858 0.0276755 0.797732 0.828796 + 0.522506 0.563856 5.0 0.865961 0.034306 + 0.792363 0.815744 0.868697 0.42509 0.588946 + 0.112034 0.539611 0.674581 0.508299 0.939373 + +julia> x = 0; gc() # Julia has no `del` command, rebind `x` and call the garbage collector diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Perl-6/create-a-two-dimensional-array-at-runtime-2.pl6 b/Task/Create-a-two-dimensional-array-at-runtime/Perl-6/create-a-two-dimensional-array-at-runtime-2.pl6 index 51bd3eac13..90f2bcf9a6 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Perl-6/create-a-two-dimensional-array-at-runtime-2.pl6 +++ b/Task/Create-a-two-dimensional-array-at-runtime/Perl-6/create-a-two-dimensional-array-at-runtime-2.pl6 @@ -1,7 +1,7 @@ $ ./two-dee Dimensions? 5x35 -@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ -@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ -@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ -@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ -@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ +[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @] +[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @] +[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @] +[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @] +[@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @] diff --git a/Task/Create-a-two-dimensional-array-at-runtime/TI-83-BASIC/create-a-two-dimensional-array-at-runtime.ti-83 b/Task/Create-a-two-dimensional-array-at-runtime/TI-83-BASIC/create-a-two-dimensional-array-at-runtime.ti-83 new file mode 100644 index 0000000000..37fe624868 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/TI-83-BASIC/create-a-two-dimensional-array-at-runtime.ti-83 @@ -0,0 +1,6 @@ +Input "ROWS? ",R +Input "COLS? ",C +{R,C}→dim([A]) +42→[A](1,1) +Disp [A](1,1) +DelVar [A] diff --git a/Task/Create-an-HTML-table/Bracmat/create-an-html-table.bracmat b/Task/Create-an-HTML-table/Bracmat/create-an-html-table.bracmat new file mode 100644 index 0000000000..ac96e3a6fa --- /dev/null +++ b/Task/Create-an-HTML-table/Bracmat/create-an-html-table.bracmat @@ -0,0 +1,66 @@ +( ( makeTable + = headTexts + minRowNr + maxRowNr + headCells + cells + rows + Generator + Table + . get$"xmlio.bra" { A library that converts from Bracmat format to XML or HTML } + & !arg:(?headTexts.?minRowNr.?maxRowNr.?Generator) + & ( headCells + = cellText + . !arg:%?cellText ?arg + & (th.,!cellText) headCells$!arg + | + ) + & ( cells + = cellText cellTexts numberGenerator + . !arg + : (%?cellText ?cellTexts.(=?numberGenerator)) + & (td.,numberGenerator$) + cells$(!cellTexts.'$numberGenerator) + | + ) + & ( rows + = headTexts rowNr maxRowNr Generator + . !arg:(?headTexts.?rowNr.?maxRowNr.?Generator) + & !rowNr:~>!maxRowNr + & ( tr + . + , (td.,!rowNr) + cells$(!headTexts.!Generator) + ) + \n + rows$(!headTexts.!rowNr+1.!maxRowNr.!Generator) + | + ) + & ( table + . + , ( thead + . (align.right) + , \n (tr.,(th.," ") headCells$!headTexts) + ) + \n + ( tbody + . (align.right) + , \n + rows + $ (!headTexts.!minRowNr.!maxRowNr.!Generator) + ) + ) + : ?Table + & str$((XMLIO.convert)$!Table) { Call library function to create HTML } + ) +& makeTable + $ ( X Y Z { Column headers } + . 1 { Lowest row number } + . 4 { Highest row number } + . { Function that generates numbers 9, 10, ...} + ' ( cnt + . (cnt=$(new$(==8))) { This creates an object 'cnt' with scope as a local function variable that survives between calls. } + & !(cnt.)+1:?(cnt.) + ) + ) +) diff --git a/Task/Create-an-HTML-table/Common-Lisp/create-an-html-table.lisp b/Task/Create-an-HTML-table/Common-Lisp/create-an-html-table.lisp new file mode 100644 index 0000000000..872785c172 --- /dev/null +++ b/Task/Create-an-HTML-table/Common-Lisp/create-an-html-table.lisp @@ -0,0 +1,12 @@ +(ql:quickload :closure-html) +(use-package :closure-html) +(serialize-lhtml + `(table nil + (tr nil ,@(mapcar (lambda (x) + (list 'th nil x)) + '("" "X" "Y" "Z"))) + ,@(loop for i from 1 to 4 + collect `(tr nil + (th nil ,(format nil "~a" i)) + ,@(loop repeat 3 collect `(td nil ,(format nil "~a" (random 10000))))))) + (make-string-sink)) diff --git a/Task/Create-an-HTML-table/JavaScript/create-an-html-table.js b/Task/Create-an-HTML-table/JavaScript/create-an-html-table-1.js similarity index 100% rename from Task/Create-an-HTML-table/JavaScript/create-an-html-table.js rename to Task/Create-an-HTML-table/JavaScript/create-an-html-table-1.js diff --git a/Task/Create-an-HTML-table/JavaScript/create-an-html-table-2.js b/Task/Create-an-HTML-table/JavaScript/create-an-html-table-2.js new file mode 100644 index 0000000000..a00095e387 --- /dev/null +++ b/Task/Create-an-HTML-table/JavaScript/create-an-html-table-2.js @@ -0,0 +1,67 @@ +(function (lngCols, lngRows) { + + //range(5, 20) --> [5..20] + //range('a', 'n') --> ['a'..'n'] + function range(m, n) { + var blnAlpha = typeof m === 'string', + iFirst = blnAlpha ? m.charCodeAt(0) : m, + lstInt = Array.apply( + null, + Array((blnAlpha ? n.charCodeAt(0) : n) - iFirst + 1) + ).map(function (x, i) { + return iFirst + i; + }); + + return blnAlpha ? lstInt.map( + function (x) { + return String.fromCharCode(x); + } + ) : lstInt; + } + + // Letter label for first column (last column will be 'Z') + var strFirstCol = String.fromCharCode('Z'.charCodeAt(0) - (lngCols - 1)); + + var lstData = [[''].concat(range(strFirstCol, 'Z'))].concat( + range(1, lngRows).map( + function (row) { + return [row].concat( + range(1, lngCols).map( + function () { + return Math.floor( + Math.random() * 9999 + ); + } + ) + ); + } + ) + ); + + return [ + '

" < \v-1/<>">elb" +<^ >:#,_$10 |!:<>\#v_ vv"ta" +v-",":\-"&":\-"<":\<>5#05#"/"v +>#v_$$$0">dt<>dt/<"vv"tr>"+<5 v"<"< +>^>\#v_$$0";pma&" v>"/<>d"v5 v , < +$ > \#v_$0";tl&"v v" : | +^_>#!,#:<>#<0#<\#<<< >:#,_$#^_v@ $< diff --git a/Task/CSV-to-HTML-translation/Befunge/csv-to-html-translation-2.bf b/Task/CSV-to-HTML-translation/Befunge/csv-to-html-translation-2.bf new file mode 100644 index 0000000000..0b77e5d433 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Befunge/csv-to-html-translation-2.bf @@ -0,0 +1,8 @@ + + + + + + + +
CharacterSpeech
The multitudeThe messiah! Show us the messiah!
Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitudeWho are you?
Brians motherI'm his mother; that's who!
The multitudeBehold his mother! Behold his mother!
diff --git a/Task/CSV-to-HTML-translation/Bracmat/csv-to-html-translation-1.bracmat b/Task/CSV-to-HTML-translation/Bracmat/csv-to-html-translation-1.bracmat new file mode 100644 index 0000000000..76229ed672 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Bracmat/csv-to-html-translation-1.bracmat @@ -0,0 +1,31 @@ +( ( CSVtoHTML + = p q Character Speech swor rows row + . 0:?p + & :?swor:?rows + & ( @( !arg + : ? + ( [!p ?Character "," ?Speech \n [?q ? + & !q:?p + & (tr.,(td.,!Character) (td.,!Speech)) + !swor + : ?swor + & ~ + ) + ) + | whl + ' ( !swor:%?row %?swor + & !row \n !rows:?rows + ) + & toML + $ (table.,(thead.,!swor) \n (tbody.,!rows)) + ) + ) +& CSVtoHTML + $ "Character,Speech +The multitude,The messiah! Show us the messiah! +Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +The multitude,Who are you? +Brians mother,I'm his mother; that's who! +The multitude,Behold his mother! Behold his mother! +" +) diff --git a/Task/CSV-to-HTML-translation/Bracmat/csv-to-html-translation-2.bracmat b/Task/CSV-to-HTML-translation/Bracmat/csv-to-html-translation-2.bracmat new file mode 100644 index 0000000000..0b206f3076 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Bracmat/csv-to-html-translation-2.bracmat @@ -0,0 +1,7 @@ + + + + + + +
CharacterSpeech
The multitudeThe messiah! Show us the messiah!
Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitudeWho are you?
Brians motherI'm his mother; that's who!
The multitudeBehold his mother! Behold his mother!
diff --git a/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation.euphoria b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.euphoria similarity index 100% rename from Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation.euphoria rename to Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-1.euphoria diff --git a/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.euphoria b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.euphoria new file mode 100644 index 0000000000..0964db10ff --- /dev/null +++ b/Task/CSV-to-HTML-translation/Euphoria/csv-to-html-translation-2.euphoria @@ -0,0 +1,8 @@ + + + + + + + +
CharacterSpeech
The multitudeThe messiah! Show us the messiah!
Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitudeWho are you?
Brians motherI'm his mother; that's who!
The multitudeBehold his mother! Behold his mother!
diff --git a/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia new file mode 100644 index 0000000000..1aed96274e --- /dev/null +++ b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia @@ -0,0 +1,66 @@ +function csv2html(fname::ASCIIString; header::Bool=false) + csv = readcsv(fname) + @assert(length(csv) > 0) + str = """ + + + + + + + +

csv2html Example

+ + +""" + tags = header ? ("") : ("") + + for i=1:size(csv, 2) + str *= " " * tags[1] * csv[1, i] * tags[2] * "\n" + end + + str *= " "^8 * "\n" + + for i=2:size(csv, 1) + str *= " \n" + + for j=1:size(csv, 2) + str *= " " * "\n" + end + + str *= " \n" + end + + str * "
", "", "
" * csv[i, j] * "
\n\n\n\n" +end + +print(csv2html("input.csv", header=true)) diff --git a/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia new file mode 100644 index 0000000000..930691c88b --- /dev/null +++ b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia @@ -0,0 +1,66 @@ + + + + + + + +

csv2html Example

+ + + + + + + + + + + + + + + + + + + + + + + + + +
CharacterSpeech
The multitudeThe messiah! Show us the messiah!
Brians motherNow you listen here! He's not the messiah; he's a very naughty boy! Now go away!
The multitudeWho are you?
Brians motherI'm his mother; that's who!
The multitudeBehold his mother! Behold his mother!
+ + + diff --git a/Task/CSV-to-HTML-translation/Perl-6/csv-to-html-translation-1.pl6 b/Task/CSV-to-HTML-translation/Perl-6/csv-to-html-translation-1.pl6 index 488d58fcf5..c171689eae 100644 --- a/Task/CSV-to-HTML-translation/Perl-6/csv-to-html-translation-1.pl6 +++ b/Task/CSV-to-HTML-translation/Perl-6/csv-to-html-translation-1.pl6 @@ -8,7 +8,7 @@ The multitude,Behold his mother! Behold his mother!"; # comment the next line out, if you want to read from standard input instead of the hard-coded $str above # my $str = $*IN.slurp; -my &escape = *.trans([ <& < \>>] => [<& < >> ]); # a function with one argument that escapes the entities +my &escape = *.trans(« & < > » => « & < > »); # a function with one argument that escapes the entities my &tag = {"<$^tag>"~$^what~""}; printf diff --git a/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation.rexx b/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation.rexx index 718c9ae479..8c082edb34 100644 --- a/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation.rexx +++ b/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation.rexx @@ -1,17 +1,17 @@ -/*REXX program to convert CSV ───► HTML table representing the CSV data.*/ -arg header_ . /*see if the user wants a header.*/ -wantsHdr= (header_=='HEADER') /*arg (low/upp/mix case)=HEADER ?*/ +/*REXX program converts CSV ───► HTML table representing the CSV data. */ +arg header_ . /*determine if the user wants a header.*/ +wantsHdr= (header_=='HEADER') /*is the arg (low/upp/mix case)=HEADER?*/ - iFID= 'CSV_HTML.TXT' /*the input fileID. */ -if wantsHdr then oFID= 'OUTPUTH.HTML' /*output fileID with header, */ - else oFID= 'OUTPUT.HTML' /* " " without header. */ + iFID= 'CSV_HTML.TXT' /*the input fileID to be used. */ +if wantsHdr then oFID= 'OUTPUTH.HTML' /*the output fileID with header.*/ + else oFID= 'OUTPUT.HTML' /* " " " without " */ - do rows=0 while lines(iFID)\==0 /*read the rows from a (txt) file*/ + do rows=0 while lines(iFID)\==0 /*read the rows from a (text/txt) file.*/ row.rows=strip(linein(iFID)) end /*rows*/ -convFrom= '& < > "' /*special characters to convert. */ -convTo = '& < > "' /*what they are converted into. */ +convFrom= '& < > "' /*special characters to be converted. */ +convTo = '& < > "' /*display what they are converted into.*/ call write , '' call write , '' @@ -22,7 +22,7 @@ call write , '
' do while row.j\==''; parse var row.j yyy ',' row.j do k=1 for words(convFrom) - yyy=changestr(word(convFrom,k),yyy,word(convTo,k)) + yyy=changestr(word(convFrom, k), yyy, word(convTo, k)) end /*k*/ call write 10, '<'tx">"yyy'" end /*forever*/ @@ -31,6 +31,6 @@ call write , '
' call write 5, '' call write , '
' call write , '' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────WRITE subroutine────────────────────*/ -write: call lineout oFID, left('', 0 || arg(1))arg(2); return +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +write: call lineout oFID, left('', 0 || arg(1))arg(2); return diff --git a/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vb b/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vb new file mode 100644 index 0000000000..2eadb9ed6f --- /dev/null +++ b/Task/CSV-to-HTML-translation/VBScript/csv-to-html-translation.vb @@ -0,0 +1,33 @@ +Set objfso = CreateObject("Scripting.FileSystemObject") + +parent_folder = objfso.GetParentFolderName(WScript.ScriptFullName) & "\" + +Set objcsv = objfso.OpenTextFile(parent_folder & "in.csv",1,False) +Set objhtml = objfso.OpenTextFile(paren_folder & "out.html",2,True) + +objhtml.Write(csv_to_html(objcsv.ReadAll)) + +objcsv.Close +objhtml.Close +Set objfso = Nothing + +Function csv_to_html(s) + row = Split(s,vbCrLf) + 'write the header + tmp = "" + For i = 0 To UBound(row) + field = Split(row(i),",") + If i = 0 Then + tmp = tmp & "" + Else + tmp = tmp & "" + End If + Next + 'write the footer + tmp = tmp & "
" & replace_chars(field(0)) & "" & replace_chars(field(1)) & "
" & replace_chars(field(0)) & "" & replace_chars(field(1)) & "
" + csv_to_html = tmp +End Function + +Function replace_chars(s) + replace_chars = Replace(Replace(s,"<","<"),">",">") +End Function diff --git a/Task/Caesar-cipher/Elena/caesar-cipher.elena b/Task/Caesar-cipher/Elena/caesar-cipher.elena index 9df8aff7d5..cc3b8381b7 100644 --- a/Task/Caesar-cipher/Elena/caesar-cipher.elena +++ b/Task/Caesar-cipher/Elena/caesar-cipher.elena @@ -1,74 +1,71 @@ #define system. #define system'routines. -#define extensions. #define system'math. - -// --- Constants --- +#define extensions. #symbol Letters = "abcdefghijklmnopqrstuvwxyz". #symbol BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ". #symbol TestText = "Pack my box with five dozen liquor jugs.". #symbol Key = 12. -// --- Encrypt / Decript --- - -#class Encrypting +#class Encrypting :: Enumerator { #field theKey. - #field theExtendee. + #field theEnumerator. - #constructor new : aKey &extending:anObject + #constructor new &key:aKey &text:aText [ theKey := aKey. - theExtendee := anObject. + theEnumerator := aText enumerator. ] - #method eval : aChar + #method next => theEnumerator. + + #method reset => theEnumerator. + + #method get [ - #var anIndex := Letters indexOf &index:0 &char:aChar. + #var aChar := theEnumerator get. + + #var anIndex := Letters indexOf:0:aChar. (-1 < anIndex) ? [ - theExtendee eval:(Letters @ ((theKey+anIndex) int mod:26)) + ^ Letters @ ((theKey+anIndex) mod:26). ] ! [ - anIndex := BigLetters indexOf &index:0 &char:aChar. + anIndex := BigLetters indexOf:0:aChar. (-1 < anIndex) ? [ - theExtendee eval:(BigLetters @ ((theKey+anIndex) int mod:26)) + ^ BigLetters @ ((theKey+anIndex) mod:26). ] ! [ - theExtendee eval:aChar. + ^ aChar. ]. ]. ] - - #method => theExtendee. } -// --- Functions --- - -#symbol encrypt = (:aText:aKey) - [ Encrypting new:aKey &extending:(Summing new:(String new)) foreach:aText literal ]. - -#symbol decrypt = (:aText:aKey) - [ Encrypting new:(26 - aKey) &extending:(Summing new:(String new)) foreach:aText literal ]. +#class(extension)encryptOp +{ + #method encrypt : aKey + = Encrypting new &key:aKey &text:self summarize:(String new). -// --- Program --- + #method decrypt :aKey + = Encrypting new &key:(26 - aKey) &text:self summarize:(String new). +} #symbol program = [ - #var anS := TestText. - - consoleEx writeLine:"Original text :" :anS. + console writeLine:"Original text :" :TestText. - anS := encrypt:anS:Key. + #var anEncryptedText := TestText encrypt:Key. - consoleEx writeLine:"Encrypted text:" :anS. + console writeLine:"Encrypted text:" :anEncryptedText. - anS := decrypt:anS:Key. + #var aDecryptedText := anEncryptedText decrypt:Key. - consoleEx writeLine:"Decrypted text:" :anS. + console writeLine:"Decrypted text:" :aDecryptedText. - consoleEx readChar. + console readChar. ]. diff --git a/Task/Caesar-cipher/Elixir/caesar-cipher.elixir b/Task/Caesar-cipher/Elixir/caesar-cipher.elixir new file mode 100644 index 0000000000..7c6141999a --- /dev/null +++ b/Task/Caesar-cipher/Elixir/caesar-cipher.elixir @@ -0,0 +1,18 @@ +defmodule Caesar_cipher do + defp set_map(map, range, key) do + org = Enum.map(range, &List.to_string [&1]) + {a, b} = Enum.split(org, key) + Enum.zip(org, b ++ a) |> Enum.into(map) + end + + def encode(text, key) do + map = Map.new |> set_map(?a..?z, key) |> set_map(?A..?Z, key) + String.codepoints(text) |> Enum.map_join(fn c -> Dict.get(map, c, c) end) + end +end + +text = "The five boxing wizards jump quickly" +key = 3 +IO.puts "Original: #{text}" +IO.puts "Encrypted: #{enc = Caesar_cipher.encode(text, key)}" +IO.puts "Decrypted: #{Caesar_cipher.encode(enc, -key)}" diff --git a/Task/Caesar-cipher/R/caesar-cipher.r b/Task/Caesar-cipher/R/caesar-cipher.r new file mode 100644 index 0000000000..283d761aa9 --- /dev/null +++ b/Task/Caesar-cipher/R/caesar-cipher.r @@ -0,0 +1,26 @@ +# based on Rot-13 solution: http://rosettacode.org/wiki/Rot-13#R +ceasar <- function(x, key) +{ + # if key is negative, wrap to be positive + if (key < 0) { + key <- 26 + key + } + + old <- paste(letters, LETTERS, collapse="", sep="") + new <- paste(substr(old, key * 2 + 1, 52), substr(old, 1, key * 2), sep="") + chartr(old, new, x) +} + +# simple examples from description +print(ceasar("hi",2)) +print(ceasar("hi",20)) + +# more advanced example +key <- 3 +plaintext <- "The five boxing wizards jump quickly." +cyphertext <- ceasar(plaintext, key) +decrypted <- ceasar(cyphertext, -key) + +print(paste(" Plain Text: ", plaintext, sep="")) +print(paste(" Cypher Text: ", cyphertext, sep="")) +print(paste("Decrypted Text: ", decrypted, sep="")) diff --git a/Task/Calendar/Batch-File/calendar.bat b/Task/Calendar/Batch-File/calendar.bat new file mode 100644 index 0000000000..b08ad43a36 --- /dev/null +++ b/Task/Calendar/Batch-File/calendar.bat @@ -0,0 +1,93 @@ +::Calender Task from Rosetta Code Wiki +::Batch File Implementation + +@echo off +setlocal enabledelayedexpansion + + %== Set a valid year [will not be validated] ==% +set y=1969 + + %== Set the variables for months (feb_l=the normal 28 days) ==% +set jan_l=31&set apr_l=30 +set mar_l=31&set jun_l=30 +set may_l=31&set sep_l=30 +set jul_l=31&set nov_l=30 +set aug_l=31&set feb_l=28 +set oct_l=31 +set dec_l=31 + + %== Compute day for first day of the year ==% +set /a d=(y/4+y)-(y/100-y/400) + + %== Check if that year is a leap year ==% +set /a "op1=y%%4","op2=y%%100","op3=y%%400" +if not "%op1%"=="0" (goto :no_leap) +if not "%op2%"=="0" (goto :yes_leap) +if not "%op3%"=="0" (goto :no_leap) + :yes_leap + %== Ooops... Leap year. Change feb_l to 29. ==% + set feb_l=29 + set/a d-=1 + :no_leap + + %== Compute weekday of the first day... ==% +set /a d%%=7 + + %== Generate everything that's inside the calendar ==% +for %%a in (jan feb mar apr may jun jul aug sep oct nov dec) do ( + set %%a= + set chars_added=0 + for /l %%b in (1,1,!d!) do (set "%%a=!%%a! "&set /a chars_added+=3) + for /l %%c in (1,1,!%%a_l!) do ( + if %%c lss 10 (set "%%a=!%%a! %%c ") else (set "%%a=!%%a!%%c ") + set /a chars_added+=3 + ) + for /l %%d in (!chars_added!,1,124) do set "%%a=!%%a! " + set /a d=^(d+%%a_l^)%%7 +) + + %== Display the calendar ==% +cls +echo. +echo. [SNOOPY] +echo. +echo. YEAR = %y% +echo. +echo. January February March +echo. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa +echo. %jan:~0,20% %feb:~0,20% %mar:~0,20% +echo. %jan:~21,20% %feb:~21,20% %mar:~21,20% +echo. %jan:~42,20% %feb:~42,20% %mar:~42,20% +echo. %jan:~63,20% %feb:~63,20% %mar:~63,20% +echo. %jan:~84,20% %feb:~84,20% %mar:~84,20% +echo. %jan:~105% %feb:~105% %mar:~105% +echo. +echo. April May June +echo. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa +echo. %apr:~0,20% %may:~0,20% %jun:~0,20% +echo. %apr:~21,20% %may:~21,20% %jun:~21,20% +echo. %apr:~42,20% %may:~42,20% %jun:~42,20% +echo. %apr:~63,20% %may:~63,20% %jun:~63,20% +echo. %apr:~84,20% %may:~84,20% %jun:~84,20% +echo. %apr:~105% %may:~105% %jun:~105% +echo. +echo. July August September +echo. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa +echo. %jul:~0,20% %aug:~0,20% %sep:~0,20% +echo. %jul:~21,20% %aug:~21,20% %sep:~21,20% +echo. %jul:~42,20% %aug:~42,20% %sep:~42,20% +echo. %jul:~63,20% %aug:~63,20% %sep:~63,20% +echo. %jul:~84,20% %aug:~84,20% %sep:~84,20% +echo. %jul:~105% %aug:~105% %sep:~105% +echo. +echo. October November December +echo. Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa +echo. %oct:~0,20% %nov:~0,20% %dec:~0,20% +echo. %oct:~21,20% %nov:~21,20% %dec:~21,20% +echo. %oct:~42,20% %nov:~42,20% %dec:~42,20% +echo. %oct:~63,20% %nov:~63,20% %dec:~63,20% +echo. %oct:~84,20% %nov:~84,20% %dec:~84,20% +echo. %oct:~105% %nov:~105% %dec:~105% +echo. +pause +endlocal diff --git a/Task/Calendar/Fortran/calendar.f b/Task/Calendar/Fortran/calendar.f new file mode 100644 index 0000000000..6daabde319 --- /dev/null +++ b/Task/Calendar/Fortran/calendar.f @@ -0,0 +1,283 @@ + MODULE DATEGNASH !Assorted vexations. Time and calendar games, with local flavourings added. + + TYPE DateBag !Pack three parts into one. + INTEGER DAY,MONTH,YEAR !The usual suspects. + END TYPE DateBag !Simple enough. + + CHARACTER*9 MONTHNAME(12),DAYNAME(0:6) !Re-interpretations. + PARAMETER (MONTHNAME = (/"January","February","March","April", + 1 "May","June","July","August","September","October","November", + 2 "December"/)) + PARAMETER (DAYNAME = (/"Sunday","Monday","Tuesday","Wednesday", + 1 "Thursday","Friday","Saturday"/)) !Index this array with DayNum mod 7. + CHARACTER*3 MTHNAME(12) !The standard abbreviations. + PARAMETER (MTHNAME = (/"JAN","FEB","MAR","APR","MAY","JUN", + 1 "JUL","AUG","SEP","OCT","NOV","DEC"/)) + + INTEGER*4 JDAYSHIFT !INTEGER*2 just isn't enough. + PARAMETER (JDAYSHIFT = 2415020) !Thus shall 31/12/1899 give 0, a Sunday, via DAYNUM. + CONTAINS + INTEGER FUNCTION LSTNB(TEXT) !Sigh. Last Not Blank. +Concocted yet again by R.N.McLean (whom God preserve) December MM. +Code checking reveals that the Compaq compiler generates a copy of the string and then finds the length of that when using the latter-day intrinsic LEN_TRIM. Madness! +Can't DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ') !Control chars. regarded as spaces. +Curse the morons who think it good that the compiler MIGHT evaluate logical expressions fully. +Crude GO TO rather than a DO-loop, because compilers use a loop counter as well as updating the index variable. +Comparison runs of GNASH showed a saving of ~3% in its mass-data reading through the avoidance of DO in LSTNB alone. +Crappy code for character comparison of varying lengths is avoided by using ICHAR which is for single characters only. +Checking the indexing of CHARACTER variables for bounds evoked astounding stupidities, such as calculating the length of TEXT(L:L) by subtracting L from L! +Comparison runs of GNASH showed a saving of ~25-30% in its mass data scanning for this, involving all its two-dozen or so single-character comparisons, not just in LSTNB. + CHARACTER*(*),INTENT(IN):: TEXT !The bumf. If there must be copy-in, at least there need not be copy back. + INTEGER L !The length of the bumf. + L = LEN(TEXT) !So, what is it? + 1 IF (L.LE.0) GO TO 2 !Are we there yet? + IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2 !Control chars are regarded as spaces also. + L = L - 1 !Step back one. + GO TO 1 !And try again. + 2 LSTNB = L !The last non-blank, possibly zero. + RETURN !Unsafe to use LSTNB as a variable. + END FUNCTION LSTNB !Compilers can bungle it. + CHARACTER*2 FUNCTION I2FMT(N) !These are all the same. + INTEGER*4 N !But, the compiler doesn't offer generalisations. + IF (N.LT.0) THEN !Negative numbers cop a sign. + IF (N.LT.-9) THEN !But there's not much room left. + I2FMT = "-!" !So this means 'overflow'. + ELSE !Otherwise, room for one negative digit. + I2FMT = "-"//CHAR(ICHAR("0") - N) !Thus. Presume adjacent character codes, etc. + END IF !So much for negative numbers. + ELSE IF (N.LT.10) THEN !Single digit positive? + I2FMT = " " //CHAR(ICHAR("0") + N) !Yes. This. + ELSE IF (N.LT.100) THEN !Two digit positive? + I2FMT = CHAR(N/10 + ICHAR("0")) !Yes. + 1 //CHAR(MOD(N,10) + ICHAR("0")) !These. + ELSE !Otherwise, + I2FMT = "+!" !Positive overflow. + END IF !So much for that. + END FUNCTION I2FMT !No WRITE and FORMAT unlimbering. + CHARACTER*8 FUNCTION I8FMT(N) !Oh for proper strings. + INTEGER*4 N + CHARACTER*8 HIC + WRITE (HIC,1) N + 1 FORMAT (I8) + I8FMT = HIC + END FUNCTION I8FMT + + SUBROUTINE SAY(OUT,TEXT) !Gutted version that maintains no file logging output, etc. + INTEGER OUT + CHARACTER*(*) TEXT + WRITE (6,1) TEXT(1:LSTNB(TEXT)) + 1 FORMAT (A) + END SUBROUTINE SAY + + INTEGER*4 FUNCTION DAYNUM(YY,M,D) !Computes (JDayN - JDayShift), not JDayN. +C Conversion from a Gregorian calendar date to a Julian day number, JDayN. +C Valid for any Gregorian calendar date producing a Julian day number +C greater than zero, though remember that the Gregorian calendar +C was not used before y1582m10d15 and often, not after that either. +C thus in England (et al) when Wednesday 2'nd September 1752 (Julian style) +C was followed by Thursday the 14'th, occasioning the Eleven Day riots +C because creditors demanded a full month's payment instead of 19/30'ths. +C The zero of the Julian day number corresponds to the first of January +C 4713BC on the *Julian* calendar's naming scheme, as extended backwards +C with current usage into epochs when it did not exist: the proleptic Julian calendar. +c This function employs the naming scheme of the *Gregorian* calendar, +c and if extended backwards into epochs when it did not exist (thus the +c proleptic Gregorian calendar) it would compute a zero for y-4713m11d24 *if* +c it is supposed there was a year zero between 1BC and 1AD (as is convenient +c for modern mathematics and astronomers and their simple calculations), *but* +c 1BC immediately preceeds 1AD without any year zero in between (and is a leap year) +c thus the adjustment below so that the date is y-4714m11d24 or 4714BCm11d24, +c not that this name was in use at the time... +c Although the Julian calendar (introduced by himself in what we would call 45BC, +c which was what the Romans occasionally called 709AUC) was provoked by the +c "years of confusion" resulting from arbitrary application of the rules +c for the existing Roman calendar, other confusions remain unresolved, +c so precise dating remains uncertain despite apparently precise specifications +c (and much later, Dennis the Short chose wrongly for the birth of Christ) +c and the Roman practice of inclusive reckoning meant that every four years +c was interpreted as every third (by our exclusive reckoning) so that the +c leap years were not as we now interpret them. This was resolved by Augustus +c but exactly when (and what date name is assigned) and whose writings used +c which system at the time of writing is a matter of more confusion, +c and this has continued for centuries. +C Accordingly, although an algorithm may give a regular sequence of date names, +c that does not mean that those date names were used at the time even if the +c calendar existed then, because the interpretation of the algorithm varied. +c This in turn means that a date given as being on the Julian calendar +c prior to about 10AD is not as definite as it may appear and its alignment +c with the astronomical day number is uncertain even though the calculation +c is quite definite. +c +C Computationally, year 1 is preceded by year 0, in a smooth progression. +C But there was never a year zero despite what astronomers like to say, +C so the formula's year 0 corresponds to 1BC, year -1 to 2BC, and so on back. +C Thus y-4713 in this counting would be 4714BC on the Gregorian calendar, +C were it to have existed then which it didn't. +C To conform to the civil usage, the incoming YY, presumed a proper BC (negative) +C and AD (positive) year is converted into the computational counting sequence, Y, +C and used in the formula. If a YY = 0 is (improperly) offered, it will manifest +C as 1AD. Thus YY = -4714 will lead to calculations with Y = -4713. +C Thus, 1BC is a leap year on the proleptic Gregorian calendar. +C For their convenience, astronomers decreed that a day starts at noon, so that +C in Europe, observations through the night all have the same day number. +C The current Western civil calendar however has the day starting just after midnight +C and that day's number lasts until the following midnight. +C +C There is no constraint on the values of D, which is just added as it stands. +C This means that if D = 0, the daynumber will be that of the last day of the +C previous month. Likewise, M = 0 or M = 13 will wrap around so that Y,M + 1,0 +C will give the last day of month M (whatever its length) as one day before +C the first day of the next month. +C +C Example: Y = 1970, M = 1, D = 1; JDAYN = 2440588, a Thursday but MOD(2440588,7) = 3. +C and with the adjustment JDAYSHIFT, DAYNUM = 25568; mod 7 = 4 and DAYNAME(4) = "Thursday". +C The Julian Day number 2440588.0 is for NOON that Thursday, 2440588.5 is twelve hours later. +C And Julian Day number 2440587.625 is for three a.m. Thursday. +C +C DAYNUM and MUNYAD are the infamous routines of H. F. Fliegel and T.C. van Flandern, +C presented in Communications of the ACM, Vol. 11, No. 10 (October, 1968). +Carefully typed in again by R.N.McLean (whom God preserve) December XXMMIIX. +C Though I remain puzzled as to why they used I,J,K for Y,M,D, +C given that the variables were named in the INTEGER statement anyway. + INTEGER*4 JDAYN !Without rebasing, this won't fit in INTEGER*2. + INTEGER YY,Y,M,MM,D !NB! Full year number, so 1970, not 70. +Caution: integer division in Fortran does not produce fractional results. +C The fractional part is discarded so that 4/3 gives 1 and -4/3 gives -1. +C Thus 4/3 might be Trunc(4/3) or 4 div 3 in other languages. Beware of negative numbers! + Y = YY !I can fiddle this copy without damaging the original's value. + IF (Y.LT.1) Y = Y + 1 !Thus YY = -2=2BC, -1=1BC, +1=1AD, ... becomes Y = -1, 0, 1, ... + MM = (M - 14)/12 !Calculate once. Note that this is integer division, truncating. + JDAYN = D - 32075 !This is the proper astronomer's Julian Day Number. + a + 1461*(Y + 4800 + MM)/4 + b + 367*(M - 2 - MM*12)/12 + c - 3*((Y + 4900 + MM)/100)/4 + DAYNUM = JDAYN - JDAYSHIFT !Thus, *NOT* the actual *Julian* Day Number. + END FUNCTION DAYNUM !But one such that Mod(n,7) gives day names. + +Could compute the day of the year somewhat as follows... +c DN:=D + (61*Month + (Month div 8)) div 2 - 30 +c + if Month > 2 then FebLength - 30 else 0; + + TYPE(DATEBAG) FUNCTION MUNYAD(DAYNUM) !Oh for palindromic programming! +Conversion from a Julian day number to a Gregorian calendar date. See JDAYN/DAYNUM. + INTEGER*4 DAYNUM,JDAYN !Without rebasing, this won't fit in INTEGER*2. + INTEGER Y,M,D,L,N !Y will be a full year number: 1950 not 50. + JDAYN = DAYNUM + JDAYSHIFT !Revert to a proper Julian day number. + L = JDAYN + 68569 !Further machinations of H. F. Fliegel and T.C. van Flandern. + N = 4*L/146097 + L = L - (146097*N + 3)/4 + Y = 4000*(L + 1)/1461001 + L = L - 1461*Y/4 + 31 + M = 80*L/2447 + D = L - 2447*M/80 + L = M/11 + M = M + 2 - 12*L + Y = 100*(N - 49) + Y + L + IF (Y.LT.1) Y = Y - 1 !The other side of conformity to BC/AD, as in DAYNUM. + MUNYAD%YEAR = Y !Now place for the world to see. + MUNYAD%MONTH = M + MUNYAD%DAY = D + END FUNCTION MUNYAD !A year has 365.2421988 days... + + INTEGER FUNCTION PMOD(N,M) !Remainder, mod M; always positive even if N is negative. +c For date calculations, the MOD function is expected to yield positive remainders, +c in line with the idea that MOD(a,b) = MOD(a ± b,b) as is involved in shifting the zero +c of the daynumber count by a multiple of seven when considering the day of the week. +c For this reason, the zero day was chosen to be 31/12/1899, a Sunday, so that all +c day numbers would be positive. But, there was generation at Reefton in 1886. +c For some computers, the positive interpretation is implemented, for others, not. +c In the case MOD(N,M) = N - Truncate(N/M)*M, MOD(-6,7) = -6 even though MOD(1,7) = 1. + INTEGER N,M !The numbers. M presumed positive. + PMOD = MOD(MOD(N,M) + M,M) !Double do does de deed. + END FUNCTION PMOD !Simple enough. + + SUBROUTINE CALENDAR(Y1,Y2,COLUMNS) !Print a calendar, with holiday annotations. +Careful with the MOD function. MOD(-6,7) may be negative on some systems, positive on others. Thus, PMOD. + INTEGER Y1,Y2,YEAR !Ah yes. Year stuff. + INTEGER M,M1,M2,MONTH !And within each year are the months. + INTEGER*4 DN1,DN2,DN,D !But days are handled via day numbers. + INTEGER W,G !Layout: width and gap. + INTEGER L,LINE !Vertical layout. + INTEGER COL,COLUMNS,COLWIDTH !Horizontal layout. + INTEGER CODE !Days are not all alike. + CHARACTER*200 STRIPE(6),SPECIAL(6),MLINE,DLINE !Scratchpads. + IF (Y1.LE.0) CALL SAY(MSG,"Despite the insinuations of " + 1 //"astronomers seduced by the ease of their arithmetic, " + 2 //"there is no year zero. 1AD is preceded by 1BC, " + 3 //"corresponding to year -1, 2BC to year -2, etc.") + IF (Y1.LT.1582) CALL SAY(MSG,"This Gregorian calendar" + 1 //" scheme did not exist prior to 1582.") +c COLUMNS = 4 !Number of months across the page. +c W = 4 !Width of a day's field. +c G = 3 !Added gap between month columns. + W = 3 !Abandon the annotation of the day's class, so just a space and two digits. + G = 1 ! + COLWIDTH = 7*W + G !Seven days to a week, plus a gap. + Y:DO YEAR = Y1,Y2 !Step through the years. + CALL SAY(MSG,"") !Space out between each year's schedule. + IF (YEAR.EQ.0) THEN !This year number is improper. + CALL SAY(MSG,"There is no year zero.") !Declare correctness. + CYCLE Y !Skip this year. + END IF !Otherwise, no evasions. + MLINE = "" !Prepare a field.. + L = (COLUMNS*COLWIDTH - G - 8)/2 !Find the centre. + IF (YEAR.GT.0) THEN !Ordinary Anno Domine years? + MLINE(L:) = I8FMT(YEAR) !Yes. Place the year number. + ELSE !Otherwise, we're in BC. + MLINE(L - 1:) = I8FMT(-YEAR)//"BC" !There is no year zero. + END IF !So much for year games. + CALL SAY(MSG,MLINE) !Splot the year. + DO MONTH = 1,12,COLUMNS !Step through the months of this YEAR. + M1 = MONTH !The first of this lot. + M2 = MIN(12,M1 + COLUMNS - 1) !The last. + MLINE = "" !Scrub the month names. + DLINE = "" !Wipe the day names in case COLUMNS does not divide 12. + STRIPE = "" !Scrub the day table. + SPECIAL = "" !And the associated special day remarks. +c L0 = W - 1 !Locate the first day number's first column. + L0 = 1 !Cram: no space in front of the Sunday day-of-the-month. + DO M = M1,M2 !Work through the months. + L = (COLWIDTH - G - LSTNB(MONTHNAME(M)))/2 - 1 !Centre the month name. + MLINE(L0 + L:) = MONTHNAME(M) !Splot. + DO D = 0,6 !Prepare this month's day name heading. + L = L0 + (3 - W) + D*W !Locate its first column. + DLINE(L:L + 2) = DAYNAME(D)(1:W - 1) !Squish. + END DO !On to the next day. + DN1 = DAYNUM(YEAR,M,1) !Day number of the first day of the month. + DN2 = DAYNUM(YEAR,M + 1,0)!Thus the last, without annoyance. + COL = MOD(PMOD(DN1,7) + 7,7) !What day of the week is the first day? + LINE = 1 !Whichever it is, it is on the first line. + D = 1 !Day of the month, not number of the day. + DO DN = DN1,DN2 !Step through the day numbers of this month. + L = L0 + COL*W !Finger the starting column. + STRIPE(LINE)(L:L + 1) = I2FMT(D) !Place the two-digit day number. + D = D + 1 !Advance to the next day of the current month + COL = COL + 1 !So, one more day along in the week. + IF (COL.GT.6) THEN !A fresh week is needed? + LINE = LINE + 1 !Yes. + COL = 0 !Start the new week. + END IF !So much for the end of a week. + END DO !On to the next day of this month. + L0 = L0 + 7*W + G !Locate the start column of the next month's column. + END DO !On to the next month in this layer. + CALL SAY(MSG,MLINE) !Name the months. +C CALL SAY(MSG,"") !Set off. + CALL SAY(MSG,DLINE) !Give the day name headings. + DO LINE = 1,6 !Now roll the day number table. + IF (STRIPE(LINE).NE."") THEN !Perhaps there was no use of the sixth line. + CALL SAY(MSG,STRIPE(LINE)) !Ah well. Show the day numbers. + END IF !So much for that week line. + END DO !On to the next week line. + END DO !On to the next batch of months of the YEAR. + END DO Y !On to the next YEAR. + CALL SAY(MSG,"") !Take a breath. + END SUBROUTINE CALENDAR !Enough of this. + END MODULE DATEGNASH !An ad-hoc assemblage. + + PROGRAM SHOW1968 !Put it to the test. + USE DATEGNASH + INTEGER NCOL + DO NCOL = 1,6 + CALL CALENDAR(1969,1969,NCOL) + END DO + END diff --git a/Task/Calendar/Racket/calendar.rkt b/Task/Calendar/Racket/calendar.rkt index 3494429752..a6faa684ad 100644 --- a/Task/Calendar/Racket/calendar.rkt +++ b/Task/Calendar/Racket/calendar.rkt @@ -1,5 +1,5 @@ #lang racket -(require racket/date) +(require racket/date net/base64 file/gunzip) (define (calendar yr) (define (nsplit n l) (if (null? l) l (cons (take l n) (nsplit n (drop l n))))) (define months @@ -18,14 +18,12 @@ ,@(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#2X3x7! 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* #rx"!" (string-append* s) "\n")] - [s (regexp-replace* #rx".(?:[1-7][0-9]*|[1-9])" s - (λ(m) (make-string (string->number (substring m 1)) - (string-ref m 0))))]) - (printf s yr)) + (let ([s #"nZA7CsAgDED3nCLgoAU/3Uvv4SCE3qKD5OyNWvoBhdIHSswjMYp4YR2z80Tk8StOgP + sY0EyrMZOE6WsL3u4G5lyV+d8MyVOy8hZBt7RSMca9Ac/KUIs1L/BOysb50XMtMzEj + ZqiuRxIVqI+4kSpy7GqpXNsz+bfpfWIGOAA="] + [o (open-output-string)]) + (inflate (open-input-bytes (base64-decode s)) o) + (display (regexp-replace #rx"~a" (get-output-string o) (~a yr)))) (for-each displayln (dropf-right (for*/list ([3ms (nsplit 3 months)] [s (apply map list 3ms)]) (regexp-replace #rx" +$" (string-join s " ") "")) diff --git a/Task/Call-a-foreign-language-function/ALGOL-68/call-a-foreign-language-function.alg b/Task/Call-a-foreign-language-function/ALGOL-68/call-a-foreign-language-function.alg new file mode 100644 index 0000000000..37a70f665a --- /dev/null +++ b/Task/Call-a-foreign-language-function/ALGOL-68/call-a-foreign-language-function.alg @@ -0,0 +1,67 @@ +BEGIN + MODE PASSWD = STRUCT (STRING name, passwd, INT uid, gid, STRING gecos, dir, shell); + PROC getpwnam = (STRING name) PASSWD : + BEGIN + FILE c source; + create (c source, stand out channel); + putf (c source, ($gl$, +"#include ", +"#include ", +"#include ", +"main ()", +"{", +" char name[256];", +" scanf (""%s"", name);", +" struct passwd *pass = getpwnam (name);", +" if (pass == (struct passwd *) NULL) {", +" putchar ('\n');", +" } else {", +" printf (""%s\n"", pass->pw_name);", +" printf (""%s\n"", pass->pw_passwd);", +" printf (""%d\n"", pass->pw_uid);", +" printf (""%d\n"", pass->pw_gid);", +" printf (""%s\n"", pass->pw_gecos);", +" printf (""%s\n"", pass->pw_dir);", +" printf (""%s\n"", pass->pw_shell);", +" }", +"}" + )); + STRING source name = idf (c source); + STRING bin name = source name + ".bin"; + INT child pid = execve child ("/usr/bin/gcc", + ("gcc", "-x", "c", source name, "-o", bin name), + ""); + wait pid (child pid); + PIPE p = execve child pipe (bin name, "Ding dong, a68g calling", ""); + put (write OF p, (name, newline)); + STRING line; + PASSWD result; + IF get (read OF p, (line, newline)); line = "" + THEN + result := ("", "", -1, -1, "", "", "") + CO + Return to sender, address unknown. + No such number, no such zone. + CO + ELSE + name OF result := line; + get (read OF p, (passwd OF result, newline)); + get (read OF p, (uid OF result, newline)); + get (read OF p, (gid OF result, newline)); + get (read OF p, (gecos OF result, newline)); + get (read OF p, (dir OF result, newline)); + get (read OF p, (shell OF result, newline)) + FI; + close (write OF p); CO Sundry cleaning up. CO + close (read OF p); + execve child ("/bin/rm", ("rm", "-f", source name, bin name), ""); + result + END; + PASSWD mr root = getpwnam ("root"); + IF name OF mr root = "" + THEN + print (("Oh dear, we seem to be rootless.", newline)) + ELSE + printf (($2(g,":"), 2(g(0),":"), 2(g,":"), gl$, mr root)) + FI +END diff --git a/Task/Call-a-foreign-language-function/Clojure/call-a-foreign-language-function-1.clj b/Task/Call-a-foreign-language-function/Clojure/call-a-foreign-language-function-1.clj new file mode 100644 index 0000000000..a8ed54fd1e --- /dev/null +++ b/Task/Call-a-foreign-language-function/Clojure/call-a-foreign-language-function-1.clj @@ -0,0 +1 @@ +(JNIDemo/callStrdup "Hello World!") diff --git a/Task/Call-a-foreign-language-function/Clojure/call-a-foreign-language-function-2.clj b/Task/Call-a-foreign-language-function/Clojure/call-a-foreign-language-function-2.clj new file mode 100644 index 0000000000..1d17539ae7 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Clojure/call-a-foreign-language-function-2.clj @@ -0,0 +1,7 @@ +(require '[net.n01se.clojure-jna :as jna]) + +(jna/invoke Integer c/strcmp "apple" "banana" ) ; returns -1 + +(jna/invoke Integer c/strcmp "banana" "apple" ) ; returns 1 + +(jna/invoke Integer c/strcmp "banana" "banana" ) ; returns 0 diff --git a/Task/Call-a-foreign-language-function/Fortran/call-a-foreign-language-function-1.f b/Task/Call-a-foreign-language-function/Fortran/call-a-foreign-language-function-1.f new file mode 100644 index 0000000000..7da5cb19c8 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Fortran/call-a-foreign-language-function-1.f @@ -0,0 +1,4 @@ +double add_n(double* a, double* b) +{ +return *a + *b; +} diff --git a/Task/Call-a-foreign-language-function/Fortran/call-a-foreign-language-function-2.f b/Task/Call-a-foreign-language-function/Fortran/call-a-foreign-language-function-2.f new file mode 100644 index 0000000000..e4b8166b06 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Fortran/call-a-foreign-language-function-2.f @@ -0,0 +1,258 @@ +!----------------------------------------------------------------------- +!module dll_module +!----------------------------------------------------------------------- +module dll_module + use iso_c_binding + implicit none + private ! all by default + public :: os_type, dll_type, load_dll, free_dll, init_os_type, init_dll + ! general constants: + ! the number of bits in an address (32-bit or 64-bit). + integer, parameter :: bits_in_addr = c_intptr_t*8 + ! global error-level variables: + integer, parameter :: errid_none = 0 + integer, parameter :: errid_info = 1 + integer, parameter :: errid_warn = 2 + integer, parameter :: errid_severe = 3 + integer, parameter :: errid_fatal = 4 + + integer :: os_id + + type os_type + character(10) :: endian + character(len=:), allocatable :: newline + character(len=:), allocatable :: os_desc + character(1) :: pathsep + character(1) :: swchar + character(11) :: unfform + end type os_type + + type dll_type + integer(c_intptr_t) :: fileaddr + type(c_ptr) :: fileaddrx + type(c_funptr) :: procaddr + character(1024) :: filename + character(1024) :: procname + end type dll_type + + ! interface to linux API + interface + function dlopen(filename,mode) bind(c,name="dlopen") + ! void *dlopen(const char *filename, int mode); + use iso_c_binding + implicit none + type(c_ptr) :: dlopen + character(c_char), intent(in) :: filename(*) + integer(c_int), value :: mode + end function + + function dlsym(handle,name) bind(c,name="dlsym") + ! void *dlsym(void *handle, const char *name); + use iso_c_binding + implicit none + type(c_funptr) :: dlsym + type(c_ptr), value :: handle + character(c_char), intent(in) :: name(*) + end function + + function dlclose(handle) bind(c,name="dlclose") + ! int dlclose(void *handle); + use iso_c_binding + implicit none + integer(c_int) :: dlclose + type(c_ptr), value :: handle + end function + end interface + +contains + + + !----------------------------------------------------------------------- + !Subroutine init_dll + !----------------------------------------------------------------------- + subroutine init_dll(dll) + implicit none + type(dll_type), intent(inout) :: dll + dll % fileaddr = 0 + dll % fileaddrx = c_null_ptr + dll % procaddr = c_null_funptr + dll % filename = " " + dll % procname = " " + end subroutine init_dll + + !----------------------------------------------------------------------- + !Subroutine init_os_type + !----------------------------------------------------------------------- + subroutine init_os_type(os_id,os) + implicit none + integer, intent(in) :: os_id + type(os_type), intent(inout) :: os + + select case (os_id) + case (1) ! Linux + + os % endian = 'big_endian' + os % newline = achar(10) + os % os_desc = 'Linux' + os % pathsep = '/' + os % swchar = '-' + os % unfform = 'unformatted' + + case (2) ! MacOS + + os % endian = 'big_endian' + os % newline = achar(10) + os % os_desc = 'MacOS' + os % pathsep = '/' + os % swchar = '-' + os % unfform = 'unformatted' + + case default + + end select + + end subroutine init_os_type + + !----------------------------------------------------------------------- + !Subroutine load_dll + !----------------------------------------------------------------------- + subroutine load_dll (os, dll, errstat, errmsg ) + ! this subroutine is used to dynamically load a dll. + + + type (os_type), intent(in) :: os + type (dll_type), intent(inout) :: dll + integer, intent( out) :: errstat + character(*), intent( out) :: errmsg + + integer(c_int), parameter :: rtld_lazy=1 + integer(c_int), parameter :: rtld_now=2 + integer(c_int), parameter :: rtld_global=256 + integer(c_int), parameter :: rtld_local=0 + + errstat = errid_none + errmsg = '' + + select case (os%os_desc) + case ("Linux","MacOS") + ! load the dll and get the file address: + dll%fileaddrx = dlopen( trim(dll%filename)//c_null_char, rtld_lazy ) + if( .not. c_associated(dll%fileaddrx) ) then + errstat = errid_fatal + write(errmsg,'(i2)') bits_in_addr + errmsg = 'the dynamic library '//trim(dll%filename)//' could not be loaded. check that the file '// & + 'exists in the specified location and that it is compiled for '//trim(errmsg)//'-bit systems.' + return + end if + + ! get the procedure address: + dll%procaddr = dlsym( dll%fileaddrx, trim(dll%procname)//c_null_char ) + if(.not. c_associated(dll%procaddr)) then + errstat = errid_fatal + errmsg = 'the procedure '//trim(dll%procname)//' in file '//trim(dll%filename)//' could not be loaded.' + return + end if + + case ("Windows") + errstat = errid_fatal + errmsg = ' load_dll not implemented for '//trim(os%os_desc) + + case default + errstat = errid_fatal + errmsg = ' load_dll not implemented for '//trim(os%os_desc) + end select + return + end subroutine load_dll + + !----------------------------------------------------------------------- + !Subroutine free_dll + !----------------------------------------------------------------------- + subroutine free_dll (os, dll, errstat, errmsg ) + + ! this subroutine is used to free a dynamically loaded dll + type (os_type), intent(in) :: os + type (dll_type), intent(inout) :: dll + integer, intent( out) :: errstat + character(*), intent( out) :: errmsg + + integer(c_int) :: success + + errstat = errid_none + errmsg = '' + + select case (os%os_desc) + case ("Linux","MacOS") + + ! close the library: + success = dlclose( dll%fileaddrx ) + if ( success /= 0 ) then + errstat = errid_fatal + errmsg = 'the dynamic library could not be freed.' + return + else + errstat = errid_none + errmsg = '' + end if + + case ("Windows") + + errstat = errid_fatal + errmsg = ' free_dll not implemented for '//trim(os%os_desc) + + case default + errstat = errid_fatal + errmsg = ' free_dll not implemented for '//trim(os%os_desc) + end select + + return + end subroutine free_dll +end module dll_module + + + +!----------------------------------------------------------------------- +!Main program +!----------------------------------------------------------------------- +program test_load_dll + use, intrinsic :: iso_c_binding + use dll_module + implicit none + + ! interface to our shared lib + abstract interface + function add_n(a,b) + use, intrinsic :: iso_c_binding + implicit none + real(c_double), intent(in) :: a,b + real(c_double) :: add_n + end function add_n + end interface + + type(os_type) :: os + type(dll_type) :: dll + integer :: errstat + character(1024) :: errmsg + type(c_funptr) :: cfun + procedure(add_n), pointer :: fproc + + call init_os_type(1,os) + call init_dll(dll) + + dll%filename="/full_path_to/shared_lib.so" + ! name of the procedure in shared_lib + dll%procname="add_n" + + write(*,*) "address: ", dll%procaddr + + call load_dll(os, dll, errstat, errmsg ) + write(*,*)"load_dll: errstat=", errstat + write(*,*) "address: ", dll%procaddr + + call c_f_procpointer(dll%procaddr,fproc) + + write(*,*) "add_n(2,5)=",fproc(2.d0,5.d0) + + call free_dll (os, dll, errstat, errmsg ) + write(*,*)"free_dll: errstat=", errstat + +end program test_load_dll diff --git a/Task/Call-a-foreign-language-function/NewLISP/call-a-foreign-language-function.newlisp b/Task/Call-a-foreign-language-function/NewLISP/call-a-foreign-language-function.newlisp new file mode 100644 index 0000000000..347d2d1c1b --- /dev/null +++ b/Task/Call-a-foreign-language-function/NewLISP/call-a-foreign-language-function.newlisp @@ -0,0 +1,7 @@ +; simple FFI interface on Mac OSX +(import "libc.dylib" "strdup") +(println (get-string (strdup "hello world"))) + +; or extended FFI interface on Mac OSX +(import "libc.dylib" "strdup" "char*" "char*") +(println (strdup "hello world")) diff --git a/Task/Call-a-foreign-language-function/REXX/call-a-foreign-language-function.rexx b/Task/Call-a-foreign-language-function/REXX/call-a-foreign-language-function.rexx new file mode 100644 index 0000000000..d99898697c --- /dev/null +++ b/Task/Call-a-foreign-language-function/REXX/call-a-foreign-language-function.rexx @@ -0,0 +1,8 @@ +/*REXX program calls (invoke) a "foreign" (non-REXX) language routine/program.*/ + +cmd = "MODE" /*define the command that is to be used*/ +opts= 'CON: CP /status' /*define the options to be used for cmd*/ + +address 'SYSTEM' cmd opts /*invoke a cmd via the SYSTEM interface*/ + + /*stick a fork in it, we're all done. */ diff --git a/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada b/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada index 31681a2af2..ea14761474 100644 --- a/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada +++ b/Task/Call-a-function-in-a-shared-library/Ada/call-a-function-in-a-shared-library-1.ada @@ -7,12 +7,12 @@ with Ada.Unchecked_Conversion; procedure Shared_Library_Call is -- - -- Interface to kernel32.dll which is resposible for loading DLLs under Windows. - -- There are ready to use Win32 binding. We don't want to use them here. + -- Interface to kernel32.dll which is responsible for loading DLLs under Windows. + -- There are ready to use Win32 bindings. We don't want to use them here. -- type HANDLE is new Unsigned_32; function LoadLibrary (lpFileName : char_array) return HANDLE; - pragma Import (stdcall, LoadLibrary, "LoadLibrary", "_LoadLibraryA"); -- Ada95 don't has @n. + pragma Import (stdcall, LoadLibrary, "LoadLibrary", "_LoadLibraryA"); -- Ada95 does not have the @n suffix. function GetProcAddress (hModule : HANDLE; lpProcName : char_array) return Address; diff --git a/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-1.f b/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-1.f new file mode 100644 index 0000000000..7da5cb19c8 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-1.f @@ -0,0 +1,4 @@ +double add_n(double* a, double* b) +{ +return *a + *b; +} diff --git a/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-2.f b/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-2.f new file mode 100644 index 0000000000..eac699508f --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-2.f @@ -0,0 +1,8 @@ +function add_nf(a,b) bind(c, name='add_nf') +use, intrinsic :: iso_c_binding +implicit none +real(c_double), intent(in) :: a,b +real(c_double) :: add_nf + +add_nf = a + b +end function add_nf diff --git a/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-3.f b/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-3.f new file mode 100644 index 0000000000..4c91a916b8 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Fortran/call-a-function-in-a-shared-library-3.f @@ -0,0 +1,274 @@ +!----------------------------------------------------------------------- +!module dll_module +!----------------------------------------------------------------------- +module dll_module + use iso_c_binding + implicit none + private ! all by default + public :: os_type, dll_type, load_dll, free_dll, init_os_type, init_dll + ! general constants: + ! the number of bits in an address (32-bit or 64-bit). + integer, parameter :: bits_in_addr = c_intptr_t*8 + ! global error-level variables: + integer, parameter :: errid_none = 0 + integer, parameter :: errid_info = 1 + integer, parameter :: errid_warn = 2 + integer, parameter :: errid_severe = 3 + integer, parameter :: errid_fatal = 4 + + integer :: os_id + + type os_type + character(10) :: endian + character(len=:), allocatable :: newline + character(len=:), allocatable :: os_desc + character(1) :: pathsep + character(1) :: swchar + character(11) :: unfform + end type os_type + + type dll_type + integer(c_intptr_t) :: fileaddr + type(c_ptr) :: fileaddrx + type(c_funptr) :: procaddr + character(1024) :: filename + character(1024) :: procname + end type dll_type + + ! interface to linux API + interface + function dlopen(filename,mode) bind(c,name="dlopen") + ! void *dlopen(const char *filename, int mode); + use iso_c_binding + implicit none + type(c_ptr) :: dlopen + character(c_char), intent(in) :: filename(*) + integer(c_int), value :: mode + end function + + function dlsym(handle,name) bind(c,name="dlsym") + ! void *dlsym(void *handle, const char *name); + use iso_c_binding + implicit none + type(c_funptr) :: dlsym + type(c_ptr), value :: handle + character(c_char), intent(in) :: name(*) + end function + + function dlclose(handle) bind(c,name="dlclose") + ! int dlclose(void *handle); + use iso_c_binding + implicit none + integer(c_int) :: dlclose + type(c_ptr), value :: handle + end function + end interface + +contains + + + !----------------------------------------------------------------------- + !Subroutine init_dll + !----------------------------------------------------------------------- + subroutine init_dll(dll) + implicit none + type(dll_type), intent(inout) :: dll + dll % fileaddr = 0 + dll % fileaddrx = c_null_ptr + dll % procaddr = c_null_funptr + dll % filename = " " + dll % procname = " " + end subroutine init_dll + + !----------------------------------------------------------------------- + !Subroutine init_os_type + !----------------------------------------------------------------------- + subroutine init_os_type(os_id,os) + implicit none + integer, intent(in) :: os_id + type(os_type), intent(inout) :: os + + select case (os_id) + case (1) ! Linux + + os % endian = 'big_endian' + os % newline = achar(10) + os % os_desc = 'Linux' + os % pathsep = '/' + os % swchar = '-' + os % unfform = 'unformatted' + + case (2) ! MacOS + + os % endian = 'big_endian' + os % newline = achar(10) + os % os_desc = 'MacOS' + os % pathsep = '/' + os % swchar = '-' + os % unfform = 'unformatted' + + case default + + end select + + end subroutine init_os_type + + !----------------------------------------------------------------------- + !Subroutine load_dll + !----------------------------------------------------------------------- + subroutine load_dll (os, dll, errstat, errmsg ) + ! this subroutine is used to dynamically load a dll. + + + type (os_type), intent(in) :: os + type (dll_type), intent(inout) :: dll + integer, intent( out) :: errstat + character(*), intent( out) :: errmsg + + integer(c_int), parameter :: rtld_lazy=1 + integer(c_int), parameter :: rtld_now=2 + integer(c_int), parameter :: rtld_global=256 + integer(c_int), parameter :: rtld_local=0 + + errstat = errid_none + errmsg = '' + + select case (os%os_desc) + case ("Linux","MacOS") + ! load the dll and get the file address: + dll%fileaddrx = dlopen( trim(dll%filename)//c_null_char, rtld_lazy ) + if( .not. c_associated(dll%fileaddrx) ) then + errstat = errid_fatal + write(errmsg,'(i2)') bits_in_addr + errmsg = 'the dynamic library '//trim(dll%filename)//' could not be loaded. check that the file '// & + 'exists in the specified location and that it is compiled for '//trim(errmsg)//'-bit systems.' + return + end if + + ! get the procedure address: + dll%procaddr = dlsym( dll%fileaddrx, trim(dll%procname)//c_null_char ) + if(.not. c_associated(dll%procaddr)) then + errstat = errid_fatal + errmsg = 'the procedure '//trim(dll%procname)//' in file '//trim(dll%filename)//' could not be loaded.' + return + end if + + case ("Windows") + errstat = errid_fatal + errmsg = ' load_dll not implemented for '//trim(os%os_desc) + + case default + errstat = errid_fatal + errmsg = ' load_dll not implemented for '//trim(os%os_desc) + end select + return + end subroutine load_dll + + !----------------------------------------------------------------------- + !Subroutine free_dll + !----------------------------------------------------------------------- + subroutine free_dll (os, dll, errstat, errmsg ) + + ! this subroutine is used to free a dynamically loaded dll + type (os_type), intent(in) :: os + type (dll_type), intent(inout) :: dll + integer, intent( out) :: errstat + character(*), intent( out) :: errmsg + + integer(c_int) :: success + + errstat = errid_none + errmsg = '' + + select case (os%os_desc) + case ("Linux","MacOS") + + ! close the library: + success = dlclose( dll%fileaddrx ) + if ( success /= 0 ) then + errstat = errid_fatal + errmsg = 'the dynamic library could not be freed.' + return + else + errstat = errid_none + errmsg = '' + end if + + case ("Windows") + + errstat = errid_fatal + errmsg = ' free_dll not implemented for '//trim(os%os_desc) + + case default + errstat = errid_fatal + errmsg = ' free_dll not implemented for '//trim(os%os_desc) + end select + + return + end subroutine free_dll +end module dll_module + + + +!----------------------------------------------------------------------- +!Main program +!----------------------------------------------------------------------- +program test_load_dll + use, intrinsic :: iso_c_binding + use dll_module + implicit none + + ! interface to our shared lib + abstract interface + function add_n(a,b) + use, intrinsic :: iso_c_binding + implicit none + real(c_double), intent(in) :: a,b + real(c_double) :: add_n + end function add_n + end interface + + type(os_type) :: os + type(dll_type) :: dll + integer :: errstat + character(1024) :: errmsg + type(c_funptr) :: cfun + procedure(add_n), pointer :: fproc + + call init_os_type(1,os) + call init_dll(dll) + + dll%filename="/full_path_to/shared_lib/shared_lib_new.so" + ! name of the procedure in shared_lib + ! c version of the function + dll%procname="add_n" + + write(*,*) "address: ", dll%procaddr + + call load_dll(os, dll, errstat, errmsg ) + write(*,*)"load_dll: errstat=", errstat + write(*,*) "address: ", dll%procaddr + + call c_f_procpointer(dll%procaddr,fproc) + + write(*,*) "add_n(2,5)=",fproc(2.d0,5.d0) + + call free_dll (os, dll, errstat, errmsg ) + write(*,*)"free_dll: errstat=", errstat + + ! fortran version + dll%procname="add_nf" + + call load_dll(os, dll, errstat, errmsg ) + write(*,*)"load_dll: errstat=", errstat + write(*,*) "address: ", dll%procaddr + + call c_f_procpointer(dll%procaddr,fproc) + + write(*,*) "add_nf(2,5)=",fproc(2.d0,5.d0) + + call free_dll (os, dll, errstat, errmsg ) + write(*,*)"free_dll: errstat=", errstat + + +end program test_load_dll diff --git a/Task/Call-a-function-in-a-shared-library/REXX/call-a-function-in-a-shared-library.rexx b/Task/Call-a-function-in-a-shared-library/REXX/call-a-function-in-a-shared-library.rexx new file mode 100644 index 0000000000..a818326aaa --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/REXX/call-a-function-in-a-shared-library.rexx @@ -0,0 +1,16 @@ +/*REXX pgm calls a function (systextscreensize) in a shared library (regutil).*/ +z=rxfuncadd('sysloadfuncs', "regutil", 'sysloadfuncs') /*add a function lib.*/ +if z\==0 then do /*test the return cod*/ + say 'return code' z "from rxfuncadd" /*tell about bad RC. */ + exit z /*exit this program. */ + end + +call sysloadfuncs /*load the functions.*/ + + /* [↓] call a particular function. */ +y=systextscreensize() /*Y now contains 2 numbers: rows cols */ +parse var y rows cols . /*obtain the two numeric words in Y. */ +say 'rows=' rows /*display the number of (terminal) rows*/ +say 'cols=' cols /* " " " " " cols*/ +call SysDropFuncs /*clean up: make functions inaccessible*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Call-a-function/C++/call-a-function-1.cpp b/Task/Call-a-function/C++/call-a-function-1.cpp new file mode 100644 index 0000000000..bdd6c8d1a1 --- /dev/null +++ b/Task/Call-a-function/C++/call-a-function-1.cpp @@ -0,0 +1,2 @@ +/* function with no arguments */ +foo(); diff --git a/Task/Call-a-function/C++/call-a-function-2.cpp b/Task/Call-a-function/C++/call-a-function-2.cpp new file mode 100644 index 0000000000..355c82c0da --- /dev/null +++ b/Task/Call-a-function/C++/call-a-function-2.cpp @@ -0,0 +1,5 @@ +/* passing arguments by value*/ +/* function with one argument */ +bar(arg1); +/* function with multiple arguments */ +baz(arg1, arg2); diff --git a/Task/Call-a-function/C++/call-a-function-3.cpp b/Task/Call-a-function/C++/call-a-function-3.cpp new file mode 100644 index 0000000000..e849ff42a2 --- /dev/null +++ b/Task/Call-a-function/C++/call-a-function-3.cpp @@ -0,0 +1,2 @@ +/* get return value of a function */ +variable = function(args); diff --git a/Task/Call-a-function/C++/call-a-function-4.cpp b/Task/Call-a-function/C++/call-a-function-4.cpp new file mode 100644 index 0000000000..ad907045b9 --- /dev/null +++ b/Task/Call-a-function/C++/call-a-function-4.cpp @@ -0,0 +1,14 @@ +#include +using namespace std; +/* passing arguments by reference */ +void f(int &y) /* variable is now passed by reference */ +{ +y++; +} +int main() +{ +int x = 0; +cout<<"x = "< "foo" +foo() #=> "foo" diff --git a/Task/Call-a-function/Ruby/call-a-function-10.rb b/Task/Call-a-function/Ruby/call-a-function-10.rb new file mode 100644 index 0000000000..c5432f1363 --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-10.rb @@ -0,0 +1,13 @@ +# return value substance +i = 3 +p 1 + i #=> 4 1.+(i) +p i < 5 #=> true i.<(5) +p 2 ** i #=> 8 2.**(i) +p -i #=> -3 i.-@() +a = [1,2,3] +p a[0] #=> 1 a.[](0) +a[2] = "0" # a.[]=(2,"0") +p a << 5 #=> [1, 2, "0", 5] a.<<(5) +p a & [4,2] #=> [2] a.&([4,2]) +p "abcde"[1..3] #=> "bcd" "abcde".[](1..3) +p "%2d %4s" % [1,"xyz"] #=> " 1 xyz" "%2d %4s".%([1,"xyz"]) diff --git a/Task/Call-a-function/Ruby/call-a-function-2.rb b/Task/Call-a-function/Ruby/call-a-function-2.rb new file mode 100644 index 0000000000..6f729120c4 --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-2.rb @@ -0,0 +1,5 @@ +def foo arg; p arg end # one argument + +foo(1) #=> 1 +foo "1" #=> "1" +foo [0,1,2] #=> [0, 1, 2] (one Array) diff --git a/Task/Call-a-function/Ruby/call-a-function-3.rb b/Task/Call-a-function/Ruby/call-a-function-3.rb new file mode 100644 index 0000000000..1c20d1ce73 --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-3.rb @@ -0,0 +1,6 @@ +def foo(x=0, y=x, flag=true) p [x,y,flag] end + +foo #=> [0, 0, true] +foo(1) #=> [1, 1, true] +foo(1,2) #=> [1, 2, true] +foo 1,2,false #=> [1, 2, false] diff --git a/Task/Call-a-function/Ruby/call-a-function-4.rb b/Task/Call-a-function/Ruby/call-a-function-4.rb new file mode 100644 index 0000000000..ecd144f0c0 --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-4.rb @@ -0,0 +1,4 @@ +def foo(*args) p args end + +foo #=> [] +foo(1,2,3,4,5) #=> [1, 2, 3, 4, 5] diff --git a/Task/Call-a-function/Ruby/call-a-function-5.rb b/Task/Call-a-function/Ruby/call-a-function-5.rb new file mode 100644 index 0000000000..f86f32bd24 --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-5.rb @@ -0,0 +1,3 @@ +def foo(id:0, name:"", age:0) p [id, name, age] end + +foo(age:22, name:"Tom") #=> [0, "Tom", 22] diff --git a/Task/Call-a-function/Ruby/call-a-function-6.rb b/Task/Call-a-function/Ruby/call-a-function-6.rb new file mode 100644 index 0000000000..2e26364a11 --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-6.rb @@ -0,0 +1,12 @@ +def foo(a,b) a + b end + +bar = foo 10,20 +p bar #=> 30 +p foo("abc","def") #=> "abcdef" + +# return multiple values +def sum_and_product(a,b) return a+b,a*b end + +x,y = sum_and_product(3,5) +p x #=> 8 +p y #=> 15 diff --git a/Task/Call-a-function/Ruby/call-a-function-7.rb b/Task/Call-a-function/Ruby/call-a-function-7.rb new file mode 100644 index 0000000000..33a94114cb --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-7.rb @@ -0,0 +1,12 @@ +puts "OK!" # Kernel#puts +raise "Error input" # Kernel#raise +Integer("123") # Kernel#Integer +rand(6) # Kernel#rand +throw(:exit) # Kernel#throw + +# method which can be seen like a reserved word. +attr_accessor # Module#attr_accessor +include # Module#include +private # Module#private +require # Kernel#require +loop { } # Kernel#loop diff --git a/Task/Call-a-function/Ruby/call-a-function-8.rb b/Task/Call-a-function/Ruby/call-a-function-8.rb new file mode 100644 index 0000000000..08641cab1a --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-8.rb @@ -0,0 +1,14 @@ +class Array + def sum(init=0, &blk) + if blk + inject(init){|s, n| s + blk.call(n)} + else + inject(init){|s, n| s + n} + end + end +end + +ary = [1,2,3,4,5] +p ary.sum #=> 15 +p ary.sum(''){|n| (-n).to_s} #=> "-1-2-3-4-5" +p (ary.sum do |n| n * n end) #=> 55 diff --git a/Task/Call-a-function/Ruby/call-a-function-9.rb b/Task/Call-a-function/Ruby/call-a-function-9.rb new file mode 100644 index 0000000000..edcc955011 --- /dev/null +++ b/Task/Call-a-function/Ruby/call-a-function-9.rb @@ -0,0 +1,6 @@ +def foo(a,b,c) p [a,b,c] end + +args = [1,2,3] +foo *args #=> [1, 2, 3] +args = [1,2] +foo(0,*args) #=> [0, 1, 2] diff --git a/Task/Call-an-object-method/Forth/call-an-object-method.fth b/Task/Call-an-object-method/Forth/call-an-object-method-1.fth similarity index 100% rename from Task/Call-an-object-method/Forth/call-an-object-method.fth rename to Task/Call-an-object-method/Forth/call-an-object-method-1.fth diff --git a/Task/Call-an-object-method/Forth/call-an-object-method-2.fth b/Task/Call-an-object-method/Forth/call-an-object-method-2.fth new file mode 100644 index 0000000000..c1f6c32427 --- /dev/null +++ b/Task/Call-an-object-method/Forth/call-an-object-method-2.fth @@ -0,0 +1,29 @@ +include FMS-SI.f + +:class animal + variable cnt 0 cnt ! \ static instance variable + :m init: 1 cnt +! ;m + :m cnt: cnt @ . ;m +;class + +:class cat 2 ok +Sparky cnt: \ => 2 ok +Frisky speak \ => meow ok +Sparky speak \ => woof ok diff --git a/Task/Call-an-object-method/JavaScript/call-an-object-method.js b/Task/Call-an-object-method/JavaScript/call-an-object-method.js new file mode 100644 index 0000000000..080a8a3cb4 --- /dev/null +++ b/Task/Call-an-object-method/JavaScript/call-an-object-method.js @@ -0,0 +1 @@ +x.y() diff --git a/Task/Call-an-object-method/Logtalk/call-an-object-method-1.logtalk b/Task/Call-an-object-method/Logtalk/call-an-object-method-1.logtalk new file mode 100644 index 0000000000..6d836ac851 --- /dev/null +++ b/Task/Call-an-object-method/Logtalk/call-an-object-method-1.logtalk @@ -0,0 +1,10 @@ +% avoid infinite metaclass regression by +% making the metaclass an instance of itself +:- object(metaclass, + instantiates(metaclass)). + + :- public(me/1). + me(Me) :- + self(Me). + +:- end_object. diff --git a/Task/Call-an-object-method/Logtalk/call-an-object-method-2.logtalk b/Task/Call-an-object-method/Logtalk/call-an-object-method-2.logtalk new file mode 100644 index 0000000000..d8c2eb3857 --- /dev/null +++ b/Task/Call-an-object-method/Logtalk/call-an-object-method-2.logtalk @@ -0,0 +1,9 @@ +:- object(class, + instantiates(metaclass)). + + :- public(my_class/1). + my_class(Class) :- + self(Self), + instantiates_class(Self, Class). + +:- end_object. diff --git a/Task/Call-an-object-method/Logtalk/call-an-object-method-3.logtalk b/Task/Call-an-object-method/Logtalk/call-an-object-method-3.logtalk new file mode 100644 index 0000000000..4e9cb5f17b --- /dev/null +++ b/Task/Call-an-object-method/Logtalk/call-an-object-method-3.logtalk @@ -0,0 +1,4 @@ +:- object(instance, + instantiates(class)). + +:- end_object. diff --git a/Task/Call-an-object-method/Logtalk/call-an-object-method-4.logtalk b/Task/Call-an-object-method/Logtalk/call-an-object-method-4.logtalk new file mode 100644 index 0000000000..db71f07d6b --- /dev/null +++ b/Task/Call-an-object-method/Logtalk/call-an-object-method-4.logtalk @@ -0,0 +1,7 @@ +| ?- class::me(Me). +Me = class +yes + +| ?- instance::my_class(Class). +Class = class +yes diff --git a/Task/Canny-edge-detector/J/canny-edge-detector-1.j b/Task/Canny-edge-detector/J/canny-edge-detector-1.j new file mode 100644 index 0000000000..620d02c544 --- /dev/null +++ b/Task/Canny-edge-detector/J/canny-edge-detector-1.j @@ -0,0 +1,88 @@ +NB. 2D convolution, filtering, ... + +convolve =: 4 : 'x apply (($x) partition y)' +partition=: 2 1 3 0 |: {:@[ ]\ 2 1 0 |: {.@[ ]\ ] +apply=: [: +/ [: +/ * +max3x3 =: 3 : '(0<1{1{y) * (>./>./y)' +addborder =: (0&,@|:@|.)^:4 +normalize =: ]%+/@, +attach =: 3 : 'max3x3 (3 3 partition (addborder y))' +unique =: 3 : 'y*i.$y' +connect =: 3 : 'attach^:_ unique y' + +NB. on low memory devices, cropping or resampling of high-resolution images may be required +crop =: 4 : 0 + 'h w h0 w0' =: x + |: w{. w0}. |: h{. h0}. y +) +resample =: 4 : '|: (1{-x)(+/%#)\ |: (0{-x)(+/%#)\ y' +NB. on e. g. smartphones, image may need to be expanded for viewing +inflate1 =: 4 : 0 + 'h w' =: $y + r =: ,y + c =: #r + rr =: (c$x) # r + (h,x*w)$rr +) +inflate =: 4 : '|: x inflate1 (|: x inflate1 y)' + +NB. Step 1 - gaussian smoothing +step1 =: 3 : 0 + NB. Gaussian kernel (from Wikipedia article) + <] gaussianKernel =: 5 5$2 4 5 4 2 4 9 12 9 4 5 12 15 12 5 4 9 12 9 4 2 4 5 4 2 + gaussianKernel =: gaussianKernel % 159 + gaussianKernel convolve y +) + +NB. Step 2 - gradient +step2 =: 3 : 0 + <] gradientKernel =: 3 3$0 _1 0 0j_1 0 0j1 0 1 0 + gradientKernel convolve y +) + +NB. Step 3 - edge detection +step3 =: 3 : 0 + NB. find the octant (eighth of circle) in which the gradient lies + octant =: 3 : '4|(>.(_0.5+((4%(o. 1))*(12&o. y))))' + <(i:6)(4 : 'octant (x j. y)')"0/(i:6) + + NB. is this gradient greater than [the projection of] a neighbor? + greaterThan =: 4 : ' (9 o.((x|.y)%y))<1' + + NB. is this gradient the greatest of immmediate colinear neighbore? + greatestOf =: 4 : '(x greaterThan y) *. ((-x) greaterThan y)' + + NB. relative address of neighbor relevant to grad direction + krnl0 =. _1 0 + krnl1 =. _1 _1 + krnl2 =. 0 _1 + krnl3 =. 1 _1 + + image =. y + og =. octant image + + NB. mask for maximum gradient colinear with gradient + ok0 =. (0=og) *. krnl0 greatestOf image + ok1 =. (1=og) *. krnl1 greatestOf image + ok2 =. (2=og) *. krnl2 greatestOf image + ok3 =. (3=og) *. krnl3 greatestOf image + image *. (ok0 +. ok1 +. ok2 +. ok3) +) + +NB. Step 4 - Weak edge suppression +step4 =: 3 : 0 + magnitude =. 10&o. y + NB. weak, strong threshholds + NB. TODO: parameter picker algorithm or helper + threshholds =. 1e14 1e15 + nearbyKernel =. 3 3 $ 4 1 4 # 1 0 1 + weak =. magnitude > 0{threshholds + strong =. magnitude > 1{threshholds + strongs =. addborder (nearbyKernel convolve strong) > 0 + strong +. (weak *. strongs) +) + +NB. given the edge points, find the edges + step5 =: connect + +canny =: step5 @ step4 @ step3 @ step2 @ step1 diff --git a/Task/Canny-edge-detector/J/canny-edge-detector-2.j b/Task/Canny-edge-detector/J/canny-edge-detector-2.j new file mode 100644 index 0000000000..28af06fca9 --- /dev/null +++ b/Task/Canny-edge-detector/J/canny-edge-detector-2.j @@ -0,0 +1,58 @@ +require 'gl2' +coclass 'edge' +coinsert'jgl2' + +PJ=: jpath '~Projects/edges/' NB. optionally install and run as project under IDE +load PJ,'canny.ijs' + +run=: 3 : 0 + wd 'pc form;pn canny' + wd 'cc txt static;cn "Canny in J";' + wd 'cc png isidraw' + wd 'cc inc button;cn "Next";' + wd 'pshow' + glclear'' + image =: readimg_jqtide_ PJ,'valve.png' + image =: 240 360 120 150 crop image + edges =: canny 256 | image + ids =: }. ~.,edges + nids =: # ids + case =: 0 +) + +form_inc_button =: 3 : 0 + select. case + case. 0 do. + wd 'set txt text "original image";' + img =: 255 setalpha image + case. 1 do. + wd 'set txt text "points on edges";' + img =: edges>0 + img =: 1-img + img =: img * (+/ 256^i.3) * 255 + img =: 255 setalpha img + ix =: 0 + case. 2 do. + wd 'set txt text "... iterating over edges with >75 points ...";' + img =: edges=ix{ids + whilst. (num<75) *. (ix:ix + if. ix=#ids do. case=:_1 end. + end. + img =: 1-img + img =: img * (+/ 256^i.3) * 255 + img =: 255 setalpha img + ix =: (#ids)|(>:ix) + end. + if. case<2 do. case =: >: case end. + NB. img =: 5 inflate img NB. might need this for high-res cellphone display + glfill 255 128 255 + glpixels 0 0,(|.$img), ,img + glpaint'' +) + +form_close=: exit bind 0 + +run'' diff --git a/Task/Canny-edge-detector/MATLAB/canny-edge-detector.m b/Task/Canny-edge-detector/MATLAB/canny-edge-detector.m new file mode 100644 index 0000000000..eadd1148a7 --- /dev/null +++ b/Task/Canny-edge-detector/MATLAB/canny-edge-detector.m @@ -0,0 +1 @@ +BWImage = edge(GrayscaleImage,'canny'); diff --git a/Task/Canny-edge-detector/Mathematica/canny-edge-detector.math b/Task/Canny-edge-detector/Mathematica/canny-edge-detector.math new file mode 100644 index 0000000000..7b3fa01c8e --- /dev/null +++ b/Task/Canny-edge-detector/Mathematica/canny-edge-detector.math @@ -0,0 +1 @@ +Export["out.bmp", EdgeDetect[Import[InputString[]]]]; diff --git a/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-1.julia b/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-1.julia new file mode 100644 index 0000000000..85c36fc988 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-1.julia @@ -0,0 +1,19 @@ +function carmichael{T<:Integer}(pmax::T) + 0 < pmax || throw(DomainError()) + car = T[] + for p in primes(pmax) + for h₃ in 2:(p-1) + m = (p - 1)*(h₃ + p) + pmh = mod(-p^2, h₃) + for Δ in 1:(h₃+p-1) + m%Δ==0 && Δ%h₃==pmh || continue + q = div(m, Δ) + 1 + isprime(q) || continue + r = div((p*q - 1), h₃) + 1 + isprime(r) && mod(q*r, (p-1))==1 || continue + append!(car, [p, q, r]) + end + end + end + reshape(car, 3, div(length(car), 3)) +end diff --git a/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-2.julia b/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-2.julia new file mode 100644 index 0000000000..727ab57be2 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-2.julia @@ -0,0 +1,23 @@ +hi = 61 +car = carmichael(hi) + +curp = 0 +tcnt = 0 +print("Carmichael 3 (p\u00d7q\u00d7r) Pseudoprimes, up to p = ", hi, ":") +for j in sortperm(1:size(car)[2], by=x->(car[1,x], car[2,x], car[3,x])) + p, q, r = car[:,j] + c = prod(car[:,j]) + if p != curp + curp = p + print(@sprintf("\n\np = %d\n ", p)) + tcnt = 0 + end + if tcnt == 4 + print("\n ") + tcnt = 1 + else + tcnt += 1 + end + print(@sprintf("p\u00d7%d\u00d7%d = %d ", q, r, c)) +end +println("\n\n", size(car)[2], " results in total.") diff --git a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx index 7e7194592e..d3d148464b 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx +++ b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx @@ -20,7 +20,6 @@ carms=0 /*number of Carmichael #s so far.*/ if \isPrime(r) then iterate carms=carms+1; @.q=r /*bump Carmichael #; add to array*/ if bot==0 then bot=q; bot=min(bot,q); top=max(top,q) - /*find the maximum. */ end /*d*/ /* [↑] find minimum and maximum.*/ end /*h3*/ $=0 /*display a list of some Carm #s.*/ diff --git a/Task/Carmichael-3-strong-pseudoprimes/Ruby/carmichael-3-strong-pseudoprimes.rb b/Task/Carmichael-3-strong-pseudoprimes/Ruby/carmichael-3-strong-pseudoprimes.rb index 5ff00fb73a..897b387ba8 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/Ruby/carmichael-3-strong-pseudoprimes.rb +++ b/Task/Carmichael-3-strong-pseudoprimes/Ruby/carmichael-3-strong-pseudoprimes.rb @@ -1,21 +1,18 @@ # Generate Charmichael Numbers -# -# Nigel_Galloway -# November 30th., 2012. -# + require 'prime' -Integer.each_prime(61) {|p| - (2...p).each {|h3| +Prime.each(61) do |p| + (2...p).each do |h3| g = h3 + p - (1...g).each {|d| - next if (g*(p-1)) % d != 0 or (-1*p*p) % h3 != d % h3 + (1...g).each do |d| + next if (g*(p-1)) % d != 0 or (-p*p) % h3 != d % h3 q = 1 + ((p - 1) * g / d) - next if not q.prime? + next unless q.prime? r = 1 + (p * q / h3) - next if not r.prime? or not (q * r) % (p - 1) == 1 - puts "#{p} X #{q} X #{r}" - } - } - puts "" -} + next unless r.prime? and (q * r) % (p - 1) == 1 + puts "#{p} x #{q} x #{r}" + end + end + puts +end diff --git a/Task/Case-sensitivity-of-identifiers/ALGOL-W/case-sensitivity-of-identifiers.alg b/Task/Case-sensitivity-of-identifiers/ALGOL-W/case-sensitivity-of-identifiers.alg new file mode 100644 index 0000000000..c6cf4ebd2a --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/ALGOL-W/case-sensitivity-of-identifiers.alg @@ -0,0 +1,16 @@ +begin + string(8) dog; + dog := "Benjamin"; + begin + string(8) Dog; + Dog := "Samba"; + begin + string(8) DOG; + DOG := "Bernie"; + if DOG not = Dog + or DOG not = dog + then write( "The three dogs are named: ", dog, ", ", Dog, " and ", DOG ) + else write( "There is just one dog named: ", DOG ) + end + end +end. diff --git a/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia b/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia new file mode 100644 index 0000000000..38ea5769ca --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia @@ -0,0 +1,9 @@ +dog = "Benjamin" +Dog = "Samba" +DOG = "Bernie" + +if is(dog, Dog) + println("There is only one dog, ", DOG) +else + println("The three dogs are: ", dog, ", ", Dog, " and ", DOG) +end diff --git a/Task/Catalan-numbers-Pascals-triangle/Elixir/catalan-numbers-pascals-triangle.elixir b/Task/Catalan-numbers-Pascals-triangle/Elixir/catalan-numbers-pascals-triangle.elixir new file mode 100644 index 0000000000..a66bed856f --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Elixir/catalan-numbers-pascals-triangle.elixir @@ -0,0 +1,15 @@ +defmodule Catalan do + def numbers(num) do + {result,_} = Enum.reduce(1..num, {[],{0,1}}, fn i,{list,t0} -> + t1 = numbers(i, t0) + t2 = numbers(i+1, Tuple.insert_at(t1, i+1, elem(t1, i))) + {[elem(t2, i+1) - elem(t2, i) | list], t2} + end) + Enum.reverse(result) + end + + defp numbers(0, t), do: t + defp numbers(n, t), do: numbers(n-1, put_elem(t, n, elem(t, n-1) + elem(t, n))) +end + +IO.inspect Catalan.numbers(15) diff --git a/Task/Catalan-numbers-Pascals-triangle/Haskell/catalan-numbers-pascals-triangle.hs b/Task/Catalan-numbers-Pascals-triangle/Haskell/catalan-numbers-pascals-triangle.hs new file mode 100644 index 0000000000..a52153200c --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Haskell/catalan-numbers-pascals-triangle.hs @@ -0,0 +1,19 @@ +import System.Environment (getArgs) + +-- Pascal's triangle. +pascal :: [[Integer]] +pascal = [1] : map (\row -> 1 : zipWith (+) row (tail row) ++ [1]) pascal + +-- The Catalan numbers from Pascal's triangle. This uses a method from +-- http://www.cut-the-knot.org/arithmetic/algebra/CatalanInPascal.shtml +-- (see "Grimaldi"). +catalan :: [Integer] +catalan = map (diff . uncurry drop) $ zip [0..] (alt pascal) + where alt (x:_:zs) = x : alt zs -- every other element of an infinite list + diff (x:y:_) = x - y + diff (x:_) = x + +main :: IO () +main = do + ns <- fmap (map read) getArgs :: IO [Int] + mapM_ (print . flip take catalan) ns diff --git a/Task/Catalan-numbers-Pascals-triangle/JavaScript/catalan-numbers-pascals-triangle.js b/Task/Catalan-numbers-Pascals-triangle/JavaScript/catalan-numbers-pascals-triangle.js new file mode 100644 index 0000000000..7b569e9259 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/JavaScript/catalan-numbers-pascals-triangle.js @@ -0,0 +1,7 @@ +var n=15 +for (var t=[0,1], i=1; i<=n; i++) { + for (var j=i; j>1; j--) t[j] += t[j-1] + t[i+1] = t[i]; + for (var j=i+1; j>1; j--) t[j] += t[j-1] + document.write(i==1 ? '' : ', ', t[i+1] - t[i]) +} diff --git a/Task/Catalan-numbers-Pascals-triangle/Perl-6/catalan-numbers-pascals-triangle.pl6 b/Task/Catalan-numbers-Pascals-triangle/Perl-6/catalan-numbers-pascals-triangle.pl6 index 09b1b7240b..964c18a758 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Perl-6/catalan-numbers-pascals-triangle.pl6 +++ b/Task/Catalan-numbers-Pascals-triangle/Perl-6/catalan-numbers-pascals-triangle.pl6 @@ -1,4 +1,4 @@ -constant @pascal = [1], -> @p { [0, @p Z+ @p, 0] } ... *; +constant @pascal = [1], -> @p { [0, |@p Z+ |@p, 0] } ... *; constant @catalan = gather for 2, 4 ... * -> $ix { my @row := @pascal[$ix]; 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 index fa0d6665b6..7f63f98512 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Ruby/catalan-numbers-pascals-triangle.rb +++ b/Task/Catalan-numbers-Pascals-triangle/Ruby/catalan-numbers-pascals-triangle.rb @@ -1,6 +1,6 @@ def catalan(num) t = [0, 1] #grows as needed - 1.upto(num).map do |i| + (1..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]} @@ -8,4 +8,4 @@ def catalan(num) end end -puts catalan(15).join(", ") +p catalan(15) diff --git a/Task/Catalan-numbers/360-Assembly/catalan-numbers.360 b/Task/Catalan-numbers/360-Assembly/catalan-numbers.360 new file mode 100644 index 0000000000..1db03f7569 --- /dev/null +++ b/Task/Catalan-numbers/360-Assembly/catalan-numbers.360 @@ -0,0 +1,22 @@ +CATALAN CSECT + USING CATALAN,R15 + LA R7,1 c=1 + LA R6,1 i=1 +LOOPI CH R6,=H'15' do i=1 to 15 + BH ELOOPI + XDECO R6,PG edit i + LR R5,R6 i + SLA R5,1 *2 + BCTR R5,0 -1 + SLA R5,1 *2 + MR R4,R7 *c + LA R6,1(R6) i=i+1 + DR R4,R6 /i + LR R7,R5 c=2*(2*i-1)*c/(i+1) + XDECO R7,PG+12 edit c + XPRNT PG,24 print + B LOOPI next i +ELOOPI BR R14 +PG DS CL24 + YREGS + END CATALAN diff --git a/Task/Catalan-numbers/Befunge/catalan-numbers.bf b/Task/Catalan-numbers/Befunge/catalan-numbers.bf new file mode 100644 index 0000000000..1b71d55cfb --- /dev/null +++ b/Task/Catalan-numbers/Befunge/catalan-numbers.bf @@ -0,0 +1,4 @@ +0>:.:000p1>\:00g-#v_v +v 2-1*2p00 :+1g00\< $ +> **00g1+/^v,*84,"="< +_^#<`*53:+1>#,.#+5< @ diff --git a/Task/Catalan-numbers/Eiffel/catalan-numbers.e b/Task/Catalan-numbers/Eiffel/catalan-numbers.e new file mode 100644 index 0000000000..b1ded6700c --- /dev/null +++ b/Task/Catalan-numbers/Eiffel/catalan-numbers.e @@ -0,0 +1,35 @@ +class + APPLICATION + +create + make + +feature {NONE} + + make + do + across + 0 |..| 14 as c + loop + io.put_double (catalan_numbers (c.item)) + io.new_line + end + end + + nth_catalan_number (n: INTEGER): DOUBLE + --'n'th number in the sequence of Catalan numbers. + require + n_not_negative: n >= 0 + local + s, t: DOUBLE + do + if n = 0 then + Result := 1.0 + else + t := 4 * n.to_double - 2 + s := n.to_double + 1 + Result := t / s * catalan_numbers (n - 1) + end + end + +end diff --git a/Task/Catalan-numbers/Elixir/catalan-numbers.elixir b/Task/Catalan-numbers/Elixir/catalan-numbers.elixir new file mode 100644 index 0000000000..b48b69b594 --- /dev/null +++ b/Task/Catalan-numbers/Elixir/catalan-numbers.elixir @@ -0,0 +1,23 @@ +defmodule Catalan do + def cat(n), do: div( factorial(2*n), factorial(n+1) * factorial(n) ) + + defp factorial(n), do: fac1(n,1) + + defp fac1(0, acc), do: acc + defp fac1(n, acc), do: fac1(n-1, n*acc) + + def cat_r1(0), do: 1 + def cat_r1(n), do: Enum.sum(for i <- 0..n-1, do: cat_r1(i) * cat_r1(n-1-i)) + + def cat_r2(0), do: 1 + def cat_r2(n), do: div(cat_r2(n-1) * 2 * (2*n - 1), n + 1) + + def test do + range = 0..14 + :io.format "Directly:~n~p~n", [(for n <- range, do: cat(n))] + :io.format "1st recusive method:~n~p~n", [(for n <- range, do: cat_r1(n))] + :io.format "2nd recusive method:~n~p~n", [(for n <- range, do: cat_r2(n))] + end +end + +Catalan.test diff --git a/Task/Catalan-numbers/Perl-6/catalan-numbers-1.pl6 b/Task/Catalan-numbers/Perl-6/catalan-numbers-1.pl6 new file mode 100644 index 0000000000..e728d22cbb --- /dev/null +++ b/Task/Catalan-numbers/Perl-6/catalan-numbers-1.pl6 @@ -0,0 +1 @@ +constant Catalan = 1, { [+] @_ Z* @_.reverse } ... *; diff --git a/Task/Catalan-numbers/Perl-6/catalan-numbers-2.pl6 b/Task/Catalan-numbers/Perl-6/catalan-numbers-2.pl6 new file mode 100644 index 0000000000..fa95984dc4 --- /dev/null +++ b/Task/Catalan-numbers/Perl-6/catalan-numbers-2.pl6 @@ -0,0 +1 @@ +constant Catalan = 1, |[\*] (2, 6 ... *) Z/ 2 .. *; diff --git a/Task/Catalan-numbers/Perl-6/catalan-numbers-3.pl6 b/Task/Catalan-numbers/Perl-6/catalan-numbers-3.pl6 new file mode 100644 index 0000000000..65a32e0c03 --- /dev/null +++ b/Task/Catalan-numbers/Perl-6/catalan-numbers-3.pl6 @@ -0,0 +1 @@ +.say for Catalan[^15]; diff --git a/Task/Catalan-numbers/Perl-6/catalan-numbers.pl6 b/Task/Catalan-numbers/Perl-6/catalan-numbers.pl6 deleted file mode 100644 index ee095b566f..0000000000 --- a/Task/Catalan-numbers/Perl-6/catalan-numbers.pl6 +++ /dev/null @@ -1,3 +0,0 @@ -constant Catalan = 1, [\*] (2, 6 ... *) Z/ 2 .. *; - -.say for Catalan[^15]; diff --git a/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx b/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx index 9d649a5d70..0e9e78bdb1 100644 --- a/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx +++ b/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx @@ -1,31 +1,31 @@ -/*REXX program calculates Catalan numbers using four different methods.*/ -parse arg bot top . /*get optional args from the C.L.*/ -if bot=='' then do; top=15; bot=0; end /*No args? Use a range of 0──►15.*/ -if top=='' then top=bot /*No top? Use the bottom for it.*/ -numeric digits max(20, 5*top) /*allows gihugic Catalan numbers.*/ -call hdr '1a'; do j=bot to top; say $cat() catalan1a(j); end -call hdr '1b'; do j=bot to top; say $cat() catalan1b(j); end -call hdr 2 ; do j=bot to top; say $cat() catalan2(j) ; end -call hdr 3 ; do j=bot to top; say $cat() catalan3(j) ; end -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one─liner subroutines───────────────*/ -$cat: return ' Catalan' right(j,length(top))": " -catalan1a: procedure expose !.; parse arg n; return comb(n+n,n)%(n+1) -catalan1b: procedure expose !.; parse arg n; return !(n+n)%((n+1)*!(n)**2) -comb: procedure; parse arg x,y; return pFact(x-y+1,x) % pFact(2,y) -pFact: procedure; !=1; do k=arg(1) to arg(2); !=!*k; end; return ! -/*──────────────────────────────────! (factorial) function──────────────*/ -!: procedure expose !.; parse arg x; if !.x\==. then return !.x -!=1; do k=1 for x; !=!*k; end /*k*/; !.x=!; return ! -/*──────────────────────────────────catalan method 2────────────────────*/ -catalan2: procedure expose c.; parse arg n; if c.n\==. then return c.n -s=0; do k=0 to n-1 - s=s + catalan2(k) * catalan2(n-k-1) /*recursive invokes*/ - end /*k*/ -c.n=s; return s /*use REXX memoization technique.*/ -/*──────────────────────────────────catalan method 3────────────────────*/ -catalan3: procedure expose c.; parse arg n; if c.n\==. then return c.n -c.n=(4*n-2) * catalan3(n-1) % (n+1); return c.n /*use memoization.*/ -/*──────────────────────────────────HDR subroutine──────────────────────*/ -hdr: !.=.; c.=.; c.0=1; say /*set some variables; blank line.*/ +/*REXX program calculates Catalan numbers using four different methods. */ +parse arg bot top . /*get optional arguments from the C.L. */ +if bot=='' then do; top=15; bot=0; end /*No args? Use a range of 0 ───► 15. */ +if top=='' then top=bot /*No top? Use the bottom for default. */ +numeric digits max(20, 5*top) /*this allows gihugic Catalan numbers. */ +@cat=' Catalan' /*a nice literal to have for the SAY. */ +w=length(top) /*width of the largest number for SAY. */ +call hdr 1A; do j=bot to top; say @cat right(j,w)": " Catalan1A(j); end +call hdr 1B; do j=bot to top; say @cat right(j,w)": " Catalan1B(j); end +call hdr 2 ; do j=bot to top; say @cat right(j,w)": " Catalan2(j); end +call hdr 3 ; do j=bot to top; say @cat right(j,w)": " Catalan3(j); end +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +Catalan1A: procedure expose !.; parse arg n; return comb(n+n, n) % (n+1) +Catalan1B: procedure expose !.; parse arg n; return !(n+n) % ((n+1) * !(n)**2) +comb: procedure; parse arg x,y; return pFact(x-y+1,x) % pFact(2,y) +pFact: procedure; !=1; do k=arg(1) to arg(2); !=!*k; end; return ! +/*────────────────────────────────────────────────────────────────────────────*/ +hdr: !.=.; c.=.; c.0=1; say say center(' Catalan numbers, method' left(arg(1),3), 79, '─'); return +/*────────────────────────────────────────────────────────────────────────────*/ +!: procedure expose !.; parse arg x; !=1; if !.x\==. then return !.x + do k=1 for x; !=!*k; end /*k*/ + !.x=!; return ! +/*──────────────────────────────────Catalan method 2──────────────────────────*/ +Catalan2: procedure expose c.; parse arg n; $=0; if c.n\==. then return c.n + do k=0 to n-1; $=$+catalan2(k)*catalan2(n-k-1); end + c.n=$; return $ /*use a REXX memoization technique. */ +/*──────────────────────────────────Catalan method 3──────────────────────────*/ +Catalan3: procedure expose c.; parse arg n + if c.n==. then c.n=(4*n-2) * catalan3(n-1) % (n+1); return c.n diff --git a/Task/Catalan-numbers/Ruby/catalan-numbers.rb b/Task/Catalan-numbers/Ruby/catalan-numbers.rb index a44b359b87..dbe9ef332b 100644 --- a/Task/Catalan-numbers/Ruby/catalan-numbers.rb +++ b/Task/Catalan-numbers/Ruby/catalan-numbers.rb @@ -1,9 +1,9 @@ -# direct - def factorial(n) - (1..n).reduce(:*) + (1..n).reduce(1, :*) end +# direct + def catalan_direct(n) factorial(2*n) / (factorial(n+1) * factorial(n)) end @@ -12,12 +12,12 @@ def catalan_direct(n) def catalan_rec1(n) return 1 if n == 0 - (0..n-1).inject(0) {|sum, i| sum + catalan_rec1(i) * catalan_rec1(n-1-i)} + (0...n).inject(0) {|sum, i| sum + catalan_rec1(i) * catalan_rec1(n-1-i)} end def catalan_rec2(n) return 1 if n == 0 - 2*(2*n - 1) * catalan_rec2(n-1) /(n+1) + 2*(2*n - 1) * catalan_rec2(n-1) / (n+1) end # performance and results @@ -26,17 +26,14 @@ def catalan_rec2(n) require 'memoize' include Memoize -Benchmark.bm(10) do |b| - b.report('forget') { - 16.times {|n| [n, catalan_direct(n), catalan_rec1(n), catalan_rec2(n)]} - } - b.report('memoized') { - memoize :factorial - memoize :catalan_direct - memoize :catalan_rec1 - memoize :catalan_rec2 - 16.times {|n| [n, catalan_direct(n), catalan_rec1(n), catalan_rec2(n)]} - } +Benchmark.bm(17) do |b| + b.report('catalan_direct') {16.times {|n| catalan_direct(n)} } + b.report('catalan_rec1') {16.times {|n| catalan_rec1(n)} } + b.report('catalan_rec2') {16.times {|n| catalan_rec2(n)} } + + memoize :catalan_rec1 + b.report('catalan_rec1(memo)'){16.times {|n| catalan_rec1(n)} } end -16.times {|n| p [n, catalan_direct(n), catalan_rec1(n), catalan_rec2(n)]} +puts "\n direct rec1 rec2" +16.times {|n| puts "%2d :%9d%9d%9d" % [n, catalan_direct(n), catalan_rec1(n), catalan_rec2(n)]} diff --git a/Task/Catalan-numbers/Rust/catalan-numbers.rust b/Task/Catalan-numbers/Rust/catalan-numbers.rust index d601e28cc7..b0e120fc97 100644 --- a/Task/Catalan-numbers/Rust/catalan-numbers.rust +++ b/Task/Catalan-numbers/Rust/catalan-numbers.rust @@ -1,13 +1,12 @@ -fn factorial(n: u64) -> u64 { - range(1u64, n + 1).fold(1u64, |a, b| a * b) -} - fn c_n(n: u64) -> u64 { - factorial(n * 2) / (factorial(n + 1) * factorial(n)) + match n { + 0 => 1, + _ => c_n(n - 1) * 2 * (2 * n - 1) / (n + 1) + } } fn main() { - for i in range(1u64, 11u64) { - println!("c_n({}) = {}", i, c_n(i)) + for i in 1..16 { + println!("c_n({}) = {}", i, c_n(i)); } } diff --git a/Task/Catalan-numbers/VBScript/catalan-numbers.vb b/Task/Catalan-numbers/VBScript/catalan-numbers.vb new file mode 100644 index 0000000000..46179b6cfa --- /dev/null +++ b/Task/Catalan-numbers/VBScript/catalan-numbers.vb @@ -0,0 +1,23 @@ +Function catalan(n) + catalan = factorial(2*n)/(factorial(n+1)*factorial(n)) +End Function + +Function factorial(n) + If n = 0 Then + Factorial = 1 + Else + For i = n To 1 Step -1 + If i = n Then + factorial = n + Else + factorial = factorial * i + End If + Next + End If +End Function + +'Find the first 15 Catalan numbers. +For j = 1 To 15 + WScript.StdOut.Write j & " = " & catalan(j) + WScript.StdOut.WriteLine +Next diff --git a/Task/Catamorphism/BBC-BASIC/catamorphism.bbc b/Task/Catamorphism/BBC-BASIC/catamorphism.bbc new file mode 100644 index 0000000000..46f28dc80f --- /dev/null +++ b/Task/Catamorphism/BBC-BASIC/catamorphism.bbc @@ -0,0 +1,15 @@ + DIM a(4) + a() = 1, 2, 3, 4, 5 + PRINT FNreduce(a(), "+") + PRINT FNreduce(a(), "-") + PRINT FNreduce(a(), "*") + END + + DEF FNreduce(arr(), op$) + REM!Keep tmp, arr() + LOCAL I%, tmp + tmp = arr(0) + FOR I% = 1 TO DIM(arr(), 1) + tmp = EVAL("tmp " + op$ + " arr(I%)") + NEXT + = tmp diff --git a/Task/Catamorphism/DCL/catamorphism.dcl b/Task/Catamorphism/DCL/catamorphism.dcl new file mode 100644 index 0000000000..3adf4467d2 --- /dev/null +++ b/Task/Catamorphism/DCL/catamorphism.dcl @@ -0,0 +1,26 @@ +$ list = "1,2,3,4,5" +$ call reduce list "+" +$ show symbol result +$ +$ numbers = "5,4,3,2,1" +$ call reduce numbers "-" +$ show symbol result +$ +$ call reduce list "*" +$ show symbol result +$ exit +$ +$ reduce: subroutine +$ local_list = 'p1 +$ value = f$integer( f$element( 0, ",", local_list )) +$ i = 1 +$ loop: +$ element = f$element( i, ",", local_list ) +$ if element .eqs. "," then $ goto done +$ value = value 'p2 f$integer( element ) +$ i = i + 1 +$ goto loop +$ done: +$ result == value +$ exit +$ endsubroutine diff --git a/Task/Catamorphism/Elixir/catamorphism.elixir b/Task/Catamorphism/Elixir/catamorphism.elixir new file mode 100644 index 0000000000..1dac4dca04 --- /dev/null +++ b/Task/Catamorphism/Elixir/catamorphism.elixir @@ -0,0 +1,6 @@ +iex(1)> Enum.reduce(1..10, fn i,acc -> i+acc end) +55 +iex(2)> Enum.reduce(1..10, fn i,acc -> i*acc end) +3628800 +iex(3)> Enum.reduce(10..-10, "", fn i,acc -> acc <> to_string(i) end) +"109876543210-1-2-3-4-5-6-7-8-9-10" diff --git a/Task/Catamorphism/Erlang/catamorphism.erl b/Task/Catamorphism/Erlang/catamorphism.erl new file mode 100644 index 0000000000..cc265cfdb3 --- /dev/null +++ b/Task/Catamorphism/Erlang/catamorphism.erl @@ -0,0 +1,18 @@ +%% @author Salvador Tamarit + +-module(catamorphism). + +-export([test/0]). + +test() -> + Nums = lists:seq(1,10), + Summation = + lists:foldl(fun(X, Acc) -> X + Acc end, 0, Nums), + Product = + lists:foldl(fun(X, Acc) -> X * Acc end, 1, Nums), + Concatenation = + lists:foldr( + fun(X, Acc) -> integer_to_list(X) ++ Acc end, + "", + Nums), + {Summation, Product, Concatenation}. diff --git a/Task/Catamorphism/Julia/catamorphism.julia b/Task/Catamorphism/Julia/catamorphism.julia new file mode 100644 index 0000000000..4f38c9a752 --- /dev/null +++ b/Task/Catamorphism/Julia/catamorphism.julia @@ -0,0 +1 @@ +for op in [+, -, *] println(reduce(op, 1:5)) end diff --git a/Task/Catmull-Clark-subdivision-surface/OCaml/catmull-clark-subdivision-surface-2.ocaml b/Task/Catmull-Clark-subdivision-surface/OCaml/catmull-clark-subdivision-surface-2.ocaml index 8aab568789..82075f9e25 100644 --- a/Task/Catmull-Clark-subdivision-surface/OCaml/catmull-clark-subdivision-surface-2.ocaml +++ b/Task/Catmull-Clark-subdivision-surface/OCaml/catmull-clark-subdivision-surface-2.ocaml @@ -1,23 +1,21 @@ type point = { x: float; y : float; z : float } +let zero = { x = 0.0; y = 0.0; z = 0.0 } let add a b = { x = a.x+.b.x; y = a.y+.b.y; z = a.z+.b.z } let mul a k = { x = a.x*.k; y = a.y*.k; z= a.z*.k } let div p k = mul p (1.0/.k) -let fsgn x y = if x < y then -1 else if x > y then 1 else 0 -let cmp a b = if a.x=b.x then if a.y=b.y then fsgn b.z a.z else fsgn b.y a.y else fsgn b.x a.x type face = Face of point list type edge = Edge of point*point -let ecmp (Edge (p1,p2)) (Edge (p3,p4)) = let sgn = cmp p1 p3 in if sgn = 0 then cmp p2 p4 else sgn -let make_edge a b = if cmp a b < 0 then Edge (b,a) else Edge (a,b) +let make_edge a b = Edge (min a b, max a b) let make_face a b c d = Face [a;b;c;d] -let centroid plist = div (List.fold_left add {x=0.0;y=0.0;z=0.0} plist) (float (List.length plist)) +let centroid plist = div (List.fold_left add zero plist) (float (List.length plist)) let mid_edge (Edge (p1,p2)) = div (add p1 p2) 2.0 let face_point (Face pl) = centroid pl let point_in_face p (Face pl) = List.mem p pl -let point_in_edge p (Edge (p1,p2)) = (p = p1 || p = p2) -let edge_in_face (Edge (p1,p2)) (Face pl) = (List.mem p1 pl && List.mem p2 pl) +let point_in_edge p (Edge (p1,p2)) = p = p1 || p = p2 +let edge_in_face (Edge (p1,p2)) f = point_in_face p1 f && point_in_face p2 f let border_edge faces e = List.length (List.filter (edge_in_face e) faces) < 2 @@ -32,47 +30,39 @@ let mod_vertex faces edges p = let v_edges = List.filter (point_in_edge p) edges in let v_faces = List.filter (point_in_face p) faces in let n = List.length v_faces in - let is_border = n != (List.length v_edges) in + let is_border = n <> (List.length v_edges) in if is_border then let border_mids = List.map mid_edge (List.filter (border_edge faces) v_edges) in (* description ambiguity: average (border+p) or average(average(border),p) ?? *) centroid (p :: border_mids) else - let avg_face = centroid (List.map face_point v_faces) in - let avg_mid = centroid (List.map mid_edge v_edges) in - div (add (add (mul p (float(n-3))) avg_face) (mul avg_mid 2.0)) (float n) + let avg_face = centroid (List.map face_point v_faces) in + let avg_mid = centroid (List.map mid_edge v_edges) in + div (add (add (mul p (float(n-3))) avg_face) (mul avg_mid 2.0)) (float n) -let iter_edges f (Face pl) = - let rec next = function - | [] -> () - | a :: [] -> f a (List.hd pl) - | a :: b :: c -> f a b; next (b::c) in - next pl;; +let edges_of_face (Face pl) = + let rec next acc = function + | [] -> invalid_arg "empty face" + | a :: [] -> List.rev (make_edge a (List.hd pl) :: acc) + | a :: (b :: _ as xs) -> next (make_edge a b :: acc) xs in + next [] pl let catmull_clark faces = - let module EdgeSet = Set.Make(struct type t = edge let compare = ecmp end) in - let eset = ref EdgeSet.empty in - let add_edge a b = eset := EdgeSet.add (make_edge a b) !eset in - let edges = (List.iter (iter_edges add_edge) faces; EdgeSet.elements !eset) in - let new_faces = ref [] in + let module EdgeSet = Set.Make(struct type t = edge let compare = compare end) in + let edges = EdgeSet.elements (EdgeSet.of_list (List.concat (List.map edges_of_face faces))) in let mod_face ((Face pl) as face) = let fp = face_point face in - let ep = ref [] in ( - iter_edges (fun a b -> ep := (edge_point faces (make_edge a b)):: !ep) face; - let e_tl = List.hd (List.rev !ep) in - let v' = List.map (mod_vertex faces edges) pl in - let rec add_facet e vl el = (match (vl,el) with - | (h1::t1),(h2::t2) -> - new_faces := (make_face e h1 h2 fp) :: !new_faces; - add_facet h2 t1 t2 - | ([],[]) -> () - | _ -> failwith "vertex/edge mismatch") in - add_facet e_tl v' !ep) in - (List.iter mod_face faces; !new_faces) + let ep = List.map (edge_point faces) (edges_of_face face) in + let e_tl = List.hd (List.rev ep) in + let vl = List.map (mod_vertex faces edges) pl in + let add_facet (e', acc) v e = e, (make_face e' v e fp :: acc) in + let _, new_faces = List.fold_left2 add_facet (e_tl, []) vl ep in + List.rev new_faces in + List.concat (List.map mod_face faces) let show_faces fl = let pr_point p = Printf.printf " (%.4f, %.4f, %.4f)" p.x p.y p.z in - let pr_face (Face(pl)) = print_string "Face:"; List.iter pr_point pl; print_string "\n" in + let pr_face (Face pl) = print_string "Face:"; List.iter pr_point pl; print_string "\n" in (print_string "surface {\n"; List.iter pr_face fl; print_string "}\n") let c p q r = let s i = if i = 0 then -1.0 else 1.0 in { x = s p; y = s q; z = s r } ;; diff --git a/Task/Character-codes/ALGOL-W/character-codes.alg b/Task/Character-codes/ALGOL-W/character-codes.alg new file mode 100644 index 0000000000..6103644fe1 --- /dev/null +++ b/Task/Character-codes/ALGOL-W/character-codes.alg @@ -0,0 +1,6 @@ +begin + % display the character code of "a" (97 in ASCII) % + write( decode( "a" ) ); + % display the character corresponding to 97 ("a" in ASCII) % + write( code( 97 ) ); +end. diff --git a/Task/Character-codes/AppleScript/character-codes.applescript b/Task/Character-codes/AppleScript/character-codes.applescript new file mode 100644 index 0000000000..9e845ce4dc --- /dev/null +++ b/Task/Character-codes/AppleScript/character-codes.applescript @@ -0,0 +1,2 @@ +log(id of "a") +log(id of "aA") diff --git a/Task/Character-codes/Elena/character-codes.elena b/Task/Character-codes/Elena/character-codes.elena index 32e8bc8032..f804a38d85 100644 --- a/Task/Character-codes/Elena/character-codes.elena +++ b/Task/Character-codes/Elena/character-codes.elena @@ -1,7 +1,9 @@ #define system. -#symbol Program => +#symbol program => [ - console write:("a" getAt:0 Number). - console write:(CharValue new &short:97). + #var ch := #97. + + console writeLine:ch. + console writeLine:(ch int). ]. diff --git a/Task/Character-codes/Elixir/character-codes.elixir b/Task/Character-codes/Elixir/character-codes.elixir new file mode 100644 index 0000000000..13dbb8e0de --- /dev/null +++ b/Task/Character-codes/Elixir/character-codes.elixir @@ -0,0 +1,4 @@ +iex(1)> code = ?a +97 +iex(2)> to_string([code]) +"a" diff --git a/Task/Character-codes/J/character-codes.j b/Task/Character-codes/J/character-codes-1.j similarity index 100% rename from Task/Character-codes/J/character-codes.j rename to Task/Character-codes/J/character-codes-1.j diff --git a/Task/Character-codes/J/character-codes-2.j b/Task/Character-codes/J/character-codes-2.j new file mode 100644 index 0000000000..756930ef45 --- /dev/null +++ b/Task/Character-codes/J/character-codes-2.j @@ -0,0 +1,2 @@ + 3 u: 'abc☺' +97 98 99 226 152 186 diff --git a/Task/Character-codes/J/character-codes-3.j b/Task/Character-codes/J/character-codes-3.j new file mode 100644 index 0000000000..b1aa6f4b2a --- /dev/null +++ b/Task/Character-codes/J/character-codes-3.j @@ -0,0 +1,4 @@ + 97 98 99{a. +abc + a.i.'abc' +97 98 99 diff --git a/Task/Character-codes/REXX/character-codes.rexx b/Task/Character-codes/REXX/character-codes-1.rexx similarity index 100% rename from Task/Character-codes/REXX/character-codes.rexx rename to Task/Character-codes/REXX/character-codes-1.rexx diff --git a/Task/Character-codes/REXX/character-codes-2.rexx b/Task/Character-codes/REXX/character-codes-2.rexx new file mode 100644 index 0000000000..28ee1d261a --- /dev/null +++ b/Task/Character-codes/REXX/character-codes-2.rexx @@ -0,0 +1,14 @@ +/* REXX */ +yyy='c' /*assign a lowercase c to YYY */ +yyy='83'x /*assign hexadecimal 83 to YYY */ + /*the X can be upper/lowercase.*/ +yyy=x2c(83) /* (same as above) */ +yyy='10000011'b /* (same as above) */ +yyy='1000 0011'b /* (same as above) */ + /*the B can be upper/lowercase.*/ +yyy=d2c(129) /*assign decimal code 129 to YYY */ + +say yyy /*displays the value of YYY */ +say c2x(yyy) /*displays the value of YYY in hexadecimal. */ +say c2d(yyy) /*displays the value of YYY in decimal. */ +say x2b(c2x(yyy))/*displays the value of YYY in binary (bit string). */ diff --git a/Task/Character-codes/Rust/character-codes.rust b/Task/Character-codes/Rust/character-codes.rust new file mode 100644 index 0000000000..5616af64b1 --- /dev/null +++ b/Task/Character-codes/Rust/character-codes.rust @@ -0,0 +1,11 @@ +use std::char::from_u32; + +fn main() { + //ascii char + println!("{}", 'a' as u8); + println!("{}", 97 as char); + + //unicode char + println!("{}", 'π' as u32); + println!("{}", from_u32(960).unwrap()); +} diff --git a/Task/Character-codes/VBScript/character-codes.vb b/Task/Character-codes/VBScript/character-codes.vb new file mode 100644 index 0000000000..4be511c69b --- /dev/null +++ b/Task/Character-codes/VBScript/character-codes.vb @@ -0,0 +1,5 @@ +'prints a +WScript.StdOut.WriteLine Chr(97) + +'prints 97 +WScript.StdOut.WriteLine Asc("a") diff --git a/Task/Check-Machin-like-formulas/00DESCRIPTION b/Task/Check-Machin-like-formulas/00DESCRIPTION index 97dece1003..92f70a8543 100644 --- a/Task/Check-Machin-like-formulas/00DESCRIPTION +++ b/Task/Check-Machin-like-formulas/00DESCRIPTION @@ -24,7 +24,11 @@ and confirm that the following formula is incorrect by showing '''tan'''(''right These identities are useful in calculating the values: : \tan(a + b) = {\tan(a) + \tan(b) \over 1 - \tan(a) \tan(b)} -: \tan\left(\arctan{a\over b}\right) = {a\over b} + +: \tan\left(\arctan{a \over b}\right) = {a \over b} + : \tan(-a) = -\tan(a) You can store the equations in any convenient data structure, but for extra credit parse them from human-readable [[Check_Machin-like_formulas/text_equations|text input]]. + +Note that to formally prove the formula correct you would also have to show that ''{-3 pi \over 4} < right hand side < {5 pi \over 4}'' due to ''\tan()'' periodicity. diff --git a/Task/Check-Machin-like-formulas/Perl/check-machin-like-formulas.pl b/Task/Check-Machin-like-formulas/Perl/check-machin-like-formulas.pl new file mode 100644 index 0000000000..edda40eef3 --- /dev/null +++ b/Task/Check-Machin-like-formulas/Perl/check-machin-like-formulas.pl @@ -0,0 +1,40 @@ +use Math::BigRat try=>"GMP"; + +sub taneval { + my($coef,$f) = @_; + $f = Math::BigRat->new($f) unless ref($f); + return 0 if $coef == 0; + return $f if $coef == 1; + return -taneval(-$coef, $f) if $coef < 0; + my($a,$b) = ( taneval($coef>>1, $f), taneval($coef-($coef>>1),$f) ); + ($a+$b)/(1-$a*$b); +} + +sub tans { + my @xs=@_; + return taneval(@{$xs[0]}) if scalar(@xs)==1; + my($a,$b) = ( tans(@xs[0..($#xs>>1)]), tans(@xs[($#xs>>1)+1..$#xs]) ); + ($a+$b)/(1-$a*$b); +} + +sub test { + printf "%5s (%s)\n", (tans(@_)==1)?"OK":"Error", join(" ",map{"[@$_]"} @_); +} + +test([1,'1/2'], [1,'1/3']); +test([2,'1/3'], [1,'1/7']); +test([4,'1/5'], [-1,'1/239']); +test([5,'1/7'],[2,'3/79']); +test([5,'29/278'],[7,'3/79']); +test([1,'1/2'],[1,'1/5'],[1,'1/8']); +test([4,'1/5'],[-1,'1/70'],[1,'1/99']); +test([5,'1/7'],[4,'1/53'],[2,'1/4443']); +test([6,'1/8'],[2,'1/57'],[1,'1/239']); +test([8,'1/10'],[-1,'1/239'],[-4,'1/515']); +test([12,'1/18'],[8,'1/57'],[-5,'1/239']); +test([16,'1/21'],[3,'1/239'],[4,'3/1042']); +test([22,'1/28'],[2,'1/443'],[-5,'1/1393'],[-10,'1/11018']); +test([22,'1/38'],[17,'7/601'],[10,'7/8149']); +test([44,'1/57'],[7,'1/239'],[-12,'1/682'],[24,'1/12943']); +test([88,'1/172'],[51,'1/239'],[32,'1/682'],[44,'1/5357'],[68,'1/12943']); +test([88,'1/172'],[51,'1/239'],[32,'1/682'],[44,'1/5357'],[68,'1/12944']); diff --git a/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx b/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx index f025634e0b..5549a7b279 100644 --- a/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx +++ b/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx @@ -1,6 +1,6 @@ -/*REXX program evaluates some expressions and verifies their veracity.*/ -parse arg digs .; if digs=='' then digs=100 /*use default for digs?*/ -numeric digits digs+10; numeric fuzz 3; pi=pi(); @.= +/*REXX program evaluates some Machin-like formulas and verifies their veracity*/ +parse arg digs .; if digs=='' then digs=100 /*use default for decimal digs?*/ +numeric digits digs+10; numeric fuzz 3; pi=pi(); @.= @.1 = 'pi/4 = atan(1/2) + atan(1/3)' @.2 = 'pi/4 = 2*atan(1/3) + atan(1/7)' @.3 = 'pi/4 = 4*atan(1/5) - atan(1/239)' @@ -19,32 +19,34 @@ numeric digits digs+10; numeric fuzz 3; pi=pi(); @.= @.16 = 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12943)' @.17 = 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12944)' - do j=1 while @.j\=='' /*evaluate each of the formulas. */ - interpret 'answer=' "(" @.j ")" /*the heavy lifting.*/ + do j=1 while @.j\=='' /*evaluate each "Machin-like" formulas.*/ + interpret 'answer=' "(" @.j ")" /*this is the heavy lifting.*/ say right(word('bad OK',answer+1),3)": " space(@.j,0) - end /*j*/ /* [↑] show OK | bad, formula. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────subroutines─────────────────────────*/ + end /*j*/ /* [↑] show OK or bad, and the formula*/ +exit /*stick a fork in it, we're all done. */ +/*────broutines───────────────────────────────────────────────────────────────*/ +pi: return 3.14159265358979323846264338327950288419716939937510582097494459 ||, + 230781640628620899862803482534211706798214808651 +AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X='||x +AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X='||x +tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x +tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 + Acos: procedure; parse arg x; if x<-1 | x>1 then call AcosErr - return .5*pi()-Asin(x) + return .5*pi()-Asin(x) -Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x -if abs(x)>=sqrt(2)*.5 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z - do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end -return z +Asin: procedure expose $.; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a + if a>1 then call AsinErr x /*X argument is out of valid range. */ + if a>=sqrt(2)*.5 then return sign(x)*acos(sqrt(1-aa), '-ASIN') + do j=2 by 2 until p=z; p=z; o=o*aa*(j-1)/j; z=z+o/(j+1); end + return z /* [↑] compute until no more noise. */ Atan: procedure; parse arg x; if abs(x)=1 then return pi()/4*sign(x) return Asin(x/sqrt(1+x**2)) -sqrt: procedure; parse arg x; if x=0 then return 0; m.=9; p=digits(); i= -numeric digits 9; if x<0 then do; x=-x; i='i'; end; 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)i -pi: return, -3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651 -AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X='||x -AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X='||x -tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x -tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Check-that-file-exists/00DESCRIPTION b/Task/Check-that-file-exists/00DESCRIPTION index 76ae248e94..432587f942 100644 --- a/Task/Check-that-file-exists/00DESCRIPTION +++ b/Task/Check-that-file-exists/00DESCRIPTION @@ -1,2 +1,4 @@ In this task, the job is to verify that a file called "input.txt" and the directory called "docs" exist. This should be done twice: once for the current working directory and once for a file and a directory in the filesystem root. + +Optional criteria (May 2015): verify it works with 0-length files; and with an unusual filename: `Abdu'l-Bahá.txt diff --git a/Task/Check-that-file-exists/AWK/check-that-file-exists-1.awk b/Task/Check-that-file-exists/AWK/check-that-file-exists-1.awk new file mode 100644 index 0000000000..0ec9009f5f --- /dev/null +++ b/Task/Check-that-file-exists/AWK/check-that-file-exists-1.awk @@ -0,0 +1,14 @@ +@load "filefuncs" +BEGIN { + exists("input.txt") + exists("/input.txt") + exists("docs") + exists("/docs") +} + +function exists(name ,fd) { + if ( stat(name, fd) == -1) + print name " doesn't exist" + else + print name " exists" +} diff --git a/Task/Check-that-file-exists/AWK/check-that-file-exists-2.awk b/Task/Check-that-file-exists/AWK/check-that-file-exists-2.awk new file mode 100644 index 0000000000..063ec96802 --- /dev/null +++ b/Task/Check-that-file-exists/AWK/check-that-file-exists-2.awk @@ -0,0 +1,26 @@ +BEGIN { + exists("input.txt") + exists("\\input.txt") + exists("docs") + exists("\\docs") + exit(0) +} + +# +# Check if file or directory exists, even 0-length file. +# Return 0 if not exist, 1 if exist +# +function exists(file ,line, msg) +{ + if ( (getline line < file) == -1 ) + { + # "Permission denied" is for MS-Windows + msg = (ERRNO ~ /Permission denied/ || ERRNO ~ /a directory/) ? "1" : "0" + close(file) + return msg + } + else { + close(file) + return 1 + } +} diff --git a/Task/Check-that-file-exists/AWK/check-that-file-exists-3.awk b/Task/Check-that-file-exists/AWK/check-that-file-exists-3.awk new file mode 100644 index 0000000000..72840e0f00 --- /dev/null +++ b/Task/Check-that-file-exists/AWK/check-that-file-exists-3.awk @@ -0,0 +1 @@ +gawk 'BEGINFILE{if (ERRNO) {print "Not exist."; exit} } {print "Exist."; exit}' input.txt diff --git a/Task/Check-that-file-exists/AWK/check-that-file-exists.awk b/Task/Check-that-file-exists/AWK/check-that-file-exists.awk deleted file mode 100644 index 658db43956..0000000000 --- a/Task/Check-that-file-exists/AWK/check-that-file-exists.awk +++ /dev/null @@ -1,18 +0,0 @@ -# syntax: GAWK -f CHECK_THAT_FILE_EXISTS.AWK -BEGIN { - check_exists("input.txt") - check_exists("\\input.txt") - check_exists("docs") - check_exists("\\docs") - exit(0) -} -function check_exists(name, fnr,msg,rec) { - while (getline rec 0) { - fnr++ - break - } - # "Permission denied" is for MS-Windows - msg = (ERRNO == 0 || ERRNO ~ /Permission denied/ || fnr > 0) ? "exists" : "does not exist" - printf("%s - %s\n",name,msg) - close(name) -} diff --git a/Task/Check-that-file-exists/DCL/check-that-file-exists.dcl b/Task/Check-that-file-exists/DCL/check-that-file-exists.dcl new file mode 100644 index 0000000000..102767c22c --- /dev/null +++ b/Task/Check-that-file-exists/DCL/check-that-file-exists.dcl @@ -0,0 +1,24 @@ +$ if f$search( "input.txt" ) .eqs. "" +$ then +$ write sys$output "input.txt not found" +$ else +$ write sys$output "input.txt found" +$ endif +$ if f$search( "docs.dir" ) .eqs. "" +$ then +$ write sys$output "directory docs not found" +$ else +$ write sys$output "directory docs found" +$ endif +$ if f$search( "[000000]input.txt" ) .eqs. "" +$ then +$ write sys$output "[000000]input.txt not found" +$ else +$ write sys$output "[000000]input.txt found" +$ endif +$ if f$search( "[000000]docs.dir" ) .eqs. "" +$ then +$ write sys$output "directory [000000]docs not found" +$ else +$ write sys$output "directory [000000]docs found" +$ endif diff --git a/Task/Check-that-file-exists/Elixir/check-that-file-exists.elixir b/Task/Check-that-file-exists/Elixir/check-that-file-exists.elixir new file mode 100644 index 0000000000..42374806eb --- /dev/null +++ b/Task/Check-that-file-exists/Elixir/check-that-file-exists.elixir @@ -0,0 +1,4 @@ +File.regular?("input.txt") +File.dir?("docs") +File.regular?("/input.txt") +File.dir?("/docs") diff --git a/Task/Check-that-file-exists/REXX/check-that-file-exists.rexx b/Task/Check-that-file-exists/REXX/check-that-file-exists-1.rexx similarity index 100% rename from Task/Check-that-file-exists/REXX/check-that-file-exists.rexx rename to Task/Check-that-file-exists/REXX/check-that-file-exists-1.rexx diff --git a/Task/Check-that-file-exists/REXX/check-that-file-exists-2.rexx b/Task/Check-that-file-exists/REXX/check-that-file-exists-2.rexx new file mode 100644 index 0000000000..0f20078832 --- /dev/null +++ b/Task/Check-that-file-exists/REXX/check-that-file-exists-2.rexx @@ -0,0 +1,8 @@ +/* Check if a file already exists */ +filename='file.txt' +IF ~Openfile(filename) THEN CALL Openfile(':'filename) +EXIT 0 +Openfile: +IF ~Exists(filename) THEN RETURN 0 +CALL Open(filehandle,filename,'APPEND') +RETURN 1 diff --git a/Task/Checkpoint-synchronization/C++/checkpoint-synchronization.cpp b/Task/Checkpoint-synchronization/C++/checkpoint-synchronization.cpp new file mode 100644 index 0000000000..fa617cee12 --- /dev/null +++ b/Task/Checkpoint-synchronization/C++/checkpoint-synchronization.cpp @@ -0,0 +1,51 @@ +#include +#include +#include +#include +#include +#include + +std::mutex cout_lock; + +class Latch +{ + std::atomic semafor; + public: + Latch(int limit) : semafor(limit) {} + + void wait() + { + semafor.fetch_sub(1); + while(semafor.load() > 0) + std::this_thread::yield(); + } +}; + +struct Worker +{ + static void do_work(int how_long, Latch& barrier, std::string name) + { + std::this_thread::sleep_for(std::chrono::milliseconds(how_long)); + { std::lock_guard lock(cout_lock); + std::cout << "Worker " << name << " finished work\n"; } + barrier.wait(); + { std::lock_guard lock(cout_lock); + std::cout << "Worker " << name << " finished assembly\n"; } + } +}; + +int main() +{ + Latch latch(5); + std::mt19937 rng(std::random_device{}()); + std::uniform_int_distribution<> dist(300, 3000); + std::thread threads[] { + std::thread(&Worker::do_work, dist(rng), std::ref(latch), "John"), + std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Henry"}, + std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Smith"}, + std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Jane"}, + std::thread{&Worker::do_work, dist(rng), std::ref(latch), "Mary"}, + }; + for(auto& t: threads) t.join(); + std::cout << "Assembly is finished"; +} diff --git a/Task/Chinese-remainder-theorem/360-Assembly/chinese-remainder-theorem.360 b/Task/Chinese-remainder-theorem/360-Assembly/chinese-remainder-theorem.360 new file mode 100644 index 0000000000..0a023cf228 --- /dev/null +++ b/Task/Chinese-remainder-theorem/360-Assembly/chinese-remainder-theorem.360 @@ -0,0 +1,44 @@ +* Chinese remainder theorem 06/09/2015 +CHINESE CSECT + USING CHINESE,R12 base addr + LR R12,R15 +BEGIN LA R9,1 m=1 + LA R6,1 j=1 +LOOPJ C R6,NN do j=1 to nn + BH ELOOPJ + LR R1,R6 j + SLA R1,2 j*4 + M R8,N-4(R1) m=m*n(j) + LA R6,1(R6) j=j+1 + B LOOPJ +ELOOPJ LA R6,1 x=1 +LOOPX CR R6,R9 do x=1 to m + BH ELOOPX + LA R7,1 i=1 +LOOPI C R7,NN do i=1 to nn + BH ELOOPI + LR R1,R7 i + SLA R1,2 i*4 + LR R5,R6 x + LA R4,0 + D R4,N-4(R1) x//n(i) + C R4,A-4(R1) if x//n(i)^=a(i) + BNE ITERX then iterate x + LA R7,1(R7) i=i+1 + B LOOPI +ELOOPI MVC PG(2),=C'x=' + XDECO R6,PG+2 edit x + XPRNT PG,14 print buffer + B RETURN +ITERX LA R6,1(R6) x=x+1 + B LOOPX +ELOOPX XPRNT NOSOL,17 print +RETURN XR R15,R15 rc=0 + BR R14 +NN DC F'3' +N DC F'3',F'5',F'7' +A DC F'2',F'3',F'2' +PG DS CL80 +NOSOL DC CL17'no solution found' + YREGS + END CHINESE diff --git a/Task/Chinese-remainder-theorem/Elixir/chinese-remainder-theorem.elixir b/Task/Chinese-remainder-theorem/Elixir/chinese-remainder-theorem.elixir new file mode 100644 index 0000000000..f6c0c60193 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Elixir/chinese-remainder-theorem.elixir @@ -0,0 +1,13 @@ +defmodule Chinese do + def remainder(mods, remainders) do + max = Enum.reduce(mods, fn x,acc -> x*acc end) + Enum.zip(mods, remainders) + |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> Enum.into(HashSet.new) end) + |> Enum.reduce(fn set,acc -> Set.intersection(set, acc) end) + |> Set.to_list + end +end + +IO.inspect Chinese.remainder([3,5,7], [2,3,2]) +IO.inspect Chinese.remainder([10,4,9], [11,22,19]) +IO.inspect Chinese.remainder([11,12,13], [10,4,12]) diff --git a/Task/Chinese-remainder-theorem/Python/chinese-remainder-theorem.py b/Task/Chinese-remainder-theorem/Python/chinese-remainder-theorem.py index 4e74febffc..2af8992414 100644 --- a/Task/Chinese-remainder-theorem/Python/chinese-remainder-theorem.py +++ b/Task/Chinese-remainder-theorem/Python/chinese-remainder-theorem.py @@ -1,3 +1,14 @@ +# Python 2.7 +def chinese_remainder(n, a): + sum = 0 + prod = reduce(lambda a, b: a*b, n) + + for n_i, a_i in zip(n, a): + p = prod / n_i + sum += a_i * mul_inv(p, n_i) * p + return sum % prod + + def mul_inv(a, b): b0 = b x0, x1 = 0, 1 @@ -9,15 +20,7 @@ def mul_inv(a, b): 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))) + print chinese_remainder(n, a) diff --git a/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-1.rexx b/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-1.rexx index fa5231dd71..888e6be2c4 100644 --- a/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-1.rexx +++ b/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-1.rexx @@ -1,24 +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. */ +/*REXX program demonstrates Sun Tzu's (or Sunzi's) Chinese Remainder Theorem.*/ +parse arg Ns As . /*get optional arguments from the C.L. */ +if Ns=='' then Ns = '3,5,7' /*Ns not specified? Then use default.*/ +if As=='' then As = '2,3,2' /*As " " " " " */ + say 'Ns: ' Ns + say 'As: ' As; say +Ns=space(translate(Ns,,',')); #=words(Ns) /*elide any 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 and Ns. */ + n.j=word(Ns,j); N=N*n.j /*get an N.j and calculate product. */ + a.j=word(As,j) /* " " A.j from the As list. */ 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. */ + do x=1 for N /*use a simple algebraic method. */ + do i=1 for # /*process each N.i and A.i number.*/ + if x//n.i\==a.i then iterate x /*is modulus correct for the number X ?*/ + end /*i*/ /* [↑] limit solution to the product. */ + say 'found a solution with X=' x /*display one possible solution. */ + exit /*stick a fork in it, we're all done. */ + end /*x*/ + +say 'no solution found.' /*oops, announce that solution ¬ 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 index 6be90a012f..b90b5973f2 100644 --- a/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-2.rexx +++ b/Task/Chinese-remainder-theorem/REXX/chinese-remainder-theorem-2.rexx @@ -1,26 +1,28 @@ -/*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. */ +/*REXX program demonstrates Sun Tzu's (or Sunzi's) Chinese Remainder Theorem.*/ +parse arg Ns As . /*get optional arguments from the C.L. */ +if Ns=='' then Ns = '3,5,7' /*Ns not specified? Then use default.*/ +if As=='' then As = '2,3,2' /*As " " " " " */ + say 'Ns: ' Ns + say 'As: ' As; say +Ns=space(translate(Ns,,',')); #=words(Ns) /*elide any 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 and Ns. */ + n.j=word(Ns,j); N=N*n.j /*get an N.j and calculate product. */ + a.j=word(As,j) /* " " A.j from the As list. */ 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.*/ +@.= /* [↓] 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 (array) list of modulo values*/ + end /*i*/ + /* [↓] find common number in the sets.*/ + do x=1 for N; if @.1.x=='' then iterate /*locate a number. */ + do v=2 to #; if @.v.x=='' then iterate x; end /*Is in all sets ? */ + say 'found a solution with X=' x /*display one possible solution. */ + exit /*stick a fork in it, we're all done. */ end /*x*/ - /*stick a fork in it, we're done.*/ -say 'no solution found.' /*oops, there's not a solution. */ + +say 'no solution found.' /*oops, announce that solution ¬ found.*/ diff --git a/Task/Cholesky-decomposition/00DESCRIPTION b/Task/Cholesky-decomposition/00DESCRIPTION index 6648b11250..0d67891916 100644 --- a/Task/Cholesky-decomposition/00DESCRIPTION +++ b/Task/Cholesky-decomposition/00DESCRIPTION @@ -71,3 +71,8 @@ Example 2: 54 86 174 134 12.72792 3.04604 1.64974 0.00000 42 62 134 106 9.89949 1.62455 1.84971 1.39262 + + +;Note: +# The Cholesky decomposition of a [[Pascal matrix generation‎|Pascal]] upper-triangle matrix is the [[wp:Identity matrix|Identity matrix]] of the same size. +# The Cholesky decomposition of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. diff --git a/Task/Cholesky-decomposition/Clojure/cholesky-decomposition-1.clj b/Task/Cholesky-decomposition/Clojure/cholesky-decomposition-1.clj new file mode 100644 index 0000000000..bf2a2df42a --- /dev/null +++ b/Task/Cholesky-decomposition/Clojure/cholesky-decomposition-1.clj @@ -0,0 +1,11 @@ +(defn cholesky + [matrix] + (let [n (count matrix) + A (to-array-2d matrix) + L (make-array Double/TYPE n n)] + (doseq [i (range n) j (range (inc i))] + (let [s (reduce + (for [k (range j)] (* (aget L i k) (aget L j k))))] + (aset L i j (if (= i j) + (Math/sqrt (- (aget A i i) s)) + (* (/ 1.0 (aget L j j)) (- (aget A i j) s)))))) + (vec (map vec L)))) diff --git a/Task/Cholesky-decomposition/Clojure/cholesky-decomposition-2.clj b/Task/Cholesky-decomposition/Clojure/cholesky-decomposition-2.clj new file mode 100644 index 0000000000..0bcafec95c --- /dev/null +++ b/Task/Cholesky-decomposition/Clojure/cholesky-decomposition-2.clj @@ -0,0 +1,10 @@ +(cholesky [[25 15 -5] [15 18 0] [-5 0 11]]) +;=> [[ 5.0 0.0 0.0] +; [ 3.0 3.0 0.0] +; [-1.0 1.0 3.0]] + +(cholesky [[18 22 54 42] [22 70 86 62] [54 86 174 134] [42 62 134 106]]) +;=> [[ 4.242640687119285 0.0 0.0 0.0 ] +; [ 5.185449728701349 6.565905201197403 0.0 0.0 ] +; [12.727922061357857 3.0460384954008553 1.6497422479090704 0.0 ] +; [ 9.899494936611667 1.624553864213788 1.8497110052313648 1.3926212476456026]] diff --git a/Task/Cholesky-decomposition/Go/cholesky-decomposition-2.go b/Task/Cholesky-decomposition/Go/cholesky-decomposition-2.go index d7fa2ffab5..77a106ff3a 100644 --- a/Task/Cholesky-decomposition/Go/cholesky-decomposition-2.go +++ b/Task/Cholesky-decomposition/Go/cholesky-decomposition-2.go @@ -6,23 +6,12 @@ import ( ) type matrix struct { - ele []complex128 stride int -} - -func matrixFromRows(rows [][]complex128) *matrix { - if len(rows) == 0 { - return &matrix{nil, 0} - } - m := &matrix{make([]complex128, len(rows)*len(rows[0])), len(rows[0])} - for rx, row := range rows { - copy(m.ele[rx*m.stride:(rx+1)*m.stride], row) - } - return m + ele []complex128 } func like(a *matrix) *matrix { - return &matrix{make([]complex128, len(a.ele)), a.stride} + return &matrix{a.stride, make([]complex128, len(a.ele))} } func (m *matrix) print(heading string) { @@ -62,17 +51,22 @@ func (a *matrix) choleskyDecomp() *matrix { } func main() { - demo("A:", matrixFromRows([][]complex128{ - {25, 15, -5}, - {15, 18, 0}, - {-5, 0, 11}, - })) - demo("A:", matrixFromRows([][]complex128{ - {18, 22, 54, 42}, - {22, 70, 86, 62}, - {54, 86, 174, 134}, - {42, 62, 134, 106}, - })) + demo("A:", &matrix{3, []complex128{ + 25, 15, -5, + 15, 18, 0, + -5, 0, 11, + }}) + demo("A:", &matrix{4, []complex128{ + 18, 22, 54, 42, + 22, 70, 86, 62, + 54, 86, 174, 134, + 42, 62, 134, 106, + }}) + // one more example, from the Numpy manual, with a non-real + demo("A:", &matrix{2, []complex128{ + 1, -2i, + 2i, 5, + }}) } func demo(heading string, a *matrix) { diff --git a/Task/Cholesky-decomposition/Go/cholesky-decomposition-3.go b/Task/Cholesky-decomposition/Go/cholesky-decomposition-3.go index 82c5332909..7f20fd8514 100644 --- a/Task/Cholesky-decomposition/Go/cholesky-decomposition-3.go +++ b/Task/Cholesky-decomposition/Go/cholesky-decomposition-3.go @@ -3,31 +3,25 @@ package main import ( "fmt" - mat "github.com/skelterjohn/go.matrix" + "github.com/gonum/matrix/mat64" ) +func cholesky(order int, elements []float64) fmt.Formatter { + t := mat64.NewTriDense(order, false, nil) + t.Cholesky(mat64.NewSymDense(order, elements), false) + return mat64.Formatted(t) +} + func main() { - demo(mat.MakeDenseMatrix([]float64{ + fmt.Println(cholesky(3, []float64{ 25, 15, -5, 15, 18, 0, -5, 0, 11, - }, 3, 3)) - demo(mat.MakeDenseMatrix([]float64{ + })) + fmt.Printf("\n%.5f\n", cholesky(4, []float64{ 18, 22, 54, 42, 22, 70, 86, 62, 54, 86, 174, 134, 42, 62, 134, 106, - }, 4, 4)) -} - -func demo(m *mat.DenseMatrix) { - fmt.Println("A:") - fmt.Println(m) - l, err := m.Cholesky() - if err != nil { - fmt.Println(err) - return - } - fmt.Println("L:") - fmt.Println(l) + })) } diff --git a/Task/Cholesky-decomposition/Go/cholesky-decomposition-4.go b/Task/Cholesky-decomposition/Go/cholesky-decomposition-4.go new file mode 100644 index 0000000000..82c5332909 --- /dev/null +++ b/Task/Cholesky-decomposition/Go/cholesky-decomposition-4.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + + mat "github.com/skelterjohn/go.matrix" +) + +func main() { + demo(mat.MakeDenseMatrix([]float64{ + 25, 15, -5, + 15, 18, 0, + -5, 0, 11, + }, 3, 3)) + demo(mat.MakeDenseMatrix([]float64{ + 18, 22, 54, 42, + 22, 70, 86, 62, + 54, 86, 174, 134, + 42, 62, 134, 106, + }, 4, 4)) +} + +func demo(m *mat.DenseMatrix) { + fmt.Println("A:") + fmt.Println(m) + l, err := m.Cholesky() + if err != nil { + fmt.Println(err) + return + } + fmt.Println("L:") + fmt.Println(l) +} diff --git a/Task/Cholesky-decomposition/Haskell/cholesky-decomposition-2.hs b/Task/Cholesky-decomposition/Haskell/cholesky-decomposition-2.hs index fdf02c7050..9dd8dee396 100644 --- a/Task/Cholesky-decomposition/Haskell/cholesky-decomposition-2.hs +++ b/Task/Cholesky-decomposition/Haskell/cholesky-decomposition-2.hs @@ -1,6 +1,23 @@ import Data.Array.IArray +import Data.List import Cholesky +takeDrop 0 xs = ([],xs) +takeDrop _ [] = ([],[]) +takeDrop n (x:xs) = (x:a,b) where (a,b) = takeDrop (n-1) xs + +fm _ [] = "" +fm _ [x] = fst x +fm width ((a,b):xs) = a ++ (take (width - b) $ cycle " ") ++ (fm width xs) + +fmt width row (xs,[]) = fm width xs +fmt width row (xs,ys) = fm width xs ++ "\n" ++ fmt width row (takeDrop row ys) + +showMatrice row xs = ys where + vs = map (\s -> let sh = show s in (sh,length sh)) xs + width = (maximum $ snd $ unzip vs) + 2 + ys = fmt width row (takeDrop row vs) + ex1, ex2 :: Arr ex1 = listArray ((0,0),(2,2)) [25, 15, -5, 15, 18, 0, @@ -13,5 +30,5 @@ ex2 = listArray ((0,0),(3,3)) [18, 22, 54, 42, main :: IO () main = do - print $ elems $ cholesky ex1 - print $ elems $ cholesky ex2 + putStrLn $ showMatrice 3 $ elems $ cholesky ex1 + putStrLn $ showMatrice 4 $ elems $ cholesky ex2 diff --git a/Task/Cholesky-decomposition/Julia/cholesky-decomposition.julia b/Task/Cholesky-decomposition/Julia/cholesky-decomposition.julia new file mode 100644 index 0000000000..3e60100e38 --- /dev/null +++ b/Task/Cholesky-decomposition/Julia/cholesky-decomposition.julia @@ -0,0 +1,5 @@ +a = [25 15 5; 15 18 0; -5 0 11] +b = [18 22 54 22; 22 70 86 62; 54 86 174 134; 42 62 134 106] + +println(a, "\n => \n", chol(a, :L)) +println(b, "\n => \n", chol(b, :L)) diff --git a/Task/Cholesky-decomposition/Perl-6/cholesky-decomposition.pl6 b/Task/Cholesky-decomposition/Perl-6/cholesky-decomposition.pl6 index 62b1811cf6..65724fc68c 100644 --- a/Task/Cholesky-decomposition/Perl-6/cholesky-decomposition.pl6 +++ b/Task/Cholesky-decomposition/Perl-6/cholesky-decomposition.pl6 @@ -3,7 +3,7 @@ sub cholesky(@A) { for ^@A -> $i { for 0..$i -> $j { @L[$i][$j] = ($i == $j ?? &sqrt !! 1/@L[$j][$j] * * )( - @A[$i][$j] - [+] (@L[$i] Z* @L[$j])[0..$j] + @A[$i][$j] - [+] (@L[$i;*] Z* @L[$j;*])[^$j] ); } } diff --git a/Task/Cholesky-decomposition/Python/cholesky-decomposition-1.py b/Task/Cholesky-decomposition/Python/cholesky-decomposition-1.py new file mode 100644 index 0000000000..976aca712d --- /dev/null +++ b/Task/Cholesky-decomposition/Python/cholesky-decomposition-1.py @@ -0,0 +1,27 @@ +from __future__ import print_function + +from pprint import pprint +from math import sqrt + + +def cholesky(A): + L = [[0.0] * len(A) for _ in xrange(len(A))] + for i in xrange(len(A)): + for j in xrange(i+1): + s = sum(L[i][k] * L[j][k] for k in xrange(j)) + L[i][j] = sqrt(A[i][i] - s) if (i == j) else \ + (1.0 / L[j][j] * (A[i][j] - s)) + return L + +if __name__ == "__main__": + m1 = [[25, 15, -5], + [15, 18, 0], + [-5, 0, 11]] + pprint(cholesky(m1)) + print() + + m2 = [[18, 22, 54, 42], + [22, 70, 86, 62], + [54, 86, 174, 134], + [42, 62, 134, 106]] + pprint(cholesky(m2), width=120) diff --git a/Task/Cholesky-decomposition/Python/cholesky-decomposition-2.py b/Task/Cholesky-decomposition/Python/cholesky-decomposition-2.py new file mode 100644 index 0000000000..bbdd30ae15 --- /dev/null +++ b/Task/Cholesky-decomposition/Python/cholesky-decomposition-2.py @@ -0,0 +1,8 @@ +def cholesky(A): + L = [[0.0] * len(A) for _ in range(len(A))] + for i, (Ai, Li) in enumerate(zip(A, L)): + for j, Lj in enumerate(L[:i+1]): + s = sum(Li[k] * Lj[k] for k in range(j)) + Li[j] = sqrt(Ai[i] - s) if (i == j) else \ + (1.0 / Lj[j] * (Ai[j] - s)) + return L diff --git a/Task/Cholesky-decomposition/Python/cholesky-decomposition.py b/Task/Cholesky-decomposition/Python/cholesky-decomposition.py deleted file mode 100644 index 7e30cf3617..0000000000 --- a/Task/Cholesky-decomposition/Python/cholesky-decomposition.py +++ /dev/null @@ -1,22 +0,0 @@ -import math, pprint - -def cholesky(A): - L = [[0.0] * len(A) for _ in xrange(len(A))] - for i in xrange(len(A)): - for j in xrange(i+1): - s = sum(L[i][k] * L[j][k] for k in xrange(j)) - L[i][j] = math.sqrt(A[i][i] - s) if (i == j) else \ - (1.0 / L[j][j] * (A[i][j] - s)) - return L - -m1 = [[25, 15, -5], - [15, 18, 0], - [-5, 0, 11]] -pprint.pprint(cholesky(m1)) -print - -m2 = [[18, 22, 54, 42], - [22, 70, 86, 62], - [54, 86, 174, 134], - [42, 62, 134, 106]] -pprint.pprint(cholesky(m2)) diff --git a/Task/Cholesky-decomposition/REXX/cholesky-decomposition.rexx b/Task/Cholesky-decomposition/REXX/cholesky-decomposition.rexx index 74e4238b7c..811309f286 100644 --- a/Task/Cholesky-decomposition/REXX/cholesky-decomposition.rexx +++ b/Task/Cholesky-decomposition/REXX/cholesky-decomposition.rexx @@ -1,66 +1,51 @@ -/*REXX program to perform the Cholesky decomposition on square matrix.*/ - -niner= '25 15 -5' , - '15 18 0' , - '-5 0 11' - call Cholesky niner -hexer= 18 22 54 42, - 22 70 86 62, - 54 86 174 134, - 42 62 134 106 - call Cholesky hexer -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────Cholesky subroutine──────────────*/ -Cholesky: procedure; arg !; call tell 'input array',! - - do row=1 for order - do col=1 for row; s=0 - do i=1 for col-1 - s=s+$.row.i*$.col.i - end /*i*/ - if row=col then $.row.row=sqrt($.row.row-s) - else $.row.col=1/$.col.col*(@.row.col-s) - end /*col*/ - end /*row*/ - -call tell 'Cholesky factor',,$.,'─' -return -/*─────────────────────────────────────TELL subroutine───&find the order*/ -tell: parse arg hdr,x,y,sep; #=0; if sep=='' then sep='═' -decPlaces = 5 /*number of decimal places past the decimal point. */ -width = 10 /*width of field to be used to display the elements*/ - -if y=='' then $.=0 - else do row=1 for order - do col=1 for order - x=x $.row.col - end /*row*/ - end /*col*/ -w=words(x) - - do order=1 until order**2>=w /*fast way to find the MAT order.*/ - end /*order*/ - -if order**2\==w then call err "matrix elements don't match its order" -say; say center(hdr, ((width+1)*w)%order, sep); say - - do row=1 for order; aLine= - do col=1 for order; #=#+1 - @.row.col=word(x,#) - if col<=row then $.row.col=@.row.col - aLine=aLine right( format(@.row.col,, decPlaces) /1, width) - end /*col*/ - say aLine - end /*row*/ -return -/*─────────────────────────────────────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: if x<0 then call err 'SQRT of negative #'; 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 -/*─────────────────────────────────────ERR subroutine───────────────────*/ -err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13 +/*REXX program performs the Cholesky decomposition on a square matrix. */ +niner = '25 15 -5' , /*define a 3x3 matrix. */ + '15 18 0' , + '-5 0 11' + call Cholesky niner +hexer = 18 22 54 42, /*define a 4x4 matrix. */ + 22 70 86 62, + 54 86 174 134, + 42 62 134 106 + call Cholesky hexer +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +Cholesky: procedure; parse arg mat; say; say; call tell 'input array',mat + do r=1 for ord + do c=1 for r; $=0; do i=1 for c-1; $=$+!.r.i*!.c.i; end /*i*/ + if r=c then !.r.r=sqrt(!.r.r-$) + else !.r.c=1/!.c.c*(@.r.c-$) + end /*c*/ + end /*r*/ + call tell 'Cholesky factor',,!.,'─' + return +/*────────────────────────────────────────────────────────────────────────────*/ +err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13 +/*────────────────────────────────────────────────────────────────────────────*/ +tell: parse arg hdr,x,y,sep; #=0; if sep=='' then sep='═' + dPlaces= 5 /*# decimal places past the decimal point*/ + width =10 /*width of field used to display elements*/ + if y=='' then !.=0 + else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end + w=words(x) + do ord=1 until ord**2>=w; end /*a fast way to find matrix's order*/ + say + if ord**2\==w then call err "matrix elements don't form a square matrix." + say center(hdr, ((width+1)*w)%ord, sep) + say + do row=1 for ord; z= + do col=1 for ord; #=#+1 + @.row.col=word(x,#) + if col<=row then !.row.col=@.row.col + z=z right( format(@.row.col,, dPlaces) / 1, width) + end /*col*/ + say z + end /*row*/ + return +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Circles-of-given-radius-through-two-points/C++/circles-of-given-radius-through-two-points.cpp b/Task/Circles-of-given-radius-through-two-points/C++/circles-of-given-radius-through-two-points.cpp new file mode 100644 index 0000000000..5be0873838 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/C++/circles-of-given-radius-through-two-points.cpp @@ -0,0 +1,64 @@ +#include +#include +#include + +struct point { double x, y; }; + +bool operator==(const point& lhs, const point& rhs) +{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); } + +enum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE }; + +using result_t = std::tuple; + +double distance(point l, point r) +{ return std::hypot(l.x - r.x, l.y - r.y); } + +result_t find_circles(point p1, point p2, double r) +{ + point ans1 { 1/0., 1/0.}, ans2 { 1/0., 1/0.}; + if (p1 == p2) { + if(r == 0.) return std::make_tuple(ONE_COINCEDENT, p1, p2 ); + else return std::make_tuple(INFINITE, ans1, ans2); + } + point center { p1.x/2 + p2.x/2, p1.y/2 + p2.y/2}; + double half_distance = distance(center, p1); + if(half_distance > r) return std::make_tuple(NONE, ans1, ans2); + if(half_distance - r == 0) return std::make_tuple(ONE_DIAMETER, center, ans2); + double root = std::hypot(r, half_distance) / distance(p1, p2); + ans1.x = center.x + root * (p1.y - p2.y); + ans1.y = center.y + root * (p2.x - p1.x); + ans2.x = center.x - root * (p1.y - p2.y); + ans2.y = center.y - root * (p2.x - p1.x); + return std::make_tuple(TWO, ans1, ans2); +} + +void print(result_t result, std::ostream& out = std::cout) +{ + point r1, r2; result_category res; + std::tie(res, r1, r2) = result; + switch(res) { + case NONE: + out << "There are no solutions, points are too far away\n"; break; + case ONE_COINCEDENT: case ONE_DIAMETER: + out << "Only one solution: " << r1.x << ' ' << r1.y << '\n'; break; + case INFINITE: + out << "Infinitely many circles can be drawn\n"; break; + case TWO: + out << "Two solutions: " << r1.x << ' ' << r1.y << " and " << r2.x << ' ' << r2.y << '\n'; break; + } +} + +int main() +{ + constexpr int size = 5; + const point points[size*2] = { + {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} + }; + const double radius[size] = {2., 1., 2., .5, 0.}; + + for(int i = 0; i < size; ++i) + print(find_circles(points[i*2], points[i*2 + 1], radius[i])); +} 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 index 2e04751a86..0d43a582cd 100644 --- 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 @@ -20,8 +20,8 @@ pure in { 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) + if (feqrel(p1.x, p2.x) >= nBits && + feqrel(p1.y, p2.y) >= nBits) throw new ValueException("coincident points give" ~ " infinite number of Circles"); diff --git a/Task/Circles-of-given-radius-through-two-points/Elixir/circles-of-given-radius-through-two-points.elixir b/Task/Circles-of-given-radius-through-two-points/Elixir/circles-of-given-radius-through-two-points.elixir new file mode 100644 index 0000000000..4a9df0b981 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Elixir/circles-of-given-radius-through-two-points.elixir @@ -0,0 +1,38 @@ +defmodule RC do + def circle(p, p, r) when r>0.0 do + raise ArgumentError, message: "Infinite number of circles, points coincide." + end + def circle(p, p, r) when r==0.0 do + {px, py} = p + [{px, py, r}] + end + def circle({p1x,p1y}, {p2x,p2y}, r) do + {dx, dy} = {p2x-p1x, p2y-p1y} + q = :math.sqrt(dx*dx + dy*dy) + if q > 2*r do + raise ArgumentError, message: "Distance of points > diameter." + else + {x3, y3} = {(p1x+p2x) / 2, (p1y+p2y) / 2} + d = :math.sqrt(r*r - q*q/4) + Enum.uniq([{x3 - d*dy/q, y3 + d+dx/q, r}, {x3 + d*dy/q, y3 - d*dx/q, r}]) + end + end +end + +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}] + +Enum.each(data, fn {p1, p2, r} -> + IO.write "Given points:\n #{inspect p1},\n #{inspect p2}\n and radius #{r}\n" + try do + circles = RC.circle(p1, p2, r) + IO.puts "You can construct the following circles:" + Enum.each(circles, fn circle -> IO.puts " #{inspect circle}" end) + rescue + e in ArgumentError -> IO.inspect e + end + IO.puts "" +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 index cfa5d7f48b..7fa4f95c30 100644 --- 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 @@ -1,5 +1,3 @@ -[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 @@ -21,6 +19,14 @@ circles =: verb define"1 end. ) +INPUT=: ".;._2]0 :0 + 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.9876 0 +) + ('x0 y0 x1 y1 r' ; 'center'),(;circles)"1 INPUT ┌───────────────────────────────┬────────────────────────────────────────────────────┐ │x0 y0 x1 y1 r │center │ diff --git a/Task/Circles-of-given-radius-through-two-points/Julia/circles-of-given-radius-through-two-points-1.julia b/Task/Circles-of-given-radius-through-two-points/Julia/circles-of-given-radius-through-two-points-1.julia new file mode 100644 index 0000000000..050bcdea11 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Julia/circles-of-given-radius-through-two-points-1.julia @@ -0,0 +1,41 @@ +immutable Point{T<:FloatingPoint} + x::T + y::T +end + +immutable Circle{T<:FloatingPoint} + c::Point{T} + r::T +end +Circle{T<:FloatingPoint}(a::Point{T}) = Circle(a, zero(T)) + +using AffineTransforms + +function circlepoints{T<:FloatingPoint}(a::Point{T}, b::Point{T}, r::T) + cp = Circle{T}[] + r >= 0 || return (cp, "No Solution, Negative Radius") + if a == b + if abs(r) < 2eps(zero(T)) + return (push!(cp, Circle(a)), "Point Solution, Zero Radius") + else + return (cp, "Infinite Solutions, Indefinite Center") + end + end + ca = Complex(a.x, a.y) + cb = Complex(b.x, b.y) + d = (ca + cb)/2 + tfd = tformtranslate([real(d), imag(d)]) + tfr = tformrotate(angle(cb-ca)) + tfm = tfd*tfr + u = abs(cb-ca)/2 + r-u > -5eps(r) || return(cp, "No Solution, Radius Too Small") + if r-u < 5eps(r) + push!(cp, Circle(apply(Point, tfm*[0.0, 0.0]), r)) + return return (cp, "Single Solution, Degenerate Centers") + end + v = sqrt(r^2 - u^2) + for w in [v, -v] + push!(cp, Circle(apply(Point, tfm*[0.0, w]), r)) + end + return (cp, "Two Solutions") +end diff --git a/Task/Circles-of-given-radius-through-two-points/Julia/circles-of-given-radius-through-two-points-2.julia b/Task/Circles-of-given-radius-through-two-points/Julia/circles-of-given-radius-through-two-points-2.julia new file mode 100644 index 0000000000..882427a870 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Julia/circles-of-given-radius-through-two-points-2.julia @@ -0,0 +1,27 @@ +tp = [Point(0.1234, 0.9876), + Point(0.0000, 2.0000), + Point(0.1234, 0.9876), + Point(0.1234, 0.9876), + Point(0.1234, 0.9876)] + +tq = [Point(0.8765, 0.2345), + Point(0.0000, 0.0000), + Point(0.1234, 0.9876), + Point(0.8765, 0.2345), + Point(0.1234, 0.9876)] + +tr = [2.0, 1.0, 2.0, 0.5, 0.0] + +println("Testing circlepoints:") +for i in 1:length(tp) + p = tp[i] + q = tq[i] + r = tr[i] + (cp, rstatus) = circlepoints(p, q, r) + println(@sprintf("(%.4f, %.4f), (%.4f, %.4f), %.4f => %s", + p.x, p.y, q.x, q.y, r, rstatus)) + for c in cp + println(@sprintf(" (%.4f, %.4f), %.4f", + c.c.x, c.c.y, c.r)) + end +end diff --git a/Task/Circles-of-given-radius-through-two-points/Liberty-BASIC/circles-of-given-radius-through-two-points-1.liberty b/Task/Circles-of-given-radius-through-two-points/Liberty-BASIC/circles-of-given-radius-through-two-points-1.liberty new file mode 100644 index 0000000000..ef80b947ca --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Liberty-BASIC/circles-of-given-radius-through-two-points-1.liberty @@ -0,0 +1,45 @@ +'[RC] Circles of given radius through two points +for i = 1 to 5 + read x1, y1, x2, y2,r + print i;") ";x1, y1, x2, y2,r + call twoCircles x1, y1, x2, y2,r +next +end + +'p1 p2 r +data 0.1234, 0.9876, 0.8765, 0.2345, 2.0 +data 0.0000, 2.0000, 0.0000, 0.0000, 1.0 +data 0.1234, 0.9876, 0.1234, 0.9876, 2.0 +data 0.1234, 0.9876, 0.8765, 0.2345, 0.5 +data 0.1234, 0.9876, 0.1234, 0.9876, 0.0 + +sub twoCircles x1, y1, x2, y2,r + + if x1=x2 and y1=y2 then '2.If the points are coincident + if r=0 then ' unless r==0.0 + print "It will be a single point (";x1;",";y1;") of radius 0" + exit sub + else + print "There are any number of circles via single point (";x1;",";y1;") of radius ";r + exit sub + end if + end if + r2 = sqr((x1-x2)^2+(y1-y2)^2)/2 'half distance between points + if r 2 r := + Message[circs::dist, p1x, p1y, p2x, p2y, r]; +circs[p1 : {p1x_, p1y_}, p2 : {p2x_, p2y_}, r_] := + Values /@ + Solve[Abs[x - p1x]^2 + Abs[y - p1y]^2 == + Abs[x - p2x]^2 + Abs[y - p2y]^2 == r^2, {x, y}]; diff --git a/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx b/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx index 0f508944c8..52012c9554 100644 --- a/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx +++ b/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx @@ -1,31 +1,33 @@ -/*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 +/*REXX program finds two 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*/ +say ' ════════ ════════ ════════ ════════ ══════ ════════ ════════ ════════ ════════' + do j=1 while @.j\=='' /*process the points and radii. */ + do k=1 for 4; w.k=f(word(@.j,k)) /*format # with 4 decimal digits.*/ end /*k*/ - say w.1 w.2 w.3 w.4 center(word(@.j,5)/1,9) "───► " twoCircles(@.j) + say w.1 w.2 w.3 w.4 center(word(@.j,5)/1,9) "───► " 2circ(@.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) +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +2circ: procedure; parse arg px py qx qy r .; x=(qx-px)/2; y=(qy-py)/2 + bx=px+x; by=py+y; pb=sqrt(x**2+y**2) + if r=0 then return 'radius of zero yields no circles.' + if pb=0 then return 'coincident points give infinite circles.' + if pb>r then return 'points are too far apart for the specified radius.' + cb=sqrt(r**2-pb**2); x1=y*cb/pb; y1=x*cb/pb + return f(bx-x1) f(by+y1) f(bx+x1) f(by-y1) +/*────────────────────────────────────────────────────────────────────────────*/ +f: f=right(format(arg(1),,4),9); _=f /*format # with four decimal digits.*/ + if pos(.,f)\==0 then f=strip(f,'T',0) /*strip trailing 0s if decimal point*/ + return left(strip(f,'T',.),length(_)) /*maybe strip trailing decimal point*/ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Circles-of-given-radius-through-two-points/Run-BASIC/circles-of-given-radius-through-two-points.run b/Task/Circles-of-given-radius-through-two-points/Run-BASIC/circles-of-given-radius-through-two-points.run new file mode 100644 index 0000000000..b4749e334e --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Run-BASIC/circles-of-given-radius-through-two-points.run @@ -0,0 +1,46 @@ +html "" +html "" +for i = 1 to 5 + read x1, y1, x2, y2,r +html "" + gosub [twoCircles] +next +html "
No.x1y1x2y2rcir x1cir y1cir x2cir y2
";i;"";x1;"";y1;"";x2;"";y2;"";r;"
" +end + +'p1 p2 r +data 0.1234, 0.9876, 0.8765, 0.2345, 2.0 +data 0.0000, 2.0000, 0.0000, 0.0000, 1.0 +data 0.1234, 0.9876, 0.1234, 0.9876, 2.0 +data 0.1234, 0.9876, 0.8765, 0.2345, 0.5 +data 0.1234, 0.9876, 0.1234, 0.9876, 0.0 + +[twoCircles] + + if x1=x2 and y1=y2 then '2.If the points are coincident + if r=0 then ' unless r==0.0 + html "
It will be a single point (";x1;",";y1;") of radius 0
There are any number of circles via single point (";x1;",";y1;") of radius ";r;"
";cx+dy;"";cy+dx;"";cx-dy;"";cy-dx;"
', + + ' ', + ' ' + lstData[0].reduce( + function (a, s) { + return a + ''; + }, '' + ) + '', + ' ', + + ' ', + lstData.slice(1).map( + function (row) { + return ' ' + row.reduce( + function (a, s) { + return a + ''; + }, '' + ) + ''; + } + ).join('\n'), + ' ', + + '
' + s + '
' + s + '
' + ].join('\n'); + +})(3, 4); // (3 columns --> [X..Z]), (4 rows --> [1..4]) diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh index 038d7dc99d..d440a0c603 100644 --- a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh +++ b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh @@ -2,6 +2,9 @@ ConvertTo-Html -inputobject (Get-Date) # Create a PowerShell object using a HashTable -$object = New-Object -TypeName PSObject -Property (@{'A'=(Get-Random -Minimum 0 -Maximum 10);'B'=(Get-Random -Minimum 0 -Maximum 10);'C'=(Get-Random -Minimum 0 -Maximum 10)}) +$object = [PSCustomObject]@{ + 'A'=(Get-Random -Minimum 0 -Maximum 10); + 'B'=(Get-Random -Minimum 0 -Maximum 10); + 'C'=(Get-Random -Minimum 0 -Maximum 10)} $object | ConvertTo-Html diff --git a/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx b/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx index dea32ed52d..a24d204293 100644 --- a/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx +++ b/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx @@ -1,23 +1,23 @@ -/*REXX program to create an HTML table of five rows and three columns.*/ -arg rows .; if rows=='' then rows=5 /*no ROWS specified? Use default*/ - cols = 3 /*specify three columns for table*/ - maxRand = 9999 /*4-digit numbers, allow negative*/ -headerInfo = 'X Y Z' /*column header information. */ - oFID = 'a_table.html' /*name of the output file. */ - w = 0 /*number of writes to output file*/ +/*REXX program creates an HTML table of five rows and three columns. */ +arg rows .; if rows=='' then rows=5 /*no ROWS specified? Then use default.*/ + cols = 3 /*specify three columns for the table. */ + maxRand = 9999 /*4-digit numbers, allows negative nums*/ +headerInfo = 'X Y Z' /*specifify column header information. */ + oFID = 'a_table.html' /*name of the output file. */ + w = 0 /*number of writes to the output file. */ call wrt "" call wrt "" call wrt "" call wrt "" - do r=0 to rows /* [↓] handle row zero special. */ + do r=0 to rows /* [↓] handle row 0 as being special.*/ if r==0 then call wrt "" - else call wrt "" + else call wrt "" - do c=1 for cols /* [↓] for row zero, add hdrInfo*/ - if r==0 then call wrt "" - else call wrt "" + do c=1 for cols /* [↓] for row 0, add the header info*/ + if r==0 then call wrt "" + else call wrt "" end /*c*/ end /*r*/ @@ -25,8 +25,7 @@ call wrt "
" r "
" r "" word(headerInfo,c) "" rnd() "" word(headerInfo,c) "" rnd() "
" call wrt "" call wrt "" say; say w ' records were written to the output file: ' oFID -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one-liner subroutines───────────────*/ -rnd: return right(random(0,maxRand*2)-maxRand,5) /*REXX doesn't gen negs*/ -wrt: call lineout oFID,arg(1); say '══►' arg(1); w=w+1; return /*write.*/ - /* [↑] functions were subroutinized for better viewabilityness.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +rnd: return right(random(0,maxRand*2)-maxRand,5) /*REXX doesn't gen neg RANDs.*/ +wrt: call lineout oFID,arg(1); say '══►' arg(1); w=w+1; return /*write.*/ diff --git a/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb new file mode 100644 index 0000000000..35deed3f02 --- /dev/null +++ b/Task/Create-an-HTML-table/VBScript/create-an-html-table.vb @@ -0,0 +1,40 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") + +'Open the input csv file for reading. The file is in the same folder as the script. +Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\in.csv",1) + +'Create the output html file. +Set objOutHTML = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\out.html",2,True) + +'Write the html opening tags. +objOutHTML.Write "" & vbCrLf + +'Declare table properties. +objOutHTML.Write "" & vbCrLf + +'Write column headers. +objOutHTML.Write "" & vbCrLf + +'Go through each line of the input csv file and write to the html output file. +n = 1 +Do Until objInFile.AtEndOfStream + line = objInFile.ReadLine + If Len(line) > 0 Then + token = Split(line,",") + objOutHTML.Write "" + For i = 0 To UBound(token) + objOutHTML.Write "" + Next + objOutHTML.Write "" & vbCrLf + End If + n = n + 1 +Loop + +'Write the html closing tags. +objOutHTML.Write "
XYZ
" & n & "" & token(i) & "
" + +objInFile.Close +objOutHTML.Close +Set objFSO = Nothing diff --git a/Task/Create-an-object-at-a-given-address/C/create-an-object-at-a-given-address-2.c b/Task/Create-an-object-at-a-given-address/C/create-an-object-at-a-given-address-2.c index 5c5531feca..80e05041ab 100644 --- a/Task/Create-an-object-at-a-given-address/C/create-an-object-at-a-given-address-2.c +++ b/Task/Create-an-object-at-a-given-address/C/create-an-object-at-a-given-address-2.c @@ -1,15 +1,17 @@ +#include +#include + // This is a port variable located at address 0x100 #define PORT_A (*(volatile uint32_t*)0x100) -void main() +int main() { uint32_t dat; + size_t addr; PORT_A ^= 0x01; // Toggle bit 0 of PORT_A dat = PORT_A; // Read PORT_A addr = &PORT_A; // addr = 0x100 - while (1) - { - } + return 0; } diff --git a/Task/Currying/Clojure/currying.clj b/Task/Currying/Clojure/currying.clj new file mode 100644 index 0000000000..c163ca9463 --- /dev/null +++ b/Task/Currying/Clojure/currying.clj @@ -0,0 +1,4 @@ +(def plus-a-hundred (partial + 100)) +(assert (= + (plus-a-hundred 1) + 101)) diff --git a/Task/Currying/JavaScript/currying.js b/Task/Currying/JavaScript/currying-1.js similarity index 100% rename from Task/Currying/JavaScript/currying.js rename to Task/Currying/JavaScript/currying-1.js diff --git a/Task/Currying/JavaScript/currying-2.js b/Task/Currying/JavaScript/currying-2.js new file mode 100644 index 0000000000..ad04ebfba7 --- /dev/null +++ b/Task/Currying/JavaScript/currying-2.js @@ -0,0 +1 @@ +(a,b) => expr_using_a_and_b diff --git a/Task/Currying/JavaScript/currying-3.js b/Task/Currying/JavaScript/currying-3.js new file mode 100644 index 0000000000..9fc60dfb57 --- /dev/null +++ b/Task/Currying/JavaScript/currying-3.js @@ -0,0 +1 @@ +a => b => expr_using_a_and_b diff --git a/Task/Currying/JavaScript/currying-4.js b/Task/Currying/JavaScript/currying-4.js new file mode 100644 index 0000000000..c1058a8a69 --- /dev/null +++ b/Task/Currying/JavaScript/currying-4.js @@ -0,0 +1,23 @@ +let + fix = // This is a variant of the Applicative order Y combinator + f => (f => f(f))(g => f((...a) => g(g)(...a))), + curry = + f => ( + fix( + z => (n,...a) => ( + n>0 + ?b => z(n-1,...a,b) + :f(...a))) + (f.length)), + curryrest = + f => ( + fix( + z => (n,...a) => ( + n>0 + ?b => z(n-1,...a,b) + :(...b) => f(...a,...b))) + (f.length)), + curriedmax=curry(Math.max), + curryrestedmax=curryrest(Math.max); +print(curriedmax(8)(4),curryrestedmax(8)(4)(),curryrestedmax(8)(4)(9,7,2)); +// 8,8,9 diff --git a/Task/Currying/Logtalk/currying.logtalk b/Task/Currying/Logtalk/currying.logtalk new file mode 100644 index 0000000000..37ec3b753e --- /dev/null +++ b/Task/Currying/Logtalk/currying.logtalk @@ -0,0 +1,3 @@ +| ?- logtalk << call([Z]>>(call([X,Y]>>(Y is X*X), 5, R), Z is R*R), T). +T = 625 +yes diff --git a/Task/Currying/Scala/currying.scala b/Task/Currying/Scala/currying.scala new file mode 100644 index 0000000000..2ca6dbe51a --- /dev/null +++ b/Task/Currying/Scala/currying.scala @@ -0,0 +1,3 @@ +def add(a: Int)(b: Int) = a + b +val add5 = add(5) _ +add5(2) diff --git a/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-1.e b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-1.e new file mode 100644 index 0000000000..1802a1b9b5 --- /dev/null +++ b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-1.e @@ -0,0 +1,36 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + -- Finds solution for cut a rectangle up to 10 x 10. + local + i, j, n: Integer + r: GRID + do + n := 10 + from + i := 1 + until + i > n + loop + from + j := 1 + until + j > i + loop + if i.bit_and (1) /= 1 or j.bit_and (1) /= 1 then + create r.make (i, j) + r.print_solution + end + j := j + 1 + end + i := i + 1 + end + end + +end diff --git a/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-2.e b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-2.e new file mode 100644 index 0000000000..035fe0d7f0 --- /dev/null +++ b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-2.e @@ -0,0 +1,163 @@ +class + GRID + +create + make + +feature {NONE} + + n: INTEGER + + m: INTEGER + +feature + + print_solution + -- Prints solution to cut a rectangle. + do + calculate_possibilities + io.put_string ("Rectangle " + n.out + " x " + m.out + ": " + count.out + " possibilities%N") + end + + count: INTEGER + -- Number of solutions + + make (a_n: INTEGER; a_m: INTEGER) + -- Initialize Problem with 'a_n' and 'a_m'. + require + a_n > 0 + a_m > 0 + do + n := a_n + m := a_m + count := 0 + end + + calculate_possibilities + -- Select all possible starting points. + local + i: INTEGER + do + if (n = 1 or m = 1) then + count := 1 + end + + from + i := 0 + until + i > n or (n = 1 or m = 1) + loop + solve (create {POINT}.make_with_values (i, 0), create {POINT}.make_with_values (n - i, m), create {LINKED_LIST [POINT]}.make, create {LINKED_LIST [POINT]}.make) + i := i + 1 + variant + n - i + 1 + end + from + i := 0 + until + i > m or (n = 1 or m = 1) + loop + solve (create {POINT}.make_with_values (n, i), create {POINT}.make_with_values (0, m - i), create {LINKED_LIST [POINT]}.make, create {LINKED_LIST [POINT]}.make) + i := i + 1 + variant + m - i + 1 + end + end + +feature {NONE} + + solve (p, q: POINT; visited_p, visited_q: LINKED_LIST [POINT]) + -- Recursive solution of cut a rectangle. + local + possible_next: LINKED_LIST [POINT] + next: LINKED_LIST [POINT] + opposite: POINT + do + if p.negative or q.negative then + + elseif p.same (q) then + add_solution + else + possible_next := get_possible_next (p) + create next.make + across + possible_next as x + loop + if x.item.x >= n or x.item.y >= m then + -- Next point cannot be on the border. Do nothing. + + elseif x.item.same (q) then + add_solution + elseif not contains (x.item, visited_p) and not contains (x.item, visited_q) then + next.extend (x.item) + end + end + + across + next as x + loop + -- Move in one direction + -- Calculate the opposite end of the cut by moving into the opposite direction (compared to p -> x) + create opposite.make_with_values (q.x - (x.item.x - p.x), q.y - (x.item.y - p.y)) + + visited_p.extend (p) + visited_q.extend (q) + + solve (x.item, opposite, visited_p, visited_q) + + -- Remove last point again + visited_p.finish + visited_p.remove + + visited_q.finish + visited_q.remove + end + end + end + + get_possible_next (p: POINT): LINKED_LIST [POINT] + -- Four possible next points. + local + q: POINT + do + create Result.make + + --up + create q.make_with_values (p.x + 1, p.y) + if q.valid and q.x <= n and q.y <= m then + Result.extend (q); + end + + --down + create q.make_with_values (p.x - 1, p.y) + if q.valid and q.x <= n and q.y <= m then + Result.extend (q) + end + + --left + create q.make_with_values (p.x, p.y - 1) + if q.valid and q.x <= n and q.y <= m then + Result.extend (q) + end + + --right + create q.make_with_values (p.x, p.y + 1) + if q.valid and q.x <= n and q.y <= m then + Result.extend (q) + end + end + + add_solution + -- Increment count. + do + count := count + 1 + end + + contains (p: POINT; set: LINKED_LIST [POINT]): BOOLEAN + -- Does set contain 'p'? + do + set.compare_objects + Result := set.has (p) + end + +end diff --git a/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-3.e b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-3.e new file mode 100644 index 0000000000..782c3f5369 --- /dev/null +++ b/Task/Cut-a-rectangle/Eiffel/cut-a-rectangle-3.e @@ -0,0 +1,47 @@ +class + POINT + +create + make, make_with_values + + + +feature + + make_with_values (a_x: INTEGER; a_y: INTEGER) + -- Initialize x and y with 'a_x' and 'a_y'. + do + x := a_x + y := a_y + end + + make + -- Initialize x and y with 0. + do + x := 0 + y := 0 + end + + x: INTEGER + + y: INTEGER + + negative: BOOLEAN + -- Are x or y negative? + do + Result := x < 0 or y < 0 + end + + same (other: POINT): BOOLEAN + -- Does x and y equal 'other's x and y? + do + Result := (x = other.x) and (y = other.y) + end + + valid: BOOLEAN + -- Are x and y valid points? + do + Result := (x > 0) and (y > 0) + end + +end diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx new file mode 100644 index 0000000000..8fe0805a50 --- /dev/null +++ b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-1.rexx @@ -0,0 +1,45 @@ +/*REXX program cuts rectangles into two symmetric pieces, the rectangles are */ +/*────────────────────────────── cut along unit dimensions and may be rotated.*/ +numeric digits 20 /*be able to handle some big integers. */ +parse arg N .; if N=='' then N=10 /*N not specified? Then use default.*/ +dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*four directions*/ + + do y=2 to N; say /*calculate rectangles up to size NxN.*/ + do x=1 for y; if x//2 & y//2 then iterate /*not if both X&Y odd.*/ + _=solve(y,x,1); _=right(_,max(10,length(_))) /*align the output. */ + say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(_)'.' + end /*x*/ + end /*y*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────S subroutine──────────────────────────────*/ +s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/ +/*──────────────────────────────────SOLVE subroutine──────────────────────────*/ +solve: procedure expose # dir. @. h len next. w +parse arg hh 1 h,ww 1 w,recur; @.=0 /*get args; zero rectangle coördinates.*/ +if h//2 then do; t=w; w=h; h=t; if h//2 then return 0 + end +if w==1 then return 1 +if w==2 then return h +if h==2 then return w /* % is REXX's integer division. */ +cy = h%2; cx=w%2 /*cut the [XY] rectangle in half. */ +len = (h+1) * (w+1) - 1 /*extend the area of the rectangle. */ +next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction and distance.*/ +if recur then #=0 + do x=cx+1 to w-1; t=x+cy*(w+1) + @.t=1; _=len-t; @._=1; call walk cy-1,x + end /*x*/ +#=#+1 +if h==w then #=#+# /*double the count of rectangle cuts. */ + else if w//2==0 & recur then call solve w,h,0 +return # +/*──────────────────────────────────WALK subroutine───────────────────────────*/ +walk: procedure expose # dir. @. h len next. w; parse arg y,x +if y==h | x==0 | x==w | y==0 then do; #=#=2; return; end +t=x + y*(w+1); @.t=@.t+1; _=len-t +@._=@._+1 + do j=0 for 4; _ = t+next.j /*try four directions.*/ + if @._==0 then call walk y+dir.j.0, x+dir.j.1 + end /*j*/ +@.t=@.t-1 +_=len-t; @._=@._-1 +return diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx new file mode 100644 index 0000000000..ae1d4f557b --- /dev/null +++ b/Task/Cut-a-rectangle/REXX/cut-a-rectangle-2.rexx @@ -0,0 +1,55 @@ +/*REXX program cuts rectangles into two symmetric pieces, the rectangles are */ +/*────────────────────────────── cut along unit dimensions and may be rotated.*/ +numeric digits 20 /*be able to handle some big integers. */ +parse arg N .; if N=='' then N=10 /*N not specified? Then use default.*/ +dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*four directions*/ + + do y=2 to N; say /*calculate rectangles up to size NxN.*/ + do x=1 for y; if x//2 & y//2 then iterate /*not if both X&Y odd.*/ + _=solve(y,x,1); _=right(_,max(10,length(_))) /*align the output. */ + say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(_)'.' + end /*x*/ + end /*y*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────S subroutine──────────────────────────────*/ +s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/ +/*──────────────────────────────────SOLVE subroutine──────────────────────────*/ +solve: procedure expose # dir. @. h len next. w +parse arg hh 1 h,ww 1 w,recur; @.=0 /*get args; zero rectangle coördinates.*/ +if h//2 then do; parse value w h w with t w h; if h//2 then return 0 + end +if w==1 then return 1 +if w==2 then return h +if h==2 then return w /* % is REXX's integer division. */ +cy = h%2; cx=w%2 /*cut the [XY] rectangle in half. */ +len = (h+1) * (w+1) - 1 /*extend the area of the rectangle. */ +next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction and distance.*/ +if recur then #=0 + do x=cx+1 to w-1; t=x+cy*(w+1) + @.t=1; _=len-t; @._=1; call walk cy-1,x + end /*x*/ +#=#+1 +if h==w then #=#+# /*double the count of rectangle cuts. */ + else if w//2==0 & recur then call solve w,h,0 +return # +/*──────────────────────────────────WALK subroutine───────────────────────────*/ +walk: procedure expose # dir. @. h len next. w; parse arg y,x +if y==h then do; #=#+2; return; end /* ◄──┐ REXX short circuit. */ +if x==0 then do; #=#+2; return; end /* ◄──┤ " " " */ +if x==w then do; #=#+2; return; end /* ◄──┤ " " " */ +if y==0 then do; #=#+2; return; end /* ◄──┤ " " " */ +t=x + y*(w+1); @.t=@.t+1; _=len-t /* │ ordered by most likely ►───┐ */ +@._=@._+1 /* └─────────────────────────────┘ */ + do j=0 for 4; _ = t+next.j /*try four directions.*/ + if @._==0 then do + yn=y+dir.j.0; xn=x+dir.j.1 + if yn==h then do; #=#+2; iterate; end + if xn==0 then do; #=#+2; iterate; end + if xn==w then do; #=#+2; iterate; end + if yn==0 then do; #=#+2; iterate; end + call walk yn, xn + end + end /*j*/ +@.t=@.t-1 +_=len-t; @._=@._-1 +return diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx deleted file mode 100644 index fbc0af8bff..0000000000 --- a/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx +++ /dev/null @@ -1,50 +0,0 @@ -/*REXX program cuts rectangles into two symmetric pieces, the rectangles*/ -/*──────────────────── are cut along unit dimensions and may be rotated.*/ -numeric digits 20 /*be able to handle big integers.*/ -parse arg N .; if N=='' then N=10 /*N not specified? Use default.*/ -dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*directions.*/ - - do y=2 to N; say /*calculate rectangles up to NxN.*/ - do x=1 for y; if x//2 & y//2 then iterate /*not if both odd.*/ - _=solve(y,x,1); _=right(_,max(10,length(_))) /*align the output*/ - say right(y,9) "x" right(x,2) 'rectangle can be cut' _ "way"s(_)'.' - end /*x*/ - end /*y*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────S subroutine────────────────────────*/ -s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*plurals*/ -/*──────────────────────────────────SOLVE subroutine────────────────────*/ -solve: procedure expose # dir. @. h len next. w -parse arg hh 1 h,ww 1 w,recur; @.=0 /*zero the rectangle coördinates.*/ - -if h//2 then do; t=w; w=h; h=t - if h//2 then return 0 - end -if w==1 then return 1 -if w==2 then return h -if h==2 then return w -cy = h%2; cx=w%2 /*cut the [XY] rectangle in half.*/ -len = (h+1) * (w+1) - 1 /*extended area of the rectangle.*/ -next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction distance.*/ -if recur then #=0 - do x=cx+1 to w-1; t=x+cy*(w+1) - @.t=1; _=len-t; @._=1; call walk cy-1,x - end /*x*/ -#=#+1 -if h==w then #=#+# /*double count of rectangle cuts.*/ - else if w//2==0 & recur then call solve w,h,0 -return # -/*──────────────────────────────────WALK subroutine─────────────────────*/ -walk: procedure expose # dir. @. h len next. w; parse arg y,x -if y==h then do; #=#+2; return; end /* ◄──┐ REXX short circuit.*/ -if x==0 then do; #=#+2; return; end /* ◄──┤ " " " */ -if x==w then do; #=#+2; return; end /* ◄──┤ " " " */ -if y==0 then do; #=#+2; return; end /* ◄──┤ " " " */ -t=x + y*(w+1); @.t=@.t+1; _=len-t /* │ ordered by most likely►─┐*/ -@._=@._+1 /* └─────────────────────────┘*/ - do j=0 for 4; _ = t+next.j /*try 4 directions*/ - if @._==0 then call walk y+dir.j.0, x+dir.j.1 - end /*j*/ -@.t=@.t-1 -_=len-t; @._=@._-1 -return diff --git a/Task/DNS-query/Batch-File/dns-query.bat b/Task/DNS-query/Batch-File/dns-query.bat new file mode 100644 index 0000000000..222f30a51b --- /dev/null +++ b/Task/DNS-query/Batch-File/dns-query.bat @@ -0,0 +1,21 @@ +@echo off +setlocal enabledelayedexpansion + +set "Temp_File=%TMP%\NSLOOKUP_%RANDOM%.TMP" +set "Domain=www.kame.net" + +echo.Domain: %Domain% +echo. +echo.IP Addresses: + + ::The Main Processor +nslookup %Domain% >"%Temp_File%" 2>nul +for /f "tokens=*" %%A in ( +'findstr /B /C:"Address" "%Temp_File%" ^& findstr /B /C:" " "%Temp_File%"' +) do ( + set data=%%A + echo.!data:*s: =!|findstr /VBC:"192.168." /VBC:"127.0.0.1" +) +del /Q "%Temp_File%" +echo. +pause diff --git a/Task/DNS-query/Common-Lisp/dns-query-4.lisp b/Task/DNS-query/Common-Lisp/dns-query-4.lisp new file mode 100644 index 0000000000..e78130dc32 --- /dev/null +++ b/Task/DNS-query/Common-Lisp/dns-query-4.lisp @@ -0,0 +1,3 @@ +(socket:ipaddr-to-dotted + (socket:dns-query "www.rosettacode.org")) +"104.28.10.103" diff --git a/Task/DNS-query/J/dns-query-1.j b/Task/DNS-query/J/dns-query-1.j new file mode 100644 index 0000000000..fae50f6e08 --- /dev/null +++ b/Task/DNS-query/J/dns-query-1.j @@ -0,0 +1,7 @@ + 2!:0'dig -4 +short www.kame.net' +orange.kame.net. +203.178.141.194 + + 2!:0'dig -6 +short www.kame.net' +|interface error +| 2!:0'dig -6 +short www.kame.net' diff --git a/Task/DNS-query/J/dns-query-2.j b/Task/DNS-query/J/dns-query-2.j new file mode 100644 index 0000000000..78757db877 --- /dev/null +++ b/Task/DNS-query/J/dns-query-2.j @@ -0,0 +1,21 @@ +import java.net.InetAddress; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.UnknownHostException; + +class DnsQuery { + public static void main(String[] args) { + try { + InetAddress[] ipAddr = InetAddress.getAllByName("www.kame.net"); + for(int i=0; i < ipAddr.length ; i++) { + if (ipAddr[i] instanceof Inet4Address) { + System.out.println("IPv4 : " + ipAddr[i].getHostAddress()); + } else if (ipAddr[i] instanceof Inet6Address) { + System.out.println("IPv6 : " + ipAddr[i].getHostAddress()); + } + } + } catch (UnknownHostException uhe) { + System.err.println("unknown host"); + } + } +} diff --git a/Task/DNS-query/REXX/dns-query-1.rexx b/Task/DNS-query/REXX/dns-query-1.rexx new file mode 100644 index 0000000000..23eac7b49b --- /dev/null +++ b/Task/DNS-query/REXX/dns-query-1.rexx @@ -0,0 +1,17 @@ +/*REXX program displays IPv4 and IPv6 addresses for a supplied domain name.*/ +trace off /*don't show PING none─zero return code*/ +parse arg tar . /*obtain optional domain name from C.L.*/ +if tar=='' then tar='www.kame.net' /*Not specified? Then use the default.*/ +tempFID='\TEMP\DNSQUERY.$$$.' /*define temp file to store the IPv4. */ +pingOpts='-l 0 -n 1 -w 1' tar /*define options for the PING command. */ + + do j=4 to 6 by 2 /*handle IPv4 and IPv6 addresses. */ + 'PING' (-j) pingOpts ">" tempFID /*restrict PING's output to a minimum. */ + q=charin(tempFID,1,999) /*read the output file from PING cmd.*/ + parse var q '[' IPA ']' /*parse IP address from the output. */ + say 'IPv'j 'for domain name ' tar " is " IPA /*IPv4 or IPv6 address.*/ + call lineout tempFID /* ◄──┬─◄ needed by some REXXes to */ + end /*j*/ /* └─◄ force file integrity.*/ + +'ERASE' tempFID /*clean up (delete) the temporary file.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/DNS-query/REXX/dns-query-2.rexx b/Task/DNS-query/REXX/dns-query-2.rexx new file mode 100644 index 0000000000..e7d685aa6c --- /dev/null +++ b/Task/DNS-query/REXX/dns-query-2.rexx @@ -0,0 +1,5 @@ +irb(main):001:0> require 'socket' +=> true +irb(main):002:0> Addrinfo.getaddrinfo("www.kame.net", nil, nil, :DGRAM) \ +irb(main):003:0* .map! { |ai| ai.ip_address } +=> ["203.178.141.194", "2001:200:dff:fff1:216:3eff:feb1:44d7"] diff --git a/Task/DNS-query/REXX/dns-query.rexx b/Task/DNS-query/REXX/dns-query.rexx deleted file mode 100644 index a656d748dc..0000000000 --- a/Task/DNS-query/REXX/dns-query.rexx +++ /dev/null @@ -1,16 +0,0 @@ -/*REXX pgm displays IPv4 and IPv6 addresses for a supplied domain name.*/ -trace off /*don't show the PING return code*/ -parse arg dn . /*get the optional domain name. */ -if dn=='' then dn = 'www.kame.net' /*Not specified? Then use default*/ -tmp = '\TEMP\TEMP.PING' /*define temp file to store IPv4.*/ - - do j=4 to 6 by 2 /*handle IPv4 and IPv6 addresses.*/ - 'PING' (-j) '-l 0 -n 1' dn ">" tmp /*restrict PING's output to min. */ - q=charin(tmp,1,999) /*read output file from PING cmd.*/ - parse var q '[' IPA ']' /*parse IP a ddress from output.*/ - say 'IPv'j 'for domain name ' dn " is " IPA /*IPv4 | IPv6 addr.*/ - call lineout tmp /*needed by most REXXes to ··· */ - end /*j*/ /* [↑] ··· force file integrity.*/ - -'ERASE' tmp /*clean up the temporary file. */ - /*stick a fork in it, we're done.*/ diff --git a/Task/DNS-query/Scala/dns-query.scala b/Task/DNS-query/Scala/dns-query.scala index 60c035648b..6c0c4231a1 100644 --- a/Task/DNS-query/Scala/dns-query.scala +++ b/Task/DNS-query/Scala/dns-query.scala @@ -1,9 +1,8 @@ -import java.net.{InetAddress,Inet4Address,Inet6Address} +import java.net.{Inet4Address, Inet6Address, InetAddress} object DnsQuery extends App { - val ipAddresses = InetAddress.getAllByName("www.kame.net"); - ipAddresses.foreach { ipAddr => - if (ipAddr.isInstanceOf[Inet4Address]) println("IPv4 : " + ipAddr.getHostAddress()) - else if (ipAddr.isInstanceOf[Inet6Address]) println("IPv6 : " + ipAddr.getHostAddress()) + InetAddress.getAllByName("google.com").foreach { + case x: Inet4Address => println(s"IPv4 : ${x.getHostAddress}") + case x: Inet6Address => println(s"IPv6 : ${x.getHostAddress}") } } diff --git a/Task/DNS-query/VBScript/dns-query.vb b/Task/DNS-query/VBScript/dns-query.vb new file mode 100644 index 0000000000..2636f7ad2b --- /dev/null +++ b/Task/DNS-query/VBScript/dns-query.vb @@ -0,0 +1,16 @@ +Function dns_query(url,ver) + Set r = New RegExp + r.Pattern = "Pinging.+?\[(.+?)\].+" + Set objshell = CreateObject("WScript.Shell") + Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url) + WScript.StdOut.WriteLine "URL: " & url + Do Until objexec.StdOut.AtEndOfStream + line = objexec.StdOut.ReadLine + If r.Test(line) Then + WScript.StdOut.WriteLine "IP Version " &_ + ver & ": " & r.Replace(line,"$1") + End If + Loop +End Function + +Call dns_query(WScript.Arguments(0),WScript.Arguments(1)) diff --git a/Task/Date-format/00DESCRIPTION b/Task/Date-format/00DESCRIPTION index f7caf096b9..cb7e517319 100644 --- a/Task/Date-format/00DESCRIPTION +++ b/Task/Date-format/00DESCRIPTION @@ -1 +1,2 @@ -{{Clarified-review}}Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007". + {{Clarified-review}} +Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007". diff --git a/Task/Date-format/CoffeeScript/date-format-1.coffee b/Task/Date-format/CoffeeScript/date-format-1.coffee index b660f6fc13..f934d1a151 100644 --- a/Task/Date-format/CoffeeScript/date-format-1.coffee +++ b/Task/Date-format/CoffeeScript/date-format-1.coffee @@ -1,26 +1,13 @@ -# JS does not have extensive formatting support out of the box. This code shows -# how you could create a date formatter object. -DateFormatter = -> - weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] - months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] - pad = (n) -> - if n < 10 - "0" + n - else - n +date = new Date - brief: (date) -> - month = 1 + date.getMonth() - "#{date.getFullYear()}-#{pad month}-#{pad date.getDate()}" +console.log date.toLocaleDateString 'en-GB', + month: '2-digit' + day: '2-digit' + year: 'numeric' +.split('/').reverse().join '-' - verbose: (date) -> - weekday = weekdays[date.getDay()] - month = months[date.getMonth()] - day = date.getDate() - year = date.getFullYear(); - "#{weekday}, #{month} #{day}, #{year}" - -formatter = DateFormatter() -date = new Date() -console.log formatter.brief(date) -console.log formatter.verbose(date) +console.log date.toLocaleDateString 'en-US', + weekday: 'long' + month: 'long' + day: 'numeric' + year: 'numeric' diff --git a/Task/Date-format/CoffeeScript/date-format-2.coffee b/Task/Date-format/CoffeeScript/date-format-2.coffee index f8514694b2..b660f6fc13 100644 --- a/Task/Date-format/CoffeeScript/date-format-2.coffee +++ b/Task/Date-format/CoffeeScript/date-format-2.coffee @@ -1,3 +1,26 @@ -> coffee date_format.coffee -2012-01-14 -Saturday, January 14, 2012 +# JS does not have extensive formatting support out of the box. This code shows +# how you could create a date formatter object. +DateFormatter = -> + weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] + months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] + pad = (n) -> + if n < 10 + "0" + n + else + n + + brief: (date) -> + month = 1 + date.getMonth() + "#{date.getFullYear()}-#{pad month}-#{pad date.getDate()}" + + verbose: (date) -> + weekday = weekdays[date.getDay()] + month = months[date.getMonth()] + day = date.getDate() + year = date.getFullYear(); + "#{weekday}, #{month} #{day}, #{year}" + +formatter = DateFormatter() +date = new Date() +console.log formatter.brief(date) +console.log formatter.verbose(date) diff --git a/Task/Date-format/Elixir/date-format.elixir b/Task/Date-format/Elixir/date-format.elixir new file mode 100644 index 0000000000..6c5856b397 --- /dev/null +++ b/Task/Date-format/Elixir/date-format.elixir @@ -0,0 +1,25 @@ +defmodule Date do + def iso_date, do: iso_date(:erlang.date) + + def iso_date(year, month, day), do: iso_date({year, month, day}) + + def iso_date(date), do: + :io.format("~4b-~2..0B-~2..0B~n", Tuple.to_list(date)) + + def long_date, do: long_date(:erlang.date) + + def long_date(year, month, day), do: long_date({year, month, day}) + + def long_date(date = {year, month, day}) do + months = { "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December" } + weekdays = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" } + weekday = :calendar.day_of_the_week(date) + IO.puts "#{elem(weekdays, weekday-1)}, #{elem(months, month-1)} #{day}, #{year}" + end +end + +Date.iso_date +Date.iso_date(2007,11,10) +Date.long_date +Date.long_date(2007,11,10) diff --git a/Task/Date-format/Julia/date-format.julia b/Task/Date-format/Julia/date-format.julia new file mode 100644 index 0000000000..f15fd6125b --- /dev/null +++ b/Task/Date-format/Julia/date-format.julia @@ -0,0 +1,5 @@ +ts = time() + +println("Today's date is:") +println(" ", strftime("%F", ts)) +println(" ", strftime("%A, %B %d, %Y", ts)) diff --git a/Task/Date-format/VBScript/date-format.vb b/Task/Date-format/VBScript/date-format.vb new file mode 100644 index 0000000000..039fb4d00a --- /dev/null +++ b/Task/Date-format/VBScript/date-format.vb @@ -0,0 +1,5 @@ +'YYYY-MM-DD format +WScript.StdOut.WriteLine Year(Date) & "-" & Right("0" & Month(Date),2) & "-" & Right("0" & Day(Date),2) + +'Weekday_Name, Month_Name DD, YYYY format +WScript.StdOut.WriteLine FormatDateTime(Now,1) diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-1.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-1.basic new file mode 100644 index 0000000000..a8fcdd2b16 --- /dev/null +++ b/Task/Day-of-the-week/BASIC/day-of-the-week-1.basic @@ -0,0 +1,45 @@ +Declare Function modulo(x As Double, y As Double) As Double +Declare Function wd(m As Double, d As Double, y As Double) As Integer + +Cls +Dim yr As Double +For yr = 2008 To 2121 + If wd(12,25,yr) = 1 Then + Print "Dec " & 25 & ", " & yr + EndIf +Next +Sleep + +Function modulo(x As Double, y As Double) As Double + If y = 0 Then + Return x + Else + Return x - y * Int(x / y) + End If +End Function + +Function wd(m As Double, d As Double, y As Double) As Integer + If m = 1 Or m = 2 Then + m += 12 + y-= 1 + End If + Return modulo(365 * y + Fix(y / 4) - Fix(y / 100) + Fix(y / 400) + d + Fix((153 * m + 8) / 5), 7) + 1 +End Function + +Dec 25, 2011 +Dec 25, 2016 +Dec 25, 2022 +Dec 25, 2033 +Dec 25, 2039 +Dec 25, 2044 +Dec 25, 2050 +Dec 25, 2061 +Dec 25, 2067 +Dec 25, 2072 +Dec 25, 2078 +Dec 25, 2089 +Dec 25, 2095 +Dec 25, 2101 +Dec 25, 2107 +Dec 25, 2112 +Dec 25, 2118 diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic new file mode 100644 index 0000000000..eea41b6f14 --- /dev/null +++ b/Task/Day-of-the-week/BASIC/day-of-the-week-2.basic @@ -0,0 +1,24 @@ +' version 17-06-2015 +' compile with: fbc -s console + +Function wd(m As Integer, d As Integer, y As Integer) As Integer + If m < 3 Then ' If m = 1 Or m = 2 Then + m += 12 + y -= 1 + End If + Return (y + (y \ 4) - (y \ 100) + (y \ 400) + d + ((153 * m + 8) \ 5)) Mod 7 +End Function + +' ------=< MAIN >=------ + +For yr As Integer = 2008 To 2121 + If wd(12, 25, yr) = 0 Then + Print "Dec 25 "; yr + EndIf +Next + +' empty keyboard buffer +While InKey <> "" : Var _key_ = InKey : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic b/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic new file mode 100644 index 0000000000..0662da8314 --- /dev/null +++ b/Task/Day-of-the-week/BASIC/day-of-the-week-3.basic @@ -0,0 +1,17 @@ +' version 17-06-2015 +' Weekday And DateSerial only works with #Include "vbcompat.bi" +' compile with: fbc -s console + +#Include Once "vbcompat.bi" +Dim As Double a + +For yr As Integer = 2008 To 2121 + a = DateSerial (yr, 12, 25) + If Weekday(a) = 1 Then Print Format(a, "dd-mm-yyyy") ' 1 = sunday, 2 = monday ... +Next + +' empty keyboard buffer +While InKey <> "" : Var _key_ = InKey : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Day-of-the-week/Batch-File/day-of-the-week.bat b/Task/Day-of-the-week/Batch-File/day-of-the-week.bat new file mode 100644 index 0000000000..2a71e2d127 --- /dev/null +++ b/Task/Day-of-the-week/Batch-File/day-of-the-week.bat @@ -0,0 +1,30 @@ +:: Day of the Week task from Rosetta Code Wiki +:: Batch File Implementation +:: +:: In what years between 2008 and 2121 will the 25th of December be a Sunday? +:: +:: This implementation uses Zeller's Rule... + +@echo off + +::Set month code for December +set mon=33 + +::Set day number +set day=25 + +for /L %%w in (2008,1,2121) do ( +call :check_day %%w +) +pause>nul +exit /b + +:check_day +set yr=%1 +set /a a=%yr%/100 +set /a b=%yr%-(%a%*100) +set /a weekday=(%day%+%mon%+%b%+(%b%/4)+(%a%/4)+(5*%a%))%%7 +if %weekday%==1 ( +echo Dec 25, %yr% is a Sunday. +) +goto :EOF diff --git a/Task/Day-of-the-week/Delphi/day-of-the-week.delphi b/Task/Day-of-the-week/Delphi/day-of-the-week.delphi index 41a1b469e0..f0c8f329aa 100644 --- a/Task/Day-of-the-week/Delphi/day-of-the-week.delphi +++ b/Task/Day-of-the-week/Delphi/day-of-the-week.delphi @@ -13,5 +13,8 @@ outputyears := ''; outputyears := outputyears + inttostr(i) + ' '; end; end; + //CONSOLE + //writeln(outputyears); + //GUI form1.label1.caption := outputyears; end; diff --git a/Task/Day-of-the-week/Elixir/day-of-the-week.elixir b/Task/Day-of-the-week/Elixir/day-of-the-week.elixir new file mode 100644 index 0000000000..02b7e8caa6 --- /dev/null +++ b/Task/Day-of-the-week/Elixir/day-of-the-week.elixir @@ -0,0 +1,4 @@ +Enum.each(2008..2121, fn year -> + wday = :calendar.day_of_the_week(year, 12, 25) + if wday==7, do: IO.puts "25 December #{year} is sunday" +end) diff --git a/Task/Day-of-the-week/Julia/day-of-the-week.julia b/Task/Day-of-the-week/Julia/day-of-the-week.julia new file mode 100644 index 0000000000..298658aba8 --- /dev/null +++ b/Task/Day-of-the-week/Julia/day-of-the-week.julia @@ -0,0 +1,15 @@ +isdefined(:Date) || using Dates + +lo = 2008 +hi = 2121 +xmas = Date(lo, 12, 25):Year(1):Date(hi, 12, 25) + +smas = recur(xmas) do y + Dates.dayofweek(y) == Dates.Sun +end + +println("Years (from ", lo, " to ", hi, ") having Christmas on a Sunday:") + +for y in smas + println(" ", Dates.year(y)) +end diff --git a/Task/Day-of-the-week/Logo/day-of-the-week.logo b/Task/Day-of-the-week/Logo/day-of-the-week.logo new file mode 100644 index 0000000000..6daea9a63e --- /dev/null +++ b/Task/Day-of-the-week/Logo/day-of-the-week.logo @@ -0,0 +1,34 @@ +; Determine if a Gregorian calendar year is leap +to leap? :year + output (and + equal? 0 modulo :year 4 + not member? modulo :year 400 [100 200 300] + ) +end + +; Convert Gregorian calendar date to a simple day count from +; day 1 = January 1, 1 CE +to day_number :year :month :day + local "elapsed make "elapsed difference :year 1 + output (sum product 365 :elapsed + int quotient :elapsed 4 + minus int quotient :elapsed 100 + int quotient :elapsed 400 + int quotient difference product 367 :month 362 12 + ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2 + :day) +end + +; Find the day of the week from a day number; 0 = Sunday through 6 = Saturday +to day_of_week :day_number + output modulo :day_number 7 +end + +; True if the given day is a Sunday +to sunday? :year :month :day + output equal? 0 day_of_week day_number :year :month :day +end + +; Put it all together to answer the question posed in the problem +print filter [sunday? ? 12 25] iseq 2008 2121 +bye diff --git a/Task/Day-of-the-week/Oberon-2/day-of-the-week.oberon-2 b/Task/Day-of-the-week/Oberon-2/day-of-the-week.oberon-2 new file mode 100644 index 0000000000..8abece7175 --- /dev/null +++ b/Task/Day-of-the-week/Oberon-2/day-of-the-week.oberon-2 @@ -0,0 +1,13 @@ +MODULE DayOfWeek; +IMPORT NPCT:Dates, Out; +VAR + year: INTEGER; + date: Dates.Date; +BEGIN + FOR year := 2008 TO 2121 DO + date := Dates.NewDate(25,12,year); + IF date.DayOfWeek() = Dates.sunday THEN + Out.Int(date.year,4);Out.Ln + END + END +END DayOfWeek. diff --git a/Task/Day-of-the-week/PARI-GP/day-of-the-week.pari b/Task/Day-of-the-week/PARI-GP/day-of-the-week.pari new file mode 100644 index 0000000000..b1f2ad3784 --- /dev/null +++ b/Task/Day-of-the-week/PARI-GP/day-of-the-week.pari @@ -0,0 +1,10 @@ +njd(D) = +{ + my (m, y); + + if (D[2] > 2, y = D[1]; m = D[2]+1, y = D[1]-1; m = D[2]+13); + + (1461*y)\4 + (306001*m)\10000 + D[3] - 694024 + if (100*(100*D[1]+D[2])+D[3] > 15821004, 2 - y\100 + y\400) +} + +for (y = 2008, 2121, if (njd([y,12,25]) % 7 == 1, print(y))); diff --git a/Task/Day-of-the-week/Python/day-of-the-week.py b/Task/Day-of-the-week/Python/day-of-the-week.py index 4b0627699f..1396944d3d 100644 --- a/Task/Day-of-the-week/Python/day-of-the-week.py +++ b/Task/Day-of-the-week/Python/day-of-the-week.py @@ -1,8 +1,6 @@ -import datetime +from datetime import date -def yuletide(): - sunday = 6 - days = (day.strftime('%d %b %Y') for day in (datetime.date(year, 12, 25) for year in range(2008,2122)) if day.weekday() == sunday) - print '\n'.join(days) - -yuletide() +for year in range(2008, 2122): + day = date(year, 12, 25) + if day.weekday() == 6: + print(day.strftime('%d %b %Y')) diff --git a/Task/Day-of-the-week/Ruby/day-of-the-week-1.rb b/Task/Day-of-the-week/Ruby/day-of-the-week-1.rb index ee9feb6b0b..a43d4d16a3 100644 --- a/Task/Day-of-the-week/Ruby/day-of-the-week-1.rb +++ b/Task/Day-of-the-week/Ruby/day-of-the-week-1.rb @@ -1,5 +1,3 @@ require 'date' -(2008..2121).each do |year| - puts "25 Dec #{year}" if Date.new(year, 12, 25).wday == 0 # Ruby 1.9: if Date.new(year, 12, 25).sunday? -end +(2008..2121).each {|year| puts "25 Dec #{year}" if Date.new(year, 12, 25).sunday? } diff --git a/Task/Day-of-the-week/TI-83-BASIC/day-of-the-week.ti-83 b/Task/Day-of-the-week/TI-83-BASIC/day-of-the-week.ti-83 index 26e010e4db..8b47f5038e 100644 --- a/Task/Day-of-the-week/TI-83-BASIC/day-of-the-week.ti-83 +++ b/Task/Day-of-the-week/TI-83-BASIC/day-of-the-week.ti-83 @@ -1,5 +1,4 @@ -:For(A, 2008,2121 -:dayofWk(A,12,25 -:If Ans=1 +:For(A,2008,2121 +:If dayofWk(A,12,25)=1 :Disp A :End diff --git a/Task/Day-of-the-week/VBScript/day-of-the-week.vb b/Task/Day-of-the-week/VBScript/day-of-the-week.vb new file mode 100644 index 0000000000..5c4fa890dc --- /dev/null +++ b/Task/Day-of-the-week/VBScript/day-of-the-week.vb @@ -0,0 +1,6 @@ +For i = 2008 To 2121 + If Weekday(i & "-12-25") = 1 Then + WScript.StdOut.Write i + WScript.StdOut.WriteLine + End If +Next diff --git a/Task/Deal-cards-for-FreeCell/Befunge/deal-cards-for-freecell.bf b/Task/Deal-cards-for-FreeCell/Befunge/deal-cards-for-freecell.bf new file mode 100644 index 0000000000..ccf34c5359 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Befunge/deal-cards-for-freecell.bf @@ -0,0 +1,5 @@ +vutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDC +>4$0" :rebmun emaG">:#,_$&>55+,>"O?+"**2+*"C4'' "**v +>8%!492*+*48*\-,1-:11p0g\0p11g#^_@A23456789TJQKCDHS* +^+3:g11,g2+"/"%4,g2+g14/4:-\"v"g0:%g11+*-/2-10-1*<>+ +>8#8*#4*#::#%*#*/#*:#*0#:\#*`#:8#::#*:#8*#8:#2*#+^#< diff --git a/Task/Deal-cards-for-FreeCell/Clojure/deal-cards-for-freecell.clj b/Task/Deal-cards-for-FreeCell/Clojure/deal-cards-for-freecell.clj new file mode 100644 index 0000000000..4eb5751b2c --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Clojure/deal-cards-for-freecell.clj @@ -0,0 +1,16 @@ +(def deck (into [] (for [rank "A23456789TJQK" suit "CDHS"] (str rank suit)))) + +(defn lcg [seed] + (map #(bit-shift-right % 16) + (rest (iterate #(mod (+ (* % 214013) 2531011) (bit-shift-left 1 31)) seed)))) + +(defn gen [seed] + (map (fn [rnd rng] (into [] [(mod rnd rng) (dec rng)])) + (lcg seed) (range 52 0 -1))) + +(defn xchg [v [src dst]] (assoc v dst (v src) src (v dst))) + +(defn show [seed] (map #(println %) (partition 8 8 "" + (reverse (reduce xchg deck (gen seed)))))) + +(show 1) diff --git a/Task/Deal-cards-for-FreeCell/Mathematica/deal-cards-for-freecell.math b/Task/Deal-cards-for-FreeCell/Mathematica/deal-cards-for-freecell.math new file mode 100644 index 0000000000..eb509f0179 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Mathematica/deal-cards-for-freecell.math @@ -0,0 +1,13 @@ +next[last_] := Mod[214013 last + 2531011, 2^31]; +deal[n_] := + Module[{last = n, idx, + deck = StringJoin /@ + Tuples[{{"A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", + "Q", "K"}, {"C", "D", "H", "S"}}], res = {}}, + While[deck != {}, last = next[last]; + idx = Mod[BitShiftRight[last, 16], Length[deck]] + 1; + deck = ReplacePart[deck, {idx -> deck[[-1]], -1 -> deck[[idx]]}]; + AppendTo[res, deck[[-1]]]; deck = deck[[;; -2]]]; res]; +format[deal_] := Grid[Partition[deal, 8, 8, {1, 4}, Null]]; +Print[format[deal[1]]]; +Print[format[deal[617]]]; diff --git a/Task/Deal-cards-for-FreeCell/Perl-6/deal-cards-for-freecell.pl6 b/Task/Deal-cards-for-FreeCell/Perl-6/deal-cards-for-freecell.pl6 index 83cebfe439..6a269bc8b5 100644 --- a/Task/Deal-cards-for-FreeCell/Perl-6/deal-cards-for-freecell.pl6 +++ b/Task/Deal-cards-for-FreeCell/Perl-6/deal-cards-for-freecell.pl6 @@ -5,7 +5,7 @@ sub dealgame ($game-number = 1) { my @ms-lcg := (&ms-lcg-method ... *).map: * +> 16; constant CardBlock = '🂠'.ord; - my @deck = gather for 1..11,13,14 X+ (48,32...0) -> $off { + my @deck = gather for flat(1..11,13,14) X+ (48,32...0) -> $off { take chr CardBlock + $off; } diff --git a/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx b/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx new file mode 100644 index 0000000000..5c01186044 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx @@ -0,0 +1,26 @@ +/*REXX pgm deals cards for a specific FreeCell solitaire card game (0──►32767)*/ +numeric digits 15 /*ensure enough digits for the random #*/ +parse arg g .; if g=='' then g=1 /*if game isn't specified, use default.*/ +state=g /*seed the random # generator with game*/ +if 8=='f8'x then suit='cdhs' /*EBCDIC? Then use letters for suits.*/ + else suit='♣♦♥♠' /* ASCII? " " symbols " " */ +rank='A23456789TJQK' /*T in the rank represents a ten (10).*/ +__=left('', 13) /*used for indentation for the tableau.*/ +say center('tableau for FreeCell game' g,50,'─'); say /*show title for game#*/ +#=-1 /*$ is an array of all the 52 cards.*/ + do r=1 for length(rank) /*build deck first by the rank.*/ + do s=1 for length(suit); #=#+1 /* " " secondly by suit. */ + $.#=substr(rank,r,1)substr(suit,s,1) /*build array 1 card at at time*/ + end /*s*/ /* [↑] first card is number 0.*/ + end /*r*/ /* [↑] build deck per FreeCell rules. */ +@=__ /*@: cards to be dealt, eight at a time*/ + do cards=51 by -1 for 52 /* [↓] deal the cards for the tableau.*/ + ?=rand() // (cards+1) /*get next rand#; card # is remainder.*/ + @=@ $.?; $.?=$.cards /*swap 2 cards: random & last*/ + if words(@)==8 then do; say @; @=__; end /*deal cards for the tableau.*/ + end /*cards*/ /*8 cards are dealt to a row.*/ + /* [↓] residual cards exist.*/ + if @\=='' then say @ /*residual cards for tableau.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────RAND subroutine───────────────────────────*/ +rand: state = (214013 * state + 2531011) // 2**31; return state % 2**16 diff --git a/Task/Deal-cards-for-FreeCell/Ruby/deal-cards-for-freecell.rb b/Task/Deal-cards-for-FreeCell/Ruby/deal-cards-for-freecell.rb index 9ab3282702..07c725996e 100644 --- a/Task/Deal-cards-for-FreeCell/Ruby/deal-cards-for-freecell.rb +++ b/Task/Deal-cards-for-FreeCell/Ruby/deal-cards-for-freecell.rb @@ -1,55 +1,16 @@ -# Deal cards for FreeCell. -# http://rosettacode.org/wiki/Deal_cards_for_FreeCell - -require 'optparse' - -# Parse command-line arguments. # games = ARGV converted to Integer # No arguments? Pick any of first 32000 games. -games = nil -OptionParser.new do |o| - begin - o.banner = "Usage: #{o.program_name} number..." - o.parse! - games = ARGV.map {|s| Integer(s)} - games.empty? and games = [rand(32000)] - rescue => e - $stderr.puts e, o - abort - end -end - -# Define methods for old Ruby versions. -# Enumerable#each_slice appeared in Ruby 1.8.7. -# Enumerable#flat_map appeared in Ruby 1.9.2. -module Enumerable - unless method_defined? :each_slice - def each_slice(count) - block_given? or return enum_for(:each_slice, count) - ary = [] - each {|e| - ary << e - ary.length == count and (yield ary.dup; ary.clear)} - ary.empty? or yield ary.dup - nil - end - end - - unless method_defined? :flat_map - def flat_map - block_given? or return enum_for(:flat_map) - ary = [] - each {|e| - y = yield e - ary.concat(y) rescue ary.push(y)} - ary - end - end +begin + games = ARGV.map {|s| Integer(s)} +rescue => err + $stderr.puts err.inspect + $stderr.puts "Usage: #{__FILE__} number..." + abort end +games.empty? and games = [rand(32000)] # Create original deck of 52 cards, not yet shuffled. -orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K -}.flat_map {|rank| %w{C D H S}.map {|suit| "#{rank}#{suit}"}} +orig_deck = %w{A 2 3 4 5 6 7 8 9 T J Q K}.product(%w{C D H S}).map(&:join) games.each do |seed| deck = orig_deck.dup @@ -69,4 +30,5 @@ def flat_map # Deal cards. puts "Game ##{seed}" deck.each_slice(8) {|row| puts " " + row.join(" ")} + puts end diff --git a/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust b/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust index 24586a4c28..71003a7eac 100644 --- a/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust +++ b/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust @@ -1,85 +1,59 @@ -/* - * Microsoft C Run-time-Library-compatible Random Number Generator - * Copyright by Shlomi Fish, 2011. - * Released under the MIT/X11 License - * ( http://en.wikipedia.org/wiki/MIT_License ). - * */ - -struct MSVC_Rand_Gen { - seed: i32 +struct MSVCRandGen { + seed: u32 } -impl MSVC_Rand_Gen { - fn rand(&mut self) -> i32 { - self.seed = ((self.seed * 214013 + 2531011) & 0x7FFFFFFF); - return ((self.seed >> 16) & 0x7FFF); +impl MSVCRandGen { + fn rand(&mut self) -> u32 { + self.seed = (self.seed.wrapping_mul(214013).wrapping_add(2531011)) % 0x80000000; + assert!(self.seed >> 16 < 32768); + (self.seed >> 16) & 0x7FFF } - fn max_rand(&mut self, mymax: i32) -> i32 { - return self.rand() % mymax; + fn max_rand(&mut self, mymax: u32) -> u32 { + self.rand() % mymax } fn shuffle(&mut self, deck: &mut [T]) { if deck.len() > 0 { - let mut i = (deck.len() as i32) - 1; + let mut i = (deck.len() as u32) - 1; while i > 0 { let j = self.max_rand(i+1); - vec::swap(deck, i as uint, j as uint); + deck.swap(i as usize, j as usize); i = i-1; } } } } -/* - * Microsoft Windows Freecell / Freecell Pro boards generation. - * - * See: - * - * - http://rosettacode.org/wiki/Deal_cards_for_FreeCell - * - * - http://www.solitairelaboratory.com/mshuffle.txt - * - * Under MIT/X11 Licence. - * - * */ - - -fn deal_ms_fc_board(seed: i32) -> ~str { - let mut randomizer = MSVC_Rand_Gen { seed: seed, }; +fn deal_ms_fc_board(seed: u32) -> String { + let mut randomizer = MSVCRandGen { seed: seed, }; let num_cols = 8; - let mut columns = vec::from_elem(num_cols, ~[]); - let mut deck = vec::from_fn(4*13, |i| i); + let mut columns = vec![Vec::new(); num_cols]; + let mut deck: Vec<_> = (0..4*13).collect(); - let rank_strings = str::to_chars("A23456789TJQK"); - let suit_strings = str::to_chars("CDHS"); + let rank_strings: Vec = "A23456789TJQK".chars().collect(); + let suit_strings: Vec = "CDHS".chars().collect(); - randomizer.shuffle(deck); + randomizer.shuffle(&mut deck); - vec::reverse(deck); + deck.reverse(); - for uint::range(0, 52) |i| { + for i in 0..52 { columns[i % num_cols].push(deck[i]); - }; - - let render_card = |card: &uint| { - let suit = card % 4; - let rank = card / 4; + } - fmt!("%c%c",rank_strings[rank], suit_strings[suit]) + let render_card = |card: usize| -> String { + let (suit, rank) = (card % 4, card / 4); + format!("{}{}", rank_strings[rank], suit_strings[suit]) }; - let render_column = |col: &~[uint]| { - fmt!(": %s\n", str::connect((col.map(render_card)), " ")) + let render_column = |col: Vec| -> String { + format!(": {}\n", col.into_iter().map(&render_card).collect::>().join(" ")) }; - return str::concat(columns.map(render_column)); + columns.into_iter().map(render_column).collect::>().join("") } fn main() { - let args: ~[~str] = os::args(); - - match uint::from_str(args[1]) { - Some(x) => print(deal_ms_fc_board(x as i32)), - None => println("I need a real number"), - } + let arg: u32 = std::env::args().nth(1).and_then(|n| n.parse().ok()).expect("I need a number."); + print!("{}", deal_ms_fc_board(arg)); } diff --git a/Task/Death-Star/J/death-star.j b/Task/Death-Star/J/death-star.j new file mode 100644 index 0000000000..f0d3d92fd0 --- /dev/null +++ b/Task/Death-Star/J/death-star.j @@ -0,0 +1,40 @@ +load'graphics/viewmat' +mag =: +/&.:*:"1 +norm=: %"1 0 mag +dot =: +/@:*"1 + +NB. (pos;posr;neg;negr) getvec (x,y) +getvec =: 4 :0 "1 + pt =. y + 'pos posr neg negr' =. x + if. (dot~ pt-}:pos) > *:posr do. + 0 0 0 + else. + zb =. ({:pos) (-,+) posr -&.:*: pt mag@:- }:pos + if. (dot~ pt-}:neg) > *:negr do. + (pt,{:zb) - pos + else. + zs =. ({:neg) (-,+) negr -&.:*: pt mag@:- }:neg + if. zs >&{. zb do. (pt,{:zb) - pos + elseif. zs >&{: zb do. 0 0 0 + elseif. ({.zs) < ({:zb) do. neg - (pt,{.zs) + elseif. do. (pt,{.zb) - pos end. + end. + end. +) + + +NB. (k;ambient;light) draw_sphere (pos;posr;neg;negr) +draw_sphere =: 4 :0 + 'pos posr neg negr' =. y + 'k ambient light' =. x + vec=. norm y getvec ,"0// (2{.pos) +/ i: 200 j.~ 0.5+posr + + b=. (mag vec) * ambient + k * 0>. light dot vec +) + +togray =: 256#. 255 255 255 <.@*"1 0 (%>./@,) + +env=.(2; 0.5; (norm _50 30 50)) +sph=. 20 20 0; 20; 1 1 _6; 20 +'rgb' viewmat togray env draw_sphere sph diff --git a/Task/Death-Star/Perl-6/death-star.pl6 b/Task/Death-Star/Perl-6/death-star.pl6 index edd584b3c7..1873583d7d 100644 --- a/Task/Death-Star/Perl-6/death-star.pl6 +++ b/Task/Death-Star/Perl-6/death-star.pl6 @@ -33,7 +33,7 @@ sub MAIN ($outfile = 'deathstar-perl6.pgm') { my $out = open( $outfile, :w, :bin ) or die "$!\n"; $out.say("P5\n$x $y\n$depth"); # .pgm header say 'Calculating row:'; - $out.print( draw_ds(3, .15)».chrs ); + $out.write( Blob.new( draw_ds(3, .15) ) ); $out.close; } @@ -41,7 +41,7 @@ sub draw_ds ( $k, $ambient ) { my @pixels; my $bs = "\b" x 8; for ($pos.cy - $pos.r) .. ($pos.cy + $pos.r) -> $y { - note $bs, $y, ' '; # monitor progress + print $bs, $y, ' '; # monitor progress for ($pos.cx - $pos.r) .. ($pos.cx + $pos.r) -> $x { # black if we don't hit positive sphere, ignore negative sphere if not hit($pos, $x, $y, my $posz) { @@ -69,10 +69,10 @@ sub draw_ds ( $k, $ambient ) { } # normalize a vector -sub normalize (@vec) { return @vec »/» ([+] @vec Z* @vec).sqrt } +sub normalize (@vec) { return @vec »/» ([+] @vec »*« @vec).sqrt } # dot product of two vectors -sub dot (@x, @y) { return -([+] @x Z* @y) max 0 } +sub dot (@x, @y) { return -([+] @x »*« @y) max 0 } # are the coordinates within the radius of the sphere? sub hit ($sphere, $x is copy, $y is copy, $z is rw) { diff --git a/Task/Death-Star/REXX/death-star.rexx b/Task/Death-Star/REXX/death-star.rexx index 8e01935930..11a18d83b6 100644 --- a/Task/Death-Star/REXX/death-star.rexx +++ b/Task/Death-Star/REXX/death-star.rexx @@ -1,75 +1,58 @@ -/*REXX program to draw a "deathstar", a sphere with another subtracted. */ -signal on syntax; signal on noValue /*handle REXX program errors. */ -numeric digits 20 /*use a fair amount of precision.*/ - lightSource = norm('-50 30 50') -call drawSphereM 2, .5, lightSource -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────DRAWSPHEREM subroutine──────────────*/ -drawSphereM: procedure; parse arg k,ambient,lightSource -z1=0; z2=0 -parse var lightSource s1 s2 s3 /*break-apart the light source. */ - - shading='·:!ºoe@░▒▓' /*shading chars for ASCI machines*/ -if 1=='f1'x then shading='.:!*oe&#%@' /*shading chars for EBCDIC machs.*/ - -shadesLength=length(shading) -shades.=' '; do i=1 for shadesLength - shades.i=substr(shading,i,1) - end /*i*/ - -ship= 20 20 0 20 ; parse var ship ship.cx ship.cy ship.cz ship.radius -hole=' 1 1 -6 20'; parse var hole hole.cx hole.cy hole.cz hole.radius - - do i=floor(ship.cy-ship.radius) to ceil(ship.cy+ship.radius)+1; y=i+.5; aLine= - do j=trunc(floor(ship.cx - 2*ship.radius) ) to , - trunc( ceil(ship.cx + 2*ship.radius) +1) - x=.5*(j-ship.cx) + .5 + ship.cx; !bg=0; !pos=0; !neg=0; z1=0; z2=0 - ?=hitSphere(ship, x, y); zb1=z1; zb2=z2 - - if \? then !bg=1 /*ray lands in blank space, draw the background. */ - else do - ?=hitsphere(hole, x, y); zs1=z1; zs2=z2 - if \? then !pos=1 /*ray hits ship but not the hole, draw ship surface. */ - else if zs1>zb1 then !pos=1 /*ray hits both, but ship front surface is closer. */ - else if zs2>zb2 then !bg=1 /*ship surface is inside hole, show background. */ - else if zs2>zb1 then !neg=1 /*back surface in hole is inside ship, the only place hole surface will be shown.*/ - else !pos=1 +/*REXX pgm draws a sphere with another sphere subtracted where superimposed. */ +call deathStar 2, .5, v3('-50 30 50') +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines────────────────────────────────────────*/ +dot.: procedure; parse arg x,y; d=dot(x,y); if d<0 then return -d; return 0 +dot: procedure; parse arg x,y; s=0; do j=1 for words(x); s=s+word(x,j)*word(y,j); end; return s +ceil: procedure; parse arg x; _=trunc(x); return _+(x>0)*(x\=_) +floor: procedure; parse arg x; _=trunc(x); return _-(x<0)*(x\=_) +v3: procedure; parse arg a b c; s=sqrt(a**2+b**2+c**2); return a/s b/s c/s +/*──────────────────────────────────DEATHSTAR subroutine──────────────────────*/ +deathStar: procedure; parse arg k,ambient,sun /* [↓] draw deathstar*/ +parse var sun s1 s2 s3 /*identify the lightsource coördinates.*/ + +if 6=='f6'x then shading= '.:!*oe&#%@' /*shading characters for EBCDIC machine*/ + else shading= '·:!ºoe@░▒▓' /* " " " ASCII " */ + +shadesLen=length(shading) +shades.=' '; do i=1 for shadesLen; shades.i=substr(shading,i,1); end /*i*/ + +ship= 20 20 0 20 ; parse var ship ship.cx ship.cy ship.cz ship.radius +hole=' 1 1 -6 20'; parse var hole hole.cx hole.cy hole.cz hole.radius + + do i=floor(ship.cy-ship.radius) to ceil(ship.cy+ship.radius) +1; y=i+.5; $= + do j=trunc(floor(ship.cx-2*ship.radius)) to trunc(ceil(ship.cx+2*ship.radius) +1) + x=.5*(j-ship.cx)+.5+ship.cx; !.=0 + ?=hitSphere(ship, x, y); b1=!.z1; b2=!.z2 /*? is boolean, "true" indicates ray hits the sphere.*/ + + if \? then !.bg=1 /*ray lands in blank space, so draw the background. */ + else do; ?=hitSphere(hole, x, y); s1=!.z1; s2=!.z2 + if \? then !.pos=1 /*ray hits ship but not the hole, so draw ship surface. */ + else if s1>b1 then !.pos=1 /*ray hits both, but ship front surface is closer. */ + else if s2>b2 then !.bg=1 /*ship surface is inside hole, so show the background. */ + else if s2>b1 then !.neg=1 /*hole back surface is inside ship; the only place hole surface will be shown.*/ + else !.pos=1 end select - when !bg then do; aLine=aLine' '; iterate j; end - when !pos then vec_=V3(x-ship.cx y-ship.cy zb1-ship.cz) - when !neg then vec_=V3(hole.cx-x hole.cy-y hole.cz-zs2) + when !.bg then do; $=$' '; iterate j; end /*append a blank to the line to be displayed.*/ + when !.pos then vec_=v3(x-ship.cx y-ship.cy b1-ship.cz) + when !.neg then vec_=v3(hole.cx-x hole.cy-y hole.cz-s2) end /*select*/ - nvec=norm(vec_) - b=dot.(lightSource,nvec)**k + ambient - intensity=trunc((1-b) * shadesLength) - intensity=min(shadesLength, max(0, intensity)) + 1 - aLine=aLine || shades.intensity - end /*j*/ + b=1+min(shadesLen,max(0,trunc((1-(dot.(sun,v3(vec_))**k+ambient))*shadesLen))) + $=$ || shades.b /*B is the ray's intensity│brightness*/ + end /*j*/ /* [↑] build line for showing sphere.*/ - if aline\='' then say strip(aLine,'T') - end /*i*/ + if $\='' then say strip($,'T') /*strip any trailing blanks from line.*/ + end /*i*/ /* [↑] show all lines for the sphere.*/ return -/*──────────────────────────────────HITSPHERE subroutine────────────────*/ -hitSphere: procedure expose z1 z2; parse arg $.cx $.cy $.cz $.radius, x0, y0 - x=x0-$.cx - y=y0-$.cy - zsq=$.radius**2 - (x**2 + y**2); if zsq<0 then return 0 - _=sqrt(zsq) - z1=$.cz-_ - z2=$.cz+_ - return 1 -/*──────────────────────────────────one─liner subroutines────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -dot.: procedure; parse arg x,y; d=dot(x,y); if d<0 then return -d; return 0 -dot: procedure; parse arg x,y; s=0; do j=1 for words(x); s=s+word(x,j)*word(y,j); end; return s -err: say; say; say center(' error! ',max(40,linesize()%2),"*"); say; do j=1 for arg(); say arg(j); say; end; say; exit 13 -ceil: procedure; parse arg x; _=trunc(x); return _ + (x>0) * (x\=_) -floor: procedure; parse arg x; _=trunc(x); return _ - (x<0) * (x\=_) -norm: parse arg _1 _2 _3; _=sqrt(_1**2+_2**2+_3**2); return _1/_ _2/_ _3/_ -noValue: syntax: call err 'REXX program' condition('C') "error", condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl) -sqrt: procedure; parse arg x; if x=0 then return 0; return .sqrt(x)/1 -.sqrt: d=digits();numeric digits 11;g=.sqrtG();do j=0 while p>9;m.j=p;p=p%2+1;end;do k=j+5 by -1 to 0;if m.k>11 then numeric digits m.k;g=.5*(g+x/g);end;return g -.sqrtG: numeric form; m.=11; p=d+d%4+2; v=format(x,2,1,,0) 'E0'; parse var v g 'E' _ .; return g*.5'E'_%2 -V3: procedure; parse arg v; return norm(v) +/*──────────────────────────────────HITSPHERE subroutine──────────────────────────*/ +hitSphere: procedure expose !.; parse arg xx yy zz r,x0,y0; x=x0-xx; y=y0-yy +z=r**2-(x**2+y**2); if z<0 then return 0; _=sqrt(z); !.z1=zz-_; !.z2=zz+_; return 1 +/*──────────────────────────────────SQRT subroutine───────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ diff --git a/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 b/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 index edaec53b6e..255cf96994 100644 --- a/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 +++ b/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 @@ -1,10 +1,10 @@ sub deconvolve (@g, @f) { my $h = 1 + @g - @f; my @m; - @m[^@g]>>.[^$h] >>+=>> 0; - @m[^@g]>>.[$h] >>=<< @g; + @m[^@g;^$h] >>+=>> 0; + @m[^@g;$h] >>=<< @g; for ^$h -> $j { for @f.kv -> $k, $v { @m[$j + $k][$j] = $v } } - return rref( @m )[^$h]>>.[$h]; + return rref( @m )[^$h;$h]; } sub convolve (@f, @h) { @@ -16,7 +16,7 @@ sub convolve (@f, @h) { # Reduced Row Echelon Form simultaneous equation solver. # Can handle over-specified systems of equations. # (n unknowns in n + m equations) -sub rref ($m is rw) { +sub rref ($m is copy) { return unless $m; my ($lead, $rows, $cols) = 0, +$m, +$m[0]; @@ -41,7 +41,7 @@ sub rref ($m is rw) { $m[$r] >>/=>> $lv; for ^$rows -> $n { next if $n == $r; - $m[$n] >>-=>> $m[$r] >>*>> $m[$n][$lead]; + $m[$n] >>-=>> $m[$r] >>*>> ($m[$n][$lead]//0); } ++$lead; } diff --git a/Task/Deepcopy/Mathematica/deepcopy.math b/Task/Deepcopy/Mathematica/deepcopy.math new file mode 100644 index 0000000000..3a16780eca --- /dev/null +++ b/Task/Deepcopy/Mathematica/deepcopy.math @@ -0,0 +1,9 @@ +a = {"foo", \[Pi], {<| + "deep" -> {# + + 1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \ +{{"programming"}, {"language!"}}}}|>}}; +b = a; +a[[2]] -= 3; +a[[3, 1, 1, 1]] = #^2 &; +Print[a]; +Print[b]; diff --git a/Task/Define-a-primitive-data-type/Perl-6/define-a-primitive-data-type-1.pl6 b/Task/Define-a-primitive-data-type/Perl-6/define-a-primitive-data-type-1.pl6 index 8671ff92e6..df5e308092 100644 --- a/Task/Define-a-primitive-data-type/Perl-6/define-a-primitive-data-type-1.pl6 +++ b/Task/Define-a-primitive-data-type/Perl-6/define-a-primitive-data-type-1.pl6 @@ -1,4 +1,4 @@ -subset OneToTen of Int where 1..10 +subset OneToTen of Int where 1..10; my OneToTen $n = 5; $n += 6; diff --git a/Task/Delegates/ALGOL-68/delegates.alg b/Task/Delegates/ALGOL-68/delegates.alg new file mode 100644 index 0000000000..0c4d37a671 --- /dev/null +++ b/Task/Delegates/ALGOL-68/delegates.alg @@ -0,0 +1,75 @@ +# An Algol 68 approximation of delegates # + +# The delegate mode - the delegate is a STRUCT with a single field # +# that is a REF PROC STRING. If this is NIL, it doesn't implement # +# thing # +MODE DELEGATE = STRUCT( REF PROC STRING thing ); + + +# A delegator mode that will invoke the delegate's thing method # +# - if there is a delegate and the delegate has a thing method # +MODE DELEGATOR = STRUCT( REF DELEGATE delegate + , PROC( REF DELEGATE )STRING thing + ); + +# constructs a new DELEGATE with the specified PROC as its thing # +# Algol 68 HEAP is like "new" in e.g. Java, but it can't take # +# parameters, so this PROC does the equivalent # +PROC new delegate = ( REF PROC STRING thing )REF DELEGATE: + BEGIN + REF DELEGATE result = HEAP DELEGATE; + thing OF result := thing; + + result + END # new delegate # +; + +# constructs a new DELEGATOR with the specified DELEGATE # +PROC new delegator = ( REF DELEGATE delegate )REF DELEGATOR: + HEAP DELEGATOR := ( delegate + , # anonymous PROC to invoke the delegate's thing # + ( REF DELEGATE delegate )STRING: + IF delegate IS REF DELEGATE(NIL) + THEN + # we have no delegate # + "default implementation" + + ELIF thing OF delegate IS REF PROC STRING(NIL) + THEN + # the delegate doesn't have an implementation # + "default implementation" + + ELSE + # the delegate can thing # + thing OF delegate + + FI + ) +; + + +# invokes the delegate's thing via the delagator # +# Because the PROCs of a STRUCT don't have an equivalent of e.g. Java's # +# "this", we have to explicitly pass the delegate as a parameter # +PROC invoke thing = ( REF DELEGATOR delegator )STRING: + # the following is Algol 68 for what would be written in Java as # + # "delegator.thing( delegator.delegate )" # + ( thing OF delegator )( delegate OF delegator ) +; + +main: +( + + print( ( "No delegate : " + , invoke thing( new delegator( NIL ) ) + , newline + , "Delegate with no thing: " + , invoke thing( new delegator( new delegate( NIL ) ) ) + , newline + , "Delegate with a thing : " + , invoke thing( new delegator( new delegate( HEAP PROC STRING := STRING: ( "delegate implementation" ) ) ) ) + , newline + ) + ) + +) diff --git a/Task/Delegates/Forth/delegates.fth b/Task/Delegates/Forth/delegates.fth new file mode 100644 index 0000000000..2c07246b9a --- /dev/null +++ b/Task/Delegates/Forth/delegates.fth @@ -0,0 +1,67 @@ +include FMS-SI.f + +-1 [if] \ add optional introspection facility to FMS + +: fm' ( selector-ID link -- xt | 0 ) \ find method, linked-list search + begin @ dup + while 2dup cell+ @ = + if [ 2 cells ] literal + nip @ exit then + repeat 2drop false ; + +: has-meth-L ( obj addr -- xt | 0 ) + swap >class over @ + fm' ; + +: >xt' ( table-offset ^dispatch -- xt | 0 ) + 2dup @ > if 2drop false exit then + + @ ; + +: has-meth-D ( obj addr -- xt | 0 ) + @ swap @ >xt' ; + +: (has-meth) ( obj addr sel-type -- xt | 0 ) + seltype-L = + if ( obj addr ) has-meth-L + else ( obj addr ) has-meth-D + then ; + +: [has-meth] ( obj "messageName" -- xt | 0 ) \ compile time only, can use ex-meth on xt to execute the method + ' >body dup postpone literal cell+ @ postpone literal postpone (has-meth) ; immediate + +: has-meth ( obj "messageName" -- xt | 0 ) \ interpret time only, can use ex-meth on xt to execute the method + ' >body dup cell+ @ (has-meth) ; +[then] + + + +:class delegate + :m thing ." delegate implementation" ;m +;class + +delegate slave + +:class delegator + ivar del \ object container + :m !: ( n -- ) del ! ;m + :m init: 0 del ! ;m + :m default ." default implementation" ;m + :m operation + del @ 0= if self default exit then + del @ [has-meth] thing + if del @ thing + else self default + then ;m +;class + +delegator master + +\ First, without a delegate +master operation \ => default implementation + +\ then with a delegate that does not implement "thing" +object o +o master !: +master operation \ => default implementation + +\ and last with a delegate that implements "thing" +slave master !: +master operation \ => delegate implementation diff --git a/Task/Delegates/Mathematica/delegates.math b/Task/Delegates/Mathematica/delegates.math new file mode 100644 index 0000000000..6bdc6467aa --- /dev/null +++ b/Task/Delegates/Mathematica/delegates.math @@ -0,0 +1,6 @@ +delegator[del_]@operate := + If[StringQ[del@operate], del@operate, "default implementation"]; +del1 = Null; +del2@banana = "phone"; +del3@operate = "delegate implementation"; +Print[delegator[#]@operate] & /@ {del1, del2, del3}; diff --git a/Task/Delete-a-file/Elixir/delete-a-file.elixir b/Task/Delete-a-file/Elixir/delete-a-file.elixir new file mode 100644 index 0000000000..a3483b8fa5 --- /dev/null +++ b/Task/Delete-a-file/Elixir/delete-a-file.elixir @@ -0,0 +1,4 @@ +File.rm!("input.txt") +File.rmdir!("docs") +File.rm!("/input.txt") +File.rmdir!("/docs") diff --git a/Task/Delete-a-file/Mercury/delete-a-file.mercury b/Task/Delete-a-file/Mercury/delete-a-file.mercury new file mode 100644 index 0000000000..7f609d3bf7 --- /dev/null +++ b/Task/Delete-a-file/Mercury/delete-a-file.mercury @@ -0,0 +1,14 @@ +:- module delete_file. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +main(!IO) :- + io.remove_file("input.txt", _, !IO), + io.remove_file("/input.txt", _, !IO), + io.remove_file("docs", _, !IO), + io.remove_file("/docs", _, !IO). diff --git a/Task/Detect-division-by-zero/Batch-File/detect-division-by-zero.bat b/Task/Detect-division-by-zero/Batch-File/detect-division-by-zero.bat new file mode 100644 index 0000000000..9e13612c89 --- /dev/null +++ b/Task/Detect-division-by-zero/Batch-File/detect-division-by-zero.bat @@ -0,0 +1,5 @@ +@echo off +set /a dummy=5/0 2>nul + +if %errorlevel%==1073750993 echo I caught a division by zero operation... +exit /b 0 diff --git a/Task/Detect-division-by-zero/Elixir/detect-division-by-zero.elixir b/Task/Detect-division-by-zero/Elixir/detect-division-by-zero.elixir new file mode 100644 index 0000000000..e33e83d2c8 --- /dev/null +++ b/Task/Detect-division-by-zero/Elixir/detect-division-by-zero.elixir @@ -0,0 +1,15 @@ +defmodule Division do + def by_zero?(x,y) do + try do + _ = x / y + false + rescue + ArithmeticError -> true + end + end +end + +[{2, 3}, {3, 0}, {0, 5}, {0, 0}, {2.0, 3.0}, {3.0, 0.0}, {0.0, 5.0}, {0.0, 0.0}] +|> Enum.each(fn {x,y} -> + IO.puts "#{x} / #{y}\tdivision by zero #{Division.by_zero?(x,y)}" +end) diff --git a/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-1.f b/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-1.f new file mode 100644 index 0000000000..0cd24de9d7 --- /dev/null +++ b/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-1.f @@ -0,0 +1,41 @@ +program rosetta_divbyzero + implicit none + integer, parameter :: rdp = kind(1.d0) + real(rdp) :: normal,zero + + normal = 1.d0 + zero = 0.d0 + + call div_by_zero_check(normal,zero) + + contains + + subroutine div_by_zero_check(x,y) + use, intrinsic :: ieee_exceptions + use, intrinsic :: ieee_arithmetic + implicit none + real(rdp), intent(in) :: x,y + + real(rdp) :: check + type(ieee_status_type) :: status_value + logical :: flag + flag = .false. + ! Get the flags + call ieee_get_status(status_value) + ! Set the flags quiet + call ieee_set_flag(ieee_divide_by_zero,.false.) + write(*,*)"Inf supported? ",ieee_support_inf(check) + + ! Calculation involving exception handling + check = x/y + write(*,*)"Is check finite?",ieee_is_finite(check), check + + call ieee_get_flag(ieee_divide_by_zero, flag) + if (flag) write(*,*)"Warning! Division by zero detected" + + ! Restore the flags + call ieee_set_status(status_value) + + end subroutine div_by_zero_check + +end program rosetta_divbyzero diff --git a/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-2.f b/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-2.f new file mode 100644 index 0000000000..7d64715d79 --- /dev/null +++ b/Task/Detect-division-by-zero/Fortran/detect-division-by-zero-2.f @@ -0,0 +1,8 @@ +program rosetta_integer_divbyzero + implicit none + integer :: normal,zero,answer + normal = 1 + zero = 0 + answer = normal/ zero + write(*,*) answer +end program rosetta_integer_divbyzero diff --git a/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia b/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia new file mode 100644 index 0000000000..9f378300aa --- /dev/null +++ b/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia @@ -0,0 +1,13 @@ +function isdefinite{T<:Number}(n::T) + !isequal(n, NaN) && abs(n) != Inf +end + +for n in {1, 1//1, 1.0, 1im, 0} + d = n/0 + print("Divding ", n, " by 0 ") + if isdefinite(d) + println("results in ", d, ".") + else + println("yields an indefinite value (", d, ").") + end +end diff --git a/Task/Detect-division-by-zero/PowerShell/detect-division-by-zero.psh b/Task/Detect-division-by-zero/PowerShell/detect-division-by-zero.psh new file mode 100644 index 0000000000..082dcaa5db --- /dev/null +++ b/Task/Detect-division-by-zero/PowerShell/detect-division-by-zero.psh @@ -0,0 +1,6 @@ +function div ($a, $b) { + try{$a/$b} + catch{"Bad parameters: `$a = $a and `$b = $b"} +} +div 10 2 +div 1 0 diff --git a/Task/Detect-division-by-zero/VBScript/detect-division-by-zero.vb b/Task/Detect-division-by-zero/VBScript/detect-division-by-zero.vb new file mode 100644 index 0000000000..b123e4dd65 --- /dev/null +++ b/Task/Detect-division-by-zero/VBScript/detect-division-by-zero.vb @@ -0,0 +1,13 @@ +Function div(num,den) + On Error Resume Next + n = num/den + If Err.Number <> 0 Then + div = Err.Description & " is not allowed." + Else + div = n + End If +End Function + +WScript.StdOut.WriteLine div(6,3) +WScript.StdOut.WriteLine div(6,0) +WScript.StdOut.WriteLine div(7,-4) diff --git a/Task/Determine-if-a-string-is-numeric/00META.yaml b/Task/Determine-if-a-string-is-numeric/00META.yaml index 88eb5468ca..ac97287d53 100644 --- a/Task/Determine-if-a-string-is-numeric/00META.yaml +++ b/Task/Determine-if-a-string-is-numeric/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Text processing diff --git a/Task/Determine-if-a-string-is-numeric/ALGOL-W/determine-if-a-string-is-numeric.alg b/Task/Determine-if-a-string-is-numeric/ALGOL-W/determine-if-a-string-is-numeric.alg new file mode 100644 index 0000000000..8814170c90 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/ALGOL-W/determine-if-a-string-is-numeric.alg @@ -0,0 +1,135 @@ +begin + + % determnines whether the string contains an integer, real or imaginary % + % number. Returns true if it does, false otherwise % + logical procedure isNumeric( string(32) value text ) ; + begin + + logical ok; + % the "number" cannot be blank % + ok := ( text not = " " ); + if ok then begin + + % there is at least one non-blank character % + % must have either an integer or real/immaginary number % + % integer: [+|-]digit-sequence % + % real: [+|-][digit-sequence].digit-sequence['integer][L] % + % or: [+|-]digit-sequence[.[digit-sequence]]'integer[L] % + % imaginary: % + % [+|-][digit-sequence].digit-sequence['integer][L]I% + % or: [+|-]digit-sequence[.[digit-sequence]]'integer[L]I% + % The "I" at the end of an imaginary number can appear % + % before or after the "L" (which indicates a long number) % + % the "I" and "L" can be in either case % + + procedure nextChar ; charPos := charPos + 1; + logical procedure have( string(1) value ch ) ; + ( charPos <= maxChar and text(charPos//1) = ch ) ; + + logical procedure haveDigit ; + ( charPos <= maxChar and text(charPos//1) >= "0" and text(charPos//1) <= "9" ) ; + + + integer charPos, maxChar; + logical hadDigits, isReal; + charPos := 0; + maxChar := 31; + hadDigits := false; + isReal := false; + + % skip trailing spaces % + while maxChar > 0 and text(maxChar//1) = " " do maxChar := maxChar - 1; + % skip leading spacesx % + while have( " " ) do nextChar; + + % skip optional sign % + if have( "+" ) or have( "-" ) then nextChar; + + if haveDigit then begin + % have a digit sequence % + hadDigits := true; + while haveDigit do nextChar + end if_have_sign ; + + if have( "." ) then begin + % real or imaginary number % + nextChar; + isReal := true; + hadDigits := hadDigits or haveDigit; + while haveDigit do nextChar + end if_have_point ; + + % should have had some digits % + ok := hadDigits; + + if ok and have( "'" ) then begin + % the number has an exponent % + isReal := true; + nextChar; + % skip optional sign % + if have( "+" ) or have( "-" ) then nextChar; + % must have a digit sequence % + ok := haveDigit; + while haveDigit do nextChar; + end if_ok_and_have_exponent ; + + % if it is a real number, there could be L/I suffixes % + if ok and isReal then begin + integer LCount, ICount; + LCount := 0; + ICount := 0; + while have( "L" ) or have( "l" ) or have( "I" ) or have( "i" ) do begin + if have( "L" ) or have( "l" ) + then LCount := LCount + 1 + else ICount := ICount + 1; + nextChar + end while_have_L_or_I ; + % there can be at most one L and at most 1 I % + ok := ( LCount < 2 and ICount < 2 ) + end if_ok_and_isReal ; + + % must now be at the end if the number % + ok := ok and charPos >= maxChar + + end if_ok ; + + ok + end isNumeric ; + + + % test the isNumeric procedure % + procedure testIsNumeric( string(32) value n + ; logical value expectedResult + ) ; + begin + logical actualResult; + actualResult := isNumeric( n ); + write( s_w := 0 + , """", n, """ is " + , if actualResult then "" else "not " + , "numeric " + , if actualResult = expectedResult then "" else " NOT " + , "as expected" + ) + end testIsNumeric ; + + + testIsNumeric( "", false ); + testIsNumeric( "b", false ); + testIsNumeric( ".", false ); + testIsNumeric( ".'3", false ); + testIsNumeric( "3.'", false ); + testIsNumeric( "0.0z44", false ); + testIsNumeric( "-1IL", false ); + testIsNumeric( "4.5'23ILL", false ); + + write( "---------" ); + + testIsNumeric( "-1", true ); + testIsNumeric( " +.345", true ); + testIsNumeric( "4.5'23I", true ); + testIsNumeric( "-5'+3i", true ); + testIsNumeric( "-5'-3l", true ); + testIsNumeric( " -.345LI", true ); + +end. diff --git a/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir b/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir new file mode 100644 index 0000000000..a7381f48a5 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Elixir/determine-if-a-string-is-numeric.elixir @@ -0,0 +1,14 @@ +defmodule RC do + def is_numeric(str) do + case Float.parse(str) do + {_num, ""} -> true + {_num, _r} -> false # _r : remainder_of_bianry + :error -> false + end + end +end + +strs = ["123", "-12.3", "123.", ".05", "-12e5", "+123", " 123", "abc", "123a", "12.3e", "1 2"] +Enum.each(strs, fn str -> + IO.puts "#{inspect str}\t=> #{RC.is_numeric(str)}" +end) diff --git a/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia b/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia new file mode 100644 index 0000000000..71cc34b1a8 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia @@ -0,0 +1,23 @@ +function isnumeric{T<:String}(s::T) + isa(parse(s), Number) +end + +tests = ["1", + "-121", + "one", + "pi", + "1 + 1", + "NaN", + "1234567890123456789", + "1234567890123456789123456789", + "1234567890123456789123456789.0", + "1.3", + "1.4e10", + "Inf", + "1//2", + "1.0 + 1.0im"] + +for t in tests + fl = isnumeric(t) ? "is" : "is not" + println(@sprintf(" %35s %s a direct numeric literal.", t, fl)) +end diff --git a/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 b/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 index e7109f928d..34b7c53825 100644 --- a/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 +++ b/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 @@ -1,4 +1,4 @@ -my $name = $*PROGRAM_NAME; +my $name = $*PROGRAM-NAME; my $pid = $*PID; my $lockdir = "/tmp"; diff --git a/Task/Determine-if-only-one-instance-is-running/REXX/determine-if-only-one-instance-is-running.rexx b/Task/Determine-if-only-one-instance-is-running/REXX/determine-if-only-one-instance-is-running.rexx new file mode 100644 index 0000000000..9d924d919e --- /dev/null +++ b/Task/Determine-if-only-one-instance-is-running/REXX/determine-if-only-one-instance-is-running.rexx @@ -0,0 +1,18 @@ +/* Simple ARexx program to open a port after checking if it's already open */ +IF Show('PORTS','ROSETTA') THEN DO /* Port is already open; exit */ + SAY 'This program may only be run in a single instance at a time.' + EXIT 5 /* Exit with a mild warning */ + END + /* Open rexxsupport.library so that ports can be opened */ +IF ~Show('LIBRARIES','rexxsupport.library') + THEN CALL AddLib('rexxsupport.library',0,-30,0) + +IF ~OpenPort('ROSETTA') THEN EXIT 10 /* Open port, end if it fails */ + +SAY 'Program is now running.' + +DO FOREVER /* Busyloop */ + /* Program stuff here */ + END + +EXIT 0 diff --git a/Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.elixir b/Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.elixir new file mode 100644 index 0000000000..8e459c0f19 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Elixir/digital-root-multiplicative-digital-root.elixir @@ -0,0 +1,37 @@ +defmodule Digital do + def mdroot(n), do: mdroot(n, 0) + + defp mdroot(n, persist) when n < 10, do: {n, persist} + defp mdroot(n, persist), do: mdroot(product(n, 1), persist+1) + + defp product(0, prod), do: prod + defp product(n, prod), do: product(div(n, 10), prod*rem(n, 10)) + + def task1(data) do + IO.puts "Number: MDR MP\n====== === ==" + Enum.each(data, fn n -> + {mdr, persist} = mdroot(n) + :io.format "~6w: ~w ~2w~n", [n, mdr, persist] + end) + end + + def task2(m \\ 5) do + IO.puts "\nMDR: [n0..n#{m-1}]\n=== ========" + map = add_map(0, m, Map.new) + Enum.each(0..9, fn i -> + first = map[i] |> Enum.reverse |> Enum.take(m) + IO.puts " #{i}: #{inspect first}" + end) + end + + defp add_map(n, m, map) do + {mdr, _persist} = mdroot(n) + new_map = Dict.update(map, mdr, [n], fn vals -> [n | vals] end) + min_len = Dict.values(new_map) |> Enum.map(&length(&1)) |> Enum.min + if min_len < m, do: add_map(n+1, m, new_map), + else: new_map + end +end + +Digital.task1([123321, 7739, 893, 899998]) +Digital.task2(5) diff --git a/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.julia b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.julia new file mode 100644 index 0000000000..ae124d8ad9 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-1.julia @@ -0,0 +1,10 @@ +function digitalmultroot{S<:Integer,T<:Integer}(n::S, bs::T=10) + -1 < n && 1 < bs || throw(DomainError()) + ds = n + pers = 0 + while bs <= ds + ds = prod(digits(ds, bs)) + pers += 1 + end + return (pers, ds) +end diff --git a/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.julia b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.julia new file mode 100644 index 0000000000..98a205d2f9 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Julia/digital-root-multiplicative-digital-root-2.julia @@ -0,0 +1,34 @@ +const bs = 10 +const excnt = 5 + +println("Testing Multiplicative Digital Root.\n") +for i in [123321, 7739, 893, 899998] + (pers, ds) = digitalmultroot(i, bs) + print(@sprintf("%8d", i)) + print(" has persistence ", pers) + println(" and digital root ", ds) +end + +dmr = zeros(Int, bs, excnt) +hasroom = trues(bs) +dex = ones(Int, bs) + +i = 0 +while any(hasroom) + (pers, ds) = digitalmultroot(i, bs) + ds += 1 + if hasroom[ds] + dmr[ds, dex[ds]] = i + dex[ds] += 1 + if dex[ds] > excnt + hasroom[ds] = false + end + end + i += 1 +end + +println("\n MDR: First ", excnt, " numbers having this MDR") +for (i, d) in enumerate(0:(bs-1)) + print(@sprintf("%4d: ", d)) + println(join([@sprintf("%6d", dmr[i, j]) for j in 1:excnt], ",")) +end diff --git a/Task/Digital-root/ALGOL-W/digital-root.alg b/Task/Digital-root/ALGOL-W/digital-root.alg new file mode 100644 index 0000000000..4ecfc22151 --- /dev/null +++ b/Task/Digital-root/ALGOL-W/digital-root.alg @@ -0,0 +1,63 @@ +begin + + % calculates the digital root and persistence of an integer in base 10 % + % in order to allow for numbers larger than 2^31, the number is passed % + % as the lower and upper digits e.g. 393900588225 can be processed by % + % specifying upper = 393900, lower = 58825 % + procedure findDigitalRoot( integer value upper, lower + ; integer result digitalRoot, persistence + ) ; + begin + + integer procedure sumDigits( integer value n ) ; + begin + integer digits, sum; + + digits := abs n; + sum := 0; + + while digits > 0 + do begin + sum := sum + ( digits rem 10 ); + digits := digits div 10 + end % while digits > 0 % ; + + % result: % sum + end sumDigits; + + digitalRoot := sumDigits( upper ) + sumDigits( lower ); + persistence := 1; + + while digitalRoot > 9 + do begin + persistence := persistence + 1; + digitalRoot := sumDigits( digitalRoot ); + end % while digitalRoot > 9 % ; + + end findDigitalRoot ; + + % calculates and prints the digital root and persistence % + procedure printDigitalRootAndPersistence( integer value upper, lower ) ; + begin + integer digitalRoot, persistence; + findDigitalRoot( upper, lower, digitalRoot, persistence ); + write( s_w := 0 % set field saeparator width for this statement % + , i_w := 8 % set integer field width for this statement % + , upper + , ", " + , lower + , i_w := 2 % change integer field width % + , ": digital root: " + , digitalRoot + , ", persistence: " + , persistence + ) + end printDigitalRootAndPersistence ; + + % test the digital root and persistence procedures % + printDigitalRootAndPersistence( 0, 627615 ); + printDigitalRootAndPersistence( 0, 39390 ); + printDigitalRootAndPersistence( 0, 588225 ); + printDigitalRootAndPersistence( 393900, 588225 ) + +end. diff --git a/Task/Digital-root/Batch-File/digital-root.bat b/Task/Digital-root/Batch-File/digital-root.bat new file mode 100644 index 0000000000..0b4075a2c0 --- /dev/null +++ b/Task/Digital-root/Batch-File/digital-root.bat @@ -0,0 +1,44 @@ +:: +::Digital Root Task from Rosetta Code Wiki +::Batch File Implementation +:: +::Base 10... +:: + +@echo off +setlocal enabledelayedexpansion + +::THE MAIN THING... +for %%x in (9876543214 393900588225 1985989328582 34559) do ( + call :droot %%x +) +echo. +pause +exit /b +::/THE MAIN THING... + +::THE FUNCTION +:droot +set inp2sum=%1&set persist=1 + +:cyc1 +set sum=0 +set scan_digit=0 +:cyc2 +set digit=!inp2sum:~%scan_digit%,1! +if "%digit%"=="" (goto :sumdone) +set /a sum+=%digit% +set /a scan_digit+=1 +goto :cyc2 + +:sumdone +if %sum% lss 10 ( + echo. + echo ^(%1^) + echo Additive Persistence=%persist% Digital Root=%sum%. + goto :EOF +) +set /a persist+=1 +set inp2sum=%sum% +goto :cyc1 +::/THE FUNCTION diff --git a/Task/Digital-root/Befunge/digital-root.bf b/Task/Digital-root/Befunge/digital-root.bf new file mode 100644 index 0000000000..c5d7ec77ab --- /dev/null +++ b/Task/Digital-root/Befunge/digital-root.bf @@ -0,0 +1,8 @@ +0" :rebmun retnE">:#,_0 0v +v\1:/+55p00:55+%00g+^>9`+#v_+\ 1+\^ +>|`9:p000<_v#`1\$< v"gi"< +|> \ 1 + \ >0" :toor lat"^ +>$$00g\1+^@,+#+ 5< +>:#,_$ . 5 5 ^>:#,_\.55+,v +^"Additive Persistence: "< diff --git a/Task/Digital-root/DCL/digital-root.dcl b/Task/Digital-root/DCL/digital-root.dcl new file mode 100644 index 0000000000..df6205cd9b --- /dev/null +++ b/Task/Digital-root/DCL/digital-root.dcl @@ -0,0 +1,18 @@ +$ x = p1 +$ count = 0 +$ sum = x +$ loop1: +$ length = f$length( x ) +$ if length .eq. 1 then $ goto done +$ i = 0 +$ sum = 0 +$ loop2: +$ digit = f$extract( i, 1, x ) +$ sum = sum + digit +$ i = i + 1 +$ if i .lt. length then $ goto loop2 +$ x = f$string( sum ) +$ count = count + 1 +$ goto loop1 +$ done: +$ write sys$output p1, " has additive persistence ", count, " and digital root of ", sum diff --git a/Task/Digital-root/Elixir/digital-root.elixir b/Task/Digital-root/Elixir/digital-root.elixir new file mode 100644 index 0000000000..5937d61023 --- /dev/null +++ b/Task/Digital-root/Elixir/digital-root.elixir @@ -0,0 +1,25 @@ +defmodule Digital do + def root(n, base \\ 10), do: root(n, base, 0) + + def root(n, base, ap) when n < base, do: {n, ap} + def root(n, base, ap) do + Integer.to_string(n, base) + |> String.codepoints + |> Enum.reduce(0, fn x,acc -> acc + String.to_integer(x, base) end) + |> root(base, ap+1) + end +end + +data = [627615, 39390, 588225, 393900588225] +Enum.each(data, fn n -> + {dr, ap} = Digital.root(n) + IO.puts "#{n} has additive persistence #{ap} and digital root of #{dr}" +end) + +base = 16 +IO.puts "\nBase = #{base}" +fmt = "~.#{base}B(#{base}) has additive persistence ~w and digital root of ~w~n" +Enum.each(data, fn n -> + {dr, ap} = Digital.root(n, base) + :io.format fmt, [n, ap, dr] +end) diff --git a/Task/Digital-root/Julia/digital-root.julia b/Task/Digital-root/Julia/digital-root.julia new file mode 100644 index 0000000000..fcb5e22b15 --- /dev/null +++ b/Task/Digital-root/Julia/digital-root.julia @@ -0,0 +1,15 @@ +function digitalroot{S<:Integer,T<:Integer}(n::S, bs::T=10) + -1 < n && 1 < bs || throw(DomainError()) + ds = n + pers = 0 + while bs <= ds + ds = sum(digits(ds, bs)) + pers += 1 + end + return (pers, ds) +end + +for i in {627615, 39390, 588225, 393900588225, big(2)^100} + (pers, ds) = digitalroot(i) + println(i, " has persistence ", pers, " and digital root ", ds) +end diff --git a/Task/Digital-root/Python/digital-root.py b/Task/Digital-root/Python/digital-root.py index 53491cb521..1e12753de0 100644 --- a/Task/Digital-root/Python/digital-root.py +++ b/Task/Digital-root/Python/digital-root.py @@ -1,10 +1,13 @@ -def droot (n): - x = [n] - while x[-1] > 10: - x.append(sum(int(dig) for dig in str(x[-1]))) - return len(x) - 1, x[-1] +def digital_root (n): + ap = 0 + n = abs(int(n)) + while n >= 10: + n = sum(int(digit) for digit in str(n)) + ap += 1 + return ap, n -for n in [627615, 39390, 588225, 393900588225]: - a, d = droot (n) - print "%12i has additive persistance %2i and digital root of %i" % ( - n, a, d) +if __name__ == '__main__': + for n in [627615, 39390, 588225, 393900588225, 55]: + persistance, root = digital_root(n) + print("%12i has additive persistance %2i and digital root %i." + % (n, persistance, root)) diff --git a/Task/Digital-root/VBScript/digital-root.vb b/Task/Digital-root/VBScript/digital-root.vb new file mode 100644 index 0000000000..11eb475c91 --- /dev/null +++ b/Task/Digital-root/VBScript/digital-root.vb @@ -0,0 +1,15 @@ +Function digital_root(n) + ap = 0 + Do Until Len(n) = 1 + x = 0 + For i = 1 To Len(n) + x = x + CInt(Mid(n,i,1)) + Next + n = x + ap = ap + 1 + Loop + digital_root = "Additive Persistence = " & ap & vbCrLf &_ + "Digital Root = " & n & vbCrLf +End Function + +WScript.StdOut.Write digital_root(WScript.Arguments(0)) diff --git a/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION b/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION index 5248139f09..27764ac02c 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION +++ b/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION @@ -1,5 +1,5 @@ {{omit from|GUISS}} -The task is to '''solve Dinesman's multiple dwelling [http://www-mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3.2 problem] but in a way that most naturally follows the problem statement given below'''. +The task is to '''solve Dinesman's multiple dwelling [http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3.2 problem] but in a way that most naturally follows the problem statement given below'''. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. diff --git a/Task/Dinesmans-multiple-dwelling-problem/Elixir/dinesmans-multiple-dwelling-problem.elixir b/Task/Dinesmans-multiple-dwelling-problem/Elixir/dinesmans-multiple-dwelling-problem.elixir new file mode 100644 index 0000000000..58d1bd541e --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Elixir/dinesmans-multiple-dwelling-problem.elixir @@ -0,0 +1,27 @@ +defmodule Dinesman do + def problem do + names = ~w( Baker Cooper Fletcher Miller Smith )a + predicates = [fn(c)-> :Baker != List.last(c) end, + fn(c)-> :Cooper != List.first(c) end, + fn(c)-> :Fletcher != List.first(c) && :Fletcher != List.last(c) end, + fn(c)-> floor(c, :Miller) > floor(c, :Cooper) end, + fn(c)-> abs(floor(c, :Smith) - floor(c, :Fletcher)) != 1 end, + fn(c)-> abs(floor(c, :Cooper) - floor(c, :Fletcher)) != 1 end] + + permutation(names) + |> Enum.filter(fn candidate -> + Enum.all?(predicates, fn predicate -> predicate.(candidate) end) + end) + |> Enum.each(fn name_list -> + Enum.with_index(name_list) + |> Enum.each(fn {name,i} -> IO.puts "#{name} lives on #{i+1}" end) + end) + end + + defp floor(c, name), do: Enum.find_index(c, fn x -> x == name end) + + defp permutation([]), do: [[]] + defp permutation(list), do: (for x <- list, y <- permutation(list -- [x]), do: [x|y]) +end + +Dinesman.problem diff --git a/Task/Dinesmans-multiple-dwelling-problem/UNIX-Shell/dinesmans-multiple-dwelling-problem.sh b/Task/Dinesmans-multiple-dwelling-problem/UNIX-Shell/dinesmans-multiple-dwelling-problem.sh index 2703a33864..d693852ba8 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/UNIX-Shell/dinesmans-multiple-dwelling-problem.sh +++ b/Task/Dinesmans-multiple-dwelling-problem/UNIX-Shell/dinesmans-multiple-dwelling-problem.sh @@ -1,15 +1,21 @@ #!/bin/bash +# NAMES is a list of names. It can be changed as needed. It can be more than five names, or less. NAMES=(Baker Cooper Fletcher Miller Smith) +# CRITERIA are the rules imposed on who lives where. Each criterion must be a valid bash expression +# that will be evaluated. TOP is the top floor; BOTTOM is the bottom floor. + +# The CRITERIA can be changed to create different rules. + CRITERIA=( - 'Baker != TOP' - 'Cooper != BOTTOM' - 'Fletcher != TOP' - 'Fletcher != BOTTOM' - 'Miller > Cooper' - '$(abs $(( Smith - Fletcher )) ) > 1' - '$(abs $(( Fletcher - Cooper )) ) > 1' + 'Baker != TOP' # Baker does not live on the top floor + 'Cooper != BOTTOM' # Cooper does not live on the bottom floor + 'Fletcher != TOP' # Fletcher does not live on the top floor + 'Fletcher != BOTTOM' # and Fletch also does not live on the bottom floor + 'Miller > Cooper' # Miller lives above Cooper + '$(abs $(( Smith - Fletcher )) ) > 1' # Smith and Fletcher are not on adjacent floors + '$(abs $(( Fletcher - Cooper )) ) > 1' # Fletcher and Cooper are not on adjacent floors ) # Code below here shouldn't need to change to vary parameters @@ -17,11 +23,7 @@ let BOTTOM=0 let TOP=${#NAMES[@]}-1 # Not available as a builtin -function abs { - let n=$1 - if (( n < 0 )); then let n=-n; fi - echo "$n" -} +abs() { local n=$(( 10#$1 )) ; echo $(( n < 0 ? -n : n )) ; } # Algorithm we use to iterate over the permutations # requires that we start with the array sorted lexically diff --git a/Task/Dining-philosophers/C++/dining-philosophers.cpp b/Task/Dining-philosophers/C++/dining-philosophers-1.cpp similarity index 100% rename from Task/Dining-philosophers/C++/dining-philosophers.cpp rename to Task/Dining-philosophers/C++/dining-philosophers-1.cpp diff --git a/Task/Dining-philosophers/C++/dining-philosophers-2.cpp b/Task/Dining-philosophers/C++/dining-philosophers-2.cpp new file mode 100644 index 0000000000..12abd43ac3 --- /dev/null +++ b/Task/Dining-philosophers/C++/dining-philosophers-2.cpp @@ -0,0 +1,129 @@ +#include +#include +#include +#include +//We are using only standard library, so snprintf instead of Boost::Format +#include +#include +#include +#include +#include +#include + +std::mutex cout_mutex; + +struct Fork { + std::mutex mutex; +}; + +struct Dinner { + std::atomic ready {false}; + std::array forks; + ~Dinner() { std::cout << "Dinner is over"; } +}; + +class Philosopher +{ + std::mt19937 rng{std::random_device {}()}; + + const std::string name; + const Dinner& dinner; + Fork& left; + Fork& right; + std::thread worker; + + void live(); + void dine(); + void ponder(); + public: + Philosopher(std::string name_, const Dinner& dinn, Fork& l, Fork& r) + : name(std::move(name_)), dinner(dinn) , left(l), right(r), worker(&Philosopher::live, this) + {} + ~Philosopher() + { + worker.join(); + std::lock_guard cout_lock(cout_mutex); + std::cout << name << " went to sleep." << std::endl; + } +}; + +void Philosopher::live() +{ + while (not dinner.ready) + ; //You spin me right round, baby, right round... + do {//Aquire forks first + //lock uses deadlock prevention mechanism to acquire mutexes safely + std::lock(left.mutex, right.mutex); + dine(); //Dine adopts lock on forks and releases them + if(not dinner.ready) break; + ponder(); + } while(dinner.ready); +} + +void Philosopher::dine() +{ + std::lock_guard left_lock( left.mutex, std::adopt_lock); + std::lock_guard right_lock(right.mutex, std::adopt_lock); + + thread_local std::array foods {{"chicken", "rice", "soda"}}; + thread_local std::array reactions {{ + "I like this %s!", "This %s is good.", "Mmm, %s..." + }}; + thread_local std::uniform_int_distribution<> dist(1, 6); + std::shuffle( foods.begin(), foods.end(), rng); + std::shuffle(reactions.begin(), reactions.end(), rng); + + if(not dinner.ready) return; + { + std::lock_guard cout_lock(cout_mutex); + std::cout << name << " started eating." << std::endl; + } + constexpr size_t buf_size = 64; + char buffer[buf_size]; + for(int i = 0; i < 3; ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng)*50)); + snprintf(buffer, buf_size, reactions[i], foods[i]); + std::lock_guard cout_lock(cout_mutex); + std::cout << name << ": " << buffer << std::endl; + } + std::this_thread::sleep_for(std::chrono::milliseconds(dist(rng))*50); + std::lock_guard cout_lock(cout_mutex); + std::cout << name << " finished and left." << std::endl; +} + +void Philosopher::ponder() +{ + static constexpr std::array topics {{ + "politics", "art", "meaning of life", "source of morality", "how many straws makes a bale" + }}; + thread_local std::uniform_int_distribution<> wait(1, 6); + thread_local std::uniform_int_distribution<> dist(0, topics.size() - 1); + while(dist(rng) > 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng)*150)); + std::lock_guard cout_lock(cout_mutex); + std::cout << name << " is pondering about " << topics[dist(rng)] << '.' << std::endl; + if(not dinner.ready) return; + } + std::this_thread::sleep_for(std::chrono::milliseconds(wait(rng)*150)); + std::lock_guard cout_lock(cout_mutex); + std::cout << name << " is hungry again!" << std::endl; +} + +int main() +{ + Dinner dinner; + std::array philosophers {{ + {"Aristotle", dinner, dinner.forks[0], dinner.forks[1]}, + {"Kant", dinner, dinner.forks[1], dinner.forks[2]}, + {"Spinoza", dinner, dinner.forks[2], dinner.forks[3]}, + {"Marx", dinner, dinner.forks[3], dinner.forks[4]}, + {"Russell", dinner, dinner.forks[4], dinner.forks[0]}, + }}; + std::this_thread::sleep_for(std::chrono::seconds(1)); + std::cout << "Dinner started!" << std::endl; + dinner.ready = true; + std::this_thread::sleep_for(std::chrono::seconds(5)); + dinner.ready = false; + std::lock_guard cout_lock(cout_mutex); + std::cout << "It is dark outside..." << std::endl; +} diff --git a/Task/Dining-philosophers/Perl-6/dining-philosophers.pl6 b/Task/Dining-philosophers/Perl-6/dining-philosophers.pl6 index f99a013338..605714ad4b 100644 --- a/Task/Dining-philosophers/Perl-6/dining-philosophers.pl6 +++ b/Task/Dining-philosophers/Perl-6/dining-philosophers.pl6 @@ -1,11 +1,11 @@ class Fork { has $!lock = Lock.new; method grab($who, $which) { - remark "$who grabbing $which fork"; + say "$who grabbing $which fork"; $!lock.lock; } method drop($who, $which) { - remark "$who dropping $which fork"; + say "$who dropping $which fork"; $!lock.unlock; } } @@ -16,10 +16,6 @@ class Lollipop { method yours { $!channel.receive } } -my $out = Channel.new; -sub remark($msg) { $out.send($msg) } -start { loop { $out.receive.say } } - sub dally($sec) { sleep 0.01 + rand * $sec } sub MAIN(*@names) { @@ -31,25 +27,25 @@ sub MAIN(*@names) { my $lollipop = Lollipop.new; start { $lollipop.yours; } - my @philosophers = do for @names Z @lfork Z @rfork -> $n, $l, $r { + my @philosophers = do for flat @names Z @lfork Z @rfork -> $n, $l, $r { start { sleep 1 + rand*4; loop { $l.grab($n,'left'); dally 1; # give opportunity for deadlock $r.grab($n,'right'); - remark "$n eating"; + say "$n eating"; dally 10; $l.drop($n,'left'); $r.drop($n,'right'); $lollipop.mine($n); sleep 1; # lick at least once - remark "$n lost lollipop to $lollipop.yours(), now digesting"; + say "$n lost lollipop to $lollipop.yours(), now digesting"; dally 20; } } } - await @philosophers; + sink await @philosophers; } diff --git a/Task/Dining-philosophers/REXX/dining-philosophers.rexx b/Task/Dining-philosophers/REXX/dining-philosophers.rexx index b70116e42a..95e5bee11f 100644 --- a/Task/Dining-philosophers/REXX/dining-philosophers.rexx +++ b/Task/Dining-philosophers/REXX/dining-philosophers.rexx @@ -1,48 +1,48 @@ -/*REXX prm demonstrates a solution to solve dining philosophers problem.*/ -parse arg seed diners /*get optional arguments from CL.*/ -if seed\=='' & seed\==',' then call random ,, seed /*for repeatability*/ -if diners='' then diners='Aristotle,Kant,Spinoza,Marx,Russell' -tell=left(seed,1)\=='+' /*Leading + in SEED? No stats.*/ -diners=translate(diners,,',') /*change a commatized diners list*/ -#=words(diners); @.=0 /*the number of dining philospers*/ - eatL=15; eatH= 60 /*min & max minutes for eating. */ -thinkL=30; thinkH=180 /* " " " " " thinking.*/ -forks.=1 /*indicate all forks are on table*/ - do tic=1 /*use minutes as time advancement*/ - call grabForks /*see if anybody can grab 2 forks*/ - call passTime /*handle diners eating | thinking*/ - end /*tic*/ /* ··· and time marches on ··· */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FORK subroutine─────────────────────*/ -fork: parse arg x 1 ox; x=abs(x); L=x-1; if L==0 then L=# /*boundry ? */ -if ox<0 then do; forks.L=1; forks.x=1; return; end /*drop forks*/ -got2=forks.L & forks.x /*did we get two forks or not? */ -if got2 then do; forks.L=0; forks.x=0; end /*got forks.*/ -return got2 /*return with success or failure.*/ -/*──────────────────────────────────GRABFORKS subroutine────────────────*/ -grabForks: do person=1 for # /*see if any person can grab two.*/ - if @.person.status\==0 then iterate /*diner ain't waiting*/ - if \fork(person) then iterate /*diner didn't grab 2*/ - @.person.status='eating' /*diner now chomps on spaghetti. */ - @.person.dur=random(eatL,eatH) /*how long will diner eat? */ - end /*person*/ +/*REXX pgm demonstrates a solution in solving the dining philosophers problem.*/ +signal on halt /*branches to HALT: (on Ctrl─break).*/ +parse arg seed diners /*obtain optional arguments from the CL*/ +if datatype(seed,'W') then call random ,, seed /*for random repeatability.*/ +if diners='' then diners = 'Aristotle, Kant, Spinoza, Marx, Russell' + tell=(left(seed,1)\=='+') /*Leading + in SEED? Then no statistics*/ +diners=space(translate(diners,,',')) /*change to an uncommatized diners list*/ + #=words(diners); @.= 0 /*#: the number of dining philosophers.*/ + eatL=15; eatH= 60 /*minimum & maximum minutes for eating.*/ +thinkL=30; thinkH=180 /* " " " " " thinking*/ +forks.=1 /*indicate that all forks are on table.*/ + do tic=1 /*'til halted.*/ /*use "minutes" for time advancement.*/ + call grabForks /*determine if anybody can grab 2 forks*/ + call passTime /*handle philosophers eating|thinking. */ + end /*tic*/ /* ··· and time marches on ··· */ + /* [↓] this REXX program was halted,*/ +halt: say ' ··· REXX program halted!' /*probably by Ctrl─Break or equivalent.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────FORK subroutine───────────────────────────*/ +fork: parse arg x 1 ox; x=abs(x); L=x-1; if L==0 then L=# /*on a boundary? */ +if ox<0 then do; forks.L=1; forks.x=1; return; end /*drop the forks.*/ +got2=forks.L & forks.x /*get 2 forks │ ¬*/ +if got2 then do; forks.L=0; forks.x=0; end /*got two forks. */ +return got2 /*return with success ··· or failure. */ +/*──────────────────────────────────GRABFORKS subroutine──────────────────────*/ +grabForks: do person=1 for # /*see if any person can grab two forks.*/ + if @.person.state\==0 then iterate /*the diner ain't waiting. */ + if \fork(person) then iterate /*the diner didn't grab 2. */ + @.person.state= 'eating' /*diner spaghetti slurping.*/ + @.person.dur=random(eatL,eatH) /*how long will diner eat? */ + end /*person*/ /* [↑] handle all diners. */ return -/*──────────────────────────────────PASSTIME subroutine─────────────────*/ -passTime: if tell then say /*show a (blank line) separator. */ - do p=1 for # /*process each diner's activity. */ - if tell then say right(tic,9,'.') right(word(diners,p),20), - right(word(@.p.status 'waiting',1+(@.p.status==0)),9) right(@.p.dur,5) - if @.p.dur==0 then iterate /*diner is waiting for two forks.*/ - @.p.dur=@.p.dur-1 /*indicate 1 timeUnit has gone by*/ - if @.p.dur\==0 then iterate /*Activity done? No, keep it up.*/ - select /*handle the activity being done.*/ - when @.p.status=='eating' then do /*now, leave the table.*/ - call fork -p /*drop the forks.*/ - @.p.status='thinking' /*status.*/ - @.p.dur=random(thinkL,thinkH) - end - when @.p.status=='thinking' then @.p.status=0 /*──► table*/ - otherwise nop /*diner must be waiting on forks.*/ - end /*select*/ - end /*p*/ +/*──────────────────────────────────PASSTIME subroutine───────────────────────*/ +passTime: if tell then say /*display a handy blank line separator.*/ + do p=1 for # /*handle each of the diner's activity. */ + if tell then say right(tic,9,.) right(word(diners,p),20), + right(word(@.p.state 'waiting', 1+(@.p.state==0)),9) right(@.p.dur,5) + if @.p.dur==0 then iterate /*this diner is waiting for two forks. */ + @.p.dur=@.p.dur - 1 /*indicate single time unit has passed.*/ + if @.p.dur\==0 then iterate /*Activity done? No, then keep it up.*/ + if @.p.state=='eating' then do /*now, leave the table.*/ + call fork -p /*drop the darn forks. */ + @.p.state='thinking' /*status.*/ + @.p.dur=random(thinkL,thinkH) /*length.*/ + end /* [↓] diner ──► the table.*/ + else if @.p.state=='thinking' then @.p.state=0 + end /*p*/ /*[↑] P (person) ≡dining philosophers.*/ return diff --git a/Task/Dining-philosophers/Rust/dining-philosophers.rust b/Task/Dining-philosophers/Rust/dining-philosophers.rust index 0ef57df899..aca4bf00cb 100644 --- a/Task/Dining-philosophers/Rust/dining-philosophers.rust +++ b/Task/Dining-philosophers/Rust/dining-philosophers.rust @@ -1,99 +1,63 @@ -extern mod extra; -use std::rt::io::timer; -use extra::comm::DuplexStream; +use std::thread; +use std::sync::{Mutex, Arc}; -fn phil(phil: ~str, diner: &DuplexStream, firstChopstick: int, secondChopstick: int) -{ - let mut sleep_time: u64; - print(fmt!("%s sat down\n", phil)); - for _ in range(1,3) - { - print(fmt!("%s is thinking\n", phil)); - sleep_time = std::rand::random(); - timer::sleep((sleep_time%5)*500); - print(fmt!("%s is hungry\n", phil)); - //get left chopstick - diner.send(firstChopstick); - let mut recv: int = diner.recv(); - while recv == 0 - { - diner.send(firstChopstick); - recv = diner.recv(); - } - print(fmt!("%s picked up his left chopstick\n", phil)); - //get right chopstick - diner.send(secondChopstick); - recv = diner.recv(); - while recv == 0 - { - diner.send(secondChopstick); - recv = diner.recv(); +struct Philosopher { + name: String, + left: usize, + right: usize, +} + +impl Philosopher { + fn new(name: &str, left: usize, right: usize) -> Philosopher { + Philosopher { + name: name.to_string(), + left: left, + right: right, } - print(fmt!("%s picked up his right chopstick\n", phil)); - //eat - print(fmt!("%s is eating...\n", phil)); - sleep_time = std::rand::random(); - timer::sleep((sleep_time%3)*500); - print(fmt!("%s is done eating\n", phil)); - //set down left chopstick - print(fmt!("%s set down his left chopstick\n", phil)); - diner.send(-1*firstChopstick); - //set down right chopstick - print(fmt!("%s set down his right chopstick\n", phil)); - diner.send(-1*secondChopstick); + } + + fn eat(&self, table: &Table) { + let _left = table.forks[self.left].lock().unwrap(); + let _right = table.forks[self.right].lock().unwrap(); + + println!("{} is eating.", self.name); + thread::sleep_ms(1000); + + println!("{} is done eating.", self.name); } - diner.send(0); - diner.recv(); - print(fmt!("%s has exited\n", phil)); } -fn main() -{ - //set the table: - //false means chopstick is on the table - //true means chopstick is taken - let mut chopsticks: ~[bool] = ~[false, false, false, false, false]; +struct Table { + forks: Vec>, +} - //diner_ will try to take resources from the table, host_ - //will respond with whether that action was successful. - let (diner1, host1) = DuplexStream(); - let (diner2, host2) = DuplexStream(); - let (diner3, host3) = DuplexStream(); - let (diner4, host4) = DuplexStream(); - let (diner5, host5) = DuplexStream(); +fn main() { + let table = Arc::new(Table { forks: vec![ + Mutex::new(()), + Mutex::new(()), + Mutex::new(()), + Mutex::new(()), + Mutex::new(()), + ]}); - //Make the first 4 "right-handed" philosophers - do spawn{ phil(~"Hobbes", &diner1, 1, 2); } - do spawn{ phil(~"Locke", &diner2, 2, 3); } - do spawn{ phil(~"Machiavelli", &diner3, 3, 4); } - do spawn{ phil(~"Montesquieu", &diner4, 4, 5); } - //Make the last, "left-handed" philosopher - do spawn{ phil(~"Rousseau", &diner5, 1, 5); } + let philosophers = vec![ + Philosopher::new("Baruch Spinoza", 0, 1), + Philosopher::new("Gilles Deleuze", 1, 2), + Philosopher::new("Karl Marx", 2, 3), + Philosopher::new("Friedrich Nietzsche", 3, 4), + Philosopher::new("Michel Foucault", 0, 4), + ]; - //keep track of number of people still at the table - let mut remaining = 5; - while remaining > 0 - { - matchReq(&mut chopsticks, &host1, &mut remaining); - matchReq(&mut chopsticks, &host2, &mut remaining); - matchReq(&mut chopsticks, &host3, &mut remaining); - matchReq(&mut chopsticks, &host4, &mut remaining); - matchReq(&mut chopsticks, &host5, &mut remaining); - std::task::deschedule(); - } -} + let handles: Vec<_> = philosophers.into_iter().map(|p| { + let table = table.clone(); -fn matchReq(chopsticks: &mut ~[bool], host: &DuplexStream, remaining: &mut int) { - if (host.peek()) - { - let from = host.try_recv(); - match from - { - Some(0) => { *remaining += -1; host.try_send(0); return; }, - Some(x) if x > 0 => { if(chopsticks[x-1]) { host.send(0); } else { chopsticks[x-1] = true; host.send(1); } }, - Some(x) => { chopsticks[(-x)-1] = false; }, - None => { *remaining += -1; host.try_send(0); return; } - } + thread::spawn(move || { + p.eat(&table); + }) + }).collect(); + + for h in handles { + h.join().unwrap(); } } diff --git a/Task/Discordian-date/00META.yaml b/Task/Discordian-date/00META.yaml index 776d3a14cc..0b8885a678 100644 --- a/Task/Discordian-date/00META.yaml +++ b/Task/Discordian-date/00META.yaml @@ -1,4 +1,2 @@ --- -category: -- Date and time -note: Discordian date +note: Date and time diff --git a/Task/Discordian-date/BASIC/discordian-date.basic b/Task/Discordian-date/BASIC/discordian-date.basic index 4afb668ee1..41211c744b 100644 --- a/Task/Discordian-date/BASIC/discordian-date.basic +++ b/Task/Discordian-date/BASIC/discordian-date.basic @@ -2,7 +2,6 @@ DECLARE FUNCTION julian(AS DOUBLE) AS INTEGER - SeasonNames: DATA "Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath" Weekdays: @@ -26,7 +25,7 @@ IF (2 = MONTH(tmpdate)) AND (29 = DAY(tmpdate)) THEN ELSE jday = julian(tmpdate) RESTORE SeasonNames - FOR L0 = 1 TO (jday \ 73) + 1 + FOR L0 = 1 TO ((jday - 1) \ 73) + 1 READ dseason NEXT dday = (jday MOD 73) diff --git a/Task/Discordian-date/Befunge/discordian-date.bf b/Task/Discordian-date/Befunge/discordian-date.bf new file mode 100644 index 0000000000..2ad0be559a --- /dev/null +++ b/Task/Discordian-date/Befunge/discordian-date.bf @@ -0,0 +1,5 @@ +0" :raeY">:#,_&>\" :htnoM">:#,_&>04p" :yaD">:#,_$&>55+,1-:47*v +v"f I".+1%,,,,"Day I":$_:#<0#!4#:p#-4#1g4-#0+#<<_v#!*!-2g40!-< +>"o",,,/:5+*66++:4>g#<:#44#:9#+*#1-#,_$$0 v_v#!< >$ 0 "yaD " v +@,+55.+*+92"j"$_,#!>#:<", in the YOLD"*84 <.>,:^ :"St. Tib's"< +$# #"#"##"#"Chaos$Discord$Confusion$Bureaucracy$The Aftermath$ diff --git a/Task/Discordian-date/C++/discordian-date.cpp b/Task/Discordian-date/C++/discordian-date.cpp index d247785801..b4717eb2b2 100644 --- a/Task/Discordian-date/C++/discordian-date.cpp +++ b/Task/Discordian-date/C++/discordian-date.cpp @@ -2,75 +2,85 @@ #include #include #include - -//-------------------------------------------------------------------------------------------------- +#include using namespace std; - -//-------------------------------------------------------------------------------------------------- class myTuple { public: void set( int a, int b, string c ) { t.first.first = a; t.first.second = b; t.second = c; } bool operator == ( pair p ) { return p.first == t.first.first && p.second == t.first.second; } - string second(){ return t.second; } + string second() { return t.second; } private: pair, string> t; }; -//-------------------------------------------------------------------------------------------------- class discordian { public: - discordian() - { - myTuple t; - t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t ); - t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t ); - t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t ); - t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t ); - t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t ); - t.set( 8, 12, "Afflux" ); holyday.push_back( t ); - seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" ); - seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" ); - wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" ); - wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" ); + discordian() { + myTuple t; + t.set( 5, 1, "Mungday" ); holyday.push_back( t ); t.set( 19, 2, "Chaoflux" ); holyday.push_back( t ); + t.set( 29, 2, "St. Tib's Day" ); holyday.push_back( t ); t.set( 19, 3, "Mojoday" ); holyday.push_back( t ); + t.set( 3, 5, "Discoflux" ); holyday.push_back( t ); t.set( 31, 5, "Syaday" ); holyday.push_back( t ); + t.set( 15, 7, "Confuflux" ); holyday.push_back( t ); t.set( 12, 8, "Zaraday" ); holyday.push_back( t ); + t.set( 26, 9, "Bureflux" ); holyday.push_back( t ); t.set( 24, 10, "Maladay" ); holyday.push_back( t ); + t.set( 8, 12, "Afflux" ); holyday.push_back( t ); + seasons.push_back( "Chaos" ); seasons.push_back( "Discord" ); seasons.push_back( "Confusion" ); + seasons.push_back( "Bureaucracy" ); seasons.push_back( "The Aftermath" ); + wdays.push_back( "Setting Orange" ); wdays.push_back( "Sweetmorn" ); wdays.push_back( "Boomtime" ); + wdays.push_back( "Pungenday" ); wdays.push_back( "Prickle-Prickle" ); } - - void convert( int d, int m, int y ) - { - if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { cout << "\nThis is not a date!"; return; } - pair p; p.first = d, p.second = m; vector::iterator f; - f = find( holyday.begin(), holyday.end(), p ); int dd = 0, day, wday, mon, yr = y + 1166; - if( d == 29 && m == 2 && isLeap( y ) ) - { cout << ( *f ).second() << ", Year of Our Lady of Discord " << yr; return; } - for( int x = 1; x < m; x++ ) dd += getMaxDay( x, 1 ); dd += d; day = dd % 73; wday = dd % 5; mon = dd / 73; - cout << wdays[wday] << ", " << seasons[mon] << " " << day << ", Year of Our Lady of Discord " << yr; - if( f != holyday.end() ) cout << " - " << ( *f ).second(); + void convert( int d, int m, int y ) { + if( d == 0 || m == 0 || m > 12 || d > getMaxDay( m, y ) ) { + cout << "\nThis is not a date!"; + return; + } + vector::iterator f = find( holyday.begin(), holyday.end(), make_pair( d, m ) ); + int dd = d, day, wday, sea, yr = y + 1166; + for( int x = 1; x < m; x++ ) + dd += getMaxDay( x, 1 ); + day = dd % 73; if( !day ) day = 73; + wday = dd % 5; + sea = ( dd - 1 ) / 73; + if( d == 29 && m == 2 && isLeap( y ) ) { + cout << ( *f ).second() << " " << seasons[sea] << ", Year of Our Lady of Discord " << yr; + return; + } + cout << wdays[wday] << " " << seasons[sea] << " " << day; + if( day > 10 && day < 14 ) cout << "th"; + else switch( day % 10) { + case 1: cout << "st"; break; + case 2: cout << "nd"; break; + case 3: cout << "rd"; break; + default: cout << "th"; + } + cout << ", Year of Our Lady of Discord " << yr; + if( f != holyday.end() ) cout << " - " << ( *f ).second(); } - private: - int getMaxDay( int m, int y ) - { int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; } - - bool isLeap( int y ) - { bool l = false; if( !( y % 4 ) ) { if( y % 100 ) l = true; else if( !( y % 400 ) ) l = true; } return l; } - + int getMaxDay( int m, int y ) { + int dd[] = { 0, 31, isLeap( y ) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; return dd[m]; + } + bool isLeap( int y ) { + bool l = false; + if( !( y % 4 ) ) { + if( y % 100 ) l = true; + else if( !( y % 400 ) ) l = true; + } + return l; + } vector holyday; vector seasons, wdays; }; -//-------------------------------------------------------------------------------------------------- -int main( int argc, char* argv[] ) -{ +int main( int argc, char* argv[] ) { string date; discordian disc; - while( true ) - { - cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break; - if( date.length() == 10 ) - { - istringstream iss( date ); vector vc; - copy( istream_iterator( iss ), istream_iterator(), back_inserter >( vc ) ); - disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); cout << "\n\n\n"; - } - else cout << "\nIs this a date?!\n\n"; + while( true ) { + cout << "Enter a date (dd mm yyyy) or 0 to quit: "; getline( cin, date ); if( date == "0" ) break; + if( date.length() == 10 ) { + istringstream iss( date ); + vector vc; + copy( istream_iterator( iss ), istream_iterator(), back_inserter >( vc ) ); + disc.convert( atoi( vc[0].c_str() ), atoi( vc[1].c_str() ), atoi( vc[2].c_str() ) ); + cout << "\n\n\n"; + } else cout << "\nIs this a date?!\n\n"; } return 0; } -//-------------------------------------------------------------------------------------------------- diff --git a/Task/Discordian-date/J/discordian-date-2.j b/Task/Discordian-date/J/discordian-date-2.j index b8daed7f89..266af672ac 100644 --- a/Task/Discordian-date/J/discordian-date-2.j +++ b/Task/Discordian-date/J/discordian-date-2.j @@ -8,3 +8,9 @@ 3178 5 73j1 disc 2013 1 1 3179 1 1 + disc 2100 12 31 +3266 5 73 + disc 2015 10 19 +3181 4 73 + disc 2000 3 13 +3166 1 72j1 diff --git a/Task/Discordian-date/Java/discordian-date.java b/Task/Discordian-date/Java/discordian-date.java index 18be9a8483..3deb9ebf86 100644 --- a/Task/Discordian-date/Java/discordian-date.java +++ b/Task/Discordian-date/Java/discordian-date.java @@ -16,39 +16,43 @@ public class DiscordianDate { "Bureflux", "Afflux"}; public static String discordianDate(final GregorianCalendar date) { - int y = date.get(Calendar.YEAR) + 1166; - int m = date.get(Calendar.MONTH); - int d = date.get(Calendar.DATE); + int y = date.get(Calendar.YEAR); + int yold = y + 1166; + int dayOfYear = date.get(Calendar.DAY_OF_YEAR); - if (date.isLeapYear(y) && m == 2 && d == 29) - return "St. Tib's Day, in the YOLD " + y; + if (date.isLeapYear(y)) { + if (dayOfYear == 60) + return "St. Tib's Day, in the YOLD " + yold; + else if (dayOfYear > 60) + dayOfYear--; + } - int dayOfYear = date.get(Calendar.DAY_OF_YEAR); - if (date.isLeapYear(y) && dayOfYear >= 60) - dayOfYear--; + dayOfYear--; - int seasonDay = dayOfYear % 73; + int seasonDay = dayOfYear % 73 + 1; if (seasonDay == 5) - return apostle[dayOfYear / 73] + ", in the YOLD " + y; + return apostle[dayOfYear / 73] + ", in the YOLD " + yold; if (seasonDay == 50) - return holiday[dayOfYear / 73] + ", in the YOLD " + y; + return holiday[dayOfYear / 73] + ", in the YOLD " + yold; String season = seasons[dayOfYear / 73]; - String dayOfWeek = weekday[(dayOfYear - 1) % 5]; + String dayOfWeek = weekday[dayOfYear % 5]; return String.format("%s, day %s of %s in the YOLD %s", - dayOfWeek, seasonDay, season, y); + dayOfWeek, seasonDay, season, yold); } public static void main(String[] args) { + System.out.println(discordianDate(new GregorianCalendar())); - test(2010, 7, 22, "Pungenday, day 57 of Confusion in the YOLD 3176"); - test(2012, 2, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178"); - test(2012, 2, 29, "St. Tib's Day, in the YOLD 3178"); - test(2012, 3, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178"); - test(2010, 1, 5, "Mungday, in the YOLD 3176"); - test(2011, 5, 3, "Discoflux, in the YOLD 3177"); + test(2010, 6, 22, "Pungenday, day 57 of Confusion in the YOLD 3176"); + test(2012, 1, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178"); + test(2012, 1, 29, "St. Tib's Day, in the YOLD 3178"); + test(2012, 2, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178"); + test(2010, 0, 5, "Mungday, in the YOLD 3176"); + test(2011, 4, 3, "Discoflux, in the YOLD 3177"); + test(2015, 9, 19, "Boomtime, day 73 of Bureaucracy in the YOLD 3181"); } private static void test(int y, int m, int d, final String result) { diff --git a/Task/Discordian-date/REXX/discordian-date.rexx b/Task/Discordian-date/REXX/discordian-date.rexx index 63705e12ee..3c152048da 100644 --- a/Task/Discordian-date/REXX/discordian-date.rexx +++ b/Task/Discordian-date/REXX/discordian-date.rexx @@ -1,30 +1,35 @@ -/*REXX program converts mm/dd/yyyy Gregorian date ───> Discordian date. */ -/*Gregorian date may be m/d/yy ──or── m/d format. */ +/*REXX program converts a mm/dd/yyyy Gregorian date ───► Discordian date. */ +@day.1= 'Sweetness' /*define the 1st day─of─Discordian─week*/ +@day.2= 'Boomtime' /* " " 2nd " " " " */ +@day.3= 'Pungenday' /* " " 3rd " " " " */ +@day.4= 'Prickle-Prickle' /* " " 4th " " " " */ +@day.5= 'Setting Orange' /* " " 5th " " " " */ -day.1='Sweetness' /*define 1st day-of-Discordian-week.*/ -day.2='Boomtime' /*define 2nd day-of-Discordian-week.*/ -day.3='Pungenday' /*define 3rd day-of-Discordian-week.*/ -day.4='Prickle-Prickle' /*define 4th day-of-Discordian-week.*/ -day.5='Setting Orange' /*define 5th day-of-Discordian-week.*/ +@seas.0= "St. Tib's day," /*define the leap─day of Discordian yr.*/ +@seas.1= 'Chaos' /* " 1st season─of─Discordian─year.*/ +@seas.2= 'Discord' /* " 2nd " " " " */ +@seas.3= 'Confusion' /* " 3rd " " " " */ +@seas.4= 'Bureaucracy' /* " 4th " " " " */ +@seas.5= 'The Aftermath' /* " 5th " " " " */ -seas.0="St. Tib's day," /*define the leap-day of Discordian yr.*/ -seas.1='Chaos' /*define 1st season-of-Discordian-year.*/ -seas.2='Discord' /*define 2nd season-of-Discordian-year.*/ -seas.3='Confusion' /*define 3rd season-of-Discordian-year.*/ -seas.4='Bureaucracy' /*define 4th season-of-Discordian-year.*/ -seas.5='The Aftermath' /*define 5th season-of-Discordian-year.*/ +parse arg gM '/' gD "/" gY . /*get the specified Gregorian date*/ +if gM=='' | gM=='*' then parse value date('U') with gM '/' gD "/" gY . -parse arg gM '/' gD "/" gY . /*get the date specified. */ -gY=left(right(date(),4),4-length(Gy))gY /*adjust for a 2-dig yr or none*/ - /*below:get day-of-year,adj LeapY*/ -doy=date('d',gY||right(gM,2,0)right(gD,2,0),"s")-(leapyear(gY) & gM>2) -dW=doy//5;if dW==0 then dW=5 /*compute the Discordian weekday.*/ -dS=(doy-1)%73+1 /*compute the Discordian season. */ -dD=doy//73;if dD==0 then dD=73; dD=dD',' /*Discordian day-of-month.*/ -if leapyear(gY) & gM==02 & gD==29 then do; dD=''; ds=0; end /*St. Tib's?*/ -say space(day.dW',' seas.dS dD gY+1166) /*show and tell Discordian date*/ -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────LEAPYEAR subroutine──────────────*/ -leapyear: procedure; arg y -if y//4\==0 then return 0 /* not ≈ by 4? Not a leapyear.*/ -return y//100\==0 | y//400==0 /*apply 100 and 400 year rule. */ +gY=left(right(date(),4),4-length(Gy))gY /*adjust for 2─digit year or none.*/ + + /* [↓] day─of─year, leapyear adj.*/ +doy=date('d',gY || right(gM,2,0)right(gD,2,0), "s") - (leapyear(gY) & gM>2) + +dW=doy//5; if dW==0 then dW=5 /*compute the Discordian weekday. */ +dS=(doy-1)%73+1 /* " " " season. */ +dD=doy//73; if dD==0 then dD=73 /*compute Discordian day─of─month.*/ +dD=dD',' /*append a comma to Discordian day*/ +if leapyear(gY) & gM=2 & gD=29 then ds=0 /*is this St. Tib's day (leapday)?*/ +if ds==0 then dD= /*adjust for Discordian leap day. */ + +say space(@day.dW',' @seas.dS dD gY+1166) /*display the Discordian date. */ +exit /*stick a fork in it, we're done.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +leapyear: procedure; parse arg y /*obtain four-digit Gregorian year*/ + if y//4\==0 then return 0 /*Not ÷ by 4? Not a leapyear.*/ + return y//100\==0 | y//400==0 /*apply the 100 and 400 year rule.*/ diff --git a/Task/Documentation/C/documentation.c b/Task/Documentation/C/documentation.c index 34b5dc8fc2..396031bc00 100644 --- a/Task/Documentation/C/documentation.c +++ b/Task/Documentation/C/documentation.c @@ -1,11 +1,11 @@ /** - * \brief Perform addition on \b a and \b b. + * \brief Perform addition on \p a and \p b. * - * \param int One of the numbers to be added. - * \param int Another number to be added. - * \return The sum of \b a and \b + * \param a One of the numbers to be added. + * \param b Another number to be added. + * \return The sum of \p a and \p b. * \code - * int sum = add(1, 2) + * int sum = add(1, 2); * \endcode */ int add(int a, int b) { diff --git a/Task/Documentation/Elixir/documentation-1.elixir b/Task/Documentation/Elixir/documentation-1.elixir new file mode 100644 index 0000000000..e64d2c6bb2 --- /dev/null +++ b/Task/Documentation/Elixir/documentation-1.elixir @@ -0,0 +1,8 @@ +def project do + [app: :repo + version: "0.1.0-dev", + name: "REPO", + source_url: "https://github.com/USER/REPO", + homepage_url: "http://YOUR_PROJECT_HOMEPAGE" + deps: deps] +end diff --git a/Task/Documentation/Elixir/documentation-2.elixir b/Task/Documentation/Elixir/documentation-2.elixir new file mode 100644 index 0000000000..f7749e0b0b --- /dev/null +++ b/Task/Documentation/Elixir/documentation-2.elixir @@ -0,0 +1,10 @@ +defmodule MyModule do + @moduledoc """ + About MyModule + + ## Some Header + + iex> MyModule.my_function + :result + """ +end diff --git a/Task/Documentation/REXX/documentation-2.rexx b/Task/Documentation/REXX/documentation-2.rexx index aec0f7d193..1be6b67b58 100644 --- a/Task/Documentation/REXX/documentation-2.rexx +++ b/Task/Documentation/REXX/documentation-2.rexx @@ -4,7 +4,7 @@ **********************************************************************/ beghelp=here()+1 /* line where the docmentation begins Documentation -any test explaining the program's invocaion and workings +any text explaining the program's invocation and workings --- and where it ends */ endhelp=here()-2 diff --git a/Task/Dot-product/ALGOL-W/dot-product.alg b/Task/Dot-product/ALGOL-W/dot-product.alg new file mode 100644 index 0000000000..f92054b09f --- /dev/null +++ b/Task/Dot-product/ALGOL-W/dot-product.alg @@ -0,0 +1,23 @@ +begin + % computes the dot product of two equal length integer vectors % + % (single dimension arrays ) the length of the vectors must be specified % + % in length. % + integer procedure integerDotProduct( integer array a ( * ) + ; integer array b ( * ) + ; integer value length + ) ; + begin + integer product; + product := 0; + for i := 1 until length do product := product + ( a(i) * b(i) ); + product + end integerDotProduct ; + + % declare two vectors of length 3 % + integer array v1, v2 ( 1 :: 3 ); + % initialise the vectors % + v1(1) := 1; v1(2) := 3; v1(3) := -5; + v2(1) := 4; v2(2) := -2; v2(3) := -1; + % output the dot product % + write( integerDotProduct( v1, v2, 3 ) ) +end. diff --git a/Task/Dot-product/APL/dot-product.apl b/Task/Dot-product/APL/dot-product.apl new file mode 100644 index 0000000000..9c1e4bc0b8 --- /dev/null +++ b/Task/Dot-product/APL/dot-product.apl @@ -0,0 +1 @@ +1 3 ¯5 +.× 4 ¯2 ¯1 diff --git a/Task/Dot-product/Elixir/dot-product.elixir b/Task/Dot-product/Elixir/dot-product.elixir new file mode 100644 index 0000000000..f10f5e1826 --- /dev/null +++ b/Task/Dot-product/Elixir/dot-product.elixir @@ -0,0 +1,11 @@ +defmodule Vector do + def dot_product(a,b) when length(a)==length(b), do: dot_product(a,b,0) + def dot_product(_,_) do + raise ArgumentError, message: "Vectors must have the same length." + end + + defp dot_product([],[],product), do: product + defp dot_product([h1|t1], [h2|t2], product), do: dot_product(t1, t2, product+h1*h2) +end + +IO.puts Vector.dot_product([1,3,-5],[4,-2,-1]) diff --git a/Task/Dot-product/Emacs-Lisp/dot-product.l b/Task/Dot-product/Emacs-Lisp/dot-product.l new file mode 100644 index 0000000000..cc20b3c85d --- /dev/null +++ b/Task/Dot-product/Emacs-Lisp/dot-product.l @@ -0,0 +1,9 @@ +(defun dot-product (v1 v2) + (setq res 0) + (dotimes (i (length v1)) + (setq res (+ (* (elt v1 i) (elt v2 i) ) res) )) + res) + +(progn + (insert (format "%d\n" (dot-product [1 2 3] [1 2 3]) )) + (insert (format "%d\n" (dot-product '(1 2 3) '(1 2 3) )))) diff --git a/Task/Dot-product/Go/dot-product-1.go b/Task/Dot-product/Go/dot-product-1.go new file mode 100644 index 0000000000..a61012a8c7 --- /dev/null +++ b/Task/Dot-product/Go/dot-product-1.go @@ -0,0 +1,30 @@ +package main + +import ( + "errors" + "fmt" + "log" +) + +var ( + v1 = []int{1, 3, -5} + v2 = []int{4, -2, -1} +) + +func dot(x, y []int) (r int, err error) { + if len(x) != len(y) { + return 0, errors.New("incompatible lengths") + } + for i, xi := range x { + r += xi * y[i] + } + return +} + +func main() { + d, err := dot([]int{1, 3, -5}, []int{4, -2, -1}) + if err != nil { + log.Fatal(err) + } + fmt.Println(d) +} diff --git a/Task/Dot-product/Go/dot-product-2.go b/Task/Dot-product/Go/dot-product-2.go new file mode 100644 index 0000000000..272c50243a --- /dev/null +++ b/Task/Dot-product/Go/dot-product-2.go @@ -0,0 +1,16 @@ +package main + +import ( + "fmt" + + "github.com/gonum/floats" +) + +var ( + v1 = []float64{1, 3, -5} + v2 = []float64{4, -2, -1} +) + +func main() { + fmt.Println(floats.Dot(v1, v2)) +} diff --git a/Task/Dot-product/Go/dot-product.go b/Task/Dot-product/Go/dot-product.go deleted file mode 100644 index 6a49539f4e..0000000000 --- a/Task/Dot-product/Go/dot-product.go +++ /dev/null @@ -1,25 +0,0 @@ -package main - -import ( - "errors" - "fmt" -) - -func dot(x, y []int) (r int, err error) { - if len(x) != len(y) { - return 0, errors.New("incompatible lengths") - } - for i := range x { - r += x[i] * y[i] - } - return -} - -func main() { - d, err := dot([]int{1, 3, -5}, []int{4, -2, -1}) - if err != nil { - fmt.Println(err) - return - } - fmt.Println(d) -} diff --git a/Task/Dot-product/Julia/dot-product.julia b/Task/Dot-product/Julia/dot-product.julia index 9ea824e3a6..315d6e321c 100644 --- a/Task/Dot-product/Julia/dot-product.julia +++ b/Task/Dot-product/Julia/dot-product.julia @@ -1,3 +1,4 @@ x = [1, 3, -5] y = [4, -2, -1] z = dot(x, y) +z = x'*y diff --git a/Task/Dot-product/PowerShell/dot-product.psh b/Task/Dot-product/PowerShell/dot-product.psh new file mode 100644 index 0000000000..1ef773d778 --- /dev/null +++ b/Task/Dot-product/PowerShell/dot-product.psh @@ -0,0 +1,7 @@ +function dotproduct( $a, $b) { + $i = $res = 0 + $a | foreach{ $($_)*$b[$i++] } | foreach{ $res += $_ } + $res +} +dotproduct (1..2) (1..2) +dotproduct (1..10) (11..20) diff --git a/Task/Dot-product/REXX/dot-product-1.rexx b/Task/Dot-product/REXX/dot-product-1.rexx new file mode 100644 index 0000000000..35fbdb90d5 --- /dev/null +++ b/Task/Dot-product/REXX/dot-product-1.rexx @@ -0,0 +1,15 @@ +/*REXX program computes the dot product of two equal size vectors. */ +vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/ +vectorB = ' 4 -2 -1 ' /* " " B " " " */ +say; say 'vector A = ' vectorA /*display the elements in the vector A.*/ + say 'vector B = ' vectorB /* " " " " " " B.*/ +p=dotProd(vectorA, vectorB) /*invoke function & compute dot product*/ +say; say 'dot product = ' p /*blank line; display the dot product.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +dotProd: procedure; parse arg A,B /*this function compute the dot product*/ +$=0 /*initialize the sum to 0 (zero). */ + do j=1 for words(A) /*multiply each number in the vectors. */ + $=$+word(A,j) * word(B,j) /* ··· and add the product to the sum.*/ + end /*j*/ +return $ /*return the sum to invoker of function*/ diff --git a/Task/Dot-product/REXX/dot-product-2.rexx b/Task/Dot-product/REXX/dot-product-2.rexx new file mode 100644 index 0000000000..1b68f31849 --- /dev/null +++ b/Task/Dot-product/REXX/dot-product-2.rexx @@ -0,0 +1,34 @@ +/*REXX program computes the dot product of two equal size vectors. */ +vectorA = ' 1 3 -5 ' /*populate vector A with some numbers*/ +vectorB = ' 4 -2 -1 ' /* " " B " " " */ +say; say 'vector A = ' vectorA /*display the elements in the vector A.*/ + say 'vector B = ' vectorB /* " " " " " " B.*/ +p=dotProd(vectorA, vectorB) /*invoke function & compute dot product*/ +say; say 'dot product = ' p /*blank line; display the dot product.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +dotProd: procedure; parse arg A,B /*this function compute the dot product*/ +lenA = words(A) /*the number of numbers in vector A. */ +lenB = words(B) /* " " " " " " B. */ +e='***error!*** '; @.='A'; @.2='B' /*define some literals for error msgs. */ + +if lenA\==lenB then do /*oops─ay.*/ + say e "vectors aren't the same size:" + say ' vector A length = ' lenA + say ' vector B length = ' lenB + exit 13 /*exit with bad─boy return code 13. */ + end +$=0 /*initialize the sum to 0 (zero). */ + do j=1 for lenA /*multiply each number in the vectors. */ + n.1=word(A,j); n.2=word(B,j) + + do k=1 for 2; notNum=\datatype(n.k,'Number') /*verify numbers.*/ + if notNum then do /*oops─ay, ¬ num.*/ + say e "vector" @.k 'element' j "isn't numeric:" n.k + exit 13 /*exit with return code 13.*/ + end + end /*k*/ + + $=$+n.1 * n.2 /* ··· and add the product to the sum.*/ + end /*j*/ +return $ /*return the sum to invoker of function*/ diff --git a/Task/Dot-product/REXX/dot-product.rexx b/Task/Dot-product/REXX/dot-product.rexx deleted file mode 100644 index 9e3513171d..0000000000 --- a/Task/Dot-product/REXX/dot-product.rexx +++ /dev/null @@ -1,26 +0,0 @@ -/*REXX program computes the dot product of two equal size vectors. */ -vectorA = ' 1 3 -5 ' /*populate vectorA with numbers, */ -vectorB = ' 4 -2 -1 ' /* ∙∙∙ and the same for vectorB. */ -say /*display a blank line. */ -say 'vector A = ' vectorA /*echo the elements in vector A. */ -say 'vector B = ' vectorB /* " " " " " B. */ -say /*display another blank line. */ -p = dotProd(vectorA, vectorB) /*go and compute the dot product.*/ -say 'dot product = ' p /*show and tell the dot product. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────DOTPROD subroutine──────────────────*/ -dotProd: procedure; parse arg A,B /*compute the dot product. */ -lenA = words(A) /*number of numbers in vector A.*/ -lenB = words(B) /* " " " " " B.*/ -if lenA\==lenB then do /*are vectors unequal in size? */ - say '*** error! ***' - say "vectors aren't the same size:" - say ' vector A length = ' lenA - say ' vector B length = ' lenB - exit 13 /*exit with return code 13. */ - end -sum=0 /*initialize the sum to 0 (zero).*/ - do j=1 for lenA /*multiply each number in vectors*/ - sum=sum+word(A,j)*word(B,j) /*∙∙∙ and add the product to SUM.*/ - end /*j*/ -return sum /*return the SUM to the invoker. */ diff --git a/Task/Dot-product/Rust/dot-product-1.rust b/Task/Dot-product/Rust/dot-product-1.rust new file mode 100644 index 0000000000..2264ba3959 --- /dev/null +++ b/Task/Dot-product/Rust/dot-product-1.rust @@ -0,0 +1,18 @@ +// alternatively, fn dot_product(a: &Vec, b: &Vec) +// but using slices is more general and rustic +fn dot_product(a: &[i32], b: &[i32]) -> Option { + if a.len() != b.len() { return None } + Some( + a.iter() + .zip( b.iter() ) + .fold(0, |sum, (el_a, el_b)| sum + el_a*el_b) + ) +} + + +fn main() { + let v1 = vec![1, 3, -5]; + let v2 = vec![4, -2, -1]; + + println!("{}", dot_product(&v1, &v2).unwrap()); +} diff --git a/Task/Dot-product/Rust/dot-product-2.rust b/Task/Dot-product/Rust/dot-product-2.rust new file mode 100644 index 0000000000..883589a50e --- /dev/null +++ b/Task/Dot-product/Rust/dot-product-2.rust @@ -0,0 +1,29 @@ +#![feature(zero_one)] // <-- unstable feature +use std::ops::{Add, Mul}; +use std::num::Zero; + +fn dot_product(lhs: I1, rhs: I2) -> Option + where T1: Mul, + U: Add + Zero, + I1: IntoIterator, + I2: IntoIterator, + I1::IntoIter: ExactSizeIterator, + I2::IntoIter: ExactSizeIterator, +{ + let (iter_lhs, iter_rhs) = (lhs.into_iter(), rhs.into_iter()); + match (iter_lhs.len(), iter_rhs.len()) { + (0, _) | (_, 0) => None, + (a,b) if a != b => None, + (_,_) => Some( iter_lhs.zip(iter_rhs) + .fold(U::zero(), |sum, (a, b)| sum + (a * b)) ) + } +} + + + +fn main() { + let v1 = vec![1, 3, -5]; + let v2 = vec![4, -2, -1]; + + println!("{}", dot_product(&v1, &v2).unwrap()); +} diff --git a/Task/Dot-product/Rust/dot-product.rust b/Task/Dot-product/Rust/dot-product.rust deleted file mode 100644 index e6763b16b9..0000000000 --- a/Task/Dot-product/Rust/dot-product.rust +++ /dev/null @@ -1,14 +0,0 @@ -fn dot_product(a: Vec, b: Vec) -> int { - let mut s = 0; - for i in range(0, a.len()) { - s += a[i] * b[i]; - } - return s; -} - -fn main() { - let v1 = vec!(1, 3, -5); - let v2 = vec!(4, -2, -1); - - println!("{}", dot_product(v1, v2)); -} diff --git a/Task/Dot-product/VBScript/dot-product.vb b/Task/Dot-product/VBScript/dot-product.vb new file mode 100644 index 0000000000..eb7892d8a1 --- /dev/null +++ b/Task/Dot-product/VBScript/dot-product.vb @@ -0,0 +1,14 @@ +WScript.Echo DotProduct("1,3,-5","4,-2,-1") + +Function DotProduct(vector1,vector2) + arrv1 = Split(vector1,",") + arrv2 = Split(vector2,",") + If UBound(arrv1) <> UBound(arrv2) Then + WScript.Echo "The vectors are not of the same length." + Exit Function + End If + DotProduct = 0 + For i = 0 To UBound(arrv1) + DotProduct = DotProduct + (arrv1(i) * arrv2(i)) + Next +End Function diff --git a/Task/Doubly-linked-list-Definition/C++/doubly-linked-list-definition.cpp b/Task/Doubly-linked-list-Definition/C++/doubly-linked-list-definition.cpp new file mode 100644 index 0000000000..9645d20461 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/C++/doubly-linked-list-definition.cpp @@ -0,0 +1,14 @@ +#include +#include + +int main () +{ + std::list numbers {1, 5, 7, 0, 3, 2}; + numbers.insert(numbers.begin(), 9); //Insert at the beginning + numbers.insert(numbers.end(), 4); //Insert at the end + auto it = std::next(numbers.begin(), numbers.size() / 2); //Iterator to the middle of the list + numbers.insert(it, 6); //Insert in the middle + for(const auto& i: numbers) + std::cout << i << ' '; + std::cout << '\n'; +} diff --git a/Task/Doubly-linked-list-Element-definition/C++/doubly-linked-list-element-definition.cpp b/Task/Doubly-linked-list-Element-definition/C++/doubly-linked-list-element-definition.cpp new file mode 100644 index 0000000000..37e61ad188 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/C++/doubly-linked-list-element-definition.cpp @@ -0,0 +1,7 @@ +template +struct Node +{ + Node* next; + Node* prev; + T data; +}; diff --git a/Task/Doubly-linked-list-Element-definition/Objeck/doubly-linked-list-element-definition.objeck b/Task/Doubly-linked-list-Element-definition/Objeck/doubly-linked-list-element-definition.objeck new file mode 100644 index 0000000000..9ec0234e88 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Objeck/doubly-linked-list-element-definition.objeck @@ -0,0 +1,33 @@ +class ListNode { + @value : Base; + @next : ListNode; + @previous: ListNode; + + New(value : Base) { + @value := value; + } + + method : public : Set(value : Base) ~ Nil { + @value := value; + } + + method : public : Get() ~ Base { + return @value; + } + + method : public : SetNext(next : Collection.ListNode) ~ Nil { + @next := next; + } + + method : public : GetNext() ~ ListNode { + return @next; + } + + method : public : SetPrevious(previous : Collection.ListNode) ~ Nil { + @previous := previous; + } + + method : public : GetPrevious() ~ ListNode { + return @previous; + } +} diff --git a/Task/Doubly-linked-list-Element-insertion/C++/doubly-linked-list-element-insertion.cpp b/Task/Doubly-linked-list-Element-insertion/C++/doubly-linked-list-element-insertion.cpp new file mode 100644 index 0000000000..329f2868a0 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/C++/doubly-linked-list-element-insertion.cpp @@ -0,0 +1,8 @@ +template +void insert_after(Node* N, T&& data) +{ + auto node = new Node{N, N->next, std::forward(data)}; + if(N->next != nullptr) + N->next->prev = node; + N->next = node; +} diff --git a/Task/Doubly-linked-list-Element-insertion/Objeck/doubly-linked-list-element-insertion.objeck b/Task/Doubly-linked-list-Element-insertion/Objeck/doubly-linked-list-element-insertion.objeck new file mode 100644 index 0000000000..5c83a0909f --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Objeck/doubly-linked-list-element-insertion.objeck @@ -0,0 +1,12 @@ +method : public : native : AddBack(value : Base) ~ Nil { + node := ListNode->New(value); + if(@head = Nil) { + @head := node; + @tail := @head; + } + else { + @tail->SetNext(node); + node->SetPrevious(@tail); + @tail := node; + }; +} diff --git a/Task/Doubly-linked-list-Traversal/ALGOL-68/doubly-linked-list-traversal-1.alg b/Task/Doubly-linked-list-Traversal/ALGOL-68/doubly-linked-list-traversal-1.alg new file mode 100644 index 0000000000..454c082cfb --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/ALGOL-68/doubly-linked-list-traversal-1.alg @@ -0,0 +1,102 @@ +# Node struct - contains next and prev NODE pointers and DATA # +MODE NODE = STRUCT( + DATA data, + REF NODE prev, + REF NODE next + ); + +# List structure - contains head and tail NODE pointers # +MODE LIST = STRUCT( + REF NODE head, + REF NODE tail + ); + +# --- PREPEND - Adds a node to the beginning of the list ---# +PRIO PREPEND = 1; +OP PREPEND = (REF LIST list, DATA data) VOID: +( + HEAP NODE n := (data, NIL, NIL); + IF head OF list IS REF NODE(NIL) THEN + head OF list := tail OF list := n + ELSE + next OF n := head OF list; + prev OF head OF list := head OF list := n + FI +); +#--- APPEND - Adds a node to the end of the list ---# +PRIO APPEND = 1; +OP APPEND = (REF LIST list, DATA data) VOID: +( + HEAP NODE n := (data, NIL, NIL); + IF head OF list IS REF NODE(NIL) THEN + head OF list := tail OF list := n + ELSE + prev OF n := tail OF list; + next OF tail OF list := tail OF list := n + FI +); + +#--- REMOVE_FIRST - removes & returns node at end of the list ---# +PRIO REMOVE_FIRST = 1; +OP REMOVE_FIRST = (REF LIST list) DATA: +( + IF head OF list ISNT REF NODE(NIL) THEN + DATA d := data OF head OF list; + prev OF next OF head OF list := NIL; + head OF list := next OF head OF list; + d # return d # + FI +); +#--- REMOVE_LAST: removes & returns node at front of list --- # +PRIO REMOVE_LAST = 1; +OP REMOVE_LAST = (REF LIST list) DATA: +( + IF head OF list ISNT REF NODE(NIL) THEN + DATA d := data OF tail OF list; + next OF prev OF tail OF list := NIL; + tail OF list := prev OF tail OF list; + d # return d # + FI +); +#--- PURGE - removes all elements from the list ---# +PRIO PURGE = 2; +OP PURGE = (REF LIST list) VOID: +( + head OF list := tail OF list := NIL +); + +#--- returns the data at the end of the list ---# +PRIO LAST_IN = 2; +OP LAST_IN = (REF LIST list) DATA: ( + IF head OF list ISNT REF NODE(NIL) THEN + data OF tail OF list + FI +); + +#--- returns the data at the front of the list ---# +PRIO FIRST_IN = 2; +OP FIRST_IN = (REF LIST list) DATA: ( + IF head OF list ISNT REF NODE(NIL) THEN + data OF head OF list + FI +); + +#--- Traverses through the list forwards ---# +PROC forward traversal = (LIST list) VOID: +( + REF NODE travel := head OF list; + WHILE travel ISNT REF NODE(NIL) DO + list visit(data OF travel); + travel := next OF travel + OD +); + +#--- Traverses through the list backwards ---# +PROC backward traversal = (LIST list) VOID: +( + REF NODE travel := tail OF list; + WHILE travel ISNT REF NODE(NIL) DO + list visit(data OF travel); + travel := prev OF travel + OD +) diff --git a/Task/Doubly-linked-list-Traversal/ALGOL-68/doubly-linked-list-traversal-2.alg b/Task/Doubly-linked-list-Traversal/ALGOL-68/doubly-linked-list-traversal-2.alg new file mode 100644 index 0000000000..f5fef4677b --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/ALGOL-68/doubly-linked-list-traversal-2.alg @@ -0,0 +1,43 @@ +PR READ "LinkedList.alg" PR; + +MODE EMPLOYEE = STRUCT(STRING name, INT salary, INT years); +MODE DATA = EMPLOYEE; #Sets the data type that is in the list# + +# Function that traversals call for each node in list # +PROC list visit = (REF DATA data) VOID: +( + print(( + "EMPLOYEE NAME : ", name OF data , newline, + " SALARY: " , salary OF data, newline, + " YEARS : " , years OF data, newline + )) +); + +#***************************************************************# +main: +( + EMPLOYEE empl; + name OF empl := "one"; + salary OF empl := 100; + years OF empl := 10; + + LIST list := (NIL, NIL); + + list PREPEND empl; + name OF empl := "two"; + salary OF empl := 200; + years OF empl := 20; + list APPEND empl; + name OF empl := "three"; + salary OF empl := 300; + years OF empl := 30; + list APPEND empl; + salary OF empl := 400; + years OF empl := 40; + name OF empl := "four"; + list APPEND empl; + + forward traversal(list); + PURGE list; + forward traversal(list) +) diff --git a/Task/Doubly-linked-list-Traversal/C++/doubly-linked-list-traversal.cpp b/Task/Doubly-linked-list-Traversal/C++/doubly-linked-list-traversal.cpp new file mode 100644 index 0000000000..a836527b4f --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/C++/doubly-linked-list-traversal.cpp @@ -0,0 +1,10 @@ +#include +#include + +int main () +{ + std::list numbers {1, 5, 7, 0, 3, 2}; + for(const auto& i: numbers) + std::cout << i << ' '; + std::cout << '\n'; +} diff --git a/Task/Doubly-linked-list-Traversal/Haskell/doubly-linked-list-traversal.hs b/Task/Doubly-linked-list-Traversal/Haskell/doubly-linked-list-traversal-1.hs similarity index 100% rename from Task/Doubly-linked-list-Traversal/Haskell/doubly-linked-list-traversal.hs rename to Task/Doubly-linked-list-Traversal/Haskell/doubly-linked-list-traversal-1.hs diff --git a/Task/Doubly-linked-list-Traversal/Haskell/doubly-linked-list-traversal-2.hs b/Task/Doubly-linked-list-Traversal/Haskell/doubly-linked-list-traversal-2.hs new file mode 100644 index 0000000000..f04c1668f3 --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Haskell/doubly-linked-list-traversal-2.hs @@ -0,0 +1,48 @@ +class DoubleLink (value, prev_link, next_link) + + # insert given node after this one, removing its existing connections + method insert_after (node) + node.prev_link := self + if (\next_link) then next_link.prev_link := node + node.next_link := next_link + self.next_link := node + end + + # use a generator to traverse + # - keep suspending the prev/next link until a null node is reached + method traverse_backwards () + current := self + while \current do { + suspend current + current := current.prev_link + } + end + + method traverse_forwards () + current := self + while \current do { + suspend current + current := current.next_link + } + end + + initially (value, prev_link, next_link) + self.value := value + self.prev_link := prev_link # links are 'null' if not given + self.next_link := next_link +end + +procedure main () + l1 := DoubleLink (1) + l2 := DoubleLink (2) + l1.insert_after (l2) + l1.insert_after (DoubleLink (3)) + + write ("Traverse from beginning to end") + every (node := l1.traverse_forwards ()) do + write (node.value) + + write ("Traverse from end to beginning") + every (node := l2.traverse_backwards ()) do + write (node.value) +end diff --git a/Task/Dragon-curve/REXX/dragon-curve.rexx b/Task/Dragon-curve/REXX/dragon-curve.rexx index debe23e79c..f97f9f1f1c 100644 --- a/Task/Dragon-curve/REXX/dragon-curve.rexx +++ b/Task/Dragon-curve/REXX/dragon-curve.rexx @@ -1,36 +1,36 @@ -/*REXX program to draw an ASCII Dragon Curve (or Harter-Heighway dragon)*/ -d.=1; d.L=-1; @.=' '; x=0; x2=x; y=0; y2=y; @.x.y='∙'; z=1 -plot_pts='123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZΘ' -minX=0; maxX=0; minY=0; maxY=0 /*assign various constants & vars*/ -parse arg # p c . /*# is # iterations, P=init dir.*/ -if #=='' | #==',' then #=11 /*Not specified? Use the default*/ -if p=='' | p==',' then p=0 /*Not specified? Use the default*/ -if c=='' then c=plot_pts /*Not specified? Use the default*/ -if length(c)==2 then c=x2c(c) /*hexadecimal code was specified?*/ -if length(c)==3 then c=d2c(c) /* decimal " " " ?*/ -$= /*nullify the dragon curve string*/ - do # /*create the dragon curve string.*/ - $=$'R'reverse(translate($, 'RL', 'LR')) /*append,flip,reverse.*/ - end /*#*/ - /*create dragon curve.*/ - do j=1 for length($); _=substr($, j, 1) /*get next direction.*/ - p=(p+d._)//4; if p<0 then p=p+4 /*move in a direction.*/ - if p==0 then do; y=y+1; y2=y+1; end /*going east map-wise.*/ - if p==1 then do; x=x+1; x2=x+1; end /* " south " */ - if p==2 then do; y=y-1; y2=y-1; end /* " west " */ - if p==3 then do; x=x-1; x2=x-1; end /* " north " */ - if j>2**z then z=z+1 /*the curve being done*/ - !=substr(c,z,1); if !==' ' then !=right(c,1) /*choose plot pt char.*/ - @.x.y=!; @.x2.y2=! /*draw part of dragon.*/ - minX=min(minX,x,x2); maxX=max(maxX,x,x2); x=x2 /*define graph limits.*/ - minY=min(minY,y,y2); maxY=max(maxY,y,y2); y=y2 /* " " " */ - end /*j*/ - /* [↓] display the dragon curve.*/ - do r=minX to maxX; a= /*nullify the line to be drawn. */ - do c=minY to maxY /*create a line (row) of points. */ - a=a || @.r.c /*build one column at a time. */ +/*REXX program draws an ASCII Dragon Curve (or Harter-Heighway dragon curve)*/ +z=1; d.=1; d.L=-d.; @.=' '; x=0; x2=x; y=0; y2=y; @.x.y='∙' +plot_pts = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZΘ' +minX=0; maxX=0; minY=0; maxY=0 /*assign various constants & variables.*/ +parse arg # p c . /*#: number of iterations; P=init dir.*/ +if #=='' | #==',' then #=11 /*Not specified? Then use the default.*/ +if p=='' | p==',' then p=0 /* " " " " " " */ +if c=='' then c=plot_pts /* " " " " " " */ +if length(c)==2 then c=x2c(c) /*was a hexadecimal code specified? */ +if length(c)==3 then c=d2c(c) /* " " decimal " " ? */ +$= /*assign a null to dragon curve string.*/ + do # /* [↓] create dragon curve.*/ + $=$'R'reverse(translate($, "RL", 'LR')) /*append, flip, and reverse.*/ + end /*#*/ /* [↑] TRANSLATE flips chrs*/ + /* [↓] create dragon curve.*/ + do j=1 for length($); _=substr($, j, 1) /*obtain the next direction.*/ + p=(p+d._)//4; if p<0 then p=p+4 /*move curve in a direction.*/ + if p==0 then do; y=y+1; y2=y+1; end /*going east cartologically*/ + if p==1 then do; x=x+1; x2=x+1; end /* " south " */ + if p==2 then do; y=y-1; y2=y-1; end /* " west " */ + if p==3 then do; x=x-1; x2=x-1; end /* " north " */ + if j>2**z then z=z+1 /*identify curve being built*/ + !=substr(c,z,1); if !==' ' then !=right(c,1) /*choose the plot point char*/ + @.x.y=!; @.x2.y2=! /*draw part of dragon curve.*/ + minX=min(minX,x,x2); maxX=max(maxX,x,x2); x=x2 /*define the X graph limits.*/ + minY=min(minY,y,y2); maxY=max(maxY,y,y2); y=y2 /* " " Y " " */ + end /*j*/ /* [↑] process all of $ str*/ + /* [↓] display the dragon curve. */ + do r=minX to maxX; a= /*nullify the line that will bee drawn.*/ + do c=minY to maxY /*create a line (row) of curve points. */ + a=a || @.r.c /*add a single column of row at a time.*/ end /*c*/ - a=strip(a, 'T') /*be nice & strip trailing blanks*/ - if a\=='' then say a /*display a line (row) of points.*/ + a=strip(a, 'T') /*be nice and strip any trailing blanks*/ + if a\=='' then say a /*display a line (row) of curve points.*/ end /*r*/ - /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Dragon-curve/Scala/dragon-curve.scala b/Task/Dragon-curve/Scala/dragon-curve.scala new file mode 100644 index 0000000000..322fb99326 --- /dev/null +++ b/Task/Dragon-curve/Scala/dragon-curve.scala @@ -0,0 +1,51 @@ +import javax.swing.JFrame +import java.awt.Graphics + +class DragonCurve(depth: Int) extends JFrame(s"Dragon Curve (depth $depth)") { + + setBounds(100, 100, 800, 600); + setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + val len = 400 / Math.pow(2, depth / 2.0); + val startingAngle = -depth * (Math.PI / 4); + val steps = getSteps(depth).filterNot(c => c == 'X' || c == 'Y') + + def getSteps(depth: Int): Stream[Char] = { + if (depth == 0) { + "FX".toStream + } else { + getSteps(depth - 1).flatMap{ + case 'X' => "XRYFR" + case 'Y' => "LFXLY" + case c => c.toString + } + } + } + + override def paint(g: Graphics): Unit = { + var (x, y) = (230, 350) + var (dx, dy) = ((Math.cos(startingAngle) * len).toInt, (Math.sin(startingAngle) * len).toInt) + for (c <- steps) c match { + case 'F' => { + g.drawLine(x, y, x + dx, y + dy) + x = x + dx + y = y + dy + } + case 'L' => { + val temp = dx + dx = dy + dy = -temp + } + case 'R' => { + val temp = dx + dx = -dy + dy = temp + } + } + } + +} + +object DragonCurve extends App { + new DragonCurve(14).setVisible(true); +} diff --git a/Task/Draw-a-clock/Batch-File/draw-a-clock.bat b/Task/Draw-a-clock/Batch-File/draw-a-clock.bat new file mode 100644 index 0000000000..b752046d65 --- /dev/null +++ b/Task/Draw-a-clock/Batch-File/draw-a-clock.bat @@ -0,0 +1,106 @@ +::Draw a Clock Task from Rosetta Code Wiki +::Batch File Implementation +:: +::Directly open the Batch File... +@echo off & mode 44,8 +title Sample Batch Clock +setlocal enabledelayedexpansion + + ::Set the characters... +set "#0_1=ÛÛÛÛÛ" +set "#0_2=Û Û" +set "#0_3=Û Û" +set "#0_4=Û Û" +set "#0_5=ÛÛÛÛÛ" + +set "#1_1= Û" +set "#1_2= Û" +set "#1_3= Û" +set "#1_4= Û" +set "#1_5= Û" + +set "#2_1=ÛÛÛÛÛ" +set "#2_2= Û" +set "#2_3=ÛÛÛÛÛ" +set "#2_4=Û " +set "#2_5=ÛÛÛÛÛ" + +set "#3_1=ÛÛÛÛÛ" +set "#3_2= Û" +set "#3_3=ÛÛÛÛÛ" +set "#3_4= Û" +set "#3_5=ÛÛÛÛÛ" + +set "#4_1=Û Û" +set "#4_2=Û Û" +set "#4_3=ÛÛÛÛÛ" +set "#4_4= Û" +set "#4_5= Û" + +set "#5_1=ÛÛÛÛÛ" +set "#5_2=Û " +set "#5_3=ÛÛÛÛÛ" +set "#5_4= Û" +set "#5_5=ÛÛÛÛÛ" + +set "#6_1=ÛÛÛÛÛ" +set "#6_2=Û " +set "#6_3=ÛÛÛÛÛ" +set "#6_4=Û Û" +set "#6_5=ÛÛÛÛÛ" + +set "#7_1=ÛÛÛÛÛ" +set "#7_2= Û" +set "#7_3= Û" +set "#7_4= Û" +set "#7_5= Û" + +set "#8_1=ÛÛÛÛÛ" +set "#8_2=Û Û" +set "#8_3=ÛÛÛÛÛ" +set "#8_4=Û Û" +set "#8_5=ÛÛÛÛÛ" + +set "#9_1=ÛÛÛÛÛ" +set "#9_2=Û Û" +set "#9_3=ÛÛÛÛÛ" +set "#9_4= Û" +set "#9_5=ÛÛÛÛÛ" + +set "#C_1= " +set "#C_2=Û" +set "#C_3= " +set "#C_4=Û" +set "#C_5= " + +:clock_loop + ::Clear display [leaving a whitespace]... +for /l %%C in (1,1,5) do set "display%%C= " + + ::Get current time [all spaces will be replaced to zero]... + ::Also, all colons will be replaced to "C" because colon has a function in variables... +set "curr_time=%time: =0%" +set "curr_time=%curr_time::=C%" + + ::Process the numbers to display [we will now use the formats we SET above]... +for /l %%T in (0,1,7) do ( + ::Check for each number and colons... + for %%N in (0 1 2 3 4 5 6 7 8 9 C) do ( + if "!curr_time:~%%T,1!"=="%%N" ( + ::Now, barbeque each formatted char in 5 rows... + for /l %%D in (1,1,5) do set "display%%D=!display%%D!!#%%N_%%D! " + ) + ) +) + + ::Refresh the clock... +cls +echo. +echo.[%display1%] +echo.[%display2%] +echo.[%display3%] +echo.[%display4%] +echo.[%display5%] +echo. +timeout /t 1 /nobreak >nul +goto :clock_loop diff --git a/Task/Draw-a-clock/Java/draw-a-clock.java b/Task/Draw-a-clock/Java/draw-a-clock.java index b48704a0d2..5b3280c326 100644 --- a/Task/Draw-a-clock/Java/draw-a-clock.java +++ b/Task/Draw-a-clock/Java/draw-a-clock.java @@ -1,29 +1,27 @@ import java.awt.*; import java.awt.event.*; -import java.util.Calendar; +import static java.lang.Math.*; +import java.time.LocalTime; import javax.swing.*; class Clock extends JPanel { - final float degrees06 = (float) Math.toRadians(6); + final float degrees06 = (float) (PI / 30); final float degrees30 = degrees06 * 5; final float degrees90 = degrees30 * 3; - final int size = 550; - final int spacing = 20; + final int size = 590; + final int spacing = 40; final int diameter = size - 2 * spacing; - final int x = diameter / 2 + spacing; - final int y = diameter / 2 + spacing; + final int cx = diameter / 2 + spacing; + final int cy = 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(); - } + new Timer(1000, (ActionEvent e) -> { + repaint(); }).start(); } @@ -34,46 +32,50 @@ public void paintComponent(Graphics gg) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setColor(Color.black); - g.drawOval(spacing, spacing, diameter, diameter); + drawFace(g); - Calendar date = Calendar.getInstance(); - int hours = date.get(Calendar.HOUR); - int minutes = date.get(Calendar.MINUTE); - int seconds = date.get(Calendar.SECOND); + final LocalTime time = LocalTime.now(); + int hour = time.getHour(); + int minute = time.getMinute(); + int second = time.getSecond(); - float angle = degrees90 - (degrees06 * seconds); + float angle = degrees90 - (degrees06 * second); drawHand(g, angle, diameter / 2 - 30, Color.red); - float minsecs = (minutes + seconds / 60.0F); + float minsecs = (minute + second / 60.0F); angle = degrees90 - (degrees06 * minsecs); drawHand(g, angle, diameter / 3 + 10, Color.black); - float hourmins = (hours + minsecs / 60.0F); + float hourmins = (hour + minsecs / 60.0F); angle = degrees90 - (degrees30 * hourmins); drawHand(g, angle, diameter / 4 + 10, Color.black); } + private void drawFace(Graphics2D g) { + g.setStroke(new BasicStroke(2)); + g.setColor(Color.white); + g.fillOval(spacing, spacing, diameter, diameter); + g.setColor(Color.black); + g.drawOval(spacing, spacing, diameter, diameter); + } + 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 + int x = cx + (int) (radius * cos(angle)); + int y = cy - (int) (radius * sin(angle)); g.setColor(color); - g.drawLine(x, y, x2, y2); + g.drawLine(cx, cy, x, y); } 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); - } + SwingUtilities.invokeLater(() -> { + 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-cuboid/C++/draw-a-cuboid.cpp b/Task/Draw-a-cuboid/C++/draw-a-cuboid.cpp new file mode 100644 index 0000000000..8371c27466 --- /dev/null +++ b/Task/Draw-a-cuboid/C++/draw-a-cuboid.cpp @@ -0,0 +1,19 @@ +#include +#include + +int main() +{ + int k; + initwindow(1500,810,"Rosetta Cuboid"); + + do{ + std::cout<<"Enter ratio of sides ( 0 or -ve to exit) : "; + std::cin>>k; + + if(k>0){ + bar3d(100, 100, 100 + 2*k, 100 + 4*k, 3*k, 1); + } + }while(k>0); + + return 0; +} diff --git a/Task/Draw-a-cuboid/Elixir/draw-a-cuboid.elixir b/Task/Draw-a-cuboid/Elixir/draw-a-cuboid.elixir new file mode 100644 index 0000000000..336d2d74e4 --- /dev/null +++ b/Task/Draw-a-cuboid/Elixir/draw-a-cuboid.elixir @@ -0,0 +1,37 @@ +defmodule Cuboid do + @x 6 + @y 2 + @z 3 + @dir %{-: {1,0}, |: {0,1}, /: {1,1}} + + def draw(nx, ny, nz) do + IO.puts "cuboid #{nx} #{ny} #{nz}:" + {x, y, z} = {@x*nx, @y*ny, @z*nz} + area = Map.new + area = Enum.reduce(0..nz-1, area, fn i,acc -> draw_line(acc, x, 0, @z*i, :-) end) + area = Enum.reduce(0..ny, area, fn i,acc -> draw_line(acc, x, @y*i, z+@y*i, :-) end) + area = Enum.reduce(0..nx-1, area, fn i,acc -> draw_line(acc, z, @x*i, 0, :|) end) + area = Enum.reduce(0..ny, area, fn i,acc -> draw_line(acc, z, x+@y*i, @y*i, :|) end) + area = Enum.reduce(0..nz-1, area, fn i,acc -> draw_line(acc, y, x, @z*i, :/) end) + area = Enum.reduce(0..nx, area, fn i,acc -> draw_line(acc, y, @x*i, z, :/) end) + Enum.each(y+z..0, fn j -> + IO.puts Enum.map(0..x+y, fn i -> Dict.get(area, {i,j}, " ") end) |> Enum.join + end) + end + + defp draw_line(area, n, sx, sy, c) do + {dx, dy} = Dict.get(@dir, c) + draw_line(area, n, sx, sy, c, dx, dy) + end + + defp draw_line(area, n, _, _, _, _, _) when n<0, do: area + defp draw_line(area, n, i, j, c, dx, dy) do + area2 = Dict.update(area, {i,j}, c, fn _ -> :+ end) + draw_line(area2, n-1, i+dx, j+dy, c, dx, dy) + end +end + +Cuboid.draw(2,3,4) +Cuboid.draw(1,1,1) +Cuboid.draw(2,4,1) +Cuboid.draw(4,2,1) diff --git a/Task/Draw-a-cuboid/Java/draw-a-cuboid.java b/Task/Draw-a-cuboid/Java/draw-a-cuboid.java index 250c0c39f8..f37de3c840 100644 --- a/Task/Draw-a-cuboid/Java/draw-a-cuboid.java +++ b/Task/Draw-a-cuboid/Java/draw-a-cuboid.java @@ -1,30 +1,92 @@ import java.awt.*; +import java.awt.event.*; +import static java.lang.Math.*; import javax.swing.*; -public class Cuboid extends JFrame { +public class Cuboid extends JPanel { + double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1}, + {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}}; - public static void main(String[] args) { - JFrame f = new Cuboid(); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.setVisible(true); - } + int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6}, + {6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}}; + + int mouseX, prevMouseX, mouseY, prevMouseY; public Cuboid() { - Container content = getContentPane(); - content.setLayout(new BorderLayout()); - content.add(new CuboidPanel(), BorderLayout.CENTER); - setTitle("Cuboid"); - setResizable(false); - pack(); - setLocationRelativeTo(null); + setPreferredSize(new Dimension(640, 640)); + setBackground(Color.white); + + scale(80, 120, 160); + rotateCube(PI / 5, PI / 9); + + addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + mouseX = e.getX(); + mouseY = e.getY(); + } + }); + + addMouseMotionListener(new MouseAdapter() { + @Override + public void mouseDragged(MouseEvent e) { + prevMouseX = mouseX; + prevMouseY = mouseY; + mouseX = e.getX(); + mouseY = e.getY(); + + double incrX = (mouseX - prevMouseX) * 0.01; + double incrY = (mouseY - prevMouseY) * 0.01; + + rotateCube(incrX, incrY); + repaint(); + } + }); } -} -class CuboidPanel extends JPanel { + private void scale(double sx, double sy, double sz) { + for (double[] node : nodes) { + node[0] *= sx; + node[1] *= sy; + node[2] *= sz; + } + } - public CuboidPanel() { - setPreferredSize(new Dimension(600, 500)); - setBackground(Color.white); + private void rotateCube(double angleX, double angleY) { + double sinX = sin(angleX); + double cosX = cos(angleX); + + double sinY = sin(angleY); + double cosY = cos(angleY); + + for (double[] node : nodes) { + double x = node[0]; + double y = node[1]; + double z = node[2]; + + node[0] = x * cosX - z * sinX; + node[2] = z * cosX + x * sinX; + + z = node[2]; + + node[1] = y * cosY - z * sinY; + node[2] = z * cosY + y * sinY; + } + } + + void drawCube(Graphics2D g) { + g.translate(getWidth() / 2, getHeight() / 2); + + for (int[] edge : edges) { + double[] xy1 = nodes[edge[0]]; + double[] xy2 = nodes[edge[1]]; + g.drawLine((int) round(xy1[0]), (int) round(xy1[1]), + (int) round(xy2[0]), (int) round(xy2[1])); + } + + for (double[] node : nodes) { + g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8); + } } @Override @@ -34,13 +96,19 @@ public void paintComponent(Graphics gg) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.translate(165, -80); + drawCube(g); + } - g.drawRect(50, 275, 100, 100); - g.drawLine(50, 275, 130, 240); - g.drawLine(150, 275, 210, 240); - g.drawLine(130, 240, 210, 240); - g.drawLine(210, 240, 210, 340); - g.drawLine(150, 375, 210, 340); + public static void main(String[] args) { + SwingUtilities.invokeLater(() -> { + JFrame f = new JFrame(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setTitle("Cuboid"); + f.setResizable(false); + f.add(new Cuboid(), BorderLayout.CENTER); + f.pack(); + f.setLocationRelativeTo(null); + f.setVisible(true); + }); } } diff --git a/Task/Draw-a-cuboid/Liberty-BASIC/draw-a-cuboid-1.liberty b/Task/Draw-a-cuboid/Liberty-BASIC/draw-a-cuboid-1.liberty new file mode 100644 index 0000000000..f855f23116 --- /dev/null +++ b/Task/Draw-a-cuboid/Liberty-BASIC/draw-a-cuboid-1.liberty @@ -0,0 +1,27 @@ +Call cuboid 1,3,4 + +End + +Sub cuboid width, height, depth + wd=width*7+2: hi=height*3: dp=depth + For i=1 To wd-2 + w$=w$+"-":h$=h$+" " + Next + w$="+"+w$+"+":d$="/"+h$+"/":h$="|"+h$+"|" + px=dp+2:py=1:Locate dp+2,py:Print w$; + For i=2 To hi+1 + Locate wd+dp+1,i:Print"|"; + Next + Locate wd+dp+1, i: Print "+"; + For i=dp+1 To 1 Step -1 + py=py+1:Locate i,py:Print d$; + Next + For i=1 To dp + Locate wd+(dp+1)-i,hi+d+2+i:Print "/"; + Next + Locate 1, dp+2: Print w$; + For i=dp+3 To hi+dp+2 + Locate 1,i:Print h$; + Next + Locate 1, dp+hi+3: Print w$ +End Sub diff --git a/Task/Draw-a-cuboid/Liberty-BASIC/draw-a-cuboid-2.liberty b/Task/Draw-a-cuboid/Liberty-BASIC/draw-a-cuboid-2.liberty new file mode 100644 index 0000000000..c5b4803171 --- /dev/null +++ b/Task/Draw-a-cuboid/Liberty-BASIC/draw-a-cuboid-2.liberty @@ -0,0 +1,59 @@ +NoMainWin +Global sw, sh +sw = 400: sh = 400 +WindowWidth = sw+6 +WindowHeight= sh+32 +Open "[RC] Draw Cuboid" For graphics_nsb_nf As #g +#g "Down; Fill black; TrapClose [xit]" +#g "when leftButtonDown [xit]" + +Call drawCuboid 3,4,5 + +Wait + +[xit] +Close #g +End + +Sub drawCuboid width, height, depth + wd = width*50 + ht = height*50 + dp = depth*20 + sx = Int((sw-(wd+dp))/2) + sy = Int((sh-(ht-dp))/2) + #g "Color 0 128 255; BackColor 0 128 255" + #g "Place ";sx;" ";sy + #g "boxFilled ";sx+wd;" ";sy+ht + x1 = sx+dp : y1 = sy-dp + x2 = x1+wd-1 : y2 = y1+1 + #g "Color 0 64 128" + Call triFill sx,sy, x1,y1, x2,y2 + Call triFill sx,sy, x2,y2, sx+wd, sy + #g "Color 0 96 192" + x3 = x2: y3 = y2+ht + Call triFill x2,y2, x3,y3, sx+wd-1, sy+ht-1 + Call triFill x2,y2, sx+wd-1, sy+ht-1, sx+wd-1, sy + #g "Color white;BackColor black;Place 5 20" + #g "\Size: ";width;", ";height;", ";depth +End Sub + +Sub triFill x1,y1, x2,y2, x3,y3 + If x2x3 Then slope1=(y3-y1)/(x3-x1) + length=x2-x1 + If length<>0 Then + slope2=(y2-y1)/(x2-x1) + For x = 0 To length + #g "Line ";Int(x+x1);" ";Int(x*slope1+y1);" ";Int(x+x1);" ";Int(x*slope2+y1) + Next + End If + y = length*slope1+y1 :length=x3-x2 + If length<>0 Then + slope3=(y3-y2)/(x3-x2) + For x = 0 To length + #g "Line ";Int(x+x2);" ";Int(x*slope1+y);" ";Int(x+x2);" ";Int(x*slope3+y2) + Next + End If +End Sub diff --git a/Task/Draw-a-cuboid/Pure-Data/draw-a-cuboid.pure b/Task/Draw-a-cuboid/Pure-Data/draw-a-cuboid.pure new file mode 100644 index 0000000000..c36a4a40de --- /dev/null +++ b/Task/Draw-a-cuboid/Pure-Data/draw-a-cuboid.pure @@ -0,0 +1,21 @@ +#N canvas 1 51 450 300 10; +#X obj 66 67 gemwin; +#X obj 239 148 cuboid 2 3 4; +#X obj 239 46 gemhead; +#X obj 239 68 scale 0.3; +#X msg 66 45 lighting 1 \, create \, 1; +#X obj 61 118 gemhead; +#X obj 61 140 world_light; +#X msg 294 90 1; +#X obj 239 90 t a b; +#X obj 239 118 accumrotate; +#X connect 2 0 3 0; +#X connect 3 0 8 0; +#X connect 4 0 0 0; +#X connect 5 0 6 0; +#X connect 7 0 9 1; +#X connect 7 0 9 2; +#X connect 7 0 9 3; +#X connect 8 0 9 0; +#X connect 8 1 7 0; +#X connect 9 0 1 0; diff --git a/Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx b/Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx index 3700d42d06..5f7614a0ed 100644 --- a/Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx +++ b/Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx @@ -1,20 +1,17 @@ -/*REXX program to draw a cuboid (dimensions must be positive integers).*/ -parse arg x y z indent . /*x,y,z dimensions, indentation.*/ -x=p(x 1); y=p(y x); z=p(z y); indent=p(indent 0) - - call sayer y+2 , , "+-" - do j=1 for y; call sayer y-j+2, j-1, "/ |" ; end - call sayer , y , "+-|" - do z-1; call sayer , y , "| |" ; end - call sayer , y , "| +" - do j=1 for y; call sayer , y-j, "| /" ; end - call sayer , , "+-" - -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────P subroutine────────────────────────*/ -p: return word(arg(1),1) /*pick the first word in the list*/ -/*──────────────────────────────────SAYER subroutine────────────────────*/ -sayer: parse arg times,a,_ /*get the arguments specified. */ -say left('',indent)right(left(_,1),pick1(times 1)) || , - copies(substr(_,2,1),4*x)left(_,1)right(substr(_,3,1),pick1(a 0)+1) -return +/*REXX program displays a cuboid (dimensions must be positive integers). */ +parse arg x y z indent . /*x,y,z: dimensions and indentation. */ +x=p(x 2); y=p(y 3); z=p(z 4) /*use the defaults if not specified. */ +in=p(indent 0) + call show y+2 , , "+-" + do j=1 for y; call show y-j+2, j-1, "/ |" ; end + call show , y , "+-|" + do z-1; call show , y , "| |" ; end + call show , y , "| +" + do j=1 for y; call show , y-j, "| /" ; end + call show , , "+-" +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +p: return word(arg(1), 1) /*pick the first number or word in list*/ +/*────────────────────────────────────────────────────────────────────────────*/ +show: parse arg #,$,a 2 b 3 c 4 /*get the arguments (or parts thereof).*/ + say left('',in)right(a,p(# 1))copies(b,4*x)a || right(c,p($ 0)+1); return diff --git a/Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb b/Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb index ed5ff0d1e0..35a2499c76 100644 --- a/Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb +++ b/Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb @@ -1,22 +1,23 @@ +X, Y, Z = 6, 2, 3 DIR = {"-" => [1,0], "|" => [0,1], "/" => [1,1]} def cuboid(nx, ny, nz) puts "cuboid %d %d %d:" % [nx, ny, nz] - x, y, z = 8*nx, 2*ny, 4*nz + x, y, z = X*nx, Y*ny, Z*nz area = Array.new(y+z+1){" " * (x+y+1)} - line = lambda do |n, sx, sy, c| + draw_line = lambda do |n, sx, sy, c| dx, dy = DIR[c] (n+1).times do |i| xi, yi = sx+i*dx, sy+i*dy area[yi][xi] = (area[yi][xi]==" " ? c : "+") end end - nz .times {|i| line[x, 0, 4*i, "-"]} - (ny+1).times {|i| line[x, 2*i, z+2*i, "-"]} - nx .times {|i| line[z, 8*i, 0, "|"]} - (ny+1).times {|i| line[z, x+2*i, 2*i, "|"]} - nz .times {|i| line[y, x, 4*i, "/"]} - (nx+1).times {|i| line[y, 8*i, z, "/"]} + nz .times {|i| draw_line[x, 0, Z*i, "-"]} + (ny+1).times {|i| draw_line[x, Y*i, z+Y*i, "-"]} + nx .times {|i| draw_line[z, X*i, 0, "|"]} + (ny+1).times {|i| draw_line[z, x+Y*i, Y*i, "|"]} + nz .times {|i| draw_line[y, x, Z*i, "/"]} + (nx+1).times {|i| draw_line[y, X*i, z, "/"]} puts area.reverse end diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-1.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-1.basic index 72b4b0d8a8..55d69dbf7c 100644 --- a/Task/Draw-a-sphere/BASIC/draw-a-sphere-1.basic +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-1.basic @@ -1,19 +1,7 @@ -SCREEN 13 ' enter high-color graphic mode - -' sets palette colors B/N -FOR i = 0 TO 255 - PALETTE 255 - i, INT(i / 4) + INT(i / 4) * 256 + INT(i / 4) * 65536 -NEXT i -PALETTE 0, 0 - -' draw the sphere -FOR i = 255 TO 0 STEP -1 - x = 50 + i / 3 - y = 99 - CIRCLE (x, y), i / 3, i - PAINT (x, y), i -NEXT i - -' wait until keypress -DO: LOOP WHILE INKEY$ = "" -END +clg +color white +rect 0,0,graphwidth, graphheight +For n = 1 to 100 +color rgb(2*n,2*n,2*n) +circle 150-2*n/3,150-n/2,150-n +next n diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-10.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-10.basic new file mode 100644 index 0000000000..6b962ebe12 --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-10.basic @@ -0,0 +1,5 @@ +'This is a simple Circle +graphic #g, 300, 300 'create a graphic object +#g place(100,100) 'place the drawing pen at 100,100 +#g circle(75) 'make a circle with radius 75 +render #g 'show it diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-2.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-2.basic index 7729ff31ca..f5a4e0987c 100644 --- a/Task/Draw-a-sphere/BASIC/draw-a-sphere-2.basic +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-2.basic @@ -1 +1,117 @@ -MAKE OBJECT SPHERE 1,1 + MODE 8 + INSTALL @lib$+"D3DLIB" + D3DTS_VIEW = 2 + D3DTS_PROJECTION = 3 + D3DRS_SPECULARENABLE = 29 + + SYS "LoadLibrary", @lib$+"D3DX8BBC.DLL" TO d3dx% + IF d3dx%=0 ERROR 100, "Couldn't load D3DX8BBC.DLL" + SYS "GetProcAddress", d3dx%, "D3DXCreateSphere" TO `D3DXCreateSphere` + SYS "GetProcAddress", d3dx%, "D3DXMatrixLookAtLH" TO `D3DXMatrixLookAtLH` + SYS "GetProcAddress", d3dx%, "D3DXMatrixPerspectiveFovLH" TO `D3DXMatrixPerspectiveFovLH` + + DIM eyepos%(2), lookat%(2), up%(2), mat%(3,3) + + DIM D3Dlight8{Type%, Diffuse{r%,g%,b%,a%}, Specular{r%,g%,b%,a%}, \ + \ Ambient{r%,g%,b%,a%}, Position{x%,y%,z%}, Direction{x%,y%,z%}, \ + \ Range%, Falloff%, Attenuation0%, Attenuation1%, Attenuation2%, \ + \ Theta%, Phi%} + + DIM D3Dmaterial8{Diffuse{r%,g%,b%,a%}, Ambient{r%,g%,b%,a%}, \ + \ Specular{r%,g%,b%,a%}, Emissive{r%,g%,b%,a%}, Power%} + + DIM D3Dbasemesh8{QueryInterface%, Addref%, Release%, \ + \ DrawSubset%, GetNumFaces%, GetNumVertices%, GetFVF%, \ + \ GetDeclaration%, GetOptions%, GetDevice%, \ + \ CloneMeshFVF%, CloneMesh%, GetVertexBuffer%, GetIndexBuffer%, \ + \ LockVertexBuffer%, UnlockVertexBuffer%, LockIndexBuffer%, \ + \ UnlockIndexBuffer%, GetAttributeTable%} + + DIM D3Ddevice8{QueryInterface%, AddRef%, Release%, TestCooperativeLevel%, \ + \ GetAvailableTextureMem%, ResourceManagerDiscardBytes%, GetDirect3D%, \ + \ GetDeviceCaps%, GetDisplayMode%, GetCreationParameters%, SetCursorProperties%, \ + \ SetCursorPosition%, ShowCursor%, CreateAdditionalSwapChain%, Reset%, \ + \ Present%, GetBackBuffer%, GetRasterStatus%, SetGammaRamp%, GetGammaRamp%, \ + \ CreateTexture%, CreateVolumeTexture%, CreateCubeTexture%, CreateVertexBuffer%, \ + \ CreateIndexBuffer%, CreateRenderTarget%, CreateDepthStencilSurface%, \ + \ CreateImageSurface%, CopyRects%, UpdateTexture%, GetFrontBuffer%, \ + \ SetRenderTarget%, GetRenderTarget%, GetDepthStencilSurface%, BeginScene%, \ + \ EndScene%, Clear%, SetTransform%, GetTransform%, MultiplyTransform%, \ + \ SetViewport%, GetViewport%, SetMaterial%, GetMaterial%, SetLight%, GetLight%, \ + \ LightEnable%, GetLightEnable%, SetClipPlane%, GetClipPlane%, SetRenderState%, \ + \ GetRenderState%, BeginStateBlock%, EndStateBlock%, ApplyStateBlock%, \ + \ CaptureStateBlock%, DeleteStateBlock%, CreateStateBlock%, SetClipStatus%, \ + \ GetClipStatus%, GetTexture%, SetTexture%, GetTextureStageState%, \ + \ SetTextureStageState%, ValidateDevice%, GetInfo%, SetPaletteEntries%, \ + \ GetPaletteEntries%, SetCurrentTexturePalette%, GetCurrentTexturePalette%, \ + \ DrawPrimitive%, DrawIndexedPrimitive%, DrawPrimitiveUP%, \ + \ DrawIndexedPrimitiveUP%, ProcessVertices%, CreateVertexShader%, \ + \ SetVertexShader%, GetVertexShader%, DeleteVertexShader%, \ + \ SetVertexShaderConstant%, GetVertexShaderConstant%, GetVertexShaderDeclaration%, \ + \ GetVertexShaderFunction%, SetStreamSource%, GetStreamSource%, SetIndices%, \ + \ GetIndices%, CreatePixelShader%, SetPixelShader%, GetPixelShader%, \ + \ DeletePixelShader%, SetPixelShaderConstant%, GetPixelShaderConstant%, \ + \ GetPixelShaderFunction%, DrawRectPatch%, DrawTriPatch%, DeletePatch%} + + pDevice%=FN_initd3d(@hwnd%, 1, 1) + IF pDevice%=0 ERROR 100, "Couldn't create Direct3D8 device" + !(^D3Ddevice8{}+4) = !pDevice% + + SYS `D3DXCreateSphere`, pDevice%, FN_f4(1), 50, 50, ^meshSphere%, 0 + IF meshSphere% = 0 ERROR 100, "D3DXCreateSphere failed" + !(^D3Dbasemesh8{}+4) = !meshSphere% + + REM. Point-source light: + D3Dlight8.Type%=1 : REM. point source + D3Dlight8.Diffuse.r% = FN_f4(1) + D3Dlight8.Diffuse.g% = FN_f4(1) + D3Dlight8.Diffuse.b% = FN_f4(1) + D3Dlight8.Specular.r% = FN_f4(1) + D3Dlight8.Specular.g% = FN_f4(1) + D3Dlight8.Specular.b% = FN_f4(1) + D3Dlight8.Position.x% = FN_f4(2) + D3Dlight8.Position.y% = FN_f4(1) + D3Dlight8.Position.z% = FN_f4(4) + D3Dlight8.Range% = FN_f4(10) + D3Dlight8.Attenuation0% = FN_f4(1) + + REM. Material: + D3Dmaterial8.Diffuse.r% = FN_f4(0.2) + D3Dmaterial8.Diffuse.g% = FN_f4(0.6) + D3Dmaterial8.Diffuse.b% = FN_f4(1.0) + D3Dmaterial8.Specular.r% = FN_f4(0.4) + D3Dmaterial8.Specular.g% = FN_f4(0.4) + D3Dmaterial8.Specular.b% = FN_f4(0.4) + D3Dmaterial8.Power% = FN_f4(100) + + fovy = RAD(30) + aspect = 5/4 + znear = 1 + zfar = 1000 + bkgnd% = &7F7F7F + eyepos%() = 0, 0, FN_f4(6) + lookat%() = 0, 0, 0 + up%() = 0, FN_f4(1), 0 + + SYS D3Ddevice8.Clear%, pDevice%, 0, 0, 3, bkgnd%, FN_f4(1), 0 + SYS D3Ddevice8.BeginScene%, pDevice% + SYS D3Ddevice8.SetLight%, pDevice%, 0, D3Dlight8{} + SYS D3Ddevice8.LightEnable%, pDevice%, 0, 1 + SYS D3Ddevice8.SetMaterial%, pDevice%, D3Dmaterial8{} + SYS D3Ddevice8.SetRenderState%, pDevice%, D3DRS_SPECULARENABLE, 1 + + SYS `D3DXMatrixLookAtLH`, ^mat%(0,0), ^eyepos%(0), ^lookat%(0), ^up%(0) + SYS D3Ddevice8.SetTransform%, pDevice%, D3DTS_VIEW, ^mat%(0,0) + + SYS `D3DXMatrixPerspectiveFovLH`, ^mat%(0,0), FN_f4(fovy), \ + \ FN_f4(aspect), FN_f4(znear), FN_f4(zfar) + SYS D3Ddevice8.SetTransform%, pDevice%, D3DTS_PROJECTION, ^mat%(0,0) + + SYS D3Dbasemesh8.DrawSubset%, meshSphere%, 0 + SYS D3Ddevice8.EndScene%, pDevice% + SYS D3Ddevice8.Present%, pDevice%, 0, 0, 0, 0 + + SYS D3Ddevice8.Release%, pDevice% + SYS D3Dbasemesh8.Release%, meshSphere% + SYS "FreeLibrary", d3dx% + END diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-3.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-3.basic new file mode 100644 index 0000000000..7729ff31ca --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-3.basic @@ -0,0 +1 @@ +MAKE OBJECT SPHERE 1,1 diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-4.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-4.basic new file mode 100644 index 0000000000..220de6134d --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-4.basic @@ -0,0 +1,48 @@ +' "\" = a integer division (CPU) +' "/" = a floating point division (FPU) +' the compiler takes care of the conversion between floating point and integer +' compile with: FBC -s console "filename.bas" or FBC -s GUI "filename.bas" +' filename is whatever name you give it, .bas is mandatory + +' Sphere using XPL0 code from rosetacode sphere page +' Altered freebasic version to compile in default mode +' version 17-06-2015 +' compile with: fbc -s console or fbc -s gui +#Define W 640 +#Define H 480 + +ScreenRes W, H, 32 ' set 640x480x32 graphics mode, 32 bits color mode +WindowTitle "32 bpp Cyan Sphere FreeBASIC" + +' wait until keypress +' Color(RGB(255,255,255),RGB(0,0,0)) ' default white foreground, black background +Locate 50,2 +Print "Enter any key to start" +Sleep + +Dim As UInteger R = 100, R2 = R * R ' radius, in pixels; radius squared +Dim As UInteger X0 = W \ 2, Y0 = H \ 2 ' coordinates of center of screen +Dim As Integer X, Y, C, D2 ' coords, color, distance from center squared + +For Y = -R To R ' for all the coordinates near the circle + For X = -R To R ' which is under the sphere + D2 = X * X + Y * Y + If D2 <= R2 Then ' coordinate is inside circle under sphere + ' height of point on surface of sphere above X,Y + C = Sqr(R2 - D2) - ( X + Y) / 2 + 130 ' color is proportional; offset X and Y, and + + Color C Shl 8 + C ' = color RGB(0, C, C) + ' green + blue = cyan + PSet(X + X0, Y + Y0) + End If + Next +Next + +' wait until keypress +Locate 50,2 +Color(RGB(255,255,255),RGB(0,0,0)) ' foreground color is changed +' empty keyboard buffer +While InKey <> "" : Var _key_ = InKey : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-5.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-5.basic new file mode 100644 index 0000000000..d919926305 --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-5.basic @@ -0,0 +1,36 @@ +'Sphere for FreeBASIC May 2015 +'spherefb4.bas +'Sphere using XPL0 code from rosetacode sphere page +' +screenres 640,480,32 '\set 640x480x32 graphics mode +windowtitle "32 bpp Blue Sphere FreeBASIC" +' +' wait until keypress +locate 50,2 +color(rgb(255,255,255),rgb(0,0,0)) +Print "Enter any key to start" +sleep + R=100 : R2=R*R '\radius, in pixels; radius squared + X0=640/2 : Y0=480/2 '\coordinates of center of screen + dim as integer X, Y, Z, C, D2 '\coords, color, distance from center squared +' +for Y= -R to +R '\for all the coordinates near the circle + for X = -R to +R '\ which is under the sphere + D2 = X*X + Y*Y ' + C = 0 '\default color is black + if D2 <= R2 then '\coordinate is inside circle under sphere + Z = sqr(R2-D2) '\height of point on surface of sphere above X,Y + C = Z-(X+Y)/2+130 ' \color is proportional; offset X and Y, and + endif + color c ' \ shift color to upper limit of its range + '\green + blue = cyan orginal line don't understand + Pset(X+X0, Y+Y0) + next x + next y +' +' wait until keypress +locate 50,2 +color(rgb(255,255,255),rgb(0,0,0)) +Print "Enter any key to exit " +sleep +END diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-6.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-6.basic new file mode 100644 index 0000000000..735550a7b8 --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-6.basic @@ -0,0 +1,26 @@ +WindowWidth =420 +WindowHeight =460 + +nomainwin + +open "Sphere" for graphics_nsb_nf as #w + +#w "down ; fill lightgray" + +xS =200 +yS =200 +for radius =150 to 0 step -1 + level$ =str$( int( 256 -256 *radius /150)) + c$ =level$ +" " +level$ +" " +level$ + #w "color "; c$ + #w "backcolor "; c$ + #w "place "; xS; " "; yS + xS =xS -0.5 + yS =yS -0.2 + #w "circlefilled "; radius +next radius + +#w "flush" +wait +close #w +end diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-7.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-7.basic new file mode 100644 index 0000000000..62ec5d717d --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-7.basic @@ -0,0 +1,251 @@ +; Original by Comtois @ 28/03/06 +; +; Updated/Formated by Fluid Byte @ March.24,2009 +; +; http://www.purebasic.fr/english/viewtopic.php?p=281258#p281258 + +Declare CreateSphere(M,P) +Declare UpdateMesh() + +#_SIZEVERT = 36 +#_SIZETRIS = 6 +#FULLSCREEN = 0 + +Structure VECTOR + X.f + Y.f + Z.f +EndStructure + +Structure VERTEX + X.f + Y.f + Z.f + NX.f + NY.f + NZ.f + Color.l + U.f + V.f +EndStructure + +Structure TRIANGLE + V1.w + V2.w + V3.w +EndStructure + +Macro CALC_NORMALS + *PtrV\NX = *PtrV\X + *PtrV\NY = *PtrV\Y + *PtrV\NZ = *PtrV\Z +EndMacro + +Global *VBuffer, *IBuffer +Global Meridian = 50, Parallele = 50, PasLength = 4, Length + +Define EventID, i, NbSommet, CameraMode, Angle.f, Pas.f = 0.5 + +InitEngine3D() : InitSprite() : InitKeyboard() + +Add3DArchive(GetTemporaryDirectory(),#PB_3DArchive_FileSystem) +Add3DArchive(#PB_Compiler_Home + "Examples\Sources\Data\",#PB_3DArchive_FileSystem) + +If #FULLSCREEN + OpenScreen(800,600,32,"Sphere 3D") +Else + OpenWindow(0,0,0,800,600,"Sphere 3D",#PB_Window_SystemMenu | 1) + OpenWindowedScreen(WindowID(0),0,0,800,600,0,0,0) +EndIf + +;-Texture +CreateImage(0,128,128) +StartDrawing(ImageOutput(0)) +For i = 0 To 127 Step 4 + Box(0,i,ImageWidth(0),2,RGB(255,255,255)) + Box(0,i + 2,ImageWidth(0),2,RGB(0,0,155)) +Next i +StopDrawing() +SaveImage(0,GetTemporaryDirectory() + "temp.bmp") : FreeImage(0) + +;-Material +CreateMaterial(0,LoadTexture(0,"temp.bmp")) +RotateMaterial(0,0.1,#PB_Material_Animated) + +;-Mesh +CreateSphere(Meridian,Parallele) + +;-Entity +CreateEntity(0,MeshID(0),MaterialID(0)) +ScaleEntity(0,60,60,60) + +;-Camera +CreateCamera(0,0,0,100,100) +MoveCamera(0,0,0,-200) +CameraLookAt(0,EntityX(0),EntityY(0),EntityZ(0)) + +;-Light +AmbientColor(RGB(105, 105, 105)) +CreateLight(0, RGB(255, 255, 55), EntityX(0) + 150, EntityY(0) , EntityZ(0)) +CreateLight(1, RGB( 55, 255, 255), EntityX(0) - 150, EntityY(0) , EntityZ(0)) +CreateLight(2, RGB( 55, 55, 255), EntityX(0) , EntityY(0) + 150, EntityZ(0)) +CreateLight(3, RGB(255, 55, 255), EntityX(0) , EntityY(0) - 150, EntityZ(0)) + +; ---------------------------------------------------------------------------------------------------- +; MAINLOOP +; ---------------------------------------------------------------------------------------------------- + +Repeat + If #FULLSCREEN = 0 + Repeat + EventID = WindowEvent() + + Select EventID + Case #PB_Event_CloseWindow : End + EndSelect + Until EventID = 0 + EndIf + + Angle + Pas + RotateEntity(0, Angle, Angle,Angle) + + If PasLength > 0 : UpdateMesh() : EndIf + + If ExamineKeyboard() + If KeyboardReleased(#PB_Key_F1) + CameraMode = 1 - CameraMode + CameraRenderMode(0, CameraMode) + EndIf + EndIf + + RenderWorld() + FlipBuffers() +Until KeyboardPushed(#PB_Key_Escape) + +; ---------------------------------------------------------------------------------------------------- +; FUNCTIONS +; ---------------------------------------------------------------------------------------------------- + +Procedure CreateSphere(M,P) + ; M = Meridian + ; P = Parallele + ; The radius is 1. Front to remove it later, it's just for the demo. + + If M < 3 Or P < 2 : ProcedureReturn 0 : EndIf + + Protected Normale.VECTOR, NbSommet, i, j, Theta.f, cTheta.f, sTheta.f + Protected Alpha.f, cAlpha.f, sAlpha.f, *PtrV.VERTEX, *PtrF.TRIANGLE, NbTriangle + + NbSommet = 2 + ((M + 1) * P) + *VBuffer = AllocateMemory(#_SIZEVERT * Nbsommet) + + For i = 0 To M + Theta = i * #PI * 2.0 / M + cTheta = Cos(theta) + sTheta = Sin(theta) + + For j = 1 To P + Alpha = j * #PI / (P + 1) + cAlpha = Cos(Alpha) + sAlpha = Sin(Alpha) + *PtrV = *VBuffer + #_SIZEVERT * ((i * P) + (j - 1)) + *PtrV\X = sAlpha * cTheta + *PtrV\Y = sAlpha * sTheta + *PtrV\Z = cAlpha + *PtrV\U = Theta / (2.0 * #PI) + *PtrV\V = Alpha / #PI + CALC_NORMALS + Next j + Next i + + ; Southpole + *PtrV = *VBuffer + #_SIZEVERT * ((M + 1) * P) + *PtrV\X = 0 + *PtrV\Y = 0 + *PtrV\Z = -1 + *PtrV\U = 0 + *PtrV\V = 0 + CALC_NORMALS + + ; Northpole + *PtrV + #_SIZEVERT + *PtrV\X = 0 + *PtrV\Y = 0 + *PtrV\Z = 1 + *PtrV\U = 0 + *PtrV\V = 0 + CALC_NORMALS + + ; Les facettes + NbTriangle = 4 * M * P + *IBuffer = AllocateMemory(#_SIZETRIS * NbTriangle) + *PtrF = *IBuffer + + For i = 0 To M - 1 + For j = 1 To P - 1 + *PtrF\V1 = ((i + 1) * P) + j + *PtrF\V2 = ((i + 1) * P) + (j - 1) + *PtrF\V3 = (i * P) + (j - 1) + *PtrF + #_SIZETRIS + *PtrF\V3 = ((i + 1) * P) + j ;Recto + *PtrF\V2 = ((i + 1) * P) + (j - 1) ;Recto + *PtrF\V1 = (i * P) + (j - 1) ;Recto + *PtrF + #_SIZETRIS + *PtrF\V1 = i * P + j + *PtrF\V2 = ((i + 1) * P) + j + *PtrF\V3 = (i * P) + (j - 1) + *PtrF + #_SIZETRIS + *PtrF\V3 = i * P + j ;Recto + *PtrF\V2 = ((i + 1) * P) + j ;Recto + *PtrF\V1 = (i * P) + (j - 1) ;Recto + *PtrF + #_SIZETRIS + Next j + Next i + + ; The Poles + For i = 0 To M - 1 + *PtrF\V3 = (M + 1) * P + 1 + *PtrF\V2 = (i + 1) * P + *PtrF\V1 = i * P + *PtrF + #_SIZETRIS + *PtrF\V1 = (M + 1) * P + 1 ;Recto + *PtrF\V2 = (i + 1) * P ;Recto + *PtrF\V3 = i * P ;Recto + *PtrF + #_SIZETRIS + Next i + + For i = 0 To M - 1 + *PtrF\V3 = (M + 1) * P + *PtrF\V2 = i * P + (P - 1) + *PtrF\V1 = (i + 1) * P + (P - 1) + *PtrF + #_SIZETRIS + *PtrF\V1 = (M + 1) * P ;Recto + *PtrF\V2 = i * P + (P - 1) ;Recto + *PtrF\V3 = (i + 1) * P + (P - 1) ;Recto + *PtrF + #_SIZETRIS + Next i + + If CreateMesh(0,100) + Protected Flag = #PB_Mesh_Vertex | #PB_Mesh_Normal | #PB_Mesh_UVCoordinate | #PB_Mesh_Color + SetMeshData(0,Flag,*VBuffer,NbSommet) + SetMeshData(0,#PB_Mesh_Face,*IBuffer,NbTriangle) + ProcedureReturn 1 + EndIf + + ProcedureReturn 0 +EndProcedure + +; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +Procedure UpdateMesh() + Protected NbTriangle = 4 * Meridian * Parallele + + Length + PasLength + + If Length >= NbTriangle + PasLength = 0 + Length = Nbtriangle + EndIf + + SetMeshData(0,#PB_Mesh_Face,*IBuffer,Length) +EndProcedure diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-8.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-8.basic new file mode 100644 index 0000000000..72b4b0d8a8 --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-8.basic @@ -0,0 +1,19 @@ +SCREEN 13 ' enter high-color graphic mode + +' sets palette colors B/N +FOR i = 0 TO 255 + PALETTE 255 - i, INT(i / 4) + INT(i / 4) * 256 + INT(i / 4) * 65536 +NEXT i +PALETTE 0, 0 + +' draw the sphere +FOR i = 255 TO 0 STEP -1 + x = 50 + i / 3 + y = 99 + CIRCLE (x, y), i / 3, i + PAINT (x, y), i +NEXT i + +' wait until keypress +DO: LOOP WHILE INKEY$ = "" +END diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-9.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-9.basic new file mode 100644 index 0000000000..098b6f2b9a --- /dev/null +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-9.basic @@ -0,0 +1,18 @@ +'Run BASIC White Sphere, Black background +'runbasic.com +graphic #win, 300, 300 +#win size(1) + R=100 + R2=R*R + X0=300/2 + Y0=300/2 +for Y = -150 to 150 +for X = -150 to 150 + D2 = X*X + Y*Y + C = 0 + if D2 <= R2 then Z = sqr(R2-D2) : C = int(Z-(X+Y)/2+130) + #win color(C,C,C) + #win set(X+X0, Y+Y0) +next X +next Y +render #win diff --git a/Task/Draw-a-sphere/Befunge/draw-a-sphere.bf b/Task/Draw-a-sphere/Befunge/draw-a-sphere.bf new file mode 100644 index 0000000000..a4e78dab12 --- /dev/null +++ b/Task/Draw-a-sphere/Befunge/draw-a-sphere.bf @@ -0,0 +1,8 @@ +45*65*65*"2"30p20p10p::00p2*40p4*5vv< +>60p140g->:::*00g50g*60g40g-:*-\-v0>1 +^_@#`\g0<|`\g04:+1, <*84$$_v#`\0:<>p^ +>v>g2+:5^$>g:*++*/7g^>*:9$#<"~"/:"~"v +g:^06,+55<^03*#0 *#12#<0g:^>+::"~~"90g*80g+*70gv| +g-10g*+:9**00gv|!*`\2\`-20::/2-\/\+<> +%#&eo*!:..^g05<>$030g-*9/\20g*+60g40^ diff --git a/Task/Draw-a-sphere/J/draw-a-sphere-2.j b/Task/Draw-a-sphere/J/draw-a-sphere-2.j index d97a96eb72..bbcb8914b3 100644 --- a/Task/Draw-a-sphere/J/draw-a-sphere-2.j +++ b/Task/Draw-a-sphere/J/draw-a-sphere-2.j @@ -4,5 +4,5 @@ pts =. (0&*^:(0={:))@:(,,(0>.(*:R)-+)&.*:)"0/~ i:15j200 luminosity =. (>:ambient) %~ (ambient * * +/&.:*:"1 pts) + k^~ 0>. R%~ pts +/@:*"1 -light load 'viewmat' -togreyscale =. 256 #. [: <. 255 255 255 *"1 0 ] -'rgb' viewmat togreyscale luminosity +torgb =. 256 #. [: <. 255 255 255 *"1 0 ] +'rgb' viewmat torgb luminosity diff --git a/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 b/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 index 4f41110b8f..6eee506c40 100644 --- a/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 +++ b/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 @@ -12,15 +12,15 @@ sub MAIN ($outfile = 'sphere-perl6.pgm') { $out.close; } -sub normalize (@vec) { return @vec »/» ([+] @vec Z* @vec).sqrt } +sub normalize (@vec) { return @vec »/» ([+] @vec »*« @vec).sqrt } -sub dot (@x, @y) { return -([+] @x Z* @y) max 0 } +sub dot (@x, @y) { return -([+] @x »*« @y) max 0 } sub draw_sphere ( $rad, $k, $ambient ) { my @pixels; my $r2 = $rad * $rad; my @range = -$rad .. $rad; - for @range X @range -> $x, $y { + for flat @range X @range -> $x, $y { if (my $x2 = $x * $x) + (my $y2 = $y * $y) < $r2 { my @vector = normalize([$x, $y, ($r2 - $x2 - $y2).sqrt]); my $intensity = dot(@light, @vector) ** $k + $ambient; diff --git a/Task/Draw-a-sphere/Python/draw-a-sphere-4.py b/Task/Draw-a-sphere/Python/draw-a-sphere-4.py index 902d7ff998..a9697f7f23 100644 --- a/Task/Draw-a-sphere/Python/draw-a-sphere-4.py +++ b/Task/Draw-a-sphere/Python/draw-a-sphere-4.py @@ -1,3 +1,3 @@ from visual import * scene.title = "VPython: Draw a sphere" -sphere() # using defaults, see http://www.vpython.org/contents/docs/defaults.html defaults] +sphere() # using defaults, see http://www.vpython.org/contents/docs/defaults.html diff --git a/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx b/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx index 52be4305b8..af1ded11a5 100644 --- a/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx +++ b/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx @@ -1,38 +1,39 @@ -/*REXX program expresses a lighted sphere with simple chars for shading.*/ -call drawSphere 19, 4, 2/10 /*draw a sphere with radius 19. */ -call drawSphere 10, 2, 4/10 /*draw a sphere with radius ten. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────DRAWSPHERE subroutine───────────────*/ -drawSphere: procedure; parse arg r, k, ambient /*get the arguments*/ -if 1=='f1'x then shading='.:!*oe&#%@' /*EBCDIC dithering.*/ - else shading='·:!°oe@░▒▓' /*ASCII " */ -lightSource = '30 30 -50' /*the light source.*/ -parse value norm(lightSource) with s1 s2 s3 /*normalize light S*/ -sLen=length(shading); sLen1=sLen-1; rr=r*r /*handy-dandy vars.*/ +/*REXX program expresses a lighted sphere with simple characters for shading.*/ +call drawSphere 19, 4, 2/10 /*draw a sphere with a radius of 19. */ +call drawSphere 10, 2, 4/10 /* " " " " " " " ten. */ +exit /*stick a fork in it, we're all done. */ +/*─────────────────────────────────────one─liner subroutines──────────────────*/ +ceil: procedure; parse arg x; _=trunc(x); return _ + (x>0) *(x\=_) +floor: procedure; parse arg x; _=trunc(x); return _ - (x<0) *(x\=_) +norm: parse arg _1 _2 _3; _=sqrt(_1**2+_2**2+_3**2); return _1/_ _2/_ _3/_ +/*──────────────────────────────────DRAWSPHERE subroutine─────────────────────*/ +drawSphere: procedure; parse arg r, k, ambient /*get the arguments from CL*/ +if 1=='f1'x then shading= ".:!*oe&#%@" /* EBCDIC dithering chars. */ + else shading= "·:!°oe@░▒▓" /* ASCII " " */ +lightSource = '30 30 -50' /*position of light source.*/ +parse value norm(lightSource) with s1 s2 s3 /*normalize light source. */ +sLen=length(shading)-1; rr=r*r /*handy─dandy variables. */ - do i=floor(-r) to ceil(r) ; x= i+.5; xx=x**2; aLine= - do j=floor(-2*r) to ceil(2*r); y=j/2+.5; yy=y**2 - if xx+yy<=rr then do /*within the phere?*/ - parse value norm(x y sqrt(rr-xx-yy)) with v1 v2 v3 - dot=s1*v1 + s2*v2 + s3*v3 /*dot product of Vs*/ - if dot>0 then dot=0 /*if pos, make it 0*/ - b=abs(dot)**k + ambient /*calc. brightness.*/ - if b<=0 then brite=sLenm1 - else brite=trunc( max( (1-b) * sLen1, 0) ) - aLine=aLine || substr(shading,brite+1,1) /*build.*/ - end - else aLine=aLine' ' /*append a blank. */ + do i=floor(-r) to ceil(r) ; x= i+.5; xx=x**2; $= + do j=floor(-2*r) to ceil(r+r); y=j/2+.5; yy=y**2 + if xx+yy<=rr then do /*is point within sphere ? */ + parse value norm(x y sqrt(rr-xx-yy)) with v1 v2 v3 + dot=s1*v1 + s2*v2 + s3*v3 /*the dot product of the Vs*/ + if dot>0 then dot=0 /*if positive, make it zero*/ + b=abs(dot)**k + ambient /*calculate the brightness.*/ + if b<=0 then brite=sLen + else brite=trunc( max( (1-b) * sLen, 0) ) + $=($)substr(shading,brite+1,1) /*build a display line.*/ + end + else $=$' ' /*append a blank to line. */ end /*j*/ - say strip(aLine,'trailing') /*show a line of it*/ - end /*i*/ /* [↑] show sphere*/ + say strip($,'trailing') /*show a line of the sphere*/ + end /*i*/ /* [↑] display the sphere.*/ return -/*─────────────────────────────────────subroutines────────────────────────────*/ -ceil: procedure; parse arg x; _=trunc(x); return _ + (x>0) * (x\=_) -floor: procedure; parse arg x; _=trunc(x); return _ - (x<0) * (x\=_) -norm: parse arg _1 _2 _3; _=sqrt(_1**2+_2**2+_3**2); return _1/_ _2/_ _3/_ -/*─────────────────────────────────────SQRT subroutine────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); p=d+d%4+2; m.=11 - numeric digits m.;numeric form;parse value format(x,2,1,,0) 'E0' with g 'E' _ . - g=g*.5'E'_%2; do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end - numeric digits d; return g/1 +/*──────────────────────────────────SQRT subroutine───────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Draw-a-sphere/Tcl/draw-a-sphere.tcl b/Task/Draw-a-sphere/Tcl/draw-a-sphere.tcl index aa3d780efc..cc9f48e1d8 100644 --- a/Task/Draw-a-sphere/Tcl/draw-a-sphere.tcl +++ b/Task/Draw-a-sphere/Tcl/draw-a-sphere.tcl @@ -5,5 +5,5 @@ pack [canvas .c -height 400 -width 640 -background white] for {set i 0} {$i < 255} {incr i} { set h [grey $i] .c create arc [expr {100+$i/5}] [expr {50+$i/5}] [expr {400-$i/1.5}] [expr {350-$i/1.5}] \ - -start 0 -extent 359 -fill $h -outline $h} + -start 0 -extent 359 -fill $h -outline $h } diff --git a/Task/Dutch-national-flag-problem/00DESCRIPTION b/Task/Dutch-national-flag-problem/00DESCRIPTION index 1d35506cad..d8f60db15e 100644 --- a/Task/Dutch-national-flag-problem/00DESCRIPTION +++ b/Task/Dutch-national-flag-problem/00DESCRIPTION @@ -7,6 +7,16 @@ When the problem was first posed, Dijkstra then went on to successively refine a # Sort the balls in a way idiomatic to your language. # Check the sorted balls ''are'' in the order of the Dutch national flag. +
+; A rendition of the Dutch flag: + 
+████████████
+████████████
+████████████
+████████████
+████████████
+████████████

+ ;Cf. * [[wp:Dutch national flag problem|Dutch national flag problem]] * [https://www.google.co.uk/search?rlz=1C1DSGK_enGB472GB472&sugexp=chrome,mod=8&sourceid=chrome&ie=UTF-8&q=Dutch+national+flag+problem#hl=en&rlz=1C1DSGK_enGB472GB472&sclient=psy-ab&q=Probabilistic+analysis+of+algorithms+for+the+Dutch+national+flag+problem&oq=Probabilistic+analysis+of+algorithms+for+the+Dutch+national+flag+problem&gs_l=serp.3...60754.61818.1.62736.1.1.0.0.0.0.72.72.1.1.0...0.0.Pw3RGungndU&psj=1&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.,cf.osb&fp=c33d18147f5082cc&biw=1395&bih=951 Probabilistic analysis of algorithms for the Dutch national flag problem] by Wei-Mei Chen. (pdf) diff --git a/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir b/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir new file mode 100644 index 0000000000..ffd91a6231 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Elixir/dutch-national-flag-problem.elixir @@ -0,0 +1,32 @@ +defmodule Dutch_national_flag do + defp ball(:red), do: 1 + defp ball(:white), do: 2 + defp ball(:blue), do: 3 + + @color {:red, :white, :blue} + defp random_ball, do: elem(@color, :rand.uniform(3)-1) + defp random_ball(n), do: (for _ <- 1..n, do: random_ball) + + defp is_dutch([]), do: true + defp is_dutch([_]), do: true + defp is_dutch([b,h|l]), do: ball(b) < ball(h) and is_dutch([h|l]) + defp is_dutch(_), do: false + + def dutch(list), do: dutch([], [], [], list) + defp dutch(r, w, b, []), do: r ++ w ++ b + defp dutch(r, w, b, [:red | list]), do: dutch([:red | r], w, b, list) + defp dutch(r, w, b, [:white | list]), do: dutch(r, [:white | w], b, list) + defp dutch(r, w, b, [:blue | list]), do: dutch(r, w, [:blue | b], list) + + def problem(n \\ 10) do + list = random_ball(n) + if is_dutch(list) do + IO.puts "The random sequence #{inspect list} is already in the order of the Dutch flag!" + else + IO.puts "The starting random sequence is #{inspect list};" + IO.puts "The ordered sequence is #{inspect dutch(list)}." + end + end +end + +Dutch_national_flag.problem diff --git a/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.julia b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.julia new file mode 100644 index 0000000000..6ac9875975 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-1.julia @@ -0,0 +1,24 @@ +const COLORS = ["red", "white", "blue"] + +function dutchsort!(a::Array{ASCIIString,1}, lo=COLORS[1], hi=COLORS[end]) + i = 1 + j = 1 + n = length(a) + while j <= n + if a[j] == lo + a[i], a[j] = a[j], a[i] + i += 1 + j += 1 + elseif a[j] == hi + a[j], a[n] = a[n], a[j] + n -= 1 + else + j += 1 + end + end + return a +end + +function dutchsort(a::Array{ASCIIString,1}, lo=COLORS[1], hi=COLORS[end]) + dutchsort!(copy(a), lo, hi) +end diff --git a/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.julia b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.julia new file mode 100644 index 0000000000..d597551c58 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Julia/dutch-national-flag-problem-2.julia @@ -0,0 +1,30 @@ +function formatdf(a::Array{ASCIIString,1}) + i = 0 + s = " " + for c in a + s *= @sprintf "%6s" c + i += 1 + i %= 8 + if i == 0 + s *= "\n " + end + end + return s +end + +cnum = 20 +d = [COLORS[rand(1:3)] for i in 1:cnum] +while d == dutchsort(d) + d = [COLORS[rand(1:3)] for i in 1:cnum] +end + +println("The original list is:") +println(formatdf(d)) + +print("Sorting with dutchsort, ") +@time e = dutchsort(d) +println(formatdf(e)) + +print("Sorting conventionally, ") +@time e = sort(d, by=x->findfirst(COLORS, x)) +println(formatdf(e)) diff --git a/Task/Dutch-national-flag-problem/REXX/dutch-national-flag-problem-1.rexx b/Task/Dutch-national-flag-problem/REXX/dutch-national-flag-problem-1.rexx index 2597757634..6e9782d0f0 100644 --- a/Task/Dutch-national-flag-problem/REXX/dutch-national-flag-problem-1.rexx +++ b/Task/Dutch-national-flag-problem/REXX/dutch-national-flag-problem-1.rexx @@ -1,33 +1,32 @@ -/*REXX pgm to reorder a set of random colored balls into a correct order*/ -/*which is the order of colors on the Dutch flag: red, white, blue. */ +/*REXX program reorders a set of random colored balls into a correct order, */ +/*────────────which is the order of colors on the Dutch flag: red white blue.*/ +parse arg N colors /*get optional parameters from the CL. */ +if N=',' | N='' then N=15 /*Not specified? Then use the default.*/ +if colors='' then colors=space('red white blue') /*use the default colors? */ +#=words(colors) /*count the number of colors specified.*/ +@=word(colors,#) word(colors,1) /*ensure balls aren't already in order.*/ -parse arg N colors /*get user args from command line*/ -if N=',' | N='' then N=15 /*use default number of balls. */ -if N='' then N=15 /*use default number of balls. */ -if colors='' then colors=space('red white blue') /*use default colors.*/ -Ncolors=words(colors) /*count the number of colors. */ -@=word(colors,Ncolors) word(colors,1) /*ensure balls aren't in order. */ + do g=3 to N /*generate a random # of colored balls.*/ + @=@ word(colors, random(1, #)) /*append a random color to the @ list.*/ + end /*g*/ - do g=3 to N /*generate a random # of balls. */ - @=@ word(colors,random(1,Ncolors)) - end /*g*/ - -say 'number of colored balls generated = ' N ; say -say 'original ball order:' -say @ ; say -$=; do j=1 for Ncolors; ; _=word(colors,j) - $=$ copies(_' ',countWords(_,@)) - end /*j*/ -say ' sorted ball order:' -say space($); say - - do k=2 to N /*ensure the balls are in order. */ - if wordpos(word($,k),colors)>=wordpos(word($,k-1),colors) then iterate - say "The list of sorted balls isn't in proper order!"; exit 13 +say 'number of colored balls generated = ' N ; say +say center(' original ball order ', length(@), '─') +say @ ; say +$=; do j=1 for #; ; _=word(colors, j) + $=$ copies(_' ', countWords(_, @)) + end /*j*/ +say +say center(' sorted ball order ', length(@), '─') +say space($) +say + do k=2 to N /*verify the balls are in correct order*/ + if wordpos(word($,k), colors) >= wordpos(word($,k-1), colors) then iterate + say "The list of sorted balls isn't in proper order!"; exit 13 end /*k*/ - -say ' sorted ball list has been confirmed as being sorted correctly.' -exit /*stick a fork in it, we're done.* -/*──────────────────────────────────COUNTWORDS subroutine───────────────*/ +say +say 'The sorted colored ball list has been confirmed as being sorted correctly.' +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────COUNTWORDS subroutine─────────────────────*/ countWords: procedure; parse arg ?,hay; s=1 - do r=0 until _==0; _=wordpos(?,hay,s); s=_+1; end; return r + do r=0 until _==0; _=wordpos(?,hay,s); s=_+1; end; return r diff --git a/Task/Dutch-national-flag-problem/REXX/dutch-national-flag-problem-2.rexx b/Task/Dutch-national-flag-problem/REXX/dutch-national-flag-problem-2.rexx index 6b6b44a706..b8bd04c2b6 100644 --- a/Task/Dutch-national-flag-problem/REXX/dutch-national-flag-problem-2.rexx +++ b/Task/Dutch-national-flag-problem/REXX/dutch-national-flag-problem-2.rexx @@ -1,30 +1,29 @@ -/*REXX pgm to reorder a set of random colored balls into a correct order*/ -/*which is the order of colors on the Dutch flag: red, white, blue. */ +/*REXX program reorders a set of random colored balls into a correct order, */ +/*────────────which is the order of colors on the Dutch flag: red white blue.*/ +parse arg N colors /*get optional parameters from the CL. */ +if N=',' | N='' then N=15 /*Not specified? Then use the default.*/ +if colors='' then colors='RWB' /*use default: R=red, W=white, B=blue */ +#=length(colors) /*count the number of colors specified.*/ +@=right(colors,1)left(colors,1) /*ensure balls aren't already in order.*/ -parse arg N colors . /*get user args from command line*/ -if N==',' | N=='' then N=15 /*use default number of balls. */ -if colors='' then colors='RWB' /*default: R=red, W=white, B=blue*/ -Ncolors=length(colors) /*count the number of colors. */ -@=right(colors,1)left(colors,1) /*ensure balls aren't in order. */ + do g=3 to N /*generate a random # of colored balls.*/ + @=@ ||substr(colors,random(1,#),1) /*append a color (1char) to the @ list.*/ + end /*g*/ - do g=3 to N /*generate a random # of balls. */ - @=@ || substr(colors,random(1,Ncolors),1) - end /*g*/ - -say 'number of colored balls generated = ' N ; say -say 'original ball order:' -say @ ; say -$=; do j=1 for Ncolors; _=substr(colors,j,1) - #=length(@)-length(space(translate(@,,_),0)) - $=$||copies(_,#) - end /*j*/ -say ' sorted ball order:' -say $; say - - do k=2 to N /*ensure the balls are in order. */ - if pos(substr($,k,1),colors)>=pos(substr($,k-1,1),colors) then iterate - say "The list of sorted balls isn't in proper order!"; exit 13 +say 'number of colored balls generated = ' N ; say +say center(' original ball order ', max(30,2*#), '─') +say @ ; say +$=; do j=1 for #; _=substr(colors, j, 1) + #=length(@) - length(space(translate(@, , _), 0)) + $=$ || copies(_, #) + end /*j*/ +say center(' sorted ball order ', max(30,2*#), '─') +say $ +say + do k=2 to N /*verify the balls are in correct order*/ + if pos(substr($,k,1), colors) >= pos(substr($,k-1,1), colors) then iterate + say "The list of sorted balls isn't in proper order!"; exit 13 end /*k*/ - -say ' sorted ball list has been confirmed as being sorted correctly.' - /*stick a fork in it, we're done.*/ +say +say 'The sorted colored ball list has been confirmed as being sorted correctly.' + /*stick a fork in it, we're all done. */ diff --git a/Task/Dutch-national-flag-problem/UNIX-Shell/dutch-national-flag-problem-1.sh b/Task/Dutch-national-flag-problem/UNIX-Shell/dutch-national-flag-problem-1.sh index e879ce7a0c..5135306143 100644 --- a/Task/Dutch-national-flag-problem/UNIX-Shell/dutch-national-flag-problem-1.sh +++ b/Task/Dutch-national-flag-problem/UNIX-Shell/dutch-national-flag-problem-1.sh @@ -1,7 +1,7 @@ COLORS=(red white blue) -# to go from name to number, we make variables out of the color names (e.g. the -# variable "$red" has value "1"). +# to go from name to number, we make variables out of the color names +# (e.g. the variable "$red" has value "1"). for (( i=0; i<${#COLORS[@]}; ++i )); do eval ${COLORS[i]}=$i done diff --git a/Task/Dutch-national-flag-problem/VBScript/dutch-national-flag-problem.vb b/Task/Dutch-national-flag-problem/VBScript/dutch-national-flag-problem.vb new file mode 100644 index 0000000000..44149f2093 --- /dev/null +++ b/Task/Dutch-national-flag-problem/VBScript/dutch-national-flag-problem.vb @@ -0,0 +1,44 @@ +'Solution derived from http://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/. + +'build an unsorted array with n elements +Function build_unsort(n) + flag = Array("red","white","blue") + Set random = CreateObject("System.Random") + Dim arr() + ReDim arr(n) + For i = 0 To n + arr(i) = flag(random.Next_2(0,3)) + Next + build_unsort = arr +End Function + +'sort routine +Function sort(arr) + lo = 0 + mi = 0 + hi = UBound(arr) + Do While mi <= hi + Select Case arr(mi) + Case "red" + tmp = arr(lo) + arr(lo) = arr(mi) + arr(mi) = tmp + lo = lo + 1 + mi = mi + 1 + Case "white" + mi = mi + 1 + Case "blue" + tmp = arr(mi) + arr(mi) = arr(hi) + arr(hi) = tmp + hi = hi - 1 + End Select + Loop + sort = Join(arr,",") +End Function + +unsort = build_unsort(11) +WScript.StdOut.Write "Unsorted: " & Join(unsort,",") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Sorted: " & sort(unsort) +WScript.StdOut.WriteLine diff --git a/Task/Dynamic-variable-names/00DESCRIPTION b/Task/Dynamic-variable-names/00DESCRIPTION index ea830b64cd..582654a620 100644 --- a/Task/Dynamic-variable-names/00DESCRIPTION +++ b/Task/Dynamic-variable-names/00DESCRIPTION @@ -1,3 +1,4 @@ +{{omit from|Lily}} Create a variable with a user-defined name. The variable name should ''not'' be written in the program text, but should be taken from the user dynamically. ;See also diff --git a/Task/Dynamic-variable-names/REXX/dynamic-variable-names.rexx b/Task/Dynamic-variable-names/REXX/dynamic-variable-names.rexx index e6ddbdd209..8ebb615001 100644 --- a/Task/Dynamic-variable-names/REXX/dynamic-variable-names.rexx +++ b/Task/Dynamic-variable-names/REXX/dynamic-variable-names.rexx @@ -1,7 +1,7 @@ -/*REXX program to show use of dynamic variable names. */ - -parse arg new value -say 'Arguments as they were entered via the command line =' new value +/*REXX program demonstrates the use of dynamic variable names & setting a val.*/ +parse arg newVar newValue +say 'Arguments as they were entered via the command line: ' newVar newValue say -call value new,value -say 'The newly assigned value (as per the VALUE bif)------' new value(new) +call value newVar, newValue +say 'The newly assigned value (as per the VALUE bif)------' newVar value(newVar) + /*stick a fork in it, we're all done. */ diff --git a/Task/Echo-server/Perl-6/echo-server.pl6 b/Task/Echo-server/Perl-6/echo-server.pl6 index 56dbfb4e03..23d6205b56 100644 --- a/Task/Echo-server/Perl-6/echo-server.pl6 +++ b/Task/Echo-server/Perl-6/echo-server.pl6 @@ -5,7 +5,7 @@ my $socket = IO::Socket::INET.new: while $socket.accept -> $conn { say "Accepted connection"; - async { + start { while $conn.recv -> $stuff { say "Echoing $stuff"; $conn.send($stuff); diff --git a/Task/Empty-directory/Batch-File/empty-directory.bat b/Task/Empty-directory/Batch-File/empty-directory.bat new file mode 100644 index 0000000000..169cffbf24 --- /dev/null +++ b/Task/Empty-directory/Batch-File/empty-directory.bat @@ -0,0 +1,30 @@ +@echo off +if "%~1"=="" exit /b 3 +set "samp_path=%~1" +set "tst_var=" + + %== Store the current directory of the CMD ==% +for /f %%T in ('cd') do set curr_dir=%%T + + %== Go to the samp_path ==% +cd %samp_path% 2>nul ||goto :folder_not_found + + %== The current directory is now samp_path ==% + %== Scan what is inside samp_path ==% +for /f "usebackq delims=" %%D in ( + `dir /b 2^>nul ^& dir /b /ah 2^>nul` +) do set "tst_var=1" + +if "%tst_var%"=="1" ( + echo "%samp_path%" is NOT empty. + cd %curr_dir% + exit /b 1 +) else ( + echo "%samp_path%" is empty. + cd %curr_dir% + exit /b 0 +) + +:folder_not_found +echo Folder not found. +exit /b 2 diff --git a/Task/Empty-directory/C++/empty-directory.cpp b/Task/Empty-directory/C++/empty-directory.cpp new file mode 100644 index 0000000000..a74b5bcd8c --- /dev/null +++ b/Task/Empty-directory/C++/empty-directory.cpp @@ -0,0 +1,16 @@ +#include +#include + +using namespace boost::filesystem; + +int main(int argc, char *argv[]) +{ + for (int i = 1; i < argc; ++i) { + path p(argv[i]); + + if (exists(p) && is_directory(p)) + std::cout << "'" << argv[i] << "' is" << (!is_empty(p) ? " not" : "") << " empty\n"; + else + std::cout << "dir '" << argv[i] << "' could not be found\n"; + } +} diff --git a/Task/Empty-directory/Elixir/empty-directory.elixir b/Task/Empty-directory/Elixir/empty-directory.elixir new file mode 100644 index 0000000000..6dbc1504bb --- /dev/null +++ b/Task/Empty-directory/Elixir/empty-directory.elixir @@ -0,0 +1,2 @@ +path = hd(System.argv) +IO.puts File.dir?(path) and Enum.empty?( File.ls!(path) ) diff --git a/Task/Empty-directory/NewLISP/empty-directory.newlisp b/Task/Empty-directory/NewLISP/empty-directory.newlisp new file mode 100644 index 0000000000..432e89ec2f --- /dev/null +++ b/Task/Empty-directory/NewLISP/empty-directory.newlisp @@ -0,0 +1,3 @@ +(define (empty-dir? path-to-check) + (empty? (clean (lambda (x) (or (= "." x) (= ".." x))) (directory path-to-check))) +) diff --git a/Task/Empty-directory/PowerShell/empty-directory.psh b/Task/Empty-directory/PowerShell/empty-directory.psh new file mode 100644 index 0000000000..b1e58195fc --- /dev/null +++ b/Task/Empty-directory/PowerShell/empty-directory.psh @@ -0,0 +1,6 @@ +$path = "C:\Users" +if((Dir $path).Count -eq 0) { + "$path is empty" +} else { + "$path is not empty" +} diff --git a/Task/Empty-directory/VBScript/empty-directory.vb b/Task/Empty-directory/VBScript/empty-directory.vb new file mode 100644 index 0000000000..4684b9f920 --- /dev/null +++ b/Task/Empty-directory/VBScript/empty-directory.vb @@ -0,0 +1,12 @@ +Function IsDirEmpty(path) + IsDirEmpty = False + Set objFSO = CreateObject("Scripting.FileSystemObject") + Set objFolder = objFSO.GetFolder(path) + If objFolder.Files.Count = 0 And objFolder.SubFolders.Count = 0 Then + IsDirEmpty = True + End If +End Function + +'Test +WScript.StdOut.WriteLine IsDirEmpty("C:\Temp") +WScript.StdOut.WriteLine IsDirEmpty("C:\Temp\test") diff --git a/Task/Empty-program/ALGOL-W/empty-program.alg b/Task/Empty-program/ALGOL-W/empty-program.alg new file mode 100644 index 0000000000..e27f1f2ec2 --- /dev/null +++ b/Task/Empty-program/ALGOL-W/empty-program.alg @@ -0,0 +1 @@ +begin end. diff --git a/Task/Empty-program/Batch-File/empty-program-2.bat b/Task/Empty-program/Batch-File/empty-program-2.bat index 9699d2b163..397db75f0d 100644 --- a/Task/Empty-program/Batch-File/empty-program-2.bat +++ b/Task/Empty-program/Batch-File/empty-program-2.bat @@ -1 +1 @@ -REM +: diff --git a/Task/Empty-program/C/empty-program-1.c b/Task/Empty-program/C/empty-program-1.c index 9f0510be5a..893a0b605d 100644 --- a/Task/Empty-program/C/empty-program-1.c +++ b/Task/Empty-program/C/empty-program-1.c @@ -1,4 +1,4 @@ -int main(int argc, char* argv[]) +main() { return 0; } diff --git a/Task/Empty-program/C/empty-program-2.c b/Task/Empty-program/C/empty-program-2.c index 1482f27e53..8b8d58de0e 100644 --- a/Task/Empty-program/C/empty-program-2.c +++ b/Task/Empty-program/C/empty-program-2.c @@ -1,4 +1 @@ -int main () -{ - return 0; -} +int main() { } diff --git a/Task/Empty-program/Common-Lisp/empty-program.lisp b/Task/Empty-program/Common-Lisp/empty-program.lisp new file mode 100644 index 0000000000..6a452c185a --- /dev/null +++ b/Task/Empty-program/Common-Lisp/empty-program.lisp @@ -0,0 +1 @@ +() diff --git a/Task/Empty-program/Elixir/empty-program.elixir b/Task/Empty-program/Elixir/empty-program.elixir new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-program/Julia/empty-program.julia b/Task/Empty-program/Julia/empty-program.julia new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-program/TI-83-BASIC/empty-program.ti-83 b/Task/Empty-program/TI-83-BASIC/empty-program.ti-83 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-string/ALGOL-68/empty-string.alg b/Task/Empty-string/ALGOL-68/empty-string.alg new file mode 100644 index 0000000000..29dd9a88b3 --- /dev/null +++ b/Task/Empty-string/ALGOL-68/empty-string.alg @@ -0,0 +1,12 @@ +# declare a string variable and assign an empty string to it # +STRING s := ""; + +# test the string is empty # +IF s = "" THEN write( ( "s is empty", newline ) ) FI; + +# test the string is not empty # +IF s /= "" THEN write( ( "s is not empty", newline ) ) FI; + +# as a string is an array of characters, we could also test for emptyness by # +# checking for lower bound > upper bound # +IF LWB s > UPB s THEN write( ( "s is still empty", newline ) ) FI diff --git a/Task/Empty-string/AppleScript/empty-string.applescript b/Task/Empty-string/AppleScript/empty-string.applescript new file mode 100644 index 0000000000..33a4c3a88c --- /dev/null +++ b/Task/Empty-string/AppleScript/empty-string.applescript @@ -0,0 +1,30 @@ +-- assign empty string to str +set str to "" + + +-- check if string is empty +if str is "" then + -- str is empty +end if +-- or +if id of str is {} then + -- str is empty +end if +-- or +if (count of str) is 0 then + -- str is empty +end if + + +-- check if string is not empty +if str is not "" then + -- string is not empty +end if +-- or +if id of str is not {} then + -- str is not empty +end if +-- or +if (count of str) is not 0 then + -- str is not empty +end if diff --git a/Task/Empty-string/Burlesque/empty-string.blq b/Task/Empty-string/Burlesque/empty-string.blq new file mode 100644 index 0000000000..4c358f2763 --- /dev/null +++ b/Task/Empty-string/Burlesque/empty-string.blq @@ -0,0 +1,6 @@ +blsq ) "" +"" +blsq ) ""nu +1 +blsq ) "a"nu +0 diff --git a/Task/Empty-string/Elixir/empty-string.elixir b/Task/Empty-string/Elixir/empty-string.elixir index 3df71cabf7..7a3b65ca9c 100644 --- a/Task/Empty-string/Elixir/empty-string.elixir +++ b/Task/Empty-string/Elixir/empty-string.elixir @@ -5,8 +5,12 @@ empty_string == "" # => true String.length(empty_string) == 0 # => true +byte_size(empty_string) == 0 +# => true not_empty_string == "" # => false String.length(not_empty_string) == 0 # => false +byte_size(not_empty_string) == 0 +# => false diff --git a/Task/Empty-string/Forth/empty-string.fth b/Task/Empty-string/Forth/empty-string.fth index e7dbbac5bb..c70094c65d 100644 --- a/Task/Empty-string/Forth/empty-string.fth +++ b/Task/Empty-string/Forth/empty-string.fth @@ -1,3 +1,6 @@ -: empty? ( c-addr u -- ? ) nip 0= ; +\ string words operate on the address and count left on the stack by a string +\ ? means the word returns a true/false flag on the stack -s" " dup . empty? . \ 0 -1 +: empty? ( c-addr u -- ? ) nip 0= ; +: filled? ( c-addr u -- ? ) empty? 0= ; +: ="" ( c-addr u -- ) drop 0 ; \ It's OK to copy syntax from other languages diff --git a/Task/Empty-string/Fortran/empty-string.f b/Task/Empty-string/Fortran/empty-string.f new file mode 100644 index 0000000000..9d102b8a03 --- /dev/null +++ b/Task/Empty-string/Fortran/empty-string.f @@ -0,0 +1,11 @@ + SUBROUTINE TASTE(T) + CHARACTER*(*) T !This form allows for any size. + IF (LEN(T).LE.0) WRITE(6,*) "Empty!" + IF (LEN(T).GT.0) WRITE(6,*) "Not empty!" + END + CHARACTER*24 TEXT + CALL TASTE("") + CALL TASTE("This") + TEXT = "" !Fills the entire variable with space characters. + CALL TASTE(TEXT) !Passes all 24 of them. Result is Not empty! + END diff --git a/Task/Empty-string/Julia/empty-string.julia b/Task/Empty-string/Julia/empty-string.julia new file mode 100644 index 0000000000..cbbf1bf9de --- /dev/null +++ b/Task/Empty-string/Julia/empty-string.julia @@ -0,0 +1,11 @@ +blank = "" +nonblank = "!" + +println("The length of blank is ", length(blank)) +println("That blank is empty is ", isempty(blank)) +println("That blank is not empty is ", !isempty(blank)) + +println() +println("The length of nonblank is ", length(nonblank)) +println("That nonblank is empty is ", isempty(nonblank)) +println("That nonblank is not empty is ", !isempty(nonblank)) diff --git a/Task/Empty-string/Perl-6/empty-string.pl6 b/Task/Empty-string/Perl-6/empty-string.pl6 index 78d8c8fc45..bd03b870a9 100644 --- a/Task/Empty-string/Perl-6/empty-string.pl6 +++ b/Task/Empty-string/Perl-6/empty-string.pl6 @@ -1,3 +1,3 @@ my $s = ''; -say 'String is empty' unless $s.chars; -say 'String is not empty' if $s.chars; +say 'String is empty' unless $s; +say 'String is not empty' if $s; diff --git a/Task/Empty-string/PowerShell/empty-string.psh b/Task/Empty-string/PowerShell/empty-string.psh new file mode 100644 index 0000000000..1ed4f3c593 --- /dev/null +++ b/Task/Empty-string/PowerShell/empty-string.psh @@ -0,0 +1,2 @@ +[string]::IsNullOrEmpty("") +[string]::IsNullOrEmpty("a") diff --git a/Task/Empty-string/Self/empty-string.self b/Task/Empty-string/Self/empty-string.self new file mode 100644 index 0000000000..b60aa726ca --- /dev/null +++ b/Task/Empty-string/Self/empty-string.self @@ -0,0 +1,8 @@ +"Put an empty string in a slot called 'str'" +str: ''. + +"Check that string is empty" +str isEmpty. + +"Check that string is not empty" +str isEmpty not. diff --git a/Task/Enforced-immutability/00META.yaml b/Task/Enforced-immutability/00META.yaml index 0bb2150890..f0a631d57e 100644 --- a/Task/Enforced-immutability/00META.yaml +++ b/Task/Enforced-immutability/00META.yaml @@ -1,4 +1,2 @@ --- -category: -- Initialization -note: Enforced immutability +note: Initialization diff --git a/Task/Enforced-immutability/Ela/enforced-immutability-1.ela b/Task/Enforced-immutability/Ela/enforced-immutability-1.ela index 3f0e72d0a2..cf0f55ba91 100644 --- a/Task/Enforced-immutability/Ela/enforced-immutability-1.ela +++ b/Task/Enforced-immutability/Ela/enforced-immutability-1.ela @@ -1,2 +1,2 @@ -open cell +open unsafe.cell r = ref 0 diff --git a/Task/Enforced-immutability/Rust/enforced-immutability-1.rust b/Task/Enforced-immutability/Rust/enforced-immutability-1.rust new file mode 100644 index 0000000000..b10c631d53 --- /dev/null +++ b/Task/Enforced-immutability/Rust/enforced-immutability-1.rust @@ -0,0 +1,2 @@ +let x = 3; +x += 2; diff --git a/Task/Enforced-immutability/Rust/enforced-immutability-2.rust b/Task/Enforced-immutability/Rust/enforced-immutability-2.rust new file mode 100644 index 0000000000..1b79e1aad3 --- /dev/null +++ b/Task/Enforced-immutability/Rust/enforced-immutability-2.rust @@ -0,0 +1 @@ +let mut x = 3; diff --git a/Task/Entropy/00DESCRIPTION b/Task/Entropy/00DESCRIPTION index d1a71afbc6..8a3bed63d4 100644 --- a/Task/Entropy/00DESCRIPTION +++ b/Task/Entropy/00DESCRIPTION @@ -10,4 +10,7 @@ Therefore, given a string S of length n where P( For this task, use "1223334444" as an example. The result should be around 1.84644 bits. -Related Task: [[Fibonacci_word]] +Related Tasks: + +:::* [[Fibonacci_word]] +:::* [[Entropy/Narcissist]] diff --git a/Task/Entropy/ALGOL-W/entropy.alg b/Task/Entropy/ALGOL-W/entropy.alg new file mode 100644 index 0000000000..dc140a1a2d --- /dev/null +++ b/Task/Entropy/ALGOL-W/entropy.alg @@ -0,0 +1,54 @@ +begin + % calculates the shannon entropy of a string % + % strings are fixed length in algol W and the length is part of the % + % type, so we declare the string parameter to be the longest possible % + % string length (256 characters) and have a second parameter to % + % specify how much is actually used % + real procedure shannon_entropy ( string(256) value s + ; integer value stringLength + ); + begin + + real probability, entropy; + + % algol W assumes there are 256 possible characters % + integer MAX_CHAR; + MAX_CHAR := 256; + + % declarations must preceed statements, so we start a new % + % block here so we can use MAX_CHAR as an array bound % + begin + + % increment an integer variable % + procedure incI ( integer value result a ) ; a := a + 1; + + integer array charCount( 1 :: MAX_CHAR ); + + % count the occurances of each character in s % + for charPos := 1 until MAX_CHAR do charCount( charPos ) := 0; + for sPos := 0 until stringLength - 1 do incI( charCount( decode( s( sPos | 1 ) ) ) ); + + % calculate the entropy, we use log base 10 and then convert % + % to log base 2 after calculating the sum % + + entropy := 0.0; + for charPos := 1 until MAX_CHAR do + begin + if charCount( charPos ) not = 0 + then begin + % have a character that occurs in the string % + probability := charCount( charPos ) / stringLength; + entropy := entropy - ( probability * log( probability ) ) + end + end charPos + + end; + + entropy / log( 2 ) + end shannon_entropy ; + + % test the shannon entropy routine % + r_format := "A"; r_w := 12; r_d := 6; % set output to fixed format % + write( shannon_entropy( "1223334444", 10 ) ) + +end. diff --git a/Task/Entropy/Common-Lisp/entropy.lisp b/Task/Entropy/Common-Lisp/entropy.lisp index 7d4e381ce8..8107f2e8a2 100644 --- a/Task/Entropy/Common-Lisp/entropy.lisp +++ b/Task/Entropy/Common-Lisp/entropy.lisp @@ -1,6 +1,8 @@ -(defun entropy(input-string) - (let ((frequency-table (make-hash-table :test 'equal)) - (entropy 0)) - (map 'nil #'(lambda(c) (setf (gethash c frequency-table) (if (gethash c frequency-table) (+ (gethash c frequency-table) 1) 1))) (coerce input-string 'list)) - (maphash #'(lambda(k v) (setf entropy (+ entropy (* -1 (/ v (length input-string)) (log (/ v (length input-string)) 2))))) frequency-table) - entropy)) +(defun entropy (string) + (let ((table (make-hash-table :test 'equal)) + (entropy 0)) + (mapc (lambda (c) (setf (gethash c table) (+ (gethash c table 0) 1))) + (coerce string 'list)) + (maphash (lambda (k v) (decf entropy (* (/ v (length input-string)) (log (/ v (length input-string)) 2)))) + table) + entropy)) diff --git a/Task/Entropy/Elixir/entropy.elixir b/Task/Entropy/Elixir/entropy.elixir new file mode 100644 index 0000000000..340e1a0d79 --- /dev/null +++ b/Task/Entropy/Elixir/entropy.elixir @@ -0,0 +1,14 @@ +defmodule RC do + def entropy(str) do + leng = String.length(str) + String.split(str, "", trim: true) + |> Enum.group_by(&(&1)) + |> Enum.map(fn{_,value} -> length(value) end) + |> Enum.reduce(0, fn count, entropy -> + freq = count / leng + entropy - freq * :math.log2(freq) + end) + end +end + +IO.inspect RC.entropy("1223334444") diff --git a/Task/Entropy/J/entropy-1.j b/Task/Entropy/J/entropy-1.j index 51c80c1466..ebb45b2043 100644 --- a/Task/Entropy/J/entropy-1.j +++ b/Task/Entropy/J/entropy-1.j @@ -1 +1 @@ - entropy=: +/@:-@(* 2&^.)@(#/.~ % #) + entropy=: +/@(-@* 2&^.)@(#/.~ % #) diff --git a/Task/Entropy/J/entropy-2.j b/Task/Entropy/J/entropy-2.j index 9ff7ccd7d0..c8730f0a8a 100644 --- a/Task/Entropy/J/entropy-2.j +++ b/Task/Entropy/J/entropy-2.j @@ -1,2 +1,10 @@ entropy '1223334444' 1.84644 + entropy i.256 +8 + entropy 256$9 +0 + entropy 256$0 1 +1 + entropy 256$0 1 2 3 +2 diff --git a/Task/Entropy/Liberty-BASIC/entropy.liberty b/Task/Entropy/Liberty-BASIC/entropy.liberty new file mode 100644 index 0000000000..dd7402959e --- /dev/null +++ b/Task/Entropy/Liberty-BASIC/entropy.liberty @@ -0,0 +1,32 @@ +dim countOfChar( 255) ' all possible one-byte ASCII chars + + source$ ="1223334444" + charCount =len( source$) + usedChar$ ="" + + for i =1 to len( source$) ' count which chars are used in source + ch$ =mid$( source$, i, 1) + if not( instr( usedChar$, ch$)) then usedChar$ =usedChar$ +ch$ + 'currentCh$ =mid$( + j =instr( usedChar$, ch$) + countOfChar( j) =countOfChar( j) +1 + next i + + l =len( usedChar$) + for i =1 to l + probability =countOfChar( i) /charCount + entropy =entropy -( probability *logBase( probability, 2)) + next i + + print " Characters used and the number of occurrences of each " + for i =1 to l + print " '"; mid$( usedChar$, i, 1); "'", countOfChar( i) + next i + + print " Entropy of '"; source$; "' is "; entropy; " bits." + print " The result should be around 1.84644 bits." + + end + function logBase( x, b) ' in LB log() is base 'e'. + logBase =log( x) /log( 2) + end function diff --git a/Task/Entropy/Perl-6/entropy-2.pl6 b/Task/Entropy/Perl-6/entropy-2.pl6 index be377917e6..0ae8616929 100644 --- a/Task/Entropy/Perl-6/entropy-2.pl6 +++ b/Task/Entropy/Perl-6/entropy-2.pl6 @@ -1,4 +1,4 @@ -use MONKEY_TYPING; +use MONKEY-TYPING; augment class Bag { method entropy { [+] map -> \p { - p * log p }, diff --git a/Task/Entropy/PowerShell/entropy.psh b/Task/Entropy/PowerShell/entropy.psh new file mode 100644 index 0000000000..6c09d4e864 --- /dev/null +++ b/Task/Entropy/PowerShell/entropy.psh @@ -0,0 +1,9 @@ +function entropy ($string) { + $n = $string.Length + $string.ToCharArray() | group | foreach{ + $p = $_.Count/$n + $i = [Math]::Log($p,2) + -$p*$i + } | measure -Sum | foreach Sum +} +entropy "1223334444" diff --git a/Task/Entropy/Prolog/entropy.pro b/Task/Entropy/Prolog/entropy.pro new file mode 100644 index 0000000000..23b8cf4b88 --- /dev/null +++ b/Task/Entropy/Prolog/entropy.pro @@ -0,0 +1,131 @@ +:-module(shannon_entropy, [shannon_entropy/2]). + +%! shannon_entropy(+String, -Entropy) is det. +% +% Calculate the Shannon Entropy of String. +% +% Example query: +% == +% ?- shannon_entropy(1223334444, H). +% H = 1.8464393446710154. +% == +% +shannon_entropy(String, Entropy):- + atom_chars(String, Cs) + ,relative_frequencies(Cs, Frequencies) + ,findall(CI + ,(member(_C-F, Frequencies) + ,log2(F, L) + ,CI is F * L + ) + ,CIs) + ,foldl(sum, CIs, 0, E) + ,Entropy is -E. + +%! frequencies(+Characters,-Frequencies) is det. +% +% Calculates the relative frequencies of elements in the list of +% Characters. +% +% Frequencies is a key-value list with elements of the form: +% C-F, where C a character in the list and F its relative +% frequency in the list. +% +% Example query: +% == +% ?- relative_frequencies([a,a,a,b,b,b,b,b,b,c,c,c,a,a,f], Fs). +% Fs = [a-0.3333333333333333, b-0.4, c-0.2,f-0.06666666666666667]. +% == +% +relative_frequencies(List, Frequencies):- + run_length_encoding(List, Rle) + % Sort Run-length encoded list and aggregate lengths by element + ,keysort(Rle, Sorted_Rle) + ,group_pairs_by_key(Sorted_Rle, Elements_Run_lengths) + ,length(List, Elements_in_list) + ,findall(E-Frequency_of_E + ,(member(E-RLs, Elements_Run_lengths) + % Sum the list of lengths of runs of E + ,foldl(plus, RLs, 0, Occurences_of_E) + ,Frequency_of_E is Occurences_of_E / Elements_in_list + ) + ,Frequencies). + + +%! run_length_encoding(+List, -Run_length_encoding) is det. +% +% Converts a list to its run-length encoded form where each "run" +% of contiguous repeats of the same element is replaced by that +% element and the length of the run. +% +% Run_length_encoding is a key-value list, where each element is a +% term: +% +% Element:term-Repetitions:number. +% +% Example query: +% == +% ?- run_length_encoding([a,a,a,b,b,b,b,b,b,c,c,c,a,a,f], RLE). +% RLE = [a-3, b-6, c-3, a-2, f-1]. +% == +% +run_length_encoding([], []-0):- + !. % No more results needed. + +run_length_encoding([Head|List], Run_length_encoded_list):- + run_length_encoding(List, [Head-1], Reversed_list) + % The resulting list is in reverse order due to the head-to-tail processing + ,reverse(Reversed_list, Run_length_encoded_list). + +%! run_length_encoding(+List,+Initialiser,-Accumulator) is det. +% +% Business end of run_length_encoding/3. Calculates the run-length +% encoded form of a list and binds the result to the Accumulator. +% Initialiser is a list [H-1] where H is the first element of the +% input list. +% +run_length_encoding([], Fs, Fs). + +% Run of F consecutive occurrences of C +run_length_encoding([C|Cs],[C-F|Fs], Acc):- + % Backtracking would produce successive counts + % of runs of C at different indices in the list. + ! + ,F_ is F + 1 + ,run_length_encoding(Cs, [C-F_| Fs], Acc). + +% End of a run of consecutive identical elements. +run_length_encoding([C|Cs], Fs, Acc):- + run_length_encoding(Cs,[C-1|Fs], Acc). + + +/* Arithmetic helper predicates */ + +%! log2(N, L2_N) is det. +% +% L2_N is the logarithm with base 2 of N. +% +log2(N, L2_N):- + L_10 is log10(N) + ,L_2 is log10(2) + ,L2_N is L_10 / L_2. + +%! sum(+A,+B,?Sum) is det. +% +% True when Sum is the sum of numbers A and B. +% +% Helper predicate to allow foldl/4 to do addition. The following +% call will raise an error (because there is no predicate +/3): +% == +% foldl(+, [1,2,3], 0, Result). +% == +% +% This will not raise an error: +% == +% foldl(sum, [1,2,3], 0, Result). +% == +% +sum(A, B, Sum):- + must_be(number, A) + ,must_be(number, B) + ,Sum is A + B. diff --git a/Task/Entropy/PureBasic/entropy.purebasic b/Task/Entropy/PureBasic/entropy.purebasic new file mode 100644 index 0000000000..1b24800202 --- /dev/null +++ b/Task/Entropy/PureBasic/entropy.purebasic @@ -0,0 +1,22 @@ +#TESTSTR="1223334444" +NewMap uchar.i() : Define.d e + +Procedure.d nlog2(x.d) : ProcedureReturn Log(x)/Log(2) : EndProcedure + +Procedure countchar(s$, Map uchar()) + If Len(s$) + uchar(Left(s$,1))=CountString(s$,Left(s$,1)) + s$=RemoveString(s$,Left(s$,1)) + ProcedureReturn countchar(s$, uchar()) + EndIf +EndProcedure + +countchar(#TESTSTR,uchar()) + +ForEach uchar() + e-uchar()/Len(#TESTSTR)*nlog2(uchar()/Len(#TESTSTR)) +Next + +OpenConsole() +Print("Entropy of ["+#TESTSTR+"] = "+StrD(e,15)) +Input() diff --git a/Task/Entropy/Python/entropy-3.py b/Task/Entropy/Python/entropy-3.py new file mode 100644 index 0000000000..628234bd92 --- /dev/null +++ b/Task/Entropy/Python/entropy-3.py @@ -0,0 +1,19 @@ +def Entropy(text): + import math + log2=lambda x:math.log(x)/math.log(2) + exr={} + infoc=0 + for each in text: + try: + exr[each]+=1 + except: + exr[each]=1 + textlen=len(text) + for k,v in exr.items(): + freq = 1.0*v/textlen + infoc+=freq*log2(freq) + infoc*=-1 + return infoc + +while True: + print Entropy(raw_input('>>>')) diff --git a/Task/Entropy/REXX/entropy-3.rexx b/Task/Entropy/REXX/entropy-3.rexx index b699fc2ec0..1f522bf8ff 100644 --- a/Task/Entropy/REXX/entropy-3.rexx +++ b/Task/Entropy/REXX/entropy-3.rexx @@ -1,30 +1,30 @@ -/*REXX program calculates the information entropy for a given char str.*/ -numeric digits 30 /*use thirty digits for precision*/ -parse arg $; if $=='' then $=1223334444 /*obtain optional input*/ -n=0; @.=0; L=length($); $$= +/*REXX program calculates the information entropy for a given character string*/ +numeric digits 50 /*use 50 decimal digits for precision. */ +parse arg $; if $='' then $=1223334444 /*obtain the optional input from the CL*/ +#=0; @.=0; L=length($); $$= /*define handy-dandy REXX variables. */ - do j=1 for L; _=substr($,j,1) /*process each character in $ str*/ - if @._==0 then do; n=n+1 /*if unique, bump char counter. */ - $$=$$ || _ /*add this character to the list.*/ + do j=1 for L; _=substr($,j,1) /*process each character in $ string.*/ + if @._==0 then do; #=#+1 /*Unique? Yes, bump character counter.*/ + $$=$$ || _ /*add this character to the $$ list. */ end - @._ = @._+1 /*keep track of this char count. */ + @._=@._+1 /*keep track of this character's count.*/ end /*j*/ -sum=0 /*calc info entropy for each char*/ - do i=1 for n; _=substr($$,i,1) /*obtain a char from unique list.*/ - sum=sum - @._/L * log2(@._/L) /*add (negatively) the entropies.*/ +sum=0 /*calculate info entropy for each char.*/ + do i=1 for #; _=substr($$,i,1) /*obtain a character from unique list. */ + sum=sum - @._/L * log2(@._/L) /*add (negatively) the char entropies. */ end /*i*/ -say ' input string: ' $ -say 'string length: ' L -say ' unique chars: ' n ; say -say 'the information entropy of the string ──► ' format(sum,,12) " bits." -exit /*stick a fork in it, we're done.*/ +say ' input string: ' $ +say 'string length: ' L +say ' unique chars: ' # ; say +say 'the information entropy of the string ──► ' format(sum,,12) " bits." +exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────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().*/ +log2: procedure; parse arg x 1 ox; 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) + do while ig & ox>1.5 | \ig&ox<.5; _=e; do k=-1; iz=ox* _**-is + if k>=0 & (ig & iz<1 | \ig&iz>.5) then leave; _=_*_; izz=iz; end + ox=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 /*k*/ + r=z+ii; if arg()==2 then return r; return r/log2(2,0) diff --git a/Task/Entropy/Ruby/entropy-1.rb b/Task/Entropy/Ruby/entropy-1.rb index 91cf2a7a3c..ee385ab685 100644 --- a/Task/Entropy/Ruby/entropy-1.rb +++ b/Task/Entropy/Ruby/entropy-1.rb @@ -1,9 +1,12 @@ def entropy(s) - counts = Hash.new(0) + counts = Hash.new(0.0) s.each_char { |c| counts[c] += 1 } + leng = s.length counts.values.reduce(0) do |entropy, count| - freq = count / s.length.to_f + freq = count / leng entropy - freq * Math.log2(freq) end end + +p entropy("1223334444") diff --git a/Task/Entropy/Rust/entropy.rust b/Task/Entropy/Rust/entropy.rust index ecca6a0bf1..afec2b1661 100644 --- a/Task/Entropy/Rust/entropy.rust +++ b/Task/Entropy/Rust/entropy.rust @@ -1,16 +1,20 @@ -// works for Rust 0.9 -fn entropy(s: &str) -> f32 { - let mut entropy: f32 = 0.0; - let mut histogram = [0, ..256]; - let len = s.len(); +fn entropy(s: &[u8]) -> f32 { + let mut entropy: f32 = 0.0; + let mut histogram = [0; 256]; - for i in range(0, len) { histogram[s[i]] += 1; } - for i in range(0, 256) { - if histogram[i] > 0 { - let ratio = (histogram[i] as f32 / len as f32) as f32; - entropy -= (ratio * log2(ratio)) as f32; - } - } + for i in 0..s.len() { + histogram.get_mut(s[i] as usize).map(|v| *v += 1); + } + for i in 0..256 { + if histogram[i] > 0 { + let ratio = (histogram[i] as f32 / s.len() as f32) as f32; + entropy -= (ratio * ratio.log2()) as f32; + } + } + entropy +} - entropy +fn main() { + let arg = std::env::args().nth(1).expect("Need a string."); + println!("Entropy of {} is {}.", arg, entropy(&arg.bytes().collect::>())); } diff --git a/Task/Enumerations/Elixir/enumerations-1.elixir b/Task/Enumerations/Elixir/enumerations-1.elixir new file mode 100644 index 0000000000..8c58d79bad --- /dev/null +++ b/Task/Enumerations/Elixir/enumerations-1.elixir @@ -0,0 +1,4 @@ +fruits = [:apple, :banana, :cherry] +# fruits = ~w(apple banana cherry)a +val = :banana +Enum.member?(fruits, val) #=> true diff --git a/Task/Enumerations/Elixir/enumerations-2.elixir b/Task/Enumerations/Elixir/enumerations-2.elixir new file mode 100644 index 0000000000..787158f8c4 --- /dev/null +++ b/Task/Enumerations/Elixir/enumerations-2.elixir @@ -0,0 +1,10 @@ +fruits = [{:apple, 1}, {:banana, 2}, {:cherry, 3}] # Keyword list +fruits = [apple: 1, banana: 2, cherry: 3] # Above-mentioned different notation +fruits[:apple] #=> 1 +Dict.has_key?(fruits, :banana) #=> true + +fruits = %{:apple=>1, :banana=>2, :cherry=>3} # Map +fruits = %{apple: 1, banana: 2, cherry: 3} # Above-mentioned different notation +fruits[:apple] #=> 1 +fruits.apple #=> 1 (Only When the key is Atom) +Dict.has_key?(fruits, :banana) #=> true diff --git a/Task/Enumerations/Elixir/enumerations-3.elixir b/Task/Enumerations/Elixir/enumerations-3.elixir new file mode 100644 index 0000000000..10bdc44744 --- /dev/null +++ b/Task/Enumerations/Elixir/enumerations-3.elixir @@ -0,0 +1,2 @@ +fruits = ~w(apple banana cherry)a |> Enum.with_index +#=> [apple: 0, banana: 1, cherry: 2] diff --git a/Task/Enumerations/Rust/enumerations.rust b/Task/Enumerations/Rust/enumerations.rust index f086eb674d..9f06a45395 100644 --- a/Task/Enumerations/Rust/enumerations.rust +++ b/Task/Enumerations/Rust/enumerations.rust @@ -3,3 +3,13 @@ enum Fruits { Banana, Cherry } + +enum FruitsWithNumbers { + Strawberry = 0, + Pear = 27, +} + +fn main() { + // Access to numerical value by conversion + println!("{}", FruitsWithNumbers::Pear as u8); +} diff --git a/Task/Environment-variables/00DESCRIPTION b/Task/Environment-variables/00DESCRIPTION index e651b16152..15885f2de6 100644 --- a/Task/Environment-variables/00DESCRIPTION +++ b/Task/Environment-variables/00DESCRIPTION @@ -1,6 +1,6 @@ -{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} {{omit from|M4}} +{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} {{omit from|Unlambda|Does not provide access to environment variables.}} -{{task|Programming environment operations}} + Show how to get one of your process's [[wp:Environment variable|environment variables]]. The available variables vary by system; some of the common ones available on Unix include PATH, HOME, USER. diff --git a/Task/Environment-variables/00META.yaml b/Task/Environment-variables/00META.yaml index 8f2d61dd8a..b693f5e5c4 100644 --- a/Task/Environment-variables/00META.yaml +++ b/Task/Environment-variables/00META.yaml @@ -2,4 +2,5 @@ category: - Environment variables - Initialization -note: Environment variables +- Simple +note: Programming environment operations diff --git a/Task/Environment-variables/AWK/environment-variables-1.awk b/Task/Environment-variables/AWK/environment-variables-1.awk index 1ad6c819f2..db6a5589ab 100644 --- a/Task/Environment-variables/AWK/environment-variables-1.awk +++ b/Task/Environment-variables/AWK/environment-variables-1.awk @@ -1,2 +1 @@ $ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["USER"]}' -HOME:/home/suchrich USER:SuchRich diff --git a/Task/Environment-variables/AWK/environment-variables-2.awk b/Task/Environment-variables/AWK/environment-variables-2.awk index 99e42e6910..10055b5184 100644 --- a/Task/Environment-variables/AWK/environment-variables-2.awk +++ b/Task/Environment-variables/AWK/environment-variables-2.awk @@ -1,2 +1 @@ $ awk -v h=$HOME -v u=$USER 'BEGIN{print "HOME:"h,"USER:"u}' -HOME:/home/suchrich USER:SuchRich diff --git a/Task/Environment-variables/AWK/environment-variables-3.awk b/Task/Environment-variables/AWK/environment-variables-3.awk new file mode 100644 index 0000000000..e3e2eebebe --- /dev/null +++ b/Task/Environment-variables/AWK/environment-variables-3.awk @@ -0,0 +1,5 @@ +# http://ideone.com/St5SHF +BEGIN { print "# Environment:" + for (e in ENVIRON) { printf( "%10s = %s\n", e, ENVIRON[e] ) } +} +END { print "# Done." } diff --git a/Task/Environment-variables/Elixir/environment-variables.elixir b/Task/Environment-variables/Elixir/environment-variables.elixir new file mode 100644 index 0000000000..22da1d5c69 --- /dev/null +++ b/Task/Environment-variables/Elixir/environment-variables.elixir @@ -0,0 +1 @@ +System.get_env("PATH") diff --git a/Task/Environment-variables/Modula-3/environment-variables.mod3 b/Task/Environment-variables/Modula-3/environment-variables.mod3 new file mode 100644 index 0000000000..b3170d38d9 --- /dev/null +++ b/Task/Environment-variables/Modula-3/environment-variables.mod3 @@ -0,0 +1,15 @@ +MODULE EnvVars EXPORTS Main; + +IMPORT IO, Env; + +VAR + k, v: TEXT; + +BEGIN + IO.Put(Env.Get("HOME") & "\n"); + + FOR i := 0 TO Env.Count - 1 DO + Env.GetNth(i, k, v); + IO.Put(k & " = " & v & "\n") + END +END EnvVars. diff --git a/Task/Equilibrium-index/AWK/equilibrium-index.awk b/Task/Equilibrium-index/AWK/equilibrium-index.awk new file mode 100644 index 0000000000..a9523c5e67 --- /dev/null +++ b/Task/Equilibrium-index/AWK/equilibrium-index.awk @@ -0,0 +1,27 @@ +# syntax: GAWK -f EQUILIBRIUM_INDEX.AWK +BEGIN { + main("-7 1 5 2 -4 3 0") + main("2 4 6") + main("2 9 2") + main("1 -1 1 -1 1 -1 1") + exit(0) +} +function main(numbers, x) { + x = equilibrium(numbers) + printf("numbers: %s\n",numbers) + printf("indices: %s\n\n",length(x)==0?"none":x) +} +function equilibrium(numbers, arr,i,leftsum,leng,str,sum) { + leng = split(numbers,arr," ") + for (i=1; i<=leng; i++) { + sum += arr[i] + } + for (i=1; i<=leng; i++) { + sum -= arr[i] + if (leftsum == sum) { + str = str i " " + } + leftsum += arr[i] + } + return(str) +} diff --git a/Task/Equilibrium-index/Batch-File/equilibrium-index.bat b/Task/Equilibrium-index/Batch-File/equilibrium-index.bat new file mode 100644 index 0000000000..e9e60cd3e6 --- /dev/null +++ b/Task/Equilibrium-index/Batch-File/equilibrium-index.bat @@ -0,0 +1,42 @@ +@echo off +setlocal enabledelayedexpansion + +call :equilibrium-index "-7 1 5 2 -4 3 0" +call :equilibrium-index "2 4 6" +call :equilibrium-index "2 9 2" +call :equilibrium-index "1 -1 1 -1 1 -1 1" +pause>nul +exit /b + + %== The Function ==% +:equilibrium-index + ::Set the pseudo-array sequence... +set "seq=%~1" +set seq.length=0 +for %%S in (!seq!) do ( + set seq[!seq.length!]=%%S + set /a seq.length+=1 +) + ::Initialization of other variables... +set "equilms=" +set /a last=seq.length - 1 + ::The main checking... +for /l %%e in (0,1,!last!) do ( + set left=0 + set right=0 + + for /l %%i in (0,1,!last!) do ( + if %%i lss %%e (set /a left+=!seq[%%i]!) + if %%i gtr %%e (set /a right+=!seq[%%i]!) + ) + if !left!==!right! ( + if defined equilms ( + set "equilms=!equilms! %%e" + ) else ( + set "equilms=%%e" + ) + ) +) +echo [!equilms!] +goto :EOF + %==/The Function ==% diff --git a/Task/Equilibrium-index/Elixir/equilibrium-index-1.elixir b/Task/Equilibrium-index/Elixir/equilibrium-index-1.elixir new file mode 100644 index 0000000000..0ce59391a8 --- /dev/null +++ b/Task/Equilibrium-index/Elixir/equilibrium-index-1.elixir @@ -0,0 +1,8 @@ +defmodule Equilibrium do + def index(list) do + last = length(list) + Enum.filter(0..last-1, fn i -> + Enum.sum(Enum.slice(list, 0, i)) == Enum.sum(Enum.slice(list, i+1..last)) + end) + end +end diff --git a/Task/Equilibrium-index/Elixir/equilibrium-index-2.elixir b/Task/Equilibrium-index/Elixir/equilibrium-index-2.elixir new file mode 100644 index 0000000000..315943980d --- /dev/null +++ b/Task/Equilibrium-index/Elixir/equilibrium-index-2.elixir @@ -0,0 +1,7 @@ +defmodule Equilibrium do + def index(list), do: index(list,0,0,Enum.sum(list),[]) + + defp index([],_,_,_,acc), do: Enum.reverse(acc) + defp index([h|t],i,left,right,acc) when left==right-h, do: index(t,i+1,left+h,right-h,[i|acc]) + defp index([h|t],i,left,right,acc) , do: index(t,i+1,left+h,right-h,acc) +end diff --git a/Task/Equilibrium-index/Elixir/equilibrium-index-3.elixir b/Task/Equilibrium-index/Elixir/equilibrium-index-3.elixir new file mode 100644 index 0000000000..c0c2bf643e --- /dev/null +++ b/Task/Equilibrium-index/Elixir/equilibrium-index-3.elixir @@ -0,0 +1,9 @@ +indices = [ + [-7, 1, 5, 2,-4, 3, 0], + [2, 4, 6], + [2, 9, 2], + [1,-1, 1,-1, 1,-1, 1] +] +Enum.each(indices, fn list -> + IO.puts "#{inspect list} => #{inspect Equilibrium.index(list)}" +end) diff --git a/Task/Equilibrium-index/Haskell/equilibrium-index-1.hs b/Task/Equilibrium-index/Haskell/equilibrium-index-1.hs index 60bf4b9421..058a75aa18 100644 --- a/Task/Equilibrium-index/Haskell/equilibrium-index-1.hs +++ b/Task/Equilibrium-index/Haskell/equilibrium-index-1.hs @@ -1,11 +1,11 @@ -import Data.List -import Control.Monad -import Control.Arrow -import System.Random +import System.Random (randomRIO) +import Data.List (elemIndices, takeWhile) +import Control.Monad (replicateM, liftM2) +import Control.Arrow ((&&&)) -equilibr xs = elemIndices True. map (uncurry((.sum).(==). sum)). - takeWhile(not.null.snd) $ map (flip (liftM2 (&&&) take (drop. pred)) xs) [1..] +equilibr xs = elemIndices True . map (uncurry $ (. sum) . (==) . sum) . + takeWhile (not . null . snd) $ map (flip (liftM2 (&&&) take $ drop . pred) xs) [1..] langeSliert = replicateM 2000 (randomRIO (-15,15) :: IO Int) - >>= print. equilibr + >>= print . equilibr diff --git a/Task/Equilibrium-index/JavaScript/equilibrium-index.js b/Task/Equilibrium-index/JavaScript/equilibrium-index.js new file mode 100644 index 0000000000..0e69b2f815 --- /dev/null +++ b/Task/Equilibrium-index/JavaScript/equilibrium-index.js @@ -0,0 +1,21 @@ +function equilibrium (array) { + var equilibriums = []; + + array.forEach(function(_, idx, arr) { + var left = 0, right = 0; + + for (var i = 0; i < arr.length; i++) { + if (i < idx) { + left += array[i]; + } else if (i > idx) { + right += array[i]; + } + } + + if (left === right) equilibriums.push(idx); + }); + + return equilibriums; +} + +console.log(equilibrium([-7,1,5,2,-4,3,0])); diff --git a/Task/Equilibrium-index/PowerShell/equilibrium-index.psh b/Task/Equilibrium-index/PowerShell/equilibrium-index.psh new file mode 100644 index 0000000000..5a447df6f0 --- /dev/null +++ b/Task/Equilibrium-index/PowerShell/equilibrium-index.psh @@ -0,0 +1,15 @@ +function equil($arr){ + $res=@() + for($i=0;$i -lt $arr.length;$i++){ + $left=0;$right=0 + + for($j=0;$j -lt $arr.length;$j++){ + if ($j -lt $i){$left+=$arr[$j]} + if ($j -gt $i){$right+=$arr[$j]} + } + if($left -eq $right){$res+=$i} + } + [String]$res +} + +equil -7,1,5,2,-4,3,0 diff --git a/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx b/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx index 40334f7f28..4b262509f2 100644 --- a/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx +++ b/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx @@ -1,30 +1,22 @@ -/*REXX program finds the equilibrium index for a numeric array (list).*/ -parse arg x /*get array's numbers from the CL*/ -if x='' then x=copies(' 7 -7',50) 7 /*Nothing given? Generate a list*/ -say ' array list: ' space(x) /*echo the array list to screen. */ -n=words(x) /*the number of words in the list*/ - do j=0 for n /*0─start is for zero─based array*/ - A.j=word(x,j+1) /*define the array element. */ - end /*j*/ /* [↑] assign A.0 A.1 A.3 ···*/ -say /*··· and also show a blank line.*/ -ans=equilibriumIndex(n) /*calculate the equilibrium Index*/ -@indexes=word('indices index',1+(ans==1)) /*adjust for single index?*/ -say 'equilibrium' @indexes": " ans /*show equilibrium index/indices.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────EQUILIBRIUMINDEX subroutine─────────*/ -equilibriumIndex: procedure expose A. /*have the array A. be exposed.*/ -parse arg top; high=top-1 /*stemmed array A. starts at 0*/ -q= /*equilibrium indexes (so far). */ - do e=0 to high /*find various sums (top/bot). */ - sumB=0 /*sum of bottom part of the list*/ - do b=0 to e-1 /*add the " " " " " */ - sumB=sumB + A.b /*add this array element to sumB.*/ - end /*b*/ /* [↑] summation of bottom part.*/ - sumT=0 /*sum of top part of the list*/ - do t=e+1 to high /*add the " " " " " */ - sumT=sumT + A.t /*add this array element to sumT.*/ - end /*t*/ /* [↑] summation of the top part*/ - if sumB==sumT then q=q e /*if both sums equal, found one. */ - end /*e*/ /* [↑] add quilibrium to E list.*/ -if q=='' then q="(none)" /*adjust if no indices are found.*/ -return strip(q) /*return the equilibrium list. */ +/*REXX program finds the equilibrium index for a numeric array (list). */ +parse arg x /*get array's numbers from the CL.*/ +if x='' then x=copies(' 7 -7',50) 7 /*Nothing given? Generate a list.*/ +say ' array list: ' space(x) /*echo the array list to screen. */ +n=words(x) /*the number of words in the list.*/ + do j=0 for n /*0─start is for zero─based array.*/ + A.j=word(x, j+1) /*define the array element. */ + end /*j*/ /* [↑] assign A.0 A.1 A.3 ··· */ +say /*··· and also show a blank line. */ +ans=equilibrium_index(n) /*calculate the equilibrium index.*/ +say 'equilibrium' word('indices index', 1 + (words(ans==1)))": " ans +exit /*stick a fork in it, we're done. */ +/*──────────────────────────────────EQUILIBRIUM_INDEX subroutine─────────*/ +equilibrium_index: procedure expose A. /*have the array A. be exposed.*/ +parse arg # /*stemmed array A. starts at 0*/ +$= /*equilibrium indices (so far). */ + do i=0 for #; sum=0 + do k=0 for #; sum=sum + A.k*sign(k-i); end /*k*/ + if sum=0 then $=$ i + end /*i*/ +if $=='' then $="(none)" /*adjust if no indices are found. */ +return strip($) /*return the equilibrium list. */ diff --git a/Task/Equilibrium-index/VBScript/equilibrium-index.vb b/Task/Equilibrium-index/VBScript/equilibrium-index.vb new file mode 100644 index 0000000000..c54e48fe2d --- /dev/null +++ b/Task/Equilibrium-index/VBScript/equilibrium-index.vb @@ -0,0 +1,19 @@ +arr = Array(-7,1,5,2,-4,3,0) +WScript.StdOut.Write equilibrium(arr,UBound(arr)) +WScript.StdOut.WriteLine + +Function equilibrium(arr,n) + sum = 0 + leftsum = 0 + 'find the sum of the whole array + For i = 0 To UBound(arr) + sum = sum + arr(i) + Next + For i = 0 To UBound(arr) + sum = sum - arr(i) + If leftsum = sum Then + equilibrium = equilibrium & i & ", " + End If + leftsum = leftsum + arr(i) + Next +End Function diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-1.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-1.basic new file mode 100644 index 0000000000..d720605383 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-1.basic @@ -0,0 +1,35 @@ +{{works with|QBasic}}While building the table, it's easier to simply not print unused values, rather than have to go back and strike them out afterward. (Both that and the actual adding happen in the "IF NOT (isEven(x))" block.)DECLARE FUNCTION half% (a AS INTEGER) +DECLARE FUNCTION doub% (a AS INTEGER) +DECLARE FUNCTION isEven% (a AS INTEGER) + +DIM x AS INTEGER, y AS INTEGER, outP AS INTEGER + +x = 17 +y = 34 + +DO + PRINT x, + IF NOT (isEven(x)) THEN + outP = outP + y + PRINT y + ELSE + PRINT + END IF + IF x < 2 THEN EXIT DO + x = half(x) + y = doub(y) +LOOP + +PRINT " =", outP + +FUNCTION doub% (a AS INTEGER) + doub% = a * 2 +END FUNCTION + +FUNCTION half% (a AS INTEGER) + half% = a \ 2 +END FUNCTION + +FUNCTION isEven% (a AS INTEGER) + isEven% = (a MOD 2) - 1 +END FUNCTION diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-2.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-2.basic new file mode 100644 index 0000000000..58c6c595f3 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-2.basic @@ -0,0 +1,22 @@ + x% = 17 + y% = 34 + + REPEAT + IF NOT FNeven(x%) THEN + p% += y% + PRINT x%, y% + ELSE + PRINT x%, " ---" + ENDIF + x% = FNhalve(x%) + y% = FNdouble(y%) + UNTIL x% = 0 + PRINT " " , " ===" + PRINT " " , p% + END + + DEF FNdouble(A%) = A% * 2 + + DEF FNhalve(A%) = A% DIV 2 + + DEF FNeven(A%) = ((A% AND 1) = 0) diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-3.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-3.basic new file mode 100644 index 0000000000..6b659ad2d6 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-3.basic @@ -0,0 +1,87 @@ +Function double_(y As String) As String + Var answer="0"+y + Var addcarry=0 + For n_ As Integer=Len(y)-1 To 0 Step -1 + Var addup=y[n_]+y[n_]-96 + answer[n_+1]=(addup+addcarry) Mod 10+48 + addcarry=(-(10<=(addup+addcarry))) + Next n_ + answer[0]=addcarry+48 + Return Ltrim(answer,"0") +End Function + +Function Accumulate(NUM1 As String,NUM2 As String) As String + Var three="0"+NUM1 + Var two=String(len(NUM1)-len(NUM2),"0")+NUM2 + Var addcarry=0 + For n2 As Integer=len(NUM1)-1 To 0 Step -1 + Var addup=two[n2]+NUM1[n2]-96 + three[n2+1]=(addup+addcarry) Mod 10+48 + addcarry=(-(10<=(addup+addcarry))) + Next n2 + three[0]=addcarry+48 + three=Ltrim(three,"0") + If three="" Then Return "0" + Return three +End Function + +Function Half(Byref x As String) As String + Var carry=0 + For z As Integer=0 To Len(x)-1 + Var temp=(x[z]-48+carry) + Var main=temp Shr 1 + carry=(temp And 1) Shl 3 +(temp And 1) Shl 1 + x[z]=main+48 + Next z + x= Ltrim(x,"0") + Return x +End Function + +Function IsEven(x As String) As Integer + If x[Len(x)-1] And 1 Then Return 0 + return -1 +End Function + +Function EthiopianMultiply(n1 As String,n2 As String) As String + Dim As String x=n1,y=n2 + If Len(y)>Len(x) Then Swap y,x + 'set the largest one to be halfed + If Len(y)=Len(x) Then + If x"" + temprint="" + odd="" + If not IsEven(x) Then + temprint=" *" + odd=" <-- odd" + ans=Accumulate(y,ans) + End If + Print x;odd;tab(30);y;temprint + x=Half(x) + y= Double_(y) + Wend + Return ans +End Function +'================= Example ==================== +Print +Dim As String s1="17" +Dim As String s2="34" +Print "Half";tab(30);"Double * marks those accumulated" +print "Biggest";tab(30);"Smallest" + + +Print + +Var ans= EthiopianMultiply(s1,s2) + +Print +Print +Print "Final answer" +Print " ";ans +print "Float check" +Print Val(s1)*Val(s2) + +Sleep diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-4.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-4.basic new file mode 100644 index 0000000000..509d216c77 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-4.basic @@ -0,0 +1,10 @@ +10 DEF FNE(A)=(A+1) MOD 2 +20 DEF FNH(A)=INT(A/2) +30 DEF FND(A)=2*A +40 X=17:Y=34:TOT=0 +50 WHILE X>=1 +60 PRINT X, +70 IF FNE(X)=0 THEN TOT=TOT+Y:PRINT Y ELSE PRINT +80 X=FNH(X):Y=FND(Y) +90 WEND +100 PRINT "=", TOT diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-5.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-5.basic new file mode 100644 index 0000000000..0330729a24 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-5.basic @@ -0,0 +1,29 @@ +x = 17 +y = 34 +msg$ = str$(x) + " * " + str$(y) + " = " +Print str$(x) + " " + str$(y) +'In this routine we will not worry about discarding the right hand value whos left hand partner is even; +'we will just not add it to our product. +Do Until x < 2 + If Not(isEven(x)) Then + product = (product + y) + End If + x = halveInt(x) + y = doubleInt(y) + Print str$(x) + " " + str$(y) +Loop +product = (product + y) +If (x < 0) Then product = (product * -1) +Print msg$ + str$(product) + +Function isEven(num) + isEven = Abs(Not(num Mod 2)) +End Function + +Function halveInt(num) + halveInt = Int(num/ 2) +End Function + +Function doubleInt(num) + doubleInt = (num * 2) +End Function diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-6.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-6.basic new file mode 100644 index 0000000000..d7e6262e40 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-6.basic @@ -0,0 +1,33 @@ +Procedure isEven(x) + ProcedureReturn (x & 1) ! 1 +EndProcedure + +Procedure halveValue(x) + ProcedureReturn x / 2 +EndProcedure + +Procedure doubleValue(x) + ProcedureReturn x << 1 +EndProcedure + +Procedure EthiopianMultiply(x, y) + Protected sum + Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ... ") + Repeat + If Not isEven(x) + sum + y + EndIf + x = halveValue(x) + y = doubleValue(y) + Until x < 1 + PrintN(" equals " + Str(sum)) + ProcedureReturn sum +EndProcedure + +If OpenConsole() + EthiopianMultiply(17,34) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-7.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-7.basic new file mode 100644 index 0000000000..91695fb6bf --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-7.basic @@ -0,0 +1,38 @@ +Procedure isEven(x) + ProcedureReturn (x & 1) ! 1 +EndProcedure + +Procedure halveValue(x) + ProcedureReturn x / 2 +EndProcedure + +Procedure doubleValue(x) + ProcedureReturn x << 1 +EndProcedure + +Procedure EthiopianMultiply(x, y) + Protected sum, sign = x + + Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ...") + Repeat + If Not isEven(x) + sum + y + EndIf + x = halveValue(x) + y = doubleValue(y) + Until x = 0 + If sign < 0 : sum * -1: EndIf + + PrintN(" equals " + Str(sum)) + ProcedureReturn sum +EndProcedure + +If OpenConsole() + EthiopianMultiply(17,34) + EthiopianMultiply(-17,34) + EthiopianMultiply(-17,-34) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication.basic deleted file mode 100644 index ba019dedce..0000000000 --- a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication.basic +++ /dev/null @@ -1,35 +0,0 @@ -DECLARE FUNCTION half% (a AS INTEGER) -DECLARE FUNCTION doub% (a AS INTEGER) -DECLARE FUNCTION isEven% (a AS INTEGER) - -DIM x AS INTEGER, y AS INTEGER, outP AS INTEGER - -x = 17 -y = 34 - -DO - PRINT x, - IF NOT (isEven(x)) THEN - outP = outP + y - PRINT y - ELSE - PRINT - END IF - IF x < 2 THEN EXIT DO - x = half(x) - y = doub(y) -LOOP - -PRINT " =", outP - -FUNCTION doub% (a AS INTEGER) - doub% = a * 2 -END FUNCTION - -FUNCTION half% (a AS INTEGER) - half% = a \ 2 -END FUNCTION - -FUNCTION isEven% (a AS INTEGER) - isEven% = (a MOD 2) - 1 -END FUNCTION diff --git a/Task/Ethiopian-multiplication/Bracmat/ethiopian-multiplication.bracmat b/Task/Ethiopian-multiplication/Bracmat/ethiopian-multiplication.bracmat new file mode 100644 index 0000000000..c2c654a41c --- /dev/null +++ b/Task/Ethiopian-multiplication/Bracmat/ethiopian-multiplication.bracmat @@ -0,0 +1,25 @@ +( (halve=.div$(!arg.2)) +& (double=.2*!arg) +& (isEven=.mod$(!arg.2):0) +& ( mul + = a b as bs newbs result + . !arg:(?as.?bs) + & whl + ' ( !as:? (%@:~1:?a) + & !as halve$!a:?as + & !bs:? %@?b + & !bs double$!b:?bs + ) + & :?newbs + & whl + ' ( !as:%@?a ?as + & !bs:%@?b ?bs + & (isEven$!a|!newbs !b:?newbs) + ) + & 0:?result + & whl + ' (!newbs:%@?b ?newbs&!b+!result:?result) + & !result + ) +& out$(mul$(17.34)) +); diff --git a/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication.e b/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication.e new file mode 100644 index 0000000000..44505f1059 --- /dev/null +++ b/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication.e @@ -0,0 +1,58 @@ +class + APPLICATION + +create + make + +feature {NONE} + + make + do + io.put_integer (ethiopian_multiplication (17, 34)) + end + + ethiopian_multiplication (a, b: INTEGER): INTEGER + -- Product of 'a' and 'b'. + require + a_positive: a > 0 + b_positive: b > 0 + local + x, y: INTEGER + do + x := a + y := b + from + until + x <= 0 + loop + if not is_even_int (x) then + Result := Result + y + end + x := halve_int (x) + y := double_int (y) + end + ensure + Result_correct: Result = a * b + end + +feature {NONE} + + double_int (n: INTEGER): INTEGER + --Two times 'n'. + do + Result := n * 2 + end + + halve_int (n: INTEGER): INTEGER + --'n' divided by two. + do + Result := n // 2 + end + + is_even_int (n: INTEGER): BOOLEAN + --Is 'n' an even integer? + do + Result := n \\ 2 = 0 + end + +end diff --git a/Task/Ethiopian-multiplication/Ela/ethiopian-multiplication.ela b/Task/Ethiopian-multiplication/Ela/ethiopian-multiplication.ela index 0f865a5183..529d5ba2dc 100644 --- a/Task/Ethiopian-multiplication/Ela/ethiopian-multiplication.ela +++ b/Task/Ethiopian-multiplication/Ela/ethiopian-multiplication.ela @@ -6,3 +6,5 @@ double = (2*) ethiopicmult a b = sum <| map snd <| filter (odd << fst) <| zip (takeWhile (>=1) <| iterate halve a) (iterate double b) + +ethiopicmult 17 34 diff --git a/Task/Ethiopian-multiplication/Elixir/ethiopian-multiplication.elixir b/Task/Ethiopian-multiplication/Elixir/ethiopian-multiplication.elixir new file mode 100644 index 0000000000..00b4216222 --- /dev/null +++ b/Task/Ethiopian-multiplication/Elixir/ethiopian-multiplication.elixir @@ -0,0 +1,19 @@ +defmodule Ethiopian do + def halve(n), do: div(n, 2) + + def double(n), do: n * 2 + + def even(n), do: rem(n, 2) == 0 + + def multiply(lhs, rhs) when is_integer(lhs) and lhs > 0 and is_integer(rhs) and rhs > 0 do + multiply(lhs, rhs, 0) + end + + def multiply(1, rhs, acc), do: rhs + acc + def multiply(lhs, rhs, acc) do + if even(lhs), do: multiply(halve(lhs), double(rhs), acc), + else: multiply(halve(lhs), double(rhs), acc+rhs) + end +end + +IO.inspect Ethiopian.multiply(17, 34) diff --git a/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-4.java b/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-4.java new file mode 100644 index 0000000000..1ea4761dee --- /dev/null +++ b/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-4.java @@ -0,0 +1 @@ +def pairs: while( .[0] > 0; [ (.[0] | halve), (.[1] | double) ]); diff --git a/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-5.java b/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-5.java new file mode 100644 index 0000000000..8cef496ce6 --- /dev/null +++ b/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-5.java @@ -0,0 +1,15 @@ +def halve: (./2) | floor; + +def double: 2 * .; + +def isEven: . % 2 == 0; + +def ethiopian_multiply(a;b): + def pairs: recurse( if .[0] > 0 + then [ (.[0] | halve), (.[1] | double) ] + else empty + end ); + reduce ([a,b] | pairs + | select( .[0] | isEven | not) + | .[1] ) as $i + (0; . + $i) ; diff --git a/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-6.java b/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-6.java new file mode 100644 index 0000000000..e89ad806a5 --- /dev/null +++ b/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-6.java @@ -0,0 +1 @@ +ethiopian_multiply(17;34) # => 578 diff --git a/Task/Ethiopian-multiplication/Python/ethiopian-multiplication-1.py b/Task/Ethiopian-multiplication/Python/ethiopian-multiplication-1.py index 812da2bff4..a1285d97a0 100644 --- a/Task/Ethiopian-multiplication/Python/ethiopian-multiplication-1.py +++ b/Task/Ethiopian-multiplication/Python/ethiopian-multiplication-1.py @@ -1,28 +1,31 @@ tutor = True def halve(x): - return x//2 + return x // 2 def double(x): - return x*2 + return x * 2 def even(x): return not x % 2 def ethiopian(multiplier, multiplicand): if tutor: - print( "Ethiopian multiplication of %i and %i" % - (multiplier, multiplicand) ) + print("Ethiopian multiplication of %i and %i" % + (multiplier, multiplicand)) result = 0 while multiplier >= 1: if even(multiplier): - if tutor: print( "%4i %6i STRUCK" % - (multiplier, multiplicand) ) + if tutor: + print("%4i %6i STRUCK" % + (multiplier, multiplicand)) else: - if tutor: print( "%4i %6i KEPT" % - (multiplier, multiplicand) ) + if tutor: + print("%4i %6i KEPT" % + (multiplier, multiplicand)) result += multiplicand multiplier = halve(multiplier) multiplicand = double(multiplicand) - if tutor: print() + if tutor: + print() return result diff --git a/Task/Ethiopian-multiplication/R/ethiopian-multiplication.r b/Task/Ethiopian-multiplication/R/ethiopian-multiplication-1.r similarity index 100% rename from Task/Ethiopian-multiplication/R/ethiopian-multiplication.r rename to Task/Ethiopian-multiplication/R/ethiopian-multiplication-1.r diff --git a/Task/Ethiopian-multiplication/R/ethiopian-multiplication-2.r b/Task/Ethiopian-multiplication/R/ethiopian-multiplication-2.r new file mode 100644 index 0000000000..d105b32b1d --- /dev/null +++ b/Task/Ethiopian-multiplication/R/ethiopian-multiplication-2.r @@ -0,0 +1,15 @@ +halve <- function(a) floor(a/2) +double <- function(a) a*2 +iseven <- function(a) (a%%2)==0 + +ethiopicmult<-function(x,y){ + res<-ifelse(iseven(y),0,x) + while(!y==1){ + x<-double(x) + y<-halve(y) + if(!iseven(y)) res<-res+x + } + return(res) +} + +print(ethiopicmult(17,34)) diff --git a/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication-1.rexx b/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication-1.rexx new file mode 100644 index 0000000000..f8b4a6184c --- /dev/null +++ b/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication-1.rexx @@ -0,0 +1,20 @@ +/*REXX program multiplies two integers by the Ethiopian/Russian peasant method*/ +numeric digits 3000 /*handle some gihugeic integers. */ +parse arg a b . /*get two numbers from the command line*/ +say 'a=' a +say 'b=' b +say 'product=' eMult(a,b) +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +eMult: procedure; parse arg x 1 ox,y /*X and OX are set to the 1st argument.*/ +$=0 /*product of the two integers (so far).*/ + do while x\==0 /*keep processing while X not 0.*/ + if \isEven(x) then $=$+y /*if odd, then add Y to product.*/ + x= halve(x) /*invoke the HALVE function. */ + y=double(y) /* " " DOUBLE " */ + end /*while*/ /* [↑] Ethiopian multiplication*/ +return $*sign(ox) /*maintain correct sign for prod*/ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ +double: return arg(1) * 2 /* * is REXX multiplication. */ +halve: return arg(1) % 2 /* % " " integer division. */ +isEven: return arg(1) // 2 == 0 /* // " " " remainder. */ diff --git a/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication-2.rexx b/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication-2.rexx new file mode 100644 index 0000000000..3defa11ba8 --- /dev/null +++ b/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication-2.rexx @@ -0,0 +1,26 @@ +/*REXX program multiplies two integers by the Ethiopian/Russian peasant method*/ +numeric digits 3000 /*handle some ginormous integers. */ +parse arg a b _ . /*get two numbers from the command line*/ +if \datatype(a,'W') then call error "1st argument isn't an integer." +if \datatype(b,'N') then call error "2nd argument isn't a valid number." +if b=='' | _\=='' then call error "two arguments weren't specified." +p=eMult(a,b) /*Ethiopian or Russian peasant method. */ +w=max(length(a), length(b), length(p)) /*find the maximum width of 3 numbers. */ +say ' a=' right(a,w) /*use right justification to display A.*/ +say ' b=' right(b,w) /* " " " " " B.*/ +say 'product=' right(p,w) /* " " " " " P.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +eMult: procedure; parse arg x 1 ox,y /*X and OX are set to the 1st argument.*/ +$=0 /*product of the two integers (so far).*/ + do while x\==0 /*keep processing while X not 0.*/ + if \isEven(x) then $=$+y /*if odd, then add Y to product.*/ + x= halve(x) /*invoke the HALVE function. */ + y=double(y) /* " " DOUBLE " */ + end /*while*/ /* [↑] Ethiopian multiplication*/ +return $*sign(ox)/1 /*maintain correct sign for prod*/ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ +double: return arg(1) * 2 /* * is REXX multiplication. */ +halve: return arg(1) % 2 /* % " " integer division. */ +isEven: return arg(1) // 2 == 0 /* // " " " remainder. */ +error: say '***error!***' arg(1); exit 13 /*display an error message.*/ diff --git a/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication.rexx b/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication.rexx deleted file mode 100644 index 1d9ecf5570..0000000000 --- a/Task/Ethiopian-multiplication/REXX/ethiopian-multiplication.rexx +++ /dev/null @@ -1,30 +0,0 @@ -/*REXX program multiplies 2 integers by Ethiopian/Russian peasant method*/ -numeric digits 1000 /*handle very large integers. */ -parse arg a b . /*handles zeroes & negative ints.*/ - /*A & B should be checked if ints*/ -say 'a=' a -say 'b=' b -say 'product=' emult(a,b) -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────EMULT subroutine────────────────────*/ -emult: procedure; parse arg x 1 ox,y -prod=0 - do while x\==0 - if \iseven(x) then prod=prod+y - x=halve(x) - y=double(y) - end -return prod*sign(ox) -/*──────────────────────────────────subroutines─────────────────────────*/ -halve: return arg(1)%2 -double: return arg(1)*2 -iseven: return arg(1)//2==0 - - /*Note: the above procedures don't modify (or define) any */ - /*local variables, so there is no need to specify PROCEDURE */ - - /*REXX allows multiple definitions, only the 1st one is used. */ - /*Three different argument names (methodologies?) are shown. */ -halve: procedure; parse arg ?; return ?%2 -double: procedure; parse arg x; return x+x -iseven: procedure; parse arg _; return _//2 == 0 diff --git a/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust b/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust index 53bac168c3..9adbf62881 100644 --- a/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust +++ b/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust @@ -1,28 +1,35 @@ -fn double(a : int) -> int{ - a << 1 +fn double(a: i32) -> i32 { + 2*a } -fn halve(a : int) -> int{ - a >> 1 +fn halve(a: i32) -> i32 { + a/2 } -fn is_even(a : int) -> bool{ - a & 1 == 0 +fn is_even(a: i32) -> bool { + a % 2 == 0 } -fn ethiopian_multiplication(mut x : int, mut y : int) -> int{ - let mut sum = 0; - - while x >= 1 { - print!("{} \t {}", x, y); - if is_even(x) { - println!("\t Not Kept"); - } else { - sum = sum + y; - println!("\t Kept"); - } - x = halve(x); - y = double(y); - } - sum +fn ethiopian_multiplication(mut x: i32, mut y: i32) -> i32 { + let mut sum = 0; + + while x >= 1 { + print!("{} \t {}", x, y); + match is_even(x) { + true => println!("\t Not Kept"), + false => { + println!("\t Kept"); + sum += y; + } + } + x = halve(x); + y = double(y); + } + sum +} + +fn main() { + let output = ethiopian_multiplication(17, 34); + println!("---------------------------------"); + println!("\t {}", output); } diff --git a/Task/Euler-method/BASIC/euler-method-1.basic b/Task/Euler-method/BASIC/euler-method-1.basic new file mode 100644 index 0000000000..432f76c6ac --- /dev/null +++ b/Task/Euler-method/BASIC/euler-method-1.basic @@ -0,0 +1,15 @@ + PROCeuler("-0.07*(y-20)", 100, 0, 100, 2) + PROCeuler("-0.07*(y-20)", 100, 0, 100, 5) + PROCeuler("-0.07*(y-20)", 100, 0, 100, 10) + END + + DEF PROCeuler(df$, y, a, b, s) + LOCAL t, @% + @% = &2030A + t = a + WHILE t <= b + PRINT t, y + y += s * EVAL(df$) + t += s + ENDWHILE + ENDPROC diff --git a/Task/Euler-method/BASIC/euler-method-2.basic b/Task/Euler-method/BASIC/euler-method-2.basic new file mode 100644 index 0000000000..66749bbe52 --- /dev/null +++ b/Task/Euler-method/BASIC/euler-method-2.basic @@ -0,0 +1,24 @@ +'Freebasic .9 +'Custom rounding +#define round(x,N) Rtrim(Rtrim(Left(Str((x)+(.5*Sgn((x)))/(10^(N))),Instr(Str((x)+(.5*Sgn((x)))/(10^(N))),".")+(N)),"0"),".") + +#macro Euler(fn,_y,min,max,h,printoption) +Print "Step ";#h;":":Print +Print "time","Euler"," Analytic" +If printoption<>"print" Then Print "Data omitted ..." +Scope + Dim As Double temp=(min),y=(_y) + Do + If printoption="print" Then Print temp,round(y,3),20+80*Exp(-0.07*temp) + y=y+(h)*(fn) + temp=temp+(h) + Loop Until temp>(max) + Print"________________" + Print +End Scope +#endmacro + +Euler(-.07*(y-20),100,0,100,2,"don't print") +Euler(-.07*(y-20),100,0,100,5,"print") +Euler(-.07*(y-20),100,0,100,10,"print") +Sleep diff --git a/Task/Euler-method/BASIC/euler-method-3.basic b/Task/Euler-method/BASIC/euler-method-3.basic new file mode 100644 index 0000000000..6cffaf383f --- /dev/null +++ b/Task/Euler-method/BASIC/euler-method-3.basic @@ -0,0 +1,14 @@ +x = euler(-0.07,-20, 100, 0, 100, 2) +x = euler-0.07,-20, 100, 0, 100, 5) +x = euler(-0.07,-20, 100, 0, 100, 10) +end + +FUNCTION euler(da,db, y, a, b, s) +print "===== da:";da;" db:";db;" y:";y;" a:";a;" b:";b;" s:";s;" ===================" +t = a +WHILE t <= b + PRINT t;chr$(9);y + y = y + s * (da * (y + db)) + t = t + s +WEND +END FUNCTION diff --git a/Task/Euler-method/Elixir/euler-method.elixir b/Task/Euler-method/Elixir/euler-method.elixir new file mode 100644 index 0000000000..e700dabf30 --- /dev/null +++ b/Task/Euler-method/Elixir/euler-method.elixir @@ -0,0 +1,13 @@ +defmodule Euler do + def method(_, _, t, b, _) when t>b, do: :ok + def method(f, y, t, b, h) do + :io.format "~7.3f ~7.3f~n", [t,y] + method(f, y + h * f.(t,y), t + h, b, h) + end +end + +f = fn _time, temp -> -0.07 * (temp - 20) end +Enum.each([10, 5, 2], fn step -> + IO.puts "\nStep = #{step}" + Euler.method(f, 100.0, 0.0, 100.0, step) +end) diff --git a/Task/Euler-method/PowerShell/euler-method.psh b/Task/Euler-method/PowerShell/euler-method.psh new file mode 100644 index 0000000000..f91c09651e --- /dev/null +++ b/Task/Euler-method/PowerShell/euler-method.psh @@ -0,0 +1,43 @@ +function euler (${f}, ${y}, $y0, $t0, $tEnd) { + function f-euler ($tn, $yn, $h) { + $yn + $h*(f $tn $yn) + } + function time ($t0, $h, $tEnd) { + $end = [MATH]::Floor(($tEnd - $t0)/$h) + foreach ($_ in 0..$end) { $_*$h + $t0 } + } + $time = time $t0 10 $tEnd + $time5 = time $t0 5 $tEnd + $time2 = time $t0 2 $tEnd + $yn10 = $yn5 = $yn2 = $y0 + $i2 = $i5 = 0 + foreach ($tn10 in $time) { + while($time2[$i2] -ne $tn10) { + $i2++ + $yn2 = (f-euler $time2[$i2] $yn2 2) + } + while($time5[$i5] -ne $tn10) { + $i5++ + $yn5 = (f-euler $time5[$i5] $yn5 5) + } + [pscustomobject]@{ + t = "$tn10" + Analytical = "$("{0:N5}" -f (y $tn10))" + "Euler h = 2" = "$("{0:N5}" -f $yn2)" + "Euler h = 5" = "$("{0:N5}" -f $yn5)" + "Euler h = 10" = "$("{0:N5}" -f $yn10)" + "Error h = 2" = "$("{0:N5}" -f [MATH]::abs($yn2 - (y $tn10)))" + "Error h = 5" = "$("{0:N5}" -f [MATH]::abs($yn5 - (y $tn10)))" + "Error h = 10" = "$("{0:N5}" -f [MATH]::abs($yn10 - (y $tn10)))" + } + $yn10 = (f-euler $tn10 $yn10 10) + } +} +$k, $yr, $y0, $t0, $tEnd = 0.07, 20, 100, 0, 100 +function f ($t, $y) { + -$k *($y - $yr) +} +function y ($t) { + $yr + ($y0 - $yr)*[MATH]::Exp(-$k*$t) +} +euler f y $y0 $t0 $tEnd | Format-Table -AutoSize diff --git a/Task/Euler-method/Python/euler-method.py b/Task/Euler-method/Python/euler-method.py index 0b70ae4a33..1c00e47cfe 100644 --- a/Task/Euler-method/Python/euler-method.py +++ b/Task/Euler-method/Python/euler-method.py @@ -1,6 +1,6 @@ def euler(f,y0,a,b,h): t,y = a,y0 - while t < b: + while t <= b: print "%6.3f %6.3f" % (t,y) t += h y += h * f(t,y) diff --git a/Task/Euler-method/REXX/euler-method.rexx b/Task/Euler-method/REXX/euler-method.rexx index e7a4e712a2..feb6c6be8a 100644 --- a/Task/Euler-method/REXX/euler-method.rexx +++ b/Task/Euler-method/REXX/euler-method.rexx @@ -51,3 +51,22 @@ o: Parse Arg v Say right(t,3) format(Tr+(T0-Tr)/exp(k*t),5,10) format(v,5,10) Return + +exp: Procedure + Parse Arg x,prec + If prec<9 Then prec=9 + Numeric Digits (2*prec) + Numeric Fuzz 3 + o=1 + u=1 + r=1 + Do i=1 By 1 + ra=r + o=o*x + u=u*i + r=r+(o/u) + If r=ra Then Leave + End + Numeric Digits (prec) + r=r+0 + Return r diff --git a/Task/Evaluate-binomial-coefficients/360-Assembly/evaluate-binomial-coefficients.360 b/Task/Evaluate-binomial-coefficients/360-Assembly/evaluate-binomial-coefficients.360 new file mode 100644 index 0000000000..5506491b3e --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/360-Assembly/evaluate-binomial-coefficients.360 @@ -0,0 +1,24 @@ +* Evaluate binomial coefficients - 29/09/2015 +BINOMIAL CSECT + USING BINOMIAL,R15 set base register + SR R4,R4 clear for mult and div + LA R5,1 r=1 + LA R7,1 i=1 + L R8,N m=n +LOOP LR R4,R7 do while i<=k + C R4,K i<=k + BH LOOPEND if not then exit while + MR R4,R8 r*m + DR R4,R7 r=r*m/i + LA R7,1(R7) i=i+1 + BCTR R8,0 m=m-1 + B LOOP loop while +LOOPEND XDECO R5,PG edit r + XPRNT PG,12 print r + XR R15,R15 set return code + BR R14 return to caller +N DC F'10' <== input value +K DC F'4' <== input value +PG DS CL12 buffer + YREGS + END BINOMIAL diff --git a/Task/Evaluate-binomial-coefficients/ABAP/evaluate-binomial-coefficients.abap b/Task/Evaluate-binomial-coefficients/ABAP/evaluate-binomial-coefficients.abap new file mode 100644 index 0000000000..51791732f8 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/ABAP/evaluate-binomial-coefficients.abap @@ -0,0 +1,28 @@ +CLASS lcl_binom DEFINITION CREATE PUBLIC. + + PUBLIC SECTION. + CLASS-METHODS: + calc + IMPORTING n TYPE i + k TYPE i + RETURNING VALUE(r_result) TYPE f. + +ENDCLASS. + +CLASS lcl_binom IMPLEMENTATION. + + METHOD calc. + + r_result = 1. + DATA(i) = 1. + DATA(m) = n. + + WHILE i <= k. + r_result = r_result * m / i. + i = i + 1. + m = m - 1. + ENDWHILE. + + ENDMETHOD. + +ENDCLASS. diff --git a/Task/Evaluate-binomial-coefficients/ALGOL-W/evaluate-binomial-coefficients.alg b/Task/Evaluate-binomial-coefficients/ALGOL-W/evaluate-binomial-coefficients.alg new file mode 100644 index 0000000000..aeab272dde --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/ALGOL-W/evaluate-binomial-coefficients.alg @@ -0,0 +1,32 @@ +begin + % calculates n!/k! % + integer procedure factorialOverFactorial( integer value n, k ) ; + if k > n then 0 + else if k = n then 1 + else % k < n % begin + integer f; + f := 1; + for i := k + 1 until n do f := f * i; + f + end factorialOverFactorial ; + + % calculates n! % + integer procedure factorial( integer value n ) ; + begin + integer f; + f := 1; + for i := 2 until n do f := f * i; + f + end factorial ; + + % calculates the binomial coefficient of (n k) % + % uses the factorialOverFactorial procedure for a slight optimisation % + integer procedure binomialCoefficient( integer value n, k ) ; + if ( n - k ) > k + then factorialOverFactorial( n, n - k ) div factorial( k ) + else factorialOverFactorial( n, k ) div factorial( n - k ); + + % display the binomial coefficient of (5 3) % + write( binomialCoefficient( 5, 3 ) ) + +end. diff --git a/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d b/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients-1.d similarity index 100% rename from Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d rename to Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients-1.d diff --git a/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients-2.d b/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients-2.d new file mode 100644 index 0000000000..276cc790cb --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients-2.d @@ -0,0 +1,22 @@ +T BinomialCoeff(T)(in T n, in T k) +{ + T nn = n, kk = k, c = cast(T)1; + + if (kk > nn - kk) kk = nn - kk; + + for (T i = cast(T)0; i < kk; i++) + { + c = c * (nn - i); + c = c / (i + cast(T)1); + } + + return c; +} + +void main() +{ + import std.stdio, std.bigint; + + BinomialCoeff(10UL, 3UL).writeln; + BinomialCoeff(100.BigInt, 50.BigInt).writeln; +} diff --git a/Task/Evaluate-binomial-coefficients/Elixir/evaluate-binomial-coefficients.elixir b/Task/Evaluate-binomial-coefficients/Elixir/evaluate-binomial-coefficients.elixir new file mode 100644 index 0000000000..349996ff85 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Elixir/evaluate-binomial-coefficients.elixir @@ -0,0 +1,11 @@ +defmodule RC do + def choose(n,k) when is_integer(n) and is_integer(k) and n>=0 and k>=0 and n>=k do + if k==0, do: 1, else: choose(n,k,1,1) + end + + def choose(n,k,k,acc), do: div(acc * (n-k+1), k) + def choose(n,k,i,acc), do: choose(n, k, i+1, div(acc * (n-i+1), i)) +end + +IO.inspect RC.choose(5,3) +IO.inspect RC.choose(60,30) diff --git a/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients.julia b/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients.julia new file mode 100644 index 0000000000..676fbd4e33 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients.julia @@ -0,0 +1,10 @@ +function binom(n,k) + n >= k || return 0 #short circuit base cases + n == 1 && return 1 + k == 0 && return 1 + + binom(n-1,k-1) + binom (n-1,k) #recursive call +end + +julia> binom(5,2) +10 diff --git a/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 b/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients-1.pl6 similarity index 100% rename from Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 rename to Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients-1.pl6 diff --git a/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients-2.pl6 b/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients-2.pl6 new file mode 100644 index 0000000000..019115371d --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients-2.pl6 @@ -0,0 +1 @@ +sub infix: { ([*] ($^n ... 0) Z/ 1 .. $^p).Int } diff --git a/Task/Evaluate-binomial-coefficients/PowerShell/evaluate-binomial-coefficients.psh b/Task/Evaluate-binomial-coefficients/PowerShell/evaluate-binomial-coefficients.psh new file mode 100644 index 0000000000..95fd9963d7 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/PowerShell/evaluate-binomial-coefficients.psh @@ -0,0 +1,17 @@ +function choose($n,$k) { + if($k -le $n -and 0 -le $k) { + $numerator = $denominator = 1 + 0..($k-1) | foreach{ + $numerator *= ($n-$_) + $denominator *= ($_ + 1) + } + $numerator/$denominator + } else { + "$k is greater than $n or lower than 0" + } +} +choose 5 3 +choose 2 1 +choose 10 10 +choose 10 2 +choose 10 8 diff --git a/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-1.rexx b/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-1.rexx index b99e7362dc..9fcde676fd 100644 --- a/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-1.rexx +++ b/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-1.rexx @@ -1,9 +1,9 @@ -/*REXX program calculates binomial coefficients (aka, combinations). */ -numeric digits 100000 /*allow some gihugeic numbers. */ -parse arg n k . /*get N and K from the C.L.*/ -say 'combinations('n","k')=' comb(n,k) /*display the result to terminal.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────COMB subroutine─────────────────────*/ -comb: procedure; parse arg x,y; return fact(x) % (fact(x-y) * fact(y)) -/*──────────────────────────────────FACT subroutine─────────────────────*/ -fact: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! +/*REXX program calculates binomial coefficients (aka, combinations). */ +numeric digits 100000 /*be able to handle gihugeic numbers. */ +parse arg n k . /*obtain N and K from the C.L. */ +say 'combinations('n","k')=' comb(n,k) /*display the number of combinations. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +comb: procedure; parse arg x,y; return !(x) % (!(x-y) * !(y)) +/*────────────────────────────────────────────────────────────────────────────*/ +!: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! diff --git a/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-2.rexx b/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-2.rexx index d9444e4b48..630ea3a018 100644 --- a/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-2.rexx +++ b/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-2.rexx @@ -1,9 +1,9 @@ -/*REXX program calculates binomial coefficients (aka, combinations). */ -numeric digits 100000 /*allow some gihugeic numbers. */ -parse arg n k . /*get N and K from the C.L.*/ -say 'combinations('n","k')=' comb(n,k) /*display the result to terminal.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────COMB subroutine─────────────────────*/ -comb: procedure; parse arg x,y; return pfact(x-y+1,x) % pfact(2,y) -/*──────────────────────────────────PFACT subroutine────────────────────*/ -pfact: procedure; !=1; do j=arg(1) to arg(2); !=!*j; end; return ! +/*REXX program calculates binomial coefficients (aka, combinations). */ +numeric digits 100000 /*be able to handle gihugeic numbers. */ +parse arg n k . /*obtain N and K from the C.L. */ +say 'combinations('n","k')=' comb(n,k) /*display the number of combinations. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +comb: procedure; parse arg x,y; return pfact(x-y+1,x) % pfact(2,y) +/*────────────────────────────────────────────────────────────────────────────*/ +pfact: procedure; !=1; do j=arg(1) to arg(2); !=!*j; end; return ! diff --git a/Task/Evaluate-binomial-coefficients/TI-83-BASIC/evaluate-binomial-coefficients.ti-83 b/Task/Evaluate-binomial-coefficients/TI-83-BASIC/evaluate-binomial-coefficients.ti-83 new file mode 100644 index 0000000000..fc39bb010d --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/TI-83-BASIC/evaluate-binomial-coefficients.ti-83 @@ -0,0 +1 @@ +10 nCr 4 diff --git a/Task/Evaluate-binomial-coefficients/VBScript/evaluate-binomial-coefficients.vb b/Task/Evaluate-binomial-coefficients/VBScript/evaluate-binomial-coefficients.vb new file mode 100644 index 0000000000..bbb70951ee --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/VBScript/evaluate-binomial-coefficients.vb @@ -0,0 +1,21 @@ +Function binomial(n,k) + binomial = factorial(n)/(factorial(n-k)*factorial(k)) +End Function + +Function factorial(n) + If n = 0 Then + factorial = 1 + Else + For i = n To 1 Step -1 + If i = n Then + factorial = n + Else + factorial = factorial * i + End If + Next + End If +End Function + +'calling the function +WScript.StdOut.Write "the binomial coefficient of 5 and 3 = " & binomial(5,3) +WScript.StdOut.WriteLine diff --git a/Task/Even-or-odd/ABAP/even-or-odd.abap b/Task/Even-or-odd/ABAP/even-or-odd.abap new file mode 100644 index 0000000000..46f84189c2 --- /dev/null +++ b/Task/Even-or-odd/ABAP/even-or-odd.abap @@ -0,0 +1,11 @@ +cl_demo_output=>display( + VALUE string_table( + FOR i = -5 WHILE i < 6 ( + COND string( + LET r = i MOD 2 IN + WHEN r = 0 THEN |{ i } is even| + ELSE |{ i } is odd| + ) + ) + ) +). diff --git a/Task/Even-or-odd/ALGOL-68/even-or-odd.alg b/Task/Even-or-odd/ALGOL-68/even-or-odd.alg index 3139bfcd3e..6453c257bc 100644 --- a/Task/Even-or-odd/ALGOL-68/even-or-odd.alg +++ b/Task/Even-or-odd/ALGOL-68/even-or-odd.alg @@ -1,4 +1,4 @@ -# Algol 68 has a standard operator: ODD which returns TRUE if it's integer # +# Algol 68 has a standard operator: ODD which returns TRUE if its integer # # operand is odd and FALSE if it is even # # E.g.: # diff --git a/Task/Even-or-odd/ALGOL-W/even-or-odd.alg b/Task/Even-or-odd/ALGOL-W/even-or-odd.alg new file mode 100644 index 0000000000..555305cc6d --- /dev/null +++ b/Task/Even-or-odd/ALGOL-W/even-or-odd.alg @@ -0,0 +1,8 @@ +begin + % the Algol W standard procedure odd returns true if its integer % + % parameter is odd, false if it is even % + for i := 1, 1702, 23, -26 + do begin + write( i, " is ", if odd( i ) then "odd" else "even" ) + end for_i +end. diff --git a/Task/Even-or-odd/AppleScript/even-or-odd.applescript b/Task/Even-or-odd/AppleScript/even-or-odd.applescript new file mode 100644 index 0000000000..d2f455e6f5 --- /dev/null +++ b/Task/Even-or-odd/AppleScript/even-or-odd.applescript @@ -0,0 +1,8 @@ +set nList to {3, 2, 1, 0, -1, -2, -3} +repeat with n in nList + if (n / 2) = n / 2 as integer then + log "Value " & n & " is even." + else + log "Value " & n & " is odd." + end if +end repeat diff --git a/Task/Even-or-odd/Befunge/even-or-odd.bf b/Task/Even-or-odd/Befunge/even-or-odd.bf new file mode 100644 index 0000000000..bcfa9f15a1 --- /dev/null +++ b/Task/Even-or-odd/Befunge/even-or-odd.bf @@ -0,0 +1 @@ +&2%52**"E"+,@ diff --git a/Task/Even-or-odd/C++/even-or-odd-1.cpp b/Task/Even-or-odd/C++/even-or-odd-1.cpp new file mode 100644 index 0000000000..4a4bf894b1 --- /dev/null +++ b/Task/Even-or-odd/C++/even-or-odd-1.cpp @@ -0,0 +1,9 @@ +bool isOdd(int x) +{ + return x % 2; +} + +bool isEven(int x) +{ + return !(x % 2); +} diff --git a/Task/Even-or-odd/C++/even-or-odd-2.cpp b/Task/Even-or-odd/C++/even-or-odd-2.cpp new file mode 100644 index 0000000000..3f4b9cdcee --- /dev/null +++ b/Task/Even-or-odd/C++/even-or-odd-2.cpp @@ -0,0 +1,17 @@ +template < typename T > +constexpr inline bool isEven( const T& v ) +{ + return isEven( int( v ) ); +} + +template <> +constexpr inline bool isEven< int >( const int& v ) +{ + return (v & 1) == 0; +} + +template < typename T > +constexpr inline bool isOdd( const T& v ) +{ + return !isEven(v); +} diff --git a/Task/Even-or-odd/C++/even-or-odd.cpp b/Task/Even-or-odd/C++/even-or-odd.cpp deleted file mode 100644 index fea9b2dd48..0000000000 --- a/Task/Even-or-odd/C++/even-or-odd.cpp +++ /dev/null @@ -1,3 +0,0 @@ -bool isEven(int x) { - return x % 2; -} diff --git a/Task/Even-or-odd/DCL/even-or-odd.dcl b/Task/Even-or-odd/DCL/even-or-odd.dcl new file mode 100644 index 0000000000..58c508a6d3 --- /dev/null +++ b/Task/Even-or-odd/DCL/even-or-odd.dcl @@ -0,0 +1,8 @@ +$! in DCL, for integers, the least significant bit determines the logical value, where 1 is true and 0 is false +$ +$ i = -5 +$ loop1: +$ if i then $ write sys$output i, " is odd" +$ if .not. i then $ write sys$output i, " is even" +$ i = i + 1 +$ if i .le. 6 then $ goto loop1 diff --git a/Task/Even-or-odd/Eiffel/even-or-odd.e b/Task/Even-or-odd/Eiffel/even-or-odd.e new file mode 100644 index 0000000000..8f59170161 --- /dev/null +++ b/Task/Even-or-odd/Eiffel/even-or-odd.e @@ -0,0 +1,14 @@ +--bit testing +if i.bit_and (1) = 0 then + -- i is even +end + +--built-in bit testing (uses bit_and) +if i.bit_test (0) then + -- i is odd +end + +--integer remainder (modulo) +if i \\ 2 = 0 then + -- i is even +end diff --git a/Task/Even-or-odd/Elixir/even-or-odd-1.elixir b/Task/Even-or-odd/Elixir/even-or-odd-1.elixir new file mode 100644 index 0000000000..45429c262c --- /dev/null +++ b/Task/Even-or-odd/Elixir/even-or-odd-1.elixir @@ -0,0 +1,14 @@ +defmodule RC do + require Integer + + def even_or_odd(n) when Integer.is_even(n), do: "#{n} is even" + def even_or_odd(n) , do: "#{n} is odd" + # In second "def", the guard clauses of "is_odd(n)" is unnecessary. + + # Another definition way + def even_or_odd2(n) do + if Integer.is_even(n), do: "#{n} is even", else: "#{n} is odd" + end +end + +Enum.each(-2..3, fn n -> IO.puts RC.even_or_odd(n) end) diff --git a/Task/Even-or-odd/Elixir/even-or-odd-2.elixir b/Task/Even-or-odd/Elixir/even-or-odd-2.elixir new file mode 100644 index 0000000000..cbc5ba4883 --- /dev/null +++ b/Task/Even-or-odd/Elixir/even-or-odd-2.elixir @@ -0,0 +1 @@ +rem(n,2) == 0 diff --git a/Task/Even-or-odd/Emacs-Lisp/even-or-odd-1.l b/Task/Even-or-odd/Emacs-Lisp/even-or-odd-1.l new file mode 100644 index 0000000000..1a72e8de3e --- /dev/null +++ b/Task/Even-or-odd/Emacs-Lisp/even-or-odd-1.l @@ -0,0 +1,11 @@ +(defun odd (n) + (if (oddp n) (format "%d is odd\n" n) + (format "%d is even\n" n))) + +(defun even (n) + (if (evenp n) (format "%d is even\n" n) + (format "%d is odd\n" n))) + +(progn + (insert (even 3) ) + (insert (odd 2) ))) diff --git a/Task/Even-or-odd/Emacs-Lisp/even-or-odd-2.l b/Task/Even-or-odd/Emacs-Lisp/even-or-odd-2.l new file mode 100644 index 0000000000..dfb0136281 --- /dev/null +++ b/Task/Even-or-odd/Emacs-Lisp/even-or-odd-2.l @@ -0,0 +1,11 @@ +(defun odd (n) + (if (= 1 (mod n 2) ) (format "%d is odd\n" n) + (format "%d is even\n" n))) + +(defun even (n) + (if (= 0 (mod n 2) ) (format "%d is even\n" n) + (format "%d is odd\n" n))) + +(progn + (insert (even 3) ) + (insert (odd 2) )) diff --git a/Task/Even-or-odd/Logo/even-or-odd.logo b/Task/Even-or-odd/Logo/even-or-odd.logo new file mode 100644 index 0000000000..b8e3d86622 --- /dev/null +++ b/Task/Even-or-odd/Logo/even-or-odd.logo @@ -0,0 +1,3 @@ +to even? :num + output equal? 0 modulo :num 2 +end diff --git a/Task/Even-or-odd/OCaml/even-or-odd-3.ocaml b/Task/Even-or-odd/OCaml/even-or-odd-3.ocaml new file mode 100644 index 0000000000..25c5037526 --- /dev/null +++ b/Task/Even-or-odd/OCaml/even-or-odd-3.ocaml @@ -0,0 +1,8 @@ +(* hmm, only valid for N0 *) +let rec myeven = function + | 0 -> true + | 1 -> false + | n -> myeven (n - 2) + +(* and here we have the not function in if form *) +let myodd n = if myeven n then false else true diff --git a/Task/Even-or-odd/PowerShell/even-or-odd.psh b/Task/Even-or-odd/PowerShell/even-or-odd.psh new file mode 100644 index 0000000000..1787352638 --- /dev/null +++ b/Task/Even-or-odd/PowerShell/even-or-odd.psh @@ -0,0 +1,9 @@ +function parity($n) { + if($n%2 -eq 0) { + "$n is even" + } else { + "$n is odd" + } +} +parity 0 +parity 1 diff --git a/Task/Even-or-odd/REXX/even-or-odd.rexx b/Task/Even-or-odd/REXX/even-or-odd.rexx index d98d400ae9..2eb512cb30 100644 --- a/Task/Even-or-odd/REXX/even-or-odd.rexx +++ b/Task/Even-or-odd/REXX/even-or-odd.rexx @@ -1,29 +1,85 @@ -/*REXX program displays if an integer is even or odd. */ -numeric digits 1000 /*handle most big 'uns from the CL*/ -parse arg x _ . /*get arg(s) from the command line*/ -if x=='' then call terr 'no input' -if _\=='' | arg()\==1 then call terr 'too many arguments: ' arg(1) -if \datatype(x,'N') then call terr x " isn't numeric" -if \datatype(x,'W') then call terr x " isn't an integer" -y=abs(x)/1 /*just in case X is negative, */ - /*(remainder of neg # might be -1)*/ - /*══════════════════════════════════════════════════*/ - say center('test using remainder)method',40,'─') +/*REXX program tests and displays if an integer is even or odd.*/ +!.=0; do j=0 by 2 to 8; !.j=1; end /*assign 0,2,4,6,8 to a "true" value.*/ + /* [↑] assigns even digits to "true".*/ +numeric digits 1000 /*handle most huge numbers from the CL.*/ +parse arg x _ . /*get an argument from the command line*/ +if x=='' then call terr "no input integer." /*error.*/ +if _\=='' | arg()\==1 then call terr "too many arguments: " _ arg(2) /*error.*/ +if \datatype(x,'N') then call terr x " isn't numeric." /*error.*/ +if \datatype(x,'W') then call terr x " isn't an integer." /*error.*/ +y=abs(x)/1 /*in case X is negative or malformed,*/ + /* [↑] remainder of neg # might be -1.*/ + /*malformed #s: 007 9.0 4.8e1 .21e2 */ + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'remainder method (oddness)' if y//2 then say x 'is odd' else say x 'is even' - /*══════════════════════════════════════════════════*/ -say; say center('test rightmost digit for evenness',40,'─') + /* [↑] uses division to get remainder.*/ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'rightmost digit using BIF (not evenness)' _=right(y,1) -if pos(_,02468)==0 then say x 'is odd' - else say x 'is even' - /*══════════════════════════════════════════════════*/ -say; say center('test rightmost digit for oddness',40,'─') -if pos(right(y,1),13579)==0 then say x 'is even' - else say x 'is odd' - /*══════════════════════════════════════════════════*/ -say; say center('test rightmost (binary) bit',40,'─') -if right(x2b(d2x(y)),1) then say x 'is odd' - else say x 'is even' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────TERR subroutine─────────────────────*/ -terr: say; say '***error!***'; say; say arg(1); say; exit 13 +if pos(_,86420)==0 then say x 'is odd' + else say x 'is even' + /* [↑] uses 2 BIF (built─in functions)*/ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'rightmost digit using BIF (evenness)' +_=right(y,1) +if pos(_,86420)\==0 then say x 'is even' + else say x 'is odd' + /* [↑] uses 2 BIF (built─in functions)*/ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'even rightmost digit using array (evenness)' +_=right(y,1) +if !._ then say x 'is even' + else say x 'is odd' + /* [↑] uses a BIF (built─in function).*/ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'remainder of division via function invoke (evenness)' +if even(y) then say x 'is even' + else say x 'is odd' + /* [↑] uses (even) function invocation*/ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'remainder of division via function invoke (oddness)' +if odd(y) then say x 'is odd' + else say x 'is even' + /* [↑] uses (odd) function invocation*/ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'rightmost digit using BIF (not oddness)' +_=right(y,1) +if pos(_,13579)==0 then say x 'is even' + else say x 'is odd' + /* [↑] uses 2 BIF (built─in functions)*/ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'rightmost (binary) bit (oddness)' +if right(x2b(d2x(y)),1) then say x 'is odd' + else say x 'is even' + /* [↑] requires extra numeric digits. */ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'parse statement using BIF (not oddness)' +parse var y '' -1 _ /*obtain last decimal digit of the Y #.*/ +if pos(_,02468)==0 then say x 'is odd' + else say x 'is even' + /* [↑] uses a BIF (built─in function).*/ + + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +call sayr 'parse statement using array (evenness)' +parse var y '' -1 _ /*obtain last decimal digit of the Y #.*/ +if !._ then say x 'is even' + else say x 'is odd' + /* [↑] this is the fastest algorithm. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ +even: return \ ( arg(1)//2 ) /*actual algorithm used can be varied. */ +even: return arg(1)//2 == 0 /* " " " " " " */ +even: parse arg '' -1 _; return !._ /* " " " " " " */ +odd: return arg(1)//2 /* " " " " " " */ +sayr: say; say center('using the' arg(1), 79, '═'); return +terr: say; say '***error!***'; say; say arg(1); say; exit 13 diff --git a/Task/Even-or-odd/Rust/even-or-odd-1.rust b/Task/Even-or-odd/Rust/even-or-odd-1.rust index 4668146ced..b7b0ad75b4 100644 --- a/Task/Even-or-odd/Rust/even-or-odd-1.rust +++ b/Task/Even-or-odd/Rust/even-or-odd-1.rust @@ -1,2 +1,2 @@ -let isodd = |x: int| x & 1 == 1; -let iseven = |x: int| x & 1 == 0; +let is_odd = |x: i32| x & 1 == 1; +let is_even = |x: i32| x & 1 == 0; diff --git a/Task/Even-or-odd/Rust/even-or-odd-2.rust b/Task/Even-or-odd/Rust/even-or-odd-2.rust index ffd0ef47b2..228d6bed02 100644 --- a/Task/Even-or-odd/Rust/even-or-odd-2.rust +++ b/Task/Even-or-odd/Rust/even-or-odd-2.rust @@ -1,2 +1,2 @@ -let isodd = |x: int| x % 2 == 1; -let iseven = |x: int| x % 2 == 0; +let is_odd = |x: i32| x % 2 != 0; +let is_even = |x: i32| x % 2 == 0; diff --git a/Task/Even-or-odd/TI-83-BASIC/even-or-odd.ti-83 b/Task/Even-or-odd/TI-83-BASIC/even-or-odd.ti-83 new file mode 100644 index 0000000000..918776c9d2 --- /dev/null +++ b/Task/Even-or-odd/TI-83-BASIC/even-or-odd.ti-83 @@ -0,0 +1,6 @@ +If fPart(.5Ans +Then +Disp "ODD +Else +Disp "EVEN +End diff --git a/Task/Even-or-odd/VBScript/even-or-odd.vb b/Task/Even-or-odd/VBScript/even-or-odd.vb new file mode 100644 index 0000000000..0fbd1489fd --- /dev/null +++ b/Task/Even-or-odd/VBScript/even-or-odd.vb @@ -0,0 +1,12 @@ +Function odd_or_even(n) + If n Mod 2 = 0 Then + odd_or_even = "Even" + Else + odd_or_even = "Odd" + End If +End Function + +WScript.StdOut.Write "Please enter a number: " +n = WScript.StdIn.ReadLine +WScript.StdOut.Write n & " is " & odd_or_even(CInt(n)) +WScript.StdOut.WriteLine diff --git a/Task/Events/Elixir/events.elixir b/Task/Events/Elixir/events.elixir new file mode 100644 index 0000000000..e4f3711332 --- /dev/null +++ b/Task/Events/Elixir/events.elixir @@ -0,0 +1,26 @@ +defmodule Events do + def log(msg) do + {h,m,s} = :erlang.time + :io.fwrite("~2.B:~2.B:~2.B => ~s~n",[h,m,s,msg]) + end + + def task do + log("Task start") + receive do + :go -> :ok + end + log("Task resumed") + end + + def main do + log("Program start") + pid = spawn(Events,:task,[]) + log("Program sleeping") + :timer.sleep(1000) + log("Program signalling event") + send(pid, :go) + :timer.sleep(100) + end +end + +Events.main diff --git a/Task/Evolutionary-algorithm/00DESCRIPTION b/Task/Evolutionary-algorithm/00DESCRIPTION index d0672513eb..42bb6475c8 100644 --- a/Task/Evolutionary-algorithm/00DESCRIPTION +++ b/Task/Evolutionary-algorithm/00DESCRIPTION @@ -11,3 +11,25 @@ Starting with: Cf: [[wp:Weasel_program#Weasel_algorithm|Weasel algorithm]] and [[wp:Evolutionary algorithm|Evolutionary algorithm]] Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions + +=========== +A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, +* While the parent is not yet the target: +:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. + +Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" + + (:* repeat until the parent converges, (hopefully), to the target. + +Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! + +As illustration of this error, the code for 8th has the following remark. + + Create a new string based on the TOS, '''changing randomly any characters which + don't already match the target''': + +''NOTE:'' this has been changed, the 8th version is completely random now + +Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! + +To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent. diff --git a/Task/Evolutionary-algorithm/AWK/evolutionary-algorithm.awk b/Task/Evolutionary-algorithm/AWK/evolutionary-algorithm.awk new file mode 100644 index 0000000000..6946d6958d --- /dev/null +++ b/Task/Evolutionary-algorithm/AWK/evolutionary-algorithm.awk @@ -0,0 +1,62 @@ +#!/bin/awk -f +function randchar(){ +return substr(charset,randint(length(charset)+1),1) +} +function mutate(gene,rate ,l,newgene){ +newgene = "" +for (l=1; l < 1+length(gene); l++){ +if (rand() < rate) + newgene = newgene randchar() +else + newgene = newgene substr(gene,l,1) +} +return newgene +} +function fitness(gene,target ,k,fit){ +fit = 0 +for (k=1;k<1+length(gene);k++){ +if (substr(gene,k,1) == substr(target,k,1)) fit = fit + 1 +} +return fit +} +function randint(n){ +return int(n * rand()) +} +function evolve(){ + maxfit = fitness(parent,target) + oldfit = maxfit + maxj = 0 + for (j=1; j < D; j++){ + child[j] = mutate(parent,mutrate) + fit[j] = fitness(child[j],target) + if (fit[j] > maxfit) { + maxfit = fit[j] + maxj = j + } + } + if (maxfit > oldfit) parent = child[maxj] + } + +BEGIN{ +target = "METHINKS IT IS LIKE A WEASEL" +charset = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" +mutrate = 0.10 +if (ARGC > 1) mutrate = ARGV[1] +lenset = length(charset) +C = 100 +D = C + 1 +parent = "" +for (j=1; j < length(target)+1; j++) { + parent = parent randchar() + } +print "target: " target +print "fitness of target: " fitness(target,target) +print "initial parent: " parent +gens = 0 +while (parent != target){ + evolve() + gens = gens + 1 + if (gens % 10 == 0) print "after " gens " generations,","new parent: " parent," with fitness: " fitness(parent,target) + } +print "after " gens " generations,"," evolved parent: " parent +} diff --git a/Task/Evolutionary-algorithm/C++/evolutionary-algorithm.cpp b/Task/Evolutionary-algorithm/C++/evolutionary-algorithm.cpp index 064eb7329f..5a7e7eaf61 100644 --- a/Task/Evolutionary-algorithm/C++/evolutionary-algorithm.cpp +++ b/Task/Evolutionary-algorithm/C++/evolutionary-algorithm.cpp @@ -4,6 +4,7 @@ #include #include #include +#include std::string allowed_chars = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"; diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-1.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-1.elixir new file mode 100644 index 0000000000..92eec62082 --- /dev/null +++ b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-1.elixir @@ -0,0 +1,15 @@ +defmodule Rand do + def init do # Initialize the random values. + << a :: 32, b :: 32, c :: 32 >> = :crypto.strong_rand_bytes(12) + :random.seed(a,b,c) + end + + def num do # Returns a value between 0.0 and 1.0. + init + :random.uniform + end + + def char(list) do # Returns a random letter or a space. + Enum.at(list, :random.uniform(length(list)) - 1) + end +end diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-2.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-2.elixir new file mode 100644 index 0000000000..91adc351c1 --- /dev/null +++ b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-2.elixir @@ -0,0 +1,9 @@ +defmodule Log do + def show(offspring,i) do + IO.puts "Generation: #{i}, Offspring: #{offspring}" + end + + def found([target|i]) do + IO.puts "#{target} found in #{i} iterations" + end +end diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-3.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-3.elixir new file mode 100644 index 0000000000..e0e70e9698 --- /dev/null +++ b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-3.elixir @@ -0,0 +1,57 @@ +defmodule Evolution do + def select(target) do + # Generate char list from A to Z; 32 is the ord value for space. + chars = (?A..?Z) |> Enum.to_list() |> List.insert_at(0, 32) + + (1..String.length(target)) # Creates parent for generation 0. + |> Enum.map(fn _-> Rand.char(chars) end) + |> mutate(String.to_char_list(target),0,[],chars) + |> Log.found() + end + + # w is used to denote fitness in population genetics. + + def mutate(parent,target,i,_,_) when target == parent, do: [parent|i] + def mutate(parent,target,i,_,chars) when target != parent do + w = fitness(parent,target) + prev = reproduce(target,parent,w,0,mu_rate(w),chars) + + # Check if the most fit member of the new gen has a greater fitness than the parent. + if w < fitness(prev,target) do + parent = prev + Log.show(parent,i) + end + mutate(parent,target,i+1,prev,chars) + end + + # Generate 100 offspring and select the one with the greatest fitness. + + def reproduce(target,parent,_,_,rate,chars) do + (1..100) + |> Enum.to_list() + |> Stream.map(fn _-> mutation(parent,rate,chars) end) + |> List.insert_at(0, parent) + |> Enum.max_by(fn n -> fitness(n,target) end) + end + + # Calculate fitness by checking difference between parent and offspring chars. + + def fitness(t,r) do + (0..length(t)-1) + |> Stream.map(fn n -> abs(Enum.at(t,n) - Enum.at(r,n)) end) + |> Enum.reduce(fn a,b -> a + b end) + |> calc() + end + + # Generate offspring based on parent. + + def mutation(p,r,chars) do + # Copy the parent chars, then check each val against the random mutation rate + (0..length(p)-1) + |> Stream.map(fn n -> Enum.at(p,n) end) + |> Enum.map(fn n -> if Rand.num <= r, do: Rand.char(chars), else: n end) + end + + def calc(sum), do: 100 * :math.exp(sum/-10) + def mu_rate(n), do: 1 - :math.exp(-(100-n)/400) +end diff --git a/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-4.elixir b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-4.elixir new file mode 100644 index 0000000000..5c9e247529 --- /dev/null +++ b/Task/Evolutionary-algorithm/Elixir/evolutionary-algorithm-4.elixir @@ -0,0 +1 @@ +Evolution.select("METHINKS IT IS LIKE A WEASEL") diff --git a/Task/Evolutionary-algorithm/MATLAB/evolutionary-algorithm-3.m b/Task/Evolutionary-algorithm/MATLAB/evolutionary-algorithm-3.m new file mode 100644 index 0000000000..a3f1813275 --- /dev/null +++ b/Task/Evolutionary-algorithm/MATLAB/evolutionary-algorithm-3.m @@ -0,0 +1,110 @@ +%% Genetic Algorithm -- Solves For A User Input String + +% #### PLEASE NOTE: you can change the selection and crossover type in the +% parameters and see how the algorithm changes. #### + +clear;close all;clc; %Clears variables, closes windows, and clears the command window +tic % Begins the timer + +%% Select Target String +target = 'METHINKS IT IS LIKE A WEASEL'; +% *Can Be Any String With Any Values and Any Length!* +% but for this example we use 'METHINKS IT IS LIKE A WEASEL' + +%% Parameters +popSize = 1000; % Population Size (100-10000 generally produce good results) +genome = length(target); % Genome Size +mutRate = .01; % Mutation Rate (5%-25% produce good results) +S = 4; % Tournament Size (2-6 produce good results) +best = Inf; % Initialize Best (arbitrarily large) +MaxVal = max(double(target)); % Max Integer Value Needed +ideal = double(target); % Convert Target to Integers + +selection = 0; % 0: Tournament + % 1: 50% Truncation + +crossover = 1; % 0: Uniform crossover + % 1: 1 point crossover + % 2: 2 point crossover +%% Initialize Population +Pop = round(rand(popSize,genome)*(MaxVal-1)+1); % Creates Population With Corrected Genome Length + +for Gen = 1:1e6 % A Very Large Number Was Chosen, But Shouldn't Be Needed + + %% Fitness + + % The fitness function starts by converting the characters into integers and then + % subtracting each element of each member of the population from each element of + % the target string. The function then takes the absolute value of + % the differences and sums each row and stores the function as a mx1 matrix. + + F = sum(abs(bsxfun(@minus,Pop,ideal)),2); + + + + % Finding Best Members for Score Keeping and Printing Reasons + [current,currentGenome] = min(F); % current is the minimum value of the fitness array F + % currentGenome is the index of that value in the F array + + % Stores New Best Values and Prints New Best Scores + if current < best + best = current; + bestGenome = Pop(currentGenome,:); % Uses that index to find best value + + fprintf('Gen: %d | Fitness: %d | ',Gen, best); % Formatted printing of generation and fitness + disp(char(bestGenome)); % Best genome so far + elseif best == 0 + break % Stops program when we are done + end + + %% Selection + + % TOURNAMENT + if selection == 0 + T = round(rand(2*popSize,S)*(popSize-1)+1); % Tournaments + [~,idx] = min(F(T),[],2); % Index to Determine Winners + W = T(sub2ind(size(T),(1:2*popSize)',idx)); % Winners + + % 50% TRUNCATION + elseif selection == 1 + [~,V] = sort(F,'descend'); % Sort Fitness in Ascending Order + V = V(popSize/2+1:end); % Winner Pool + W = V(round(rand(2*popSize,1)*(popSize/2-1)+1))'; % Winners + end + + %% Crossover + + % UNIFORM CROSSOVER + if crossover == 0 + idx = logical(round(rand(size(Pop)))); % Index of Genome from Winner 2 + Pop2 = Pop(W(1:2:end),:); % Set Pop2 = Pop Winners 1 + P2A = Pop(W(2:2:end),:); % Assemble Pop2 Winners 2 + Pop2(idx) = P2A(idx); % Combine Winners 1 and 2 + + % 1-POINT CROSSOVER + elseif crossover == 1 + Pop2 = Pop(W(1:2:end),:); % New Population From Pop 1 Winners + P2A = Pop(W(2:2:end),:); % Assemble the New Population + Ref = ones(popSize,1)*(1:genome); % The Reference Matrix + idx = (round(rand(popSize,1)*(genome-1)+1)*ones(1,genome))>Ref; % Logical Indexing + Pop2(idx) = P2A(idx); % Recombine Both Parts of Winners + + % 2-POINT CROSSOVER + elseif crossover == 2 + Pop2 = Pop(W(1:2:end),:); % New Pop is Winners of old Pop + P2A = Pop(W(2:2:end),:); % Assemble Pop2 Winners 2 + Ref = ones(popSize,1)*(1:genome); % Ones Matrix + CP = sort(round(rand(popSize,2)*(genome-1)+1),2); % Crossover Points + idx = CP(:,1)*ones(1,genome)Ref; % Index + Pop2(idx)=P2A(idx); % Recombine Winners + end + %% Mutation + idx = rand(size(Pop2))9�JU#(E�UO�PHI +Gen: 2 | Fitness: 429 | W=P6>D�I)VU6$T 99,� B�BMP0JH +Gen: 3 | Fitness: 366 | P�;R08AS�GJ�IS&T38IE�)SJERLJ +Gen: 4 | Fitness: 322 | KI8M5LAS�GJ�IS�SP�@)D�V@ +JCP +Gen: 5 | Fitness: 295 | UAUR08AS�GJ�IS�8HG*�+�=C?UB( +Gen: 6 | Fitness: 259 | VCUQH35S�HR4.L�ISJQ%J�OC*T=E +Gen: 7 | Fitness: 226 | LFB8GPET(LODKQ�KQBQGF +Gen: 9 | Fitness: 159 | N8R7?SOU�NO$OK O?K?!;�MB?QHG +Gen: 10 | Fitness: 146 | TGN@EQR4)PS%IS#TFJQ%A!U>BVLI +Gen: 11 | Fitness: 120 | L?VMALJS%?R EK IILE�6'RRERLJ +Gen: 12 | Fitness: 102 | R@T9COMR�NU CS*R?K?!; VD>LCL +Gen: 13 | Fitness: 96 | NENMVOMR�NU CS*R?K?!; VD>LCL +Gen: 14 | Fitness: 82 | REJGNPMU�KR CS JKI@+D�UD?QHG +Gen: 15 | Fitness: 75 | NETI=HPQ�FT ID EFKE D"WD>QDQ +Gen: 16 | Fitness: 70 | R@TKCOOT)@R$IS KKLE�D"WC?UBJ +Gen: 17 | Fitness: 61 | NESIKQRP�NU CS�MFKE ; SEETCP +Gen: 18 | Fitness: 57 | LFSGLPTN�NU GQ IIKE D"VD>LCL +Gen: 19 | Fitness: 40 | NENKJLMS�GS%IS#MFKE B UFATCL +Gen: 21 | Fitness: 39 | NETIGPEU�KR IS IIKD"? UFDQEK +Gen: 22 | Fitness: 33 | NETGCOMT�LU IS#MFKE B UFATCL +Gen: 23 | Fitness: 32 | NETIKNPQ�NU IS#IIKE B UFATCL +Gen: 24 | Fitness: 27 | NETKJLMS�LU IS MFKE B UFATCL +Gen: 25 | Fitness: 23 | LETIKOMS LU IS IIKE D WEDQEK +Gen: 26 | Fitness: 22 | NETIKMJS LU IS IIKE D WEDQEK +Gen: 27 | Fitness: 20 | LETIKOMS LU IS KILE B"WFATCL +Gen: 28 | Fitness: 19 | NESGJQJS�GU IS KIKE B WFATEK +Gen: 29 | Fitness: 16 | NETIHPMS KR IS KIKE B WFATEK +Gen: 30 | Fitness: 15 | NESHLPKS KU IS KIKE B WFATEK +Gen: 31 | Fitness: 13 | NETGGNKS KU IS KIKE C WFATEK +Gen: 32 | Fitness: 12 | NETHGNJS IU IS JIKE B WFATCL +Gen: 33 | Fitness: 11 | NETIJPKS IU IS KIKE B WFATEK +Gen: 35 | Fitness: 8 | LEUIHNJS IT IS JIKE A WEATEL +Gen: 37 | Fitness: 7 | NETIHNJS IS IS LIKE B WFASEL +Gen: 38 | Fitness: 6 | NETHGNJS IT IS LIKE A WFASEK +Gen: 39 | Fitness: 4 | METGHNKS IT IS LIKE B WEATEL +Gen: 42 | Fitness: 3 | NETHINKS IT IS KIKE B WEASEL +Gen: 43 | Fitness: 2 | NETHINKS IT IS LIKE A WFASEL +Gen: 44 | Fitness: 1 | METHHNKS IT IS LIKE A WEASEL +Gen: 46 | Fitness: 0 | METHINKS IT IS LIKE A WEASEL +Elapsed time is 0.099618 seconds. diff --git a/Task/Evolutionary-algorithm/Pascal/evolutionary-algorithm.pascal b/Task/Evolutionary-algorithm/Pascal/evolutionary-algorithm.pascal new file mode 100644 index 0000000000..97f638a700 --- /dev/null +++ b/Task/Evolutionary-algorithm/Pascal/evolutionary-algorithm.pascal @@ -0,0 +1,108 @@ +PROGRAM EVOLUTION (OUTPUT); + +CONST + TARGET = 'METHINKS IT IS LIKE A WEASEL'; + COPIES = 100; (* 100 children in each generation. *) + RATE = 1000; (* About one character in 1000 will be a mutation. *) + +TYPE + STRLIST = ARRAY [1..COPIES] OF STRING; + +FUNCTION RANDCHAR : CHAR; + (* Generate a random letter or space. *) + VAR RANDNUM : INTEGER; + BEGIN + RANDNUM := RANDOM(27); + IF RANDNUM = 26 THEN + RANDCHAR := ' ' + ELSE + RANDCHAR := CHR(RANDNUM + ORD('A')) + END; + +FUNCTION RANDSTR (SIZE : INTEGER) : STRING; + (* Generate a random string. *) + VAR + N : INTEGER; + S : STRING; + BEGIN + S := ''; + FOR N := 1 TO SIZE DO + INSERT(RANDCHAR, S, 1); + RANDSTR := S + END; + +FUNCTION FITNESS (CANDIDATE, GOAL : STRING) : INTEGER; + (* Count the number of correct letters in the correct places *) + VAR N, MATCHES : INTEGER; + BEGIN + MATCHES := 0; + FOR N := 1 TO LENGTH(GOAL) DO + IF CANDIDATE[N] = GOAL[N] THEN + MATCHES := MATCHES + 1; + FITNESS := MATCHES + END; + +FUNCTION MUTATE (RATE : INTEGER; S : STRING) : STRING; + (* Randomly alter a string. Characters change with probability 1/RATE. *) + VAR + N : INTEGER; + CHANGE : BOOLEAN; + BEGIN + FOR N := 1 TO LENGTH(TARGET) DO + BEGIN + CHANGE := RANDOM(RATE) = 0; + IF CHANGE THEN + S[N] := RANDCHAR + END; + MUTATE := S + END; + +PROCEDURE REPRODUCE (RATE : INTEGER; PARENT : STRING; VAR CHILDREN : STRLIST); + (* Generate children with random mutations. *) + VAR N : INTEGER; + BEGIN + FOR N := 1 TO COPIES DO + CHILDREN[N] := MUTATE(RATE, PARENT) + END; + +FUNCTION FITTEST(CHILDREN : STRLIST; GOAL : STRING) : STRING; + (* Measure the fitness of each child and return the fittest. *) + (* If multiple children equally match the target, then return the first. *) + VAR + MATCHES, MOST_MATCHES, BEST_INDEX, N : INTEGER; + BEGIN + MOST_MATCHES := 0; + BEST_INDEX := 1; + FOR N := 1 TO COPIES DO + BEGIN + MATCHES := FITNESS(CHILDREN[N], GOAL); + IF MATCHES > MOST_MATCHES THEN + BEGIN + MOST_MATCHES := MATCHES; + BEST_INDEX := N + END + END; + FITTEST := CHILDREN[BEST_INDEX] + END; + +VAR + PARENT, BEST_CHILD : STRING; + CHILDREN : STRLIST; + GENERATIONS : INTEGER; + +BEGIN + RANDOMIZE; + GENERATIONS := 0; + PARENT := RANDSTR(LENGTH(TARGET)); + WHILE NOT (PARENT = TARGET) DO + BEGIN + IF (GENERATIONS MOD 100) = 0 THEN WRITELN(PARENT); + GENERATIONS := GENERATIONS + 1; + REPRODUCE(RATE, PARENT, CHILDREN); + BEST_CHILD := FITTEST(CHILDREN, TARGET); + IF FITNESS(PARENT, TARGET) < FITNESS(BEST_CHILD, TARGET) THEN + PARENT := BEST_CHILD + END; + WRITE('The string was matched in '); + WRITELN(GENERATIONS, ' generations.') +END. diff --git a/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 b/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 index 47446132e3..26e3679218 100644 --- a/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 +++ b/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 @@ -1,6 +1,6 @@ constant target = "METHINKS IT IS LIKE A WEASEL"; constant mutate_chance = .08; -constant alphabet = 'A'..'Z',' '; +constant alphabet = flat 'A'..'Z',' '; constant C = 100; sub mutate { $^string.comb.map({ rand < mutate_chance ?? alphabet.pick !! $_ }).join } diff --git a/Task/Evolutionary-algorithm/Python/evolutionary-algorithm-1.py b/Task/Evolutionary-algorithm/Python/evolutionary-algorithm-1.py index e2502eb9c4..86e06afd34 100644 --- a/Task/Evolutionary-algorithm/Python/evolutionary-algorithm-1.py +++ b/Task/Evolutionary-algorithm/Python/evolutionary-algorithm-1.py @@ -1,13 +1,14 @@ -from string import ascii_uppercase +from string import letters from random import choice, random target = list("METHINKS IT IS LIKE A WEASEL") -charset = ascii_uppercase + ' ' +charset = letters + ' ' parent = [choice(charset) for _ in range(len(target))] minmutaterate = .09 C = range(100) perfectfitness = float(len(target)) + def fitness(trial): 'Sum of matching chars by position' return sum(t==h for t,h in zip(trial, target)) @@ -24,12 +25,23 @@ def que(): print ("#%-4i, fitness: %4.1f%%, '%s'" % (iterations, fitness(parent)*100./perfectfitness, ''.join(parent))) +def mate(a, b): + place = 0 + if choice(xrange(10)) < 7: + place = choice(xrange(len(target))) + else: + return a, b + + return a, b, a[:place] + b[place:], b[:place] + a[place:] + iterations = 0 +center = len(C)/2 while parent != target: - rate = mutaterate() + rate = mutaterate() iterations += 1 if iterations % 100 == 0: que() copies = [ mutate(parent, rate) for _ in C ] + [parent] - parent = max(copies, key=fitness) -print () + parent1 = max(copies[:center], key=fitness) + parent2 = max(copies[center:], key=fitness) + parent = max(mate(parent1, parent2), key=fitness) que() diff --git a/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx b/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx index ed71bb9879..d5d3e7a1d7 100644 --- a/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx +++ b/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-1.rexx @@ -1,35 +1,34 @@ -/*REXX program demonstrates an evolutionary algorithm (using mutation).*/ -parse arg children MR seed . /*get options (maybe) from C.L. */ -if children=='' then children = 10 /*# of children produced each gen*/ -if MR =='' then MR = '4%' /*the char Mutation Rate each gen*/ -if right(MR,1)=='%' then MR=strip(MR,,'%')/100 /*expressed as %? Adjust*/ -if seed\=='' then call random ,,seed /*allow the runs to be repeatable*/ -abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ; Labc=length(abc) -target= 'METHINKS IT IS LIKE A WEASEL' ; Ltar=length(target) -parent= mutate( left('',Ltar), 1) /*gen rand str,same length as tar*/ -say center('target string',Ltar,'─') "children" 'mutationRate' -say target center(children,8) center((MR*100/1)'%',12) ; say -say center('new string',Ltar,'─') "closeness" 'generation' +/*REXX program demonstrates an evolutionary algorithm (by using mutation). */ +parse arg children MR seed . /*get optional arguments from the C.L. */ +if children=='' then children = 10 /*# children produced each generation. */ +if MR =='' then MR = '4%' /*the character Mutation Rate each gen.*/ +if right(MR,1)=='%' then MR=strip(MR,,'%')/100 /*expressed as %? Then adjust*/ +if seed\=='' then call random ,,seed /*SEED allow the runs to be repeatable.*/ +abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ; Labc=length(abc) +target= 'METHINKS IT IS LIKE A WEASEL' ; Ltar=length(target) +parent= mutate( left('',Ltar), 1) /*gen rand string,same length as target*/ +say center('target string',Ltar,'─') "children" 'mutationRate' +say target center(children,8) center((MR*100/1)'%',12); say +say center('new string',Ltar,'─') "closeness" 'generation' - do gen=0 until parent==target; close=fitness(parent) + do gen=0 until parent==target; close=fitness(parent) almost=parent - do children; child=mutate(parent,MR) - _=fitness(child); if _<=close then iterate - close=_; almost=child - say almost right(close,9) right(gen,10) + do children; child=mutate(parent,MR) + _=fitness(child); if _<=close then iterate + close=_; almost=child + say almost right(close,9) right(gen,10) end /*children*/ parent=almost end /*gen*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────FITNESS subroutine─────────────────*/ -fitness: parse arg x; hit=0; do k=1 for Ltar - hit=hit+(substr(x,k,1)==substr(target,k,1)) - end /*k*/ -return hit -/*───────────────────────────────────MUTATE subroutine──────────────────*/ -mutate: parse arg x,rate,? /*set ? to a null, x=string. */ - do j=1 for Ltar; r=random(1,100000) - if .00001*r<=rate then ?=? || substr(abc,r//Labc+1,1) - else ?=? || substr(x,j,1) - end /*j*/ -return ? +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +fitness: parse arg x; $=0 + do k=1 for Ltar; $=$+(substr(x,k,1)==substr(target,k,1)); end /*k*/ + return $ +/*────────────────────────────────────────────────────────────────────────────*/ +mutate: parse arg x,rate $ /*set X to 1st argument, RATE to 2nd.*/ + $=; do j=1 for Ltar; r=random(1,100000) /*REXX's max.*/ + if .00001*r<=rate then $=$ || substr(abc,r//Labc+1,1) + else $=$ || substr(x,j,1) + end /*j*/ + return $ diff --git a/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-2.rexx b/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-2.rexx index d7f21be771..5a3280db32 100644 --- a/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-2.rexx +++ b/Task/Evolutionary-algorithm/REXX/evolutionary-algorithm-2.rexx @@ -1,45 +1,43 @@ -/*REXX program demonstrates an evolutionary algorithm (using mutation).*/ -parse arg children MR seed . /*get options (maybe) from C.L. */ -if children=='' then children = 10 /*# of children produced each gen*/ -if MR =='' then MR = "4%" /*the char Mutation Rate each gen*/ -if right(MR,1)=='%' then MR=strip(MR,,"%")/100 /*expressed as %? Adjust*/ -if seed\=='' then call random ,,seed /*allow the runs to be repeatable*/ -abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ; Labc=length(abc) +/*REXX program demonstrates an evolutionary algorithm (by using mutation). */ +parse arg children MR seed . /*get optional arguments from the C.L. */ +if children=='' then children = 10 /*# children produced each generation. */ +if MR =='' then MR = '4%' /*the character Mutation Rate each gen.*/ +if right(MR,1)=='%' then MR=strip(MR,,'%')/100 /*expressed as %? Then adjust*/ +if seed\=='' then call random ,,seed /*SEED allow the runs to be repeatable.*/ +abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '; Labc=length(abc) - do i=0 for Labc /*define array (faster compare), */ - A.i=substr(abc, i+1, 1) /* it's better than picking out a*/ - end /*i*/ /* byte from a character string. */ + do i=0 for Labc /*define array (for faster compare), */ + @.i=substr(abc,i+1,1) /* it's better than picking out a */ + end /*i*/ /* byte from a character string. */ target= 'METHINKS IT IS LIKE A WEASEL' ; Ltar=length(target) - do i=1 for Ltar /*define array (faster compare), */ - T.i=substr(target, i, 1) /*it's better than a byte-by-byte*/ - end /*i*/ /*compare using character strings*/ + do i=1 for Ltar /*define an array (for faster compare),*/ + T.i=substr(target,i,1) /* it's better than a byte-by-byte */ + end /*i*/ /* compare using character strings.*/ -parent= mutate( left('', Ltar), 1) /*gen rand str,same length as tar*/ -say center('target string', Ltar, '─') "children" 'mutationRate' -say target center(children, 8) center((MR*100/1)'%', 12) ; say -say center('new string', Ltar, '─') "closeness" 'generation' +parent= mutate( left('',Ltar), 1) /*gen rand string, same length as tar. */ +say center('target string',Ltar,'─') "children" 'mutationRate' +say target center(children,8) center((MR*100/1)'%',12); say +say center('new string',Ltar,'─') "closeness" 'generation' - do gen=0 until parent==target; close=fitness(parent) + do gen=0 until parent==target; close=fitness(parent) almost=parent - do children; child=mutate(parent, MR) - _=fitness(child); if _<=close then iterate - close=_; almost=child - say almost right(close, 9) right(gen, 10) + do children; child=mutate(parent,MR) + _=fitness(child); if _<=close then iterate + close=_; almost=child + say almost right(close,9) right(gen,10) end /*children*/ parent=almost end /*gen*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────FITNESS subroutine─────────────────*/ -fitness: parse arg x; hit=0; do k=1 for Ltar - hit=hit + (substr(x,k,1) == T.k) - end /*k*/ -return hit -/*───────────────────────────────────MUTATE subroutine──────────────────*/ -mutate: parse arg x,rate,? /*set ? to a null, x=string. */ - do j=1 for Ltar; r=random(1, 100000) - if .00001*r<=rate then do; _=r//Labc; ?=? || A._; end - else ?=? || substr(x,j,1) - end /*j*/ -return ? +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +fitness: parse arg x; $=0; do k=1 for Ltar; $=$+(substr(x,k,1)==T.k); end + return $ +/*────────────────────────────────────────────────────────────────────────────*/ +mutate: parse arg x,rate /*set X to 1st argument, RATE to 2nd.*/ + $=; do j=1 for Ltar; r=random(1,100000) /*REXX's max.*/ + if .00001*r<=rate then do; _=r//Labc; $=$ || @._; end + else $=$ || substr(x,j,1) + end /*j*/ + return $ diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Clojure/exceptions-catch-an-exception-thrown-in-a-nested-call.clj b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Clojure/exceptions-catch-an-exception-thrown-in-a-nested-call.clj new file mode 100644 index 0000000000..b8b6b06561 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Clojure/exceptions-catch-an-exception-thrown-in-a-nested-call.clj @@ -0,0 +1,17 @@ +(def U0 (ex-info "U0" {})) +(def U1 (ex-info "U1" {})) + +(defn baz [x] (if (= x 0) (throw U0) (throw U1))) +(defn bar [x] (baz x)) + +(defn foo [] + (dotimes [x 2] + (try + (bar x) + (catch clojure.lang.ExceptionInfo e + (if (= e U0) + (println "foo caught U0") + (throw e)))))) + +(defn -main [& args] + (foo)) diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elixir/exceptions-catch-an-exception-thrown-in-a-nested-call.elixir b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elixir/exceptions-catch-an-exception-thrown-in-a-nested-call.elixir new file mode 100644 index 0000000000..91ed6446d9 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elixir/exceptions-catch-an-exception-thrown-in-a-nested-call.elixir @@ -0,0 +1,21 @@ +defmodule U0, do: defexception [:message] +defmodule U1, do: defexception [:message] + +defmodule ExceptionsTest do + def foo do + Enum.each([0,1], fn i -> + try do + bar(i) + rescue + U0 -> IO.puts "U0 rescued" + end + end) + end + + def bar(i), do: baz(i) + + def baz(0), do: raise U0 + def baz(1), do: raise U1 +end + +ExceptionsTest.foo diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call.rb b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call.rb index 56f5163e92..60d31659a5 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call.rb +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call.rb @@ -1,25 +1,23 @@ def foo - begin - bar - rescue U0 - puts "captured exception U0" + 2.times do |i| + begin + bar(i) + rescue U0 + $stderr.puts "captured exception U0" + end end end -def bar - baz +def bar(i) + baz(i) end -def baz - @bazcount = @bazcount.to_i + 1 - raise @bazcount == 1 ? U0 : U1 +def baz(i) + raise i == 0 ? U0 : U1 end -class U0 < StandardError -end +class U0 < StandardError; end -class U1 < StandardError -end +class U1 < StandardError; end foo -foo diff --git a/Task/Exceptions/ALGOL-68/exceptions-1.alg b/Task/Exceptions/ALGOL-68/exceptions-1.alg index 6a9593a778..34c60d4954 100644 --- a/Task/Exceptions/ALGOL-68/exceptions-1.alg +++ b/Task/Exceptions/ALGOL-68/exceptions-1.alg @@ -1,9 +1,119 @@ -# a user defined object # -MODE FOO = STRUCT ( ... ) - FOOOBJECTNEW = STRUCT (FOOMEND foo exception x mended, FOO instance), - FOOOBJECT = REF FOOOBJECTNEW, - FOOMEND = PROC (FOOOBJECT)BOOL; +COMMENT + Define an general event handling mechanism on MODE OBJ: + * try to parallel pythons exception handling flexibility +END COMMENT -PROC on foo exception x = (FOOOBJECT foo, PROC (FOOOBJECT)BOOL foo exception x mend)VOID: ( - foo exception x mended OF foo := foo exception x mend +COMMENT + REQUIRES: + MODE OBJ # These can be a UNION of REF types # + OP OBJIS + PROVIDES: + OP ON, RAISE, RESET + PROC obj on, obj raise, obj reset +END COMMENT + +# define object related to OBJ EVENTS # +MODE + RAISEOBJ = PROC(OBJ)VOID, RAWMENDOBJ = PROC(OBJ)BOOL, + MENDOBJ = UNION(RAWMENDOBJ, PROC VOID), # Generalise: Allow PROC VOID (a GOTO) as a short hand # + NEWSCOPEOBJ = STRUCT(REF NEWSCOPEOBJ up, FLEXOBJ obj flex, FLEXEVENTOBJ event flex, MENDOBJ mended), + SCOPEOBJ = REF NEWSCOPEOBJ; + +MODE FLEXOBJ=FLEX[0]OBJ; + +# Provide an INIT to convert a GO TO to a MEND ... useful for direct aborts # +OP INITMENDOBJ = (PROC VOID go to)MENDOBJ: (go to; SKIP); + +SCOPEOBJ obj scope end = NIL; +SCOPEOBJ obj scope begin := obj scope end; # INITialise stack # +OBJ obj any = EMPTY; +EVENTOBJ obj event any = NIL; + +# Some crude Singly Linked-List manipulations of the scopes, aka stack ... # +# An event/mended can be shared for all OBJ of the same type: # +PRIO INITAB = 1, +=: = 1; +OP INITAB = (SCOPEOBJ lhs, MENDOBJ obj mend)SCOPEOBJ: + lhs := (obj scope end, obj any, obj event any, obj mend); + +OP INITSCOPE = (MENDOBJ obj mend)SCOPEOBJ: HEAP NEWSCOPEOBJ INITAB obj mend; +OP +=: = (SCOPEOBJ item, REF SCOPEOBJ rhs)SCOPEOBJ: ( up OF item := rhs; rhs := item ); +OP +=: = (MENDOBJ mend, REF SCOPEOBJ rhs)SCOPEOBJ: INITSCOPE mend +=: rhs; +#OP -=: = (REF SCOPEOBJ scope)SCOPEOBJ: scope := up OF scope;# + +COMMENT Restore the prio event scope: ~ END COMMENT +PROC obj reset = (SCOPEOBJ up scope)VOID: obj scope begin := up scope; +MENDOBJ obj unmendable = (OBJ obj)BOOL: FALSE; + +MODE NEWEVENTOBJ = STRUCT( # the is simple a typed place holder # + SCOPEOBJ scope, + STRING description, + PROC (OBJ #obj#, MENDOBJ #obj mend#)SCOPEOBJ on, + PROC (OBJ #obj#, STRING #msg#)VOID raise +), EVENTOBJ = REF NEWEVENTOBJ; + +MODE FLEXEVENTOBJ = FLEX[0]EVENTOBJ; + +COMMENT Define how to catch an event: + obj - IF obj IS NIL then mend event on all OBJects + obj mend - PROC to call to repair the object + return the prior event scope +END COMMENT +PROC obj on = (FLEXOBJ obj flex, FLEXEVENTOBJ event flex, MENDOBJ mend)SCOPEOBJ: ( + mend +=: obj scope begin; + IF obj any ISNTIN obj flex THEN obj flex OF obj scope begin := obj flex FI; + IF obj event any ISNTIN event flex THEN event flex OF obj scope begin := event flex FI; + up OF obj scope begin ); + +PRIO OBJIS = 4, OBJISNT = 4; # pick the same PRIOrity as EQ and NE # +OP OBJISNT = (OBJ a,b)BOOL: NOT(a OBJIS b); + +PRIO ISIN = 4, ISNTIN = 4; +OP ISNTIN = (OBJ obj, FLEXOBJ obj flex)BOOL: ( + BOOL isnt in := FALSE; + FOR i TO UPB obj flex WHILE isnt in := obj OBJISNT obj flex[i] DO SKIP OD; + isnt in +); +OP ISIN = (OBJ obj, FLEXOBJ obj flex)BOOL: NOT(obj ISNTIN obj flex); + +OP ISNTIN = (EVENTOBJ event, FLEXEVENTOBJ event flex)BOOL: ( + BOOL isnt in := TRUE; + FOR i TO UPB event flex WHILE isnt in := event ISNT event flex[i] DO SKIP OD; + isnt in +); +OP ISIN = (EVENTOBJ event, FLEXEVENTOBJ event flex)BOOL: NOT(event ISNTIN event flex); + +COMMENT Define how to raise an event, once it is raised try and mend it: + if all else fails produce an error message and stop +END COMMENT +PROC obj raise = (OBJ obj, EVENTOBJ event, STRING msg)VOID:( + SCOPEOBJ this scope := obj scope begin; +# until mended this event should cascade through scope event handlers/members # + FOR i WHILE this scope ISNT SCOPEOBJ(obj scope end) DO + IF (obj any ISIN obj flex OF this scope OR obj ISIN obj flex OF this scope ) AND + (obj event any ISIN event flex OF this scope OR event ISIN event flex OF this scope) + THEN + CASE mended OF this scope IN + (RAWMENDOBJ mend):IF mend(obj) THEN break mended FI, + (PROC VOID go to): (go to; stop) + OUT put(stand error, "undefined: raise stop"); stop + ESAC + FI; + this scope := up OF this scope + OD; + put(stand error, ("OBJ event: ",msg)); stop; FALSE +EXIT + break mended: TRUE +); + +CO define ON and some useful(?) RAISE OPs CO +PRIO ON = 1, RAISE = 1; +OP ON = (MENDOBJ mend, EVENTOBJ event)SCOPEOBJ: obj on(obj any, event, mend), + RAISE = (OBJ obj, EVENTOBJ event)VOID: obj raise(obj, event, "unnamed event"), + RAISE = (OBJ obj, MENDOBJ mend)VOID: ( mend ON obj event any; obj RAISE obj event any), + RAISE = (EVENTOBJ event)VOID: obj raise(obj any, event, "unnamed event"), + RAISE = (MENDOBJ mend)VOID: ( mend ON obj event any; RAISE obj event any), + RAISE = (STRING msg, EVENTOBJ event)VOID: obj raise(obj any, event, msg); +OP (SCOPEOBJ #up scope#)VOID RESET = obj reset; + +SKIP diff --git a/Task/Exceptions/ALGOL-68/exceptions-2.alg b/Task/Exceptions/ALGOL-68/exceptions-2.alg index db1870bcc2..fad33e7c68 100644 --- a/Task/Exceptions/ALGOL-68/exceptions-2.alg +++ b/Task/Exceptions/ALGOL-68/exceptions-2.alg @@ -1,4 +1,48 @@ -PROC raise foo exception x = (FOOOBJECT foo)BOOL: - IF NOT (foo exception x mended OF foo instance)(foo instance) THEN - except foo exception x - FI +#!/usr/bin/a68g --script # + +MODE OBJ=UNION(REF INT, REF REAL, REF STRING,# etc # VOID); + +OP OBJIS = (OBJ a,b)BOOL: # Are a and b at the same address? # + CASE a IN # Ironically Algol68's STRONG typing means we cannot simply compare addresses # + (REF INT a): a IS (b|(REF INT b):b|NIL), + (REF REAL a): a IS (b|(REF REAL b):b|NIL), + (REF STRING a): a IS (b|(REF STRING b):b|NIL) + OUT FALSE + ESAC; + +PR READ "prelude/event_base(obj).a68" PR; +NEWEVENTOBJ obj eventa := SKIP; +NEWEVENTOBJ obj eventb := SKIP; +NEWEVENTOBJ user defined exception := SKIP; + +# An event can be continued "mended" or break "unmended" # +PROC found sum sqs continue = (OBJ obj)BOOL: ( print("."); TRUE); # mended # +PROC found sum sqs break = (OBJ obj)BOOL: (found sq sum sqs; FALSE); # unmended # + +INT sum sqs:=0; +REAL x:=111, y:=222, z:=333; + +SCOPEOBJ obj scope reset := obj on((sum sqs, x,y,z), (obj eventa,obj eventb), VOID:found sq sum sqs); + +# An event handler specific to the specific object instance: # +#SCOPEOBJ obj scope reset := obj on eventb(sum sqs, VOID:found sq sum sqs);# + +# Or... An "obj any" event handler: # +# SCOPEOBJ obj scope reset := found sum sqs break ON obj eventb; # + +# Raise the "event eventb" on an object: # + FOR i DO + sum sqs +:= i*i; + IF sum sqs = 70*70 THEN # 1st try to use an instance specific mend on the object # + obj raise(sum sqs, obj eventb, "Found a sq sum of sqs") FI; # OR ... # + IF sum sqs = 70*70 THEN "Found a sq sum of sqs" RAISE obj eventb FI; # OR ... # + IF sum sqs = 70*70 THEN RAISE found sum sqs break FI # simplest # + OD; + RESET obj scope reset # need to manually reset back to prior handlers # + +# Catch "event eventb": # +EXIT found sq sum sqs: + print(("sum sqs:",sum sqs, new line)); # event eventb caught code here ... # + RESET obj scope reset; + + "finally: raise the base unmendable event" RAISE obj eventb diff --git a/Task/Exceptions/Bracmat/exceptions.bracmat b/Task/Exceptions/Bracmat/exceptions.bracmat new file mode 100644 index 0000000000..17ce3453ba --- /dev/null +++ b/Task/Exceptions/Bracmat/exceptions.bracmat @@ -0,0 +1,17 @@ +( ( MyFunction + = someText XMLstuff + . ( get$!arg:?someText + & get$("CorporateData.xml",X,ML):?XMLstuff + | out + $ ( str + $ ( "Something went wrong when reading your file \"" + !arg + "\". Or was it the Corporate Data? Hard to say. Anyhow, now I throw you out." + ) + ) + & ~ + ) + & contemplate$(!someText,!XMLstuff) + ) +& MyFunction$"Tralula.txt" +); diff --git a/Task/Exceptions/PL-pgSQL/exceptions-1.sql b/Task/Exceptions/PL-pgSQL/exceptions-1.sql new file mode 100644 index 0000000000..32ddf70aa4 --- /dev/null +++ b/Task/Exceptions/PL-pgSQL/exceptions-1.sql @@ -0,0 +1,4 @@ +begin + raise exception 'this is a generic user exception'; + raise exception division_by_zero; +end; diff --git a/Task/Exceptions/PL-pgSQL/exceptions-2.sql b/Task/Exceptions/PL-pgSQL/exceptions-2.sql new file mode 100644 index 0000000000..293b78c5ee --- /dev/null +++ b/Task/Exceptions/PL-pgSQL/exceptions-2.sql @@ -0,0 +1,16 @@ +create function special_division(p_num double precision, p_den double precision) returns text +as $body$ +begin + return p_num/p_den::text; +EXCEPTION + when division_by_zero then + if p_num>0 then + return 'Inf'; + ELSIF p_num<0 then + return '-Inf'; + else + return 'INDEF'; + end if; + when others then + raise; +end; diff --git a/Task/Exceptions/Perl-6/exceptions.pl6 b/Task/Exceptions/Perl-6/exceptions.pl6 index 3a0542695e..1a59b39448 100644 --- a/Task/Exceptions/Perl-6/exceptions.pl6 +++ b/Task/Exceptions/Perl-6/exceptions.pl6 @@ -1,9 +1,17 @@ -try { die "Help I'm dieing!"; CATCH { note $_.uc; say "Cough, Cough, Aiee!!" } } - -CATCH { note "No you're not."; say $_; } +try { + die "Help I'm dieing!"; + CATCH { + when X::AdHoc { note .Str.uc; say "Cough, Cough, Aiee!!" } + default { note "Unexpected exception, $_!" } + } +} say "Yay. I'm alive."; die "I'm dead."; say "Arrgh."; + +CATCH { + default { note "No you're not."; say $_.Str; } +} diff --git a/Task/Exceptions/REXX/exceptions.rexx b/Task/Exceptions/REXX/exceptions.rexx index bf24da2fe9..9d74874db8 100644 --- a/Task/Exceptions/REXX/exceptions.rexx +++ b/Task/Exceptions/REXX/exceptions.rexx @@ -1,16 +1,15 @@ -/*REXX pgm to demonstrate handling an exception; catching is via a label*/ - do j=9 by -5 for 100 +/*REXX program demonstrates handling an exception; catching is via a label. */ + do j=9 by -5 say 'square root of' j "is" sqrt(j) end /*j*/ -exit /*stick a fork in it, we're done.*/ +exit /*stick a fork in it, we're all done. */ .sqrtNeg: say 'illegal SQRT argument (argument is negative):' x -exit /*exit (terminate) this program. */ - -/*─────────────────────────────────────SQRT subroutine──────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits();numeric dig - 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) - numeric digits d; return g/1 -.sqrtGuess: if x<0 then signal .sqrtNeg; numeric form; m.=11; p=d+d% - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_% +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then signal .sqrtNeg + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1) /*make complex if X < 0.*/ diff --git a/Task/Execute-Brain----/Rust/execute-brain----.rust b/Task/Execute-Brain----/Rust/execute-brain----.rust new file mode 100644 index 0000000000..38295212ff --- /dev/null +++ b/Task/Execute-Brain----/Rust/execute-brain----.rust @@ -0,0 +1,99 @@ +use std::collections::HashMap; +use std::env; +use std::fs::File; +use std::io::prelude::*; +use std::io::stdin; +use std::num::Wrapping; + +fn main() { + let args: Vec<_> = env::args().collect(); + if args.len() < 2 { + println!("Usage: {} [path] (--debug)", args[0]); + return; + } + + let src: Vec = { + let mut buf = String::new(); + match File::open(&args[1]) + { + Ok(mut f) => { f.read_to_string(&mut buf).unwrap(); } + Err(e) => { + println!("Error opening '{}': {}", args[1], e); + return; + } + } + + buf.chars().collect() + }; + + // Launch options + let debug = args.contains(&"--debug".to_owned()); + + // One pass to find bracket pairs. + let brackets: HashMap = { + let mut m = HashMap::new(); + let mut scope_stack = Vec::new(); + for (idx, ch) in src.iter().enumerate() { + match ch { + &'[' => { scope_stack.push(idx); } + &']' => { m.insert(scope_stack.pop().unwrap(), idx); } + _ => { /* ignore */ } + } + } + + m + }; + + let mut pc: usize = 0; // Program counter + let mut mem: [Wrapping;5000] = [Wrapping(0);5000]; // Program cemory + let mut ptr: usize = 0; // Pointer + let mut stack: Vec = Vec::new(); // Bracket stack + + let stdin_ = stdin(); + let mut reader = stdin_.lock().bytes(); + while pc < src.len() { + let Wrapping(val) = mem[ptr]; + + if debug { + println!("(BFDB) PC: {:04} \tPTR: {:04} \t$PTR: {:03} \tSTACK_DEPTH: {} \tSYMBOL: {}", pc, ptr, val, stack.len(), src[pc]); + } + + const ONE: Wrapping = Wrapping(1); + match src[pc] { + '>' => { ptr += 1; } + '<' => { ptr -= 1; } + + '+' => { mem[ptr] = mem[ptr] + ONE; } + '-' => { mem[ptr] = mem[ptr] - ONE; } + + '[' => { + if val == 0 { + pc = brackets[&pc]; + } else { + stack.push(pc); + } + } + ']' => { + let matching_bracket = stack.pop().unwrap(); + if val != 0 { + pc = matching_bracket - 1; + } + } + + '.' => { + if debug { + println!("(BFDB) STDOUT: '{}'", val as char); // Intercept output + } else { + print!("{}", val as char); + } + } + ',' => { + mem[ptr] = Wrapping(reader.next().unwrap().unwrap()); + } + + _ => { /* ignore */ } + } + + pc += 1; + } +} diff --git a/Task/Execute-HQ9+/Ela/execute-hq9+-1.ela b/Task/Execute-HQ9+/Ela/execute-hq9+-1.ela index e1621e4380..f3f38ae1fd 100644 --- a/Task/Execute-HQ9+/Ela/execute-hq9+-1.ela +++ b/Task/Execute-HQ9+/Ela/execute-hq9+-1.ela @@ -1,4 +1,4 @@ -open console char cell imperative +open unsafe.console char unsafe.cell imperative eval src = eval' src where eval' [] = () diff --git a/Task/Execute-HQ9+/Perl-6/execute-hq9+-1.pl6 b/Task/Execute-HQ9+/Perl-6/execute-hq9+-1.pl6 index 86baa6f04a..e05ee1f358 100644 --- a/Task/Execute-HQ9+/Perl-6/execute-hq9+-1.pl6 +++ b/Task/Execute-HQ9+/Perl-6/execute-hq9+-1.pl6 @@ -28,3 +28,10 @@ class HQ9Interpreter { } } } + +# Feed it a command string: + +my $hq9 = HQ9Interpreter.new; +$hq9.run("hHq+++Qq"); +say ''; +$hq9.run("Jhq.k+hQ"); diff --git a/Task/Execute-HQ9+/Perl-6/execute-hq9+-2.pl6 b/Task/Execute-HQ9+/Perl-6/execute-hq9+-2.pl6 index fae4f32a06..f26f465e40 100644 --- a/Task/Execute-HQ9+/Perl-6/execute-hq9+-2.pl6 +++ b/Task/Execute-HQ9+/Perl-6/execute-hq9+-2.pl6 @@ -1,4 +1,6 @@ my $hq9 = HQ9Interpreter.new; -$hq9.run("hHq+++Qq"); -say; -$hq9.run("Jhq.k+hQ"); +while 1 { + my $in = prompt('HQ9+>').chomp; + last unless $in.chars; + $hq9.run($in) +} diff --git a/Task/Execute-HQ9+/XSLT/execute-hq9+-1.xslt b/Task/Execute-HQ9+/XSLT/execute-hq9+-1.xslt new file mode 100644 index 0000000000..8fee1a3a98 --- /dev/null +++ b/Task/Execute-HQ9+/XSLT/execute-hq9+-1.xslt @@ -0,0 +1,53 @@ + + + + + + + + + Hello, world! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Task/Execute-HQ9+/XSLT/execute-hq9+-2.xslt b/Task/Execute-HQ9+/XSLT/execute-hq9+-2.xslt new file mode 100644 index 0000000000..2759ffb70c --- /dev/null +++ b/Task/Execute-HQ9+/XSLT/execute-hq9+-2.xslt @@ -0,0 +1 @@ +qqqq diff --git a/Task/Execute-HQ9+/XSLT/execute-hq9+-3.xslt b/Task/Execute-HQ9+/XSLT/execute-hq9+-3.xslt new file mode 100644 index 0000000000..b2d1ef5506 --- /dev/null +++ b/Task/Execute-HQ9+/XSLT/execute-hq9+-3.xslt @@ -0,0 +1,110 @@ + + + + + + + + + Hello, world! + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Task/Execute-HQ9+/XSLT/execute-hq9+-4.xslt b/Task/Execute-HQ9+/XSLT/execute-hq9+-4.xslt new file mode 100644 index 0000000000..2759ffb70c --- /dev/null +++ b/Task/Execute-HQ9+/XSLT/execute-hq9+-4.xslt @@ -0,0 +1 @@ +qqqq diff --git a/Task/Execute-HQ9+/XSLT/execute-hq9+-5.xslt b/Task/Execute-HQ9+/XSLT/execute-hq9+-5.xslt new file mode 100644 index 0000000000..af727e649d --- /dev/null +++ b/Task/Execute-HQ9+/XSLT/execute-hq9+-5.xslt @@ -0,0 +1,4 @@ + + qqqq + ++++ + diff --git a/Task/Execute-HQ9+/XSLT/execute-hq9+-6.xslt b/Task/Execute-HQ9+/XSLT/execute-hq9+-6.xslt new file mode 100644 index 0000000000..af688a43b0 --- /dev/null +++ b/Task/Execute-HQ9+/XSLT/execute-hq9+-6.xslt @@ -0,0 +1,5 @@ +qqqq +qqqq +qqqq +qqqq + diff --git a/Task/Execute-HQ9+/XSLT/execute-hq9+-7.xslt b/Task/Execute-HQ9+/XSLT/execute-hq9+-7.xslt new file mode 100644 index 0000000000..8da74564b7 --- /dev/null +++ b/Task/Execute-HQ9+/XSLT/execute-hq9+-7.xslt @@ -0,0 +1,55 @@ + + + + + + + + on the wall + + bottle + s + of beer + + + + + + + + + + + + + + + + Take one down, pass it around + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Task/Execute-SNUSP/Python/execute-snusp.py b/Task/Execute-SNUSP/Python/execute-snusp.py new file mode 100644 index 0000000000..7ffe1d2b09 --- /dev/null +++ b/Task/Execute-SNUSP/Python/execute-snusp.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 + +HW = r''' +/++++!/===========?\>++.>+.+++++++..+++\ +\+++\ | /+>+++++++>/ /++++++++++<<.++>./ +$+++/ | \+++++++++>\ \+++++.>.+++.-----\ + \==-<<<<+>+++/ /=.>.+>.--------.-/''' + +def snusp(store, code): + ds = bytearray(store) # data store + dp = 0 # data pointer + cs = code.splitlines() # 2 dimensional code store + ipr, ipc = 0, 0 # instruction pointers in row and column + for r, row in enumerate(cs): + try: + ipc = row.index('$') + ipr = r + break + except ValueError: + pass + rt, dn, lt, up = range(4) + id = rt # instruction direction. starting direction is always rt + def step(): + nonlocal ipr, ipc + if id&1: + ipr += 1 - (id&2) + else: + ipc += 1 - (id&2) + while ipr >= 0 and ipr < len(cs) and ipc >= 0 and ipc < len(cs[ipr]): + op = cs[ipr][ipc] + if op == '>': + dp += 1 + elif op == '<': + dp -= 1 + elif op == '+': + ds[dp] += 1 + elif op == '-': + ds[dp] -= 1 + elif op == '.': + print(chr(ds[dp]), end='') + elif op == ',': + ds[dp] = input() + elif op == '/': + id = ~id + elif op == '\\': + id ^= 1 + elif op == '!': + step() + elif op == '?': + if not ds[dp]: + step() + step() + +if __name__ == '__main__': + snusp(5, HW) diff --git a/Task/Execute-a-Markov-algorithm/Perl-6/execute-a-markov-algorithm.pl6 b/Task/Execute-a-Markov-algorithm/Perl-6/execute-a-markov-algorithm.pl6 index 9abf20d84e..9177af8421 100644 --- a/Task/Execute-a-Markov-algorithm/Perl-6/execute-a-markov-algorithm.pl6 +++ b/Task/Execute-a-Markov-algorithm/Perl-6/execute-a-markov-algorithm.pl6 @@ -46,7 +46,7 @@ multi sub MAIN(Bool :$verbose?) { my $ruleset = slurp($rulefile); say $start_value.perl(); say run(:$ruleset, :$start_value, :$verbose).perl; - say; + say ''; } } diff --git a/Task/Execute-a-Markov-algorithm/REXX/execute-a-markov-algorithm.rexx b/Task/Execute-a-Markov-algorithm/REXX/execute-a-markov-algorithm.rexx index 9b1775c78d..3028501b0a 100644 --- a/Task/Execute-a-Markov-algorithm/REXX/execute-a-markov-algorithm.rexx +++ b/Task/Execute-a-Markov-algorithm/REXX/execute-a-markov-algorithm.rexx @@ -1,41 +1,41 @@ -/*REXX pgm to execute a Markov algorithm(s) against specified entries.*/ -parse arg low high . /*allow which ruleset to process.*/ -if low=='' | low==',' then low=1 /*assume a default if none given.*/ -if high=='' | high==',' then high=6 /*assume a default if none given.*/ -tellE = low<0; tellR = high<0 /*flags: display file contents. */ +/*REXX program executes a Markov algorithm(s) against specified entries. */ +parse arg low high . /*allows which ruleset to process. */ +if low=='' | low==',' then low=1 /*Not specified? Then use the default.*/ +if high=='' | high==',' then high=6 /* " " " " " " */ +tellE=low<0; tellR=high<0 /*flags: used to display file contents.*/ call readEntry - do j=abs(low) to abs(high) /*process each of these rulesets.*/ - call readRules j /*read a particular ruleset. */ - call execRules j /*execute " " " */ + do j=abs(low) to abs(high) /*process each of these rulesets. */ + call readRules j /*read a particular ruleset. */ + call execRules j /*execute " " " */ say 'result for ruleset' j"≡"!.j end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────EXECRULES──────────────────────────────*/ -execRules: parse arg q .; if tellE | tellR then say - do f=1 /* forever */ - do k=1 while @.k\==''; if left(@.k,1)=='#' | @.k='' then iterate - parse var @.k a ' ->' b; a=strip(a); b=strip(b) - fullstop= left(b,1)=='.' /*is this a fullstop rule? */ - if fullstop then b=substr(b,2) /*purify the B part of the rule. */ - old=!.q /*remember value before change. */ - !.q=changestr(a, !.q, b) /*implement the ruleset change. */ - if fullstop then if old\==!.q then return /*should we stop?*/ - if old\==!.q then iterate f /*Entry changed? Then start over*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +execRules: parse arg q .; if tellE | tellR then say /*a blank line*/ + do f=1 + do k=1 while @.k\==''; if left(@.k,1)=='#' | @.k='' then iterate + parse var @.k a ' ->' b; a=strip(a); b=strip(b) + fullstop= left(b,1)=='.' /*is this a "fullstop" rule? */ + if fullstop then b=substr(b,2) /*purify the B part of the rule. */ + old=!.q /*remember the value before the change.*/ + !.q=changestr(a, !.q, b) /*implement the ruleset change. */ + if fullstop then if old\==!.q then return /*should we stop? */ + if old\==!.q then iterate f /*Has Entry changed? Then start over.*/ end /*k*/ leave end /*f*/ return -/*───────────────────────────────READRULES──────────────────────────────*/ +/*────────────────────────────────────────────────────────────────────────────*/ readRules: parse arg ? .; rFID='MARKOV_R.'?; if tellR then say -@.= /*placeholder: all Markov rules.*/ - do r=1 while lines(rFID)\==0 /*read the input file until E-O-F*/ +@.= /*placeholder for all the Markov rules.*/ + do r=1 while lines(rFID)\==0 /*read the input file until End-Of-File*/ @.r=linein(rFID); if tellR then say 'ruleSet' ?"."left(r,4)'≡'@.r - end /*r*/ /*(above) read and maybe echo it.*/ + end /*r*/ /*(above) read and maybe echo the rule.*/ return -/*───────────────────────────────READENTRY──────────────────────────────*/ -readEntry: eFID='MARKOV.ENT'; if tellE then say -!.= /*placeholder: all test entries.*/ - do e=1 while lines(eFID)\==0 /*read the input file until E-O-F*/ +/*────────────────────────────────────────────────────────────────────────────*/ +readEntry: eFID='MARKOV.ENT'; if tellE then say +!.= /*placeholder for all the test entries.*/ + do e=1 while lines(eFID)\==0 /*read the input file until End-Of-File*/ !.e=linein(eFID); if tellE then say 'test entry' e"≡"!.e - end /*e*/ /*(above) read and maybe echo it.*/ + end /*e*/ /*(above) read and maybe echo the entry*/ return diff --git a/Task/Execute-a-Markov-algorithm/SNOBOL4/execute-a-markov-algorithm.sno b/Task/Execute-a-Markov-algorithm/SNOBOL4/execute-a-markov-algorithm.sno new file mode 100644 index 0000000000..e9ab88ab67 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/SNOBOL4/execute-a-markov-algorithm.sno @@ -0,0 +1,128 @@ +#!/bin/sh + exec "snobol4" "-r" "$0" "$@" +* +* http://rosettacode.org/wiki/Execute_a_Markov_algorithm +* + define('repl(s1,s2,s3)c,t,findc') :(repl_end) +repl s2 len(1) . c = :f(freturn) + findc = break(c) . t len(1) + s2 = pos(0) s2 +repl_1 s1 findc = :f(repl_2) + s1 s2 = :f(repl_3) + repl = repl t s3 :(repl_1) +repl_3 repl = repl t c :(repl_1) +repl_2 repl = repl s1 :(return) +repl_end +* + define('quote(s)q,qq') :(quote_end) +quote q = "'"; qq = '"' + quote = q repl(s, q, q ' ' qq q qq ' ' q) q :(return) +quote_end +* + whitespace = span(' ' char(9)) +top r = 0 +read s = input :f(end) + s pos(0) 'ENDRULE' rpos(0) :s(interp) + s pos(0) '#' :s(read) + pattern =; replacement =; term = + s arb . pattern whitespace '->' whitespace ++ ('.' | '') . term arb . replacement rpos(0) :f(syntax) + r = r + 1 + f = ident(term, '.') ' :(done)' + f = ident(term) ' :f(rule' r + 1 ')s(rule1)' + c = 'rule' r ' s ' quote(pattern) ' = ' quote(replacement) f + code(c) :s(read) + output = 'rule: ' s ' generates code ' c ' in error' :(end) +syntax output = 'rule: ' s ' in error' :(read) +interp code('rule' r + 1 ' :(done)') +go s = input :f(end) + s pos(0) 'END' rpos(0) :s(top)f(rule1) +done output = s :(go) +end +# This rules file is extracted from Wikipedia: +# http://en.wikipedia.org/wiki/Markov_Algorithm +A -> apple +B -> bag +S -> shop +T -> the +the shop -> my brother +a never used -> .terminating rule +ENDRULE +I bought a B of As from T S. +END +# Slightly modified from the rules on Wikipedia +A -> apple +B -> bag +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule +ENDRULE +I bought a B of As from T S. +END +# BNF Syntax testing rules +A -> apple +WWWW -> with +Bgage -> ->.* +B -> bag +->.* -> money +W -> WW +S -> .shop +T -> the +the shop -> my brother +a never used -> .terminating rule +ENDRULE +I bought a B of As W my Bgage from T S. +END +### Unary Multiplication Engine, for testing Markov Algorithm implementations +### By Donal Fellows. +# Unary addition engine +_+1 -> _1+ +1+1 -> 11+ +# Pass for converting from the splitting of multiplication into ordinary +# addition +1! -> !1 +,! -> !+ +_! -> _ +# Unary multiplication by duplicating left side, right side times +1*1 -> x,@y +1x -> xX +X, -> 1,1 +X1 -> 1X +_x -> _X +,x -> ,X +y1 -> 1y +y_ -> _ +# Next phase of applying +1@1 -> x,@y +1@_ -> @_ +,@_ -> !_ +++ -> + +# Termination cleanup for addition +_1 -> 1 +1+_ -> 1 +_+_ -> +ENDRULE +_1111*11111_ +END +# Turing machine: three-state busy beaver +# +# state A, symbol 0 => write 1, move right, new state B +A0 -> 1B +# state A, symbol 1 => write 1, move left, new state C +0A1 -> C01 +1A1 -> C11 +# state B, symbol 0 => write 1, move left, new state A +0B0 -> A01 +1B0 -> A11 +# state B, symbol 1 => write 1, move right, new state B +B1 -> 1B +# state C, symbol 0 => write 1, move left, new state B +0C0 -> B01 +1C0 -> B11 +# state C, symbol 1 => write 1, move left, halt +0C1 -> H01 +1C1 -> H11 +ENDRULE +000000A000000 +END diff --git a/Task/Execute-a-system-command/AWK/execute-a-system-command.awk b/Task/Execute-a-system-command/AWK/execute-a-system-command-1.awk similarity index 100% rename from Task/Execute-a-system-command/AWK/execute-a-system-command.awk rename to Task/Execute-a-system-command/AWK/execute-a-system-command-1.awk diff --git a/Task/Execute-a-system-command/AWK/execute-a-system-command-2.awk b/Task/Execute-a-system-command/AWK/execute-a-system-command-2.awk new file mode 100644 index 0000000000..b1e954ee1a --- /dev/null +++ b/Task/Execute-a-system-command/AWK/execute-a-system-command-2.awk @@ -0,0 +1,15 @@ +BEGIN { + ls = sys2var("ls") + print ls +} +function sys2var(command ,fish, scale, ship) { + command = command " 2>/dev/null" + while ( (command | getline fish) > 0 ) { + if ( ++scale == 1 ) + ship = fish + else + ship = ship "\n" fish + } + close(command) + return ship +} diff --git a/Task/Execute-a-system-command/AutoIt/execute-a-system-command.autoit b/Task/Execute-a-system-command/AutoIt/execute-a-system-command.autoit new file mode 100644 index 0000000000..fcd817add6 --- /dev/null +++ b/Task/Execute-a-system-command/AutoIt/execute-a-system-command.autoit @@ -0,0 +1 @@ +Run(@ComSpec & " /c " & 'pause', "", @SW_HIDE) diff --git a/Task/Execute-a-system-command/D/execute-a-system-command.d b/Task/Execute-a-system-command/D/execute-a-system-command.d index 9857e12305..10b14600d0 100644 --- a/Task/Execute-a-system-command/D/execute-a-system-command.d +++ b/Task/Execute-a-system-command/D/execute-a-system-command.d @@ -1 +1,9 @@ -std.process.system("ls"); +import std.process, std.stdio; +//these two alternatives wait for the process to return, and capture the output +//each process function returns a Tuple of (int)"status" and (string)"output +auto ls_string = executeShell("ls -l"); //takes single string +writeln((ls_string.status == 0) ? ls_string.output : "command failed"); + +auto ls_array = execute(["ls", "-l"]); //takes array of strings +writeln((ls_array.status == 0) ? ls_array.output : "command failed"); +//other alternatives exist to spawn processes in parallel and capture output via pipes diff --git a/Task/Execute-a-system-command/Julia/execute-a-system-command.julia b/Task/Execute-a-system-command/Julia/execute-a-system-command.julia new file mode 100644 index 0000000000..69521e7766 --- /dev/null +++ b/Task/Execute-a-system-command/Julia/execute-a-system-command.julia @@ -0,0 +1 @@ +run(`ls`) diff --git a/Task/Execute-a-system-command/Perl-6/execute-a-system-command.pl6 b/Task/Execute-a-system-command/Perl-6/execute-a-system-command.pl6 index 9b70d5dfdd..6c1d39719d 100644 --- a/Task/Execute-a-system-command/Perl-6/execute-a-system-command.pl6 +++ b/Task/Execute-a-system-command/Perl-6/execute-a-system-command.pl6 @@ -3,4 +3,4 @@ run "ls" or die $!; # output to stdout my @ls = qx/ls/; # output to variable my $cmd = 'ls'; -my @ls = qqx/$ls/; # same thing with interpolation +@ls = qqx/$cmd/; # same thing with interpolation diff --git a/Task/Execute-a-system-command/Rust/execute-a-system-command.rust b/Task/Execute-a-system-command/Rust/execute-a-system-command.rust new file mode 100644 index 0000000000..eb9075c708 --- /dev/null +++ b/Task/Execute-a-system-command/Rust/execute-a-system-command.rust @@ -0,0 +1,7 @@ +use std::process::Command; +fn main() { + let output = Command::new("ls").output().unwrap_or_else(|e| { + panic!("failed to execute process: {}", e) + }); + println!("{}", String::from_utf8_lossy(&output.stdout)); +} diff --git a/Task/Execute-a-system-command/VBScript/execute-a-system-command.vb b/Task/Execute-a-system-command/VBScript/execute-a-system-command.vb new file mode 100644 index 0000000000..6b06a04e7f --- /dev/null +++ b/Task/Execute-a-system-command/VBScript/execute-a-system-command.vb @@ -0,0 +1,2 @@ +Set objShell = CreateObject("WScript.Shell") +objShell.Run "%comspec% /K dir",3,True diff --git a/Task/Exponentiation-operator/00DESCRIPTION b/Task/Exponentiation-operator/00DESCRIPTION index ea9672f517..4f1a76c2bb 100644 --- a/Task/Exponentiation-operator/00DESCRIPTION +++ b/Task/Exponentiation-operator/00DESCRIPTION @@ -1,4 +1,4 @@ -Most all programming languages have a built-in implementation of exponentiation. +Most programming languages have a built-in implementation of exponentiation. Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants. diff --git a/Task/Exponentiation-operator/Elixir/exponentiation-operator.elixir b/Task/Exponentiation-operator/Elixir/exponentiation-operator.elixir new file mode 100644 index 0000000000..46fdd43976 --- /dev/null +++ b/Task/Exponentiation-operator/Elixir/exponentiation-operator.elixir @@ -0,0 +1,31 @@ +defmodule My do + def exp(x,y) when is_integer(x) and is_integer(y) and y>=0 do + IO.write("int> ") # debug test + exp_int(x,y) + end + def exp(x,y) when is_integer(y) do + IO.write("float> ") # debug test + exp_float(x,y) + end + def exp(x,y), do: (IO.write(" "); :math.pow(x,y)) + + defp exp_int(_,0), do: 1 + defp exp_int(x,y), do: Enum.reduce(1..y, 1, fn _,acc -> x * acc end) + + defp exp_float(_,y) when y==0, do: 1.0 + defp exp_float(x,y) when y<0, do: 1/exp_float(x,-y) + defp exp_float(x,y), do: Enum.reduce(1..y, 1, fn _,acc -> x * acc end) +end + +list = [{2,0}, {2,3}, {2,-2}, + {2.0,0}, {2.0,3}, {2.0,-2}, + {0.5,0}, {0.5,3}, {0.5,-2}, + {-2,2}, {-2,3}, {-2.0,2}, {-2.0,3}, + ] +IO.puts " ___My.exp___ __:math.pow_" +Enum.each(list, fn {x,y} -> + sxy = "#{x} ** #{y}" + sexp = inspect My.exp(x,y) + spow = inspect :math.pow(x,y) # For the comparison + :io.fwrite("~10s = ~12s, ~12s~n", [sxy, sexp, spow]) +end) diff --git a/Task/Exponentiation-operator/Erlang/exponentiation-operator.erl b/Task/Exponentiation-operator/Erlang/exponentiation-operator.erl new file mode 100644 index 0000000000..743ea9b8d5 --- /dev/null +++ b/Task/Exponentiation-operator/Erlang/exponentiation-operator.erl @@ -0,0 +1,10 @@ +pow(X, Y) when Y < 0 -> + 1/pow(X, -Y); +pow(X, Y) when is_integer(Y) -> + pow(X, Y, 1). + +pow(_, 0, B) -> + B; +pow(X, Y, B) -> + B2 = if Y rem 2 =:= 0 -> B; true -> X * B end, + pow(X * X, Y div 2, B2). diff --git a/Task/Exponentiation-operator/Python/exponentiation-operator.py b/Task/Exponentiation-operator/Python/exponentiation-operator.py index 41beb48a2f..a708757756 100644 --- a/Task/Exponentiation-operator/Python/exponentiation-operator.py +++ b/Task/Exponentiation-operator/Python/exponentiation-operator.py @@ -1,22 +1,15 @@ ->>> import operator ->>> class num(int): - def __pow__(self, b): - print "Empowered" - return operator.__pow__(self+0, b) - +MULTIPLY = lambda x, y: x*y ->>> x = num(3) ->>> x**2 -Empowered -9 ->>> class num(float): +class num(float): + # the following method has complexity O(b) + # rather than O(log b) via the rapid exponentiation def __pow__(self, b): - print "Empowered" - return operator.__pow__(self+0, b) + return reduce(MULTIPLY, [self]*b, 1) +# works with ints as function or operator +print num(2).__pow__(3) +print num(2) ** 3 ->>> x = num(2.5) ->>> x**2 -Empowered -6.25 ->>> +# works with floats as function or operator +print num(2.3).__pow__(8) +print num(2.3) ** 8 diff --git a/Task/Exponentiation-operator/REXX/exponentiation-operator.rexx b/Task/Exponentiation-operator/REXX/exponentiation-operator.rexx index a468ff0c4c..2be61bd331 100644 --- a/Task/Exponentiation-operator/REXX/exponentiation-operator.rexx +++ b/Task/Exponentiation-operator/REXX/exponentiation-operator.rexx @@ -1,4 +1,4 @@ -/*REXX program to show various (integer) exponentations. */ +/*REXX program to show various (integer) exponentiations. */ say center('digits='digits(),79,'─') say '17**65 is:' say 17**65 diff --git a/Task/Exponentiation-operator/Ruby/exponentiation-operator-1.rb b/Task/Exponentiation-operator/Ruby/exponentiation-operator-1.rb index fbdf97c3de..643bbd982a 100644 --- a/Task/Exponentiation-operator/Ruby/exponentiation-operator-1.rb +++ b/Task/Exponentiation-operator/Ruby/exponentiation-operator-1.rb @@ -2,12 +2,7 @@ class Numeric def pow(m) raise TypeError, "exponent must be an integer: #{m}" unless m.is_a? Integer puts "pow!!" - - # below requires Ruby 1.8.7 Array.new(m, self).reduce(1, :*) - - # for earlier versions of Ruby - #Array.new(m, self).inject(1) { |res, n| res * n } end end diff --git a/Task/Exponentiation-operator/VBScript/exponentiation-operator.vb b/Task/Exponentiation-operator/VBScript/exponentiation-operator.vb new file mode 100644 index 0000000000..03a1a584ef --- /dev/null +++ b/Task/Exponentiation-operator/VBScript/exponentiation-operator.vb @@ -0,0 +1,23 @@ +Function pow(x,y) + pow = 1 + If y < 0 Then + For i = 1 To Abs(y) + pow = pow * (1/x) + Next + Else + For i = 1 To y + pow = pow * x + Next + End If +End Function + +WScript.StdOut.Write "2 ^ 0 = " & pow(2,0) +WScript.StdOut.WriteLine +WScript.StdOut.Write "7 ^ 6 = " & pow(7,6) +WScript.StdOut.WriteLine +WScript.StdOut.Write "3.14159265359 ^ 9 = " & pow(3.14159265359,9) +WScript.StdOut.WriteLine +WScript.StdOut.Write "4 ^ -6 = " & pow(4,-6) +WScript.StdOut.WriteLine +WScript.StdOut.Write "-3 ^ 5 = " & pow(-3,5) +WScript.StdOut.WriteLine diff --git a/Task/Extend-your-language/COBOL/extend-your-language.cobol b/Task/Extend-your-language/COBOL/extend-your-language.cobol new file mode 100644 index 0000000000..389ed85f94 --- /dev/null +++ b/Task/Extend-your-language/COBOL/extend-your-language.cobol @@ -0,0 +1,10 @@ +EVALUATE EXPRESSION-1 ALSO EXPRESSION-2 + WHEN TRUE ALSO TRUE + DISPLAY 'Both are true.' + WHEN TRUE ALSO FALSE + DISPLAY 'Expression 1 is true.' + WHEN FALSE ALSO TRUE + DISPLAY 'Expression 2 is true.' + WHEN OTHER + DISPLAY 'Neither is true.' +END-EVALUATE diff --git a/Task/Extend-your-language/REXX/extend-your-language-1.rexx b/Task/Extend-your-language/REXX/extend-your-language-1.rexx index 2d638900b8..3afb3fdbf5 100644 --- a/Task/Extend-your-language/REXX/extend-your-language-1.rexx +++ b/Task/Extend-your-language/REXX/extend-your-language-1.rexx @@ -1,8 +1,16 @@ -if2( some expression that results in a boolean value, some other expression that results in a boolean value.) +if2( some-expression-that-results-in-a-boolean-value, some-other-expression-that-results-in-a-boolean-value) + + + /*this part is a REXX comment*/ /*could be a DO structure.*/ + select /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/ /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/ + + when if.11 /*{condition 1 & 2 are true}*/ then perform-a-REXX-statement + when if.10 /*{condition 1 is true}*/ then " " " " + when if.01 /*{condition 2 is true}*/ then " " " " + when if.00 /*{no condition is true}*/ then " " " " - select - when if.11 {condition 1 & 2 are true} then perform-a-REXX-statement. - when if.10 {condition 1 is true} " " " " " - when if.01 {condition 2 is true} " " " " " - when if.00 {no condition is true} " " " " " end + +/*an example of a DO structure for the first clause: */ + + when if.11 /*{condition 1 & 2 are true}*/ then do; x=12; y=length(y); end diff --git a/Task/Extend-your-language/REXX/extend-your-language-2.rexx b/Task/Extend-your-language/REXX/extend-your-language-2.rexx index 436a8f7b50..208f352e7c 100644 --- a/Task/Extend-your-language/REXX/extend-your-language-2.rexx +++ b/Task/Extend-your-language/REXX/extend-your-language-2.rexx @@ -1,20 +1,23 @@ -/*REXX program introduces IF2, a type of four-way compound IF: */ +/*REXX program introduces IF2, a type of a four-way compound IF: */ +parse arg bot top . /*obtain optional arguments from the CL*/ +if bot=='' | bot==',' then bot=10 /*Not specified? Then use the default.*/ +if top=='' | top==',' then top=25 /* " " " " " " */ +w=max(length(bot), length(top)) + 10 /*W: max width, used for displaying #. */ - do n=10 to 20 /*put DO loop through it's paces.*/ - /* [↓] divisible by 2 and/or 3? */ - if2( n//2==0, n//3==0) /*use the four-way IF statement.*/ - select /*now, test the 4 possible cases.*/ - when if.11 then say n "is divisible by both two and three." - when if.10 then say n "is divisible by two, but not by three." - when if.01 then say n "is divisible by three, but not by two." - when if.00 then say n "is neither divisible by two, nor by three." - otherwise nop /* ◄─┬─this statement is optional*/ - end /*select*/ /* ├─ and only exists in case */ - end /*n*/ /* ├─ one or more WHENs (above)*/ - /* └─ are omitted. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────IF2 routine─────────────────────────*/ -if2: parse arg if.10, if.01 /*assign the cases 10 and 01 */ - if.11= if.10 & if.01 /* " " case 11 */ - if.00= \(if.10 | if.01) /* " " " 00 */ -return '' /*return to the invoker of IF2. */ + do #=bot to top /*put a DO loop through its paces. */ + /* [↓] divisible by two and/or three? */ + if2( #//2==0, #//3==0) /*use a new four-way IF statement. */ + select /*now, test the four possible cases. */ + when if.11 then say right(#,w) " is divisible by both two and three." + when if.10 then say right(#,w) " is divisible by two, but not by three." + when if.01 then say right(#,w) " is divisible by three, but not by two." + when if.00 then say right(#,w) " isn't divisible by two, nor by three." + otherwise nop /*◄──┬◄ this statement is optional and */ + end /*select*/ /* ├◄ only exists in case one or more*/ + end /*#*/ /* └◄ WHENs (above) are omitted. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────IF2 routine───────────────────────────────*/ +if2: parse arg if.10, if.01 /*assign the cases 10 and 01 */ + if.11= if.10 & if.01 /* " " case 11 */ + if.00= \(if.10 | if.01) /* " " " 00 */ +return '' diff --git a/Task/Extend-your-language/TXR/extend-your-language.txr b/Task/Extend-your-language/TXR/extend-your-language.txr new file mode 100644 index 0000000000..9bdf6a543b --- /dev/null +++ b/Task/Extend-your-language/TXR/extend-your-language.txr @@ -0,0 +1,9 @@ +(defmacro if2 (cond1 cond2 both first second . neither) + (let ((res1 (gensym)) + (res2 (gensym))) + ^(let ((,res1 ,cond1) + (,res2 ,cond2)) + (cond ((and ,res1 ,res2) ,both) + (,res1 ,first) + (,res2 ,second) + (t ,*neither))))) diff --git a/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-2.hs b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-2.hs index 30c6143d8a..4fda4e771a 100644 --- a/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-2.hs +++ b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-2.hs @@ -1 +1,11 @@ -![2,3,5,7] | (nc := 11) | (nc +:= |wheel2345) + λ> take 20 primesW +[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71] + + λ> takeWhile (< 150) . dropWhile (< 100) $ primesW +[101,103,107,109,113,127,131,137,139,149] + + λ> length . takeWhile (< 8000) . dropWhile (< 7700) $ primesW +30 + + λ> (!! (10000-1)) primesW +104729 diff --git a/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-3.hs b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-3.hs index 5dbb6fe349..30c6143d8a 100644 --- a/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-3.hs +++ b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-3.hs @@ -1,38 +1 @@ -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 +![2,3,5,7] | (nc := 11) | (nc +:= |wheel2345) diff --git a/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-4.hs b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-4.hs new file mode 100644 index 0000000000..5dbb6fe349 --- /dev/null +++ b/Task/Extensible-prime-generator/Haskell/extensible-prime-generator-4.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-1.j similarity index 100% rename from Task/Extensible-prime-generator/J/extensible-prime-generator.j rename to Task/Extensible-prime-generator/J/extensible-prime-generator-1.j diff --git a/Task/Extensible-prime-generator/J/extensible-prime-generator-2.j b/Task/Extensible-prime-generator/J/extensible-prime-generator-2.j new file mode 100644 index 0000000000..149e40e705 --- /dev/null +++ b/Task/Extensible-prime-generator/J/extensible-prime-generator-2.j @@ -0,0 +1,2 @@ + 4 p: 104729 +104743 diff --git a/Task/Extensible-prime-generator/PARI-GP/extensible-prime-generator-1.pari b/Task/Extensible-prime-generator/PARI-GP/extensible-prime-generator-1.pari new file mode 100644 index 0000000000..2c7bffca8c --- /dev/null +++ b/Task/Extensible-prime-generator/PARI-GP/extensible-prime-generator-1.pari @@ -0,0 +1,10 @@ +void +showprimes(GEN lower, GEN upper) +{ + forprime_t T; + if (!forprime_init(&T, a,b)) return; + while(forprime_next(&T)) + { + pari_printf("%Ps\n", T.pp); + } +} diff --git a/Task/Extensible-prime-generator/PARI-GP/extensible-prime-generator-2.pari b/Task/Extensible-prime-generator/PARI-GP/extensible-prime-generator-2.pari new file mode 100644 index 0000000000..16fb1621ad --- /dev/null +++ b/Task/Extensible-prime-generator/PARI-GP/extensible-prime-generator-2.pari @@ -0,0 +1,5 @@ +primes(20) +primes([100,150]) +#primes([7700,8000]) /* or */ +s=0; forprime(p=7700,8000,s++); s +prime(10000) diff --git a/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal b/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal index 10bdff7100..cf747b748e 100644 --- a/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal +++ b/Task/Extensible-prime-generator/Pascal/extensible-prime-generator.pascal @@ -1,95 +1,129 @@ -program prime7; +program prime; {$IFDEF FPC} {$MODE DELPHI} {$OPTIMIZATION ON,REGVAR,PEEPHOLE,CSE,ASMCSE} - {$Smartlink ON} - {$CODEALIGN proc=32} + {$CODEALIGN proc=8} +// {$R+,V+,O+} {$ELSE} {$APPLICATION CONSOLE} {$ENDIF} uses - popcount; + sysutils; +type + tSievenum = NativeUint; const - + cBitSize = SizeOf(tSievenum)*8; + cAndMask = cBitSize-1; 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 = 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; +//Don't sieve with primes that are multiples of 2..InitPrim[BIS] + BIS = 5; + MaxMulFac = 22; {array [0..9] of byte= (2,4,6,10,14,22,26,34,40,50);} + cMaxZahl = 30030; + cRepFldLen = 5760; + MaxUpperLimit = 100*1000*1000*1000-1; + + MAXIMUM = ((MaxUpperLimit-1) DIV cMaxZahl+1)*cMaxZahl; + MAXSUCHE = (((MAXIMUM-1) div cMaxZahl+1)*cRepFldLen-1) + DIV cBitSize; type - tSievenum = Uint32;// Uint64 doubles run-time in 32 Bit + tRpFldIdx = 0..cRepFldLen-1; + pNativeUint = ^ NativeUint; + (* numberField as Bit array *) + tsearchFld = array of tSievenum; + tSegment = record dOfs, - dSegment :LongWord; + dSegment :tSievenum; 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; + tnumberField= array [0..cMaxZahl-1] of word; //word-> 0..cRepFldLen-1 + tRevIdx = array [tRpFldIdx] of word;//word-> 0..cMaxZahl-1 + tDiffFeld = array [tRpFldIdx] of byte; + tNewPosFeld = array [tRpFldIdx] of Uint64; tRecPrime = record - rpPrime :tSievenum; - rpsvPos, + rpPrime, + rpsvPos : Uint64; rpOfs, rpSeg :LongWord; end; var + BitSet, + BitClr : Array [0..cAndMask] Of NativeUint; + deltaNewPos : tNewPosFeld; MulFeld : tMulFeld; searchFld : tsearchFld; number : tnumberField; DiffFld : tDiffFeld; RevIdx : tRevIdx; - Quadrat : Uint64; - MaxPos : NativeUint; + actSquare : Uint64; + NewStartPos, + MaxPos : Uint64; 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} +//K1 = $0101010101010101; + K55 = $5555555555555555; + K33 = $3333333333333333; + KF1 = $0F0F0F0F0F0F0F0F; + KF2 = $00FF00FF00FF00FF; + KF4 = $0000FFFF0000FFFF; + KF8 = $00000000FFFFFFFF; + +function popcnt(n:Uint64):integer;overload;inline; +var + c,b,k : NativeUint; +begin + b := n; + k := NativeUint(K55);c := (b shr 1) AND k; b := (b AND k)+C; + k := NativeUint(K33);c := ((b shr 2) AND k);b := (b AND k)+C; + k := NativeUint(KF1);c := ((b shr 4) AND k);b := (b AND k)+c; + k := NativeUint(KF2);c := ((b shr 8) AND k);b := (b AND k)+c; + k := NativeUint(KF4);c := ((b shr 16) AND k);b := (b AND k)+c; + k := NativeUint(KF8);c := (b shr 32)+(b AND k); + result := c; +end; + +function popcnt(n:LongWord):integer;overload; +var + c,k : LongWord; +begin + result := n; + IF result = 0 then + EXIT; + k := LongWord(K55);c := (result shr 1) AND k; result := (result AND k)+C; + k := LongWord(K33);c := ((result shr 2) AND k);result := (result AND k)+C; + k := LongWord(KF1);c := ((result shr 4) AND k);result := (result AND k)+c; + k := LongWord(KF2);c := ((result shr 8) AND k);result := (result AND k)+c; + k := LongWord(KF4); + result := (result shr 16) AND k +(result AND k); +end; + +procedure Init; +{simple sieve of erathosthenes only eliminating small primes} var pr,i,j,Ofs : NativeUint; Begin + //Init Bitmasks + j := 1; + For i := 0 to cAndMask do + Begin + BitSet[i] := J; + BitClr[i] := NativeUint(NOT(J)); + j:= j+j; + end; + //building number wheel excluding multiples of small primes Fillchar(number,SizeOf(number),#0); For i := 0 to BIS do Begin @@ -101,6 +135,7 @@ Begin until j <= 0; end; + // build reverse Index and save distances i := 1; j := 0; RevIdx[0]:= 1; @@ -122,24 +157,24 @@ Begin for i := 0 to cRepFldLen-2 do begin inc(Ofs,DiffFld[i]); - number[Ofs] := i+1; + number[ofs] := i+1; end; + //direct index into Mulfeld 2->0 ,4-> 1 ... 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; +function CalcPos(m: Uint64): Uint64; {search right position of m} var - i,res : Uint32; + i,res : NativeUint; Begin res := m div cMaxZahl; - i := m mod cMaxzahl; + i := m-res* Uint64(cMaxzahl);//m mod cMaxZahl while (number[i]= 0) and (i <>1) do begin iF i = 0 THEN @@ -149,18 +184,26 @@ Begin end; dec(i); end; {while} - CalcPos := res *cRepFldLen +number[i]; + CalcPos := res *Uint64(cRepFldLen) +number[i]; +end; + +procedure CalcSqrOfs(out Segment,Ofs :Uint64); +Begin + Segment := actSquare div cMaxZahl; + Ofs := actSquare-Segment*cMaxZahl; //ofs Mod cMaxZahl + Segment := Segment*cRepFldLen; end; -procedure MulTab(searchPr:Nativeint); +procedure MulTab(sievePr:Nativeint); var k,Segment,Segment0,Rest,Rest0: NativeUint; Begin - {Multiplikationstabelle der Differenzen} - searchPr := searchPr+searchPr; - Segment0 := searchPr div cMaxzahl; + {multiplication-table of differences} + {2* sievePr,4* ,6* ...MaxMulFac*sievePr } + sievePr := sievePr+sievePr; + Segment0 := sievePr div cMaxzahl; - Rest0 := searchPr-Segment0*cMaxzahl; + Rest0 := sievePr-Segment0*cMaxzahl; Segment0 := Segment0 * cRepFldLen; Segment := Segment0; @@ -189,92 +232,139 @@ Begin 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 +procedure CalcDeltaNewPos(sievePr,MulPos:NativeUint); var - Ofs,Segment,Position,k : tSievenum;//NativeUint; - p : pLongWord; + Ofs,Segment,prevPos,actPos : Uint64; + i: NativeInt; 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 + MulTab(sievePr); + //start at sqr sievePrime + CalcSqrOfs(Segment,Ofs); + NewStartPos := Segment+number[Ofs]; + prevPos := NewStartPos; + deltaNewPos[0]:= prevPos; + For i := 0 to cRepFldLen-2 do + begin + inc(mulpos); + IF mulpos >= cRepFldLen then + mulpos := 0; + With MulFeld[DiffFld[mulpos]] do begin - k:= Ofs+dOfs; + Ofs:= Ofs+dOfs; Segment := Segment+dSegment; end; - - If k >= cMaxZahl then + If Ofs >= cMaxZahl then begin - k := k-cMaxZahl; + Ofs := Ofs-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; + actPos := Segment+number[Ofs]; + deltaNewPos[i]:= actPos - prevPos; + IF actPos> maxPos then + BREAK; + + prevPos := actPos; + end; + deltaNewPos[cRepFldLen-1] := NewStartPos+cRepFldLen*sievePr-prevPos; +end; + +procedure SieveByOnePrime(var sf:tsearchFld;sievePr:NativeUint); +var + pNewPos : ^Uint64; + pSiev0, + pSiev : ^tSievenum;// dynamic arrays are slow + Ofs : Int64; + Position : UINt64; + i: NativeInt; + +Begin + pSiev0 := @sf[0]; + Ofs := MaxPos-sievePr *cRepFldLen; + Position := NewStartPos; + {unmark multiples of sieve prime} + repeat + IF Position < Ofs then + Begin + pNewPos:= @deltaNewPos[0]; + For i := Low(deltaNewPos) to High(deltaNewPos) do + Begin + pSiev := pSiev0; + inc(pSiev,Position DIV cBitSize); + //pSiev^ == @sf[Position DIV cBitSize] + pSiev^ := pSiev^ AND BitCLR[Position AND cAndMask]; + inc(Position,pNewPos^); + inc(pNewPos); + end + end else - //case of overflow try 2E10 with 32-Bit - Break; + Begin + pNewPos:= @deltaNewPos[0]; + For i := Low(deltaNewPos) to High(deltaNewPos) do + Begin + IF Position >= MaxPos then + Break; + pSiev := pSiev0; + inc(pSiev,Position DIV cBitSize); + pSiev^ := pSiev^ AND BitCLR[Position AND cAndMask]; + inc(Position,pNewPos^); + inc(pNewPos); + end + end; until Position >= MaxPos; end; procedure SieveAll; var i, - searchPr, + sievePr, PrimPos, srPrPos : NativeUint; + l: Uint64; Begin - BuildWheel; - MaxPos := CalcPos(MaxZahl); + Init; + MaxPos := CalcPos(MaxUpperLimit); {start of prime sieving} - fillchar(searchFld,SizeOf(searchFld),#0); + i := (MaxPos-1) DIV cBitSize+1; + setlength(searchFld,i); + IF Length(searchFld) <> i then + Begin + writeln('Not enough memory'); + Halt(-227); + end; + For i := High(searchFld) downto 0 do + searchFld[i] := NativeUint(-1); {the first prime} srPrPos := 0; PrimPos := 0; - searchPr := 1; - Quadrat := searchPr; + sievePr := 1; + actSquare := sievePr; 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 + actSquare := actSquare+(2*sievePr+i)*i; + inc(sievePr,i); + + IF actSquare > MaxUpperLimit THEN BREAK; - {if searchPr == prime then sieve with searchPr} - if NOT((srPrPos and 31) in searchFld[srPrPos shr 5] )then - Sieben(searchFld,searchPr,PrimPos); + {if sievePr == prime then sieve with sievePr} + if BitSet[srPrPos AND cAndMask] AND + searchFld[srPrPos DIV cBitSize] <> 0then + Begin + write(sievePr:8,#8#8#8#8#8#8#8#8); + CalcDeltaNewPos(sievePr,PrimPos); + SieveByOnePrime(searchFld,sievePr); + end; inc(PrimPos); if PrimPos = cRepFldLen then dec(PrimPos,PrimPos);// := 0; until false; end; -function InitRecPrime(pr: tSievenum):tRecPrime; +function InitRecPrime(pr: UInt64):tRecPrime; var - svPos,sg : LongWord; + svPos,sg : NativeUint; Begin svPos := CalcPos(pr); sg := svPos DIV cRepFldLen; @@ -287,7 +377,7 @@ Begin end; end; -function InitPrimeSvPos(svPos: LongWord):tRecPrime; +function InitPrimeSvPos(svPos: Uint64):tRecPrime; var sg : LongWord; Begin @@ -301,9 +391,10 @@ Begin end; end; -Procedure NextPrime(var pr: tRecPrime); +function NextPrime(var pr: tRecPrime):Boolean; var - ofs,svPos : LongWord; + ofs : LongWord; + svPos : Uint64; Begin with pr do Begin @@ -312,45 +403,53 @@ Begin repeat inc(svPos); if svPos > MaxPos then + Begin + result := false; EXIT; + end; inc(Ofs); IF Ofs >= cRepFldLen then Begin ofs := 0; - inc(rpSeg,cRepFldLen); + inc(rpSeg); end; - until NOT((svPos and 31) in searchFld[svPos shr 5] ); - rpPrime := rpSeg*cMaxZahl+RevIdx[Ofs]; + until BitSet[svPos AND cAndMask] AND + searchFld[svPos DIV cBitSize] <> 0; + rpPrime := rpSeg*Uint64(cMaxZahl)+RevIdx[Ofs]; rpSvPos := svPos; rpOfs := Ofs; end; + result := true; end; -function GetNthPrime(n: LongWord):tRecPrime; +function GetNthPrime(n: Uint64):tRecPrime; var - i,cnt : longWord; + i : longWord; + cnt: Uint64; 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; + For i := 0 to n DIV cBitSize do + inc(cnt,PopCnt(NativeUint(searchFld[i]))); + i := n DIV cBitSize+1; + while cnt < n do Begin - inc(cnt,PopCnt(NOT(Uint32(searchFld[i])))); + inc(cnt,PopCnt(NativeUint(searchFld[i]))); inc(i); end; dec(i); - dec(cnt,PopCnt(NOT(Uint32(searchFld[i])))); - result := InitPrimeSvPos(i*32-1); + + dec(cnt,PopCnt(NativeUint(searchFld[i]))); + result := InitPrimeSvPos(i*Uint64(cBitSize)-1); while cnt < n do - Begin - NextPrime(Result); - inc(cnt); - end; + IF NextPrime(Result) then + inc(cnt) + else + Break; end; procedure ShowPrimes(loLmt,HiLmt: NativeInt); @@ -361,10 +460,13 @@ Begin exit; p1 := InitRecPrime(loLmt); while p1.rpPrime < LoLmt do - NextPrime(p1); + IF Not(NextPrime(p1)) Then + EXIT; + repeat write(p1.rpPrime,' '); - NextPrime(p1); + IF Not(NextPrime(p1)) Then + Break; until p1.rpPrime > HiLmt; writeln; end; @@ -376,13 +478,14 @@ Begin result := 0; IF HiLmt < loLmt then exit; - p1 := InitRecPrime(loLmt); while p1.rpPrime < LoLmt do - NextPrime(p1); + IF Not(NextPrime(p1)) Then + EXIT; repeat inc(result); - NextPrime(p1); + IF Not(NextPrime(p1)) Then + Break; until p1.rpPrime > HiLmt; end; @@ -413,7 +516,7 @@ Begin {next prime} inc(svPos); inc(p,2*(DiffFld[prPos]+1)); - if NOT((svPos and 31) in searchFld[svPos shr 5] )then + if BitSet[svPos AND cAndMask] AND searchFld[svPos DIV cBitSize] <>0 then Begin write(p,' '); dec(n); @@ -426,34 +529,123 @@ Begin writeln; end; +function RvsNumL(var n: Uint64):Uint64; +//reverse and last digit, most of the time n > base therefor repeat +const + base = 10; var + q, c: Int64; +Begin + result := n; + q := 0; + repeat + c:= result div Base; + q := result+ (q-c)*Base; + result := c; + until result < Base; + n := q*Base+result; +end; + +function IsEmirp(n:Uint64):boolean; +var + lastDgt:NativeUint; + ofs: NativeUint; + seg : Uint64; +Begin + seg := n; + lastDgt:= RvsNumL(n); + result:= false; + IF (seg = n) OR (n> MaxUpperLimit) then + EXIT; + + IF lastDgt in [1,3,7,9] then + Begin + seg := n div cMaxZahl; + ofs := n-seg* cMaxzahl;//m mod cMaxZahl + IF (Number[ofs] <> 0) OR (ofs=1) then + begin + seg := seg *cRepFldLen+number[ofs]; + result := BitSet[seg AND cAndMask] AND searchFld[seg DIV cBitSize] <> 0; + end + end; +end; + +procedure GetEmirps(loLmt,HiLmt: Uint64); +var + p1 :tRecPrime; + cnt: NativeUint; +Begin + cnt := 0; + IF HiLmt < loLmt then + exit; + IF loLmt > MaxUpperLimit then + Exit; + IF HiLmt > MaxUpperLimit then + HiLmt := MaxUpperLimit; + + p1 := InitRecPrime(loLmt); + while p1.rpPrime < LoLmt do + IF Not(NextPrime(p1)) Then + EXIT; + + repeat + if isEmirp(p1.rpPrime) then + inc(cnt); + iF not(NextPrime(p1)) then + BREAK; + until p1.rpPrime > HiLmt; + + write(cnt:10); +end; + +var + T1,T0: TDateTime; Anzahl :Uint64; - i : NativeUint; + i,j : Uint64; + n : LongInt; Begin + T0 := now; 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 + T1 := now; + writeln(' '); + Writeln('time for sieving ',FormatDateTime('NN:SS.ZZZ',T1-T0)); + Anzahl := BIS; + For n := MaxPos DIV cBitSize-1 downto 0 do + inc(Anzahl,PopCnt(NativeUint(searchFld[n]))); + n := MaxPos AND cAndMask; + IF n >0 then Begin - IF Not(i in searchFld[MaxPos shr 5]) then - inc(Anzahl); - dec(i); + dec(n); + repeat + IF BitSet[n] AND searchFld[MaxPos DIV cBitSize] <> 0 then + inc(Anzahl); + dec(n); + until n< 0; end; -// Writeln('Bis ',MaxZahl,' sind es ',Anzahl,' Primzahlen'); + + Writeln('there are ',Anzahl,' primes til ',MaxUpperLimit); WriteCntSmallPrimes(20); - write('Primes between 100 and 150: '); + write('primes between 100 and 150: '); ShowPrimes(100,150); - write('Number of primes between 7700 and 8000 '); + write('count 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; + until i*25 > MaxUpperLimit; + + writeln; + writeln('Count Emirps'); + j := 10; + repeat + writeln(j:10); + GetEmirps( j, j+j-1);//10..00->19..99 + GetEmirps(3*j,3*j+j-1);//30..00->39..99 + GetEmirps(7*j,7*j+j-1);//70..00->79..99 + GetEmirps(9*j,9*j+j-1);//90..00->99..99 + writeln; + j:=j*10; + until j >= MaxUpperLimit; + 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 index 8e6a2ff716..2d7108629e 100644 --- a/Task/Extensible-prime-generator/Perl-6/extensible-prime-generator.pl6 +++ b/Task/Extensible-prime-generator/Perl-6/extensible-prime-generator.pl6 @@ -1,4 +1,4 @@ -my @primes := gather for 1 .. * { .take if $_.is-prime } +my @primes = lazy 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", ', ')}]"; diff --git a/Task/Extensible-prime-generator/Python/extensible-prime-generator-3.py b/Task/Extensible-prime-generator/Python/extensible-prime-generator-3.py new file mode 100644 index 0000000000..603d515987 --- /dev/null +++ b/Task/Extensible-prime-generator/Python/extensible-prime-generator-3.py @@ -0,0 +1,35 @@ +def wsieve(): # ideone.com/mqO25A + wh11 = [ 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] + cs = accumulate( chain( [11], cycle( wh11))) + yield( next( cs)) # cf. ideone.com/WFv4f + ps = wsieve() # codereview.stackexchange.com/q/92365/9064 + p = next(ps) # 11 stackoverflow.com/q/30553925/849891 + psq = p*p # 121 + D = dict( zip( accumulate( chain( [0], wh11)), count(0))) # start from + mults = {} + for c in cs: + if c in mults: + wheel = mults.pop(c) + elif c < psq: + yield c ; continue + else: # c==psq: map (p*) (roll wh from p) = roll (wh*p) from (p*p) + x = [p*d for d in wh11] + i = D[ (p-11) % 210] + wheel = accumulate( chain( [psq+x[i]], cycle( x[i+1:] + x[:i+1]))) + p = next(ps) ; psq = p*p + for m in wheel: + if not m in mults: + break + mults[m] = wheel + +def primes(): + yield from (2, 3, 5, 7) + yield from wsieve() + +print( list( islice( primes(), 0, 20))) +print( list( takewhile( lambda x: x<150, + dropwhile( lambda x: x<100, primes())))) +print( len( list( takewhile( lambda x: x<8000, + dropwhile( lambda x: x<7700, primes()))))) +print( list( islice( primes(), 10000-1, 10000))[0]) diff --git a/Task/Extreme-floating-point-values/J/extreme-floating-point-values-1.j b/Task/Extreme-floating-point-values/J/extreme-floating-point-values-1.j index 73147cab41..4c7736d3fa 100644 --- a/Task/Extreme-floating-point-values/J/extreme-floating-point-values-1.j +++ b/Task/Extreme-floating-point-values/J/extreme-floating-point-values-1.j @@ -1,4 +1,4 @@ Inf=: _ NegInf=: __ - NB. Negative zero cannot be represented in J. + NB. Negative zero cannot be represented in J to be distinct from 0. NaN=. _. diff --git a/Task/Factorial/ALGOL-W/factorial.alg b/Task/Factorial/ALGOL-W/factorial.alg new file mode 100644 index 0000000000..d52282365a --- /dev/null +++ b/Task/Factorial/ALGOL-W/factorial.alg @@ -0,0 +1,15 @@ +begin + % computes factorial n iteratively % + integer procedure factorial( integer value n ) ; + if n < 2 + then 1 + else begin + integer f; + f := 2; + for i := 3 until n do f := f * i; + f + end factorial ; + + for t := 0 until 10 do write( "factorial: ", t, factorial( t ) ); + +end. diff --git a/Task/Factorial/ATS/factorial-1.ats b/Task/Factorial/ATS/factorial-1.ats new file mode 100644 index 0000000000..02914a4dba --- /dev/null +++ b/Task/Factorial/ATS/factorial-1.ats @@ -0,0 +1,10 @@ +fun +fact +( + n: int +) : int = res where +{ + var n: int = n + var res: int = 1 + val () = while (n > 0) (res := res * n; n := n - 1) +} diff --git a/Task/Factorial/ATS/factorial-2.ats b/Task/Factorial/ATS/factorial-2.ats new file mode 100644 index 0000000000..04792d09fd --- /dev/null +++ b/Task/Factorial/ATS/factorial-2.ats @@ -0,0 +1,5 @@ +fun +factorial + (n:int): int = + if n > 0 then n * factorial(n-1) else 1 +// end of [factorial] diff --git a/Task/Factorial/ATS/factorial-3.ats b/Task/Factorial/ATS/factorial-3.ats new file mode 100644 index 0000000000..db235be993 --- /dev/null +++ b/Task/Factorial/ATS/factorial-3.ats @@ -0,0 +1,8 @@ +fun +factorial + (n:int): int = let + fun loop(n: int, res: int): int = + if n > 0 then loop(n-1, n*res) else res +in + loop(n, 1) +end // end of [factorial] diff --git a/Task/Factorial/Elixir/factorial.elixir b/Task/Factorial/Elixir/factorial.elixir index 7ff6cee4ac..95baee4e0b 100644 --- a/Task/Factorial/Elixir/factorial.elixir +++ b/Task/Factorial/Elixir/factorial.elixir @@ -4,11 +4,12 @@ defmodule Factorial do def fac(n) when n > 0, do: n * fac(n - 1) # Tail recursive function + def fac_tail(0), do: 1 def fac_tail(n), do: fac_tail(n, 1) - def fac_tail(0, acc), do: acc - def fac_tail(n, acc) when n > 0, do: fac_tail(n - 1, acc * n) + def fac_tail(1, acc), do: acc + def fac_tail(n, acc) when n > 1, do: fac_tail(n - 1, acc * n) # Using Enumeration features - def fac_reduce(0), do: 0 + def fac_reduce(0), do: 1 def fac_reduce(n) when n > 0, do: Enum.reduce(1..n, 1, &*/2) end diff --git a/Task/Factorial/Emacs-Lisp/factorial-2.l b/Task/Factorial/Emacs-Lisp/factorial-2.l index b7d69a4dfa..69ad879be5 100644 --- a/Task/Factorial/Emacs-Lisp/factorial-2.l +++ b/Task/Factorial/Emacs-Lisp/factorial-2.l @@ -1,4 +1 @@ -(require 'calc) -(calc-eval "fact(30)") -=> -"265252859812191058636308480000000" +(defun fact (n) (apply '* (number-sequence 1 n))) diff --git a/Task/Factorial/Emacs-Lisp/factorial-3.l b/Task/Factorial/Emacs-Lisp/factorial-3.l new file mode 100644 index 0000000000..b7d69a4dfa --- /dev/null +++ b/Task/Factorial/Emacs-Lisp/factorial-3.l @@ -0,0 +1,4 @@ +(require 'calc) +(calc-eval "fact(30)") +=> +"265252859812191058636308480000000" diff --git a/Task/Factorial/JavaScript/factorial-1.js b/Task/Factorial/JavaScript/factorial-1.js index f94f8ecd87..2a3e0d135c 100644 --- a/Task/Factorial/JavaScript/factorial-1.js +++ b/Task/Factorial/JavaScript/factorial-1.js @@ -1,7 +1,12 @@ function factorial(n) { - var x = 1; - for (var i = 2; i <= n; i++) { - x *= i; - } - return x; + //check our edge case + if (n < 0) { throw "Number must be non-negative"; } + + var sum = 1; + //we skip zero and one since both are 1 and are identity + while (n > 1) { + sum *= n; + n -= 1; + } + return sum; } diff --git a/Task/Factorial/JavaScript/factorial-2.js b/Task/Factorial/JavaScript/factorial-2.js index 9035ce0b2e..a44b4b5f42 100644 --- a/Task/Factorial/JavaScript/factorial-2.js +++ b/Task/Factorial/JavaScript/factorial-2.js @@ -1,3 +1 @@ -function factorial(n) { - return n < 2 ? 1 : n * factorial(n - 1); -} +var factorial = n => (n < 2) ? 1 : n * factorial(n - 1); diff --git a/Task/Factorial/Perl-6/factorial-2.pl6 b/Task/Factorial/Perl-6/factorial-2.pl6 index 91166a09b9..71ed1679e6 100644 --- a/Task/Factorial/Perl-6/factorial-2.pl6 +++ b/Task/Factorial/Perl-6/factorial-2.pl6 @@ -1,2 +1,2 @@ -constant fact = 1, [\*] 1..*; +constant fact = 1, |[\*] 1..*; say fact[5] diff --git a/Task/Factorial/Ruby/factorial.rb b/Task/Factorial/Ruby/factorial.rb index 17350ea554..011260aec2 100644 --- a/Task/Factorial/Ruby/factorial.rb +++ b/Task/Factorial/Ruby/factorial.rb @@ -21,7 +21,7 @@ def factorial_inject(n) # Iterative with Range#reduce, requires Ruby 1.8.7 def factorial_reduce(n) - (1..n).reduce(:*) + (2..n).reduce(1, :*) end diff --git a/Task/Factorial/Rust/factorial.rust b/Task/Factorial/Rust/factorial.rust index 35f7ae7c37..02a5170c41 100644 --- a/Task/Factorial/Rust/factorial.rust +++ b/Task/Factorial/Rust/factorial.rust @@ -1,19 +1,19 @@ -fn factorial_recursive (n: uint) -> uint { - match n { - 0 => 1, - _ => n * factorial_recursive(n-1) - } +fn factorial_recursive (n: u64) -> u64 { + match n { + 0 => 1, + _ => n * factorial_recursive(n-1) + } } -fn factorial_iterative(n: uint) -> uint { - range(1u, n+1).fold(1, |p, t| p * t) +fn factorial_iterative(n: u64) -> u64 { + (1..n+1).fold(1, |p, n| p*n) } fn main () { - for i in range(1u, 10u) { - println!("{}", factorial_recursive(i)) - } - for i in range(1u, 10u) { - println!("{}", factorial_iterative(i)) - } + for i in 1..10 { + println!("{}", factorial_recursive(i)) + } + for i in 1..10 { + println!("{}", factorial_iterative(i)) + } } diff --git a/Task/Factorial/Self/factorial-1.self b/Task/Factorial/Self/factorial-1.self new file mode 100644 index 0000000000..c7dad66ec9 --- /dev/null +++ b/Task/Factorial/Self/factorial-1.self @@ -0,0 +1 @@ +n factorial diff --git a/Task/Factorial/Self/factorial-2.self b/Task/Factorial/Self/factorial-2.self new file mode 100644 index 0000000000..507a0a5bd4 --- /dev/null +++ b/Task/Factorial/Self/factorial-2.self @@ -0,0 +1 @@ +factorial: n = (|r <- 1| 1 to: n + 1 Do: [|:i| r: r * i]. r) diff --git a/Task/Factorial/Self/factorial-3.self b/Task/Factorial/Self/factorial-3.self new file mode 100644 index 0000000000..8936eb943c --- /dev/null +++ b/Task/Factorial/Self/factorial-3.self @@ -0,0 +1 @@ +factorial: n = (n <= 1 ifTrue: 1 False: [n * (factorial: n predecessor)]) diff --git a/Task/Factorial/Self/factorial-4.self b/Task/Factorial/Self/factorial-4.self new file mode 100644 index 0000000000..f7c900376f --- /dev/null +++ b/Task/Factorial/Self/factorial-4.self @@ -0,0 +1 @@ +factorial: n = (((vector copySize: n) mapBy: [|:e. :i| i + 1]) product) diff --git a/Task/Factors-of-a-Mersenne-number/360-Assembly/factors-of-a-mersenne-number.360 b/Task/Factors-of-a-Mersenne-number/360-Assembly/factors-of-a-mersenne-number.360 new file mode 100644 index 0000000000..feee8c3e4a --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/360-Assembly/factors-of-a-mersenne-number.360 @@ -0,0 +1,90 @@ +* Factors of a Mersenne number 11/09/2015 +MERSENNE CSECT + USING MERSENNE,R15 + MVC Q,=F'929' q=929 (M929=2**929-1) + LA R6,1 k=1 +LOOPK C R6,=F'1048576' do k=1 to 2**20 + BNL ELOOPK + LR R5,R6 k + M R4,Q *q + SLA R5,1 *2 by shift left 1 + LA R5,1(R5) +1 + ST R5,P p=k*q*2+1 + L R2,P p + N R2,=F'7' p&7 + C R2,=F'1' if ((p&7)=1) p='*001' + BE OK + C R2,=F'7' or if ((p&7)=7) p='*111' + BNE NOTOK +OK MVI PRIME,X'00' then prime=false is prime? + LA R2,2 loop count=2 + LA R1,2 j=2 and after j=3 +J2J3 L R4,P p + SRDA R4,32 r4>>r5 + DR R4,R1 p/j + LTR R4,R4 if p//j=0 + BZ NOTPRIME then goto notprime + LA R1,1(R1) j=j+1 + BCT R2,J2J3 + LA R7,5 d=5 +WHILED LR R5,R7 d + MR R4,R7 *d + C R5,P do while(d*d<=p) + BH EWHILED + LA R2,2 loop count=2 + LA R1,2 j=2 and after j=4 +J2J4 L R4,P p + SRDA R4,32 r4>>r5 + DR R4,R7 /d + LTR R4,R4 if p//d=0 + BZ NOTPRIME then goto notprime + AR R7,R1 d=d+j + LA R1,2(R1) j=j+2 + BCT R2,J2J4 + B WHILED +EWHILED MVI PRIME,X'01' prime=true so is prime +NOTPRIME L R8,Q i=q + MVC Y,=F'1' y=1 + MVC Z,=F'2' z=2 +WHILEI LTR R8,R8 do while(i^=0) + BZ EWHILEI + ST R8,PG i + TM PG+3,B'00000001' if first bit of i not 1 + BZ NOTFIRST + L R5,Y y + M R4,Z *z + LA R4,0 + D R4,P /p + ST R4,Y y=(y*z)//p +NOTFIRST L R5,Z z + M R4,Z *z + LA R4,0 + D R4,P /p + ST R4,Z z=(z*z)//p + SRA R8,1 i=i/2 by shift right 1 + B WHILEI +EWHILEI CLI PRIME,X'01' if prime + BNE NOTOK + CLC Y,=F'1' and if y=1 + BNE NOTOK + MVC FACTOR,P then factor=p + B OKFACTOR +NOTOK LA R6,1(R6) k=k+1 + B LOOPK +ELOOPK MVC FACTOR,=F'0' factor=0 +OKFACTOR L R1,Q + XDECO R1,PG edit q + L R1,FACTOR + XDECO R1,PG+12 edit factor + XPRNT PG,24 print + XR R15,R15 + BR R14 +PRIME DS X flag for prime +Q DS F +P DS F +Y DS F +Z DS F +FACTOR DS F a factor of q +PG DS CL24 buffer + YREGS + END MERSENNE diff --git a/Task/Factors-of-a-Mersenne-number/Erlang/factors-of-a-mersenne-number.erl b/Task/Factors-of-a-Mersenne-number/Erlang/factors-of-a-mersenne-number.erl new file mode 100644 index 0000000000..2945c72c1c --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Erlang/factors-of-a-mersenne-number.erl @@ -0,0 +1,42 @@ +-module(mersene2). +-export([prime/1,modpow/3,mf/1]). + +mf(P) -> merseneFactor(P,math:sqrt(math:pow(2,P)-1),2). + +merseneFactor(P,Limit,Acc) when Acc >= Limit -> io:write("None found"); +merseneFactor(P,Limit,Acc) -> + Q = 2 * P * Acc + 1, + Isprime = prime(Q), + Mod = modpow(2,P,Q), + + if + Isprime == false -> + merseneFactor(P,Limit,Acc+1); + + Q rem 8 =/= 1 andalso Q rem 8 =/= 7 -> + merseneFactor(P,Limit,Acc+1); + + Mod == 1 -> + io:format("M~w is composite with Factor: ~w~n",[P,Q]); + + true -> merseneFactor(P,Limit,Acc+1) + end. + +modpow(B, E, M) -> modpow(B, E, M, 1). + +modpow(_B, E, _M, R) when E =< 0 -> R; +modpow(B, E, M, R) -> + R1 = case E band 1 =:= 1 of + true -> (R * B) rem M; + false -> R + end, + modpow( (B*B) rem M, E bsr 1, M, R1). + +prime(N) -> divisors(N, N-1). + +divisors(N, 1) -> true; +divisors(N, C) -> + case N rem C =:= 0 of + true -> false; + false -> divisors(N, C-1) + end. diff --git a/Task/Factors-of-a-Mersenne-number/Perl-6/factors-of-a-mersenne-number.pl6 b/Task/Factors-of-a-Mersenne-number/Perl-6/factors-of-a-mersenne-number.pl6 index 1f4093587d..c2aa371888 100644 --- a/Task/Factors-of-a-Mersenne-number/Perl-6/factors-of-a-mersenne-number.pl6 +++ b/Task/Factors-of-a-Mersenne-number/Perl-6/factors-of-a-mersenne-number.pl6 @@ -1,4 +1,4 @@ -my @primes := 2, 3, -> $n is copy { +my @primes = 2, 3, -> $n is copy { repeat { $n += 2 } until $n %% none do for @primes -> $p { last if $p > sqrt($n); $p; @@ -31,7 +31,7 @@ sub mtest($bits, $p) { $sq == 1; } -for 2 .. 60, 929 -> $m { +for flat 2 .. 60, 929 -> $m { next unless is_prime($m); my $f = 0; my $x = 2**$m - 1; diff --git a/Task/Factors-of-a-Mersenne-number/PicoLisp/factors-of-a-mersenne-number.l b/Task/Factors-of-a-Mersenne-number/PicoLisp/factors-of-a-mersenne-number.l index 9d784e6821..a322372f45 100644 --- a/Task/Factors-of-a-Mersenne-number/PicoLisp/factors-of-a-mersenne-number.l +++ b/Task/Factors-of-a-Mersenne-number/PicoLisp/factors-of-a-mersenne-number.l @@ -13,9 +13,10 @@ (and (> N 1) (bit? 1 N) - (for (D 3 T (+ D 2)) - (T (> D (sqrt N)) T) - (T (=0 (% N D)) NIL) ) ) ) ) + (let S (sqrt N) + (for (D 3 T (+ D 2)) + (T (> D S) T) + (T (=0 (% N D)) NIL) ) ) ) ) ) (de mFactor (P) (let (Lim (sqrt (dec (** 2 P))) K 0 Q) diff --git a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx index 584ab4f0a4..b8d47817ec 100644 --- a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx +++ b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx @@ -1,39 +1,38 @@ -/*REXX program uses exponent-&-mod operator to test possible Mersenne #s*/ -numeric digits 500 /*we're dealing with some biggies*/ +/*REXX program uses exponent─&─mod operator to test possible Mersenne numbers.*/ +numeric digits 500 /*dealing with some ginormous numbers. */ - do j=1 to 61; z=j /*when J=61, it turns into 929. */ - if z==61 then z=929 /*switcheroo, 61 turns into 929.*/ - if \isPrime(z) then iterate /*if not prime, keep plugging. */ - r=testM(z) /*not, give it the 3rd degree. */ - if r==0 then say right('M'z,8) "──────── is a Mersenne prime." - else say right('M'z,48) "is composite, a factor:" r + do j=1 to 61; z=j /*when J reaches 61, it turns into 929.*/ + if z==61 then z=929 /*now, a switcheroo, 61 turns into 929.*/ + if \isPrime(z) then iterate /*if Z isn't a prime, keep plugging.*/ + r=testM(z) /*If Z is prime, give Z the 3rd degree.*/ + if r==0 then say right('M'z,8) "──────── is a Mersenne prime." + else say right('M'z,48) "is composite, a factor:" r end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────MODPOW subroutine───────────────────*/ -modPow: procedure; parse arg base,n,div; sq=1 -bits=x2b(d2x(n))+0 /*dec──► hex──► binary, normalize*/ - do until bits==''; sq=sq ** 2 - if left(bits,1) then sq=sq * base // div - bits=substr(bits,2) - end /*until*/ -return sq -/*─────────────────────────────────────ISPRIME subroutine───────────────*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ isPrime: procedure; parse arg x; if wordpos(x,'2 3 5 7')\==0 then return 1 -if x<11 then return 0; if x//2==0 then return 0; if x//3==0 then return 0 -do j=5 by 6; if x//j==0|x//(j+2)==0 then return 0; if j*j>x then return 1;end -/*─────────────────────────────────────ISQRT subroutine─────────────────*/ -iSqrt: procedure; parse arg x; r=0; q=1; do while q<=x; q=q*4; end -do while q>1; q=q%4;_=x-r-q;r=r%2;if _>=0 then do;x=_;r=r+q;end;end; return r -/*──────────────────────────────────TESTM subroutine────────────────────*/ -testM: procedure; parse arg x /*test a possible Mersenne prime.*/ -sqroot=iSqrt(2**x) /*iSqrt is: integer square root.*/ - /*───── ─ ── ─ ─ */ - do k=1; q=2*k*x + 1 /* _____ */ - if q>sqroot then leave /*Is q>√(2^x) ? Then we're done*/ - _=q // 8 /*perform modulus arithmetic. */ - if _\==1 & _\==7 then iterate /*must be either one or seven. */ - if \isPrime(q) then iterate /*if not prime, keep on trukin'. */ - if modPow(2,x,q)==1 then return q /*Not a prime? Return a factor.*/ - end /*k*/ - -return 0 /*it's a Mersenne prime, by gum. */ + if x<11 then return 0; if x//2==0 | x//3 ==0 then return 0 + do j=5 by 6; if x//j==0 | x//(j+2)==0 then return 0 + if j*j>x then return 1 + end /*j*/ +/*────────────────────────────────────────────────────────────────────────────*/ +iSqrt: procedure; parse arg x; r=0; q=1; do while q<=x; q=q*4; end + do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end;end + return r +/*────────────────────────────────────────────────────────────────────────────*/ +modPow: procedure; parse arg base,n,div; sq=1; $=x2b(d2x(n))+0 + do until $==''; sq=sq**2 + if left($,1) then sq=sq*base//div; $=substr($,2) + end /*until ··· */ + return sq +/*────────────────────────────────────────────────────────────────────────────*/ +testM: procedure; parse arg x /*test a possible Mersenne prime*/ + sqRoot=iSqrt(2**x) /*iSqrt is: integer square root*/ + /*───── ─ ── ─ ─ */ + do k=1; q=2*k*x + 1 /* _____ */ + if q>sqRoot then return 0 /*Is q>√(2^x)? A Mersenne prime*/ + _=q // 8 /*obtain the remainder when ÷ 8.*/ + if _\==1 & _\==7 then iterate /*must be either one or seven*/ + if \isPrime(q) then iterate /*Q ¬prime? Then keep on looking*/ + if modPow(2,x,q)==1 then return q /*Not a prime? Return a factor.*/ + end /*k*/ diff --git a/Task/Factors-of-a-Mersenne-number/TI-83-BASIC/factors-of-a-mersenne-number-1.ti-83 b/Task/Factors-of-a-Mersenne-number/TI-83-BASIC/factors-of-a-mersenne-number-1.ti-83 new file mode 100644 index 0000000000..e7357afe55 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/TI-83-BASIC/factors-of-a-mersenne-number-1.ti-83 @@ -0,0 +1 @@ +remainder(A,B) equivalent to iPart(B*fPart(A/B)) diff --git a/Task/Factors-of-a-Mersenne-number/TI-83-BASIC/factors-of-a-mersenne-number-2.ti-83 b/Task/Factors-of-a-Mersenne-number/TI-83-BASIC/factors-of-a-mersenne-number-2.ti-83 new file mode 100644 index 0000000000..7873b9e2a0 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/TI-83-BASIC/factors-of-a-mersenne-number-2.ti-83 @@ -0,0 +1,33 @@ +Prompt Q +1→K:0→T +While K≤2^20 and T=0 +2KQ+1→P +remainder(P,8)→W +If W=1 or W=7 +Then +0→E:0→M +If remainder(P,2)=0:1→M +If remainder(P,3)=0:1→M +5→D +While M=0 and DD≤P +If remainder(P,D)=0:1→M +D+2→D +If remainder(P,D)=0:1→M +D+4→D +End +If M=0:1→E +Q→I:1→Y:2→Z +While I≠0 +If remainder(I,2)=1:remainder(YZ,P)→Y +remainder(ZZ,P)→Z +iPart(I/2)→I +End +If E=1 and Y=1 +Then +P→F:1→T +End +End +K+1→K +End +If T=0:0→F +Disp Q,F diff --git a/Task/Factors-of-a-Mersenne-number/VBScript/factors-of-a-mersenne-number.vb b/Task/Factors-of-a-Mersenne-number/VBScript/factors-of-a-mersenne-number.vb new file mode 100644 index 0000000000..ebd698dd12 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/VBScript/factors-of-a-mersenne-number.vb @@ -0,0 +1,63 @@ +' Factors of a Mersenne number + for i=1 to 59 + z=i + if z=59 then z=929 ':) 61 turns into 929. + if isPrime(z) then + r=testM(z) + zz=left("M" & z & space(4),4) + if r=0 then + Wscript.echo zz & " prime." + else + Wscript.echo zz & " not prime, a factor: " & r + end if + end if + next + +function modPow(base,n,div) + dim i,y,z + i = n : y = 1 : z = base + do while i + if i and 1 then y = (y * z) mod div + z = (z * z) mod div + i = i \ 2 + loop + modPow= y +end function + +function isPrime(x) + dim i + if x=2 or x=3 or _ + x=5 or x=7 _ + then isPrime=1: exit function + if x<11 then isPrime=0: exit function + if x mod 2=0 then isPrime=0: exit function + if x mod 3=0 then isPrime=0: exit function + i=5 + do + if (x mod i) =0 or _ + (x mod (i+2)) =0 _ + then isPrime=0: exit function + if i*i>x then isPrime=1: exit function + i=i+6 + loop +end function + +function testM(x) + dim sqroot,k,q + sqroot=Sqr(2^x) + k=1 + do + q=2*k*x+1 + if q>sqroot then exit do + if (q and 7)=1 or (q and 7)=7 then + if isPrime(q) then + if modPow(2,x,q)=1 then + testM=q + exit function + end if + end if + end if + k=k+1 + loop + testM=0 +end function diff --git a/Task/Factors-of-a-Mersenne-number/Visual-Basic/factors-of-a-mersenne-number.vb b/Task/Factors-of-a-Mersenne-number/Visual-Basic/factors-of-a-mersenne-number.vb new file mode 100644 index 0000000000..ec849407ee --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Visual-Basic/factors-of-a-mersenne-number.vb @@ -0,0 +1,36 @@ +Sub mersenne() + Dim q As Long, k As Long, p As Long, d As Long + Dim factor As Long, i As Long, y As Long, z As Long + Dim prime As Boolean + q = 929 'input value + For k = 1 To 1048576 '2**20 + p = 2 * k * q + 1 + If (p And 7) = 1 Or (p And 7) = 7 Then 'p=*001 or p=*111 + 'p is prime? + prime = False + If p Mod 2 = 0 Then GoTo notprime + If p Mod 3 = 0 Then GoTo notprime + d = 5 + Do While d * d <= p + If p Mod d = 0 Then GoTo notprime + d = d + 2 + If p Mod d = 0 Then GoTo notprime + d = d + 4 + Loop + prime = True + notprime: 'modpow + i = q: y = 1: z = 2 + Do While i 'i <> 0 + On Error GoTo okfactor + If i And 1 Then y = (y * z) Mod p 'test first bit + z = (z * z) Mod p + On Error GoTo 0 + i = i \ 2 + Loop + If prime And y = 1 Then factor = p: GoTo okfactor + End If + Next k + factor = 0 +okfactor: + Debug.Print "M" & q, "factor=" & factor +End Sub diff --git a/Task/Factors-of-an-integer/00DESCRIPTION b/Task/Factors-of-an-integer/00DESCRIPTION index b402dcfc33..aa3f2090df 100644 --- a/Task/Factors-of-an-integer/00DESCRIPTION +++ b/Task/Factors-of-an-integer/00DESCRIPTION @@ -1,7 +1,10 @@ -{{basic data operation}} + {{basic data operation}} [[Category:Arithmetic operations]] [[Category:Mathematical_operations]] -Compute the [[wp:Divisor|factors]] of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result (though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases). Note that even prime numbers will have at least two factors; ‘1’ and themselves. +Compute the [[wp:Divisor|factors]] of a positive integer. +These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. +(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases). +Note that every prime number has two factors; ‘1’ and itself. See also: * [[Prime decomposition]] diff --git a/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer.coffee b/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer.coffee new file mode 100644 index 0000000000..50fa310a15 --- /dev/null +++ b/Task/Factors-of-an-integer/CoffeeScript/factors-of-an-integer.coffee @@ -0,0 +1,59 @@ +# Reference implementation for finding factors is slow, but hopefully +# robust--we'll use it to verify the more complicated (but hopefully faster) +# algorithm. +slow_factors = (n) -> + (i for i in [1..n] when n % i == 0) + +# The rest of this code does two optimizations: +# 1) When you find a prime factor, divide it out of n (smallest_prime_factor). +# 2) Find the prime factorization first, then compute composite factors from those. + +smallest_prime_factor = (n) -> + for i in [2..n] + return n if i*i > n + return i if n % i == 0 + +prime_factors = (n) -> + return {} if n == 1 + spf = smallest_prime_factor n + result = prime_factors(n / spf) + result[spf] or= 0 + result[spf] += 1 + result + +fast_factors = (n) -> + prime_hash = prime_factors n + exponents = [] + for p of prime_hash + exponents.push + p: p + exp: 0 + result = [] + while true + factor = 1 + for obj in exponents + factor *= Math.pow obj.p, obj.exp + result.push factor + break if factor == n + # roll the odometer + for obj, i in exponents + if obj.exp < prime_hash[obj.p] + obj.exp += 1 + break + else + obj.exp = 0 + + return result.sort (a, b) -> a - b + +verify_factors = (factors, n) -> + expected_result = slow_factors n + throw Error("wrong length") if factors.length != expected_result.length + for factor, i in expected_result + console.log Error("wrong value") if factors[i] != factor + + +for n in [1, 3, 4, 8, 24, 37, 1001, 11111111111, 99999999999] + factors = fast_factors n + console.log n, factors + if n < 1000000 + verify_factors factors, n diff --git a/Task/Factors-of-an-integer/Common-Lisp/factors-of-an-integer.lisp b/Task/Factors-of-an-integer/Common-Lisp/factors-of-an-integer.lisp index 3ab77c0701..e736b92f8e 100644 --- a/Task/Factors-of-an-integer/Common-Lisp/factors-of-an-integer.lisp +++ b/Task/Factors-of-an-integer/Common-Lisp/factors-of-an-integer.lisp @@ -1,9 +1,9 @@ (defun factors (n &aux (lows '()) (highs '())) - (do ((limit (isqrt n)) (factor 1 (1+ factor))) + (do ((limit (1+ (isqrt n))) (factor 1 (1+ factor))) ((= factor limit) (when (= n (* limit limit)) (push limit highs)) - (nreconc lows highs)) + (remove-duplicates (nreconc lows highs))) (multiple-value-bind (quotient remainder) (floor n factor) (when (zerop remainder) (push factor lows) diff --git a/Task/Factors-of-an-integer/Elixir/factors-of-an-integer.elixir b/Task/Factors-of-an-integer/Elixir/factors-of-an-integer.elixir new file mode 100644 index 0000000000..517619497c --- /dev/null +++ b/Task/Factors-of-an-integer/Elixir/factors-of-an-integer.elixir @@ -0,0 +1,10 @@ +defmodule RC do + def factor(1), do: [1] + def factor(n) do + (for i <- 1..div(n,2), rem(n,i)==0, do: i) ++ [n] + end +end + +Enum.each([45, 53, 64], fn n -> + IO.puts "#{n}: #{inspect RC.factor(n)}" +end) diff --git a/Task/Factors-of-an-integer/Erlang/factors-of-an-integer.erl b/Task/Factors-of-an-integer/Erlang/factors-of-an-integer-1.erl similarity index 100% rename from Task/Factors-of-an-integer/Erlang/factors-of-an-integer.erl rename to Task/Factors-of-an-integer/Erlang/factors-of-an-integer-1.erl diff --git a/Task/Factors-of-an-integer/Erlang/factors-of-an-integer-2.erl b/Task/Factors-of-an-integer/Erlang/factors-of-an-integer-2.erl new file mode 100644 index 0000000000..a86a153c9f --- /dev/null +++ b/Task/Factors-of-an-integer/Erlang/factors-of-an-integer-2.erl @@ -0,0 +1,17 @@ +-module(divs). +-export([divs/1]). + +divs(0) -> []; +divs(1) -> []; +divs(N) -> lists:sort(divisors(1,N))++[N]. + +divisors(1,N) -> + [1] ++ divisors(2,N,math:sqrt(N)). + +divisors(K,_N,Q) when K > Q -> []; +divisors(K,N,_Q) when N rem K =/= 0 -> + [] ++ divisors(K+1,N,math:sqrt(N)); +divisors(K,N,_Q) when K * K == N -> + [K] ++ divisors(K+1,N,math:sqrt(N)); +divisors(K,N,_Q) -> + [K, N div K] ++ divisors(K+1,N,math:sqrt(N)). diff --git a/Task/Factors-of-an-integer/JavaScript/factors-of-an-integer.js b/Task/Factors-of-an-integer/JavaScript/factors-of-an-integer-1.js similarity index 100% rename from Task/Factors-of-an-integer/JavaScript/factors-of-an-integer.js rename to Task/Factors-of-an-integer/JavaScript/factors-of-an-integer-1.js diff --git a/Task/Factors-of-an-integer/JavaScript/factors-of-an-integer-2.js b/Task/Factors-of-an-integer/JavaScript/factors-of-an-integer-2.js new file mode 100644 index 0000000000..6c7cd0e0d2 --- /dev/null +++ b/Task/Factors-of-an-integer/JavaScript/factors-of-an-integer-2.js @@ -0,0 +1,59 @@ +console.log( + (function (lstTest) { + + // INTEGER FACTORS + function integerFactors(n) { + var rRoot = Math.sqrt(n), + intRoot = Math.floor(rRoot), + + lows = range(1, intRoot).filter(function (x) { + return (n % x) === 0; + }); + + // for perfect squares, we can drop the head of the 'highs' list + return lows.concat(lows.map(function (x) { + return n / x; + }).reverse().slice((rRoot === intRoot) | 0)); + } + + // [m .. n] + function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map(function (x, i) { + return m + i; + }); + } + + /*************************** TESTING *****************************/ + + // TABULATION OF RESULTS IN SPACED AND ALIGNED COLUMNS + function alignedTable(lstRows, lngPad, fnAligned) { + var lstColWidths = range(0, lstRows.reduce(function (a, x) { + return x.length > a ? x.length : a; + }, 0) - 1).map(function (iCol) { + return lstRows.reduce(function (a, lst) { + var w = lst[iCol] ? lst[iCol].toString().length : 0; + return (w > a) ? w : a; + }, 0); + }); + + return lstRows.map(function (lstRow) { + return lstRow.map(function (v, i) { + return fnAligned(v, lstColWidths[i] + lngPad); + }).join('') + }).join('\n'); + } + + function alignRight(n, lngWidth) { + var s = n.toString(); + return Array(lngWidth - s.length + 1).join(' ') + s; + } + + // TEST + return '\nintegerFactors(n)\n\n' + alignedTable( + lstTest.map(integerFactors).map(function (x, i) { + return [lstTest[i], '-->'].concat(x); + }), 2, alignRight + ) + '\n'; + + })([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767]) +); diff --git a/Task/Factors-of-an-integer/JavaScript/factors-of-an-integer-3.js b/Task/Factors-of-an-integer/JavaScript/factors-of-an-integer-3.js new file mode 100644 index 0000000000..aadbea12c6 --- /dev/null +++ b/Task/Factors-of-an-integer/JavaScript/factors-of-an-integer-3.js @@ -0,0 +1,12 @@ +integerFactors(n) + + 25 --> 1 5 25 + 45 --> 1 3 5 9 15 45 + 53 --> 1 53 + 64 --> 1 2 4 8 16 32 64 + 100 --> 1 2 4 5 10 20 25 50 100 + 102 --> 1 2 3 6 17 34 51 102 + 120 --> 1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120 + 12345 --> 1 3 5 15 823 2469 4115 12345 + 32766 --> 1 2 3 6 43 86 127 129 254 258 381 762 5461 10922 16383 32766 + 32767 --> 1 7 31 151 217 1057 4681 32767 diff --git a/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx b/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx index d90e12635c..a105698e2c 100644 --- a/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx +++ b/Task/Factors-of-an-integer/REXX/factors-of-an-integer-1.rexx @@ -1,23 +1,24 @@ -/*REXX pgm displays divisors of any (negative/zero/positive) integers.*/ -@.=left('',7); @.1='{unity}'; @.2='[prime]' /*unity & prime tags.*/ -parse arg low high inc . /*get optional args. */ -high=word(high low 20,1); low=word(low 1,1); inc=word(inc 1,1) /*opts*/ -w=length(high)+1; numeric digits max(9,w) /*'nuff digs for // */ -say center('n',1+w) '#divisors' center('divisors',60) /*header. */ -say copies('─',1+w) '─────────' copies('─' ,60) /*separator.*/ +/*REXX program displays divisors of any [negative/zero/positive] integer(s).*/ +parse arg bot top inc . /*optional args.*/ +top=word(top bot 20,1); bot=word(bot 1,1); inc=word(inc 1,1) /*range options.*/ +w=length(high)+1; numeric digits max(9,w); $='∞' /*digits for // */ +@.=left('',7); @.1='{unity}'; @.2='[prime]'; @.$=' {'$"} " /*some literals.*/ +say center('n',1+w) '#divisors' center('divisors',60) /*show a header.*/ +say copies('═',1+w) '═════════' copies('═' ,60) /* " " sep. */ - do n=low to high by inc; divs=divisors(n); #=words(divs); p=@.# - if divs=='infinite' then #='∞'; if n<1 then p=@.. /*handle N<1*/ - say right(n,w)" " center('['#"]",9) "──► " p ' ' divs - end /*n*/ /* [↑] process a range of ints.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────DIVISORS subroutine─────────────────*/ -divisors: procedure; parse arg x; x=abs(x); if x==1 then return 1; b=x -if x==0 then return 'infinite'; odd=x//2 -a=1 /* [↓] use only EVEN|ODD integers*/ - do j=2+odd by 1+odd while j*j x / i Then corresponding_factors = x / i & ", " & corresponding_factors + End If + Next i + If x <> 1 Then Factors = Factors & ", " & corresponding_factors +End Function diff --git a/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp b/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp index 3e7e851d2e..ecdb002975 100644 --- a/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp +++ b/Task/Fast-Fourier-transform/C++/fast-fourier-transform.cpp @@ -7,7 +7,8 @@ const double PI = 3.141592653589793238460; typedef std::complex Complex; typedef std::valarray CArray; -// Cooley–Tukey FFT (in-place) +// Cooley–Tukey FFT (in-place, divide-and-conquer) +// Higher memory requirements and redundancy although more intuitive void fft(CArray& x) { const size_t N = x.size(); @@ -30,6 +31,56 @@ void fft(CArray& x) } } +// Cooley-Tukey FFT (in-place, breadth-first, decimation-in-frequency) +// Better optimized but less intuitive +void fft(CArray &x) +{ + // DFT + unsigned int N = x.size(), k = N, n; + double thetaT = 3.14159265358979323846264338328L / N; + Complex phiT = Complex(cos(thetaT), sin(thetaT)), T; + while (k > 1) + { + n = k; + k >>= 1; + phiT = phiT * phiT; + T = 1.0L; + for (unsigned int l = 0; l < k; l++) + { + for (unsigned int a = l; a < N; a += n) + { + unsigned int b = a + k; + Complex t = x[a] - x[b]; + x[a] += x[b]; + x[b] = t * T; + } + T *= phiT; + } + } + // Decimate + unsigned int m = (unsigned int)log2(N); + for (unsigned int a = 0; a < N; a++) + { + unsigned int b = a; + // Reverse bits + b = (((b & 0xaaaaaaaa) >> 1) | ((b & 0x55555555) << 1)); + b = (((b & 0xcccccccc) >> 2) | ((b & 0x33333333) << 2)); + b = (((b & 0xf0f0f0f0) >> 4) | ((b & 0x0f0f0f0f) << 4)); + b = (((b & 0xff00ff00) >> 8) | ((b & 0x00ff00ff) << 8)); + b = ((b >> 16) | (b << 16)) >> (32 - m); + if (b > a) + { + Complex t = x[a]; + x[a] = x[b]; + x[b] = t; + } + } + //// Normalize (This section make it not working correctly) + //Complex f = 1.0 / sqrt(N); + //for (unsigned int i = 0; i < N; i++) + // x[i] *= f; +} + // inverse fft (in-place) void ifft(CArray& x) { diff --git a/Task/Fast-Fourier-transform/Common-Lisp/fast-fourier-transform.lisp b/Task/Fast-Fourier-transform/Common-Lisp/fast-fourier-transform.lisp new file mode 100644 index 0000000000..0027d8b1df --- /dev/null +++ b/Task/Fast-Fourier-transform/Common-Lisp/fast-fourier-transform.lisp @@ -0,0 +1,14 @@ +(defun fft (x) + (if (<= (length x) 1) x + (let* + ( + (even (fft (loop for i from 0 below (length x) by 2 collect (nth i x)))) + (odd (fft (loop for i from 1 below (length x) by 2 collect (nth i x)))) + (aux (loop for k from 0 below (/ (length x) 2) collect (* (exp (/ (* (complex 0 -2) pi k ) (length x))) (nth k odd)))) + ) + (append (mapcar #'+ even aux) (mapcar #'- even aux)) + ) + ) +) + +(mapcar (lambda (x) (format t "~a~&" x)) (fft '(1 1 1 1 0 0 0 0))) diff --git a/Task/Fast-Fourier-transform/Fortran/fast-fourier-transform.f b/Task/Fast-Fourier-transform/Fortran/fast-fourier-transform.f index a8483aef11..b1154306ae 100644 --- a/Task/Fast-Fourier-transform/Fortran/fast-fourier-transform.f +++ b/Task/Fast-Fourier-transform/Fortran/fast-fourier-transform.f @@ -29,9 +29,7 @@ recursive subroutine fft(x) ! combine do i=1,N/2 - - -t=exp(cmplx(0.0_dp,-2.0_dp*pi*real(i-1,dp)/real(N,dp),KIND=DP))*even(i) + t=exp(cmplx(0.0_dp,-2.0_dp*pi*real(i-1,dp)/real(N,dp),kind=dp))*even(i) x(i) = odd(i) + t x(i+N/2) = odd(i) - t end do diff --git a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 index e044fe05dd..70f41341e2 100644 --- a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 +++ b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 @@ -2,7 +2,7 @@ sub fft { return @_ if @_ == 1; my @evn = fft( @_[0, 2 ... *] ); my @odd = fft( @_[1, 3 ... *] ) Z* - (1, * * cis( 2 * pi / @_ ) ... *); + map &cis, (0, 2 * pi / @_ ... *); return @evn »+« @odd, @evn »-« @odd; } diff --git a/Task/Fast-Fourier-transform/Python/fast-fourier-transform-1.py b/Task/Fast-Fourier-transform/Python/fast-fourier-transform-1.py index ded43e91aa..8fe4b722df 100644 --- a/Task/Fast-Fourier-transform/Python/fast-fourier-transform-1.py +++ b/Task/Fast-Fourier-transform/Python/fast-fourier-transform-1.py @@ -3,8 +3,8 @@ def fft(x): N = len(x) if N <= 1: return x - even = fft2(x[0::2]) - odd = fft2(x[1::2]) + even = fft(x[0::2]) + odd = fft(x[1::2]) T= [exp(-2j*pi*k/N)*odd[k] for k in xrange(N/2)] return [even[k] + T[k] for k in xrange(N/2)] + \ [even[k] - T[k] for k in xrange(N/2)] diff --git a/Task/Fibonacci-n-step-number-sequences/Elixir/fibonacci-n-step-number-sequences.elixir b/Task/Fibonacci-n-step-number-sequences/Elixir/fibonacci-n-step-number-sequences.elixir new file mode 100644 index 0000000000..562bf9a6b3 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Elixir/fibonacci-n-step-number-sequences.elixir @@ -0,0 +1,29 @@ +defmodule RC do + def anynacci(start_sequence, count) do + n = length(start_sequence) + anynacci(Enum.reverse(start_sequence), count-n, n) + end + + def anynacci(seq, 0, _), do: Enum.reverse(seq) + def anynacci(seq, count, n) do + next = Enum.sum(Enum.take(seq, n)) + anynacci([next|seq], count-1, n) + end +end + +IO.inspect RC.anynacci([1,1], 15) + +naccis = [ lucus: [2,1], + fibonacci: [1,1], + tribonacci: [1,1,2], + tetranacci: [1,1,2,4], + pentanacci: [1,1,2,4,8], + hexanacci: [1,1,2,4,8,16], + heptanacci: [1,1,2,4,8,16,32], + octonacci: [1,1,2,4,8,16,32,64], + nonanacci: [1,1,2,4,8,16,32,64,128], + decanacci: [1,1,2,4,8,16,32,64,128,256] ] +Enum.each(naccis, fn {name, list} -> + :io.format("~11s: ", [name]) + IO.inspect RC.anynacci(list, 15) +end) diff --git a/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-1.julia b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-1.julia new file mode 100644 index 0000000000..836c53faa2 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-1.julia @@ -0,0 +1,30 @@ +type NFib{T<:Integer} + n::T + klim::T + seeder::Function +end + +type FState + a::Array{BigInt,1} + adex::Integer + k::Integer +end + +function Base.start{T<:Integer}(nf::NFib{T}) + a = nf.seeder(nf.n) + adex = 1 + k = 1 + return FState(a, adex, k) +end + +function Base.done{T<:Integer}(nf::NFib{T}, fs::FState) + fs.k > nf.klim +end + +function Base.next{T<:Integer}(nf::NFib{T}, fs::FState) + f = sum(fs.a) + fs.a[fs.adex] = f + fs.adex = rem1(fs.adex+1, nf.n) + fs.k += 1 + return (f, fs) +end diff --git a/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-2.julia b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-2.julia new file mode 100644 index 0000000000..acb72585a3 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-2.julia @@ -0,0 +1,9 @@ +function fib_seeder{T<:Integer}(n::T) + a = zeros(BigInt, n) + a[1] = one(BigInt) + return a +end + +function fib{T<:Integer}(n::T, k::T) + NFib(n, k, fib_seeder) +end diff --git a/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-3.julia b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-3.julia new file mode 100644 index 0000000000..256a34a405 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-3.julia @@ -0,0 +1,10 @@ +function luc_rc_seeder{T<:Integer}(n::T) + a = zeros(BigInt, n) + a[1] = 3 + a[2] = -1 + return a +end + +function luc_rc{T<:Integer}(n::T, k::T) + NFib(n, k, luc_rc_seeder) +end diff --git a/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-4.julia b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-4.julia new file mode 100644 index 0000000000..3260f86e14 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-4.julia @@ -0,0 +1,9 @@ +function luc_seeder{T<:Integer}(n::T) + a = -ones(BigInt, n) + a[end] = big(n) + return a +end + +function luc{T<:Integer}(n::T, k::T) + NFib(n, k, luc_seeder) +end diff --git a/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-5.julia b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-5.julia new file mode 100644 index 0000000000..4e4b4387ed --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Julia/fibonacci-n-step-number-sequences-5.julia @@ -0,0 +1,35 @@ +lo = 2 +hi = 10 +klim = 16 + +print("n-step Fibonacci for n = (", lo, ",", hi) +println(") up to k = ", klim, ":") +for i in 2:10 + print(@sprintf("%5d => ", i)) + for j in fib(i, klim) + print(j, " ") + end + println() +end + +println() +print("n-step Rosetta Code Lucas for n = (", lo, ",", hi) +println(") up to k = ", klim, ":") +for i in 2:10 + print(@sprintf("%5d => ", i)) + for j in luc_rc(i, klim) + print(j, " ") + end + println() +end + +println() +print("n-step MathWorld Lucas for n = (", lo, ",", hi) +println(") up to k = ", klim, ":") +for i in 2:10 + print(@sprintf("%5d => ", i)) + for j in luc(i, klim) + print(j, " ") + end + println() +end diff --git a/Task/Fibonacci-n-step-number-sequences/REXX/fibonacci-n-step-number-sequences.rexx b/Task/Fibonacci-n-step-number-sequences/REXX/fibonacci-n-step-number-sequences.rexx index aca60056be..5294ee59eb 100644 --- a/Task/Fibonacci-n-step-number-sequences/REXX/fibonacci-n-step-number-sequences.rexx +++ b/Task/Fibonacci-n-step-number-sequences/REXX/fibonacci-n-step-number-sequences.rexx @@ -1,11 +1,7 @@ -/*REXX program calculates and displays N-step Fibonacci sequences. */ -parse arg FibName values /*allow user to specify which Fib*/ - -if FibName\='' then do /*if specified, show that Fib. */ - call nStepFib FibName, values - exit /*stick a fork in it, we're done.*/ - end - /*nothing given, so show a bunch.*/ +/*REXX program calculates and displays a N-step Fibonacci sequence(s). */ +parse arg FibName values /*allows a Fibonacci name, starter vals*/ +if FibName\='' then do; call nStepFib FibName,values; signal done; end + /* [↓] no args specified, show a bunch*/ call nStepFib 'Lucas' , 2 1 call nStepFib 'fibonacci' , 1 1 call nStepFib 'tribonacci' , 1 1 2 @@ -19,22 +15,21 @@ call nStepFib 'decanacci' , 1 1 2 4 8 16 32 64 128 256 call nStepFib 'undecanacci' , 1 1 2 4 8 16 32 64 128 256 512 call nStepFib 'dodecanacci' , 1 1 2 4 8 16 32 64 128 256 512 1024 call nStepFib '13th-order' , 1 1 2 4 8 16 32 64 128 256 512 1024 2048 -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────NSTEPFIB subroutine─────────────────*/ -nStepFib: procedure; parse arg Fname,vals,m; if m=='' then m=30; L= +done: exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +nStepFib: procedure; parse arg Fname,vals,m; if m=='' then m=30; L= N=words(vals) - do pop=1 for N /*use N initial vals*/ - @.pop=word(vals,pop) /*populate initial #s.*/ - end /*pop*/ - do j=1 for m /*calculate M Fibonacci numbers*/ - if j>N then do; @.j=0 /*inialize the sum. */ - do k=j-N for N /*sum the last N #.s*/ - @.j=@.j+@.k /*add the [N-j]th #.*/ - end /*k*/ - end - L=L @.j /*append this Fib num to the list*/ + do pop=1 for N /*use N initial values. */ + @.pop=word(vals,pop) /*populate initial numbers*/ + end /*pop*/ + do j=1 for m /*calculate M Fib numbers.*/ + if j>N then do; @.j=0 /*initialize the sum to 0.*/ + do k=j-N for N /*sum the last N numbers.*/ + @.j=@.j+@.k /*add the [N-j]th number.*/ + end /*k*/ + end + L=L @.j /*append Fib number──►list*/ end /*j*/ -say right(Fname,11)'[sum'right(N,3) "terms]:" strip(L) '...' /*show #s*/ +say right(Fname,11)'[sum'right(N,3) "terms]:" strip(L) '···' return diff --git a/Task/Fibonacci-n-step-number-sequences/Racket/fibonacci-n-step-number-sequences.rkt b/Task/Fibonacci-n-step-number-sequences/Racket/fibonacci-n-step-number-sequences.rkt index 15012a6e18..44d5fc74f1 100644 --- a/Task/Fibonacci-n-step-number-sequences/Racket/fibonacci-n-step-number-sequences.rkt +++ b/Task/Fibonacci-n-step-number-sequences/Racket/fibonacci-n-step-number-sequences.rkt @@ -1,45 +1,25 @@ #lang racket -;; fib-n : Nat x Nat -> [List Nat] -;; Outputs the first x numbers in the -;; n-step fibonacci sequence -;; n > 1 -(define (fib-n n x) - (cond - [(= x 0) empty] - [(= x 1) '(1)] - [(= x 2) '(1 1)] - [(<= x (add1 n)) (append '(1 1) (build-list (- x 2) (λ (y) (expt 2 (add1 y)))))] - [else (local ((define first-values (append '(1 1) (build-list (- n 1) (λ (x) (expt 2 (add1 x)))))) - (define (add-values lon y acc) - (cond [(= y 0) acc] - [else (add-values (rest lon) (sub1 y) (+ (first lon) acc))])) - (define (acc lon y) - (cond [(= y x) lon] - [else (acc (cons (add-values lon n 0) lon) (add1 y))]))) - (reverse (acc (reverse first-values) (add1 n))))])) -;; fib-list : [List Nat] x Nat -> [List Nat] -;; Given a list of natural numbers, -;; the length of the list becomes the -;; size of the step, and outputs -;; the first x numbers of the sequence -;; (len lon) > 1 -(define (fib-list lon x) - (local ((define step (length lon))) - (cond - [(= x step) lon] - [(< x step) - (local ((define (extract-values lon y) - (cond [(= y 0) empty] - [else (cons (first lon) (extract-values (rest lon) (sub1 y)))]))) - (extract-values lon x))] - [else (local ((define (add-values lon y acc) - (cond [(= y 0) acc] - [else (add-values (rest lon) (sub1 y) (+ (first lon) acc))])) - (define (acc lon y) - (cond [(= y x) lon] - [else (acc (cons (add-values lon step 0) lon) (add1 y))]))) - (reverse (acc (reverse lon) step)))]))) -; Now compute the series: -(for/list ([n (in-range 2 11)]) - (fib-list (fib-n n n) 20)) +;; fib-list : [Listof Nat] x Nat -> [Listof Nat] +;; Given a non-empty list of natural numbers, the length of the list +;; becomes the size of the step; return the first n numbers of the +;; sequence; assume n >= (length lon) +(define (fib-list lon n) + (define len (length lon)) + (reverse (for/fold ([lon (reverse lon)]) ([_ (in-range (- n len))]) + (cons (apply + (take lon len)) lon)))) + +;; Show the series ... +(define (show-fibs name l) + (printf "~a: " name) + (for ([n (in-list (fib-list l 20))]) (printf "~a, " n)) + (printf "...\n")) + +;; ... with initial 2-powers lists +(for ([n (in-range 2 11)]) + (show-fibs (format "~anacci" (case n [(2) 'fibo] [(3) 'tribo] [(4) 'tetra] + [(5) 'penta] [(6) 'hexa] [(7) 'hepta] + [(8) 'octo] [(9) 'nona] [(10) 'deca])) + (cons 1 (build-list (sub1 n) (curry expt 2))))) +;; and with an initial (2 1) +(show-fibs "lucas" '(2 1)) diff --git a/Task/Fibonacci-n-step-number-sequences/VBScript/fibonacci-n-step-number-sequences.vb b/Task/Fibonacci-n-step-number-sequences/VBScript/fibonacci-n-step-number-sequences.vb new file mode 100644 index 0000000000..1cbcceb740 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/VBScript/fibonacci-n-step-number-sequences.vb @@ -0,0 +1,31 @@ +'function arguments: +'init - initial series of the sequence(e.g. "1,1") +'rep - how many times the sequence repeats - init +Function generate_seq(init,rep) + token = Split(init,",") + step_count = UBound(token) + rep = rep - (UBound(token) + 1) + out = init + For i = 1 To rep + sum = 0 + n = step_count + Do While n >= 0 + sum = sum + token(UBound(token)-n) + n = n - 1 + Loop + 'add the next number to the sequence + ReDim Preserve token(UBound(token) + 1) + token(UBound(token)) = sum + out = out & "," & sum + Next + generate_seq = out +End Function + +WScript.StdOut.Write "fibonacci: " & generate_seq("1,1",15) +WScript.StdOut.WriteLine +WScript.StdOut.Write "tribonacci: " & generate_seq("1,1,2",15) +WScript.StdOut.WriteLine +WScript.StdOut.Write "tetranacci: " & generate_seq("1,1,2,4",15) +WScript.StdOut.WriteLine +WScript.StdOut.Write "lucas: " & generate_seq("2,1",15) +WScript.StdOut.WriteLine diff --git a/Task/Fibonacci-sequence/Delphi/fibonacci-sequence-3.delphi b/Task/Fibonacci-sequence/Delphi/fibonacci-sequence-3.delphi index b1958cc9c9..641e0d65d1 100644 --- a/Task/Fibonacci-sequence/Delphi/fibonacci-sequence-3.delphi +++ b/Task/Fibonacci-sequence/Delphi/fibonacci-sequence-3.delphi @@ -1,37 +1,36 @@ -function fib(n:Int64):int64; +function fib(n: Int64): Int64; - type TFibMat = array[0..1] of array[0..1] of int64; + type TFibMat = array[0..1] of array[0..1] of Int64; - function FibMatMul(a,b:TFibMat):TFibMat; - var i,j,k:integer; - tmp:TFibMat; - begin - for i:=0 to 1 do - for j:=0 to 1 do - begin - tmp[i,j]:=0; - for k:=0 to 1 do tmp[i,j]:=tmp[i,j]+a[i,k]*b[k,j]; - end; - FibMatMul:=tmp; - end; - - function FibMatExp(a:TFibMat;n:int64):TFibmat; - begin - if n<=1 then fibmatexp:=a else - if (n mod 2 = 0) then FibMatExp:=FibMatExp(FibMatMul(a,a), n div 2) else - if (n mod 2 = 1) then FibMatExp:=FibMatMul(a,FibMatExp(FibMatMul(a,a),(n) div 2)); - end; + function FibMatMul(a,b: TFibMat): TFibMat; + var i,j,k: integer; + tmp: TFibMat; + begin + for i := 0 to 1 do + for j := 0 to 1 do + begin + tmp[i,j] := 0; + for k := 0 to 1 do tmp[i,j] := tmp[i,j] + a[i,k] * b[k,j]; + end; + FibMatMul := tmp; + end; + function FibMatExp(a: TFibMat; n: Int64): TFibmat; + begin + if n <= 1 then fibmatexp := a + else if (n mod 2 = 0) then FibMatExp := FibMatExp(FibMatMul(a,a), n div 2) + else if (n mod 2 = 1) then FibMatExp := FibMatMul(a, FibMatExp(FibMatMul(a,a), n div 2)); + end; var - matrix:TFibMat; + matrix: TFibMat; begin -matrix[0,0]:=1; -matrix[0,1]:=1; -matrix[1,0]:=1; -matrix[1,1]:=0; -if n>1 then -matrix:=fibmatexp(matrix,n-1); -fib:=matrix[0,0]; + matrix[0,0] := 1; + matrix[0,1] := 1; + matrix[1,0] := 1; + matrix[1,1] := 0; + if n > 1 then + matrix := fibmatexp(matrix,n-1); + fib := matrix[0,0]; end; diff --git a/Task/Fibonacci-sequence/Elixir/fibonacci-sequence-1.elixir b/Task/Fibonacci-sequence/Elixir/fibonacci-sequence-1.elixir new file mode 100644 index 0000000000..54aa4ef81d --- /dev/null +++ b/Task/Fibonacci-sequence/Elixir/fibonacci-sequence-1.elixir @@ -0,0 +1,13 @@ +defmodule Fibonacci do + def fib(0), do: 0 + def fib(1), do: 1 + def fib(n), do: fib(0, 1, n-2) + + def fib(_, prv, -1), do: prv + def fib(prvprv, prv, n) do + next = prv + prvprv + fib(prv, next, n-1) + end +end + +IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) end) diff --git a/Task/Fibonacci-sequence/Elixir/fibonacci-sequence-2.elixir b/Task/Fibonacci-sequence/Elixir/fibonacci-sequence-2.elixir new file mode 100644 index 0000000000..ae8121d12c --- /dev/null +++ b/Task/Fibonacci-sequence/Elixir/fibonacci-sequence-2.elixir @@ -0,0 +1 @@ +Stream.unfold({0,1}, fn {a,b} -> {a,{b,a+b}} end) |> Enum.take(10) diff --git a/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-1.l b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-1.l new file mode 100644 index 0000000000..d997c0ab32 --- /dev/null +++ b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-1.l @@ -0,0 +1,5 @@ +(defun fib (n a b c) + (if (< c n) (fib n b (+ a b) (+ 1 c) ) + (if (= c n) b a) )) + +(defun fibonacci (n) (if (< n 2) n (fib n 0 1 1) )) diff --git a/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-2.l b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-2.l new file mode 100644 index 0000000000..5d4554cfd3 --- /dev/null +++ b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-2.l @@ -0,0 +1,10 @@ +(defun fibonacci (n) + (let ( (vec) (i) (j) (k) ) + (if (< n 2) n + (progn + (setq vec (make-vector (+ n 1) 0) i 0 j 1 k 2) + (setf (aref vec 1) 1) + (while (<= k n) + (setf (aref vec k) (+ (elt vec i) (elt vec j) )) + (setq i (+ 1 i) j (+ 1 j) k (+ 1 k) )) + (elt vec n) )))) diff --git a/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-3.l b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-3.l new file mode 100644 index 0000000000..c322f70c7a --- /dev/null +++ b/Task/Fibonacci-sequence/Emacs-Lisp/fibonacci-sequence-3.l @@ -0,0 +1,3 @@ +(insert + (mapconcat '(lambda (n) (format "%d" (fibonacci n) )) + (number-sequence 0 15) " ") ) diff --git a/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-1.erl b/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-1.erl index 69d03b2fbd..ecdeca770e 100644 --- a/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-1.erl +++ b/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-1.erl @@ -1,3 +1,6 @@ -fib(0) -> 0; +-module(fib). +-export([fib/1). + +fib(0) -> 1; fib(1) -> 1; -fib(N) when N > 1 -> fib(N-1) + fib(N-2). +fib(N) -> fib(N-1) + fib(N-2). diff --git a/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-2.erl b/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-2.erl index 45e27cafba..bc42bc6621 100644 --- a/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-2.erl +++ b/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-2.erl @@ -1,3 +1,12 @@ -fib(N) -> fib(N,0,1). -fib(0,Res,_) -> Res; -fib(N,Res,Next) when N > 0 -> fib(N-1, Next, Res+Next). +-module(fiblin). +-export([fib/1]) + +fib(0) -> 0; +fib(1) -> 1; +fib(2) -> 1; +fib(3) -> 2; +fib(4) -> 3; +fib(5) -> 5; + +fib(N) when is_integer(N) -> fib(N - 6, 5, 8). +fib(N, A, B) -> if N < 1 -> B; true -> fib(N-1, B, A+B) end. diff --git a/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-3.erl b/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-3.erl new file mode 100644 index 0000000000..1826ac5a7e --- /dev/null +++ b/Task/Fibonacci-sequence/Erlang/fibonacci-sequence-3.erl @@ -0,0 +1 @@ +io:write([fiblin:fib(X) || X <- lists:seq(1,10) ]). diff --git a/Task/Fibonacci-sequence/Fexl/fibonacci-sequence.fexl b/Task/Fibonacci-sequence/Fexl/fibonacci-sequence.fexl index e2c3d9b940..777d9abecc 100644 --- a/Task/Fibonacci-sequence/Fexl/fibonacci-sequence.fexl +++ b/Task/Fibonacci-sequence/Fexl/fibonacci-sequence.fexl @@ -1,14 +1,16 @@ # (fib n) = the nth Fibonacci number \fib= ( - (@\loop\x\y\n - le n 0 x; - \z=(+ x y) - \n=(- n 1) - loop y z n - ) - 0 1 + \loop== + (\x\y\n + le n 0 x; + \z=(+ x y) + \n=(- n 1) + loop y z n + ) + loop 0 1 ) + # Now test it: for 0 20 (\n say (fib n)) diff --git a/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-1.newlisp b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-1.newlisp index 3494dc9551..b0c512c5b8 100644 --- a/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-1.newlisp +++ b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-1.newlisp @@ -1,8 +1,5 @@ (define (fibonacci n) - (let (a 0 b 1 c n i 2) - (while (<= i n) - (setq c (+ a b) - a b - b c) - (++ i)) - c)) + (let (L '(0 1)) + (dotimes (i n) + (setq L (list (L 1) (apply + L)))) + (L 1)) ) diff --git a/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-2.newlisp b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-2.newlisp index a3f1f67a13..dff7eff464 100644 --- a/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-2.newlisp +++ b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-2.newlisp @@ -1,4 +1,4 @@ (define (fibonacci n) (if (< n 2) 1 -(+ (fibonacci (- n 1)) (fibonacci (- n 2))))) -(print(fibonacci 10)) ;;89 + (+ (fibonacci (- n 1)) + (fibonacci (- n 2))))) diff --git a/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-3.newlisp b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-3.newlisp new file mode 100644 index 0000000000..cc8ff5fa22 --- /dev/null +++ b/Task/Fibonacci-sequence/NewLISP/fibonacci-sequence-3.newlisp @@ -0,0 +1,7 @@ +(define (fibonacci n) + (letn (f '((0 1) (1 1)) fib f) + (dotimes (i n) + (set 'fib (multiply fib f))) + (fib 0 1)) ) + +(print(fibonacci 10)) ;;89 diff --git a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-1.pl6 b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-1.pl6 index d8d8c24814..6d921f8dcb 100644 --- a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-1.pl6 +++ b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-1.pl6 @@ -1,6 +1 @@ -sub fib (Int $n --> Int) { - $n > 1 or return $n; - my ($prev, $this) = 0, 1; - ($prev, $this) = $this, $this + $prev for 1 ..^ $n; - return $this; -} +my constant @fib := 0, 1, *+* ... *; diff --git a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-2.pl6 b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-2.pl6 index 9f73216174..d662f8153a 100644 --- a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-2.pl6 +++ b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-2.pl6 @@ -1,4 +1 @@ -proto fib (Int $n --> Int) is cached {*} -multi fib (0) { 0 } -multi fib (1) { 1 } -multi fib ($n) { fib($n - 1) + fib($n - 2) } +sub fib ($n) { @fib[$n] } diff --git a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-3.pl6 b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-3.pl6 index 69b60b69f3..add3cebf46 100644 --- a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-3.pl6 +++ b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-3.pl6 @@ -1,6 +1,2 @@ -sub fib (Int $n --> Int) { - constant φ1 = 1 / constant φ = (1 + sqrt 5)/2; - constant invsqrt5 = 1 / sqrt 5; - - floor invsqrt5 * (φ**$n + φ1**$n); -} +my constant @neg_fib := 0, 1, *-* ... *; +sub fib ($n) { $n >= 0 and @fib[$n] or @neg_fib[-$n]; } diff --git a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-4.pl6 b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-4.pl6 index dae7e0b40c..d8d8c24814 100644 --- a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-4.pl6 +++ b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-4.pl6 @@ -1 +1,6 @@ -my @fib := 0, 1, *+* ... *; +sub fib (Int $n --> Int) { + $n > 1 or return $n; + my ($prev, $this) = 0, 1; + ($prev, $this) = $this, $this + $prev for 1 ..^ $n; + return $this; +} diff --git a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-5.pl6 b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-5.pl6 index d662f8153a..9f73216174 100644 --- a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-5.pl6 +++ b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-5.pl6 @@ -1 +1,4 @@ -sub fib ($n) { @fib[$n] } +proto fib (Int $n --> Int) is cached {*} +multi fib (0) { 0 } +multi fib (1) { 1 } +multi fib ($n) { fib($n - 1) + fib($n - 2) } diff --git a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-6.pl6 b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-6.pl6 index a2a539f393..69b60b69f3 100644 --- a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-6.pl6 +++ b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-6.pl6 @@ -1,2 +1,6 @@ -my @neg_fib := 0, 1, *-* ... *; -sub fib ($n) { $n >= 0 and @fib[$n] or @neg_fib[-$n]; } +sub fib (Int $n --> Int) { + constant φ1 = 1 / constant φ = (1 + sqrt 5)/2; + constant invsqrt5 = 1 / sqrt 5; + + floor invsqrt5 * (φ**$n + φ1**$n); +} diff --git a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-1.rb b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-1.rb index 94298eecbc..4711e0c055 100644 --- a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-1.rb +++ b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-1.rb @@ -1,6 +1,8 @@ -def fib_iter(n) - return 0 if n == 0 - fib_prev, fib = 1, 1 - (n.abs - 2).times { fib_prev, fib = fib, fib + fib_prev } - fib * (n < 0 ? (-1)**(n + 1) : 1) +def fib(n, sequence=[1]) + n.times do + current_number, last_number = sequence.last(2) + sequence << current_number + (last_number or 0) + end + + sequence.last end diff --git a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-2.rb b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-2.rb index b47eecfae3..20974ec138 100644 --- a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-2.rb +++ b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-2.rb @@ -1,9 +1,8 @@ -def fib_rec(n) - if n <= -2 - (-1)**(n + 1) * fib_rec(n.abs) - elsif n <= 1 - n.abs - else - fib_rec(n - 1) + fib_rec(n - 2) - end +def fib(n, sequence=[1]) + return sequence.last if n == 0 + + current_number, last_number = sequence.last(2) + sequence << current_number + (last_number or 0) + + fib(n-1, sequence) end diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-1.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-1.rust index 49bbcee9ba..24ce21e1d9 100644 --- a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-1.rust +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-1.rust @@ -1,66 +1,31 @@ -// Works with 0.13.0-dev (f673e9841) -fn fib(n: i64, f: F) -> (i64, i64) where F: Fn(i64) { - if n < 0 { - // Let these variables be mutated, otherwise too slow - let mut n1:i64 = 0; - let mut n2:i64 = -1; - let mut i:i64 = 0; - let mut tmp:i64; +use std::env; - while i > n { - f(n1); - tmp = n1-n2; - if tmp > 0 && n2 > 0 { //Detect overflow - println!("\nReached the limit of i64, halting"); - return (n1, i); - } - n1 = n2; - n2 = tmp; - i -= 1; - } - (n1+n2, n) - } else if n > 0 { - // And these variables - let mut n1:i64 = 0; - let mut n2:i64 = 1; - let mut i:i64 = 0; - let mut tmp:i64; +fn fib(n: u64, f: F) -> (u64, u64) where F: Fn(u64) { + if n == 0 { + f(0); + (0,1) + } else { + let mut n1:u64 = 0; + let mut n2:u64 = 1; - while i < n { + for _i in (0..n) { f(n1); - tmp = n1+n2; - if tmp < 0 { //Detect overflow - println!("\nReached the limit of i64, halting"); - return (n1, i); - } + let tmp = n1+n2; // Will panic on overflow n1 = n2; n2 = tmp; - i += 1; } (n2-n1, n) - } else { - f(0); - (0,1) } } fn main() { - let args = std::os::args(); - let default_n = 10i64; + let args: Vec = env::args().collect(); + let default_n = 10u64; let n = match args.len() { 1 => default_n, _ => args[1].parse().unwrap_or(default_n) }; - /* Use the loop protocol to be able to do things - * with the sequence given, in this case, print them out. - * The loop itself returns a tuple with where it got to and - * what the number is. - */ - let (result, n) = fib(n, |num| { - //print out the sequence - print!("{} ", num); - }); - + let (result, n) = fib(n, |num| { print!("{} ", num); }); println!("\nThe {}th fibonacci number is: {}", n, result); } diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust index 7a60c2063e..64a8e80e71 100644 --- a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust @@ -1,7 +1,6 @@ -// Works with 0.13.0-dev (f673e9841) fn main() { - fn fib(n: int) -> int { - fn _fib(n: int, a: int, b: int) -> int { + fn fib(n: i32) -> i32 { + fn _fib(n: i32, a: i32, b: i32) -> i32 { match (n, a, b) { (0, _, _) => a, _ => _fib(n-1, a+b, a) @@ -11,7 +10,7 @@ fn main() { _fib(n, 0, 1) } - for n in range(0, 20) { + for n in 0..20 { println!("{}", fib(n)); } } diff --git a/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-4.ss b/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-4.ss index 64c6335cfc..4847ec3d24 100644 --- a/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-4.ss +++ b/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-4.ss @@ -1,19 +1,10 @@ -;;; Fibonacci numbers using Edsger Dijkstra's algorithm -;;; http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF +(define (fib) + (define (nxt lv nv) (cons nv (lambda () (nxt nv (+ lv nv))))) + (cons 0 (lambda () (nxt 0 1)))) -(define (fib n) - (define (fib-aux a b p q count) - (cond ((= count 0) b) - ((even? count) - (fib-aux a - b - (+ (* p p) (* q q)) - (+ (* q q) (* 2 p q)) - (/ count 2))) - (else - (fib-aux (+ (* b q) (* a q) (* a p)) - (+ (* b p) (* a q)) - p - q - (- count 1))))) - (fib-aux 1 0 0 1 n)) +;;; test... +(define (show-stream-take n strm) + (define (shw-nxt n strm) (begin (display (car strm)) + (if (> n 1) (begin (display " ") (shw-nxt (- n 1) ((cdr strm)))) (display ")")))) + (begin (display "(") (shw-nxt n strm))) +(show-stream-take 30 (fib)) diff --git a/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-5.ss b/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-5.ss new file mode 100644 index 0000000000..64c6335cfc --- /dev/null +++ b/Task/Fibonacci-sequence/Scheme/fibonacci-sequence-5.ss @@ -0,0 +1,19 @@ +;;; Fibonacci numbers using Edsger Dijkstra's algorithm +;;; http://www.cs.utexas.edu/users/EWD/ewd06xx/EWD654.PDF + +(define (fib n) + (define (fib-aux a b p q count) + (cond ((= count 0) b) + ((even? count) + (fib-aux a + b + (+ (* p p) (* q q)) + (+ (* q q) (* 2 p q)) + (/ count 2))) + (else + (fib-aux (+ (* b q) (* a q) (* a p)) + (+ (* b p) (* a q)) + p + q + (- count 1))))) + (fib-aux 1 0 0 1 n)) diff --git a/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-1.ti-83 b/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-1.ti-83 index 1402102a8a..a038facd07 100644 --- a/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-1.ti-83 +++ b/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-1.ti-83 @@ -1,13 +1,5 @@ - :Disp "0" //Dirty, I know, however this does not interfere with the code - :Disp "1" - :Disp "1" - :1→A - :1→B - :0→C - :Goto 1 - :Lbl 1 - :A+B→C - :Disp C - :B→A - :C→B - :Goto 1 +{0,1 +While 1 +Disp Ans(1 +{Ans(2),sum(Ans +End diff --git a/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-2.ti-83 b/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-2.ti-83 index 9b5515016e..31f965d28f 100644 --- a/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-2.ti-83 +++ b/Task/Fibonacci-sequence/TI-83-BASIC/fibonacci-sequence-2.ti-83 @@ -1,9 +1,3 @@ -:Prompt N -:0→A -:1→B -:For(I,1,N) - :A→C - :B→A - :C+B→B -:End -:A +Prompt N +.5(1+√(5 //golden ratio +(Ans^N–(-Ans)^-N)/√(5 diff --git a/Task/Fibonacci-word-fractal/C/fibonacci-word-fractal.c b/Task/Fibonacci-word-fractal/C/fibonacci-word-fractal.c new file mode 100644 index 0000000000..88e19f899d --- /dev/null +++ b/Task/Fibonacci-word-fractal/C/fibonacci-word-fractal.c @@ -0,0 +1,17 @@ +#include + +int main(void) +{ + puts( "%!PS-Adobe-3.0 EPSF\n" + "%%BoundingBox: -10 -10 400 565\n" + "/a{0 0 moveto 0 .4 translate 0 0 lineto stroke -1 1 scale}def\n" + "/b{a 90 rotate}def"); + + char i; + for (i = 'c'; i <= 'z'; i++) + printf("/%c{%c %c}def\n", i, i-1, i-2); + + puts("0 setlinewidth z showpage\n%%EOF"); + + return 0; +} diff --git a/Task/Fibonacci-word-fractal/Elixir/fibonacci-word-fractal.elixir b/Task/Fibonacci-word-fractal/Elixir/fibonacci-word-fractal.elixir new file mode 100644 index 0000000000..7605fca8a0 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Elixir/fibonacci-word-fractal.elixir @@ -0,0 +1,35 @@ +defmodule Fibonacci do + def fibonacci_word, do: Stream.unfold({"1","0"}, fn{a,b} -> {a, {b, b<>a}} end) + + def word_fractal(n) do + word = fibonacci_word |> Enum.at(n) + walk(to_char_list(word), 1, 0, 0, 0, -1, %{{0,0}=>"S"}) + |> print + end + + defp walk([], _, _, _, _, _, map), do: map + defp walk([h|t], n, x, y, dx, dy, map) do + map2 = Dict.put(map, {x+dx, y+dy}, (if dx==0, do: "|", else: "-")) + |> Dict.put({x2=x+2*dx, y2=y+2*dy}, "+") + if h == ?0 do + if rem(n,2)==0, do: walk(t, n+1, x2, y2, dy, -dx, map2), + else: walk(t, n+1, x2, y2, -dy, dx, map2) + else + walk(t, n+1, x2, y2, dx, dy, map2) + end + end + + defp print(map) do + xkeys = Dict.keys(map) |> Enum.map(fn {x,_} -> x end) + xmin = Enum.min(xkeys) + xmax = Enum.max(xkeys) + ykeys = Dict.keys(map) |> Enum.map(fn {_,y} -> y end) + ymin = Enum.min(ykeys) + ymax = Enum.max(ykeys) + Enum.each(ymin..ymax, fn y -> + IO.puts Enum.map_join(xmin..xmax, fn x -> Dict.get(map, {x,y}, " ") end) + end) + end +end + +Fibonacci.word_fractal(16) diff --git a/Task/Fibonacci-word-fractal/REXX/fibonacci-word-fractal.rexx b/Task/Fibonacci-word-fractal/REXX/fibonacci-word-fractal.rexx index b3610187cd..5dab8e5bfc 100644 --- a/Task/Fibonacci-word-fractal/REXX/fibonacci-word-fractal.rexx +++ b/Task/Fibonacci-word-fractal/REXX/fibonacci-word-fractal.rexx @@ -1,36 +1,41 @@ -/*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*/ +/*REXX program generates a Fibonacci word, then displays the fractal curve.*/ +parse arg ord . /*obtain optional arguments from the CL*/ +if ord=='' then ord=23 /*Not specified? Then use the default*/ +s=FibWord(ord) /*obtain the order of Fibonacci word.*/ + x=0; maxX=0; dx=0; b=' '; @.=b; xp=0 + y=0; maxY=0; dy=1; @.0.0=.; yp=0 + do n=1 for length(s); x=x+dx; y=y+dy /*advance the plot for the next point. */ + maxX=max(maxX,x); maxY=max(maxY,y) /*set the maximums for displaying plot.*/ + c='│'; if dx\==0 then c='─'; if n==1 then c='┌' /*The 1st plot?*/ + @.x.y=c /*assign a plotting character for curve*/ + if @(xp-1,yp)\==b & @(xp,yp-1)\==b then call @ xp,yp,'┐' /*fix-up.*/ + if @(xp-1,yp)\==b & @(xp,yp+1)\==b then call @ xp,yp,'┘' /* " */ + if @(xp+1,yp)\==b & @(xp,yp+1)\==b then call @ xp,yp,'└' /* " */ + if @(xp+1,yp)\==b & @(xp,yp-1)\==b then call @ xp,yp,'┌' /* " */ + xp=x; yp=y; z=substr(s,n,1) /*save old x,y; assign plot character.*/ + if z==1 then iterate /*Is Z equal to unity? Then ignore 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 the sign for the 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. */ +call @ x,y,'∙' /*set the last point that was plotted. */ + do r=maxY to 0 by -1; _= /*show single row at a time, top first.*/ + do c=0 to maxX; _=_ || @.c.r; end /*c*/ + if _\='' then say strip(_,'T') /*if not blank, then display a line. */ + + + if _\='' then call lineout 'FIBFRACT.OUT',strip(_,'T') /*write to file*/ + + + end /*r*/ /* [↑] only display the non-blank rows*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +@: parse arg xx,yy,p; if arg(3)=='' then return @.xx.yy; @.xx.yy=p; return +/*────────────────────────────────────────────────────────────────────────────*/ +FibWord: procedure; arg x; !.=0; !.1=1 /*obtain the order of Fibonacci word. */ + do k=3 to x; k1=k-1; k2=k-2 /*generate the Kth Fibonacci word. */ + !.k=!.k1 || !.k2 /*construct the next Fibonacci word. */ + end /*k*/ /* [↑] generate a Fibonacci word. */ +return !.x /*return the Xth Fibonacci word. */ diff --git a/Task/Fibonacci-word-fractal/Ruby/fibonacci-word-fractal.rb b/Task/Fibonacci-word-fractal/Ruby/fibonacci-word-fractal.rb index 9d67c865ca..33d9422e36 100644 --- a/Task/Fibonacci-word-fractal/Ruby/fibonacci-word-fractal.rb +++ b/Task/Fibonacci-word-fractal/Ruby/fibonacci-word-fractal.rb @@ -1,8 +1,6 @@ def fibonacci_word(n) words = ["1", "0"] - (words.size..n).each do |i| - words << words[i-1] + words[i-2] - end + (n-1).times{ words << words[-1] + words[-2] } words[n] end @@ -18,15 +16,11 @@ def print_fractal(word) 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 + (xmin, xmax), (ymin, ymax) = area.keys.transpose.map(&:minmax) for y in ymin..ymax - for x in xmin..xmax - print area[[x,y]] - end - puts + puts (xmin..xmax).map{|x| area[[x,y]]}.join end end -word = fibonacci_word(11) +word = fibonacci_word(16) print_fractal(word) diff --git a/Task/Fibonacci-word/00DESCRIPTION b/Task/Fibonacci-word/00DESCRIPTION index ebca0da00f..b26ba86509 100644 --- a/Task/Fibonacci-word/00DESCRIPTION +++ b/Task/Fibonacci-word/00DESCRIPTION @@ -10,3 +10,8 @@ For this task we shall do this for n = 37. You may display the first few but not Instead create a table for F_Words 1 to 37 which shows: :The number of characters in the word :The word's [[Entropy]]. + +Related Tasks: + +:::* [[Entropy]] +:::* [[Entropy/Narcissist]] diff --git a/Task/Fibonacci-word/Common-Lisp/fibonacci-word.lisp b/Task/Fibonacci-word/Common-Lisp/fibonacci-word.lisp new file mode 100644 index 0000000000..2a5aa73383 --- /dev/null +++ b/Task/Fibonacci-word/Common-Lisp/fibonacci-word.lisp @@ -0,0 +1,32 @@ +(defun make-fibwords (array) + (loop for i from 0 below 37 + for j = "0" then (concatenate 'string j k) + and k = "1" then j + do (setf (aref array i) k)) + array) + +(defvar *fib* (make-fibwords (make-array 37))) + +(defun entropy (string) + (let ((table (make-hash-table :test 'eql)) + (entropy 0d0) + (n (length string))) + (mapc (lambda (c) + (setf (gethash c table) (+ (gethash c table 0) 1))) + (coerce string 'list)) + (maphash (lambda (k v) + (declare (ignore k)) + (decf entropy (* (/ v n) (log (/ v n) 2)))) + table) + entropy)) + +(defun string-or-dots (string) + (if (> (length string) 40) + "..." + string)) + +(format t "~2A ~10A ~17A ~A~%" "N" "Length" "Entropy" "Fibword") +(loop for i below 37 + for n = (aref *fib* i) do + (format t "~2D ~10D ~17,15F ~A~%" + (1+ i) (length n) (entropy n) (string-or-dots n))) diff --git a/Task/Fibonacci-word/Elixir/fibonacci-word.elixir b/Task/Fibonacci-word/Elixir/fibonacci-word.elixir new file mode 100644 index 0000000000..0505afecae --- /dev/null +++ b/Task/Fibonacci-word/Elixir/fibonacci-word.elixir @@ -0,0 +1,22 @@ +defmodule RC do + def entropy(str) do + leng = String.length(str) + String.to_char_list(str) + |> Enum.reduce(Map.new, fn c,acc -> Dict.update(acc, c, 1, &(&1+1)) end) + |> Dict.values + |> Enum.reduce(0, fn count, entropy -> + freq = count / leng + entropy - freq * :math.log2(freq) # log2 was added with Erlang/OTP 18 + end) + end +end + +fibonacci_word = Stream.unfold({"1","0"}, fn{a,b} -> {a, {b, b<>a}} end) + +IO.puts " N Length Entropy Fibword" +fibonacci_word |> Enum.take(37) |> Enum.with_index +|> Enum.each(fn {word,i} -> + len = String.length(word) + str = if len < 60, do: word, else: "" + :io.format "~3w ~8w ~17.15f ~s~n", [i+1, len, RC.entropy(word), str] +end) diff --git a/Task/Fibonacci-word/JavaScript/fibonacci-word.js b/Task/Fibonacci-word/JavaScript/fibonacci-word.js new file mode 100644 index 0000000000..a1d47c3c90 --- /dev/null +++ b/Task/Fibonacci-word/JavaScript/fibonacci-word.js @@ -0,0 +1,101 @@ +//makes outputting a table possible in environments +//that don't support console.table() +function console_table(xs) { + function pad(n,s) { + var res = s; + for (var i = s.length; i < n; i++) + res += " "; + return res; + } + + if (xs.length === 0) + console.log("No data"); + else { + var widths = []; + var cells = []; + for (var i = 0; i <= xs.length; i++) + cells.push([]); + + for (var s in xs[0]) { + var len = s.length; + cells[0].push(s); + + for (var i = 0; i < xs.length; i++) { + var ss = "" + xs[i][s]; + len = Math.max(len, ss.length); + cells[i+1].push(ss); + } + widths.push(len); + } + var s = ""; + for (var x = 0; x < cells.length; x++) { + for (var y = 0; y < widths.length; y++) + s += "|" + pad(widths[y], cells[x][y]); + s += "|\n"; + } + console.log(s); + } +} + +//returns the entropy of a string as a number +function entropy(s) { + //create an object containing each individual char + //and the amount of iterations per char + function prob(s) { + var h = Object.create(null); + s.split('').forEach(function(c) { + h[c] && h[c]++ || (h[c] = 1); + }); + return h; + } + + s = s.toString(); //just in case + var e = 0, l = s.length, h = prob(s); + + for (var i in h ) { + var p = h[i]/l; + e -= p * Math.log(p) / Math.log(2); + } + return e; +} + +//creates Fibonacci Word to n as described on Rosetta Code +//see rosettacode.org/wiki/Fibonacci_word +function fibWord(n) { + var wOne = "1", wTwo = "0", wNth = [wOne, wTwo], w = "", o = []; + + for (var i = 0; i < n; i++) { + if (i === 0 || i === 1) { + w = wNth[i]; + } else { + w = wNth[i - 1] + wNth[i - 2]; + wNth.push(w); + } + var l = w.length; + var e = entropy(w); + + if (l <= 21) { + o.push({ + N: i + 1, + Length: l, + Entropy: e, + Word: w + }); + } else { + o.push({ + N: i + 1, + Length: l, + Entropy: e, + Word: "..." + }); + } + } + + try { + console.table(o); + } catch (err) { + console_table(o); + } +} + +fibWord(37); diff --git a/Task/Fibonacci-word/PureBasic/fibonacci-word.purebasic b/Task/Fibonacci-word/PureBasic/fibonacci-word.purebasic new file mode 100644 index 0000000000..487b1a69c9 --- /dev/null +++ b/Task/Fibonacci-word/PureBasic/fibonacci-word.purebasic @@ -0,0 +1,35 @@ +EnableExplicit +Define fwx$, n.i +NewMap uchar.i() + +Macro RowPrint(ns,ls,es,ws) + Print(RSet(ns,4," ")+RSet(ls,12," ")+" "+es+" ") : If Len(ws)<55 : PrintN(ws) : Else : PrintN("...") : EndIf +EndMacro + +Procedure.d nlog2(x.d) : ProcedureReturn Log(x)/Log(2) : EndProcedure + +Procedure countchar(s$, Map uchar()) + If Len(s$) + uchar(Left(s$,1))=CountString(s$,Left(s$,1)) : s$=RemoveString(s$,Left(s$,1)) + ProcedureReturn countchar(s$, uchar()) + EndIf +EndProcedure + +Procedure.d ce(fw$) + Define e.d + Shared uchar() + countchar(fw$,uchar()) + ForEach uchar() : e-uchar()/Len(fw$)*nlog2(uchar()/Len(fw$)) : Next + ProcedureReturn e +EndProcedure + +Procedure.s fw(n.i,a$="0",b$="1",m.i=2) + Select n : Case 1 : ProcedureReturn a$ : Case 2 : ProcedureReturn b$ : EndSelect + If m2 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().*/ +/*REXX program lists number of chars in a fibonacci word, the word's entropy. */ +d=20; de=d+6; numeric digits d /*use more precision (the default is 9)*/ +parse arg N . /*get optional argument from the C.L. */ +if N=='' then N=42 /*Not specified? Then use the default.*/ +@.1=1; @.2=0 /*define some initial values of FIBword*/ +say center('N',5) center('length',12) center('entropy',de) center('Fib word',56) +say copies('─',5) copies('─' ,12) copies('─' ,de) copies('─' ,56) + /* [↓] display N fibonacci words. */ + do j=1 for N; j1=j-1; j2=j-2 /*use temporary variables for @ indices*/ + if j>2 then @.j=@.j1 || @.j2 /*calculate the FIBword if we need to.*/ + L=length(@.j) + if L<56 then Fw= @.j + else Fw= '{the word is too wide to display.}' + say right(j,4) right(L,12) ' ' entropy() ' ' Fw; drop @.j2 + end /*j*/ /*display text msg; free memory of @.j2*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +entropy: if L==1 then return left(0,d+2) /*handle special case of 1 character*/ +!.0=length(space(translate(@.j, , 1), 0)) /*this is a fast way to count zeroes*/ +!.1=L-!.0 /*also, calculate the number of ones*/ +S=0; do i=1 for 2; _=i-1 /*construct character 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" (one).*/ + return format(S,,d) /*normalize the sum (S) number. */ +/*────────────────────────────────────────────────────────────────────────────*/ +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) + 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/Ruby/fibonacci-word.rb b/Task/Fibonacci-word/Ruby/fibonacci-word.rb index 7c7829a11b..b9111fe282 100644 --- a/Task/Fibonacci-word/Ruby/fibonacci-word.rb +++ b/Task/Fibonacci-word/Ruby/fibonacci-word.rb @@ -1,11 +1,12 @@ #encoding: ASCII-8BIT def entropy(s) - counts = Hash.new(0) + counts = Hash.new(0.0) s.each_char { |c| counts[c] += 1 } + leng = s.length counts.values.reduce(0) do |entropy, count| - freq = count / s.length.to_f + freq = count / leng entropy - freq * Math.log2(freq) end end @@ -17,7 +18,7 @@ def entropy(s) words << words[-1] + words[-2] end -puts '%3s %10s %15s %s' % %w[N Length Entropy Fibword] +puts '%3s %9s %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 : ''] + puts '%3i %9i %15.12f %s' % [i, word.length, entropy(word), word.length<60 ? word : ''] end diff --git a/Task/File-input-output/D/file-input-output-2.d b/Task/File-input-output/D/file-input-output-2.d index 2316dc604c..a1a98ef2b1 100644 --- a/Task/File-input-output/D/file-input-output-2.d +++ b/Task/File-input-output/D/file-input-output-2.d @@ -1,15 +1,5 @@ -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; +void main() { +import std.file; +auto data = std.file.read("input.txt"); +std.file.write("output.txt", data); } diff --git a/Task/File-input-output/D/file-input-output-3.d b/Task/File-input-output/D/file-input-output-3.d index 72dac05f17..2316dc604c 100644 --- a/Task/File-input-output/D/file-input-output-3.d +++ b/Task/File-input-output/D/file-input-output-3.d @@ -1,9 +1,15 @@ -import tango.io.device.File; - -void main() -{ - auto from = new File("input.txt"); - auto to = new File("output.txt", File.WriteCreate); - to.copy(from).close; - from.close; +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-input-output/D/file-input-output-4.d b/Task/File-input-output/D/file-input-output-4.d index a6be2eaa5d..72dac05f17 100644 --- a/Task/File-input-output/D/file-input-output-4.d +++ b/Task/File-input-output/D/file-input-output-4.d @@ -2,6 +2,8 @@ import tango.io.device.File; void main() { + auto from = new File("input.txt"); auto to = new File("output.txt", File.WriteCreate); - to.copy(new File("input.txt")).close; + to.copy(from).close; + from.close; } diff --git a/Task/File-input-output/D/file-input-output-5.d b/Task/File-input-output/D/file-input-output-5.d new file mode 100644 index 0000000000..a6be2eaa5d --- /dev/null +++ b/Task/File-input-output/D/file-input-output-5.d @@ -0,0 +1,7 @@ +import tango.io.device.File; + +void main() +{ + auto to = new File("output.txt", File.WriteCreate); + to.copy(new File("input.txt")).close; +} diff --git a/Task/File-input-output/DCL/file-input-output.dcl b/Task/File-input-output/DCL/file-input-output.dcl new file mode 100644 index 0000000000..3635543201 --- /dev/null +++ b/Task/File-input-output/DCL/file-input-output.dcl @@ -0,0 +1,9 @@ +$ open input input.txt +$ open /write output output.txt +$ loop: +$ read /end_of_file = done input line +$ write output line +$ goto loop +$ done: +$ close input +$ close output diff --git a/Task/File-input-output/Elixir/file-input-output-1.elixir b/Task/File-input-output/Elixir/file-input-output-1.elixir new file mode 100644 index 0000000000..60736d1244 --- /dev/null +++ b/Task/File-input-output/Elixir/file-input-output-1.elixir @@ -0,0 +1,16 @@ +defmodule FileReadWrite do + def copy(path,new_path) do + case File.read(path) do + # In case of success, write to the new file + {:ok, body} -> + # Can replace with :write! to generate an error upon failure + File.write(new_path,body) + # If not successful, raise an error + {:error,reason} -> + # Using Erlang's format_error to generate error string + :file.format_error(reason) + end + end +end + +FileReadWrite.copy("input.txt","output.txt") diff --git a/Task/File-input-output/Elixir/file-input-output-2.elixir b/Task/File-input-output/Elixir/file-input-output-2.elixir new file mode 100644 index 0000000000..92877ff2d8 --- /dev/null +++ b/Task/File-input-output/Elixir/file-input-output-2.elixir @@ -0,0 +1 @@ +File.cp!("input.txt", "output.txt") diff --git a/Task/File-input-output/Rust/file-input-output.rust b/Task/File-input-output/Rust/file-input-output.rust index 212f6e82c3..831bc1900b 100644 --- a/Task/File-input-output/Rust/file-input-output.rust +++ b/Task/File-input-output/Rust/file-input-output.rust @@ -1,20 +1,10 @@ -extern mod std; -use std::io; +use std::fs::File; +use std::io::{Read, Write}; fn main() { - let input_file = &Path("input.txt"); - let input = io::read_whole_file_str(input_file); - match input { - Err(e) => fail!(e), - Ok(_) => {} - } - - let output_file = &Path("output.txt"); - let output = io::file_writer(output_file, [io::Create, io::Truncate]); - match output { - Err(e) => fail!(e), - Ok(_) => {} - } - - output.unwrap().write_str(input.unwrap()); + let mut file = File::open("input.txt").unwrap(); + let mut data = Vec::new(); + file.read_to_end(&mut data).unwrap(); + let mut file = File::create("output.txt").unwrap(); + file.write_all(&data).unwrap(); } diff --git a/Task/File-modification-time/00DESCRIPTION b/Task/File-modification-time/00DESCRIPTION index 81873a1f15..2803ead688 100644 --- a/Task/File-modification-time/00DESCRIPTION +++ b/Task/File-modification-time/00DESCRIPTION @@ -6,6 +6,7 @@ {{omit from|PARI/GP}} {{omit from|Retro}} {{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} +{{omit from|Axe}} {{omit from|ZX Spectrum Basic|Does not have a real time clock.}} {{task|File System Operations}} This task will attempt to get and set the modification time of a file. diff --git a/Task/File-modification-time/ALGOL-68/file-modification-time.alg b/Task/File-modification-time/ALGOL-68/file-modification-time.alg new file mode 100644 index 0000000000..03625ff667 --- /dev/null +++ b/Task/File-modification-time/ALGOL-68/file-modification-time.alg @@ -0,0 +1,10 @@ +PROC get output = (STRING cmd) VOID: +IF STRING sh cmd = " " + cmd + " ; 2>&1"; + STRING output; + execve output ("/bin/sh", ("sh", "-c", sh cmd), "", output) >= 0 +THEN print (output) FI; +get output ("rm -rf WTC_1"); CO Ensure file doesn't exist CO +get output ("touch WTC_1"); CO Create file CO +get output ("ls -l --time-style=full-iso WTC_1"); CO Display its last modified time CO +get output ("touch -t 200109111246.40 WTC_1"); CO Change its last modified time CO +get output ("ls -l --time-style=full-iso WTC_1") CO Verify it changed CO diff --git a/Task/File-modification-time/AWK/file-modification-time-1.awk b/Task/File-modification-time/AWK/file-modification-time-1.awk new file mode 100644 index 0000000000..3c32145def --- /dev/null +++ b/Task/File-modification-time/AWK/file-modification-time-1.awk @@ -0,0 +1,15 @@ +@load "filefuncs" +BEGIN { + + name = "input.txt" + + # display time + stat(name, fd) + printf("%s\t%s\n", name, strftime("%a %b %e %H:%M:%S %Z %Y", fd["mtime"]) ) + + # change time + cmd = "touch -t 201409082359.59 " name + system(cmd) + close(cmd) + +} diff --git a/Task/File-modification-time/AWK/file-modification-time.awk b/Task/File-modification-time/AWK/file-modification-time-2.awk similarity index 100% rename from Task/File-modification-time/AWK/file-modification-time.awk rename to Task/File-modification-time/AWK/file-modification-time-2.awk diff --git a/Task/File-modification-time/Julia/file-modification-time.julia b/Task/File-modification-time/Julia/file-modification-time.julia new file mode 100644 index 0000000000..264f5a8be0 --- /dev/null +++ b/Task/File-modification-time/Julia/file-modification-time.julia @@ -0,0 +1,11 @@ +fname = "fool.txt" +tfmt = "%FT%T%z" + +println("The modification time of ", fname, " is ") +println(" ", strftime(tfmt, mtime(fname))) + +println("\nTouch this file.") +touch(fname) + +println("The modification time of ", fname, " is now ") +println(" ", strftime(tfmt, mtime(fname))) diff --git a/Task/File-modification-time/REXX/file-modification-time.rexx b/Task/File-modification-time/REXX/file-modification-time.rexx new file mode 100644 index 0000000000..3c2e86ff50 --- /dev/null +++ b/Task/File-modification-time/REXX/file-modification-time.rexx @@ -0,0 +1,8 @@ +/*REXX program (Regina) to obtain/display a file's time of modification. */ +parse arg $ . /*get the fileID from the CL*/ +if $=='' then do; say "***error*** no filename was specified."; exit 13; end +q=stream($, 'C', "QUERY TIMESTAMP") /*get file's mod time info. */ +if q=='' then q="specified file doesn't exist." /*give an error indication. */ +say 'For file: ' $ /*display the file ID. */ +say 'timestamp of last modification: ' q /*display modification time.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/File-size/AWK/file-size-1.awk b/Task/File-size/AWK/file-size-1.awk new file mode 100644 index 0000000000..2c1970f8e5 --- /dev/null +++ b/Task/File-size/AWK/file-size-1.awk @@ -0,0 +1,9 @@ +@load "filefuncs" +BEGIN { + printsize("input.txt") + printsize("/input.txt") +} +function printsize(name ,fd) { + stat(name, fd) + printf("%s\t%s\n", name, fd["size"]) +} diff --git a/Task/File-size/AWK/file-size-2.awk b/Task/File-size/AWK/file-size-2.awk new file mode 100644 index 0000000000..32c9cc2c02 --- /dev/null +++ b/Task/File-size/AWK/file-size-2.awk @@ -0,0 +1,44 @@ +BEGIN { + + # Windows + out = system2var("for %I in (input.txt) do @echo %~zI") + printf("input.txt\t%s\n", out) + out = system2var("for %I in (\input.txt) do @echo %~zI") + printf("\input.txt\t%s\n", out) + + # Non-Windows + out = getline2var("ls -l input.txt") + split(out, size, " ") + printf("input.txt\t%s\n", size[5]) + out = getline2var("ls -l /input.txt") + split(out, size, " ") + printf("/input.txt\t%s\n", size[5]) +} + +# Windows system() method +function system2var(command ,tempfile, cmd, out, rec, data, i) { + tempfile = "C:\\TEMP\\TMP.TMP" + cmd = command " > " tempfile + system(cmd) + close(cmd) + while (getline rec < tempfile > 0) { + if ( ++i == 1 ) + data = rec + else + data = data "\n" rec + } + return(data) +} + +# Non-windows getline method +function getline2var(command ,fish, scale, ship) { + command = command " 2>/dev/null" + while ( (command | getline fish) > 0 ) { + if ( ++scale == 1 ) + ship = fish + else + ship = ship "\n" fish + } + close(command) + return ship +} diff --git a/Task/File-size/AWK/file-size.awk b/Task/File-size/AWK/file-size.awk deleted file mode 100644 index 59a279bed1..0000000000 --- a/Task/File-size/AWK/file-size.awk +++ /dev/null @@ -1,17 +0,0 @@ -# usage: awk -f filesize.awk -v fn=input.txt - -BEGIN { # Filesize on Unix, using ls - #system("ls -l") - - if(!fn) fn ="input.txt" - cmd="ls -l " fn - print "#", cmd - system(cmd) - - cmd | getline x - close(cmd) - #print x - n=split(x,stat," ") - #for (i in stat) {print i, stat[i] } - print "file:", stat[9], "size:", stat[5] -} diff --git a/Task/File-size/Clojure/file-size.clj b/Task/File-size/Clojure/file-size.clj index 9fc4b80b82..8134cf99a9 100644 --- a/Task/File-size/Clojure/file-size.clj +++ b/Task/File-size/Clojure/file-size.clj @@ -1,6 +1,6 @@ -(import '[java.io File]) +(require '[clojure.java.io :as io]) (defn show-size [filename] - (println filename "size:" (.length (File. filename)))) + (println filename "size:" (.length (io/file filename)))) (show-size "input.txt") (show-size "/input.txt") diff --git a/Task/File-size/Elixir/file-size.elixir b/Task/File-size/Elixir/file-size.elixir new file mode 100644 index 0000000000..3a0054cc3b --- /dev/null +++ b/Task/File-size/Elixir/file-size.elixir @@ -0,0 +1,2 @@ +IO.puts File.stat!("input.txt").size +IO.puts File.stat!("/input.txt").size diff --git a/Task/File-size/REXX/file-size-2.rexx b/Task/File-size/REXX/file-size-2.rexx index 2068d7f653..347d096188 100644 --- a/Task/File-size/REXX/file-size-2.rexx +++ b/Task/File-size/REXX/file-size-2.rexx @@ -1,11 +1,16 @@ -/*REXX pgm to verify a file's size (by reading the lines) on default MD.*/ -parse arg iFID /*let user specify the file ID. */ -if iFID='' then iFID="FILESIZ DAT A" /*Not specified? Then use default*/ -say 'size of' iFID "=" filesize(iFID) 'bytes' /*on the default MD.*/ -exit /*stick a fork in it, we're done.*/ +/*REXX pgm to verify a file's size */ +parse arg iFID . /*let user specify the file ID. */ +if iFID=='' then iFID="FILESIZ.DAT" /*Not specified? Then use default*/ +say 'size of' iFID':' +Say chars(ifid) '(CR LF included)' +Call lineout ifid /* close the file */ +say filesize(ifid) '(net data)' +Call lineout ifid +exit -/*──────────────────────────────────FILESIZE subroutine─────────────────*/ -filesize: parse arg f; $=0; do while lines(f)\==0 - $=$+length(linein(f)) - end /*while*/ -return $ +filesize: parse arg f; + sz=0; + Do while lines(f)\==0 + sz=sz+length(linein(f)) + End + return sz diff --git a/Task/File-size/REXX/file-size-3.rexx b/Task/File-size/REXX/file-size-3.rexx new file mode 100644 index 0000000000..2068d7f653 --- /dev/null +++ b/Task/File-size/REXX/file-size-3.rexx @@ -0,0 +1,11 @@ +/*REXX pgm to verify a file's size (by reading the lines) on default MD.*/ +parse arg iFID /*let user specify the file ID. */ +if iFID='' then iFID="FILESIZ DAT A" /*Not specified? Then use default*/ +say 'size of' iFID "=" filesize(iFID) 'bytes' /*on the default MD.*/ +exit /*stick a fork in it, we're done.*/ + +/*──────────────────────────────────FILESIZE subroutine─────────────────*/ +filesize: parse arg f; $=0; do while lines(f)\==0 + $=$+length(linein(f)) + end /*while*/ +return $ diff --git a/Task/File-size/Rust/file-size.rust b/Task/File-size/Rust/file-size.rust index b3ab788445..ce7dfc50a8 100644 --- a/Task/File-size/Rust/file-size.rust +++ b/Task/File-size/Rust/file-size.rust @@ -1,7 +1,13 @@ +use std::fs; + fn main() { - let path_wd = Path::new("input.txt"); - println!("{}", path_wd.stat().size); + let metadata = match fs::metadata("file.txt") { + Err(e) => { + println!("Error: {}", e); + return; + }, + Ok(f) => f, + }; - let path_root = Path::new("/input.txt"); - println!("{}", path_root.stat().size); + println!("Size of file.txt is {}", metadata.len()); } diff --git a/Task/Filter/Elixir/filter.elixir b/Task/Filter/Elixir/filter.elixir new file mode 100644 index 0000000000..2ff83da8ac --- /dev/null +++ b/Task/Filter/Elixir/filter.elixir @@ -0,0 +1,6 @@ +iex(10)> numbers = Enum.to_list(1..9) +[1, 2, 3, 4, 5, 6, 7, 8, 9] +iex(11)> Enum.filter(numbers, fn x -> rem(x,2)==0 end) +[2, 4, 6, 8] +iex(12)> for x <- numbers, rem(x,2)==0, do: x # comprehension +[2, 4, 6, 8] diff --git a/Task/Filter/Rust/filter.rust b/Task/Filter/Rust/filter.rust index 5bb6d34750..36be86332f 100644 --- a/Task/Filter/Rust/filter.rust +++ b/Task/Filter/Rust/filter.rust @@ -1,27 +1,12 @@ fn main() { - // Create a new vector, then use retain to filter what we want. - // Hopefully we will see .copy_iter() or .clone_iter() soon so - // we can write code like this: - - /* - let nums = range(1i32, 20i32).collect::>(); - let evens = nums.copy_iter().filter(|x| x % 2 == 0).collect::>(); - for i in evens.iter() { - println!("{}", i) - } - */ println!("new vec filtered: "); - let nums = range(1i32, 20i32).collect::>(); - let evens = nums.iter().map(|x| x.clone()).filter(|x| x % 2 == 0).collect::>(); - for i in evens.iter() { - println!("{}", i) - } + let nums: Vec = (1..20).collect(); + let evens: Vec = nums.iter().cloned().filter(|x| x % 2 == 0).collect(); + println!("{:?}", evens); // Filter an already existing vector println!("original vec filtered: "); - let mut nums = range(1i32, 20i32).collect::>(); + let mut nums: Vec = (1..20).collect(); nums.retain(|x| x % 2 == 0); - for i in nums.iter() { - println!("{}", i) - } + println!("{:?}", nums); } diff --git a/Task/Filter/VBScript/filter.vb b/Task/Filter/VBScript/filter.vb new file mode 100644 index 0000000000..68981a6f51 --- /dev/null +++ b/Task/Filter/VBScript/filter.vb @@ -0,0 +1,47 @@ +test_arr_1 = Array(1,2,3,4,5,6,7,8,9,10) +test_arr_2 = Array(1,2,3,4,5,6,7,8,9,10) + +WScript.StdOut.Write "Scenario 1: Create a new array" +WScript.StdOut.WriteLine +WScript.StdOut.Write "Input: " & Join(test_arr_1,",") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Output: " & filter_create(test_arr_1) +WScript.StdOut.WriteBlankLines(2) + +WScript.StdOut.Write "Scenario 2: Destructive approach" +WScript.StdOut.WriteLine +WScript.StdOut.Write "Input: " & Join(test_arr_2,",") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Output: " & filter_destruct(test_arr_2) +WScript.StdOut.WriteBlankLines(2) + +Function filter_create(arr) + ReDim arr_new(0) + For i = 0 To UBound(arr) + If arr(i) Mod 2 = 0 Then + If arr_new(0) = "" Then + arr_new(0) = arr(i) + Else + ReDim Preserve arr_new(UBound(arr_new)+1) + arr_new(UBound(arr_new)) = arr(i) + End If + End If + Next + filter_create = Join(arr_new,",") +End Function + +Function filter_destruct(arr) + count = 0 + For i = 0 To UBound(arr) + If arr(i) Mod 2 <> 0 Then + count = count + 1 + For j = i To UBound(arr) + If j + 1 <= UBound(arr) Then + arr(j) = arr(j+1) + End If + Next + End If + Next + ReDim Preserve arr(UBound(arr)-count) + filter_destruct = Join(arr,",") +End Function diff --git a/Task/Find-common-directory-path/00DESCRIPTION b/Task/Find-common-directory-path/00DESCRIPTION index a8519dbfc9..6dac691feb 100644 --- a/Task/Find-common-directory-path/00DESCRIPTION +++ b/Task/Find-common-directory-path/00DESCRIPTION @@ -7,3 +7,8 @@ Test your routine using the forward slash '/' character as the directory separat Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task. + +'''''See Also:''''' +* [[Longest common prefix]] + +
diff --git a/Task/Find-common-directory-path/Elixir/find-common-directory-path.elixir b/Task/Find-common-directory-path/Elixir/find-common-directory-path.elixir new file mode 100644 index 0000000000..5fe74dc10f --- /dev/null +++ b/Task/Find-common-directory-path/Elixir/find-common-directory-path.elixir @@ -0,0 +1,11 @@ +defmodule RC do + def common_directory_path(dirs, separator \\ "/") do + dir1 = Enum.min(dirs) |> String.split(separator) + dir2 = Enum.max(dirs) |> String.split(separator) + Enum.zip(dir1,dir2) |> Enum.take_while(fn {a,b} -> a==b end) + |> Enum.map_join(separator, fn {a,a} -> a end) + end +end + +dirs = ~w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members ) +IO.inspect RC.common_directory_path(dirs) diff --git a/Task/Find-common-directory-path/Julia/find-common-directory-path.julia b/Task/Find-common-directory-path/Julia/find-common-directory-path.julia new file mode 100644 index 0000000000..0b9d42a342 --- /dev/null +++ b/Task/Find-common-directory-path/Julia/find-common-directory-path.julia @@ -0,0 +1,27 @@ +function commonpath{T<:String}(ds::Array{T,1}, delim::Char='/') + 0 < length(ds) || return convert(T, "") + 1 < length(ds) || return ds[1] + p = split(ds[1], delim) + mcnt = length(p) + for d in ds[2:end] + q = split(d, delim) + mcnt = min(mcnt, length(q)) + hits = findfirst(p[1:mcnt] .== q[1:mcnt], false) + hits != 0 || continue + mcnt = hits - 1 + mcnt != 0 || return convert(T, "") + end + 1 < mcnt || p[1] != "" || return convert(T, string(delim)) + convert(T, join(p[1:mcnt], delim)) +end + +test = ["/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members"] + +println("Comparing") +for s in test + println(" ", s) +end +println("for their common directory path yields:") +println(" ", commonpath(test)) diff --git a/Task/Find-common-directory-path/PowerShell/find-common-directory-path-3.psh b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-3.psh new file mode 100644 index 0000000000..eb190d30ff --- /dev/null +++ b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-3.psh @@ -0,0 +1,14 @@ +Function Get-CommonPath( $Separator, $PathList ){ + $SplitPaths = $PathList | foreach { , $_.Split($Separator) } + $MinDirectoryDepth = $SplitPaths | Measure-Object -Property Length -Minimum | Select -ExpandProperty Minimum + $CommonPath = foreach ($Index in 0..($MinDirectoryDepth - 1)) { + $UniquePath = @($SplitPaths | foreach { $_[$Index] } | Sort -Unique) + if ($UniquePath.Length -gt 1) { + break; + } + + $UniquePath + } + + [String]::Join($Separator, $CommonPath) +} diff --git a/Task/Find-common-directory-path/PowerShell/find-common-directory-path-4.psh b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-4.psh new file mode 100644 index 0000000000..39d6a466f5 --- /dev/null +++ b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-4.psh @@ -0,0 +1,2 @@ +PS> Get-CommonPath '/' "/home/user1/tmp/coverage/test","/home/user1/tmp/covert/operator","/home/user1/tmp/coven/members" +/home/user1/tmp diff --git a/Task/Find-common-directory-path/Python/find-common-directory-path-2.py b/Task/Find-common-directory-path/Python/find-common-directory-path-2.py index 056d82d5f3..f53cf88529 100644 --- a/Task/Find-common-directory-path/Python/find-common-directory-path-2.py +++ b/Task/Find-common-directory-path/Python/find-common-directory-path-2.py @@ -1,5 +1,5 @@ ->>> def commonprefix(*args, sep='/'): - return os.path.commonprefix(*args).rpartition(sep)[0] +>>> def commonprefix(args, sep='/'): + return os.path.commonprefix(args).rpartition(sep)[0] >>> commonprefix(['/home/user1/tmp/coverage/test', '/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members']) diff --git a/Task/Find-common-directory-path/Ruby/find-common-directory-path-2.rb b/Task/Find-common-directory-path/Ruby/find-common-directory-path-2.rb index fe95b04764..1b177ceb6f 100644 --- a/Task/Find-common-directory-path/Ruby/find-common-directory-path-2.rb +++ b/Task/Find-common-directory-path/Ruby/find-common-directory-path-2.rb @@ -1,5 +1,5 @@ separator = '/' -paths = dirs.collect {|dir| dir.split(separator)} -uncommon_idx = paths[0].zip(*paths[1..-1]).index {|dirnames| dirnames.uniq.length > 1} -uncommon_idx = paths[0].length unless uncommon_idx # if uncommon_idx==nil -common_directory = paths[0][0...uncommon_idx].join(separator) # => "/home/user1/tmp" +path0, *paths = dirs.collect {|dir| dir.split(separator)} +uncommon_idx = path0.zip(*paths).index {|dirnames| dirnames.uniq.length > 1} +uncommon_idx = path0.length unless uncommon_idx # if uncommon_idx==nil +common_directory = path0[0...uncommon_idx].join(separator) # => "/home/user1/tmp" diff --git a/Task/Find-common-directory-path/Ruby/find-common-directory-path-3.rb b/Task/Find-common-directory-path/Ruby/find-common-directory-path-3.rb new file mode 100644 index 0000000000..e16700c1d0 --- /dev/null +++ b/Task/Find-common-directory-path/Ruby/find-common-directory-path-3.rb @@ -0,0 +1,6 @@ +def common_directory_path(dirs, separator='/') + dir1, dir2 = dirs.minmax.map{|dir| dir.split(separator)} + dir1.zip(dir2).take_while{|dn1,dn2| dn1==dn2}.map(&:first).join(separator) +end + +p common_directory_path(dirs) #=> "/home/user1/tmp" diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Eiffel/find-largest-left-truncatable-prime-in-a-given-base.e b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Eiffel/find-largest-left-truncatable-prime-in-a-given-base.e new file mode 100644 index 0000000000..bbfd56dc0f --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Eiffel/find-largest-left-truncatable-prime-in-a-given-base.e @@ -0,0 +1,122 @@ +class + LARGEST_LEFT_TRUNCABLE_PRIME + +create + make + +feature + + make + -- Tests find_prime for different bases. + local + i: INTEGER + decimal: INTEGER_64 + do + from + i := 3 + until + i = 10 + loop + largest := 0 + find_prime ("", i) + decimal := convert_to_decimal (largest, i) + io.put_string (i.out + ":%T" + decimal.out) + io.new_line + i := i + 1 + end + end + + find_prime (right_part: STRING; base: INTEGER) + -- Largest left truncable prime for a given 'base'. + local + i, larger, larger_dec: INTEGER_64 + right: STRING + prime: BOOLEAN + do + from + i := 1 + until + i = base + loop + create right.make_empty + right.deep_copy (right_part) + right.prepend (i.out) + larger := right.to_integer_64 + if base /= 10 then + larger_dec := convert_to_decimal (larger, base) + if larger_dec < 0 then + io.put_string ("overflow") + prime := False + else + prime := is_prime (larger_dec) + end + else + prime := is_prime (larger) + end + if prime = TRUE then + find_prime (larger.out, base) + else + if right_part.count > 0 and right_part.to_integer_64 > largest then + largest := right_part.to_integer_64 + end + end + i := i + 1 + end + end + + largest: INTEGER_64 + + convert_to_decimal (given, base: INTEGER_64): INTEGER_64 + -- 'given' converted to base ten. + require + local + n, i: INTEGER + st_digits: STRING + dec: REAL_64 + do + n := given.out.count + dec := 0 + st_digits := given.out + from + i := 1 + until + n < 0 or i > given.out.count + loop + n := n - 1 + dec := dec + st_digits.at (i).out.to_integer * base ^ n + i := i + 1 + end + Result := dec.truncated_to_integer_64 + end + + is_prime (n: INTEGER_64): BOOLEAN + --Is 'n' a prime number? + require + positiv_input: n > 0 + local + i: INTEGER + max: REAL_64 + math: DOUBLE_MATH + do + create math + if n = 2 then + Result := True + elseif n <= 1 or n \\ 2 = 0 then + Result := False + else + Result := True + max := math.sqrt (n) + from + i := 3 + until + i > max + loop + if n \\ i = 0 then + Result := False + end + i := i + 2 + end + end + end + +end diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-1.j b/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-1.j new file mode 100644 index 0000000000..367cd5ddf3 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-1.j @@ -0,0 +1,7 @@ +ltp=:3 :0 + probe=. i.1 0 + while. #probe do. + probe=. (#~ 1 p: y #.]),/(}.i.y),"0 _1/have=. probe + end. + >./y#.have +) diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-2.j b/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-2.j new file mode 100644 index 0000000000..0151e2fe55 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-2.j @@ -0,0 +1,10 @@ + (,ltp)"0]3 4 5 6 7 8 9 10 11 + 3 23 + 4 4091 + 5 7817 + 6 4836525320399 + 7 817337 + 8 14005650767869 + 9 1676456897 +10 992429121339693967 +11 2276005673 diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-3.j b/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-3.j new file mode 100644 index 0000000000..6daa0400f7 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base-3.j @@ -0,0 +1,18 @@ + (,ltp)"0]3}.i.20x + 3 23 + 4 4091 + 5 7817 + 6 4836525320399 + 7 817337 + 8 14005650767869 + 9 1676456897 +10 357686312646216567629137 +11 2276005673 +12 13092430647736190817303130065827539 +13 812751503 +14 615419590422100474355767356763 +15 34068645705927662447286191 +16 1088303707153521644968345559987 +17 13563641583101 +18 571933398724668544269594979167602382822769202133808087 +19 546207129080421139 diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base.j b/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base.j deleted file mode 100644 index d8e11c81be..0000000000 --- a/Task/Find-largest-left-truncatable-prime-in-a-given-base/J/find-largest-left-truncatable-prime-in-a-given-base.j +++ /dev/null @@ -1,30 +0,0 @@ -Filter=: (#~`)(`:6) -Filter=: (#~`)(`:6) - -f=: 3 : 0 -BASE=. y -primes=. (1&p:)Filter -DIGITS=. }. i. x: BASE -R=. 0 -A=. ,0 -while. #A do. - R=. >: R - B=. A - A=. primes , , A +/ BASE #. (_,R) {. ,. DIGITS -end. ->./ B -) -l -NB. f N where N is the base. - (,. f"0) (3+i.8) - 3 23 - 4 4091 - 5 7817 - 6 4836525320399 - 7 817337 - 8 14005650767869 - 9 1676456897 -10 357686312646216567629137 - - f 11 -2276005673 diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Julia/find-largest-left-truncatable-prime-in-a-given-base.julia b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Julia/find-largest-left-truncatable-prime-in-a-given-base.julia new file mode 100644 index 0000000000..860a7b7b3d --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Julia/find-largest-left-truncatable-prime-in-a-given-base.julia @@ -0,0 +1,35 @@ +function addmsdigit{T<:Integer}(p::T, b::T, s::T) + a = T[] + q = p + for i in 1:(b-1) + q += s + isprime(q) || continue + push!(a, q) + end + return a +end + +function lefttruncprime{T<:Integer}(pbase::T) + b = convert(BigInt, pbase) + a = BigInt[] + append!(a, primes(b-1)) + mlt = zero(BigInt) + s = one(BigInt) + while !isempty(a) + mlt = maximum(a) + s *= b + for i in 1:length(a) + p = shift!(a) + append!(a, addmsdigit(p, b, s)) + end + end + return mlt +end + +lo, hi = 3, 17 +print("The largest left truncatable primes for bases") +println(@sprintf " %d to %d." lo hi) +for i in lo:hi + mlt = lefttruncprime(i) + println(@sprintf " %3d %d (%s)" i mlt base(i, mlt)) +end diff --git a/Task/Find-limit-of-recursion/ALGOL-68/find-limit-of-recursion.alg b/Task/Find-limit-of-recursion/ALGOL-68/find-limit-of-recursion.alg new file mode 100644 index 0000000000..7bd44aaec6 --- /dev/null +++ b/Task/Find-limit-of-recursion/ALGOL-68/find-limit-of-recursion.alg @@ -0,0 +1 @@ +PROC recurse = VOID : recurse; recurse diff --git a/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-1.julia b/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-1.julia new file mode 100644 index 0000000000..6f9e8ba2bf --- /dev/null +++ b/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-1.julia @@ -0,0 +1,7 @@ +function divedivedive(d::Int) + try + divedivedive(d+1) + catch + return d + end +end diff --git a/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-2.julia b/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-2.julia new file mode 100644 index 0000000000..46037ddf4f --- /dev/null +++ b/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-2.julia @@ -0,0 +1,5 @@ +function divedivedive() + global depth + depth += 1 + divedivedive() +end diff --git a/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-3.julia b/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-3.julia new file mode 100644 index 0000000000..5de986dde7 --- /dev/null +++ b/Task/Find-limit-of-recursion/Julia/find-limit-of-recursion-3.julia @@ -0,0 +1,8 @@ +depth = divedivedive(0) +println("A clean dive reaches a depth of ", depth, ".") + +depth = 0 +try + divedivedive() +end +println("A dirty dive reaches a depth of ", depth, ".") diff --git a/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion.rust b/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion.rust new file mode 100644 index 0000000000..db98837774 --- /dev/null +++ b/Task/Find-limit-of-recursion/Rust/find-limit-of-recursion.rust @@ -0,0 +1,8 @@ +fn recurse(n: i32) { + println!("depth: {}", n); + recurse(n + 1) +} + +fn main() { + recurse(0); +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Befunge/find-the-last-sunday-of-each-month.bf b/Task/Find-the-last-Sunday-of-each-month/Befunge/find-the-last-sunday-of-each-month.bf new file mode 100644 index 0000000000..569542a55e --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Befunge/find-the-last-sunday-of-each-month.bf @@ -0,0 +1,6 @@ +":raeY",,,,,&>55+,:::45*:*%\"d"%!*\4%+!3v +v2++6**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5< +>:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v +^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6 +>$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8 +^<# #"#"##"#"##!` +76:+1g00,+55,+*< diff --git a/Task/Find-the-last-Sunday-of-each-month/C/find-the-last-sunday-of-each-month.c b/Task/Find-the-last-Sunday-of-each-month/C/find-the-last-sunday-of-each-month.c new file mode 100644 index 0000000000..739d0df4f5 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/C/find-the-last-sunday-of-each-month.c @@ -0,0 +1,57 @@ +#include +#include +#include + +#define NUM_MONTHS 12 + +void LastSundays(int year) +{ + time_t t; + struct tm* datetime; + + int sunday=0; + int dayOfWeek=0; + int month=0; + int monthDay=0; + int isLeapYear=0; + int daysInMonth[NUM_MONTHS]={ + 31,28,31,30,31,30,31,31,30,31,30,31 + }; + + isLeapYear=(year%4==0 || ((year%100==0) && (year%400==0))); + + if(isLeapYear) + { + daysInMonth[1]=29; + } + + time(&t); + datetime = localtime(&t); + datetime->tm_year=year-1900; + for(month=0; month<12;month++) + { + datetime->tm_mon=month; + monthDay=daysInMonth[month]; + datetime->tm_mday=monthDay; + + t = mktime(datetime); + dayOfWeek=datetime->tm_wday; + + while(dayOfWeek!=sunday) + { + monthDay--; + datetime->tm_mday=monthDay; + t = mktime(datetime); + dayOfWeek=datetime->tm_wday; + + } + printf("%d-%02d-%02d\n",year,month+1,monthDay); + } + +} + +int main() +{ + LastSundays(2013); + return 0; +} diff --git a/Task/Find-the-last-Sunday-of-each-month/Elixir/find-the-last-sunday-of-each-month.elixir b/Task/Find-the-last-Sunday-of-each-month/Elixir/find-the-last-sunday-of-each-month.elixir new file mode 100644 index 0000000000..9b6c10614b --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Elixir/find-the-last-sunday-of-each-month.elixir @@ -0,0 +1,15 @@ +defmodule RC do + def lastSunday(year) do + Enum.map(1..12, fn month -> + lastday = :calendar.last_day_of_the_month(year, month) + daynum = :calendar.day_of_the_week(year, month, lastday) + sunday = lastday - rem(daynum, 7) + {year, month, sunday} + end) + end +end + +y = String.to_integer(hd(System.argv)) +Enum.each(RC.lastSunday(y), fn {year, month, day} -> + :io.format "~4b-~2..0w-~2..0w~n", [year, month, day] +end) diff --git a/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month.js b/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month.js new file mode 100644 index 0000000000..f4d4758d54 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month.js @@ -0,0 +1,11 @@ +function lastSundayOfEachMonths(year) { + var lastDay = [31,28,31,30,31,30,31,31,30,31,30,31] + if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) lastDay[2] = 29 + for (var date = new Date(), month=0; month<12; month+=1) { + date.setFullYear(year, month, lastDay[month]) + date.setDate(date.getDate()-date.getDay()) + document.write(date.toISOString().substring(0,10), '
') + } +} + +lastSundayOfEachMonths(2013) diff --git a/Task/Find-the-last-Sunday-of-each-month/Julia/find-the-last-sunday-of-each-month.julia b/Task/Find-the-last-Sunday-of-each-month/Julia/find-the-last-sunday-of-each-month.julia new file mode 100644 index 0000000000..a46adc0e7a --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Julia/find-the-last-sunday-of-each-month.julia @@ -0,0 +1,25 @@ +isdefined(:Date) || using Dates + +const wday = Dates.Sun +const lo = 1 +const hi = 12 + +print("\nThis script will print the last ", Dates.dayname(wday)) +println("s of each month of the year given.") +println("(Leave input empty to quit.)") + +while true + print("\nYear> ") + y = chomp(readline()) + 0 < length(y) || break + y = try + parseint(y) + catch + println("Sorry, but that does not compute as a year.") + continue + end + println() + for m in Date(y, lo):Month(1):Date(y, hi) + println(" ", tolast(m, wday)) + end +end diff --git a/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 b/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 index 77d88811fc..b9da41e6c5 100644 --- a/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 +++ b/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 @@ -1,8 +1,6 @@ -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 ; +sub MAIN ($year = Date.new.year) { + for 1..12 -> $mo { + my $month-end = Date.new($year, $mo, Date.days-in-month($year, $mo)); + say $month-end - $month-end.day-of-week % 7; + } } diff --git a/Task/Find-the-missing-permutation/00DESCRIPTION b/Task/Find-the-missing-permutation/00DESCRIPTION index 259e257666..38dda59fd6 100644 --- a/Task/Find-the-missing-permutation/00DESCRIPTION +++ b/Task/Find-the-missing-permutation/00DESCRIPTION @@ -12,6 +12,10 @@ Hint : if all permutations were here, how many times would A appear in each position ? What is the parity of this number ? +There is another alternate method. +Hint: if you add up the letter values of each column, does a missing letter A, B, C, D +from each column cause the total value for each column to be unique? +
ABCD
 CABD
 ACDB
diff --git a/Task/Find-the-missing-permutation/Elixir/find-the-missing-permutation.elixir b/Task/Find-the-missing-permutation/Elixir/find-the-missing-permutation.elixir
new file mode 100644
index 0000000000..1c0609ac80
--- /dev/null
+++ b/Task/Find-the-missing-permutation/Elixir/find-the-missing-permutation.elixir
@@ -0,0 +1,18 @@
+defmodule RC do
+  def find_miss_perm(head, perms) do
+    all_permutations(head) -- perms
+  end
+
+  defp all_permutations(string) do
+    list = String.split(string, "", trim: true)
+    Enum.map(permutations(list), fn x -> Enum.join(x) end)
+  end
+
+  defp permutations([]), do: [[]]
+  defp permutations(list), do: (for x <- list, y <- permutations(list -- [x]), do: [x|y])
+end
+
+perms = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",
+         "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]
+
+IO.inspect RC.find_miss_perm( hd(perms), perms )
diff --git a/Task/Find-the-missing-permutation/J/find-the-missing-permutation-7.j b/Task/Find-the-missing-permutation/J/find-the-missing-permutation-7.j
new file mode 100644
index 0000000000..df811415e4
--- /dev/null
+++ b/Task/Find-the-missing-permutation/J/find-the-missing-permutation-7.j
@@ -0,0 +1,2 @@
+   ,(~.#~2|(#/.~))"1|:data
+DBAC
diff --git a/Task/Find-the-missing-permutation/J/find-the-missing-permutation-8.j b/Task/Find-the-missing-permutation/J/find-the-missing-permutation-8.j
new file mode 100644
index 0000000000..f8417e08ee
--- /dev/null
+++ b/Task/Find-the-missing-permutation/J/find-the-missing-permutation-8.j
@@ -0,0 +1,2 @@
+   ({.data){~|(->./)+/({.i.])data
+DBAC
diff --git a/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-1.julia b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-1.julia
new file mode 100644
index 0000000000..8e2f3e2a4d
--- /dev/null
+++ b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-1.julia
@@ -0,0 +1,15 @@
+function find_missing_permutations{T<:String}(a::Array{T,1})
+    std = unique(sort(split(a[1], "")))
+    needsperm = trues(factorial(length(std)))
+    for s in a
+        b = split(s, "")
+        p = map(x->findfirst(std, x), b)
+        isperm(p) || throw(DomainError())
+        needsperm[nthperm(p)] = false
+    end
+    mperms = T[]
+    for i in findn(needsperm)[1]
+        push!(mperms, join(nthperm(std, i), ""))
+    end
+    return mperms
+end
diff --git a/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-2.julia b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-2.julia
new file mode 100644
index 0000000000..5bb63072ef
--- /dev/null
+++ b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-2.julia
@@ -0,0 +1,24 @@
+test = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",
+        "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA",
+        "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD",
+        "BADC", "BDAC", "CBDA", "DBCA", "DCAB"]
+
+missperms = find_missing_permutations(test)
+
+print("The test list is:\n    ")
+i = 0
+for s in test
+    print(s, " ")
+    i += 1
+    i %= 5
+    i != 0 || print("\n    ")
+end
+i == 0 || println()
+if length(missperms) > 0
+    println("The following permutations are missing:")
+    for s in missperms
+        println("    ", s)
+    end
+else
+    println("There are no missing permutations.")
+end
diff --git a/Task/Find-the-missing-permutation/PowerShell/find-the-missing-permutation.psh b/Task/Find-the-missing-permutation/PowerShell/find-the-missing-permutation.psh
new file mode 100644
index 0000000000..22c6bcf55c
--- /dev/null
+++ b/Task/Find-the-missing-permutation/PowerShell/find-the-missing-permutation.psh
@@ -0,0 +1,56 @@
+function permutation ($array) {
+    function generate($n, $array, $A) {
+        if($n -eq 1) {
+            $array[$A] -join ''
+        }
+        else{
+            for( $i = 0; $i -lt ($n - 1); $i += 1) {
+                generate ($n - 1) $array $A
+                if($n % 2 -eq 0){
+                    $i1, $i2 = $i, ($n-1)
+                    $temp = $A[$i1]
+                    $A[$i1] = $A[$i2]
+                    $A[$i2] = $temp
+                }
+                else{
+                    $i1, $i2 = 0, ($n-1)
+                    $temp = $A[$i1]
+                    $A[$i1] = $A[$i2]
+                    $A[$i2] = $temp
+                }
+            }
+            generate ($n - 1) $array $A
+        }
+    }
+    $n = $array.Count
+    if($n -gt 0) {
+        (generate $n $array (0..($n-1)))
+    } else {$array}
+}
+$perm = permutation @('A','B','C', 'D')
+$find = @(
+"ABCD"
+"CABD"
+"ACDB"
+"DACB"
+"BCDA"
+"ACBD"
+"ADCB"
+"CDAB"
+"DABC"
+"BCAD"
+"CADB"
+"CDBA"
+"CBAD"
+"ABDC"
+"ADBC"
+"BDCA"
+"DCBA"
+"BACD"
+"BADC"
+"BDAC"
+"CBDA"
+"DBCA"
+"DCAB"
+)
+$perm | where{-not $find.Contains($_)}
diff --git a/Task/Find-the-missing-permutation/REXX/find-the-missing-permutation.rexx b/Task/Find-the-missing-permutation/REXX/find-the-missing-permutation.rexx
index 1b6e34067d..494f6c188e 100644
--- a/Task/Find-the-missing-permutation/REXX/find-the-missing-permutation.rexx
+++ b/Task/Find-the-missing-permutation/REXX/find-the-missing-permutation.rexx
@@ -1,30 +1,29 @@
-/*REXX program finds (a)  missing permutation(s)  from an internal list.*/
-list = 'ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA',
-       'CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'
-@.=                                    /* [↓]  needs to be THINGS long. */
-@abcU  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  /*an uppercase (Latin) alphabet. */
-things = 4                             /*# of unique letters to be used.*/
-bunch  = 4                             /*# letters to be used at a time.*/
-                 do j=1  for things
-                 $.j=substr(@abcU,j,1)
-                 end   /*j*/           /* [↑]  construct a letter array.*/
-call permset 1                         /*invoke  PERMSET  (recursively).*/
-exit                                   /*stick a fork in it, we're done.*/
-/*──────────────────────────────────PERMSET subroutine──────────────────*/
-permset: procedure expose $. @. bunch list things;   parse arg ?
+/*REXX program finds one or more  missing permutations  from an internal list.*/
+          list = 'ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA',
+                 'CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'
+@.=                                    /* [↓]  needs to be as long as  THINGS.*/
+@abcU  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  /*an uppercase (Latin/Roman) alphabet. */
+things = 4                             /*number of unique letters to be used. */
+bunch  = 4                             /*number letters to be used at a time. */
+                 do j=1  for things    /* [↓]  only get a portion of alphabet.*/
+                 $.j=substr(@abcU,j,1) /*extract just one letter from alphabet*/
+                 end   /*j*/           /* [↑]  build a letter array for speed.*/
+call permSet 1                         /*invoke  PERMSET  sub. (recursively). */
+exit                                   /*stick a fork in it,  we're all done. */
+/*────────────────────────────────────────────────────────────────────────────*/
+permSet: procedure expose $. @. bunch list things;    parse arg ?
 if ?>bunch  then do
-                 _=;         do m=1  for bunch       /*build permutation*/
-                             _=_ || @.m              /*add perm ──► list*/
-                             end   /*m*/
-                                                     /* [↓]  is in list?*/
-                 if wordpos(_,list)==0  then say _ ' is missing from the list.'
+                 _=;      do m=1  for bunch           /*build a permutation.  */
+                          _=_ || @.m                  /*add permutation──►list*/
+                          end   /*m*/
+                                                      /* [↓]  is in the list? */
+                 if wordpos(_,list)==0  then say _  ' is missing from the list.'
                  end
-            else do x=1  for things                  /*build a new perm.*/
-
-                             do k=1  for ?-1
-                             if @.k==$.x  then iterate x   /*been built?*/
-                             end  /*k*/
-                 @.?=$.x                             /*define as built. */
-                 call permset ?+1                    /*call recursively.*/
+            else do x=1  for things                   /*build a permutation.  */
+                          do k=1  for ?-1
+                          if @.k==$.x then iterate x  /*was permutation built?*/
+                          end  /*k*/
+                 @.?=$.x                              /*define as being built.*/
+                 call permSet  ?+1                    /*call subr. recursively*/
                  end   /*x*/
 return
diff --git a/Task/First-class-functions-Use-numbers-analogously/Perl-6/first-class-functions-use-numbers-analogously.pl6 b/Task/First-class-functions-Use-numbers-analogously/Perl-6/first-class-functions-use-numbers-analogously.pl6
index 0c10f55670..f21db5782a 100644
--- a/Task/First-class-functions-Use-numbers-analogously/Perl-6/first-class-functions-use-numbers-analogously.pl6
+++ b/Task/First-class-functions-Use-numbers-analogously/Perl-6/first-class-functions-use-numbers-analogously.pl6
@@ -10,4 +10,4 @@ my $zi = 1.0 / ( $x + $y );
 my @numbers = $x, $y, $z;
 my @inverses = $xi, $yi, $zi;
 
-for @numbers Z @inverses { say multiplied($^g, $^f)(.5) }
+for flat @numbers Z @inverses { say multiplied($^g, $^f)(.5) }
diff --git a/Task/First-class-functions/Julia/first-class-functions.julia b/Task/First-class-functions/Julia/first-class-functions.julia
new file mode 100644
index 0000000000..629af99463
--- /dev/null
+++ b/Task/First-class-functions/Julia/first-class-functions.julia
@@ -0,0 +1,11 @@
+#!/usr/bin/julia
+
+function compose(f::Function, g::Function)
+  return x -> f(g(x))
+end
+
+value = 0.5
+for pair in [(sin, asin), (cos, acos), (x -> x^3, x -> x^(1/3))]
+  func, inverse = pair
+  println(compose(func, inverse)(value))
+end
diff --git a/Task/First-class-functions/REXX/first-class-functions.rexx b/Task/First-class-functions/REXX/first-class-functions.rexx
index 1b466cdd4f..0a3f0be5bd 100644
--- a/Task/First-class-functions/REXX/first-class-functions.rexx
+++ b/Task/First-class-functions/REXX/first-class-functions.rexx
@@ -7,35 +7,27 @@ w=digits()                             /*W=width of numbers to be shown.*/
      say center("number",w) center('function',3*w+1) center("inverse",4*w)
      say copies("─",w)      copies("─",3*w+1)        copies("─",4*w)
      if j<2   then call test j, 20  60   500   /*x2d,d2x; integers only.*/
-              else call test j,  0  0.5  1  2  /*all else, floating pt. */
+              else call test j, 0  0.5  1  2   /*all else, floating pt. */
      end   /*j*/
 exit                                   /*stick a fork in it, we're done.*/
-/*──────────────────────────────────INVOKE subroutine───────────────────*/
-invoke: parse arg fn,v;  q='"';  if datatype(v,'N')  then q=
-_=fn||'('q||v||q')';     interpret 'func='_;         return func
-/*──────────────────────────────────TEST subroutine─────────────────────*/
-test: procedure expose A B w;  parse arg fu,xList    /*xList=bunch of #s*/
-        do k=1  for words(xList);                      x=word(xList,k)
-        numeric digits digits()+5                    /*higher precision.*/
-        fun=word(A,fu);   funV=invoke(fun,x)   ;              funInvoke=_
-        inv=word(B,fu);   invV=invoke(inv,funV);              invInvoke=_
-        numeric digits digits()-5                    /*restore precision*/
-        if datatype(funV,'N')  then funV=funV/1      /*round to digits()*/
-        if datatype(invV,'N')  then invV=invV/1      /*round to digits()*/
-        say center(x,w)   right(funInvoke,2*w)'='left(funV,w),
-                          right(invInvoke,3*w)'='left(invV,w)
-        end   /*k*/
-return
-/*──────────────────────────────────subroutines (functions)─────────────*/
+/*──────────────────────────────────subroutines (functions)───────────────────*/
+Acos:    procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x)
+r2r:     return arg(1) // (2*pi())       /*normalize radians ──► 1 unit circle*/
+square:  return arg(1) ** 2
+tellErr: say;   say '*** error! ***';  say;  say arg(1);  say;  exit 13
+tanErr:  call tellErr 'tan('||x") causes division by zero, X="               ||x
+AsinErr: call tellErr 'Asin(x),  X  must be in the range of  -1 ──► +1,  X=' ||x
+AcosErr: call tellErr 'Acos(x),  X  must be in the range of  -1 ──► +1,  X=' ||x
+
 Asin: procedure;   arg x;   if x<-1 | x>1 then call AsinErr;   s=x*x
-      if abs(x)>=.7  then return sign(x)*Acos(sqrt(1-s));  z=x;  o=x;  p=z
-      do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end
-      return z
+          if abs(x)>=.7  then return sign(x)*Acos(sqrt(1-s));  z=x;  o=x;  p=z
+          do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end
+          return z
 
-cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9)
-                if a=pi() then return -1;  if a=pi()/2 | a=2*pi() then return 0
-                if a=pi()/3 then return .5;  if a=2*pi()/3 then return -.5
-                return .sinCos(1,1,-1)
+cos:  procedure; parse arg x;       x=r2r(x);         a=abs(x);      hpi=pi*.5
+          numeric fuzz min(6,digits()-3);          if a=pi()    then return -1
+          if a=hpi | a=hpi*3  then return  0 ;     if a=pi()/3  then return .5
+          if a=pi()*2/3       then return -.5;            return .sinCos(1,1,-1)
 
 sin: procedure; arg x;  x=r2r(x);    numeric fuzz min(5,digits()-3)
                 if abs(x)=pi()  then return 0;   return .sinCos(x,x,1)
@@ -43,20 +35,28 @@ sin: procedure; arg x;  x=r2r(x);    numeric fuzz min(5,digits()-3)
 .sinCos: parse arg z 1 p,_,i;  x=x*x
          do k=2 by 2; _=-_*x/(k*(k+i));z=z+_;if z=p then leave;p=z;end; return z
 
-sqrt: procedure; parse arg x; if x=0  then return 0;  m.=9; p=digits(); i=
-numeric digits 9; if x<0  then do; x=-x; i='i'; end;  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)i
-
-pi: return,                            /*a bit of overkill,  but hey !! */
-3.1415926535897932384626433832795028841971693993751058209749445923078164062862
-
-Acos:  procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x)
-r2r:   return arg(1)//(2*pi())         /*normalize radians►1 unit circle*/
-square:  return arg(1)**2
-tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13
-tanErr:  call tellErr 'tan('||x") causes division by zero, X="||x
-AsinErr: call tellErr 'Asin(x),  X  must be in the range of  -1 ──► +1,  X='||x
-AcosErr: call tellErr 'Acos(x),  X  must be in the range of  -1 ──► +1,  X='||x
+invoke:  parse arg fn,v;  q='"';  if datatype(v,'N')  then q=
+         _=fn || '('q||v||q')';      interpret 'func='_;             return func
+
+pi:   pi=3.141592653589793238462643383279502884197169399375105820974944 ||,
+           5923078164062862;                 return pi
+
+sqrt: procedure; parse arg x;   if x=0  then return 0;  d=digits();  i=;   m.=9
+      numeric digits 9; numeric form; h=d+6;  if x<0  then  do; x=-x; i='i'; end
+      parse value format(x,2,1,,0) 'E0'  with  g 'E' _ .;       g=g*.5'e'_%2
+         do j=0  while h>9;      m.j=h;              h=h%2+1;         end  /*j*/
+         do k=j+5  to 0  by -1;  numeric digits m.k; g=(g+x/g)*.5;    end  /*k*/
+      numeric digits d;     return (g/1)i            /*make complex if  X < 0.*/
+
+test: procedure expose A B w;  parse arg fu,xList          /*xList=bunch of #s*/
+              do k=1  for words(xList);                 x=word(xList,k)
+              numeric digits digits()+5                    /*higher precision.*/
+              fun=word(A,fu);   funV=invoke(fun,x)   ;  funInvoke=_
+              inv=word(B,fu);   invV=invoke(inv,funV);  invInvoke=_
+              numeric digits digits()-5                    /*restore precision*/
+              if datatype(funV,'N')  then funV=funV/1      /*round to digits()*/
+              if datatype(invV,'N')  then invV=invV/1      /*round to digits()*/
+              say center(x,w)   right(funInvoke,2*w)'='left(funV,w),
+                                right(invInvoke,3*w)'='left(invV,w)
+              end   /*k*/
+      return
diff --git a/Task/Five-weekends/00META.yaml b/Task/Five-weekends/00META.yaml
index 2f9fac8f1f..035a20a5fd 100644
--- a/Task/Five-weekends/00META.yaml
+++ b/Task/Five-weekends/00META.yaml
@@ -1,5 +1,4 @@
 ---
 category:
-- Date and time
 - Puzzles
-note: Five weekends
+note: Date and time
diff --git a/Task/Five-weekends/CoffeeScript/five-weekends-1.coffee b/Task/Five-weekends/CoffeeScript/five-weekends-1.coffee
new file mode 100644
index 0000000000..4e8c8748fb
--- /dev/null
+++ b/Task/Five-weekends/CoffeeScript/five-weekends-1.coffee
@@ -0,0 +1,40 @@
+startsOnFriday = (month, year) ->
+  # 0 is Sunday, 1 is Monday, ... 5 is Friday, 6 is Saturday
+  new Date(year, month, 1).getDay() == 5
+
+has31Days = (month, year) ->
+  new Date(year, month, 31).getDate() == 31
+
+checkMonths = (year) ->
+  month = undefined
+  count = 0
+  month = 0
+  while month < 12
+    if startsOnFriday(month, year) and has31Days(month, year)
+      count += 1
+      console.log year + ' ' + month + ''
+    month += 1
+  count
+
+fiveWeekends = ->
+  startYear = 1900
+  endYear = 2100
+  year = undefined
+  monthTotal = 0
+  yearsWithoutFiveWeekends = []
+  total = 0
+  year = startYear
+  while year <= endYear
+    monthTotal = checkMonths(year)
+    total += monthTotal
+    # extra credit
+    if monthTotal == 0
+      yearsWithoutFiveWeekends.push year
+    year += 1
+  console.log 'Total number of months: ' + total + ''
+  console.log ''
+  console.log yearsWithoutFiveWeekends + ''
+  console.log 'Years with no five-weekend months: ' + yearsWithoutFiveWeekends.length + ''
+  return
+
+fiveWeekends()
diff --git a/Task/Five-weekends/CoffeeScript/five-weekends-2.coffee b/Task/Five-weekends/CoffeeScript/five-weekends-2.coffee
new file mode 100644
index 0000000000..428e4c1591
--- /dev/null
+++ b/Task/Five-weekends/CoffeeScript/five-weekends-2.coffee
@@ -0,0 +1,30 @@
+1901 2
+1902 7
+1903 4
+1904 0
+1904 6
+1905 11
+1907 2
+1908 4
+1909 0
+1909 9
+1910 6
+1911 11
+1912 2
+1913 7
+1914 4
+1915 0
+1915 9
+1916 11
+1918 2
+1919 7
+1920 9
+1921 6
+1922 11
+1924 7
+..
+
+Total number of months: 201
+1900,1906,1917,1923,1928,1934,1945,1951,1956,1962,1973,1979,1984,1990,2001,2007,2012,2018,2029,2035,2040,2046,2057,2063,2068,2074,2085,2091,2096
+
+Years with no five-weekend months: 29
diff --git a/Task/Five-weekends/Elixir/five-weekends.elixir b/Task/Five-weekends/Elixir/five-weekends.elixir
new file mode 100644
index 0000000000..346b7289db
--- /dev/null
+++ b/Task/Five-weekends/Elixir/five-weekends.elixir
@@ -0,0 +1,18 @@
+defmodule Date do
+  @months { "January", "February", "March",     "April",   "May",      "June",
+            "July",    "August",   "September", "October", "November", "December" }
+
+  def five_weekends(year) do
+    for m <-[1,3,5,7,8,10,12], :calendar.day_of_the_week(year, m, 31) == 7, do: elem(@months, m-1)
+  end
+end
+
+months = Enum.map(1900..2100, fn year -> {year, Date.five_weekends(year)} end)
+{none, months5} = Enum.partition(months, fn {_,m} -> Enum.empty?(m) end)
+count = Enum.reduce(months5, 0, fn {year, months}, acc ->
+  IO.puts "#{year} : #{Enum.join(months, ", ")}"
+  acc + length(months)
+end)
+IO.puts "Found #{count} month with 5 weekends."
+IO.puts "\nFound #{length(none)} years with no month having 5 weekends:"
+IO.puts "#{inspect Enum.map(none, fn {y,_}-> y end)}"
diff --git a/Task/Five-weekends/Julia/five-weekends.julia b/Task/Five-weekends/Julia/five-weekends.julia
new file mode 100644
index 0000000000..b16692c175
--- /dev/null
+++ b/Task/Five-weekends/Julia/five-weekends.julia
@@ -0,0 +1,26 @@
+isdefined(:Date) || using Dates
+
+const wday = Dates.Fri
+const lo = 1900
+const hi = 2100
+const showres = 5
+
+mfive = recur(Date(lo, 1):Month(1):Date(hi, 12)) do m
+    Dates.daysinmonth(m) == 31 && Dates.dayofweek(m) == wday
+end
+
+println("Considering the years from ", lo, " to ", hi, ".\n")
+println("There are ", length(mfive), " months having 5 3-day weekends.")
+
+println("The first ", showres, " such months are:")
+for m in mfive[1:showres]
+    println("    ", Dates.monthname(m), " ", Dates.year(m))
+end
+
+println("\nThe last ", showres, " such months are:")
+for m in mfive[end-showres+1:end]
+    println("    ", Dates.monthname(m), " ", Dates.year(m))
+end
+
+print("\nThere are ", length(filter(y -> !(y in year(mfive)), lo:hi)))
+println(" years that have no such months.")
diff --git a/Task/Five-weekends/Perl-6/five-weekends.pl6 b/Task/Five-weekends/Perl-6/five-weekends.pl6
index 5127fe4a8b..8c80fd1326 100644
--- a/Task/Five-weekends/Perl-6/five-weekends.pl6
+++ b/Task/Five-weekends/Perl-6/five-weekends.pl6
@@ -1,11 +1,10 @@
 # A month has 5 weekends iff it has 31 days and starts on Friday.
 
 my @years = 1900 .. 2100;
-my @ym = @years X 1, 3, 5, 7, 8, 10, 12; # Months with 31 days
+my @has31 = 1, 3, 5, 7, 8, 10, 12;
+my @happy = ($_ when *.day-of-week == 5 for (@years X @has31).map(-> ($y, $m) { Date.new: $y, $m, 1 }));
 
-my @happy = @ym.map({ Date.new: $^a, $^b, 1 }).grep: { .day-of-week == 5 };
-
-say 'Happy month count:  ',  +@happy;
+say 'Happy month count:  ', +@happy;
 say 'First happy months: ' ~ @happy[^5];
 say 'Last  happy months: ' ~ @happy[*-5 .. *];
-say 'Dreary years count: ',  @years - @happy».year.uniq;
+say 'Dreary years count: ',  @years - @happy».year.squish;
diff --git a/Task/Five-weekends/PowerShell/five-weekends.psh b/Task/Five-weekends/PowerShell/five-weekends.psh
new file mode 100644
index 0000000000..ac7d839d6c
--- /dev/null
+++ b/Task/Five-weekends/PowerShell/five-weekends.psh
@@ -0,0 +1,20 @@
+$fiveWeekends = @()
+$yearsWithout = @()
+foreach ($y in 1900..2100) {
+  $hasFiveWeekendMonth = $FALSE
+  foreach ($m in @("01","03","05","07","08",10,12)) {
+    if ((Get-Date "$y-$m-1").DayOfWeek -eq "Friday") {
+      $fiveWeekends += "$y-$m"
+      $hasFiveWeekendMonth = $TRUE
+    }
+  }
+  if ($hasFiveWeekendMonth -eq $FALSE) {
+     $yearsWithout += $y
+  }
+}
+Write-Output "Between the years 1900 and 2100, inclusive, there are $($fiveWeekends.count) months with five full weekends:"
+Write-Output "$($fiveWeekends[0..4] -join ","),...,$($fiveWeekends[-5..-1] -join ",")"
+
+Write-Output ""
+Write-Output "Extra Credit: these $($yearsWithout.count) years have no such month:"
+Write-Output ($yearsWithout -join ",")
diff --git a/Task/Five-weekends/Scala/five-weekends.scala b/Task/Five-weekends/Scala/five-weekends.scala
new file mode 100644
index 0000000000..81c6d2f84b
--- /dev/null
+++ b/Task/Five-weekends/Scala/five-weekends.scala
@@ -0,0 +1,35 @@
+import java.util.Calendar._
+import java.util.GregorianCalendar
+
+import org.scalatest.{FlatSpec, Matchers}
+
+class FiveWeekends extends FlatSpec with Matchers {
+
+  case class YearMonth[T](year: T, month: T)
+  implicit class CartesianProd[T](val seq: Seq[T]) {
+    def x(other: Seq[T]) = for(s1 <- seq; s2 <- other) yield YearMonth(year=s1,month=s2)
+    def -(other: Seq[T]): Seq[T] = seq diff other
+  }
+
+  def has5weekends(ym: { val year: Int; val month: Int}) = {
+    val date = new GregorianCalendar(ym.year, ym.month-1, 1)
+    date.get(DAY_OF_WEEK) == FRIDAY && date.getActualMaximum(DAY_OF_MONTH) == 31
+  }
+
+  val expectedFirstFive = Seq(
+    YearMonth(1901,3), YearMonth(1902,8), YearMonth(1903,5), YearMonth(1904,1), YearMonth(1904,7))
+  val expectedFinalFive = Seq(
+    YearMonth(2097,3), YearMonth(2098,8), YearMonth(2099,5), YearMonth(2100,1), YearMonth(2100,10))
+  val expectedNon5erYears = Seq(1900, 1906, 1917, 1923, 1928, 1934, 1945, 1951, 1956, 1962,
+                                1973, 1979, 1984, 1990, 2001, 2007, 2012, 2018, 2029, 2035,
+                                2040, 2046, 2057, 2063, 2068, 2074, 2085, 2091, 2096)
+
+  "Five Weekend Algorithm" should "match specification" in {
+    val months = (1900 to 2100) x (1 to 12) filter has5weekends
+    months.size shouldBe 201
+    months.take(5) shouldBe expectedFirstFive
+    months.takeRight(5) shouldBe expectedFinalFive
+
+    (1900 to 2100) - months.map(_.year) shouldBe expectedNon5erYears
+  }
+}
diff --git a/Task/FizzBuzz/ABAP/fizzbuzz.abap b/Task/FizzBuzz/ABAP/fizzbuzz.abap
new file mode 100644
index 0000000000..a68f8e974f
--- /dev/null
+++ b/Task/FizzBuzz/ABAP/fizzbuzz.abap
@@ -0,0 +1,13 @@
+DATA: tab TYPE TABLE OF string.
+
+tab = VALUE #(
+  FOR i = 1 WHILE i <= 100 (
+    COND string( LET r3 = i MOD 3
+                     r5 = i MOD 5 IN
+                 WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ|
+                 WHEN r3 = 0            THEN |FIZZ|
+                 WHEN r5 = 0            THEN |BUZZ|
+                 ELSE i ) ) ).
+
+cl_demo_output=>write( tab ).
+cl_demo_output=>display( ).
diff --git a/Task/FizzBuzz/ALGOL-W/fizzbuzz.alg b/Task/FizzBuzz/ALGOL-W/fizzbuzz.alg
new file mode 100644
index 0000000000..2103bca167
--- /dev/null
+++ b/Task/FizzBuzz/ALGOL-W/fizzbuzz.alg
@@ -0,0 +1,9 @@
+begin
+    i_w := 1; % set integers to print in minimum space %
+    for i := 1 until 100 do begin
+        if      i rem 15 = 0 then write( "FizzBuzz" )
+        else if i rem  5 = 0 then write( "Buzz" )
+        else if i rem  3 = 0 then write( "Fizz" )
+        else                      write( i )
+    end for_i
+end.
diff --git a/Task/FizzBuzz/APL/fizzbuzz-3.apl b/Task/FizzBuzz/APL/fizzbuzz-3.apl
new file mode 100644
index 0000000000..b6e7b109d0
--- /dev/null
+++ b/Task/FizzBuzz/APL/fizzbuzz-3.apl
@@ -0,0 +1 @@
+{ ⍵ 'Fizz' 'Buzz' 'FizzBuzz'[ +/1 2×0=3 5|⍵] }¨1+⍳100
diff --git a/Task/FizzBuzz/C/fizzbuzz-7.c b/Task/FizzBuzz/C/fizzbuzz-7.c
new file mode 100644
index 0000000000..6cf2ee6c45
--- /dev/null
+++ b/Task/FizzBuzz/C/fizzbuzz-7.c
@@ -0,0 +1,10 @@
+#include 
+int main()
+{
+    for (int i=0;++i<101;puts(""))
+    {
+        char f[] = "FizzBuzz%d";
+        f[8-i%5&12]=0;
+        printf (f+(-i%3&4+f[8]/8), i);
+    }
+}
diff --git a/Task/FizzBuzz/COBOL/fizzbuzz-3.cobol b/Task/FizzBuzz/COBOL/fizzbuzz-3.cobol
new file mode 100644
index 0000000000..04d5b75a4a
--- /dev/null
+++ b/Task/FizzBuzz/COBOL/fizzbuzz-3.cobol
@@ -0,0 +1,26 @@
+       IDENTIFICATION DIVISION.
+       PROGRAM-ID.  FIZZBUZZ.
+       ENVIRONMENT DIVISION.
+       DATA DIVISION.
+       WORKING-STORAGE SECTION.
+       01  X PIC 999.
+       01  Y PIC 999.
+       01  REM3 PIC 999.
+       01  REM5 PIC 999.
+       PROCEDURE DIVISION.
+           PERFORM VARYING X FROM 1 BY 1 UNTIL X > 100
+               DIVIDE X BY 3 GIVING Y REMAINDER REM3
+               DIVIDE X BY 5 GIVING Y REMAINDER REM5
+            EVALUATE REM3 ALSO REM5
+              WHEN ZERO ALSO ZERO
+                DISPLAY "FizzBuzz"
+              WHEN ZERO ALSO ANY
+                DISPLAY "Fizz"
+              WHEN ANY ALSO ZERO
+                DISPLAY "Buzz"
+              WHEN OTHER
+                DISPLAY X
+            END-EVALUATE
+           END-PERFORM
+           STOP RUN
+           .
diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-1.clj b/Task/FizzBuzz/Clojure/fizzbuzz-1.clj
index 09465645d5..c4fff08cd1 100644
--- a/Task/FizzBuzz/Clojure/fizzbuzz-1.clj
+++ b/Task/FizzBuzz/Clojure/fizzbuzz-1.clj
@@ -1,9 +1,9 @@
-(defn fizzbuzz [start finish] (map (fn [n]
+(defn fizzbuzz [start finish]
+  (map (fn [n]
 	(cond
+		(zero? (mod n 15)) "FizzBuzz"
 		(zero? (mod n 3)) "Fizz"
 		(zero? (mod n 5)) "Buzz"
-		(zero? (mod n 15)) "FizzBuzz"
 		:else n))
-	(range start finish))
-)
+	(range start finish)))
 (fizzbuzz 1 100)
diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-9.clj b/Task/FizzBuzz/Clojure/fizzbuzz-9.clj
new file mode 100644
index 0000000000..ee5abb51f9
--- /dev/null
+++ b/Task/FizzBuzz/Clojure/fizzbuzz-9.clj
@@ -0,0 +1,2 @@
+(let [n nil fizz (cycle [n n "fizz"]) buzz (cycle [n n n n "buzz"]) nums (iterate inc 1)]
+  (take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums)))
diff --git a/Task/FizzBuzz/CoffeeScript/fizzbuzz-2.coffee b/Task/FizzBuzz/CoffeeScript/fizzbuzz-2.coffee
index c85b29af26..dbf7f7f9e0 100644
--- a/Task/FizzBuzz/CoffeeScript/fizzbuzz-2.coffee
+++ b/Task/FizzBuzz/CoffeeScript/fizzbuzz-2.coffee
@@ -1,2 +1,10 @@
 for i in [1..100]
-  console.log(['Fizz' if i % 3 is 0] + ['Buzz' if i % 5 is 0] or i)
+  console.log \
+    if i % 15 is 0
+      "FizzBuzz"
+    else if i % 3 is 0
+      "Fizz"
+    else if i % 5 is 0
+      "Buzz"
+    else
+      i
diff --git a/Task/FizzBuzz/CoffeeScript/fizzbuzz-3.coffee b/Task/FizzBuzz/CoffeeScript/fizzbuzz-3.coffee
new file mode 100644
index 0000000000..c85b29af26
--- /dev/null
+++ b/Task/FizzBuzz/CoffeeScript/fizzbuzz-3.coffee
@@ -0,0 +1,2 @@
+for i in [1..100]
+  console.log(['Fizz' if i % 3 is 0] + ['Buzz' if i % 5 is 0] or i)
diff --git a/Task/FizzBuzz/Dart/fizzbuzz.dart b/Task/FizzBuzz/Dart/fizzbuzz.dart
index e47163c2a6..86a204e82b 100644
--- a/Task/FizzBuzz/Dart/fizzbuzz.dart
+++ b/Task/FizzBuzz/Dart/fizzbuzz.dart
@@ -1,4 +1,5 @@
 main() {
-  for(int i=1;i<=100;i++)
-    print((i%3==0?"Fizz":"")+(i%5==0?"Buzz":"")+(i%3!=0&&i%5!=0?i:""));
+  for (int i = 1; i <= 100; i++) {
+    print((i % 3 == 0 ? "Fizz" : "") + (i % 5 == 0 ? "Buzz" : "") + (i % 3 != 0 && i % 5 != 0 ? "$i" : ""));
+  }
 }
diff --git a/Task/FizzBuzz/Eiffel/fizzbuzz.e b/Task/FizzBuzz/Eiffel/fizzbuzz.e
index 1f43230922..c8433aebfa 100644
--- a/Task/FizzBuzz/Eiffel/fizzbuzz.e
+++ b/Task/FizzBuzz/Eiffel/fizzbuzz.e
@@ -1,10 +1,10 @@
 class
 	APPLICATION
-inherit
-	ARGUMENTS
+
 create
 	make
-feature {NONE} -- Initialization
+
+feature
 
 	make
 		do
@@ -12,24 +12,22 @@ feature {NONE} -- Initialization
 		end
 
 	fizzbuzz
-	local
-		i: INTEGER
-	do
-		from
-			i:= 1
-		until
-			i>100
-		loop
-			if i\\15= 0 then
-				io.put_string ("FIZZBUZZ%N")
-			elseif i\\3=0 then
-				io.put_string ("FIZZ%N")
-			elseif i\\5=0  then
-				io.put_string ("BUZZ%N")
-			else
-				io.put_string (i.out + "%N")
+	        --Numbers up to 100, prints "Fizz" instead of multiples of 3, and "Buzz" for multiples of 5.
+	        --For multiples of both 3 and 5 prints "FizzBuzz".
+		do
+			across
+				1 |..| 100 as c
+			loop
+				if c.item \\ 15 = 0 then
+					io.put_string ("FIZZBUZZ%N")
+				elseif c.item \\ 3 = 0 then
+					io.put_string ("FIZZ%N")
+				elseif c.item \\ 5 = 0 then
+					io.put_string ("BUZZ%N")
+				else
+					io.put_string (c.item.out + "%N")
+				end
 			end
-			i:= i+1
 		end
-	end
+
 end
diff --git a/Task/FizzBuzz/Elixir/fizzbuzz-1.elixir b/Task/FizzBuzz/Elixir/fizzbuzz-1.elixir
index 6a67105e90..6e30c9d36e 100644
--- a/Task/FizzBuzz/Elixir/fizzbuzz-1.elixir
+++ b/Task/FizzBuzz/Elixir/fizzbuzz-1.elixir
@@ -1,12 +1,8 @@
 Enum.each 1..100, fn x ->
-  IO.puts(case { rem(x, 5) == 0, rem(x,3) == 0 } do
-    { true, true } ->
-      "FizzBuzz"
-    { true, false } ->
-      "Fizz"
-    { false, true } ->
-      "Buzz"
-    { false, false } ->
-      x
+  IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do
+    { true, true }   -> "FizzBuzz"
+    { true, false }  -> "Fizz"
+    { false, true }  -> "Buzz"
+    { false, false } -> x
   end)
 end
diff --git a/Task/FizzBuzz/Elixir/fizzbuzz-2.elixir b/Task/FizzBuzz/Elixir/fizzbuzz-2.elixir
index 8ab6ffcdd6..9ca685762e 100644
--- a/Task/FizzBuzz/Elixir/fizzbuzz-2.elixir
+++ b/Task/FizzBuzz/Elixir/fizzbuzz-2.elixir
@@ -1,13 +1,9 @@
 #!/usr/bin/env elixir
 1..100 |> Enum.map(fn i ->
   cond do
-    rem(i,3*5) == 0 ->
-      "fizzbuzz"
-    rem(i,3) == 0 ->
-      "fizz"
-    rem(i,5) == 0 ->
-      "buzz"
-    true ->
-      i
+    rem(i,3*5) == 0 -> "fizzbuzz"
+    rem(i,3) == 0   -> "fizz"
+    rem(i,5) == 0   -> "buzz"
+    true            -> i
   end
-end) |> Enum.map(fn i -> IO.puts i end)
+end) |> Enum.each(fn i -> IO.puts i end)
diff --git a/Task/FizzBuzz/Elixir/fizzbuzz-3.elixir b/Task/FizzBuzz/Elixir/fizzbuzz-3.elixir
new file mode 100644
index 0000000000..71b44afb2e
--- /dev/null
+++ b/Task/FizzBuzz/Elixir/fizzbuzz-3.elixir
@@ -0,0 +1,14 @@
+defmodule RC do
+  def fizzbuzz(limit \\ 100) do
+    fizz = Stream.cycle(["", "", "Fizz"])
+    buzz = Stream.cycle(["", "", "", "", "Buzz"])
+    Stream.zip(fizz, buzz)
+    |> Stream.with_index
+    |> Enum.take(limit)
+    |> Enum.each(fn {{f,b},i} ->
+         IO.puts if f<>b=="", do: i+1, else: f<>b
+       end)
+  end
+end
+
+RC.fizzbuzz
diff --git a/Task/FizzBuzz/Fortran/fizzbuzz-2.f b/Task/FizzBuzz/Fortran/fizzbuzz-2.f
index 9bead5b406..fc6d6a1810 100644
--- a/Task/FizzBuzz/Fortran/fizzbuzz-2.f
+++ b/Task/FizzBuzz/Fortran/fizzbuzz-2.f
@@ -1,12 +1,11 @@
-program fizzbuzz_select
-    integer :: i
+program FizzBuzz
+implicit none
+integer :: i = 1
 
-    do i = 1, 100
-       select case (mod(i,15))
-          case 0;        print *, 'FizzBuzz'
-          case 3,6,9,12; print *, 'Fizz'
-          case 5,10;     print *, 'Buzz'
-          case default;  print *, i
-       end select
-    end do
- end program fizzbuzz_select
+do i = 1, 100
+    if (Mod(i,3) == 0)write(*,"(A)",advance='no')  "Fizz"
+    if (Mod(i,5) == 0)write(*,"(A)",advance='no') "Buzz"
+    if (Mod(i,3) /= 0 .and. Mod(i,5) /=0 )write(*,"(I3)",advance='no') i
+    print *, ""
+end do
+end program FizzBuzz
diff --git a/Task/FizzBuzz/Fortran/fizzbuzz-3.f b/Task/FizzBuzz/Fortran/fizzbuzz-3.f
new file mode 100644
index 0000000000..9bead5b406
--- /dev/null
+++ b/Task/FizzBuzz/Fortran/fizzbuzz-3.f
@@ -0,0 +1,12 @@
+program fizzbuzz_select
+    integer :: i
+
+    do i = 1, 100
+       select case (mod(i,15))
+          case 0;        print *, 'FizzBuzz'
+          case 3,6,9,12; print *, 'Fizz'
+          case 5,10;     print *, 'Buzz'
+          case default;  print *, i
+       end select
+    end do
+ end program fizzbuzz_select
diff --git a/Task/FizzBuzz/Frege/fizzbuzz.frege b/Task/FizzBuzz/Frege/fizzbuzz.frege
new file mode 100644
index 0000000000..0ac033abeb
--- /dev/null
+++ b/Task/FizzBuzz/Frege/fizzbuzz.frege
@@ -0,0 +1,7 @@
+gen n word = cycle (take (n - 1) (repeat "") ++ [word])
+pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz")
+fizzbuzz = zipWith combine pattern [1..] where
+    combine word number = if null word
+                             then show number
+                             else word
+show $ take 100 fizzbuzz
diff --git a/Task/FizzBuzz/Inform-7/fizzbuzz.inf b/Task/FizzBuzz/Inform-7/fizzbuzz-1.inf
similarity index 100%
rename from Task/FizzBuzz/Inform-7/fizzbuzz.inf
rename to Task/FizzBuzz/Inform-7/fizzbuzz-1.inf
diff --git a/Task/FizzBuzz/Inform-7/fizzbuzz-2.inf b/Task/FizzBuzz/Inform-7/fizzbuzz-2.inf
new file mode 100644
index 0000000000..12ff1e0023
--- /dev/null
+++ b/Task/FizzBuzz/Inform-7/fizzbuzz-2.inf
@@ -0,0 +1,16 @@
+The space is a room.  An item is a kind of thing.  In the space are 100 items.
+
+To say the name:
+	let the count be the number of items carried by the player;
+	say "[if the count is the count to the nearest 15]fizzbuzz.[otherwise if the count is the count to the nearest 3]fizz.[otherwise if the count is the count to the nearest 5]buzz.[otherwise][the count in words].".
+
+To count:
+	if an item is in the space
+	begin;
+		let the next one be a random item in the space; silently try taking the next one;
+		say "[the name]" in sentence case;
+		count;
+		end the story;
+	end if.
+		
+When play begins: count.  Use no scoring.
diff --git a/Task/FizzBuzz/J/fizzbuzz-1.j b/Task/FizzBuzz/J/fizzbuzz-1.j
index 592c724370..5dde9baf98 100644
--- a/Task/FizzBuzz/J/fizzbuzz-1.j
+++ b/Task/FizzBuzz/J/fizzbuzz-1.j
@@ -1,2 +1,2 @@
-   test =: +/@(1 2 * 0 = 3 5&|~)
-   (":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. test"0)  >:i.100
+   classify =: +/@(1 2 * 0 = 3 5&|~)
+   (":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. classify "0)  >:i.100
diff --git a/Task/FizzBuzz/J/fizzbuzz-6.j b/Task/FizzBuzz/J/fizzbuzz-6.j
new file mode 100644
index 0000000000..3b006a37bf
--- /dev/null
+++ b/Task/FizzBuzz/J/fizzbuzz-6.j
@@ -0,0 +1,2 @@
+   ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~ 0 = 3 5 |/ ])i.101
+1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fiz...
diff --git a/Task/FizzBuzz/J/fizzbuzz-7.j b/Task/FizzBuzz/J/fizzbuzz-7.j
new file mode 100644
index 0000000000..caa56ca729
--- /dev/null
+++ b/Task/FizzBuzz/J/fizzbuzz-7.j
@@ -0,0 +1,36 @@
+   i.10
+0 1 2 3 4 5 6 7 8 9
+   (3 5 |/ ])i.10
+0 1 2 0 1 2 0 1 2 0
+0 1 2 3 4 0 1 2 3 4
+   (0=3 5 |/ ])i.10
+1 0 0 1 0 0 1 0 0 1
+1 0 0 0 0 1 0 0 0 0
+   (;:'Fizz Buzz')
+┌────┬────┐
+│Fizz│Buzz│
+└────┴────┘
+   ((;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
+┌────┬┬┬────┬┬────┬────┬┬┬────┐
+│Fizz│││Fizz││    │Fizz│││Fizz│
+├────┼┼┼────┼┼────┼────┼┼┼────┤
+│Buzz│││    ││Buzz│    │││    │
+└────┴┴┴────┴┴────┴────┴┴┴────┘
+   ([: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
+┌────────┬┬┬────┬┬────┬────┬┬┬────┐
+│FizzBuzz│││Fizz││Buzz│Fizz│││Fizz│
+└────────┴┴┴────┴┴────┴────┴┴┴────┘
+   (":&.>)i.10
+┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐
+│0│1│2│3│4│5│6│7│8│9│
+└─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘
+   (":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
+┌────────┬─┬─┬────┬─┬────┬────┬─┬─┬────┐
+│FizzBuzz│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│
+└────────┴─┴─┴────┴─┴────┴────┴─┴─┴────┘
+   }.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
+┌─┬─┬────┬─┬────┬────┬─┬─┬────┐
+│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│
+└─┴─┴────┴─┴────┴────┴─┴─┴────┘
+   ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
+1 2 Fizz 4 Buzz Fizz 7 8 Fizz
diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-1.js b/Task/FizzBuzz/JavaScript/fizzbuzz-1.js
index 23309d3cf0..f864f2c40a 100644
--- a/Task/FizzBuzz/JavaScript/fizzbuzz-1.js
+++ b/Task/FizzBuzz/JavaScript/fizzbuzz-1.js
@@ -1,7 +1,9 @@
-var i, output;
-for (i = 1; i < 101; i++) {
-  output = '';
-  if (!(i % 3)) output += 'Fizz';
-  if (!(i % 5)) output += 'Buzz';
-  console.log(output || i);
-}
+var fizzBuzz = function () {
+  var i, output;
+  for (i = 1; i < 101; i += 1) {
+    output = '';
+    if (!(i % 3)) { output += 'Fizz'; }
+    if (!(i % 5)) { output += 'Buzz'; }
+    console.log(output || i);//empty string is false, so we short-circuit
+  }
+};
diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-2.js b/Task/FizzBuzz/JavaScript/fizzbuzz-2.js
index 6d37d23951..5242b49e54 100644
--- a/Task/FizzBuzz/JavaScript/fizzbuzz-2.js
+++ b/Task/FizzBuzz/JavaScript/fizzbuzz-2.js
@@ -1,25 +1,7 @@
-var divs = [15, 3, 5];
-var says = ['FizzBuzz', 'Fizz', 'Buzz'];
-
-function fizzBuzz(first, last) {
-    for (var n = first; n <= last; n++) {
-        print(getFizzBuzz(n));
-    }
+for (var i = 1; i <= 100; i++) {
+  console.log({
+    truefalse: 'Fizz',
+    falsetrue: 'Buzz',
+    truetrue: 'FizzBuzz'
+  }[(i%3==0) + '' + (i%5==0)] || i)
 }
-
-function getFizzBuzz(n) {
-    var sayWhat = n;
-    for (var d = 0; d < divs.length; d++) {
-        if (isMultOf(n, divs[d])) {
-            sayWhat = says[d];
-            break;
-        }
-    }
-    return sayWhat;
-}
-
-function isMultOf(n, d) {
-    return n % d == 0;
-}
-
-fizzBuzz(1, 100);
diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-3.js b/Task/FizzBuzz/JavaScript/fizzbuzz-3.js
index cba8766afa..ba8f59578f 100644
--- a/Task/FizzBuzz/JavaScript/fizzbuzz-3.js
+++ b/Task/FizzBuzz/JavaScript/fizzbuzz-3.js
@@ -1 +1 @@
-for(var i=1; i<=100; console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i), i++);
+for(i=1;i<101;i++)console.log((x=(i%3?'':'Fizz')+(i%5?'':'Buzz'))?x:i);
diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-4.js b/Task/FizzBuzz/JavaScript/fizzbuzz-4.js
index 04679acfbc..9733b1f347 100644
--- a/Task/FizzBuzz/JavaScript/fizzbuzz-4.js
+++ b/Task/FizzBuzz/JavaScript/fizzbuzz-4.js
@@ -1 +1,11 @@
-for(i=0;i<100;console.log(++i%15?i%5?i%3?i:f='Fizz':b='Buzz':f+b));
+(function rng(i) {
+    return i ? rng(i - 1).concat(i) : []
+})(100).map(
+    function (n) {
+        return n % 3 ? (
+            n % 5 ? n : "Buzz"
+        ) : (
+            n % 5 ? "Fizz" : "FizzBuzz"
+        )
+    }
+).join(' ')
diff --git a/Task/FizzBuzz/Kotlin/fizzbuzz.kotlin b/Task/FizzBuzz/Kotlin/fizzbuzz.kotlin
new file mode 100644
index 0000000000..b9ebdb9783
--- /dev/null
+++ b/Task/FizzBuzz/Kotlin/fizzbuzz.kotlin
@@ -0,0 +1,10 @@
+public fun fizzBuzz() {
+    for (i in 1..100) {
+        when {
+            i % 15 == 0 -> println("FizzBuzz")
+            i % 3 == 0 -> println("Fizz")
+            i % 5 == 0 -> println("Buzz")
+            else -> println(i)
+        }
+    }
+}
diff --git a/Task/FizzBuzz/Neko/fizzbuzz.neko b/Task/FizzBuzz/Neko/fizzbuzz.neko
new file mode 100644
index 0000000000..5bb9b435de
--- /dev/null
+++ b/Task/FizzBuzz/Neko/fizzbuzz.neko
@@ -0,0 +1,15 @@
+var i = 1
+
+while(i < 100) {
+	if(i % 15 == 0) {
+		$print("FizzBuzz\n");
+	} else if(i % 3 == 0) {
+		$print("Fizz\n");
+	} else if(i % 5 == 0) {
+		$print("Buzz\n");
+	} else {
+		$print(i + "\n");
+	}
+
+	i ++= 1
+}
diff --git a/Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6 b/Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6
index 860c42dac8..2fd0c40b74 100644
--- a/Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6
+++ b/Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6
@@ -1,4 +1,8 @@
 .say for
-  (('' xx 2, 'Fizz') xx * Z~
-   ('' xx 4, 'Buzz') xx *) Z||
-  1 .. 100;
+    (
+      (flat ('' xx 2, 'Fizz') xx *)
+      Z~
+      (flat ('' xx 4, 'Buzz') xx *)
+    )
+    Z||
+    1 .. 100;
diff --git a/Task/FizzBuzz/Python/fizzbuzz-3.py b/Task/FizzBuzz/Python/fizzbuzz-3.py
index b29ebd9a54..dc80287fec 100644
--- a/Task/FizzBuzz/Python/fizzbuzz-3.py
+++ b/Task/FizzBuzz/Python/fizzbuzz-3.py
@@ -1,13 +1 @@
-from itertools import cycle, izip, count, islice
-
-fizzes = cycle([""] * 2 + ["Fizz"])
-buzzes = cycle([""] * 4 + ["Buzz"])
-both = (f + b for f, b in izip(fizzes, buzzes))
-
-# if the string is "", yield the number
-# otherwise yield the string
-fizzbuzz = (word or n for word, n in izip(both, count(1)))
-
-# print the first 100
-for i in islice(fizzbuzz, 100):
-    print i
+for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1)
diff --git a/Task/FizzBuzz/Python/fizzbuzz-4.py b/Task/FizzBuzz/Python/fizzbuzz-4.py
index 6d89ba54cb..b29ebd9a54 100644
--- a/Task/FizzBuzz/Python/fizzbuzz-4.py
+++ b/Task/FizzBuzz/Python/fizzbuzz-4.py
@@ -1,4 +1,13 @@
-print ('\n'.join(''.join(''.join(['' if i%3 else 'Fizz',
-                                  '' if i%5 else 'Buzz'])
-                         or str(i))
-                 for i in range(1,101)))
+from itertools import cycle, izip, count, islice
+
+fizzes = cycle([""] * 2 + ["Fizz"])
+buzzes = cycle([""] * 4 + ["Buzz"])
+both = (f + b for f, b in izip(fizzes, buzzes))
+
+# if the string is "", yield the number
+# otherwise yield the string
+fizzbuzz = (word or n for word, n in izip(both, count(1)))
+
+# print the first 100
+for i in islice(fizzbuzz, 100):
+    print i
diff --git a/Task/FizzBuzz/Q/fizzbuzz-1.q b/Task/FizzBuzz/Q/fizzbuzz-1.q
new file mode 100644
index 0000000000..dc67ad758f
--- /dev/null
+++ b/Task/FizzBuzz/Q/fizzbuzz-1.q
@@ -0,0 +1 @@
+{$[0=x mod 15;"FizzBuzz";0=x mod 5;"Buzz";0=x mod 3;"Fizz";string x]} each 1+til 15
diff --git a/Task/FizzBuzz/Q/fizzbuzz-2.q b/Task/FizzBuzz/Q/fizzbuzz-2.q
new file mode 100644
index 0000000000..8be0bd2a98
--- /dev/null
+++ b/Task/FizzBuzz/Q/fizzbuzz-2.q
@@ -0,0 +1 @@
+-1 "\n" sv{$[0=x mod 15;"FizzBuzz";0=x mod 5;"Buzz";0=x mod 3;"Fizz";string x]} each 1+til 15;
diff --git a/Task/FizzBuzz/R/fizzbuzz-2.r b/Task/FizzBuzz/R/fizzbuzz-2.r
index 4a49ed548b..4580f40996 100644
--- a/Task/FizzBuzz/R/fizzbuzz-2.r
+++ b/Task/FizzBuzz/R/fizzbuzz-2.r
@@ -1,2 +1,6 @@
-x <- paste(rep("", 100), c("", "", "Fizz"), c("", "", "", "", "Buzz"), sep="")
-cat(ifelse(x == "", 1:100, x), "\n")
+xx <- rep("", 100)
+x <- 1:100
+xx[x %% 3 == 0] <- paste0(xx[x %% 3 == 0], "Fizz")
+xx[x %% 5 == 0] <- paste0(xx[x %% 5 == 0], "Buzz")
+xx[xx == ""] <- x[xx == ""]
+xx
diff --git a/Task/FizzBuzz/R/fizzbuzz-3.r b/Task/FizzBuzz/R/fizzbuzz-3.r
index 4b53d16efe..4a49ed548b 100644
--- a/Task/FizzBuzz/R/fizzbuzz-3.r
+++ b/Task/FizzBuzz/R/fizzbuzz-3.r
@@ -1,4 +1,2 @@
-x <- 1:100
-ifelse(x %% 15 == 0, 'FizzBuzz',
-       ifelse(x %% 5 == 0, 'Buzz',
-              ifelse(x %% 3 == 0, 'Fizz', x)))
+x <- paste(rep("", 100), c("", "", "Fizz"), c("", "", "", "", "Buzz"), sep="")
+cat(ifelse(x == "", 1:100, x), "\n")
diff --git a/Task/FizzBuzz/R/fizzbuzz-4.r b/Task/FizzBuzz/R/fizzbuzz-4.r
new file mode 100644
index 0000000000..4b53d16efe
--- /dev/null
+++ b/Task/FizzBuzz/R/fizzbuzz-4.r
@@ -0,0 +1,4 @@
+x <- 1:100
+ifelse(x %% 15 == 0, 'FizzBuzz',
+       ifelse(x %% 5 == 0, 'Buzz',
+              ifelse(x %% 3 == 0, 'Fizz', x)))
diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-10.rb b/Task/FizzBuzz/Ruby/fizzbuzz-10.rb
index 18ccc56ae3..1e8df2732d 100644
--- a/Task/FizzBuzz/Ruby/fizzbuzz-10.rb
+++ b/Task/FizzBuzz/Ruby/fizzbuzz-10.rb
@@ -1,8 +1,3 @@
-class Integer
-  def fizzbuzz
-    v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}"
-    v.empty? ? self : v
-  end
-end
-
-puts *(1..100).map(&:fizzbuzz)
+seq = *0..100
+{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}}
+puts seq.drop(1)
diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-11.rb b/Task/FizzBuzz/Ruby/fizzbuzz-11.rb
index 3a6a18d553..18ccc56ae3 100644
--- a/Task/FizzBuzz/Ruby/fizzbuzz-11.rb
+++ b/Task/FizzBuzz/Ruby/fizzbuzz-11.rb
@@ -1,8 +1,8 @@
-fizzbuzz = ->(i) do
-  (i%15).zero? and next "FizzBuzz"
-  (i%3).zero?  and next "Fizz"
-  (i%5).zero?  and next "Buzz"
-  i
+class Integer
+  def fizzbuzz
+    v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}"
+    v.empty? ? self : v
+  end
 end
 
-puts (1..100).map(&fizzbuzz).join("\n")
+puts *(1..100).map(&:fizzbuzz)
diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-12.rb b/Task/FizzBuzz/Ruby/fizzbuzz-12.rb
new file mode 100644
index 0000000000..3a6a18d553
--- /dev/null
+++ b/Task/FizzBuzz/Ruby/fizzbuzz-12.rb
@@ -0,0 +1,8 @@
+fizzbuzz = ->(i) do
+  (i%15).zero? and next "FizzBuzz"
+  (i%3).zero?  and next "Fizz"
+  (i%5).zero?  and next "Buzz"
+  i
+end
+
+puts (1..100).map(&fizzbuzz).join("\n")
diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-8.rb b/Task/FizzBuzz/Ruby/fizzbuzz-8.rb
index 7d491782ed..424d8803e3 100644
--- a/Task/FizzBuzz/Ruby/fizzbuzz-8.rb
+++ b/Task/FizzBuzz/Ruby/fizzbuzz-8.rb
@@ -1,5 +1 @@
-f = [nil, nil, :Fizz].cycle
-b = [nil, nil, nil, nil, :Buzz].cycle
-(1..100).each do |i|
-  puts "#{f.next}#{b.next}"[/.+/] || i
-end
+1.upto(100){|i|puts'FizzBuzz '[n=i**4%-15,n+13]||i}
diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-9.rb b/Task/FizzBuzz/Ruby/fizzbuzz-9.rb
index 1e8df2732d..7d491782ed 100644
--- a/Task/FizzBuzz/Ruby/fizzbuzz-9.rb
+++ b/Task/FizzBuzz/Ruby/fizzbuzz-9.rb
@@ -1,3 +1,5 @@
-seq = *0..100
-{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}}
-puts seq.drop(1)
+f = [nil, nil, :Fizz].cycle
+b = [nil, nil, nil, nil, :Buzz].cycle
+(1..100).each do |i|
+  puts "#{f.next}#{b.next}"[/.+/] || i
+end
diff --git a/Task/FizzBuzz/Rust/fizzbuzz-1.rust b/Task/FizzBuzz/Rust/fizzbuzz-1.rust
index 867479dc0b..9369a60a94 100644
--- a/Task/FizzBuzz/Rust/fizzbuzz-1.rust
+++ b/Task/FizzBuzz/Rust/fizzbuzz-1.rust
@@ -1,12 +1,13 @@
-// rust 0.13
+#![feature(into_cow)]
+use std::borrow::IntoCow;
+
 fn main() {
-    for i in range(1i, 101){
-        let value = i.to_string();
-        println!("{}", match (i % 3, i % 5) {
-                         (0,0) => "FizzBuzz",
-                         (0,_) => "Fizz",
-                         (_,0) => "Buzz",
-                          _ => value.as_slice()
-                       });
+    for i in 1..101 {
+        println!("{}", match (i%3, i%5) {
+                            (0,0) => "FizzBuzz".into_cow(),
+                            (0,_) => "Fizz".into_cow(),
+                            (_,0) => "Buzz".into_cow(),
+                            _ => i.to_string().into_cow(),
+                        });
     }
 }
diff --git a/Task/FizzBuzz/Rust/fizzbuzz-2.rust b/Task/FizzBuzz/Rust/fizzbuzz-2.rust
index adce026b3f..9396e02b56 100644
--- a/Task/FizzBuzz/Rust/fizzbuzz-2.rust
+++ b/Task/FizzBuzz/Rust/fizzbuzz-2.rust
@@ -1,11 +1,10 @@
-// rust 0.11
 fn main() {
-    for num in std::iter::range_inclusive(1i, 100) {
-        match (num % 3, num % 5) {
-            (0, 0) => println!("FizzBuzz"),
-            (0, _) => println!("Fizz"),
-            (_, 0) => println!("Buzz"),
-            (_, _) => println!("{}", num),
+    for i in 1..101 {
+        match (i % 3 == 0, i % 5 == 0) {
+            (true, true)   => println!("FizzBuzz"),
+            (true, false)  => println!("Fizz"),
+            (false, true)  => println!("Buzz"),
+            (false, false) => println!("{}", i),
         }
     }
 }
diff --git a/Task/FizzBuzz/Scala/fizzbuzz-4.scala b/Task/FizzBuzz/Scala/fizzbuzz-4.scala
index 9f6125c0f9..8a1a4fb728 100644
--- a/Task/FizzBuzz/Scala/fizzbuzz-4.scala
+++ b/Task/FizzBuzz/Scala/fizzbuzz-4.scala
@@ -1 +1 @@
-for (n <- 1 to 100) println(List((15, "FizzBuzz"), (3, "Fizz"), (5, "Buzz")).find(t => n % t._1 == 0).getOrElse((0, n.toString))._2)
+for (i <- 1 to 100) println(Seq(15 -> "FizzBuzz", 3 -> "Fizz", 5 -> "Buzz").find(i % _._1 == 0).map(_._2).getOrElse(i))
diff --git a/Task/FizzBuzz/Scala/fizzbuzz-5.scala b/Task/FizzBuzz/Scala/fizzbuzz-5.scala
new file mode 100644
index 0000000000..0c48d04958
--- /dev/null
+++ b/Task/FizzBuzz/Scala/fizzbuzz-5.scala
@@ -0,0 +1,5 @@
+def fizzbuzz(l: List[String], n: Int, s: String) = if (l.head.toInt % n == 0) l :+ s else l
+def fizz(l: List[String]) = fizzbuzz(l, 3, "Fizz")
+def buzz(l: List[String]) = fizzbuzz(l, 5, "Buzz")
+def headOrTail(l: List[String]) = if (l.tail.size == 0) l.head else l.tail.mkString
+Stream.from(1).take(100).map(n => List(n.toString)).map(fizz).map(buzz).map(headOrTail).foreach(println)
diff --git a/Task/FizzBuzz/UNIX-Shell/fizzbuzz-7.sh b/Task/FizzBuzz/UNIX-Shell/fizzbuzz-7.sh
new file mode 100644
index 0000000000..98d765ff3d
--- /dev/null
+++ b/Task/FizzBuzz/UNIX-Shell/fizzbuzz-7.sh
@@ -0,0 +1,13 @@
+@ n = 1
+while ( $n <= 100 )
+  if ($n % 15 == 0) then
+    echo FizzBuzz
+  else if ($n % 5 == 0) then
+    echo Buzz
+  else if ($n % 3 == 0) then
+    echo Fizz
+  else
+    echo $n
+  endif
+  @ n += 1
+end
diff --git a/Task/FizzBuzz/Visual-Prolog/fizzbuzz.pro b/Task/FizzBuzz/Visual-Prolog/fizzbuzz.pro
new file mode 100644
index 0000000000..0564f8ffa5
--- /dev/null
+++ b/Task/FizzBuzz/Visual-Prolog/fizzbuzz.pro
@@ -0,0 +1,22 @@
+implement main
+   open core, console
+
+class predicates
+   fizzbuzz : (integer) -> string procedure (i).
+
+clauses
+    fizzbuzz(X) = S :- X mod 15 = 0, S = "FizzBuzz", !.
+    fizzbuzz(X) = S :- X mod 5 = 0, S = "Buzz", !.
+    fizzbuzz(X) = S :- X mod 3 = 0, S = "Fizz", !.
+    fizzbuzz(X) = S :- S = toString(X).
+
+    run() :-
+        foreach X = std::fromTo(1,100) do
+            write(fizzbuzz(X)), write("\n")
+        end foreach,
+        succeed.
+
+end implement main
+
+goal
+    console::runUtf8(main::run).
diff --git a/Task/Flatten-a-list/Bracmat/flatten-a-list.bracmat b/Task/Flatten-a-list/Bracmat/flatten-a-list.bracmat
index bec60e0c93..ae349ee023 100644
--- a/Task/Flatten-a-list/Bracmat/flatten-a-list.bracmat
+++ b/Task/Flatten-a-list/Bracmat/flatten-a-list.bracmat
@@ -1,7 +1,7 @@
 ( (myList = ((1), 2, ((3,4), 5), ((())), (((6))), 7, 8, ()))
 & put$("Unevaluated:")
 & lst$myList
-& !myList:?myList          { the expression !list evaluates myList }
+& !myList:?myList          { the expression !myList evaluates myList }
 & put$("Flattened:")
 & lst$myList
 )
diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-2.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-2.lisp
index 1f2ed730de..7a6e2fa07a 100644
--- a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-2.lisp
+++ b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-2.lisp
@@ -1,5 +1,3 @@
 (defun flatten (ls)
-  (labels (
-    (mklist (x) (if (listp x) x (list x)))
-    )
+  (labels ((mklist (x) (if (listp x) x (list x))))
     (mapcan #'(lambda (x) (if (atom x) (mklist x) (flatten x))) ls)))
diff --git a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-3.lisp b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-3.lisp
index 4931477c1b..7c717c0e7a 100644
--- a/Task/Flatten-a-list/Common-Lisp/flatten-a-list-3.lisp
+++ b/Task/Flatten-a-list/Common-Lisp/flatten-a-list-3.lisp
@@ -1,7 +1,7 @@
 (defun flatten (obj)
   (let (result)
     (labels ((grep (obj)
-               (cond ((null obj))
+               (cond ((null obj) nil)
                      ((atom obj) (push obj result))
                      (t (grep (rest obj))
                         (grep (first obj))))))
diff --git a/Task/Flatten-a-list/Forth/flatten-a-list.fth b/Task/Flatten-a-list/Forth/flatten-a-list.fth
new file mode 100644
index 0000000000..dfc3831814
--- /dev/null
+++ b/Task/Flatten-a-list/Forth/flatten-a-list.fth
@@ -0,0 +1,12 @@
+include FMS-SI.f
+include FMS-SILib.f
+
+: flatten {: list1 list2 --  :}
+  list1 size: 0 ?do i list1 at:
+                  dup is-a object-list2
+                  if list2 recurse else list2 add: then  loop ;
+
+object-list2 list
+o{ o{ 1 } 2 o{ o{ 3 4 } 5 } o{ o{ o{ } } } o{ o{ o{ 6 } } } 7 8 o{ } }
+list flatten
+list p: \ o{ 1 2 3 4 5 6 7 8 } ok
diff --git a/Task/Flatten-a-list/Fortran/flatten-a-list.f b/Task/Flatten-a-list/Fortran/flatten-a-list-1.f
similarity index 100%
rename from Task/Flatten-a-list/Fortran/flatten-a-list.f
rename to Task/Flatten-a-list/Fortran/flatten-a-list-1.f
diff --git a/Task/Flatten-a-list/Fortran/flatten-a-list-2.f b/Task/Flatten-a-list/Fortran/flatten-a-list-2.f
new file mode 100644
index 0000000000..f63ce68b93
--- /dev/null
+++ b/Task/Flatten-a-list/Fortran/flatten-a-list-2.f
@@ -0,0 +1,33 @@
+      SUBROUTINE CRUSH(LIST)	!Changes LIST.
+Crushes a list holding multi-level entries within [...] to a list of single-level entries. Null entries are purged.
+Could escalate to recognising quoted strings as list entries (preserving spaces), not just strings of digits.
+       CHARACTER*(*) LIST	!The text manifesting the list.
+       INTEGER I,L		!Fingers.
+       LOGICAL LIVE		!Scan state.
+        L = 1		!Output finger. The starting [ is already in place.
+        LIVE = .FALSE.	!A list element is not in progress.
+        DO I = 2,LEN(LIST)	!Scan the characters of the list.
+          SELECT CASE(LIST(I:I))	!Consider one.
+           CASE("[","]",","," ")	!Punctuation or spacing?
+            IF (LIVE) THEN		!Yes. If previously in an element,
+              L = L + 1			!Advance the finger,
+              LIST(L:L) = ","		!And place its terminating comma.
+              LIVE = .FALSE.		!Thus the element is finished.
+            END IF		!So much for punctuation and empty space.
+           CASE DEFAULT		!Everything else is an element's content.
+            LIVE = .TRUE.		!So we're in an element.
+            L = L + 1			!Advance the finger.
+            LIST(L:L) = LIST(I:I)	!And copy the content's character.
+          END SELECT		!Either we're in an element, or, we're not.
+        END DO			!On to the next character.
+Completed the crush. At least one ] must have followed the last character of the last element.
+        LIST(L:L) = "]"		!It had provoked a trailing comma. Now it is the ending ].
+        LIST(L + 1:) = ""	!Scrub any tail end, just to be neat.
+      END		!Trailing spaces are the caller's problem.
+
+      CHARACTER*88 STUFF	!Work area.
+      STUFF = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]"	!The example.
+      WRITE (6,*) "Original: ",STUFF
+      CALL CRUSH(STUFF)		!Can't be a constant, as it will be changed.
+      WRITE (6,*) " Crushed: ",STUFF	!Behold!
+      END
diff --git a/Task/Flatten-a-list/Java/flatten-a-list-3.java b/Task/Flatten-a-list/Java/flatten-a-list-3.java
new file mode 100644
index 0000000000..e918058606
--- /dev/null
+++ b/Task/Flatten-a-list/Java/flatten-a-list-3.java
@@ -0,0 +1,17 @@
+import java.util.List;
+import java.util.stream.Stream;
+import java.util.stream.Collectors;
+
+public final class FlattenUtil {
+
+	public static Stream flattenToStream(List list) {
+		return list.stream().flatMap(item ->
+			item instanceof List ?
+			flattenToStream((List)item) :
+			Stream.of(item));
+	}
+
+	public static List flatten(List list) {
+		return flattenToStream(list).collect(Collectors.toList());
+	}
+}
diff --git a/Task/Flatten-a-list/Joy/flatten-a-list.joy b/Task/Flatten-a-list/Joy/flatten-a-list.joy
new file mode 100644
index 0000000000..76cd2b3b31
--- /dev/null
+++ b/Task/Flatten-a-list/Joy/flatten-a-list.joy
@@ -0,0 +1,5 @@
+"seqlib" libload.
+
+[[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] treeflatten.
+
+(* output: [1 2 3 4 5 6 7 8] *)
diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-3.julia b/Task/Flatten-a-list/Julia/flatten-a-list-3.julia
index 6b4f560cf9..b5ada8a348 100644
--- a/Task/Flatten-a-list/Julia/flatten-a-list-3.julia
+++ b/Task/Flatten-a-list/Julia/flatten-a-list-3.julia
@@ -1 +1 @@
-flat(A) = mapreduce(x->isa(x,Array)? flat(x): x, vcat, A)
+flat(A) = mapreduce(x->isa(x,Array)? flat(x): x, vcat, [], A)
diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-4.julia b/Task/Flatten-a-list/Julia/flatten-a-list-4.julia
index 822d2a47df..3fce66af5a 100644
--- a/Task/Flatten-a-list/Julia/flatten-a-list-4.julia
+++ b/Task/Flatten-a-list/Julia/flatten-a-list-4.julia
@@ -1,5 +1,5 @@
 function flat(A)
-   result = {}
+   result = Any[]
    grep(a) = for x in a
                isa(x,Array) ? grep(x) : push!(result,x)
              end
diff --git a/Task/Flatten-a-list/PL-I/flatten-a-list.pli b/Task/Flatten-a-list/PL-I/flatten-a-list.pli
index e69d65be09..50811c50cb 100644
--- a/Task/Flatten-a-list/PL-I/flatten-a-list.pli
+++ b/Task/Flatten-a-list/PL-I/flatten-a-list.pli
@@ -1,10 +1,6 @@
-list = translate (list, '  ', '[]' );
-list = '[' || list || ']';
-
-
-
-/* the above will erroneously return:
-
-[  1 , 2,   3,4 , 5 ,       ,    6   , 7, 8,    ]
-
-*/
+list = translate (list, '  ', '[]' ); /*Produces "  1 , 2,   3,4 , 5 ,       ,    6   , 7, 8,     " */
+list = Replace(list,'',' ');          /*Converts spaces to nothing. Same parameter order as Translate.*/
+do while index(list,',,') > 0;        /*Is there a double comma anywhere?
+  list = Replace(list,',',',,');      /*Yes. Convert double commas to single, nullifying empty lists*/
+end;                                  /*And search afresh, in case of multiple commas in a row.*/
+list = '[' || list || ']';            /*Repackage the list.*/
diff --git a/Task/Flatten-a-list/PowerShell/flatten-a-list.psh b/Task/Flatten-a-list/PowerShell/flatten-a-list.psh
new file mode 100644
index 0000000000..caca73b5d5
--- /dev/null
+++ b/Task/Flatten-a-list/PowerShell/flatten-a-list.psh
@@ -0,0 +1,7 @@
+function flatten($a) {
+    if($a.Count -gt 1) {
+        $a | foreach{ $(flatten $_)}
+    } else {$a}
+}
+$a = @(@(1), 2, @(@(3,4), 5), @(@(@())), @(@(@(6))), 7, 8, @())
+"$(flatten $a)"
diff --git a/Task/Flatten-a-list/Python/flatten-a-list-1.py b/Task/Flatten-a-list/Python/flatten-a-list-1.py
index 2510fa9e16..775c064adc 100644
--- a/Task/Flatten-a-list/Python/flatten-a-list-1.py
+++ b/Task/Flatten-a-list/Python/flatten-a-list-1.py
@@ -1,11 +1,7 @@
->>> def flatten(lst, results=[]):      # 'results' defaults to an empty list []
-        for e in lst:                  #   for each element 'e' in lst
-            if type(e) is list:        #      if that element is a list, then
-                flatten(e, results)    #         flatten that sublist, appending results to "results"
-            else:                      #      if element is not a list, then
-                results.append(e)      #         insert a copy of it at the end of "results"
-        return results
+>>> def flatten(lst):
+	return sum( ([x] if not isinstance(x, list) else flatten(x)
+		     for x in lst), [] )
 
->>> l = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
->>> flatten(l)
+>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]
+>>> flatten(lst)
 [1, 2, 3, 4, 5, 6, 7, 8]
diff --git a/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx b/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx
index 9641e67941..66bd0c56f9 100644
--- a/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx
+++ b/Task/Flatten-a-list/REXX/flatten-a-list-2.rexx
@@ -1,12 +1,17 @@
-/*REXX pgm demonstrates how to flatten a list  (it need not be numeric).*/
+/*REXX pgm demonstrates how to flatten a list  (it need not be numeric). */
 y = '[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]'
 
-z = translate( y, ,'[,]' )             /*change brackets&commas──►blanks*/
-z = space(z)                           /*remove extraneous blanks.      */
-z = changestr( ' ', z, ", " )          /*change blanks to "comma blank".*/
-z = '[' || z || "]"                    /*add brackets via concatenation.*/
-                                       /*another version of above:      */
-                                         z = '['z"]"
+z = translate( y, ,'[,]' )             /*change brackets&commas──►blanks.*/
+z = space(z)                           /*remove any extraneous blanks.   */
+z = changestr( ' ', z, ", " )          /*change blanks to "comma blank". */
+z = '[' || z || "]"                    /*add brackets via concatenation. */
+
+                                       /*alternate of the above statement*/
+                                       /*  (add brackets via abutment)   */
+
+                                       /* ╔════════════════════════════╗ */
+                                       /* ║         z = '['z"]"        ║ */
+                                       /* ╚════════════════════════════╝ */
 say ' input =' y
 say 'output =' z
-                                       /*stick a fork in it, we're done.*/
+                                       /*stick a fork in it,  we're done.*/
diff --git a/Task/Flatten-a-list/Ruby/flatten-a-list.rb b/Task/Flatten-a-list/Ruby/flatten-a-list-1.rb
similarity index 100%
rename from Task/Flatten-a-list/Ruby/flatten-a-list.rb
rename to Task/Flatten-a-list/Ruby/flatten-a-list-1.rb
diff --git a/Task/Flatten-a-list/Ruby/flatten-a-list-2.rb b/Task/Flatten-a-list/Ruby/flatten-a-list-2.rb
new file mode 100644
index 0000000000..45b5201de9
--- /dev/null
+++ b/Task/Flatten-a-list/Ruby/flatten-a-list-2.rb
@@ -0,0 +1,2 @@
+p flatten_once = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []].flatten(1)
+# => [1, 2, [3, 4], 5, [[]], [[6]], 7, 8]
diff --git a/Task/Flipping-bits-game/Clojure/flipping-bits-game.clj b/Task/Flipping-bits-game/Clojure/flipping-bits-game.clj
new file mode 100644
index 0000000000..0b940ee288
--- /dev/null
+++ b/Task/Flipping-bits-game/Clojure/flipping-bits-game.clj
@@ -0,0 +1,65 @@
+(defn cols [board]
+  (mapv vec (apply map list board)))
+
+(defn flipv [v]
+  (mapv #(if (> % 0) 0 1) v))
+
+(defn flip-row [board n]
+  (assoc board n (flipv (get board n))))
+
+(defn flip-col [board n]
+  (cols (flip-row (cols board) n)))
+
+(defn play-rand [board n]
+  (if (= n 0)
+    board
+    (let [f (if (= (rand-int 2) 0) flip-row flip-col)]
+      (recur (f board (rand-int (count board))) (dec n)))))
+
+(defn rand-binary-vec [size]
+  (vec (take size (repeatedly #(rand-int 2)))))
+
+(defn rand-binary-board [size]
+  (vec (take size (repeatedly #(rand-binary-vec size)))))
+
+(defn numbers->letters [coll]
+  (map #(char (+ 97 %)) coll))
+
+(defn column-labels [size]
+  (apply str (interpose " " (numbers->letters (range size)))))
+
+(defn print-board [board]
+  (let [size (count board)]
+    (println "\t " (column-labels size))
+    (dotimes [n size] (println (inc n) "\t" (board n)))))
+
+(defn key->move [key]
+  (let [start (int (first key))
+        row-value (try (Long/valueOf key) (catch NumberFormatException e))]
+    (cond
+      (<= 97 start 122) [:col (- start 97)]
+      (<= 65 start 90) [:col (- start 65)]
+      (> row-value 0) [:row (dec row-value)]
+      :else nil)))
+
+(defn play-game [target-board current-board n]
+  (println "\nTurn " n)
+  (print-board current-board)
+  (if (= target-board current-board)
+    (println "You win!")
+    (let [move (key->move (read-line))
+          axis (first move)
+          idx (second move)]
+      (cond
+        (= axis :row) (play-game target-board (flip-row current-board idx) (inc n))
+        (= axis :col) (play-game target-board (flip-col current-board idx) (inc n))
+        :else (println "Quitting!")))))
+
+(defn -main
+  "Flip the Bits Game!"
+  [& args]
+  (if-not (empty? args)
+    (let [target-board (rand-binary-board (Long/valueOf (first args)))]
+      (println "Target")
+      (print-board target-board)
+      (play-game target-board (play-rand target-board 3) 0))))
diff --git a/Task/Floyds-triangle/Befunge/floyds-triangle.bf b/Task/Floyds-triangle/Befunge/floyds-triangle.bf
new file mode 100644
index 0000000000..1d83373b3a
--- /dev/null
+++ b/Task/Floyds-triangle/Befunge/floyds-triangle.bf
@@ -0,0 +1,3 @@
+0" :swor fo rebmuN">:#,_&>55v
+>1+\1-:#v_$$1+\1- 55+,:v>$$@+
+^,*84.:\<+1\+1/2*+1:::\_^#:,<
diff --git a/Task/Floyds-triangle/Elixir/floyds-triangle.elixir b/Task/Floyds-triangle/Elixir/floyds-triangle.elixir
new file mode 100644
index 0000000000..7f917b04d9
--- /dev/null
+++ b/Task/Floyds-triangle/Elixir/floyds-triangle.elixir
@@ -0,0 +1,18 @@
+defmodule Floyd do
+  def triangle(n) do
+    max = trunc(n * (n + 1) / 2)
+    widths = for m <- (max - n + 1)..max, do: (m |> Integer.to_string |> String.length) + 1
+    format = Enum.map(widths, fn wide -> "~#{wide}w" end) |> List.to_tuple
+    line(n, 0, 1, format)
+  end
+
+  def line(n, n, _, _), do: :ok
+  def line(n, i, count, format) do
+    Enum.each(0..i, fn j -> :io.fwrite(elem(format,j), [count+j]) end)
+    IO.puts ""
+    line(n, i+1, count+i+1, format)
+  end
+end
+
+Floyd.triangle(5)
+Floyd.triangle(14)
diff --git a/Task/Floyds-triangle/JavaScript/floyds-triangle-1.js b/Task/Floyds-triangle/JavaScript/floyds-triangle-1.js
new file mode 100644
index 0000000000..1795b4fd03
--- /dev/null
+++ b/Task/Floyds-triangle/JavaScript/floyds-triangle-1.js
@@ -0,0 +1,78 @@
+// Floyd triangles of 5 and 14 rows
+// right-aligned monospaced columns (nMargin allows for extra spacing)
+// () --> s
+function main() {
+    // minimum space between numbers - adjust for visual preference
+    var nMargin = 1;
+
+    // Formatted strings for Floyd's triangles of 5 and 14 rows
+    return (function (lstN) {
+        return lstN.map(function (nFloydRows) {
+            var lstRows = floydIntegerLists(nFloydRows),
+                iLast = nFloydRows - 1;
+
+            return colsSpacedRight(
+                lstRows,
+                // Minimum space required per number cell
+                // nMargin more than the width of the final number
+                lstRows[iLast][iLast].toString().length + nMargin
+            )
+        }).join('\n\n');
+    })([5, 14]);
+}
+
+// n Floyd's triangle rows
+// n --> [[n]]
+function floydIntegerLists(nRows) {
+
+    // Full integer list folded into list of rows
+    // [n] --> [[n]]
+    return (function triangleNumbers(lstInt, startWidth) {
+        var n = startWidth || 1;
+
+        return n > lstInt.length ? [] : [lstInt.slice(0, n)].concat(
+            triangleNumbers(lstInt.slice(n), n + 1)
+        )
+    })(
+        range(
+            1,
+            Math.floor(
+                (nRows * nRows) / 2
+            ) + Math.ceil(
+                nRows / 2
+            )
+        )
+    );
+}
+
+// list of list of numbers --> lines of fixed right-aligned col width
+// [[n]] --> s
+function colsSpacedRight(lstLines, nColWidth) {
+    return lstLines.reduce(
+        function (s, line) {
+            return s + line.map(function (n) {
+                return rightAligned(n, nColWidth)
+            }).join('') + '\n';
+        }, ''
+    )
+}
+
+// range(1, 20) --> [1..20]
+function range(m, n) {
+    return Array.apply(null, Array(n - m + 1)).map(
+        function (x, i) {
+            return m + i;
+        }
+    );
+}
+
+// Integer as right-padded string of given width
+// n --> n --> s
+function rightAligned(n, width) {
+    var strN = n.toString();
+    return Array(width - strN.length + 1).join(' ') + strN;
+}
+
+console.log( // if the context is a browser
+    main()
+);
diff --git a/Task/Floyds-triangle/JavaScript/floyds-triangle.js b/Task/Floyds-triangle/JavaScript/floyds-triangle-2.js
similarity index 100%
rename from Task/Floyds-triangle/JavaScript/floyds-triangle.js
rename to Task/Floyds-triangle/JavaScript/floyds-triangle-2.js
diff --git a/Task/Floyds-triangle/Julia/floyds-triangle-2.julia b/Task/Floyds-triangle/Julia/floyds-triangle-2.julia
index b437097c3e..e5c87f9144 100644
--- a/Task/Floyds-triangle/Julia/floyds-triangle-2.julia
+++ b/Task/Floyds-triangle/Julia/floyds-triangle-2.julia
@@ -1,4 +1,6 @@
 floyd(n) =
-  print([join([lpad(j+binomial(i,2), (j==1?0:1)+ndigits(j+binomial(n,2)), " ")
+  pprint([join([lpad(j+binomial(i,2), (j==1?0:1)+ndigits(j+binomial(n,2)), " ")
                for j=1:i])
          for i=1:n])
+
+pprint(matrix) = for i = 1:size(matrix,1) println(join(matrix[i,:])) end
diff --git a/Task/Floyds-triangle/Perl-6/floyds-triangle.pl6 b/Task/Floyds-triangle/Perl-6/floyds-triangle.pl6
index 6dfdd54e66..457bf655a5 100644
--- a/Task/Floyds-triangle/Perl-6/floyds-triangle.pl6
+++ b/Task/Floyds-triangle/Perl-6/floyds-triangle.pl6
@@ -1,14 +1,10 @@
-sub chunk(@flat is copy, *@size) {
-    gather for @size -> $s { take [@flat.shift xx $s] }
-}
-
-constant @floyd = chunk 1..*, 1..*;
+constant @floyd = gather for 1..* -> $s { take [++$ xx $s] }
 
 sub say-floyd($n) {
-    my @fmt = @floyd[$n-1].map: {"%{.chars}s"}
+    my @formats = @floyd[$n-1].map: {"%{.chars}s"}
 
     for @floyd[^$n] -> @i {
-        say join ' ', (@i Z @fmt).map: -> $i, $f { $i.fmt($f) }
+        say ~(@i Z @formats).map: -> ($i, $f) { $i.fmt($f) }
     }
 }
 
diff --git a/Task/Forest-fire/BASIC/forest-fire-1.basic b/Task/Forest-fire/BASIC/forest-fire-1.basic
new file mode 100644
index 0000000000..316e7df8c4
--- /dev/null
+++ b/Task/Forest-fire/BASIC/forest-fire-1.basic
@@ -0,0 +1,38 @@
+N = 150 : M = 150 : P = 0.03 : F = 0.00003
+
+dim f(N+2,M+2) # 1 tree, 0 empty, 2 fire
+dim fn(N+2,M+2)
+graphsize N,M
+fastgraphics
+
+for x = 1 to N
+	for y = 1 to M
+		if rand<0.5 then f[x,y] = 1
+	next y
+next x
+
+while True
+	for x = 1 to N
+		for y = 1 to M
+			if not f[x,y] and rand

RND(1) THEN + new&(x%,y%) = 1 + GCOL 2 + PLOT 4*x%,4*y% + ENDIF + WHEN 1: + IF f > RND(1) OR old&(x%-1,y%)=2 OR old&(x%+1,y%)=2 OR \ + \ old&(x%-1,y%-1)=2 OR old&(x%,y%-1)=2 OR old&(x%+1,y%-1)=2 OR \ + \ old&(x%-1,y%+1)=2 OR old&(x%,y%+1)=2 OR old&(x%+1,y%+1)=2 THEN + new&(x%,y%) = 2 + GCOL 1 + PLOT 4*x%,4*y% + ENDIF + WHEN 2: + new&(x%,y%) = 0 + GCOL 15 + PLOT 4*x%,4*y% + ENDCASE + NEXT + NEXT x% + old&() = new&() + UNTIL FALSE diff --git a/Task/Forest-fire/BASIC/forest-fire-3.basic b/Task/Forest-fire/BASIC/forest-fire-3.basic new file mode 100644 index 0000000000..0726239fc7 --- /dev/null +++ b/Task/Forest-fire/BASIC/forest-fire-3.basic @@ -0,0 +1,96 @@ +'[RC] Forest Fire +'written for FreeBASIC v16 +'Program code based on BASIC256 from Rosettacode website +'http://rosettacode.org/wiki/Forest_fire#BASIC256 + +dim fire as double +dim p as single +P = 0.003 : fire = 0.00003 +gen = 0 +N = 400 : M = 400 + +dim f0(-1 to N+2,-1 to M+2) +dim fn(-1 to N+2,-1 to M+2) +dim number1 as double + +white = 15 'color 15 is white +yellow = 14 'color 14 is yellow +black = 0 'color 0 is black +green = 2 'color 2 is green +red = 4 'color 4 is red + +screen 18 'Resolution 640x480 with at least 256 colors +randomize timer + +locate 28,1 + BEEP +Print " Welcome to Forest Fire" +locate 29,1 +print " press any key to start" +sleep +locate 28,1 +Print " Welcome to Forest Fire" +locate 29,1 +print " " + +' 1 tree, 0 empty, 2 fire +color green ' this is green color for trees +for x = 1 to N + for y = 1 to M + if rnd < 0.5 then 'populate original tree density + f0(x,y) = 1 + pset (x,y) + end if + next y +next x + +color white +locate 29,1 +Print " Press any key to continue " +sleep +locate 29,1 +Print " Press 'space bar' to continue/pause, ESC to stop " + +do +press$ = inkey$ + for x = 1 to N + for y = 1 to M + if not f0(x,y) and rnd

max + n=max + EndIf + ProcedureReturn n +EndProcedure + +Procedure SpreadFire(x,y) + Protected cnt=0, i, j + For i=Limit(x-1, 0, #Width) To Limit(x+1, 0, #Width) + For j=Limit(y-1, 0, #Height) To Limit(y+1, 0, #Height) + If Forest(i,j)>=#Tree + Forest(i,j)=#Ignited + EndIf + Next + Next +EndProcedure + +Procedure InitMap() + Protected x, y, type + For y=1 To #Height + For x=1 To #Width + If Rnd()<=#SeedATree + type=#Tree + Else + type=#Empty + EndIf + Forest(x,y)=type + Next + Next +EndProcedure + +Procedure UpdateMap() + Protected x, y + For y=1 To #Height + For x=1 To #Width + Select Forest(x,y) + Case #Burning + Forest(x,y)=#Empty + SpreadFire(x,y) + Case #Ignited + Forest(x,y)=#Burning + Case #Empty + If Rnd()<=#p + Forest(x,y)=#Tree + EndIf + Default + If Rnd()<=#f + Forest(x,y)=#Burning + Else + Forest(x,y)+1 + EndIf + EndSelect + Next + Next +EndProcedure + +Procedure PresentMap() + Protected x, y, c + cnt+1 + SetWindowTitle(0,Title$+", time frame="+Str(cnt)) + StartDrawing(ImageOutput(1)) + For y=0 To OutputHeight()-1 + For x=0 To OutputWidth()-1 + Select Forest(x,y) + Case #Empty + c=#BackGround + Case #Burning, #Ignited + c=#Fire + Default + If Forest(x,y)<#Tree+#Old + c=#YoungTree + ElseIf Forest(x,y)<#Tree+2*#Old + c=#NormalTree + ElseIf Forest(x,y)<#Tree+3*#Old + c=#MatureTree + ElseIf Forest(x,y)<#Tree+4*#Old + c=#OldTree + Else ; Tree died of old age + Forest(x,y)=#Empty + c=#Black + EndIf + EndSelect + Plot(x,y,c) + Next + CompilerIf #UnLoadCPU>1 + Delay(1) + CompilerEndIf + Next + StopDrawing() + ImageGadget(1, 0, 0, #Width, #Height, ImageID(1)) +EndProcedure + +If OpenWindow(0, 10, 30, #Width, #Height, Title$, #PB_Window_MinimizeGadget) + SmartWindowRefresh(0, 1) + If CreateImage(1, #Width, #Height) + Define Event, freq + If ExamineDesktops() And DesktopFrequency(0) + freq=DesktopFrequency(0) + Else + freq=60 + EndIf + AddWindowTimer(0,0,5000/freq) + InitMap() + Repeat + Event = WaitWindowEvent() + Select Event + Case #PB_Event_CloseWindow + End + Case #PB_Event_Timer + CompilerIf #UnLoadCPU>0 + Delay(25) + CompilerEndIf + UpdateMap() + PresentMap() + EndSelect + ForEver + EndIf +EndIf diff --git a/Task/Forest-fire/BASIC/forest-fire-5.basic b/Task/Forest-fire/BASIC/forest-fire-5.basic new file mode 100644 index 0000000000..09e3fcf37b --- /dev/null +++ b/Task/Forest-fire/BASIC/forest-fire-5.basic @@ -0,0 +1,65 @@ +Sub Run() + //Handy named constants + Const empty = 0 + Const tree = 1 + Const fire = 2 + Const ablaze = &cFF0000 //Using the &c numeric operator to indicate a color in hex + Const alive = &c00FF00 + Const dead = &c804040 + + //Our forest + Dim worldPic As New Picture(480, 480, 32) + Dim newWorld(120, 120) As Integer + Dim oldWorld(120, 120) As Integer + + //Initialize forest + Dim rand As New Random + For x as Integer = 0 to 119 + For y as Integer = 0 to 119 + if rand.InRange(0, 2) = 0 Or x = 119 or y = 119 or x = 0 or y = 0 Then + newWorld(x, y) = empty + worldPic.Graphics.ForeColor = dead + worldPic.Graphics.FillRect(x*4, y*4, 4, 4) + Else + newWorld(x, y) = tree + worldPic.Graphics.ForeColor = alive + worldPic.Graphics.FillRect(x*4, y*4, 4, 4) + end if + Next + Next + oldWorld = newWorld + + //Burn, baby burn! + While Window1.stop = False + For x as Integer = 0 To 119 + For y As Integer = 0 to 119 + Dim willBurn As Integer = rand.InRange(0, Window1.burnProb.Value) + Dim willGrow As Integer = rand.InRange(0, Window1.growProb.Value) + if x = 119 or y = 119 or x = 0 or y = 0 Then + Continue + end if + Select Case oldWorld(x, y) + Case empty + If willGrow = (Window1.growProb.Value) Then + newWorld(x, y) = tree + worldPic.Graphics.ForeColor = alive + worldPic.Graphics.FillRect(x*4, y*4, 4, 4) + end if + Case tree + if oldWorld(x - 1, y) = fire Or oldWorld(x, y - 1) = fire Or oldWorld(x + 1, y) = fire Or oldWorld(x, y + 1) = fire Or oldWorld(x + 1, y + 1) = fire Or oldWorld(x - 1, y - 1) = fire Or oldWorld(x - 1, y + 1) = fire Or oldWorld(x + 1, y - 1) = fire Or willBurn = (Window1.burnProb.Value) Then + newWorld(x, y) = fire + worldPic.Graphics.ForeColor = ablaze + worldPic.Graphics.FillRect(x*4, y*4, 4, 4) + end if + Case fire + newWorld(x, y) = empty + worldPic.Graphics.ForeColor = dead + worldPic.Graphics.FillRect(x*4, y*4, 4, 4) + End Select + Next + Next + Window1.Canvas1.Graphics.DrawPicture(worldPic, 0, 0) + oldWorld = newWorld + me.Sleep(Window1.speed.Value) + Wend +End Sub diff --git a/Task/Forest-fire/BASIC/forest-fire-6.basic b/Task/Forest-fire/BASIC/forest-fire-6.basic new file mode 100644 index 0000000000..150d62e642 --- /dev/null +++ b/Task/Forest-fire/BASIC/forest-fire-6.basic @@ -0,0 +1,11 @@ +Sub Open() + //First method to run on the creation of a new Window. We instantiate an instance of our forestFire thread and run it. + Dim fire As New forestFire + fire.Run() +End Sub + +stop As Boolean //a globally accessible property of Window1. Boolean properties default to False. + +Sub Pushbutton1.Action() + stop = True +End Sub diff --git a/Task/Forest-fire/BASIC/forest-fire-7.basic b/Task/Forest-fire/BASIC/forest-fire-7.basic new file mode 100644 index 0000000000..049ad7a6d4 --- /dev/null +++ b/Task/Forest-fire/BASIC/forest-fire-7.basic @@ -0,0 +1,25 @@ +graphic #g, 200,200 +dim preGen(200,200) +dim newGen(200,200) + +for gen = 1 to 200 + for x = 1 to 199 + for y = 1 to 199 + select case preGen(x,y) + case 0 + if rnd(0) > .99 then newGen(x,y) = 1 : #g "color green ; set "; x; " "; y + case 2 + newGen(x,y) = 0 : #g "color brown ; set "; x; " "; y + case 1 + if preGen(x-1,y-1) = 2 or preGen(x-1,y) = 2 or preGen(x-1,y+1) = 2 _ + or preGen(x,y-1) = 2 or preGen(x,y+1) = 2 or preGen(x+1,y-1) = 2 _ + or preGen(x+1,y) = 2 or preGen(x+1,y+1) = 2 or rnd(0) > .999 then + #g "color red ; set "; x; " "; y + newGen(x,y) = 2 + end if + end select + preGen(x-1,y-1) = newGen(x-1,y-1) + next y + next x +next gen +render #g diff --git a/Task/Forest-fire/BASIC/forest-fire-8.basic b/Task/Forest-fire/BASIC/forest-fire-8.basic new file mode 100644 index 0000000000..c6dab6da3f --- /dev/null +++ b/Task/Forest-fire/BASIC/forest-fire-8.basic @@ -0,0 +1,104 @@ +Public Class ForestFire + Private _forest(,) As ForestState + Private _isBuilding As Boolean + Private _bm As Bitmap + Private _gen As Integer + Private _sw As Stopwatch + + Private Const _treeStart As Double = 0.5 + Private Const _f As Double = 0.00001 + Private Const _p As Double = 0.001 + + Private Const _winWidth As Integer = 300 + Private Const _winHeight As Integer = 300 + + Private Enum ForestState + Empty + Burning + Tree + End Enum + + Private Sub ForestFire_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load + Me.ClientSize = New Size(_winWidth, _winHeight) + ReDim _forest(_winWidth, _winHeight) + + Dim rnd As New Random() + For i As Integer = 0 To _winHeight - 1 + For j As Integer = 0 To _winWidth - 1 + _forest(j, i) = IIf(rnd.NextDouble <= _treeStart, ForestState.Tree, ForestState.Empty) + Next + Next + + _sw = New Stopwatch + _sw.Start() + DrawForest() + Timer1.Start() + End Sub + + Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick + If _isBuilding Then Exit Sub + + _isBuilding = True + GetNextGeneration() + + DrawForest() + _isBuilding = False + End Sub + + Private Sub GetNextGeneration() + Dim forestCache(_winWidth, _winHeight) As ForestState + Dim rnd As New Random() + + For i As Integer = 0 To _winHeight - 1 + For j As Integer = 0 To _winWidth - 1 + Select Case _forest(j, i) + Case ForestState.Tree + If forestCache(j, i) <> ForestState.Burning Then + forestCache(j, i) = IIf(rnd.NextDouble <= _f, ForestState.Burning, ForestState.Tree) + End If + + Case ForestState.Burning + For i2 As Integer = i - 1 To i + 1 + If i2 = -1 OrElse i2 >= _winHeight Then Continue For + For j2 As Integer = j - 1 To j + 1 + If j2 = -1 OrElse i2 >= _winWidth Then Continue For + If _forest(j2, i2) = ForestState.Tree Then forestCache(j2, i2) = ForestState.Burning + Next + Next + forestCache(j, i) = ForestState.Empty + + Case Else + forestCache(j, i) = IIf(rnd.NextDouble <= _p, ForestState.Tree, ForestState.Empty) + End Select + Next + Next + + _forest = forestCache + _gen += 1 + End Sub + + Private Sub DrawForest() + Dim bmCache As New Bitmap(_winWidth, _winHeight) + + For i As Integer = 0 To _winHeight - 1 + For j As Integer = 0 To _winWidth - 1 + Select Case _forest(j, i) + Case ForestState.Tree + bmCache.SetPixel(j, i, Color.Green) + + Case ForestState.Burning + bmCache.SetPixel(j, i, Color.Red) + End Select + Next + Next + + _bm = bmCache + Me.Refresh() + End Sub + + Private Sub ForestFire_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint + e.Graphics.DrawImage(_bm, 0, 0) + + Me.Text = "Gen " & _gen.ToString() & " @ " & (_gen / (_sw.ElapsedMilliseconds / 1000)).ToString("F02") & " FPS: Forest Fire" + End Sub +End Class diff --git a/Task/Forest-fire/Perl-6/forest-fire.pl6 b/Task/Forest-fire/Perl-6/forest-fire.pl6 index ed3a2d05c3..c9b453b12e 100644 --- a/Task/Forest-fire/Perl-6/forest-fire.pl6 +++ b/Task/Forest-fire/Perl-6/forest-fire.pl6 @@ -4,69 +4,66 @@ my $GREEN = "\e[1;32m"; my $CLEAR = "\e[0m"; enum Cell-State ; -my @show = (' ', $GREEN ~ '木', $YELLOW ~ '木', $RED ~ '木'); +my @pix = ' ', $GREEN ~ '木', $YELLOW ~ '木', $RED ~ '木'; class Forest { - has @!grid; - has @!neighbors; has Int $.height; has Int $.width; - has $.p; - has $.f; - has @!cells = ^$!height X ^$!width; - - method new(Int $height, Int $width, $p=0.01, $f=0.001) { - my $c = self.bless(:$height, :$width, :$p, :$f); - $c!init-grid; - $c!init-neighbors; - return $c; - } + has $.p = 0.01; + has $.f = 0.001; + has @!coords; + has @!spot; + has @!neighbors; - method !init-grid { - @!grid = [ (Bool.pick ?? Tree !! Empty) xx $!width ] xx $!height; + method BUILD (Int :$!height, Int :$!width) { + @!coords = ^$!height X ^$!width; + @!spot = [ (Bool.pick ?? Tree !! Empty) xx $!width ] xx $!height; + self!init-neighbors; } method !init-neighbors { - for @!cells -> $i, $j { + for @!coords -> ($i, $j) { @!neighbors[$i][$j] = eager gather for [-1,-1],[+0,-1],[+1,-1], - [-1,+0],( ),[+1,+0], + [-1,+0], [+1,+0], [-1,+1],[+0,+1],[+1,+1] { - take-rw @!grid[$i + .[0]][$j + .[1]] // next; + take-rw @!spot[$i + .[0]][$j + .[1]] // next; } } } method step { my @heat; - for @!cells -> $i, $j { - given @!grid[$i][$j] { - when Empty { @!grid[$i][$j] = rand < $!p ?? Tree !! Empty } - when Tree { @!grid[$i][$j] = rand < $!f ?? Heating !! Tree } - when Heating { @!grid[$i][$j] = Burning; push @heat, $i, $j; } - when Burning { @!grid[$i][$j] = Empty } + for @!coords -> ($i, $j) { + given @!spot[$i][$j] { + when Empty { $_ = Tree if rand < $!p } + when Tree { $_ = Heating if rand < $!f } + when Heating { $_ = Burning; push @heat, ($i, $j); } + when Burning { $_ = Empty } } } - for @heat -> $i,$j { + for @heat -> ($i,$j) { $_ = Heating for @!neighbors[$i][$j].grep(Tree); } } method show { for ^$!height -> $i { - say @show[@!grid[$i].list].join; + say @pix[@!spot[$i].list].join; } } } -my Forest $f .= new(20,30); -print "\e[2J"; # ANSI clear screen +my ($ROWS, $COLS) = +«qx/stty size/.words; -my $i = 0; -loop { - print "\e[H"; # ANSI home - say $CLEAR, $i++; - $f.show; - $f.step; +sub MAIN (Int $height = $ROWS - 2, Int $width = $COLS div 2 - 1) { + my Forest $forest .= new(:$height, :$width); + print "\e[2J"; # ANSI clear screen + loop { + print "\e[H"; # ANSI home + say $++; + $forest.show; + $forest.step; + } } diff --git a/Task/Forest-fire/REXX/forest-fire.rexx b/Task/Forest-fire/REXX/forest-fire.rexx index 2605f56ec7..3d3c268156 100644 --- a/Task/Forest-fire/REXX/forest-fire.rexx +++ b/Task/Forest-fire/REXX/forest-fire.rexx @@ -1,63 +1,60 @@ -/*REXX program grows and displays a forest (with growth and lightning). - ┌───────────────────────────elided version─────────────────────────┐ - ├─── full version has many more options and enhanced displays. ────┤ - └──────────────────────────────────────────────────────────────────┘ */ -signal on syntax; signal on novalue /*handle REXX program errors. */ -signal on halt /*handle growth interruptus. */ -_= /*(below) nullify some options. */ -parse var _ generations rows cols birth lightning bare! fire! tree!, - randseed clearscreen every -if randseed\=='' then call random ,,randseed - percent = 100 /*handy-dandy constant for using%*/ - field = percent**2 /*size of the probability field. */ - blank = 'BLANK' -generations = p(generations 100) - rows = p(rows word(scrsize(),1)-2) - cols = p(cols max(79,linesize())-1) - bare! = pickchar(bare! blank) - fire! = pickchar(fire! '▒') - tree! = pickchar(tree! '18'x) -clearscreen = p(clearscreen 1) - every = p(every 999999999) - birth = p(strip(birth,,'%') 50 )*percent - lightning = p(strip(lightning,,'%') 1/8)*percent -$.=bare! /*the forest is a treeless field.*/ -@.=bare! /*also, the alternate universe. */ +/*REXX pgm grows and displays a forest (with growth and fires (lightning). + ┌────────────────────────────elided version──────────────────────────┐ + ├──── original version has many more options & enhanced displays.────┤ + └────────────────────────────────────────────────────────────────────┘*/ +signal on syntax; signal on noValue /*handle run─time REXX pgm errors*/ +signal on halt /*handle forest life interruptus.*/ +parse value scrSize() with sd sw . /*the size of the term. display. */ +parse arg generations birth lightning randSeed . /*get optional args. */ +if randSeed\=='' then call random ,,randSeed /*want repeatability?*/ +generations = p(generations 100) /*maybe use 100 generations. */ + birth = p(strip(birth , ,'%') 50 ) * 100 /*calculate the %*/ + lightning = p(strip(lightning, ,'%') 1/8) * 100 /* " " "*/ +clearScreen = 1 /*(or 0) ─── uses CLS (DOS cmd)*/ + forest = 100**2 /* " " " " forest (field).*/ + bare! = ' ' /*glyph used to show a bare place*/ + fire! = '▒' /*well, close to a fire glyph. */ + tree! = '18'x /*this is an up─arrow [↑] glyph.*/ + rows = max(12, sd-2) /*shrink the screen rows by two. */ + cols = max(79, sw-1) /* " " " cols " one. */ + every = 999999999 /*shows a snapshot every Nth time*/ +$.=bare! /*forest: now a treeless field. */ +@.=$. /*ditto, the "shadow" forest. */ gens=abs(generations) /*use this for convenience. */ /*═════════════════════════════════════watch the forest grow and/or burn*/ - do life=1 for gens /*process a forest life cycle. */ - do r=1 for rows; rank=bare! + do life=1 for gens /*simulate a forest's life cycle.*/ + do r=1 for rows; rank=bare! /*start a rank with it being bare*/ do c=2 for cols; ?=substr($.r,c,1); ??=? select /*select da quickest choice first*/ - when ?==tree! then if ignite?() then ??=fire! - when ?==bare! then if random(1,field)<=birth then ??=tree! - otherwise /*fire*/ ??=bare! - end /*select*/ - rank=rank || ?? - end /*c*/ /*ignore column 1, start with 2.*/ - @.r=rank - end /*r*/ + when ?==tree! then if ignite?() then ??=fire! + when ?==bare! then if random(1,forest)<=birth then ??=tree! + otherwise /*it's bare.*/ ??=bare! + end /*select*/ /* [↑] when┼if ≡ short circuit. */ + rank=rank || ?? /*build rank: 1 thingy at a time.*/ + end /*c*/ /*ignore column 1, start with 2. */ + @.r=rank /*and assign to alternate forest.*/ + end /*r*/ /* [↓] ···and, later, back again*/ do r=1 for rows; $.r=@.r; end /*assign alternate cells ──► real*/ if life//every==0 | generations>0 | life==gens then call showForest end /*life*/ /*═════════════════════════════════════stop watching the forest grow. */ -halt: cycles=life-1; if cycles\==gens then say 'REXX program interrupted.' +halt: if life-1\==gens then say 'REXX program interrupted.' /*HALTed?*/ exit /*stick a fork in it, we're done.*/ /*───────────────────────────────SHOWFOREST subroutine──────────────────*/ -showForest: if clearscreen then 'CLS' /* ◄─── change this for your OS.*/ +showForest: if clearScreen then 'CLS' /* ◄─── change this for your OS.*/ do r=rows by -1 for rows /*show the forest in proper order*/ say strip(substr($.r,2),'T') /*be neat about trailing blanks. */ - end /*r*/ + end /*r*/ /* [↑] that's to say, remove 'em*/ say right(copies('═',cols)life, cols) /*show&tell for a stand of trees.*/ return -/*──────────────────────────────────IGNITE? subroutine──────────────────*/ -ignite?: if substr($.r,c+1,1)==fire! then return 1 /*east on fire ?*/ - if substr($.r,c-1,1)==fire! then return 1; rp=r+1; rm=r-1 -cm=c-1; if pos(fire!,substr($.rm,cm,3)substr($.rp,cm,3))\==0 then return 1 -return random(1,field) <= lightning +/*──────────────────────────────────IGNITE? subroutine──────────────────────*/ +ignite?: if substr($.r,c+1,1)==fire! then return 1 /*is east on fire? */ + if substr($.r,c-1,1)==fire! then return 1; /* " west " " */ + rp=r+1; rm=r-1 /*curr. row offsets.*/ + if pos(fire!,substr($.rm,c-1,3)substr($.rp,c-1,3))\==0 then return 1 + return random(1,forest)<=lightning /*───────────────────────────────1─liner subroutines─────────────────────────────────────────────────────────────────────────────────*/ -err: say;say;say center(' error! ',max(40,linesize()%2),"*");say;do j=1 for arg();say arg(j);say;end;say;exit 13 -novalue: syntax: call err 'REXX program' condition('C') "error",condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl) -pickchar: _=p(arg(1));if translate(_)==blank then _=' ';if length(_) ==3 then _=d2c(_);if length(_) ==2 then _=x2c(_);return _ -p: return word(arg(1),1) +err: say; say; say center(' error! ',max(40,sw%2),"*"); say; do _=1 for arg(); say arg(_); say; end; say; exit 13 +noValue: syntax: call err 'REXX program' condition('C') "error",condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl) +p: return word(arg(1),1) /*pick─a─word: first or second word.*/ diff --git a/Task/Fork/DCL/fork-1.dcl b/Task/Fork/DCL/fork-1.dcl new file mode 100644 index 0000000000..3de619e181 --- /dev/null +++ b/Task/Fork/DCL/fork-1.dcl @@ -0,0 +1,7 @@ +$! looper.com procedure +$ i = 10 +$ loop: +$ show time +$ wait 'p1 +$ i = i - 1 +$ if i .gt. 0 then $ goto loop diff --git a/Task/Fork/DCL/fork-2.dcl b/Task/Fork/DCL/fork-2.dcl new file mode 100644 index 0000000000..49da8c0afb --- /dev/null +++ b/Task/Fork/DCL/fork-2.dcl @@ -0,0 +1,3 @@ +$! fork.com procedure +$ set noverify ! detached processes have verify on by default which clutters up the output log file +$ @looper 0::2 diff --git a/Task/Fork/Elixir/fork.elixir b/Task/Fork/Elixir/fork.elixir new file mode 100644 index 0000000000..56c296d776 --- /dev/null +++ b/Task/Fork/Elixir/fork.elixir @@ -0,0 +1,10 @@ +defmodule Fork do + def start do + spawn(fn -> child end) + IO.puts "This is the original process" + end + + def child, do: IO.puts "This is the new process" +end + +Fork.start diff --git a/Task/Formal-power-series/Python/formal-power-series-3.py b/Task/Formal-power-series/Python/formal-power-series-3.py new file mode 100644 index 0000000000..2d28f09fbe --- /dev/null +++ b/Task/Formal-power-series/Python/formal-power-series-3.py @@ -0,0 +1,110 @@ +from itertools import count, chain, tee, islice, cycle +from fractions import Fraction + +# infinite polynomial class +class Poly: + def __init__(self, gen = None): + self.gen, self.source = (None, gen) if type(gen) is Poly \ + else (gen, None) + + def __iter__(self): + # We're essentially tee'ing it everytime the iterator + # is, well, iterated. This may be excessive. + return Poly(self) + + def getsource(self): + if self.gen == None: + s = self.source + s.getsource() + (a,b) = tee(s.gen, 2) + s.gen = a + self.gen = b + + def next(self): + self.getsource() + return next(self.gen) + + __next__ = next + + # Overload "<<" as stream input operator. Hey, C++ does it. + def __lshift__(self, a): self.gen = a + + # The other operators are pretty much what one would expect + def __neg__(self): return Poly(-x for x in self) + + def __sub__(a, b): return a + (-b) + + def __rsub__(a, n): + a = Poly(a) + def gen(): + yield(n - next(a)) + for x in a: yield(-x) + return Poly(gen()) + + def __add__(a, b): + if type(b) is Poly: + return Poly(x + y for (x,y) in zip(a,b)) + + a = Poly(a) + def gen(): + yield(next(a) + b) + for x in a: yield(x) + return Poly(gen()) + + def __radd__(a,b): + return a + b + + def __mul__(a,b): + if not type(b) is Poly: + return Poly(x*b for x in a) + + def gen(): + s = Poly(cycle([0])) + for y in b: + s += y*a + yield(next(s)) + + return Poly(gen()) + + def __rmul__(a,b): return a*b + + def __truediv__(a,b): + if not type(b) is Poly: + return Poly(Fraction(x, b) for x in a) + + a, b = Poly(a), Poly(b) + def gen(): + r, bb = a,next(b) + while True: + aa = next(r) + q = Fraction(aa, bb) + yield(q) + r -= q*b + + return Poly(gen()) + +# these two would probably be better as class methods +def inte(a): + def gen(): + yield(0) + for (x,n) in zip(a, count(1)): + yield(Fraction(x,n)) + return Poly(gen()) + +def diff(a): + def gen(): + for (x, n) in zip(a, count(0)): + if n: yield(x*n) + return Poly(gen()) + + +# all that for the syntactic sugar +sinx, cosx, tanx, expx = Poly(), Poly(), Poly(), Poly() + +sinx << inte(cosx) +cosx << 1 - inte(sinx) +tanx << sinx / cosx # "=" would also work here +expx << 1 + inte(expx) + +for n,x in zip(("sin", "cos", "tan", "exp"), (sinx, cosx, tanx, expx)): + print(n, ', '.join(map(str, list(islice(x, 10))))) diff --git a/Task/Formatted-numeric-output/Elixir/formatted-numeric-output.elixir b/Task/Formatted-numeric-output/Elixir/formatted-numeric-output.elixir new file mode 100644 index 0000000000..4570a9dde5 --- /dev/null +++ b/Task/Formatted-numeric-output/Elixir/formatted-numeric-output.elixir @@ -0,0 +1,14 @@ +n = 7.125 +:io.fwrite "~f~n", [n] +:io.fwrite "~.3f~n", [n] +:io.fwrite "~9f~n", [n] +:io.fwrite "~9.3f~n", [n] +:io.fwrite "~9..0f~n", [n] +:io.fwrite "~9.3.0f~n", [n] +:io.fwrite "~9.3._f~n", [n] +:io.fwrite "~f~n", [-n] +:io.fwrite "~9.3f~n", [-n] +:io.fwrite "~9.3.0f~n", [-n] +:io.fwrite "~e~n", [n] +:io.fwrite "~12.4e~n", [n] +:io.fwrite "~12.4.0e~n", [n] diff --git a/Task/Formatted-numeric-output/Fortran/formatted-numeric-output.f b/Task/Formatted-numeric-output/Fortran/formatted-numeric-output-1.f similarity index 100% rename from Task/Formatted-numeric-output/Fortran/formatted-numeric-output.f rename to Task/Formatted-numeric-output/Fortran/formatted-numeric-output-1.f diff --git a/Task/Formatted-numeric-output/Fortran/formatted-numeric-output-2.f b/Task/Formatted-numeric-output/Fortran/formatted-numeric-output-2.f new file mode 100644 index 0000000000..a1af480e4a --- /dev/null +++ b/Task/Formatted-numeric-output/Fortran/formatted-numeric-output-2.f @@ -0,0 +1,7 @@ + INTEGER IV + REAL V + DATA V/7.125/ !A positive number. + IV = V !Grab the integer part. + WRITE (6,1) V,IV + 1 FORMAT (F9.3,T1,I5.5) + END diff --git a/Task/Formatted-numeric-output/Julia/formatted-numeric-output.julia b/Task/Formatted-numeric-output/Julia/formatted-numeric-output.julia new file mode 100644 index 0000000000..92f3a5b764 --- /dev/null +++ b/Task/Formatted-numeric-output/Julia/formatted-numeric-output.julia @@ -0,0 +1,14 @@ +test = [7.125, [rand()*10^rand(0:4) for i in 1:9]] + +println("Formatting some numbers with the @sprintf macro (using \"%09.3f\"):") +for i in test + println(@sprintf " %09.3f" i) +end + +using Formatting +println() +println("The same thing using the Formatting package:") +fe = FormatExpr(" {1:09.3f}") +for i in test + printfmtln(fe, i) +end diff --git a/Task/Formatted-numeric-output/Ruby/formatted-numeric-output.rb b/Task/Formatted-numeric-output/Ruby/formatted-numeric-output.rb index 64eb341b18..092a4c84be 100644 --- a/Task/Formatted-numeric-output/Ruby/formatted-numeric-output.rb +++ b/Task/Formatted-numeric-output/Ruby/formatted-numeric-output.rb @@ -1 +1,9 @@ -printf " %09.3f\n", 7.125 +r = 7.125 +printf " %9.3f\n", r #=> 7.125 +printf " %09.3f\n", r #=> 00007.125 +printf " %09.3f\n", -r #=> -0007.125 +printf " %+09.3f\n", r #=> +0007.125 +puts " %9.3f" % r #=> 7.125 +puts " %09.3f" % r #=> 00007.125 +puts " %09.3f" % -r #=> -0007.125 +puts " %+09.3f" % r #=> +0007.125 diff --git a/Task/Forward-difference/00DESCRIPTION b/Task/Forward-difference/00DESCRIPTION index f10fa20388..0fe02145e3 100644 --- a/Task/Forward-difference/00DESCRIPTION +++ b/Task/Forward-difference/00DESCRIPTION @@ -1,6 +1,22 @@ Provide code that produces a list of numbers which is the n-th order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers (A) is a new list (B) where Bn = An+1 - An. List B should have one fewer element as a result. -The second-order forward difference of A will be the same as the first-order forward difference of B. +The second-order forward difference of A will be tdefmodule Diff do + def forward(arr,i\\1) do + forward(arr,[],i) + end + + def forward([_|[]],diffs,i) do + if i == 1 do + IO.inspect diffs + else + forward(diffs,[],i-1) + end + end + + def forward([val1|[val2|vals]],diffs,i) do + forward([val2|vals],diffs++[val2-val1],i) + end +endhe same as the first-order forward difference of B. That new list will have two fewer elements than A and one less than B. The goal of this task is to repeat this process up to the desired order. diff --git a/Task/Forward-difference/Elixir/forward-difference.elixir b/Task/Forward-difference/Elixir/forward-difference.elixir new file mode 100644 index 0000000000..d1519ce77c --- /dev/null +++ b/Task/Forward-difference/Elixir/forward-difference.elixir @@ -0,0 +1,15 @@ +defmodule Diff do + def forward(list,i\\1) do + forward(list,[],i) + end + + def forward([_],diffs,1), do: IO.inspect diffs + def forward([_],diffs,i), do: forward(diffs,[],i-1) + def forward([val1,val2|vals],diffs,i) do + forward([val2|vals],diffs++[val2-val1],i) + end +end + +Enum.each(1..9, fn i -> + Diff.forward([90, 47, 58, 29, 22, 32, 55, 5, 55, 73],i) +end) diff --git a/Task/Forward-difference/REXX/forward-difference-1.rexx b/Task/Forward-difference/REXX/forward-difference-1.rexx index e9af4e5aaf..f4d94ef1a7 100644 --- a/Task/Forward-difference/REXX/forward-difference-1.rexx +++ b/Task/Forward-difference/REXX/forward-difference-1.rexx @@ -1,41 +1,24 @@ - butchers/mangles some of the characters in the documentation box. --> -/*REXX program computes the forward difference of a list of numbers. - ╔════════════════════════════════════════════════════════════════════╗ - ║ /\ n n n-k ║ - ║ / \ n [ƒ] (x) ≡ Σ C ∙ (-1) ∙ ƒ(x+k) ║ - ║ /____\ k=0 k ║ - ║ ↑ ↑ ↑ ║ - ║ │ │ │ ║ - ║ {delta}─────┘ {n=order} {C=comb or binomial coeff.} ║ - ╚════════════════════════════════════════════════════════════════════╝*/ -numeric digits 100 /*ensure enough accuracy (digits)*/ -parse arg xxx ',' N /*input: ε1 ε2 ε3 ε4 ··· , order*/ -if xxx=='' then xxx='90 47 58 29 22 32 55 5 55 73' /*default numbers.*/ -w=words(xxx) /*set W to # of numbers in list.*/ - /* [↓] validate the input numbers*/ - do i=1 for w; _=word(xxx,i) /*process each number 1 at a time*/ - if \datatype(_,'N') then call ser _ "isn't a valid number" - @.i=_/1 /*normalize the #, prettify the #*/ - end /*i*/ /* [↑] removes superfluous stuff*/ - /* [↓] process (optional) order.*/ -if w==0 then call ser 'no numbers were specified.' -if N\=='' & N<0 then call ser N "(order) can't be negative." -if N\=='' & N>w then call ser N "(order) can't be greater than" w -say right(w 'numbers:', 44) xxx /*display the header ··· */ -say left('', 44)copies('─', length(xxx)+2) /* and the header fence.*/ -if N=='' then do; bot=0; top=w; end /*define default orders. */ - else do; bot=N; top=N; end /*just a specific order? */ -/*═════════════════════════════════════════where da rubber meets da road*/ - do #=bot to top; do r=1 for w; !.r=@.r; end; $= - do j=1 for #; d=!.j; do k=j+1 to w - parse value !.k !.k-d with d !.k - end /*k*/ - end /*j*/ - do i=#+1 to w; $=$ !.i/1; end - if $=='' then $='[null]' - say right(#, 7)th(#)'-order forward difference vector = ' strip($) - end /*o*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one─liner subroutines───────────────*/ -ser: say; say '***error!***'; say arg(1); say; exit 13 -th: arg ?; return word('th st nd rd',1+?//10*(?//100%10\==1)*(?//10<4)) +/*REXX program computes the forward difference of a list of numbers. */ +numeric digits 100 /*ensure enough accuracy (decimal digs)*/ +parse arg e ',' N /*get a list: ε1 ε2 ε3 ε4 ··· , order */ +if e=='' then e='90 47 58 29 22 32 55 5 55 73' /*use some default numbers. */ +#=words(e) /*# is the number of elements in list.*/ + /* [↓] assign list numbers to @ array.*/ + do i=1 for #; @.i=word(e,i)/1; end /*process each number one at a time. */ + /* [↓] process the optional order. */ +if N=='' then parse value 0 # # with bot top N /*define default order range. */ + else parse var N bot 1 top /*Specified? Use only 1 order*/ +say right(# 'numbers:', 44) e /*display the header (title) and ··· */ +say left('',44)copies('─',length(e)+2) /*display the header fence. */ + /* [↓] where da rubber meets da road. */ + do o=bot to top; do r=1 for #; !.r=@.r; end; $= + do j=1 for o; d=!.j; do k=j+1 to #; parse value !.k !.k-d with d !.k; end + end /*j*/ + do i=o+1 to #; $=$ !.i/1; end + if $=='' then $='[null]' + say right(o,7)th(o)'─order forward difference vector =' $ + end /*o*/ + +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +th: arg ?; return word('th st nd rd',1+?//10*(?//100%10\==1)*(?//10<4)) diff --git a/Task/Forward-difference/REXX/forward-difference-2.rexx b/Task/Forward-difference/REXX/forward-difference-2.rexx index ea46c43523..983f5ea480 100644 --- a/Task/Forward-difference/REXX/forward-difference-2.rexx +++ b/Task/Forward-difference/REXX/forward-difference-2.rexx @@ -1,35 +1,30 @@ -/* REXX *************************************************************** -* Forward differences -* 18.08.2012 Walter Pachl derived from PL/I -**********************************************************************/ -Do n=-1 To 11 - Call differences '90 47 58 29 22 32 55 5 55 73',n - End -Exit +/*REXX program computes the forward difference of a list of numbers. */ +numeric digits 100 /*ensure enough accuracy (decimal digs)*/ +parse arg e ',' N /*get a list: ε1 ε2 ε3 ε4 ··· , order */ +if e=='' then e='90 47 58 29 22 32 55 5 55 73' /*use some default numbers. */ +#=words(e) /*# is the number of elements in list.*/ + /* [↓] verify list items are numeric. */ + do i=1 for #; _=word(e,i) /*process each number one at a time. */ + if \datatype(_,'N') then call ser _ "isn't a valid number"; @.i=_/1 + end /*i*/ /* [↑] removes superfluous stuff. */ + /* [↓] process the optional order. */ +if N=='' then parse value 0 # # with bot top N /*define default order range. */ + else parse var N bot 1 top /*Specified? Use only 1 order*/ +if #==0 then call ser "no numbers were specified." +if N<0 then call ser N "(order) can't be negative." +if N># then call ser N "(order) can't be greater than" # +say right(# 'numbers:', 44) e /*display the header (title) and ··· */ +say left('',44)copies('─',length(e)+2) /*display the header fence. */ + /* [↓] where da rubber meets da road. */ + do o=bot to top; do r=1 for #; !.r=@.r; end; $= + do j=1 for o; d=!.j; do k=j+1 to #; parse value !.k !.k-d with d !.k; end + end /*j*/ + do i=o+1 to #; $=$ !.i/1; end + if $=='' then $=' [null]' + say right(o,7)th(o)'─order forward difference vector =' $ + end /*o*/ -differences: Procedure - Parse Arg a,n - m=words(a) - Select - When n<0 Then Say 'n is negative:' n '<' 0 - When n>m Then Say 'n is too large:' n '>' m - Otherwise Do - Do i=1 By 1 while a<>'' - Parse Var a a.i a - End - Do i = 1 to n; - t = a.i; - Do j = i+1 to m; - u = a.j - a.j = a.j-t; - t = u; - end; - end; - ol='' - Do k=n+1 to m - ol=ol a.k - End - Say n ol - End - End - Return +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +ser: say; say '***error!***'; say arg(1); say; exit 13 +th: arg ?; return word('th st nd rd',1+?//10*(?//100%10\==1)*(?//10<4)) diff --git a/Task/Forward-difference/REXX/forward-difference-3.rexx b/Task/Forward-difference/REXX/forward-difference-3.rexx new file mode 100644 index 0000000000..e7f359f44e --- /dev/null +++ b/Task/Forward-difference/REXX/forward-difference-3.rexx @@ -0,0 +1,34 @@ +/*REXX program computes the forward difference of a list of numbers. */ +numeric digits 100 /*ensure enough accuracy (decimal digs)*/ +parse arg e ',' N /*get a list: ε1 ε2 ε3 ε4 ··· , order */ +if e=='' then e='90 47 58 29 22 32 55 5 55 73' /*use some default numbers. */ +#=words(e); w=5 /*# is the number of elements in list.*/ + /* [↓] verify list items are numeric. */ + do i=1 for #; _=word(e,i) /*process each number one at a time. */ + if \datatype(_,'N') then call ser _ "isn't a valid number"; @.i=_/1 + w=max(w,length(@.i)) /*use the maximum length of an element.*/ + end /*i*/ /* [↑] removes superfluous stuff. */ + /* [↓] process the optional order. */ +if N=='' then parse value 0 # # with bot top N /*define default order range. */ + else parse var N bot 1 top /*Specified? Use only 1 order*/ +if #==0 then call ser "no numbers were specified." +if N<0 then call ser N "(order) can't be negative." +if N># then call ser N "(order) can't be greater than" # +_=; do k=1 for #; _=_ right(@.k,w); end /*k*/; _=substr(_,2) +say right(# 'numbers:', 44) _ /*display the header (title) and ··· */ +say left('',44)copies('─',w*#+#) /*display the header fence. */ + /* [↓] where da rubber meets da road. */ + do o=bot to top; do r=1 for #; !.r=@.r; end /*r*/; $= + do j=1 for o; d=!.j; do k=j+1 to #; parse value !.k !.k-d with d !.k + w=max(w,length(!.k)) + end /*k*/ + end /*j*/ + do i=o+1 to #; $=$ right(!.i/1,w); end /*i*/ + if $=='' then $='[null]' + say right(o,7)th(o)'─order forward difference vector =' $ + end /*o*/ + +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +ser: say; say '***error!***'; say arg(1); say; exit 13 +th: arg ?; return word('th st nd rd',1+?//10*(?//100%10\==1)*(?//10<4)) diff --git a/Task/Forward-difference/REXX/forward-difference-4.rexx b/Task/Forward-difference/REXX/forward-difference-4.rexx new file mode 100644 index 0000000000..ea46c43523 --- /dev/null +++ b/Task/Forward-difference/REXX/forward-difference-4.rexx @@ -0,0 +1,35 @@ +/* REXX *************************************************************** +* Forward differences +* 18.08.2012 Walter Pachl derived from PL/I +**********************************************************************/ +Do n=-1 To 11 + Call differences '90 47 58 29 22 32 55 5 55 73',n + End +Exit + +differences: Procedure + Parse Arg a,n + m=words(a) + Select + When n<0 Then Say 'n is negative:' n '<' 0 + When n>m Then Say 'n is too large:' n '>' m + Otherwise Do + Do i=1 By 1 while a<>'' + Parse Var a a.i a + End + Do i = 1 to n; + t = a.i; + Do j = i+1 to m; + u = a.j + a.j = a.j-t; + t = u; + end; + end; + ol='' + Do k=n+1 to m + ol=ol a.k + End + Say n ol + End + End + Return diff --git a/Task/Four-bit-adder/Julia/four-bit-adder-1.julia b/Task/Four-bit-adder/Julia/four-bit-adder-1.julia new file mode 100644 index 0000000000..da2f03738e --- /dev/null +++ b/Task/Four-bit-adder/Julia/four-bit-adder-1.julia @@ -0,0 +1,28 @@ +xor{T<:Bool}(a::T, b::T) = (a&~b)|(~a&b) + +halfadder{T<:Bool}(a::T, b::T) = (xor(a,b), a&b) + +function fulladder{T<:Bool}(a::T, b::T, c::T=false) + (s, ca) = halfadder(c, a) + (s, cb) = halfadder(s, b) + (s, ca|cb) +end + +function adder(a::BitArray{1}, b::BitArray{1}, c0::Bool=false) + len = length(a) + length(b) == len || error("Addend width mismatch.") + c = c0 + s = falses(len) + for i in 1:len + (s[i], c) = fulladder(a[i], b[i], c) + end + (s, c) +end + +function adder{T<:Integer}(m::T, n::T, wid::T=4, c0::Bool=false) + a = bitpack(digits(m, 2, wid))[1:wid] + b = bitpack(digits(n, 2, wid))[1:wid] + adder(a, b, c0) +end + +Base.bits(n::BitArray{1}) = join(reverse(int(n)), "") diff --git a/Task/Four-bit-adder/Julia/four-bit-adder-2.julia b/Task/Four-bit-adder/Julia/four-bit-adder-2.julia new file mode 100644 index 0000000000..1c637be373 --- /dev/null +++ b/Task/Four-bit-adder/Julia/four-bit-adder-2.julia @@ -0,0 +1,18 @@ +xavail = trues(15,15) +xcnt = 0 +xgoal = 10 +println("Testing adder with 4-bit words:") +while xcnt < xgoal + m = rand(1:15) + n = rand(1:15) + xavail[m,n] || continue + xavail[m,n] = xavail[n,m] = false + xcnt += 1 + (s, c) = adder(m, n) + oflow = c ? "*" : "" + print(@sprintf " %2d + %2d = %2d => " m n m+n) + println(@sprintf("%s + %s = %s%s", + bits(m)[end-3:end], + bits(n)[end-3:end], + bits(s), oflow)) +end diff --git a/Task/Four-bit-adder/Verilog/four-bit-adder.v b/Task/Four-bit-adder/Verilog/four-bit-adder.v new file mode 100644 index 0000000000..8bf83c763b --- /dev/null +++ b/Task/Four-bit-adder/Verilog/four-bit-adder.v @@ -0,0 +1,48 @@ +module Half_Adder( output c, s, input a, b ); + xor xor01 (s, a, b); + and and01 (c, a, b); +endmodule // Half_Adder + +module Full_Adder( output c_out, s, input a, b, c_in ); + + wire s_ha1, c_ha1, c_ha2; + + Half_Adder ha01( c_ha1, s_ha1, a, b ); + Half_Adder ha02( c_ha2, s, s_ha1, c_in ); + or or01 ( c_out, c_ha1, c_ha2 ); + +endmodule // Full_Adder + +module Full_Adder4( output [4:0] s, input [3:0] a, b, input c_in ); + + wire [4:0] c; + + Full_Adder adder00 ( c[1], s[0], a[0], b[0], c_in ); + Full_Adder adder01 ( c[2], s[1], a[1], b[1], c[1] ); + Full_Adder adder02 ( c[3], s[2], a[2], b[2], c[2] ); + Full_Adder adder03 ( c[4], s[3], a[3], b[3], c[3] ); + + assign s[4] = c[4]; + +endmodule // Full_Adder4 + +module test_Full_Adder(); + + reg [3:0] a; + reg [3:0] b; + wire [4:0] s; + + Full_Adder4 FA4 ( s, a, b, 0 ); + + initial begin + $display( " a + b = s" ); + $monitor( "%4d + %4d = %5d", a, b, s ); + a=4'b0000; b=4'b0000; + #1 a=4'b0000; b=4'b0001; + #1 a=4'b0001; b=4'b0001; + #1 a=4'b0011; b=4'b0001; + #1 a=4'b0111; b=4'b0001; + #1 a=4'b1111; b=4'b0001; + end + +endmodule // test_Full_Adder diff --git a/Task/Fractal-tree/Common-Lisp/fractal-tree.lisp b/Task/Fractal-tree/Common-Lisp/fractal-tree.lisp new file mode 100644 index 0000000000..cc0690c0a6 --- /dev/null +++ b/Task/Fractal-tree/Common-Lisp/fractal-tree.lisp @@ -0,0 +1,37 @@ +;; (require :lispbuilder-sdl) + +(defun deg-to-radian (deg) + "converts degrees to radians" + (* deg pi 1/180)) + +(defun cos-deg (angle) + "returns cosin of the angle expressed in degress" + (cos (deg-to-radian angle))) + +(defun sin-deg (angle) + "returns sin of the angle expressed in degress" + (sin (deg-to-radian angle))) + +(defun draw-tree (surface x y angle depth) + "draws a branch of the tree on the sdl-surface" + (when (plusp depth) + (let ((x2 (+ x (round (* depth 10 (cos-deg angle))))) + (y2 (+ y (round (* depth 10 (sin-deg angle)))))) + (sdl:draw-line-* x y x2 y2 :surface surface :color sdl:*green*) + (draw-tree surface x2 y2 (- angle 20) (1- depth)) + (draw-tree surface x2 y2 (+ angle 20) (1- depth))))) + +(defun fractal-tree (depth) + "shows a window with a fractal tree" + (sdl:with-init () + (sdl:window 800 600 :title-caption "fractal-tree") + (sdl:clear-display sdl:*black*) + (draw-tree sdl:*default-surface* 400 500 -90 depth) + (sdl:update-display) + (sdl:with-events () + (:video-expose-event () + (sdl:update-display)) + (:quit-event () + t)))) + +(fractal-tree 9) diff --git a/Task/Fractal-tree/JavaScript/fractal-tree.js b/Task/Fractal-tree/JavaScript/fractal-tree.js index e4733b70ee..5ac8ac000e 100644 --- a/Task/Fractal-tree/JavaScript/fractal-tree.js +++ b/Task/Fractal-tree/JavaScript/fractal-tree.js @@ -1,33 +1,37 @@ + + diff --git a/Task/Fractran/Batch-File/fractran.bat b/Task/Fractran/Batch-File/fractran.bat new file mode 100644 index 0000000000..956eee44cc --- /dev/null +++ b/Task/Fractran/Batch-File/fractran.bat @@ -0,0 +1,56 @@ +@echo off +setlocal enabledelayedexpansion + + ::Set the inputs +set "code=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" +set "n=2" + + ::Basic validation of code +for %%. in (!code!) do ( + echo.%%.|findstr /r /c:"^[0-9][0-9]*/[1-9][0-9]*$">nul||goto error_code +) + ::Validate the input +set /a "tst=1*!n!" 2>nul +if !tst! lss 0 goto error_input +if !tst! equ 0 (if not "!n!"=="0" (goto error_input)) + + ::Set the limit outputs + set limit=20 + + ::Execute the code +echo.Input: +echo. !n! +echo.Output: +for /l %%? in (1,1,!limit!) do ( + set shouldwehalt=1 + for %%A in (!code!) do ( + for /f "tokens=1,2 delims=/" %%B in ("%%A") do ( + set /a "tst=!n! %% %%C" + if !tst! equ 0 ( + if !shouldwehalt! equ 1 ( + set shouldwehalt=0 + set /a "n=n*%%B/%%C" + echo. !n! + ) + ) + ) + ) + if !shouldwehalt! equ 1 goto halt +) + +:halt +echo. +pause +exit /b 0 + +:error_code +echo.Syntax error in code. +echo. +pause +exit /b 1 + +:error_input +echo.Invalid input. +echo. +pause +exit /b 1 diff --git a/Task/Fractran/C++/fractran.cpp b/Task/Fractran/C++/fractran.cpp index a7be3afd55..0f68fa192b 100644 --- a/Task/Fractran/C++/fractran.cpp +++ b/Task/Fractran/C++/fractran.cpp @@ -2,7 +2,7 @@ #include #include #include -#include +#include using namespace std; @@ -33,13 +33,13 @@ class fractran private: void exec( vector< pair >* v ) { - int cnt = 0; bool found; float r; + int cnt = 0; while( cnt < limit ) { cout << cnt << " : " << start << "\n"; cnt++; vector< pair >::iterator it = v->begin(); - found = false; + bool found = false; float r; while( it != v->end() ) { r = start * ( ( *it ).first / ( *it ).second ); @@ -60,5 +60,6 @@ class fractran 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" ); + cin.get(); + return 0; } diff --git a/Task/Fractran/Perl-6/fractran-1.pl6 b/Task/Fractran/Perl-6/fractran-1.pl6 index 1882f33ce0..822d885eee 100644 --- a/Task/Fractran/Perl-6/fractran-1.pl6 +++ b/Task/Fractran/Perl-6/fractran-1.pl6 @@ -1,6 +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 + |<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/Scala/fractran.scala b/Task/Fractran/Scala/fractran.scala new file mode 100644 index 0000000000..05d38ba924 --- /dev/null +++ b/Task/Fractran/Scala/fractran.scala @@ -0,0 +1,24 @@ +class TestFractran extends FunSuite { + val program = 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") + val expect = List(2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290, 770, 910, 170, 156, 132) + + test("find first fifteen fractran figures") { + assert((program .execute(2) take 15 toList) === expect) + } +} + +object Fractran { + val pattern = """\s*(\d+)\s*/\s*(\d+)\s*""".r + def parse(m: Match) = ((m group 1).toInt, (m group 2).toInt) + def apply(program: String) = new Fractran( + pattern.findAllMatchIn(program).map(parse).toList) +} + +class Fractran(val numDem: List[(Int,Int)]) { + def execute(value: Int) = unfold(value) { v => + numDem indexWhere(v % _._2 == 0) match { + case i if i > -1 => Some(v, numDem(i)._1 * v / numDem(i)._2) + case _ => None + } + } +} diff --git a/Task/Function-composition/Elixir/function-composition.elixir b/Task/Function-composition/Elixir/function-composition.elixir new file mode 100644 index 0000000000..ee5c8532c8 --- /dev/null +++ b/Task/Function-composition/Elixir/function-composition.elixir @@ -0,0 +1,11 @@ +defmodule RC do + def compose(f, g), do: fn(x) -> f.(g.(x)) end + + def multicompose(fs), do: List.foldl(fs, fn(x) -> x end, &compose/2) +end + +sin_asin = RC.compose(&:math.sin/1, &:math.asin/1) +IO.puts sin_asin.(0.5) + +IO.puts RC.multicompose([&:math.sin/1, &:math.asin/1, fn x->1/x end]).(0.5) +IO.puts RC.multicompose([&(&1*&1), &(1/&1), &(&1*&1)]).(0.5) diff --git a/Task/Function-composition/Java/function-composition-2.java b/Task/Function-composition/Java/function-composition-2.java index 349e6a1858..aeb3d832b1 100644 --- a/Task/Function-composition/Java/function-composition-2.java +++ b/Task/Function-composition/Java/function-composition-2.java @@ -1,12 +1,8 @@ import java.util.function.Function; public class Compose { - public static Function compose(Function f, Function g) { - return x -> f.apply(g.apply(x)); - } - public static void main(String[] args) { - Function sin_asin = compose(Math::sin, Math::asin); + Function sin_asin = ((Function)Math::sin).compose(Math::asin); System.out.println(sin_asin.apply(0.5)); // prints "0.5" } diff --git a/Task/Function-composition/Java/function-composition-3.java b/Task/Function-composition/Java/function-composition-3.java new file mode 100644 index 0000000000..349e6a1858 --- /dev/null +++ b/Task/Function-composition/Java/function-composition-3.java @@ -0,0 +1,13 @@ +import java.util.function.Function; + +public class Compose { + public static Function compose(Function f, Function g) { + return x -> f.apply(g.apply(x)); + } + + public static void main(String[] args) { + Function sin_asin = compose(Math::sin, Math::asin); + + System.out.println(sin_asin.apply(0.5)); // prints "0.5" + } +} diff --git a/Task/Function-composition/Perl-6/function-composition.pl6 b/Task/Function-composition/Perl-6/function-composition.pl6 new file mode 100644 index 0000000000..c88b867d54 --- /dev/null +++ b/Task/Function-composition/Perl-6/function-composition.pl6 @@ -0,0 +1,3 @@ +sub triple($n) { 3 * $n } +my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 }; +say &f(5); # Prints "-21". diff --git a/Task/Function-composition/PowerShell/function-composition-1.psh b/Task/Function-composition/PowerShell/function-composition-1.psh new file mode 100644 index 0000000000..e6196e8576 --- /dev/null +++ b/Task/Function-composition/PowerShell/function-composition-1.psh @@ -0,0 +1,7 @@ +function g ($x) { + $x + $x +} +function f ($x) { + $x*$x*$x +} +f (g 1) diff --git a/Task/Function-composition/PowerShell/function-composition-2.psh b/Task/Function-composition/PowerShell/function-composition-2.psh new file mode 100644 index 0000000000..5cbf753f3f --- /dev/null +++ b/Task/Function-composition/PowerShell/function-composition-2.psh @@ -0,0 +1,4 @@ +function fg (${function:f}, ${function:g}, $x) { + f (g $x) +} +fg f g 1 diff --git a/Task/Function-definition/360-Assembly/function-definition.360 b/Task/Function-definition/360-Assembly/function-definition.360 new file mode 100644 index 0000000000..d2580eb886 --- /dev/null +++ b/Task/Function-definition/360-Assembly/function-definition.360 @@ -0,0 +1,38 @@ +DEFFUN CSECT + USING DEFFUN,R13 +SAVEAREA B PROLOG-SAVEAREA(R15) + DC 17F'0' +PROLOG STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 set base register +BEGIN L R2,=F'13' + ST R2,X X=13 + L R2,=F'17' + ST R2,Y Y=17 + LA R1,PARMLIST R1->PARMLIST + B SKIPPARM +PARMLIST DS 0F + DC A(X) + DC A(Y) +SKIPPARM BAL R14,MULTPLIC call MULTPLIC + ST R0,Z Z=MULTPLIC(X,Y) +RETURN L R13,4(0,R13) epilog + LM R14,R12,12(R13) + XR R15,R15 set return code + BR R14 return to caller +* +MULTPLIC EQU * function MULTPLIC(X,Y) + L R2,0(R1) R2=(A(X),A(Y)) + XR R4,R4 R4=0 + L R5,0(R2) R5=X + L R6,4(R2) R6=Y + MR R4,R6 R4R5=R4R5*R6 + LR R0,R5 R0=X*Y (R0 return value) + BR R14 end function MULTPLIC +* +X DS F +Y DS F +Z DS F + YREGS + END DEFFUN diff --git a/Task/Function-definition/ALGOL-W/function-definition.alg b/Task/Function-definition/ALGOL-W/function-definition.alg new file mode 100644 index 0000000000..eb8ffeb08b --- /dev/null +++ b/Task/Function-definition/ALGOL-W/function-definition.alg @@ -0,0 +1,4 @@ +long real procedure multiply( long real value a, b ); +begin + a * b +end diff --git a/Task/Function-definition/Elixir/function-definition.elixir b/Task/Function-definition/Elixir/function-definition.elixir new file mode 100644 index 0000000000..43717ca744 --- /dev/null +++ b/Task/Function-definition/Elixir/function-definition.elixir @@ -0,0 +1,9 @@ +defmodule RosettaCode do + def multiply(x,y) do + x * y + end + + def task, do: IO.puts multiply(3,5) +end + +RosettaCode.task diff --git a/Task/Function-definition/Fortran/function-definition-1.f b/Task/Function-definition/Fortran/function-definition-1.f index 6530c5319a..a9d166fcef 100644 --- a/Task/Function-definition/Fortran/function-definition-1.f +++ b/Task/Function-definition/Fortran/function-definition-1.f @@ -1,4 +1 @@ -FUNCTION MULTIPLY(X,Y) -REAL MULTIPLY, X, Y -MULTIPLY = X * Y -END + XMULTF(X,Y)=X*Y diff --git a/Task/Function-definition/Fortran/function-definition-2.f b/Task/Function-definition/Fortran/function-definition-2.f index 7a09110cd2..85dca9b20f 100644 --- a/Task/Function-definition/Fortran/function-definition-2.f +++ b/Task/Function-definition/Fortran/function-definition-2.f @@ -1,8 +1 @@ -module elemFunc -contains - elemental function multiply(x, y) - real, intent(in) :: x, y - real :: multiply - multiply = x * y - end function multiply -end module elemFunc + MULTF(I,J)=I*J diff --git a/Task/Function-definition/Fortran/function-definition-3.f b/Task/Function-definition/Fortran/function-definition-3.f index 2732739225..6530c5319a 100644 --- a/Task/Function-definition/Fortran/function-definition-3.f +++ b/Task/Function-definition/Fortran/function-definition-3.f @@ -1,10 +1,4 @@ -program funcDemo - use elemFunc - - real :: a = 20.0, b = 30.0, c - real, dimension(5) :: x = (/ 1.0, 2.0, 3.0, 4.0, 5.0 /), y = (/ 32.0, 16.0, 8.0, 4.0, 2.0 /), z - - c = multiply(a,b) ! works with either function definition above - - z = multiply(x,y) ! element-wise invocation only works with elemental function -end program funcDemo +FUNCTION MULTIPLY(X,Y) +REAL MULTIPLY, X, Y +MULTIPLY = X * Y +END diff --git a/Task/Function-definition/Fortran/function-definition-4.f b/Task/Function-definition/Fortran/function-definition-4.f index 8e6692f2ba..7d7080ba44 100644 --- a/Task/Function-definition/Fortran/function-definition-4.f +++ b/Task/Function-definition/Fortran/function-definition-4.f @@ -1,2 +1,4 @@ -c = multiply(y=b, x=a) ! the same as multiply(a, b) -z = multiply(y=x, x=y) ! the same as multiply(y, x) +FUNCTION MULTINT(X,Y) +INTEGER MULTINT, X, Y +MULTINT = X * Y +END diff --git a/Task/Function-definition/Fortran/function-definition-5.f b/Task/Function-definition/Fortran/function-definition-5.f index 95fcb20391..7a09110cd2 100644 --- a/Task/Function-definition/Fortran/function-definition-5.f +++ b/Task/Function-definition/Fortran/function-definition-5.f @@ -1,8 +1,8 @@ module elemFunc contains - elemental function multiply(x, y) result(z) + elemental function multiply(x, y) real, intent(in) :: x, y - real :: z - z = x * y + real :: multiply + multiply = x * y end function multiply end module elemFunc diff --git a/Task/Function-definition/Fortran/function-definition-6.f b/Task/Function-definition/Fortran/function-definition-6.f new file mode 100644 index 0000000000..2732739225 --- /dev/null +++ b/Task/Function-definition/Fortran/function-definition-6.f @@ -0,0 +1,10 @@ +program funcDemo + use elemFunc + + real :: a = 20.0, b = 30.0, c + real, dimension(5) :: x = (/ 1.0, 2.0, 3.0, 4.0, 5.0 /), y = (/ 32.0, 16.0, 8.0, 4.0, 2.0 /), z + + c = multiply(a,b) ! works with either function definition above + + z = multiply(x,y) ! element-wise invocation only works with elemental function +end program funcDemo diff --git a/Task/Function-definition/Fortran/function-definition-7.f b/Task/Function-definition/Fortran/function-definition-7.f new file mode 100644 index 0000000000..8e6692f2ba --- /dev/null +++ b/Task/Function-definition/Fortran/function-definition-7.f @@ -0,0 +1,2 @@ +c = multiply(y=b, x=a) ! the same as multiply(a, b) +z = multiply(y=x, x=y) ! the same as multiply(y, x) diff --git a/Task/Function-definition/Fortran/function-definition-8.f b/Task/Function-definition/Fortran/function-definition-8.f new file mode 100644 index 0000000000..95fcb20391 --- /dev/null +++ b/Task/Function-definition/Fortran/function-definition-8.f @@ -0,0 +1,8 @@ +module elemFunc +contains + elemental function multiply(x, y) result(z) + real, intent(in) :: x, y + real :: z + z = x * y + end function multiply +end module elemFunc diff --git a/Task/Function-definition/Neko/function-definition.neko b/Task/Function-definition/Neko/function-definition.neko index d91f8af0b8..3180a1395d 100644 --- a/Task/Function-definition/Neko/function-definition.neko +++ b/Task/Function-definition/Neko/function-definition.neko @@ -1,12 +1,5 @@ -// a function definition can be written either as var multiply = function(a, b) { a * b } -// or -function multiply(a, b) { - a * b -} - -// and calling a function -$print(multiply(2,3)); +$print(multiply(2, 3)) diff --git a/Task/Function-definition/Rust/function-definition.rust b/Task/Function-definition/Rust/function-definition.rust new file mode 100644 index 0000000000..6a4ea33cfb --- /dev/null +++ b/Task/Function-definition/Rust/function-definition.rust @@ -0,0 +1,3 @@ +fn multiply(a: i32, b: i32) -> i32 { + a * b +} diff --git a/Task/Function-definition/Visual-Basic/function-definition.vb b/Task/Function-definition/Visual-Basic/function-definition.vb new file mode 100644 index 0000000000..109db99b9a --- /dev/null +++ b/Task/Function-definition/Visual-Basic/function-definition.vb @@ -0,0 +1,3 @@ +Function multiply(a As Integer, b As Integer) As Integer + multiply = a * b +End Function diff --git a/Task/Function-prototype/Lua/function-prototype.lua b/Task/Function-prototype/Lua/function-prototype.lua new file mode 100644 index 0000000000..e8e1277cfc --- /dev/null +++ b/Task/Function-prototype/Lua/function-prototype.lua @@ -0,0 +1,15 @@ +function Func() -- Does not require arguments + return 1 +end + +function Func(a,b) -- Requires arguments + return a + b +end + +function Func(a,b) -- Arguments are optional + return a or 4 + b or 2 +end + +function Func(a,...) -- One argument followed by varargs + return a,{...} -- Returns both arguments, varargs as table +end diff --git a/Task/GUI-component-interaction/AutoHotkey/gui-component-interaction.ahk b/Task/GUI-component-interaction/AutoHotkey/gui-component-interaction.ahk index 2e23545235..fd7492c302 100644 --- a/Task/GUI-component-interaction/AutoHotkey/gui-component-interaction.ahk +++ b/Task/GUI-component-interaction/AutoHotkey/gui-component-interaction.ahk @@ -1,10 +1,9 @@ -GUI, add, Edit,Number w50 vUserInput, 0 ; Number Specifies Numbers-only, but other characters can still be pasted in, +GUI, add, Edit,Number w50 vUserInput gMakeSure, 0 ; Number Specifies Numbers-only, but other characters can still be pasted in, ; Making our own check necessary. (MakeSure) GUI, add, Button, gIncrement, Increment ; Instead of an increment button, the UpDown control could be used, but this was not specified. GUI, add, Button, gRando, Random Gui, Show, W200 y200, Title ; Shows the GUI with a width and height of 200px -SetTimer, MakeSure, 1000 ; Runs MakeSure every second return ; End Auto-Execute Section diff --git a/Task/GUI-component-interaction/C++/gui-component-interaction-4.cpp b/Task/GUI-component-interaction/C++/gui-component-interaction-4.cpp new file mode 100644 index 0000000000..78952d67e3 --- /dev/null +++ b/Task/GUI-component-interaction/C++/gui-component-interaction-4.cpp @@ -0,0 +1,46 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) { + qsrand(QTime::currentTime().msec()); + + QApplication app(argc, argv); + + auto *edit = new QLineEdit("0"); + edit->setValidator(new QIntValidator()); + + auto *incButton = new QPushButton("&Increment"); + QObject::connect(incButton, &QPushButton::clicked, + [edit]() { edit->setText( QString::number(edit->text().toInt() + 1)); } ); + + auto *rndButton = new QPushButton("&Random"); + QObject::connect(rndButton, &QPushButton::clicked, + [edit]() { + auto result = QMessageBox( + QMessageBox::Warning, + "Random", + "Overwrite current value with a random number ?", + QMessageBox::Ok | QMessageBox::Cancel + ).exec(); + + if (result == QMessageBox::Ok) + edit->setText( QString::number(qrand())); + } ); + + auto *vbox = new QVBoxLayout; + vbox->addWidget(edit); + vbox->addWidget(incButton); + vbox->addWidget(rndButton); + + QWidget mainWindow; + mainWindow.setLayout(vbox); + mainWindow.show(); + + return app.exec(); +} diff --git a/Task/GUI-component-interaction/Common-Lisp/gui-component-interaction.lisp b/Task/GUI-component-interaction/Common-Lisp/gui-component-interaction.lisp new file mode 100644 index 0000000000..0c8f01cb9c --- /dev/null +++ b/Task/GUI-component-interaction/Common-Lisp/gui-component-interaction.lisp @@ -0,0 +1,39 @@ +;; Using the LTK library... + +(defun gui-test () + "the main window for the input test" + (ltk:with-ltk () + (ltk:wm-title ltk:*tk* "GUI Test") + (ltk:bind ltk:*tk* "" (lambda (evt) + (declare (ignore evt)) + (setf ltk:*exit-mainloop* t))) + (let* (;; Initializing random generator + (*random-state* (make-random-state t)) + ;; Creating widgets + (the-input (make-instance 'ltk:entry + :text "0" + :validate :key)) + (f (make-instance 'ltk:frame)) + (btn1 (make-instance 'ltk:button :text "random" :master f)) + (btn2 (make-instance 'ltk:button :text "increment" :master f))) + ;; Associating actions with widgets + (ltk:bind btn1 "" + (lambda (evt) + (declare (ignore evt)) + (when (ltk:ask-yesno "Really reset to random?" :title "Question") + (setf (ltk:text the-input) (write-to-string (random 10000)))))) + (ltk:bind btn2 "" + (lambda (evt) + (declare (ignore evt)) + (setf (ltk:text the-input) + (write-to-string (1+ (parse-integer (ltk:text the-input))))))) + (ltk:format-wish "~A configure -validatecommand {string is int %P}" + (ltk:widget-path the-input)) + (ltk:focus the-input) + ;; Placing widgets on the window + (ltk:pack the-input :side :top) + (ltk:pack f :side :bottom) + (ltk:pack btn1 :side :left) + (ltk:pack btn2 :side :right)))) + +(gui-test) diff --git a/Task/GUI-component-interaction/Elena/gui-component-interaction.elena b/Task/GUI-component-interaction/Elena/gui-component-interaction.elena new file mode 100644 index 0000000000..851be83677 --- /dev/null +++ b/Task/GUI-component-interaction/Elena/gui-component-interaction.elena @@ -0,0 +1,70 @@ +#import system. +#import forms. +#import extensions. + +#class Window + +{ + #field form. + #field btmIncrement. + #field btmRandom. + #field txtNumber. + + #constructor new + [ + form := SDIDialog new. + btmIncrement := Button new. + btmRandom := Button new. + txtNumber := Edit new. + + form controls + += btmIncrement + += btmRandom + += txtNumber. + + form set &caption:"Rosseta Code". + form set &x:100 &y:100. + form set &width:160 &height:120. + + txtNumber set &x:7 &y:7. + txtNumber set &width:140 &height:25. + txtNumber set &caption:"0". + + btmIncrement set &x:7 &y:35. + btmIncrement set &width:140 &height:25. + btmIncrement set &caption:"Increment". + btmIncrement set &onClick:args + + [ $self $onButtonIncrementClick. ]. + + btmRandom set &x:7 &y:65. + btmRandom set &width:140 &height:25. + btmRandom set &caption:"Random". + btmRandom set &onClick:args + + [ $self $onButtonRandomClick. ]. + ] + + #method $onButtonIncrementClick + [ + #var number := txtNumber value toInt. + + number := number + 1. + $self $changeTextBoxValue:number. + ] + + #method $onButtonRandomClick + [ + (messageDialog open &caption:"Inf" &question:"Really reset to random value?")? + [ + $self $changeTextBoxValue:(randomGenerator eval:99999999). + ]. + ] + + #method $changeTextBoxValue : number + [ + txtNumber set &caption:(number literal). + ] + + #method => form. +} diff --git a/Task/GUI-component-interaction/Perl-6/gui-component-interaction.pl6 b/Task/GUI-component-interaction/Perl-6/gui-component-interaction.pl6 new file mode 100644 index 0000000000..0f4d1daaf8 --- /dev/null +++ b/Task/GUI-component-interaction/Perl-6/gui-component-interaction.pl6 @@ -0,0 +1,33 @@ +use GTK::Simple; + +my GTK::Simple::App $app .= new(title => 'GUI component interaction'); + +$app.set_content( + my $box = GTK::Simple::VBox.new( + my $value = GTK::Simple::Entry.new(text => '0'), + my $increment = GTK::Simple::Button.new(label => 'Increment'), + my $random = GTK::Simple::Button.new(label => 'Random'), + ) +); + +$app.size_request(400, 100); +$app.border_width = 20; +$box.spacing = 10; + +$value.changed.tap: { + ($value.text ||= '0') ~~ s:g/<-[0..9]>//; +} + +$increment.clicked.tap: { + $value.text += 1; +} + +$random.clicked.tap: { + # Dirty hack to work around the fact that GTK::Simple doesn't provide + # access to GTK message dialogs yet :P + if run «zenity --question --text "Reset to random value?"» { + $value.text = (^100).pick; + } +} + +$app.run; diff --git a/Task/GUI-enabling-disabling-of-controls/AutoHotkey/gui-enabling-disabling-of-controls.ahk b/Task/GUI-enabling-disabling-of-controls/AutoHotkey/gui-enabling-disabling-of-controls.ahk index 2a4e738899..b350354d95 100644 --- a/Task/GUI-enabling-disabling-of-controls/AutoHotkey/gui-enabling-disabling-of-controls.ahk +++ b/Task/GUI-enabling-disabling-of-controls/AutoHotkey/gui-enabling-disabling-of-controls.ahk @@ -1,8 +1,8 @@ -GUI, Add, Edit, w150 number vValue, 0 ; Number specifies a numbers-only edit field. +GUI, Add, Edit, w150 number vValue gEnableDisable, 0 ; Number specifies a numbers-only edit field. g specifies a subroutine to run when the value of control changes. GUI, Add, button,, Increment GUI, Add, button, xp+70 yp, Decrement ; xp+70 and yp are merely positioning options GUI, Show, w200 y200, Title ; Shows the GUI. Add your own title if you wish -SetTimer, EnableDisable, 100 ; Sets EnableDisable to run 10 times per second (100ms) +;No timer is needed return ; ----------End Auto-Execute Section---------- ButtonIncrement: diff --git a/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 b/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 index 03aca62999..2396296933 100644 --- a/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 +++ b/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 @@ -1,17 +1,18 @@ use GTK::Simple; -my GTK::Simple::App $app .= new( title => 'Controls Enable \ Disable' ); - -$app.border_width = 20; +my GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' ); $app.set_content( - GTK::Simple::HBox.new( + my $box = GTK::Simple::HBox.new( my $inc = GTK::Simple::Button.new( label => ' + ' ), my $value = GTK::Simple::Entry.new, my $dec = GTK::Simple::Button.new( label => ' - ' ) ) ); +$app.border_width = 10; +$box.spacing = 10; + $value.changed.tap: { $value.text.=subst(/\D/, ''); $inc.sensitive = $value.text < 10; diff --git a/Task/Galton-box-animation/00META.yaml b/Task/Galton-box-animation/00META.yaml index 182e87560a..4cf3537d10 100644 --- a/Task/Galton-box-animation/00META.yaml +++ b/Task/Galton-box-animation/00META.yaml @@ -1,5 +1,4 @@ --- category: -- Animation - Randomness -note: Galton box animation +note: Animation diff --git a/Task/Galton-box-animation/C++/galton-box-animation.cpp b/Task/Galton-box-animation/C++/galton-box-animation.cpp new file mode 100644 index 0000000000..9c8027c635 --- /dev/null +++ b/Task/Galton-box-animation/C++/galton-box-animation.cpp @@ -0,0 +1,218 @@ +#include "stdafx.h" +#include +#include + +const int BMP_WID = 410, BMP_HEI = 230, MAX_BALLS = 120; + +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(); + } + 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 point { +public: + int x; float y; + void set( int a, float b ) { x = a; y = b; } +}; +typedef struct { + point position, offset; + bool alive, start; +}ball; +class galton { +public : + galton() { + bmp.create( BMP_WID, BMP_HEI ); + initialize(); + } + void setHWND( HWND hwnd ) { _hwnd = hwnd; } + void simulate() { + draw(); update(); Sleep( 1 ); + } +private: + void draw() { + bmp.clear(); + bmp.setPenColor( RGB( 0, 255, 0 ) ); + bmp.setBrushColor( RGB( 0, 255, 0 ) ); + int xx, yy; + for( int y = 3; y < 14; y++ ) { + yy = 10 * y; + for( int x = 0; x < 41; x++ ) { + xx = 10 * x; + if( pins[y][x] ) + Rectangle( bmp.getDC(), xx - 3, yy - 3, xx + 3, yy + 3 ); + } + } + bmp.setPenColor( RGB( 255, 0, 0 ) ); + bmp.setBrushColor( RGB( 255, 0, 0 ) ); + ball* b; + for( int x = 0; x < MAX_BALLS; x++ ) { + b = &balls[x]; + if( b->alive ) + Rectangle( bmp.getDC(), static_cast( b->position.x - 3 ), static_cast( b->position.y - 3 ), + static_cast( b->position.x + 3 ), static_cast( b->position.y + 3 ) ); + } + for( int x = 0; x < 70; x++ ) { + if( cols[x] > 0 ) { + xx = 10 * x; + Rectangle( bmp.getDC(), xx - 3, 160, xx + 3, 160 + cols[x] ); + } + } + HDC dc = GetDC( _hwnd ); + BitBlt( dc, 0, 0, BMP_WID, BMP_HEI, bmp.getDC(), 0, 0, SRCCOPY ); + ReleaseDC( _hwnd, dc ); + } + void update() { + ball* b; + for( int x = 0; x < MAX_BALLS; x++ ) { + b = &balls[x]; + if( b->alive ) { + b->position.x += b->offset.x; b->position.y += b->offset.y; + if( x < MAX_BALLS - 1 && !b->start && b->position.y > 50.0f ) { + b->start = true; + balls[x + 1].alive = true; + } + int c = ( int )b->position.x, d = ( int )b->position.y + 6; + if( d > 10 || d < 41 ) { + if( pins[d / 10][c / 10] ) { + if( rand() % 30 < 15 ) b->position.x -= 10; + else b->position.x += 10; + } + } + if( b->position.y > 160 ) { + b->alive = false; + cols[c / 10] += 1; + } + } + } + } + void initialize() { + for( int x = 0; x < MAX_BALLS; x++ ) { + balls[x].position.set( 200, -10 ); + balls[x].offset.set( 0, 0.5f ); + balls[x].alive = balls[x].start = false; + } + balls[0].alive = true; + for( int x = 0; x < 70; x++ ) + cols[x] = 0; + for( int y = 0; y < 70; y++ ) + for( int x = 0; x < 41; x++ ) + pins[x][y] = false; + int p; + for( int y = 0; y < 11; y++ ) { + p = ( 41 / 2 ) - y; + for( int z = 0; z < y + 1; z++ ) { + pins[3 + y][p] = true; + p += 2; + } + } + } + myBitmap bmp; + HWND _hwnd; + bool pins[70][40]; + ball balls[MAX_BALLS]; + int cols[70]; +}; +class wnd { +public: + int wnd::Run( HINSTANCE hInst ) { + _hInst = hInst; + _hwnd = InitAll(); + _gtn.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 ); + } else _gtn.simulate(); + } + return UnregisterClass( "_GALTON_", _hInst ); + } +private: + static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { + switch( msg ) { + case WM_DESTROY: PostQuitMessage( 0 ); break; + default: + return static_cast( 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 = "_GALTON_"; + RegisterClassEx( &wcex ); + RECT rc; + SetRect( &rc, 0, 0, BMP_WID, BMP_HEI ); + AdjustWindowRect( &rc, WS_CAPTION, FALSE ); + return CreateWindow( "_GALTON_", ".: Galton Box -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, _hInst, NULL ); + } + HINSTANCE _hInst; + HWND _hwnd; + galton _gtn; +}; +int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow ) { + srand( GetTickCount() ); + wnd myWnd; + return myWnd.Run( hInstance ); +} diff --git a/Task/Galton-box-animation/Perl-6/galton-box-animation.pl6 b/Task/Galton-box-animation/Perl-6/galton-box-animation.pl6 index 2d559df092..817a7cf205 100644 --- a/Task/Galton-box-animation/Perl-6/galton-box-animation.pl6 +++ b/Task/Galton-box-animation/Perl-6/galton-box-animation.pl6 @@ -10,18 +10,18 @@ sub display-board(@positions, @stats is copy, $halfstep) { # precompute a board my @tmpl; sub out(*@stuff) { - @tmpl.push: @stuff>>.ords.item; + @tmpl.push: $[@stuff.join>>.ords.flat]; } # three lines of space above - for (1..3) { + for 1..3 { out " ", " " x (2 * $row-count); } # $row-count lines of pegs - for ($row-count...1) Z (1...$row-count) -> $spaces, $pegs { + for flat ($row-count...1) Z (1...$row-count) -> $spaces, $pegs { out " ", " " x $spaces, ($peg xx $pegs).join(" "), " " x $spaces; } # four lines of space below - for (1..4) { + for 1..4 { out " ", " " x (2 * $row-count); } @tmpl diff --git a/Task/Gamma-function/Elixir/gamma-function.elixir b/Task/Gamma-function/Elixir/gamma-function.elixir new file mode 100644 index 0000000000..38d9561db6 --- /dev/null +++ b/Task/Gamma-function/Elixir/gamma-function.elixir @@ -0,0 +1,21 @@ +defmodule Gamma do + @a [ 1.00000_00000_00000_00000, 0.57721_56649_01532_86061, -0.65587_80715_20253_88108, + -0.04200_26350_34095_23553, 0.16653_86113_82291_48950, -0.04219_77345_55544_33675, + -0.00962_19715_27876_97356, 0.00721_89432_46663_09954, -0.00116_51675_91859_06511, + -0.00021_52416_74114_95097, 0.00012_80502_82388_11619, -0.00002_01348_54780_78824, + -0.00000_12504_93482_14267, 0.00000_11330_27231_98170, -0.00000_02056_33841_69776, + 0.00000_00061_16095_10448, 0.00000_00050_02007_64447, -0.00000_00011_81274_57049, + 0.00000_00001_04342_67117, 0.00000_00000_07782_26344, -0.00000_00000_03696_80562, + 0.00000_00000_00510_03703, -0.00000_00000_00020_58326, -0.00000_00000_00005_34812, + 0.00000_00000_00001_22678, -0.00000_00000_00000_11813, 0.00000_00000_00000_00119, + 0.00000_00000_00000_00141, -0.00000_00000_00000_00023, 0.00000_00000_00000_00002 ] + |> Enum.reverse + def taylor(x) do + y = x - 1 + 1 / Enum.reduce(@a, 0, fn a,sum -> sum * y + a end) + end +end + +Enum.each(Enum.map(1..10, &(&1/3)), fn x -> + :io.format "~f ~18.15f~n", [x, Gamma.taylor(x)] +end) diff --git a/Task/Gamma-function/REXX/gamma-function.rexx b/Task/Gamma-function/REXX/gamma-function.rexx index d94e1abc60..6ee21bd1a3 100644 --- a/Task/Gamma-function/REXX/gamma-function.rexx +++ b/Task/Gamma-function/REXX/gamma-function.rexx @@ -1,68 +1,68 @@ -/*REXX pgm calculates GAMMA using Taylor series coefficients, ≈80 digits*/ - /*The GAMMA function symbol is the Greek capital letter: Γ */ -numeric digits 84 /*able to use extended precision.*/ -parse arg y z . /*allow specification of Γ arg.*/ - /*either show a range or a ··· */ - do j=word(y 1,1) to word(z y 9,1) /* ··· single gamma value(s). */ - say 'gamma('j") =" gamma(j) /*compute gamma of J and display.*/ +/*REXX pgm calculates GAMMA using Taylor series coefficients, ≈80 decimal digs*/ + /*The GAMMA function symbol is the Greek capital letter: Γ */ +numeric digits 90 /*be able to handle extended precision.*/ +parse arg y z . /*allow specification of gamma argument*/ + /* [↓] either show a range or a ··· */ + do j=word(y 1,1) to word(z y 9,1) /* ··· single gamma value(s). */ + say 'gamma('j") =" gamma(j) /*compute gamma of J and display value.*/ end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────GAMMA subroutine=──────────────────*/ +exit /*stick a fork in it, we're all done. */ +/*───────────────────────────────────GAMMA subroutine─────────────────────────────────*/ gamma: procedure; parse arg x; xm=x-1; sum=0 - /*coefficients thanks to: Arne Fransén and Staffan Wrigge.*/ - #.1 = 1 /* [↓] #.2 is the Euler-Mascheroni constant.*/ - #.2 = 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467 - #.3 = -0.65587807152025388107701951514539048127976638047858434729236244568387083835372210 - #.4 = -0.04200263503409523552900393487542981871139450040110609352206581297618009687597599 - #.5 = 0.16653861138229148950170079510210523571778150224717434057046890317899386605647425 - #.6 = -0.04219773455554433674820830128918739130165268418982248637691887327545901118558900 - #.7 = -0.00962197152787697356211492167234819897536294225211300210513886262731167351446074 - #.8 = 0.00721894324666309954239501034044657270990480088023831800109478117362259497415854 - #.9 = -0.00116516759185906511211397108401838866680933379538405744340750527562002584816653 -#.10 = -0.00021524167411495097281572996305364780647824192337833875035026748908563946371678 -#.11 = 0.00012805028238811618615319862632816432339489209969367721490054583804120355204347 -#.12 = -0.00002013485478078823865568939142102181838229483329797911526116267090822918618897 -#.13 = -0.00000125049348214267065734535947383309224232265562115395981534992315749121245561 -#.14 = 0.00000113302723198169588237412962033074494332400483862107565429550539546040842730 -#.15 = -0.00000020563384169776071034501541300205728365125790262933794534683172533245680371 -#.16 = 0.00000000611609510448141581786249868285534286727586571971232086732402927723507435 -#.17 = 0.00000000500200764446922293005566504805999130304461274249448171895337887737472132 -#.18 = -0.00000000118127457048702014458812656543650557773875950493258759096189263169643391 -#.19 = 0.00000000010434267116911005104915403323122501914007098231258121210871073927347588 -#.20 = 0.00000000000778226343990507125404993731136077722606808618139293881943550732692987 -#.21 = -0.00000000000369680561864220570818781587808576623657096345136099513648454655443000 -#.22 = 0.00000000000051003702874544759790154813228632318027268860697076321173501048565735 -#.23 = -0.00000000000002058326053566506783222429544855237419746091080810147188058196444349 -#.24 = -0.00000000000000534812253942301798237001731872793994898971547812068211168095493211 -#.25 = 0.00000000000000122677862823826079015889384662242242816545575045632136601135999606 -#.26 = -0.00000000000000011812593016974587695137645868422978312115572918048478798375081233 -#.27 = 0.00000000000000000118669225475160033257977724292867407108849407966482711074006109 -#.28 = 0.00000000000000000141238065531803178155580394756670903708635075033452562564122263 -#.29 = -0.00000000000000000022987456844353702065924785806336992602845059314190367014889830 -#.30 = 0.00000000000000000001714406321927337433383963370267257066812656062517433174649858 -#.31 = 0.00000000000000000000013373517304936931148647813951222680228750594717618947898583 -#.32 = -0.00000000000000000000020542335517666727893250253513557337960820379352387364127301 -#.33 = 0.00000000000000000000002736030048607999844831509904330982014865311695836363370165 -#.34 = -0.00000000000000000000000173235644591051663905742845156477979906974910879499841377 -#.35 = -0.00000000000000000000000002360619024499287287343450735427531007926413552145370486 -#.36 = 0.00000000000000000000000001864982941717294430718413161878666898945868429073668232 -#.37 = -0.00000000000000000000000000221809562420719720439971691362686037973177950067567580 -#.38 = 0.00000000000000000000000000012977819749479936688244144863305941656194998646391332 -#.39 = 0.00000000000000000000000000000118069747496652840622274541550997151855968463784158 -#.40 = -0.00000000000000000000000000000112458434927708809029365467426143951211941179558301 -#.41 = 0.00000000000000000000000000000012770851751408662039902066777511246477487720656005 -#.42 = -0.00000000000000000000000000000000739145116961514082346128933010855282371056899245 -#.43 = 0.00000000000000000000000000000000001134750257554215760954165259469306393008612196 -#.44 = 0.00000000000000000000000000000000004639134641058722029944804907952228463057968680 -#.45 = -0.00000000000000000000000000000000000534733681843919887507741819670989332090488591 -#.46 = 0.00000000000000000000000000000000000032079959236133526228612372790827943910901464 -#.47 = -0.00000000000000000000000000000000000000444582973655075688210159035212464363740144 -#.48 = -0.00000000000000000000000000000000000000131117451888198871290105849438992219023663 -#.49 = 0.00000000000000000000000000000000000000016470333525438138868182593279063941453996 -#.50 = -0.00000000000000000000000000000000000000001056233178503581218600561071538285049997 -#.51 = 0.00000000000000000000000000000000000000000026784429826430494783549630718908519485 -#.52 = 0.00000000000000000000000000000000000000000002424715494851782689673032938370921241 - do j=52 by -1 to 1 - sum = sum * xm + #.j - end /*j*/ + /*coefficients thanks to: Arne Fransén and Staffan Wrigge.*/ + #.1= 1 /* [↓] #.2 is the Euler-Mascheroni constant. */ + #.2= 0.57721566490153286060651209008240243104215933593992359880576723488486772677766467 + #.3=-0.65587807152025388107701951514539048127976638047858434729236244568387083835372210 + #.4=-0.04200263503409523552900393487542981871139450040110609352206581297618009687597599 + #.5= 0.16653861138229148950170079510210523571778150224717434057046890317899386605647425 + #.6=-0.04219773455554433674820830128918739130165268418982248637691887327545901118558900 + #.7=-0.00962197152787697356211492167234819897536294225211300210513886262731167351446074 + #.8= 0.00721894324666309954239501034044657270990480088023831800109478117362259497415854 + #.9=-0.00116516759185906511211397108401838866680933379538405744340750527562002584816653 +#.10=-0.00021524167411495097281572996305364780647824192337833875035026748908563946371678 +#.11= 0.00012805028238811618615319862632816432339489209969367721490054583804120355204347 +#.12=-0.00002013485478078823865568939142102181838229483329797911526116267090822918618897 +#.13=-0.00000125049348214267065734535947383309224232265562115395981534992315749121245561 +#.14= 0.00000113302723198169588237412962033074494332400483862107565429550539546040842730 +#.15=-0.00000020563384169776071034501541300205728365125790262933794534683172533245680371 +#.16= 0.00000000611609510448141581786249868285534286727586571971232086732402927723507435 +#.17= 0.00000000500200764446922293005566504805999130304461274249448171895337887737472132 +#.18=-0.00000000118127457048702014458812656543650557773875950493258759096189263169643391 +#.19= 0.00000000010434267116911005104915403323122501914007098231258121210871073927347588 +#.20= 0.00000000000778226343990507125404993731136077722606808618139293881943550732692987 +#.21=-0.00000000000369680561864220570818781587808576623657096345136099513648454655443000 +#.22= 0.00000000000051003702874544759790154813228632318027268860697076321173501048565735 +#.23=-0.00000000000002058326053566506783222429544855237419746091080810147188058196444349 +#.24=-0.00000000000000534812253942301798237001731872793994898971547812068211168095493211 +#.25= 0.00000000000000122677862823826079015889384662242242816545575045632136601135999606 +#.26=-0.00000000000000011812593016974587695137645868422978312115572918048478798375081233 +#.27= 0.00000000000000000118669225475160033257977724292867407108849407966482711074006109 +#.28= 0.00000000000000000141238065531803178155580394756670903708635075033452562564122263 +#.29=-0.00000000000000000022987456844353702065924785806336992602845059314190367014889830 +#.30= 0.00000000000000000001714406321927337433383963370267257066812656062517433174649858 +#.31= 0.00000000000000000000013373517304936931148647813951222680228750594717618947898583 +#.32=-0.00000000000000000000020542335517666727893250253513557337960820379352387364127301 +#.33= 0.00000000000000000000002736030048607999844831509904330982014865311695836363370165 +#.34=-0.00000000000000000000000173235644591051663905742845156477979906974910879499841377 +#.35=-0.00000000000000000000000002360619024499287287343450735427531007926413552145370486 +#.36= 0.00000000000000000000000001864982941717294430718413161878666898945868429073668232 +#.37=-0.00000000000000000000000000221809562420719720439971691362686037973177950067567580 +#.38= 0.00000000000000000000000000012977819749479936688244144863305941656194998646391332 +#.39= 0.00000000000000000000000000000118069747496652840622274541550997151855968463784158 +#.40=-0.00000000000000000000000000000112458434927708809029365467426143951211941179558301 +#.41= 0.00000000000000000000000000000012770851751408662039902066777511246477487720656005 +#.42=-0.00000000000000000000000000000000739145116961514082346128933010855282371056899245 +#.43= 0.00000000000000000000000000000000001134750257554215760954165259469306393008612196 +#.44= 0.00000000000000000000000000000000004639134641058722029944804907952228463057968680 +#.45=-0.00000000000000000000000000000000000534733681843919887507741819670989332090488591 +#.46= 0.00000000000000000000000000000000000032079959236133526228612372790827943910901464 +#.47=-0.00000000000000000000000000000000000000444582973655075688210159035212464363740144 +#.48=-0.00000000000000000000000000000000000000131117451888198871290105849438992219023663 +#.49= 0.00000000000000000000000000000000000000016470333525438138868182593279063941453996 +#.50=-0.00000000000000000000000000000000000000001056233178503581218600561071538285049997 +#.51= 0.00000000000000000000000000000000000000000026784429826430494783549630718908519485 +#.52= 0.00000000000000000000000000000000000000000002424715494851782689673032938370921241 +#=52; do k=# by -1 for # + sum=sum*xm + #.k + end /*k*/ return 1/sum diff --git a/Task/Gaussian-elimination/Delphi/gaussian-elimination.delphi b/Task/Gaussian-elimination/Delphi/gaussian-elimination.delphi new file mode 100644 index 0000000000..73cd57a2f9 --- /dev/null +++ b/Task/Gaussian-elimination/Delphi/gaussian-elimination.delphi @@ -0,0 +1,144 @@ +program GuassianElimination; + +// Modified from: +// R. Sureshkumar (10 January 1997) +// Gregory J. McRae (22 October 1997) +// http://web.mit.edu/10.001/Web/Course_Notes/Gauss_Pivoting.c + +{$APPTYPE CONSOLE} + +{$R *.res} + +uses + System.SysUtils; + +type + TMatrix = class + private + _r, _c : integer; + data : array of TDoubleArray; + function getValue(rIndex, cIndex : integer): double; + procedure setValue(rIndex, cIndex : integer; value: double); + public + constructor Create (r, c : integer); + destructor Destroy; override; + + property r : integer read _r; + property c : integer read _c; + property value[rIndex, cIndex: integer]: double read getValue write setValue; default; + end; + + +constructor TMatrix.Create (r, c : integer); +begin + inherited Create; + self.r := r; self.c := c; + setLength (data, r, c); +end; + +destructor TMatrix.Destroy; +begin + data := nil; + inherited; +end; + +function TMatrix.getValue(rIndex, cIndex: Integer): double; +begin + Result := data[rIndex-1, cIndex-1]; // 1-based array +end; + +procedure TMatrix.setValue(rIndex, cIndex : integer; value: double); +begin + data[rIndex-1, cIndex-1] := value; // 1-based array +end; + +// Solve A x = b +procedure gauss (A, b, x : TMatrix); +var rowx : integer; + i, j, k, n, m : integer; + amax, xfac, temp, temp1 : double; +begin + rowx := 0; // Keep count of the row interchanges + n := A.r; + for k := 1 to n - 1 do + begin + amax := abs (A[k,k]); + m := k; + // Find the row with largest pivot + for i := k + 1 to n do + begin + xfac := abs (A[i,k]); + if xfac > amax then + begin + amax := xfac; + m := i; + end; + end; + + if m <> k then + begin // Row interchanges + rowx := rowx+1; + temp1 := b[k,1]; + b[k,1] := b[m,1]; + b[m,1] := temp1; + for j := k to n do + begin + temp := a[k,j]; + a[k,j] := a[m,j]; + a[m,j] := temp; + end; + end; + + for i := k+1 to n do + begin + xfac := a[i, k]/a[k, k]; + for j := k+1 to n do + a[i,j] := a[i,j]-xfac*a[k,j]; + b[i,1] := b[i,1] - xfac*b[k,1] + end; + end; + + // Back substitution + for j := 1 to n do + begin + k := n-j + 1; + x[k,1] := b[k,1]; + for i := k+1 to n do + begin + x[k,1] := x[k,1] - a[k,i]*x[i,1]; + end; + x[k,1] := x[k,1]/a[k,k]; + end; +end; + + +var A, b, x : TMatrix; + +begin + try + // Could have been done with simple arrays rather than a specific TMatrix class + A := TMatrix.Create (4,4); + // Note ideal but use TMatrix to define the vectors as well + b := TMatrix.Create (4,1); + x := TMatrix.Create (4,1); + + A[1,1] := 2; A[1,2] := 1; A[1,3] := 0; A[1,4] := 0; + A[2,1] := 1; A[2,2] := 1; A[2,3] := 1; A[2,4] := 0; + A[3,1] := 0; A[3,2] := 1; A[3,3] := 2; A[3,4] := 1; + A[4,1] := 0; A[3,2] := 0; A[4,3] := 1; A[4,4] := 2; + + b[1,1] := 2; b[2,1] := 1; b[3,1] := 4; b[4,1] := 8; + + gauss (A, b, x); + + writeln (x[1,1]:5:2); + writeln (x[2,1]:5:2); + writeln (x[3,1]:5:2); + writeln (x[4,1]:5:2); + + readln; + except + on E: Exception do + Writeln(E.ClassName, ': ', E.Message); + end; +end. diff --git a/Task/Gaussian-elimination/JavaScript/gaussian-elimination.js b/Task/Gaussian-elimination/JavaScript/gaussian-elimination.js new file mode 100644 index 0000000000..14b3936daf --- /dev/null +++ b/Task/Gaussian-elimination/JavaScript/gaussian-elimination.js @@ -0,0 +1,119 @@ +// Lower Upper Solver +function lusolve(A, b, update) { + var lu = ludcmp(A, update) + if (lu === undefined) return // Singular Matrix! + return lubksb(lu, b, update) +} + +// Lower Upper Decomposition +function ludcmp(A, update) { + // A is a matrix that we want to decompose into Lower and Upper matrices. + var d = true + var n = A.length + var idx = new Array(n) // Output vector with row permutations from partial pivoting + var vv = new Array(n) // Scaling information + + for (var i=0; i max) max = temp + } + if (max == 0) return // Singular Matrix! + vv[i] = 1 / max // Scaling + } + + if (!update) { // make a copy of A + var Acpy = new Array(n) + for (var i=0; i= max) { + max = temp + jmax = j + } + } + if (i <= jmax) { + for (var j=0; j -1) + for (var j=ii; j=0; i--) { + var sum = b[i] + for (var j=i+1; j48*,:4%2*1#v+#02#\3#g<< +v"B"*2%4:/4p\0p4/:6%0:0g>68*`#^_\:| +v"RKRNN"p11/6$p0\ "Q" \< +>"NRNKRRNNKRNRKNRRNKNR"v +v"NRNKRNRKNRNRKRNRNNKR"< +>"RKRNN"11g:!#v_\$\$\$\v +v _v#!`*86:g0:<^!:-1$\$< +>$\>,1+ :7`#@_^> v960v < 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 index 33fcdfa69f..67bf5ae0e6 100644 --- a/Task/Generate-Chess960-starting-position/C++/generate-chess960-starting-position.cpp +++ b/Task/Generate-Chess960-starting-position/C++/generate-chess960-starting-position.cpp @@ -2,68 +2,56 @@ #include #include using namespace std; -class chess960 + +namespace { -public: - void generate( int c ) + void placeRandomly(char* p, char c) { - for( int x = 0; x < c; x++ ) - cout << startPos() << "\n"; + int loc = rand() % 8; + if (!p[loc]) + p[loc] = c; + else + placeRandomly(p, c); // try again + } + int placeFirst(char* p, char c, int loc = 0) + { + while (p[loc]) ++loc; + p[loc] = c; + return loc; } -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'; - } + // bishops on opposite color + p[2 * (rand() % 4)] = 'B'; + p[2 * (rand() % 4) + 1] = 'B'; - // rook king rook - q = false; - for( int x = 0; x < 3; x++ ) - { - int a = 0; - for( ; a < 8; a++ ) - if( !p[a] ) break; + // queen knight knight, anywhere + for (char c : "QNN") + placeRandomly(p, c); - if( !q ) - { p[a] = 'R'; q = true; } - else - { p[a] = 'K'; q = false; } - } + // rook king rook, in that order + placeFirst(p, 'R', placeFirst(p, 'K', placeFirst(p, 'R'))); - string s; - for( int x = 0; x < 8; x++ ) - s.append( 1, p[x] ); + return string(p, 8); + } +} // leave local - return s; +namespace chess960 +{ + void generate( int c ) + { + for( int x = 0; x < c; x++ ) + cout << startPos() << "\n"; } -}; +} int main( int argc, char* argv[] ) { srand( time( NULL ) ); - chess960 c; - c.generate( 10 ); + chess960::generate( 10 ); cout << "\n\n"; return system( "pause" ); } diff --git a/Task/Generate-Chess960-starting-position/Julia/generate-chess960-starting-position.julia b/Task/Generate-Chess960-starting-position/Julia/generate-chess960-starting-position.julia new file mode 100644 index 0000000000..10e6467e3f --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Julia/generate-chess960-starting-position.julia @@ -0,0 +1,30 @@ +# placeholder knights +rank1 = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘'] + +# function to check if a space is available +isfree(x::Int) = rank1[x] == '♘' + +# place king +king = rand(2:7) +rank1[king] = '♔' + +# place rooks +rook1 = rand(filter(isfree, 1:8)) +rank1[rook1] = '♖' + +if rook1 > king + rank1[rand(filter(x -> isfree(x) && x < king, 1:8))] = '♖' +else + rank1[rand(filter(x -> isfree(x) && x > king, 1:8))] = '♖' +end + +# place bishops +bishop1 = rand(filter(isfree, 1:8)) +rank1[bishop1] = '♗' +rank1[rand(filter(x -> isfree(x) && iseven(x) != iseven(bishop1), 1:8))] = '♗' + +# place queen +rank1[rand(filter(isfree, 1:8))] = '♕' + +# print first rank +println(join(rank1)) diff --git a/Task/Generate-Chess960-starting-position/Mathematica/generate-chess960-starting-position.math b/Task/Generate-Chess960-starting-position/Mathematica/generate-chess960-starting-position.math new file mode 100644 index 0000000000..3cde47f0da --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Mathematica/generate-chess960-starting-position.math @@ -0,0 +1,9 @@ +Print[StringJoin[ + RandomChoice[ + Select[Union[ + Permutations[{"\[WhiteKing]", "\[WhiteQueen]", "\[WhiteRook]", + "\[WhiteRook]", "\[WhiteBishop]", "\[WhiteBishop]", + "\[WhiteKnight]", "\[WhiteKnight]"}]], + MatchQ[#, {___, "\[WhiteRook]", ___, "\[WhiteKing]", ___, + "\[WhiteRook]", ___}] && + OddQ[Subtract @@ Flatten[Position[#, "\[WhiteBishop]"]]] &]]]]; 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 index 3c4d7b2357..06ddbe1149 100644 --- 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 @@ -1,6 +1,7 @@ -constant chess960 = - map *.subst(:nth(2), /'♜'/, '♚'), - grep rx/ '♝' [..]* '♝' /, - < ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.pick(*).join xx *; +sub chess960 { + .subst(:nth(2), /'♜'/, '♚') given + first rx/ '♝' [..]* '♝' /, + < ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.pick(*).join xx *; +} -.say for chess960[^10]; +say chess960; 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 index 4d3b72d527..9f4cc9f95f 100644 --- 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 @@ -1,26 +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.*/ +/*REXX program generates a random starting position for the Chess960 game. */ +parse arg seed . /*allow for (RANDOM BIF) repeatability.*/ +if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/ +@.=. /*define the first rank as being empty.*/ +r1=random(1,6) /*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*/ + 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*/ +@.r2='r' /*place the second rook on rank 1. */ +k=random(min(r1, r2)+1, max(r1, r2)-1) /*find a random position for the king. */ +@.k='K' /*place king between the two 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 /*is a 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.*/ + end /*forever*/ /* [↑] find a place for the 1st bishop*/ + end /* _ */ /* [↑] " " " " " 2nd " */ +@.b1='B' /*place the 1st bishop on rank 1. */ +@.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 be placed. */ + do i=1 for 8; _=_ || @.i; end /*construct the output: first rank only*/ +say translate(translate(_, 'q', .)) /*stick a fork in it, we're all 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 index 2353387a8f..51b215ea3d 100644 --- 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 @@ -1,38 +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 ══════════════════════════════════════════════════════════════*/ +/*REXX program generates all random starting positions for the Chess960 game. */ +parse arg seed . /*allow for (RANDOM BIF) repeatability.*/ +if seed\=='' then call random ,,seed /*if SEED was specified, use the seed.*/ +x.=0; #=0; rg='random generations: ' /*initialize game placeholder; # games.*/ + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +do t=1 /* [↓] display every 1,000 generations*/ /*▒*/ +if t//1000==0 then say right(t,9) rg # " unique starting positions." /*▒*/ +@.=. /*define the first rank as being empty.*/ /*▒*/ +r1=random(1,6) /*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. */ /*▒*/ +k=random(min(r1, r2)+1, max(r1, r2)-1) /*find a random position for the king. */ /*▒*/ +@.k='K' /*place king between the two 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 /*is a bad position?*/ /*▒*/ + leave _ /*found position for the 2 clergy*/ /*▒*/ + end /*forever*/ /* [↑] find a place for the 1st bishop*/ /*▒*/ + end /* _ */ /* [↑] " " " " " 2nd " */ /*▒*/ +@.b1='B' /*place the 1st bishop on rank 1. */ /*▒*/ +@.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 be placed. */ /*▒*/ + do i=1 for 8; _=_ || @.i; end /*construct the output: first rank only*/ /*▒*/ +upper _ /*uppercase all the chess pieces. */ /*▒*/ +if x._ then iterate /*This position found before? Skip it.*/ /*▒*/ +x._=1 /*define this position as being found. */ /*▒*/ +#=#+1 /*bump the # of 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.*/ + /*stick a fork in it, we're all done. */ /**/ diff --git a/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet.abap b/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet.abap new file mode 100644 index 0000000000..f6c07fa24a --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet.abap @@ -0,0 +1 @@ +DATA(alpha) = to_lower( sy-abcde ). diff --git a/Task/Generate-lower-case-ASCII-alphabet/AutoIt/generate-lower-case-ascii-alphabet.autoit b/Task/Generate-lower-case-ASCII-alphabet/AutoIt/generate-lower-case-ascii-alphabet.autoit new file mode 100644 index 0000000000..b9b3738870 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/AutoIt/generate-lower-case-ascii-alphabet.autoit @@ -0,0 +1,7 @@ +Func _a2z() + Local $a2z = "" + For $i = 97 To 122 + $a2z &= Chr($i) + Next + Return $a2z +EndFunc diff --git a/Task/Generate-lower-case-ASCII-alphabet/Befunge/generate-lower-case-ascii-alphabet.bf b/Task/Generate-lower-case-ASCII-alphabet/Befunge/generate-lower-case-ascii-alphabet.bf new file mode 100644 index 0000000000..235085a7ee --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Befunge/generate-lower-case-ascii-alphabet.bf @@ -0,0 +1,2 @@ +0"z":>"a"`#v_ >:#,_$@ + ^:- 1:< diff --git a/Task/Generate-lower-case-ASCII-alphabet/CoffeeScript/generate-lower-case-ascii-alphabet.coffee b/Task/Generate-lower-case-ASCII-alphabet/CoffeeScript/generate-lower-case-ascii-alphabet.coffee new file mode 100644 index 0000000000..9edcea2bed --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/CoffeeScript/generate-lower-case-ascii-alphabet.coffee @@ -0,0 +1 @@ +(String.fromCharCode(x) for x in [97..122]) diff --git a/Task/Generate-lower-case-ASCII-alphabet/Elixir/generate-lower-case-ascii-alphabet.elixir b/Task/Generate-lower-case-ASCII-alphabet/Elixir/generate-lower-case-ascii-alphabet.elixir new file mode 100644 index 0000000000..f3706c5824 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Elixir/generate-lower-case-ascii-alphabet.elixir @@ -0,0 +1,4 @@ +iex(1)> Enum.to_list(?a .. ?z) +'abcdefghijklmnopqrstuvwxyz' +iex(2)> Enum.to_list(?a .. ?z) |> List.to_string +"abcdefghijklmnopqrstuvwxyz" diff --git a/Task/Generate-lower-case-ASCII-alphabet/Erlang/generate-lower-case-ascii-alphabet.erl b/Task/Generate-lower-case-ASCII-alphabet/Erlang/generate-lower-case-ascii-alphabet.erl new file mode 100644 index 0000000000..087df9efaa --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Erlang/generate-lower-case-ascii-alphabet.erl @@ -0,0 +1 @@ +lists:seq($a,$z). diff --git a/Task/Generate-lower-case-ASCII-alphabet/Forth/generate-lower-case-ascii-alphabet-1.fth b/Task/Generate-lower-case-ASCII-alphabet/Forth/generate-lower-case-ascii-alphabet-1.fth new file mode 100644 index 0000000000..3ebdb9da9d --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Forth/generate-lower-case-ascii-alphabet-1.fth @@ -0,0 +1,24 @@ +\ generate a string filled with the lowercase ASCII alphabet +\ RAW Forth is quite low level. Strings are simply named memory spaces in Forth. +\ Typically they return an address on the Forth Stack (a pointer) with a count value in CHARs +\ These examples use a string with the first byte containing the length of the string + +\ We show 2 ways to load the ASCII values + +create lalpha 27 chars allot \ create a string for 26 letters and count byte + +: ]lalpha ( index -- addr ) \ word to index the string like an array + lalpha char+ + ; + +\ method 1: use a loop +: fillit ( -- ) + 26 0 + do + [char] a I + \ calc. the ASCII value + I ]lalpha c! \ store the char (c!) in the string at I + loop + 26 lalpha c! ; \ store the count byte at the head of the string + + +\ method 2: load with a string literal +: Loadit s" abcdefghijklmnopqrstuvwxyz" lalpha PLACE ; diff --git a/Task/Generate-lower-case-ASCII-alphabet/Forth/generate-lower-case-ascii-alphabet-2.fth b/Task/Generate-lower-case-ASCII-alphabet/Forth/generate-lower-case-ascii-alphabet-2.fth new file mode 100644 index 0000000000..3083e8d3e5 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Forth/generate-lower-case-ascii-alphabet-2.fth @@ -0,0 +1,9 @@ +fillit ok + +lalpha count type abcdefghijklmnopqrstuvwxyz ok + +loadit ok + +lalpha count type abcdefghijklmnopqrstuvwxyz ok + + ok diff --git a/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet-1.j b/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet-1.j new file mode 100644 index 0000000000..80e7814202 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet-1.j @@ -0,0 +1,3 @@ + thru=: <. + i.@(+*)@-~ + thru&.(a.&i.)/'az' +abcdefghijklmnopqrstuvwxyz diff --git a/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet-2.j b/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet-2.j new file mode 100644 index 0000000000..59acf63a84 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet-2.j @@ -0,0 +1,2 @@ + u:97+i.26 +abcdefghijklmnopqrstuvwxyz 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 deleted file mode 100644 index 3cda1ab708..0000000000 --- a/Task/Generate-lower-case-ASCII-alphabet/J/generate-lower-case-ascii-alphabet.j +++ /dev/null @@ -1,2 +0,0 @@ - ([+i.@-.@-)&.(a.&i.)/'az' -abcdefghijklmnopqrstuvwxyz diff --git a/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-1.js b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-1.js new file mode 100644 index 0000000000..036dd582eb --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-1.js @@ -0,0 +1,17 @@ +(function (cFrom, cTo) { + + function cRange(cFrom, cTo) { + var iStart = cFrom.charCodeAt(0); + + return Array.apply( + null, Array(cTo.charCodeAt(0) - iStart + 1) + ).map(function (_, i) { + + return String.fromCharCode(iStart + i); + + }); + } + + return cRange(cFrom, cTo); + +})('a', 'z'); diff --git a/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-2.js b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-2.js new file mode 100644 index 0000000000..adc34d7b32 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-2.js @@ -0,0 +1 @@ +["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/JavaScript/generate-lower-case-ascii-alphabet-3.js b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-3.js new file mode 100644 index 0000000000..16d6971aab --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-3.js @@ -0,0 +1,22 @@ +(function (lstRanges) { + + function cRange(cFrom, cTo) { + var iStart = cFrom.codePointAt(0); + + return Array.apply( + null, Array(cTo.codePointAt(0) - iStart + 1) + ).map(function (_, i) { + + return String.fromCodePoint(iStart + i); + + }); + } + + return lstRanges.map(function (lst) { + return cRange(lst[0], lst[1]); + }); + +})([ + ['a', 'z'], + ['🐐', '🐟'] +]); diff --git a/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-4.js b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-4.js new file mode 100644 index 0000000000..eceeb17152 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-4.js @@ -0,0 +1,2 @@ +[["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/JavaScript/generate-lower-case-ascii-alphabet.js b/Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-5.js similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet.js rename to Task/Generate-lower-case-ASCII-alphabet/JavaScript/generate-lower-case-ascii-alphabet-5.js 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-1.logo similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet.logo rename to Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet-1.logo diff --git a/Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet-2.logo b/Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet-2.logo new file mode 100644 index 0000000000..0551660d68 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Logo/generate-lower-case-ascii-alphabet-2.logo @@ -0,0 +1 @@ +show map "char apply "iseq map "ascii [a z] diff --git a/Task/Generate-lower-case-ASCII-alphabet/R/generate-lower-case-ascii-alphabet.r b/Task/Generate-lower-case-ASCII-alphabet/R/generate-lower-case-ascii-alphabet.r new file mode 100644 index 0000000000..9f4f99e7f3 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/R/generate-lower-case-ascii-alphabet.r @@ -0,0 +1,2 @@ +# From constants built into R: +letters diff --git a/Task/Generate-lower-case-ASCII-alphabet/Run-BASIC/generate-lower-case-ascii-alphabet.run b/Task/Generate-lower-case-ASCII-alphabet/Run-BASIC/generate-lower-case-ascii-alphabet.run new file mode 100644 index 0000000000..4f590de5f7 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Run-BASIC/generate-lower-case-ascii-alphabet.run @@ -0,0 +1,3 @@ +for i = asc("a") to asc("z") + print chr$(i); +next i diff --git a/Task/Generate-lower-case-ASCII-alphabet/Seed7/generate-lower-case-ascii-alphabet.seed7 b/Task/Generate-lower-case-ASCII-alphabet/Seed7/generate-lower-case-ascii-alphabet.seed7 new file mode 100644 index 0000000000..fd23406b3f --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Seed7/generate-lower-case-ascii-alphabet.seed7 @@ -0,0 +1,12 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var string: lower is ""; + var char: ch is ' '; + begin + for ch range 'a' to 'z' do + lower &:= ch; + end for; + writeln(lower); + end func; diff --git a/Task/Generate-lower-case-ASCII-alphabet/VBScript/generate-lower-case-ascii-alphabet.vb b/Task/Generate-lower-case-ASCII-alphabet/VBScript/generate-lower-case-ascii-alphabet.vb new file mode 100644 index 0000000000..1f99b8fd82 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/VBScript/generate-lower-case-ascii-alphabet.vb @@ -0,0 +1,9 @@ +Function ASCII_Sequence(range) + arr = Split(range,"..") + For i = Asc(arr(0)) To Asc(arr(1)) + ASCII_Sequence = ASCII_Sequence & Chr(i) & " " + Next +End Function + +WScript.StdOut.Write ASCII_Sequence(WScript.Arguments(0)) +WScript.StdOut.WriteLine diff --git a/Task/Generator-Exponential/Forth/generator-exponential.fth b/Task/Generator-Exponential/Forth/generator-exponential.fth new file mode 100644 index 0000000000..94bb9c9b14 --- /dev/null +++ b/Task/Generator-Exponential/Forth/generator-exponential.fth @@ -0,0 +1,46 @@ +\ genexp-rcode.fs Generator/Exponential for RosettaCode.org + +\ Generator/filter implementation using return stack as continuations stack +: ENTER ( cont.addr -- ;borrowed from M.L.Gasanenko papers) + >R +; +: | ( f -- ;true->go ahead, false->return into generator ) + IF EXIT THEN R> DROP +; +: GEN ( -- ;generate forever what is between 'GEN' and ';' ) + BEGIN R@ ENTER AGAIN +; +: STOP ( f -- ;return to caller of word that contain 'GEN' ) + IF R> DROP R> DROP R> DROP THEN +; + +\ Problem at hand +: square ( n -- n^2 ) dup * ; +: cube ( n -- n^3 ) dup square * ; + +\ Faster tests using info that tested numbers are monotonic growing + VARIABLE Sqroot \ last square root + VARIABLE Cbroot \ last cubic root +: square? ( u -- f ;test U for square number) + BEGIN + Sqroot @ square over < + WHILE + 1 Sqroot +! + REPEAT + Sqroot @ square = +; +: cube? ( u -- f ;test U for cubic number) + BEGIN + Cbroot @ cube over < + WHILE + 1 Cbroot +! + REPEAT + Cbroot @ cube = +; + VARIABLE Counter +: (go) ( u -- u' ) + GEN 1+ Counter @ 30 >= STOP + dup square? | dup cube? 0= | Counter @ 20 >= 1 Counter +! | dup . +; +:noname 0 Counter ! 1 Sqroot ! 1 Cbroot ! 0 (go) drop ; +execute cr bye diff --git a/Task/Generator-Exponential/Perl-6/generator-exponential.pl6 b/Task/Generator-Exponential/Perl-6/generator-exponential.pl6 index 8f34a133f1..ce861d3411 100644 --- a/Task/Generator-Exponential/Perl-6/generator-exponential.pl6 +++ b/Task/Generator-Exponential/Perl-6/generator-exponential.pl6 @@ -1,7 +1,7 @@ sub powers($m) { 0..* X** $m } -my @squares := powers(2); -my @cubes := powers(3); +my @squares = powers(2); +my @cubes = powers(3); sub infix: (@orig,@veto) { gather for @veto -> $veto { diff --git a/Task/Generator-Exponential/REXX/generator-exponential.rexx b/Task/Generator-Exponential/REXX/generator-exponential.rexx index 6c5e4c8a8e..149af9f91a 100644 --- a/Task/Generator-Exponential/REXX/generator-exponential.rexx +++ b/Task/Generator-Exponential/REXX/generator-exponential.rexx @@ -1,47 +1,40 @@ -/*REXX program to show how to use a generator (also known as iterators).*/ -numeric digits 10000 /*just in case we need big 'uns. */ -parse arg show; show = word(show 0, 1) /*show this many.*/ -@gen.= /*generators start from scratch. */ - do j=1 to show; call tell 'squares' ,gen_squares(j) ; end - do j=1 to show; call tell 'cubes' ,gen_cubes(j) ; end - do j=1 to show; call tell 'sq¬cubes',gen_sqNcubes(j) ; end - if show>0 then say 'dropping 1st ──► 20th values.' - do j=1 to 20; drop @gen.sqNcubes.j ; end - do j=20+1 for 10 ; call tell 'sq¬cubes',gen_sqNcubes(j) ; end -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────gen_powers iterator──────────────*/ -gen_powers: procedure expose @gen.; parse arg x,p; if x=='' then return -if @gen.powers.x.p=='' then @gen.powers.x.p=x**p; return @gen.powers.x.p -/*─────────────────────────────────────gen_squares iterator─────────────*/ -gen_squares: procedure expose @gen.; parse arg x; if x=='' then return -if @gen.squares.x=='' then do; call gen_powers x,2 - @gen.squares.x=@gen.powers.x.2 - end -return @gen.squares.x -/*─────────────────────────────────────gen_cubes iterator───────────────*/ -gen_cubes: procedure expose @gen.; parse arg x; if x=='' then return -if @gen.cubes.j=='' then do; call gen_powers x,3 - @gen.cubes.x=@gen.powers.x.3 - end -return @gen.cubes.x -/*─────────────────────────────────────gen_squares not cubes iterator───*/ -gen_sqNcubes: procedure expose @gen.; parse arg x; if x=='' then return -s=0 -if @gen.sqNcubes.x=='' then do j=1 to x - if @gen.sqNcubes\=='' then do; sq=sq+1 - iterate - end - do s=s+1 /*slow way to weed out cubes*/ - ?=gen_squares(s) - do c=1 until gen_cubes(c)>? - if gen_cubes(c)==? then iterate s - end /*c*/ - leave - end /*s*/ - @gen.sqNcubes.x=? - @gen.sqNcubes.x=@gen.squares.s - end /*j*/ -return @gen.sqNcubes.x -/*──────────────────────────────────TELL subroutine─────────────────────*/ -tell: if j==1 then say /* [↓] format args to be aligned.*/ - say right(arg(1),20) right(j,5) right(arg(2),20); return +/*REXX program demonstrates how to use a generator (also known as iterators).*/ +parse arg N .; if N=='' then N=20 /*N not specified? Then use default.*/ +@.= /* [↓] calculate squares,cubes,pureSq.*/ + do j=1 for N; call Gsquare j + call Gcube j + call GpureSquare j /*these are cube─free squares.*/ + end /*j*/ + + do k=1 for N; @.pureSquare.k=; end /*k*/ /*dropping 1st N values.*/ + +w=length(N+10); ps='pure square' /*width of the numbers. */ + + do m=N+1 for 10; say ps right(m, w)":" right(GpureSquare(m), 3*w) + end /*m*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +Gpower: procedure expose @.; parse arg x,p; q=@.pow.x.p + if q\=='' then return q; _=x**p + if pos(.,_)\==0 then do + parse var _ 'E' e; numeric digits e+5; _=x**p + end /* [↑] re─calculate with more digits.*/ + @.pow.x.p=_ + return _ +/*────────────────────────────────────────────────────────────────────────────*/ +Gsquare: procedure expose @.; parse arg x; q=@.square.x + if q=='' then @.square.x=Gpower(x,2) + return @.square.x +/*────────────────────────────────────────────────────────────────────────────*/ +Gcube: procedure expose @.; parse arg x; q=@.cube.x + if q=='' then @.cube.x=Gpower(x,3); _=@.cube.x; @.3pow._=1 + return @.cube.x +/*────────────────────────────────────────────────────────────────────────────*/ +GpureSquare: procedure expose @.; parse arg x; q=@.pureSquare.x + if q\=='' then return q + #=0 + do j=1 until #==x; ?=Gpower(j,2) /*search for pure square*/ + if @.3pow.?==1 then iterate /*is it a power of 3 ? */ + #=#+1; @.pureSquare.#=? /*assign next pureSquare*/ + end /*j*/ + return @.pureSquare.x diff --git a/Task/Generic-swap/00DESCRIPTION b/Task/Generic-swap/00DESCRIPTION index 12724a48e2..20bc477450 100644 --- a/Task/Generic-swap/00DESCRIPTION +++ b/Task/Generic-swap/00DESCRIPTION @@ -1,6 +1,8 @@ -The task is to write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. If your solution language is statically typed please describe the way your language provides genericity. +The task is to write a generic swap function or operator which exchanges the values of two variables (or, more generally, any two storage places that can be assigned), regardless of their types. +If your solution language is statically typed please describe the way your language provides genericity. -If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. +If variables are typed in the given language, it is permissible that the two variables be constrained to having a mutually compatible type, such that each is permitted to hold the value previously stored in the other without a type violation. +That is to say, solutions do not have to be capable of exchanging, say, a string and integer value, if the underlying storage locations are not attributed with types that permit such an exchange. Generic swap is a task which brings together a few separate issues in programming language semantics. diff --git a/Task/Generic-swap/C++/generic-swap-3.cpp b/Task/Generic-swap/C++/generic-swap-3.cpp new file mode 100644 index 0000000000..a6e2f962fc --- /dev/null +++ b/Task/Generic-swap/C++/generic-swap-3.cpp @@ -0,0 +1,6 @@ +template +void swap(T &lhs, T &rhs){ + T tmp = std::move(lhs); + lhs = std::move(rhs); + rhs = std::move(tmp); +} diff --git a/Task/Generic-swap/C/generic-swap-1.c b/Task/Generic-swap/C/generic-swap-1.c index b79e5e53c0..d37c95b48e 100644 --- a/Task/Generic-swap/C/generic-swap-1.c +++ b/Task/Generic-swap/C/generic-swap-1.c @@ -1,6 +1,6 @@ void swap(void *va, void *vb, size_t s) { char t, *a = (char*)va, *b = (char*)vb; - while(--s) + while(s--) t = a[s], a[s] = b[s], b[s] = t; } diff --git a/Task/Generic-swap/Chapel/generic-swap-1.chapel b/Task/Generic-swap/Chapel/generic-swap-1.chapel new file mode 100644 index 0000000000..ca8e5233ca --- /dev/null +++ b/Task/Generic-swap/Chapel/generic-swap-1.chapel @@ -0,0 +1 @@ +a <=> b diff --git a/Task/Generic-swap/Chapel/generic-swap.chapel b/Task/Generic-swap/Chapel/generic-swap-2.chapel similarity index 100% rename from Task/Generic-swap/Chapel/generic-swap.chapel rename to Task/Generic-swap/Chapel/generic-swap-2.chapel diff --git a/Task/Generic-swap/DCL/generic-swap.dcl b/Task/Generic-swap/DCL/generic-swap.dcl new file mode 100644 index 0000000000..3a8e61f4eb --- /dev/null +++ b/Task/Generic-swap/DCL/generic-swap.dcl @@ -0,0 +1,12 @@ +$ a1 = 123 +$ a2 = "hello" +$ show symbol a* +$ gosub swap +$ show symbol a* +$ exit +$ +$ swap: +$ t = a1 +$ a1 = a2 +$ a2 = t +$ return diff --git a/Task/Generic-swap/Elixir/generic-swap-1.elixir b/Task/Generic-swap/Elixir/generic-swap-1.elixir new file mode 100644 index 0000000000..c1ad560d48 --- /dev/null +++ b/Task/Generic-swap/Elixir/generic-swap-1.elixir @@ -0,0 +1,10 @@ +x = 4 +y = 5 + +{y,x} = {x,y} +y # => 4 +x # => 5 + +[x,y] = [y,x] +x # => 4 +y # => 5 diff --git a/Task/Generic-swap/Elixir/generic-swap-2.elixir b/Task/Generic-swap/Elixir/generic-swap-2.elixir new file mode 100644 index 0000000000..3552e1f6ac --- /dev/null +++ b/Task/Generic-swap/Elixir/generic-swap-2.elixir @@ -0,0 +1,4 @@ +swap = fn x,y -> [y|x] end +[x|y] = swap.(1,2) +x # => 2 +y # => 1 diff --git a/Task/Generic-swap/Elixir/generic-swap-3.elixir b/Task/Generic-swap/Elixir/generic-swap-3.elixir new file mode 100644 index 0000000000..af23bf681d --- /dev/null +++ b/Task/Generic-swap/Elixir/generic-swap-3.elixir @@ -0,0 +1,9 @@ +swap_tuple = fn {x,y} -> {y,x} end +{a,b} = swap_tuple.({1,:ok}) +a # => :ok +b # => 1 + +swap_list = fn [x,y] -> [y,x] end +[a,b] = swap_list.([1,"2"]) +a # => "2" +b # => 1 diff --git a/Task/Generic-swap/Rust/generic-swap.rust b/Task/Generic-swap/Rust/generic-swap.rust new file mode 100644 index 0000000000..1bfa87943e --- /dev/null +++ b/Task/Generic-swap/Rust/generic-swap.rust @@ -0,0 +1,6 @@ +fn main() { + let mut a="Anna".to_owned(); + let mut b="Bob".to_owned(); + std::mem::swap(&mut a, &mut b); + println!("a={},b={}",a,b); +} diff --git a/Task/Generic-swap/Tcl/generic-swap-5.tcl b/Task/Generic-swap/Tcl/generic-swap-5.tcl new file mode 100644 index 0000000000..b4e9562750 --- /dev/null +++ b/Task/Generic-swap/Tcl/generic-swap-5.tcl @@ -0,0 +1,5 @@ +set a 1 +set b 2 +puts "before\ta=$a\tb=$b" +set a $b[set b $a;lindex {}] +puts "after\ta=$a\tb=$b" diff --git a/Task/Gray-code/00DESCRIPTION b/Task/Gray-code/00DESCRIPTION index 9c9f633f11..ba26fee0e5 100644 --- a/Task/Gray-code/00DESCRIPTION +++ b/Task/Gray-code/00DESCRIPTION @@ -1,26 +1,24 @@ -[[wp:Gray code|Gray code]] is a form of binary encoding -where transitions between consecutive numbers differ by only one bit. -This is a useful encoding for reducing hardware data hazards -with values that change rapidly and/or connect to slower hardware as inputs. -It is also useful for generating inputs for [[wp:Karnaugh map|Karnaugh maps]] -in order from left to right or top to bottom. +[[wp:Gray code|Gray code]] is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for [[wp:Karnaugh map|Karnaugh maps]] in order from left to right or top to bottom. Create functions to encode a number to and decode a number from Gray code. -Display the normal binary representations, Gray code representations, -and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, -leading 0's not necessary). -There are many possible Gray codes. -The following encodes what is called "binary reflected Gray code." +Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). + +There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): +

if b[i-1] = 1
    g[i] = not b[i]
 else
    g[i] = b[i]
+ Or: +
g = b xor (b logically right shifted 1 time)
+ Decoding (MSB is bit 0, b is binary, g is Gray code): +
b[0] = g[0]
 
 for other bits:
diff --git a/Task/Gray-code/ALGOL-68/gray-code.alg b/Task/Gray-code/ALGOL-68/gray-code.alg
new file mode 100644
index 0000000000..1a66d040ef
--- /dev/null
+++ b/Task/Gray-code/ALGOL-68/gray-code.alg
@@ -0,0 +1,12 @@
+BEGIN
+   OP GRAY = (BITS b) BITS : b XOR (b SHR 1);	CO Convert to Gray code CO
+   OP YARG = (BITS g) BITS :			CO Convert from Gray code CO
+   BEGIN
+      BITS b := g, mask := g SHR 1;
+      WHILE mask /= 2r0 DO b := b XOR mask; mask := mask SHR 1 OD;
+      b
+   END;
+   FOR i FROM 0 TO 31 DO
+      printf (($zd, ": ", 2(2r5d, " >= "), 2r5dl$, i, BIN i, GRAY BIN i, YARG GRAY BIN i))
+   OD
+END
diff --git a/Task/Gray-code/C++/gray-code.cpp b/Task/Gray-code/C++/gray-code.cpp
index fb9d327a02..cd4c1e7849 100644
--- a/Task/Gray-code/C++/gray-code.cpp
+++ b/Task/Gray-code/C++/gray-code.cpp
@@ -1,6 +1,7 @@
 #include 
 #include 
 #include 
+#include 
 
 uint32_t gray_encode(uint32_t b)
 {
@@ -30,8 +31,8 @@ int main()
     for (uint32_t n = 0; n < 32; ++n)
     {
         uint32_t g = gray_encode(n);
-        uint32_t b = gray_decode(g);
+        assert(gray_decode(g) == n);
 
-        std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << b << "\n";
+        std::cout << n << "\t" << to_binary(n) << "\t" << to_binary(g) << "\t" << g << "\n";
     }
 }
diff --git a/Task/Gray-code/Elixir/gray-code.elixir b/Task/Gray-code/Elixir/gray-code.elixir
new file mode 100644
index 0000000000..48750075bc
--- /dev/null
+++ b/Task/Gray-code/Elixir/gray-code.elixir
@@ -0,0 +1,15 @@
+defmodule Gray_code do
+  use Bitwise
+  def encode(n), do: bxor(n, bsr(n,1))
+
+  def decode(g), do: decode(g,0)
+
+  def decode(0,n), do: n
+  def decode(g,n), do: decode(bsr(g,1), bxor(g,n))
+end
+
+Enum.each(0..31, fn(n) ->
+  g = Gray_code.encode(n)
+  d = Gray_code.decode(g)
+  :io.fwrite("~2B : ~5.2.0B : ~5.2.0B : ~5.2.0B : ~2B~n", [n, n, g, d, d])
+end)
diff --git a/Task/Gray-code/Limbo/gray-code.limbo b/Task/Gray-code/Limbo/gray-code.limbo
new file mode 100644
index 0000000000..9ecfa3938d
--- /dev/null
+++ b/Task/Gray-code/Limbo/gray-code.limbo
@@ -0,0 +1,50 @@
+implement Gray;
+
+include "sys.m"; sys: Sys;
+	print: import sys;
+include "draw.m";
+
+Gray: module {
+	init: fn(nil: ref Draw->Context, args: list of string);
+	# Export gray and grayinv so that this module can be used as either a
+	# standalone program or as a library:
+	gray: fn(n: int): int;
+	grayinv: fn(n: int): int;
+};
+
+init(nil: ref Draw->Context, args: list of string)
+{
+	sys = load Sys Sys->PATH;
+	for(i := 0; i < 32; i++) {
+		g := gray(i);
+		f := grayinv(g);
+		print("%2d  %5s  %2d  %5s  %5s  %2d\n", i, binstr(i), g, binstr(g), binstr(f), f);
+	}
+}
+
+gray(n: int): int
+{
+	return n ^ (n >> 1);
+}
+
+grayinv(n: int): int
+{
+	r := 0;
+	while(n) {
+		r ^= n;
+		n >>= 1;
+	}
+	return r;
+}
+
+binstr(n: int): string
+{
+	if(!n)
+		return "0";
+	s := "";
+	while(n) {
+		s = (string (n&1)) + s;
+		n >>= 1;
+	}
+	return s;
+}
diff --git a/Task/Gray-code/REXX/gray-code.rexx b/Task/Gray-code/REXX/gray-code.rexx
index 93ea003347..94773504f2 100644
--- a/Task/Gray-code/REXX/gray-code.rexx
+++ b/Task/Gray-code/REXX/gray-code.rexx
@@ -1,25 +1,25 @@
-/*REXX program to convert decimal───> binary ───> gray code ───> binary.*/
-parse arg N .;    if N=='' then N=31   /*Not specified? Then use default*/
-L=max(1,length(strip(x2b(d2x(N)),'L',0)))   /*for cell width formatting.*/
-w=14                                   /*used for cell width formatting.*/
-_=center('binary',w,'─')               /*2nd and 4th part of the header.*/
-say center('decimal',w,'─')">" _">" center('gray code',w,'─')">" _ /*hdr*/
-
-     do j=0  to N;     b=right(x2b(d2x(j)),L,0)      /*handle 0  ──►  N.*/
-     g=b2gray(b)                       /*convert binary to gray code.   */
-     a=gray2b(g)                       /*convert gray code to binary.   */
-     say center(j,w+1) center(b,w+1) center(g,w+1) center(a,w+1)  /*tell*/
+/*REXX program converts decimal number ───► binary ───► gray code ───► binary.*/
+parse arg N .                          /*get the optional argument from the CL*/
+if N==''  | N==","   then N=31         /*Not specified?  Then use the default.*/
+L=max(1,length(strip(x2b(d2x(N)),'L',0)))   /*find the max binary length of N.*/
+w=14                                   /*used for the formatting of cell width*/
+_=center('binary',w,'─')               /*the  2nd and 4th  part of the header.*/
+say center('decimal', w, "─")'►'     _"►"    center('gray code', w, '─')"►"    _
+                                                     /* [+]  the output header*/
+     do j=0  to N;     b=right(x2b(d2x(j)),L,0)      /*process   0  ──►  N.   */
+     g=b2gray(b)                       /*convert binary number to gray code.  */
+     a=gray2b(g)                       /*convert the gray code to binary.     */
+     say center(j,w+1)   center(b,w+1)   center(g,w+1)   center(a,w+1)
      end   /*j*/
-exit                                   /*stick a fork in it, we're done.*/
-/*───────────────────────────────────B2GRAY subroutine──────────────────*/
-b2gray: procedure; parse arg x
-$=left(x,1);                    do b=2  to length(x)
-                                $=$||(substr(x,b-1,1) && substr(x,b,1))
-                                end   /*b*/        /* && is eXclusive OR*/
-return $
-/*───────────────────────────────────GRAY2B subroutine──────────────────*/
-gray2b: procedure; parse arg x
-$=left(x,1);                    do g=2  to length(x)
-                                $=$ || (right($,1)    && substr(x,g,1))
-                                end   /*g*/        /* && is eXclusive OR*/
-return $
+exit                                   /*stick a fork in it,  we're all done. */
+/*────────────────────────────────────────────────────────────────────────────*/
+b2gray: procedure; parse arg x 1 $ 2;    do b=2  to length(x)
+                                         $=$||(substr(x,b-1,1) && substr(x,b,1))
+                                         end   /*b*/
+        return $
+/*────────────────────────────────────────────────────────────────────────────*/
+gray2b: procedure; parse arg x 1 $ 2;    do g=2  to length(x)
+                                         $=$ || (right($,1)    && substr(x,g,1))
+                                         end   /*g*/        /*  ↑  */
+                                                            /*  │  */
+        return $           /*this is an eXclusive OR  ►─────────┘  */
diff --git a/Task/Gray-code/Rust/gray-code.rust b/Task/Gray-code/Rust/gray-code.rust
index 7274ae6580..77e7164fba 100644
--- a/Task/Gray-code/Rust/gray-code.rust
+++ b/Task/Gray-code/Rust/gray-code.rust
@@ -1,19 +1,18 @@
-fn gray_encode(integer: uint) -> uint {
-	(integer >> 1) ^ integer
+fn gray_encode(integer: u64) -> u64 {
+    (integer >> 1) ^ integer
 }
 
-fn gray_decode(integer: uint) -> uint {
-	match integer {
-		0 => 0,
-		_ => integer ^ gray_decode(integer >> 1)
-	}
+fn gray_decode(integer: u64) -> u64 {
+    match integer {
+        0 => 0,
+        _ => integer ^ gray_decode(integer >> 1)
+    }
 }
 
-
 fn main() {
-	for i in range(0u,32u) {
-		println!("{:2} {:0>5t} {:0>5t} {:2}", i, i, gray_encode(i),
-			gray_decode(i));
-	}
+    for i in 0..32 {
+        println!("{:2} {:0>5b} {:0>5b} {:2}", i, i, gray_encode(i),
+            gray_decode(i));
+    }
 
 }
diff --git a/Task/Grayscale-image/Julia/grayscale-image-1.julia b/Task/Grayscale-image/Julia/grayscale-image-1.julia
new file mode 100644
index 0000000000..52010d33ac
--- /dev/null
+++ b/Task/Grayscale-image/Julia/grayscale-image-1.julia
@@ -0,0 +1,20 @@
+using Color, Images, FixedPointNumbers
+
+const M_RGB_Y = reshape(Color.M_RGB_XYZ[2,:], 3)
+
+function rgb2gray(img::Image)
+    g = red(img)*M_RGB_Y[1] + green(img)*M_RGB_Y[2] + blue(img)*M_RGB_Y[3]
+    g = clamp(g, 0.0, 1.0)
+    return grayim(g)
+end
+
+function gray2rgb(img::Image)
+    colorspace(img) == "Gray" || return img
+    g = map((x)->RGB{Ufixed8}(x, x, x), img.data)
+    return Image(g, spatialorder=spatialorder(img))
+end
+
+ima = imread("grayscale_image_color.png")
+imb = rgb2gray(ima)
+imc = gray2rgb(imb)
+imwrite(imc, "grayscale_image_rc.png")
diff --git a/Task/Grayscale-image/Julia/grayscale-image-2.julia b/Task/Grayscale-image/Julia/grayscale-image-2.julia
new file mode 100644
index 0000000000..ae3134e3ac
--- /dev/null
+++ b/Task/Grayscale-image/Julia/grayscale-image-2.julia
@@ -0,0 +1,5 @@
+using Color, Images, FixedPointNumbers
+
+ima = imread("grayscale_image_color.png")
+imb = convert(Image{Gray{Ufixed8}}, ima)
+imwrite(imb, "grayscale_image_julia.png")
diff --git a/Task/Greatest-common-divisor/ALGOL-W/greatest-common-divisor.alg b/Task/Greatest-common-divisor/ALGOL-W/greatest-common-divisor.alg
new file mode 100644
index 0000000000..605ce5c48c
--- /dev/null
+++ b/Task/Greatest-common-divisor/ALGOL-W/greatest-common-divisor.alg
@@ -0,0 +1,22 @@
+begin
+    % iterative Greatest Common Divisor routine                               %
+    integer procedure gcd ( integer value m, n ) ;
+    begin
+        integer a, b, newA;
+        a := abs( m );
+        b := abs( n );
+        if a = 0 then begin
+            b
+            end
+        else begin
+            while b not = 0 do begin
+                newA := b;
+                b    := a rem b;
+                a    := newA;
+            end;
+            a
+        end
+    end gcd ;
+
+    write( gcd( -21, 35 ) );
+end.
diff --git a/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-2.lisp b/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-2.lisp
index d4eba491ba..4775f7fe06 100644
--- a/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-2.lisp
+++ b/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-2.lisp
@@ -1,3 +1,3 @@
-(defun gcd2 (a b)
+(defun gcd* (a b)
   (do () ((zerop b) (abs a))
     (shiftf a b (mod a b))))
diff --git a/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-3.lisp b/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-3.lisp
index 835e20ebdc..6949d283b8 100644
--- a/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-3.lisp
+++ b/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-3.lisp
@@ -1,3 +1,4 @@
-(defun gcd2 (a b)
-  (if (zerop b) a
+(defun gcd* (a b)
+  (if (zerop b)
+       a
       (gcd2 b (mod a b))))
diff --git a/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-4.lisp b/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-4.lisp
index 49f8d8ce80..6d0c211768 100644
--- a/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-4.lisp
+++ b/Task/Greatest-common-divisor/Common-Lisp/greatest-common-divisor-4.lisp
@@ -1,4 +1,4 @@
-(defun gcd2 (a b)
+(defun gcd* (a b)
   (loop for x = a then y
         and y = b then (mod x y)
         until (zerop y)
diff --git a/Task/Greatest-common-divisor/Elixir/greatest-common-divisor.elixir b/Task/Greatest-common-divisor/Elixir/greatest-common-divisor.elixir
new file mode 100644
index 0000000000..51af9414f8
--- /dev/null
+++ b/Task/Greatest-common-divisor/Elixir/greatest-common-divisor.elixir
@@ -0,0 +1,7 @@
+defmodule RC do
+  def gcd(a,0), do: abs(a)
+  def gcd(a,b), do: gcd(b, rem(a,b))
+end
+
+IO.puts RC.gcd(1071, 1029)
+IO.puts RC.gcd(3528, 3780)
diff --git a/Task/Greatest-common-divisor/Excel/greatest-common-divisor.excel b/Task/Greatest-common-divisor/Excel/greatest-common-divisor.excel
new file mode 100644
index 0000000000..9f6c104ce9
--- /dev/null
+++ b/Task/Greatest-common-divisor/Excel/greatest-common-divisor.excel
@@ -0,0 +1 @@
+=GCD(A1:E1)
diff --git a/Task/Greatest-common-divisor/J/greatest-common-divisor-3.j b/Task/Greatest-common-divisor/J/greatest-common-divisor-3.j
new file mode 100644
index 0000000000..a4531536ed
--- /dev/null
+++ b/Task/Greatest-common-divisor/J/greatest-common-divisor-3.j
@@ -0,0 +1 @@
+gcd=: (| gcd [)^:(0<[)&|
diff --git a/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-1.js b/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-1.js
index f0c9597bce..f821cc9c25 100644
--- a/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-1.js
+++ b/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-1.js
@@ -1,11 +1,17 @@
 function gcd(a,b) {
-    if (a < 0) a = -a;
-    if (b < 0) b = -b;
-    if (b > a) {var temp = a; a = b; b = temp;}
-    while (true) {
-        a %= b;
-        if (a == 0) return b;
-        b %= a;
-        if (b == 0) return a;
-    }
+  a = Math.abs(a);
+  b = Math.abs(b);
+
+  if (b > a) {
+    var temp = a;
+    a = b;
+    b = temp;
+  }
+
+  while (true) {
+    a %= b;
+    if (a === 0) { return b; }
+    b %= a;
+    if (b === 0) { return a; }
+  }
 }
diff --git a/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-2.js b/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-2.js
index ff62f38e98..cacd33eec4 100644
--- a/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-2.js
+++ b/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-2.js
@@ -1,7 +1,3 @@
 function gcd_rec(a, b) {
-    if (b) {
-        return gcd_rec(b, a % b);
-    } else {
-        return Math.abs(a);
-    }
+  return b ? gcd_rec(b, a % b) : Math.abs(a);
 }
diff --git a/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-3.js b/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-3.js
index 0ca0d4ac1c..9e130c750e 100644
--- a/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-3.js
+++ b/Task/Greatest-common-divisor/JavaScript/greatest-common-divisor-3.js
@@ -1,14 +1,18 @@
-function GCD(A)   // A is an integer array (e.g. [57,0,-45,-18,90,447])
-{
-    var n = A.length, x = A[0] < 0 ? -A[0] : A[0];
-    for (var i = 1; i < n; i++)
-     { var y = A[i] < 0 ? -A[i] : A[i];
-       while (x && y){ x > y ? x %= y : y %= x; }
-       x += y;
-     }
-    return x;
+function GCD(arr) {
+  var i, y,
+      n = arr.length,
+      x = Math.abs(arr[0]);
+
+  for (i = 1; i < n; i++) {
+    y = Math.abs(arr[i]);
+
+    while (x && y) {
+      (x > y) ? x %= y : y %= x;
+    }
+    x += y;
+  }
+  return x;
 }
 
-/* For example:
-   GCD([57,0,-45,-18,90,447]) -> 3
-*/
+//For example:
+GCD([57,0,-45,-18,90,447]); //=> 3
diff --git a/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-2.ocaml b/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-2.ocaml
index 34be4ae7a5..7afe5f508a 100644
--- a/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-2.ocaml
+++ b/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-2.ocaml
@@ -1,4 +1,4 @@
-#load "nums.cma";;
-open Big_int;;
-let gcd a b =
-  int_of_big_int (gcd_big_int (big_int_of_int a) (big_int_of_int b))
+let rec gcd1 a b =
+  match (a mod b) with
+    0 -> b
+  | r -> gcd1 b r
diff --git a/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-3.ocaml b/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-3.ocaml
new file mode 100644
index 0000000000..34be4ae7a5
--- /dev/null
+++ b/Task/Greatest-common-divisor/OCaml/greatest-common-divisor-3.ocaml
@@ -0,0 +1,4 @@
+#load "nums.cma";;
+open Big_int;;
+let gcd a b =
+  int_of_big_int (gcd_big_int (big_int_of_int a) (big_int_of_int b))
diff --git a/Task/Greatest-common-divisor/PostScript/greatest-common-divisor.ps b/Task/Greatest-common-divisor/PostScript/greatest-common-divisor-1.ps
similarity index 100%
rename from Task/Greatest-common-divisor/PostScript/greatest-common-divisor.ps
rename to Task/Greatest-common-divisor/PostScript/greatest-common-divisor-1.ps
diff --git a/Task/Greatest-common-divisor/PostScript/greatest-common-divisor-2.ps b/Task/Greatest-common-divisor/PostScript/greatest-common-divisor-2.ps
new file mode 100644
index 0000000000..1d2681a2df
Binary files /dev/null and b/Task/Greatest-common-divisor/PostScript/greatest-common-divisor-2.ps differ
diff --git a/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor.psh b/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-1.psh
similarity index 100%
rename from Task/Greatest-common-divisor/PowerShell/greatest-common-divisor.psh
rename to Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-1.psh
diff --git a/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-2.psh b/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-2.psh
new file mode 100644
index 0000000000..758caaf4e0
--- /dev/null
+++ b/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-2.psh
@@ -0,0 +1,3 @@
+function Get-GCD ($x, $y) {
+  if ($y -eq 0) { $x } else { Get-GCD $y ($x%$y) }
+}
diff --git a/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-3.psh b/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-3.psh
new file mode 100644
index 0000000000..795e42f037
--- /dev/null
+++ b/Task/Greatest-common-divisor/PowerShell/greatest-common-divisor-3.psh
@@ -0,0 +1,6 @@
+Function Get-GCD( $x, $y ) {
+    while ($y -ne 0) {
+        $x, $y = $y, ($x % $y)
+    }
+    [Math]::abs($x)
+}
diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust
index c411443790..14a0133611 100644
--- a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust
+++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-1.rust
@@ -1 +1,2 @@
-use std::num::gcd;
+extern crate num;
+use num::integer::gcd;
diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust
index a09e7930ec..0018a92535 100644
--- a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust
+++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-2.rust
@@ -1,8 +1,8 @@
-fn gcd(mut m: int, mut n: int) -> int {
+fn gcd(mut m: i32, mut n: i32) -> i32 {
    while m != 0 {
-       let temp = m;
-       m = n % temp;
-       n = temp;
+       let old_m = m;
+       m = n % m;
+       n = old_m;
    }
    n.abs()
 }
diff --git a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust
index bbde08408b..427616d50a 100644
--- a/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust
+++ b/Task/Greatest-common-divisor/Rust/greatest-common-divisor-3.rust
@@ -1,6 +1,7 @@
-fn gcd(m: int, n: int) -> int {
-   if m == 0
-      { n.abs() }
-   else
-      { gcd(n % m, m) }
+fn gcd(m: i32, n: i32) -> i32 {
+   if m == 0 {
+      n.abs()
+   } else {
+      gcd(n % m, m)
+   }
 }
diff --git a/Task/Greatest-common-divisor/SQL/greatest-common-divisor.sql b/Task/Greatest-common-divisor/SQL/greatest-common-divisor.sql
new file mode 100644
index 0000000000..316e30a3f0
--- /dev/null
+++ b/Task/Greatest-common-divisor/SQL/greatest-common-divisor.sql
@@ -0,0 +1,34 @@
+drop table tbl;
+create table tbl
+(
+        u       number,
+        v       number
+);
+
+insert into tbl ( u, v ) values ( 20, 50 );
+insert into tbl ( u, v ) values ( 21, 50 );
+insert into tbl ( u, v ) values ( 21, 51 );
+insert into tbl ( u, v ) values ( 22, 50 );
+insert into tbl ( u, v ) values ( 22, 55 );
+
+commit;
+
+with
+        function gcd ( ui in number, vi in number )
+        return number
+        is
+                u number := ui;
+                v number := vi;
+                t number;
+        begin
+                while v > 0
+                loop
+                        t := u;
+                        u := v;
+                        v:= mod(t, v );
+                end loop;
+                return abs(u);
+        end gcd;
+        select u, v, gcd ( u, v )
+        from tbl
+/
diff --git a/Task/Greatest-common-divisor/Z80-Assembly/greatest-common-divisor.z80 b/Task/Greatest-common-divisor/Z80-Assembly/greatest-common-divisor.z80
new file mode 100644
index 0000000000..7269fad7bd
--- /dev/null
+++ b/Task/Greatest-common-divisor/Z80-Assembly/greatest-common-divisor.z80
@@ -0,0 +1,22 @@
+; Inputs: a, b
+; Outputs: a = gcd(a, b)
+; Destroys: c
+; Assumes: a and b are positive one-byte integers
+gcd:
+    cp b
+    ret z                   ; while a != b
+
+    jr c, else              ; if a > b
+
+    sub b                   ; a = a - b
+
+    jr gcd
+
+else:
+    ld c, a                 ; Save a
+    ld a, b                 ; Swap b into a so we can do the subtraction
+    sub c                   ; b = b - a
+    ld b, a                 ; Put a and b back where they belong
+    ld a, c
+
+    jr gcd
diff --git a/Task/Greatest-element-of-a-list/ALGOL-W/greatest-element-of-a-list.alg b/Task/Greatest-element-of-a-list/ALGOL-W/greatest-element-of-a-list.alg
new file mode 100644
index 0000000000..0510c6a502
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/ALGOL-W/greatest-element-of-a-list.alg
@@ -0,0 +1,27 @@
+begin
+    % simple list type                                                       %
+    record IntList( integer val; reference(IntList) next );
+
+    % find the maximum element of an IntList, returns 0 for an empty list    %
+    integer procedure maxElement( reference(IntList) value list ) ;
+        begin
+            integer maxValue;
+            reference(IntList) listPos;
+            maxValue := 0;
+            listPos  := list;
+            if listPos not = null then begin
+                % non-empty list                                             %
+                maxValue := val(listPos);
+                listPos  := next(listPos);
+                while listPos not = null do begin
+                    if val(listPos) > maxValue then maxValue := val(listPos);
+                    listPos := next(listPos)
+                end while_listPos_ne_null ;
+            end if_listPos_ne_null ;
+            maxValue
+        end maxElement ;
+
+    % test the maxElement procedure                                          %
+    write( maxElement( IntList( -767, IntList( 2397, IntList( 204, null ) ) ) ) )
+
+end.
diff --git a/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list.applescript b/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list.applescript
index 61e8dd101c..515eb3db94 100644
--- a/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list.applescript
+++ b/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list.applescript
@@ -1,3 +1,5 @@
+max({1, 2, 3, 4, 20, 6, 11, 3, 9, 7})
+
 on max(aList)
 	set _curMax to first item of aList
 	repeat with i in (rest of aList)
diff --git a/Task/Greatest-element-of-a-list/BBC-BASIC/greatest-element-of-a-list.bbc b/Task/Greatest-element-of-a-list/BBC-BASIC/greatest-element-of-a-list.bbc
index 6d32b3c6fa..4881829834 100644
--- a/Task/Greatest-element-of-a-list/BBC-BASIC/greatest-element-of-a-list.bbc
+++ b/Task/Greatest-element-of-a-list/BBC-BASIC/greatest-element-of-a-list.bbc
@@ -4,9 +4,10 @@
 
       DEF FNmax(list$)
       LOCAL index%, number, max
+      max = VAL(list$)
       REPEAT
+        index% = INSTR(list$, ",", index%+1)
         number = VAL(MID$(list$, index%+1))
         IF number > max THEN max = number
-        index% = INSTR(list$, ",", index%+1)
       UNTIL index% = 0
       = max
diff --git a/Task/Greatest-element-of-a-list/DCL/greatest-element-of-a-list.dcl b/Task/Greatest-element-of-a-list/DCL/greatest-element-of-a-list.dcl
new file mode 100644
index 0000000000..232f68575a
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/DCL/greatest-element-of-a-list.dcl
@@ -0,0 +1,12 @@
+$ list = "45,65,81,12,0,13,-56,123,-123,888,12,0"
+$ max = f$integer( f$element( 0, ",", list ))
+$ i = 1
+$ loop:
+$  element = f$element( i, ",", list )
+$  if element .eqs. "," then $ goto done
+$  element = f$integer( element )
+$  if element .gt. max then $ max = element
+$  i = i + 1
+$  goto loop
+$ done:
+$ show symbol max
diff --git a/Task/Greatest-element-of-a-list/Elixir/greatest-element-of-a-list.elixir b/Task/Greatest-element-of-a-list/Elixir/greatest-element-of-a-list.elixir
new file mode 100644
index 0000000000..ab7cafbfc2
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/Elixir/greatest-element-of-a-list.elixir
@@ -0,0 +1,2 @@
+iex(1)> Enum.max([3,1,4,1,5,9,2,6,5,3])
+9
diff --git a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-1.go b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-1.go
index b96a6ee0c0..25725517e6 100644
--- a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-1.go
+++ b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-1.go
@@ -2,37 +2,10 @@ package main
 
 import (
     "fmt"
-    "math/rand"
-    "time"
-)
 
-// function, per task description
-func largest(a []int) (lg int, ok bool) {
-    if len(a) == 0 {
-        return
-    }
-    lg = a[0]
-    for _, e := range a[1:] {
-        if e > lg {
-            lg = e
-        }
-    }
-    return lg, true
-}
+    "github.com/gonum/floats"
+)
 
 func main() {
-    // random size slice
-    rand.Seed(time.Now().UnixNano())
-    a := make([]int, rand.Intn(11))
-    for i := range a {
-        a[i] = rand.Intn(101) - 100 // fill with random numbers
-    }
-
-    fmt.Println(a)
-    lg, ok := largest(a)
-    if ok {
-        fmt.Println(lg)
-    } else {
-        fmt.Println("empty list.  no maximum.")
-    }
+    fmt.Println(floats.Max([]float64{3, 1, 4, 1}))
 }
diff --git a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-2.go b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-2.go
index 563ff2f853..b96a6ee0c0 100644
--- a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-2.go
+++ b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-2.go
@@ -2,63 +2,37 @@ package main
 
 import (
     "fmt"
-    "math"
     "math/rand"
     "time"
 )
 
-// Function, per task description.  Interesting with the float64 type because
-// of the NaN value.  NaNs do not compare to other values, so the result of
-// a "largest" function on a set containing a NaN might be open to
-// interpretation.  The solution provided here is to return the largest
-// of the non-NaNs, and also return a bool indicating the presense of a NaN.
-func largest(s map[float64]bool) (lg float64, ok, nan bool) {
-    if len(s) == 0 {
+// function, per task description
+func largest(a []int) (lg int, ok bool) {
+    if len(a) == 0 {
         return
     }
-    for e := range s {
-        switch {
-        case math.IsNaN(e):
-            nan = true
-        case !ok || e > lg:
+    lg = a[0]
+    for _, e := range a[1:] {
+        if e > lg {
             lg = e
-            ok = true
         }
     }
-    return
+    return lg, true
 }
 
 func main() {
+    // random size slice
     rand.Seed(time.Now().UnixNano())
-    // taking "set" literally from task description
-    s := map[float64]bool{}
-    // pick number of elements to add to set
-    n := rand.Intn(11)
-    // add random numbers, also throw in an occasional NaN or Inf.
-    for i := 0; i < n; i++ {
-        switch rand.Intn(10) {
-        case 0:
-            s[math.NaN()] = true
-        case 1:
-            s[math.Inf(1)] = true
-        default:
-            s[rand.ExpFloat64()] = true
-        }
+    a := make([]int, rand.Intn(11))
+    for i := range a {
+        a[i] = rand.Intn(101) - 100 // fill with random numbers
     }
 
-    fmt.Print("s:")
-    for e := range s {
-        fmt.Print(" ", e)
-    }
-    fmt.Println()
-    switch lg, ok, nan := largest(s); {
-    case ok && !nan:
-        fmt.Println("largest:", lg)
-    case ok:
-        fmt.Println("largest:", lg, "(NaN present in data)")
-    case nan:
-        fmt.Println("no largest, all data NaN")
-    default:
-        fmt.Println("no largest, empty set")
+    fmt.Println(a)
+    lg, ok := largest(a)
+    if ok {
+        fmt.Println(lg)
+    } else {
+        fmt.Println("empty list.  no maximum.")
     }
 }
diff --git a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-3.go b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-3.go
new file mode 100644
index 0000000000..563ff2f853
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-3.go
@@ -0,0 +1,64 @@
+package main
+
+import (
+    "fmt"
+    "math"
+    "math/rand"
+    "time"
+)
+
+// Function, per task description.  Interesting with the float64 type because
+// of the NaN value.  NaNs do not compare to other values, so the result of
+// a "largest" function on a set containing a NaN might be open to
+// interpretation.  The solution provided here is to return the largest
+// of the non-NaNs, and also return a bool indicating the presense of a NaN.
+func largest(s map[float64]bool) (lg float64, ok, nan bool) {
+    if len(s) == 0 {
+        return
+    }
+    for e := range s {
+        switch {
+        case math.IsNaN(e):
+            nan = true
+        case !ok || e > lg:
+            lg = e
+            ok = true
+        }
+    }
+    return
+}
+
+func main() {
+    rand.Seed(time.Now().UnixNano())
+    // taking "set" literally from task description
+    s := map[float64]bool{}
+    // pick number of elements to add to set
+    n := rand.Intn(11)
+    // add random numbers, also throw in an occasional NaN or Inf.
+    for i := 0; i < n; i++ {
+        switch rand.Intn(10) {
+        case 0:
+            s[math.NaN()] = true
+        case 1:
+            s[math.Inf(1)] = true
+        default:
+            s[rand.ExpFloat64()] = true
+        }
+    }
+
+    fmt.Print("s:")
+    for e := range s {
+        fmt.Print(" ", e)
+    }
+    fmt.Println()
+    switch lg, ok, nan := largest(s); {
+    case ok && !nan:
+        fmt.Println("largest:", lg)
+    case ok:
+        fmt.Println("largest:", lg, "(NaN present in data)")
+    case nan:
+        fmt.Println("no largest, all data NaN")
+    default:
+        fmt.Println("no largest, empty set")
+    }
+}
diff --git a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-2.js b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-2.js
index 28b6b9b7ba..4160653903 100644
--- a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-2.js
+++ b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-2.js
@@ -1 +1,99 @@
-Math.max(...[ 0, 1, 2, 5, 4 ]); // 5
+(function () {
+
+    // Generalised max() function
+    // [a] -> (a -> n) -> a
+    function max(list, fnCompare) {
+        return list.reduce(function (acc, b) {
+            var a = acc || b,
+                lngDiff = fnCompare(a, b);
+
+            return lngDiff ? (lngDiff > 0 ? b : a) : a;
+        }, null)
+    }
+
+    // Comparison functions for specific data types
+
+    function wordSortFirst(a, b) {
+        return a === null ? b : a === b ? 0 : a < b ? -1 : 1;
+    }
+
+    function wordSortLast(a, b) {
+        return a === null ? b : a === b ? 0 : a < b ? 1 : -1;
+    }
+
+    function wordLongest(a, b) {
+        var lngA = a ? a.length : b.length,
+            lngB = b.length;
+
+        return lngA === lngB ? 0 : lngA > lngB ? -1 : 1;
+    }
+
+    function cityPopulationMost(a, b) {
+        var nA = a ? a.population : b.population,
+            nB = b.population;
+
+        return nA === nB ? 0 : nA > nB ? -1 : 1;
+    }
+
+    function cityPopulationLeast(a, b) {
+        var nA = a ? a.population : b.population,
+            nB = b.population;
+
+        return nA === nB ? 0 : nA < nB ? -1 : 1;
+    }
+
+    function cityNameSortFirst(a, b) {
+        var sA = a ? a.name : b.name,
+            sB = b.name;
+
+        return sA === sB ? 0 : sA < sB ? -1 : 1;
+    }
+
+    function cityNameSortLast(a, b) {
+        var sA = a ? a.name : b.name,
+            sB = b.name;
+
+        return sA === sB ? 0 : sA > sB ? -1 : 1;
+    }
+
+    var lstWords = [
+            'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta',
+            'theta', 'iota', 'kappa', 'lambda'
+        ];
+
+    var lstCities = [
+            {
+                name: 'Shanghai',
+                population: 24.15
+            }, {
+                name: 'Karachi',
+                population: 23.5
+            }, {
+                name: 'Beijing',
+                population: 21.5
+            }, {
+                name: 'Tianjin',
+                population: 14.7
+            }, {
+                name: 'Istanbul',
+                population: 14.4
+            }, , {
+                name: 'Lagos',
+                population: 13.4
+            }, , {
+                name: 'Tokyo',
+                population: 13.3
+            }
+        ];
+
+    return [
+        max(lstWords, wordSortFirst),
+        max(lstWords, wordSortLast),
+        max(lstWords, wordLongest),
+        max(lstCities, cityPopulationMost),
+        max(lstCities, cityPopulationLeast),
+        max(lstCities, cityNameSortFirst),
+        max(lstCities, cityNameSortLast)
+    ]
+
+})();
diff --git a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-3.js b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-3.js
new file mode 100644
index 0000000000..f419d9c4bb
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-3.js
@@ -0,0 +1,21 @@
+[
+  "alpha",
+  "zeta",
+  "epsilon",
+  {
+    "name": "Shanghai",
+    "population": 24.15
+  },
+  {
+    "name": "Tokyo",
+    "population": 13.3
+  },
+  {
+    "name": "Beijing",
+    "population": 21.5
+  },
+  {
+    "name": "Tokyo",
+    "population": 13.3
+  }
+]
diff --git a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-4.js b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-4.js
new file mode 100644
index 0000000000..28b6b9b7ba
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-4.js
@@ -0,0 +1 @@
+Math.max(...[ 0, 1, 2, 5, 4 ]); // 5
diff --git a/Task/Greatest-element-of-a-list/PureBasic/greatest-element-of-a-list.purebasic b/Task/Greatest-element-of-a-list/PureBasic/greatest-element-of-a-list-1.purebasic
similarity index 100%
rename from Task/Greatest-element-of-a-list/PureBasic/greatest-element-of-a-list.purebasic
rename to Task/Greatest-element-of-a-list/PureBasic/greatest-element-of-a-list-1.purebasic
diff --git a/Task/Greatest-element-of-a-list/PureBasic/greatest-element-of-a-list-2.purebasic b/Task/Greatest-element-of-a-list/PureBasic/greatest-element-of-a-list-2.purebasic
new file mode 100644
index 0000000000..cb58a5312d
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/PureBasic/greatest-element-of-a-list-2.purebasic
@@ -0,0 +1,8 @@
+Procedure.f maxelement(List tl.f())
+  ForEach tl() : mx.f=mx*Bool(mx>=tl())+tl()*Bool(mx tmp_num Then
+			tmp_num = arr(i)
+		End If
+	Next
+	greatest_element = tmp_num
+End Function
+
+WScript.Echo greatest_element(Array(1,2,3,44,5,6,8))
diff --git a/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-1.elixir b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-1.elixir
new file mode 100644
index 0000000000..6e77d260d3
--- /dev/null
+++ b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-1.elixir
@@ -0,0 +1,11 @@
+defmodule Greatest do
+  def subseq_sum(list) do
+    limit = length(list) - 1
+    ij = for i <- 0..limit, j <- i..limit, do: {i,j}
+    Enum.reduce(ij, {0, []}, fn {i,j},{max, subseq} ->
+      slice = Enum.slice(list, i..j)
+      sum = Enum.sum(slice)
+      if sum > max, do: {sum, slice}, else: {max, subseq}
+    end)
+  end
+end
diff --git a/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-2.elixir b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-2.elixir
new file mode 100644
index 0000000000..9c96b245be
--- /dev/null
+++ b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-2.elixir
@@ -0,0 +1,9 @@
+data = [ [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5],
+         [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1],
+         [-1, -2, -3, -4, -5],
+         [] ]
+Enum.each(data, fn input ->
+  IO.puts "\nInput seq: #{inspect input}"
+  {max, subseq} = Greatest.subseq_sum(input)
+  IO.puts "  Max sum: #{max}\n   Subseq: #{inspect subseq}"
+end)
diff --git a/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-3.elixir b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-3.elixir
new file mode 100644
index 0000000000..03ba19ff52
--- /dev/null
+++ b/Task/Greatest-subsequential-sum/Elixir/greatest-subsequential-sum-3.elixir
@@ -0,0 +1,17 @@
+defmodule Greatest do
+  def subseq_sum(list) do
+    list_i = Enum.with_index(list)
+    acc = {0, 0, length(list), 0, 0}
+    {_,max,first,last,_} = Enum.reduce(list_i, acc, fn {elm,i},{curr,max,first,last,curr_first} ->
+      if curr < 0 do
+        if elm > max, do: {elm, elm, i,     i,    curr_first},
+                    else: {elm, max, first, last, curr_first}
+      else
+        cur2 = curr + elm
+        if cur2 > max, do: {cur2, cur2, curr_first, i, curr_first},
+                     else: {cur2, max,  first,   last, curr_first}
+      end
+    end)
+    {max, Enum.slice(list, first..last)}
+  end
+end
diff --git a/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum-1.fth b/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum-1.fth
new file mode 100644
index 0000000000..78c1d6e50b
--- /dev/null
+++ b/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum-1.fth
@@ -0,0 +1,23 @@
+2variable best
+variable best-sum
+
+: sum ( array len -- sum )
+  0 -rot cells over + swap do i @ + cell +loop ;
+
+: max-sub ( array len -- sub len )
+  over 0 best 2!  0 best-sum !
+  dup 1 do                  \ foreach length
+    2dup i - 1+ cells over + swap do   \ foreach start
+      i j sum
+      dup best-sum @ > if
+        best-sum !
+        i j best 2!
+      else drop then
+    cell +loop
+  loop
+  2drop best 2@ ;
+
+: .array  ." [" dup 0 ?do over i cells + @ . loop ." ] = " sum . ;
+
+create test  -1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1 ,
+create test2 -1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , 99 ,
diff --git a/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum-2.fth b/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum-2.fth
new file mode 100644
index 0000000000..436045a6d4
--- /dev/null
+++ b/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum-2.fth
@@ -0,0 +1,2 @@
+test 11 max-sub .array [3 5 6 -2 -1 4 ] = 15 ok
+test2 11 max-sub .array [3 5 6 -2 -1 4 -4 2 99 ] = 112 ok
diff --git a/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum.fth b/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum.fth
deleted file mode 100644
index 378df2114a..0000000000
--- a/Task/Greatest-subsequential-sum/Forth/greatest-subsequential-sum.fth
+++ /dev/null
@@ -1,24 +0,0 @@
-2variable best
-variable best-sum
-
-: sum ( array len -- sum )
-  0 -rot cells over + swap do i @ + cell +loop ;
-
-: max-sub ( array len -- sub len )
-  over 0 best 2!  0 best-sum !
-  dup 1 do                  \ foreach length
-    2dup i - cells over + swap do   \ foreach start
-      i j sum
-      dup best-sum @ > if
-        best-sum !
-        i j best 2!
-      else drop then
-    cell +loop
-  loop
-  2drop best 2@ ;
-
-: .array  ." [" dup 0 ?do over i cells + @ . loop ." ] = " sum . ;
-
-create test -1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1 ,
-
-test 11 max-sub .array    \ [3 5 6 -2 -1 4 ] = 15
diff --git a/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia b/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia
new file mode 100644
index 0000000000..ce97aac472
--- /dev/null
+++ b/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia
@@ -0,0 +1,14 @@
+const A = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]
+maxval = 0
+maxseq = Int[]
+
+for head=1:length(A), tail=head:length(A)
+    val = sum(A[head:tail])
+    if val > maxval
+        maxval = val
+        maxseq = A[head:tail]
+    end
+end
+
+println(maxseq)
+println(maxval)
diff --git a/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-1.rexx b/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-1.rexx
index bde0344a92..bf9a51f4c9 100644
--- a/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-1.rexx
+++ b/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-1.rexx
@@ -1,14 +1,14 @@
-/*REXX program finds the  shortest  greatest continuous subsequence sum.*/
-parse arg @;         w=words(@)        /*get arg list;  # words in list.*/
-say 'words='w    "   list="@           /*show #words &  LIST to console.*/
-sum=0;  L=0;  at=w+1                   /*default sum, length, starts at.*/
-                                       /* [↓]  process the list of nums.*/
-  do j=1  for w;     f=word(@,j)       /*select one number at a time.   */
-      do k=j  to w                     /* [↓]  process a sub─list of #s.*/
-      s=f;           do m=j+1  to k;  s=s+word(@,m);     end  /*m*/
+/*REXX program finds the  shortest  greatest continuous subsequence sum.      */
+parse arg @;         w=words(@)        /*get arg list;  number words in list. */
+say 'words='w    "   list="@           /*show number words & LIST to terminal,*/
+sum=0;  L=0;  at=w+1                   /*default sum, length, and "starts at".*/
+                                       /* [↓]  process the list of numbers.   */
+  do j=1  for w;     f=word(@,j)       /*select one number at a time from list*/
+      do k=j  to w;  s=f               /* [↓]  process a sub─list of numbers. */
+                     do m=j+1  to k;  s=s+word(@,m);     end  /*m*/
       if s>sum  then do;       sum=s;  at=j;  L=k-j+1;   end
-      end   /*k*/                      /* [↑]  chose greatest sum of #s.*/
+      end   /*k*/                      /* [↑]  chose greatest sum of numbers. */
   end       /*j*/
 
-$=subword(@,at,L);    if $==''  then $="[NULL]"         /*Englishize it.*/
-say;  say 'sum='sum/1  "   sequence="$ /*stick a fork in it, we're done.*/
+$=subword(@,at,L);    if $==''  then $="[NULL]"       /*Englishize the  null. */
+say;  say 'sum='sum/1  "   sequence="$ /*stick a fork in it,  we're all done. */
diff --git a/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-2.rexx b/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-2.rexx
index eae256b02b..1c1e8ee026 100644
--- a/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-2.rexx
+++ b/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-2.rexx
@@ -1,14 +1,14 @@
-/*REXX program finds the  longest  greatest continuous subsequence  sum.*/
-parse arg @;         w=words(@)        /*get arg list;  # words in list.*/
-say 'words='w    "   list="@           /*show #words &  LIST to console.*/
-sum=0;  L=0;  at=w+1                   /*default sum, length, starts at.*/
-                                       /* [↓]  process the list of nums.*/
-  do j=1  for w;     f=word(@,j)       /*select one number at a time.   */
-      do k=j  to w;  _=k-j+1           /* [↓]  process a sub─list of #s.*/
-      s=f;           do m=j+1  to k;   s=s+word(@,m);    end  /*m*/
+/*REXX program finds the  longest  greatest continuous subsequence  sum.      */
+parse arg @;         w=words(@)        /*get arg list;  number words in list. */
+say 'words='w    "   list="@           /*show number words & LIST to terminal,*/
+sum=0;  L=0;  at=w+1                   /*default sum, length, and "starts at".*/
+                                       /* [↓]  process the list of numbers.   */
+  do j=1  for w;     f=word(@,j)       /*select one number at a time from list*/
+      do k=j  to w;  _=k-j+1;     s=f  /* [↓]  process a sub─list of numbers. */
+                     do m=j+1  to k;   s=s+word(@,m);    end  /*m*/
       if (s==sum & _>L)  |  s>sum  then do;  sum=s;   at=j;    L=_;    end
-      end   /*k*/                      /* [↑] chose longest greatest sum*/
+      end   /*k*/                      /* [↑]  chose the longest greatest sum.*/
   end       /*j*/
 
-$=subword(@,at,L);    if $==''  then $="[NULL]"         /*Englishize it.*/
-say;  say 'sum='sum/1  "   sequence="$ /*stick a fork in it, we're done.*/
+$=subword(@,at,L);    if $==''  then $="[NULL]"       /*Englishize the  null. */
+say;  say 'sum='sum/1  "   sequence="$ /*stick a fork in it,  we're all done. */
diff --git a/Task/Greatest-subsequential-sum/Rust/greatest-subsequential-sum.rust b/Task/Greatest-subsequential-sum/Rust/greatest-subsequential-sum.rust
new file mode 100644
index 0000000000..937a846518
--- /dev/null
+++ b/Task/Greatest-subsequential-sum/Rust/greatest-subsequential-sum.rust
@@ -0,0 +1,19 @@
+fn main() {
+    let nums = [1,2,39,34,20, -20, -16, 35, 0];
+
+    let mut max = 0;
+    let mut boundaries = 0..0;
+
+    for length in 0..nums.len() {
+        for start in 0..nums.len()-length {
+            let sum = (&nums[start..start+length]).iter()
+                .fold(0, |sum, elem| sum+elem);
+            if sum > max {
+                max = sum;
+                boundaries = start..start+length;
+            }
+        }
+    }
+
+    println!("Max subsequence sum: {} for {:?}", max, &nums[boundaries]);;
+}
diff --git a/Task/Greyscale-bars-Display/Perl-6/greyscale-bars-display.pl6 b/Task/Greyscale-bars-Display/Perl-6/greyscale-bars-display.pl6
index b40ba1f5b2..7cbcf11161 100644
--- a/Task/Greyscale-bars-Display/Perl-6/greyscale-bars-display.pl6
+++ b/Task/Greyscale-bars-Display/Perl-6/greyscale-bars-display.pl6
@@ -1,5 +1,5 @@
 my $wininfo = qx[xwininfo -root];
-my ($width,$height) = ($wininfo ~~ /'Width: ' (\d+) .*? 'Height: ' (\d+)/)[];
+my ($width,$height) = ($wininfo ~~ /'Width: ' (\d+) .*? 'Height: ' (\d+)/).list;
 ($width,$height) = 1280,768 unless $width;
 
 my $PGM = open "greybars.pgm", :w or die "Can't create greybars.pgm: $!";
@@ -35,5 +35,5 @@ shell "eog -f greybars.pgm";
 
 sub divvy($all, $div) {
     my @marks = ((1/$div,2/$div ... 1) X* $all)».round;
-    @marks Z- 0,@marks;
+    @marks Z- 0,|@marks;
 }
diff --git a/Task/Guess-the-number-With-feedback--player-/AppleScript/guess-the-number-with-feedback--player-.applescript b/Task/Guess-the-number-With-feedback--player-/AppleScript/guess-the-number-with-feedback--player-.applescript
new file mode 100644
index 0000000000..ff3f71e926
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback--player-/AppleScript/guess-the-number-with-feedback--player-.applescript
@@ -0,0 +1,31 @@
+-- defining the range of the number to be guessed
+property minLimit : 1
+property maxLimit : 100
+
+on run
+	-- ask the user to think of  a number in the given range
+	display dialog "Please think of a number between " & minLimit & " and " & maxLimit
+	
+	-- prepare a variable for the lowest guessed value	
+	set lowGuess to minLimit
+	-- prepare a variable for the highest guessed value	
+	set highGuess to maxLimit
+	
+	repeat
+		-- guess a number inside the logical range
+		set computersGuess to (random number from lowGuess to highGuess)
+		-- ask the user to check my guess
+		set guessResult to button returned of (display dialog "I guess " & computersGuess & "!" & return & "What do you think?" buttons {"Lower", "Correct", "Higher"})
+		if guessResult = "Lower" then
+			-- the number is less than the guess, switch the upper limit to the guess
+			set highGuess to computersGuess
+		else if guessResult = "Higher" then
+			-- the number is greater than the guess, switch the lower limit to the guess
+			set lowGuess to computersGuess
+		else if guessResult = "Correct" then
+			-- the computer guessed the number, beep and exit
+			beep
+			exit repeat
+		end if
+	end repeat
+end run
diff --git a/Task/Guess-the-number-With-feedback--player-/Elixir/guess-the-number-with-feedback--player-.elixir b/Task/Guess-the-number-With-feedback--player-/Elixir/guess-the-number-with-feedback--player-.elixir
new file mode 100644
index 0000000000..ec1a14f692
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback--player-/Elixir/guess-the-number-with-feedback--player-.elixir
@@ -0,0 +1,21 @@
+defmodule Game do
+  def guess(a..b) do
+    :random.seed(:os.timestamp)
+    x = :random.uniform(b-a+1) + a - 1
+    guess(x, a..b)
+  end
+
+  defp guess(x, a..b) when x == div(a+b, 2) do
+    IO.puts "Is it #{x}?"
+    IO.puts " So the number is: #{x}"
+  end
+  defp guess(x, a..b) when x < div(a+b, 2) do
+    IO.puts "Is it #{div(a+b, 2)}? Too High."
+    guess(x, a..div(a+b, 2))
+  end
+  defp guess(x, a..b) when x > div(a+b, 2) do
+    IO.puts "Is it #{div(a+b, 2)}? Too Low."
+    guess(x, div(a+b+1, 2)..b)
+  end
+end
+Game.guess(1..100)
diff --git a/Task/Guess-the-number-With-feedback--player-/Haskell/guess-the-number-with-feedback--player--1.hs b/Task/Guess-the-number-With-feedback--player-/Haskell/guess-the-number-with-feedback--player--1.hs
new file mode 100644
index 0000000000..1dd77c8ea9
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback--player-/Haskell/guess-the-number-with-feedback--player--1.hs
@@ -0,0 +1,23 @@
+main :: IO ()
+main = do
+    putStrLn "Please enter the range:"
+    putStr   "From: "
+    from <- getLine
+    putStr   "To: "
+    to   <- getLine
+    case (from, to) of
+         (_) | [(from', "")] <- reads from
+             , [(to'  , "")] <- reads to
+             , from'         < to' -> loop from' to'
+         (_)  -> putStrLn "Invalid input." >> main
+
+loop :: Integer -> Integer -> IO ()
+loop from to = do
+    let guess = (to + from) `div` 2
+    putStrLn $ "Is it " ++ show guess ++ "? ((l)ower, (c)orrect, (h)igher)"
+    answer <- getLine
+    case answer of
+        "c" -> putStrLn "Awesome!"
+        "l" -> loop from  guess
+        "h" -> loop guess to
+        (_) -> putStrLn "Invalid answer." >> loop from to
diff --git a/Task/Guess-the-number-With-feedback--player-/Haskell/guess-the-number-with-feedback--player--2.hs b/Task/Guess-the-number-With-feedback--player-/Haskell/guess-the-number-with-feedback--player--2.hs
new file mode 100644
index 0000000000..3bd823e698
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback--player-/Haskell/guess-the-number-with-feedback--player--2.hs
@@ -0,0 +1,7 @@
+main = f 0 100
+  where f x y = let g = div (x + y) 2 in
+          putStrLn (show g ++ "? (l,h,c)") >>
+          getLine >>= \a -> case a of
+                              "l" -> f x g
+                              "h" -> f g y
+                              "c" -> putStrLn "Yay!"
diff --git a/Task/Guess-the-number-With-feedback--player-/Julia/guess-the-number-with-feedback--player-.julia b/Task/Guess-the-number-With-feedback--player-/Julia/guess-the-number-with-feedback--player-.julia
new file mode 100644
index 0000000000..e4e15db444
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback--player-/Julia/guess-the-number-with-feedback--player-.julia
@@ -0,0 +1,48 @@
+print("Enter an upper bound: ")
+lower = 0
+input = readline()
+upper = parse(Int, input)
+
+if upper < 1
+    throw(DomainError)
+end
+
+attempts = 1
+print("Think of a number, ", lower, "--", upper, ", then press ENTER.")
+readline()
+const maxattempts = round(Int, ceil(-log(1 / (upper - lower)) / log(2)))
+println("I will need at most ", maxattempts, " attempts ",
+    "(⌈-log(1 / (", upper, " - ", lower, ")) / log(2)⌉ = ",
+    maxattempts, ").\n")
+previous = -1
+guess = -1
+
+while true
+    previous = guess
+    guess = lower + round(Int, (upper - lower) / 2, RoundNearestTiesUp)
+
+    if guess == previous || attempts > maxattempts
+        println("\nThis is impossible; did you forget your number?")
+        exit()
+    end
+
+    print("I guess ", guess, ".\n[l]ower, [h]igher, or [c]orrect? ")
+    input = chomp(readline())
+
+    while input ∉ ["c", "l", "h"]
+        print("Please enter one of \"c\", \"l\", or \"h\". ")
+        input = chomp(readline())
+    end
+
+    if input == "l"
+        upper = guess
+    elseif input == "h"
+        lower = guess
+    else
+        break
+    end
+
+    attempts += 1
+end
+
+println("\nI win after ", attempts, attempts == 1 ? " attempt." : " attempts.")
diff --git a/Task/Guess-the-number-With-feedback--player-/Rust/guess-the-number-with-feedback--player-.rust b/Task/Guess-the-number-With-feedback--player-/Rust/guess-the-number-with-feedback--player-.rust
index 8acea45316..b3f840b364 100644
--- a/Task/Guess-the-number-With-feedback--player-/Rust/guess-the-number-with-feedback--player-.rust
+++ b/Task/Guess-the-number-With-feedback--player-/Rust/guess-the-number-with-feedback--player-.rust
@@ -1,21 +1,22 @@
-use std::io::stdio::stdin;
+use std::io::stdin;
 
 const MIN: isize = 1;
 const MAX: isize = 100;
 
 fn main() {
-    let mut stdin = stdin();
     loop {
         let mut min = MIN;
         let mut max = MAX;
-        let mut num_guesses = 1is;
+        let mut num_guesses = 1;
         println!("Please think of a number between {} and {}", min, max);
         loop {
             let guess = (min + max) / 2;
             println!("Is it {}?", guess);
             println!("(type h if my guess is too high, l if too low, e if equal and q to quit)");
 
-            match stdin.read_line().ok().and_then(|line| Some(line.as_slice().char_at(0).to_uppercase())) {
+            let mut line = String::new();
+            stdin().read_line(&mut line).unwrap();
+            match Some(line.chars().next().unwrap().to_uppercase().next().unwrap()) {
                 Some('H') => {
                     max = guess - 1;
                     num_guesses += 1;
diff --git a/Task/Guess-the-number-With-feedback/AppleScript/guess-the-number-with-feedback.applescript b/Task/Guess-the-number-With-feedback/AppleScript/guess-the-number-with-feedback.applescript
new file mode 100644
index 0000000000..627364af82
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback/AppleScript/guess-the-number-with-feedback.applescript
@@ -0,0 +1,39 @@
+-- defining the range of the number to be guessed
+property minLimit : 1
+property maxLimit : 100
+
+on run
+	-- define the number to be guessed
+	set numberToGuess to (random number from minLimit to maxLimit)
+	-- prepare a variable to store the user's answer
+	set guessedNumber to missing value
+	-- prepare a variable for feedback
+	set tip to ""
+	-- start a loop (will be exited by using "exit repeat" after a correct guess)
+	repeat
+		-- ask the user for his/her guess, the variable tip contains text after first guess only
+		set usersChoice to (text returned of (display dialog "Guess the number between " & minLimit & " and " & maxLimit & " inclusive" & return & tip default answer "" buttons {"Check"} default button "Check"))
+		-- try to convert the given answer to an integer and compare it the number to be guessed
+		try
+			set guessedNumber to usersChoice as integer
+			if guessedNumber is greater than maxLimit or guessedNumber is less than minLimit then
+				-- the user guessed a number outside the given range
+				set tip to "(Tipp: Enter a number between " & minLimit & " and " & maxLimit & ")"
+			else if guessedNumber is less than numberToGuess then
+				-- the user guessed a number less than the correct number
+				set tip to "(Tipp: The number is greater than " & guessedNumber & ")"
+			else if guessedNumber is greater than numberToGuess then
+				-- the user guessed a number greater than the correct number
+				set tip to "(Tipp: The number is less than " & guessedNumber & ")"
+			else if guessedNumber is equal to numberToGuess then
+				-- the user guessed the correct number and gets informed
+				display dialog "Well guessed! The number was " & numberToGuess buttons {"OK"} default button "OK"
+				-- exit the loop (quits this application)
+				exit repeat
+			end if
+		on error
+			-- something went wrong, remind the user to enter a numeric value
+			set tip to "(Tipp: Enter a number between " & minLimit & " and " & maxLimit & ")"
+		end try
+	end repeat
+end run
diff --git a/Task/Guess-the-number-With-feedback/DCL/guess-the-number-with-feedback.dcl b/Task/Guess-the-number-With-feedback/DCL/guess-the-number-with-feedback.dcl
new file mode 100644
index 0000000000..231e2a88f3
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback/DCL/guess-the-number-with-feedback.dcl
@@ -0,0 +1,15 @@
+$ rnd = f$extract( 21, 2, f$time() )
+$ count = 0
+$ loop:
+$ inquire guess "guess what number between 0 and 99 inclusive I am thinking of"
+$ guess = f$integer( guess )
+$ if guess .lt. 0 .or. guess .gt. 99
+$ then
+$  write sys$output "out of range"
+$  goto loop
+$ endif
+$ count = count + 1
+$ if guess .lt. rnd then $ write sys$output "too small"
+$ if guess .gt. rnd then $ write sys$output "too large"
+$ if guess .ne. rnd then $ goto loop
+$ write sys$output "it only took you ", count, " guesses"
diff --git a/Task/Guess-the-number-With-feedback/Ela/guess-the-number-with-feedback.ela b/Task/Guess-the-number-With-feedback/Ela/guess-the-number-with-feedback.ela
index dbf8419b24..c74b147043 100644
--- a/Task/Guess-the-number-With-feedback/Ela/guess-the-number-with-feedback.ela
+++ b/Task/Guess-the-number-With-feedback/Ela/guess-the-number-with-feedback.ela
@@ -1,31 +1,36 @@
-open random core console string datetime read
+open string datetime random core monad io
 
-rnd' v = rnd s 1 v where s = milliseconds <| datetime.now()
+guess () = do
+  putStrLn "What's the upper bound?"
+  ub <- readAny
+  main ub
+  where main ub
+          | ub < 0 = "Bound should be greater than 0."
+          | else = do
+              putStrLn $ format "Guess a number from 1 to {0}" ub
+              dt <- datetime.now
+              guesser (rnd (milliseconds $ dt) 1 ub)
+        guesser v = do
+          x <- readAny
+          if x == v then
+              cont ()
+            else if x < v then
+              do putStrLn "Too small!"
+                 guesser v
+            else
+              do putStrLn "Too big!"
+                 guesser v
+        cont () = do
+          putStrLn "Correct! Do you wish to continue (Y/N)?"
+          ask ()
+        ask () = do
+          a <- readStr
+          if a == "y" || a == "Y" then
+              guess ()
+            else if a == "n" || a == "N" then
+              do putStrLn "Bye!"
+            else
+              do putStrLn "Say what?"
+                 ask ()
 
-start () =
-    match bound() with
-          Some v = writen ("Guess a number from 1 to " ++ show v) `seq` (guess <| rnd' v)
-          None   = start()
-
-bound () =
-    writen "What's the upper bound?" `seq` (bound' <| readStr <| readn())
-    where bound' v | v <= 0 = writen "Bound should be greater than 0." `seq` None
-                   | else   = Some v
-
-success v =
-    writen "Correct! Do you want to continue? (Y/N)" `seq` ask()
-    where ask () = read <| upper <| readn()
-          read "Y" = start()
-          read "N" = writen "Bye!"
-          read x   = writen "Say what?" `seq` ask()
-
-failed v n =
-    writen ("No, this is not " ++ show v ++ ". " ++ hint) `seq` guess n
-    where hint | v < n = "Try bigger."
-               | else  = "Try smaller."
-
-guess n = g <| readStr <| readn()
-    where g v | v == n = success v
-              | else   = failed v n
-
-start()
+guess () ::: IO
diff --git a/Task/Guess-the-number-With-feedback/Elixir/guess-the-number-with-feedback.elixir b/Task/Guess-the-number-With-feedback/Elixir/guess-the-number-with-feedback.elixir
index 362ba62bea..2b5a0a31c8 100644
--- a/Task/Guess-the-number-With-feedback/Elixir/guess-the-number-with-feedback.elixir
+++ b/Task/Guess-the-number-With-feedback/Elixir/guess-the-number-with-feedback.elixir
@@ -1,21 +1,15 @@
 defmodule GuessingGame do
-  def init() do
-    :random.seed(:erlang.now())
-  end
   def play(lower, upper) do
+    :random.seed(:os.timestamp)
     play(lower, upper, :random.uniform(upper + 1 - lower) + lower - 1)
   end
   defp play(lower, upper, number) do
     guess = Integer.parse(IO.gets "Guess a number (#{lower}-#{upper}): ")
     case guess do
-      {n, _} when n == number ->
+      {^number, _} ->
         IO.puts "Well guessed!"
-      {n, _} when lower <= n and n <= upper ->
-        if n > number do
-          IO.puts "Too high."
-        else
-          IO.puts "Too low."
-        end
+      {n, _} when n in lower..upper ->
+        IO.puts if n > number, do: "Too high.", else:  "Too low."
         play(lower, upper, number)
       _ ->
         IO.puts "Guess not in valid range."
@@ -24,5 +18,4 @@ defmodule GuessingGame do
   end
 end
 
-GuessingGame.init()
 GuessingGame.play(1, 100)
diff --git a/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia b/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia
index 3f7ed2aed0..f7a3e1882f 100644
--- a/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia
+++ b/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia
@@ -3,8 +3,9 @@ function guess_feedback(n)
   print("I choose a number between 1 and $n\nYour guess? ")
   while((guess = chomp(readline(STDIN))) != string(number))
     isdigit(guess) ?
-      print("Too $(int(guess) < number ? "small" : "big")\nNew guess?  ") :
-      print("Enter an integer please\nNew guess?  ")
+      print("Too $(parse(Int,guess) < number ? "small" : "big")") :
+      print("Enter an integer please")
+  print("\nNew guess? ")
   end
   print("you guessed right!")
 end
diff --git a/Task/Guess-the-number-With-feedback/Maple/guess-the-number-with-feedback-1.maple b/Task/Guess-the-number-With-feedback/Maple/guess-the-number-with-feedback-1.maple
new file mode 100644
index 0000000000..06690c77c5
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback/Maple/guess-the-number-with-feedback-1.maple
@@ -0,0 +1,17 @@
+GuessANumber := proc(low, high)
+    local number, input;
+    randomize():
+    printf( "Guess a number between %d and %d:\n:> ", low, high );
+    number := rand(low..high)();
+    do
+        input := parse(readline());
+        if input > number then
+            printf("Too high, try again!\n:> ");
+        elif input < number then
+            printf("Too low, try again!\n:> ");
+        else
+            printf("Well guessed! The answer was %d.\n", number);
+            break;
+        end if;
+    end do:
+end proc:
diff --git a/Task/Guess-the-number-With-feedback/Maple/guess-the-number-with-feedback-2.maple b/Task/Guess-the-number-With-feedback/Maple/guess-the-number-with-feedback-2.maple
new file mode 100644
index 0000000000..3e56bf48ef
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback/Maple/guess-the-number-with-feedback-2.maple
@@ -0,0 +1 @@
+GuessANumber(2,5);
diff --git a/Task/Guess-the-number-With-feedback/R/guess-the-number-with-feedback.r b/Task/Guess-the-number-With-feedback/R/guess-the-number-with-feedback.r
new file mode 100644
index 0000000000..2c615ebe64
--- /dev/null
+++ b/Task/Guess-the-number-With-feedback/R/guess-the-number-with-feedback.r
@@ -0,0 +1,15 @@
+GuessANumber <- function( low, high ) {
+  print( sprintf("Guess a number between %d and %d until you get it right", low, high ) );
+  X <- low:high;
+  number <- sample( X, 1 );
+  repeat {
+    input <- as.numeric(readline());
+    if (input > number) {
+      print("Too high, try again"); }
+    else if (input < number) {
+      print("Too low, try again");}
+    else {
+      print("Correct!");
+      break; }
+  }
+}
diff --git a/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust b/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust
index 89fd9bcce8..6aadccbaee 100644
--- a/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust
+++ b/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust
@@ -1,39 +1,37 @@
-use std::io::IoResult;
-use std::io::stdio::stdin;
-use std::rand::{Rng, thread_rng};
-use std::str::FromStr;
+use std::io::stdin;
+use rand::{Rng, thread_rng};
+
+extern crate rand;
 
 const LOWEST: isize = 1;
 const HIGHEST: isize = 100;
 
 fn main() {
-	let mut rng = thread_rng();
-	let mut stdin = stdin();
-
-	loop {
-
-		let number: isize = rng.gen_range(LOWEST, HIGHEST + 1);
-		let mut num_guesses = 0is;
-
-		println!("I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST);
-
-		loop {
-
-			num_guesses += 1;
-
-			let line: IoResult = stdin.read_line();
-			let input: Option = line.ok().map_or(None, |line| line.as_slice().trim().parse());
-
-			match input {
-				None => println!("numbers only, please"),
-				Some(n) if n == number => {
-					println!("you got it in {} tries!", num_guesses);
-					break;
-				}
-				Some(n) if n < number => println!("too low!"),
-				Some(n) if n > number => println!("too high!"),
-				Some(_) => println!("something went wrong")
-			}
-		}
-	}
+    let mut rng = thread_rng();
+
+    loop {
+        let number: isize = rng.gen_range(LOWEST, HIGHEST + 1);
+        let mut num_guesses = 0;
+
+        println!("I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST);
+
+        loop {
+            num_guesses += 1;
+
+            let mut line = String::new();
+            let res = stdin().read_line(&mut line);
+            let input: Option = res.ok().map_or(None, |_| line.trim().parse().ok());
+
+            match input {
+                None => println!("numbers only, please"),
+                Some(n) if n == number => {
+                    println!("you got it in {} tries!", num_guesses);
+                    break;
+                }
+                Some(n) if n < number => println!("too low!"),
+                Some(n) if n > number => println!("too high!"),
+                Some(_) => println!("something went wrong")
+            }
+        }
+    }
 }
diff --git a/Task/Guess-the-number/AppleScript/guess-the-number.applescript b/Task/Guess-the-number/AppleScript/guess-the-number.applescript
new file mode 100644
index 0000000000..c4e42d36f4
--- /dev/null
+++ b/Task/Guess-the-number/AppleScript/guess-the-number.applescript
@@ -0,0 +1,25 @@
+on run
+	-- define the number to be guessed
+	set numberToGuess to (random number from 1 to 10)
+	-- prepare a variable to store the user's answer
+	set guessedNumber to missing value
+	-- start a loop (will be exited by using "exit repeat" after a correct guess)
+	repeat
+		try
+			-- ask the user for his/her guess
+			set usersChoice to (text returned of (display dialog "Guess the number between 1 and 10 inclusive" default answer "" buttons {"Check"} default button "Check"))
+			-- try to convert the given answer to an integer
+			set guessedNumber to usersChoice as integer
+		on error
+			-- something gone wrong, overwrite user's answer with a non-matching value
+			set guessedNumber to missing value
+		end try
+		-- decide if the user's answer was the right one
+		if guessedNumber is equal to numberToGuess then
+			-- the user guessed the correct number and gets informed
+			display dialog "Well guessed! The number was " & numberToGuess buttons {"OK"} default button "OK"
+			-- exit the loop (quits this application)
+			exit repeat
+		end if
+	end repeat
+end run
diff --git a/Task/Guess-the-number/Bracmat/guess-the-number.bracmat b/Task/Guess-the-number/Bracmat/guess-the-number.bracmat
new file mode 100644
index 0000000000..16c42c52d6
--- /dev/null
+++ b/Task/Guess-the-number/Bracmat/guess-the-number.bracmat
@@ -0,0 +1,12 @@
+( ( GuessTheNumber
+  =   mynumber
+    .   clk$:?mynumber
+      & mod$(!mynumber*den$!mynumber.10)+1:?mynumber
+      &   whl
+        ' ( put'"Guess my number:"
+          & get':~!mynumber:?K
+          )
+      & out'"Well guessed!"
+  )
+& GuessTheNumber$
+);
diff --git a/Task/Guess-the-number/DCL/guess-the-number.dcl b/Task/Guess-the-number/DCL/guess-the-number.dcl
new file mode 100644
index 0000000000..6a6d63da79
--- /dev/null
+++ b/Task/Guess-the-number/DCL/guess-the-number.dcl
@@ -0,0 +1,6 @@
+$ time = f$time()
+$ number = f$extract( f$length( time ) - 1, 1, time ) + 1
+$ loop:
+$  inquire guess "enter a guess (integer 1-10) "
+$  if guess .nes. number then $ goto loop
+$ write sys$output "Well guessed!"
diff --git a/Task/Guess-the-number/Eiffel/guess-the-number.e b/Task/Guess-the-number/Eiffel/guess-the-number.e
index 72de7a0341..85e3cce2ef 100644
--- a/Task/Guess-the-number/Eiffel/guess-the-number.e
+++ b/Task/Guess-the-number/Eiffel/guess-the-number.e
@@ -1,33 +1,36 @@
 class
 	APPLICATION
 
-inherit
-	ARGUMENTS
-
 create
 	make
 
-feature {NONE} -- Initialization
+feature {NONE}
 
 	make
-			-- Run application.
 		local
-		    number : INTEGER_32 -- Number to guess
-		    random : RANDOM
+			number, seed: INTEGER_32
+			random: RANDOM
 		do
-		    create random.make
-                    number := (random.double_item*10.0).truncated_to_integer + 1
-                    print ("I'm thinking of a number between 1 and 10.%N")
-		    print ("Please guess the number!%N")
-
-		    from io.read_integer
-		    until io.last_integer = number
-		    loop
-			    print ("Sorry. Please guess again!%N")
-			    io.read_integer
-		    end
-			
-                    print ("Correct!%N")
+			from
+			until
+				seed > 0
+			loop
+				io.put_string ("Enter a positive integer.%NYour play will be generated from it.%N")
+				io.read_integer
+				seed := io.last_integer
+			end
+			create random.set_seed (seed)
+			number := (random.double_i_th (seed) * 10.0).truncated_to_integer + 1
+			io.put_string ("Please guess the number!%N")
+			from
+				io.read_integer
+			until
+				io.last_integer = number
+			loop
+				io.put_string ("Please guess again!%N")
+				io.read_integer
+			end
+			io.put_string ("Well guessed!%N")
 		end
 
 end
diff --git a/Task/Guess-the-number/Elixir/guess-the-number.elixir b/Task/Guess-the-number/Elixir/guess-the-number.elixir
index fddfc6bfbb..454b4f9737 100644
--- a/Task/Guess-the-number/Elixir/guess-the-number.elixir
+++ b/Task/Guess-the-number/Elixir/guess-the-number.elixir
@@ -1,16 +1,15 @@
 defmodule GuessingGame do
-  def init() do
-    :random.seed(:erlang.now())
-  end
-  def play() do
+  def play do
+    :random.seed(:os.timestamp)
     play(:random.uniform(10))
   end
+
   defp play(number) do
     guess = Integer.parse(IO.gets "Guess a number (1-10): ")
     case guess do
-      {n, _} when n == number ->
+      {^number, _} ->
         IO.puts "Well guessed!"
-      {n, _} when 1 <= n and n <= 10 ->
+      {n, _} when n in 1..10 ->
         IO.puts "That's not it."
         play(number)
       _ ->
@@ -20,5 +19,4 @@ defmodule GuessingGame do
   end
 end
 
-GuessingGame.init()
-GuessingGame.play()
+GuessingGame.play
diff --git a/Task/Guess-the-number/Maple/guess-the-number-1.maple b/Task/Guess-the-number/Maple/guess-the-number-1.maple
new file mode 100644
index 0000000000..aaee5ec8dc
--- /dev/null
+++ b/Task/Guess-the-number/Maple/guess-the-number-1.maple
@@ -0,0 +1,10 @@
+GuessNumber := proc()
+    local number;
+    randomize():
+    printf("Guess a number between 1 and 10 until you get it right:\n:");
+    number := rand(1..10)();
+    while parse(readline()) <> number do
+        printf("Try again!\n:");
+    end do:
+    printf("Well guessed! The answer was %d.\n", number);
+end proc:
diff --git a/Task/Guess-the-number/Maple/guess-the-number-2.maple b/Task/Guess-the-number/Maple/guess-the-number-2.maple
new file mode 100644
index 0000000000..013939352d
--- /dev/null
+++ b/Task/Guess-the-number/Maple/guess-the-number-2.maple
@@ -0,0 +1 @@
+GuessNumber();
diff --git a/Task/Guess-the-number/PureBasic/guess-the-number.purebasic b/Task/Guess-the-number/PureBasic/guess-the-number.purebasic
index 9cb25fb783..3faa7a9284 100644
--- a/Task/Guess-the-number/PureBasic/guess-the-number.purebasic
+++ b/Task/Guess-the-number/PureBasic/guess-the-number.purebasic
@@ -1,7 +1,13 @@
-TheNumber=Random(9)+1
+If OpenConsole()
+  Define TheNumber=Random(9)+1
 
-Repeat
-  Print("Guess the number: ")
-Until TheNumber=Val(Input())
+  PrintN("I've picked a number from 1 to 10." + #CRLF$)
+  Repeat
+    Print("Guess the number: ")
+  Until TheNumber=Val(Input())
 
-PrintN("Well guessed!")
+  PrintN("Well guessed!")
+
+  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
+  CloseConsole()
+EndIf
diff --git a/Task/Guess-the-number/Rust/guess-the-number.rust b/Task/Guess-the-number/Rust/guess-the-number.rust
index 6c238d7c88..88f0f41581 100644
--- a/Task/Guess-the-number/Rust/guess-the-number.rust
+++ b/Task/Guess-the-number/Rust/guess-the-number.rust
@@ -1,26 +1,25 @@
-use std::num;
-use std::rand::random;
-use std::io::stdio::stdin;
+extern crate rand;
 
 fn main() {
-	println!("Type in an integer between 1 and 10 and press enter.");
+    println!("Type in an integer between 1 and 10 and press enter.");
 
-	let n = num::abs(random::()) % 10 + 1;
-	loop {
-		let line = stdin().read_line().unwrap();
-		let option: Option = from_str(line.as_slice().trim());
-		match option {
-			Some(guess) => {
-				if guess < 1 || guess > 10 {
-					println!("Guess is out of bounds; try again.");
-				} else if guess == n {
-					println!("Well guessed!");
-					break;
-				} else {
-					println!("Wrong! Try again.");
-				}
-			},
-			None => println!("Invalid input; try again.")
-		}
-	}
+    let n = rand::random::() % 10 + 1;
+    loop {
+        let mut line = String::new();
+        std::io::stdin().read_line(&mut line).unwrap();
+        let option: Result = line.trim().parse();
+        match option {
+            Ok(guess) => {
+                if guess < 1 || guess > 10 {
+                    println!("Guess is out of bounds; try again.");
+                } else if guess == n {
+                    println!("Well guessed!");
+                    break;
+                } else {
+                    println!("Wrong! Try again.");
+                }
+            },
+            Err(_) => println!("Invalid input; try again.")
+        }
+    }
 }
diff --git a/Task/Guess-the-number/Self/guess-the-number-1.self b/Task/Guess-the-number/Self/guess-the-number-1.self
new file mode 100644
index 0000000000..41ebffc93b
--- /dev/null
+++ b/Task/Guess-the-number/Self/guess-the-number-1.self
@@ -0,0 +1,13 @@
+(|
+parent* = traits clonable.
+copy = (resend.copy secretNumber: random integerBetween: 1 And: 10).
+secretNumber.
+
+ask             = ((userQuery askString: 'Guess the Number: ') asInteger).
+reportSuccess   = (userQuery report: 'You got it!').
+reportFailure   = (userQuery report: 'Nope. Guess again.').
+sayIntroduction = (userQuery report: 'Try to guess my secret number between 1 and 10.').
+
+hasGuessed = ( [ask = secretNumber] onReturn: [|:r| r ifTrue: [reportSuccess] False: [reportFailure]] ).
+run  = (sayIntroduction. [hasGuessed] whileFalse)
+|) copy run
diff --git a/Task/Guess-the-number/Self/guess-the-number-2.self b/Task/Guess-the-number/Self/guess-the-number-2.self
new file mode 100644
index 0000000000..fa4ce3d7cf
--- /dev/null
+++ b/Task/Guess-the-number/Self/guess-the-number-2.self
@@ -0,0 +1,6 @@
+| n |
+userQuery report: 'Try to guess my secret number between 1 and 10.'.
+n: random integerBetween: 1 And: 10.
+[(userQuery askString: 'Guess the Number.') asInteger = n] whileFalse: [
+    userQuery report: 'Nope. Guess again.'].
+userQuery report: 'You got it!'
diff --git a/Task/Guess-the-number/X86-Assembly/guess-the-number.x86 b/Task/Guess-the-number/X86-Assembly/guess-the-number.x86
new file mode 100644
index 0000000000..fa9978d07e
--- /dev/null
+++ b/Task/Guess-the-number/X86-Assembly/guess-the-number.x86
@@ -0,0 +1,77 @@
+global _start
+
+section .data
+
+    rand dd 0
+    guess dd 0
+    msg1 db "Guess my number (1-10)", 10
+    len1 equ $ - msg1
+    msg2 db "Wrong, try again!", 10
+    len2 equ $ - msg2
+    msg3 db "Well guessed!", 10
+    len3 equ $ - msg3
+
+section .text
+
+    _start:
+        ; random number using time
+        mov eax, 13
+        mov ebx, rand
+        int 80h
+        mov eax, [ebx]
+        mov ebx, 10
+        xor edx, edx
+        div ebx
+        inc edx
+        mov [rand], edx
+
+        ; print msg1
+        mov eax, 4
+        mov ebx, 1
+        mov ecx, msg1
+        mov edx, len1
+        int 80h
+
+    input:
+        ; get input
+        mov eax, 3
+        xor ebx, ebx
+        mov ecx, msg1
+        mov edx, 1
+        int 80h
+        mov al, [ecx]
+        cmp al, 48
+        jl check
+        cmp al, 57
+        jg check
+        ; if number
+        sub al, 48
+        xchg eax, [guess]
+        mov ebx, 10
+        mul ebx
+        add [guess], eax
+        jmp input
+
+    check:
+        ; else check number
+        mov eax, 4
+        inc ebx
+        mov ecx, [guess]
+        cmp ecx, [rand]
+        je done
+        ; if not equal
+        mov ecx, msg2
+        mov edx, len2
+        mov dword [guess], 0
+        int 80h
+        jmp input
+
+    done:
+        ; well guessed
+        mov ecx, msg3
+        mov edx, len3
+        int 80h
+        ; exit
+        mov eax, 1
+        xor    ebx, ebx
+        int 80h
diff --git a/Task/HTTP/AWK/http.awk b/Task/HTTP/AWK/http.awk
new file mode 100644
index 0000000000..f41fec9a5f
--- /dev/null
+++ b/Task/HTTP/AWK/http.awk
@@ -0,0 +1,20 @@
+BEGIN {
+  site="en.wikipedia.org"
+  path="/wiki/"
+  name="Rosetta_Code"
+
+  server = "/inet/tcp/0/" site "/80"
+  print "GET " path name " HTTP/1.0" |& server
+  print "Host: " site |& server
+  print "\r\n\r\n" |& server
+
+  while ( (server |& getline fish) > 0 ) {
+    if ( ++scale == 1 )
+      ship = fish
+    else
+      ship = ship "\n" fish
+  }
+  close(server)
+
+  print ship
+}
diff --git a/Task/HTTP/Emacs-Lisp/http.l b/Task/HTTP/Emacs-Lisp/http.l
new file mode 100644
index 0000000000..7324edc254
--- /dev/null
+++ b/Task/HTTP/Emacs-Lisp/http.l
@@ -0,0 +1,6 @@
+(with-current-buffer
+    (url-retrieve-synchronously "http://www.rosettacode.org")
+  (goto-char (point-min))
+  (search-forward "\n\n" nil t)  ;; skip headers
+  (prin1 (buffer-substring (point) (point-max)))
+  (kill-buffer (current-buffer)))
diff --git a/Task/HTTP/J/http.j b/Task/HTTP/J/http.j
index 8514e1f80e..f855acb4f9 100644
--- a/Task/HTTP/J/http.j
+++ b/Task/HTTP/J/http.j
@@ -1 +1,2 @@
+require'web/gethttp'
 gethttp 'http://www.rosettacode.org'
diff --git a/Task/HTTP/NetRexx/http.netrexx b/Task/HTTP/NetRexx/http.netrexx
index 09dcbf863e..b33543e4e9 100644
--- a/Task/HTTP/NetRexx/http.netrexx
+++ b/Task/HTTP/NetRexx/http.netrexx
@@ -1,5 +1,5 @@
 /* NetRexx */
-options replace format comments java crossref savelog symbols binary
+options replace format comments java crossref symbols binary
 
 import java.util.Scanner
 import java.net.URL
diff --git a/Task/HTTP/Scheme/http.ss b/Task/HTTP/Scheme/http-1.ss
similarity index 100%
rename from Task/HTTP/Scheme/http.ss
rename to Task/HTTP/Scheme/http-1.ss
diff --git a/Task/HTTP/Scheme/http-2.ss b/Task/HTTP/Scheme/http-2.ss
new file mode 100644
index 0000000000..ac8e040ae9
--- /dev/null
+++ b/Task/HTTP/Scheme/http-2.ss
@@ -0,0 +1,4 @@
+(use http-client)
+(print
+  (with-input-from-request "http://google.com/"
+                           #f read-string))
diff --git a/Task/HTTPS-Authenticated/Clojure/https-authenticated.clj b/Task/HTTPS-Authenticated/Clojure/https-authenticated.clj
new file mode 100644
index 0000000000..d2226cbd7e
--- /dev/null
+++ b/Task/HTTPS-Authenticated/Clojure/https-authenticated.clj
@@ -0,0 +1,2 @@
+(clj-http.client/get "https://somedomain.com"
+                     {:basic-auth ["user" "pass"]})
diff --git a/Task/HTTPS-Authenticated/Run-BASIC/https-authenticated.run b/Task/HTTPS-Authenticated/Run-BASIC/https-authenticated.run
new file mode 100644
index 0000000000..5bfd8e8e1b
--- /dev/null
+++ b/Task/HTTPS-Authenticated/Run-BASIC/https-authenticated.run
@@ -0,0 +1,32 @@
+html "
+
+ +
LOGIN
UserName" + TEXTBOX #userName, "" +html "
Password:" +PasswordBox #passWord, "" + +html "
" +button #si, "Signin", [doSignin] +html " " +button #ex, "Exit", [exit] +html "
" +WAIT + +[doSignin] +loginUserName$ = trim$(#userName contents$()) +loginPassWord$ = trim$(#passWord contents$()) +if (loginUserName$ = "admin" and loginPassWord$ = "admin" then + print "Login ok" + else + print "invalid User or Pass" + cls + goto [loop] +end if + +print Platform$ ' OS where Run BASIC is being hosted +print UserInfo$ ' Information about the user's web browser +print UserAddress$ ' IP address of the user + +[exit] +end diff --git a/Task/Hailstone-sequence/360-Assembly/hailstone-sequence.360 b/Task/Hailstone-sequence/360-Assembly/hailstone-sequence.360 new file mode 100644 index 0000000000..b06a79d331 --- /dev/null +++ b/Task/Hailstone-sequence/360-Assembly/hailstone-sequence.360 @@ -0,0 +1,103 @@ +* Hailstone sequence 16/08/2015 +HAILSTON CSECT + USING HAILSTON,R12 + LR R12,R15 + ST R14,SAVER14 +BEGIN L R11,=F'100000' nmax + LA R8,27 n=27 + LR R1,R8 + MVI FTAB,X'01' ftab=true + BAL R14,COLLATZ + LR R10,R1 p + XDECO R8,XDEC n + MVC BUF1+10(6),XDEC+6 + XDECO R10,XDEC p + MVC BUF1+18(5),XDEC+7 + LA R5,6 + LA R3,0 i + LA R4,BUF1+25 +LOOPED L R2,TAB(R3) tab(i) + XDECO R2,XDEC + MVC 0(7,R4),XDEC+5 + LA R3,4(R3) i=i+1 + LA R4,7(R4) + C R5,=F'4' + BNE BCT + LA R4,7(R4) +BCT BCT R5,LOOPED + XPRNT BUF1,80 print hailstone(n)=p,tab(*) + MVC LONGEST,=F'0' longest=0 + MVI FTAB,X'00' ftab=true + LA R8,1 i +LOOPI CR R8,R11 do i=1 to nmax + BH ELOOPI + LR R1,R8 n + BAL R14,COLLATZ + LR R10,R1 p + L R4,LONGEST + CR R4,R10 if longest

1) + BNH ELOOPP + CLI FTAB,X'01' if ftab + BNE NONOK + C R6,=F'1' if p>=1 + BL NONOK + C R6,=F'3' & p<=3 + BH NONOK + LR R1,R6 then + BCTR R1,0 + SLA R1,2 + ST R7,TAB(R1) tab(p)=m +NONOK LR R4,R7 m + N R4,=F'1' m&1 + LTR R4,R4 if m//2=0 (if not(m&1)) + BNZ ODD +EVEN SRA R7,1 m=m/2 + B EIFM +ODD LA R3,3 + MR R2,R7 *m + LA R7,1(R3) m=m*3+1 +EIFM CLI FTAB,X'01' if ftab + BNE NEXTP + MVC TAB+12,TAB+16 tab(4)=tab(5) + MVC TAB+16,TAB+20 tab(5)=tab(6) + ST R7,TAB+20 tab(6)=m +NEXTP LA R6,1(R6) p=p+1 + B LOOPP +ELOOPP LR R1,R6 end p; return(p) + BR R14 end collatz +* +RETURN L R14,SAVER14 restore caller address + XR R15,R15 set return code + BR R14 return to caller +SAVER14 DS F +IVAL DS F +LONGEST DS F +N DS F +TAB DS 6F +FTAB DS X +BUF1 DC CL80'hailstone(nnnnnn)=nnnnn : nnnnnn nnnnnn nnnnnn ...* + ... nnnnnn nnnnnn nnnnnn' +BUF2 DC CL80'longest ) + WITH TABLE KEY start = start. + IF sy-subrc = 0. + INSERT LINES OF -seq INTO TABLE r_sequence. + ELSE. + DATA(seq) = get_sequence( get_next( start ) ). + INSERT LINES OF seq INTO TABLE r_sequence. + INSERT VALUE ty_seq( start = start + seq = seq ) INTO TABLE sequence_buffer. + ENDIF. + ENDMETHOD. + + METHOD get_longest_sequence_upto. + DATA: max_seq TYPE ty_seq_len, + act_seq TYPE ty_seq_len. + + DO limit TIMES. + act_seq-len = lines( get_sequence( sy-index ) ). + + IF act_seq-len > max_seq-len. + max_seq-len = act_seq-len. + max_seq-start = sy-index. + ENDIF. + ENDDO. + + r_longest_sequence = max_seq. + ENDMETHOD. +ENDCLASS. + +START-OF-SELECTION. + cl_demo_output=>begin_section( |Hailstone sequence of 27 is: | ). + cl_demo_output=>write( REDUCE string( INIT result = `` + FOR item IN lcl_hailstone=>get_sequence( 27 ) + NEXT result = |{ result } { item }| ) ). + cl_demo_output=>write( |With length: { lines( lcl_hailstone=>get_sequence( 27 ) ) }| ). + cl_demo_output=>begin_section( |Longest hailstone sequence upto 100k| ). + cl_demo_output=>write( lcl_hailstone=>get_longest_sequence_upto( 100000 ) ). + cl_demo_output=>display( ). diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic index 8f487d6014..3eb772985a 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-3.basic @@ -1,52 +1,91 @@ -print "Part 1: Create a routine to generate the hailstone sequence for a number." -print "" -while hailstone < 1 or hailstone <> int(hailstone) - input "Please enter a positive integer: "; hailstone -wend -print "" -print "The following is the 'Hailstone Sequence' for your number..." -print "" -print hailstone -while hailstone <> 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - print hailstone -wend -print "" -input "Hit 'Enter' to continue to part 2...";dummy$ -cls -print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." -print "" -print "No. in Seq.","Hailstone Sequence Number for 27" -print "" -c = 1: hailstone = 27 -print c, hailstone -while hailstone <> 1 - c = c + 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - print c, hailstone -wend -print "" -input "Hit 'Enter' to continue to part 3...";dummy$ -cls -print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" -print "" -print "Calculating result... Please wait... This could take a little while..." -print "" -print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far" -print "" -for cc = 1 to 99999 - hailstone = cc: c = 1 - while hailstone <> 1 - c = c + 1 - if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 - wend - if c > max then max = c: largesthailstone = cc - locate 1, 7 - print " " - locate 1, 7 - print using("###.###", cc / 99999 * 100);"%", cc, c, max - scan -next cc -print "" -print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"." -end +' version 17-06-2015 +' compile with: fbc -s console + +Function hailstone_fast(number As ULongInt) As ULongInt + ' faster version + ' only counts the sequence + + Dim As ULongInt count = 1 + + While number <> 1 + If (number And 1) = 1 Then + number += number Shr 1 + 1 ' 3*n+1 and n/2 in one + count += 2 + Else + number Shr= 1 ' divide number by 2 + count += 1 + End If + Wend + + Return count + +End Function + +Sub hailstone_print(number As ULongInt) + ' print the number and sequence + + Dim As ULongInt count = 1 + + Print "sequence for number "; number + Print Using "########"; number; 'starting number + + While number <> 1 + If (number And 1) = 1 Then + number = number * 3 + 1 ' n * 3 + 1 + count += 1 + Else + number = number \ 2 ' n \ 2 + count += 1 + End If + Print Using "########"; number; + Wend + + Print : Print + Print "sequence length = "; count + Print + Print String(79,"-") + +End Sub + +Function hailstone(number As ULongInt) As ULongInt + ' normal version + ' only counts the sequence + + Dim As ULongInt count = 1 + + While number <> 1 + If (number And 1) = 1 Then + number = number * 3 + 1 ' n * 3 + 1 + count += 1 + End If + number = number \ 2 ' divide number by 2 + count += 1 + Wend + + Return count + +End Function + +' ------=< MAIN >=------ + +Dim As ULongInt number +Dim As UInteger x, max_x, max_seq + +hailstone_print(27) +Print + +For x As UInteger = 1 To 100000 + number = hailstone(x) + If number > max_seq Then + max_x = x + max_seq = number + End If +Next + +Print "The longest sequence is for "; max_x; ", it has a sequence length of "; max_seq + +' empty keyboard buffer +While Inkey <> "" : Var _key_ = Inkey : Wend +Print : Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic index d8536360e3..8f487d6014 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-4.basic @@ -1,37 +1,52 @@ -function Hailstone(sys *n) -'========================= -if n and 1 - n=n*3+1 -else - n=n>>1 -end if -end function - -function HailstoneSequence(sys n) as sys -'======================================= -count=1 -do - Hailstone n - Count++ - if n=1 then exit do -end do -return count -end function - -'MAIN -'==== - -maxc=0 -maxn=0 -e=100000 -for n=1 to e - c=HailstoneSequence n - if c>maxc - maxc=c - maxn=n - end if -next - -print e ", " maxn ", " maxc - -'result 100000, 77031, 351 +print "Part 1: Create a routine to generate the hailstone sequence for a number." +print "" +while hailstone < 1 or hailstone <> int(hailstone) + input "Please enter a positive integer: "; hailstone +wend +print "" +print "The following is the 'Hailstone Sequence' for your number..." +print "" +print hailstone +while hailstone <> 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + print hailstone +wend +print "" +input "Hit 'Enter' to continue to part 2...";dummy$ +cls +print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." +print "" +print "No. in Seq.","Hailstone Sequence Number for 27" +print "" +c = 1: hailstone = 27 +print c, hailstone +while hailstone <> 1 + c = c + 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + print c, hailstone +wend +print "" +input "Hit 'Enter' to continue to part 3...";dummy$ +cls +print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" +print "" +print "Calculating result... Please wait... This could take a little while..." +print "" +print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far" +print "" +for cc = 1 to 99999 + hailstone = cc: c = 1 + while hailstone <> 1 + c = c + 1 + if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1 + wend + if c > max then max = c: largesthailstone = cc + locate 1, 7 + print " " + locate 1, 7 + print using("###.###", cc / 99999 * 100);"%", cc, c, max + scan +next cc +print "" +print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"." +end diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic index 76de11443f..d8536360e3 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-5.basic @@ -1,48 +1,37 @@ -NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array +function Hailstone(sys *n) +'========================= +if n and 1 + n=n*3+1 +else + n=n>>1 +end if +end function -Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list - Shared Hailstones() ; Get access to the Hailstones-List - ClearList(Hailstones()) ; Remove old data - Repeat - AddElement(Hailstones()) ; Add an element to the list - Hailstones()=n ; Fill current value in the new list element - If n=1 - ProcedureReturn ListSize(Hailstones()) - ElseIf n%2=0 - n/2 - Else - n=(3*n)+1 - EndIf - ForEver -EndProcedure +function HailstoneSequence(sys n) as sys +'======================================= +count=1 +do + Hailstone n + Count++ + if n=1 then exit do +end do +return count +end function -If OpenConsole() - Define i, l, maxl, maxi - l=FillHailstones(27) - Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$) - ForEach Hailstones() - If i=6 - Print(#CRLF$) - i=0 - EndIf - i+1 - Print(RSet(Str(Hailstones()),5)) - If Hailstones()<>1 - Print(", ") - EndIf - Next +'MAIN +'==== - i=1 - Repeat - l=FillHailstones(i) - If l>maxl - maxl=l - maxi=i - EndIf - i+1 - Until i>=100000 - Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.") +maxc=0 +maxn=0 +e=100000 +for n=1 to e + c=HailstoneSequence n + if c>maxc + maxc=c + maxn=n + end if +next - Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input() - CloseConsole() -EndIf +print e ", " maxn ", " maxc + +'result 100000, 77031, 351 diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic index 84d246dfee..76de11443f 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-6.basic @@ -1,40 +1,48 @@ -print "Part 1: Create a routine to generate the hailstone sequence for a number." -print "" +NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array -while hailstone < 1 or hailstone <> int(hailstone) - input "Please enter a positive integer: "; hailstone -wend -count = doHailstone(hailstone,"Y") +Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list + Shared Hailstones() ; Get access to the Hailstones-List + ClearList(Hailstones()) ; Remove old data + Repeat + AddElement(Hailstones()) ; Add an element to the list + Hailstones()=n ; Fill current value in the new list element + If n=1 + ProcedureReturn ListSize(Hailstones()) + ElseIf n%2=0 + n/2 + Else + n=(3*n)+1 + EndIf + ForEver +EndProcedure -print: print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." -count = doHailstone(27,"Y") +If OpenConsole() + Define i, l, maxl, maxi + l=FillHailstones(27) + Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$) + ForEach Hailstones() + If i=6 + Print(#CRLF$) + i=0 + EndIf + i+1 + Print(RSet(Str(Hailstones()),5)) + If Hailstones()<>1 + Print(", ") + EndIf + Next -print: print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" -print "Calculating result... Please wait... This could take a little while..." -print "Stone Percent Count" -for i = 1 to 99999 - count = doHailstone(i,"N") - if count > maxCount then - theBigStone = i - maxCount = count - print using("#####",i);" ";using("###.#", i / 99999 * 100);"% ";using("####",count) - end if -next i -end + i=1 + Repeat + l=FillHailstones(i) + If l>maxl + maxl=l + maxi=i + EndIf + i+1 + Until i>=100000 + Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.") -'--------------------------------------------- -' pass number and print (Y/N) -FUNCTION doHailstone(hailstone,prnt$) -if prnt$ = "Y" then - print - print "The following is the 'Hailstone Sequence' for number:";hailstone -end if -while hailstone <> 1 - if (hailstone and 1) then hailstone = (hailstone * 3) + 1 else hailstone = hailstone / 2 - doHailstone = doHailstone + 1 - if prnt$ = "Y" then - print hailstone;chr$(9); - if (doHailstone mod 10) = 0 then print - end if -wend -END FUNCTION + Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input() + CloseConsole() +EndIf diff --git a/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic b/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic index 3cbc39d283..84d246dfee 100644 --- a/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic +++ b/Task/Hailstone-sequence/BASIC/hailstone-sequence-7.basic @@ -1,42 +1,40 @@ -Module HailstoneSequence - Sub Main() - ' Checking sequence of 27. - - Dim l As List(Of Long) = HailstoneSequence(27) - Console.WriteLine("27 has {0} elements in sequence:", l.Count()) - - For i As Integer = 0 To 3 : Console.Write("{0}, ", l(i)) : Next - Console.Write("... ") - For i As Integer = l.Count - 4 To l.Count - 1 : Console.Write(", {0}", l(i)) : Next - - Console.WriteLine() - - ' Finding longest sequence for numbers below 100000. - - Dim max As Integer = 0 - Dim maxCount As Integer = 0 - - For i = 1 To 99999 - l = HailstoneSequence(i) - If l.Count > maxCount Then - max = i - maxCount = l.Count - End If - Next - Console.WriteLine("Max elements in sequence for number below 100k: {0} with {1} elements.", max, maxCount) - Console.ReadLine() - End Sub - - Private Function HailstoneSequence(ByVal n As Long) As List(Of Long) - Dim valList As New List(Of Long)() - valList.Add(n) - - Do Until n = 1 - n = IIf(n Mod 2 = 0, n / 2, (3 * n) + 1) - valList.Add(n) - Loop - - Return valList - End Function - -End Module +print "Part 1: Create a routine to generate the hailstone sequence for a number." +print "" + +while hailstone < 1 or hailstone <> int(hailstone) + input "Please enter a positive integer: "; hailstone +wend +count = doHailstone(hailstone,"Y") + +print: print "Part 2: Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1." +count = doHailstone(27,"Y") + +print: print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!" +print "Calculating result... Please wait... This could take a little while..." +print "Stone Percent Count" +for i = 1 to 99999 + count = doHailstone(i,"N") + if count > maxCount then + theBigStone = i + maxCount = count + print using("#####",i);" ";using("###.#", i / 99999 * 100);"% ";using("####",count) + end if +next i +end + +'--------------------------------------------- +' pass number and print (Y/N) +FUNCTION doHailstone(hailstone,prnt$) +if prnt$ = "Y" then + print + print "The following is the 'Hailstone Sequence' for number:";hailstone +end if +while hailstone <> 1 + if (hailstone and 1) then hailstone = (hailstone * 3) + 1 else hailstone = hailstone / 2 + doHailstone = doHailstone + 1 + if prnt$ = "Y" then + print hailstone;chr$(9); + if (doHailstone mod 10) = 0 then print + end if +wend +END FUNCTION diff --git a/Task/Hailstone-sequence/Batch-File/hailstone-sequence-1.bat b/Task/Hailstone-sequence/Batch-File/hailstone-sequence-1.bat index 07d6ae4cf5..068aa88c80 100644 --- a/Task/Hailstone-sequence/Batch-File/hailstone-sequence-1.bat +++ b/Task/Hailstone-sequence/Batch-File/hailstone-sequence-1.bat @@ -1,31 +1,41 @@ @echo off setlocal enabledelayedexpansion -if "%1" equ "" goto :eof -call :hailstone %1 seq cnt -echo %seq% -goto :eof +echo. +::Task #1 +call :hailstone 111 +echo Task #1: (Start:!sav!) +echo !seq! +echo. +echo Sequence has !cnt! elements. +echo. +::Task #2 +call :hailstone 27 +echo Task #2: (Start:!sav!) +echo !seq! +echo. +echo Sequence has !cnt! elements. +echo. +pause>nul +exit /b 0 +::The Function :hailstone set num=%1 -set %2=%1 +set seq=%1 +set sav=%1 +set cnt=0 :loop -if %num% equ 1 goto :eof -call :iseven %num% res -if %res% equ T goto divideby2 -set /a num = (3 * num) + 1 -set %2=!%2! %num% +set /a cnt+=1 +if !num! equ 1 goto :eof +set /a isodd=%num%%%2 +if !isodd! equ 0 goto divideby2 + +set /a num=(3*%num%)+1 +set seq=!seq! %num% goto loop + :divideby2 -set /a num = num / 2 -set %2=!%2! %num% +set /a num/=2 +set seq=!seq! %num% goto loop - -:iseven -set /a tmp = %1 %% 2 -if %tmp% equ 1 ( - set %2=F -) else ( - set %2=T -) -goto :eof diff --git a/Task/Hailstone-sequence/Batch-File/hailstone-sequence-2.bat b/Task/Hailstone-sequence/Batch-File/hailstone-sequence-2.bat index dcf4e48eb4..3d5340e20a 100644 --- a/Task/Hailstone-sequence/Batch-File/hailstone-sequence-2.bat +++ b/Task/Hailstone-sequence/Batch-File/hailstone-sequence-2.bat @@ -1,2 +1,23 @@ ->hailstone.cmd 20 -20 10 5 16 8 4 2 1 +@echo off +setlocal enableDelayedExpansion +if "%~1"=="test" ( + for /l %%. in () do ( + set /a "test1=num %% 2, cnt=cnt+1" + if !test1! equ 0 (set /a num/=2 & if !num! equ 1 exit !cnt!) else (set /a num=3*num+1) + ) +) + +set max=0 +set record=0 + +for /l %%X in (2,1,100000) do ( + set num=%%X & cmd /c "%~f0" test + if !errorlevel! gtr !max! (set /a "max=!errorlevel!,record=%%X") +) +set /a max+=1 + +echo.Number less than 100000 with longest sequence: %record% +echo.With length %max%. +pause>nul + +exit /b 0 diff --git a/Task/Hailstone-sequence/Befunge/hailstone-sequence.bf b/Task/Hailstone-sequence/Befunge/hailstone-sequence.bf index adca2bdc33..951d85b1c5 100644 --- a/Task/Hailstone-sequence/Befunge/hailstone-sequence.bf +++ b/Task/Hailstone-sequence/Befunge/hailstone-sequence.bf @@ -1,18 +1,4 @@ -93*:. v -> :2%v > -v+1*3_2/ ->" ",:.v v< -^>::v ->" "03pv :* p -v67:" "< 0: 1 ->p78p25 *^*p0 - v!-1: <<*^< -9$_:0\ ^-^< v -v01g00:< 1 4 ->g"@"*+`v^ <+ -v01/"@":_ $ ^, ->p"@"%00p\$:^. -vg01g00 ,+49< ->"@"*+.@ +&>:.:1-| + >3*^ @ + |%2: < + V>2/>+ diff --git a/Task/Hailstone-sequence/DCL/hailstone-sequence-1.dcl b/Task/Hailstone-sequence/DCL/hailstone-sequence-1.dcl new file mode 100644 index 0000000000..851537c30a --- /dev/null +++ b/Task/Hailstone-sequence/DCL/hailstone-sequence-1.dcl @@ -0,0 +1,23 @@ +$ n = f$integer( p1 ) +$ i = 1 +$ loop: +$ if p2 .nes. "QUIET" then $ s'i = n +$ if n .eq. 1 then $ goto done +$ i = i + 1 +$ if .not. n +$ then +$ n = n / 2 +$ else +$ if n .gt. 715827882 then $ exit ! avoid overflowing +$ n = 3 * n + 1 +$ endif +$ goto loop +$ done: +$ if p2 .nes. "QUIET" +$ then +$ penultimate_i = i - 1 +$ antepenultimate_i = i - 2 +$ preantepenultimate_i = i - 3 +$ write sys$output "sequence has ", i, " elements starting with ", s1, ", ", s2, ", ", s3, ", ", s4, " and ending with ", s'preantepenultimate_i, ", ", s'antepenultimate_i, ", ", s'penultimate_i, ", ", s'i +$ endif +$ sequence_length == i diff --git a/Task/Hailstone-sequence/DCL/hailstone-sequence-2.dcl b/Task/Hailstone-sequence/DCL/hailstone-sequence-2.dcl new file mode 100644 index 0000000000..28f8f7456e --- /dev/null +++ b/Task/Hailstone-sequence/DCL/hailstone-sequence-2.dcl @@ -0,0 +1,41 @@ +$ limit = f$integer( p1 ) +$ i = 1 +$ max_so_far = 0 +$ loop: +$ call hailstone 'i quiet +$ if sequence_length .gt. max_so_far +$ then +$ max_so_far = sequence_length +$ current_record_holder = i +$ endif +$ i = i + 1 +$ if i .lt. limit then $ goto loop +$ write sys$output current_record_holder, " is the number less than ", limit, " which has the longest hailstone sequence which is ", max_so_far, " in length" +$ exit +$ +$ hailstone: subroutine +$ n = f$integer( p1 ) +$ i = 1 +$ loop: +$ if p2 .nes. "QUIET" then $ s'i = n +$ if n .eq. 1 then $ goto done +$ i = i + 1 +$ if .not. n +$ then +$ n = n / 2 +$ else +$ if n .gt. 715827882 then $ exit ! avoid overflowing +$ n = 3 * n + 1 +$ endif +$ goto loop +$ done: +$ if p2 .nes. "QUIET" +$ then +$ penultimate_i = i - 1 +$ antepenultimate_i = i - 2 +$ preantepenultimate_i = i - 3 +$ write sys$output "sequence has ", i, " elements starting with ", s1, ", ", s2, ", ", s3, ", ", s4, " and ending with ", s'preantepenultimate_i, ", ", s'antepenultimate_i, ", ", s'penultimate_i, ", ", s'i +$ endif +$ sequence_length == I +$ exit +$ endsubroutine diff --git a/Task/Hailstone-sequence/Eiffel/hailstone-sequence.e b/Task/Hailstone-sequence/Eiffel/hailstone-sequence.e new file mode 100644 index 0000000000..0d4ded36b0 --- /dev/null +++ b/Task/Hailstone-sequence/Eiffel/hailstone-sequence.e @@ -0,0 +1,67 @@ +class + APPLICATION + +create + make + +feature + + make + local + test: LINKED_LIST [INTEGER] + count, number, te: INTEGER + do + create test.make + test := hailstone_sequence (27) + io.put_string ("There are " + test.count.out + " elements in the sequence for the number 27.") + io.put_string ("%NThe first 4 elements are: ") + across + 1 |..| 4 as t + loop + io.put_string (test [t.item].out + "%T") + end + io.put_string ("%NThe last 4 elements are: ") + across + (test.count - 3) |..| test.count as t + loop + io.put_string (test [t.item].out + "%T") + end + across + 1 |..| 99999 as c + loop + test := hailstone_sequence (c.item) + te := test.count + if te > count then + count := te + number := c.item + end + end + io.put_string ("%NThe longest sequence for numbers below 100000 is " + count.out + " for the number " + number.out + ".") + end + + hailstone_sequence (n: INTEGER): LINKED_LIST [INTEGER] + -- Members of the Hailstone Sequence starting from 'n'. + require + n_is_positive: n > 0 + local + seq: INTEGER + do + create Result.make + from + seq := n + until + seq = 1 + loop + Result.extend (seq) + if seq \\ 2 = 0 then + seq := seq // 2 + else + seq := ((3 * seq) + 1) + end + end + Result.extend (seq) + ensure + sequence_terminated: Result.last = 1 + end + +end diff --git a/Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir b/Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir index d5b76ffa23..407e4a0ec3 100644 --- a/Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir +++ b/Task/Hailstone-sequence/Elixir/hailstone-sequence.elixir @@ -1,21 +1,22 @@ defmodule Hailstone do - def step(1), do: 0 - def step(n) when Integer.even?(n), do: div(n,2) - def step(n) when Integer.odd?(n), do: n*3 + 1 + require Integer + + def step(1) , do: 0 + def step(n) when Integer.is_even(n), do: div(n,2) + def step(n) , do: n*3 + 1 + def sequence(n) do - Enum.to_list(Stream.take_while(Stream.iterate(n, &step/1), &(&1 > 0))) + Stream.iterate(n, &step/1) |> Stream.take_while(&(&1 > 0)) |> Enum.to_list end def run do - seq27 = Hailstone.sequence(27) + seq27 = sequence(27) len27 = length(seq27) - repr = String.replace(inspect(seq27, limit: 4), "]", - String.replace(inspect(Enum.drop(seq27,len27-4)), "[", ", ")) - IO.puts("Hailstone(27) has #{len27} elements: #{repr}") + repr = String.replace(inspect(seq27, limit: 4) <> inspect(Enum.drop(seq27,len27-4)), "][", ", ") + IO.puts "Hailstone(27) has #{len27} elements: #{repr}" - {start, len} = Enum.max_by( Enum.map(1..100_000, fn(n) -> {n, length(Hailstone.sequence(n))} end), - fn({_,len}) -> len end ) - IO.puts("Longest sequence starting under 100000 begins with #{start} and has #{len} elements.") + {len, start} = Enum.map(1..100_000, fn(n) -> {length(sequence(n)), n} end) |> Enum.max + IO.puts "Longest sequence starting under 100000 begins with #{start} and has #{len} elements." end end diff --git a/Task/Hailstone-sequence/Erlang/hailstone-sequence.erl b/Task/Hailstone-sequence/Erlang/hailstone-sequence-1.erl similarity index 100% rename from Task/Hailstone-sequence/Erlang/hailstone-sequence.erl rename to Task/Hailstone-sequence/Erlang/hailstone-sequence-1.erl diff --git a/Task/Hailstone-sequence/Erlang/hailstone-sequence-2.erl b/Task/Hailstone-sequence/Erlang/hailstone-sequence-2.erl new file mode 100644 index 0000000000..91265cb1c0 --- /dev/null +++ b/Task/Hailstone-sequence/Erlang/hailstone-sequence-2.erl @@ -0,0 +1,28 @@ +-module(collatz). +-export([main/0,collatz/1,coll/1,max_atz_under/1]). + +collatz(1) -> 1; +collatz(N) when N rem 2 == 0 -> 1 + collatz(N div 2); +collatz(N) when N rem 2 > 0 -> 1 + collatz(3 * N +1). + +max_atz_under(N) -> + F = fun (X) -> {collatz(X), X} end, + {_, Index} = lists:max(lists:map(F, lists:seq(1, N))), + Index. + +coll(1) -> [1]; +coll(N) when N rem 2 == 0 -> [N|coll(N div 2)]; +coll(N) -> [N|coll(3 * N + 1)]. + +main() -> + io:format("collatz(4) non-list total: ~w~n", [collatz(4)]), + io:format("coll(4) with lists ~w~n", [coll(4)] ), + Seq27 = coll(27), + Seq1000 = coll(max_atz_under(100000)), + io:format("coll(27) length: ~B~n", [length(Seq27)]), + io:format("coll(27) first 4: ~w~n", [lists:sublist(Seq27, 4)]), + io:format("collatz(27) last 4: ~w~n", + [lists:nthtail(length(Seq27) - 4, Seq27)]), + io:format("maximum N <= 100000..."), + io:format("Max: ~w~n", [max_atz_under(100000)]), + io:format("Total: ~w~n", [ length( Seq1000 ) ] ). diff --git a/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs b/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs new file mode 100644 index 0000000000..b0500be0f4 --- /dev/null +++ b/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs @@ -0,0 +1,18 @@ +import Data.List (maximumBy) +import Data.Ord (comparing) + +main = do putStrLn $ "Collatz sequence for 27: " + ++ ((show.hailstone) 27) + ++ "\n" + ++ "The number " + ++ (show longestChain) + ++" has the longest hailstone sequence" + ++" for any number less then 100000. " + ++"The sequence has length " + ++ (show.length.hailstone $ longestChain) + +hailstone = takeWhile (/=1) . (iterate collatz) + where collatz n = if even n then n `div` 2 else 3*n+1 + +longestChain = fst $ maximumBy (comparing snd) $ + map ((\x -> (x,(length.hailstone) x))) [1..100000] diff --git a/Task/Hailstone-sequence/Haskell/hailstone-sequence.hs b/Task/Hailstone-sequence/Haskell/hailstone-sequence-2.hs similarity index 100% rename from Task/Hailstone-sequence/Haskell/hailstone-sequence.hs rename to Task/Hailstone-sequence/Haskell/hailstone-sequence-2.hs diff --git a/Task/Hailstone-sequence/Mathematica/hailstone-sequence-5.math b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-5.math new file mode 100644 index 0000000000..916fedb5bf --- /dev/null +++ b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-5.math @@ -0,0 +1 @@ +With[{seq = HailstoneFP[27]}, { Length[seq], Take[seq, 4], Take[seq, -4]}] diff --git a/Task/Hailstone-sequence/Mathematica/hailstone-sequence-6.math b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-6.math new file mode 100644 index 0000000000..d95d8e083f --- /dev/null +++ b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-6.math @@ -0,0 +1 @@ +Short[HailstoneFP[27],0.45] diff --git a/Task/Hailstone-sequence/Mathematica/hailstone-sequence-7.math b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-7.math new file mode 100644 index 0000000000..d31f38fb6a --- /dev/null +++ b/Task/Hailstone-sequence/Mathematica/hailstone-sequence-7.math @@ -0,0 +1 @@ +MaximalBy[Table[{i, Length[HailstoneFP[i]]}, {i, 100000}], Last] diff --git a/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh b/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh index 2cb529eb3f..5c40ad9e6f 100644 --- a/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh +++ b/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh @@ -1,5 +1,3 @@ -# Author M. McNabb - function Get-HailStone { param($n) @@ -13,15 +11,10 @@ function Get-HailStone { function Get-HailStoneBelowLimit { param($UpperLimit) - $Counts = @() - for ($i = 1; $i -lt $UpperLimit; $i++) { - $Object = [pscustomobject]@{ + [pscustomobject]@{ 'Number' = $i 'Count' = (Get-HailStone $i).count } - $Counts += $Object } - - $Counts } diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx index b2675b302a..12ff10f6f0 100644 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx @@ -1,27 +1,28 @@ -/*REXX pgm tests a number and a range for hailstone (Collatz) sequences.*/ -parse arg x y . /*get optional arguments from CL.*/ -if x=='' | x==',' then x=27 /*Any 1st argument? Use default.*/ -if y=='' | y==',' then y=100000-1 /*Any 2nd argument? Use default.*/ -numeric digits 20; @.=0 /*handle big #s; initialize array*/ -$=hailstone(x) /*═══════════════════task 1═════════════════════════*/ +/*REXX pgm tests a number and also a range for hailstone (Collatz) sequences. */ +numeric digits 20 /*be able to handle gihugeic numbers. */ +parse arg x y . /*get optional arguments from the C.L. */ +if x=='' | x==',' then x=27 /*No 1st argument? Then use default.*/ +if y=='' | y==',' then y=100000-1 /* " 2nd " " " " */ +$=hailstone(x) /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 1▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ say x ' has a hailstone sequence of ' words($) -say ' and starts with: ' subword($, 1, 4) " ∙∙∙" -say ' and ends with: ∙∙∙' subword($, max(1, words($)-3)) +say ' and starts with: ' subword($, 1, 4) " ∙∙∙" +say ' and ends with: ∙∙∙' subword($, max(5, words($)-3)) +if y==0 then exit /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 2▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ say -if y==0 then exit /*═══════════════════task 2═════════════════════════*/ -w=0; do j=1 for y /*traipse through the numbers. */ - call hailstone j /*compute the hailstone sequence.*/ - if #hs<=w then iterate /*Not big 'nuff? Then keep going.*/ - bigJ=j; w=#hs /*remember what # has biggest HS.*/ +w=0; do j=1 for y /*traipse through the range of numbers.*/ + call hailstone j /*compute the hailstone sequence for J.*/ + if #hs<=w then iterate /*Not big 'nuff? Then keep traipsing.*/ + bigJ=j; w=#hs /*remember what # has biggest hailstone*/ end /*j*/ -say '(between 1──►'y") " bigJ ' has the longest hailstone sequence:' w -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────HAILSTONE subroutine────────────────*/ -hailstone: procedure expose #hs; parse arg n 1 s /*N & S set to 1st arg*/ +say '(between 1──►'y") " bigJ ' has the longest hailstone sequence:' w +say 'and took' +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────HAILSTONE subroutine──────────────────────*/ +hailstone: procedure expose #hs; parse arg n 1 s /*N & S are set to 1st arg.*/ - do #hs=1 while n\==1 /*loop while N isn't unity. */ - if n//2 then n=n*3+1 /*if N is odd, calc: 3*n +1 */ - else n=n%2 /* " " " even, perform fast ÷ */ - s=s n /*build a sequence list (append).*/ - end /*#hs*/ -return s + do #hs=1 while n\==1 /*keep loop while N isn't unity. */ + if n//2 then n=n*3 + 1 /*N is odd ? Then calculate 3*n + 1 */ + else n=n%2 /*" " even? Then calculate fast ÷ */ + s=s n /* [↑] % is REXX integer division. */ + end /*#hs*/ /* [↑] append N to the sequence list*/ +return s /*return the S string to the invoker.*/ diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx index 685ec6aad1..b160cf41d5 100644 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx @@ -1,30 +1,38 @@ -/*REXX pgm tests a number and a range for hailstone (Collatz) sequences.*/ -parse arg x y . /*get optional arguments from CL.*/ -if x=='' | x==',' then x=27 /*Any 1st argument? Use default.*/ -if y=='' | y==',' then y=99999 /*Any 2nd argument? Use default.*/ -numeric digits 20; @.=0 /*handle big #s; initialize array*/ -$=hailstone(x) /*═══════════════════task 1═════════════════════════*/ +/*REXX pgm tests a number and also a range for hailstone (Collatz) sequences. */ +!.=0; !.0=1; !.2=1; !.4=1; !.6=1; !.8=1 /*assign even digits to be "true". */ +numeric digits 20; @.=0 /*handle big numbers; initialize array.*/ +parse arg x y z .; !.h=y /*get optional arguments from the C,L. */ +if x=='' | x==',' then x=27 /*No 1st argument? Then use default.*/ +if y=='' | y==',' then y=100000-1 /* " 2nd " " " " */ +if z=='' | z==',' then z=12 /*head/tail number? " " " */ +$=hailstone(x) /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 1▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ say x ' has a hailstone sequence of ' words($) -say ' and starts with: ' subword($, 1, 4) " ∙∙∙" -say ' and ends with: ∙∙∙' subword($, max(1, words($)-3)) -say -if y==0 then exit /*═══════════════════task 2═════════════════════════*/ -w=0; do j=1 for y /*loop through all numbers <100k.*/ - $=hailstone(j) /*compute the hailstone sequence.*/ - #hs=words($) /*find the length of the sequence*/ - if #hs<=w then iterate /*Not big 'nuff? Then keep going.*/ - bigJ=j; w=#hs /*remember what # has biggest HS.*/ +say ' and starts with: ' subword($, 1, z) " ∙∙∙" +say ' and ends with: ∙∙∙' subword($, max(z+1, words($)-z+1)) +say /*Z: show first & last Z numbers*/ +if y==0 then exit /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 2▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +w=0; do j=1 for y /*traipse through the range of numbers.*/ + $=hailstone(j) /*compute the hailstone sequence for J.*/ + #hs=words($) /*find the length of the hailstone seq.*/ + if #hs<=w then iterate /*Not big 'nuff? Then keep traipsing.*/ + bigJ=j; w=#hs /*remember what # has biggest hailstone*/ end /*j*/ -say '(between 1──►'y") " bigJ ' has the longest hailstone sequence:' w +say '(between 1──►'y") " bigJ ' has the longest hailstone sequence:' w exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────HAILSTONE subroutine────────────────*/ -hailstone: procedure expose @.; parse arg n 1 s 1 o /*N,S,O = 1st arg.*/ -@.1= /*special case for unity. */ - do while @.n==0 /*loop while residual is unknown.*/ - if n//2 then n=n*3+1 /*if N is odd, calc: 3*n +1 */ - else n=n%2 /* " " " even, perform fast ÷ */ - s=s n /*build a sequence list (append).*/ +/*──────────────────────────────────HAILSTONE subroutine──────────────────────*/ +hailstone: procedure expose @. !.; parse arg n 1 s 1 o /*N,S,O are 1st arg.*/ +@.1= /*handle the special case for unity (1)*/ + do while @.n==0 /*loop while the residual is unknown. */ + parse var n '' -1 L /*extract the last decimal digit of N.*/ + if !.L then n=n%2 /*N is even? Then calculate fast ÷ */ + else n=n*3 + 1 /*? ? odd ? Then calculate 3*n + 1 */ + s=s n /* [↑] %: is the REXX integer division*/ + end /*#hs*/ /* [↑] append N to the sequence list*/ +s=s @.n /*append the number to a sequence list.*/ +@.o=subword(s,2) /*use memoization for this hailstone #.*/ +r=s; h=!.h + do while r\==''; parse var r _ r /*get next the subsequence. */ + if @._\==0 then return s /*Already found? Return S. */ + if _>! then return s /*Out of range? Return S. */ + @._=r /*assign the subsequence #. */ end /*while*/ -s=s @.n /*append to a sequence list. */ -@.o=subword(s,2) /*memoization for this hailstone.*/ -return s diff --git a/Task/Hailstone-sequence/Rust/hailstone-sequence.rust b/Task/Hailstone-sequence/Rust/hailstone-sequence.rust index 1b9f31967f..3d54e71d11 100644 --- a/Task/Hailstone-sequence/Rust/hailstone-sequence.rust +++ b/Task/Hailstone-sequence/Rust/hailstone-sequence.rust @@ -1,27 +1,40 @@ -use std::vec::Vec; - -fn hailstone(mut n : int) -> Vec{ - let mut v = vec!(n); - while n > 1{ - n = if n % 2 == 0 { n / 2 } - else { 3 * n + 1 }; - v.push(n); +fn hailstone(start : u32) -> Vec { + let mut res = Vec::new(); + let mut next = start; + + res.push(start); + + while next != 1 { + next = if next % 2 == 0 { next/2 } else { 3*next+1 }; + res.push(next); } - return v; + res } + fn main() { - let mut max_sequence = 0i; - let mut number_max_sequence = 0i; - let hs27 = hailstone(27); - println!("hailstone(27) has {} elements, starting from {} and ending to {}.", hs27.len(), hs27[0..4], hs27[hs27.len()-4..hs27.len()]); - - for i in range(1i, 100000) { - let hs_i = hailstone(i); - if hs_i.len() as int > max_sequence { - max_sequence = hs_i.len() as int; - number_max_sequence = i; + let test_num = 27; + let test_hailseq = hailstone(test_num); + + println!("For {} number of elements is {} ", test_num, test_hailseq.len()); + + let fst_slice = test_hailseq[0..4].iter() + .fold("".to_owned(), |acc, i| { acc + &*(i.to_string()).to_owned() + ", " }); + let last_slice = test_hailseq[test_hailseq.len()-4..].iter() + .fold("".to_owned(), |acc, i| { acc + &*(i.to_string()).to_owned() + ", " }); + + println!(" hailstone starting with {} ending with {} ", fst_slice, last_slice); + + let max_range = 100000; + let mut max_len = 0; + let mut max_seed = 0; + for i_seed in 1..max_range { + let i_len = hailstone(i_seed).len(); + + if i_len > max_len { + max_len = i_len; + max_seed = i_seed; } } - println!("Maximum : {} elements with number {}.", max_sequence, number_max_sequence); + println!("Longest sequence is {} element long for seed {}", max_len, max_seed); } diff --git a/Task/Hailstone-sequence/VBScript/hailstone-sequence.vb b/Task/Hailstone-sequence/VBScript/hailstone-sequence.vb new file mode 100644 index 0000000000..28d846a02d --- /dev/null +++ b/Task/Hailstone-sequence/VBScript/hailstone-sequence.vb @@ -0,0 +1,42 @@ +'function arguments: "num" is the number to sequence and "return" is the value to return - "s" for the sequence or +'"e" for the number elements. +Function hailstone_sequence(num,return) + n = num + sequence = num + elements = 1 + Do Until n = 1 + If n Mod 2 = 0 Then + n = n / 2 + Else + n = (3 * n) + 1 + End If + sequence = sequence & " " & n + elements = elements + 1 + Loop + Select Case return + Case "s" + hailstone_sequence = sequence + Case "e" + hailstone_sequence = elements + End Select +End Function + +'test driving. +'show sequence for 27 +WScript.StdOut.WriteLine "Sequence for 27: " & hailstone_sequence(27,"s") +WScript.StdOut.WriteLine "Number of Elements: " & hailstone_sequence(27,"e") +WScript.StdOut.WriteBlankLines(1) +'show the number less than 100k with the longest sequence +count = 1 +n_elements = 0 +n_longest = "" +Do While count < 100000 + current_n_elements = hailstone_sequence(count,"e") + If current_n_elements > n_elements Then + n_elements = current_n_elements + n_longest = "Number: " & count & " Length: " & n_elements + End If + count = count + 1 +Loop +WScript.StdOut.WriteLine "Number less than 100k with the longest sequence: " +WScript.StdOut.WriteLine n_longest diff --git a/Task/Hamming-numbers/Clojure/hamming-numbers.clj b/Task/Hamming-numbers/Clojure/hamming-numbers-1.clj similarity index 100% rename from Task/Hamming-numbers/Clojure/hamming-numbers.clj rename to Task/Hamming-numbers/Clojure/hamming-numbers-1.clj diff --git a/Task/Hamming-numbers/Clojure/hamming-numbers-2.clj b/Task/Hamming-numbers/Clojure/hamming-numbers-2.clj new file mode 100644 index 0000000000..a5e0941df1 --- /dev/null +++ b/Task/Hamming-numbers/Clojure/hamming-numbers-2.clj @@ -0,0 +1,13 @@ +(defn hamming + "Computes the unbounded sequence of Hamming 235 numbers." + [] + (letfn [(merge [xs ys] + (let [xv (first xs), yv (first ys)] + (if (< xv yv) (cons xv (lazy-seq (merge (next xs) ys))) + (cons yv (lazy-seq (merge xs (next ys))))))), + (smult [m s] ;; equiv to map (* m) s -- faster + (cons (*' m (first s)) (lazy-seq (smult m (next s)))))] + (do (def s5 (cons 5 (lazy-seq (smult 5 s5)))) + (def s35 (cons 3 (lazy-seq (merge s5 (smult 3 s35))))) + (def s235 (cons 2 (lazy-seq (merge s35 (smult 2 s235))))) + (cons 1 (lazy-seq s235))))) diff --git a/Task/Hamming-numbers/DCL/hamming-numbers.dcl b/Task/Hamming-numbers/DCL/hamming-numbers.dcl new file mode 100644 index 0000000000..77841cb927 --- /dev/null +++ b/Task/Hamming-numbers/DCL/hamming-numbers.dcl @@ -0,0 +1,43 @@ +$ limit = p1 +$ +$ n = 0 +$ h_'n = 1 +$ x2 = 2 +$ x3 = 3 +$ x5 = 5 +$ i = 0 +$ j = 0 +$ k = 0 +$ +$ n = 1 +$ loop: +$ x = x2 +$ if x3 .lt. x then $ x = x3 +$ if x5 .lt. x then $ x = x5 +$ h_'n = x +$ if x2 .eq. h_'n +$ then +$ i = i + 1 +$ x2 = 2 * h_'i +$ endif +$ if x3 .eq. h_'n +$ then +$ j = j + 1 +$ x3 = 3 * h_'j +$ endif +$ if x5 .eq. h_'n +$ then +$ k = k + 1 +$ x5 = 5 * h_'k +$ endif +$ n = n + 1 +$ if n .le. limit then $ goto loop +$ +$ i = 0 +$ loop2: +$ write sys$output h_'i +$ i = i + 1 +$ if i .lt. 20 then $ goto loop2 +$ +$ n = limit - 1 +$ write sys$output h_'n diff --git a/Task/Hamming-numbers/Elixir/hamming-numbers.elixir b/Task/Hamming-numbers/Elixir/hamming-numbers.elixir new file mode 100644 index 0000000000..7fa47675a9 --- /dev/null +++ b/Task/Hamming-numbers/Elixir/hamming-numbers.elixir @@ -0,0 +1,32 @@ +defmodule Hamming do + def generater do + queues = [{2, queue}, {3, queue}, {5, queue}] + Stream.unfold({1, queues}, fn {n, q} -> next(n, q) end) + end + + defp next(n, queues) do + queues = Enum.map(queues, fn {m, queue} -> {m, push(queue, m*n)} end) + min = Enum.map(queues, fn {_, queue} -> top(queue) end) |> Enum.min + queues = Enum.map(queues, fn {m, queue} -> + {m, (if min==top(queue), do: erase_top(queue), else: queue)} + end) + {n, {min, queues}} + end + + defp queue, do: {[], []} + + defp push({input, output}, term), do: {[term | input], output} + + defp top({input, []}), do: List.last(input) + defp top({_, [h|_]}), do: h + + defp erase_top({input, []}), do: erase_top({[], Enum.reverse(input)}) + defp erase_top({input, [_|t]}), do: {input, t} +end + +IO.puts "first twenty Hamming numbers:" +IO.inspect Hamming.generater |> Enum.take(20) +IO.puts "1691st Hamming number:" +IO.puts Hamming.generater |> Enum.take(1691) |> List.last +IO.puts "one millionth Hamming number:" +IO.puts Hamming.generater |> Enum.take(1_000_000) |> List.last diff --git a/Task/Hamming-numbers/Scala/hamming-numbers-4.scala b/Task/Hamming-numbers/Scala/hamming-numbers-4.scala new file mode 100644 index 0000000000..45ff339304 --- /dev/null +++ b/Task/Hamming-numbers/Scala/hamming-numbers-4.scala @@ -0,0 +1,13 @@ + def hamming(): Stream[BigInt] = { + def merge(a: Stream[BigInt], b: Stream[BigInt]): Stream[BigInt] = { + val av = a.head; val bv = b.head + if (av < bv) av #:: merge(a.tail, b) + else bv #:: merge(a, b.tail) + } + def smult(m:BigInt, s: Stream[BigInt]): Stream[BigInt] = + (m * s.head) #:: smult(m, s.tail) // equiv to map (m *) s - faster + lazy val s5: Stream[BigInt] = 5 #:: smult(5, s5) + lazy val s35: Stream[BigInt] = 3 #:: merge(s5, smult(3, s35)) + lazy val s235: Stream[BigInt] = 2 #:: merge(s35, smult(2, s235)) + 1 #:: s235 + } diff --git a/Task/Hamming-numbers/Scheme/hamming-numbers.ss b/Task/Hamming-numbers/Scheme/hamming-numbers-1.ss similarity index 100% rename from Task/Hamming-numbers/Scheme/hamming-numbers.ss rename to Task/Hamming-numbers/Scheme/hamming-numbers-1.ss diff --git a/Task/Hamming-numbers/Scheme/hamming-numbers-2.ss b/Task/Hamming-numbers/Scheme/hamming-numbers-2.ss new file mode 100644 index 0000000000..1c15857856 --- /dev/null +++ b/Task/Hamming-numbers/Scheme/hamming-numbers-2.ss @@ -0,0 +1,22 @@ +(define (hamming) + (define (merge a b) + (let ((x (car a)) (y (car b))) + (if (< x y) (cons x (delay (merge (force (cdr a)) b))) + (cons y (delay (merge a (force (cdr b)))))))) + (define (smult m s) (cons (* m (car s)) + (delay (smult m (force (cdr s)))))) ;; equiv to map (* m) s + (define s5 (cons 5 (delay (smult 5 s5)))) + (define s35 (cons 3 (delay (merge s5 (smult 3 s35))))) + (define s235 (cons 2 (delay (merge s35 (smult 2 s235))))) + (cons 1 (delay s235))) + +;;; test... +(define (stream-take->list n strm) + (if (= n 0) (list) (cons (car strm) + (stream-take->list (- n 1) (force (cdr strm)))))) +(define (stream-ref strm nth) + (do ((nxt strm (force (cdr nxt))) (cnt 0 (+ cnt 1))) + ((>= cnt nth) (car nxt)))) +(display (stream-take->list 20 (hamming))) (newline) +(display (stream-ref (hamming) (- 1691 1))) (newline) +(display (stream-ref (hamming) (- 1000000 1))) (newline) diff --git a/Task/Hamming-numbers/Smalltalk/hamming-numbers.st b/Task/Hamming-numbers/Smalltalk/hamming-numbers-1.st similarity index 100% rename from Task/Hamming-numbers/Smalltalk/hamming-numbers.st rename to Task/Hamming-numbers/Smalltalk/hamming-numbers-1.st diff --git a/Task/Hamming-numbers/Smalltalk/hamming-numbers-2.st b/Task/Hamming-numbers/Smalltalk/hamming-numbers-2.st new file mode 100644 index 0000000000..8d9931fcee --- /dev/null +++ b/Task/Hamming-numbers/Smalltalk/hamming-numbers-2.st @@ -0,0 +1,21 @@ +limit := 10 raisedToInteger: 84. +tape := Set new. + +hammingProcess := [:newHamming| + (newHamming <= limit) + ifTrue: + [| index | + index := tape scanFor: newHamming. + (tape array at: index) + ifNil: + [tape atNewIndex: index put: newHamming asSetElement. + hammingProcess value: newHamming * 2. + hammingProcess value: newHamming * 3. + hammingProcess value: newHamming * 5]]]. + +hammingProcess value: 1. + +sc := tape asSortedCollection. +sc first: 20. "a SortedCollection(1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36)" +sc at: 1691. "2125764000" +sc at: 1000000. "519312780448388736089589843750000000000000000000000000000000000000000000000000000000" diff --git a/Task/Hamming-numbers/VBScript/hamming-numbers.vb b/Task/Hamming-numbers/VBScript/hamming-numbers.vb new file mode 100644 index 0000000000..ef464f0463 --- /dev/null +++ b/Task/Hamming-numbers/VBScript/hamming-numbers.vb @@ -0,0 +1,22 @@ +For h = 1 To 20 + WScript.StdOut.Write "H(" & h & ") = " & Hamming(h) + WScript.StdOut.WriteLine +Next +WScript.StdOut.Write "H(" & 1691 & ") = " & Hamming(1691) +WScript.StdOut.WriteLine + +Function Hamming(l) + Dim h() : Redim h(l) : h(0) = 1 + i = 0 : j = 0 : k = 0 + x2 = 2 : x3 = 3 : x5 = 5 + For n = 1 To l-1 + m = x2 + If m > x3 Then m = x3 End If + If m > x5 Then m = x5 End If + h(n) = m + If m = x2 Then i = i + 1 : x2 = 2 * h(i) End If + If m = x3 Then j = j + 1 : x3 = 3 * h(j) End If + If m = x5 Then k = k + 1 : x5 = 5 * h(k) End If + Next + Hamming = h(l-1) +End Function diff --git a/Task/Handle-a-signal/00DESCRIPTION b/Task/Handle-a-signal/00DESCRIPTION index 25f1b1f5c1..a63536252c 100644 --- a/Task/Handle-a-signal/00DESCRIPTION +++ b/Task/Handle-a-signal/00DESCRIPTION @@ -1,4 +1,5 @@ {{omit from|Erlang|Does not handle signals.}} +{{omit from|Batch File|"Pure" Batch files cannot really handle signals.}} {{omit from|GUISS}} {{omit from|M4}} {{omit from|ML/I}} diff --git a/Task/Handle-a-signal/Common-Lisp/handle-a-signal.lisp b/Task/Handle-a-signal/Common-Lisp/handle-a-signal.lisp new file mode 100644 index 0000000000..222d7c9c3a --- /dev/null +++ b/Task/Handle-a-signal/Common-Lisp/handle-a-signal.lisp @@ -0,0 +1,24 @@ +(ql:quickload :cffi) + +(defvar *SIGINT* 2) + +(defmacro set-signal-handler (signo &body body) + (let ((handler (gensym "HANDLER"))) + `(progn + (cffi:defcallback ,handler :void ((signo :int)) + (declare (ignore signo)) + ,@body) + (cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler))))) + +(defvar *initial* (get-internal-real-time)) + +(set-signal-handler *SIGINT* + (format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second)) + (quit)) + +(let ((i 0)) + (loop do + (format t "~a~&" (incf i)) + (sleep 0.5) + ) +) diff --git a/Task/Handle-a-signal/Julia/handle-a-signal.julia b/Task/Handle-a-signal/Julia/handle-a-signal.julia new file mode 100644 index 0000000000..5c53e47529 --- /dev/null +++ b/Task/Handle-a-signal/Julia/handle-a-signal.julia @@ -0,0 +1,12 @@ +ccall(:jl_exit_on_sigint, Void, (Cint,), 0) +tic() +ticks = 0 +try + while true + sleep(0.5) + ticks += 1 + println(ticks) + end +end +println() +toc() diff --git a/Task/Handle-a-signal/NewLISP/handle-a-signal.newlisp b/Task/Handle-a-signal/NewLISP/handle-a-signal.newlisp index 2f3b398933..86457c5dff 100644 --- a/Task/Handle-a-signal/NewLISP/handle-a-signal.newlisp +++ b/Task/Handle-a-signal/NewLISP/handle-a-signal.newlisp @@ -1,3 +1,4 @@ +; Mac OSX, BSDs or Linux only, not Windows (setq start-time (now)) (signal 2 (lambda() diff --git a/Task/Handle-a-signal/PowerShell/handle-a-signal.psh b/Task/Handle-a-signal/PowerShell/handle-a-signal.psh new file mode 100644 index 0000000000..600c941fd7 --- /dev/null +++ b/Task/Handle-a-signal/PowerShell/handle-a-signal.psh @@ -0,0 +1,18 @@ +$Start_Time = (Get-date).second +Write-Host "Type CTRL-C to Terminate..." +$n = 1 +Try +{ + While($true) + { + Write-Host $n + $n ++ + Start-Sleep -m 500 + } +} +Finally +{ + $End_Time = (Get-date).second + $Time_Diff = $End_Time - $Start_Time + Write-Host "Total time in seconds"$Time_Diff +} diff --git a/Task/Happy-numbers/00DESCRIPTION b/Task/Happy-numbers/00DESCRIPTION index da58ac2ec1..b446795518 100644 --- a/Task/Happy-numbers/00DESCRIPTION +++ b/Task/Happy-numbers/00DESCRIPTION @@ -1,5 +1,9 @@ From Wikipedia, the free encyclopedia: -:A [[wp:Happy number|happy number]] is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here. +:A [[wp:Happy number|happy number]] is defined by the following process: + +: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals   '''1'''   (where it will stay),   or it loops endlessly in a cycle which does not include   '''1'''.   Those numbers for which this process ends in   '''1'''   are happy numbers,   while those that do not end in   '''1'''   are unhappy numbers. + +Display an example of your output here. '''Task:''' Find and print the first 8 happy numbers. diff --git a/Task/Happy-numbers/AppleScript/happy-numbers.applescript b/Task/Happy-numbers/AppleScript/happy-numbers.applescript new file mode 100644 index 0000000000..9deba2cf39 --- /dev/null +++ b/Task/Happy-numbers/AppleScript/happy-numbers.applescript @@ -0,0 +1,32 @@ +on run + set howManyHappyNumbers to 8 + set happyNumberList to {} + set globalCounter to 1 + + repeat howManyHappyNumbers times + repeat while not isHappy(globalCounter) + set globalCounter to globalCounter + 1 + end repeat + set end of happyNumberList to globalCounter + set globalCounter to globalCounter + 1 + end repeat + log happyNumberList +end run + +on isHappy(numberToCheck) + set localCycle to {} + repeat while (numberToCheck ≠ 1) + if localCycle contains numberToCheck then + exit repeat + end if + set end of localCycle to numberToCheck + set tempNumber to 0 + repeat while (numberToCheck > 0) + set digitOfNumber to numberToCheck mod 10 + set tempNumber to tempNumber + (digitOfNumber ^ 2) + set numberToCheck to (numberToCheck - digitOfNumber) / 10 + end repeat + set numberToCheck to tempNumber + end repeat + return (numberToCheck = 1) +end isHappy diff --git a/Task/Happy-numbers/Clojure/happy-numbers.clj b/Task/Happy-numbers/Clojure/happy-numbers-1.clj similarity index 100% rename from Task/Happy-numbers/Clojure/happy-numbers.clj rename to Task/Happy-numbers/Clojure/happy-numbers-1.clj diff --git a/Task/Happy-numbers/Clojure/happy-numbers-2.clj b/Task/Happy-numbers/Clojure/happy-numbers-2.clj new file mode 100644 index 0000000000..fc9059eae5 --- /dev/null +++ b/Task/Happy-numbers/Clojure/happy-numbers-2.clj @@ -0,0 +1,35 @@ +(require '[clojure.set :refer [union]]) + +(def ^{:private true} cache {:happy (atom #{}) :sad (atom #{})}) + +(defn break-apart [n] + (->> (str n) + (map str) + (map #(Long/parseLong %)))) + +(defn next-number [n] + (->> (break-apart n) + (map #(* % %)) + (apply +))) + +(defn happy-or-sad? [prev n] + (cond (or (= n 1) ((deref (:happy cache)) n)) :happy + (or ((deref (:sad cache)) n) (some #(= % n) prev)) :sad + :else :unknown)) + +(defn happy-algo [n] + (let [get-next (fn [[prev n]] [(conj prev n) (next-number n)]) + my-happy-or-sad? (fn [[prev n]] [(happy-or-sad? prev n) (conj prev n)]) + unknown? (fn [[res nums]] (= res :unknown)) + [res nums] (->> [#{} n] + (iterate get-next) + (map my-happy-or-sad?) + (drop-while unknown?) + first) + _ (swap! (res cache) union nums)] + res)) + +(def happy-numbers (->> (iterate inc 1) + (filter #(= :happy (happy-algo %))))) + +(println (take 8 happy-numbers)) diff --git a/Task/Happy-numbers/DCL/happy-numbers.dcl b/Task/Happy-numbers/DCL/happy-numbers.dcl new file mode 100644 index 0000000000..cfa968cf12 --- /dev/null +++ b/Task/Happy-numbers/DCL/happy-numbers.dcl @@ -0,0 +1,50 @@ +$ happy_1 = 1 +$ found = 0 +$ i = 1 +$ loop1: +$ n = i +$ seen_list = "," +$ loop2: +$ if f$type( happy_'n ) .nes. "" then $ goto happy +$ if f$type( unhappy_'n ) .nes. "" then $ goto unhappy +$ if f$locate( "," + n + ",", seen_list ) .eq. f$length( seen_list ) +$ then +$ seen_list = seen_list + f$string( n ) + "," +$ else +$ goto unhappy +$ endif +$ ns = f$string( n ) +$ nl = f$length( ns ) +$ j = 0 +$ sumsq = 0 +$ loop3: +$ digit = f$integer( f$extract( j, 1, ns )) +$ sumsq = sumsq + digit * digit +$ j = j + 1 +$ if j .lt. nl then $ goto loop3 +$ n = sumsq +$ goto loop2 +$ unhappy: +$ j = 1 +$ loop4: +$ x = f$element( j, ",", seen_list ) +$ if x .eqs. "" then $ goto continue +$ unhappy_'x = 1 +$ j = j + 1 +$ goto loop4 +$ happy: +$ found = found + 1 +$ found_'found = i +$ if found .eq. 8 then $ goto done +$ j = 1 +$ loop5: +$ x = f$element( j, ",", seen_list ) +$ if x .eqs. "" then $ goto continue +$ happy_'x = 1 +$ j = j + 1 +$ goto loop5 +$ continue: +$ i = i + 1 +$ goto loop1 +$ done: +$ show symbol found* diff --git a/Task/Happy-numbers/Elixir/happy-numbers.elixir b/Task/Happy-numbers/Elixir/happy-numbers.elixir new file mode 100644 index 0000000000..f34337f6ed --- /dev/null +++ b/Task/Happy-numbers/Elixir/happy-numbers.elixir @@ -0,0 +1,27 @@ +defmodule Happy do + def task(num) do + Process.put({:happy, 1}, true) + Stream.iterate(1, &(&1+1)) + |> Stream.filter(fn n -> happy?(n) end) + |> Enum.take(num) + end + + defp happy?(n) do + sum = square_sum(n, 0) + val = Process.get({:happy, sum}) + if val == nil do + Process.put({:happy, sum}, false) + val = happy?(sum) + Process.put({:happy, sum}, val) + end + val + end + + defp square_sum(0, sum), do: sum + defp square_sum(n, sum) do + r = rem(n, 10) + square_sum(div(n, 10), sum + r*r) + end +end + +IO.inspect Happy.task(8) diff --git a/Task/Happy-numbers/Julia/happy-numbers-2.julia b/Task/Happy-numbers/Julia/happy-numbers-2.julia index c56966e92e..82b71edb0c 100644 --- a/Task/Happy-numbers/Julia/happy-numbers-2.julia +++ b/Task/Happy-numbers/Julia/happy-numbers-2.julia @@ -3,9 +3,9 @@ sumhappy(n) = sum(x->x^2, digits(n)) function ishappy(x, mem = []) x == 1? true : x in mem? false : - ishappy(sumhappy(x),[mem, x]) + ishappy(sumhappy(x),[mem ; x]) end nexthappy (x) = ishappy(x+1) ? x+1 : nexthappy(x+1) -happy(n) = [z = 1, [z = nexthappy(z) for i = 1:n-1]] +happy(n) = [z = 1 ; [z = nexthappy(z) for i = 1:n-1]] diff --git a/Task/Happy-numbers/Perl-6/happy-numbers-1.pl6 b/Task/Happy-numbers/Perl-6/happy-numbers-1.pl6 index f89211b365..2b49192cae 100644 --- a/Task/Happy-numbers/Perl-6/happy-numbers-1.pl6 +++ b/Task/Happy-numbers/Perl-6/happy-numbers-1.pl6 @@ -1,6 +1,6 @@ sub happy (Int $n is copy --> Bool) { - my %seen; loop { + state %seen; $n = [+] $n.comb.map: { $_ ** 2 } return True if $n == 1; return False if %seen{$n}++; diff --git a/Task/Happy-numbers/Perl-6/happy-numbers-2.pl6 b/Task/Happy-numbers/Perl-6/happy-numbers-2.pl6 index 311d293e03..baf2b5548f 100644 --- a/Task/Happy-numbers/Perl-6/happy-numbers-2.pl6 +++ b/Task/Happy-numbers/Perl-6/happy-numbers-2.pl6 @@ -1,4 +1,4 @@ -my @happy := gather for 1..* -> $number { +my @happy = lazy gather for 1..* -> $number { my %stopper = 1 => 1; my $n = $number; repeat until %stopper{$n}++ { diff --git a/Task/Happy-numbers/REXX/happy-numbers-1.rexx b/Task/Happy-numbers/REXX/happy-numbers-1.rexx index 5eaa968e55..d250d87058 100644 --- a/Task/Happy-numbers/REXX/happy-numbers-1.rexx +++ b/Task/Happy-numbers/REXX/happy-numbers-1.rexx @@ -1,19 +1,19 @@ -/*REXX program displays eight (or a specified limit) happy numbers. */ -parse arg limit . /*get optional argument LIMIT. */ -if limit=='' | limit==',' then limit=8 /*Not specified? Set LIMIT to 8.*/ -haps=0 /*count of happy numbers so far. */ +/*REXX program computes and displays a specified number of happy numbers. */ +parse arg limit . /*get optional arguments from the C.L. */ +if limit=='' | limit==',' then limit=8 /*Not specified? Then use the default.*/ +haps=0 /*count of the happy numbers (so far).*/ - do n=1 while hapssw then do /*if the list is too long, split */ - say strip($) /*and display what we've got.*/ - $=n /*set next line to overflow. */ - end /* [↑] now contains overlow.*/ + @.n=1 /*mark N as a happy number. */ + haps=haps+1 /*bump the count of the happy numbers. */ + if hapssw then do /*if the list is too long, then split */ + say strip($) /*··· and display what we've got. */ + $=n /*Set the next line to overflow. */ + end /* [↑] now contains overflow. */ end /*n*/ -if $\='' then say strip($) /*display any residual happy nums*/ - /*stick a fork in it, we're done.*/ - /*stick a fork in it, we're done.*/ +if $\='' then say strip($) /*display any residual happy numbers. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Happy-numbers/VBScript/happy-numbers.vb b/Task/Happy-numbers/VBScript/happy-numbers.vb new file mode 100644 index 0000000000..42f73f84ce --- /dev/null +++ b/Task/Happy-numbers/VBScript/happy-numbers.vb @@ -0,0 +1,30 @@ +count = 0 +firsteigth="" +For i = 1 To 100 + If IsHappy(CInt(i)) Then + firsteight = firsteight & i & "," + count = count + 1 + End If + If count = 8 Then + Exit For + End If +Next +WScript.Echo firsteight + +Function IsHappy(n) + IsHappy = False + m = 0 + Do Until m = 60 + sum = 0 + For j = 1 To Len(n) + sum = sum + (Mid(n,j,1))^2 + Next + If sum = 1 Then + IsHappy = True + Exit Do + Else + n = sum + m = m + 1 + End If + Loop +End Function diff --git a/Task/Harshad-or-Niven-series/ALGOL-68/harshad-or-niven-series.alg b/Task/Harshad-or-Niven-series/ALGOL-68/harshad-or-niven-series.alg new file mode 100644 index 0000000000..aeef759076 --- /dev/null +++ b/Task/Harshad-or-Niven-series/ALGOL-68/harshad-or-niven-series.alg @@ -0,0 +1,13 @@ +BEGIN + PROC digit sum = (INT i) INT : + BEGIN + INT res := i %* 10, h := i; + WHILE (h %:= 10) > 0 DO res +:= h %* 10 OD; + res + END; + INT found := 0; + FOR i WHILE found < 20 DO + (i %* digit sum (i) = 0 | found +:= 1; printf (($g(0)", "$, i)) ) OD; + FOR i FROM 1001 DO + (i %* digit sum (i) = 0 | printf (($g(0)l$, i)); stop) OD +END diff --git a/Task/Harshad-or-Niven-series/Befunge/harshad-or-niven-series.bf b/Task/Harshad-or-Niven-series/Befunge/harshad-or-niven-series.bf new file mode 100644 index 0000000000..118113aa83 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Befunge/harshad-or-niven-series.bf @@ -0,0 +1,5 @@ +45*1>::01-\>:55+%\vv\0< +>\1+^ + <|:/<+55<` : +^_>1-\:.v@1>\:0\`#v_+\^ +>^1\,+55<.^_:#%$:#<"}"v +^!:\_ ^###< !`*8< diff --git a/Task/Harshad-or-Niven-series/C++/harshad-or-niven-series.cpp b/Task/Harshad-or-Niven-series/C++/harshad-or-niven-series.cpp new file mode 100644 index 0000000000..cf9590ae6a --- /dev/null +++ b/Task/Harshad-or-Niven-series/C++/harshad-or-niven-series.cpp @@ -0,0 +1,34 @@ +#include +#include + +int sumDigits ( int number ) { + int sum = 0 ; + while ( number != 0 ) { + sum += number % 10 ; + number /= 10 ; + } + return sum ; +} + +bool isHarshad ( int number ) { + return number % ( sumDigits ( number ) ) == 0 ; +} + +int main( ) { + std::vector harshads ; + int i = 0 ; + while ( harshads.size( ) != 20 ) { + i++ ; + if ( isHarshad ( i ) ) + harshads.push_back( i ) ; + } + std::cout << "The first 20 Harshad numbers:\n" ; + for ( int number : harshads ) + std::cout << number << " " ; + std::cout << std::endl ; + int start = 1001 ; + while ( ! ( isHarshad ( start ) ) ) + start++ ; + std::cout << "The smallest Harshad number greater than 1000 : " << start << '\n' ; + return 0 ; +} diff --git a/Task/Harshad-or-Niven-series/Elixir/harshad-or-niven-series.elixir b/Task/Harshad-or-Niven-series/Elixir/harshad-or-niven-series.elixir new file mode 100644 index 0000000000..83f7e718ef --- /dev/null +++ b/Task/Harshad-or-Niven-series/Elixir/harshad-or-niven-series.elixir @@ -0,0 +1,12 @@ +defmodule Harshad do + def series, do: Stream.iterate(1, &(&1+1)) |> Stream.filter(&(number?(&1))) + + def number?(n), do: rem(n, digit_sum(n, 0)) == 0 + + defp digit_sum(0, sum), do: sum + defp digit_sum(n, sum), do: digit_sum(div(n, 10), sum + rem(n, 10)) +end + +IO.inspect Harshad.series |> Enum.take(20) + +IO.inspect Harshad.series |> Stream.drop_while(&(&1 <= 1000)) |> Enum.take(1) |> hd diff --git a/Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series.erl b/Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series-1.erl similarity index 100% rename from Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series.erl rename to Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series-1.erl diff --git a/Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series-2.erl b/Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series-2.erl new file mode 100644 index 0000000000..8cf091db30 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Erlang/harshad-or-niven-series-2.erl @@ -0,0 +1,30 @@ +-module(harshad). +-export([main/0,harshad/1,seq/1]). + +% We return the number R if harshad, else 0 +harshad(R) -> + case R + rem lists:sum([X - $0|| X <- erlang:integer_to_list(R)]) of 0 + -> R; _ -> 0 end. + +% build a list of harshads retrieving input from harshad(R) +% filter out the nulls and return +hlist(A,B) -> + RL = [ harshad(X) || X <- lists:seq(A,B) ], + lists:filter( fun(X) -> X > 0 end, RL). + +seq(Total) -> seq(Total, [], 0). + +seq(Total,L,_) when length(L) == Total-> L; +seq(Total,L,Acc) when length(L) < Total -> + NL = hlist(1,Total + Acc), + seq(Total,NL,Acc+1). + +gt(_,L) when length(L) == 1 -> hd(L); +gt(X,_) -> + NL = hlist(X+1,X+2), + gt(X+2,NL). + +main() -> + io:format("seq(20): ~w~n", [ seq(20) ]), + io:format("gt(1000): ~w~n", [ gt(1000,[]) ]). diff --git a/Task/Harshad-or-Niven-series/J/harshad-or-niven-series.j b/Task/Harshad-or-Niven-series/J/harshad-or-niven-series.j index a4620457db..8d80f5f144 100644 --- a/Task/Harshad-or-Niven-series/J/harshad-or-niven-series.j +++ b/Task/Harshad-or-Niven-series/J/harshad-or-niven-series.j @@ -11,5 +11,5 @@ assert 1002 -: nextHarshad 1000 NB. next Harshad number in base 6. Input and output are in base 6. NB. Verification left to you, gentle programmer. nextHarshad_base_6 =: (>: Until (6&isHarshad))@:>: - 6#.inv nextHarshad_base_6 6b23235 -2 3 2 5 3 + ' '-.~":6#.inv nextHarshad_base_6 6b23235 +23253 diff --git a/Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series.js b/Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series.js new file mode 100644 index 0000000000..c56ee81621 --- /dev/null +++ b/Task/Harshad-or-Niven-series/JavaScript/harshad-or-niven-series.js @@ -0,0 +1,24 @@ +function isHarshad(n) { + var s = 0; + var n_str = new String(n); + for (var i = 0; i < n_str.length; ++i) { + s += parseInt(n_str.charAt(i)); + } + return n % s === 0; +} + +var count = 0; +var harshads = []; + +for (var n = 1; count < 20; ++n) { + if (isHarshad(n)) { + count++; + harshads.push(n); + } +} + +console.log(harshads.join(" ")); + +var h = 1000; +while (!isHarshad(++h)); +console.log(h); diff --git a/Task/Harshad-or-Niven-series/Lua/harshad-or-niven-series.lua b/Task/Harshad-or-Niven-series/Lua/harshad-or-niven-series.lua new file mode 100644 index 0000000000..6103f19e24 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Lua/harshad-or-niven-series.lua @@ -0,0 +1,28 @@ +function isHarshad(n) + local s=0 + local n_str=tostring(n) + for i=1,#n_str do + s=s+tonumber(n_str:sub(i,i)) + end + return n%s==0 +end + +local count=0 +local harshads={} +local n=1 + +while count<20 do + if isHarshad(n) then + count=count+1 + table.insert(harshads, n) + end + n=n+1 +end + +print(table.concat(harshads, " ")) + +local h=1001 +while not isHarshad(h) do + h=h+1 +end +print(h) diff --git a/Task/Harshad-or-Niven-series/Perl-6/harshad-or-niven-series.pl6 b/Task/Harshad-or-Niven-series/Perl-6/harshad-or-niven-series.pl6 index 5ad27f71ef..e51bdf7806 100644 --- a/Task/Harshad-or-Niven-series/Perl-6/harshad-or-niven-series.pl6 +++ b/Task/Harshad-or-Niven-series/Perl-6/harshad-or-niven-series.pl6 @@ -1,4 +1,4 @@ -constant harshad = grep { $_ %% [+] .comb }, 1 .. *; +constant @harshad = grep { $_ %% [+] .comb }, 1 .. *; -say harshad[^20]; -say harshad.first: * > 1000; +say @harshad[^20]; +say @harshad.first: * > 1000; diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx index 87c9149a59..548e988b4d 100644 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx @@ -1,24 +1,21 @@ -/*REXX program finds first X Niven numbers; also first Niven number > Y.*/ -parse arg X Y . /*get optional arguments: X Y */ -if X=='' then X=20 /*Not specified? Then use default*/ -if Y=='' then Y=1000 /* " " " " " */ -#=0; $= /*Niven# count; Niven# list. */ +/*REXX program finds the first A Niven numbers; also first Niven number > B.*/ +parse arg A B . /*get optional arguments from the C.L. */ +if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ +if B=='' | B==',' then B=1000 /* " " " " " " */ +numeric digits 1+max(8, length(A), length(B)) /*enable use of any sized #s*/ +#=0; $= /*set Niven numbers count; Niven list.*/ - do j=1 until #==X /*let's go Niven number hunting. */ - if j//sumDigs(j)\==0 then iterate /*Not a Niven number? Then skip.*/ - #=#+1; $=$ j /*bump Niven# count; add to list.*/ - end /*j*/ + do j=1 until #==A /* [↓] let's go Niven number hunting. */ + if j//sumDigs(j)==0 then do; #=#+1; $=$ j; end /*bump count; append──►list.*/ + end /*j*/ -say 'first' X 'Niven numbers:' $ +say 'first' A 'Niven numbers:' $ - do t=Y+1 /*let's go Niven number searching*/ - if t//sumDigs(t)\==0 then iterate /*Not a Niven number? Then skip.*/ - if t>Y then leave /*if greater than Y, go & show it*/ - end /*t*/ + do t=B+1 until t//sumDigs(t)==0; end /*hunt for a Niven (or Harshad) number.*/ -say 'first Niven number >' Y " is: " t -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SUMDIGS subroutine──────────────────*/ -sumDigs: procedure; parse arg ?; sum = left(?,1) - do k=2 to length(?); sum = sum+substr(?,k,1); end /*k*/ -return sum +say 'first Niven number >' B " is: " t +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sumDigs: procedure; parse arg x; s=0 + do k=1 for length(x); s=s+substr(x,k,1); end /*k*/ + return s diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx index 72bc3413b1..c091915ffd 100644 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx @@ -1,23 +1,21 @@ -/*REXX program finds first X Niven numbers; also first Niven number > Y.*/ -parse arg X Y . /*get optional arguments: X Y */ -if X=='' then X=20 /*Not specified? Then use default*/ -if Y=='' then Y=1000 /* " " " " " */ -#=0; $= /*Niven# count; Niven# list. */ +/*REXX program finds the first A Niven numbers; also first Niven number > B.*/ +parse arg A B . /*get optional arguments from the C.L. */ +if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ +if B=='' | B==',' then B=1000 /* " " " " " " */ +numeric digits 1+max(8, length(A), length(B)) /*enable use of any sized #s*/ +#=0; $= /*set Niven numbers count; Niven list.*/ - do j=1 until #==X /*let's go Niven number hunting. */ - if \isNiven(j) then iterate /*Not a Niven number? Then skip.*/ - #=#+1; $=$ j /*bump Niven# count; add to list.*/ - end /*j*/ + do j=1 until #==A /* [↓] let's go Niven number hunting. */ + if isNiven(j) then do; #=#+1; $=$ j; end /*bump count; append──►list.*/ + end /*j*/ -say 'first' X 'Niven numbers:' $ +say 'first' A 'Niven numbers:' $ - do t=Y+1 /*let's go Niven number searching*/ - if isNiven(t) & t>y then leave /*is a Niven # AND > Y, show it*/ - end /*t*/ + do t=B+1 until isNiven(t); end /*hunt for a Niven (or Harshad) number.*/ -say 'first Niven number >' Y " is: " t -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────isNiven subroutine──────────────────*/ -isNiven: procedure; parse arg ?; sum = left(?,1) - do k=2 to length(?); sum = sum+substr(?,k,1); end /*k*/ -return ?//sum==0 +say 'first Niven number >' B " is: " t +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +isNiven: procedure; parse arg x; s=0 + do k=1 for length(x); s=s+substr(x,k,1); end /*k*/ + return x//s==0 diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-3.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-3.rexx new file mode 100644 index 0000000000..50240f0ad5 --- /dev/null +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-3.rexx @@ -0,0 +1,22 @@ +/*REXX program finds the first A Niven numbers; also first Niven number > B.*/ +parse arg A B . /*get optional arguments from the C.L. */ +if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ +if B=='' | B==',' then B=1000 /* " " " " " " */ +numeric digits 1+max(8, length(A), length(B)) /*enable use of any sized #s*/ +#=0; $= /*set Niven numbers count; Niven list.*/ + + do j=1 until #==A /* [↓] let's go Niven number hunting. */ + if isNiven(j) then do; #=#+1; $=$ j; end /*bump count; append──►list.*/ + end /*j*/ + +say 'first' A 'Niven numbers:' $ + + do t=B+1 until isNiven(t); end /*hunt for a Niven (or Harshad) number.*/ + +say 'first Niven number >' B " is: " t +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +isNiven: procedure; parse arg x 1 s 2 q /*use first digit for S (the sum),*/ + do while q\==''; parse var q _ 2 q; s=s+_; end /*k*/ + /* ↑ */ + return x//s==0 /* └──◄is destructively parsed*/ diff --git a/Task/Harshad-or-Niven-series/VBScript/harshad-or-niven-series.vb b/Task/Harshad-or-Niven-series/VBScript/harshad-or-niven-series.vb new file mode 100644 index 0000000000..73f823165e --- /dev/null +++ b/Task/Harshad-or-Niven-series/VBScript/harshad-or-niven-series.vb @@ -0,0 +1,36 @@ +n = 0 +m = 1 +first20 = "" +after1k = "" + +Do + If IsHarshad(m) And n <= 20 Then + first20 = first20 & m & ", " + n = n + 1 + m = m + 1 + ElseIf IsHarshad(m) And m > 1000 Then + after1k = m + Exit Do + Else + m = m + 1 + End If +Loop + +WScript.StdOut.Write "First twenty Harshad numbers are: " +WScript.StdOut.WriteLine +WScript.StdOut.Write first20 +WScript.StdOut.WriteLine +WScript.StdOut.Write "The first Harshad number after 1000 is: " +WScript.StdOut.WriteLine +WScript.StdOut.Write after1k + +Function IsHarshad(s) + IsHarshad = False + sum = 0 + For i = 1 To Len(s) + sum = sum + CInt(Mid(s,i,1)) + Next + If s Mod sum = 0 Then + IsHarshad = True + End If +End Function diff --git a/Task/Hash-from-two-arrays/Elixir/hash-from-two-arrays.elixir b/Task/Hash-from-two-arrays/Elixir/hash-from-two-arrays.elixir new file mode 100644 index 0000000000..48672f47da --- /dev/null +++ b/Task/Hash-from-two-arrays/Elixir/hash-from-two-arrays.elixir @@ -0,0 +1,6 @@ +iex(1)> keys = [:one, :two, :three] +[:one, :two, :three] +iex(2)> values = [1, 2, 3] +[1, 2, 3] +iex(3)> Enum.zip(keys, values) |> Enum.into(Map.new) +%{one: 1, three: 3, two: 2} diff --git a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-1.pl6 b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-1.pl6 index 3c5091636c..3af0bf6178 100644 --- a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-1.pl6 +++ b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-1.pl6 @@ -1,3 +1,3 @@ my @keys = ; my @vals = ^5; -my %hash = @keys Z @vals; +my %hash = flat @keys Z @vals; diff --git a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-2.pl6 b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-2.pl6 index 8d2e3faa68..4a1c69dfbf 100644 --- a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-2.pl6 +++ b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-2.pl6 @@ -1,2 +1,2 @@ my @v = ; -my %hash = @v Z @v.keys; +my %hash = @v Z=> @v.keys; diff --git a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-4.pl6 b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-4.pl6 index a2603b135f..d6aa0241b9 100644 --- a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-4.pl6 +++ b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays-4.pl6 @@ -1 +1 @@ -{ Z=> ^5 } +%( Z=> ^5 ) diff --git a/Task/Hash-join/Elixir/hash-join.elixir b/Task/Hash-join/Elixir/hash-join.elixir new file mode 100644 index 0000000000..6b49efebdb --- /dev/null +++ b/Task/Hash-join/Elixir/hash-join.elixir @@ -0,0 +1,20 @@ +defmodule Hash do + def join(table1, index1, table2, index2) do + h = Enum.group_by(table1, fn s -> elem(s, index1) end) + Enum.flat_map(table2, fn r -> + Enum.map(h[elem(r, index2)], fn s -> {s, r} end) + end) + end +end + +table1 = [{27, "Jonah"}, + {18, "Alan"}, + {28, "Glory"}, + {18, "Popeye"}, + {28, "Alan"}] +table2 = [{"Jonah", "Whales"}, + {"Jonah", "Spiders"}, + {"Alan", "Ghosts"}, + {"Alan", "Zombies"}, + {"Glory", "Buffy"}] +Hash.join(table1, 1, table2, 0) |> Enum.each(&IO.inspect &1) diff --git a/Task/Hash-join/REXX/hash-join.rexx b/Task/Hash-join/REXX/hash-join.rexx index b42a075a3b..6b4f907512 100644 --- a/Task/Hash-join/REXX/hash-join.rexx +++ b/Task/Hash-join/REXX/hash-join.rexx @@ -1,33 +1,32 @@ -/*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.*/ +/*REXX program demonstrates the classic hash join algorithm for two 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 (array). */ + do #=1 while S.#\==''; parse var S.# age name /*extract information*/ + hash.name=hash.name # /*build a hash table entry with its idx*/ + end /*#*/ /* [↑] REXX does the heavy work here. */ +#=#-1 /*adjust for the DO loop (#) overage.*/ + do j=1 while R.j\=='' /*process a nemesis for a name element.*/ + parse var R.j x nemesis /*extract the name and its nemesis. */ + if hash.x=='' then do; #=#+1 /*Not in hash? Then a new name; bump #*/ + S.#=',' x /*add a new name to the S table. */ + hash.x=# /* " " " " " " hash " */ + end /* [↑] this DO isn't used today. */ + do k=1 for words(hash.x); _=word(hash.x,k) /*get the pointer.*/ + S._=S._ nemesis /*add the 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,_) +_='─' /*the character used for the separator.*/ +pad=left('',6-2) /*spacing used in header and the 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.*/ + do n=1 for #; parse var S.n age name nems /*get information.*/ + if nems=='' then iterate /*No nemesis? Skip*/ + say pad right(age,3) pad center(name,20) pad nems /*display an S. */ end /*n*/ - /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Hash-join/VBScript/hash-join.vb b/Task/Hash-join/VBScript/hash-join.vb new file mode 100644 index 0000000000..647bba39d0 --- /dev/null +++ b/Task/Hash-join/VBScript/hash-join.vb @@ -0,0 +1,30 @@ +Dim t_age(4,1) +t_age(0,0) = 27 : t_age(0,1) = "Jonah" +t_age(1,0) = 18 : t_age(1,1) = "Alan" +t_age(2,0) = 28 : t_age(2,1) = "Glory" +t_age(3,0) = 18 : t_age(3,1) = "Popeye" +t_age(4,0) = 28 : t_age(4,1) = "Alan" + +Dim t_nemesis(4,1) +t_nemesis(0,0) = "Jonah" : t_nemesis(0,1) = "Whales" +t_nemesis(1,0) = "Jonah" : t_nemesis(1,1) = "Spiders" +t_nemesis(2,0) = "Alan" : t_nemesis(2,1) = "Ghosts" +t_nemesis(3,0) = "Alan" : t_nemesis(3,1) = "Zombies" +t_nemesis(4,0) = "Glory" : t_nemesis(4,1) = "Buffy" + +Call hash_join(t_age,1,t_nemesis,0) + +Sub hash_join(table_1,index_1,table_2,index_2) + Set hash = CreateObject("Scripting.Dictionary") + For i = 0 To UBound(table_1) + hash.Add i,Array(table_1(i,0),table_1(i,1)) + Next + For j = 0 To UBound(table_2) + For Each key In hash.Keys + If hash(key)(index_1) = table_2(j,index_2) Then + WScript.StdOut.WriteLine hash(key)(0) & "," & hash(key)(1) &_ + " = " & table_2(j,0) & "," & table_2(j,1) + End If + Next + Next +End Sub diff --git a/Task/Haversine-formula/00DESCRIPTION b/Task/Haversine-formula/00DESCRIPTION index 6e4fa4d0ed..2b280115aa 100644 --- a/Task/Haversine-formula/00DESCRIPTION +++ b/Task/Haversine-formula/00DESCRIPTION @@ -30,3 +30,13 @@ As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways).

+ +Most of the examples below adopted Kaimbridge's recommended value of +6372.8 km for the earth radius. However, the derivation of this +[http://math.wikia.com/wiki/Ellipsoidal_quadratic_mean_radius ellipsoidal quadratic mean radius] +is wrong (the averaging over azimuth is biased). When applying these +examples in real applications, it is better to use the +[https://en.wikipedia.org/wiki/Earth_radius#Mean_radius mean earth radius], +6371 km. This value is recommended by the International Union of +Geodesy and Geophysics and it minimizes the RMS relative error between the +great circle and geodesic distance. diff --git a/Task/Haversine-formula/Delphi/haversine-formula.delphi b/Task/Haversine-formula/Delphi/haversine-formula.delphi new file mode 100644 index 0000000000..93f6bac179 --- /dev/null +++ b/Task/Haversine-formula/Delphi/haversine-formula.delphi @@ -0,0 +1,20 @@ +program HaversineDemo; +uses Math; + +function HaversineDist(th1, ph1, th2, ph2:double):double; +const diameter = 2 * 6372.8; +var dx, dy, dz:double; +begin + ph1 := degtorad(ph1 - ph2); + th1 := degtorad(th1); + th2 := degtorad(th2); + + dz := sin(th1) - sin(th2); + dx := cos(ph1) * cos(th1) - cos(th2); + dy := sin(ph1) * cos(th1); + Result := arcsin(sqrt(sqr(dx) + sqr(dy) + sqr(dz)) / 2) * diameter; +end; + +begin + Writeln('Haversine distance: ', HaversineDist(36.12, -86.67, 33.94, -118.4):7:2, ' km.'); +end. diff --git a/Task/Haversine-formula/Elixir/haversine-formula.elixir b/Task/Haversine-formula/Elixir/haversine-formula.elixir new file mode 100644 index 0000000000..0adf7edb80 --- /dev/null +++ b/Task/Haversine-formula/Elixir/haversine-formula.elixir @@ -0,0 +1,14 @@ +defmodule Haversine do + @v :math.pi / 180 + @r 6372.8 # km for the earth radius + def distance({lat1, long1}, {lat2, long2}) do + dlat = :math.sin((lat2 - lat1) * @v / 2) + dlong = :math.sin((long2 - long1) * @v / 2) + a = dlat * dlat + dlong * dlong * :math.cos(lat1 * @v) * :math.cos(lat2 * @v) + @r * 2 * :math.asin(:math.sqrt(a)) + end +end + +bna = {36.12, -86.67} +lax = {33.94, -118.40} +IO.puts Haversine.distance(bna, lax) diff --git a/Task/Haversine-formula/Fortran/haversine-formula.f b/Task/Haversine-formula/Fortran/haversine-formula.f index fa0a9c8436..87878fde0e 100644 --- a/Task/Haversine-formula/Fortran/haversine-formula.f +++ b/Task/Haversine-formula/Fortran/haversine-formula.f @@ -10,10 +10,10 @@ program example function to_radian(degree) result(rad) ! degrees to radians real,intent(in) :: degree - real :: rad,pi + real, parameter :: deg_to_rad = atan(1.0)/45 ! exploit intrinsic atan to generate pi/180 runtime constant + real :: rad - pi = 4*atan(1.0) ! exploit intrinsic atan to generate pi - rad = degree*pi/180 + rad = degree*deg_to_rad end function to_radian function haversine(deglat1,deglon1,deglat2,deglon2) result (dist) diff --git a/Task/Haversine-formula/Java/haversine-formula.java b/Task/Haversine-formula/Java/haversine-formula.java index d6f0ba8370..d84f3c52f7 100644 --- a/Task/Haversine-formula/Java/haversine-formula.java +++ b/Task/Haversine-formula/Java/haversine-formula.java @@ -6,7 +6,7 @@ public static double haversine(double lat1, double lon1, double lat2, double lon lat1 = Math.toRadians(lat1); lat2 = Math.toRadians(lat2); - double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2); + double a = Math.pow(Math.sin(dLat / 2),2) + Math.pow(Math.sin(dLon / 2),2) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.asin(Math.sqrt(a)); return R * c; } diff --git a/Task/Haversine-formula/Lua/haversine-formula-1.lua b/Task/Haversine-formula/Lua/haversine-formula-1.lua new file mode 100644 index 0000000000..79e694fedf --- /dev/null +++ b/Task/Haversine-formula/Lua/haversine-formula-1.lua @@ -0,0 +1,6 @@ +local function haversine(x1, y1, x2, y2) +r=0.017453292519943295769236907684886127; +x1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1; +a = math.pow(math.sin(dx/2),2) + math.cos(x1) * math.cos(x2) * math.pow(math.sin(dy/2),2); c = 2 * math.asin(math.sqrt(a)); d = 6372.8 * c; +return d; +end diff --git a/Task/Haversine-formula/Lua/haversine-formula-2.lua b/Task/Haversine-formula/Lua/haversine-formula-2.lua new file mode 100644 index 0000000000..beed5986dd --- /dev/null +++ b/Task/Haversine-formula/Lua/haversine-formula-2.lua @@ -0,0 +1 @@ +print(haversine(36.12, -86.67, 33.94, -118.4)); diff --git a/Task/Haversine-formula/Maple/haversine-formula-1.maple b/Task/Haversine-formula/Maple/haversine-formula-1.maple new file mode 100644 index 0000000000..20d32a0348 --- /dev/null +++ b/Task/Haversine-formula/Maple/haversine-formula-1.maple @@ -0,0 +1 @@ +distance := (theta1, phi1, theta2, phi2)->2*6378.14*arcsin( sqrt((1-cos(theta2-theta1))/2 + cos(theta1)*cos(theta2)*(1-cos(phi2-phi1))/2) ); diff --git a/Task/Haversine-formula/Maple/haversine-formula-2.maple b/Task/Haversine-formula/Maple/haversine-formula-2.maple new file mode 100644 index 0000000000..28f2134c92 --- /dev/null +++ b/Task/Haversine-formula/Maple/haversine-formula-2.maple @@ -0,0 +1,2 @@ +haversin := theta->(1-cos(theta))/2; +distance := (theta1, phi1, theta2, phi2)->2*6378.14*arcsin( sqrt(haversin(theta2-theta1) + cos(theta1)*cos(theta2)*haversin(phi2-phi1)) ); diff --git a/Task/Haversine-formula/Perl/haversine-formula.pl b/Task/Haversine-formula/Perl/haversine-formula.pl new file mode 100644 index 0000000000..b89298f527 --- /dev/null +++ b/Task/Haversine-formula/Perl/haversine-formula.pl @@ -0,0 +1,18 @@ +use ntheory qw/Pi/; + +sub asin { my $x = shift; atan2($x, sqrt(1-$x*$x)); } + +sub surfacedist { + my($lat1, $lon1, $lat2, $lon2) = @_; + my $radius = 6372.8; + my $radians = Pi() / 180;; + my $dlat = ($lat2 - $lat1) * $radians; + my $dlon = ($lon2 - $lon1) * $radians; + $lat1 *= $radians; + $lat2 *= $radians; + my $a = sin($dlat/2)**2 + cos($lat1) * cos($lat2) * sin($dlon/2)**2; + my $c = 2 * asin(sqrt($a)); + return $radius * $c; +} + +printf "Distance: %.3f km\n", surfacedist(36.12, -86.67, 33.94, -118.4); diff --git a/Task/Haversine-formula/REXX/haversine-formula.rexx b/Task/Haversine-formula/REXX/haversine-formula.rexx new file mode 100644 index 0000000000..3d5a0aa024 --- /dev/null +++ b/Task/Haversine-formula/REXX/haversine-formula.rexx @@ -0,0 +1,59 @@ +/*REXX program calculates distance between Nashville and Los Angles airports.*/ +call pi; numeric digits length(pi)%2 /*use ½ of the decimal digs that PI has*/ +say " Nashville: north 36º 7.2', west 86º 40.2' = 36.12º, -86.67º" +say " Los Angles: north 33º 56.4', west 118º 24.0' = 33.94º, -118.40º" +@using_radius='using the mean radius of the earth as ' /*literal for SAY.*/ +radii.=.; radii.1=6372.8; radii.2=6371 /*mean radii of the earth in kilometers*/ +say; m=1/0.621371192237 /*M: length of one mile in kilometers.*/ + do radius=1 while radii.radius\==. /*calc. distance using specific radius.*/ + d=surfaceDistance( 36.12, -86.67, 33.94, -118.4, radii.radius) + say + say center(@using_radius radii.radius ' kilometers', 75, '─') + say ' Distance between: ' format(d/1 ,,2) " kilometers," + say ' or ' format(d/m ,,2) " statute miles," + say ' or ' format(d/m*5280/6076.1,,2) " nautical (or air miles)." + end /*radius*/ /*only display └───◄ 2 digits of dist.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +surfaceDistance: arg th1,ph1,th2,ph2,r /*use haversine formula for distance.*/ +numeric digits digits()*2 /*double the number of decimal digits. */ + ph1 = d2r(ph1-ph2) /*convert degrees ──► radians & reduce.*/ + th1 = d2r(th1); th2 = d2r(th2) /* " " " " " " */ + x = cos(ph1) * cos(th1) - cos(th2) + y = sin(ph1) * cos(th1) + z = sin(th1) - sin(th2) +return Asin( sqrt( x**2 + y**2 + z**2) / 2 ) * r * 2 +/*═════════════════════════════general subroutines════════════════════════════*/ +d2d: return arg(1) // 360 /*normalize degrees to a unit circle. */ +d2r: return r2r(arg(1)*pi() / 180) /*normalize and convert deg ──► radians*/ +r2d: return d2d((arg(1)*180 / pi())) /*normalize and convert rad ──► degrees*/ +r2r: return arg(1) // (pi()*2) /*normalize radians to a unit circle. */ +p: return word(arg(1),1) /*pick the first of two words (numbers)*/ +pi: pi=3.141592653589793238462643383279502884197169399375105820975; return pi + +Acos: procedure; parse arg x; if x<-1 | x>1 then call $81r -1,1,x,"ACOS" + return .5*pi()-Asin(x) /*$81R says argument X is out of range,*/ + /* ··· and the sub isn't included here.*/ +Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a + if a>1 then call $81r -1,1,x,"ASIN" /*X argument is out of range.*/ + if a>=sqrt(2)*.5 then return sign(x) * Acos(sqrt(1-aa), '-ASIN') + do j=2 by 2 until p=z; p=z; o=o*aa*(j-1)/j; z=z+o/(j+1); end + return z /* [↑] compute until no more noise. */ + +cos: procedure; parse arg x; x=r2r(x); a=abs(x); Hpi=pi*.5 + numeric fuzz min(6,digits()-3); if a=pi() then return -1 + if a=Hpi | a=Hpi*3 then return 0; if a=pi()/3 then return .5 + if a=pi()*2/3 then return -.5; return .sinCos(1,1,-1) + +sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5, digits()-3) + if abs(x)=pi() then return 0; return .sinCos(x,x,1) + +.sinCos: parse arg z,_,i; q=x*x; p=z; do k=2 by 2; _=-_*q/(k*(k+i)); z=z+_ + if z=p then leave; p=z; end; return z /*used by SIN & COS*/ + +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Haversine-formula/Run-BASIC/haversine-formula.run b/Task/Haversine-formula/Run-BASIC/haversine-formula.run index 8d85db7700..33593ecbca 100644 --- a/Task/Haversine-formula/Run-BASIC/haversine-formula.run +++ b/Task/Haversine-formula/Run-BASIC/haversine-formula.run @@ -9,11 +9,12 @@ Lt2 = 33.94 * D2R hDist = asn((dx^2 + dy^2 + dz^2)^0.5 /2) * diam print "Haversine distance: ";using("####.#############",hDist);" km." - 'Tips: ( 36 deg 7 min 12 sec ) = print 36+(7/60)+(12/3600). Produces: 36.12 deg + 'Tips: ( 36 deg 7 min 12 sec ) = print 36+(7/60)+(12/3600). Produces: 36.12 deg. ' - ' Put "36.12,-86.67" into http://maps.google.com (no quotes). Click map, - ' satellite, center the pin "A", zoom in, and see airport. Extra: in "Get - ' Directions" enter 36.12,-86.66999 and see pin "B" about one meter away. - ' (.00089846878 km., or 35.37 in.) - ' - ' This code also works in Liberty BASIC. + ' http://maps.google.com + ' Search 36.12,-86.67 + ' Earth. + ' Center the pin, zoom airport. + ' Directions (destination). + ' 36.12.-86.66999 + ' Distance is 35.37 inches. diff --git a/Task/Hello-world-Line-printer/ALGOL-68/hello-world-line-printer.alg b/Task/Hello-world-Line-printer/ALGOL-68/hello-world-line-printer.alg new file mode 100644 index 0000000000..57e72a52e8 --- /dev/null +++ b/Task/Hello-world-Line-printer/ALGOL-68/hello-world-line-printer.alg @@ -0,0 +1,19 @@ +BEGIN + STRING printer name = "/dev/lp0"; + FILE line printer; + IF open (line printer, printer name, stand out channel) = 0 THEN + put (line printer, ("Hello world", newline)); + close (line printer) + ELSE + put (stand error, ("Can't contact line printer on ", printer name, newline)); + put (stand error, ("Trying to use lpr(1)", newline)); + PIPE printer pipe = execve child pipe ("lpr", "", ""); + IF pid OF printer pipe < 0 THEN + put (stand error, ("Oh dear, that didn't seem to work either. Giving up.", newline)); + stop + FI; + put (write OF printer pipe, ("Hello world", newline)); + close (read OF printer pipe); + close (write OF printer pipe) + FI +END diff --git a/Task/Hello-world-Line-printer/Fortran/hello-world-line-printer.f b/Task/Hello-world-Line-printer/Fortran/hello-world-line-printer.f new file mode 100644 index 0000000000..66271a3d43 --- /dev/null +++ b/Task/Hello-world-Line-printer/Fortran/hello-world-line-printer.f @@ -0,0 +1,3 @@ + WRITE (6,1) + 1 FORMAT ("+HELLO WORLD!") + END diff --git a/Task/Hello-world-Newbie/00DESCRIPTION b/Task/Hello-world-Newbie/00DESCRIPTION index 83b4dc0ee4..86510ff971 100644 --- a/Task/Hello-world-Newbie/00DESCRIPTION +++ b/Task/Hello-world-Newbie/00DESCRIPTION @@ -11,3 +11,5 @@ to run the languages' example in the [[Hello world/Text]] task. ;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. + +{{omit from|ABAP|There's no newbie frienly way to install ABAP. It's part of the enterprise NetWeaver Application Server.}} diff --git a/Task/Hello-world-Newbie/BASIC256/hello-world-newbie-1.basic256 b/Task/Hello-world-Newbie/BASIC256/hello-world-newbie-1.basic256 new file mode 100644 index 0000000000..856e9f2bdc --- /dev/null +++ b/Task/Hello-world-Newbie/BASIC256/hello-world-newbie-1.basic256 @@ -0,0 +1 @@ +Print "HelloWorld!" diff --git a/Task/Hello-world-Newbie/BASIC256/hello-world-newbie-2.basic256 b/Task/Hello-world-Newbie/BASIC256/hello-world-newbie-2.basic256 new file mode 100644 index 0000000000..a431ce58f6 --- /dev/null +++ b/Task/Hello-world-Newbie/BASIC256/hello-world-newbie-2.basic256 @@ -0,0 +1,4 @@ +clg # Clear the graphics screen +font "Arial",10,100 # Set the font style, size, and weight respectively +color black # Set the color... +text 0,0,"HelloWorld!" # Display in (x,y) the text HelloWorld! diff --git a/Task/Hello-world-Newbie/Common-Lisp/hello-world-newbie-1.lisp b/Task/Hello-world-Newbie/Common-Lisp/hello-world-newbie-1.lisp new file mode 100644 index 0000000000..32df744fbc --- /dev/null +++ b/Task/Hello-world-Newbie/Common-Lisp/hello-world-newbie-1.lisp @@ -0,0 +1 @@ +(format t "Hello world!~%") diff --git a/Task/Hello-world-Newbie/Common-Lisp/hello-world-newbie-2.lisp b/Task/Hello-world-Newbie/Common-Lisp/hello-world-newbie-2.lisp new file mode 100644 index 0000000000..52d26fffa0 --- /dev/null +++ b/Task/Hello-world-Newbie/Common-Lisp/hello-world-newbie-2.lisp @@ -0,0 +1 @@ +(load "hello.lisp") diff --git a/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-1.psh b/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-1.psh new file mode 100644 index 0000000000..5f0a6ab5af --- /dev/null +++ b/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-1.psh @@ -0,0 +1 @@ +"Hello, World!" #This is a comment. diff --git a/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-2.psh b/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-2.psh new file mode 100644 index 0000000000..4daef0ccd8 --- /dev/null +++ b/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-2.psh @@ -0,0 +1 @@ +wRiTe-HOsT "Hello, World!" #PowerShell is case-insensitive. diff --git a/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-3.psh b/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-3.psh new file mode 100644 index 0000000000..88817f9a76 --- /dev/null +++ b/Task/Hello-world-Newbie/PowerShell/hello-world-newbie-3.psh @@ -0,0 +1 @@ +Write-Host Hello`, World! #The backtick escapes the next character. diff --git a/Task/Hello-world-Newbie/Racket/hello-world-newbie.rkt b/Task/Hello-world-Newbie/Racket/hello-world-newbie.rkt new file mode 100644 index 0000000000..3300c5b2c9 --- /dev/null +++ b/Task/Hello-world-Newbie/Racket/hello-world-newbie.rkt @@ -0,0 +1,2 @@ +#lang racket +(displayln "Hello world!") diff --git a/Task/Hello-world-Newline-omission/AutoIt/hello-world-newline-omission.autoit b/Task/Hello-world-Newline-omission/AutoIt/hello-world-newline-omission.autoit new file mode 100644 index 0000000000..ea03e33b41 --- /dev/null +++ b/Task/Hello-world-Newline-omission/AutoIt/hello-world-newline-omission.autoit @@ -0,0 +1 @@ +ConsoleWrite("Goodbye, World!") diff --git a/Task/Hello-world-Newline-omission/Brainf---/hello-world-newline-omission.bf b/Task/Hello-world-Newline-omission/Brainf---/hello-world-newline-omission.bf new file mode 100644 index 0000000000..f7fa31cb1a --- /dev/null +++ b/Task/Hello-world-Newline-omission/Brainf---/hello-world-newline-omission.bf @@ -0,0 +1,3 @@ ++++++[>++++>+>+>++++>>+++<<<+<+<++[>++>+++>+++>++++>+>+[<]>>-]<-] +>>+.>>+..<.--.++>>+.<<+.>>>-.>++.[<]++++[>++++<-]>.>>.+++.------.<-.[>]<+. + G oo d b y e , W o r l d ! diff --git a/Task/Hello-world-Newline-omission/Emacs-Lisp/hello-world-newline-omission.l b/Task/Hello-world-Newline-omission/Emacs-Lisp/hello-world-newline-omission.l new file mode 100644 index 0000000000..977843a519 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Emacs-Lisp/hello-world-newline-omission.l @@ -0,0 +1 @@ +(insert "Goodbye, World!") diff --git a/Task/Hello-world-Newline-omission/J/hello-world-newline-omission-1.j b/Task/Hello-world-Newline-omission/J/hello-world-newline-omission-1.j new file mode 100644 index 0000000000..92cdc5315d --- /dev/null +++ b/Task/Hello-world-Newline-omission/J/hello-world-newline-omission-1.j @@ -0,0 +1,2 @@ + 'Goodbye, World!' 1!:3 <'/proc/self/fd/1' +Goodbye, World! diff --git a/Task/Hello-world-Newline-omission/J/hello-world-newline-omission-2.j b/Task/Hello-world-Newline-omission/J/hello-world-newline-omission-2.j new file mode 100644 index 0000000000..9d6e9a27b8 --- /dev/null +++ b/Task/Hello-world-Newline-omission/J/hello-world-newline-omission-2.j @@ -0,0 +1,3 @@ + load 'general/misc/prompt' + prompt 'Goodbye, World!' +Goodbye, World! diff --git a/Task/Hello-world-Newline-omission/J/hello-world-newline-omission.j b/Task/Hello-world-Newline-omission/J/hello-world-newline-omission.j deleted file mode 100644 index e73b2c1edc..0000000000 --- a/Task/Hello-world-Newline-omission/J/hello-world-newline-omission.j +++ /dev/null @@ -1,3 +0,0 @@ - load'misc' - prompt 'hello world' -hello world diff --git a/Task/Hello-world-Newline-omission/PowerShell/hello-world-newline-omission.psh b/Task/Hello-world-Newline-omission/PowerShell/hello-world-newline-omission.psh new file mode 100644 index 0000000000..9fa91ea6b0 --- /dev/null +++ b/Task/Hello-world-Newline-omission/PowerShell/hello-world-newline-omission.psh @@ -0,0 +1,2 @@ +Write-Host -NoNewLine "Goodbye, " +Write-Host -NoNewLine "World!" diff --git a/Task/Hello-world-Newline-omission/Rust/hello-world-newline-omission.rust b/Task/Hello-world-Newline-omission/Rust/hello-world-newline-omission.rust index 4ad3588602..68903eaed7 100644 --- a/Task/Hello-world-Newline-omission/Rust/hello-world-newline-omission.rust +++ b/Task/Hello-world-Newline-omission/Rust/hello-world-newline-omission.rust @@ -1,3 +1,3 @@ fn main () { - print!("Goodbye, World!"); + print!("Goodbye, World!"); } diff --git a/Task/Hello-world-Standard-error/00DESCRIPTION b/Task/Hello-world-Standard-error/00DESCRIPTION index e7d19a7c7d..8594e2f7dc 100644 --- a/Task/Hello-world-Standard-error/00DESCRIPTION +++ b/Task/Hello-world-Standard-error/00DESCRIPTION @@ -6,6 +6,7 @@ {{omit from|dc|Always prints to standard output.}} {{omit from|GUISS|Cannot customize error messages}} {{omit from|Integer BASIC}} +{{omit from|Jack|No other output stream available.}} {{omit from|TI-83 BASIC|Same reason as TI-89.}} {{omit from|TI-89 BASIC|no analogue to stderr, unless you count graph display vs. program IO}} {{omit from|Unlambda|No concept of standard error (or alternate output streams in general).}} diff --git a/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp b/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp index 9326f1286f..8089af8f0a 100644 --- a/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp +++ b/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp @@ -1,5 +1,5 @@ #include int main () { - std::cerr << "Goodbye, World!\n"; + std::cerr << "Goodbye, World!" << std::endl; } diff --git a/Task/Hello-world-Standard-error/Elixir/hello-world-standard-error.elixir b/Task/Hello-world-Standard-error/Elixir/hello-world-standard-error.elixir new file mode 100644 index 0000000000..f4242af8ae --- /dev/null +++ b/Task/Hello-world-Standard-error/Elixir/hello-world-standard-error.elixir @@ -0,0 +1 @@ +IO.puts :stderr, "Goodbye, World!" diff --git a/Task/Hello-world-Standard-error/Emacs-Lisp/hello-world-standard-error.l b/Task/Hello-world-Standard-error/Emacs-Lisp/hello-world-standard-error.l new file mode 100644 index 0000000000..035594d38a --- /dev/null +++ b/Task/Hello-world-Standard-error/Emacs-Lisp/hello-world-standard-error.l @@ -0,0 +1 @@ +(error "Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/Rust/hello-world-standard-error.rust b/Task/Hello-world-Standard-error/Rust/hello-world-standard-error.rust index 929082b400..a6b1cb50dd 100644 --- a/Task/Hello-world-Standard-error/Rust/hello-world-standard-error.rust +++ b/Task/Hello-world-Standard-error/Rust/hello-world-standard-error.rust @@ -1,7 +1,6 @@ -#![allow(unused_must_use)] -use std::io; +use std::io::{self,Write}; fn main() { let mut stderr = io::stderr(); - stderr.write(bytes!("Goodbye, World!\n")); + let bytes_read_or_error = stderr.write(b"Goodbye, World!\n"); } diff --git a/Task/Hello-world-Text/00DESCRIPTION b/Task/Hello-world-Text/00DESCRIPTION index 135fd15110..a47a3a264e 100644 --- a/Task/Hello-world-Text/00DESCRIPTION +++ b/Task/Hello-world-Text/00DESCRIPTION @@ -1,6 +1,6 @@ {{selection|Short Circuit|Console Program Basics}} [[Category:Simple]] -In this User Output task, the goal is to display the string "Goodbye, World!" [sic] on a text console. +In this User Output task, the goal is to display the string "Hello world!" [sic] on a text console. '''See also''' * [[Hello world/Graphical]] diff --git a/Task/Hello-world-Text/0815/hello-world-text.0815 b/Task/Hello-world-Text/0815/hello-world-text.0815 index b26fc123c9..7414c30d49 100644 --- a/Task/Hello-world-Text/0815/hello-world-text.0815 +++ b/Task/Hello-world-Text/0815/hello-world-text.0815 @@ -1,5 +1,4 @@ -<:47:x<:6F:=<:64:$=$$=$ -<:62:x<:79:=<:65:$=$=$ -<:2C:x<:20:=<:57:$=$=$ -<:6F:x<:72:=<:6C:$=$=$ -<:64:x<:21:=<:0D:$=$=$ +<:48:x<:65:=<:6C:$=$=$$~<:03:+ +$~<:ffffffffffffffb1:+$<:77:~$ +~<:fffffffffffff8:x+$~<:03:+$~ +<:06:x-$x<:0e:x-$=x<:43:x-$ diff --git a/Task/Hello-world-Text/360-Assembly/hello-world-text-1.360 b/Task/Hello-world-Text/360-Assembly/hello-world-text-1.360 index 08160f58b9..4bbca5938a 100644 --- a/Task/Hello-world-Text/360-Assembly/hello-world-text-1.360 +++ b/Task/Hello-world-Text/360-Assembly/hello-world-text-1.360 @@ -4,5 +4,5 @@ MSGAREA EQU * Message Area DC AL2(19) Total area length = 19 (Prefix length:4 + Data Length:15) DC XL2'00' 2 bytes binary of zeros - DC C'Goodbye, World!' Text to be written to system console + DC C'Hello world!' Text to be written to system console END diff --git a/Task/Hello-world-Text/360-Assembly/hello-world-text-2.360 b/Task/Hello-world-Text/360-Assembly/hello-world-text-2.360 index fd4f81d79f..4d8d79476b 100644 --- a/Task/Hello-world-Text/360-Assembly/hello-world-text-2.360 +++ b/Task/Hello-world-Text/360-Assembly/hello-world-text-2.360 @@ -1,3 +1,3 @@ - WTO 'Goodbye, World!' + WTO 'Hello world!' BR 14 Return END diff --git a/Task/Hello-world-Text/4DOS-Batch/hello-world-text.4dos b/Task/Hello-world-Text/4DOS-Batch/hello-world-text.4dos index fd705ab250..3af583cd85 100644 --- a/Task/Hello-world-Text/4DOS-Batch/hello-world-text.4dos +++ b/Task/Hello-world-Text/4DOS-Batch/hello-world-text.4dos @@ -1 +1 @@ -echo Goodbye, World! +echo Hello world! diff --git a/Task/Hello-world-Text/6502-Assembly/hello-world-text.6502 b/Task/Hello-world-Text/6502-Assembly/hello-world-text.6502 index 05ce162a15..8acfce74bc 100644 --- a/Task/Hello-world-Text/6502-Assembly/hello-world-text.6502 +++ b/Task/Hello-world-Text/6502-Assembly/hello-world-text.6502 @@ -19,4 +19,4 @@ done: .rodata text: - .byte "Goodbye, World!", a_cr, 0 + .byte "Hello world!", a_cr, 0 diff --git a/Task/Hello-world-Text/6800-Assembly/hello-world-text.6800 b/Task/Hello-world-Text/6800-Assembly/hello-world-text.6800 index 772ee84cd6..6ef8b4b915 100644 --- a/Task/Hello-world-Text/6800-Assembly/hello-world-text.6800 +++ b/Task/Hello-world-Text/6800-Assembly/hello-world-text.6800 @@ -2,10 +2,10 @@ .tf gbye6800.obj,AP1 .lf gbye6800 ;=====================================================; -; Goodbye, World! for the Motorola 6800 ; +; Hello world! for the Motorola 6800 ; ; by barrym 2013-03-17 ; ;-----------------------------------------------------; -; Prints the message "Goodbye, World!" to an ascii ; +; Prints the message "Hello world!" to an ascii ; ; terminal (console) connected to a 1970s vintage ; ; SWTPC 6800 system, which is the target device for ; ; this assembly. ; @@ -27,5 +27,5 @@ puts ldaa ,x ;Load a string character bne outs ;Print it if non-null swi ; else return to the monitor ;=====================================================; -string .as "Goodbye, World!",#13,#10,#0 +string .as "Hello world!",#13,#10,#0 .en diff --git a/Task/Hello-world-Text/8086-Assembly/hello-world-text.8086 b/Task/Hello-world-Text/8086-Assembly/hello-world-text.8086 index 7164843ed7..dce13316c6 100644 --- a/Task/Hello-world-Text/8086-Assembly/hello-world-text.8086 +++ b/Task/Hello-world-Text/8086-Assembly/hello-world-text.8086 @@ -1,7 +1,7 @@ DOSSEG .MODEL TINY .DATA -TXT DB "Goodbye, World!$" +TXT DB "Hello world!$" .CODE START: MOV ax, @DATA diff --git a/Task/Hello-world-Text/ABAP/hello-world-text.abap b/Task/Hello-world-Text/ABAP/hello-world-text.abap index d00a545f70..8d2851d666 100644 --- a/Task/Hello-world-Text/ABAP/hello-world-text.abap +++ b/Task/Hello-world-Text/ABAP/hello-world-text.abap @@ -1,2 +1,2 @@ REPORT zgoodbyeworld. - WRITE 'Goodbye, World!'. + WRITE 'Hello world!'. diff --git a/Task/Hello-world-Text/ACL2/hello-world-text.acl2 b/Task/Hello-world-Text/ACL2/hello-world-text.acl2 index afd55197c9..f055f1423e 100644 --- a/Task/Hello-world-Text/ACL2/hello-world-text.acl2 +++ b/Task/Hello-world-Text/ACL2/hello-world-text.acl2 @@ -1 +1 @@ -(cw "Goodbye, World!~%") +(cw "Hello world!~%") diff --git a/Task/Hello-world-Text/ALGOL-60/hello-world-text.alg b/Task/Hello-world-Text/ALGOL-60/hello-world-text.alg index 4ccd0c9ee1..84df69933d 100644 --- a/Task/Hello-world-Text/ALGOL-60/hello-world-text.alg +++ b/Task/Hello-world-Text/ALGOL-60/hello-world-text.alg @@ -1,4 +1,4 @@ 'BEGIN' - OUTSTRING(1,'('GOODBYE, WORLD!')'); + OUTSTRING(1,'('Hello world!')'); SYSACT(1,14,1) 'END' diff --git a/Task/Hello-world-Text/ALGOL-68/hello-world-text.alg b/Task/Hello-world-Text/ALGOL-68/hello-world-text.alg index bb912a9c4e..1b6a20bee8 100644 --- a/Task/Hello-world-Text/ALGOL-68/hello-world-text.alg +++ b/Task/Hello-world-Text/ALGOL-68/hello-world-text.alg @@ -1,3 +1,3 @@ main: ( - printf($"Goodbye, World!"l$) + printf($"Hello world!"l$) ) diff --git a/Task/Hello-world-Text/ALGOL-W/hello-world-text.alg b/Task/Hello-world-Text/ALGOL-W/hello-world-text.alg new file mode 100644 index 0000000000..ad938cc4cd --- /dev/null +++ b/Task/Hello-world-Text/ALGOL-W/hello-world-text.alg @@ -0,0 +1,3 @@ +begin + write( "Hello world!" ) +end. diff --git a/Task/Hello-world-Text/ARM-Assembly/hello-world-text.arm b/Task/Hello-world-Text/ARM-Assembly/hello-world-text.arm new file mode 100644 index 0000000000..93e54940f1 --- /dev/null +++ b/Task/Hello-world-Text/ARM-Assembly/hello-world-text.arm @@ -0,0 +1,12 @@ +.global main + +message: + .asciz "Hello world!\n" + .align 4 + +main: + ldr r0, =message + bl printf + + mov r7, #1 + swi 0 diff --git a/Task/Hello-world-Text/ATS/hello-world-text.ats b/Task/Hello-world-Text/ATS/hello-world-text.ats index cad6057a6a..47131a59b8 100644 --- a/Task/Hello-world-Text/ATS/hello-world-text.ats +++ b/Task/Hello-world-Text/ATS/hello-world-text.ats @@ -1 +1 @@ -implement main0 () = print "Goodbye, World!\n" +implement main0 () = print "Hello world!\n" diff --git a/Task/Hello-world-Text/AWK/hello-world-text-1.awk b/Task/Hello-world-Text/AWK/hello-world-text-1.awk index 1bc6c6ef55..4312484e83 100644 --- a/Task/Hello-world-Text/AWK/hello-world-text-1.awk +++ b/Task/Hello-world-Text/AWK/hello-world-text-1.awk @@ -1 +1 @@ -BEGIN{print "Goodbye, World!"} +BEGIN{print "Hello world!"} diff --git a/Task/Hello-world-Text/AWK/hello-world-text-2.awk b/Task/Hello-world-Text/AWK/hello-world-text-2.awk index d02edc3e26..1041a5e6e8 100644 --- a/Task/Hello-world-Text/AWK/hello-world-text-2.awk +++ b/Task/Hello-world-Text/AWK/hello-world-text-2.awk @@ -1,3 +1,3 @@ END { - print "Goodbye, World!" + print "Hello world!" } diff --git a/Task/Hello-world-Text/AWK/hello-world-text-3.awk b/Task/Hello-world-Text/AWK/hello-world-text-3.awk index 0226fd5081..beda1ded23 100644 --- a/Task/Hello-world-Text/AWK/hello-world-text-3.awk +++ b/Task/Hello-world-Text/AWK/hello-world-text-3.awk @@ -1,4 +1,4 @@ // { - print "Goodbye, World!" + print "Hello world!" exit } diff --git a/Task/Hello-world-Text/AWK/hello-world-text-4.awk b/Task/Hello-world-Text/AWK/hello-world-text-4.awk index 524b476182..3cd9421e89 100644 --- a/Task/Hello-world-Text/AWK/hello-world-text-4.awk +++ b/Task/Hello-world-Text/AWK/hello-world-text-4.awk @@ -1,3 +1,3 @@ // { - print "Goodbye, World!" + print "Hello world!" } diff --git a/Task/Hello-world-Text/ActionScript/hello-world-text.as b/Task/Hello-world-Text/ActionScript/hello-world-text.as index f2c4a774ba..f00ea826cd 100644 --- a/Task/Hello-world-Text/ActionScript/hello-world-text.as +++ b/Task/Hello-world-Text/ActionScript/hello-world-text.as @@ -1 +1 @@ -trace("Goodbye, World!"); +trace("Hello world!"); diff --git a/Task/Hello-world-Text/Ada/hello-world-text.ada b/Task/Hello-world-Text/Ada/hello-world-text.ada index 738d3b2a47..7bd04f60c0 100644 --- a/Task/Hello-world-Text/Ada/hello-world-text.ada +++ b/Task/Hello-world-Text/Ada/hello-world-text.ada @@ -1,5 +1,5 @@ with Ada.Text_IO; use Ada.Text_IO; procedure Main is begin - Put_Line ("Goodbye, World!"); + Put_Line ("Hello world!"); end Main; diff --git a/Task/Hello-world-Text/Aime/hello-world-text-1.aime b/Task/Hello-world-Text/Aime/hello-world-text-1.aime index 076aad6f4a..82c5fe4a52 100644 --- a/Task/Hello-world-Text/Aime/hello-world-text-1.aime +++ b/Task/Hello-world-Text/Aime/hello-world-text-1.aime @@ -1 +1 @@ -o_text("Goodbye, World!\n"); +o_text("Hello world!\n"); diff --git a/Task/Hello-world-Text/Aime/hello-world-text-2.aime b/Task/Hello-world-Text/Aime/hello-world-text-2.aime index 913833c72c..25c8ea5cea 100644 --- a/Task/Hello-world-Text/Aime/hello-world-text-2.aime +++ b/Task/Hello-world-Text/Aime/hello-world-text-2.aime @@ -1,7 +1,7 @@ integer main(void) { - o_text("Goodbye, World!\n"); + o_text("Hello world!\n"); return 0; } diff --git a/Task/Hello-world-Text/Algae/hello-world-text.algae b/Task/Hello-world-Text/Algae/hello-world-text.algae index 981a55417b..e84c223938 100644 --- a/Task/Hello-world-Text/Algae/hello-world-text.algae +++ b/Task/Hello-world-Text/Algae/hello-world-text.algae @@ -1 +1 @@ -printf("Goodbye, World\n"); +printf("Hello world!\n"); diff --git a/Task/Hello-world-Text/Alore/hello-world-text.alore b/Task/Hello-world-Text/Alore/hello-world-text.alore index d8dba31817..575c10ab06 100644 --- a/Task/Hello-world-Text/Alore/hello-world-text.alore +++ b/Task/Hello-world-Text/Alore/hello-world-text.alore @@ -1 +1 @@ -Print('Goodbye, World!') +Print('Hello world!') diff --git a/Task/Hello-world-Text/AmbientTalk/hello-world-text.ambient b/Task/Hello-world-Text/AmbientTalk/hello-world-text.ambient index a945b1d028..490f4f2ee0 100644 --- a/Task/Hello-world-Text/AmbientTalk/hello-world-text.ambient +++ b/Task/Hello-world-Text/AmbientTalk/hello-world-text.ambient @@ -1 +1 @@ -system.println("Goodbye, World!") +system.println("Hello world!") diff --git a/Task/Hello-world-Text/AmigaE/hello-world-text.amiga b/Task/Hello-world-Text/AmigaE/hello-world-text.amiga index c6ac128669..5d9816f6df 100644 --- a/Task/Hello-world-Text/AmigaE/hello-world-text.amiga +++ b/Task/Hello-world-Text/AmigaE/hello-world-text.amiga @@ -1,3 +1,3 @@ PROC main() - WriteF('Goodbye, World!\n') + WriteF('Hello world!\n') ENDPROC diff --git a/Task/Hello-world-Text/AppleScript/hello-world-text-1.applescript b/Task/Hello-world-Text/AppleScript/hello-world-text-1.applescript index 1e9d709f27..6ccebb9abe 100644 --- a/Task/Hello-world-Text/AppleScript/hello-world-text-1.applescript +++ b/Task/Hello-world-Text/AppleScript/hello-world-text-1.applescript @@ -1 +1 @@ -"Goodbye, World!" +"Hello world!" diff --git a/Task/Hello-world-Text/AppleScript/hello-world-text-2.applescript b/Task/Hello-world-Text/AppleScript/hello-world-text-2.applescript index a70b284f81..7cfdeef9b8 100644 --- a/Task/Hello-world-Text/AppleScript/hello-world-text-2.applescript +++ b/Task/Hello-world-Text/AppleScript/hello-world-text-2.applescript @@ -1 +1 @@ -log "Goodbye, World!" +log "Hello world!" diff --git a/Task/Hello-world-Text/Applesoft-BASIC/hello-world-text.applesoft b/Task/Hello-world-Text/Applesoft-BASIC/hello-world-text.applesoft index 094ab76917..4dc0bee937 100644 --- a/Task/Hello-world-Text/Applesoft-BASIC/hello-world-text.applesoft +++ b/Task/Hello-world-Text/Applesoft-BASIC/hello-world-text.applesoft @@ -1 +1 @@ - PRINT "GOODBYE, WORLD!" + PRINT "Hello world!" diff --git a/Task/Hello-world-Text/Argile/hello-world-text.argile b/Task/Hello-world-Text/Argile/hello-world-text.argile index 7c3c5a8862..bac72d25fd 100644 --- a/Task/Hello-world-Text/Argile/hello-world-text.argile +++ b/Task/Hello-world-Text/Argile/hello-world-text.argile @@ -1,2 +1,2 @@ use std -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/Asymptote/hello-world-text.asymptote b/Task/Hello-world-Text/Asymptote/hello-world-text.asymptote index b2ae9ccd8a..98cd47e538 100644 --- a/Task/Hello-world-Text/Asymptote/hello-world-text.asymptote +++ b/Task/Hello-world-Text/Asymptote/hello-world-text.asymptote @@ -1 +1 @@ -write('Goodbye, World!'); +write('Hello world!'); diff --git a/Task/Hello-world-Text/AutoHotkey/hello-world-text-3.ahk b/Task/Hello-world-Text/AutoHotkey/hello-world-text-3.ahk index 88c6afa82a..7f46b913ab 100644 --- a/Task/Hello-world-Text/AutoHotkey/hello-world-text-3.ahk +++ b/Task/Hello-world-Text/AutoHotkey/hello-world-text-3.ahk @@ -1 +1 @@ -SendInput Goodbye, World{!} +SendInput Hello world!{!} diff --git a/Task/Hello-world-Text/AutoIt/hello-world-text.autoit b/Task/Hello-world-Text/AutoIt/hello-world-text.autoit index 91a674d4bc..b70cc1cab7 100644 --- a/Task/Hello-world-Text/AutoIt/hello-world-text.autoit +++ b/Task/Hello-world-Text/AutoIt/hello-world-text.autoit @@ -1 +1 @@ -ConsoleWrite("Goodbye, World!" & @CRLF) +ConsoleWrite("Hello world!" & @CRLF) diff --git a/Task/Hello-world-Text/BASIC/hello-world-text-1.basic b/Task/Hello-world-Text/BASIC/hello-world-text-1.basic index 298c3c904d..d687c507a7 100644 --- a/Task/Hello-world-Text/BASIC/hello-world-text-1.basic +++ b/Task/Hello-world-Text/BASIC/hello-world-text-1.basic @@ -1 +1 @@ -10 print "Goodbye, World!" +10 print "Hello world!" diff --git a/Task/Hello-world-Text/BASIC/hello-world-text-2.basic b/Task/Hello-world-Text/BASIC/hello-world-text-2.basic index 2dffd5dbb8..386f4e4cc6 100644 --- a/Task/Hello-world-Text/BASIC/hello-world-text-2.basic +++ b/Task/Hello-world-Text/BASIC/hello-world-text-2.basic @@ -1 +1 @@ -PRINT "Goodbye, World!" +PRINT "Hello world!" diff --git a/Task/Hello-world-Text/BASIC256/hello-world-text.basic256 b/Task/Hello-world-Text/BASIC256/hello-world-text.basic256 index 2dffd5dbb8..386f4e4cc6 100644 --- a/Task/Hello-world-Text/BASIC256/hello-world-text.basic256 +++ b/Task/Hello-world-Text/BASIC256/hello-world-text.basic256 @@ -1 +1 @@ -PRINT "Goodbye, World!" +PRINT "Hello world!" diff --git a/Task/Hello-world-Text/BBC-BASIC/hello-world-text.bbc b/Task/Hello-world-Text/BBC-BASIC/hello-world-text.bbc index 4b77be9e32..3fac7d0992 100644 --- a/Task/Hello-world-Text/BBC-BASIC/hello-world-text.bbc +++ b/Task/Hello-world-Text/BBC-BASIC/hello-world-text.bbc @@ -1 +1 @@ - PRINT "Goodbye, World!" + PRINT "Hello world!" diff --git a/Task/Hello-world-Text/BCPL/hello-world-text.bcpl b/Task/Hello-world-Text/BCPL/hello-world-text.bcpl index f3e65eee38..84c1ba0ad9 100644 --- a/Task/Hello-world-Text/BCPL/hello-world-text.bcpl +++ b/Task/Hello-world-Text/BCPL/hello-world-text.bcpl @@ -1,6 +1,6 @@ GET "libhdr" LET start() = VALOF -{ writef("Goodbye, World!") +{ writef("Hello world!") RESULTIS 0 } diff --git a/Task/Hello-world-Text/Babel/hello-world-text.pb b/Task/Hello-world-Text/Babel/hello-world-text.pb index 99e79ce0f5..6adf1e451a 100644 --- a/Task/Hello-world-Text/Babel/hello-world-text.pb +++ b/Task/Hello-world-Text/Babel/hello-world-text.pb @@ -1 +1 @@ -((main { "Goodbye, World!" << })) +((main { "Hello world!" << })) diff --git a/Task/Hello-world-Text/Batch-File/hello-world-text-1.bat b/Task/Hello-world-Text/Batch-File/hello-world-text-1.bat index fd705ab250..3af583cd85 100644 --- a/Task/Hello-world-Text/Batch-File/hello-world-text-1.bat +++ b/Task/Hello-world-Text/Batch-File/hello-world-text-1.bat @@ -1 +1 @@ -echo Goodbye, World! +echo Hello world! diff --git a/Task/Hello-world-Text/Batch-File/hello-world-text-2.bat b/Task/Hello-world-Text/Batch-File/hello-world-text-2.bat index bbd99d564b..404dd4bacd 100644 --- a/Task/Hello-world-Text/Batch-File/hello-world-text-2.bat +++ b/Task/Hello-world-Text/Batch-File/hello-world-text-2.bat @@ -1,2 +1,2 @@ setlocal enableDelayedExpansion -echo Goodbye, World^^^! +echo Hello world!^^! diff --git a/Task/Hello-world-Text/Befunge/hello-world-text.bf b/Task/Hello-world-Text/Befunge/hello-world-text.bf index 389a88090a..2047f26d89 100644 --- a/Task/Hello-world-Text/Befunge/hello-world-text.bf +++ b/Task/Hello-world-Text/Befunge/hello-world-text.bf @@ -1 +1 @@ -0"!dlroW ,eybdooG">:#,_@ +52*"!dlroW ,eybdooG">:#,_@ diff --git a/Task/Hello-world-Text/Blast/hello-world-text.blast b/Task/Hello-world-Text/Blast/hello-world-text.blast index 37586d20e5..1e32b54632 100644 --- a/Task/Hello-world-Text/Blast/hello-world-text.blast +++ b/Task/Hello-world-Text/Blast/hello-world-text.blast @@ -1,5 +1,5 @@ # This will display a goodbye message on the terminal screen .begin -display "Goodbye, World!" +display "Hello world!" return # This is the end of the script. diff --git a/Task/Hello-world-Text/Boo/hello-world-text.boo b/Task/Hello-world-Text/Boo/hello-world-text.boo index a9f594ad30..ed708ec5fb 100644 --- a/Task/Hello-world-Text/Boo/hello-world-text.boo +++ b/Task/Hello-world-Text/Boo/hello-world-text.boo @@ -1 +1 @@ -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/Brace/hello-world-text.brace b/Task/Hello-world-Text/Brace/hello-world-text.brace index a9c9dcace8..7e9f77a149 100644 --- a/Task/Hello-world-Text/Brace/hello-world-text.brace +++ b/Task/Hello-world-Text/Brace/hello-world-text.brace @@ -1,4 +1,4 @@ #!/usr/bin/env bx use b Main: - say("Goodbye, World!") + say("Hello world!") diff --git a/Task/Hello-world-Text/Bracmat/hello-world-text.bracmat b/Task/Hello-world-Text/Bracmat/hello-world-text.bracmat index f80f47d891..449917d5b7 100644 --- a/Task/Hello-world-Text/Bracmat/hello-world-text.bracmat +++ b/Task/Hello-world-Text/Bracmat/hello-world-text.bracmat @@ -1 +1 @@ -put$"Goodbye, World!" +put$"Hello world!" diff --git a/Task/Hello-world-Text/Brat/hello-world-text.brat b/Task/Hello-world-Text/Brat/hello-world-text.brat index 8b8559124c..8eb97c06b2 100644 --- a/Task/Hello-world-Text/Brat/hello-world-text.brat +++ b/Task/Hello-world-Text/Brat/hello-world-text.brat @@ -1 +1 @@ -p "Goodbye, World!" +p "Hello world!" diff --git a/Task/Hello-world-Text/Brlcad/hello-world-text.brlcad b/Task/Hello-world-Text/Brlcad/hello-world-text.brlcad index fd705ab250..3af583cd85 100644 --- a/Task/Hello-world-Text/Brlcad/hello-world-text.brlcad +++ b/Task/Hello-world-Text/Brlcad/hello-world-text.brlcad @@ -1 +1 @@ -echo Goodbye, World! +echo Hello world! diff --git a/Task/Hello-world-Text/Burlesque/hello-world-text.blq b/Task/Hello-world-Text/Burlesque/hello-world-text.blq index 7a5b504380..a34b4439b7 100644 --- a/Task/Hello-world-Text/Burlesque/hello-world-text.blq +++ b/Task/Hello-world-Text/Burlesque/hello-world-text.blq @@ -1 +1 @@ -"Goodbye, World!"sh +"Hello world!"sh diff --git a/Task/Hello-world-Text/C++-CLI/hello-world-text.cpp b/Task/Hello-world-Text/C++-CLI/hello-world-text.cpp index 75239c29f6..ec50ca2045 100644 --- a/Task/Hello-world-Text/C++-CLI/hello-world-text.cpp +++ b/Task/Hello-world-Text/C++-CLI/hello-world-text.cpp @@ -1,5 +1,5 @@ using namespace System; int main() { - Console::WriteLine("Goodbye, World!"); + Console::WriteLine("Hello world!"); } diff --git a/Task/Hello-world-Text/C++/hello-world-text.cpp b/Task/Hello-world-Text/C++/hello-world-text.cpp index 705a64a10d..01f656d5a1 100644 --- a/Task/Hello-world-Text/C++/hello-world-text.cpp +++ b/Task/Hello-world-Text/C++/hello-world-text.cpp @@ -1,5 +1,5 @@ #include int main () { - std::cout << "Goodbye, World!\n"; + std::cout << "Hello world!" << std::endl; } diff --git a/Task/Hello-world-Text/C/hello-world-text-1.c b/Task/Hello-world-Text/C/hello-world-text-1.c index a41f806c57..25b7d304c2 100644 --- a/Task/Hello-world-Text/C/hello-world-text-1.c +++ b/Task/Hello-world-Text/C/hello-world-text-1.c @@ -3,6 +3,6 @@ int main(void) { - printf("Goodbye, World!\n"); + printf("Hello world!\n"); return EXIT_SUCCESS; } diff --git a/Task/Hello-world-Text/C/hello-world-text-2.c b/Task/Hello-world-Text/C/hello-world-text-2.c index de46ea5230..ccbb562e43 100644 --- a/Task/Hello-world-Text/C/hello-world-text-2.c +++ b/Task/Hello-world-Text/C/hello-world-text-2.c @@ -3,6 +3,6 @@ int main(void) { - puts("Goodbye, World!"); + puts("Hello world!"); return EXIT_SUCCESS; } diff --git a/Task/Hello-world-Text/C/hello-world-text-3.c b/Task/Hello-world-Text/C/hello-world-text-3.c index 9b0dbef888..172c037a05 100644 --- a/Task/Hello-world-Text/C/hello-world-text-3.c +++ b/Task/Hello-world-Text/C/hello-world-text-3.c @@ -2,6 +2,6 @@ int main() { - printf("\nGoodbye, World!"); + printf("\nHello world!"); return 0; } diff --git a/Task/Hello-world-Text/CLIPS/hello-world-text.clips b/Task/Hello-world-Text/CLIPS/hello-world-text.clips index 70fa59a2af..ee6f1084d9 100644 --- a/Task/Hello-world-Text/CLIPS/hello-world-text.clips +++ b/Task/Hello-world-Text/CLIPS/hello-world-text.clips @@ -1 +1 @@ -(printout t "Goodbye, World!" crlf) +(printout t "Hello world!" crlf) diff --git a/Task/Hello-world-Text/CMake/hello-world-text.cmake b/Task/Hello-world-Text/CMake/hello-world-text.cmake index bd0ddb4c42..115a18869f 100644 --- a/Task/Hello-world-Text/CMake/hello-world-text.cmake +++ b/Task/Hello-world-Text/CMake/hello-world-text.cmake @@ -1 +1 @@ -message(STATUS "Goodbye, World!") +message(STATUS "Hello world!") diff --git a/Task/Hello-world-Text/COBOL/hello-world-text.cobol b/Task/Hello-world-Text/COBOL/hello-world-text.cobol index 6457871e9d..26d3e7edbd 100644 --- a/Task/Hello-world-Text/COBOL/hello-world-text.cobol +++ b/Task/Hello-world-Text/COBOL/hello-world-text.cobol @@ -1,4 +1,4 @@ program-id. hello. procedure division. - display "Goodbye, World!". + display "Hello world!". stop run. diff --git a/Task/Hello-world-Text/Cat/hello-world-text.cat b/Task/Hello-world-Text/Cat/hello-world-text.cat index 8f9f0307f6..e02c1ad24e 100644 --- a/Task/Hello-world-Text/Cat/hello-world-text.cat +++ b/Task/Hello-world-Text/Cat/hello-world-text.cat @@ -1 +1 @@ -"Goodbye, World!" writeln +"Hello world!" writeln diff --git a/Task/Hello-world-Text/Cduce/hello-world-text.cduce b/Task/Hello-world-Text/Cduce/hello-world-text.cduce index 8d7839e5df..b36e0394ff 100644 --- a/Task/Hello-world-Text/Cduce/hello-world-text.cduce +++ b/Task/Hello-world-Text/Cduce/hello-world-text.cduce @@ -1 +1 @@ -print "Goodbye, World!";; +print "Hello world!";; diff --git a/Task/Hello-world-Text/Clay/hello-world-text.clay b/Task/Hello-world-Text/Clay/hello-world-text.clay index f04344c563..fe58f2d2db 100644 --- a/Task/Hello-world-Text/Clay/hello-world-text.clay +++ b/Task/Hello-world-Text/Clay/hello-world-text.clay @@ -1,3 +1,3 @@ main() { - println("Goodbye, World!"); + println("Hello world!"); } diff --git a/Task/Hello-world-Text/Clean/hello-world-text.clean b/Task/Hello-world-Text/Clean/hello-world-text.clean index 7fec74bc18..55908039de 100644 --- a/Task/Hello-world-Text/Clean/hello-world-text.clean +++ b/Task/Hello-world-Text/Clean/hello-world-text.clean @@ -1 +1 @@ -Start = "Goodbye, World!" +Start = "Hello world!" diff --git a/Task/Hello-world-Text/Clipper/hello-world-text.clipper b/Task/Hello-world-Text/Clipper/hello-world-text.clipper index c2a9edcb19..4e54ed208b 100644 --- a/Task/Hello-world-Text/Clipper/hello-world-text.clipper +++ b/Task/Hello-world-Text/Clipper/hello-world-text.clipper @@ -1 +1 @@ -? "Goodbye, World!" +? "Hello world!" diff --git a/Task/Hello-world-Text/Clojure/hello-world-text.clj b/Task/Hello-world-Text/Clojure/hello-world-text.clj index 2b23b653e6..fe1102b873 100644 --- a/Task/Hello-world-Text/Clojure/hello-world-text.clj +++ b/Task/Hello-world-Text/Clojure/hello-world-text.clj @@ -1 +1 @@ -(println "Goodbye, World!") +(println "Hello world!") diff --git a/Task/Hello-world-Text/Cobra/hello-world-text.cobra b/Task/Hello-world-Text/Cobra/hello-world-text.cobra index 684e41e0df..b03d27bb22 100644 --- a/Task/Hello-world-Text/Cobra/hello-world-text.cobra +++ b/Task/Hello-world-Text/Cobra/hello-world-text.cobra @@ -1,3 +1,3 @@ class Hello def main - print 'Goodbye, World!' + print 'Hello world!' diff --git a/Task/Hello-world-Text/CoffeeScript/hello-world-text-1.coffee b/Task/Hello-world-Text/CoffeeScript/hello-world-text-1.coffee index 4cc9152eb3..1af81a40dc 100644 --- a/Task/Hello-world-Text/CoffeeScript/hello-world-text-1.coffee +++ b/Task/Hello-world-Text/CoffeeScript/hello-world-text-1.coffee @@ -1 +1 @@ -console.log "Goodbye, World!" +console.log "Hello world!" diff --git a/Task/Hello-world-Text/CoffeeScript/hello-world-text-2.coffee b/Task/Hello-world-Text/CoffeeScript/hello-world-text-2.coffee index a9f594ad30..ed708ec5fb 100644 --- a/Task/Hello-world-Text/CoffeeScript/hello-world-text-2.coffee +++ b/Task/Hello-world-Text/CoffeeScript/hello-world-text-2.coffee @@ -1 +1 @@ -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/ColdFusion/hello-world-text.cfm b/Task/Hello-world-Text/ColdFusion/hello-world-text.cfm index fc87663cef..04d0d4460a 100644 --- a/Task/Hello-world-Text/ColdFusion/hello-world-text.cfm +++ b/Task/Hello-world-Text/ColdFusion/hello-world-text.cfm @@ -1 +1 @@ -Goodbye, World! +Hello world! diff --git a/Task/Hello-world-Text/Common-Lisp/hello-world-text-1.lisp b/Task/Hello-world-Text/Common-Lisp/hello-world-text-1.lisp new file mode 100644 index 0000000000..32df744fbc --- /dev/null +++ b/Task/Hello-world-Text/Common-Lisp/hello-world-text-1.lisp @@ -0,0 +1 @@ +(format t "Hello world!~%") diff --git a/Task/Hello-world-Text/Common-Lisp/hello-world-text-2.lisp b/Task/Hello-world-Text/Common-Lisp/hello-world-text-2.lisp new file mode 100644 index 0000000000..d441299f14 --- /dev/null +++ b/Task/Hello-world-Text/Common-Lisp/hello-world-text-2.lisp @@ -0,0 +1 @@ +(print "Hello world!") diff --git a/Task/Hello-world-Text/Common-Lisp/hello-world-text.lisp b/Task/Hello-world-Text/Common-Lisp/hello-world-text.lisp deleted file mode 100644 index 2618e2e53b..0000000000 --- a/Task/Hello-world-Text/Common-Lisp/hello-world-text.lisp +++ /dev/null @@ -1 +0,0 @@ -(format t "Goodbye, World!~%") diff --git a/Task/Hello-world-Text/Component-Pascal/hello-world-text.component b/Task/Hello-world-Text/Component-Pascal/hello-world-text.component index 52ae0c5b90..aea7d4fdc7 100644 --- a/Task/Hello-world-Text/Component-Pascal/hello-world-text.component +++ b/Task/Hello-world-Text/Component-Pascal/hello-world-text.component @@ -3,6 +3,6 @@ MODULE Hello; PROCEDURE Do*; BEGIN - Out.String("Goodbye, World!"); Out.Ln + Out.String("Hello world!"); Out.Ln END Do; END Hello. diff --git a/Task/Hello-world-Text/Crack/hello-world-text.crack b/Task/Hello-world-Text/Crack/hello-world-text.crack index b239168ba2..9e64187370 100644 --- a/Task/Hello-world-Text/Crack/hello-world-text.crack +++ b/Task/Hello-world-Text/Crack/hello-world-text.crack @@ -1,2 +1,2 @@ import crack.io cout; -cout `Goodbye, World!\n`; +cout `Hello world!\n`; diff --git a/Task/Hello-world-Text/D/hello-world-text.d b/Task/Hello-world-Text/D/hello-world-text.d index 934b3adabc..fbe9ad9c8f 100644 --- a/Task/Hello-world-Text/D/hello-world-text.d +++ b/Task/Hello-world-Text/D/hello-world-text.d @@ -1,5 +1,5 @@ import std.stdio; void main() { - writeln("Goodbye, World!"); + writeln("Hello world!"); } diff --git a/Task/Hello-world-Text/DCL/hello-world-text.dcl b/Task/Hello-world-Text/DCL/hello-world-text.dcl new file mode 100644 index 0000000000..1c55ffb586 --- /dev/null +++ b/Task/Hello-world-Text/DCL/hello-world-text.dcl @@ -0,0 +1 @@ +$ write sys$output "Hello world!" diff --git a/Task/Hello-world-Text/DWScript/hello-world-text.dw b/Task/Hello-world-Text/DWScript/hello-world-text.dw index 130e69df6c..3e3864afaa 100644 --- a/Task/Hello-world-Text/DWScript/hello-world-text.dw +++ b/Task/Hello-world-Text/DWScript/hello-world-text.dw @@ -1 +1 @@ -PrintLn('Goodbye, World!'); +PrintLn('Hello world!'); diff --git a/Task/Hello-world-Text/Dao/hello-world-text.dao b/Task/Hello-world-Text/Dao/hello-world-text.dao index cd3630f39a..c1815a23f2 100644 --- a/Task/Hello-world-Text/Dao/hello-world-text.dao +++ b/Task/Hello-world-Text/Dao/hello-world-text.dao @@ -1 +1 @@ -io.writeln( 'Goodbye, World!' ) +io.writeln( 'Hello world!' ) diff --git a/Task/Hello-world-Text/Dart/hello-world-text.dart b/Task/Hello-world-Text/Dart/hello-world-text.dart index b7edaeb7d7..987a9a572d 100644 --- a/Task/Hello-world-Text/Dart/hello-world-text.dart +++ b/Task/Hello-world-Text/Dart/hello-world-text.dart @@ -1,4 +1,4 @@ main() { - var bye = 'Goodbye, World!'; + var bye = 'Hello world!'; print("$bye"); } diff --git a/Task/Hello-world-Text/Deja-Vu/hello-world-text.djv b/Task/Hello-world-Text/Deja-Vu/hello-world-text.djv index a2009a57ae..87b7baccb8 100644 --- a/Task/Hello-world-Text/Deja-Vu/hello-world-text.djv +++ b/Task/Hello-world-Text/Deja-Vu/hello-world-text.djv @@ -1 +1 @@ -!print "Goodbye, World!" +!print "Hello world!" diff --git a/Task/Hello-world-Text/Delphi/hello-world-text.delphi b/Task/Hello-world-Text/Delphi/hello-world-text.delphi index c4f89335d4..c73e7adb0c 100644 --- a/Task/Hello-world-Text/Delphi/hello-world-text.delphi +++ b/Task/Hello-world-Text/Delphi/hello-world-text.delphi @@ -1,5 +1,5 @@ program ProjectGoodbye; {$APPTYPE CONSOLE} begin - WriteLn('Goodbye, World!'); + WriteLn('Hello world!'); end. diff --git a/Task/Hello-world-Text/Dylan.NET/hello-world-text-1.dylan.net b/Task/Hello-world-Text/Dylan.NET/hello-world-text-1.dylan.net index 991ed56716..64532cd76e 100644 --- a/Task/Hello-world-Text/Dylan.NET/hello-world-text-1.dylan.net +++ b/Task/Hello-world-Text/Dylan.NET/hello-world-text-1.dylan.net @@ -1 +1 @@ -Console::WriteLine("Goodbye, World!") +Console::WriteLine("Hello world!") diff --git a/Task/Hello-world-Text/Dylan.NET/hello-world-text-2.dylan.net b/Task/Hello-world-Text/Dylan.NET/hello-world-text-2.dylan.net index bcc476172c..95b6b6e38d 100644 --- a/Task/Hello-world-Text/Dylan.NET/hello-world-text-2.dylan.net +++ b/Task/Hello-world-Text/Dylan.NET/hello-world-text-2.dylan.net @@ -10,7 +10,7 @@ ver 1.2.0.0 class public Program method public static void main() - Console::WriteLine("Goodbye, World!") + Console::WriteLine("Hello world!") end method end class diff --git a/Task/Hello-world-Text/Dylan/hello-world-text.dylan b/Task/Hello-world-Text/Dylan/hello-world-text.dylan index a254efc1b1..6e6f9b1b41 100644 --- a/Task/Hello-world-Text/Dylan/hello-world-text.dylan +++ b/Task/Hello-world-Text/Dylan/hello-world-text.dylan @@ -1,3 +1,3 @@ module: hello-world -format-out("%s\n", "Goodbye, World!"); +format-out("%s\n", "Hello world!"); diff --git a/Task/Hello-world-Text/E/hello-world-text.e b/Task/Hello-world-Text/E/hello-world-text.e index 316775bb31..f0a133af27 100644 --- a/Task/Hello-world-Text/E/hello-world-text.e +++ b/Task/Hello-world-Text/E/hello-world-text.e @@ -1,3 +1,3 @@ -println("Goodbye, World!") +println("Hello world!") -stdout.println("Goodbye, World!") +stdout.println("Hello world!") diff --git a/Task/Hello-world-Text/EGL/hello-world-text.egl b/Task/Hello-world-Text/EGL/hello-world-text.egl index 2d2feb5383..b1c6607098 100644 --- a/Task/Hello-world-Text/EGL/hello-world-text.egl +++ b/Task/Hello-world-Text/EGL/hello-world-text.egl @@ -1,5 +1,5 @@ program HelloWorld function main() - SysLib.writeStdout("Goodbye, World!"); + SysLib.writeStdout("Hello world!"); end end diff --git a/Task/Hello-world-Text/Efene/hello-world-text-1.efene b/Task/Hello-world-Text/Efene/hello-world-text-1.efene index bdc2fb652e..4b6fd834ec 100644 --- a/Task/Hello-world-Text/Efene/hello-world-text-1.efene +++ b/Task/Hello-world-Text/Efene/hello-world-text-1.efene @@ -1 +1 @@ -io.format("Goodbye, World!~n") +io.format("Hello world!~n") diff --git a/Task/Hello-world-Text/Efene/hello-world-text-2.efene b/Task/Hello-world-Text/Efene/hello-world-text-2.efene index 0b7b258efa..bf9dc0dfa3 100644 --- a/Task/Hello-world-Text/Efene/hello-world-text-2.efene +++ b/Task/Hello-world-Text/Efene/hello-world-text-2.efene @@ -1,4 +1,4 @@ @public run = fn () { - io.format("Goodbye, World!~n") + io.format("Hello world!~n") } diff --git a/Task/Hello-world-Text/Eiffel/hello-world-text.e b/Task/Hello-world-Text/Eiffel/hello-world-text.e index a895106d01..ed426bbcd3 100644 --- a/Task/Hello-world-Text/Eiffel/hello-world-text.e +++ b/Task/Hello-world-Text/Eiffel/hello-world-text.e @@ -5,6 +5,6 @@ create feature make do - print ("Goodbye, World!%N") + print ("Hello world!%N") end end diff --git a/Task/Hello-world-Text/Ela/hello-world-text.ela b/Task/Hello-world-Text/Ela/hello-world-text.ela index ab9ebfd156..969a3192b9 100644 --- a/Task/Hello-world-Text/Ela/hello-world-text.ela +++ b/Task/Hello-world-Text/Ela/hello-world-text.ela @@ -1,2 +1,2 @@ -open console -writen "Goodbye, World!" +open monad io +do putStrLn "Googbye, World!" ::: IO diff --git a/Task/Hello-world-Text/Elena/hello-world-text-1.elena b/Task/Hello-world-Text/Elena/hello-world-text-1.elena index 2796e9981c..1a0079060e 100644 --- a/Task/Hello-world-Text/Elena/hello-world-text-1.elena +++ b/Task/Hello-world-Text/Elena/hello-world-text-1.elena @@ -1,4 +1,4 @@ #symbol Program = [ - system'console writeLine:"Goodbye, World!". + system'console writeLine:"Hello world!". ]. diff --git a/Task/Hello-world-Text/Elena/hello-world-text-2.elena b/Task/Hello-world-Text/Elena/hello-world-text-2.elena index 643327edad..fa06f6a031 100644 --- a/Task/Hello-world-Text/Elena/hello-world-text-2.elena +++ b/Task/Hello-world-Text/Elena/hello-world-text-2.elena @@ -2,4 +2,4 @@ #define start ::= "?" < system'console.eval&writeLine( > $literal < ) >; ]] -? "Hello World!!" +? "Hello world!" diff --git a/Task/Hello-world-Text/Elisa/hello-world-text.elisa b/Task/Hello-world-Text/Elisa/hello-world-text.elisa index 62164fa889..dbb7cb5541 100644 --- a/Task/Hello-world-Text/Elisa/hello-world-text.elisa +++ b/Task/Hello-world-Text/Elisa/hello-world-text.elisa @@ -1 +1 @@ - "Goodbye, World!"? + "Hello world!"? diff --git a/Task/Hello-world-Text/Elixir/hello-world-text.elixir b/Task/Hello-world-Text/Elixir/hello-world-text.elixir index c26d110595..a1c1f83f5d 100644 --- a/Task/Hello-world-Text/Elixir/hello-world-text.elixir +++ b/Task/Hello-world-Text/Elixir/hello-world-text.elixir @@ -1 +1 @@ -IO.puts "Goodbye, World!" +IO.puts "Hello world!" diff --git a/Task/Hello-world-Text/Emacs-Lisp/hello-world-text.l b/Task/Hello-world-Text/Emacs-Lisp/hello-world-text.l index 977843a519..9215ea3a26 100644 --- a/Task/Hello-world-Text/Emacs-Lisp/hello-world-text.l +++ b/Task/Hello-world-Text/Emacs-Lisp/hello-world-text.l @@ -1 +1 @@ -(insert "Goodbye, World!") +(insert "Hello world!") diff --git a/Task/Hello-world-Text/Erlang/hello-world-text.erl b/Task/Hello-world-Text/Erlang/hello-world-text.erl index 07e4771bb5..157818e9de 100644 --- a/Task/Hello-world-Text/Erlang/hello-world-text.erl +++ b/Task/Hello-world-Text/Erlang/hello-world-text.erl @@ -1 +1 @@ -io:format("Goodbye, World!~n"). +io:format("Hello world!~n"). diff --git a/Task/Hello-world-Text/FALSE/hello-world-text.false b/Task/Hello-world-Text/FALSE/hello-world-text.false index bfc340df1b..a829090ff5 100644 --- a/Task/Hello-world-Text/FALSE/hello-world-text.false +++ b/Task/Hello-world-Text/FALSE/hello-world-text.false @@ -1,2 +1,2 @@ -"Goodbye, World! +"Hello world! " diff --git a/Task/Hello-world-Text/Factor/hello-world-text.factor b/Task/Hello-world-Text/Factor/hello-world-text.factor index 26e70906de..873822625e 100644 --- a/Task/Hello-world-Text/Factor/hello-world-text.factor +++ b/Task/Hello-world-Text/Factor/hello-world-text.factor @@ -1 +1 @@ -"Goodbye, World!" print +"Hello world!" print diff --git a/Task/Hello-world-Text/Falcon/hello-world-text-1.falcon b/Task/Hello-world-Text/Falcon/hello-world-text-1.falcon index 2494f2a107..2ad8518f5b 100644 --- a/Task/Hello-world-Text/Falcon/hello-world-text-1.falcon +++ b/Task/Hello-world-Text/Falcon/hello-world-text-1.falcon @@ -1 +1 @@ -printl("Goodbye, World!") +printl("Hello world!") diff --git a/Task/Hello-world-Text/Falcon/hello-world-text-2.falcon b/Task/Hello-world-Text/Falcon/hello-world-text-2.falcon index 7d0512316b..615f0029cd 100644 --- a/Task/Hello-world-Text/Falcon/hello-world-text-2.falcon +++ b/Task/Hello-world-Text/Falcon/hello-world-text-2.falcon @@ -1 +1 @@ -> "Goodbye, World!" +> "Hello world!" diff --git a/Task/Hello-world-Text/Fantom/hello-world-text.fantom b/Task/Hello-world-Text/Fantom/hello-world-text.fantom index 960455f495..2cc4c24d2f 100644 --- a/Task/Hello-world-Text/Fantom/hello-world-text.fantom +++ b/Task/Hello-world-Text/Fantom/hello-world-text.fantom @@ -2,6 +2,6 @@ class HelloText { public static Void main () { - echo ("Goodbye, World!") + echo ("Hello world!") } } diff --git a/Task/Hello-world-Text/Fexl/hello-world-text.fexl b/Task/Hello-world-Text/Fexl/hello-world-text.fexl index 2d546acdaa..891f7f6e6e 100644 --- a/Task/Hello-world-Text/Fexl/hello-world-text.fexl +++ b/Task/Hello-world-Text/Fexl/hello-world-text.fexl @@ -1 +1 @@ -say "Goodbye, World!" +say "Hello world!" diff --git a/Task/Hello-world-Text/Fish/hello-world-text.fish b/Task/Hello-world-Text/Fish/hello-world-text.fish index 523d858890..3262a22760 100644 --- a/Task/Hello-world-Text/Fish/hello-world-text.fish +++ b/Task/Hello-world-Text/Fish/hello-world-text.fish @@ -1,2 +1,2 @@ -!v"Goodbye, World!"r! +!v"Hello world!"r! >l?!;o diff --git a/Task/Hello-world-Text/Forth/hello-world-text-1.fth b/Task/Hello-world-Text/Forth/hello-world-text-1.fth index 1489b37634..f19cc23afe 100644 --- a/Task/Hello-world-Text/Forth/hello-world-text-1.fth +++ b/Task/Hello-world-Text/Forth/hello-world-text-1.fth @@ -1 +1 @@ -." Goodbye, World!" +." Hello world!" diff --git a/Task/Hello-world-Text/Forth/hello-world-text-2.fth b/Task/Hello-world-Text/Forth/hello-world-text-2.fth index 945a905263..ddbb19a91f 100644 --- a/Task/Hello-world-Text/Forth/hello-world-text-2.fth +++ b/Task/Hello-world-Text/Forth/hello-world-text-2.fth @@ -1 +1 @@ -: goodbye ( -- ) ." Goodbye, World!" CR ; +: goodbye ( -- ) ." Hello world!" CR ; diff --git a/Task/Hello-world-Text/Fortran/hello-world-text-1.f b/Task/Hello-world-Text/Fortran/hello-world-text-1.f index 100df01b18..3ffd164b8c 100644 --- a/Task/Hello-world-Text/Fortran/hello-world-text-1.f +++ b/Task/Hello-world-Text/Fortran/hello-world-text-1.f @@ -1 +1 @@ -print *,"Goodbye, World!" +print *,"Hello world!" diff --git a/Task/Hello-world-Text/Fortran/hello-world-text-2.f b/Task/Hello-world-Text/Fortran/hello-world-text-2.f index f1686a5452..6e7d43cd4c 100644 --- a/Task/Hello-world-Text/Fortran/hello-world-text-2.f +++ b/Task/Hello-world-Text/Fortran/hello-world-text-2.f @@ -1,2 +1,2 @@ 100 format (5X,A,"!") - print 100,"Goodbye, World!" + print 100,"Hello world!" diff --git a/Task/Hello-world-Text/Fortran/hello-world-text-3.f b/Task/Hello-world-Text/Fortran/hello-world-text-3.f index 48988ab0ed..d3f92bbc7f 100644 --- a/Task/Hello-world-Text/Fortran/hello-world-text-3.f +++ b/Task/Hello-world-Text/Fortran/hello-world-text-3.f @@ -1 +1 @@ -write (89,100) "Goodbye, World!" +write (89,100) "Hello world!" diff --git a/Task/Hello-world-Text/Fortress/hello-world-text.fortress b/Task/Hello-world-Text/Fortress/hello-world-text.fortress index 51008f7285..18e8831941 100644 --- a/Task/Hello-world-Text/Fortress/hello-world-text.fortress +++ b/Task/Hello-world-Text/Fortress/hello-world-text.fortress @@ -1,3 +1,3 @@ export Executable -run() = println("Goodbye, World!") +run() = println("Hello world!") diff --git a/Task/Hello-world-Text/Frege/hello-world-text.frege b/Task/Hello-world-Text/Frege/hello-world-text.frege index c768b1d3a1..579e65c2a5 100644 --- a/Task/Hello-world-Text/Frege/hello-world-text.frege +++ b/Task/Hello-world-Text/Frege/hello-world-text.frege @@ -1,2 +1,2 @@ module HelloWorld where -main _ = println "Goodbye, World!" +main _ = println "Hello world!" diff --git a/Task/Hello-world-Text/Frink/hello-world-text.frink b/Task/Hello-world-Text/Frink/hello-world-text.frink index 54290b41d9..314c8e0de4 100644 --- a/Task/Hello-world-Text/Frink/hello-world-text.frink +++ b/Task/Hello-world-Text/Frink/hello-world-text.frink @@ -1 +1 @@ -println["Goodbye, World!"] +println["Hello world!"] diff --git a/Task/Hello-world-Text/GAP/hello-world-text.gap b/Task/Hello-world-Text/GAP/hello-world-text.gap index be47f9bad2..de057aff9f 100644 --- a/Task/Hello-world-Text/GAP/hello-world-text.gap +++ b/Task/Hello-world-Text/GAP/hello-world-text.gap @@ -1,10 +1,10 @@ # Several ways to do it -"Goodbye, World!"; +"Hello world!"; -Print("Goodbye, World!\n"); # No EOL appended +Print("Hello world!\n"); # No EOL appended -Display("Goodbye, World!"); +Display("Hello world!"); f := OutputTextUser(); -WriteLine(f, "Goodbye, World!\n"); +WriteLine(f, "Hello world!\n"); CloseStream(f); diff --git a/Task/Hello-world-Text/GLBasic/hello-world-text.glbasic b/Task/Hello-world-Text/GLBasic/hello-world-text.glbasic index 4370b68927..f62247f6bf 100644 --- a/Task/Hello-world-Text/GLBasic/hello-world-text.glbasic +++ b/Task/Hello-world-Text/GLBasic/hello-world-text.glbasic @@ -1 +1 @@ -STDOUT "GOODBYE, WORLD!" +STDOUT "Hello world!" diff --git a/Task/Hello-world-Text/GML/hello-world-text.gml b/Task/Hello-world-Text/GML/hello-world-text.gml index 31d117624e..a5cecafbe6 100644 --- a/Task/Hello-world-Text/GML/hello-world-text.gml +++ b/Task/Hello-world-Text/GML/hello-world-text.gml @@ -1,2 +1,2 @@ -show_message("Goodbye, World!"); // displays a pop-up message -show_debug_message("Goodbye, World!"); // sends text to the debug log or IDE +show_message("Hello world!"); // displays a pop-up message +show_debug_message("Hello world!"); // sends text to the debug log or IDE diff --git a/Task/Hello-world-Text/GW-BASIC/hello-world-text.gw-basic b/Task/Hello-world-Text/GW-BASIC/hello-world-text.gw-basic index bb029a7873..323b369b99 100644 --- a/Task/Hello-world-Text/GW-BASIC/hello-world-text.gw-basic +++ b/Task/Hello-world-Text/GW-BASIC/hello-world-text.gw-basic @@ -1 +1 @@ -10 PRINT "Goodbye, World!" +10 PRINT "Hello world!" diff --git a/Task/Hello-world-Text/Gambas/hello-world-text.gambas b/Task/Hello-world-Text/Gambas/hello-world-text.gambas index 2dffd5dbb8..386f4e4cc6 100644 --- a/Task/Hello-world-Text/Gambas/hello-world-text.gambas +++ b/Task/Hello-world-Text/Gambas/hello-world-text.gambas @@ -1 +1 @@ -PRINT "Goodbye, World!" +PRINT "Hello world!" diff --git a/Task/Hello-world-Text/Gema/hello-world-text.gema b/Task/Hello-world-Text/Gema/hello-world-text.gema index 926fc7025e..55dc11086d 100644 --- a/Task/Hello-world-Text/Gema/hello-world-text.gema +++ b/Task/Hello-world-Text/Gema/hello-world-text.gema @@ -1,2 +1,2 @@ *= ! ignore off content of input -\B=Goodbye, World\! ! Start output with this text. +\B=Hello world!\! ! Start output with this text. diff --git a/Task/Hello-world-Text/Gentee/hello-world-text.gentee b/Task/Hello-world-Text/Gentee/hello-world-text.gentee index 03575e8d23..54aaa9d6eb 100644 --- a/Task/Hello-world-Text/Gentee/hello-world-text.gentee +++ b/Task/Hello-world-Text/Gentee/hello-world-text.gentee @@ -1,4 +1,4 @@ func hello
{ - print("Goodbye, World!") + print("Hello world!") } diff --git a/Task/Hello-world-Text/Glee/hello-world-text-1.glee b/Task/Hello-world-Text/Glee/hello-world-text-1.glee index 1e9d709f27..6ccebb9abe 100644 --- a/Task/Hello-world-Text/Glee/hello-world-text-1.glee +++ b/Task/Hello-world-Text/Glee/hello-world-text-1.glee @@ -1 +1 @@ -"Goodbye, World!" +"Hello world!" diff --git a/Task/Hello-world-Text/Glee/hello-world-text-2.glee b/Task/Hello-world-Text/Glee/hello-world-text-2.glee index ff76edc774..adb9840044 100644 --- a/Task/Hello-world-Text/Glee/hello-world-text-2.glee +++ b/Task/Hello-world-Text/Glee/hello-world-text-2.glee @@ -1 +1 @@ -'Goodbye, World!' +'Hello world!' diff --git a/Task/Hello-world-Text/Go/hello-world-text.go b/Task/Hello-world-Text/Go/hello-world-text.go index bb44e8b725..7fe4a1897d 100644 --- a/Task/Hello-world-Text/Go/hello-world-text.go +++ b/Task/Hello-world-Text/Go/hello-world-text.go @@ -2,4 +2,4 @@ package main import "fmt" -func main() { fmt.Println("Goodbye, World!") } +func main() { fmt.Println("Hello world!") } diff --git a/Task/Hello-world-Text/Golfscript/hello-world-text.golf b/Task/Hello-world-Text/Golfscript/hello-world-text.golf index 1e9d709f27..6ccebb9abe 100644 --- a/Task/Hello-world-Text/Golfscript/hello-world-text.golf +++ b/Task/Hello-world-Text/Golfscript/hello-world-text.golf @@ -1 +1 @@ -"Goodbye, World!" +"Hello world!" diff --git a/Task/Hello-world-Text/Gosu/hello-world-text.gosu b/Task/Hello-world-Text/Gosu/hello-world-text.gosu index b4f3181031..f1a18139c8 100644 --- a/Task/Hello-world-Text/Gosu/hello-world-text.gosu +++ b/Task/Hello-world-Text/Gosu/hello-world-text.gosu @@ -1 +1 @@ -print("Goodbye, World!") +print("Hello world!") diff --git a/Task/Hello-world-Text/Groovy/hello-world-text.groovy b/Task/Hello-world-Text/Groovy/hello-world-text.groovy index 8fa3591166..3351bb7ccd 100644 --- a/Task/Hello-world-Text/Groovy/hello-world-text.groovy +++ b/Task/Hello-world-Text/Groovy/hello-world-text.groovy @@ -1 +1 @@ -println "Goodbye, World!" +println "Hello world!" diff --git a/Task/Hello-world-Text/HLA/hello-world-text.hla b/Task/Hello-world-Text/HLA/hello-world-text.hla index d7f52e4992..ca220c57c5 100644 --- a/Task/Hello-world-Text/HLA/hello-world-text.hla +++ b/Task/Hello-world-Text/HLA/hello-world-text.hla @@ -2,6 +2,6 @@ program goodbyeWorld; #include("stdlib.hhf") begin goodbyeWorld; - stdout.put( "Goodbye, World!" nl ); + stdout.put( "Hello world!" nl ); end goodbyeWorld; diff --git a/Task/Hello-world-Text/Haskell/hello-world-text.hs b/Task/Hello-world-Text/Haskell/hello-world-text.hs index bd50e65f95..bc88e41bcf 100644 --- a/Task/Hello-world-Text/Haskell/hello-world-text.hs +++ b/Task/Hello-world-Text/Haskell/hello-world-text.hs @@ -1 +1 @@ -main = putStrLn "Goodbye, World!" +main = putStrLn "Hello world!" diff --git a/Task/Hello-world-Text/Haxe/hello-world-text.haxe b/Task/Hello-world-Text/Haxe/hello-world-text.haxe index f2c4a774ba..f00ea826cd 100644 --- a/Task/Hello-world-Text/Haxe/hello-world-text.haxe +++ b/Task/Hello-world-Text/Haxe/hello-world-text.haxe @@ -1 +1 @@ -trace("Goodbye, World!"); +trace("Hello world!"); diff --git a/Task/Hello-world-Text/HicEst/hello-world-text.hicest b/Task/Hello-world-Text/HicEst/hello-world-text.hicest index 09fa11b14f..fa691f697e 100644 --- a/Task/Hello-world-Text/HicEst/hello-world-text.hicest +++ b/Task/Hello-world-Text/HicEst/hello-world-text.hicest @@ -1 +1 @@ -WRITE() 'Goodbye, World!' +WRITE() 'Hello world!' diff --git a/Task/Hello-world-Text/IDL/hello-world-text.idl b/Task/Hello-world-Text/IDL/hello-world-text.idl index 57c420036f..2e6d5c0697 100644 --- a/Task/Hello-world-Text/IDL/hello-world-text.idl +++ b/Task/Hello-world-Text/IDL/hello-world-text.idl @@ -1 +1 @@ -print,'Goodbye, World!' +print,'Hello world!' diff --git a/Task/Hello-world-Text/Icon/hello-world-text.icon b/Task/Hello-world-Text/Icon/hello-world-text.icon index 58efa3eb4a..abf46ae27c 100644 --- a/Task/Hello-world-Text/Icon/hello-world-text.icon +++ b/Task/Hello-world-Text/Icon/hello-world-text.icon @@ -1,3 +1,3 @@ procedure main() - write( "Goodbye, World!" ) + write( "Hello world!" ) end diff --git a/Task/Hello-world-Text/Inform-6/hello-world-text.inf b/Task/Hello-world-Text/Inform-6/hello-world-text.inf index 0d163a54b3..662e7b76e1 100644 --- a/Task/Hello-world-Text/Inform-6/hello-world-text.inf +++ b/Task/Hello-world-Text/Inform-6/hello-world-text.inf @@ -1,3 +1,3 @@ [Main; - print "Goodbye, World!^"; + print "Hello world!^"; ]; diff --git a/Task/Hello-world-Text/Integer-BASIC/hello-world-text.integer b/Task/Hello-world-Text/Integer-BASIC/hello-world-text.integer index efdcc2b172..7fd757457e 100644 --- a/Task/Hello-world-Text/Integer-BASIC/hello-world-text.integer +++ b/Task/Hello-world-Text/Integer-BASIC/hello-world-text.integer @@ -1,2 +1,2 @@ - 10 PRINT "GOODBYE, WORLD!" + 10 PRINT "Hello world!" 20 END diff --git a/Task/Hello-world-Text/Io/hello-world-text.io b/Task/Hello-world-Text/Io/hello-world-text.io index 08ea2f6744..074245447f 100644 --- a/Task/Hello-world-Text/Io/hello-world-text.io +++ b/Task/Hello-world-Text/Io/hello-world-text.io @@ -1 +1 @@ -"Goodbye, World!" println +"Hello world!" println diff --git a/Task/Hello-world-Text/Ioke/hello-world-text.ioke b/Task/Hello-world-Text/Ioke/hello-world-text.ioke index 08ea2f6744..074245447f 100644 --- a/Task/Hello-world-Text/Ioke/hello-world-text.ioke +++ b/Task/Hello-world-Text/Ioke/hello-world-text.ioke @@ -1 +1 @@ -"Goodbye, World!" println +"Hello world!" println diff --git a/Task/Hello-world-Text/J/hello-world-text-1.j b/Task/Hello-world-Text/J/hello-world-text-1.j index 39c972e7ca..6b8183b470 100644 --- a/Task/Hello-world-Text/J/hello-world-text-1.j +++ b/Task/Hello-world-Text/J/hello-world-text-1.j @@ -1,2 +1,2 @@ - 'Goodbye, World!' -Goodbye, World! + 'Hello world!' +Hello world! diff --git a/Task/Hello-world-Text/J/hello-world-text-2.j b/Task/Hello-world-Text/J/hello-world-text-2.j index f4b2c424e3..5d07467dcb 100644 --- a/Task/Hello-world-Text/J/hello-world-text-2.j +++ b/Task/Hello-world-Text/J/hello-world-text-2.j @@ -1,6 +1,6 @@ - [data=. 'Goodbye, World!' -Goodbye, World! + [data=. 'Hello world!' +Hello world! data -Goodbye, World! +Hello world! smoutput data -Goodbye, World! +Hello world! diff --git a/Task/Hello-world-Text/JCL/hello-world-text.jcl b/Task/Hello-world-Text/JCL/hello-world-text.jcl index 7383f874d9..2061fd90d7 100644 --- a/Task/Hello-world-Text/JCL/hello-world-text.jcl +++ b/Task/Hello-world-Text/JCL/hello-world-text.jcl @@ -1 +1 @@ -/*MESSAGE Goodbye, World! +/*MESSAGE Hello world! diff --git a/Task/Hello-world-Text/Java/hello-world-text.java b/Task/Hello-world-Text/Java/hello-world-text.java index 1e51bb296c..4225ecfaf6 100644 --- a/Task/Hello-world-Text/Java/hello-world-text.java +++ b/Task/Hello-world-Text/Java/hello-world-text.java @@ -2,6 +2,6 @@ public class HelloWorld { public static void main(String[] args) { - System.out.println("Goodbye, World!"); + System.out.println("Hello world!"); } } diff --git a/Task/Hello-world-Text/JavaScript/hello-world-text-1.js b/Task/Hello-world-Text/JavaScript/hello-world-text-1.js index 44f0887c57..a4c6e72ffa 100644 --- a/Task/Hello-world-Text/JavaScript/hello-world-text-1.js +++ b/Task/Hello-world-Text/JavaScript/hello-world-text-1.js @@ -1 +1 @@ -document.write("Goodbye, World!"); +document.write("Hello world!"); diff --git a/Task/Hello-world-Text/JavaScript/hello-world-text-2.js b/Task/Hello-world-Text/JavaScript/hello-world-text-2.js index ebe9fadde8..009072f619 100644 --- a/Task/Hello-world-Text/JavaScript/hello-world-text-2.js +++ b/Task/Hello-world-Text/JavaScript/hello-world-text-2.js @@ -1 +1 @@ -print('Goodbye, World!'); +print('Hello world!'); diff --git a/Task/Hello-world-Text/JavaScript/hello-world-text-3.js b/Task/Hello-world-Text/JavaScript/hello-world-text-3.js index 488ccbf140..30a32b3b59 100644 --- a/Task/Hello-world-Text/JavaScript/hello-world-text-3.js +++ b/Task/Hello-world-Text/JavaScript/hello-world-text-3.js @@ -1 +1 @@ -WScript.Echo("Goodbye, World!"); +WScript.Echo("Hello world!"); diff --git a/Task/Hello-world-Text/JavaScript/hello-world-text-4.js b/Task/Hello-world-Text/JavaScript/hello-world-text-4.js index 9848c0d61c..6a5ba06c60 100644 --- a/Task/Hello-world-Text/JavaScript/hello-world-text-4.js +++ b/Task/Hello-world-Text/JavaScript/hello-world-text-4.js @@ -1 +1 @@ -console.log("Goodbye, World!") +console.log("Hello world!") diff --git a/Task/Hello-world-Text/Joy/hello-world-text.joy b/Task/Hello-world-Text/Joy/hello-world-text.joy index 6b50dbca5a..2b1cf72b7c 100644 --- a/Task/Hello-world-Text/Joy/hello-world-text.joy +++ b/Task/Hello-world-Text/Joy/hello-world-text.joy @@ -1 +1 @@ -"Goodbye, World!" putchars. +"Hello world!" putchars. diff --git a/Task/Hello-world-Text/Julia/hello-world-text.julia b/Task/Hello-world-Text/Julia/hello-world-text.julia index d0337b0351..50095f70c5 100644 --- a/Task/Hello-world-Text/Julia/hello-world-text.julia +++ b/Task/Hello-world-Text/Julia/hello-world-text.julia @@ -1 +1 @@ -println("Goodbye, World!") +println("Hello world!") diff --git a/Task/Hello-world-Text/Kaya/hello-world-text.kaya b/Task/Hello-world-Text/Kaya/hello-world-text.kaya index 44abad835a..b9509a7e40 100644 --- a/Task/Hello-world-Text/Kaya/hello-world-text.kaya +++ b/Task/Hello-world-Text/Kaya/hello-world-text.kaya @@ -2,5 +2,5 @@ program hello; Void main() { // My first program! - putStrLn("Goodbye, World!"); + putStrLn("Hello world!"); } diff --git a/Task/Hello-world-Text/Kite/hello-world-text.kite b/Task/Hello-world-Text/Kite/hello-world-text.kite index b47e8d6fcf..4d5ce411f0 100644 --- a/Task/Hello-world-Text/Kite/hello-world-text.kite +++ b/Task/Hello-world-Text/Kite/hello-world-text.kite @@ -1,3 +1,3 @@ "#!/usr/local/bin/kite -"Goodbye, World!"|print; +"Hello world!"|print; diff --git a/Task/Hello-world-Text/KonsolScript/hello-world-text.konsol b/Task/Hello-world-Text/KonsolScript/hello-world-text.konsol index b53be6fde7..8d41cd9fe1 100644 --- a/Task/Hello-world-Text/KonsolScript/hello-world-text.konsol +++ b/Task/Hello-world-Text/KonsolScript/hello-world-text.konsol @@ -1,3 +1,3 @@ function main() { - Konsol:Log("Goodbye, World!") + Konsol:Log("Hello world!") } diff --git a/Task/Hello-world-Text/Kotlin/hello-world-text.kotlin b/Task/Hello-world-Text/Kotlin/hello-world-text.kotlin new file mode 100644 index 0000000000..0476fd7c36 --- /dev/null +++ b/Task/Hello-world-Text/Kotlin/hello-world-text.kotlin @@ -0,0 +1,3 @@ +fun main(args: Array) { + println("Hello world!") +} diff --git a/Task/Hello-world-Text/LOLCODE/hello-world-text.lol b/Task/Hello-world-Text/LOLCODE/hello-world-text.lol index 3ea1818f8b..b08c82a5d6 100644 --- a/Task/Hello-world-Text/LOLCODE/hello-world-text.lol +++ b/Task/Hello-world-Text/LOLCODE/hello-world-text.lol @@ -1,4 +1,4 @@ HAI CAN HAS STDIO? -VISIBLE "Goodbye, World!" +VISIBLE "Hello world!" KTHXBYE diff --git a/Task/Hello-world-Text/LSE64/hello-world-text.lse64 b/Task/Hello-world-Text/LSE64/hello-world-text.lse64 index 3906efcea8..a6f23f56c4 100644 --- a/Task/Hello-world-Text/LSE64/hello-world-text.lse64 +++ b/Task/Hello-world-Text/LSE64/hello-world-text.lse64 @@ -1 +1 @@ -"Goodbye, World!" ,t nl +"Hello world!" ,t nl diff --git a/Task/Hello-world-Text/Lang5/hello-world-text.lang5 b/Task/Hello-world-Text/Lang5/hello-world-text.lang5 index 004ce7a41f..9c7e3e003d 100644 --- a/Task/Hello-world-Text/Lang5/hello-world-text.lang5 +++ b/Task/Hello-world-Text/Lang5/hello-world-text.lang5 @@ -1 +1 @@ -"Goodbye, World!\n" . +"Hello world!\n" . diff --git a/Task/Hello-world-Text/Liberty-BASIC/hello-world-text.liberty b/Task/Hello-world-Text/Liberty-BASIC/hello-world-text.liberty index a9f594ad30..ed708ec5fb 100644 --- a/Task/Hello-world-Text/Liberty-BASIC/hello-world-text.liberty +++ b/Task/Hello-world-Text/Liberty-BASIC/hello-world-text.liberty @@ -1 +1 @@ -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/Limbo/hello-world-text.limbo b/Task/Hello-world-Text/Limbo/hello-world-text.limbo index ab62b15e6f..32e3c1884e 100644 --- a/Task/Hello-world-Text/Limbo/hello-world-text.limbo +++ b/Task/Hello-world-Text/Limbo/hello-world-text.limbo @@ -10,5 +10,5 @@ implement Command; init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH; - sys->print("Goodby, World!\n"); + sys->print("Hello world!\n"); } diff --git a/Task/Hello-world-Text/Lisaac/hello-world-text-1.lisaac b/Task/Hello-world-Text/Lisaac/hello-world-text-1.lisaac index c3f41a6792..279ef9dd07 100644 --- a/Task/Hello-world-Text/Lisaac/hello-world-text-1.lisaac +++ b/Task/Hello-world-Text/Lisaac/hello-world-text-1.lisaac @@ -2,4 +2,4 @@ Section Header // The Header section is required. + name := GOODBYE; // Define the name of this object. Section Public - - main <- ("Goodbye, World!\n".print;); + - main <- ("Hello world!\n".print;); diff --git a/Task/Hello-world-Text/Lisaac/hello-world-text-2.lisaac b/Task/Hello-world-Text/Lisaac/hello-world-text-2.lisaac index dd29f31d1d..dd958f731d 100644 --- a/Task/Hello-world-Text/Lisaac/hello-world-text-2.lisaac +++ b/Task/Hello-world-Text/Lisaac/hello-world-text-2.lisaac @@ -2,4 +2,4 @@ Section Header // The Header section is required. + name := GOODBYE2; // Define the name of this object. Section Public - - main <- (IO.put_string "Goodbye, World!\n";); + - main <- (IO.put_string "Hello world!\n";); diff --git a/Task/Hello-world-Text/Logo/hello-world-text-1.logo b/Task/Hello-world-Text/Logo/hello-world-text-1.logo index 25e0a6d51a..13f27995d1 100644 --- a/Task/Hello-world-Text/Logo/hello-world-text-1.logo +++ b/Task/Hello-world-Text/Logo/hello-world-text-1.logo @@ -1 +1 @@ -print [Goodbye, World!] +print [Hello world!] diff --git a/Task/Hello-world-Text/Logo/hello-world-text-2.logo b/Task/Hello-world-Text/Logo/hello-world-text-2.logo index d115fd0908..cc75f97e4a 100644 --- a/Task/Hello-world-Text/Logo/hello-world-text-2.logo +++ b/Task/Hello-world-Text/Logo/hello-world-text-2.logo @@ -1 +1 @@ -type [Goodbye, World!] +type [Hello world!] diff --git a/Task/Hello-world-Text/Logtalk/hello-world-text.logtalk b/Task/Hello-world-Text/Logtalk/hello-world-text.logtalk index c6fbe1017e..f1b9a2697d 100644 --- a/Task/Hello-world-Text/Logtalk/hello-world-text.logtalk +++ b/Task/Hello-world-Text/Logtalk/hello-world-text.logtalk @@ -2,6 +2,6 @@ % the initialization/1 directive argument is automatically executed % when the object is loaded into memory: - :- initialization(write('Goodbye, World!\n')). + :- initialization(write('Hello world!\n')). :- end_object. diff --git a/Task/Hello-world-Text/LotusScript/hello-world-text.lotus b/Task/Hello-world-Text/LotusScript/hello-world-text.lotus index 89d8bbdcc3..96d9645e3b 100644 --- a/Task/Hello-world-Text/LotusScript/hello-world-text.lotus +++ b/Task/Hello-world-Text/LotusScript/hello-world-text.lotus @@ -1,5 +1,5 @@ :- object(hello_world). 'This will send the output to the status bar at the bottom of the Notes client screen - print "Goodbye, World!" + print "Hello world!" :- end_object. diff --git a/Task/Hello-world-Text/Lua/hello-world-text-1.lua b/Task/Hello-world-Text/Lua/hello-world-text-1.lua index a9f594ad30..ed708ec5fb 100644 --- a/Task/Hello-world-Text/Lua/hello-world-text-1.lua +++ b/Task/Hello-world-Text/Lua/hello-world-text-1.lua @@ -1 +1 @@ -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/M4/hello-world-text.m4 b/Task/Hello-world-Text/M4/hello-world-text.m4 index 76aa175531..e71ae40d23 100644 --- a/Task/Hello-world-Text/M4/hello-world-text.m4 +++ b/Task/Hello-world-Text/M4/hello-world-text.m4 @@ -1 +1 @@ -`Goodbye, World!' +`Hello world!' diff --git a/Task/Hello-world-Text/MATLAB/hello-world-text.m b/Task/Hello-world-Text/MATLAB/hello-world-text.m index 6882cf79f0..09623a85fd 100644 --- a/Task/Hello-world-Text/MATLAB/hello-world-text.m +++ b/Task/Hello-world-Text/MATLAB/hello-world-text.m @@ -1,5 +1 @@ ->> 'Goodbye, World!' - -ans = - -Goodbye, World! +>> disp('Hello world!') diff --git a/Task/Hello-world-Text/MAXScript/hello-world-text-1.max b/Task/Hello-world-Text/MAXScript/hello-world-text-1.max index a9f594ad30..ed708ec5fb 100644 --- a/Task/Hello-world-Text/MAXScript/hello-world-text-1.max +++ b/Task/Hello-world-Text/MAXScript/hello-world-text-1.max @@ -1 +1 @@ -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/MAXScript/hello-world-text-2.max b/Task/Hello-world-Text/MAXScript/hello-world-text-2.max index 7d1ac51fed..532162609b 100644 --- a/Task/Hello-world-Text/MAXScript/hello-world-text-2.max +++ b/Task/Hello-world-Text/MAXScript/hello-world-text-2.max @@ -1 +1 @@ -format "%" "Goodbye, World!" +format "%" "Hello world!" diff --git a/Task/Hello-world-Text/MIPS-Assembly/hello-world-text.mips b/Task/Hello-world-Text/MIPS-Assembly/hello-world-text.mips index 5c15dfe390..65359dd6b3 100644 --- a/Task/Hello-world-Text/MIPS-Assembly/hello-world-text.mips +++ b/Task/Hello-world-Text/MIPS-Assembly/hello-world-text.mips @@ -1,5 +1,5 @@ .data -hello: .asciiz "Goodbye, World!" +hello: .asciiz "Hello world!" .text main: diff --git a/Task/Hello-world-Text/ML-I/hello-world-text.ml b/Task/Hello-world-Text/ML-I/hello-world-text.ml index f06c489626..cd0875583a 100644 --- a/Task/Hello-world-Text/ML-I/hello-world-text.ml +++ b/Task/Hello-world-Text/ML-I/hello-world-text.ml @@ -1 +1 @@ -Goodbye, World! +Hello world! diff --git a/Task/Hello-world-Text/MUF/hello-world-text.muf b/Task/Hello-world-Text/MUF/hello-world-text.muf index efeb2cb78c..8ff63de4a1 100644 --- a/Task/Hello-world-Text/MUF/hello-world-text.muf +++ b/Task/Hello-world-Text/MUF/hello-world-text.muf @@ -1,4 +1,4 @@ : main[ -- ] -me @ "Goodbye, World!" notify +me @ "Hello world!" notify exit ; diff --git a/Task/Hello-world-Text/MUMPS/hello-world-text.mumps b/Task/Hello-world-Text/MUMPS/hello-world-text.mumps index 89c0d829d0..fe55bfda90 100644 --- a/Task/Hello-world-Text/MUMPS/hello-world-text.mumps +++ b/Task/Hello-world-Text/MUMPS/hello-world-text.mumps @@ -1 +1 @@ -Write "Goodbye, World!",! +Write "Hello world!",! diff --git a/Task/Hello-world-Text/Maple/hello-world-text.maple b/Task/Hello-world-Text/Maple/hello-world-text.maple index b7346c3c1b..58d3effde9 100644 --- a/Task/Hello-world-Text/Maple/hello-world-text.maple +++ b/Task/Hello-world-Text/Maple/hello-world-text.maple @@ -1,2 +1,2 @@ -> printf( "Goodbye, World!\n" ): # print without quotes -Goodbye, World! +> printf( "Hello world!\n" ): # print without quotes +Hello world! diff --git a/Task/Hello-world-Text/Mathematica/hello-world-text.math b/Task/Hello-world-Text/Mathematica/hello-world-text.math index fc3ee4c8a9..5c09770df6 100644 --- a/Task/Hello-world-Text/Mathematica/hello-world-text.math +++ b/Task/Hello-world-Text/Mathematica/hello-world-text.math @@ -1 +1 @@ -Print["Goodbye, World!"] +Print["Hello world!"] diff --git a/Task/Hello-world-Text/Maxima/hello-world-text.maxima b/Task/Hello-world-Text/Maxima/hello-world-text.maxima index eac215fa44..defc677327 100644 --- a/Task/Hello-world-Text/Maxima/hello-world-text.maxima +++ b/Task/Hello-world-Text/Maxima/hello-world-text.maxima @@ -1 +1 @@ -print("Goodbye, World!"); +print("Hello world!"); diff --git a/Task/Hello-world-Text/Mercury/hello-world-text.mercury b/Task/Hello-world-Text/Mercury/hello-world-text.mercury index 161d4dc494..cfc1455fea 100644 --- a/Task/Hello-world-Text/Mercury/hello-world-text.mercury +++ b/Task/Hello-world-Text/Mercury/hello-world-text.mercury @@ -5,4 +5,4 @@ :- implementation. main(!IO) :- - io.write_string("Goodbye, World!\n", !IO). + io.write_string("Hello world!\n", !IO). diff --git a/Task/Hello-world-Text/Metafont/hello-world-text.metafont b/Task/Hello-world-Text/Metafont/hello-world-text.metafont index dc716d0de1..0beb4de830 100644 --- a/Task/Hello-world-Text/Metafont/hello-world-text.metafont +++ b/Task/Hello-world-Text/Metafont/hello-world-text.metafont @@ -1 +1 @@ -message "Goodbye, World!"; end +message "Hello world!"; end diff --git a/Task/Hello-world-Text/Modula-2/hello-world-text.mod2 b/Task/Hello-world-Text/Modula-2/hello-world-text.mod2 index b8300cc918..453faa08e1 100644 --- a/Task/Hello-world-Text/Modula-2/hello-world-text.mod2 +++ b/Task/Hello-world-Text/Modula-2/hello-world-text.mod2 @@ -2,6 +2,6 @@ MODULE Hello; IMPORT InOut; BEGIN - InOut.WriteString('Goodbye, World!'); + InOut.WriteString('Hello world!'); InOut.WriteLn END Hello. diff --git a/Task/Hello-world-Text/Modula-3/hello-world-text.mod3 b/Task/Hello-world-Text/Modula-3/hello-world-text.mod3 index 133d8da65d..a9cece92b0 100644 --- a/Task/Hello-world-Text/Modula-3/hello-world-text.mod3 +++ b/Task/Hello-world-Text/Modula-3/hello-world-text.mod3 @@ -3,5 +3,5 @@ MODULE Goodbye EXPORTS Main; IMPORT IO; BEGIN - IO.Put("Goodbye, World!\n"); + IO.Put("Hello world!\n"); END Goodbye. diff --git a/Task/Hello-world-Text/MySQL/hello-world-text.sql b/Task/Hello-world-Text/MySQL/hello-world-text.sql index 2fabe73bf3..78914dc4f2 100644 --- a/Task/Hello-world-Text/MySQL/hello-world-text.sql +++ b/Task/Hello-world-Text/MySQL/hello-world-text.sql @@ -1 +1 @@ -SELECT 'Goodbye, World!'; +SELECT 'Hello world!'; diff --git a/Task/Hello-world-Text/Mythryl/hello-world-text.mythryl b/Task/Hello-world-Text/Mythryl/hello-world-text.mythryl index 06eb32599c..b1988172b9 100644 --- a/Task/Hello-world-Text/Mythryl/hello-world-text.mythryl +++ b/Task/Hello-world-Text/Mythryl/hello-world-text.mythryl @@ -1 +1 @@ -print "Goodbye, World!"; +print "Hello world!"; diff --git a/Task/Hello-world-Text/Neat/hello-world-text.neat b/Task/Hello-world-Text/Neat/hello-world-text.neat index ab97a2646b..e3b805f3aa 100644 --- a/Task/Hello-world-Text/Neat/hello-world-text.neat +++ b/Task/Hello-world-Text/Neat/hello-world-text.neat @@ -1 +1 @@ -void main() writeln "Goodbye, World!"; +void main() writeln "Hello world!"; diff --git a/Task/Hello-world-Text/Neko/hello-world-text.neko b/Task/Hello-world-Text/Neko/hello-world-text.neko index 8ed64406d4..1328fa7569 100644 --- a/Task/Hello-world-Text/Neko/hello-world-text.neko +++ b/Task/Hello-world-Text/Neko/hello-world-text.neko @@ -1 +1 @@ -$print("Hello, World!"); +$print("Hello world!"); diff --git a/Task/Hello-world-Text/Nemerle/hello-world-text-1.nemerle b/Task/Hello-world-Text/Nemerle/hello-world-text-1.nemerle index 9defd3f17b..2ea02035a8 100644 --- a/Task/Hello-world-Text/Nemerle/hello-world-text-1.nemerle +++ b/Task/Hello-world-Text/Nemerle/hello-world-text-1.nemerle @@ -2,6 +2,6 @@ class Hello { static Main () : void { - System.Console.WriteLine ("Goodbye, World!"); + System.Console.WriteLine ("Hello world!"); } } diff --git a/Task/Hello-world-Text/Nemerle/hello-world-text-2.nemerle b/Task/Hello-world-Text/Nemerle/hello-world-text-2.nemerle index b1f5473b85..c9486a9522 100644 --- a/Task/Hello-world-Text/Nemerle/hello-world-text-2.nemerle +++ b/Task/Hello-world-Text/Nemerle/hello-world-text-2.nemerle @@ -1 +1 @@ -System.Console.WriteLine("Goodbye, World!"); +System.Console.WriteLine("Hello world!"); diff --git a/Task/Hello-world-Text/NetRexx/hello-world-text.netrexx b/Task/Hello-world-Text/NetRexx/hello-world-text.netrexx index 8c798aab61..bbf76183ce 100644 --- a/Task/Hello-world-Text/NetRexx/hello-world-text.netrexx +++ b/Task/Hello-world-Text/NetRexx/hello-world-text.netrexx @@ -1 +1 @@ -say 'Goodbye, World!' +say 'Hello world!' diff --git a/Task/Hello-world-Text/OCaml/hello-world-text.ocaml b/Task/Hello-world-Text/OCaml/hello-world-text.ocaml index b504b7e416..d90c3537b2 100644 --- a/Task/Hello-world-Text/OCaml/hello-world-text.ocaml +++ b/Task/Hello-world-Text/OCaml/hello-world-text.ocaml @@ -1 +1 @@ -print_endline "Goodbye, World!" +print_endline "Hello world!" diff --git a/Task/Hello-world-Text/OOC/hello-world-text-1.ooc b/Task/Hello-world-Text/OOC/hello-world-text-1.ooc index b9fdcac47b..c35a40ce1f 100644 --- a/Task/Hello-world-Text/OOC/hello-world-text-1.ooc +++ b/Task/Hello-world-Text/OOC/hello-world-text-1.ooc @@ -1,3 +1,3 @@ main: func { - "Goodbye, World!" println() + "Hello world!" println() } diff --git a/Task/Hello-world-Text/OOC/hello-world-text-2.ooc b/Task/Hello-world-Text/OOC/hello-world-text-2.ooc index fb973c0dd9..1430eb94c3 100644 --- a/Task/Hello-world-Text/OOC/hello-world-text-2.ooc +++ b/Task/Hello-world-Text/OOC/hello-world-text-2.ooc @@ -1,3 +1,3 @@ main: func { - println("Goodbye, World!") + println("Hello world!") } diff --git a/Task/Hello-world-Text/Oberon-2/hello-world-text.oberon-2 b/Task/Hello-world-Text/Oberon-2/hello-world-text.oberon-2 index d2044b8374..507075b263 100644 --- a/Task/Hello-world-Text/Oberon-2/hello-world-text.oberon-2 +++ b/Task/Hello-world-Text/Oberon-2/hello-world-text.oberon-2 @@ -2,7 +2,7 @@ MODULE Goodbye; IMPORT Out; PROCEDURE World*; BEGIN - Out.String("Goodbye, World!");Out.Ln + Out.String("Hello world!");Out.Ln END World; BEGIN World; diff --git a/Task/Hello-world-Text/Objeck/hello-world-text.objeck b/Task/Hello-world-Text/Objeck/hello-world-text.objeck index 480818b4e4..c2b5c86ed9 100644 --- a/Task/Hello-world-Text/Objeck/hello-world-text.objeck +++ b/Task/Hello-world-Text/Objeck/hello-world-text.objeck @@ -1,5 +1,5 @@ class Hello { function : Main(args : String[]) ~ Nil { - "Goodbye, World!"->PrintLine(); + "Hello world!"->PrintLine(); } } diff --git a/Task/Hello-world-Text/Objective-C/hello-world-text-1.m b/Task/Hello-world-Text/Objective-C/hello-world-text-1.m index 993876a0e6..0c05f24bb2 100644 --- a/Task/Hello-world-Text/Objective-C/hello-world-text-1.m +++ b/Task/Hello-world-Text/Objective-C/hello-world-text-1.m @@ -1 +1,7 @@ -printf("Goodbye, World!"); +#import + +int main() { + @autoreleasepool { + NSLog(@"Hello, World!"); + } +} diff --git a/Task/Hello-world-Text/Objective-C/hello-world-text-2.m b/Task/Hello-world-Text/Objective-C/hello-world-text-2.m index d2fa2ce824..fb6a763a1f 100644 --- a/Task/Hello-world-Text/Objective-C/hello-world-text-2.m +++ b/Task/Hello-world-Text/Objective-C/hello-world-text-2.m @@ -1 +1,9 @@ -printf("%s", [@"Goodbye, World!" UTF8String]); +#import + +int main() { + @autoreleasepool { + NSFileHandle *standardOutput = [NSFileHandle fileHandleWithStandardOutput]; + NSString *message = @"Hello, World!\n"; + [standardOutput writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } +} diff --git a/Task/Hello-world-Text/Objective-C/hello-world-text-3.m b/Task/Hello-world-Text/Objective-C/hello-world-text-3.m index 842002e0ae..899b76ce0f 100644 --- a/Task/Hello-world-Text/Objective-C/hello-world-text-3.m +++ b/Task/Hello-world-Text/Objective-C/hello-world-text-3.m @@ -1 +1,8 @@ -[@"Goodbye, World!" writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:NULL]; +#import + +int main() { + @autoreleasepool { + NSString *message = @"Hello, World!\n"; + printf("%s", message.UTF8String); + } +} diff --git a/Task/Hello-world-Text/Occam/hello-world-text.occam b/Task/Hello-world-Text/Occam/hello-world-text.occam index 0cc9fc474c..ce07507476 100644 --- a/Task/Hello-world-Text/Occam/hello-world-text.occam +++ b/Task/Hello-world-Text/Occam/hello-world-text.occam @@ -1,4 +1,4 @@ #USE "course.lib" PROC main (CHAN BYTE screen!) - out.string("Goodbye, World!*c*n", 0, screen) + out.string("Hello world!*c*n", 0, screen) : diff --git a/Task/Hello-world-Text/Octave/hello-world-text-1.octave b/Task/Hello-world-Text/Octave/hello-world-text-1.octave index 2a78fe60de..ed2464682d 100644 --- a/Task/Hello-world-Text/Octave/hello-world-text-1.octave +++ b/Task/Hello-world-Text/Octave/hello-world-text-1.octave @@ -1 +1 @@ -disp("Goodbye, World!"); +disp("Hello world!"); diff --git a/Task/Hello-world-Text/Octave/hello-world-text-2.octave b/Task/Hello-world-Text/Octave/hello-world-text-2.octave index 993876a0e6..b0faad6066 100644 --- a/Task/Hello-world-Text/Octave/hello-world-text-2.octave +++ b/Task/Hello-world-Text/Octave/hello-world-text-2.octave @@ -1 +1 @@ -printf("Goodbye, World!"); +printf("Hello world!"); diff --git a/Task/Hello-world-Text/Onyx/hello-world-text.onyx b/Task/Hello-world-Text/Onyx/hello-world-text.onyx index fd2c19129a..7b9a5bda79 100644 --- a/Task/Hello-world-Text/Onyx/hello-world-text.onyx +++ b/Task/Hello-world-Text/Onyx/hello-world-text.onyx @@ -1 +1 @@ -`Goodbye, World!\n' print +`Hello world!\n' print diff --git a/Task/Hello-world-Text/Openscad/hello-world-text.scad b/Task/Hello-world-Text/Openscad/hello-world-text.scad index a5580ff455..a560d61ce1 100644 --- a/Task/Hello-world-Text/Openscad/hello-world-text.scad +++ b/Task/Hello-world-Text/Openscad/hello-world-text.scad @@ -1 +1 @@ -echo("Goodbye, World!"); +echo("Hello world!"); diff --git a/Task/Hello-world-Text/Oxygene/hello-world-text.oxy b/Task/Hello-world-Text/Oxygene/hello-world-text.oxy index 501886288f..4cceff3d83 100644 --- a/Task/Hello-world-Text/Oxygene/hello-world-text.oxy +++ b/Task/Hello-world-Text/Oxygene/hello-world-text.oxy @@ -12,7 +12,7 @@ implementation class method HelloClass.Main; begin - System.Console.WriteLine('Goodbye, World!'); + System.Console.WriteLine('Hello world!'); end; end. diff --git a/Task/Hello-world-Text/Oz/hello-world-text.oz b/Task/Hello-world-Text/Oz/hello-world-text.oz index a32f5c4c5f..b799b247fe 100644 --- a/Task/Hello-world-Text/Oz/hello-world-text.oz +++ b/Task/Hello-world-Text/Oz/hello-world-text.oz @@ -1 +1 @@ -{Show "Goodbye, World!"} +{Show "Hello world!"} diff --git a/Task/Hello-world-Text/PARI-GP/hello-world-text.pari b/Task/Hello-world-Text/PARI-GP/hello-world-text.pari index b4f3181031..f1a18139c8 100644 --- a/Task/Hello-world-Text/PARI-GP/hello-world-text.pari +++ b/Task/Hello-world-Text/PARI-GP/hello-world-text.pari @@ -1 +1 @@ -print("Goodbye, World!") +print("Hello world!") diff --git a/Task/Hello-world-Text/PASM/hello-world-text.pasm b/Task/Hello-world-Text/PASM/hello-world-text.pasm index bba999a87c..b4b6acc747 100644 --- a/Task/Hello-world-Text/PASM/hello-world-text.pasm +++ b/Task/Hello-world-Text/PASM/hello-world-text.pasm @@ -1,2 +1,2 @@ -print "Goodbye, World!\n" +print "Hello world!\n" end diff --git a/Task/Hello-world-Text/PDP-11-Assembly/hello-world-text.pdp-11 b/Task/Hello-world-Text/PDP-11-Assembly/hello-world-text.pdp-11 index 8ac332f2b4..c803dc363c 100644 --- a/Task/Hello-world-Text/PDP-11-Assembly/hello-world-text.pdp-11 +++ b/Task/Hello-world-Text/PDP-11-Assembly/hello-world-text.pdp-11 @@ -7,5 +7,5 @@ start: rts pc .data -outtext: +outtext: outlen = . - outtext diff --git a/Task/Hello-world-Text/PHP/hello-world-text-1.php b/Task/Hello-world-Text/PHP/hello-world-text-1.php index cbbf2eac24..7f04413a9a 100644 --- a/Task/Hello-world-Text/PHP/hello-world-text-1.php +++ b/Task/Hello-world-Text/PHP/hello-world-text-1.php @@ -1,3 +1,3 @@ diff --git a/Task/Hello-world-Text/PHP/hello-world-text-2.php b/Task/Hello-world-Text/PHP/hello-world-text-2.php index f06c489626..cd0875583a 100644 --- a/Task/Hello-world-Text/PHP/hello-world-text-2.php +++ b/Task/Hello-world-Text/PHP/hello-world-text-2.php @@ -1 +1 @@ -Goodbye, World! +Hello world! diff --git a/Task/Hello-world-Text/PIR/hello-world-text.pir b/Task/Hello-world-Text/PIR/hello-world-text.pir index 9a8b6b6b52..d609e46d2f 100644 --- a/Task/Hello-world-Text/PIR/hello-world-text.pir +++ b/Task/Hello-world-Text/PIR/hello-world-text.pir @@ -1,3 +1,3 @@ .sub hello_world_text :main - print "Goodbye, World!\n" + print "Hello world!\n" .end diff --git a/Task/Hello-world-Text/PL-I/hello-world-text.pli b/Task/Hello-world-Text/PL-I/hello-world-text.pli index 2e8a4f8e4e..61035203e7 100644 --- a/Task/Hello-world-Text/PL-I/hello-world-text.pli +++ b/Task/Hello-world-Text/PL-I/hello-world-text.pli @@ -1,3 +1,3 @@ goodbye:proc options(main); - put list('Goodbye, World!'); + put list('Hello world!'); end goodbye; diff --git a/Task/Hello-world-Text/Pascal/hello-world-text.pascal b/Task/Hello-world-Text/Pascal/hello-world-text.pascal index df516149df..5309f44f08 100644 --- a/Task/Hello-world-Text/Pascal/hello-world-text.pascal +++ b/Task/Hello-world-Text/Pascal/hello-world-text.pascal @@ -1,4 +1,4 @@ program byeworld; begin - writeln('Goodbye, World!'); + writeln('Hello world!'); end. diff --git a/Task/Hello-world-Text/Perl-6/hello-world-text.pl6 b/Task/Hello-world-Text/Perl-6/hello-world-text.pl6 index e25905b5d5..343cf162d1 100644 --- a/Task/Hello-world-Text/Perl-6/hello-world-text.pl6 +++ b/Task/Hello-world-Text/Perl-6/hello-world-text.pl6 @@ -1 +1 @@ -say 'Goodbye, World!'; +say 'Hello world!'; diff --git a/Task/Hello-world-Text/Perl/hello-world-text-1.pl b/Task/Hello-world-Text/Perl/hello-world-text-1.pl index 6663ed5a14..3a38582b3f 100644 --- a/Task/Hello-world-Text/Perl/hello-world-text-1.pl +++ b/Task/Hello-world-Text/Perl/hello-world-text-1.pl @@ -1 +1 @@ -print "Goodbye, World!\n"; +print "Hello world!\n"; diff --git a/Task/Hello-world-Text/Perl/hello-world-text-2.pl b/Task/Hello-world-Text/Perl/hello-world-text-2.pl index fc8aced088..f8b7ce87fc 100644 --- a/Task/Hello-world-Text/Perl/hello-world-text-2.pl +++ b/Task/Hello-world-Text/Perl/hello-world-text-2.pl @@ -1,2 +1,2 @@ use feature 'say'; -say 'Goodbye, World!'; +say 'Hello world!'; diff --git a/Task/Hello-world-Text/Perl/hello-world-text-3.pl b/Task/Hello-world-Text/Perl/hello-world-text-3.pl index c3abccc964..b20723a7cd 100644 --- a/Task/Hello-world-Text/Perl/hello-world-text-3.pl +++ b/Task/Hello-world-Text/Perl/hello-world-text-3.pl @@ -1,2 +1,2 @@ use 5.010; -say 'Goodbye, World!'; +say 'Hello world!'; diff --git a/Task/Hello-world-Text/PicoLisp/hello-world-text.l b/Task/Hello-world-Text/PicoLisp/hello-world-text.l index 76b3193378..222c73d329 100644 --- a/Task/Hello-world-Text/PicoLisp/hello-world-text.l +++ b/Task/Hello-world-Text/PicoLisp/hello-world-text.l @@ -1 +1 @@ -(prinl "Goodbye, World!") +(prinl "Hello world!") diff --git a/Task/Hello-world-Text/Pike/hello-world-text.pike b/Task/Hello-world-Text/Pike/hello-world-text.pike index eac04091be..6238d3f08b 100644 --- a/Task/Hello-world-Text/Pike/hello-world-text.pike +++ b/Task/Hello-world-Text/Pike/hello-world-text.pike @@ -1,3 +1,3 @@ int main(){ - write("Goodbye, World!\n"); + write("Hello world!\n"); } diff --git a/Task/Hello-world-Text/Pop11/hello-world-text.pop11 b/Task/Hello-world-Text/Pop11/hello-world-text.pop11 index 3055dffd7d..8ded4b45b7 100644 --- a/Task/Hello-world-Text/Pop11/hello-world-text.pop11 +++ b/Task/Hello-world-Text/Pop11/hello-world-text.pop11 @@ -1 +1 @@ -printf('Goodbye, World!\n'); +printf('Hello world!\n'); diff --git a/Task/Hello-world-Text/PostScript/hello-world-text-1.ps b/Task/Hello-world-Text/PostScript/hello-world-text-1.ps index 261dcc9ebd..d2d42ca3d5 100644 Binary files a/Task/Hello-world-Text/PostScript/hello-world-text-1.ps and b/Task/Hello-world-Text/PostScript/hello-world-text-1.ps differ diff --git a/Task/Hello-world-Text/PostScript/hello-world-text-2.ps b/Task/Hello-world-Text/PostScript/hello-world-text-2.ps index bf672e57cc..9d858c3664 100644 Binary files a/Task/Hello-world-Text/PostScript/hello-world-text-2.ps and b/Task/Hello-world-Text/PostScript/hello-world-text-2.ps differ diff --git a/Task/Hello-world-Text/PostScript/hello-world-text-3.ps b/Task/Hello-world-Text/PostScript/hello-world-text-3.ps index ba63c54b66..984ff1d327 100644 Binary files a/Task/Hello-world-Text/PostScript/hello-world-text-3.ps and b/Task/Hello-world-Text/PostScript/hello-world-text-3.ps differ diff --git a/Task/Hello-world-Text/PowerShell/hello-world-text.psh b/Task/Hello-world-Text/PowerShell/hello-world-text.psh index 6d5a22616d..725fd2cb97 100644 --- a/Task/Hello-world-Text/PowerShell/hello-world-text.psh +++ b/Task/Hello-world-Text/PowerShell/hello-world-text.psh @@ -1,7 +1,7 @@ -'Goodbye, World!' +'Hello world!' #It's considered good practice to use Write-Host, although it works just fine without too -Write-Host 'Goodbye, World!' +Write-Host 'Hello world!' # For extra flair, you can specify colored output -Write-Host 'Goodbye, World!' -foregroundcolor red +Write-Host 'Hello world!' -foregroundcolor red diff --git a/Task/Hello-world-Text/ProDOS/hello-world-text.dos b/Task/Hello-world-Text/ProDOS/hello-world-text.dos index e36a57ed7b..7fcfec2dd6 100644 --- a/Task/Hello-world-Text/ProDOS/hello-world-text.dos +++ b/Task/Hello-world-Text/ProDOS/hello-world-text.dos @@ -1 +1 @@ -printline Goodbye, World! +printline Hello world! diff --git a/Task/Hello-world-Text/Prolog/hello-world-text.pro b/Task/Hello-world-Text/Prolog/hello-world-text.pro index 6135c08f95..2e4c919cde 100644 --- a/Task/Hello-world-Text/Prolog/hello-world-text.pro +++ b/Task/Hello-world-Text/Prolog/hello-world-text.pro @@ -1 +1 @@ -:- write('Goodbye, World!'), nl. +:- write('Hello world!'), nl. diff --git a/Task/Hello-world-Text/Pure/hello-world-text.pure b/Task/Hello-world-Text/Pure/hello-world-text.pure index 9710889721..afbbb2d469 100644 --- a/Task/Hello-world-Text/Pure/hello-world-text.pure +++ b/Task/Hello-world-Text/Pure/hello-world-text.pure @@ -1,3 +1,3 @@ using system; -puts "Goodbye, World!\n" ; +puts "Hello world!\n" ; diff --git a/Task/Hello-world-Text/PureBasic/hello-world-text.purebasic b/Task/Hello-world-Text/PureBasic/hello-world-text.purebasic index 47c375fd00..04263d7ecc 100644 --- a/Task/Hello-world-Text/PureBasic/hello-world-text.purebasic +++ b/Task/Hello-world-Text/PureBasic/hello-world-text.purebasic @@ -1,3 +1,3 @@ OpenConsole() -PrintN("Goodbye, World!") +PrintN("Hello world!") Input() ; Wait for enter diff --git a/Task/Hello-world-Text/Python/hello-world-text-1.py b/Task/Hello-world-Text/Python/hello-world-text-1.py index a9f594ad30..ed708ec5fb 100644 --- a/Task/Hello-world-Text/Python/hello-world-text-1.py +++ b/Task/Hello-world-Text/Python/hello-world-text-1.py @@ -1 +1 @@ -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/Python/hello-world-text-2.py b/Task/Hello-world-Text/Python/hello-world-text-2.py index 9b94478bef..ddbc7d8f6e 100644 --- a/Task/Hello-world-Text/Python/hello-world-text-2.py +++ b/Task/Hello-world-Text/Python/hello-world-text-2.py @@ -1,2 +1,2 @@ import sys -sys.stdout.write("Goodbye, World!\n") +sys.stdout.write("Hello world!\n") diff --git a/Task/Hello-world-Text/Python/hello-world-text-3.py b/Task/Hello-world-Text/Python/hello-world-text-3.py index b4f3181031..f1a18139c8 100644 --- a/Task/Hello-world-Text/Python/hello-world-text-3.py +++ b/Task/Hello-world-Text/Python/hello-world-text-3.py @@ -1 +1 @@ -print("Goodbye, World!") +print("Hello world!") diff --git a/Task/Hello-world-Text/Quill/hello-world-text.quill b/Task/Hello-world-Text/Quill/hello-world-text.quill index 26e70906de..873822625e 100644 --- a/Task/Hello-world-Text/Quill/hello-world-text.quill +++ b/Task/Hello-world-Text/Quill/hello-world-text.quill @@ -1 +1 @@ -"Goodbye, World!" print +"Hello world!" print diff --git a/Task/Hello-world-Text/R/hello-world-text.r b/Task/Hello-world-Text/R/hello-world-text.r index 3ac1a07fbe..59c003643f 100644 --- a/Task/Hello-world-Text/R/hello-world-text.r +++ b/Task/Hello-world-Text/R/hello-world-text.r @@ -1 +1 @@ - cat("Goodbye, World!\n") + cat("Hello world!\n") diff --git a/Task/Hello-world-Text/REALbasic/hello-world-text.realbasic b/Task/Hello-world-Text/REALbasic/hello-world-text.realbasic index a137a08bbd..d914c76c38 100644 --- a/Task/Hello-world-Text/REALbasic/hello-world-text.realbasic +++ b/Task/Hello-world-Text/REALbasic/hello-world-text.realbasic @@ -1,4 +1,4 @@ Function Run(args() as String) As Integer - Print "Goodbye, World!" + Print "Hello world!" Quit End Function diff --git a/Task/Hello-world-Text/REBOL/hello-world-text.rebol b/Task/Hello-world-Text/REBOL/hello-world-text.rebol index a9f594ad30..ed708ec5fb 100644 --- a/Task/Hello-world-Text/REBOL/hello-world-text.rebol +++ b/Task/Hello-world-Text/REBOL/hello-world-text.rebol @@ -1 +1 @@ -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/REXX/hello-world-text-1.rexx b/Task/Hello-world-Text/REXX/hello-world-text-1.rexx index 783400cbd1..cc59a33973 100644 --- a/Task/Hello-world-Text/REXX/hello-world-text-1.rexx +++ b/Task/Hello-world-Text/REXX/hello-world-text-1.rexx @@ -1,2 +1,2 @@ /*REXX program to show a line of text. */ -say 'Goodbye, World!' +say 'Hello world!' diff --git a/Task/Hello-world-Text/REXX/hello-world-text-2.rexx b/Task/Hello-world-Text/REXX/hello-world-text-2.rexx index 6fc68cc3e9..f0168e9777 100644 --- a/Task/Hello-world-Text/REXX/hello-world-text-2.rexx +++ b/Task/Hello-world-Text/REXX/hello-world-text-2.rexx @@ -1,3 +1,3 @@ /*REXX program to show a line of text. */ -yyy = 'Goodbye, World!' +yyy = 'Hello world!' say yyy diff --git a/Task/Hello-world-Text/REXX/hello-world-text-3.rexx b/Task/Hello-world-Text/REXX/hello-world-text-3.rexx index 94acfd0405..3403bb311a 100644 --- a/Task/Hello-world-Text/REXX/hello-world-text-3.rexx +++ b/Task/Hello-world-Text/REXX/hello-world-text-3.rexx @@ -1,3 +1,3 @@ /*REXX program to show a line of text. */ -call lineout ,"Goodbye, World!" +call lineout ,"Hello world!" diff --git a/Task/Hello-world-Text/RTL-2/hello-world-text.rtl b/Task/Hello-world-Text/RTL-2/hello-world-text.rtl index 32722d9204..9a56e359d5 100644 --- a/Task/Hello-world-Text/RTL-2/hello-world-text.rtl +++ b/Task/Hello-world-Text/RTL-2/hello-world-text.rtl @@ -6,7 +6,7 @@ EXT PROC(REF ARRAY BYTE) TWRT; ENT PROC INT RRJOB(); - TWRT("Goodbye, World!#NL#"); + TWRT("Hello world!#NL#"); RETURN(1); ENDPROC; diff --git a/Task/Hello-world-Text/Racket/hello-world-text.rkt b/Task/Hello-world-Text/Racket/hello-world-text.rkt index e3f9786f3c..9e95024797 100644 --- a/Task/Hello-world-Text/Racket/hello-world-text.rkt +++ b/Task/Hello-world-Text/Racket/hello-world-text.rkt @@ -1 +1 @@ -(printf "Goodbye, World!\n") +(printf "Hello world!\n") diff --git a/Task/Hello-world-Text/Raven/hello-world-text.raven b/Task/Hello-world-Text/Raven/hello-world-text.raven index 53d1c80379..d2788f669d 100644 --- a/Task/Hello-world-Text/Raven/hello-world-text.raven +++ b/Task/Hello-world-Text/Raven/hello-world-text.raven @@ -1 +1 @@ -'Goodbye, World!' print +'Hello world!' print diff --git a/Task/Hello-world-Text/Retro/hello-world-text.retro b/Task/Hello-world-Text/Retro/hello-world-text.retro index a84145f357..4851ed0931 100644 --- a/Task/Hello-world-Text/Retro/hello-world-text.retro +++ b/Task/Hello-world-Text/Retro/hello-world-text.retro @@ -1 +1 @@ -"Goodbye, World!" puts +"Hello world!" puts diff --git a/Task/Hello-world-Text/Ruby/hello-world-text-1.rb b/Task/Hello-world-Text/Ruby/hello-world-text-1.rb index 7aed8b2172..08b85bf458 100644 --- a/Task/Hello-world-Text/Ruby/hello-world-text-1.rb +++ b/Task/Hello-world-Text/Ruby/hello-world-text-1.rb @@ -1 +1 @@ -puts "Goodbye, World!" +puts "Hello world!" diff --git a/Task/Hello-world-Text/Ruby/hello-world-text-2.rb b/Task/Hello-world-Text/Ruby/hello-world-text-2.rb index 2af954a040..0d2863d713 100644 --- a/Task/Hello-world-Text/Ruby/hello-world-text-2.rb +++ b/Task/Hello-world-Text/Ruby/hello-world-text-2.rb @@ -1 +1 @@ -$stdout.puts "Goodbye, World!" +$stdout.puts "Hello world!" diff --git a/Task/Hello-world-Text/Ruby/hello-world-text-3.rb b/Task/Hello-world-Text/Ruby/hello-world-text-3.rb index 26f1aea355..7ec366585f 100644 --- a/Task/Hello-world-Text/Ruby/hello-world-text-3.rb +++ b/Task/Hello-world-Text/Ruby/hello-world-text-3.rb @@ -1 +1 @@ - STDOUT.write "Goodbye, World!\n" + STDOUT.write "Hello world!\n" diff --git a/Task/Hello-world-Text/Run-BASIC/hello-world-text.run b/Task/Hello-world-Text/Run-BASIC/hello-world-text.run index a9f594ad30..ed708ec5fb 100644 --- a/Task/Hello-world-Text/Run-BASIC/hello-world-text.run +++ b/Task/Hello-world-Text/Run-BASIC/hello-world-text.run @@ -1 +1 @@ -print "Goodbye, World!" +print "Hello world!" diff --git a/Task/Hello-world-Text/Rust/hello-world-text.rust b/Task/Hello-world-Text/Rust/hello-world-text.rust index 5de77e6a8c..35fce80971 100644 --- a/Task/Hello-world-Text/Rust/hello-world-text.rust +++ b/Task/Hello-world-Text/Rust/hello-world-text.rust @@ -1,3 +1,3 @@ fn main () { - println!("Goodbye, World!"); + println!("Hello world!"); } diff --git a/Task/Hello-world-Text/SAS/hello-world-text.sas b/Task/Hello-world-Text/SAS/hello-world-text.sas index 6dba036026..be7cc6b2c3 100644 --- a/Task/Hello-world-Text/SAS/hello-world-text.sas +++ b/Task/Hello-world-Text/SAS/hello-world-text.sas @@ -1,4 +1,4 @@ /* Using a data step. Will print the string in the log window */ data _null_; -put "Goodbye, World!"; +put "Hello world!"; run; diff --git a/Task/Hello-world-Text/SIMPOL/hello-world-text.simpol b/Task/Hello-world-Text/SIMPOL/hello-world-text.simpol index af06051379..0b9b377227 100644 --- a/Task/Hello-world-Text/SIMPOL/hello-world-text.simpol +++ b/Task/Hello-world-Text/SIMPOL/hello-world-text.simpol @@ -1,2 +1,2 @@ function main() -end function "Goodbye, World!{d}{a}" +end function "Hello world!{d}{a}" diff --git a/Task/Hello-world-Text/SNOBOL4/hello-world-text.sno b/Task/Hello-world-Text/SNOBOL4/hello-world-text.sno index 84d6d3e30e..e71ff3c047 100644 --- a/Task/Hello-world-Text/SNOBOL4/hello-world-text.sno +++ b/Task/Hello-world-Text/SNOBOL4/hello-world-text.sno @@ -1,2 +1,2 @@ - OUTPUT = "Goodbye, World!" + OUTPUT = "Hello world!" END diff --git a/Task/Hello-world-Text/SPARC-Assembly/hello-world-text.sparc b/Task/Hello-world-Text/SPARC-Assembly/hello-world-text.sparc index 6661f252a4..a3a0a837e2 100644 --- a/Task/Hello-world-Text/SPARC-Assembly/hello-world-text.sparc +++ b/Task/Hello-world-Text/SPARC-Assembly/hello-world-text.sparc @@ -12,5 +12,5 @@ _start: ta 8 .msg: - .ascii "Goodbye, world!\n" + .ascii "Hello world!\n" .msgend: diff --git a/Task/Hello-world-Text/Salmon/hello-world-text-1.salmon b/Task/Hello-world-Text/Salmon/hello-world-text-1.salmon index 531b52099f..6416ef55b5 100644 --- a/Task/Hello-world-Text/Salmon/hello-world-text-1.salmon +++ b/Task/Hello-world-Text/Salmon/hello-world-text-1.salmon @@ -1 +1 @@ -"Goodbye, World!"! +"Hello world!"! diff --git a/Task/Hello-world-Text/Salmon/hello-world-text-2.salmon b/Task/Hello-world-Text/Salmon/hello-world-text-2.salmon index 56a083bb6c..94ed812314 100644 --- a/Task/Hello-world-Text/Salmon/hello-world-text-2.salmon +++ b/Task/Hello-world-Text/Salmon/hello-world-text-2.salmon @@ -1 +1 @@ -print("Goodbye, World!\n"); +print("Hello world!\n"); diff --git a/Task/Hello-world-Text/Salmon/hello-world-text-3.salmon b/Task/Hello-world-Text/Salmon/hello-world-text-3.salmon index c4c94b94f0..776bd3f143 100644 --- a/Task/Hello-world-Text/Salmon/hello-world-text-3.salmon +++ b/Task/Hello-world-Text/Salmon/hello-world-text-3.salmon @@ -1 +1 @@ -standard_output.print("Goodbye, World!\n"); +standard_output.print("Hello world!\n"); diff --git a/Task/Hello-world-Text/Sather/hello-world-text.sa b/Task/Hello-world-Text/Sather/hello-world-text.sa index 01ca7e1136..3b983758e3 100644 --- a/Task/Hello-world-Text/Sather/hello-world-text.sa +++ b/Task/Hello-world-Text/Sather/hello-world-text.sa @@ -1,5 +1,5 @@ class GOODBYE_WORLD is main is - #OUT+"Goodbye, World!\n"; + #OUT+"Hello world!\n"; end; end; diff --git a/Task/Hello-world-Text/Scala/hello-world-text-1.scala b/Task/Hello-world-Text/Scala/hello-world-text-1.scala index d0337b0351..50095f70c5 100644 --- a/Task/Hello-world-Text/Scala/hello-world-text-1.scala +++ b/Task/Hello-world-Text/Scala/hello-world-text-1.scala @@ -1 +1 @@ -println("Goodbye, World!") +println("Hello world!") diff --git a/Task/Hello-world-Text/Scala/hello-world-text-2.scala b/Task/Hello-world-Text/Scala/hello-world-text-2.scala index 5ad810d88f..f8baec7afd 100644 --- a/Task/Hello-world-Text/Scala/hello-world-text-2.scala +++ b/Task/Hello-world-Text/Scala/hello-world-text-2.scala @@ -1 +1 @@ -System.out.println("Goodbye, World!") +System.out.println("Hello world!") diff --git a/Task/Hello-world-Text/Scala/hello-world-text-3.scala b/Task/Hello-world-Text/Scala/hello-world-text-3.scala index d0337b0351..50095f70c5 100644 --- a/Task/Hello-world-Text/Scala/hello-world-text-3.scala +++ b/Task/Hello-world-Text/Scala/hello-world-text-3.scala @@ -1 +1 @@ -println("Goodbye, World!") +println("Hello world!") diff --git a/Task/Hello-world-Text/Scheme/hello-world-text-1.ss b/Task/Hello-world-Text/Scheme/hello-world-text-1.ss index 69701a0394..82d3d9d534 100644 --- a/Task/Hello-world-Text/Scheme/hello-world-text-1.ss +++ b/Task/Hello-world-Text/Scheme/hello-world-text-1.ss @@ -1,2 +1,2 @@ -(display "Goodbye, World!") +(display "Hello world!") (newline) diff --git a/Task/Hello-world-Text/Scheme/hello-world-text-2.ss b/Task/Hello-world-Text/Scheme/hello-world-text-2.ss index 6e7296b324..d441299f14 100644 --- a/Task/Hello-world-Text/Scheme/hello-world-text-2.ss +++ b/Task/Hello-world-Text/Scheme/hello-world-text-2.ss @@ -1 +1 @@ -(print "Goodbye, World!") +(print "Hello world!") diff --git a/Task/Hello-world-Text/Scheme/hello-world-text-3.ss b/Task/Hello-world-Text/Scheme/hello-world-text-3.ss index 1e9d709f27..6ccebb9abe 100644 --- a/Task/Hello-world-Text/Scheme/hello-world-text-3.ss +++ b/Task/Hello-world-Text/Scheme/hello-world-text-3.ss @@ -1 +1 @@ -"Goodbye, World!" +"Hello world!" diff --git a/Task/Hello-world-Text/Scheme/hello-world-text-4.ss b/Task/Hello-world-Text/Scheme/hello-world-text-4.ss index 1ef3d1da78..5ba8eec3e0 100644 --- a/Task/Hello-world-Text/Scheme/hello-world-text-4.ss +++ b/Task/Hello-world-Text/Scheme/hello-world-text-4.ss @@ -1,4 +1,4 @@ (import (scheme base) (scheme write)) -(display "Hello, world!") +(display "Hello world!") (newline) diff --git a/Task/Hello-world-Text/Scilab/hello-world-text.scilab b/Task/Hello-world-Text/Scilab/hello-world-text.scilab index 2a78fe60de..ed2464682d 100644 --- a/Task/Hello-world-Text/Scilab/hello-world-text.scilab +++ b/Task/Hello-world-Text/Scilab/hello-world-text.scilab @@ -1 +1 @@ -disp("Goodbye, World!"); +disp("Hello world!"); diff --git a/Task/Hello-world-Text/Seed7/hello-world-text.seed7 b/Task/Hello-world-Text/Seed7/hello-world-text.seed7 index 52889f6144..147c49475f 100644 --- a/Task/Hello-world-Text/Seed7/hello-world-text.seed7 +++ b/Task/Hello-world-Text/Seed7/hello-world-text.seed7 @@ -2,5 +2,5 @@ $ include "seed7_05.s7i"; const proc: main is func begin - writeln("Goodbye, World!"); + writeln("Hello world!"); end func; diff --git a/Task/Hello-world-Text/Self/hello-world-text.self b/Task/Hello-world-Text/Self/hello-world-text.self index 0a48b8d1b8..9215f91ccf 100644 --- a/Task/Hello-world-Text/Self/hello-world-text.self +++ b/Task/Hello-world-Text/Self/hello-world-text.self @@ -1 +1 @@ -'Goodbye, World!' printLine. +'Hello world!' printLine. diff --git a/Task/Hello-world-Text/Shiny/hello-world-text.shiny b/Task/Hello-world-Text/Shiny/hello-world-text.shiny index a1ec6ead2c..351d6c09b3 100644 --- a/Task/Hello-world-Text/Shiny/hello-world-text.shiny +++ b/Task/Hello-world-Text/Shiny/hello-world-text.shiny @@ -1 +1 @@ -say 'Goodbye, World!' +say 'Hello world!' diff --git a/Task/Hello-world-Text/Simula/hello-world-text.simula b/Task/Hello-world-Text/Simula/hello-world-text.simula index c3e21c1749..ff7eb45ecc 100644 --- a/Task/Hello-world-Text/Simula/hello-world-text.simula +++ b/Task/Hello-world-Text/Simula/hello-world-text.simula @@ -1,4 +1,4 @@ BEGIN - OUTTEXT("Goodbye, World!"); + OUTTEXT("Hello world!"); OUTIMAGE END diff --git a/Task/Hello-world-Text/Sisal/hello-world-text.sisal b/Task/Hello-world-Text/Sisal/hello-world-text.sisal index dc18b45f0b..49acf63279 100644 --- a/Task/Hello-world-Text/Sisal/hello-world-text.sisal +++ b/Task/Hello-world-Text/Sisal/hello-world-text.sisal @@ -6,5 +6,5 @@ define main type string = array[character]; function main(returns string) - "Goodbye, World!" + "Hello world!" end function diff --git a/Task/Hello-world-Text/Slate/hello-world-text.slate b/Task/Hello-world-Text/Slate/hello-world-text.slate index 5a082b9390..eb4a1460c7 100644 --- a/Task/Hello-world-Text/Slate/hello-world-text.slate +++ b/Task/Hello-world-Text/Slate/hello-world-text.slate @@ -1 +1 @@ -inform: 'Goodbye, World!'. +inform: 'Hello world!'. diff --git a/Task/Hello-world-Text/Smalltalk/hello-world-text-1.st b/Task/Hello-world-Text/Smalltalk/hello-world-text-1.st index 31ab449d30..7c2455ee3a 100644 --- a/Task/Hello-world-Text/Smalltalk/hello-world-text-1.st +++ b/Task/Hello-world-Text/Smalltalk/hello-world-text-1.st @@ -1 +1 @@ -Transcript show: 'Goodbye, World!'; cr. +Transcript show: 'Hello world!'; cr. diff --git a/Task/Hello-world-Text/Smalltalk/hello-world-text-2.st b/Task/Hello-world-Text/Smalltalk/hello-world-text-2.st index ec793eba5a..af5a8c8003 100644 --- a/Task/Hello-world-Text/Smalltalk/hello-world-text-2.st +++ b/Task/Hello-world-Text/Smalltalk/hello-world-text-2.st @@ -1 +1 @@ -'Goodbye, World!' printNl. +'Hello world!' printNl. diff --git a/Task/Hello-world-Text/Standard-ML/hello-world-text.ml b/Task/Hello-world-Text/Standard-ML/hello-world-text.ml index 4692311bb8..053662f327 100644 --- a/Task/Hello-world-Text/Standard-ML/hello-world-text.ml +++ b/Task/Hello-world-Text/Standard-ML/hello-world-text.ml @@ -1 +1 @@ -print "Goodbye, World!\n" +print "Hello world!\n" diff --git a/Task/Hello-world-Text/Suneido/hello-world-text.suneido b/Task/Hello-world-Text/Suneido/hello-world-text.suneido index 2e5c8cf372..aabb97ebe0 100644 --- a/Task/Hello-world-Text/Suneido/hello-world-text.suneido +++ b/Task/Hello-world-Text/Suneido/hello-world-text.suneido @@ -1 +1 @@ -Print("Goodbye, World!") +Print("Hello world!") diff --git a/Task/Hello-world-Text/TI-83-BASIC/hello-world-text.ti-83 b/Task/Hello-world-Text/TI-83-BASIC/hello-world-text.ti-83 new file mode 100644 index 0000000000..4eb54b3126 --- /dev/null +++ b/Task/Hello-world-Text/TI-83-BASIC/hello-world-text.ti-83 @@ -0,0 +1 @@ +Disp "Hello world! diff --git a/Task/Hello-world-Text/TI-89-BASIC/hello-world-text.ti-89 b/Task/Hello-world-Text/TI-89-BASIC/hello-world-text.ti-89 index bf62a219b6..d16be1d3ab 100644 --- a/Task/Hello-world-Text/TI-89-BASIC/hello-world-text.ti-89 +++ b/Task/Hello-world-Text/TI-89-BASIC/hello-world-text.ti-89 @@ -1 +1 @@ -Disp "Goodbye, World!" +Disp "Hello world!" diff --git a/Task/Hello-world-Text/TPP/hello-world-text.tpp b/Task/Hello-world-Text/TPP/hello-world-text.tpp index f06c489626..cd0875583a 100644 --- a/Task/Hello-world-Text/TPP/hello-world-text.tpp +++ b/Task/Hello-world-Text/TPP/hello-world-text.tpp @@ -1 +1 @@ -Goodbye, World! +Hello world! diff --git a/Task/Hello-world-Text/TUSCRIPT/hello-world-text.tu b/Task/Hello-world-Text/TUSCRIPT/hello-world-text.tu index bc4649c93f..20bcea68e5 100644 --- a/Task/Hello-world-Text/TUSCRIPT/hello-world-text.tu +++ b/Task/Hello-world-Text/TUSCRIPT/hello-world-text.tu @@ -1,2 +1,2 @@ $$ MODE TUSCRIPT -PRINT "Goodbye, World!" +PRINT "Hello world!" diff --git a/Task/Hello-world-Text/Tcl/hello-world-text-1.tcl b/Task/Hello-world-Text/Tcl/hello-world-text-1.tcl index 7aed8b2172..08b85bf458 100644 --- a/Task/Hello-world-Text/Tcl/hello-world-text-1.tcl +++ b/Task/Hello-world-Text/Tcl/hello-world-text-1.tcl @@ -1 +1 @@ -puts "Goodbye, World!" +puts "Hello world!" diff --git a/Task/Hello-world-Text/Tcl/hello-world-text-2.tcl b/Task/Hello-world-Text/Tcl/hello-world-text-2.tcl index 4231289e8f..0b9124b8f2 100644 --- a/Task/Hello-world-Text/Tcl/hello-world-text-2.tcl +++ b/Task/Hello-world-Text/Tcl/hello-world-text-2.tcl @@ -1 +1 @@ -puts $fileID "Goodbye, World!" +puts $fileID "Hello world!" diff --git a/Task/Hello-world-Text/Teco/hello-world-text.teco b/Task/Hello-world-Text/Teco/hello-world-text.teco index abd9f08f59..be8ad7685c 100644 --- a/Task/Hello-world-Text/Teco/hello-world-text.teco +++ b/Task/Hello-world-Text/Teco/hello-world-text.teco @@ -1 +1 @@ -^AGoodbye, World!^A$$ +^AHello world!^A$$ diff --git a/Task/Hello-world-Text/TorqueScript/hello-world-text.torque b/Task/Hello-world-Text/TorqueScript/hello-world-text.torque index a5580ff455..a560d61ce1 100644 --- a/Task/Hello-world-Text/TorqueScript/hello-world-text.torque +++ b/Task/Hello-world-Text/TorqueScript/hello-world-text.torque @@ -1 +1 @@ -echo("Goodbye, World!"); +echo("Hello world!"); diff --git a/Task/Hello-world-Text/Transact-SQL/hello-world-text.sql b/Task/Hello-world-Text/Transact-SQL/hello-world-text.sql index 2dffd5dbb8..386f4e4cc6 100644 --- a/Task/Hello-world-Text/Transact-SQL/hello-world-text.sql +++ b/Task/Hello-world-Text/Transact-SQL/hello-world-text.sql @@ -1 +1 @@ -PRINT "Goodbye, World!" +PRINT "Hello world!" diff --git a/Task/Hello-world-Text/Trith/hello-world-text.trith b/Task/Hello-world-Text/Trith/hello-world-text.trith index 26e70906de..873822625e 100644 --- a/Task/Hello-world-Text/Trith/hello-world-text.trith +++ b/Task/Hello-world-Text/Trith/hello-world-text.trith @@ -1 +1 @@ -"Goodbye, World!" print +"Hello world!" print diff --git a/Task/Hello-world-Text/UNIX-Shell/hello-world-text-1.sh b/Task/Hello-world-Text/UNIX-Shell/hello-world-text-1.sh index 8bccec2bc4..2b45f6a588 100644 --- a/Task/Hello-world-Text/UNIX-Shell/hello-world-text-1.sh +++ b/Task/Hello-world-Text/UNIX-Shell/hello-world-text-1.sh @@ -1,2 +1,2 @@ #!/bin/sh -echo "Goodbye, World!" +echo "Hello world!" diff --git a/Task/Hello-world-Text/UNIX-Shell/hello-world-text-2.sh b/Task/Hello-world-Text/UNIX-Shell/hello-world-text-2.sh index 5f8410f187..1caf34a988 100644 --- a/Task/Hello-world-Text/UNIX-Shell/hello-world-text-2.sh +++ b/Task/Hello-world-Text/UNIX-Shell/hello-world-text-2.sh @@ -1,2 +1,2 @@ #!/bin/csh -f -echo "Goodbye, World\!" +echo "Hello world!\!" diff --git a/Task/Hello-world-Text/Ursala/hello-world-text-1.ursala b/Task/Hello-world-Text/Ursala/hello-world-text-1.ursala index ec67c2ed92..f51de3a683 100644 --- a/Task/Hello-world-Text/Ursala/hello-world-text-1.ursala +++ b/Task/Hello-world-Text/Ursala/hello-world-text-1.ursala @@ -1,3 +1,3 @@ #show+ -main = -[Goodbye, World!]- +main = -[Hello world!]- diff --git a/Task/Hello-world-Text/Ursala/hello-world-text-2.ursala b/Task/Hello-world-Text/Ursala/hello-world-text-2.ursala index 72a4b8a4d2..bdd6d375aa 100644 --- a/Task/Hello-world-Text/Ursala/hello-world-text-2.ursala +++ b/Task/Hello-world-Text/Ursala/hello-world-text-2.ursala @@ -2,4 +2,4 @@ #executable ('parameterized','') -main = ! +main = ! diff --git a/Task/Hello-world-Text/V/hello-world-text.v b/Task/Hello-world-Text/V/hello-world-text.v index a84145f357..4851ed0931 100644 --- a/Task/Hello-world-Text/V/hello-world-text.v +++ b/Task/Hello-world-Text/V/hello-world-text.v @@ -1 +1 @@ -"Goodbye, World!" puts +"Hello world!" puts diff --git a/Task/Hello-world-Text/VBScript/hello-world-text.vb b/Task/Hello-world-Text/VBScript/hello-world-text.vb index 28921ac42e..9410f92818 100644 --- a/Task/Hello-world-Text/VBScript/hello-world-text.vb +++ b/Task/Hello-world-Text/VBScript/hello-world-text.vb @@ -1 +1 @@ -WScript.Echo("Goodbye, World!") +WScript.Echo("Hello world!") diff --git a/Task/Hello-world-Text/VHDL/hello-world-text.vhdl b/Task/Hello-world-Text/VHDL/hello-world-text.vhdl index e3828dd5f3..2196747d7c 100644 --- a/Task/Hello-world-Text/VHDL/hello-world-text.vhdl +++ b/Task/Hello-world-Text/VHDL/hello-world-text.vhdl @@ -9,7 +9,7 @@ begin process variable line_out : line; begin - write(line_out, string'("Goodbye, World!")); + write(line_out, string'("Hello world!")); writeline(OUTPUT, line_out); wait; -- needed to stop the execution end process; diff --git a/Task/Hello-world-Text/Vala/hello-world-text.vala b/Task/Hello-world-Text/Vala/hello-world-text.vala index f62259ba1c..1cfe842b0e 100644 --- a/Task/Hello-world-Text/Vala/hello-world-text.vala +++ b/Task/Hello-world-Text/Vala/hello-world-text.vala @@ -1,3 +1,3 @@ void main(){ - stdout.printf("Goodbye, World!\n"); + stdout.printf("Hello world!\n"); } diff --git a/Task/Hello-world-Text/Vedit-macro-language/hello-world-text.vedit b/Task/Hello-world-Text/Vedit-macro-language/hello-world-text.vedit index c4e0164ec0..e471752f85 100644 --- a/Task/Hello-world-Text/Vedit-macro-language/hello-world-text.vedit +++ b/Task/Hello-world-Text/Vedit-macro-language/hello-world-text.vedit @@ -1 +1 @@ -Message("Goodbye, World!") +Message("Hello world!") diff --git a/Task/Hello-world-Text/Vim-Script/hello-world-text.vim b/Task/Hello-world-Text/Vim-Script/hello-world-text.vim index 4e4bcd978f..6c10726505 100644 --- a/Task/Hello-world-Text/Vim-Script/hello-world-text.vim +++ b/Task/Hello-world-Text/Vim-Script/hello-world-text.vim @@ -1 +1 @@ -echo "Goodbye, World!\n" +echo "Hello world!\n" diff --git a/Task/Hello-world-Text/Whenever/hello-world-text.whenever b/Task/Hello-world-Text/Whenever/hello-world-text.whenever index 114f9dd3da..f588e8c64e 100644 --- a/Task/Hello-world-Text/Whenever/hello-world-text.whenever +++ b/Task/Hello-world-Text/Whenever/hello-world-text.whenever @@ -1 +1 @@ -1 print("Goodbye, World!"); +1 print("Hello world!"); diff --git a/Task/Hello-world-Text/X86-Assembly/hello-world-text-1.x86 b/Task/Hello-world-Text/X86-Assembly/hello-world-text-1.x86 new file mode 100644 index 0000000000..2f91a10dea --- /dev/null +++ b/Task/Hello-world-Text/X86-Assembly/hello-world-text-1.x86 @@ -0,0 +1,15 @@ +section .data +msg db 'Hello world!', 0AH +len equ $-msg + +section .text +global _start +_start: mov edx, len + mov ecx, msg + mov ebx, 1 + mov eax, 4 + int 80h + + mov ebx, 0 + mov eax, 1 + int 80h diff --git a/Task/Hello-world-Text/X86-Assembly/hello-world-text-2.x86 b/Task/Hello-world-Text/X86-Assembly/hello-world-text-2.x86 new file mode 100644 index 0000000000..70c66b30c4 --- /dev/null +++ b/Task/Hello-world-Text/X86-Assembly/hello-world-text-2.x86 @@ -0,0 +1,14 @@ +.section .text + +.globl main + +main: + movl $4,%eax #syscall number 4 + movl $1,%ebx #number 1 for stdout + movl $str,%ecx #string pointer + movl $16,%edx #number of bytes + int $0x80 #syscall interrupt + ret + +.section .data +str: .ascii "Hello world!\12" diff --git a/Task/Hello-world-Text/X86-Assembly/hello-world-text.x86 b/Task/Hello-world-Text/X86-Assembly/hello-world-text.x86 deleted file mode 100644 index 9c9a26fe95..0000000000 --- a/Task/Hello-world-Text/X86-Assembly/hello-world-text.x86 +++ /dev/null @@ -1,15 +0,0 @@ -section .data -msg db 'Goodbye, World!', 0AH -len equ $-msg - -section .text -global _start -_start: mov edx, len - mov ecx, msg - mov ebx, 1 - mov eax, 4 - int 80h - - mov ebx, 0 - mov eax, 1 - int 80h diff --git a/Task/Hello-world-Text/XL/hello-world-text.xl b/Task/Hello-world-Text/XL/hello-world-text.xl index c2f04b999a..646ef0c3fc 100644 --- a/Task/Hello-world-Text/XL/hello-world-text.xl +++ b/Task/Hello-world-Text/XL/hello-world-text.xl @@ -1,2 +1,2 @@ use XL.UI.CONSOLE -WriteLn "Goodbye, World!" +WriteLn "Hello world!" diff --git a/Task/Hello-world-Text/XPL0/hello-world-text.xpl0 b/Task/Hello-world-Text/XPL0/hello-world-text.xpl0 index 58e89659e2..e4ae2b5d38 100644 --- a/Task/Hello-world-Text/XPL0/hello-world-text.xpl0 +++ b/Task/Hello-world-Text/XPL0/hello-world-text.xpl0 @@ -1,3 +1,3 @@ code Text=12; -Text(0, "Goodbye, World! +Text(0, "Hello world! ") diff --git a/Task/Hello-world-Text/XSLT/hello-world-text.xslt b/Task/Hello-world-Text/XSLT/hello-world-text.xslt index 015be6a039..b1fd4ee78e 100644 --- a/Task/Hello-world-Text/XSLT/hello-world-text.xslt +++ b/Task/Hello-world-Text/XSLT/hello-world-text.xslt @@ -1,2 +1,2 @@ -Goodbye, World! +Hello world! diff --git a/Task/Hello-world-Text/Yorick/hello-world-text.yorick b/Task/Hello-world-Text/Yorick/hello-world-text.yorick index ad5164a125..98e01cda0d 100644 --- a/Task/Hello-world-Text/Yorick/hello-world-text.yorick +++ b/Task/Hello-world-Text/Yorick/hello-world-text.yorick @@ -1 +1 @@ -write, "Goodbye, World!" +write, "Hello world!" diff --git a/Task/Hello-world-Text/Z80-Assembly/hello-world-text.z80 b/Task/Hello-world-Text/Z80-Assembly/hello-world-text.z80 index 7b0062b66d..6d5df72702 100644 --- a/Task/Hello-world-Text/Z80-Assembly/hello-world-text.z80 +++ b/Task/Hello-world-Text/Z80-Assembly/hello-world-text.z80 @@ -15,4 +15,4 @@ print: ld a,(hl) end: pop hl ret -world: defm "Goodbye, World!\r\n\0" +world: defm "Hello world!\r\n\0" diff --git a/Task/Hello-world-Web-server/AutoIt/hello-world-web-server.autoit b/Task/Hello-world-Web-server/AutoIt/hello-world-web-server.autoit new file mode 100644 index 0000000000..4d76bc8ab9 --- /dev/null +++ b/Task/Hello-world-Web-server/AutoIt/hello-world-web-server.autoit @@ -0,0 +1,17 @@ +TCPStartup() +$socket = TCPListen("0.0.0.0",8080) +$string = "Goodbye, World!" +While 1 + Do + $newConnection = TCPAccept($socket) + Sleep(1) + Until $newConnection <> -1 + $content = TCPRecv($newConnection, 2048) + If StringLen($content) > 0 Then + TCPSend($newConnection, Binary("HTTP/1.1 200 OK" & @CRLF)) + TCPSend($newConnection, Binary("Content-Type: text/html" & @CRLF)) + TCPSend($newConnection, Binary("Content-Length: "& BinaryLen($string) & @CRLF & @CRLF)) + TCPSend($newConnection, $string) + EndIf + TCPCloseSocket($newConnection) +WEnd diff --git a/Task/Here-document/Elixir/here-document-1.elixir b/Task/Here-document/Elixir/here-document-1.elixir new file mode 100644 index 0000000000..12dc8d27c3 --- /dev/null +++ b/Task/Here-document/Elixir/here-document-1.elixir @@ -0,0 +1,4 @@ +IO.puts """ +привет +мир +""" diff --git a/Task/Here-document/Elixir/here-document-2.elixir b/Task/Here-document/Elixir/here-document-2.elixir new file mode 100644 index 0000000000..afb0984c2b --- /dev/null +++ b/Task/Here-document/Elixir/here-document-2.elixir @@ -0,0 +1,2 @@ +привет +мир diff --git a/Task/Here-document/Elixir/here-document-3.elixir b/Task/Here-document/Elixir/here-document-3.elixir new file mode 100644 index 0000000000..e72863f584 --- /dev/null +++ b/Task/Here-document/Elixir/here-document-3.elixir @@ -0,0 +1,11 @@ +iex(1)> a=2 +2 +iex(2)> ''' +...(2)> 1 + 1 = #{a} +...(2)> ''' +'1 + 1 = 2\n' +iex(3)> +iex(3)> '''2''' +** (SyntaxError) iex:3: heredoc start must be followed by a new line after ''' + +iex(3)> diff --git a/Task/Here-document/Haskell/here-document.hs b/Task/Here-document/Haskell/here-document.hs new file mode 100644 index 0000000000..ec93e47f03 --- /dev/null +++ b/Task/Here-document/Haskell/here-document.hs @@ -0,0 +1,16 @@ +main :: IO () +main = do + +-- multiline String + putStrLn "Hello\ + \ World!\n" + +-- more haskell-ish way + putStrLn $ unwords ["This", "is", "an", "example", "text!\n"] + +-- now with multiple lines + putStrLn $ unlines [ + unwords ["This", "is", "the", "first" , "line."] + , unwords ["This", "is", "the", "second", "line."] + , unwords ["This", "is", "the", "third" , "line."] + ] diff --git a/Task/Here-document/Mathematica/here-document.math b/Task/Here-document/Mathematica/here-document.math new file mode 100644 index 0000000000..e0f5c05a51 --- /dev/null +++ b/Task/Here-document/Mathematica/here-document.math @@ -0,0 +1,13 @@ +Print["Mathematica + is an +interesing + language, + with its + strings + being + multiline + by\ + default + when not +back\ +s\\ashed!"]; diff --git a/Task/Here-document/Rust/here-document.rust b/Task/Here-document/Rust/here-document.rust new file mode 100644 index 0000000000..d2716edda3 --- /dev/null +++ b/Task/Here-document/Rust/here-document.rust @@ -0,0 +1,3 @@ +let x = r#" + This is a "raw string literal," roughly equivalent to a heredoc. + "#; diff --git a/Task/Heronian-triangles/C++/heronian-triangles-1.cpp b/Task/Heronian-triangles/C++/heronian-triangles-1.cpp new file mode 100644 index 0000000000..dab331a72d --- /dev/null +++ b/Task/Heronian-triangles/C++/heronian-triangles-1.cpp @@ -0,0 +1,85 @@ +#include +#include +#include +#include +#include + +int gcd(int a, int b) +{ + int rem = 1, dividend, divisor; + std::tie(divisor, dividend) = std::minmax(a, b); + while (rem != 0) { + rem = dividend % divisor; + if (rem != 0) { + dividend = divisor; + divisor = rem; + } + } + return divisor; +} + +struct Triangle +{ + int a; + int b; + int c; +}; + +int perimeter(const Triangle& triangle) +{ + return triangle.a + triangle.b + triangle.c; +} + +double area(const Triangle& t) +{ + double p_2 = perimeter(t) / 2.; + double area_sq = p_2 * ( p_2 - t.a ) * ( p_2 - t.b ) * ( p_2 - t.c ); + return sqrt(area_sq); +} + +std::vector generate_triangles(int side_limit = 200) +{ + std::vector result; + for(int a = 1; a <= side_limit; ++a) + for(int b = 1; b <= a; ++b) + for(int c = 1; c <= b; ++c) { + Triangle t{a, b, c}; + double t_area = area(t); + if(t_area == 0) continue; + if( std::floor(t_area) == std::ceil(t_area) && gcd(a, gcd(b, c)) == 1) + result.push_back(t); + } + return result; +} + +bool compare(const Triangle& lhs, const Triangle& rhs) +{ + return std::make_tuple(area(lhs), perimeter(lhs), std::max(lhs.a, std::max(lhs.b, lhs.c))) < + std::make_tuple(area(rhs), perimeter(rhs), std::max(rhs.a, std::max(rhs.b, rhs.c))); +} + +struct area_compare +{ + bool operator()(const Triangle& t, int i) { return area(t) < i; } + bool operator()(int i, const Triangle& t) { return i < area(t); } +}; + +int main() +{ + auto tri = generate_triangles(); + std::cout << "There are " << tri.size() << " primitive Heronian triangles with sides up to 200\n\n"; + + std::cout << "First ten when ordered by increasing area, then perimeter, then maximum sides:\n"; + std::sort(tri.begin(), tri.end(), compare); + std::cout << "area\tperimeter\tsides\n"; + for(int i = 0; i < 10; ++i) + std::cout << area(tri[i]) << '\t' << perimeter(tri[i]) << "\t\t" << + tri[i].a << 'x' << tri[i].b << 'x' << tri[i].c << '\n'; + + std::cout << "\nAll with area 210 subject to the previous ordering:\n"; + auto range = std::equal_range(tri.begin(), tri.end(), 210, area_compare()); + std::cout << "area\tperimeter\tsides\n"; + for(auto it = range.first; it != range.second; ++it) + std::cout << area(*it) << '\t' << perimeter(*it) << "\t\t" << + it->a << 'x' << it->b << 'x' << it->c << '\n'; +} diff --git a/Task/Heronian-triangles/C++/heronian-triangles-2.cpp b/Task/Heronian-triangles/C++/heronian-triangles-2.cpp new file mode 100644 index 0000000000..e425b0f81b --- /dev/null +++ b/Task/Heronian-triangles/C++/heronian-triangles-2.cpp @@ -0,0 +1,23 @@ +There are 517 primitive Heronian triangles with sides up to 200 + +First ten when ordered by increasing area, then perimeter, then maximum sides: +area perimeter sides +6 12 5x4x3 +12 16 6x5x5 +12 18 8x5x5 +24 32 15x13x4 +30 30 13x12x5 +36 36 17x10x9 +36 54 26x25x3 +42 42 20x15x7 +60 36 13x13x10 +60 40 17x15x8 + +All with area 210 subject to the previous ordering: +area perimeter sides +210 70 28x25x17 +210 70 29x21x20 +210 84 37x35x12 +210 84 39x28x17 +210 140 68x65x7 +210 300 149x148x3 diff --git a/Task/Heronian-triangles/Elixir/heronian-triangles.elixir b/Task/Heronian-triangles/Elixir/heronian-triangles.elixir new file mode 100644 index 0000000000..f0888af8ca --- /dev/null +++ b/Task/Heronian-triangles/Elixir/heronian-triangles.elixir @@ -0,0 +1,36 @@ +defmodule Heronian do + def triangle?(a,b,c) when a+b <= c, do: false + def triangle?(a,b,c) do + area = area(a,b,c) + area == round(area) and primitive?(a,b,c) + end + + def area(a,b,c) do + s = (a + b + c) / 2 + :math.sqrt(s * (s-a) * (s-b) * (s-c)) + end + + defp primitive?(a,b,c), do: gcd(gcd(a,b),c) == 1 + + defp gcd(a,0), do: a + defp gcd(a,b), do: gcd(b, rem(a,b)) +end + +max = 200 +triangles = for a <- 1..max, b <- a..max, c <- b..max, Heronian.triangle?(a,b,c), do: {a,b,c} +IO.puts length(triangles) + +IO.puts "\nSides\t\t\tPerim\tArea" +Enum.map(triangles, fn {a,b,c} -> {Heronian.area(a,b,c),a,b,c} end) +|> Enum.sort +|> Enum.take(10) +|> Enum.each(fn {area, a, b, c} -> + IO.puts "#{a}\t#{b}\t#{c}\t#{a+b+c}\t#{round(area)}" + end) +IO.puts "" +area_size = 210 +Enum.filter(triangles, fn {a,b,c} -> Heronian.area(a,b,c) == area_size end) +|> Enum.sort_by(fn {a,b,c} -> a+b+c end) +|> Enum.each(fn {a, b, c} -> + IO.puts "#{a}\t#{b}\t#{c}\t#{a+b+c}\t#{area_size}" + end) diff --git a/Task/Heronian-triangles/J/heronian-triangles-1.j b/Task/Heronian-triangles/J/heronian-triangles-1.j index 4f428a035d..c43972fbf1 100644 --- a/Task/Heronian-triangles/J/heronian-triangles-1.j +++ b/Task/Heronian-triangles/J/heronian-triangles-1.j @@ -1,9 +1,7 @@ -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 +a=: 0&{"1 +b=: 1&{"1 +c=: 2&{"1 +s=: (a+b+c) % 2: +area=: 2 %: s*(s-a)*(s-b)*(s-c) NB. Hero's formula +perim=: +/"1 +isPrimHero=: (0&~: * (= <.@:+))@area * 1 = a +. b +. c diff --git a/Task/Heronian-triangles/J/heronian-triangles-2.j b/Task/Heronian-triangles/J/heronian-triangles-2.j index 4852956e0a..67b359286f 100644 --- a/Task/Heronian-triangles/J/heronian-triangles-2.j +++ b/Task/Heronian-triangles/J/heronian-triangles-2.j @@ -1,22 +1,5 @@ - #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 +perim=: +/"1 +s=: -:@:perim +area=: [: %: s * [: */"1 s - ] NB. Hero's formula +isNonZeroInt=: 0&~: *. (= <.@:+) +isPrimHero=: isNonZeroInt@area *. 1 = +./&.|: diff --git a/Task/Heronian-triangles/J/heronian-triangles-3.j b/Task/Heronian-triangles/J/heronian-triangles-3.j new file mode 100644 index 0000000000..a743b833e5 --- /dev/null +++ b/Task/Heronian-triangles/J/heronian-triangles-3.j @@ -0,0 +1,27 @@ + Tri=: ~. /:"1~ 1 + 200 200 200 #: i. 200^3 NB. distinct triangles with sides <= 200 + HeroTri=: (#~ isPrimHero) Tri NB. all primitive Heronian triangles with sides <= 200 + + # HeroTri NB. count triangles found +517 + + HeroTri=: (/: area ,. perim ,. ]) HeroTri NB. sort by area, perimeter & sides + + (,. _ ,. perim ,. area) 10 {. HeroTri NB. tabulate sides, perimeter & area for top 10 triangles + 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 + + (,. _ ,. perim ,. area) (#~ 210 = area) HeroTri NB. tablulate sides, perimeter & area for triangles with area = 210 +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/Julia/heronian-triangles-1.julia b/Task/Heronian-triangles/Julia/heronian-triangles-1.julia new file mode 100644 index 0000000000..b0ae7cbb14 --- /dev/null +++ b/Task/Heronian-triangles/Julia/heronian-triangles-1.julia @@ -0,0 +1,26 @@ +type IntegerTriangle{T<:Integer} + a::T + b::T + c::T + p::T + σ::T +end + +function IntegerTriangle{T<:Integer}(a::T, b::T, c::T) + p = a + b + c + s = div(p, 2) + σ = isqrt(s*(s-a)*(s-b)*(s-c)) + (x, y, z) = sort([a, b, c]) + IntegerTriangle(x, y, z, p, σ) +end + +function isprimheronian{T<:Integer}(a::T, b::T, c::T) + p = a + b + c + iseven(p) || return false + gcd(a, b, c) == 1 || return false + s = div(p, 2) + t = s*(s-a)*(s-b)*(s-c) + 0 < t || return false + σ = isqrt(t) + σ^2 == t +end diff --git a/Task/Heronian-triangles/Julia/heronian-triangles-2.julia b/Task/Heronian-triangles/Julia/heronian-triangles-2.julia new file mode 100644 index 0000000000..fe3da671aa --- /dev/null +++ b/Task/Heronian-triangles/Julia/heronian-triangles-2.julia @@ -0,0 +1,33 @@ +slim = 200 + +ht = IntegerTriangle[] + +for a in 1:slim, b in a:slim, c in b:slim + isprimheronian(a, b, c) || continue + push!(ht, IntegerTriangle(a, b, c)) +end + +sort!(ht, by=x->(x.σ, x.p, x.c)) + +print("The number of primitive Hernonian triangles having sides ≤ ") +println(slim, " is ", length(ht)) + +tlim = 10 +tlim = min(tlim, length(ht)) + +println() +println("Tabulating the first (by σ, p, c) ", tlim, " of these:") +println(" a b c σ p") +for t in ht[1:tlim] + println(@sprintf "%6d %3d %3d %4d %4d" t.a t.b t.c t.σ t.p) +end + +tlim = 210 +println() +println("Tabulating those having σ = ", tlim, ":") +println(" a b c σ p") +for t in ht + t.σ == tlim || continue + t.σ == tlim || break + println(@sprintf "%6d %3d %3d %4d %4d" t.a t.b t.c t.σ t.p) +end diff --git a/Task/Heronian-triangles/PARI-GP/heronian-triangles.pari b/Task/Heronian-triangles/PARI-GP/heronian-triangles.pari new file mode 100644 index 0000000000..b20eecdaa0 --- /dev/null +++ b/Task/Heronian-triangles/PARI-GP/heronian-triangles.pari @@ -0,0 +1,11 @@ +Heron(v)=my([a,b,c]=v); (a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c) \\ returns 16 times the squared area +is(a,b,c)=(a+b+c)%2==0 && gcd(a,gcd(b,c))==1 && issquare(Heron([a,b,c])) +v=List(); for(a=1,200,for(b=a+1,200,for(c=b+1,200, if(is(a,b,c),listput(v, [a,b,c]))))); +v=Vec(v); #v +vecsort(v, (a,b)->Heron(a)-Heron(b))[1..10] +vecsort(v, (a,b)->vecsum(a)-vecsum(b))[1..10] +vecsort(v, 3)[1..10] \\ shortcut: order by third component +u=select(v->Heron(v)==705600, v); +vecsort(u, (a,b)->Heron(a)-Heron(b)) +vecsort(u, (a,b)->vecsum(a)-vecsum(b)) +vecsort(u, 3) \\ shortcut: order by third component diff --git a/Task/Heronian-triangles/R/heronian-triangles-1.r b/Task/Heronian-triangles/R/heronian-triangles-1.r new file mode 100644 index 0000000000..f1ee32ebf1 --- /dev/null +++ b/Task/Heronian-triangles/R/heronian-triangles-1.r @@ -0,0 +1,36 @@ +area <- function(a, b, c) { + s = (a + b + c) / 2 + a2 = s*(s-a)*(s-b)*(s-c) + if (a2>0) sqrt(a2) else 0 +} + +is.heronian <- function(a, b, c) { + h = area(a, b, c) + h > 0 && 0==h%%1 +} + +# borrowed from stackoverflow http://stackoverflow.com/questions/21502181/finding-the-gcd-without-looping-r +gcd <- function(x,y) { + r <- x%%y; + ifelse(r, gcd(y, r), y) +} + +gcd3 <- function(x, y, z) { + gcd(gcd(x, y), z) +} + +maxside = 200 +r <- NULL +for(c in 1:maxside){ + for(b in 1:c){ + for(a in 1:b){ + if(1==gcd3(a, b, c) && is.heronian(a, b, c)) { + r <- rbind(r,c(a=a, b=b, c=c, perimeter=a+b+c, area=area(a,b,c))) + } + } + } +} + +cat("There are ",nrow(r)," Heronian triangles up to a maximal side length of ",maxside,".\n", sep="") +cat("Showing the first ten ordered first by perimeter, then by area:\n") +print(head(r[order(x=r[,"perimeter"],y=r[,"area"]),],n=10)) diff --git a/Task/Heronian-triangles/R/heronian-triangles-2.r b/Task/Heronian-triangles/R/heronian-triangles-2.r new file mode 100644 index 0000000000..26363c1d72 --- /dev/null +++ b/Task/Heronian-triangles/R/heronian-triangles-2.r @@ -0,0 +1,13 @@ +There are 517 Heronian triangles up to a maximal side length of 200. +Showing the first ten ordered first by perimeter, then by area: + a b c perimeter area + [1,] 3 4 5 12 6 + [2,] 5 5 6 16 12 + [3,] 5 5 8 18 12 + [4,] 5 12 13 30 30 + [5,] 4 13 15 32 24 + [6,] 9 10 17 36 36 + [7,] 10 13 13 36 60 + [8,] 8 15 17 40 60 + [9,] 7 15 20 42 42 +[10,] 13 14 15 42 84 diff --git a/Task/Heronian-triangles/REXX/heronian-triangles.rexx b/Task/Heronian-triangles/REXX/heronian-triangles.rexx index 4a7ed8dfaf..18df34f76e 100644 --- a/Task/Heronian-triangles/REXX/heronian-triangles.rexx +++ b/Task/Heronian-triangles/REXX/heronian-triangles.rexx @@ -1,53 +1,51 @@ -/*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.*/ +/*REXX program generates primitive Heronian triangles by side length and area.*/ +parse arg N first area . /*get optional arguments from C.L.*/ +if N=='' | N==',' then N=200 /*Not specified? Then use 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 digs.*/ +call Heron; HT='Heronian triangles' /*invoke the Heron subroutine. */ +say # ' primitive' HT "found with sides up to " N ' (inclusive).' +call show , 'listing of the first ' first ' primitive' HT":" +call show area, 'listing of the (above) found primitive' HT "with an area of " area +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +Heron: @.=0; #=0; minP=9e9; maxP=0; maxA=0; minA=9e9; Ln=length(N) /* _ */ + #.=0; #.2=1 #.3=1; #.7=1; #.8=1 /*digits ¬good √ */ + do a=3 to N /*start at a minimum side length of 3. */ + odd=a//2; ev=\odd /*if A is even, B and C must be odd.*/ + do b=a+ev to N by 1+ev; ab=a+b /*AB: is a shortcut sum.*/ + if b//2==0 then bump=1 /*B is even? Then C≡odd.*/ + else if odd then bump=1 /*if A and B odd, C≡even.*/ + else bump=0 /*OK, biz is as usual. */ + do c=b+bump to N by 2; s=(ab+c)/2 /*calculate Perimeter, S.*/ + _=s*(s-a)*(s-b)*(s-c); if _<=0 then iterate /*_ isn't positive, skip.*/ + parse var _ '.' z ; if z\=='' then iterate /*not an integer, skip.*/ + parse var _ '' -1 z ; if #.z then iterate /*last dig ¬square, skip.*/ + ar=hIsqrt(_); if ar*ar\==_ then iterate /*area ¬ an integer,skip.*/ + if hGCD(a,b,c)\==1 then iterate /*GCD of sides ¬ 1, skip.*/ + #=#+1; p=ab+c /*primitive Heron triang.*/ 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.*/ + minA=min(ar,minA); maxA=max(ar,maxA); La=length(maxA); @.ar= + _=@.ar.p.0+1 /*bump triangle counter. */ + @.ar.p.0=_; @.ar.p._=right(a,Ln) right(b,Ln) right(c,Ln) /*unique.*/ + end /*c*/ /* [↑] keep each unique perimeter #. */ end /*b*/ end /*a*/ -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 +return # /*return number of Heronian triangles. */ +/*────────────────────────────────────────────────────────────────────────────*/ +hIsqrt: procedure; parse arg x; q=1;r=0; do while q<=x; q=q*4; end; do while q>1 + q=q%4; _=x-r-q; r=r%2; if _>=0 then parse value _ r+q with x r; end; return r +/*────────────────────────────────────────────────────────────────────────────*/ +show: m=0; say; say; parse arg ae; say arg(2); if ae\=='' then first=9e9 +say; $=left('',9); $a=$"area:"; $p=$'perimeter:'; $s=$"sides:" /*literals*/ + do i=minA to maxA; if ae\=='' & i\==ae then iterate /*= area? */ + do j=minP to maxP until m>=first /*only display the FIRST entries.*/ + do k=1 for @.i.j.0; m=m+1 /*display each perimeter entry. */ + say right(m,9) $a right(i,La) $p right(j,Lp) $s @.i.j.k end /*k*/ - end /*j*/ /* [↑] use known perimeters*/ - end /*i*/ /* [↑] show found triangles*/ + end /*j*/ /* [↑] use the known perimeters. */ + end /*i*/ /* [↑] show any found triangles. */ return +/*────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ +hGCD: procedure; parse arg x; do j=2 for 2; y=arg(j); do until y==0; parse value x//y y with y x; end; end; return x diff --git a/Task/Heronian-triangles/Racket/heronian-triangles.rkt b/Task/Heronian-triangles/Racket/heronian-triangles.rkt index 0e3b433579..20ec62145d 100644 --- a/Task/Heronian-triangles/Racket/heronian-triangles.rkt +++ b/Task/Heronian-triangles/Racket/heronian-triangles.rkt @@ -1,55 +1,45 @@ -#lang racket -(require xml/xml data/order) +#lang at-exp racket +(require data/order scribble/html) -;; 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 +;; Returns the area of a triangle iff the sides have gcd 1, and it is an +;; integer; #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))) + (let ([s (/ (+ a b c) 2)]) ; ** If s=\frac{a+b+c}{2} + (and (integer? s) ; (s must be an integer for the area to b an integer) + (let-values ([[q r] (integer-sqrt/remainder ; (faster than sqrt) + ; ** Then the area is \sqrt{s(s-a)(s-b)(s-c)} + (* s (- s a) (- s b) (- s c)))]) + (and (zero? r) q)))))) ; (return only integer areas) (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)) + (for*/list ([c (in-range 1 (add1 max-side))] + [b (in-range 1 (add1 c))] ; b<=c + [a (in-range (add1 (- c b)) (add1 b))] ; ensures a<=b and ctds (match-lambda [`#(,h ,p ,s) `((td ,(~a s)) (td ,(~a p)) (td ,(~a h)))])) +(define (tri-sort triangles) + (sort triangles (λ(t1 t2) (eq? '< (datum-order t1 t2))))) -(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 tritable triangles) + (table + (tr (map th '("#" sides perimeter area))) "\n" + (for/list ([i (in-naturals 1)] [triangle (in-list triangles)]) + (match-define (list area perimeter max-side sides) triangle) + (tr (td i) (td (add-between sides ",")) (td perimeter) (td area) "\n")))) (module+ main (define ts (generate-heronian-triangles 200)) - (define div-out - `(div - (p "number of primitive triangles found with perimeter "le" 200 = " ,(~a (length ts))) "\n" - ;; Show the first ten ordered triangles in a table of sides, perimeter, and area. - ,(sorted-triangles-table (take (sort ts tristring div-out))) + (output-xml + @div{@p{number of primitive triangles found with perimeter @entity{le} 200 = @(length ts)} + @; Show the first ten ordered triangles in a table of sides, perimeter, + @; and area. + @(triangles->table (take (tri-sort ts) 10)) + @; Show a similar ordered table for those triangles with area = 210 + @(triangles->table (tri-sort (filter (λ(t) (eq? 210 (car t))) ts))) + })) diff --git a/Task/Heronian-triangles/Scala/heronian-triangles.scala b/Task/Heronian-triangles/Scala/heronian-triangles.scala new file mode 100644 index 0000000000..a985230748 --- /dev/null +++ b/Task/Heronian-triangles/Scala/heronian-triangles.scala @@ -0,0 +1,35 @@ +object Heron extends scala.collection.mutable.MutableList[Seq[Int]] with App { + private final val n = 200 + for (c <- 1 to n; b <- 1 to c; a <- 1 to b if gcd(gcd(a, b), c) == 1) { + val p = a + b + c + val s = p / 2D + val area = Math.sqrt(s * (s - a) * (s - b) * (s - c)) + if (isHeron(area)) + appendElem(Seq(a, b, c, p, area.toInt)) + } + print(s"Number of primitive Heronian triangles with sides up to $n: " + length) + + private final val list = sortBy(i => (i(4), i(3))) + print("\n\nFirst ten when ordered by increasing area, then perimeter:" + header) + list slice (0, 10) map format foreach print + print("\n\nArea = 210" + header) + list filter { _(4) == 210 } map format foreach print + + private def gcd(a: Int, b: Int) = { + var leftover = 1 + var (dividend, divisor) = if (a > b) (a, b) else (b, a) + while (leftover != 0) { + leftover = dividend % divisor + if (leftover > 0) { + dividend = divisor + divisor = leftover + } + } + divisor + } + + private def isHeron(h: Double) = h % 1 == 0 && h > 0 + + private final val header = "\nSides Perimeter Area" + private def format: Seq[Int] => String = "\n%3d x %3d x %3d %5d %10d".format +} diff --git a/Task/Heronian-triangles/Tcl/heronian-triangles.tcl b/Task/Heronian-triangles/Tcl/heronian-triangles.tcl new file mode 100644 index 0000000000..63b10704fa --- /dev/null +++ b/Task/Heronian-triangles/Tcl/heronian-triangles.tcl @@ -0,0 +1,91 @@ +if {[info commands let] eq ""} { + + #make some math look nicer: + proc let {name args} { + tailcall ::set $name [uplevel 1 $args] + } + interp alias {} = {} expr + namespace import ::tcl::mathfunc::* ::tcl::mathop::* + interp alias {} sum {} + + + # a simple adaptation of gcd from http://wiki.tcl.tk/2891 + proc coprime {a args} { + set gcd $a + foreach arg $args { + while {$arg != 0} { + set t $arg + let arg = $gcd % $arg + set gcd $t + if {$gcd == 1} {return true} + } + } + return false + } +} + +namespace eval Hero { + + # Integer square root: returns 0 if n is not a square. + proc isqrt? {n} { + let r = entier(sqrt($n)) + if {$r**2 == $n} { + return $r + } else { + return 0 + } + } + + # The square of a triangle's area + proc squarea {a b c} { + let s = ($a + $b + $c) / 2.0 + let sqrA = $s * ($s - $a) * ($s - $b) * ($s - $c) + return $sqrA + } + + proc is_heronian {a b c} { + isqrt? [squarea $a $b $c] + } + + proc primitive_triangles {db max} { + for {set a 1} {$a <= $max} {incr a} { + for {set b $a} {$b <= $max} {incr b} { + let maxc = min($a+$b,$max) + for {set c $b} {$c <= $maxc} {incr c} { + set area [is_heronian $a $b $c] + if {$area && [coprime $a $b $c]} { + set perimiter [expr {$a + $b + $c}] + $db eval {insert into herons (area, perimiter, a, b, c) values ($area, $perimiter, $a, $b, $c)} + } + } + } + } + } +} + +proc main {db} { + $db eval {create table herons (area int, perimiter int, a int, b int, c int)} + + set max 200 + puts "Calculating Primitive Heronian triangles up to size length $max" + puts \t[time {Hero::primitive_triangles $db $max} 1] + + puts "Total Primitive Heronian triangles with side lengths <= $max:" + $db eval {select count(1) count from herons} { + puts "\t$count" + } + + puts "First ten when ordered by increasing area, perimiter, max side length:" + $db eval {select * from herons order by area, perimiter, c limit 10} { + puts "\t($a, $b, $c) perimiter = $perimiter; area = $area" + } + + puts "All of area 210:" + $db eval {select * from herons where area=210 order by area, perimiter, c} { + puts "\t($a, $b, $c) perimiter = $perimiter; area = $area" + } +} + + +package require sqlite3 +sqlite3 db :memory: +main db diff --git a/Task/Hickerson-series-of-almost-integers/AWK/hickerson-series-of-almost-integers.awk b/Task/Hickerson-series-of-almost-integers/AWK/hickerson-series-of-almost-integers.awk new file mode 100644 index 0000000000..e010aeae7f --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/AWK/hickerson-series-of-almost-integers.awk @@ -0,0 +1,18 @@ +# syntax: GAWK -M -f HICKERSON_SERIES_OF_ALMOST_INTEGERS.AWK +# using GNU Awk 4.1.0, API: 1.0 (GNU MPFR 3.1.2, GNU MP 5.1.2) +BEGIN { + PREC = 100 + for (i=1; i<=17; i++) { + h = sprintf("%25.5f",factorial(i) / (2 * log(2) ^ (i + 1))) + msg = (h ~ /\.[09]/) ? "true" : "false" + printf("%2d %s almost integer: %s\n",i,h,msg) + } + exit(0) +} +function factorial(n, i,out) { + out = 1 + for (i=2; i<=n; i++) { + out *= i + } + return(out) +} diff --git a/Task/Hickerson-series-of-almost-integers/Haskell/hickerson-series-of-almost-integers.hs b/Task/Hickerson-series-of-almost-integers/Haskell/hickerson-series-of-almost-integers.hs new file mode 100644 index 0000000000..46865413ad --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Haskell/hickerson-series-of-almost-integers.hs @@ -0,0 +1,14 @@ +import Data.Number.CReal -- from numbers + +hickerson :: Int -> CReal +hickerson n = (fromIntegral $ product [1..n]) / (2 * (log 2 ^ (n + 1))) + +checkHickerson :: Int -> String +checkHickerson n = + let h = hickerson n + postDecimalPointDigit = dropWhile (/='.') (show h) !! 1 + almostIntegral = '0' == postDecimalPointDigit || '9' == postDecimalPointDigit + in "h(" ++ show n ++ ") = " ++ showCReal 4 h ++ " which is" ++ (if almostIntegral then "" else " NOT") ++ " almost integral." + +main :: IO () +main = mapM_ putStrLn [checkHickerson n | n <- [1..18]] diff --git a/Task/Hickerson-series-of-almost-integers/Julia/hickerson-series-of-almost-integers.julia b/Task/Hickerson-series-of-almost-integers/Julia/hickerson-series-of-almost-integers.julia new file mode 100644 index 0000000000..fdea5a68c1 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Julia/hickerson-series-of-almost-integers.julia @@ -0,0 +1,49 @@ +function makehickerson{T<:Real}(x::T) + n = 0 + h = one(T)/2x + function hickerson() + n += 1 + h *= n/x + end +end + +function reporthickerson{T<:Real,U<:Integer}(a::T, nmax::U) + h = makehickerson(a) + hgm = makehickerson(prevfloat(a)) + hgp = makehickerson(nextfloat(a)) + + println() + print("Performing calculations using ", typeof(a)) + println(", which has ", precision(a), "-bit precision.") + for i in 1:nmax + x = h() + xm = hgm() + xp = hgp() + y = ifloor(10x) + ym = ifloor(10xm) + yp = ifloor(10xp) + println() + println("Hickerson series result for n = ", i) + println(@sprintf(" -> %25.4f ", xm)) + println(@sprintf(" 0> %25.4f ", x)) + println(@sprintf(" +> %25.4f ", xp)) + isprecok = + isint = + if ym == y == yp + print("The precision is adequate, ") + if digits(y)[1] in [0, 9] + println("and the result is an almost integer.") + else + println("but the result is not an almost integer.") + end + else + println("The precision is inadequate for a definite result.") + end + end +end + +a = log(big(2.0)) +reporthickerson(a, 17) + +a = log(2.0) +reporthickerson(a, 17) 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 index b75fdcdbea..7341bdcf39 100644 --- 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 @@ -1,5 +1,5 @@ constant ln2 = [+] (1/2.FatRat, */2 ... *) Z/ 1 .. 100; -constant h = [\*] 1/2, 1..* X/ ln2; +constant h = [\*] 1/2, |(1..*) X/ ln2; use Test; plan *; 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-1.rexx similarity index 100% rename from Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers.rexx rename to Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers-1.rexx diff --git a/Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers-2.rexx b/Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers-2.rexx new file mode 100644 index 0000000000..6520719ca8 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/REXX/hickerson-series-of-almost-integers-2.rexx @@ -0,0 +1,17 @@ +/*REXX program to calculate and show the Hickerson series (are near integer). */ +numeric digits 250 /*be able to calculate big factorials. */ +parse arg N . /*get optional number of values to use.*/ +if N=='' then N=18 /*Not specified? Then use the default. */ + /* [+] compute possible Hickerson #s. */ + do j=1 for N; #=Hickerson(j) /*traipse thru a range of Hickerson #s.*/ + t=#*10%1; ?=right(t, 1) /*massage number to obtain FDD past DP.*/ + if ?==0 | ?==9 then _= '(almost an integer)' /*da number is, */ + else _= ' ' /* or it ain't. */ + say right(j,3) _ format(#,,5) /*show the number with 9 decimal digits*/ + end /*j*/ /*FDD=1st decimal digit past dec. point*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ +!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end; return ! /* ◄─── compute the factorial of X. */ +Hickerson: procedure; parse arg z; return !(z) / (2*ln2() ** (z+1)) +ln2: return .6931471805599453094172321214581765680755001343602552541206800094933936219696947156058633269964186875420014, + || 81020570685733685520235758130557032670751635075961930727570828371435190307038623891673471123350115364497955239120475 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 index bd11f65630..0ed9a59438 100644 --- 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 @@ -1,7 +1,7 @@ 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 = Hash.new{|h,k| h[k] = k * h[k-1]} FACTORIALS[0] = 1 def hickerson(n) diff --git a/Task/Hickerson-series-of-almost-integers/TI-83-BASIC/hickerson-series-of-almost-integers.ti-83 b/Task/Hickerson-series-of-almost-integers/TI-83-BASIC/hickerson-series-of-almost-integers.ti-83 new file mode 100644 index 0000000000..ae579e2a2f --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/TI-83-BASIC/hickerson-series-of-almost-integers.ti-83 @@ -0,0 +1,8 @@ +For(N,1,17 +N!/(2ln(2)^(N+1→H +Disp N,H,"IS +round(H,1)-iPart(H) +If not(Ans=.9 or not(Ans +Disp "NOT +Disp "ALMOST INTEGER +End diff --git a/Task/Higher-order-functions/Elixir/higher-order-functions.elixir b/Task/Higher-order-functions/Elixir/higher-order-functions.elixir new file mode 100644 index 0000000000..4860fdfc26 --- /dev/null +++ b/Task/Higher-order-functions/Elixir/higher-order-functions.elixir @@ -0,0 +1,17 @@ +iex(1)> defmodule RC do +...(1)> def first(f), do: f.() +...(1)> def second, do: :hello +...(1)> end +{:module, RC, + <<70, 79, 82, 49, 0, 0, 4, 224, 66, 69, 65, 77, 69, 120, 68, 99, 0, 0, 0, 142, +131, 104, 2, 100, 0, 14, 101, 108, 105, 120, 105, 114, 95, 100, 111, 99, 115, 95 +, 118, 49, 108, 0, 0, 0, 2, 104, 2, ...>>, + {:second, 0}} +iex(2)> RC.first(fn -> RC.second end) +:hello +iex(3)> RC.first(&RC.second/0) # Another expression +:hello +iex(4)> f = fn -> :world end # Anonymous function +#Function<20.54118792/0 in :erl_eval.expr/5> +iex(5)> RC.first(f) +:world diff --git a/Task/Higher-order-functions/Frink/higher-order-functions-1.frink b/Task/Higher-order-functions/Frink/higher-order-functions-1.frink new file mode 100644 index 0000000000..be4b6daf04 --- /dev/null +++ b/Task/Higher-order-functions/Frink/higher-order-functions-1.frink @@ -0,0 +1,4 @@ +cmpFunc = {|a,b| length[a] <=> length[b]} + +a = ["tree", "apple", "bee", "monkey", "z"] +sort[a, cmpFunc] diff --git a/Task/Higher-order-functions/Frink/higher-order-functions-2.frink b/Task/Higher-order-functions/Frink/higher-order-functions-2.frink new file mode 100644 index 0000000000..c0b2e2f616 --- /dev/null +++ b/Task/Higher-order-functions/Frink/higher-order-functions-2.frink @@ -0,0 +1,5 @@ +lengthCompare[a,b] := length[a] <=> length[b] + +func = getFunction["lengthCompare", 2] +a = ["tree", "apple", "bee", "monkey", "z"] +sort[a, func] diff --git a/Task/Higher-order-functions/J/higher-order-functions-1.j b/Task/Higher-order-functions/J/higher-order-functions-1.j index 0795980450..174e6e1dae 100644 --- a/Task/Higher-order-functions/J/higher-order-functions-1.j +++ b/Task/Higher-order-functions/J/higher-order-functions-1.j @@ -11,6 +11,14 @@ +/\. 3 1 4 1 5 9 NB. sum suffix 23 20 19 15 14 9 + 2&% 1 2 3 NB. divide 2 by +2 1 0.666667 + + %&2 (1 2 3) NB. divide by 2 (need parenthesis to break up list formation) +0.5 1 1.5 + -: 1 2 3 NB. but divide by 2 happens a lot so it's a primitive +0.5 1 1.5 + f=: -:@(+ 2&%) NB. one Newton iteration f 1 1.5 diff --git a/Task/Higher-order-functions/PowerShell/higher-order-functions-1.psh b/Task/Higher-order-functions/PowerShell/higher-order-functions-1.psh new file mode 100644 index 0000000000..2321de4d9d --- /dev/null +++ b/Task/Higher-order-functions/PowerShell/higher-order-functions-1.psh @@ -0,0 +1,6 @@ +function f ($y) { + $y*$y +} +function g (${function:f}, $y) { + (f $y) +} diff --git a/Task/Higher-order-functions/PowerShell/higher-order-functions-2.psh b/Task/Higher-order-functions/PowerShell/higher-order-functions-2.psh new file mode 100644 index 0000000000..2c9eb44b88 --- /dev/null +++ b/Task/Higher-order-functions/PowerShell/higher-order-functions-2.psh @@ -0,0 +1,6 @@ +function g2($y) { + function f2($y) { + $y*$y + } + (f2 $y) +} diff --git a/Task/Higher-order-functions/PowerShell/higher-order-functions-3.psh b/Task/Higher-order-functions/PowerShell/higher-order-functions-3.psh new file mode 100644 index 0000000000..169e40e4f8 --- /dev/null +++ b/Task/Higher-order-functions/PowerShell/higher-order-functions-3.psh @@ -0,0 +1,2 @@ +g f 5 +g2 9 diff --git a/Task/Higher-order-functions/Prolog/higher-order-functions.pro b/Task/Higher-order-functions/Prolog/higher-order-functions.pro index 9fc00c925c..8771d41139 100644 --- a/Task/Higher-order-functions/Prolog/higher-order-functions.pro +++ b/Task/Higher-order-functions/Prolog/higher-order-functions.pro @@ -1,4 +1,4 @@ -first(Predicate):-Predicate. -second(Argument):-print(Argument). +first(Predicate) :- call(Predicate). +second(Argument) :- write(Argument). :-first(second('Hello World!')). diff --git a/Task/Higher-order-functions/Q/higher-order-functions.q b/Task/Higher-order-functions/Q/higher-order-functions.q new file mode 100644 index 0000000000..c12cd94e62 --- /dev/null +++ b/Task/Higher-order-functions/Q/higher-order-functions.q @@ -0,0 +1,6 @@ +q)sayHi:{-1"Hello ",x;} +q)callFuncWithParam:{x["Peter"]} +q)callFuncWithParam sayHi +Hello Peter +q)callFuncWithParam[sayHi] +Hello Peter diff --git a/Task/Higher-order-functions/REXX/higher-order-functions.rexx b/Task/Higher-order-functions/REXX/higher-order-functions.rexx index 8778be49bf..f9778b7d4f 100644 --- a/Task/Higher-order-functions/REXX/higher-order-functions.rexx +++ b/Task/Higher-order-functions/REXX/higher-order-functions.rexx @@ -1,21 +1,20 @@ -/*REXX program demonstrates passing a function as a name to a function.*/ -n=3735928559 -funcName='fib' ; q= 10; call someFunk funcName, q; call tell -funcName='fact' ; q= 6; call someFunk funcName, q; call tell -funcName='square' ; q= 13; call someFunk funcName, q; call tell -funcName='cube' ; q= 3; call someFunk funcName, q; call tell - q=721; call someFunk 'reverse',q; call tell -say copies('─',30) /*display a nice separator fence.*/ -say 'done as' d2x(n)"." /*prove that var N still intact. */ -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────subroutines─────────────────────────*/ +/*REXX program demonstrates passing a function as a name to another function. */ + n=3735928559 +funcName = 'fib' ; q= 10; call someFunk funcName, q; call tell +funcName = 'fact' ; q= 6; call someFunk funcName, q; call tell +funcName = 'square' ; q= 13; call someFunk funcName, q; call tell +funcName = 'cube' ; q= 3; call someFunk funcName, q; call tell + q=721; call someFunk 'reverse',q; call tell +say copies('═', 30) /*display a nice separator fence */ +say 'done as' d2x(n)"." /*prove that variable N is still intact*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ cube: return n**3 -fact: !=1; do j=2 to n; !=!*j; end; return ! +fact: !=1; do j=2 to n; !=!*j; end; return ! reverse: return 'REVERSE'(n) -someFunk: procedure; arg ?,n; signal value (?); say result 'result'; return +someFunk: procedure; arg ?,n; signal value (?); say result 'result'; return square: return n**2 -tell: say right(funcName'('q") = ",20) result; return - -fib: if n==0 | n==1 then return n; _=0; a=0; b=1 - do j=2 to n; _=a+b; a=b; b=_; end; return _ +tell: say right(funcName'('q") = ",20) result; return +/*────────────────────────────────────────────────────────────────────────────*/ +fib: if n==0 | n==1 then return n; _=0; a=0; b=1 + do j=2 to n; _=a+b; a=b; b=_; end; return _ diff --git a/Task/Higher-order-functions/Rust/higher-order-functions.rust b/Task/Higher-order-functions/Rust/higher-order-functions.rust new file mode 100644 index 0000000000..e895353cb2 --- /dev/null +++ b/Task/Higher-order-functions/Rust/higher-order-functions.rust @@ -0,0 +1,12 @@ +fn execute_with_10 u64> (f: F) -> u64 { + f(10) +} + +fn square(n: u64) -> u64 { + n*n +} + +fn main() { + println!("{}", execute_with_10(|n| n*n )); // closure + println!("{}", execute_with_10(square)); // function +} diff --git a/Task/History-variables/AspectJ/history-variables-1.aspectj b/Task/History-variables/AspectJ/history-variables-1.aspectj new file mode 100644 index 0000000000..7aa0bf2d55 --- /dev/null +++ b/Task/History-variables/AspectJ/history-variables-1.aspectj @@ -0,0 +1,30 @@ +public class HistoryVariable +{ + public HistoryVariable(final Object v) + { + super(); + value = v; + } + + public void update(final Object v) + { + value = v; + } + + public Object undo() + { + return value; + } + + @Override + public String toString() + { + return value.toString(); + } + + public void dispose() + { + } + + private Object value; +} diff --git a/Task/History-variables/AspectJ/history-variables-2.aspectj b/Task/History-variables/AspectJ/history-variables-2.aspectj new file mode 100644 index 0000000000..2ec1ff3a36 --- /dev/null +++ b/Task/History-variables/AspectJ/history-variables-2.aspectj @@ -0,0 +1,43 @@ +import java.util.Deque; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; + +public privileged aspect HistoryHandling +{ + before() : execution(HistoryVariable.new(..)) + { + history.put((HistoryVariable) thisJoinPoint.getTarget(), new LinkedList<>()); + } + + after() : execution(void HistoryVariable.dispose()) + { + history.remove(thisJoinPoint.getTarget()); + } + + before(Object v) : execution(void HistoryVariable.update(Object)) && args(v) + { + final HistoryVariable hv = (HistoryVariable) thisJoinPoint.getThis(); + history.get(hv).add(hv.value); + } + + after() : execution(Object HistoryVariable.undo()) + { + final HistoryVariable hv = (HistoryVariable) thisJoinPoint.getThis(); + final Deque q = history.get(hv); + if (!q.isEmpty()) + hv.value = q.pollLast(); + } + + String around() : this(HistoryVariable) && execution(String toString()) + { + final HistoryVariable hv = (HistoryVariable) thisJoinPoint.getThis(); + final Deque q = history.get(hv); + if (q == null) + return ""; + else + return "current: "+ hv.value + ", previous: " + q.toString(); + } + + private Map> history = new HashMap<>(); +} diff --git a/Task/History-variables/AspectJ/history-variables-3.aspectj b/Task/History-variables/AspectJ/history-variables-3.aspectj new file mode 100644 index 0000000000..8053d65866 --- /dev/null +++ b/Task/History-variables/AspectJ/history-variables-3.aspectj @@ -0,0 +1,17 @@ +public final class Main +{ + public static void main(final String[] args) + { + HistoryVariable hv = new HistoryVariable("a"); + hv.update(90); + hv.update(12.1D); + System.out.println(hv.toString()); + System.out.println(hv.undo()); + System.out.println(hv.undo()); + System.out.println(hv.undo()); + System.out.println(hv.undo()); + System.out.println(hv.toString()); + hv.dispose(); + System.out.println(hv.toString()); + } +} diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Bracmat/hofstadter-conway-$10,000-sequence.bracmat b/Task/Hofstadter-Conway-$10,000-sequence/Bracmat/hofstadter-conway-$10,000-sequence.bracmat new file mode 100644 index 0000000000..cb11685450 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Bracmat/hofstadter-conway-$10,000-sequence.bracmat @@ -0,0 +1,56 @@ +( ( a + = + . !arg:(1|2)&1 + | (as..find)$!arg:(?.?arg)&!arg + | (as..insert) + $ ( !arg + . a$(a$(!arg+-1))+a$(!arg+-1*a$(!arg+-1)):?arg + ) + & !arg + ) +& new$hash:?as +& 0:?n:?maxan/n +& 1:?pow +& whl + ' ( 1+!n:?n + & !pow:~>20 + & ( 2^!pow:~!n + | out + $ ( str + $ ( "Between 2^" + !pow+-1 + " and 2^" + !pow + " the maximum value of a(n)/n is reached for n = " + !maxn + " with the value " + !maxan/n + ) + ) + & 0:?maxan/n + & 1+!pow:?pow + ) + & a$!n*!n^-1:?an/n + & ( !an/n:>!maxan/n:?maxan/n + & !n:?maxn + | + ) + & ( !an/n:~<11/20:?Man/n&!n:?Mallows + | + ) + ) +& out + $ ( str + $ ( "Mallows number is " + !Mallows + ", where a(" + !Mallows + ")/" + !Mallows + " == " + !Man/n + ", which is greater than 0.55 by " + !Man/n+-11/20 + ) + ) +) diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Eiffel/hofstadter-conway-$10,000-sequence.e b/Task/Hofstadter-Conway-$10,000-sequence/Eiffel/hofstadter-conway-$10,000-sequence.e new file mode 100644 index 0000000000..4a2d35c53d --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Eiffel/hofstadter-conway-$10,000-sequence.e @@ -0,0 +1,60 @@ +class + APPLICATION + +create + make + +feature + + make + --Tests the feature sequence. + local + j, n, exp: INTEGER + max: REAL_64 + do + exp := 15 + n := (2 ^ exp).floor + sequence (n) + across + 1 |..| (exp - 1) as c + loop + max := 0 + from + j := (2 ^ c.item).floor + until + j > 2 ^ (c.item + 1) + loop + if members [j] / j > max then + max := members [j] / j + end + j := j + 1 + end + io.put_string ("Between 2^" + c.item.out + "and 2^" + (c.item + 1).out + " the max is: " + max.out) + io.new_line + end + end + +feature {NONE} + + members: LINKED_LIST [INTEGER] + -- Members of the Hofstadter Conway $10000 sequence. + + sequence (n: INTEGER) + -- Hofstadter Conway $10000 sequence up to 'n' in 'members'. + require + n_positive: n > 0 + local + last: INTEGER + do + create members.make + members.extend (1) + members.extend (1) + across + 3 |..| n as c + loop + last := members.last + members.extend (members [last] + members [c.item - last]) + end + end + +end diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Perl-6/hofstadter-conway-$10,000-sequence-1.pl6 b/Task/Hofstadter-Conway-$10,000-sequence/Perl-6/hofstadter-conway-$10,000-sequence-1.pl6 index 23c26f2034..ef3d47f430 100644 --- a/Task/Hofstadter-Conway-$10,000-sequence/Perl-6/hofstadter-conway-$10,000-sequence-1.pl6 +++ b/Task/Hofstadter-Conway-$10,000-sequence/Perl-6/hofstadter-conway-$10,000-sequence-1.pl6 @@ -1,30 +1,13 @@ -my $POW = 20; -my $top = 2**$POW; - -my @a = (0,1,1); -@a[$top] = 0; # pre-extend array - my $n = 3; -my $p = 1; - -loop ($n = 3; $n <= $top; $n++) { - @a[$n] = $p = @a[$p] + @a[$n - $p]; -} +my @a = (0,1,1, -> $p { @a[$p] + @a[$n++ - $p] } ... *); my $last55; -for 1 ..^ $POW -> $power { - - my $beg = 2 ** $power; - my $end = $beg * 2 - 1; - my $max; - my $ratio; - - loop (my $n = $beg; $n <= $end; $n++) { - my $ratio = @a[$n] / $n; - $last55 = $n if $ratio * 100 >= 55; - $max max= $ratio => $n; - } - - say $power.fmt('%2d'), $beg.fmt("%10d"), '..', $end.fmt("%-10d"), $max.key, " at ", $max.value; +for 1..19 -> $power { + my @range := 2**$power .. 2**($power+1)-1; + my @ratios = (@a[@range] Z/ @range) Z=> @range; + my $max = @ratios.max; + ($last55 = .value if .key >= .55 for @ratios) if $max.key >= .55; + say $power.fmt('%2d'), @range.min.fmt("%10d"), '..', @range.max.fmt("%-10d"), + $max.key, ' at ', $max.value; } say "Mallows' number would appear to be ", $last55; diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Perl-6/hofstadter-conway-$10,000-sequence-3.pl6 b/Task/Hofstadter-Conway-$10,000-sequence/Perl-6/hofstadter-conway-$10,000-sequence-3.pl6 index dcb00545c2..d99544f0f8 100644 --- a/Task/Hofstadter-Conway-$10,000-sequence/Perl-6/hofstadter-conway-$10,000-sequence-3.pl6 +++ b/Task/Hofstadter-Conway-$10,000-sequence/Perl-6/hofstadter-conway-$10,000-sequence-3.pl6 @@ -1,13 +1,30 @@ -my $n = 3; -my @a := (0,1,1, -> $p { @a[$p] + @a[$n++ - $p] } ... *); - -my $last55; -for 1..19 -> $power { - my @range := 2**$power .. 2**($power+1)-1; - my @ratios = (@a[@range] Z/ @range) Z=> @range; - my $max = [max] @ratios; - ($last55 = .value if .key >= .55 for @ratios) if $max.key >= .55; - say $power.fmt('%2d'), @range.min.fmt("%10d"), '..', @range.max.fmt("%-10d"), - $max.key, ' at ', $max.value; +my int $POW = 20; +my int $top = 2**$POW; + +my int @a = (0,1,1); +@a[$top] = 0; # pre-extend array + +my int $n = 3; +my int $p = 1; + +loop ($n = 3; $n <= $top; ++$n) { + @a[$n] = $p = @a[$p] + @a[$n - $p]; +} + +my int $last55; +for 1 ..^ $POW -> int $power { + + my int $beg = 2 ** $power; + my int $end = $beg * 2 - 1; + my $max; + my $ratio; + + loop (my $n = $beg; $n <= $end; ++$n) { + my $ratio = @a[$n] / $n; + $last55 = $n if $ratio * 100 >= 55; + $max max= $ratio => $n; + } + + say $power.fmt('%2d'), $beg.fmt("%10d"), '..', $end.fmt("%-10d"), $max.key, " at ", $max.value; } say "Mallows' number would appear to be ", $last55; diff --git a/Task/Hofstadter-Conway-$10,000-sequence/REXX/hofstadter-conway-$10,000-sequence.rexx b/Task/Hofstadter-Conway-$10,000-sequence/REXX/hofstadter-conway-$10,000-sequence.rexx index 0832b4412d..d64a4c86bc 100644 --- a/Task/Hofstadter-Conway-$10,000-sequence/REXX/hofstadter-conway-$10,000-sequence.rexx +++ b/Task/Hofstadter-Conway-$10,000-sequence/REXX/hofstadter-conway-$10,000-sequence.rexx @@ -1,33 +1,32 @@ -/*REXX program solves the Hofstadter-Conway $10,000 prize. */ -hC.=; i.=0; m.=0; n.=0; w=0; wi=0; few=70; L= +/*REXX program solves the Hofstadter-Conway $10,000 prize (puzzle). */ +hC.=; !.=0; @.=0; w=0; wi=0; few=70; L= - do i=1 for few; L=L hc(i) /*build first 70 numbers in seq. */ + do i=1 for few; L=L hc(i) /*build the 1st 70 numbers in sequence.*/ end /*i*/ - /*I wear a belt and suspenders. */ -say 'The first' few "numbers in the Hofstadter-Conway sequence:" -say strip(L) /*show&tell, no trees have to die*/ -say /*show a blank line for the eyes.*/ - do k=0 to 20 /*build an array, powers of two.*/ - p.k=2**k /*Bang-bang!. Er, I mean pow-pow*/ - maxp=p.k /*and remember who's da big 'un. */ + /*wearing a belt & suspenders, show ···*/ +say 'The first' few "numbers in the Hofstadter─Conway sequence:" +say strip(L) /*display the list, trees have to die. */ +say /*show a blank line for the eyeballs. */ + do k=0 to 20 /*build an array of the powers of two. */ + p.k=2**k /*Bang-bang!. Er, ··· I mean pow-pow.*/ + maxp=p.k /* ··· and remember who's da big 'un.*/ end /*k*/ -r=1 /*R: the range of the power of 2.*/ - do n=1 for maxp /*heck, let's get cracking then.*/ - if n>p.r then r=r+1 /*for golf players: r=r+(n>p.r) */ - _=hc(n)/n; if _>=.55 then w=n /*get next seq #; if ≥.55, a win?*/ - if _<=m.r then iterate /*less than? Then keep truckin'.*/ - m.r=_; i.r=n /*m.r & i.r is for ginkgo biloba*/ +r=1 /*R: is the range of the power of two.*/ + do n=1 for maxp /*heck, let's get cracking then ··· */ + if n>p.r then r=r+1 /*for golf coders: r = r + (n>p.r) */ + _=hc(n)/n; if _>=.55 then w=n /*get next seq number; if ≥.55, a win? */ + if _<=@.r then iterate /*less than prev? Then keep truckin'.*/ + @.r=_; !.r=n /*@.r and !.r are like ginkgo biloba.*/ end /*n*/ -pref='Maximum of a(n) ÷ n between ' /*prefix text of message.*/ +pref='Maximum of a(n) ÷ n between ' /*prefix for the text of message.*/ - do j=1 for 20; range='2**'right(j-1,2) "───► 2**"right(j,2) - say pref range '(inclusive) is ' left(m.j,8) ' at n='right(i.j,7) - end /*j*/ + do j=1 for 20; range='2**'right(j-1,2) "───► 2**"right(j,2) + say pref range '(inclusive) is ' left(@.j,8) ' at n='right(!.j,7) + end /*j*/ say -say 'The winning number is: ' w /*and the money shot is ... */ -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────hC [Hofstadter-Conway] subroutine*/ -hC: procedure expose hC.; parse arg n; if n<3 then return 1 -if hC.n=='' then hC.n = hC(hC(n-1)) + hC(n-hC(n-1)) -return hC.n /*return with the goodie stuff. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +hC: procedure expose hC.; parse arg n; if n<3 then return 1 + if hC.n=='' then hC.n = hC(hC(n-1)) + hC(n-hC(n-1)) + return hC.n /*return with the goodie stuff (high). */ diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence.rb b/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence.rb new file mode 100644 index 0000000000..9f6415fa8b --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Ruby/hofstadter-conway-$10,000-sequence.rb @@ -0,0 +1,29 @@ +class HofstadterConway10000 + def initialize + @sequence = [nil, 1, 1] + end + + def [](n) + raise ArgumentError, "n must be >= 1" if n < 1 + a = @sequence + a.length.upto(n) {|i| a[i] = a[a[i-1]] + a[i-a[i-1]] } + a[n] + end +end + +hc = HofstadterConway10000.new + +mallows = nil +(1...20).each do |i| + j = i + 1 + max_n, max_v = -1, -1 + (2**i .. 2**j).each do |n| + v = hc[n].to_f / n + max_n, max_v = n, v if v > max_v + # Mallows number + mallows = n if v >= 0.55 + end + puts "maximum between 2^%2d and 2^%2d occurs at%7d: %.8f" % [i, j, max_n, max_v] +end + +puts "the mallows number is #{mallows}" diff --git a/Task/Hofstadter-Figure-Figure-sequences/Julia/hofstadter-figure-figure-sequences-1.julia b/Task/Hofstadter-Figure-Figure-sequences/Julia/hofstadter-figure-figure-sequences-1.julia new file mode 100644 index 0000000000..2f8a7df2ea --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Julia/hofstadter-figure-figure-sequences-1.julia @@ -0,0 +1,61 @@ +type FigureFigure{T<:Integer} + r::Array{T,1} + rnmax::T + snmax::T + snext::T +end + +function grow!{T<:Integer}(ff::FigureFigure{T}, rnmax::T=100) + ff.rnmax < rnmax || return nothing + append!(ff.r, zeros(T, (rnmax-ff.rnmax))) + snext = ff.snext + for i in (ff.rnmax+1):rnmax + ff.r[i] = ff.r[i-1] + snext + snext += 1 + while snext in ff.r + snext += 1 + end + end + ff.rnmax = rnmax + ff.snmax = ff.r[end] - rnmax + ff.snext = snext + return nothing +end + +function FigureFigure{T<:Integer}(rnmax::T=10) + ff = FigureFigure([1], 1, 0, 2) + grow!(ff, rnmax) + return ff +end + +function FigureFigure{T<:Integer}(rnmax::T, snmax::T) + ff = FigureFigure(rnmax) + while ff.snmax < snmax + grow!(ff, 2ff.rnmax) + end + return ff +end + +function make_ffr{T<:Integer}(nmax::T=10) + ff = FigureFigure(nmax) + function ffr{T<:Integer}(n::T) + if n > ff.rnmax + grow!(ff, 2n) + end + ff.r[n] + end +end + +function make_ffs{T<:Integer}(nmax::T=100) + ff = FigureFigure(13, nmax) + function ffs{T<:Integer}(n::T) + while ff.snmax < n + grow!(ff, 2ff.rnmax) + end + s = n + for r in ff.r + r <= s || return s + s += 1 + end + end +end diff --git a/Task/Hofstadter-Figure-Figure-sequences/Julia/hofstadter-figure-figure-sequences-2.julia b/Task/Hofstadter-Figure-Figure-sequences/Julia/hofstadter-figure-figure-sequences-2.julia new file mode 100644 index 0000000000..d21e7418d3 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Julia/hofstadter-figure-figure-sequences-2.julia @@ -0,0 +1,40 @@ +NR = 40 +NS = 960 +ffr = make_ffr(NR) +ffs = make_ffs(NS) + +hi = 10 +print("The first ", hi, " values of R are:\n ") +for i in 1:hi + print(ffr(i), " ") +end +println() + +tally = falses(NR+NS) +iscontained = true +for i in 1:NR + try + tally[ffr(i)] = true + catch + iscontained = false + end +end +for i in 1:NS + try + tally[ffs(i)] = true + catch + iscontained = false + end +end + +println() +print("The first ", NR, " values of R and ", NS, " of S are ") +if !iscontained + print("not ") +end +println("contained in the interval 1:", NR+NS, ".") +print("These values ") +if !all(tally) + print("do not ") +end +println("cover the entire interval.") diff --git a/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx b/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx index e160bdf48e..0cd1e76aad 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx +++ b/Task/Hofstadter-Figure-Figure-sequences/REXX/hofstadter-figure-figure-sequences-1.rexx @@ -1,41 +1,43 @@ -/*REXX pgm calculates & verifies the Hofstadter Figure-Figure sequences.*/ -parse arg x highV bot . /*obtain any C.L. specifications.*/ -if x=='' then x=10; if highV=='' then highV=1000 /*use the defaults?*/ -if bot=='' then bot=40 /* " " " */ -low=1; if x<0 then low=abs(x) /*only show a single │X│ value.*/ -r.=0; r.1=1; rr.=r.; rr.1=1 /*initialize the R & RR arrays.*/ -s.=0; s.1=2 /* " " S array. */ -errs=0; both.=0 - do i=low to abs(x) /*show first X values of R & S */ - say right('R('i") =",20) right(ffr(i),7), /*show nice*/ - right('S('i") =",20) right(ffs(i),7) /* R & S */ +/*REXX program calculates and verifies the Hofstadter Figure─Figure sequences.*/ +parse arg x top bot . /*obtain optional arguments from the CL*/ +if x=='' | x==',' then x= 10 /*Not specified? Then use the default.*/ +if top=='' | top==',' then top=1000 /* " " " " " " */ +if bot=='' | bot==',' then bot= 40 /* " " " " " " */ +low=1; if x<0 then low=abs(x) /*only display a single │X│ value? */ +r.=0; r.1=1; rr.=r.; rr.1=1; s.=r.; s.1=2 /*initialize the R RR S arrays.*/ +errs=0; $.=0 + do i=low to abs(x) /*display the 1st X values of R & S.*/ + say right('R('i") =", 20) right(ffr(i), 7), + right('S('i") =", 20) right(ffs(i), 7) end /*i*/ -if x<1 then exit /*if x ≤ 0, then we're all done.*/ - do m=1 for bot; r=ffr(m); both.r=1 /*calculate 1st 40 R values.*/ - end /*m*/ /* [↑] build first 40 R values.*/ - do n=1 for highV-bot; s=ffs(n) /*calculate 1st 960 S values.*/ - if both.s then call sayErr 'duplicate number in R and S lists:' s - both.s=1 /*indicate it's is in both array.*/ - end /*n*/ /* [↑] build firstt 960 S values.*/ - do v=1 for highV /*verify all 1 ≤ # ≤ 1k present.*/ - if \both.v then call sayErr 'missing R │ S:' v - end /*v*/ /* [↑] verify presence&uniqueness*/ +if x<1 then exit + do m=1 for bot; r=ffr(m); $.r=1 + end /*m*/ /* [↑] calculate the 1st 40 R values.*/ + + do n=1 for top-bot; s=ffs(n) + if $.s then call ser 'duplicate number in R and S lists:' s; $.s=1 + end /*n*/ /* [↑] calculate the 1st 960 S values.*/ + + do v=1 for top + if \$.v then call ser 'missing R │ S:' v + end /*v*/ /* [↑] are all 1≤ numbers ≤1k present?*/ say -if errs==0 then say 'verification completed for all numbers from 1 ──►' highV " [inclusive]." - else say 'verification failed with' errs "errors." +if errs==0 then say 'verification completed for all numbers from 1 ──►' top " [inclusive]." + else say 'verification failed with' errs "errors." exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FFR subroutine──────────────────────*/ -ffr: procedure expose r. s. rr.; parse arg n -if r.n\==0 then return r.n /*Defined? Then return the value.*/ -_=ffr(n-1) + ffs(n-1) /*calculate the FFR value. */ -r.n=_; rr._=1; return _ /*assign value to R & RR; return.*/ -/*──────────────────────────────────FFS subroutine──────────────────────*/ -ffs: procedure expose r. s. rr.; parse arg n - do k=1 for n while s.n==0 /*search for ¬null R │ S number*/ - if s.k\==0 then if ffr(k)\==0 then iterate /*short circuit*/ - km=k-1; _=s.km+1 /*the next SS number, possibly.*/ - _=_+rr._; s.k=_ /*define an element of S array.*/ - end /*k*/ -return s.n /*return the value to the invoker*/ -/*──────────────────────────────────SAYERR subroutine───────────────────*/ -sayErr: errs=errs+1; say '***error***!' arg(1); return +/*────────────────────────────────────────────────────────────────────────────*/ +ffr: procedure expose r. s. rr.; parse arg n /*obtain the number from the arg.*/ + if r.n\==0 then return r.n /*Defined? Then return the value.*/ + _=ffr(n-1) + ffs(n-1) /*calculate the FFR & FFS values.*/ + r.n=_; rr._=1; return _ /*assign value to R & RR; return.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +ffs: procedure expose r. s. rr.; parse arg n /*search for ¬null R or S number.*/ + if s.n==0 then do k=1 for n /* [↓] 1st IF is a SHORT CIRCUIT*/ + if s.k\==0 then if r.k\==0 then iterate + call ffr k /*define R.k via FFR subroutine*/ + km=k-1; _=s.km+1 /*the next S number, possibly.*/ + _=_+rr._; s.k=_ /*define an element of S array.*/ + end /*k*/ + return s.n /*return S.n value to the invoker*/ +/*────────────────────────────────────────────────────────────────────────────*/ +ser: errs=errs+1; say '***error***!' arg(1); return diff --git a/Task/Hofstadter-Figure-Figure-sequences/VBScript/hofstadter-figure-figure-sequences.vb b/Task/Hofstadter-Figure-Figure-sequences/VBScript/hofstadter-figure-figure-sequences.vb new file mode 100644 index 0000000000..e915e3a5c5 --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/VBScript/hofstadter-figure-figure-sequences.vb @@ -0,0 +1,70 @@ +'Initialize the r and the s arrays. +Set r = CreateObject("System.Collections.ArrayList") +Set s = CreateObject("System.Collections.ArrayList") + +'Set initial values of r. +r.Add "" : r.Add 1 + +'Set initial values of s. +s.Add "" : s.Add 2 + +'Populate the r and the s arrays. +For i = 2 To 1000 + ffr(i) + ffs(i) +Next + +'r function +Function ffr(n) + r.Add r(n-1)+s(n-1) +End Function + +'s function +Function ffs(n) + 'index is the value of the last element of the s array. + index = s(n-1)+1 + Do + 'Add to s if the current index is not in the r array. + If r.IndexOf(index,0) = -1 Then + s.Add index + Exit Do + Else + index = index + 1 + End If + Loop +End Function + +'Display the first 10 values of r. +WScript.StdOut.Write "First 10 Values of R:" +WScript.StdOut.WriteLine +For j = 1 To 10 + If j = 10 Then + WScript.StdOut.Write "and " & r(j) + Else + WScript.StdOut.Write r(j) & ", " + End If +Next +WScript.StdOut.WriteBlankLines(2) + +'Show that the first 40 values of r plus the first 960 values of s include all the integers from 1 to 1000 exactly once. +'The idea here is to create another array(integer) with 1000 elements valuing from 1 to 1000. Go through the first 40 values +'of the r array and remove the corresponding element in the integer array. Do the same thing with the first 960 values of +'the s array. If the resultant count of the integer array is 0 then it is a pass. +Set integers = CreateObject("System.Collections.ArrayList") +For k = 1 To 1000 + integers.Add k +Next +For l = 1 To 960 + If l <= 40 Then + integers.Remove(r(l)) + End If + integers.Remove(s(l)) +Next +WScript.StdOut.Write "Test for the first 1000 integers: " +If integers.Count = 0 Then + WScript.StdOut.Write "Passed!!!" + WScript.StdOut.WriteLine +Else + WScript.StdOut.Write "Miserably Failed!!!" + WScript.StdOut.WriteLine +End If diff --git a/Task/Hofstadter-Q-sequence/Eiffel/hofstadter-q-sequence.e b/Task/Hofstadter-Q-sequence/Eiffel/hofstadter-q-sequence.e index 75962b195d..bfa485ff1f 100644 --- a/Task/Hofstadter-Q-sequence/Eiffel/hofstadter-q-sequence.e +++ b/Task/Hofstadter-Q-sequence/Eiffel/hofstadter-q-sequence.e @@ -1,51 +1,60 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - local - count,i: INTEGER - do - io.put_string ("%NFirst ten numbers: %N") - test:=seq (10) - across test as ar loop io.put_string (ar.item.out + "%T") end - test:= seq (100000) - io.put_string ("1000th:%N") - io.put_integer (test[1000]) - io.put_string ("%NNumber of Flips:%N") - from i:=2 - until i>100000 - loop - if test[i ]< test[i-1] then - count:= count+1 + -- Test output of the feature hofstadter_q_sequence. + local + count, i: INTEGER + test: ARRAY [INTEGER] + do + io.put_string ("%NFirst ten numbers: %N") + test := hofstadter_q_sequence (10) + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + test := hofstadter_q_sequence (100000) + io.put_string ("1000th:%N") + io.put_integer (test [1000]) + io.put_string ("%NNumber of Flips:%N") + from + i := 2 + until + i > 100000 + loop + if test [i] < test [i - 1] then + count := count + 1 + end + i := i + 1 end - i:= i+1 + io.put_integer (count) end - io.put_integer (count) - end - test: ARRAY[INTEGER] - seq(lim: INTEGER): ARRAY[INTEGER] + hofstadter_q_sequence (lim: INTEGER): ARRAY [INTEGER] + -- Hofstadter Q Sequence up to 'lim'. require - lim_positive: lim>0 + lim_positive: lim > 0 local - q: ARRAY[INTEGER] + q: ARRAY [INTEGER] i: INTEGER do - create q.make_filled(1, 1, lim) - q[1]:= 1 - q[2]:= 1 + create Result.make_filled (1, 1, lim) + Result [1] := 1 + Result [2] := 1 from - i:= 3 + i := 3 until - i> lim + i > lim loop - q[i]:= q[i-q[i-1]]+q[i-q[i-2]] - i:= i+1 + Result [i] := Result [i - Result [i - 1]] + Result [i - Result [i - 2]] + i := i + 1 end - Result:= q end + end diff --git a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-1.pl b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-1.pl index 2b16e62a90..bd865e3c3e 100644 --- a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-1.pl +++ b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-1.pl @@ -1,21 +1,5 @@ -#!/usr/bin/perl -use warnings; -use strict; - -my @hofstadters = ( 1 , 1 ); -while ( @hofstadters < 100000 ) { - my $nextn = @hofstadters + 1; -# array index counting starts at 0 , so we have to subtract 1 from the numbers! - push @hofstadters , $hofstadters [ $nextn - 1 - $hofstadters[ $nextn - 1 - 1 ] ] - + $hofstadters[ $nextn - 1 - $hofstadters[ $nextn - 2 - 1 ]]; -} -for my $i ( 0..9 ) { - print "$hofstadters[ $i ]\n"; -} -print "The 1000'th term is $hofstadters[ 999 ]!\n"; -my $less_than_preceding = 0; -for my $i ( 0..99998 ) { - $less_than_preceding++ if $hofstadters[ $i + 1 ] < $hofstadters[ $i ]; -} -print "Up to and including the 100000'th term, $less_than_preceding terms are less " . - "than their preceding terms!\n"; +my @Q = (0,1,1); +push @Q, $Q[-$Q[-1]] + $Q[-$Q[-2]] for 1..100_000; +say "First 10 terms: [@Q[1..10]]"; +say "Term 1000: $Q[1000]"; +say "Terms less than preceding in first 100k: ",scalar(grep { $Q[$_] < $Q[$_-1] } 2..100000); diff --git a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-2.pl b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-2.pl index 4c950b19f9..2b16e62a90 100644 --- a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-2.pl +++ b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-2.pl @@ -1,35 +1,21 @@ -#!perl -use strict; +#!/usr/bin/perl use warnings; -package Hofstadter; -sub TIEARRAY { - bless [undef, 1, 1], shift; +use strict; + +my @hofstadters = ( 1 , 1 ); +while ( @hofstadters < 100000 ) { + my $nextn = @hofstadters + 1; +# array index counting starts at 0 , so we have to subtract 1 from the numbers! + push @hofstadters , $hofstadters [ $nextn - 1 - $hofstadters[ $nextn - 1 - 1 ] ] + + $hofstadters[ $nextn - 1 - $hofstadters[ $nextn - 2 - 1 ]]; } -sub FETCH { - my ($self, $n) = @_; - die if $n < 1; - if( $n > $#$self ) { - my $start = $#$self + 1; - $#$self = $n; # pre-allocate for efficiency - for my $nn ( $start .. $n ) { - my ($a, $b) = (1, 2); - $_ = $self->[ $nn - $_ ] for $a, $b; - $_ = $self->[ $nn - $_ ] for $a, $b; - $self->[$nn] = $a + $b; - } - } - $self->[$n]; +for my $i ( 0..9 ) { + print "$hofstadters[ $i ]\n"; } - -package main; - -tie my (@q), "Hofstadter"; - -print "@q[1..10]\n"; -print $q[1000], "\n"; - -my $count = 0; -for my $n ( 2 .. 100_000 ) { - $count++ if $q[$n] < $q[$n - 1]; +print "The 1000'th term is $hofstadters[ 999 ]!\n"; +my $less_than_preceding = 0; +for my $i ( 0..99998 ) { + $less_than_preceding++ if $hofstadters[ $i + 1 ] < $hofstadters[ $i ]; } -print "Extra credit: $count\n"; +print "Up to and including the 100000'th term, $less_than_preceding terms are less " . + "than their preceding terms!\n"; diff --git a/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-3.pl b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-3.pl new file mode 100644 index 0000000000..4c950b19f9 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Perl/hofstadter-q-sequence-3.pl @@ -0,0 +1,35 @@ +#!perl +use strict; +use warnings; +package Hofstadter; +sub TIEARRAY { + bless [undef, 1, 1], shift; +} +sub FETCH { + my ($self, $n) = @_; + die if $n < 1; + if( $n > $#$self ) { + my $start = $#$self + 1; + $#$self = $n; # pre-allocate for efficiency + for my $nn ( $start .. $n ) { + my ($a, $b) = (1, 2); + $_ = $self->[ $nn - $_ ] for $a, $b; + $_ = $self->[ $nn - $_ ] for $a, $b; + $self->[$nn] = $a + $b; + } + } + $self->[$n]; +} + +package main; + +tie my (@q), "Hofstadter"; + +print "@q[1..10]\n"; +print $q[1000], "\n"; + +my $count = 0; +for my $n ( 2 .. 100_000 ) { + $count++ if $q[$n] < $q[$n - 1]; +} +print "Extra credit: $count\n"; diff --git a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-1.rexx b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-1.rexx index 5947996488..e19fc22129 100644 --- a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-1.rexx +++ b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-1.rexx @@ -1,24 +1,33 @@ -/*REXX program to generate Hofstadter Q sequence for any N. */ -q.=1 /*negative #s won't have values displayed.*/ -call HofstadterQ 10 -call HofstadterQ -1000; say; say '1000th value='result; say -call HofstadterQ -100000 -downs=0; do j=2 to 100000; jm=j-1 +/*REXX program generates Hofstadter Q sequence for any N. */ +parse arg a b c d . /*get optional values from the CL*/ +if \datatype(a,'W') then a= 10 /*A not specified? Use default.*/ +if \datatype(b,'W') then b= -1000 /*B " " " " */ +if \datatype(c,'W') then c= -100000 /*C " " " " */ +if \datatype(d,'W') then d=-1000000 /*D " " " " */ +q.=1; ac= abs(c) /* [↑] neg #s don't show values.*/ +call HofstadterQ a +call HofstadterQ b; say; say abs(b)th(b) 'value is:' result; say +call HofstadterQ c +downs=0; do j=2 for ac-1; jm=j-1 downs=downs + (q.j2 then if q.j==1 then do; jm1=j-1; jm2=j-2 - _1=j-q.jm1; _2=j-q.jm2 +HofstadterQ: procedure expose q.; parse arg x 1 ox /*get # to gen thru.*/ + /* [↑] OX is the same as X.*/ +x=abs(x) /*use the absolute value for X. */ +w=length(x) /*use for right justified output.*/ + do j=1 for x /* [↓] use short-circuit IF test*/ + if j>2 then if q.j==1 then do; jm1=j-1; jm2=j-2 + _1=j-q.jm1; _2=j-q.jm2 q.j=q._1+q._2 end - if ox>0 then say right(j,L) right(q.j,L) /*if X>0, tell*/ + if ox>0 then say right(j,w) right(q.j,w) /*show if OX>0*/ end /*j*/ -return q.x /*return the Xth term to caller.*/ +return q.x /*return the │X│th term to caller*/ +/*──────────────────────────────────TH subroutine───────────────────────────────────────────────*/ +th: procedure; parse arg x; x=abs(x); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) diff --git a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-2.rexx b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-2.rexx index 89aca28b27..f0de592ffc 100644 --- a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-2.rexx +++ b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-2.rexx @@ -1,23 +1,31 @@ -/*REXX program to generate Hofstadter Q sequence for any N. */ -q.=1 /*negative #s won't have values displayed.*/ -call HofstadterQ 10 -call HofstadterQ -1000; say; say '1000th value='result; say -call HofstadterQ -100000 -downs=0; do j=2 to 100000; jm=j-1 - downs=downs + (q.j2 then if q.j==1 then q.j=q(j-q(j-1)) + q(j-q(j-2)) - if ox>0 then say right(j,L) right(q.j,L) /*if X>0, tell*/ + if ox>0 then say right(j,w) right(q.j,w) /*if X>0, tell*/ end /*j*/ -return q.x /*return the Xth term to caller.*/ +return q.x /*return the │X│th term to caller*/ /*──────────────────────────────────Q subroutine────────────────────────*/ q: parse arg ?; return q.? /*return value of Q.? to invoker.*/ +/*──────────────────────────────────TH subroutine───────────────────────────────────────────────*/ +th: procedure; parse arg x; x=abs(x); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) diff --git a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-3.rexx b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-3.rexx index 088c7705ee..cc1ac71966 100644 --- a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-3.rexx +++ b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-3.rexx @@ -1,25 +1,34 @@ -/*REXX program to generate Hofstadter Q sequence for any N. */ -q.=0; q.1=1; q.2=1 /*negative #s won't have values displayed.*/ -call HofstadterQ 10 -call HofstadterQ -1000; say; say '1000th value='result; say -call HofstadterQ -100000 -downs=0; do j=2 to 100000; jm=j-1 +/*REXX pgm generates Hofstadter Q sequence (using recursion) for any N. */ +parse arg a b c . /*get optional values from the CL*/ +if \datatype(a,'W') then a= 10 /*A not specified? Use default.*/ +if \datatype(b,'W') then b= -1000 /*B " " " " */ +if \datatype(c,'W') then c= -100000 /*C " " " " */ +if \datatype(d,'W') then d=-1000000 /*D " " " " */ +q.=0; q.1=1; q.2=1; ac= abs(c) /* [↑] neg #s don't show values.*/ +call HofstadterQ a +call HofstadterQ b; say; say abs(b)th(b) 'value is:' result; say +call HofstadterQ c +downs=0; do j=2 for ac-1; jm=j-1 downs=downs + (q.j0 then say right(j,L) right(q.j,L) /*if X>0, tell*/ + if ox>0 then say right(j,w) right(q.j,w) /*show if OX>0*/ end /*j*/ return q.x /*return the Xth term to caller.*/ /*──────────────────────────────────QR subroutine───────────────────────*/ QR: procedure expose q.; parse arg n /*function is recursive. */ if q.n==0 then q.n=QR(n-QR(n-1)) + QR(n-QR(n-2)) /*¬defined? Define it*/ return q.n /*return with the value. */ +/*──────────────────────────────────TH subroutine───────────────────────────────────────────────*/ +th: procedure; parse arg x; x=abs(x); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) diff --git a/Task/Hofstadter-Q-sequence/Rust/hofstadter-q-sequence.rust b/Task/Hofstadter-Q-sequence/Rust/hofstadter-q-sequence.rust new file mode 100644 index 0000000000..179e01d213 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Rust/hofstadter-q-sequence.rust @@ -0,0 +1,26 @@ +fn hofq(q: &mut Vec, x : u32) -> u32 { + let cur_len=q.len()-1; + let i=x as usize; + if i>cur_len { + // extend storage + q.reserve(i+1); + for j in (cur_len+1)..(i+1) { + let qj=(q[j-q[j-1] as usize]+q[j-q[j-2] as usize]) as u32; + q.push(qj); + } + } + q[i] +} + +fn main() { + let mut q_memo: Vec=vec![0,1,1]; + let mut q=|i| {hofq(&mut q_memo, i)}; + for i in 1..11 { + println!("Q({})={}", i, q(i)); + } + println!("Q(1000)={}", q(1000)); + let q100001=q(100_000); // precompute all + println!("Q(100000)={}", q100000); + let nless=(1..100_000).fold(0,|s,i|{if q(i+1)1- : 9`#v_2*4+>1-:3`#v_v + ^\+*"(2":< ^\*"d":< >$ v +v"Pentcst"9"Trinity"9"Corpus"+550< +>9"nsnecsA"9"retsaE"9"raeY">:#,_$v + MarAprMayJun +v-/4::/"d"\*/2"&"%/2"&"::,9.:_@#:< +>\:8+55*/-1+3/-35*++65*%00p::"d"v, +v:%7+*84+*2%4/"d"\-g00-%4\*2/4:%<+ +>10p","2/*00g56+*+\"&"2/%+19"2"*v5 +v \+55\7\4\0+/2","-\+g01g00*7/+<5 +>"'"\>:9\>:156*+`!#v_156*+-\3v>$$^ + +9,^ ^\+3\-*65_v#`*65:\+ <^_ +*84,g4+1,g4:+1,g4:\< >:#\!#.^#, diff --git a/Task/Holidays-related-to-Easter/Elixir/holidays-related-to-easter.elixir b/Task/Holidays-related-to-Easter/Elixir/holidays-related-to-easter.elixir new file mode 100644 index 0000000000..4026276b23 --- /dev/null +++ b/Task/Holidays-related-to-Easter/Elixir/holidays-related-to-easter.elixir @@ -0,0 +1,41 @@ +defmodule Holiday do + @offsets [ Easter: 0, Ascension: 39, Pentecost: 49, Trinity: 56, Corpus: 60 ] + @mon { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" } + + def easter_date(year) do + a = rem(year, 19) + b = div(year, 100) + c = rem(year, 100) + d = div(b, 4) + e = rem(b, 4) + f = div((b + 8), 25) + g = div((b - f + 1), 3) + h = rem((19*a + b - d - g + 15), 30) + i = div(c, 4) + k = rem(c, 4) + l = rem((32 + 2*e + 2*i - h - k), 7) + m = div((a + 11*h + 22*l), 451) + numerator = h + l - 7*m + 114 + month = div(numerator, 31) + day = rem(numerator, 31) + 1 + {year, month, day} + end + + defp holidays(year) do + IO.write String.rjust("#{year}:", 5) + gday = :calendar.date_to_gregorian_days(easter_date(year)) + Enum.map_join(Keyword.values(@offsets), fn d -> + {_year, month, day} = :calendar.gregorian_days_to_date(gday + d) + String.rjust("#{day} #{elem(@mon, month-1)}", 11) + end) + end + + def task do + IO.puts "Year:" <> Enum.map_join(Keyword.keys(@offsets), &String.rjust("#{&1}",11)) + Enum.each(Enum.take_every(400..2100, 100), fn year -> IO.puts holidays(year) end) + IO.puts "" + Enum.each(2010..2020, fn year -> IO.puts holidays(year) end) + end +end + +Holiday.task diff --git a/Task/Holidays-related-to-Easter/PARI-GP/holidays-related-to-easter.pari b/Task/Holidays-related-to-Easter/PARI-GP/holidays-related-to-easter.pari new file mode 100644 index 0000000000..1d537ec4b8 --- /dev/null +++ b/Task/Holidays-related-to-Easter/PARI-GP/holidays-related-to-easter.pari @@ -0,0 +1,80 @@ +/* + * Normalized Julian Day Number from date (base 1899-12-30 00:00:00) + * D = Vec [year, month, day] + * return day number + */ +njd(D) = +{ + my (m, y); + + if (D[2] > 2, y = D[1]; m = D[2] + 1, y = D[1] - 1; m = D[2] + 13); + + (1461 * y) \ 4 + (306001 * m) \ 10000 + D[3] - 694024 + +/* Calendar reform ? */ + + if (100 * (100 * D[1] + D[2]) + D[3] > 15821004, 2 - y \ 100 + y \ 400) +} + +/* + * Date from Normalized Julian Day Number (base 1899-12-30 00:00:00) + * n = Normalized Julian Day Number + * return Vec [year, month, day] + */ +njdate(n) = +{ + my (a = n + 2415019, b, c, d, m, D, M, Y); + +/* Calendar reform ? */ + if (a >= 2299161, b = (4 * a - 7468865) \ 146097; a += 1 + b - b \ 4); + + a += 1524; + b = (20 * a - 2442) \ 7305; + c = (1461 * b) \ 4; + d = ((a - c) * 10000) \ 306001; + m = d - 1 - 12 * (d > 13); + + [b - 4715 - (m > 2), m, a - c - (306001 * d) \ 10000] +} + +/* + * Date of Easter + * Y = year + * return Vec [year, month, day] + */ +easter(y) = +{ + my (a, b, d, m); + + if (y > 1582, /* calendar reform ? */ +/* Gregorian Easter */ + a = y % 19; + b = y % 100; + d = y \ 100; + m = (19 * a + d - d \ 4 - (d - (d + 8) \ 25 + 1) \ 3 + 15) % 30; + d = (32 + (d % 4) * 2 + (b \ 4) * 2 - m - b % 4) % 7; + m += d - (a + 11 * m + 22 * d) \ 451 * 7 + 114; + , +/* Julian Easter */ + d = ((y % 19) * 19 + 15) % 30; + m = d + ((y % 4) * 2 + (y % 7) * 4 - d + 34) % 7 + 114; + ); + + [y, m \ 31, m % 31 + 1] +} + +holiday(y) = +{ + my (e = njd(easter(y)), n); + + n = njdate(e ); printf("%4d: Easter: %02d-%02d, ", y, n[2], n[3]); + n = njdate(e+39); printf("Ascension: %02d-%02d, ", n[2], n[3]); + n = njdate(e+49); printf("Pentecost: %02d-%02d, ", n[2], n[3]); + n = njdate(e+56); printf("Trinity: %02d-%02d, ", n[2], n[3]); + n = njdate(e+60); printf("Corpus: %02d-%02d\n", n[2], n[3]); +} + +print("Christian holidays, related to Easter, for years from 400 to 2100 CE:"); +forstep (y = 400, 2100, 100, holiday(y)); + +print("\nChristian holidays, related to Easter, for years from 2010 to 2020 CE:"); +for (y = 2010, 2020, holiday(y)); diff --git a/Task/Holidays-related-to-Easter/Perl-6/holidays-related-to-easter.pl6 b/Task/Holidays-related-to-Easter/Perl-6/holidays-related-to-easter.pl6 index 63874f8433..3b823c82c2 100644 --- a/Task/Holidays-related-to-Easter/Perl-6/holidays-related-to-easter.pl6 +++ b/Task/Holidays-related-to-Easter/Perl-6/holidays-related-to-easter.pl6 @@ -35,6 +35,6 @@ sub cholidays($year) { } } -for (400,500 ... 2000), (2010 ... 2020), 2100 -> $year { +for flat (400,500 ... 2000), (2010 ... 2020), 2100 -> $year { cholidays($year); } diff --git a/Task/Honeycombs/Java/honeycombs-1.java b/Task/Honeycombs/Java/honeycombs-1.java index c2ce1e2aa6..dbc6a6093e 100644 --- a/Task/Honeycombs/Java/honeycombs-1.java +++ b/Task/Honeycombs/Java/honeycombs-1.java @@ -4,19 +4,16 @@ public class Honeycombs extends JFrame { - HoneycombsPanel panel; - public static void main(String[] args) { - JFrame f = new Honeycombs(); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.setVisible(true); + SwingUtilities.invokeLater(() -> { + JFrame f = new Honeycombs(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setVisible(true); + }); } public Honeycombs() { - Container content = getContentPane(); - content.setLayout(new BorderLayout()); - panel = new HoneycombsPanel(); - content.add(panel, BorderLayout.CENTER); + add(new HoneycombsPanel(), BorderLayout.CENTER); setTitle("Honeycombs"); setResizable(false); pack(); diff --git a/Task/Honeycombs/Mathematica/honeycombs.math b/Task/Honeycombs/Mathematica/honeycombs.math new file mode 100644 index 0000000000..880628ffe0 --- /dev/null +++ b/Task/Honeycombs/Mathematica/honeycombs.math @@ -0,0 +1,33 @@ +hexagon[{x_, y_}] := + Polygon[Transpose[{{1/2, 1/4, -1/4, -1/2, -1/4, 1/4} + + x, {0, Sqrt[3]/4, Sqrt[3]/4, 0, -Sqrt[3]/4, -Sqrt[3]/4} + y}]]; +off = Transpose[{ConstantArray[0, 20], {0, 0, 0, 0, Sqrt[3]/4, + Sqrt[3]/4, Sqrt[3]/4, Sqrt[3]/4, 0, 0, 0, 0, Sqrt[3]/4, + Sqrt[3]/4, Sqrt[3]/4, Sqrt[3]/4, 0, 0, 0, 0}}]; +DynamicModule[{letters = RandomSample[CharacterRange["A", "Z"], 20], + blue = False, cols = {}, + locs = Tuples[{Range[1, 4, 3/4], + Range[1, 1 + (3 Sqrt[3])/2, Sqrt[3]/2]}] - off}, + EventHandler[ + Dynamic[Graphics[{EdgeForm[{Thick, Black}], LightGray, + hexagon /@ locs, {#[[1]], hexagon[#[[2]]]} & /@ cols, Black, + MapThread[ + Text, {Style[#, FontSize -> Large] & /@ letters, locs}], Red, + Text[Style[ + StringJoin[ + letters[[FirstPosition[locs, #[[2]]][[1]]]] & /@ + Cases[cols, {Red, _}][[All, 2]]], + FontSize -> 40], {5/2, -1/2}, {Right, Center}], Blue, + Text[Style[ + StringJoin[ + letters[[FirstPosition[locs, #[[2]]][[1]]]] & /@ + Cases[cols, {Blue, _}][[All, 2]]], + FontSize -> 40], {5/2, -1/2}, {Left, Center}]}, + PlotRange -> {{-1, 6}, Automatic}, + ImageSize -> Large]], {"MouseClicked" :> + If[! MemberQ[cols[[All, 2]], + Nearest[locs, MousePosition["Graphics"]][[1]]], + AppendTo[ + cols, {If[blue, Blue, Red], + Nearest[locs, MousePosition["Graphics"]][[1]]}]; + blue = ! blue]}]] diff --git a/Task/Horizontal-sundial-calculations/Forth/horizontal-sundial-calculations.fth b/Task/Horizontal-sundial-calculations/Forth/horizontal-sundial-calculations.fth index d9c47914ad..282ed35e08 100644 --- a/Task/Horizontal-sundial-calculations/Forth/horizontal-sundial-calculations.fth +++ b/Task/Horizontal-sundial-calculations/Forth/horizontal-sundial-calculations.fth @@ -8,12 +8,12 @@ cr ." Enter longitude: " faccept cr ." Enter legal meridian: " - faccept f- ( sin[latitude] longitude ) + faccept f- fnegate ( sin[latitude] -longitude ) cr ." Hour : HourAngle , DialAngle" 7 -6 do - cr i . ." : " - fover fover fnegate i 15 * s>d d>f f+ + cr i 4 .r ." : " + fover fover i 15 * s>d d>f f+ fdup f. ." , " - >radians ftan f* fatan >degrees f. + >radians fsincos fswap frot f* fswap fatan2 >degrees f. loop fdrop fdrop ; diff --git a/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx b/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx index a66bb39a51..c7d03107f7 100644 --- a/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx +++ b/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx @@ -1,33 +1,32 @@ -/*REXX program shows hour/sun hour angle/dial hour line angle, 6am─►6pm.*/ -numeric digits 60 /*better overkill then underkill. */ +/*REXX pgm shows: hour, sun hour angle, dial hour line angle, 6am ───► 6pm*/ +numeric digits 60 /*better overkill then underkill for dig*/ -parse arg lat lng mer . /*get the arguments (if any). */ - /*If none specified, then use the */ - /*default of Jules Verne's Lincoln*/ - /*Island, aka Ernest Legouve Reef.*/ +parse arg lat lng mer . /*get the optional arguments from the CL*/ + /*None specified? Then use the default of Jules */ + /*Verne's Lincoln Island, aka Ernest Legouve Reef.*/ -if lat=='' | lat==',' then lat=-4.95 /*No argument? Then use default.*/ -if lng=='' | lng==',' then lng=-150.5 /*No argument? Then use default.*/ -if mer=='' | mer==',' then mer=-150 /*No argument? Then use default.*/ -L=max(length(lat),length(lng),length(mer)) - say ' latitude:' right(lat,L) - say ' longitude:' right(lng,L) - say ' legal meridian:' right(mer,L) +if lat=='' | lat==',' then lat=-4.95 /*Not specified? Then use the default.*/ +if lng=='' | lng==',' then lng=-150.5 /* " " " " " " */ +if mer=='' | mer==',' then mer=-150 /* " " " " " " */ +L=max(length(lat), length(lng), length(mer)) + say ' latitude:' right(lat,L) + say ' longitude:' right(lng,L) + say ' legal meridian:' right(mer,L) sineLat=sin(d2r(lat)) -w1=max(length('hour'),length('midnight'))+2 +w1=max(length('hour') ,length('midnight'))+2 w2=max(length('sun hour') ,length('angle'))+2 w3=max(length('dial hour'),length('line angle'))+2 -indent=left('',30) /*make presentation prettier. */ -say indent center(' ',w1) center('sun hour',w2) center('dial hour' ,w3) -say indent center('hour',w1) center('angle' ,w2) center('line angle',w3) -call sep /*add separator line for eyeballs*/ +indent=left('',30) /*make the presentation prettier. */ +say indent center(' ',w1) center('sun hour',w2) center('dial hour' ,w3) +say indent center('hour',w1) center('angle' ,w2) center('line angle',w3) +call sep /*add a separator line for the eyeballs*/ - do h=-6 to 6 /*Okey dokey then, let's get busy*/ + do h=-6 to 6 /*Okey dokey then, let's get busy. */ select - when abs(h)==12 then hc='midnight' /*above artic circle ? */ - when h<0 then hc=-h 'am' /*convert hour for human beans. */ - when h==0 then hc='noon' /* ... easy to understand now. */ - when h>0 then hc=h 'pm' /* ... even meaningfull. */ + when abs(h)==12 then hc='midnight' /*above the arctic circle? */ + when h<0 then hc=-h 'am' /*convert the hour for human beans. */ + when h==0 then hc='noon' /* ... easier to understand now. */ + when h>0 then hc=h 'pm' /* ... even more meaningful. */ end /*select*/ hra=15*h-lng+mer hla=r2d(Atan(sineLat*tan(d2r(hra)))) @@ -35,50 +34,49 @@ call sep /*add separator line for eyeballs*/ end /*h*/ call sep -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────subroutines─────────────────────────*/ -/*looking at subroutines is like looking at saugages being made. Don't.*/ -sep: say indent copies('═',w1) copies('═',w2) copies('═',w3); return -pi: return, /*a bit of overkill, but hey !! */ -3.1415926535897932384626433832795028841971693993751058209749445923078164062862 - /*Note: the real PI subroutine returns PI's accuracy that */ - /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ - /*John Machin's formula is used for calculating more digits. */ - -d2d: return arg(1)//360 /*normalize degrees►1 unit circle*/ -d2r: return r2r(arg(1)*pi()/180) /*convert degrees ──► radians. */ -r2d: return d2d((arg(1)*180/pi())) /*convert radians ──► degrees. */ -r2r: return arg(1)//(2*pi()) /*normalize radians►1 unit circle*/ -tan: procedure; arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ -tanErr: call tellErr 'tan('||x") causes division by zero, X="||x +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────subroutines───────────────────────────────*/ +sep: say indent copies('═',w1) copies('═',w2) copies('═',w3); return +d2d: return arg(1) // 360 /*normalize degrees ──► a unit circle. */ +d2r: return r2r(arg(1)*pi() / 180) /*convert degrees ──► radians. */ +r2d: return d2d((arg(1)*180 / pi())) /*convert radians ──► degrees. */ +r2r: return arg(1) //(pi()*2) /*normalize radians ──► a unit circle. */ +tan: procedure; parse arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ +tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 -AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X='||x -sqrtErr: call tellErr "sqrt(x), X can't be negative, X="||x -AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X='||x -Acos: procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) +AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X=' ||x +sqrtErr: call tellErr "sqrt(x), X can't be negative, X=" || x +AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X=' ||x +Acos: procedure; arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) Atan: procedure; arg x; if abs(x)=1 then return pi()/4*sign(x) return Asin(x/sqrt(1+x**2)) -sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3) - if abs(x)=pi() then return 0; return .sinCos(x,x,1) +sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3) + if abs(x)=pi() then return 0; return .sinCos(x,x,1) + +cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi=pi*.5 + numeric fuzz min(6,digits()-3); if a=pi() then return -1 + if a=hpi | a=hpi*3 then return 0; if a=pi()/3 then return .5 + if a=pi()*2/3 then return -.5; return .sinCos(1,1,-1) -cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9) - if a=pi() then return -1; if a=pi()/2 | a=2*pi() then return 0 - if a=pi()/3 then return .5; if a=2*pi()/3 then return -.5 - return .sincos(1,1,-1) .sinCos: parse arg z,_,i; x=x*x; p=z - do k=2 by 2; _=-_*x/(k*(k+i));z=z+_; if z=p then leave;p=z;end; return z + do k=2 by 2; _=-_*x/(k*(k+i));z=z+_; if z=p then leave; p=z; end; return z Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end return z -sqrt: procedure; parse arg x; if x=0 then return 0;d=digits();numeric digits 11 - g=.sqrtGuess(); do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end - numeric digits d; return g/1 -.sqrtGuess: if x<0 then call sqrtErr; numeric form scientific; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 +pi: pi=, /*a bit of an overkill, but hey !! */ + 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 + return pi /*Note: the real PI subroutine returns PI's accuracy that */ + /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ + /*John Machin's formula is used for calculating more digits. */ + +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Horners-rule-for-polynomial-evaluation/360-Assembly/horners-rule-for-polynomial-evaluation.360 b/Task/Horners-rule-for-polynomial-evaluation/360-Assembly/horners-rule-for-polynomial-evaluation.360 new file mode 100644 index 0000000000..7243150d6c --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/360-Assembly/horners-rule-for-polynomial-evaluation.360 @@ -0,0 +1,21 @@ +* Horner's rule for polynomial evaluation - 07/10/2015 +HORNER CSECT + USING HORNER,R15 set base register + SR R5,R5 accumulator=0 + LA R2,N i=number_of_coeff +LOOP M R4,X accumulator=accumulator*x + LR R1,R2 i + SLA R1,2 i*4 + L R3,COEF-4(R1) coef(i) + AR R5,R3 accumulator=accumulator+coef(i) + BCT R2,LOOP i=i-1; loop n times + XDECO R5,PG edit accumulator + XPRNT PG,12 print buffer + XR R15,R15 set return code + BR R14 return to caller +COEF DC F'-19',F'7',F'-4',F'6' <== input values +X DC F'3' <== input value +N EQU (X-COEF)/4 number of coefficients +PG DS CL12 buffer + YREGS + END HORNER diff --git a/Task/Horners-rule-for-polynomial-evaluation/AWK/horners-rule-for-polynomial-evaluation.awk b/Task/Horners-rule-for-polynomial-evaluation/AWK/horners-rule-for-polynomial-evaluation.awk new file mode 100644 index 0000000000..8975f5d765 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/AWK/horners-rule-for-polynomial-evaluation.awk @@ -0,0 +1,12 @@ +#!/usr/bin/awk -f +function horner(x, A) { + acc = 0; + for (i = length(A); 0 List.foldr(list, 0, fn(c,acc)-> x*acc+c end) end + +IO.puts horner.([-19,7,-4,6], 3) diff --git a/Task/Horners-rule-for-polynomial-evaluation/Emacs-Lisp/horners-rule-for-polynomial-evaluation.l b/Task/Horners-rule-for-polynomial-evaluation/Emacs-Lisp/horners-rule-for-polynomial-evaluation.l new file mode 100644 index 0000000000..cc0312982b --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Emacs-Lisp/horners-rule-for-polynomial-evaluation.l @@ -0,0 +1,5 @@ +(defun horner (coeffs x) + (reduce #'(lambda (coef acc) (+ (* acc x) coef) ) + coeffs :from-end t :initial-value 0) ) + +(horner '(-19 7 -4 6) 3) diff --git a/Task/Horners-rule-for-polynomial-evaluation/JavaScript/horners-rule-for-polynomial-evaluation.js b/Task/Horners-rule-for-polynomial-evaluation/JavaScript/horners-rule-for-polynomial-evaluation.js index 1ee7474e61..2bf6fb0ffa 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/JavaScript/horners-rule-for-polynomial-evaluation.js +++ b/Task/Horners-rule-for-polynomial-evaluation/JavaScript/horners-rule-for-polynomial-evaluation.js @@ -1,4 +1,4 @@ function horner(coeffs, x) { - return coeffs.reduceRight(function(acc, coeff) {return(acc * x + coeff)}, 0); + return coeffs.reduceRight( function(acc, coeff) { return(acc * x + coeff) }, 0); } -print(horner([-19,7,-4,6],3)); // ==> 128 +console.log(horner([-19,7,-4,6],3)); // ==> 128 diff --git a/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-2.pl6 b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-2.pl6 index 01f0b18d27..17455ac1da 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-2.pl6 +++ b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-2.pl6 @@ -3,4 +3,4 @@ multi horner(Pair $c, $x) { $c.key + $x * horner( $c.value, $x ) } -print horner( [=>](-19, 7, -4, 6 ), 3 ); +say horner( [=>](-19, 7, -4, 6 ), 3 ); diff --git a/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-3.pl6 b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-3.pl6 index bfd0fb9455..7e5077b49c 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-3.pl6 +++ b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-3.pl6 @@ -1,12 +1,5 @@ -sub infix:(&f, &g) { -> $x { &f(&g($x)) } } - -sub horner ( @c, $x ) { - [\o] map { -> $u { $_ + $x * $u } }, @c; +sub horner ( @coeffs, $x ) { + ([o] map { $_ + $x * * }, @coeffs)(0); } -say map { .(0) }, horner( [ -19, 7, -4, 6 ], 3 ); - -# compute progressive approximations of exp(2) -my @c := 1 X/ 1, [\*] 1 ... *; - -say .(0) for horner( @c, 2 ); +say horner( [ -19, 7, -4, 6 ], 3 ); diff --git a/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-4.pl6 b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-4.pl6 new file mode 100644 index 0000000000..b084ab7926 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Perl-6/horners-rule-for-polynomial-evaluation-4.pl6 @@ -0,0 +1,5 @@ +sub horner ( @coeffs, $x ) { + map { .(0) }, [\o] map { $_ + $x * * }, @coeffs; +} + +say horner( [ 1 X/ (1, |[\*] 1 .. *) ], i*pi )[20]; diff --git a/Task/Horners-rule-for-polynomial-evaluation/PowerShell/horners-rule-for-polynomial-evaluation.psh b/Task/Horners-rule-for-polynomial-evaluation/PowerShell/horners-rule-for-polynomial-evaluation.psh new file mode 100644 index 0000000000..37f9515f91 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/PowerShell/horners-rule-for-polynomial-evaluation.psh @@ -0,0 +1,10 @@ +function horner($coefficients, $x) { + $accumulator = 0 + foreach($i in ($coefficients.Count-1)..0){ + $accumulator = ( $accumulator * $x ) + $coefficients[$i] + } + $accumulator +} +$coefficients = @(-19, 7, -4, 6) +$x = 3 +horner $coefficients $x diff --git a/Task/Horners-rule-for-polynomial-evaluation/Python/horners-rule-for-polynomial-evaluation-3.py b/Task/Horners-rule-for-polynomial-evaluation/Python/horners-rule-for-polynomial-evaluation-3.py new file mode 100644 index 0000000000..5ff0b871a0 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Python/horners-rule-for-polynomial-evaluation-3.py @@ -0,0 +1,3 @@ +>>> import numpy +>>> numpy.polynomial.polynomial.polyval(3, (-19, 7, -4, 6)) +128.0 diff --git a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-1.rust b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-1.rust index d3b5a67ff7..d8ba0a232a 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-1.rust +++ b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-1.rust @@ -1,15 +1,8 @@ -// rust 0.9-pre - -fn horner(v: ~[f64], x: f64) -> f64 { - let mut accum = 0.0; - let vlen = v.len(); - for idx in range(0, vlen) { - accum = accum*x + v[vlen - idx - 1]; - }; - accum +fn horner(v: &[f64], x: f64) -> f64 { + v.iter().rev().fold(0.0, |acc, coeff| acc*x + coeff) } fn main() { - let v : ~[f64] = ~[-19., 7., -4., 6.]; - println!("result: {}", horner(v, 3.0)); + let v = [-19., 7., -4., 6.]; + println!("result: {}", horner(&v, 3.0)); } diff --git a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust index 5fb909779e..75f339540e 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust +++ b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust @@ -1,11 +1,17 @@ -// rust 0.12-nightly +#![feature(zero_one) +use std::num::Zero; +use std::ops::{Mul, Add}; -std::num::zero; - -fn horner(cs:&[T], x:T) -> T { - cs.iter().rev().fold(zero::(), |acc, c| (acc*x) + (*c)) +fn horner(v: &[Arr], x: Arg) -> Out + where Arr: Clone, + Arg: Clone, + Out: Zero + Mul + Add, +{ + v.iter().rev().fold(Zero::zero(), |acc, coeff| acc*x.clone() + coeff.clone()) } fn main() { - println!("{}", horner([-19i, 7, -4, 6], 3i)); + let v = [-19., 7., -4., 6.]; + let output: f64 = horner(&v, 3.0); + println!("result: {}", output); } diff --git a/Task/Horners-rule-for-polynomial-evaluation/VBScript/horners-rule-for-polynomial-evaluation.vb b/Task/Horners-rule-for-polynomial-evaluation/VBScript/horners-rule-for-polynomial-evaluation.vb new file mode 100644 index 0000000000..bd507f6d5a --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/VBScript/horners-rule-for-polynomial-evaluation.vb @@ -0,0 +1,9 @@ +Function horners_rule(coefficients,x) + accumulator = 0 + For i = UBound(coefficients) To 0 Step -1 + accumulator = (accumulator * x) + coefficients(i) + Next + horners_rule = accumulator +End Function + +WScript.StdOut.WriteLine horners_rule(Array(-19,7,-4,6),3) diff --git a/Task/Host-introspection/Frink/host-introspection.frink b/Task/Host-introspection/Frink/host-introspection.frink new file mode 100644 index 0000000000..de45164e9a --- /dev/null +++ b/Task/Host-introspection/Frink/host-introspection.frink @@ -0,0 +1,2 @@ +println["Word size: " + callJava["java.lang.System", "getProperty", "sun.arch.data.model"]] +println["Endianness: " + callJava["java.lang.System", "getProperty", "sun.cpu.endian"]] diff --git a/Task/Host-introspection/Julia/host-introspection.julia b/Task/Host-introspection/Julia/host-introspection.julia new file mode 100644 index 0000000000..012d7134ba --- /dev/null +++ b/Task/Host-introspection/Julia/host-introspection.julia @@ -0,0 +1,8 @@ +print("This host's word size is ", WORD_SIZE, ".") +if ENDIAN_BOM == 0x04030201 + println("And it is a little-endian machine.") +elseif ENDIAN_BOM == 0x01020304 + println("And it is a big-endian machine.") +else + println("ENDIAN_BOM = ", ENDIAN_BOM, ", which is confusing") +end diff --git a/Task/Host-introspection/Perl-6/host-introspection.pl6 b/Task/Host-introspection/Perl-6/host-introspection.pl6 index de9dffe7bb..d02e5eee67 100644 --- a/Task/Host-introspection/Perl-6/host-introspection.pl6 +++ b/Task/Host-introspection/Perl-6/host-introspection.pl6 @@ -1 +1,2 @@ -say $*VM +say $*VM.config; +say pack('N', 123456789).unpack('V') == 123456789 ?? 'big-endian' !! 'little-endian'; diff --git a/Task/Host-introspection/Python/host-introspection.py b/Task/Host-introspection/Python/host-introspection.py index 25a83697cc..d02f7f46ea 100644 --- a/Task/Host-introspection/Python/host-introspection.py +++ b/Task/Host-introspection/Python/host-introspection.py @@ -1,12 +1,14 @@ ->>> import sys, math ->>> int(round(math.log(sys.maxint,2)+1)) # this only works in Python 2.x -32 ->>> import struct ->>> struct.calcsize('i') * 8 -32 +>>> import platform, sys, socket +>>> platform.architecture() +('64bit', 'ELF') +>>> platform.machine() +'x86_64' +>>> platform.node() +'yourhostname' +>>> platform.system() +'Linux' >>> sys.byteorder little ->>> import socket >>> socket.gethostname() -'PADDY3118-RESTING' +'yourhostname' >>> diff --git a/Task/Hostname/Batch-File/hostname.bat b/Task/Hostname/Batch-File/hostname.bat index ecd88aee75..91d25e66aa 100644 --- a/Task/Hostname/Batch-File/hostname.bat +++ b/Task/Hostname/Batch-File/hostname.bat @@ -1 +1 @@ -hostname +Hostname diff --git a/Task/Hostname/Emacs-Lisp/hostname.l b/Task/Hostname/Emacs-Lisp/hostname.l new file mode 100644 index 0000000000..5f9cf273c6 --- /dev/null +++ b/Task/Hostname/Emacs-Lisp/hostname.l @@ -0,0 +1 @@ +(system-name) diff --git a/Task/Hostname/Fortran/hostname.f b/Task/Hostname/Fortran/hostname-1.f similarity index 100% rename from Task/Hostname/Fortran/hostname.f rename to Task/Hostname/Fortran/hostname-1.f diff --git a/Task/Hostname/Fortran/hostname-2.f b/Task/Hostname/Fortran/hostname-2.f new file mode 100644 index 0000000000..c822988863 --- /dev/null +++ b/Task/Hostname/Fortran/hostname-2.f @@ -0,0 +1,38 @@ +program test_hostname + use, intrinsic :: iso_c_binding + implicit none + interface !to function: int gethostname(char *name, size_t namelen); + integer(c_int) function gethostname(name, namelen) bind(c) + use, intrinsic :: iso_c_binding, only: c_char, c_int, c_size_t + integer(c_size_t), value, intent(in) :: namelen + character(len=1,kind=c_char), dimension(namelen), intent(inout) :: name + end function gethostname + end interface + integer(c_int) :: status + integer,parameter :: HOST_NAME_MAX=255 + character(kind=c_char,len=1),dimension(HOST_NAME_MAX) :: cstr_hostname + integer(c_size_t) :: lenstr + character(len=:),allocatable :: hostname + lenstr = HOST_NAME_MAX + status = gethostname(cstr_hostname, lenstr) + hostname = c_to_f_string(cstr_hostname) + write(*,*) hostname, len(hostname) + + contains + ! convert c_string to f_string + pure function c_to_f_string(c_string) result(f_string) + use, intrinsic :: iso_c_binding, only: c_char, c_null_char + character(kind=c_char,len=1), intent(in) :: c_string(:) + character(len=:), allocatable :: f_string + integer i, n + i = 1 + do + if (c_string(i) == c_null_char) exit + i = i + 1 + end do + n = i - 1 ! exclude c_null_char + allocate(character(len=n) :: f_string) + f_string = transfer(c_string(1:n), f_string) + end function c_to_f_string + +end program test_hostname diff --git a/Task/Hostname/Go/hostname.go b/Task/Hostname/Go/hostname.go index f1873c75e0..7d0d13c61c 100644 --- a/Task/Hostname/Go/hostname.go +++ b/Task/Hostname/Go/hostname.go @@ -6,6 +6,5 @@ import ( ) func main() { - host, _ := os.Hostname() - fmt.Printf("hostname: %s\n", host) + fmt.Println(os.Hostname()) } diff --git a/Task/Hostname/Julia/hostname.julia b/Task/Hostname/Julia/hostname.julia new file mode 100644 index 0000000000..ca419e51cf --- /dev/null +++ b/Task/Hostname/Julia/hostname.julia @@ -0,0 +1 @@ +println(gethostname()) diff --git a/Task/Hostname/PARI-GP/hostname.pari b/Task/Hostname/PARI-GP/hostname.pari new file mode 100644 index 0000000000..60f435a683 --- /dev/null +++ b/Task/Hostname/PARI-GP/hostname.pari @@ -0,0 +1,2 @@ +str = externstr("hostname")[1]; +str = externstr("uname -n")[1]; diff --git a/Task/Hostname/VBScript/hostname.vb b/Task/Hostname/VBScript/hostname.vb new file mode 100644 index 0000000000..5d323c0115 --- /dev/null +++ b/Task/Hostname/VBScript/hostname.vb @@ -0,0 +1,2 @@ +Set objNetwork = CreateObject("WScript.Network") +WScript.Echo objNetwork.ComputerName diff --git a/Task/Hough-transform/Python/hough-transform.py b/Task/Hough-transform/Python/hough-transform.py index 4694375f45..11ca07105e 100644 --- a/Task/Hough-transform/Python/hough-transform.py +++ b/Task/Hough-transform/Python/hough-transform.py @@ -1,5 +1,5 @@ from math import hypot, pi, cos, sin -import Image +from PIL import Image def hough(im, ntx=460, mry=360): diff --git a/Task/Huffman-coding/Clojure/huffman-coding-1.clj b/Task/Huffman-coding/Clojure/huffman-coding-1.clj new file mode 100644 index 0000000000..878d7eeecf --- /dev/null +++ b/Task/Huffman-coding/Clojure/huffman-coding-1.clj @@ -0,0 +1,34 @@ +(require '[clojure.pprint :refer :all]) + +(defn probs [s] + (let [freqs (frequencies s) sum (apply + (vals freqs))] + (into {} (map (fn [[k v]] [k (/ v sum)]) freqs)))) + +(defn init-pq [weighted-items] + (let [comp (proxy [java.util.Comparator] [] + (compare [a b] (compare (:priority a) (:priority b)))) + pq (java.util.PriorityQueue. (count weighted-items) comp)] + (doseq [[item prob] weighted-items] (.add pq { :symbol item, :priority prob })) + pq)) + +(defn huffman-tree [pq] + (while (> (.size pq) 1) + (let [a (.poll pq) b (.poll pq) + new-node {:priority (+ (:priority a) (:priority b)) :left a :right b}] + (.add pq new-node))) + (.poll pq)) + +(defn symbol-map + ([t] (symbol-map t "")) + ([{:keys [symbol priority left right] :as t} code] + (if symbol [{:symbol symbol :weight priority :code code}] + (concat (symbol-map left (str code \0)) + (symbol-map right (str code \1)))))) + +(defn huffman-encode [items] + (-> items probs init-pq huffman-tree symbol-map)) + +(defn display-huffman-encode [s] + (->> s huffman-encode (sort-by :weight >) print-table)) + +(display-huffman-encode "this is an example for huffman encoding") diff --git a/Task/Huffman-coding/Clojure/huffman-coding-2.clj b/Task/Huffman-coding/Clojure/huffman-coding-2.clj new file mode 100644 index 0000000000..796978c930 --- /dev/null +++ b/Task/Huffman-coding/Clojure/huffman-coding-2.clj @@ -0,0 +1,38 @@ +(require '[clojure.data.priority-map :refer [priority-map-keyfn-by]]) +(require '[clojure.pprint :refer [print-table]]) + +(defn init-pq [s] + (let [c (count s)] + (->> s frequencies + (map (fn [[k v]] [k {:sym k :weight (/ v c)}])) + (into (priority-map-keyfn-by :weight <))))) + +(defn huffman-tree [pq] + (letfn [(build-step + [pq] + (let [a (second (peek pq)) b (second (peek (pop pq))) + nn {:sym (str (:sym a) (:sym b)) + :weight (+ (:weight a) (:weight b)) + :left a :right b}] + (assoc (pop (pop pq)) (:sym nn) nn)))] + (->> (iterate build-step pq) + (drop-while #(> (count %) 1)) + first vals first))) + +(defn symbol-map [m] + (letfn [(sym-step + [{:keys [sym weight left right] :as m} code] + (cond (and left right) #(vector (trampoline sym-step left (str code \0)) + (trampoline sym-step right (str code \1))) + left #(sym-step left (str code \0)) + right #(sym-step right (str code \1)) + :else {:sym sym :weight weight :code code}))] + (trampoline sym-step m ""))) + +(defn huffman-encode [s] + (->> s init-pq huffman-tree symbol-map flatten)) + +(defn display-huffman-encode [s] + (->> s huffman-encode (sort-by :weight >) print-table)) + +(display-huffman-encode "this is an example for huffman encoding") diff --git a/Task/Huffman-coding/Clojure/huffman-coding.clj b/Task/Huffman-coding/Clojure/huffman-coding.clj deleted file mode 100644 index eb31106fb9..0000000000 --- a/Task/Huffman-coding/Clojure/huffman-coding.clj +++ /dev/null @@ -1,36 +0,0 @@ -(use 'clojure.contrib.seq-utils) - -(defn probs [items] - (let [freqs (frequencies items) sum (reduce + (vals freqs))] - (into {} (map (fn [[k v]] [k (/ v sum)]) freqs)))) - -(defn init-pq [weighted-items] - (let [comp (proxy [java.util.Comparator] [] - (compare [a b] (compare (:priority a) (:priority b)))) - pq (java.util.PriorityQueue. (count weighted-items) comp)] - (doseq [[item prob] weighted-items] (.add pq { :symbol item, :priority prob })) - pq)) - -(defn huffman-tree [pq] - (while (> (.size pq) 1) - (let [a (.poll pq) b (.poll pq) new-node { :priority (+ (:priority a) (:priority b)), :left a, :right b }] - (.add pq new-node))) - (.poll pq)) - -(defn symbol-map - ([t] (into {} (symbol-map t []))) - ([{:keys [symbol,left,right] :as t} code] - (if symbol [[symbol code]] - (concat (symbol-map left (conj code 0)) - (symbol-map right (conj code 1)))))) - -(defn huffman-encode [items] - (-> items probs init-pq huffman-tree symbol-map)) - -(defn display-huffman-encode [s] - (println "SYMBOL\tWEIGHT\tHUFFMAN CODE") - (let [probs (probs (seq s))] - (doseq [[char code] (huffman-encode (seq s))] - (printf "%s:\t\t%s\t\t%s\n" char (probs char) (apply str code))))) - -(display-huffman-encode "this is an example for huffman encoding") diff --git a/Task/Huffman-coding/OCaml/huffman-coding.ocaml b/Task/Huffman-coding/OCaml/huffman-coding.ocaml index cca87be1ef..52356090ac 100644 --- a/Task/Huffman-coding/OCaml/huffman-coding.ocaml +++ b/Task/Huffman-coding/OCaml/huffman-coding.ocaml @@ -13,7 +13,7 @@ module HSet = Set.Make end);; let build_tree charFreqs = - let leaves = List.fold_left (fun z (c,f) -> HSet.add (f, Leaf c) z) HSet.empty charFreqs in + let leaves = HSet.of_list (List.map (fun (c,f) -> (f, Leaf c)) charFreqs) in let rec aux trees = let f1, a = HSet.min_elt trees in let trees' = HSet.remove (f1,a) trees in diff --git a/Task/Huffman-coding/Perl-6/huffman-coding-1.pl6 b/Task/Huffman-coding/Perl-6/huffman-coding-1.pl6 index 9b9a09f816..963aeaa85f 100644 --- a/Task/Huffman-coding/Perl-6/huffman-coding-1.pl6 +++ b/Task/Huffman-coding/Perl-6/huffman-coding-1.pl6 @@ -3,7 +3,7 @@ sub huffman ($s) { my @q = $s.comb.classify({$_}).map({[+.value / $de, .key]}).sort; while @q > 1 { my ($a,$b) = @q.splice(0,2); - @q = sort [$a[0] + $b[0], [$a[1], $b[1]]], @q; + @q = sort flat $[$a[0] + $b[0], [$a[1], $b[1]]], @q; } sort *.value, gather walk @q[0][1], ''; } diff --git a/Task/Huffman-coding/Perl-6/huffman-coding-2.pl6 b/Task/Huffman-coding/Perl-6/huffman-coding-2.pl6 index 444b18c54b..0a66baa1b6 100644 --- a/Task/Huffman-coding/Perl-6/huffman-coding-2.pl6 +++ b/Task/Huffman-coding/Perl-6/huffman-coding-2.pl6 @@ -5,5 +5,5 @@ say $str; my $huf = %enc{$str.comb}.join; say $huf; my $rx = join('|', map { "'" ~ .key ~ "'" }, %dec); -$rx = eval '/' ~ $rx ~ '/'; +$rx = EVAL '/' ~ $rx ~ '/'; say $huf.subst(/<$rx>/, -> $/ {%dec{~$/}}, :g); diff --git a/Task/Huffman-coding/Racket/huffman-coding.rkt b/Task/Huffman-coding/Racket/huffman-coding.rkt index 86a6c8b5e1..a2d927b046 100644 --- a/Task/Huffman-coding/Racket/huffman-coding.rkt +++ b/Task/Huffman-coding/Racket/huffman-coding.rkt @@ -14,19 +14,11 @@ (define (node<=? x y) (<= (node-freq x) (node-freq y))) -;; We keep a private sentinel-val under our own control. -(define sentinel-val (cons 'sentinel 'sentinel)) - ;; make-huffman-tree: (listof leaf) -> interior-node -;; Makes the huffman tree with basic priority-queue operations. -;; Note: we ensure that make-huffman-tree always returns an interior node. (define (make-huffman-tree leaves) (define a-heap (make-heap node<=?)) (heap-add-all! a-heap leaves) - ;; To ensure that we always get tree with at least one interior node, - ;; we also inject a sentinel leaf node with zero frequency. - (heap-add! a-heap (leaf 0 sentinel-val)) - (for ([i (in-range (length leaves))]) + (for ([i (sub1 (length leaves))]) (define min-1 (heap-min a-heap)) (heap-remove-min! a-heap) (define min-2 (heap-min a-heap)) @@ -42,7 +34,7 @@ (define ht (make-hash)) (define n (sequence-length str)) (for ([ch str]) - (hash-set! ht ch (add1 (hash-ref ht ch 0)))) + (hash-update! ht ch add1 (λ () 0))) (make-huffman-tree (for/list ([(k v) (in-hash ht)]) (leaf (/ v n) k)))) @@ -65,8 +57,8 @@ (loop (interior-left a-node) (cons #f path/rev)) (loop (interior-right a-node) (cons #t path/rev))] [(leaf? a-node) - (unless (eq? (leaf-val a-node) sentinel-val) - (hash-set! ht (reverse path/rev) (leaf-val a-node)))])) + (hash-set! ht (reverse path/rev) (leaf-val a-node))])) + (for/hash ([(k v) ht]) (values v k))) diff --git a/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk b/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk index d7d941d453..a9ab9fde37 100644 --- a/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk +++ b/Task/I-before-E-except-after-C/AWK/i-before-e-except-after-c.awk @@ -13,14 +13,14 @@ function cnt(c) { END { printf("cie: %i\nnie: %i\ncei: %i\nnei: %i\n",cie,nie-cie,cei,nei-cei); - v = ""; + v = v2 = ""; if (nie < 3 * cie) { - v=" not"; + v =" not"; } print "I before E when not preceded by C: is"v" plausible"; - v = ""; if (nei > 3 * cei) { - v=" not"; + v = v2 =" not"; } - print "E before I when preceded by C: is"v" plausible"; + print "E before I when preceded by C: is"v2" plausible"; + print "Overall rule is"v" plausible"; } diff --git a/Task/I-before-E-except-after-C/Batch-File/i-before-e-except-after-c.bat b/Task/I-before-E-except-after-C/Batch-File/i-before-e-except-after-c.bat new file mode 100644 index 0000000000..1962c47d0e --- /dev/null +++ b/Task/I-before-E-except-after-C/Batch-File/i-before-e-except-after-c.bat @@ -0,0 +1,37 @@ +::I before E except after C task from Rosetta Code Wiki +::Batch File Implementation + +@echo off +setlocal enabledelayedexpansion + ::Initialization +set ie=0 +set ei=0 +set cie=0 +set cei=0 + +set propos1=FALSE +set propos2=FALSE +set propos3=FALSE + + ::Do the matching +for /f %%X in (unixdict.txt) do ( + set word=%%X + if not "!word:ie=!"=="!word!" if "!word:cie=!"=="!word!" (set /a ie+=1) + if not "!word:ei=!"=="!word!" if "!word:cei=!"=="!word!" (set /a ei+=1) + if not "!word:cei=!"=="!word!" (set /a cei+=1) + if not "!word:cie=!"=="!word!" (set /a cie+=1) +) + +set /a "counter1=!ei!*2,counter2=!cie!*2" + +if !ie! gtr !counter1! set propos1=TRUE +echo.Plausibility of "I before E when not preceded by C": !propos1! (!ie! VS !ei!) + +if !cei! gtr !counter2! set propos2=TRUE +echo.Plausibility of "E before I when preceded by C": !propos2! (!cei! VS !cie!) + +if !propos1!==TRUE if !propos2!==TRUE (set propos3=TRUE) +echo.Overall plausibility of "I before E EXCEPT after C": !propos3! + +pause +exit /b 0 diff --git a/Task/I-before-E-except-after-C/Elixir/i-before-e-except-after-c.elixir b/Task/I-before-E-except-after-C/Elixir/i-before-e-except-after-c.elixir new file mode 100644 index 0000000000..df06cb496c --- /dev/null +++ b/Task/I-before-E-except-after-C/Elixir/i-before-e-except-after-c.elixir @@ -0,0 +1,29 @@ +defmodule RC do + def task(path) do + plausibility_ratio = 2 + rules = [ {"I before E when not preceded by C:", "ie", "ei"}, + {"E before I when preceded by C:", "cei", "cie"} ] + regex = ~r/ie|ei|cie|cei/ + counter = File.read!(path) |> countup(regex) + Enum.all?(rules, fn {str, x, y} -> + nx = counter[x] + ny = counter[y] + ratio = nx / ny + plausibility = if ratio > plausibility_ratio, do: "Plausible", else: "Implausible" + IO.puts str + IO.puts " #{x}: #{nx}; #{y}: #{ny}; Ratio: #{Float.round(ratio,3)}: #{plausibility}" + ratio > plausibility_ratio + end) + end + + def countup(binary, regex) do + String.split(binary) + |> Enum.reduce(Map.new, fn word,acc -> + if match = Regex.run(regex, word), + do: Dict.update(acc, hd(match), 1, &(&1+1)), else: acc + end) + end +end + +path = hd(System.argv) +IO.inspect RC.task(path) diff --git a/Task/I-before-E-except-after-C/Erlang/i-before-e-except-after-c.erl b/Task/I-before-E-except-after-C/Erlang/i-before-e-except-after-c.erl new file mode 100644 index 0000000000..17fd2bb6cd --- /dev/null +++ b/Task/I-before-E-except-after-C/Erlang/i-before-e-except-after-c.erl @@ -0,0 +1,24 @@ +-module(cei). +-export([plaus/0,count/3]). + +plaus() -> + {ok,Words} = file:read_file("unixdict.txt"), + Swords = string:tokens(erlang:binary_to_list(Words), "\n"), + EiF = count(Swords,"[^c]ei",0), + IeF = count(Swords,"[^c]ie",0), + CeiF = count(Swords,"cei",0), + CieF = count(Swords,"cie",0), + if CeiF >= 2 * CieF -> P1= 'is'; true -> P1 = 'is not' end, + if IeF >= 2 * EiF -> P2 = 'is'; true -> P2 = 'is not' end, + if P1 == 'is' andalso p2 == 'is' -> P3 ='is'; true -> P3 = 'is not' end, + io:format("Proposition 1. ~w plausible: ie ~w, ei ~w~n", [P2,IeF,EiF]), + io:format("Proposition 2. ~w plausible: cei ~w, cie ~w~n", [P1,CeiF,CieF]), + io:format("The rule ~w plausible~n", [P3]). + +count(List,Pattern,Acc) when length(List) == 0 -> Acc; +count(List,Pattern,Acc) -> + [H|T] = List, + case re:run(H,Pattern,[global,{capture,none}]) of + match -> count(T,Pattern, Acc + 1); + nomatch -> count(T,Pattern, Acc) + end. diff --git a/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh index 0a1ce05f03..d31f7cdb15 100644 --- a/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh +++ b/Task/I-before-E-except-after-C/PowerShell/i-before-e-except-after-c.psh @@ -20,9 +20,9 @@ if ($IE.count -gt $EI.count * 2) {$Clause1 = $true} "The plausibility of 'I before E when not preceded by C' is $Clause1" -if ($CIE.count -gt $CEI.count * 2) +if ($CEI.count -gt $CIE.count * 2) {$Clause2 = $true} -"The plausibility of 'II before E when preceded by C' is $Clause2" +"The plausibility of 'E before I when preceded by C' is $Clause2" if ($Clause1 -and $Clause2) {$MainClause = $True} diff --git a/Task/I-before-E-except-after-C/PureBasic/i-before-e-except-after-c.purebasic b/Task/I-before-E-except-after-C/PureBasic/i-before-e-except-after-c.purebasic new file mode 100644 index 0000000000..550c76886a --- /dev/null +++ b/Task/I-before-E-except-after-C/PureBasic/i-before-e-except-after-c.purebasic @@ -0,0 +1,23 @@ +If ReadFile(1,GetPathPart(ProgramFilename())+"wordlist(en).txt") + While Not Eof(1) + wl$+ReadString(1)+";" + Wend + CloseFile(1) +EndIf + +OpenConsole() +PrintN("Number of words in [wordlist(en).txt]: "+CountString(wl$,";")) +cei.i=CountString(wl$,"cei") : PrintN("Instances of [cei] : "+Str(cei)) +cie.i=CountString(wl$,"cie") : PrintN("Instances of [cie] : "+Str(cie)) +Print("Rule: 'e' before 'i' when preceded by 'c' is = ") +If cei>cie : PrintN("plausible") : Else : PrintN("not plausible") : EndIf +wl$=RemoveString(wl$,"cei") : wl$=RemoveString(wl$,"cie") +PrintN("") +ei.i=CountString(wl$,"ei") : PrintN("Instances of [*ei] '*'<>'c' : "+Str(ei)) +ie.i=CountString(wl$,"ie") : PrintN("Instances of [*ie] '*'<>'c' : "+Str(ie)) +Print("Rule: 'i' before 'e' when not preceded by 'c' is = ") +If ie>ei : PrintN("plausible") : Else : PrintN("not plausible") : EndIf +PrintN("") +Print("Overall the rule is : ") +If cei>cie And ie>ei : PrintN("PLAUSIBLE") : Else : PrintN("NOT PLAUSIBLE") : EndIf +Input() diff --git a/Task/IBAN/C++/iban.cpp b/Task/IBAN/C++/iban.cpp index 890d3bef24..f903f9addb 100644 --- a/Task/IBAN/C++/iban.cpp +++ b/Task/IBAN/C++/iban.cpp @@ -6,8 +6,8 @@ #include using namespace boost::algorithm ; -bool isValid ( const std::string &ibanstring ) { - +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 } , @@ -31,17 +31,18 @@ bool isValid ( const std::string &ibanstring ) { return false ; if ( teststring.length( ) != countrycodes[ teststring.substr( 0 , 2 ) ] ) return false ; - if ( ! ( all ( teststring , is_alnum( ) ) ) ) + if (!all(teststring, is_alnum())) return false ; to_upper( teststring ) ; - teststring = teststring.append( teststring.substr( 0 , 4 ) ) ; - teststring.assign( teststring.substr( 4 ) ) ; + std::rotate(teststring.begin(), teststring.begin() + 4, teststring.end()); + 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 ) ; + for (const auto& c : teststring) + { + if (std::isdigit(c)) + numberstring += c ; + if (std::isupper(c)) + numberstring += std::to_string(static_cast(c) - 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 @@ -63,10 +64,14 @@ bool isValid ( const std::string &ibanstring ) { 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 ; +void SayValidity(const std::string& iban) +{ + std::cout << iban << (isValid(iban) ? " is " : " is not ") << "valid\n"; +} + +int main( ) +{ + SayValidity("GB82 WEST 1234 5698 7654 32"); + SayValidity("GB82TEST12345698765432"); return 0 ; } diff --git a/Task/IBAN/C-sharp/iban-1.cs b/Task/IBAN/C-sharp/iban-1.cs index 5008d9f5d8..a030d31c7a 100644 --- a/Task/IBAN/C-sharp/iban-1.cs +++ b/Task/IBAN/C-sharp/iban-1.cs @@ -13,7 +13,7 @@ public ValidationResult Validate(string value) int lengthForCountryCode; - var countryCodeKnown = _lengths.TryGetValue(countryCode, out lengthForCountryCode); + var countryCodeKnown = Lengths.TryGetValue(countryCode, out lengthForCountryCode); if (!countryCodeKnown) { return ValidationResult.CountryCodeNotKnown; @@ -29,14 +29,13 @@ public ValidationResult Validate(string value) value = value.ToUpper(); var newIban = value.Substring(4) + value.Substring(0, 4); - newIban = Regex.Replace(newIban, @"\D", match => ((int) match.Value[0] - 55).ToString()); + newIban = Regex.Replace(newIban, @"\D", match => (match.Value[0] - 55).ToString()); var remainder = BigInteger.Parse(newIban) % 97; if (remainder != 1) return ValidationResult.ValueFailsModule97Check; - return ValidationResult.IsValid; } @@ -50,7 +49,7 @@ public enum ValidationResult CountryCodeNotKnown } - private static Dictionary _lengths = new Dictionary + private static readonly IDictionary Lengths = new Dictionary { {"AL", 28}, {"AD", 24}, diff --git a/Task/IBAN/Forth/iban.fth b/Task/IBAN/Forth/iban.fth new file mode 100644 index 0000000000..627148bd0d --- /dev/null +++ b/Task/IBAN/Forth/iban.fth @@ -0,0 +1,38 @@ +include lib/ulcase.4th \ for S>UPPER +include lib/triple.4th \ for UT/MOD +include lib/cstring.4th \ for C/STRING +include lib/todbl.4th \ for S>DOUBLE + +0 constant ud>t \ convert unsigned double to triple +88529281 constant 97^4 \ first stage modulus +char A 10 - negate +constant c>u \ convert character to IBAN digit + +: bank>t u>d rot 3 - 0 ?do 10 mu* loop 1000000000 ut* ; + \ convert country part to unsigned +: country>u ( a n -- u) + c/string c>u 10000 * >r c/string c>u 100 * >r number 100 mod abs r> + r> + +; + \ convert bank part to unsigned +: bank>u \ a n -- u) + c/string c>u 1000000 * >r \ get first digit and shift + c/string c>u 10000 * >r \ get second digit and shift + c/string c>u 100 * >r \ get third digit and shift + drop c@ c>u r> + r> + r> + \ combine all digits to number +; + +: iban>t ( a n -- triple) + s>upper \ convert to upper case and get country + over 4 country>u >r 4 /string \ get bank part, save length, convert + over 4 bank>u >r 4 /string tuck s>double + 1000000 mu* r> -rot r> u>d d+ 2>r \ now assemble everything except bank + bank>t 2r> ud>t t+ \ shift bank part and convert to triple +; + ( a n -- f) +: iban? iban>t 97^4 ut/mod 2drop 97 mod 1 = ; + \ perform modulus 97 in two stages +: checkiban ( --) + ." Enter your IBAN: " refill drop 0 parse -trailing iban? + if ." Valid" else ." Invalid" then cr +; + +checkiban diff --git a/Task/IBAN/Logtalk/iban-1.logtalk b/Task/IBAN/Logtalk/iban-1.logtalk new file mode 100644 index 0000000000..95090c3802 --- /dev/null +++ b/Task/IBAN/Logtalk/iban-1.logtalk @@ -0,0 +1,129 @@ +:- object(iban). + + :- info([ + version is 0.1, + author is 'Paulo Moura', + date is 2015/10/11, + comment is 'IBAN validation example using DCG rules.' + ]). + + :- public(valid/1). + + valid(IBAN) :- + phrase(iban, IBAN), !. + + iban --> + country_code(Code), check_digits(Check), bban(BBAN), + {(BBAN*1000000 + Code*100 + Check) mod 97 =:= 1}. + + country_code(Code) --> + letter_digits(L1, D3, D2), letter_digits(L0, D1, D0), + {country_code([L1, L0]), Code is D3*1000 + D2*100 + D1*10 + D0}. + + check_digits(Check) --> + digit(D1), digit(D0), + {Check is D1*10 + D0}. + + bban(BBAN) --> + bban_codes(Digits), + {digits_to_integer(Digits, BBAN, Count), Count =< 30}. + + bban_codes(Ds) --> + " ", bban_codes(Ds). + bban_codes([D| Ds]) --> + digit(D), bban_codes(Ds). + bban_codes([D1, D0| Ds]) --> + letter_digits(_, D1, D0), bban_codes(Ds). + bban_codes([]) --> + []. + + digit(D) --> + [C], + {0'0 =< C, C =< 0'9, D is C - 0'0}. + + letter_digits(C, D1, D0) --> + [C], + { ( 0'A =< C, C =< 0'Z -> + D is C - 0'A + 10 + ; 0'a =< C, C =< 0'z, + D is C - 0'a + 10 + ), + D1 is D div 10, + D0 is D mod 10 + }. + + digits_to_integer(Digits, BBAN, Count) :- + digits_to_integer(Digits, 0, BBAN, 0, Count). + + digits_to_integer([], BBAN, BBAN, Count, Count). + digits_to_integer([Digit| Digits], BBAN0, BBAN, Count0, Count) :- + BBAN1 is BBAN0 * 10 + Digit, + Count1 is Count0 + 1, + digits_to_integer(Digits, BBAN1, BBAN, Count1, Count). + + country_code("AL"). + country_code("AD"). + country_code("AT"). + country_code("AZ"). + country_code("BE"). + country_code("BH"). + country_code("BA"). + country_code("BR"). + country_code("BG"). + country_code("CR"). + country_code("HR"). + country_code("CY"). + country_code("CZ"). + country_code("DK"). + country_code("DO"). + country_code("EE"). + country_code("FO"). + country_code("FI"). + country_code("FR"). + country_code("GE"). + country_code("DE"). + country_code("GI"). + country_code("GR"). + country_code("GL"). + country_code("GT"). + country_code("HU"). + country_code("IS"). + country_code("IE"). + country_code("IL"). + country_code("IT"). + country_code("KZ"). + country_code("KW"). + country_code("LV"). + country_code("LB"). + country_code("LI"). + country_code("LT"). + country_code("LU"). + country_code("MK"). + country_code("MT"). + country_code("MR"). + country_code("MU"). + country_code("MC"). + country_code("MD"). + country_code("ME"). + country_code("NL"). + country_code("NO"). + country_code("PK"). + country_code("PS"). + country_code("PL"). + country_code("PT"). + country_code("RO"). + country_code("SM"). + country_code("SA"). + country_code("RS"). + country_code("SK"). + country_code("SI"). + country_code("ES"). + country_code("SE"). + country_code("CH"). + country_code("TN"). + country_code("TR"). + country_code("AE"). + country_code("GB"). + country_code("VG"). + +:- end_object. diff --git a/Task/IBAN/Logtalk/iban-2.logtalk b/Task/IBAN/Logtalk/iban-2.logtalk new file mode 100644 index 0000000000..4e17e0f19f --- /dev/null +++ b/Task/IBAN/Logtalk/iban-2.logtalk @@ -0,0 +1,2 @@ +| ?- iban::valid("GB82 WEST 1234 5698 7654 32"). +yes diff --git a/Task/IBAN/NewLISP/iban.newlisp b/Task/IBAN/NewLISP/iban.newlisp new file mode 100644 index 0000000000..117bfab889 --- /dev/null +++ b/Task/IBAN/NewLISP/iban.newlisp @@ -0,0 +1,67 @@ +(setq *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")))) + + +;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +;; Remove spaces and set upper case. +(define (sanitize-iban iban) + (upper-case (replace " " iban "")) +) + +;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +;; Check that only A-Z and 0-9 are used. +(define (valid-chars? iban) + (setq rx (string "[A-Z0-9]{" (length iban) "}" )) + (regex rx iban 1) +) + +;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +;; Check that the length is correct for the country. +(define (valid-length? iban) + (setq countries-found (lookup (int (length iban)) *iban-code-length*)) + (if (not (nil? countries-found)) + (member (0 2 iban) countries-found) + ) +) + +;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +;; Convert the IBAN to integer following the rules from Wikipedia. +(define (iban-to-integer iban) + (setq country-code (0 2 iban)) + (setq checksum (2 2 iban)) + (setq iban (string (4 iban) country-code)) + (setq iban (join (map (lambda (x) (if (regex "[0-9]" x) x (string (- (char x) 55)))) (explode iban)))) + (bigint (string iban checksum)) +) + +;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +;; Test if IBAN is correct (true) or not (nil): +;; (valid-iban? "GB82 WEST 1234 5698 7654 32") ==> true +;; (valid-iban? "GB82 TEST 1234 5698 7654 32") ==> nil +(define (valid-iban? iban) + (setq iban (sanitize-iban iban)) + (and + (valid-chars? iban) + (valid-length? iban) + (= 1L (% (iban-to-integer iban) 97)) + ) +) diff --git a/Task/IBAN/PHP/iban.php b/Task/IBAN/PHP/iban.php new file mode 100644 index 0000000000..93589b1f5c --- /dev/null +++ b/Task/IBAN/PHP/iban.php @@ -0,0 +1,79 @@ +0) + { + $slice = 7; + } + + $part = $remainder . substr($iban_all_digits, $i, $slice); + //echo "REMAINDER: " . $remainder . "
"; + //echo "PART: $part" . "
"; + $remainder = intval($part) % 97; + } + +return $remainder; + +} + + +$iban = "GB82 WEST 1234 5698 7654 32"; + +//remove space +$iban = str_replace(' ', '', $iban); + +//echo $iban; echo '
'; +$iban_length = strlen($iban); +$country_code = substr($iban, 0, 2); + +/* + IBAN lengths are country specific + full list available at + https://en.wikipedia.org/wiki/International_Bank_Account_Number#IBAN_formats_by_country +*/ +$lengths = ['GB' => 22]; + + +if ($lengths[$country_code] != $iban_length) +{ + exit ("IBAN length not valid for $country_code"); +} + + +// 2. move first four characters to the end +$iban = substr($iban, 4) . substr($iban, 0, 4); + + +//3. Replace letters in IBAN with digits +//(A=10, B=11 ... Z=35) + +$iban_arr = str_split($iban, 1); + + +$iban_all_digits = ''; + +foreach ($iban_arr as $key=>$value) +{ + if (ctype_alpha($value)) + { + $value = ord($value) - 55; + } + $iban_all_digits = $iban_all_digits . $value; +} + + +if (piece_wise($iban_all_digits) === 1) +{ + echo "VALID IBAN!"; +} + +else +{ + echo "IBAN NOT VALID"; +} diff --git a/Task/IBAN/PureBasic/iban.purebasic b/Task/IBAN/PureBasic/iban.purebasic new file mode 100644 index 0000000000..3c014d4e88 --- /dev/null +++ b/Task/IBAN/PureBasic/iban.purebasic @@ -0,0 +1,92 @@ +EnableExplicit +Enumeration IBAN + #IBAN_VAL + #IBAN_SUM + #IBAN_NOSPACE + #IBAN_VAL_FORM + #IBAN_SUM_FORM +EndEnumeration + +NewMap CData.i() +Macro CCD(SIGN,LENGTH) + CData(SIGN)=LENGTH +EndMacro + +Procedure.s IBANForm(iban.s,form.i) + Define fn.s, c.i + fn=RemoveString(UCase(iban),Chr(32)) + If form=#IBAN_NOSPACE : ProcedureReturn fn : EndIf + fn=Mid(fn,5)+Mid(fn,1,4) + For c=65 To 90 + fn=ReplaceString(fn,Chr(c),Str(c-55)) + Next c + If form=#IBAN_VAL_FORM : ProcedureReturn fn : EndIf + fn=Left(fn,Len(fn)-2)+"00" + If form=#IBAN_SUM_FORM : ProcedureReturn fn : EndIf +EndProcedure + +Procedure.s m97iban(iban.s,calculate.i) + Define i.i, part.s, rest.s + Select calculate + Case #IBAN_VAL : iban=IBANForm(iban,#IBAN_VAL_FORM) + Case #IBAN_SUM : iban=IBANForm(iban,#IBAN_SUM_FORM) + EndSelect + For i=1 To Len(iban) ; Validierung der Prüfsumme + part+Mid(iban,i,1) + If Val(rest+part)<97 : Continue : EndIf + rest=Str((Val(rest+part)) %97) : part="" + Next + Select calculate + Case #IBAN_VAL : ProcedureReturn rest + Case #IBAN_SUM : ProcedureReturn RSet(Str(98-Val(rest+part)),2,"0") + EndSelect +EndProcedure + +CCD("AL",28) : CCD("AD",24) : CCD("AT",20) : CCD("AZ",28) : CCD("BE",16) : CCD("BH",22) : CCD("BA",20) +CCD("BR",29) : CCD("BG",22) : CCD("CR",21) : CCD("HR",21) : CCD("CY",28) : CCD("CZ",24) : CCD("DK",18) +CCD("DO",28) : CCD("EE",20) : CCD("FO",18) : CCD("FI",18) : CCD("FR",27) : CCD("GE",22) : CCD("DE",22) +CCD("GI",23) : CCD("GR",27) : CCD("GL",18) : CCD("GT",28) : CCD("HU",28) : CCD("IS",26) : CCD("IE",22) +CCD("IL",23) : CCD("IT",27) : CCD("KZ",20) : CCD("KW",30) : CCD("LV",21) : CCD("LB",28) : CCD("LI",21) +CCD("LT",20) : CCD("LU",20) : CCD("MK",19) : CCD("MT",31) : CCD("MR",27) : CCD("MU",30) : CCD("MC",27) +CCD("MD",24) : CCD("ME",22) : CCD("NL",18) : CCD("NO",15) : CCD("PK",24) : CCD("PS",29) : CCD("PL",28) +CCD("PT",25) : CCD("RO",24) : CCD("SM",27) : CCD("SA",24) : CCD("RS",22) : CCD("SK",24) : CCD("SI",19) +CCD("ES",24) : CCD("SE",24) : CCD("CH",21) : CCD("TN",24) : CCD("TR",26) : CCD("AE",23) : CCD("GB",22) +CCD("VG",24) + +DataSection + IBANData: + Data.s "GB82 WEST 1234 5698 7654 32" + Data.s "GB82WEST12345698765432" + Data.s "gb82 west 1234 5698 7654 32" + Data.s "GB82 TEST 1234 5698 7654 32" + Data.s "GR16 0110 1250 0000 0001 2300 695" + Data.s "GB29 NWBK 6016 1331 9268 19" + Data.s "SA03 8000 0000 6080 1016 7519" + Data.s "CH93 0076 2011 6238 5295 7" + Data.s "IL62 0108 0000 0009 9999 999" + Data.s "IL62-0108-0000-0009-9999-999" + Data.s "US12 3456 7890 0987 6543 210" + Data.s "GR16 0110 1250 0000 0001 2300 695X" + Data.s Chr(0) +EndDataSection + +Define iban.s, cc.s +OpenConsole() +Restore IBANData +Repeat + Read.s iban : If iban=Chr(0) : Break : EndIf + Print("IBAN"+#TAB$+": "+LSet(iban,35,Chr(32))+#TAB$) + cc=Left(IBANForm(iban,#IBAN_NOSPACE),2) + If CData(cc) + If Not CData()=Len(IBANForm(iban,#IBAN_NOSPACE)) : PrintN("[INCORRECT: LENGTH]") : Continue : EndIf + Else + PrintN("[INCORRECT: COUNTRY]") : Continue + EndIf + If Not Val(m97iban(iban,#IBAN_VAL))=1 : PrintN("[INCORRECT: MOD97]") : Continue : EndIf + If Not Right(IBANForm(iban,#IBAN_VAL_FORM),2)=m97iban(iban,#IBAN_SUM) + PrintN("[INCORRECT: CHECKSUM]") : Continue + EndIf + PrintN("[CORRECT]") +ForEver +Input() +End diff --git a/Task/IBAN/REXX/iban-1.rexx b/Task/IBAN/REXX/iban-1.rexx index ebd1274bb9..2b2750f419 100644 --- a/Task/IBAN/REXX/iban-1.rexx +++ b/Task/IBAN/REXX/iban-1.rexx @@ -1,4 +1,4 @@ -/*REXX program validates an IBAN (International Bank Account Number). */ +/*REXX program validates an IBAN (International Bank Account Number). */ @. = @.1 = 'GB82 WEST 1234 5698 7654 32 ' @.2 = 'Gb82 West 1234 5698 7654 32 ' @@ -11,37 +11,37 @@ @.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*/ +parse arg @.0 /*get optional first argument from C.L.*/ + do k=0+(arg()==0) while @.k\=='' /*either: 0 or 1 ──► n*/ r = validateIBAN(@.k) 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*/ + if k==0 then leave /*User specified IBAN? Then we're 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.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────VALIDATEIBAN subroutine───────────────────*/ +validateIBAN: procedure; arg x; numeric digits 200 /*allow for big #s*/ +x=space(x,0); L=length(x) /*elide blanks; determine the length.*/ cc = 'AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21', 'CR 21 CY 28 CZ 24 DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27', 'GB 22 GE 22 GI 23 GL 18 GR 27 GT 28 HR 21 HU 28 IE 22 IL 23 IS 26', 'IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27 MD 24 ME 22', 'MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24', - 'RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*country,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. */ + 'RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*country list.*/ +@abc# = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' /*alphabet and decimal digits.*/ +cc_=left(x,2); kk=substr(x,3,2) /*get IBAN country code and checkDigits*/ +c#=wordpos(cc_,cc) /*find the country code index. */ +cL=word(cc,c#+1) /*get the length of the country's IBAN.*/ +e= '***error!*** invalid IBAN' /*literal used when displaying an error*/ +if c#==0 then return e 'country code:' cc_ +if \datatype(x,'A') then return e 'character:' substr(x,verify(x,@abc#),1) +if cL\==L then return e 'length:' L ' (should be' cL")" +y=substr(x,5)left(x,4) /*put four digs in front ───► the back.*/ +z= /* [↓] translate characters ──► digits*/ do j=1 for L; _=substr(y,j,1) if datatype(_,'U') then z=z || pos(_,@abc#)+9 else z=z || _ end /*j*/ -if z//97==1 then return 0 /*check to see if correct modulus*/ - return '***error!*** invalid check digits.' +if z//97==1 then return 0 /*check if correct remainder (modulus).*/ + return e 'check digits.' diff --git a/Task/IBAN/REXX/iban-2.rexx b/Task/IBAN/REXX/iban-2.rexx index 4fc4508596..d55396c3b8 100644 --- a/Task/IBAN/REXX/iban-2.rexx +++ b/Task/IBAN/REXX/iban-2.rexx @@ -1,4 +1,4 @@ -/*REXX program validates an IBAN (International Bank Account Number). */ +/*REXX program validates an IBAN (International Bank Account Number). */ @. = @.1 = 'GB82 WEST 1234 5698 7654 32 ' @.2 = 'Gb82 West 1234 5698 7654 32 ' @@ -13,44 +13,44 @@ @.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*/ +parse arg @.0 /*get optional first argument from C.L.*/ + do k=0+(arg()==0) while @.k\=='' /*either: 0 or 1 ──► n*/ r = validateIBAN(@.k) 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*/ + if k==0 then leave /*User specified IBAN? Then we're 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.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────VALIDATEIBAN subroutine───────────────────────────────────────*/ +validateIBAN: procedure; arg x; numeric digits 200 /*allow for big #s*/ +x=space(x,0); L=length(x) /*elide blanks; determine the length.*/ cc = 'AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21', 'CR 21 CY 28 CZ 24 DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27', 'GB 22 GE 22 GI 23 GL 18 GR 27 GT 28 HR 21 HU 28 IE 22 IL 23 IS 26', 'IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27 MD 24 ME 22', 'MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24', - 'RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*country,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. */ + 'RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*country list.*/ +@abc# = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' /*alphabet and decimal digits.*/ +cc_=left(x,2); kk=substr(x,3,2) /*get IBAN country code and checkDigits*/ +c#=wordpos(cc_,cc) /*find the country code index. */ +cL=word(cc,c#+1) /*get the length of the country's IBAN.*/ +e= '***error!*** invalid IBAN' /*literal used when displaying an error*/ +if c#==0 then return e 'country code:' cc_ +if \datatype(x,'A') then return e 'character:' substr(x,verify(x,@abc#),1) +if cL\==L then return e 'length:' L ' (should be' cL")" +if cc_=='BR' & date("S")<20130701 then return e "country, Brazil isn't valid until 1-July-2013." +if cc_=='GT' & date("S")<20140701 then return e "country, Guatemala isn't valid until 1-July-2014." +if cc_=='BA' & kk\==39 then return e "check digits for Bosnia and Herzegovina:" kk +if cc_=='MK' & kk\==07 then return e "check digits for Macedonia:" kk +if cc_=='ME' & kk\==25 then return e "check digits for Montenegro:" kk +if cc_=='PT' & kk\==50 then return e "check digits for Portugal:" kk +if cc_=='SI' & kk\==56 then return e "check digits for Slovenia:" kk +y=substr(x,5)left(x,4) /*put four digs in front ───► the back.*/ +z= /* [↓] translate characters ──► digits*/ do j=1 for L; _=substr(y,j,1) if datatype(_,'U') then z=z || pos(_,@abc#)+9 else z=z || _ end /*j*/ -if z//97==1 then return 0 /*check to see if correct modulus*/ - return '***error!*** invalid check digits.' +if z//97==1 then return 0 /*check if correct remainder (modulus).*/ + return e 'check digits.' diff --git a/Task/IBAN/VBScript/iban.vb b/Task/IBAN/VBScript/iban.vb new file mode 100644 index 0000000000..b039d8870a --- /dev/null +++ b/Task/IBAN/VBScript/iban.vb @@ -0,0 +1,58 @@ +Function validate_iban(s) + validate_iban = Chr(34) & s & Chr(34) & " is NOT valid." + Set cn_len = CreateObject("Scripting.Dictionary") + With cn_len + .Add "AL",28 : .Add "AD",24 : .Add "AT",20 : .Add "AZ",28 : .Add "BH",22 : .Add "BE",16 + .Add "BA",20 : .Add "BR",29 : .Add "BG",22 : .Add "CR",21 : .Add "HR",21 : .Add "CY",28 + .Add "CZ",24 : .Add "DK",18 : .Add "DO",28 : .Add "EE",20 : .Add "FO",18 : .Add "FI",18 + .Add "FR",27 : .Add "GE",22 : .Add "DE",22 : .Add "GI",23 : .Add "GR",27 : .Add "GL",18 + .Add "GT",28 : .Add "HU",28 : .Add "IS",26 : .Add "IE",22 : .Add "IL",23 : .Add "IT",27 + .Add "JO",30 : .Add "KZ",20 : .Add "KW",30 : .Add "LV",21 : .Add "LB",28 : .Add "LI",21 + .Add "LT",20 : .Add "LU",20 : .Add "MK",19 : .Add "MT",31 : .Add "MR",27 : .Add "MU",30 + .Add "MC",27 : .Add "MD",24 : .Add "ME",22 : .Add "NL",18 : .Add "NO",15 : .Add "PK",24 + .Add "PS",29 : .Add "PL",28 : .Add "PT",25 : .Add "QA",29 : .Add "RO",24 : .Add "SM",27 + .Add "SA",24 : .Add "RS",22 : .Add "SK",24 : .Add "SI",19 : .Add "ES",24 : .Add "SE",24 + .Add "CH",21 : .Add "TN",24 : .Add "TR",26 : .Add "AE",23 : .Add "GB",22 : .Add "VG",24 + End With + iban = Replace(s," ","") + If cn_len.Exists(Left(iban,2)) And Len(iban) = cn_len.Item(Left(iban,2)) Then + 'move the first 4 characters to the end + iban = Mid(iban,5,Len(iban)-4) & Left(iban,4) + 'convert letters to numbers A=10 to Z=35 + D = "" + For i = 1 To Len(iban) + If Asc(Mid(iban,i,1)) >= 65 And Asc(Mid(iban,i,1)) <= 90 Then + D = D & CStr(Asc(Mid(iban,i,1)) - 55) + Else + D = D & Mid(iban,i,1) + End If + Next + 'piece-wise modulo calculation + Do + If Len(D) > 9 Then + N = CLng(Left(D,9)) Mod 97 + D = CStr(N) & Mid(D,10,Len(D)-9) + Else + N = CLng(Left(D,9)) Mod 97 + Exit Do + End If + Loop + If N = 1 Then + validate_iban = Chr(34) & s & Chr(34) & " is valid." + End If + End If +End Function + +'test several scenarios +WScript.StdOut.WriteLine validate_iban("GB82 WEST 1234 5698 7654 32") +WScript.StdOut.WriteLine validate_iban("GB82WEST12345698765432") +WScript.StdOut.WriteLine validate_iban("gb82 west 1234 5698 7654 32") +WScript.StdOut.WriteLine validate_iban("GB82 TEST 1234 5698 7654 32") +WScript.StdOut.WriteLine validate_iban("GR16 0110 1250 0000 0001 2300 695") +WScript.StdOut.WriteLine validate_iban("GB29 NWBK 6016 1331 9268 19") +WScript.StdOut.WriteLine validate_iban("SA03 8000 0000 6080 1016 7519") +WScript.StdOut.WriteLine validate_iban("CH93 0076 2011 6238 5295 7") +WScript.StdOut.WriteLine validate_iban("IL62 0108 0000 0009 9999 999") +WScript.StdOut.WriteLine validate_iban("IL62-0108-0000-0009-9999-999") +WScript.StdOut.WriteLine validate_iban("US12 3456 7890 0987 6543 210") +WScript.StdOut.WriteLine validate_iban("GR16 0110 1250 0000 0001 2300 695X") diff --git a/Task/Identity-matrix/APL/identity-matrix-1.apl b/Task/Identity-matrix/APL/identity-matrix-1.apl index f692a5c359..549feab91e 100644 --- a/Task/Identity-matrix/APL/identity-matrix-1.apl +++ b/Task/Identity-matrix/APL/identity-matrix-1.apl @@ -1,4 +1,4 @@ - ∘.=/⍳¨3 3 + ∘.=⍨⍳3 1 0 0 0 1 0 0 0 1 diff --git a/Task/Identity-matrix/APL/identity-matrix-2.apl b/Task/Identity-matrix/APL/identity-matrix-2.apl index ed7d871e5f..ee8de6de60 100644 --- a/Task/Identity-matrix/APL/identity-matrix-2.apl +++ b/Task/Identity-matrix/APL/identity-matrix-2.apl @@ -1,4 +1,4 @@ - ID←{∘.=/⍳¨ ⍵ ⍵} + ID←{∘.=⍨⍳⍵} ID 5 1 0 0 0 0 0 1 0 0 0 diff --git a/Task/Identity-matrix/Applesoft-BASIC/identity-matrix.applesoft b/Task/Identity-matrix/Applesoft-BASIC/identity-matrix.applesoft new file mode 100644 index 0000000000..ef1c92efbb --- /dev/null +++ b/Task/Identity-matrix/Applesoft-BASIC/identity-matrix.applesoft @@ -0,0 +1,15 @@ +100 INPUT "MATRIX SIZE:"; SIZE% +110 GOSUB 200"IDENTITYMATRIX +120 FOR R = 0 TO SIZE% +130 FOR C = 0 TO SIZE% +140 LET S$ = CHR$(13) +150 IF C < SIZE% THEN S$ = " " +160 PRINT IM(R, C) S$; : NEXT C, R +170 END + +200 REMIDENTITYMATRIX SIZE% +210 LET SIZE% = SIZE% - 1 +220 DIM IM(SIZE%, SIZE%) +230 FOR I = 0 TO SIZE% +240 LET IM(I, I) = 1 : NEXT I +250 RETURN :IM diff --git a/Task/Identity-matrix/Delphi/identity-matrix.delphi b/Task/Identity-matrix/Delphi/identity-matrix.delphi new file mode 100644 index 0000000000..0487a2e4f3 --- /dev/null +++ b/Task/Identity-matrix/Delphi/identity-matrix.delphi @@ -0,0 +1,25 @@ +program IdentityMatrix; + +// Modified from the Pascal version + +{$APPTYPE CONSOLE} + +var + matrix: array of array of integer; + n, i, j: integer; + +begin + write('Size of matrix: '); + readln(n); + setlength(matrix, n, n); + + for i := 0 to n - 1 do + matrix[i,i] := 1; + + for i := 0 to n - 1 do + begin + for j := 0 to n - 1 do + write (matrix[i,j], ' '); + writeln; + end; +end. diff --git a/Task/Identity-matrix/Elixir/identity-matrix.elixir b/Task/Identity-matrix/Elixir/identity-matrix.elixir new file mode 100644 index 0000000000..29f018ca4b --- /dev/null +++ b/Task/Identity-matrix/Elixir/identity-matrix.elixir @@ -0,0 +1,9 @@ +defmodule Matrix do + def identity(n) do + Enum.map(0..n-1, fn i -> + for j <- 0..n-1, do: (if i==j, do: 1, else: 0) + end) + end +end + +IO.inspect Matrix.identity(5) diff --git a/Task/Identity-matrix/Fortran/identity-matrix.f b/Task/Identity-matrix/Fortran/identity-matrix-1.f similarity index 100% rename from Task/Identity-matrix/Fortran/identity-matrix.f rename to Task/Identity-matrix/Fortran/identity-matrix-1.f diff --git a/Task/Identity-matrix/Fortran/identity-matrix-2.f b/Task/Identity-matrix/Fortran/identity-matrix-2.f new file mode 100644 index 0000000000..eecf70d17c --- /dev/null +++ b/Task/Identity-matrix/Fortran/identity-matrix-2.f @@ -0,0 +1,9 @@ + Program Identity + Integer N + Parameter (N = 666) + Real A(N,N) + Integer i,j + + ForAll(i = 1:N, j = 1:N) A(i,j) = (i/j)*(j/i) + + END diff --git a/Task/Identity-matrix/Go/identity-matrix-1.go b/Task/Identity-matrix/Go/identity-matrix-1.go index 60dcbdcf4d..71ac78ad91 100644 --- a/Task/Identity-matrix/Go/identity-matrix-1.go +++ b/Task/Identity-matrix/Go/identity-matrix-1.go @@ -1,18 +1,19 @@ package main -import "fmt" +import ( + "fmt" -func main() { - fmt.Println(I(3)) -} + "github.com/gonum/matrix/mat64" +) -func I(n int) [][]float64 { - m := make([][]float64, n) - a := make([]float64, n*n) +func eye(n int) *mat64.Dense { + m := mat64.NewDense(n, n, nil) for i := 0; i < n; i++ { - a[i] = 1 - m[i] = a[:n] - a = a[n:] + m.Set(i, i, 1) } return m } + +func main() { + fmt.Println(mat64.Formatted(eye(3))) +} diff --git a/Task/Identity-matrix/Go/identity-matrix-2.go b/Task/Identity-matrix/Go/identity-matrix-2.go index 713b60d5f9..a941c4e97d 100644 --- a/Task/Identity-matrix/Go/identity-matrix-2.go +++ b/Task/Identity-matrix/Go/identity-matrix-2.go @@ -1,18 +1,11 @@ package main -import "fmt" +import ( + "fmt" -type matrix []float64 + mat "github.com/skelterjohn/go.matrix" +) func main() { - fmt.Println(I(3)) -} - -func I(n int) matrix { - m := make(matrix, n*n) - n++ - for i := 0; i < len(m); i += n { - m[i] = 1 - } - return m + fmt.Println(mat.Eye(3)) } diff --git a/Task/Identity-matrix/Go/identity-matrix-3.go b/Task/Identity-matrix/Go/identity-matrix-3.go index a941c4e97d..50fc761e32 100644 --- a/Task/Identity-matrix/Go/identity-matrix-3.go +++ b/Task/Identity-matrix/Go/identity-matrix-3.go @@ -1,11 +1,17 @@ package main -import ( - "fmt" - - mat "github.com/skelterjohn/go.matrix" -) +import "fmt" func main() { - fmt.Println(mat.Eye(3)) + fmt.Println(I(3)) +} + +func I(n int) [][]float64 { + m := make([][]float64, n) + for i := 0; i < n; i++ { + a := make([]float64, n) + a[i] = 1 + m[i] = a + } + return m } diff --git a/Task/Identity-matrix/Go/identity-matrix-4.go b/Task/Identity-matrix/Go/identity-matrix-4.go new file mode 100644 index 0000000000..60dcbdcf4d --- /dev/null +++ b/Task/Identity-matrix/Go/identity-matrix-4.go @@ -0,0 +1,18 @@ +package main + +import "fmt" + +func main() { + fmt.Println(I(3)) +} + +func I(n int) [][]float64 { + m := make([][]float64, n) + a := make([]float64, n*n) + for i := 0; i < n; i++ { + a[i] = 1 + m[i] = a[:n] + a = a[n:] + } + return m +} diff --git a/Task/Identity-matrix/Go/identity-matrix-5.go b/Task/Identity-matrix/Go/identity-matrix-5.go new file mode 100644 index 0000000000..9be0bcde73 --- /dev/null +++ b/Task/Identity-matrix/Go/identity-matrix-5.go @@ -0,0 +1,34 @@ +package main + +import "fmt" + +type matrix []float64 + +func main() { + n := 3 + m := I(n) + // dump flat represenation + fmt.Println(m) + + // function x turns a row and column into an index into the + // flat representation. + x := func(r, c int) int { return r*n + c } + + // access m by row and column. + for r := 0; r < n; r++ { + for c := 0; c < n; c++ { + fmt.Print(m[x(r, c)], " ") + } + fmt.Println() + } +} + +func I(n int) matrix { + m := make(matrix, n*n) + // a fast way to initialize the flat representation + n++ + for i := 0; i < len(m); i += n { + m[i] = 1 + } + return m +} diff --git a/Task/Identity-matrix/Perl-6/identity-matrix-1.pl6 b/Task/Identity-matrix/Perl-6/identity-matrix-1.pl6 index dcc824e645..3bef68b777 100644 --- a/Task/Identity-matrix/Perl-6/identity-matrix-1.pl6 +++ b/Task/Identity-matrix/Perl-6/identity-matrix-1.pl6 @@ -1,6 +1,6 @@ sub identity-matrix($n) { my @id; - for ^$n X ^$n -> $i, $j { + for flat ^$n X ^$n -> $i, $j { @id[$i][$j] = +($i == $j); } @id; diff --git a/Task/Identity-matrix/Perl-6/identity-matrix-3.pl6 b/Task/Identity-matrix/Perl-6/identity-matrix-3.pl6 index a0be623cce..fee0567cbe 100644 --- a/Task/Identity-matrix/Perl-6/identity-matrix-3.pl6 +++ b/Task/Identity-matrix/Perl-6/identity-matrix-3.pl6 @@ -1,3 +1,3 @@ sub identity-matrix($n) { - [1, 0 xx $n-1], *.rotate(-1).item ... *[*-1] == 1 + ([1, |(0 xx $n-1)].item, *.rotate(-1).item ... *)[^$n] } diff --git a/Task/Identity-matrix/PowerShell/identity-matrix-1.psh b/Task/Identity-matrix/PowerShell/identity-matrix-1.psh new file mode 100644 index 0000000000..c3b099c293 --- /dev/null +++ b/Task/Identity-matrix/PowerShell/identity-matrix-1.psh @@ -0,0 +1,21 @@ +function id($n) { + if($n -gt 0) { + $array = @(1..$n | foreach{ @(0) }) + 0..($n-1) | foreach{ + $i = $_ + $array[$i] = @(switch(0..($n-1)){ + $i {1} + default {0} + }) + } + $array + } else { @() } +} +function show($a) { + if($a.Count -gt 0) { + $n = $a.Count - 1 + 0..$n | foreach{ "$($a[$_][0..$n])" } + } +} +$array = id 4 +show $array diff --git a/Task/Identity-matrix/PowerShell/identity-matrix-2.psh b/Task/Identity-matrix/PowerShell/identity-matrix-2.psh new file mode 100644 index 0000000000..cc27242e94 --- /dev/null +++ b/Task/Identity-matrix/PowerShell/identity-matrix-2.psh @@ -0,0 +1,2 @@ +$array[0][0] +$array[0][1] diff --git a/Task/Identity-matrix/VBScript/identity-matrix.vb b/Task/Identity-matrix/VBScript/identity-matrix.vb new file mode 100644 index 0000000000..5c7a77dd67 --- /dev/null +++ b/Task/Identity-matrix/VBScript/identity-matrix.vb @@ -0,0 +1,29 @@ +build_matrix(7) + +Sub build_matrix(n) + Dim matrix() + ReDim matrix(n-1,n-1) + i = 0 + 'populate the matrix + For row = 0 To n-1 + For col = 0 To n-1 + If col = i Then + matrix(row,col) = 1 + Else + matrix(row,col) = 0 + End If + Next + i = i + 1 + Next + 'display the matrix + For row = 0 To n-1 + For col = 0 To n-1 + If col < n-1 Then + WScript.StdOut.Write matrix(row,col) & " " + Else + WScript.StdOut.Write matrix(row,col) + End If + Next + WScript.StdOut.WriteLine + Next +End Sub diff --git a/Task/Image-convolution/J/image-convolution-1.j b/Task/Image-convolution/J/image-convolution-1.j new file mode 100644 index 0000000000..8b02c0ee90 --- /dev/null +++ b/Task/Image-convolution/J/image-convolution-1.j @@ -0,0 +1,10 @@ +NB. pad the edges of an array with border pixels +NB. (increasing the first two dimensions by 1 less than the kernel size) +pad=: adverb define + 'a b'=. (<. ,. >.) 0.5 0.5 p. $m + a"_`(0 , ] - 1:)`(# 1:)}~&# # b"_`(0 , ] - 1:)`(# 1:)}~&(1 { $) #"1 ] +) + +kernel_filter=: adverb define + ($m)+/ .*&(,m)&(,/);._3 m pad +) diff --git a/Task/Image-convolution/J/image-convolution-2.j b/Task/Image-convolution/J/image-convolution-2.j new file mode 100644 index 0000000000..bdbcf356fa --- /dev/null +++ b/Task/Image-convolution/J/image-convolution-2.j @@ -0,0 +1,7 @@ + NB. kernels borrowed from C and TCL implementations + sharpen_kernel=: _1+10*4=i.3 3 + blur_kernel=: 3 3$%9 + emboss_kernel=: _2 _1 0,_1 1 1,:0 1 2 + sobel_emboss_kernel=: _1 _2 _1,0,:1 2 1 + + 'blurred.ppm' writeppm~ blur_kernel kernel_filter readppm 'original.ppm' diff --git a/Task/Image-convolution/J/image-convolution.j b/Task/Image-convolution/J/image-convolution.j deleted file mode 100644 index 8c7ea93a61..0000000000 --- a/Task/Image-convolution/J/image-convolution.j +++ /dev/null @@ -1,11 +0,0 @@ -NB. pad the first n dimensions of an array with zeros -NB. (increasing all dimensions by 1 less than the kernel size) -pad=: adverb define - adj1=: <.m%2 - adj2=: m-1 - (-@(adj2 + ]) {. (adj1 + ]) {. [) (#m) {. $ -) - -kernel_filter=: adverb define - [: ,/"(-#$m) ($m) +/@(,/^:(_1+#$m))@:*&m;._3 ($m)pad -) diff --git a/Task/Image-convolution/JavaScript/image-convolution.js b/Task/Image-convolution/JavaScript/image-convolution.js new file mode 100644 index 0000000000..ad853c9d95 --- /dev/null +++ b/Task/Image-convolution/JavaScript/image-convolution.js @@ -0,0 +1,76 @@ +// Image imageIn, Array kernel, function (Error error, Image imageOut) +// precondition: Image is loaded +// returns loaded Image to asynchronous callback function +function convolve(imageIn, kernel, callback) { + var dim = Math.sqrt(kernel.length), + pad = Math.floor(dim / 2); + + if (dim % 2 !== 1) { + return callback(new RangeError("Invalid kernel dimension"), null); + } + + var w = imageIn.width, + h = imageIn.height, + can = document.createElement('canvas'), + cw, + ch, + ctx, + imgIn, imgOut, + datIn, datOut; + + can.width = cw = w + pad * 2; // add padding + can.height = ch = h + pad * 2; // add padding + + ctx = can.getContext('2d'); + ctx.fillStyle = '#000'; // fill with opaque black + ctx.fillRect(0, 0, cw, ch); + ctx.drawImage(imageIn, pad, pad); + + imgIn = ctx.getImageData(0, 0, cw, ch); + datIn = imgIn.data; + + imgOut = ctx.createImageData(w, h); + datOut = imgOut.data; + + var row, col, pix, i, dx, dy, r, g, b; + + for (row = pad; row <= h; row++) { + for (col = pad; col <= w; col++) { + r = g = b = 0; + + for (dx = -pad; dx <= pad; dx++) { + for (dy = -pad; dy <= pad; dy++) { + i = (dy + pad) * dim + (dx + pad); // kernel index + pix = 4 * ((row + dy) * cw + (col + dx)); // image index + r += datIn[pix++] * kernel[i]; + g += datIn[pix++] * kernel[i]; + b += datIn[pix ] * kernel[i]; + } + } + + pix = 4 * ((row - pad) * w + (col - pad)); // destination index + datOut[pix++] = (r + .5) ^ 0; + datOut[pix++] = (g + .5) ^ 0; + datOut[pix++] = (b + .5) ^ 0; + datOut[pix ] = 255; // we want opaque image + } + } + + // reuse canvas + can.width = w; + can.height = h; + + ctx.putImageData(imgOut, 0, 0); + + var imageOut = new Image(); + + imageOut.addEventListener('load', function () { + callback(null, imageOut); + }); + + imageOut.addEventListener('error', function (error) { + callback(error, null); + }); + + imageOut.src = can.toDataURL('image/png'); +} diff --git a/Task/Image-noise/00DESCRIPTION b/Task/Image-noise/00DESCRIPTION index 0fd43fe6ad..14a0c6eee6 100644 --- a/Task/Image-noise/00DESCRIPTION +++ b/Task/Image-noise/00DESCRIPTION @@ -6,6 +6,7 @@ {{omit from|MIRC Scripting Language}} {{omit from|ML/I}} {{omit from|Sed}} +{{omit from|Batch File}} [[Category:Raster graphics operations]] Generate a random black and white 320x240 image continuously, showing FPS (frames per second). diff --git a/Task/Image-noise/Perl-6/image-noise.pl6 b/Task/Image-noise/Perl-6/image-noise.pl6 index e9ee3d0c31..98510ed4f6 100644 --- a/Task/Image-noise/Perl-6/image-noise.pl6 +++ b/Task/Image-noise/Perl-6/image-noise.pl6 @@ -26,8 +26,10 @@ sub render { SDL_SetRenderDrawColor($renderer, 0, 0, 0, 0); SDL_RenderClear($renderer); SDL_SetRenderDrawColor($renderer, 255, 255, 255, 0); - for ^$w X ^$h -> $i, $j { - SDL_RenderDrawPoint( $renderer, $i, $j ) if rand < .5; + loop (my int $i; $i < $w; $i = $i + 1) { + loop (my int $j; $j < $h; $j = $j + 1) { + SDL_RenderDrawPoint( $renderer, $i, $j ) if Bool.pick + } } SDL_RenderPresent($renderer); } diff --git a/Task/Image-noise/REXX/image-noise.rexx b/Task/Image-noise/REXX/image-noise.rexx new file mode 100644 index 0000000000..0e78dab6f1 --- /dev/null +++ b/Task/Image-noise/REXX/image-noise.rexx @@ -0,0 +1,23 @@ +/*REXX program times the generation of 100 frames of random black&white image.*/ +parse arg sw sd im . /*obtain optional args from the C.L. */ +if sw==',' | sw=='' then sw=320 /*SW specified? No, then use default.*/ +if sd==',' | sd=='' then sd=240 /*SD " " " " " */ +if im==',' | im=='' then im=100 /*IM " " " " " */ +call time 'R' /*reset the REXX elapsed (clock) timer.*/ + do frame=1 for im /*generate IM number of images. */ + call genFrame sw,sd /*generate single image of size SW x SD*/ + /* say frame */ /*do (or don't) display the frame num. */ + end /*frame*/ /*generate, but don't display the image*/ + /*measures ↓ elapsed time in seconds.*/ +say 'The average frames/second: ' format(im/time("E"),,2) /*show FPS stat.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +genFrame: parse arg x,y; @.0='ff000000'x /*hex: black. */ + @.1='ffffffff'x /*hex: white. */ +$= /*nullify image*/ + do y; _= /*nullify a row*/ + do x; ?=random(0,1); _=_ || @.? /*black │ white*/ + end /*x*/ + $=$ || _ /*append to $. */ + end /*y*/ +return diff --git a/Task/Include-a-file/360-Assembly/include-a-file.360 b/Task/Include-a-file/360-Assembly/include-a-file.360 new file mode 100644 index 0000000000..751e8b582b --- /dev/null +++ b/Task/Include-a-file/360-Assembly/include-a-file.360 @@ -0,0 +1 @@ + COPY member diff --git a/Task/Include-a-file/Emacs-Lisp/include-a-file-1.l b/Task/Include-a-file/Emacs-Lisp/include-a-file-1.l new file mode 100644 index 0000000000..4141bb9e83 --- /dev/null +++ b/Task/Include-a-file/Emacs-Lisp/include-a-file-1.l @@ -0,0 +1,2 @@ +(defun sum (ls) + (apply '+ ls) ) diff --git a/Task/Include-a-file/Emacs-Lisp/include-a-file-2.l b/Task/Include-a-file/Emacs-Lisp/include-a-file-2.l new file mode 100644 index 0000000000..afc7a868da --- /dev/null +++ b/Task/Include-a-file/Emacs-Lisp/include-a-file-2.l @@ -0,0 +1,3 @@ +(add-to-list 'load-path "./") +(load "./file1.el") +(insert (format "%d" (sum (number-sequence 1 100) ))) diff --git a/Task/Include-a-file/Logtalk/include-a-file.logtalk b/Task/Include-a-file/Logtalk/include-a-file.logtalk new file mode 100644 index 0000000000..4c65727b51 --- /dev/null +++ b/Task/Include-a-file/Logtalk/include-a-file.logtalk @@ -0,0 +1,5 @@ +:- object(foo). + + :- include(bar). + +:- end_object. diff --git a/Task/Include-a-file/Modula-3/include-a-file.mod3 b/Task/Include-a-file/Modula-3/include-a-file.mod3 new file mode 100644 index 0000000000..ed2739b859 --- /dev/null +++ b/Task/Include-a-file/Modula-3/include-a-file.mod3 @@ -0,0 +1,2 @@ +IMPORT IO, Text AS Str; +FROM Str IMPORT T diff --git a/Task/Include-a-file/REXX/include-a-file.rexx b/Task/Include-a-file/REXX/include-a-file-1.rexx similarity index 100% rename from Task/Include-a-file/REXX/include-a-file.rexx rename to Task/Include-a-file/REXX/include-a-file-1.rexx diff --git a/Task/Include-a-file/REXX/include-a-file-2.rexx b/Task/Include-a-file/REXX/include-a-file-2.rexx new file mode 100644 index 0000000000..cd3b9fd001 --- /dev/null +++ b/Task/Include-a-file/REXX/include-a-file-2.rexx @@ -0,0 +1,14 @@ +/* Include a file and INTERPRET it; this code uses ARexx file IO BIFs */ +say 'This is a program running.' +if Open(other,'SYS:Rexxc/otherprogram.rexx','READ') then do + say "Now we opened a file with another chunk of code. Let's read it into a variable." + othercode='' + do until EOF(other) + othercode=othercode || ReadLn(other) || ';' + end + call Close(other) + say 'Now we run it as part of our program.' + interpret othercode + end +say 'The usual program resumes here.' +exit 0 diff --git a/Task/Include-a-file/REXX/include-a-file-3.rexx b/Task/Include-a-file/REXX/include-a-file-3.rexx new file mode 100644 index 0000000000..ff3e7a3dc8 --- /dev/null +++ b/Task/Include-a-file/REXX/include-a-file-3.rexx @@ -0,0 +1,5 @@ +/* This is program 1 */ +say 'This is program 1 writing on standard output.' +call Program2 +say 'Thank you, program 1 is now ending.' +exit 0 diff --git a/Task/Include-a-file/REXX/include-a-file-4.rexx b/Task/Include-a-file/REXX/include-a-file-4.rexx new file mode 100644 index 0000000000..b720582c89 --- /dev/null +++ b/Task/Include-a-file/REXX/include-a-file-4.rexx @@ -0,0 +1,4 @@ +/* This is program 2 */ +say 'This is program 2 writing on standard output.' +say 'We now return to the caller.' +return diff --git a/Task/Include-a-file/RapidQ/include-a-file.rapidq b/Task/Include-a-file/RapidQ/include-a-file.rapidq new file mode 100644 index 0000000000..83357a4f3d --- /dev/null +++ b/Task/Include-a-file/RapidQ/include-a-file.rapidq @@ -0,0 +1 @@ +$INCLUDE "RAPIDQ.INC" diff --git a/Task/Include-a-file/Rust/include-a-file.rust b/Task/Include-a-file/Rust/include-a-file.rust new file mode 100644 index 0000000000..3259fe3bf9 --- /dev/null +++ b/Task/Include-a-file/Rust/include-a-file.rust @@ -0,0 +1,5 @@ +mod test + +fn main() { + test::some_function(); +} diff --git a/Task/Increment-a-numerical-string/Eiffel/increment-a-numerical-string.e b/Task/Increment-a-numerical-string/Eiffel/increment-a-numerical-string.e index aff985c367..e24b8ec5b9 100644 --- a/Task/Increment-a-numerical-string/Eiffel/increment-a-numerical-string.e +++ b/Task/Increment-a-numerical-string/Eiffel/increment-a-numerical-string.e @@ -1,17 +1,22 @@ class APPLICATION -inherit - ARGUMENTS + create make -feature {NONE} -- Initialization -make - do - inc("23") - end -inc(s:STRING) - do - io.put_string (s.to_integer.plus (1).out) - end +feature {NONE} + + make + do + io.put_string (increment_numerical_string ("7")) + io.new_line + io.put_string (increment_numerical_string ("99")) + end + + increment_numerical_string (s: STRING): STRING + -- String 's' incremented by one. + do + Result := s.to_integer.plus (1).out + end + end diff --git a/Task/Increment-a-numerical-string/Elixir/increment-a-numerical-string-1.elixir b/Task/Increment-a-numerical-string/Elixir/increment-a-numerical-string-1.elixir new file mode 100644 index 0000000000..26fd2d72e2 --- /dev/null +++ b/Task/Increment-a-numerical-string/Elixir/increment-a-numerical-string-1.elixir @@ -0,0 +1,6 @@ +increment1 = fn n -> to_string(String.to_integer(n) + 1) end +# Or piped +increment2 = fn n -> n |> String.to_integer |> +1 |> to_string end + +increment1.("1") +increment2.("100") diff --git a/Task/Increment-a-numerical-string/Elixir/increment-a-numerical-string-2.elixir b/Task/Increment-a-numerical-string/Elixir/increment-a-numerical-string-2.elixir new file mode 100644 index 0000000000..cf3b09d863 --- /dev/null +++ b/Task/Increment-a-numerical-string/Elixir/increment-a-numerical-string-2.elixir @@ -0,0 +1,2 @@ +iex(1)> (List.to_integer('12345') + 1) |> to_char_list +'12346' diff --git a/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia b/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia index fb52ededa8..c8b21c652e 100644 --- a/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia +++ b/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia @@ -1 +1 @@ -+(s::String, n::Integer) = string(parseint(typeof(n), s) + n) ++(s::String, n::Integer) = string(parse(Int, s) + n) diff --git a/Task/Increment-a-numerical-string/Rust/increment-a-numerical-string.rust b/Task/Increment-a-numerical-string/Rust/increment-a-numerical-string.rust index 6df29148c0..e7d30c39de 100644 --- a/Task/Increment-a-numerical-string/Rust/increment-a-numerical-string.rust +++ b/Task/Increment-a-numerical-string/Rust/increment-a-numerical-string.rust @@ -1,8 +1,9 @@ -// rust 0.9-pre +fn next_string(input: &str) -> String { + (input.parse::().unwrap() + 1).to_string() +} fn main() { let s = "-1"; - let s = (from_str::(s).unwrap() + 1).to_str(); - assert_eq!(s, ~"0"); - println(s); + let s2 = next_string(s); + println!("{:?}", s2); } diff --git a/Task/Infinity/Rust/infinity.rust b/Task/Infinity/Rust/infinity.rust index 7cded29da7..48cafb11c3 100644 --- a/Task/Infinity/Rust/infinity.rust +++ b/Task/Infinity/Rust/infinity.rust @@ -1,4 +1,4 @@ fn main() { - let inf : f32 = Float::infinity(); + let inf = std::f32::INFINITY; println!("{}", inf); } diff --git a/Task/Inheritance-Multiple/Forth/inheritance-multiple.fth b/Task/Inheritance-Multiple/Forth/inheritance-multiple.fth new file mode 100644 index 0000000000..802704793b --- /dev/null +++ b/Task/Inheritance-Multiple/Forth/inheritance-multiple.fth @@ -0,0 +1,14 @@ +include FMS-MIBuildGen.f +include FMS-MIHarnGen.f +include FMS-MI.f + +:class Camera +;class + +:class MobilePhone +;class + +:class CameraPhone super{ Camera MobilePhone } \ any number of superclasses may be used +;class + +CameraPhone cf \ instantiate a CameraPhone object named cf diff --git a/Task/Inheritance-Multiple/Self/inheritance-multiple-1.self b/Task/Inheritance-Multiple/Self/inheritance-multiple-1.self new file mode 100644 index 0000000000..ff546e4a32 --- /dev/null +++ b/Task/Inheritance-Multiple/Self/inheritance-multiple-1.self @@ -0,0 +1 @@ +camera = () diff --git a/Task/Inheritance-Multiple/Self/inheritance-multiple-2.self b/Task/Inheritance-Multiple/Self/inheritance-multiple-2.self new file mode 100644 index 0000000000..220ea89fd1 --- /dev/null +++ b/Task/Inheritance-Multiple/Self/inheritance-multiple-2.self @@ -0,0 +1 @@ +mobilePhone = () diff --git a/Task/Inheritance-Multiple/Self/inheritance-multiple-3.self b/Task/Inheritance-Multiple/Self/inheritance-multiple-3.self new file mode 100644 index 0000000000..0b55c20276 --- /dev/null +++ b/Task/Inheritance-Multiple/Self/inheritance-multiple-3.self @@ -0,0 +1 @@ +cameraPhone = (| cameraParent* = camera. mobilePhoneParent* = mobilePhone |) diff --git a/Task/Inheritance-Single/Forth/inheritance-single.fth b/Task/Inheritance-Single/Forth/inheritance-single-1.fth similarity index 100% rename from Task/Inheritance-Single/Forth/inheritance-single.fth rename to Task/Inheritance-Single/Forth/inheritance-single-1.fth diff --git a/Task/Inheritance-Single/Forth/inheritance-single-2.fth b/Task/Inheritance-Single/Forth/inheritance-single-2.fth new file mode 100644 index 0000000000..aa39161657 --- /dev/null +++ b/Task/Inheritance-Single/Forth/inheritance-single-2.fth @@ -0,0 +1,7 @@ +include FMS-SI.f + +:class Animal ;class +:class Dog :ok + data -> IO.write data + input_loop(stream) + end + end +end + +path = hd(System.argv) +File.open!(path, [:read], fn stream -> RC.input_loop(stream) end) diff --git a/Task/Input-loop/Frink/input-loop.frink b/Task/Input-loop/Frink/input-loop.frink new file mode 100644 index 0000000000..d1e3b17a91 --- /dev/null +++ b/Task/Input-loop/Frink/input-loop.frink @@ -0,0 +1,2 @@ +while (line = readStdin[]) != undef + println[line] diff --git a/Task/Input-loop/Perl-6/input-loop-1.pl6 b/Task/Input-loop/Perl-6/input-loop-1.pl6 new file mode 100644 index 0000000000..ab18168a3c --- /dev/null +++ b/Task/Input-loop/Perl-6/input-loop-1.pl6 @@ -0,0 +1,3 @@ +for "filename.txt".IO.lines -> $line { + ... +} diff --git a/Task/Input-loop/Perl-6/input-loop-2.pl6 b/Task/Input-loop/Perl-6/input-loop-2.pl6 new file mode 100644 index 0000000000..4c61c55808 --- /dev/null +++ b/Task/Input-loop/Perl-6/input-loop-2.pl6 @@ -0,0 +1,3 @@ +for $*IN.lines -> $line { + ... +} diff --git a/Task/Input-loop/Perl-6/input-loop-3.pl6 b/Task/Input-loop/Perl-6/input-loop-3.pl6 new file mode 100644 index 0000000000..f9c297b596 --- /dev/null +++ b/Task/Input-loop/Perl-6/input-loop-3.pl6 @@ -0,0 +1,3 @@ +for pipe("find -iname '*.txt'").lines -> $filename { + ... +} diff --git a/Task/Input-loop/Perl-6/input-loop-4.pl6 b/Task/Input-loop/Perl-6/input-loop-4.pl6 new file mode 100644 index 0000000000..861b446d15 --- /dev/null +++ b/Task/Input-loop/Perl-6/input-loop-4.pl6 @@ -0,0 +1,3 @@ +for pipe("find -iname '*.txt' -print0", :nl«\0»).lines -> $filename { + ... +} diff --git a/Task/Input-loop/Perl-6/input-loop-5.pl6 b/Task/Input-loop/Perl-6/input-loop-5.pl6 new file mode 100644 index 0000000000..adcf405c80 --- /dev/null +++ b/Task/Input-loop/Perl-6/input-loop-5.pl6 @@ -0,0 +1,3 @@ +for "filename.txt".IO.words -> $word { + ... +} diff --git a/Task/Input-loop/Perl-6/input-loop.pl6 b/Task/Input-loop/Perl-6/input-loop.pl6 deleted file mode 100644 index 54202e7c1e..0000000000 --- a/Task/Input-loop/Perl-6/input-loop.pl6 +++ /dev/null @@ -1,10 +0,0 @@ -my $handle = open "filename.txt"; # $handle could be $*IN to read from standard input - -for $handle.lines -> $line { # iterates the lines of the $handle - - # line endings are automatically stripped - - for $line.words -> $word { # iterates the words of the line - # are considered words groups of non-whitespace characters - } -} diff --git a/Task/Integer-comparison/ALGOL-W/integer-comparison.alg b/Task/Integer-comparison/ALGOL-W/integer-comparison.alg new file mode 100644 index 0000000000..8a425edc5c --- /dev/null +++ b/Task/Integer-comparison/ALGOL-W/integer-comparison.alg @@ -0,0 +1,14 @@ +begin + + integer a, b; + + write( "first number: " ); + read( a ); + write( "second number: " ); + read( b ); + + if a < b then write( a, " is less than ", b ); + if a = b then write( a, " is equal to ", b ); + if a > b then write( a, " is greater than ", b ); + +end. diff --git a/Task/Integer-comparison/Batch-File/integer-comparison.bat b/Task/Integer-comparison/Batch-File/integer-comparison.bat new file mode 100644 index 0000000000..f82e059f69 --- /dev/null +++ b/Task/Integer-comparison/Batch-File/integer-comparison.bat @@ -0,0 +1,11 @@ +@echo off +setlocal EnableDelayedExpansion +set /p a="A: " +set /p b="B: " +if %a% LSS %b% ( + echo %a% is less than %b% +) else ( if %a% GTR %b% ( + echo %a% is greater than %b% +) else ( if %a% EQU %b% ( + echo %a% is equal to %b% +))) diff --git a/Task/Integer-comparison/ColdFusion/integer-comparison-1.cfm b/Task/Integer-comparison/ColdFusion/integer-comparison-1.cfm new file mode 100644 index 0000000000..3738b05f1b --- /dev/null +++ b/Task/Integer-comparison/ColdFusion/integer-comparison-1.cfm @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Task/Integer-comparison/ColdFusion/integer-comparison-2.cfm b/Task/Integer-comparison/ColdFusion/integer-comparison-2.cfm new file mode 100644 index 0000000000..900ef764f9 --- /dev/null +++ b/Task/Integer-comparison/ColdFusion/integer-comparison-2.cfm @@ -0,0 +1,24 @@ + + function CompareInteger( Integer1, Integer2 ) { + VARIABLES.Result = ""; + if ( ARGUMENTS.Integer1 LT ARGUMENTS.Integer2 ) { + VARIABLES.Result = VARIABLES.Result & "(" & ARGUMENTS.Integer1 & " is less than " & ARGUMENTS.Integer2 & ")"; + } + if ( ARGUMENTS.Integer1 LTE ARGUMENTS.Integer2 ) { + VARIABLES.Result = VARIABLES.Result & "(" & ARGUMENTS.Integer1 & " is less than or equal to " & ARGUMENTS.Integer2 & ")"; + } + if ( ARGUMENTS.Integer1 GT ARGUMENTS.Integer2 ) { + VARIABLES.Result = VARIABLES.Result & "(" & ARGUMENTS.Integer1 & " is greater than " & ARGUMENTS.Integer2 & ")"; + } + if ( ARGUMENTS.Integer1 GTE ARGUMENTS.Integer2 ) { + VARIABLES.Result = VARIABLES.Result & "(" & ARGUMENTS.Integer1 & " is greater than or equal to " & ARGUMENTS.Integer2 & ")"; + } + if ( ARGUMENTS.Integer1 EQ ARGUMENTS.Integer2 ) { + VARIABLES.Result = VARIABLES.Result & "(" & ARGUMENTS.Integer1 & " is equal to " & ARGUMENTS.Integer2 & ")"; + } + if ( ARGUMENTS.Integer1 NEQ ARGUMENTS.Integer2 ) { + VARIABLES.Result = VARIABLES.Result & "(" & ARGUMENTS.Integer1 & " is not equal to " & ARGUMENTS.Integer2 & ")"; + } + return VARIABLES.Result; + } + diff --git a/Task/Integer-comparison/DCL/integer-comparison.dcl b/Task/Integer-comparison/DCL/integer-comparison.dcl new file mode 100644 index 0000000000..e12894cca2 --- /dev/null +++ b/Task/Integer-comparison/DCL/integer-comparison.dcl @@ -0,0 +1,5 @@ +$ inquire a "Please provide an integer" +$ inquire b "Please provide another" +$ if a .lt. b then $ write sys$output "the first integer is less" +$ if a .eq. b then $ write sys$output "the integers have the same value" +$ if a .gt. b then $ write sys$output "the first integer is greater" diff --git a/Task/Integer-comparison/Eiffel/integer-comparison.e b/Task/Integer-comparison/Eiffel/integer-comparison.e new file mode 100644 index 0000000000..19ce17a0c8 --- /dev/null +++ b/Task/Integer-comparison/Eiffel/integer-comparison.e @@ -0,0 +1,30 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make + +feature {NONE} -- Initialization + + make + local + i, j: INTEGER_32 + do + io.read_integer_32 + i := io.last_integer_32 + + io.read_integer_32 + j := io.last_integer_32 + + if i < j then + print("first is less than second%N") + end + if i = j then + print("first is equal to the second%N") + end + if i > j then + print("first is greater than second%N") + end + end +end diff --git a/Task/Integer-comparison/Elixir/integer-comparison.elixir b/Task/Integer-comparison/Elixir/integer-comparison.elixir new file mode 100644 index 0000000000..2d4d51e34d --- /dev/null +++ b/Task/Integer-comparison/Elixir/integer-comparison.elixir @@ -0,0 +1,11 @@ +{a,_} = IO.gets("Enter your first integer: ") |> Integer.parse +{b,_} = IO.gets("Enter your second integer: ") |> Integer.parse + +cond do + a < b -> + IO.puts "#{a} is less than #{b}" + a > b -> + IO.puts "#{a} is greater than #{b}" + a == b -> + IO.puts "#{a} is equal to #{b}" +end diff --git a/Task/Integer-comparison/Emacs-Lisp/integer-comparison.l b/Task/Integer-comparison/Emacs-Lisp/integer-comparison.l new file mode 100644 index 0000000000..ab4b203617 --- /dev/null +++ b/Task/Integer-comparison/Emacs-Lisp/integer-comparison.l @@ -0,0 +1,7 @@ +(progn + (if (< 1 2) (insert "True\n") (insert "False\n") ) + (if (= 1 2) (insert "True\n") (insert "False\n") ) + (if (= 1 1) (insert "True\n") (insert "False\n") ) + (if (> 1 2) (insert "True\n") (insert "False\n") ) + (if (<= 1 2) (insert "True\n") (insert "False\n") ) + (if (>= 1 2) (insert "True\n") (insert "False\n") )) diff --git a/Task/Integer-comparison/JavaScript/integer-comparison.js b/Task/Integer-comparison/JavaScript/integer-comparison.js index 7d2efaed2f..693acfd7c0 100644 --- a/Task/Integer-comparison/JavaScript/integer-comparison.js +++ b/Task/Integer-comparison/JavaScript/integer-comparison.js @@ -21,6 +21,6 @@ function compare (a, b) { } } else { // "1" and 1 are an example of this as the first is type string and the second is type number - print(a + "{" + (typeof a) + "} and " + b + "{" + (typeof b) + "} are not of the same type 4and cannot be compared."); + print(a + "{" + (typeof a) + "} and " + b + "{" + (typeof b) + "} are not of the same type and cannot be compared."); } } diff --git a/Task/Integer-comparison/NewLISP/integer-comparison.newlisp b/Task/Integer-comparison/NewLISP/integer-comparison.newlisp new file mode 100644 index 0000000000..5dcdd83edc --- /dev/null +++ b/Task/Integer-comparison/NewLISP/integer-comparison.newlisp @@ -0,0 +1,11 @@ +(print "Please enter the first number: ") +(set 'A (int (read-line))) +(print "Please enter the second number: ") +(set 'B (int (read-line))) +(println +"The first one is " + (cond + ((> A B) "greater than") + ((= A B) "equal to") + (true "less than")) +" the second.") diff --git a/Task/Integer-comparison/Python/integer-comparison-1.py b/Task/Integer-comparison/Python/integer-comparison-1.py index 1136e53130..e91983c46c 100644 --- a/Task/Integer-comparison/Python/integer-comparison-1.py +++ b/Task/Integer-comparison/Python/integer-comparison-1.py @@ -1,6 +1,6 @@ #!/usr/bin/env python -a = int(raw_input('Enter value of a: ')) -b = int(raw_input('Enter value of b: ')) +a = input('Enter value of a: ') +b = input('Enter value of b: ') if a < b: print 'a is less than b' diff --git a/Task/Integer-comparison/Python/integer-comparison-2.py b/Task/Integer-comparison/Python/integer-comparison-2.py index 68e1b61af5..fa9798148a 100644 --- a/Task/Integer-comparison/Python/integer-comparison-2.py +++ b/Task/Integer-comparison/Python/integer-comparison-2.py @@ -1,8 +1,8 @@ #!/usr/bin/env python import sys try: - a = int(raw_input('Enter value of a: ')) - b = int(raw_input('Enter value of b: ')) + a = input('Enter value of a: ') + b = input('Enter value of b: ') except (ValueError, EnvironmentError), err: print sys.stderr, "Erroneous input:", err sys.exit(1) diff --git a/Task/Integer-comparison/Rust/integer-comparison.rust b/Task/Integer-comparison/Rust/integer-comparison.rust index dbb3aec787..282f115148 100644 --- a/Task/Integer-comparison/Rust/integer-comparison.rust +++ b/Task/Integer-comparison/Rust/integer-comparison.rust @@ -1,15 +1,19 @@ -use std::io; +use std::io::{self, BufRead}; fn main() { - // #![allow(unstable)] // Currently required whilst Rust 1.0 is finalised - let a: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap(); - let b: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap(); - - let result = - match (a, b) { - (a, b) if a < b => format!("{0} is less than {1}" , a , b), - (a, b) if a == b => format!("{0} equals {1}" , a , b), - (a, b) => format!("{0} is greater than {1}" , a , b), - }; - println!("{0}" , result); + let mut reader = io::stdin(); + let mut buffer = String::new(); + let mut lines = reader.lock().lines().take(2); + let nums: Vec= lines.map(|string| + string.unwrap().trim().parse().unwrap() + ).collect(); + let a: i32 = nums[0]; + let b: i32 = nums[1]; + if a < b { + println!("{} is less than {}" , a , b) + } else if a == b { + println!("{} equals {}" , a , b) + } else if a > b { + println!("{} is greater than {}" , a , b) + }; } diff --git a/Task/Integer-comparison/TI-83-BASIC/integer-comparison.ti-83 b/Task/Integer-comparison/TI-83-BASIC/integer-comparison.ti-83 new file mode 100644 index 0000000000..3b6dee4583 --- /dev/null +++ b/Task/Integer-comparison/TI-83-BASIC/integer-comparison.ti-83 @@ -0,0 +1,4 @@ +Prompt A,B +If AB: Disp "A GREATER B" +If A=B: Disp "A EQUAL B" diff --git a/Task/Integer-comparison/XSLT/integer-comparison.xslt b/Task/Integer-comparison/XSLT/integer-comparison.xslt index e05b9273cc..9ced3fc557 100644 --- a/Task/Integer-comparison/XSLT/integer-comparison.xslt +++ b/Task/Integer-comparison/XSLT/integer-comparison.xslt @@ -8,3 +8,4 @@ a = b + diff --git a/Task/Integer-overflow/ALGOL-68/integer-overflow-1.alg b/Task/Integer-overflow/ALGOL-68/integer-overflow-1.alg new file mode 100644 index 0000000000..7b5d50a793 --- /dev/null +++ b/Task/Integer-overflow/ALGOL-68/integer-overflow-1.alg @@ -0,0 +1,4 @@ +BEGIN + print (max int); + print (1+max int) +END diff --git a/Task/Integer-overflow/ALGOL-68/integer-overflow-2.alg b/Task/Integer-overflow/ALGOL-68/integer-overflow-2.alg new file mode 100644 index 0000000000..f154dbba37 --- /dev/null +++ b/Task/Integer-overflow/ALGOL-68/integer-overflow-2.alg @@ -0,0 +1,4 @@ +BEGIN + print (long max int); + print (1+ long max int) +END diff --git a/Task/Integer-overflow/Ada/integer-overflow.ada b/Task/Integer-overflow/Ada/integer-overflow.ada index 37122cca83..1deb7a7c8b 100644 --- a/Task/Integer-overflow/Ada/integer-overflow.ada +++ b/Task/Integer-overflow/Ada/integer-overflow.ada @@ -43,9 +43,9 @@ begin P_UB; P_SB; P_UW; P_Th; P_SD; P_Cr; New_Line; - Put_Line("Forcing a variable to overflow:"); + Put_Line("Forcing a variable of type Crazy to overflow:"); loop -- endless loop Put(" " & Crazy'Image(A) & "+1"); - A := A + 1; + A := A + 1; -- line 49 -- this will later raise a CONSTRAINT_ERROR end loop; end Overflow; diff --git a/Task/Integer-overflow/Befunge/integer-overflow.bf b/Task/Integer-overflow/Befunge/integer-overflow.bf new file mode 100644 index 0000000000..1f574d929b --- /dev/null +++ b/Task/Integer-overflow/Befunge/integer-overflow.bf @@ -0,0 +1,5 @@ +"a9jc>"*:*+*+:0\- "(-",,:.048*"="99")1 -" >:#,_$v +v,,,9"="*84 .: ,,"+"*84 .: **:*" }}" ,+55 .-\0-1< +>:+. 55+, ::0\- :. 48*"-",, \:. 48*"="9,,, -. 55v +v.*: ,,,,,999"="*84 .: ,,"*"*84 .: *+8*7"s9" ,+< +>55+, 0\- "(",:.048*"="99"1-/)1 -">:#,_$ 1-01-/.@ diff --git a/Task/Integer-overflow/C++/integer-overflow.cpp b/Task/Integer-overflow/C++/integer-overflow.cpp new file mode 100644 index 0000000000..e43594111c --- /dev/null +++ b/Task/Integer-overflow/C++/integer-overflow.cpp @@ -0,0 +1,35 @@ +#include +#include +#include + +int main (int argc, char *argv[]) +{ + std::cout << std::boolalpha + << std::numeric_limits::is_modulo << '\n' + << std::numeric_limits::is_modulo << '\n' // always true + << std::numeric_limits::is_modulo << '\n' + << std::numeric_limits::is_modulo << '\n' // always true + << "Signed 32-bit:\n" + << -(-2147483647-1) << '\n' + << 2000000000 + 2000000000 << '\n' + << -2147483647 - 2147483647 << '\n' + << 46341 * 46341 << '\n' + << (-2147483647-1) / -1 << '\n' + << "Signed 64-bit:\n" + << -(-9223372036854775807-1) << '\n' + << 5000000000000000000+5000000000000000000 << '\n' + << -9223372036854775807 - 9223372036854775807 << '\n' + << 3037000500 * 3037000500 << '\n' + << (-9223372036854775807-1) / -1 << '\n' + << "Unsigned 32-bit:\n" + << -4294967295U << '\n' + << 3000000000U + 3000000000U << '\n' + << 2147483647U - 4294967295U << '\n' + << 65537U * 65537U << '\n' + << "Unsigned 64-bit:\n" + << -18446744073709551615LU << '\n' + << 10000000000000000000LU + 10000000000000000000LU << '\n' + << 9223372036854775807LU - 18446744073709551615LU << '\n' + << 4294967296LU * 4294967296LU << '\n'; + return 0; +} diff --git a/Task/Integer-overflow/Julia/integer-overflow-1.julia b/Task/Integer-overflow/Julia/integer-overflow-1.julia new file mode 100644 index 0000000000..7479905633 --- /dev/null +++ b/Task/Integer-overflow/Julia/integer-overflow-1.julia @@ -0,0 +1,8 @@ +s = subtypes(Signed) +u = subtypes(Unsigned) + +println("Integer Type Limits") +for i in 1:length(s) + println(s[i], " [", typemin(s[i]), ", ", typemax(s[i]), "]") + println(u[i], " [", typemin(u[i]), ", ", typemax(u[i]), "]") +end diff --git a/Task/Integer-overflow/Julia/integer-overflow-2.julia b/Task/Integer-overflow/Julia/integer-overflow-2.julia new file mode 100644 index 0000000000..2843dcf293 --- /dev/null +++ b/Task/Integer-overflow/Julia/integer-overflow-2.julia @@ -0,0 +1,5 @@ +println("Add to typemax") +for t in s + over = typemax(t) + 1 + println(t, " => ", over, " (", typeof(over), ")") +end diff --git a/Task/Integer-overflow/Mathematica/integer-overflow.math b/Task/Integer-overflow/Mathematica/integer-overflow.math new file mode 100644 index 0000000000..669bdf6a1b --- /dev/null +++ b/Task/Integer-overflow/Mathematica/integer-overflow.math @@ -0,0 +1,2 @@ +$MaxNumber + + 10^-15.954589770191003298111788092733772206160314 $MaxNumber diff --git a/Task/Integer-overflow/PARI-GP/integer-overflow.pari b/Task/Integer-overflow/PARI-GP/integer-overflow.pari new file mode 100644 index 0000000000..06c8dc59d3 --- /dev/null +++ b/Task/Integer-overflow/PARI-GP/integer-overflow.pari @@ -0,0 +1,2 @@ +Vecsmall([1]) +Vecsmall([2^64]) diff --git a/Task/Integer-overflow/Perl-6/integer-overflow.pl6 b/Task/Integer-overflow/Perl-6/integer-overflow.pl6 new file mode 100644 index 0000000000..e80f3acb30 --- /dev/null +++ b/Task/Integer-overflow/Perl-6/integer-overflow.pl6 @@ -0,0 +1,2 @@ +my int64 ($a, $b, $c) = 9223372036854775807, 5000000000000000000, 3037000500; +.say for -(-$a - 1), $b + $b, -$a - $a, $c * $c, (-$a - 1)/-1; diff --git a/Task/Integer-overflow/PureBasic/integer-overflow.purebasic b/Task/Integer-overflow/PureBasic/integer-overflow.purebasic new file mode 100644 index 0000000000..35e87c00a9 --- /dev/null +++ b/Task/Integer-overflow/PureBasic/integer-overflow.purebasic @@ -0,0 +1,56 @@ +#MAX_BYTE =127 + +#MAX_ASCII=255 ;=MAX_CHAR Ascii-Mode + +CompilerIf #PB_Compiler_Unicode=1 +#MAX_CHAR =65535 ;Unicode-Mode +CompilerElse +#MAX_CHAR =255 +CompilerEndIf + +#MAX_WORD =32767 + +#MAX_UNIC =65535 + +#MAX_LONG =2147483647 + +CompilerIf #PB_Compiler_Processor=#PB_Processor_x86 +#MAX_INT =2147483647 ;32-bit CPU +CompilerElseIf #PB_Compiler_Processor=#PB_Processor_x64 +#MAX_INT =9223372036854775807 ;64-bit CPU +CompilerEndIf + +#MAX_QUAD =9223372036854775807 + +Macro say(Type,maxv,minv,sz) + PrintN(Type+#TAB$+RSet(Str(minv),30,Chr(32))+#TAB$+RSet(Str(maxv),30,Chr(32))+#TAB$+RSet(Str(sz),6,Chr(32))+" Byte") +EndMacro + +OpenConsole() +PrintN("TYPE"+#TAB$+RSet("MIN",30,Chr(32))+#TAB$+RSet("MAX",30,Chr(32))+#TAB$+RSet("SIZE",6,Chr(32))) + +Define.b b1=#MAX_BYTE, b2=b1+1 +say("Byte",b1,b2,SizeOf(b1)) + +Define.a a1=#MAX_ASCII, a2=a1+1 +say("Ascii",a1,a2,SizeOf(a1)) + +Define.c c1=#MAX_CHAR, c2=c1+1 +say("Char",c1,c2,SizeOf(c1)) + +Define.w w1=#MAX_WORD, w2=w1+1 +say("Word",w1,w2,SizeOf(w1)) + +Define.u u1=#MAX_UNIC, u2=u1+1 +say("Unicode",u1,u2,SizeOf(u1)) + +Define.l l1=#MAX_LONG, l2=l1+1 +say("Long ",l1,l2,SizeOf(l1)) + +Define.i i1=#MAX_INT, i2=i1+1 +say("Int",i1,i2,SizeOf(i1)) + +Define.q q1=#MAX_QUAD, q2=q1+1 +say("Quad",q1,q2,SizeOf(q1)) + +Input() diff --git a/Task/Integer-overflow/Racket/integer-overflow.rkt b/Task/Integer-overflow/Racket/integer-overflow.rkt new file mode 100644 index 0000000000..2255d93e0e --- /dev/null +++ b/Task/Integer-overflow/Racket/integer-overflow.rkt @@ -0,0 +1,20 @@ +#lang racket +(require racket/unsafe/ops) + +(fixnum? -1073741824) ;==> #t +(fixnum? (- -1073741824)) ;==> #f + +(- -1073741824) ;==> 1073741824 +(unsafe-fx- 0 -1073741824) ;==> -1073741824 + +(+ 1000000000 1000000000) ;==> 2000000000 +(unsafe-fx+ 1000000000 1000000000) ;==> -147483648 + +(- -1073741823 1073741823) ;==> -2147483646 +(unsafe-fx- -1073741823 1073741823) ;==> 2 + +(* 46341 46341) ;==> 2147488281 +(unsafe-fx* 46341 46341) ;==> 4633 + +(/ -1073741824 -1) ;==> 1073741824 +(unsafe-fxquotient -1073741824 -1) ;==> -1073741824 diff --git a/Task/Integer-sequence/Befunge/integer-sequence.bf b/Task/Integer-sequence/Befunge/integer-sequence.bf new file mode 100644 index 0000000000..3df9cc69e2 --- /dev/null +++ b/Task/Integer-sequence/Befunge/integer-sequence.bf @@ -0,0 +1 @@ +1+:0`!#@_:.55+, diff --git a/Task/Integer-sequence/DCL/integer-sequence.dcl b/Task/Integer-sequence/DCL/integer-sequence.dcl new file mode 100644 index 0000000000..f831fd6c8b --- /dev/null +++ b/Task/Integer-sequence/DCL/integer-sequence.dcl @@ -0,0 +1,5 @@ +$ i = 1 +$ loop: +$ write sys$output i +$ i = i + 1 +$ goto loop diff --git a/Task/Integer-sequence/Elixir/integer-sequence.elixir b/Task/Integer-sequence/Elixir/integer-sequence.elixir new file mode 100644 index 0000000000..c44b6a229b --- /dev/null +++ b/Task/Integer-sequence/Elixir/integer-sequence.elixir @@ -0,0 +1 @@ +Stream.iterate(1, &(&1+1)) |> Enum.each(&(IO.puts &1)) diff --git a/Task/Integer-sequence/Rust/integer-sequence-1.rust b/Task/Integer-sequence/Rust/integer-sequence-1.rust new file mode 100644 index 0000000000..d318f35edc --- /dev/null +++ b/Task/Integer-sequence/Rust/integer-sequence-1.rust @@ -0,0 +1,5 @@ +fn main() { + for i in 0.. { + println!("{}", i); + } +} diff --git a/Task/Integer-sequence/Rust/integer-sequence-2.rust b/Task/Integer-sequence/Rust/integer-sequence-2.rust new file mode 100644 index 0000000000..a6982c7e69 --- /dev/null +++ b/Task/Integer-sequence/Rust/integer-sequence-2.rust @@ -0,0 +1,12 @@ +extern crate num; + +use num::bigint::BigUint; +use num::traits::{One,Zero}; + +fn main() { + let mut i: BigUint = BigUint::one(); + loop { + println!("{}", i); + i = i + BigUint::one(); + } +} diff --git a/Task/Integer-sequence/Rust/integer-sequence.rust b/Task/Integer-sequence/Rust/integer-sequence.rust deleted file mode 100644 index 026cb47b1b..0000000000 --- a/Task/Integer-sequence/Rust/integer-sequence.rust +++ /dev/null @@ -1,13 +0,0 @@ -extern mod extra; -use extra::bigint::BigUint; -use std::num::One; - -fn main() { - let one: BigUint = One::one(); - let mut i: BigUint = One::one(); - - loop { - println!("{:s}", i.to_str()); - i = i + one; - } -} diff --git a/Task/Interactive-programming/Batch-File/interactive-programming.bat b/Task/Interactive-programming/Batch-File/interactive-programming.bat index 079d2712e6..8303f16e35 100644 --- a/Task/Interactive-programming/Batch-File/interactive-programming.bat +++ b/Task/Interactive-programming/Batch-File/interactive-programming.bat @@ -1,2 +1,10 @@ -command.com -color f0 +>set r=Rosetta + +>set c=Code + +>set s=: + +>echo %r%%s%%s%%c% +Rosetta::Code + +> diff --git a/Task/Interactive-programming/Elixir/interactive-programming-1.elixir b/Task/Interactive-programming/Elixir/interactive-programming-1.elixir new file mode 100644 index 0000000000..03b76dfb61 --- /dev/null +++ b/Task/Interactive-programming/Elixir/interactive-programming-1.elixir @@ -0,0 +1,7 @@ +iex(1)> f = fn str1,str2,sep -> [str1,"",str2] |> Enum.join(sep) end # Join list on seperator +iex(2)> g = fn str1,str2,sep -> str1 <> sep <> sep <> str2 end # Or concatenate strings + +iex(3)> defmodule JoinStrings do +...(3)> def f(str1,str2,sep), do: [str1,"",str2] |> Enum.join(sep) +...(3)> def g(str1,str2,sep), do: str1 <> sep <> sep <> str2 +...(3)> end diff --git a/Task/Interactive-programming/Elixir/interactive-programming-2.elixir b/Task/Interactive-programming/Elixir/interactive-programming-2.elixir new file mode 100644 index 0000000000..79ca288d24 --- /dev/null +++ b/Task/Interactive-programming/Elixir/interactive-programming-2.elixir @@ -0,0 +1,4 @@ +iex(4)> f.("Rosetta","Code",":") +"Rosetta::Code" +iex(5)> JoinStrings.f("Rosetta","Code",":") +"Rosetta::Code" diff --git a/Task/Interactive-programming/MATLAB/interactive-programming.m b/Task/Interactive-programming/MATLAB/interactive-programming.m index a1f39acc8b..e2b6c9e3bb 100644 --- a/Task/Interactive-programming/MATLAB/interactive-programming.m +++ b/Task/Interactive-programming/MATLAB/interactive-programming.m @@ -1,5 +1 @@ - function x=f(a,b,sep) - x = [a,sep,b]; - return; - end; - f('Rosetta', 'Code', ':') +>> f = @(str1, str2, delim) [str1, delim, delim, str2]; diff --git a/Task/Introspection/Ruby/introspection-1.rb b/Task/Introspection/Ruby/introspection-1.rb index 7f9fa80b54..5f8580286c 100644 --- a/Task/Introspection/Ruby/introspection-1.rb +++ b/Task/Introspection/Ruby/introspection-1.rb @@ -1,2 +1,2 @@ exit if RUBY_VERSION < '1.8.6' - puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs) +puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs) diff --git a/Task/Introspection/Ruby/introspection-2.rb b/Task/Introspection/Ruby/introspection-2.rb index c37818931c..558bc45eaa 100644 --- a/Task/Introspection/Ruby/introspection-2.rb +++ b/Task/Introspection/Ruby/introspection-2.rb @@ -8,8 +8,8 @@ def variable_counter(b) end end - Kernel.global_variables.each {|varname| check_var.call(varname, eval(varname))} - eval('local_variables', b).each {|varname| check_var.call(varname, eval(varname, b))} + global_variables.each {|varname| check_var.call(varname, eval(varname.to_s))} + eval('local_variables', b).each {|varname| check_var.call(varname, eval(varname.to_s, b))} puts "these #{int_vars.length} variables in the global scope are integers:" puts int_vars.inspect diff --git a/Task/Inverted-index/C++/inverted-index.cpp b/Task/Inverted-index/C++/inverted-index.cpp new file mode 100644 index 0000000000..73d9190f86 --- /dev/null +++ b/Task/Inverted-index/C++/inverted-index.cpp @@ -0,0 +1,116 @@ +#include +#include +#include +#include +#include + +const std::string _CHARS = "abcdefghijklmnopqrstuvwxyz0123456789.:-_/"; +const size_t MAX_NODES = 41; + +class node +{ +public: + node() { clear(); } + node( char z ) { clear(); } + ~node() { for( int x = 0; x < MAX_NODES; x++ ) if( next[x] ) delete next[x]; } + void clear() { for( int x = 0; x < MAX_NODES; x++ ) next[x] = 0; isWord = false; } + bool isWord; + std::vector files; + node* next[MAX_NODES]; +}; + +class index { +public: + void add( std::string s, std::string fileName ) { + std::transform( s.begin(), s.end(), s.begin(), tolower ); + std::string h; + for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { + if( *i == 32 ) { + pushFileName( addWord( h ), fileName ); + h.clear(); + continue; + } + h.append( 1, *i ); + } + if( h.length() ) + pushFileName( addWord( h ), fileName ); + } + void findWord( std::string s ) { + std::vector v = find( s ); + if( !v.size() ) { + std::cout << s + " was not found!\n"; + return; + } + std::cout << s << " found in:\n"; + for( std::vector::iterator i = v.begin(); i != v.end(); i++ ) { + std::cout << *i << "\n"; + } + std::cout << "\n"; + } +private: + void pushFileName( node* n, std::string fn ) { + std::vector::iterator i = std::find( n->files.begin(), n->files.end(), fn ); + if( i == n->files.end() ) n->files.push_back( fn ); + } + const std::vector& find( std::string s ) { + size_t idx; + std::transform( s.begin(), s.end(), s.begin(), tolower ); + node* rt = &root; + for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { + idx = _CHARS.find( *i ); + if( idx < MAX_NODES ) { + if( !rt->next[idx] ) return std::vector(); + rt = rt->next[idx]; + } + } + if( rt->isWord ) return rt->files; + return std::vector(); + } + node* addWord( std::string s ) { + size_t idx; + node* rt = &root, *n; + for( std::string::iterator i = s.begin(); i != s.end(); i++ ) { + idx = _CHARS.find( *i ); + if( idx < MAX_NODES ) { + n = rt->next[idx]; + if( n ){ + rt = n; + continue; + } + n = new node( *i ); + rt->next[idx] = n; + rt = n; + } + } + rt->isWord = true; + return rt; + } + node root; +}; +int main( int argc, char* argv[] ) { + index t; + std::string s; + std::string files[] = { "file1.txt", "f_text.txt", "text_1b.txt" }; + + for( int x = 0; x < 3; x++ ) { + std::ifstream f; + f.open( files[x].c_str(), std::ios::in ); + if( f.good() ) { + while( !f.eof() ) { + f >> s; + t.add( s, files[x] ); + s.clear(); + } + f.close(); + } + } + + while( true ) { + std::cout << "Enter one word to search for, return to exit: "; + std::getline( std::cin, s ); + if( !s.length() ) break; + t.findWord( s ); + + } + return 0; +} diff --git a/Task/Inverted-index/Perl-6/inverted-index.pl6 b/Task/Inverted-index/Perl-6/inverted-index.pl6 index fd54b41385..bef7456ace 100644 --- a/Task/Inverted-index/Perl-6/inverted-index.pl6 +++ b/Task/Inverted-index/Perl-6/inverted-index.pl6 @@ -2,11 +2,11 @@ sub MAIN (*@files) { (my %norm).push: do for @files -> $file { $file X=> slurp($file).lc.words; } - (my %inv).push: %norm.invert.uniq; + (my %inv).push: %norm.invert.unique; while prompt("Search terms: ").words -> @words { for @words -> $word { - say "$word => %inv.{$word.lc}"; + say "$word => {%inv.{$word.lc}//'(not found)'}"; } } } diff --git a/Task/Inverted-index/REXX/inverted-index.rexx b/Task/Inverted-index/REXX/inverted-index.rexx index c4cc23629b..1d6bb4ea25 100644 --- a/Task/Inverted-index/REXX/inverted-index.rexx +++ b/Task/Inverted-index/REXX/inverted-index.rexx @@ -1,64 +1,58 @@ /*REXX program illustrates building a simple inverted index & word find.*/ @.='' /*dictionary of words (so far).*/ !='' /*a list of found words (so far).*/ - -call invertI 0, 'BURMA0.TXT' /*read file 0 ... */ -call invertI 1, 'BURMA1.TXT' /* " " 1 ... */ -call invertI 2, 'BURMA2.TXT' /* " " 2 ... */ -call invertI 3, 'BURMA3.TXT' /* " " 3 ... */ -call invertI 4, 'BURMA4.TXT' /* " " 4 ... */ -call invertI 5, 'BURMA5.TXT' /* " " 5 ... */ -call invertI 6, 'BURMA6.TXT' /* " " 6 ... */ -call invertI 7, 'BURMA7.TXT' /* " " 7 ... */ -call invertI 8, 'BURMA8.TXT' /* " " 8 ... */ -call invertI 9, 'BURMA9.TXT' /* " " 9 ... */ - +call invertI 0, 'BURMA0.TXT' /*read the file: BURMA0.TXT ...*/ +call invertI 1, 'BURMA1.TXT' /* " " ~ BURMA1.TXT ...*/ +call invertI 2, 'BURMA2.TXT' /* " " ~ BURMA2.TXT ...*/ +call invertI 3, 'BURMA3.TXT' /* " " ~ BURMA3.TXT ...*/ +call invertI 4, 'BURMA4.TXT' /* " " ~ BURMA4.TXT ...*/ +call invertI 5, 'BURMA5.TXT' /* " " ~ BURMA5.TXT ...*/ +call invertI 6, 'BURMA6.TXT' /* " " ~ BURMA6.TXT ...*/ +call invertI 7, 'BURMA7.TXT' /* " " ~ BURMA7.TXT ...*/ +call invertI 8, 'BURMA8.TXT' /* " " ~ BURMA8.TXT ...*/ +call invertI 9, 'BURMA9.TXT' /* " " ~ BURMA9.TXT ...*/ call findAword 'does' /*find a word. */ call findAword '60' /*find another word. */ call findAword "don't" /*and find another word. */ call findAword "burma-shave" /*and find yet another word. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────FINDAWORD subroutine────────────────*/ -findAword: procedure expose @. /*get A word, and uppercase it. */ -parse arg ox; arg x /*OX= word; X= uppercase version*/ -_=@.x -oxo='───'ox"───" +findAword: procedure expose @.; arg x /*get an uppercase version of X. */ +parse arg ox /*get original (as-is) value of X*/ +_=@.x; oxo='───'ox"───" if _=='' then do - say 'word' oxo "not found." + say 'word' oxo "not found." return 0 end _@=_ /*save _, pass it back to invoker*/ -say 'word' oxo "found in:" - do until _==''; parse var _ f w _; say - say ' file='f ' word='w - end /*until ... */ +say 'word' oxo "found in:" + do until _==''; parse var _ f w _ + say ' file='f ' word='w + end /*until ··· */ return _@ /*─────────────────────────────────────INVERTI subroutine───────────────*/ invertI: procedure expose @. !; parse arg #,fn /*file#, filename*/ call lineout fn /*close the file, just in case. */ -w=0 /*number of words so far. */ - - do while lines(fn)\==0 /*process the entire file (below)*/ - _=space(linein(fn)) /*read 1 line, elide extra blanks*/ - if _=='' then iterate /*if blank record, then ignore it*/ - say 'file' #",record="_ /*echo a record, just to be verbose.*/ - - do until _=='' /*pick off words until done. */ - parse upper var _ xxx _ /*pick off a word (uppercased). */ - xxx=stripper(xxx) /*strip any ending punctuation. */ - if xxx='' then iterate /*is the word now blank (null) ? */ - w=w+1 /*bump the word counter. */ - @.xxx=@.xxx # w - if wordpos(xxx,!)==0 then !=! xxx /*add to THE list of words found.*/ - end /*until ... */ - end /*while lines(fn)¬==0*/ +w=0 /*number of words found (so far).*/ + do while lines(fn)\==0 /* [↓] process the entire file.*/ + _=space(linein(fn)) /*read a line, elide extra blanks*/ + if _=='' then iterate /*if blank record, then ignore it*/ + say 'file' #", record:" _ /*echo a record (to be verbose).*/ -say; call lineout fn /*close the file, just to be neat*/ + do until _=='' /*pick off words until done. */ + parse upper var _ ? _ /*pick off a word (uppercased). */ + ?=stripper(?) /*strip any trailing punctuation.*/ + if ?='' then iterate /*is the word now blank (null) ? */ + w=w+1 /*bump the word counter (index). */ + @.?=@.? # w /*append the new word to a list. */ + if wordpos(?,!)==0 then !=! ? /*add to the list of words found.*/ + end /*until ··· */ + end /*while ··· */ +say; call lineout fn /*close the file, just to be neat*/ return w /*return the index of the word. */ /*─────────────────────────────────────STRIPPER subroutine──────────────*/ stripper: procedure; parse arg q /*remove punctuation at word-end.*/ -@punctuation='.,:;?¿!¡' /*serveral punctuation marks. */ - do j=1 for length(@punctuation) - q=strip(q,'T',substr(@punctuation,j,1)) - end /*j*/ +@punctuation='.,:;?¿!¡∙·'; do j=1 for length(@punctuation) + q=strip(q,'T',substr(@punctuation,j,1)) + end /*j*/ return q diff --git a/Task/Inverted-syntax/Metafont/inverted-syntax.metafont b/Task/Inverted-syntax/Metafont/inverted-syntax.metafont new file mode 100644 index 0000000000..0b7f6444d5 --- /dev/null +++ b/Task/Inverted-syntax/Metafont/inverted-syntax.metafont @@ -0,0 +1,2 @@ +x=6; +7=y; diff --git a/Task/Iterated-digits-squaring/BBC-BASIC/iterated-digits-squaring.bbc b/Task/Iterated-digits-squaring/BBC-BASIC/iterated-digits-squaring.bbc new file mode 100644 index 0000000000..5d79127230 --- /dev/null +++ b/Task/Iterated-digits-squaring/BBC-BASIC/iterated-digits-squaring.bbc @@ -0,0 +1,58 @@ + REM Version 1: Brute force + REM --------------------------------------------------------- + T%=TIME + N%=0 + FOR I%=1 TO 100000000 + J%=I% + REPEAT + K%=0:REPEAT K%+=(J%MOD10)^2:J%=J%DIV10:UNTIL J%=0 + J%=K% + UNTIL J%=89 OR J%=1 + IF J%>1 N%+=1 + NEXT + PRINT "Version 1: ";N% " in ";(TIME-T%)/100 " seconds." + + REM Version 2: Brute force + building lookup table + REM --------------------------------------------------------- + T%=TIME + DIM B% 9*9*8,H%(9) + N%=0 + FOR I%=1 TO 100000000 + J%=I% + H%=0 + REPEAT + K%=0:REPEAT K%+=(J%MOD10)^2:J%=J%DIV10:UNTIL J%=0 + H%(H%)=K%:H%+=1 + J%=K% + IF B%?J%=1 EXIT REPEAT + UNTIL J%=89 OR J%=1 + IF J%>1 N%+=1:WHILE H%>0:H%-=1:B%?H%(H%)=1:ENDWHILE + NEXT + PRINT "Version 2: ";N% " in ";(TIME-T%)/100 " seconds." + + REM Version 3: Calc possible combinations (translation of C) + REM --------------------------------------------------------- + T%=TIME + DIM B%(9*9*8):B%(0)=1 + FOR N%=1 TO 8 + FOR I%=9*9*N% TO 1 STEP -1 + FOR J%=1 TO 9 + S%=J%*J% + IF S%>I% EXIT FOR + B%(I%)+=B%(I%-S%) + NEXT + NEXT + NEXT + + N%=0 + FOR I%=1 TO 9*9*8 + J%=I% + REPEAT + K%=0:REPEAT K%+=(J%MOD10)^2:J%=J%DIV10:UNTIL J%=0 + J%=K% + UNTIL J%=89 OR J%=1 + IF J%>1 N%+=B%(I%) + NEXT + PRINT "Version 3: ";N% " in ";(TIME-T%)/100 " seconds." + + END diff --git a/Task/Iterated-digits-squaring/C/iterated-digits-squaring-1.c b/Task/Iterated-digits-squaring/C/iterated-digits-squaring-1.c new file mode 100644 index 0000000000..df9c4f60c6 --- /dev/null +++ b/Task/Iterated-digits-squaring/C/iterated-digits-squaring-1.c @@ -0,0 +1,47 @@ +#include + +typedef unsigned long long ull; + +int is89(int x) +{ + while (1) { + int s = 0; + do s += (x%10)*(x%10); while ((x /= 10)); + + if (s == 89) return 1; + if (s == 1) return 0; + x = s; + } +} + + +int main(void) +{ + // array bounds is sort of random here, it's big enough for 64bit unsigned. + ull sums[32*81 + 1] = {1, 0}; + + for (int n = 1; ; n++) { + for (int i = n*81; i; i--) { + for (int j = 1; j < 10; j++) { + int s = j*j; + if (s > i) break; + sums[i] += sums[i-s]; + } + } + + ull count89 = 0; + for (int i = 1; i < n*81 + 1; i++) { + if (!is89(i)) continue; + + if (sums[i] > ~0ULL - count89) { + printf("counter overflow for 10^%d\n", n); + return 0; + } + count89 += sums[i]; + } + + printf("1->10^%d: %llu\n", n, count89); + } + + return 0; +} diff --git a/Task/Iterated-digits-squaring/C/iterated-digits-squaring.c b/Task/Iterated-digits-squaring/C/iterated-digits-squaring-2.c similarity index 100% rename from Task/Iterated-digits-squaring/C/iterated-digits-squaring.c rename to Task/Iterated-digits-squaring/C/iterated-digits-squaring-2.c diff --git a/Task/Iterated-digits-squaring/Common-Lisp/iterated-digits-squaring.lisp b/Task/Iterated-digits-squaring/Common-Lisp/iterated-digits-squaring.lisp new file mode 100644 index 0000000000..4e4062c623 --- /dev/null +++ b/Task/Iterated-digits-squaring/Common-Lisp/iterated-digits-squaring.lisp @@ -0,0 +1,32 @@ +(defun square (number) + (expt number 2)) + +(defun list-digits (number) + "Return the `number' as a list of its digits." + (loop + :for (rest digit) := (multiple-value-list (truncate number 10)) + :then (multiple-value-list (truncate rest 10)) + :collect digit + :until (zerop rest))) + +(defun next (number) + (loop + :for digit :in (list-digits number) + :sum (square digit))) + +(defun chain-end (number) + "Return the ending number after summing the squaring of the digits of +`number'. Either 1 or 89." + (loop + :for next := (next number) :then (next next) + :until (or (eql next 1) + (eql next 89)) + :finally (return next))) + +(time + (loop + :with count := 0 + :for candidate :from 1 :upto 100000000 + :do (when (eql 89 (chain-end candidate)) + (incf count)) + :finally (return count))) diff --git a/Task/Iterated-digits-squaring/Frink/iterated-digits-squaring.frink b/Task/Iterated-digits-squaring/Frink/iterated-digits-squaring.frink new file mode 100644 index 0000000000..50e10b1681 --- /dev/null +++ b/Task/Iterated-digits-squaring/Frink/iterated-digits-squaring.frink @@ -0,0 +1,30 @@ +total = 0 +d = new dict +var sum + +for n = 1 to 100 million - 1 +{ + sum = n + do + { + if sum < 1000 and d@sum != undef + { + sum = d@sum + break + } + + c = sum + + sum = 0 + for digit = integerDigits[c] + sum = sum + digit^2 + } while (sum != 89) and (sum != 1) + + if (n < 1000) + d@n = sum + + if (sum == 89) + total = total + 1 +} + +println[total] diff --git a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-6.j b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-6.j index 4738c94f6c..bd80aa94df 100644 --- a/Task/Iterated-digits-squaring/J/iterated-digits-squaring-6.j +++ b/Task/Iterated-digits-squaring/J/iterated-digits-squaring-6.j @@ -1 +1,2 @@ +itdigsq1=:1 = sumdigsq^:(0=e.&4)^:_"0 digsq1e8=:(I.itdigsq1 i.649) e.~ sumdigsq diff --git a/Task/Iterated-digits-squaring/PL-I/iterated-digits-squaring.pli b/Task/Iterated-digits-squaring/PL-I/iterated-digits-squaring.pli new file mode 100644 index 0000000000..26b0a8189d --- /dev/null +++ b/Task/Iterated-digits-squaring/PL-I/iterated-digits-squaring.pli @@ -0,0 +1,29 @@ +test: procedure options (main, reorder); /* 6 August 2015 */ + + declare (m, n) fixed decimal (10); + declare (i, j, p, s, tally initial (0) ) fixed binary (31); + declare d fixed binary (7); + declare (start_time, finish_time, elapsed_time) float (15); + + start_time = secs(); + + do m = 1 to 1000000; + n = m; + do until ((n = 1) | (n = 89)); + p = n; s = 0; + do while (p > 0); + d = mod(p, 10); + p = p/10; + s = s + d*d; + end; + n = s; + end; + if n = 89 then tally = tally + 1; + end; + + finish_time = secs(); + put skip edit (Tally, ' numbers iterated to 89') (f(10), A); + elapsed_time = finish_time - start_time; + put skip edit ('Elapsed time=', elapsed_time, ' secs') (A, F(10,3)); + +end test; diff --git a/Task/Iterated-digits-squaring/PureBasic/iterated-digits-squaring-1.purebasic b/Task/Iterated-digits-squaring/PureBasic/iterated-digits-squaring-1.purebasic new file mode 100644 index 0000000000..2f96ce999f --- /dev/null +++ b/Task/Iterated-digits-squaring/PureBasic/iterated-digits-squaring-1.purebasic @@ -0,0 +1,39 @@ +Define.i +OpenConsole() +Procedure is89(x) + Repeat + s=0 + While x : s+ x%10*x%10 : x/10 : Wend + If s=89 : ProcedureReturn 1 : EndIf + If s=1 : ProcedureReturn 0 : EndIf + x=s + ForEver +EndProcedure + +Procedure main() + Dim sums(32*81+1) : sums(0)=1 : sums(1)=0 + + For n=1 To n+1 + For i=n*81 To 1 Step -1 + For j=1 To 9 + s=j*j : If s>i : Break : EndIf + sums(i)+sums(i-s) + Next + Next + count89=0 + For i=1 To n*81+1 + If Not is89(i) : Continue : EndIf + If sums(i)>9223372036854775807-count89 + PrintN("counter overflow for 10^"+Str(n)) + ProcedureReturn 0 + EndIf + count89+sums(i) + Next + PrintN("1->10^"+LSet(Str(n),2,Chr(32))+": "+Str(count89)) + Next +EndProcedure + +start=ElapsedMilliseconds() +main() +Print("elapsed milliseconds= "+Str(ElapsedMilliseconds()-start)) +Input() diff --git a/Task/Iterated-digits-squaring/PureBasic/iterated-digits-squaring-2.purebasic b/Task/Iterated-digits-squaring/PureBasic/iterated-digits-squaring-2.purebasic new file mode 100644 index 0000000000..c3525c48fa --- /dev/null +++ b/Task/Iterated-digits-squaring/PureBasic/iterated-digits-squaring-2.purebasic @@ -0,0 +1,32 @@ +Define.i +OpenConsole() +Procedure sum_square_digits(n) + num=n : sum=0 + While num>0 + digit=num%10 + num=(num-digit)/10 + sum+ digit*digit + Wend + ProcedureReturn sum +EndProcedure + +Procedure main() + i=0 : result=0 : count=0 + For i=1 To 1e8 + If Not i=1 Or Not i=89 + result=sum_square_digits(i) + Else + result=i + EndIf + While Not result=1 And Not result=89 + result=sum_square_digits(result) + Wend + If result=89 : count+1 : EndIf + Next + PrintN(Str(count)) +EndProcedure + +start=ElapsedMilliseconds() +main() +Print("elapsed milliseconds: "+Str(ElapsedMilliseconds()-start)) +Input() diff --git a/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-5.py b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-5.py new file mode 100644 index 0000000000..b3fad022c2 --- /dev/null +++ b/Task/Iterated-digits-squaring/Python/iterated-digits-squaring-5.py @@ -0,0 +1,20 @@ +from __future__ import print_function +from itertools import count + +def check89(n): + while True: + n, t = 0, n + while t: n, t = n + (t%10)**2, t//10 + if n <= 1: return False + if n ==89: return True + +a, sq, is89 = [1], [x**2 for x in range(1, 10)], [False] +for n in range(1, 500): + b, a = a, a + [0]*81 + is89 += map(check89, range(len(b), len(a))) + + for i,v in enumerate(b): + for s in sq: a[i + s] += v + + x = sum(a[i] for i in range(len(a)) if is89[i]) + print("10^%d" % n, x) diff --git a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx index 79c080f101..ecc97ecde8 100644 --- a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx +++ b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx @@ -1,22 +1,26 @@ -/*REXX program to perform iterated digits squaring ('til sum=1 | sum=89)*/ +/*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. */ +if n=='' then n=10 * 1000000 /*Was N given? No, use default.*/ +!.=0; do m=1 for 9; !.m=m**2; end /*build a short─cut for squares. */ +a.=. /*intermediate counts of some #s.*/ #.=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 j=1 for n; x=j /* [↓] process each num in range*/ + do q=1 until s==89 | s==1; s=0 /*add the sum of squared digits. */ + do until x=='' /*process each of the digits in X*/ + parse var x _ +1 x; s=s+!._ /*get a dig; sum the fast square,*/ + end /*until x ···*/ /* [↑] S≡is sum of squared digs.*/ + z.q=s /*assign sum to a temp auxiliary.*/ + if a.s\==. then do; s=a.s; leave; end /*found a previous sum.*/ + x=s /*substitute the sum for "new" X.*/ + end /*until*/ /* [↑] keep looping 'til S=1│89.*/ - 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 + do f=1 for q /* [↓] use auxiliary array. */ + _=z.f; a._=s /*assign auxiliaries for future. */ + end /*f*/ + #.s=#.s+1 /*bump the counter for 1's │ 89's*/ + end /*j*/ + + do i=1 to 89 by 88; c=right('"'i'"',5) ' 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 index bbd2ffe460..65502a6983 100644 --- a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx +++ b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx @@ -1,43 +1,39 @@ -/*REXX program to perform iterated digits squaring ('til sum=1 | sum=89)*/ +/*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.*/ +if n=='' then n=100 * 1000000 /*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*/ + do j=1 for n; s=sumDs(j) /* [↓] process each num in range*/ + #.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*/ - + do i=1 to 89 by 88; _=right('"'i'"', 5) ' chains' + say 'count of' _ '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.*/ +sumDs: parse arg z; chunk=3 /*obtain number (for adding digs)*/ +p=0 /*set the partial sum of the digs*/ + do m=1 by chunk to length(z) /*process the number, chunks of 4*/ + y=substr(z, m, chunk) /*extract a 4─byte chunk of the #*/ + if @.y==. then do; oy=y; a=0 /*Not done before? Then sum #.*/ + do until y=='' /*process each of the digits in Y*/ + parse var y _ +1 y; a=a+!._ /*get a dig; add to A*/ + end /*until y ··· [↑] A≡is sum of squared digs*/ + @.oy=a /*mark original Y as being summed*/ + end + else a=@.y /*use a pre─summed digits of Y. */ + p=p+a /*add all the parts of # together*/ + end /*m*/ + +if $.p\==. then return $.p /*Computed before? Use the value*/ +y=p /*use a new copy of P. */ + do until s==1 | s==89; s=0 /*add the squared digits of P.*/ + do until y=='' /*process each of the digits in X*/ + parse var y _ +1 y; s=s+!._ /*get a dig; sum the fast square,*/ + end /*until x ···*/ /* [↑] S≡is sum of squared digs.*/ + y=s /*substitute 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/Ruby/iterated-digits-squaring.rb b/Task/Iterated-digits-squaring/Ruby/iterated-digits-squaring.rb index b491cd8b8d..6a4db7c992 100644 --- a/Task/Iterated-digits-squaring/Ruby/iterated-digits-squaring.rb +++ b/Task/Iterated-digits-squaring/Ruby/iterated-digits-squaring.rb @@ -1,28 +1,30 @@ -# 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 } +# Count how many number chains for Natural Numbers < 10**d end with a value of 1. +def iterated_square_digit(d) + f = Array.new(d+1){|n| (1..n).inject(1, :*)} #Some small factorials + g = -> (n) { res = 0 + while n>0 + n, mod = n.divmod(10) + res += mod**2 + end + res==89 ? 0 : res + } -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 + #An array: table[n]==0 means that n translates to 89 and 1 means that n translates to 1 + table = Array.new(d*81+1){|n| n.zero? ? 1 : (i=g.call(n))==89 ? 0 : i} + table.collect!{|n| n = table[n] while n>1; n} + z = 0 #Running count of numbers translating to 1 + [*0..9].repeated_combination(d) do |rc| #Iterate over unique digit combinations + next if table[rc.inject(0){|g,n| g+n*n}].zero? #Count only ones + nn = [0] * 10 #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 + z += nn.inject(f[d]){|gn,n| gn / f[n]} #Add to the count of numbers terminating in 1 end + puts "\nd=(#{d}) in the range 1 to #{10**d-1}", + "#{z} numbers produce 1 and #{10**d-1-z} numbers produce 89" +end + +[8, 11, 14, 17].each do |d| + t0 = Time.now + iterated_square_digit(d) + puts " #{Time.now - t0} sec" end -puts "#{z} numbers produce 1 and #{10**D-z} numbers produce 89" -puts "\nTiming\n#{t}" diff --git a/Task/Iterated-digits-squaring/Rust/iterated-digits-squaring-1.rust b/Task/Iterated-digits-squaring/Rust/iterated-digits-squaring-1.rust new file mode 100644 index 0000000000..9dadf90a3c --- /dev/null +++ b/Task/Iterated-digits-squaring/Rust/iterated-digits-squaring-1.rust @@ -0,0 +1,20 @@ +fn digit_square_sum(mut num: usize) -> usize { + let mut sum = 0; + while num != 0 { + sum += (num % 10).pow(2); + num /= 10; + } + sum +} + +fn last_in_chain(num: usize) -> usize { + match num { + 1 | 89 => num, + _ => last_in_chain(digit_square_sum(num)), + } +} + +fn main() { + let count = (1..100_000_000).filter(|&n| last_in_chain(n) == 89).count(); + println!("{}", count); +} diff --git a/Task/Iterated-digits-squaring/Rust/iterated-digits-squaring-2.rust b/Task/Iterated-digits-squaring/Rust/iterated-digits-squaring-2.rust new file mode 100644 index 0000000000..f768d3f0e4 --- /dev/null +++ b/Task/Iterated-digits-squaring/Rust/iterated-digits-squaring-2.rust @@ -0,0 +1,22 @@ +fn dig_sq_sum(mut num : usize ) -> usize { + let mut sum = 0; + while num != 0 { + sum += (num % 10).pow(2); + num /= 10; + } + sum +} + +fn last_in_chain(num: usize) -> usize { + match num { + 0 => 0, + 1 | 89 => num, + _ => last_in_chain(dig_sq_sum(num)), + } +} + +fn main() { + let prec: Vec<_> = (0..649).map(|n| last_in_chain(n)).collect(); + let count = (1..100_000_000).filter(|&n| prec[dig_sq_sum(n)] == 89).count(); + println!("{}", count); +} diff --git a/Task/Iterated-digits-squaring/VBScript/iterated-digits-squaring.vb b/Task/Iterated-digits-squaring/VBScript/iterated-digits-squaring.vb new file mode 100644 index 0000000000..ce1b62881a --- /dev/null +++ b/Task/Iterated-digits-squaring/VBScript/iterated-digits-squaring.vb @@ -0,0 +1,20 @@ +start_time = Now +cnt = 0 +For i = 1 To 100000000 + n = i + sum = 0 + Do Until n = 1 Or n = 89 + For j = 1 To Len(n) + sum = sum + (CLng(Mid(n,j,1))^2) + Next + n = sum + sum = 0 + Loop + If n = 89 Then + cnt = cnt + 1 + End If +Next +end_time = Now + +WScript.Echo "Elapse Time: " & DateDiff("s",start_time,end_time) &_ + vbCrLf & "Count: " & cnt diff --git a/Task/JSON/Fortran/json.f b/Task/JSON/Fortran/json.f new file mode 100644 index 0000000000..c46ddc256e --- /dev/null +++ b/Task/JSON/Fortran/json.f @@ -0,0 +1,48 @@ +program json_fortran + use json_module + implicit none + + type phonebook_type + character(len=:),allocatable :: name + character(len=:),allocatable :: phone + end type phonebook_type + + type(phonebook_type), dimension(3) :: PhoneBook + integer :: i + type(json_value),pointer :: json_phonebook,p,e + type(json_file) :: json + + PhoneBook(1) % name = 'Adam' + PhoneBook(2) % name = 'Eve' + PhoneBook(3) % name = 'Julia' + PhoneBook(1) % phone = '0000001' + PhoneBook(2) % phone = '0000002' + PhoneBook(3) % phone = '6666666' + + call json_initialize() + + !create the root structure: + call json_create_object(json_phonebook,'') + + !create and populate the phonebook array: + call json_create_array(p,'PhoneBook') + do i=1,3 + call json_create_object(e,'') + call json_add(e,'name',PhoneBook(i)%name) + call json_add(e,'phone',PhoneBook(i)%phone) + call json_add(p,e) !add this element to array + nullify(e) !cleanup for next loop + end do + call json_add(json_phonebook,p) !add p to json_phonebook + nullify(p) !no longer need this + + !write it to a file: + call json_print(json_phonebook,'phonebook.json') + + ! read directly from a character string + call json%load_from_string('{ "PhoneBook": [ { "name": "Adam", "phone": "0000001" },& + { "name": "Eve", "phone": "0000002" }, { "name": "Julia", "phone": "6666666" } ]}') + ! print it to the console + call json%print_file() + +end program json_fortran diff --git a/Task/JSON/J/json-1.j b/Task/JSON/J/json-1.j index ac563da916..e01be6c89e 100644 --- a/Task/JSON/J/json-1.j +++ b/Task/JSON/J/json-1.j @@ -18,7 +18,7 @@ words=:(0;(0 10#:10*".;._2]0 :0);classes)&;: NB. states: ) tokens=. ;:'[ ] , { } :' -actions=: lBra`rBracket`comma`lBra`rBracket`colon`value +actions=: lBra`rBracket`comma`lBra`rBrace`colon`value NB. action verbs argument conventions: NB. x -- boxed json word @@ -32,7 +32,7 @@ jsonParse=: 0 {:: (,a:) ,&.> [: actions@.(tokens&i.@[)/ [:|.a:,words lBra=: a: ,~ ] rBracket=: _2&}.@], [:< _2&{::@], _1&{@] comma=: ] -rBrace=: _2&}.@], [:< _2&{::@], [:|: (2,~ [: -:@$ _1&{@]) $ _1&{@] +rBrace=: _2&}.@], [:< _2&{::@](, <) [:|: (2,~ [: -:@$ _1&{::@]) $ _1&{::@] colon=: ] value=: _1&}.@], [:< _1&{::@], jsonValue&.>@[ @@ -43,7 +43,8 @@ jsonValue=:] require'strings' +jsonSer2=: jsonSer1@(<"_1^:(0>.#@$-1:)) jsonSer1=: ']' ,~ '[' }:@;@; (',' ,~ jsonSerialize)&.> jsonSer0=: '"', jsonEsc@:":, '"'"_ jsonEsc=: rplc&(<;._1' \ \\ " \"') -jsonSerialize=:jsonSer0`jsonSer1@.(*@L.) +jsonSerialize=:jsonSer0`jsonSer2@.(*@L.) diff --git a/Task/JSON/J/json-2.j b/Task/JSON/J/json-2.j index 305585a38e..31f8458a92 100644 --- a/Task/JSON/J/json-2.j +++ b/Task/JSON/J/json-2.j @@ -1,10 +1,13 @@ jsonParse'{ "blue": [1,2], "ocean": "water" }' -┌──────────────────────────────┐ -│┌──────┬─────┬───────┬───────┐│ -││"blue"│┌─┬─┐│"ocean"│"water"││ -││ ││1│2││ │ ││ -││ │└─┴─┘│ │ ││ -│└──────┴─────┴───────┴───────┘│ +┌────────────────┐ +│┌──────┬───────┐│ +││"blue"│"ocean"││ +│├──────┼───────┤│ +││┌─┬─┐ │"water"││ +│││1│2│ │ ││ +││└─┴─┘ │ ││ +│└──────┴───────┘│ +└────────────────┘ └──────────────────────────────┘ jsonSerialize jsonParse'{ "blue": [1,2], "ocean": "water" }' -[["\"blue\"",["1","2"],"\"ocean\"","\"water\""]] +[[["\"blue\"","\"ocean\""],[["1","2"],"\"water\""]]] diff --git a/Task/JSON/Maple/json.maple b/Task/JSON/Maple/json.maple new file mode 100644 index 0000000000..85730a1f76 --- /dev/null +++ b/Task/JSON/Maple/json.maple @@ -0,0 +1,4 @@ +> JSON:-ParseString("[{\"tree\": \"maple\", \"count\": 21}]"); + [table(["tree" = "maple", "count" = 21])] +> JSON:-ToString( [table(["tree" = "maple", "count" = 21])] ); + "[{\"count\": 21, \"tree\": \"maple\"}]" diff --git a/Task/JSON/PureBasic/json.purebasic b/Task/JSON/PureBasic/json.purebasic new file mode 100644 index 0000000000..aa19aa1753 --- /dev/null +++ b/Task/JSON/PureBasic/json.purebasic @@ -0,0 +1,34 @@ +OpenConsole() +If CreateJSON(1) + PB_Team_Members=SetJSONObject(JSONValue(1)) + SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_1"),"Frederic Laboureur") + SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_2"),"Andre Beer") + SetJSONString(AddJSONMember(PB_Team_Members,"PB_Team_Member_3"),"Timo Harter") +EndIf + +If CreateJSON(2) + Former_Team_Members=SetJSONArray(JSONValue(2)) + SetJSONString(AddJSONElement(Former_Team_Members),"Richard Andersson") + SetJSONString(AddJSONElement(Former_Team_Members),"Benny Sels") + SetJSONString(AddJSONElement(Former_Team_Members),"Danilo Krahn") +EndIf + +PrintN("PureBasic - Team Members:") +PrintN(ComposeJSON(1,#PB_JSON_PrettyPrint)+#CRLF$) +PrintN("PureBasic - Former Team Members:") +PrintN(ComposeJSON(2,#PB_JSON_PrettyPrint)+#CRLF$) + +#DL=Chr(34) +PB_Special_thanks$="[ " +#DL+"Gary Willoughby"+#DL+", " +#DL+"Mark James"+#DL+", " +#DL+"Neil Hodgson"+#DL+" ]" +NewList otherpersons.s() + +If ParseJSON(3,PB_Special_thanks$) + ExtractJSONList(JSONValue(3),otherpersons()) + PrintN("Pure Basic - and others:") + ForEach otherpersons() : PrintN(otherpersons()) : Next +Else + PrintN(JSONErrorMessage() + " : " + Str(JSONErrorPosition())) + PrintN(Left(PB_Special_thanks$,JSONErrorPosition())) + PrintN(Mid(PB_Special_thanks$,JSONErrorPosition()+1)) +EndIf +Input() diff --git a/Task/JSON/Ruby/json.rb b/Task/JSON/Ruby/json.rb index 6cec45a5ba..ca82a5c622 100644 --- a/Task/JSON/Ruby/json.rb +++ b/Task/JSON/Ruby/json.rb @@ -5,3 +5,4 @@ puts ruby_obj["blue"].class ruby_obj["ocean"] = {"water" => %w{fishy salty}} puts JSON.generate(ruby_obj) +puts JSON.pretty_generate(ruby_obj) diff --git a/Task/JSON/Rust/json.rust b/Task/JSON/Rust/json.rust index a88ddd250a..1aad4071c5 100644 --- a/Task/JSON/Rust/json.rust +++ b/Task/JSON/Rust/json.rust @@ -1,14 +1,16 @@ -extern crate serialize; -use serialize::json; -#[deriving(Decodable, Encodable)] +extern crate rustc_serialize; + +use rustc_serialize::json; + +#[derive(RustcDecodable, RustcEncodable)] struct Penguin { name : String, born : i16 } fn main() { let pengu = Penguin { name : "pengu".to_string(), born : 1999 }; - println!("{}", json::encode(&pengu)); + println!("{}", json::encode(&pengu).unwrap()); let pingu : Penguin = json::decode(r##"{"name":"pingu","born":2001}"##).unwrap(); - assert_eq!(pingu.name.as_slice(), "pingu"); + assert_eq!(&pingu.name, "pingu"); assert_eq!(pingu.born, 2001); } diff --git a/Task/JSON/Scheme/json.ss b/Task/JSON/Scheme/json.ss new file mode 100644 index 0000000000..f9cc047a2a --- /dev/null +++ b/Task/JSON/Scheme/json.ss @@ -0,0 +1,12 @@ +(use json) +(define object-example + (with-input-from-string "{\"foo\": \"bar\", \"baz\": [1, 2, 3]}" + json-read)) +(pp object-example) +; this prints #(("foo" . "bar") ("baz" 1 2 3)) + +(json-write #([foo . bar] + [baz 1 2 3] + [qux . #((rosetta . code))])) +; this writes the following: +; {"foo": "bar", "baz": [1, 2, 3], "qux": {"foo": "bar"}} diff --git a/Task/JSON/Tcl/json-2.tcl b/Task/JSON/Tcl/json-2.tcl index ea3c147562..54bc36ba37 100644 --- a/Task/JSON/Tcl/json-2.tcl +++ b/Task/JSON/Tcl/json-2.tcl @@ -1,4 +1,5 @@ package require Tcl 8.6 +package require json::write proc tcl2json value { # Guess the type of the value; deep *UNSUPPORTED* magic! @@ -7,25 +8,14 @@ proc tcl2json value { switch $type { string { - # Skip to the mapping code at the bottom + return [json::write string $value] } dict { - set result "{" - set pfx "" - dict for {k v} $value { - append result $pfx [tcl2json $k] ": " [tcl2json $v] - set pfx ", " - } - return [append result "}"] + return [json::write object {*}[ + dict map {k v} $value {tcl2json $v}]] } list { - set result "\[" - set pfx "" - foreach v $value { - append result $pfx [tcl2json $v] - set pfx ", " - } - return [append result "\]"] + return [json::write array {*}[lmap v $value {tcl2json $v}]] } int - double { return [expr {$value}] @@ -46,11 +36,7 @@ proc tcl2json value { } elseif {[string is boolean -strict $value]} { return [expr {$value ? "true" : "false"}] } + return [json::write string $value] } } - - # For simplicity, all "bad" characters are mapped to \u... substitutions - set mapped [subst -novariables [regsub -all {[][\u0000-\u001f\\""]} \ - $value {[format "\\\\u%04x" [scan {& } %c]]}]] - return "\"$mapped\"" } diff --git a/Task/Jensens-Device/Bracmat/jensens-device.bracmat b/Task/Jensens-Device/Bracmat/jensens-device.bracmat new file mode 100644 index 0000000000..e2e48cf89d --- /dev/null +++ b/Task/Jensens-Device/Bracmat/jensens-device.bracmat @@ -0,0 +1,14 @@ +( ( sum + = I lo hi Term temp + . !arg:((=?I),?lo,?hi,(=?Term)) + & 0:?temp + & !lo:?!I + & whl + ' ( !!I:~>!hi + & !temp+!Term:?temp + & 1+!!I:?!I + ) + & !temp + ) +& sum$((=i),1,100,(=!i^-1)) +); diff --git a/Task/Jensens-Device/Elixir/jensens-device.elixir b/Task/Jensens-Device/Elixir/jensens-device.elixir new file mode 100644 index 0000000000..47f5943782 --- /dev/null +++ b/Task/Jensens-Device/Elixir/jensens-device.elixir @@ -0,0 +1,11 @@ +defmodule JensenDevice do + def task, do: sum( 1, 100, fn i -> 1 / i end ) + + defp sum( i, high, _term ) when i > high, do: 0 + defp sum( i, high, term ) do + temp = term.( i ) + temp + sum( i + 1, high, term ) + end +end + +IO.puts JensenDevice.task diff --git a/Task/Jensens-Device/Erlang/jensens-device.erl b/Task/Jensens-Device/Erlang/jensens-device.erl index 0610f7cdbc..2c74b5eec6 100644 --- a/Task/Jensens-Device/Erlang/jensens-device.erl +++ b/Task/Jensens-Device/Erlang/jensens-device.erl @@ -5,8 +5,6 @@ task() -> sum( 1, 100, fun (I) -> 1 / I end ). - - sum( I, High, _Term ) when I > High -> 0; sum( I, High, Term ) -> Temp = Term( I ), diff --git a/Task/Jensens-Device/Julia/jensens-device.julia b/Task/Jensens-Device/Julia/jensens-device.julia new file mode 100644 index 0000000000..323d163cd6 --- /dev/null +++ b/Task/Jensens-Device/Julia/jensens-device.julia @@ -0,0 +1,17 @@ +i = 0 + +macro sum(i, lo_byname, hi_byname, term) + quote + lo = $lo_byname + hi = $hi_byname + temp = 0.0 + + for i=lo:hi + temp += $term + end + + temp + end +end + +println(@sum(i, 1, 100, 1.0 / i)) diff --git a/Task/Jensens-Device/Ruby/jensens-device-3.rb b/Task/Jensens-Device/Ruby/jensens-device-3.rb new file mode 100644 index 0000000000..05176d033c --- /dev/null +++ b/Task/Jensens-Device/Ruby/jensens-device-3.rb @@ -0,0 +1,6 @@ +def sum lo, hi, &term + (lo..hi).map(&term).reduce(:+) +end +p sum(1,100){|i|1.0/i} # => 5.187377517639621 +# or using Rational: +p sum(1,100){|i|Rational(1)/i} # => 14466636279520351160221518043104131447711 / 2788815009188499086581352357412492142272 diff --git a/Task/Josephus-problem/ALGOL-68/josephus-problem.alg b/Task/Josephus-problem/ALGOL-68/josephus-problem.alg new file mode 100644 index 0000000000..820d2edb5f --- /dev/null +++ b/Task/Josephus-problem/ALGOL-68/josephus-problem.alg @@ -0,0 +1,12 @@ +BEGIN + PROC josephus = (INT n, k, m) INT : + CO Return m-th on the reversed kill list; m=0 is final survivor. CO + BEGIN + INT lm := m; CO Local copy of m CO + FOR a FROM m+1 WHILE a <= n DO lm := (lm+k) %* a OD; + lm + END; + INT n = 41, k=3; + printf (($"n = ", g(0), ", k = ", g(0), ", final survivor: ", g(0)l$, + n, k, josephus (n, k, 0))) +END diff --git a/Task/Josephus-problem/Batch-File/josephus-problem.bat b/Task/Josephus-problem/Batch-File/josephus-problem.bat new file mode 100644 index 0000000000..6b357de1d5 --- /dev/null +++ b/Task/Josephus-problem/Batch-File/josephus-problem.bat @@ -0,0 +1,32 @@ +@echo off +setlocal enabledelayedexpansion + +set "prison=41" %== Number of prisoners ==% +set "step=3" %== The step... ==% +set "survive=1" %== Number of survivors ==% +call :josephus + +set "prison=41" +set "step=3" +set "survive=3" +call :josephus +pause +exit /b 0 + + %== The Procedure ==% +:josephus +set "surv_list=" +for /l %%S in (!survive!,-1,1) do ( + + set /a "m = %%S - 1" + for /l %%X in (%%S,1,!prison!) do ( + set /a "m = (m + step) %% %%X" + ) + if defined surv_list ( + set "surv_list=!surv_list! !m!" + ) else ( + set "surv_list=!m!" + ) +) +echo !surv_list! +goto :EOF diff --git a/Task/Josephus-problem/Befunge/josephus-problem.bf b/Task/Josephus-problem/Befunge/josephus-problem.bf new file mode 100644 index 0000000000..65aeb9d8f2 --- /dev/null +++ b/Task/Josephus-problem/Befunge/josephus-problem.bf @@ -0,0 +1,4 @@ +>0" :srenosirP">:#,_&>>00p>>v +v0p01<&_,#!>#:<"Step size: "< +>1+:20p00g`!#v_0" :rovivru"v +^g02%g02+g01<<@.$_,#!>#:<"S"< diff --git a/Task/Josephus-problem/Clojure/josephus-problem.clj b/Task/Josephus-problem/Clojure/josephus-problem.clj new file mode 100644 index 0000000000..66af000c54 --- /dev/null +++ b/Task/Josephus-problem/Clojure/josephus-problem.clj @@ -0,0 +1,13 @@ +(defn rotate [n s] (lazy-cat (drop n s) (take n s))) + +(defn josephus [n k] + (letfn [(survivor [[ h & r :as l] k] + (cond (empty? r) h + :else (survivor (rest (rotate (dec k) l)) k)))] + (survivor (range n) k))) + +(let [n 41 k 3] + (println (str "Given " n " prisoners in a circle numbered 1.." n + ", an executioner moving around the")) + (println (str "circle " k " at a time will leave prisoner number " + (inc (josephus n k)) " as the last survivor."))) diff --git a/Task/Josephus-problem/D/josephus-problem.d b/Task/Josephus-problem/D/josephus-problem-1.d similarity index 100% rename from Task/Josephus-problem/D/josephus-problem.d rename to Task/Josephus-problem/D/josephus-problem-1.d diff --git a/Task/Josephus-problem/D/josephus-problem-2.d b/Task/Josephus-problem/D/josephus-problem-2.d new file mode 100644 index 0000000000..7799d0a4ac --- /dev/null +++ b/Task/Josephus-problem/D/josephus-problem-2.d @@ -0,0 +1,17 @@ +import std.stdio, std.algorithm, std.range; + +int[][] Josephus(in int n, int k, int s=1) { + int[] ks, ps = n.iota.array; + for (int i=--k; ps.length>s; i=(i+k)%ps.length) { + ks ~= ps[i]; + ps = remove(ps, i); + } + writefln("Josephus(%d,%d,%d) -> %(%d %) / %(%d %)%s", n, k, s, ps, ks[0..min($,45)], ks.length<45 ? "" : " ..." ); + return [ps, ks]; +} + +void main() { + Josephus(5, 2); + Josephus(41, 3); + Josephus(23482, 3343, 3); +}} diff --git a/Task/Josephus-problem/Eiffel/josephus-problem.e b/Task/Josephus-problem/Eiffel/josephus-problem.e new file mode 100644 index 0000000000..ec23364f26 --- /dev/null +++ b/Task/Josephus-problem/Eiffel/josephus-problem.e @@ -0,0 +1,52 @@ +class + APPLICATION + +create + make + +feature + + make + do + io.put_string ("Survivor is prisoner: " + execute (12, 4).out) + end + + execute (n, k: INTEGER): INTEGER + -- Survivor of 'n' prisoners, when every 'k'th is executed. + require + n_positive: n > 0 + k_positive: k > 0 + n_larger: n > k + local + killidx: INTEGER + prisoners: LINKED_LIST [INTEGER] + do + create prisoners.make + across + 0 |..| (n - 1) as c + loop + prisoners.extend (c.item) + end + io.put_string ("Prisoners are executed in the order:%N") + killidx := 1 + from + until + prisoners.count <= 1 + loop + killidx := killidx + k - 1 + from + until + killidx <= prisoners.count + loop + killidx := killidx - prisoners.count + end + io.put_string (prisoners.at (killidx).out + "%N") + prisoners.go_i_th (killidx) + prisoners.remove + end + Result := prisoners.at (1) + ensure + Result_in_range: Result >= 0 and Result < n + end + +end diff --git a/Task/Josephus-problem/Elixir/josephus-problem.elixir b/Task/Josephus-problem/Elixir/josephus-problem.elixir new file mode 100644 index 0000000000..cd5853b603 --- /dev/null +++ b/Task/Josephus-problem/Elixir/josephus-problem.elixir @@ -0,0 +1,15 @@ +defmodule Josephus do + def find(n,k) do + find(Enum.to_list(0..n-1),0..k-2,k..n) + end + + def find([_|[r|_]],_,_..d) when d < 3 do + IO.inspect r + end + + def find(arr,a..c,b..d) when length(arr) >= 3 do + find(Enum.slice(arr,b..d) ++ Enum.slice(arr,a..c),a..c,b..d-1) + end +end + +Josephus.find(41,3) diff --git a/Task/Josephus-problem/J/josephus-problem-4.j b/Task/Josephus-problem/J/josephus-problem-4.j index 2a3375a129..5754335f0b 100644 --- a/Task/Josephus-problem/J/josephus-problem-4.j +++ b/Task/Josephus-problem/J/josephus-problem-4.j @@ -1,4 +1,4 @@ -Josephus2 =: 4 : '(|x&+)/i.->:y' NB. this is a direct translation of the algo from C code above. +Josephus2 =: 4 : '(| x&+)/i. - 1+y' NB. this is a direct translation of the algo from C code above. 3 Josephus2 41 30 diff --git a/Task/Josephus-problem/Java/josephus-problem.java b/Task/Josephus-problem/Java/josephus-problem-1.java similarity index 100% rename from Task/Josephus-problem/Java/josephus-problem.java rename to Task/Josephus-problem/Java/josephus-problem-1.java diff --git a/Task/Josephus-problem/Java/josephus-problem-2.java b/Task/Josephus-problem/Java/josephus-problem-2.java new file mode 100644 index 0000000000..f431de4443 --- /dev/null +++ b/Task/Josephus-problem/Java/josephus-problem-2.java @@ -0,0 +1,37 @@ +import java.util.ArrayList; +import java.util.List; + +public class Josephus { + + public static void main(String[] args) { + execute(5, 1); + execute(41, 2); + execute(23482, 3342, 3); + } + + public static int[][] execute(int n, int k) { + return execute(n, k, 1); + } + + public static int[][] execute(int n, int k, int s) { + List ps = new ArrayList(n); + for (int i=0; i ks = new ArrayList(n-s); + for (int i=k; ps.size()>s; i=(i+k)%ps.size()) ks.add(ps.remove(i)); + System.out.printf("Josephus(%d,%d,%d) -> %s / %s\n", n, k, s, toString(ps), toString(ks)); + return new int[][] { + ps.stream().mapToInt(Integer::intValue).toArray(), + ks.stream().mapToInt(Integer::intValue).toArray() + }; + } + + private static String toString(List ls) { + String dot = ""; + if (ls.size() >= 45) { + dot = ", ..."; + ls = ls.subList(0, 45); + } + String s = ls.toString(); + return s.substring(1, s.length()-1) + dot; + } +} diff --git a/Task/Josephus-problem/JavaScript/josephus-problem.js b/Task/Josephus-problem/JavaScript/josephus-problem-1.js similarity index 100% rename from Task/Josephus-problem/JavaScript/josephus-problem.js rename to Task/Josephus-problem/JavaScript/josephus-problem-1.js diff --git a/Task/Josephus-problem/JavaScript/josephus-problem-2.js b/Task/Josephus-problem/JavaScript/josephus-problem-2.js new file mode 100644 index 0000000000..a769f69fda --- /dev/null +++ b/Task/Josephus-problem/JavaScript/josephus-problem-2.js @@ -0,0 +1,7 @@ +function Josephus(n, k, s) { + s = s | 1 + for (var ps=[], i=n; i--; ) ps[i]=i + for (var ks=[], i=--k; ps.length>s; i=(i+k)%ps.length) ks.push(ps.splice(i, 1)) + document.write((arguments.callee+'').split(/\s|\(/)[1], '(', [].slice.call(arguments, 0), ') -> ', ps, ' / ', ks.length<45?ks:ks.slice(0,45)+',...' , '
') + return [ps, ks] +} diff --git a/Task/Josephus-problem/PHP/josephus-problem.php b/Task/Josephus-problem/PHP/josephus-problem.php new file mode 100644 index 0000000000..7eb70756cd --- /dev/null +++ b/Task/Josephus-problem/PHP/josephus-problem.php @@ -0,0 +1,20 @@ +$dead){ + if(!$dead){//so yeah...if not dead... + if($deadpool==$k){//if their time is up in the deadpool... + $order++; + //set the deadpool value or enumerate as survivor + $prisoners[$thisPrisoner]=((($n-$m)>($order)?$order:(($n)==$order?'Call me *Titus Flavius* Josephus':'Joe\'s friend '.(($order)-($n-$m-1))))); + $deadpool=1;//reset count to next execution + }else{$duckpool++;} + } + } + } + return $prisoners; +} +echo '
'.print_r(Jotapata(41,3,5),true).'
';
diff --git a/Task/Josephus-problem/PowerShell/josephus-problem.psh b/Task/Josephus-problem/PowerShell/josephus-problem.psh
new file mode 100644
index 0000000000..85eb91f572
--- /dev/null
+++ b/Task/Josephus-problem/PowerShell/josephus-problem.psh
@@ -0,0 +1,41 @@
+function main($n=0,$k=0,$s=0) {
+	#n - number of prisoners
+	#k - kill every k'th prisoner
+	#s - number of survivors
+
+	write-host "`nn=$n k=$k s=$s"  #show arguments
+
+	#Error Checking (Optional)
+	try {
+		if ([int]$n -lt 0){write-host "[n`<0] " -nonewline;$errors++}
+		if ([int]$k -lt 0){write-host "[k`<0] " -nonewline;$errors++}
+		if ([int]$s -lt 0){write-host "[s`<0] " -nonewline;$errors++}
+		if ([int]$s -gt [int]$n){write-host "[s`>n] " -nonewline;$errors++}
+		if ($errors -gt 0) {"";return}
+	} catch {"Oops! I found a string input.";return}
+
+	$dead = @(0) * $n+1
+	$nn=$n
+	$p=-1
+	while ($n -ne $s){
+		$found=0
+		while ($found -ne $k){
+			if ($p++ -eq $nn) { $p=0 }
+			if ($dead[$p] -ne 1) {$found++}
+		}
+		$dead[$p]++
+		$killed+="$p "
+		$n--
+	}
+	for($i=0;$i -le $nn-1;$i++){
+		if ($dead[$i] -ne 1) {$survived+="$i "}
+	}
+	write-host "Killed: $killed"
+	write-host "Survived: $survived"
+	return
+}
+
+main 5 2 1
+main 41 3 1
+main 41 3 3
+main 2 -3 4
diff --git a/Task/Josephus-problem/PureBasic/josephus-problem.purebasic b/Task/Josephus-problem/PureBasic/josephus-problem.purebasic
new file mode 100644
index 0000000000..6a3978ae7b
--- /dev/null
+++ b/Task/Josephus-problem/PureBasic/josephus-problem.purebasic
@@ -0,0 +1,35 @@
+Define.i
+NewList prisoners.i()
+
+Procedure f2l(List p.i())
+  FirstElement(p())    : tmp.i=p()
+  DeleteElement(p(),1) : LastElement(p())
+  AddElement(p())      : p()=tmp
+EndProcedure
+
+Procedure l2f(List p.i())
+  LastElement(p())   : tmp.i=p()
+  DeleteElement(p()) : FirstElement(p())
+  InsertElement(p()) : p()=tmp
+EndProcedure
+
+OpenConsole()
+Repeat
+  Print(#LF$+#LF$)
+  Print("Josephus problem - input prisoners : ") : n=Val(Input())
+  If n=0 : Break : EndIf
+  Print("                 - input steps     : ") : k=Val(Input())
+  Print("                 - input survivors : ") : s=Val(Input()) : If s<1 : s=1 : EndIf
+  ClearList(prisoners()) : For i=0 To n-1 : AddElement(prisoners()) : prisoners()=i : Next
+  If n<100 : Print("Executed : ") : EndIf
+  While ListSize(prisoners())>s And n>0 And k>0 And kp then do                     /*   [↓] remove some prisoner(s).*/
+/*REXX program:  Josephus problem: N men standing in a circle, every Kth kilt.*/
+parse arg N K Z R .                    /*get the optional arguments from C.L. */
+if N==',' | N==''   then  N = 41       /*no  #prisoners?  Then use the default*/
+if K==',' | K==''   then  K =  3       /*no  kill count?    "   "   "     "   */
+if Z==',' | Z==''   then  Z =  0       /*no  initial # ?    "   "   "     "   */
+if R==',' | R==''   then  R =  1       /*no  remaining#?    "   "   "     "   */
+$=; x=;  do pop=Z for N;  $=$ pop; end /*populate prisoner's circle (with a #)*/
+c=0                                    /*initial prisoner  count─off  number. */
+    do remove=0;   p=words($)          /*keep removing until  R  are remaining*/
+    c=c+K                              /*bump the prisoner  count-off  by  K. */
+    if c>p then do                     /*   [↓] remove (kill) some prisoner(s)*/
                   do j=1  for words(x);   $=delword($,word(x,j)+1-j,1)
-                  if words($)==R  then leave remove  /*slaying done yet?*/
+                  if words($)==R  then leave remove    /*is the slaying done? */
                   end   /*j*/
-                c=(c//p)//words($); x= /*adjust prisoner count-off &list*/
+                c=(c//p)//words($); x= /*adjust prisoner count-off and circle.*/
                 end
-    if c\==0  then x=x c               /*list of prisoners to be removed*/
-    end   /*remove*/                   /*remove 'til  R  prisoners left.*/
+    if c\==0  then x=x c               /*the list of prisoners to be removed. */
+    end   /*remove*/                   /*remove 'til   R   prisoners are left.*/
 
-say 'removing every ' th(K) " prisoner out of " N ' (starting at' Z")  with ",
-    R ' survivor's(R)"," ;             say 'leaving prisoner's(R)':' $
-exit                                   /*stick a fork in it, we're done.*/
-/*──────────────────────────────────subroutines──────────────────────────*/
+say 'removing every '  th(K)  " prisoner out of " N ' (starting at' Z")  with ",
+     R ' survivor's(R)",";             say 'leaving prisoner's(R)':'  $
+exit                                   /*stick a fork in it,  we're all done. */
+/*──────────────────────────────────subroutines───────────────────────────────*/
 s:  if arg(1)==1  then return arg(3);   return word(arg(2) 's',1)
-th: arg y; return y||word('th st nd rd', 1+y//10*(y//100%10\==1)*(y//10<4))
+th: parse arg y; return y||word('th st nd rd',1+y//10*(y//100%10\==1)*(y//10<4))
diff --git a/Task/Josephus-problem/VBScript/josephus-problem.vb b/Task/Josephus-problem/VBScript/josephus-problem.vb
new file mode 100644
index 0000000000..efc7d165a7
--- /dev/null
+++ b/Task/Josephus-problem/VBScript/josephus-problem.vb
@@ -0,0 +1,32 @@
+Function josephus(n,k,s)
+	Set prisoner = CreateObject("System.Collections.ArrayList")
+	For i = 0 To n - 1
+		prisoner.Add(i)
+	Next
+	index = -1
+	Do Until prisoner.Count = s
+		step_count = 0
+		Do Until step_count = k
+			If index+1 <= prisoner.Count-1 Then
+				index = index+1
+			Else
+				index = (index+1)-(prisoner.Count)
+			End If
+			step_count = step_count+1
+		Loop
+		prisoner.RemoveAt(index)
+		index = index-1
+	Loop
+	For j = 0 To prisoner.Count-1
+		If j < prisoner.Count-1 Then
+			josephus = josephus & prisoner(j) & ","
+		Else
+			josephus = josephus & prisoner(j)
+		End If
+	Next
+End Function
+
+'testing the function
+WScript.StdOut.WriteLine josephus(5,2,1)
+WScript.StdOut.WriteLine josephus(41,3,1)
+WScript.StdOut.WriteLine josephus(41,3,3)
diff --git a/Task/Jump-anywhere/Common-Lisp/jump-anywhere.lisp b/Task/Jump-anywhere/Common-Lisp/jump-anywhere.lisp
new file mode 100644
index 0000000000..e496cd8a72
--- /dev/null
+++ b/Task/Jump-anywhere/Common-Lisp/jump-anywhere.lisp
@@ -0,0 +1,13 @@
+(tagbody
+  beginning
+    (format t "I am in the beginning~%")
+    (sleep 1)
+    (go end)
+  middle
+    (format t "I am in the middle~%")
+    (sleep 1)
+    (go beginning)
+  end
+    (format t "I am in the end~%")
+    (sleep 1)
+    (go middle))
diff --git a/Task/Jump-anywhere/DCL/jump-anywhere.dcl b/Task/Jump-anywhere/DCL/jump-anywhere.dcl
new file mode 100644
index 0000000000..0687caede0
--- /dev/null
+++ b/Task/Jump-anywhere/DCL/jump-anywhere.dcl
@@ -0,0 +1,71 @@
+$ return  ! ignored since we haven't done a gosub yet
+$
+$ if p1 .eqs. "" then $ goto main
+$ inner:
+$ exit
+$
+$ main:
+$ goto label  ! if label hasn't been read yet then DCL will read forward to find label
+$ label:
+$ write sys$output "after first occurrence of label"
+$
+$ on control_y then $ goto continue1  ! we will use this to get out of the loop that's coming up
+$
+$ label:  ! duplicate labels *are* allowed, the most recently read is the one that will be the target
+$  write sys$output "after second occurrence of label"
+$  wait 0::2  ! since we are in a loop this will slow things down
+$  goto label  ! hit ctrl-y to break out
+$
+$ continue1:  ! the previous "on control_y" remains in force despite having been triggered
+$
+$ label = "jump"
+$ goto 'label  ! target can be a variable; talk about handy
+$ jump:
+$ write sys$output "after first occurrence of jump"
+$
+$ first_time = "true"
+$ continue_label = "continue2"
+$ 'continue_label:  ! even the label can be a variable (but only backwards); talk about handy
+$ if first_time then $ goto skip
+$ break = "true"
+$ return
+$
+$ skip:
+$ first_time = "false"
+$
+$ on control_y then $ gosub 'continue_label  ! setup a new on control_y to get out the next loop coming up
+$
+$ break = "false"
+$ 'label:
+$  write sys$output "after second occurrence of jump"
+$  wait 0::2
+$  if .not. break then $ goto 'label
+$
+$ gosub sub1  ! no new scope or parameters
+$ label = "sub1"
+$ gosub 'label
+$
+$ call sub4 a1 b2 c3  ! new scope and parameters
+$
+$ @nl:  ! new scope and parameters in another file but same process
+$
+$ procedure_filename = f$environment( "procedure " )  ! what is our own filename?
+$ @'procedure_filename inner
+$
+$ exit  ! exiting outermost scope exits the command procedure altogether, i.e. back to shell
+$
+$ sub1:
+$ return
+$
+$ sub2:
+$ goto break  ! structurally disorganized but allowed
+$
+$ sub3:
+$ return
+$
+$ break:
+$ return
+$
+$ sub4: subroutine
+$ exit
+$ endsubroutine
diff --git a/Task/Jump-anywhere/Forth/jump-anywhere-1.fth b/Task/Jump-anywhere/Forth/jump-anywhere-1.fth
new file mode 100644
index 0000000000..46969c4c9f
--- /dev/null
+++ b/Task/Jump-anywhere/Forth/jump-anywhere-1.fth
@@ -0,0 +1,19 @@
+0 value goto1 0 value goto2 0 value goto3 0 value goto4 0 value goto5
+0 value goto6 0 value goto7 0 value goto8 0 value goto9 0 value goto10
+
+: proc1
+[ here to goto1 ] s" line1 " type goto7 >r exit
+[ here to goto2 ] s" line2 " type goto8 >r exit
+[ here to goto3 ] s" line3 " type goto9 >r exit
+[ here to goto4 ] s" line4 " type goto10 >r exit
+[ here to goto5 ] s" line5" type cr ;
+
+: proc2
+[ here to goto6 ] s" line6 " type goto1 >r exit
+[ here to goto7 ] s" line7 " type goto2 >r exit
+[ here to goto8 ] s" line8 " type goto3 >r exit
+[ here to goto9 ] s" line9 " type goto4 >r exit
+[ here to goto10 ] s" line10 " type goto5 >r ;
+
+proc2
+bye
diff --git a/Task/Jump-anywhere/Forth/jump-anywhere-2.fth b/Task/Jump-anywhere/Forth/jump-anywhere-2.fth
new file mode 100644
index 0000000000..c2c8c7b749
--- /dev/null
+++ b/Task/Jump-anywhere/Forth/jump-anywhere-2.fth
@@ -0,0 +1 @@
+line6 line1 line7 line2 line8 line3 line9 line4 line10 line5
diff --git a/Task/Jump-anywhere/Forth/jump-anywhere-3.fth b/Task/Jump-anywhere/Forth/jump-anywhere-3.fth
new file mode 100644
index 0000000000..804fcf9cbc
--- /dev/null
+++ b/Task/Jump-anywhere/Forth/jump-anywhere-3.fth
@@ -0,0 +1,35 @@
+create gotos 11 cells allot  \ data structure consisting of 10 cells for
+                             \ storing addrs of goto markers/labels.
+                             \ 11 cells are allocated, with the 1st cell
+                             \ unused, for the offset would be 0. to begin
+                             \ counting from 1, the offset of the 2nd cell,
+                             \ is easier to remember. this is merely a preference.
+                             \ if additional goto markers are needed, merely
+                             \ increase the quantity of cells in this data structure.
+
+: mark_goto here swap cells gotos + ! ; immediate  \ position (offset) of cell within
+                                                   \ data structure must be on stack.
+
+: goto  r> drop  cells gotos + @ >r  exit ;  \ "exit" is needed for iforth only.
+                                             \ position (offset) of cell within
+                                             \ data structure must be on stack.
+
+\ designations for commands are immaterial when using goto's,
+\ since the commands are not referenced by name, and are instead
+\ jumped into by means of the goto marker.
+
+: command1
+[ 1 ] mark_goto s" line1 " type 7 goto
+[ 2 ] mark_goto s" line2 " type 8 goto
+[ 3 ] mark_goto s" line3 " type 9 goto
+[ 4 ] mark_goto s" line4 " type 10 goto
+[ 5 ] mark_goto s" line5" type cr bye ;
+
+: command2
+[ 6 ] mark_goto s" line6 " type 1 goto
+[ 7 ] mark_goto s" line7 " type 2 goto
+[ 8 ] mark_goto s" line8 " type 3 goto
+[ 9 ] mark_goto s" line9 " type 4 goto
+[ 10 ] mark_goto s" line10 " type 5 goto ;
+
+: go 6 goto ; go
diff --git a/Task/Jump-anywhere/Forth/jump-anywhere-4.fth b/Task/Jump-anywhere/Forth/jump-anywhere-4.fth
new file mode 100644
index 0000000000..c2c8c7b749
--- /dev/null
+++ b/Task/Jump-anywhere/Forth/jump-anywhere-4.fth
@@ -0,0 +1 @@
+line6 line1 line7 line2 line8 line3 line9 line4 line10 line5
diff --git a/Task/Jump-anywhere/J/jump-anywhere.j b/Task/Jump-anywhere/J/jump-anywhere-1.j
similarity index 100%
rename from Task/Jump-anywhere/J/jump-anywhere.j
rename to Task/Jump-anywhere/J/jump-anywhere-1.j
diff --git a/Task/Jump-anywhere/J/jump-anywhere-2.j b/Task/Jump-anywhere/J/jump-anywhere-2.j
new file mode 100644
index 0000000000..67ad4b0f5d
--- /dev/null
+++ b/Task/Jump-anywhere/J/jump-anywhere-2.j
@@ -0,0 +1,18 @@
+H=: verb define
+  smoutput 'a'
+  label_b.
+  smoutput 'c'
+  goto_f.
+  label_d.
+  smoutput 'e' return.
+  label_f.
+  smoutput 'g'
+  goto_d.
+  smoutput 'h'
+)
+
+   H''
+a
+c
+g
+e
diff --git a/Task/Jump-anywhere/PureBasic/jump-anywhere.purebasic b/Task/Jump-anywhere/PureBasic/jump-anywhere.purebasic
new file mode 100644
index 0000000000..878add2d0d
--- /dev/null
+++ b/Task/Jump-anywhere/PureBasic/jump-anywhere.purebasic
@@ -0,0 +1,31 @@
+OnErrorGoto(?ErrorHandler)
+OpenConsole()
+Gosub label4
+Goto label3
+
+label1:
+Print("eins ")
+Return
+
+label2:
+Print("zwei ")
+Return
+
+label3:
+Print("drei ")
+
+label4:
+While i<3
+  i+1
+  Gosub label1
+  Gosub label2
+Wend
+Print("- ")
+i+1
+If i<=4 : Return : EndIf
+x.i=Val(Input()) : y=1/x
+Input()
+End
+
+ErrorHandler:
+PrintN(ErrorMessage()) : Goto label4
diff --git a/Task/K-d-tree/C/k-d-tree.c b/Task/K-d-tree/C/k-d-tree.c
index 628e58c361..2da396814c 100644
--- a/Task/K-d-tree/C/k-d-tree.c
+++ b/Task/K-d-tree/C/k-d-tree.c
@@ -6,168 +6,168 @@
 
 #define MAX_DIM 3
 struct kd_node_t{
-	double x[MAX_DIM];
-	struct kd_node_t *left, *right;
+    double x[MAX_DIM];
+    struct kd_node_t *left, *right;
 };
 
-inline double
+    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;
+    double t, d = 0;
+    while (dim--) {
+        t = a->x[dim] - b->x[dim];
+        d += t * t;
+    }
+    return d;
 }
+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));
+}
+
 
 /* see quickselect method */
-struct kd_node_t*
+    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;
-	}
+    if (end <= start) return NULL;
+    if (end == start + 1)
+        return start;
+
+    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*
+    struct kd_node_t*
 make_tree(struct kd_node_t *t, int len, int i, int dim)
 {
-	struct kd_node_t *n;
+    struct kd_node_t *n;
 
-	if (!len) return 0;
+    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;
+    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)
+        struct kd_node_t **best, double *best_dist)
 {
-	double d, dx, dx2;
+    double d, dx, dx2;
 
-	if (!root) return;
-	d = dist(root, nd, dim);
-	dx = root->x[i] - nd->x[i];
-	dx2 = dx * dx;
+    if (!root) return;
+    d = dist(root, nd, dim);
+    dx = root->x[i] - nd->x[i];
+    dx2 = dx * dx;
 
-	visited ++;
+    visited ++;
 
-	if (!*best || d < *best_dist) {
-		*best_dist = d;
-		*best = root;
-	}
+    if (!*best || d < *best_dist) {
+        *best_dist = d;
+        *best = root;
+    }
 
-	/* if chance of exact match is high */
-	if (!*best_dist) return;
+    /* if chance of exact match is high */
+    if (!*best_dist) return;
 
-	if (++i >= dim) i = 0;
+    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);
+    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 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;
+    int i;
+    struct kd_node_t wp[] = {
+        {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}}
+    };
+    struct kd_node_t testNode = {{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, &testNode, 0, 2, &found, &best_dist);
+
+    printf(">> WP tree\nsearching for (%g, %g)\n"
+            "found (%g, %g) dist %g\nseen %d nodes\n\n",
+            testNode.x[0], testNode.x[1],
+            found->x[0], found->x[1], sqrt(best_dist), visited);
+
+    million =(struct kd_node_t*) 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(testNode);
+
+    visited = 0;
+    found = 0;
+    nearest(root, &testNode, 0, 3, &found, &best_dist);
+
+    printf(">> Million tree\nsearching for (%g, %g, %g)\n"
+            "found (%g, %g, %g) dist %g\nseen %d nodes\n",
+            testNode.x[0], testNode.x[1], testNode.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(testNode);
+        nearest(root, &testNode, 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-means++-clustering/D/k-means++-clustering.d b/Task/K-means++-clustering/D/k-means++-clustering.d
index fcb8757165..78d6c4ae10 100644
--- a/Task/K-means++-clustering/D/k-means++-clustering.d
+++ b/Task/K-means++-clustering/D/k-means++-clustering.d
@@ -2,7 +2,7 @@ import std.stdio, std.math, std.random, std.typecons, std.algorithm;
 
 // On Windows this uses the printf from the Microsoft C runtime,
 // that doesn't handle real type and some of the C99 format
-// specifiers, but it's faster for blunk printing.
+// specifiers, but it's faster for bulk printing.
 extern(C) nothrow int printf(const char*, ...);
 
 struct Point {
@@ -69,7 +69,7 @@ in {
         assert(result[0] < centers.length);
         immutable ClusterCenter c = centers[result[0]];
         immutable d = (c.x - point.x) ^^ 2  +  (c.y - point.y) ^^ 2;
-        assert(feqrel(cast()result[1], cast()d) > 45); // Arbitrary.
+        assert(feqrel(result[1], d) > 45); // Arbitrary.
     } body {
         static double sqrDistance2D(in ref ClusterCenter a,
                                     in ref Point b) pure nothrow @nogc{
diff --git a/Task/K-means++-clustering/Perl-6/k-means++-clustering.pl6 b/Task/K-means++-clustering/Perl-6/k-means++-clustering.pl6
index c2fa4143ff..e013b71da5 100644
--- a/Task/K-means++-clustering/Perl-6/k-means++-clustering.pl6
+++ b/Task/K-means++-clustering/Perl-6/k-means++-clustering.pl6
@@ -19,6 +19,6 @@ sub infix:«-means++»(Int $K, @data) {
 }
 
 my @centers = 0, 5, 3 + 2i;
-my @data = @centers.map: { ($_ + .5 - rand + (.5 - rand) * i) xx 100 }
+my @data = flat @centers.map: { ($_ + .5 - rand + (.5 - rand) * i) xx 100 }
 @data.=pick(*);
 .say for 3-means++ @data;
diff --git a/Task/Kaprekar-numbers/Elixir/kaprekar-numbers.elixir b/Task/Kaprekar-numbers/Elixir/kaprekar-numbers.elixir
new file mode 100644
index 0000000000..2582d7f2d7
--- /dev/null
+++ b/Task/Kaprekar-numbers/Elixir/kaprekar-numbers.elixir
@@ -0,0 +1,44 @@
+defmodule KaprekarNumber do
+  def check(n), do: check(n, 10)
+
+  def check(1,_base), do: {"1", ""}
+  def check(n, base) when rem(n*(n-1), (base-1)) != 0, do: false      # casting out nine
+  def check(n, base) do
+    square = Integer.to_string(n*n, base)
+    check(n, base, square, 1, String.length(square)-1)
+  end
+
+  defp check(_, _, _, _, 0), do: false
+  defp check(n, base, square, i, remainder) do
+    {a, b} = String.split_at(square, i)
+    if String.to_integer(b, base) == 0 do
+      false
+    else
+      sum = String.to_integer(a, base) + String.to_integer(b, base)
+      if n == sum, do: {a, b}, else: check(n, base, square, i+1, remainder-1)
+    end
+  end
+end
+
+Enum.each(1..9_999, fn n ->
+  if result = KaprekarNumber.check(n) do
+    {a, b} = result
+    :io.fwrite "~6w  ~8s  ~s + ~s~n", [n, a<>b, a, b]
+  end
+end)
+
+# Extra credit
+count = Enum.reduce(1..999_999, 0, fn n,acc ->
+  if KaprekarNumber.check(n), do: acc + 1, else: acc
+end)
+IO.puts "\n#{count} kaprekar numbers under 1,000,000"
+
+# Extra extra credit
+base = 17
+IO.puts "\nbase #{base} kaprekar numbers under 1,000,000(base10)"
+Enum.each(1..999_999, fn n ->
+  if result = KaprekarNumber.check(n, base) do
+    {a, b} = result
+    :io.fwrite "~7w  ~5s  ~9s  ~s + ~s~n", [n, Integer.to_string(n,base), a<>b, a, b]
+  end
+end)
diff --git a/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia b/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia
index 8327e545c9..564b4b409d 100644
--- a/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia
+++ b/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia
@@ -1,6 +1,6 @@
-function iskaprekar (n)
+function iskaprekar(n)
     str = string(n^2)
     n == 1 ? true :
-    any([ n == int(str[1:i]) + int(str[i+1:end]) && int(str[i+1:end]) != 0
+    any([ n == parse(Int,str[1:i]) + parse(Int,str[i+1:end]) && parse(Int,str[i+1:end]) != 0
           for i = 1:length(str)-1])
 end
diff --git a/Task/Kaprekar-numbers/REXX/kaprekar-numbers.rexx b/Task/Kaprekar-numbers/REXX/kaprekar-numbers.rexx
index 50f432f9e0..47f0775f8d 100644
--- a/Task/Kaprekar-numbers/REXX/kaprekar-numbers.rexx
+++ b/Task/Kaprekar-numbers/REXX/kaprekar-numbers.rexx
@@ -1,26 +1,27 @@
-/*REXX program generates  Kaprekar  numbers  using  cast-out-nines test.*/
-/*╔════════════════════════════════════════════════════════════════════╗
-  ║ generate (any maybe show)   Kaprekar   numbers  (and their count). ║
-  ║                                                                    ║
-  ║ Kaprekar numbers were thought of by the mathematician from India,  ║
-  ║ Shri Dattathreya Ramachardra Kaprekar  (1905─1986).                ║
-  ╚════════════════════════════════════════════════════════════════════╝*/
-call Kaprekar    10000                 /*gen Kaprekar #s and &    echo #*/
-call Kaprekar -1000000                 /*gen Kaprekar #s and & no echo #*/
-exit                                   /*stick a fork in it, we're done.*/
-/*──────────────────────────────────Kaprekar subroutine─────────────────*/
-Kaprekar: procedure;  arg limit;  #=0;  if abs(limit)>=1  then call tell 1
-numeric digits max(10,2*length(limit**2))    /*insure enough digs for ².*/
+/*REXX program generates  Kaprekar  numbers  using the  cast-out-nines  test. */
+       /*╔═══════════════════════════════════════════════════════════════════╗
+         ║ Kaprekar numbers were thought of by the mathematician from India, ║
+         ║ Shri Dattathreya Ramachardra Kaprekar  (1905─1986).               ║
+         ╚═══════════════════════════════════════════════════════════════════╝*/
+parse arg A B .                        /*get optional arguments from the C.L. */
+if A=='' | A=','  then A=    10000     /*Not specified?  Then use the default.*/
+if B=='' | B=','  then B= -1000000     /* "      "         "   "   "     "    */
+call Kaprekar  A                       /*gen Kaprekar #s, with/without an echo*/
+call Kaprekar  B                       /* "     "      "    "     "     "  "  */
+exit                                   /*stick a fork in it,  we're all done. */
+/*────────────────────────────────────────────────────────────────────────────*/
+Kaprekar: procedure; parse arg N;   #=0;     aN=abs(N);         call tell 1
+          numeric digits max(10,2*length(N**2)) /*insure enough dig for square*/
 
-    do j=2  to abs(limit)-1;     s=j*j
-    if j//9 \== s//9  then iterate     /*didn't pass cast-out-9s test ? */
-                                       /*cast-out-9s test is much faster*/
-          do k=1  for  length(s) % 2
-          if j==left(s,k)+substr(s,k+1) then call tell j      /*Eureka! */
-          end   /*k*/
-    end         /*j*/
+            do j=2  for aN-1;    s=j*j       /*calculate the square of  J.    */
+            if j//9\==s//9  then iterate     /*Flunked cast-out-9s test? Skip.*/
 
-say center("There're" # 'Kaprekar numbers below' abs(limit)".",79,'=');say
-return
-/*──────────────────────────────────TELL subroutine─────echo# if limit>0*/
-tell:  #=#+1;   if limit>0 then say right(arg(1), length(limit));   return
+                do k=1  for  length(s) % 2
+                if j==left(s,k)+substr(s,k+1)  then call tell j      /*Eureka!*/
+                end   /*k*/
+            end       /*j*/
+
+          say center("There're"   #   'Kaprekar numbers below'   An".", 79, '═')
+          return
+/*────────────────────────────────────────────────────────────────────────────*/
+tell:     #=#+1;      if N>0  then say right(arg(1), length(N));          return
diff --git a/Task/Kaprekar-numbers/Ruby/kaprekar-numbers.rb b/Task/Kaprekar-numbers/Ruby/kaprekar-numbers.rb
index 5a1c77804c..97bf4c8e7f 100644
--- a/Task/Kaprekar-numbers/Ruby/kaprekar-numbers.rb
+++ b/Task/Kaprekar-numbers/Ruby/kaprekar-numbers.rb
@@ -1,13 +1,13 @@
 def kaprekar(n, base = 10)
-  n = n.to_s
-  return [1, 1, 1, ""] if n == "1"
-  sqr = (n.to_i(base) ** 2).to_s(base)
-  0.upto(sqr.length - 1) do |i|
-    a = sqr[0 .. i]
-    b = sqr[i+1 .. -1]
+  return [1, 1, 1, ""] if n == 1
+  return if n*(n-1) % (base-1) != 0     # casting out nine
+  sqr = (n ** 2).to_s(base)
+  (1...sqr.length).each do |i|
+    a = sqr[0 ... i]
+    b = sqr[i .. -1]
     break if b.delete("0").empty?
-    sum = (a.to_i(base) + b.to_i(base)).to_s(base)
-    return [n, sqr, a, b] if sum == n
+    sum = a.to_i(base) + b.to_i(base)
+    return n.to_s(base), sqr, a, b if sum == n
   end
   nil
 end
@@ -26,7 +26,7 @@ def kaprekar(n, base = 10)
 puts "\nbase17 kaprekar numbers under (base10)1,000,000"
 base = 17
 1.upto(1_000_000) do |decimal|
-  if result = kaprekar(decimal.to_s(base), base)
-    puts "%7s  %5s  %9s  %s + %s\n" % [decimal, *result]
+  if result = kaprekar(decimal, base)
+    puts "%7s  %5s  %9s  %s + %s" % [decimal, *result]
   end
 end
diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/DCL/keyboard-input-flush-the-keyboard-buffer.dcl b/Task/Keyboard-input-Flush-the-keyboard-buffer/DCL/keyboard-input-flush-the-keyboard-buffer.dcl
new file mode 100644
index 0000000000..13c05fdb9a
--- /dev/null
+++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/DCL/keyboard-input-flush-the-keyboard-buffer.dcl
@@ -0,0 +1,7 @@
+$ wait 0::10  ! gives us 10 seconds to get keystrokes into the type-ahead buffer
+$ on control_y then $ goto clean
+$ set terminal /noecho
+$ loop: read /prompt="" /time=0 sys$command /error=clean buffer
+$ goto loop
+$ clean:
+$ set terminal /echo
diff --git a/Task/Keyboard-input-Keypress-check/Clojure/keyboard-input-keypress-check.clj b/Task/Keyboard-input-Keypress-check/Clojure/keyboard-input-keypress-check.clj
new file mode 100644
index 0000000000..2569e5e912
--- /dev/null
+++ b/Task/Keyboard-input-Keypress-check/Clojure/keyboard-input-keypress-check.clj
@@ -0,0 +1,16 @@
+(ns keypress.core
+  (:import jline.Terminal)
+  (:gen-class))
+
+(def keypress (future (.readCharacter (Terminal/getTerminal) System/in)))
+
+(defn prompt []
+  (println "Awaiting char...\n")
+  (Thread/sleep 2000)
+  (if-not (realized? keypress)
+    (recur)
+    (println "key: " (char @keypress))))
+
+(defn -main [& args]
+  (prompt)
+  (shutdown-agents))
diff --git a/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py b/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py
index 3d8253efb8..4d0d3bf425 100644
--- a/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py
+++ b/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py
@@ -1,5 +1,7 @@
 #!/usr/bin/env python
 
+# this solution will work only in Windows, as msvcrt is a Windows only package
+
 import thread
 import time
 
diff --git a/Task/Keyboard-input-Keypress-check/TI-83-BASIC/keyboard-input-keypress-check.ti-83 b/Task/Keyboard-input-Keypress-check/TI-83-BASIC/keyboard-input-keypress-check.ti-83
index d664cd217d..158a2a231b 100644
--- a/Task/Keyboard-input-Keypress-check/TI-83-BASIC/keyboard-input-keypress-check.ti-83
+++ b/Task/Keyboard-input-Keypress-check/TI-83-BASIC/keyboard-input-keypress-check.ti-83
@@ -1 +1 @@
-:getkey→G
+:getKey→G
diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Clojure/keyboard-input-obtain-a-y-or-n-response.clj b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Clojure/keyboard-input-obtain-a-y-or-n-response.clj
new file mode 100644
index 0000000000..37b9b07d48
--- /dev/null
+++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Clojure/keyboard-input-obtain-a-y-or-n-response.clj
@@ -0,0 +1,17 @@
+(ns yprompt.core
+  (:import jline.Terminal)
+  (:gen-class))
+
+(defn yes? [k]
+  (if (or (= k 89) (= k 121)) true false))
+
+(defn prompt []
+    (println "\nPrompt again [Y/N]?")
+    (let [term (Terminal/getTerminal)
+          ykey (yes? (.readCharacter term System/in))]
+      (if-not ykey
+        (recur)
+        (println "Yes!"))))
+
+(defn -main [& args]
+  (prompt))
diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response-1.js b/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response-1.js
new file mode 100644
index 0000000000..3546a2a96f
--- /dev/null
+++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response-1.js
@@ -0,0 +1,12 @@
+var keypress = require('keypress');
+
+keypress(process.stdin);
+
+process.stdin.on('keypress', function (ch, key) {
+    if (key && (key.name === 'y' || key.name === 'n')) {
+       console.log('Reply:' + key.name);
+    }
+});
+
+process.stdin.setRawMode(true);
+process.stdin.resume();
diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response-2.js b/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response-2.js
new file mode 100644
index 0000000000..617fce998c
--- /dev/null
+++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response-2.js
@@ -0,0 +1,6 @@
+document.body.addEventListener('keyup', function (e) {
+  var key = String.fromCharCode(e.keyCode).toLowerCase();
+  if (key === 'y' || key === 'n') {
+    console.log('response is: ' + key);
+  }
+}, false);
diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response.js b/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response.js
deleted file mode 100644
index 3801d331cf..0000000000
--- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/JavaScript/keyboard-input-obtain-a-y-or-n-response.js
+++ /dev/null
@@ -1,14 +0,0 @@
-var keypress = require('keypress');
-
-keypress(process.stdin);
-
-process.stdin.on('keypress', function (ch, key) {
-    if (key && (key.name === 'y' || key.name === 'n')) {
-       var reply = key.name === 'y';
-       console.log('Reply:', reply);
-       // ...do something with 'reply'...
-    }
-});
-
-process.stdin.setRawMode(true);
-process.stdin.resume();
diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Ruby/keyboard-input-obtain-a-y-or-n-response.rb b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Ruby/keyboard-input-obtain-a-y-or-n-response-1.rb
similarity index 100%
rename from Task/Keyboard-input-Obtain-a-Y-or-N-response/Ruby/keyboard-input-obtain-a-y-or-n-response.rb
rename to Task/Keyboard-input-Obtain-a-Y-or-N-response/Ruby/keyboard-input-obtain-a-y-or-n-response-1.rb
diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Ruby/keyboard-input-obtain-a-y-or-n-response-2.rb b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Ruby/keyboard-input-obtain-a-y-or-n-response-2.rb
new file mode 100644
index 0000000000..7620d20396
--- /dev/null
+++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Ruby/keyboard-input-obtain-a-y-or-n-response-2.rb
@@ -0,0 +1,9 @@
+require 'io/console'
+
+def yesno
+  case $stdin.getch
+    when "Y" then true
+    when "N" then false
+    else raise "Invalid character."
+  end
+end
diff --git a/Task/Keyboard-macros/Clojure/keyboard-macros.clj b/Task/Keyboard-macros/Clojure/keyboard-macros.clj
new file mode 100644
index 0000000000..b0eb163622
--- /dev/null
+++ b/Task/Keyboard-macros/Clojure/keyboard-macros.clj
@@ -0,0 +1,10 @@
+(ns hello-seesaw.core
+  (:use seesaw.core))
+
+(defn -main [& args]
+  (invoke-later
+    (-> (frame
+           :listen [:key-pressed (fn [e] (println (.getKeyChar e) " key pressed"))]
+           :on-close :exit)
+     pack!
+     show!)))
diff --git a/Task/Keyboard-macros/REXX/keyboard-macros.rexx b/Task/Keyboard-macros/REXX/keyboard-macros.rexx
index 1b478763a7..b35dd1b10f 100644
--- a/Task/Keyboard-macros/REXX/keyboard-macros.rexx
+++ b/Task/Keyboard-macros/REXX/keyboard-macros.rexx
@@ -1,49 +1,67 @@
-/**/trace o;parse arg !;if !all(arg()) then exit;if !cms then address '';signal on halt;signal on novalue;signal on syntax
-                                             /*if not DOS, issue error. */
-if \!dos then call er 23,', DOS[environment]'
-                                             /*if not PC/REXX, issue err*/
-if \!pcrexx then call er 23,', PC/REXX[interpretor]'
-                                             /*if Windows/NT, issue err.*/
-if !nt then call er 23,!fn 'Windows/95/98/2000 REXX-program'
-
-/* This program requires  ANSI.SYS  if any keys are set or (re-)defined.*/
-/* ANSI.SYS won't function correctly under Windows/NT (XP, Vista, 7, 8).*/
-call homedrive                               /*get the homedrive envvar.*/
-$home=p(!var('$HOME') homedrive)             /*get homedrive of \#\ dir.*/
-$home=appenda($home,':')                     /*make the drive ──► drive:*/
-$path=p(!var('$PATH') '\$')                  /*get path name of \#  dir.*/
-$path=prefixa($PATH,'\')                     /*make the path  ──► \dir  */
-$path=appenda($path,'\')                     /*make the path  ──► dir\  */
-if \hascol($path)  then $path=$home || $path /*prefix with  $HOME  ?    */
-@DOSKEY   ='DOSKEY'                          /*point to the DOSKEY   cmd*/
-@ECHO     ='ECHO'                            /*point to the ECHO     cmd*/
-@TYPE     ='TYPE'                            /*point to the TYPE     cmd*/
-deffid=#path'LOGS\'!fn".LOG"
-oldfid=#path'LOGS\'!fn".OLD"
-tops='.BOX= .C=blue .H=darkcyan .E=1'
-fops='.EF='deffid
-functionkey=0
-autoenter=
-useauto=0
-@offon='OFF ON ,'
-@warns='WARNIFOFF WARNIFON ,'
-sepline=copies('═',5)  copies('═',73)
-y=space(!!)
-
-  do forever                             /*process any options.*/
+♀/*REXX program can re-define most keys (including  F  keys)  on a PC keyboard.*/
+trace off
+parse arg !
+if !all(arg())  then exit
+if !cms  then address ''
+
+signal on halt
+signal on noValue
+signal on syntax
+
+                                                   /*if not DOS, issue error. */
+if \!dos     then call er 23,', DOS[environment]'
+
+                                                   /*if not PC/REXX, issue err*/
+if \!pcrexx  then call er 23,', PC/REXX[interpreter]'
+
+                                                   /*if Windows/NT, issue err.*/
+if !nt       then call er 23,!fn 'Windows/95/98/2000 REXX-program'
+
+      /* This program requires  ANSI.SYS  if any keys are set or (re─)defined.*/
+      /* ANSI.SYS won't function correctly under Windows/NT (XP, Vista, 7, 8).*/
+
+call homeDrive                                     /*get the homeDrive envVar.*/
+
+$home=p(!var('$HOME') homeDrive)                   /*get homeDrive of \$\ dir.*/
+$home=appenda($home,':')                           /*make the drive ──► drive:*/
+$path=p(!var('$PATH') '\$')                        /*get path name of \$  dir.*/
+$path=prefixa($PATH,'\')                           /*make the path  ──► \dir  */
+$path=appenda($path,'\')                           /*make the path  ──► dir\  */
+
+if \hasCol($path)  then $path=$home || $path       /*prefix with  $HOME  ?    */
+
+@DOSKEY    = 'DOSKEY'                              /*point to the DOSKEY   cmd*/
+@ECHO      = 'ECHO'                                /*point to the ECHO     cmd*/
+@TYPE      = 'TYPE'                                /*point to the TYPE     cmd*/
+defFid     = #path'LOGS\'!fn".LOG"
+oldFid     = #path'LOGS\'!fn".OLD"
+tops       = '.BOX= .C=blue .H=darkcyan .E=1'
+fops       = '.EF='defFid
+functionKey= 0
+autoEnter  =
+useAuto    = 0
+@offon     = 'OFF ON ,'
+@warns     = 'WARNIFOFF WARNIFON ,'
+sepLine    = copies('═',5)  copies('═',73)
+y          = space(!!)
+
+  do  forever                                      /*process any & all options*/
   parse var y k1 2 1 k y
-  uk=k;upper uk
+  uk=k; upper uk
+
   if uk=='[ENTER]'    then do
-                           useauto=1
-                           autoenter=13
+                           useAuto=1
+                           autoEnter=13
                            iterate
                            end
+
   if uk=='[NOENTER]'  then do
-                           useauto=1
-                           autoenter=
+                           useAuto=1
+                           autoEnter=
                            iterate
                            end
-  if k1\=='.'  then leave
+
+  if k1\=='.'         then leave
   tops=tops k
   fops=fops k
   end   /*forever*/
@@ -57,217 +75,242 @@ if k=='??'  |,
    k=="???" |,
    k=="????"  then do
                    !cls
-                   if y=='' then y=deffid
+                   if y==''      then y=defFid
                    @type y
-                   say sepline
-                   if k=="???" then call $defkey "ALLLOCKS , WARNIFON"
-                   if k=="????" then do
-                                     call $t ".P=1 .C=blue" centre('DOSKEY macros',79,"─")
-                                     @doskey '/macro'
-                                     call $t ".C=blue" copies('─',79)
-                                     end
+                   say sepLine
+                   if k=="???"   then call $defkey "ALLLOCKS , WARNIFON"
+
+                   if k=="????"  then do
+                                      call $t ".P=1 .C=blue" centre('DOSKEY macros',79,"─")
+                                      @doskey '/macro'
+                                      call $t ".C=blue" copies('─',79)
+                                      end
                    exit rc
                    end
 
 if k=='CLEARLOG' then do
-                      lfid=deffid
-                      if lfid==deffid then do
-                                           call dosdel oldfid
-                                           call dosrename deffid,oldfid
-                                           end
-                                      else call dosdel lfid
-                      call whenstamp lfid,'log file was cleared by' !fn"."
-                      _='ECHO' sepline">>"lfid
+                      lFID=defFid
+
+                      if lFID==defFid  then do
+                                            call dosdel oldFid
+                                            call dosrename defFid,oldFid
+                                            end
+                                       else call dosdel lFID
+
+                      call whenstamp lFID,'log file was cleared by' !fn"."
+                      _='ECHO' sepLine">>"lFID
                       _
-                      'ECHO  key         new value>>'lfid
+                      'ECHO  key         new value>>'lFID
                       _
                       exit
                       end
 
 shiftkeys='NUMLOCK CAPSLOCK SCROLLLOCK ALLLOCKS'
 
-if abbrev('BLINKLOCKKEYS',k,5) then
+if abbrev('BLINKLOCKKEYS',k,5)  then
      do
      parse var o . k times secs _
-     if _\=='' then call er 59
-     if k=='' | k=="," then k="ALLLOCKS"
-     if wordpos(k,shiftkeys)==0 then call er 50,'shiftlock-key' origk
-     if times=='' | times==',' then times="ANYKEY"
-     if times\=='ANYKEY' & \isint(times) then call er 53,times 'times'
-     if secs=='' | secs==',' then secs=.1
-     if \isnum(secs) then call er 53,times "seconds-delay-time"
+     if _\==''                            then call er 59
+     if k=='' | k==","                    then k="ALLLOCKS"
+     if wordpos(k,shiftkeys)==0           then call er 50,'shiftlock-key' origk
+     if times=='' | times==','            then times="ANYKEY"
+     if times\=='ANYKEY' & \isint(times)  then call er 53,times 'times'
+     if secs=='' | secs==','              then secs=.1
+     if \isNum(secs)                      then call er 53,times "seconds-delay-time"
      secs=secs/1
-     if secs<.1 | secs>99 then call er 81,.1 99 secs 'seconds-delay-time'
+     if secs<.1 | secs>99                 then call er 81,.1 99 secs 'seconds-delay-time'
      dids=0
 
        do forever
-         do j=1 for 3
-           do jo=2 to 1 by -1
+
+         do j=1  for 3
+
+           do jo=2  to 1  by -1
            dakey=word(shiftkeys,j)
            if k=='ALLLOCKS' | k==dakey then call "$DEFKEY" dakey word(@offon,jo)
-           if secs\==0 then call delay secs
-           end   /*j*/
-         end     /*forever*/
+           if secs\==0                 then call delay secs
+           end   /*jo*/
+
+         end     /*j*/
 
        dids=dids+1
-       if times\=='ANYKEY' & dids>=times then exit
-                                         else if inkey("NOWAIT")\=='' then exit
+       if times\=='ANYKEY' & dids>=times  then exit
+                                          else if inkey("NOWAIT")\=='' then exit
        end   /*forever*/
      end
 
-if wordpos(k,shiftkeys)\==0 then
+if wordpos(k,shiftkeys)\==0  then
      do
      _=words(y)
-     if _>2 then call er 59
+     if _>2  then call er 59
      onoff=
      warnif=0
      iswas='is'
-     if y==',' then y=
-     if y\=='' then do
-                    if _==2 then do
-                                 _=word(y,2)
-                                 warnif=wordpos(translate(_),@warns)
-                                 if warnif==0 then call er 55,_ k 'WARN'
-                                 if warnif==3 then warnif=0
-                                 y=subword(y,1,1)
-                                 end
-                    onoff=wordpos(translate(y),@offon)
-                    if onoff==0 then call er 50,'ON-or-OFF' y
-                    if onoff\==3 then iswas='was'
-                    end
-     if y==',' then y=
-       do j=1 for 3
+     if y==','  then y=
+
+     if y\==''  then do
+
+                     if _==2 then do
+                                  _=word(y,2)
+                                  warnif=wordpos(translate(_),@warns)
+                                  if warnif==0 then call er 55,_ k 'WARN'
+                                  if warnif==3 then warnif=0
+                                  y=subword(y,1,1)
+                                  end
+
+                     onoff=wordpos(translate(y),@offon)
+                     if onoff==0 then call er 50,'ON-or-OFF' y
+                     if onoff\==3 then iswas='was'
+                     end
+
+     if y==','  then y=
+
+       do j=1  for 3
        dakey=word(shiftkeys,j)
-       if warnif\==0 then if shiftstate(dakey)+1==warnif then call $t ".J=r" tops dakey iswas'('word(@offon,warnif)")"
-       if k=="ALLLOCKS" | k==dakey then
+       if warnif\==0  then if shiftstate(dakey)+1==warnif then call $t ".J=r" tops dakey iswas'('word(@offon,warnif)")"
+
+       if k=="ALLLOCKS" | k==dakey  then
           do
           if y\=='' &,
-             onoff\==3 then call shiftstate dakey,onoff-1
-                       else if warnif==0 then call $t ".I=25" tops dakey 'is ('word(@offon,shiftstate(dakey)+1)")"
+             onoff\==3  then call shiftstate dakey,onoff-1
+                        else if warnif==0 then call $t ".I=25" tops dakey 'is ('word(@offon,shiftstate(dakey)+1)")"
           end
+
        end   /*j*/
+
      exit
      end
 
-if y=='' then call er 54
+if y==''  then call er 54
 cod=
 codz='Z'
 
-if pos('-',k)\==0 then
-   do
-   parse var k cod '-' k
-   _='S SHIFT C CTRL CONTROL A ALT ALTERNATE'
-   if cod=='' | wordpos(cod,_)==0 then call er 50,"key" origk
-   cod=left(cod,1)
-   codl=lower(cod)
-   codz=cod
-   if k==''  then call er 50,"key" origk
-   end
-
-if abbrev('APOSTROPHE',k,5) then k="'"
-if k=='ASTERISKKEYPAD' | k=='STARKEYPAD' then k="*KEYPAD"
-if k=='BACKSLASH' then k="\"
-if k=='COMMA' then k=","
-if k=='DEL' then k="DELETE"
-if k=='DELKEYPAD' then k="DELETEKEYPAD"
-if k=='ENT' then k="ENTER"
-if k=='ENTKEYPAD' then k="ENTERKEYPAD"
-if k=='EQUAL' then k="="
-if k=='FIVEKEYPAD' then k="5KEYPAD"
-if k=="GRAVEACCENT" | k=='GRAVE' then k="`"
-if k=='INSKEYPAD' then k="INSKEYPAD"
-if k=='LEFTBRACKET' then k="["
-if k=='MINUS' then k="-"
-if k=='MINUSKEYPAD' then k="-KEYPAD"
-if k=="PAUSE" | k=='BREAK' then k="PAUSEBREAK"
-if k=='PGDN' then k="PAGEDOWN"
-if k=='PGDNKEYPAD' then k="PAGEDOWNKEYPAD"
-if k=='PGUP' then k="PAGEUP"
-if k=='PGUPKEYPAD' then k="PAGEUPKEYPAD"
-if k=='PLUSKEYPAD' then k="+KEYPAD"
-if k=='PRINTSCRN' then k="PRINTSCREEN"
-if k=='RIGHTBRACKET' then k="]"
-if k=='SEMICOLON' then k=";"
-if k=='SPACE' | k=="SPACEBAR" then k='BLANK'
-if wordpos(k,'PERIOD DOT DECIMAL DECIMALPOINT')\==0 then k="."
-if wordpos(k,'SLASH SOLIDUS VIRGULE OBELUS')\==0 then k="/"
-if wordpos(k,'SLASHKEYPAD SOLIDUSKEYPAD VIRGULEKEYPAD OBELUSKEYPAD')\==0 then k="/KEYPAD"
+if pos('-',k)\==0  then do
+                        parse var k cod '-' k
+                        _='S SHIFT C CTRL CONTROL A ALT ALTERNATE'
+                        if cod=='' | wordpos(cod,_)==0  then call er 50,"key" origk
+                        cod=left(cod,1)
+                        codl=lower(cod)
+                        codz=cod
+                        if k==''  then call er 50,"key" origk
+                        end
+
+if abbrev('APOSTROPHE',k,5)               then k = "'"
+if k=='ASTERISKKEYPAD' | k=='STARKEYPAD'  then k = "*KEYPAD"
+if k=='BACKSLASH'                         then k = "\"
+if k=='COMMA'                             then k = ","
+if k=='DEL'                               then k = "DELETE"
+if k=='DELKEYPAD'                         then k = "DELETEKEYPAD"
+if k=='ENT'                               then k = "ENTER"
+if k=='ENTKEYPAD'                         then k = "ENTERKEYPAD"
+if k=='EQUAL'                             then k = "="
+if k=='FIVEKEYPAD'                        then k = "5KEYPAD"
+if k=="GRAVEACCENT" | k=='GRAVE'          then k = "`"
+if k=='INSKEYPAD'                         then k = "INSKEYPAD"
+if k=='LEFTBRACKET'                       then k = "["
+if k=='MINUS'                             then k = "-"
+if k=='MINUSKEYPAD'                       then k = "-KEYPAD"
+if k=="PAUSE" | k=='BREAK'                then k = "PAUSEBREAK"
+if k=='PGDN'                              then k = "PAGEDOWN"
+if k=='PGDNKEYPAD'                        then k = "PAGEDOWNKEYPAD"
+if k=='PGUP'                              then k = "PAGEUP"
+if k=='PGUPKEYPAD'                        then k = "PAGEUPKEYPAD"
+if k=='PLUSKEYPAD'                        then k = "+KEYPAD"
+if k=='PRINTSCRN'                         then k = "PRINTSCREEN"
+if k=='RIGHTBRACKET'                      then k = "]"
+if k=='SEMICOLON'                         then k = ";"
+if k=='SPACE' | k=="SPACEBAR"             then k = 'BLANK'
+
+if wordpos(k,'PERIOD DOT DECIMAL DECIMALPOINT')\==0                       then k="."
+if wordpos(k,'SLASH SOLIDUS VIRGULE OBELUS')\==0                          then k="/"
+if wordpos(k,'SLASHKEYPAD SOLIDUSKEYPAD VIRGULEKEYPAD OBELUSKEYPAD')\==0  then k="/KEYPAD"
 base=
 
-  do 1
-  len1=length(k)==1
-  uppc=isupp(k)
+  do 1                     /*the "1" enables the use of the LEAVE instruction.*/
+  len1=(length(k)==1)
+  uppc=isUpp(k)
   numb=isint(k)
+
   if len1 then do
                dkey=c2d(k)
                if uppc then do
                             if cod=='A' then do
-                                            _='30 48 46 32 18 33 34 35 23 36 37 38 50 49 24 25 16 19 31 20 22 47 17 45 21 44'
-                                            base='0;'word(_,dkey-96)
-                                            end
+                                             _='30 48 46 32 18 33 34 35 23 36 37 38 50 49 24 25 16 19 31 20 22 47 17 45 21 44'
+                                             base='0;'word(_,dkey-96)
+                                             end
                             d.z=21
                             d.s=0
                             d.c=-64
                             base=d.codz+dkey
                             end
+
                if numb then do
                             dakey=dkey-47
-                            if cod='' then base=dkey
+                            if cod=''   then base=dkey
                             if cod=='S' then base=word("41 33 64 35 36 37 94 38 42 49",dakey)
+
                             if cod=='A' then if k<3 then base="0;"word(129 120,dakey)
-                                                   else base="0;"119+dakey
+                                                    else base="0;"119+dakey
+
                             if cod=='C' then do
-                                            if k==2 then base=0
-                                            if k==6 then base=30
-                                            end
+                                             if k==2 then base=0
+                                             if k==6 then base=30
+                                             end
                             end
-               if base\=='' then leave
+
+               if base\==''  then leave
                call er 50,'key' origk
                end
+
   ik=wordpos(k,'DELETE DOWNARROW END HOME INSERT LEFTARROW PAGEDOWN PAGEUP RIGHTARROW UPARROW')
 
     select
     when left(k,1)=='F' then do
-                        functionkey=1
+                        functionKey=1
                         fn=substr(k,2)
-                        if \isint(fn) | fn<1 | fn>12 then call er 81,1 12 k "FunctionKey"
+                        if \isint(fn) | fn<1 | fn>12  then call er 81,1 12 k "FunctionKey"
                         d.z=58
                         d.s=83
                         d.c=93
                         d.a=103
-                        if fn<11 then base='0;' || (d.codz+fn)
-                                 else do
-                                      d.z=133-11
-                                      d.s=135-11
-                                      d.c=137-11
-                                      d.a=139-11
-                                      base='0;' || (d.codz+fn)
-                                      end
+                        if fn<11  then base='0;' || (d.codz+fn)
+                                  else do
+                                       d.z=133-11
+                                       d.s=135-11
+                                       d.c=137-11
+                                       d.a=139-11
+                                       base='0;' || (d.codz+fn)
+                                       end
                         end
-    when ik\==0 then do
-                     d.z='83 80 79 71 82 75 81 73 77 72'
-                     d.s=d.z
-                     d.c='147 145 117 119 146 115 118 132 116 141'
-                     d.a='163 154 159 151 162 155 161 153 157 152'
-                     base='224;'word(d.codz,ik)
-                     end
-    when k=='PRINTSCREEN' & cod="C" then base='0;114'
-    when k=='PAUSEBREAK'  & cod="C" then base='0;0'
-    when k=='NULL'        & cod=='' then base="0;3"
-    when k=='BACKSPACE' then do
-                             d.z=8
-                             d.s=8
-                             d.c=127
-                             d.a=0
-                             base=d.codz
-                             end
-    when k=='TAB' then do
-                       d.z=9
-                       d.s='0;15'
-                       d.c='0;148'
-                       d.z='0;165'
-                       base=d.codz
-                       end
+
+    when ik\==0  then do
+                      d.z='83 80 79 71 82 75 81 73 77 72'
+                      d.s=d.z
+                      d.c='147 145 117 119 146 115 118 132 116 141'
+                      d.a='163 154 159 151 162 155 161 153 157 152'
+                      base='224;'word(d.codz,ik)
+                      end
+
+    when k=='PRINTSCREEN' & cod="C"  then base='0;114'
+    when k=='PAUSEBREAK'  & cod="C"  then base='0;0'
+    when k=='NULL'        & cod==''  then base="0;3"
+
+    when k=='BACKSPACE'  then do
+                              d.z=8
+                              d.s=8
+                              d.c=127
+                              d.a=0
+                              base=d.codz
+                              end
+
+    when k=='TAB'   then do
+                         d.z=9
+                         d.s='0;15'
+                         d.c='0;148'
+                         d.z='0;165'
+                         base=d.codz
+                         end
+
     when k=='BLANK' then do
                          d.z=92
                          d.s=124
@@ -275,6 +318,7 @@ base=
                          d.a='0;43'
                          base=d.codz
                          end
+
     when k=='ENTER' then do
                          d.z=13
                          d.s=
@@ -282,240 +326,274 @@ base=
                          d.a='0;28'
                          base=d.codz
                          end
-    when k=='-' then do
-                     d.z=45
-                     d.s=95
-                     d.c=31
-                     d.a='0;130'
-                     base=d.codz
-                     end
-    when k=='=' then do
-                     d.z=61
-                     d.s=43
-                     d.c=
-                     d.a='0;131'
-                     base=d.codz
-                     end
-    when k=='[' then do
-                     d.z=91
-                     d.s=123
-                     d.c=27
-                     d.a='0;26'
-                     base=d.codz
-                     end
-    when k==']' then do
-                     d.z=93
-                     d.s=125
-                     d.c=29
-                     d.a='0;27'
-                     base=d.codz
-                     end
-    when k=='\' then do
-                     d.z=92
-                     d.s=124
-                     d.c=28
-                     d.a='0;43'
-                     base=d.codz
-                     end
-    when k==';' then do
-                     d.z=59
-                     d.s=58
-                     d.c=
-                     d.a='0;39'
-                     base=d.codz
-                     end
-    when k=="'" then do
-                     d.z=39
-                     d.s=34
-                     d.c=
-                     d.a='0;40'
-                     base=d.codz
-                     end
-    when k==',' then do
-                     d.z=44
-                     d.s=60
-                     d.c=
-                     d.a='0;51'
-                     base=d.codz
-                     end
-    when k=='.' then do
-                     d.z=46
-                     d.s=62
-                     d.c=
-                     d.a='0;52'
-                     base=d.codz
-                     end
-    when k=='/' then do
-                     d.z=47
-                     d.s=63
-                     d.c=
-                     d.a='0;53'
-                     base=d.codz
-                     end
-    when k=='`' then do
-                     d.z=96
-                     d.s=126
-                     d.c=
-                     d.a='0;41'
-                     base=d.codz
-                     end
-    when k=='HOMEKEYPAD' then do
-                              d.z='0;71'
-                              d.s=55
-                              d.c='0;119'
-                              base=d.codz
-                              end
-    when k=='UPARROWKEYPAD' then do
-                                 d.z='0;72'
-                                 d.s=55
-                                 d.c='0;141'
+
+    when k=='-'  then do
+                      d.z=45
+                      d.s=95
+                      d.c=31
+                      d.a='0;130'
+                      base=d.codz
+                      end
+
+    when k=='='  then do
+                      d.z=61
+                      d.s=43
+                      d.c=
+                      d.a='0;131'
+                      base=d.codz
+                      end
+
+    when k=='['  then do
+                      d.z=91
+                      d.s=123
+                      d.c=27
+                      d.a='0;26'
+                      base=d.codz
+                      end
+
+    when k==']'  then do
+                      d.z=93
+                      d.s=125
+                      d.c=29
+                      d.a='0;27'
+                      base=d.codz
+                      end
+
+    when k=='\'  then do
+                      d.z=92
+                      d.s=124
+                      d.c=28
+                      d.a='0;43'
+                      base=d.codz
+                      end
+
+    when k==';'  then do
+                      d.z=59
+                      d.s=58
+                      d.c=
+                      d.a='0;39'
+                      base=d.codz
+                      end
+
+    when k=="'"  then do
+                      d.z=39
+                      d.s=34
+                      d.c=
+                      d.a='0;40'
+                      base=d.codz
+                      end
+
+    when k==','  then do
+                      d.z=44
+                      d.s=60
+                      d.c=
+                      d.a='0;51'
+                      base=d.codz
+                      end
+
+    when k=='.'  then do
+                      d.z=46
+                      d.s=62
+                      d.c=
+                      d.a='0;52'
+                      base=d.codz
+                      end
+
+    when k=='/'  then do
+                      d.z=47
+                      d.s=63
+                      d.c=
+                      d.a='0;53'
+                      base=d.codz
+                      end
+
+    when k=='`'  then do
+                      d.z=96
+                      d.s=126
+                      d.c=
+                      d.a='0;41'
+                      base=d.codz
+                      end
+
+    when k=='HOMEKEYPAD'  then do
+                               d.z='0;71'
+                               d.s=55
+                               d.c='0;119'
+                               base=d.codz
+                               end
+
+    when k=='UPARROWKEYPAD'  then do
+                                  d.z='0;72'
+                                  d.s=55
+                                  d.c='0;141'
+                                  base=d.codz
+                                  end
+
+    when k=='PAGEUPKEYPAD'  then do
+                                 d.z='0;73'
+                                 d.s=57
+                                 d.c='0;132'
                                  base=d.codz
                                  end
-    when k=='PAGEUPKEYPAD' then do
-                                d.z='0;73'
-                                d.s=57
-                                d.c='0;132'
-                                base=d.codz
-                                end
-    when k=='LEFTARROWKEYPAD' then do
-                              d.z='0;75'
-                              d.s=52
-                              d.c='0;115'
+
+    when k=='LEFTARROWKEYPAD'  then do
+                                    d.z='0;75'
+                                    d.s=52
+                                    d.c='0;115'
+                                    base=d.codz
+                                    end
+
+    when k=='5KEYPAD'  then do
+                            d.z='0;76'
+                            d.s=53
+                            d.c='0;143'
+                            base=d.codz
+                            end
+
+    when k=='RIGHTARROWKEYPAD'  then do
+                                     d.z='0;77'
+                                     d.s=54
+                                     d.c='0;116'
+                                     base=d.codz
+                                     end
+
+    when k=='ENDKEYPAD'  then do
+                              d.z='0;79'
+                              d.s=49
+                              d.c='0;117'
                               base=d.codz
                               end
-    when k=='5KEYPAD' then do
-                           d.z='0;76'
-                           d.s=53
-                           d.c='0;143'
-                           base=d.codz
-                           end
-    when k=='RIGHTARROWKEYPAD' then do
-                                    d.z='0;77'
-                                    d.s=54
-                                    d.c='0;116'
+
+    when k=='DOWNARROWKEYPAD'  then do
+                                    d.z='0;80'
+                                    d.s=50
+                                    d.c='0;145'
                                     base=d.codz
                                     end
-    when k=='ENDKEYPAD' then do
-                             d.z='0;79'
-                             d.s=49
-                             d.c='0;117'
-                             base=d.codz
-                             end
-    when k=='DOWNARROWKEYPAD' then do
-                                   d.z='0;80'
-                                   d.s=50
-                                   d.c='0;145'
+
+    when k=='PAGEDOWNKEYPAD'  then do
+                                   d.z='0;81'
+                                   d.s=51
+                                   d.c='0;118'
                                    base=d.codz
                                    end
-    when k=='PAGEDOWNKEYPAD' then do
-                                  d.z='0;81'
-                                  d.s=51
-                                  d.c='0;118'
-                                  base=d.codz
-                                  end
-    when k=='INSERTKEYPAD' then do
-                                d.z='0;82'
-                                d.s=48
-                                d.c='0;146'
-                                base=d.codz
-                                end
-    when k=='DELETEKEYPAD' then do
-                                d.z='0;83'
-                                d.s=46
-                                d.c='0;147'
+
+    when k=='INSERTKEYPAD'  then do
+                                 d.z='0;82'
+                                 d.s=48
+                                 d.c='0;146'
+                                 base=d.codz
+                                 end
+
+    when k=='DELETEKEYPAD'  then do
+                                 d.z='0;83'
+                                 d.s=46
+                                 d.c='0;147'
+                                 base=d.codz
+                                 end
+
+    when k=='ENTERKEYPAD'  then do
+                                d.z=13
+                                d.c=10
+                                d.a='0;166'
                                 base=d.codz
                                 end
-    when k=='ENTERKEYPAD' then do
-                               d.z=13
-                               d.c=10
-                               d.a='0;166'
-                               base=d.codz
-                               end
-    when k=='/KEYPAD' then do
-                           d.z=47
-                           d.s=d.z
-                           d.c='0;142'
-                           d.a='0;74'
-                           base=d.codz
-                           end
-    when k=='*KEYPAD' then do
-                           d.z=42
-                           d.s='o;144'
-                           d.c='0;78'
-                           base=d.codz
-                           end
-    when k=='-KEYPAD' then do
-                           d.z=45
-                           d.s=d.z
-                           d.c='0;149'
-                           d.a='0;164'
-                           base=d.codz
-                           end
-    when k=='+KEYPAD' then do
-                           d.z=43
-                           d.s=d.z
-                           d.c='0;150'
-                           d.a='0;55'
-                           base=d.codz
-                           end
-    otherwise nop
+
+    when k=='/KEYPAD'  then do
+                            d.z=47
+                            d.s=d.z
+                            d.c='0;142'
+                            d.a='0;74'
+                            base=d.codz
+                            end
+
+    when k=='*KEYPAD'  then do
+                            d.z=42
+                            d.s='o;144'
+                            d.c='0;78'
+                            base=d.codz
+                            end
+
+    when k=='-KEYPAD'  then do
+                            d.z=45
+                            d.s=d.z
+                            d.c='0;149'
+                            d.a='0;164'
+                            base=d.codz
+                            end
+
+    when k=='+KEYPAD'  then do
+                            d.z=43
+                            d.s=d.z
+                            d.c='0;150'
+                            d.a='0;55'
+                            base=d.codz
+                            end
+    otherwise  nop
     end   /*select*/
 
-  if base\=='' then leave; call er 50,'key' origk
+  if base\==''  then leave
+  call er 50,'key' origk
   end    /*do 1*/
 
 jy=words(y)
 yy=
 
-  do j=1 for jy
+  do j=1  for jy
   w=word(y,j)
   lw=length(w)
   lc=left(w,1)
-  rc2=right(w,2);upper rc2
-  if ((lc=='"' & rc2=='"X') | (lc=="'" & rc2=="'X")) & lw>3 then
+  rc2=right(w,2);  upper rc2
+
+  if ((lc=='"' & rc2=='"X') | (lc=="'" & rc2=="'X")) & lw>3  then
      do
-     if (lw-3)//2\==0 then call er 56,w 'hexdigits for the hexstring' w
-     wm=substr(w,2,lw-3);if \ishex(wm) then call er 40,w
+     if (lw-3)//2\==0  then call er 56,w 'hexdigits for the hexstring' w
+     wm=substr(w,2,lw-3)
+     if \isHex(wm)     then call er 40,w
      w=x2c(wm)
      end
+
   yy=yy w
   end   /*j*/
-                                /*if useauto=1, then use AUTOENTER as is*/
-                                /*if useauto=0 & funcKey, then use ENTER*/
-if \useauto & functionkey then autoenter=13
+                                     /*if useAuto=1, then use AUTOENTER as is.*/
+                                     /*if useAuto=0 & funcKey, then use ENTER.*/
+if \useAuto & functionKey  then autoEnter=13
 yy=substr(yy,2)
-!!='1b'x"["                     /* ESC[s  --->  save    cursor position.*/
-                                /* ESC[u  --->  restore cursor position.*/
-                                /* ESC[1A --->  move    cursor up 1 line*/
-@echo !!"s"!! || base';"'yy'";'autoenter'p'!!"u"!!'1A'   /*issue define.*/
+!!='1b'x"["                          /* ESC[s  ───►  save    cursor position. */
+                                     /* ESC[u  ───►  restore cursor position. */
+                                     /* ESC[1A ───►  move    cursor up 1 line.*/
+
+@echo !!"s"!! || base';"'yy'";'autoEnter'p'!!"u"!!'1A'     /*issue the define.*/
 nk=k
 if cod\==''  then nk=codl"-"k
+
 call $t '.Q=1' fops right(nk,max(length(nk),5)) "──►" yy
-exit
-
-/*═════════════════════════════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))
-$defkey:!call=']$DEFKEY';call "$DEFKEY" arg(1);!call=;return result
-$t:!call=']$T';call "$T" arg(1);!call=;return
-appenda:procedure;parse arg x,_;if right(x,length(_))\==_ then x=x||_;return x
-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
-halt:call er .1
-hascol:return pos(':',arg(1))\==0
-homedrive:if symbol('HOMEDRIVE')\=="VAR" then homedrive=p(!var('HOMEDRIVE') 'C:');return homedrive
-ishex:return datatype(arg(1),'X')
-isint:return datatype(arg(1),'W')
-isnum:return datatype(arg(1),'N')
-isupp:return datatype(arg(1),'U')
-it:"ARG"(1);if rc==0 then return;call er 68,rc arg(1)
-novalue:!sigl=sigl;call er 17,!fid(2) !fid(3) !sigl condition('D') sourceline(!sigl)
-p:return word(arg(1),1)
-prefixa:procedure;parse arg x,_;if left(x,length(_))\==_ then x=_||x;return x
-squish:return space(translate(arg(1),,word(arg(2) ',',1)),0)
-syntax:!sigl=sigl;call er 13,!fid(2) !fid(3) !sigl !cal() condition('D') sourceline(!sigl)
-whenstamp:arg whenfid;call lineout whenfid,strip(left(date('U'),6)left(date("S"),4) time() arg(2));call lineout whenfid,' ';call lineout whenfid;return
+exit                                   /*stick a fork in it,  we're all done. */
+
+/*═════════════════════════════one─liner subroutines══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/
+!all:  !!=!;!=space(!);upper !;call !FID;!nt=right(!var('OS'),2)=="NT";!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,"? ?SAMPLES ?AUTHOR ?FLOW")==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1
+!cal:  if symbol('!CALL')\=="VAR"  then !call=; return !call
+!env:  !env='ENVIRONMENT';  if !sys=='MSDOS' | !brexx | !r4 | !roo  then !env='SYSTEM';  if !os2  then !env='OS2'!env;  !ebcdic=1=='f0'x;   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))
+
+$defkey:   !call=']$DEFKEY';  call "$DEFKEY" arg(1);  !call=;     return result
+$t:        !call=']$T';       call "$T" arg(1);       !call=;     return result
+appenda:   procedure;  parse arg x,_;  if right(x,length(_))\==_  then x=x || _;            return x
+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
+halt:      call er .1
+hasCol:    return pos(':',arg(1))\==0
+homeDrive: if symbol('HOMEDRIVE')\=="VAR"  then homeDrive=p(!var('HOMEDRIVE') 'C:');   return homeDrive
+isHex:     return datatype(arg(1),'X')
+isint:     return datatype(arg(1),'W')
+isNum:     return datatype(arg(1),'N')
+isUpp:     return datatype(arg(1),'U')
+it:        "ARG"(1);if rc==0  then return;  call er 68,rc arg(1)
+noValue:   !sigl=sigl;  call er 17,!FID(2) !FID(3) !sigl condition('D') sourceline(!sigl)
+p:         return word(arg(1),1)
+prefixa:   procedure;  parse arg x,_;  if left(x,length(_))\==_  then x=_ || x;   return x
+squish:    return space(translate(arg(1),,word(arg(2) ',',1)),0)
+syntax:    !sigl=sigl;  call er 13,!FID(2) !FID(3) !sigl !cal() condition('D') sourceline(!sigl)
+whenstamp: arg whenFID;  call lineout whenFID,strip(left(date('U'),6)left(date("S"),4) time() arg(2));  call lineout whenFID,' ';  call lineout whenFID;   return
diff --git a/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-1.e b/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-1.e
new file mode 100644
index 0000000000..a7b0d1bdcc
--- /dev/null
+++ b/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-1.e
@@ -0,0 +1,40 @@
+class
+	APPLICATION
+
+create
+	make
+
+feature {NONE} -- Initialization
+
+	make
+		local
+			knapsack: KNAPSACKZEROONE
+		do
+			create knapsack.make (400)
+			knapsack.add_item (create {ITEM}.make ("", 0, 0))
+			knapsack.add_item (create {ITEM}.make ("map", 9, 150))
+			knapsack.add_item (create {ITEM}.make ("compass", 13, 35))
+			knapsack.add_item (create {ITEM}.make ("water", 153, 200))
+			knapsack.add_item (create {ITEM}.make ("sandwich", 50, 160))
+			knapsack.add_item (create {ITEM}.make ("glucose", 15, 60))
+			knapsack.add_item (create {ITEM}.make ("tin", 68, 45))
+			knapsack.add_item (create {ITEM}.make ("banana", 27, 60))
+			knapsack.add_item (create {ITEM}.make ("apple", 39, 40))
+			knapsack.add_item (create {ITEM}.make ("cheese", 23, 30))
+			knapsack.add_item (create {ITEM}.make ("beer", 52, 10))
+			knapsack.add_item (create {ITEM}.make ("suntan cream", 11, 70))
+			knapsack.add_item (create {ITEM}.make ("camera", 32, 30))
+			knapsack.add_item (create {ITEM}.make ("T-shirt", 24, 15))
+			knapsack.add_item (create {ITEM}.make ("trousers", 48, 10))
+			knapsack.add_item (create {ITEM}.make ("umbrella, ella ella", 73, 40))
+			knapsack.add_item (create {ITEM}.make ("waterproof trousers", 42, 70))
+			knapsack.add_item (create {ITEM}.make ("waterproof overclothes", 43, 75))
+			knapsack.add_item (create {ITEM}.make ("note-case", 22, 80))
+			knapsack.add_item (create {ITEM}.make ("sunglasses", 7, 20))
+			knapsack.add_item (create {ITEM}.make ("towel", 18, 12))
+			knapsack.add_item (create {ITEM}.make ("socks", 4, 50))
+			knapsack.add_item (create {ITEM}.make ("book", 30, 10))
+			knapsack.compute_solution
+		end
+
+end
diff --git a/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-2.e b/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-2.e
new file mode 100644
index 0000000000..3775fbf27c
--- /dev/null
+++ b/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-2.e
@@ -0,0 +1,35 @@
+class
+	ITEM
+
+create
+	make, make_from_other
+
+feature
+
+	name: STRING
+
+	weight: INTEGER
+
+	value: INTEGER
+
+	make_from_other (other: ITEM)
+			-- Item with name, weight and value set to 'other's name, weight and value.
+		do
+			name := other.name
+			weight := other.weight
+			value := other.value
+		end
+
+	make (a_name: String; a_weight, a_value: INTEGER)
+			-- Item with name, weight and value set to 'a_name', 'a_weight' and 'a_value'.
+		require
+			a_name /= Void
+			a_weight >= 0
+			a_value >= 0
+		do
+			name := a_name
+			weight := a_weight
+			value := a_value
+		end
+
+end
diff --git a/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-3.e b/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-3.e
new file mode 100644
index 0000000000..2fd25953c4
--- /dev/null
+++ b/Task/Knapsack-problem-0-1/Eiffel/knapsack-problem-0-1-3.e
@@ -0,0 +1,106 @@
+class
+	KNAPSACKZEROONE
+
+create
+	make
+
+feature
+
+	items: ARRAY [ITEM]
+
+	max_weight: INTEGER
+
+feature
+
+	make (a_max_weight: INTEGER)
+			-- Make an empty knapsack.
+		require
+			a_max_weight >= 0
+		do
+			create items.make_empty
+			max_weight := a_max_weight
+		end
+
+	add_item (item: ITEM)
+			-- Add 'item' to knapsack.
+		local
+			temp: ITEM
+		do
+			create temp.make_from_other (item)
+			items.force (item, items.count + 1)
+		end
+
+	compute_solution
+		local
+			M: ARRAY [INTEGER]
+			n: INTEGER
+			i, j: INTEGER
+			w_i, v_i: INTEGER
+			item_i: ITEM
+			final_items: LINKED_LIST [ITEM]
+		do
+			n := items.count
+			create M.make_filled (0, 1, n * max_weight)
+			from
+				i := 2
+			until
+				(i > n)
+			loop
+				from
+					j := 1
+				until
+					j > max_weight
+				loop
+					item_i := items [i]
+					w_i := item_i.weight
+					if w_i <= j then
+						v_i := item_i.value
+						M [(i - 1) * max_weight + j] := max (M [(i - 2) * max_weight + j], M [(i - 2) * max_weight + j - w_i + 1] + v_i)
+					else
+						M [(i - 1) * max_weight + j] := M [(i - 2) * max_weight + j]
+					end
+					j := j + 1
+				end
+				i := i + 1
+			end
+			io.put_string ("The final value of the knapsack will be: ")
+			io.put_integer (M [(n - 1) * max_weight + max_weight]);
+			io.new_line
+				--compute the items that fit into the knapsack
+			create final_items.make
+			io.put_string ("We'll take the following items: %N");
+			from
+				i := n
+				j := max_weight
+			until
+				i <= 1 or j <= 1
+			loop
+				item_i := items [i]
+				w_i := item_i.weight
+				if w_i <= j then
+					v_i := item_i.value
+					if M [(i - 1) * max_weight + j] = M [(i - 2) * max_weight + j] then
+					else
+						final_items.extend (item_i)
+						io.put_string (item_i.name)
+						io.new_line
+						j := j - w_i
+					end
+				else
+				end
+				i := i - 1
+			end
+		end
+
+feature {NONE}
+
+	max (a, b: INTEGER): INTEGER
+			-- Max of 'a' and 'b'.
+		do
+			Result := a
+			if a < b then
+				Result := b
+			end
+		end
+
+end
diff --git a/Task/Knapsack-problem-0-1/Forth/knapsack-problem-0-1.fth b/Task/Knapsack-problem-0-1/Forth/knapsack-problem-0-1.fth
new file mode 100644
index 0000000000..1e744c98d1
--- /dev/null
+++ b/Task/Knapsack-problem-0-1/Forth/knapsack-problem-0-1.fth
@@ -0,0 +1,70 @@
+\ Rosetta Code Knapp-sack 0-1 problem.  Tested under GForth 0.7.3.
+\ 22 items. On current processors a set fits nicely in one CELL (32 or 64 bits).
+\ Brute force approach: for every possible set of 22 items,
+\ check for admissible solution then for optimal set.
+
+: offs HERE over - ;
+        400 VALUE WLIMIT
+        0 VALUE ITEM
+        0 VALUE VAL
+        0 VALUE /ITEM
+        0 VALUE ITEMS#
+Create Sack
+HERE
+        9 ,                     offs TO VAL
+        150 ,                   offs TO ITEM
+        s" map            " s,  offs TO /ITEM
+DROP
+ 13 ,  35 , s" compass        " s,
+153 , 200 , s" water          " s,
+ 50 , 160 , s" sandwich       " s,
+ 15 ,  60 , s" glucose        " s,
+ 68 ,  45 , s" tin            " s,
+ 27 ,  60 , s" banana         " s,
+ 39 ,  40 , s" apple          " s,
+ 23 ,  30 , s" cheese         " s,
+ 52 ,  10 , s" beer           " s,
+ 11 ,  70 , s" suntan cream   " s,
+ 32 ,  30 , s" camera         " s,
+ 24 ,  15 , s" T-shirt        " s,
+ 48 ,  10 , s" trousers       " s,
+ 73 ,  40 , s" umbrella       " s,
+ 42 ,  70 , s" wp trousers    " s,
+ 43 ,  75 , s" wp overclothes " s,
+ 22 ,  80 , s" note-case      " s,
+  7 ,  20 , s" sunglasses     " s,
+ 18 ,  12 , s" towel          " s,
+  4 ,  50 , s" socks          " s,
+ 30 ,  10 , s" book           " s,
+        HERE VALUE END-SACK
+        VARIABLE Sol            \ Solution  Set
+        VARIABLE Vmax           \ Temporary Maximum Value
+        VARIABLE Sum            \ Temporary Sum (for speed-up)
+: ]sum          ( Rtime: set -- sum  ;Ctime: hilimit.a start.a -- )
+\ Loop unwinding & precomputing addresses
+        ]
+        ]] Sum OFF [[
+        DO              ]] dup [[  1  ]] LITERAL AND IF [[  I  ]] LITERAL @ Sum +! THEN 2/ [[
+        /ITEM +LOOP     ]] drop Sum @ [[
+; IMMEDIATE
+: solve         ( -- )
+        Vmax OFF
+        [ 1 END-SACK Sack - /ITEM / lshift 1- ]L 0
+        DO
+                I [ END-SACK Sack ]sum ( by weight ) WLIMIT <
+                IF
+                        I [ END-SACK VAL + Sack VAL + ]sum ( by value )
+                        dup Vmax @ >
+                        IF  Vmax ! I Sol !  ELSE  drop  THEN
+                THEN
+        LOOP
+;
+: .solution     ( -- )
+        Sol @ END-SACK ITEM + Sack ITEM +
+        DO
+                dup 1 AND  IF  I count type cr  THEN
+                2/
+        /ITEM +LOOP
+        drop
+        ." Weight: " Sol @ [ END-SACK Sack ]sum .  ."  Value: " Sol @ [ END-SACK VAL + Sack VAL + ]sum .
+;
diff --git a/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-1.julia b/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-1.julia
new file mode 100644
index 0000000000..aab7f00b1a
--- /dev/null
+++ b/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-1.julia
@@ -0,0 +1,20 @@
+using MathProgBase
+
+immutable KPDSupply{S<:String, T<:Integer}
+    item::S
+    weight::T
+    value::T
+    quant::T
+end
+function KPDSupply{S<:String, T<:Integer}(item::S, weight::T, value::T)
+    KPDSupply(item, weight, value, one(T))
+end
+
+function solve{S<:String, T<:Integer}(gear::Array{KPDSupply{S,T},1},
+                                      capacity::T)
+    w = map(x->x.weight, gear)
+    v = map(x->x.value, gear)
+    sol = mixintprog(-v, w', '<', capacity, :Bin, 0, 1)
+    sol.status == :Optimal || error("This Problem could not be solved")
+    gear[sol.sol .== 1.0]
+end
diff --git a/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-2.julia b/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-2.julia
new file mode 100644
index 0000000000..6cd7417793
--- /dev/null
+++ b/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-2.julia
@@ -0,0 +1,32 @@
+gear = [KPDSupply("map", 9, 150),
+        KPDSupply("compass", 13, 35),
+        KPDSupply("water", 153, 200),
+        KPDSupply("sandwich", 50, 160),
+        KPDSupply("glucose", 15, 60),
+        KPDSupply("tin", 68, 45),
+        KPDSupply("banana", 27, 60),
+        KPDSupply("apple", 39, 40),
+        KPDSupply("cheese", 23, 30),
+        KPDSupply("beer", 52, 10),
+        KPDSupply("suntan cream", 11, 70),
+        KPDSupply("camera", 32, 30),
+        KPDSupply("T-shirt", 24, 15),
+        KPDSupply("trousers", 48, 10),
+        KPDSupply("umbrella", 73, 40),
+        KPDSupply("waterproof trousers", 42, 70),
+        KPDSupply("waterproof overclothes", 43, 75),
+        KPDSupply("note-case", 22, 80),
+        KPDSupply("sunglasses", 7, 20),
+        KPDSupply("towel", 18, 12),
+        KPDSupply("socks", 4, 50),
+        KPDSupply("book", 30, 10)]
+
+pack = solve(gear, 400)
+
+println("The hiker should pack:")
+for s in pack
+    println("    ", s.item)
+end
+println()
+println("Packed Weight:  ", mapreduce(x->x.weight, +, pack))
+println("Packed Value:  ", mapreduce(x->x.value, +, pack))
diff --git a/Task/Knapsack-problem-0-1/PHP/knapsack-problem-0-1-1.php b/Task/Knapsack-problem-0-1/PHP/knapsack-problem-0-1-1.php
index 59093f7153..950e5df1f5 100644
--- a/Task/Knapsack-problem-0-1/PHP/knapsack-problem-0-1-1.php
+++ b/Task/Knapsack-problem-0-1/PHP/knapsack-problem-0-1-1.php
@@ -12,7 +12,7 @@
 #
 #########################################################
 
-function knapSolveFast2($w,$v,$i,$aW,&$m) {
+function knapSolveFast2($w, $v, $i, $aW, &$m, &$pickedItems) {
 
 	global $numcalls;
 	$numcalls ++;
@@ -92,6 +92,7 @@ function knapSolveFast2($w,$v,$i,$aW,&$m) {
 echo "Chosen Items:
"; echo ""; echo ""; +$totalVal = $totalWt = 0; foreach($pickedItems as $key) { $totalVal += $v4[$key]; $totalWt += $w4[$key]; diff --git a/Task/Knapsack-problem-0-1/Python/knapsack-problem-0-1-3.py b/Task/Knapsack-problem-0-1/Python/knapsack-problem-0-1-3.py new file mode 100644 index 0000000000..3662228e48 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Python/knapsack-problem-0-1-3.py @@ -0,0 +1,36 @@ +def total_value(items, max_weight): + return sum([x[2] for x in items]) if sum([x[1] for x in items]) < max_weight else 0 + +cache = {} +def solve(items, max_weight): + if not items: + return () + if (items,max_weight) not in cache: + head = items[0] + tail = items[1:] + include = (head,) + solve(tail, max_weight - head[1]) + dont_include = solve(tail, max_weight) + if total_value(include, max_weight) > total_value(dont_include, max_weight): + answer = include + else: + answer = dont_include + cache[(items,max_weight)] = answer + return cache[(items,max_weight)] + +items = ( + ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), + ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), + ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), + ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), + ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), + ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), + ("socks", 4, 50), ("book", 30, 10), + ) +max_weight = 400 + +solution = solve(items, max_weight) +print "items:" +for x in solution: + print x[0] +print "value:", total_value(solution, max_weight) +print "weight:", sum([x[1] for x in solution]) diff --git a/Task/Knapsack-problem-0-1/REXX/knapsack-problem-0-1.rexx b/Task/Knapsack-problem-0-1/REXX/knapsack-problem-0-1.rexx index 6134a87900..23d531f451 100644 --- a/Task/Knapsack-problem-0-1/REXX/knapsack-problem-0-1.rexx +++ b/Task/Knapsack-problem-0-1/REXX/knapsack-problem-0-1.rexx @@ -1,4 +1,4 @@ -/*REXX pgm solves a knapsack problem (22 items with weight restriction).*/ +/*REXX program solves a knapsack problem (22 items with a weight restriction).*/ @.=; @.1 = 'map 9 150' @.2 = 'compass 13 35' @.3 = 'water 153 200' @@ -22,7 +22,7 @@ @.21 = 'socks 4 50' @.22 = 'book 30 10' maxWeight=400 /*the maximum weight for knapsack*/ -say; say 'maximum weight allowed for a knapsack:' comma(maxWeight); say +say; say 'maximum weight allowed for a knapsack:' commas(maxWeight); say maxL=length('item') /*maximum width for table names. */ maxL=length('knapsack items') /*maximum width for table names. */ maxW=length('weight') /* " " " " weights*/ @@ -30,10 +30,10 @@ maxV=length('value') /* " " " " values.*/ maxQ=length('pieces') /* " " " " quant. */ highQ=0 /*max quantity specified (if any)*/ items=0; i.=; w.=0; v.=0; q.=0; Tw=0; Tv=0; Tq=0 /*initialize stuff.*/ -/*────────────────────────────────sort the choices by decreasing weight.*/ +/*════════════════════════════════sort the choices by decreasing weight.*/ /*this minimizes # combinations. */ do j=1 while @.j\=='' /*process each choice and sort. */ - _=@.j; _wt=word(_,2) /*choose first item (arbitrary). */ + _=space(@.j) _wt=word(_,2) /*choose first item (arbitrary). */ _wt=word(_,2) do k=j+1 while @.k\=='' /*find a possible heavier item. */ ?wt=word(@.k,2) @@ -41,10 +41,9 @@ items=0; i.=; w.=0; v.=0; q.=0; Tw=0; Tv=0; Tq=0 /*initialize stuff.*/ end /*k*/ end /*j*/ obj=j-1 /*adjust for the DO loop index. */ -/*────────────────────────────────build list of choices.────────────────*/ +/*════════════════════════════════build list of choices.════════════════*/ do j=1 for obj /*build a list of choices. */ - _=space(@.j) /*remove superfluous blanks. */ - parse var _ item w v q . /*parse original choice for table*/ + parse var @.j item w v q . /*parse original choice for table*/ if w>maxWeight then iterate /*if the weight > maximum, ignore*/ Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 /*add totals up (for alignment). */ maxL=max(maxL,length(item)) /*find maximum width for item. */ @@ -58,11 +57,11 @@ obj=j-1 /*adjust for the DO loop index. */ end /*k*/ end /*j*/ -maxW=max(maxW,length(comma(Tw))) /*find maximum width for weight. */ -maxV=max(maxV,length(comma(Tv))) /* " " " " value. */ -maxQ=max(maxQ,length(comma(Tq))) /* " " " " quantity*/ +maxW=max(maxW,length(commas(Tw))) /*find maximum width for weight. */ +maxV=max(maxV,length(commas(Tv))) /* " " " " value. */ +maxQ=max(maxQ,length(commas(Tq))) /* " " " " quantity*/ maxL=maxL+maxL%4+4 /*extend width of name for table.*/ -/*────────────────────────────────show the list of choices.─────────────*/ +/*════════════════════════════════show the list of choices.═════════════*/ call hdr 'item'; do j=1 for obj /*show all choices, nice format. */ parse var @.j item weight value q . if highq==1 then q= @@ -71,9 +70,9 @@ call hdr 'item'; do j=1 for obj /*show all choices, nice format. */ end /*j*/ say; say 'number of items:' items; say -/*─────────────────────────────────────examine all the possible choices.*/ +/*═════════════════════════════════════examine all the possible choices.*/ h=items; ho=h+1; m=maxWeight; $=0; call sim22 -/*─────────────────────────────────────show the best choice (weight,val)*/ +/*═════════════════════════════════════show the best choice (weight,val)*/ do h-1; ?=strip(strip(?),"L",0); end bestC=?; bestW=0; bestV=$; highQ=0; totP=words(bestC) call hdr 'best choice' @@ -87,36 +86,34 @@ call hdr 'best choice' call show i._,w._,v._,q; bestW=bestw+w._ end /*j*/ call hdr2; say -call show 'best weight' ,bestW /*show a nicely formatted winnerW*/ -call show 'best value' ,,bestV /*show a nicely formatted winnerV*/ -call show 'knapsack items',,,totP /*show a nicely formatted pieces.*/ -exit /*stick a fork in it, we're done.*/ -/*────────────────────────────────COMMA subroutine───────────────────────────────────────────────*/ -comma: procedure; parse arg _,c,p,t;arg ,cu;c=word(c ",",1);if cu=='BLANK' then c=' ';o=word(p 3,1) -k=0;p=abs(o);t=word(t 999999999,1);if \datatype(p,'W')|\datatype(t,'W')|p==0|arg()>4 then return _ -n=_'.9'; #=123456789; if o<0 then do; b=verify(_,' '); if b==0 then return _ -e=length(_)-verify(reverse(_),' ')+1; end; else do; b=verify(n,#,"M") -e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1;end;do j=e to b by -p while k$ then call j? 1 +sim22: + do j1 =0 for h+1; w1 = w.j1; v1 = v.j1; if v1>$ then call j? 1 do j2 =j1 +(j1 \==0) to h;if w.j2 +w1>m then iterate j1; w2 =w1 +w.j2; v2 =v1 +v.j2; if v2>$ then call j? 2 do j3 =j2 +(j2 \==0) to h;if w.j3 +w2>m then iterate j2; w3 =w2 +w.j3; v3 =v2 +v.j3; if v3>$ then call j? 3 do j4 =j3 +(j3 \==0) to h;if w.j4 +w3>m then iterate j3; w4 =w3 +w.j4; v4 =v3 +v.j4; if v4>$ then call j? 4 @@ -138,5 +135,5 @@ sim22: do j1=0 for h+1; w1=w.j1; v1 = do j20=j19+(j19\==0) to h;if w.j20+w19>m then iterate j19;w20=w19+w.j20;v20=v19+v.j20;if v20>$ then call j? 20 do j21=j20+(j20\==0) to h;if w.j21+w20>m then iterate j20;w21=w20+w.j21;v21=v20+v.j21;if v21>$ then call j? 21 do j22=j21+(j21\==0) to h;if w.j22+w21>m then iterate j21;w22=w21+w.j22;v22=v21+v.j22;if v22>$ then call j? 22 - end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end + end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end return diff --git a/Task/Knapsack-problem-0-1/Rust/knapsack-problem-0-1.rust b/Task/Knapsack-problem-0-1/Rust/knapsack-problem-0-1.rust index ae14360bf6..b635d6f6fa 100644 --- a/Task/Knapsack-problem-0-1/Rust/knapsack-problem-0-1.rust +++ b/Task/Knapsack-problem-0-1/Rust/knapsack-problem-0-1.rust @@ -1,18 +1,18 @@ -extern crate std; use std::cmp::max; use std::vec::Vec; // This struct is used to store our items that we want in our knap-sack. +#[derive(Clone)] struct Want<'a> { name: &'a str, - weight: uint, - value: uint + weight: usize, + value: usize } // Global, immutable allocation of our items. -static items : &'static [Want<'static>] = &[ +static ITEMS: &'static [Want<'static>] = &[ Want {name: "map", weight: 9, value: 150}, Want {name: "compass", weight: 13, value: 35}, Want {name: "water", weight: 153, value: 200}, @@ -41,16 +41,16 @@ static items : &'static [Want<'static>] = &[ // This is a bottom-up dynamic programming solution to the 0-1 knap-sack problem. // maximize value // subject to weights <= max_weight -fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: uint) -> Vec> { +fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: usize) -> Vec> { // Save this value, so we don't have to make repeated calls. let xs_len = xs.len(); // Imagine we wrote a recursive function(item, max_weight) that returns a - // uint corresponding to the maximum cumulative value by considering a + // usize corresponding to the maximum cumulative value by considering a // subset of items such that the combined weight <= max_weight. // - // fn best_value(item: uint, max_weight: uint) -> uint{ + // fn best_value(item: usize, max_weight: usize) -> usize{ // if item == 0 { // return 0; // } @@ -74,24 +74,24 @@ fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: uint) -> Vec> { // In a similar vein, the top-down solution would be to memoize the // function then compute the results on demand. - let zero_vec = Vec::from_elem(max_weight + 1, 0 as uint); - let mut best_value = Vec::from_elem(xs_len + 1, zero_vec); + let zero_vec = vec![0usize; max_weight + 1]; + let mut best_value = vec![zero_vec; xs_len + 1]; // loop over the items - for i in range(0, xs_len) { + for i in 0..xs_len { // loop over the weights - for w in range(1, max_weight + 1) { + for w in 1..max_weight + 1 { // do we have room in our knapsack? if xs[i].weight > w { // if we don't, then we'll say that the value doesn't change // when considering this item - *best_value.get_mut(i + 1).get_mut(w) = best_value.get(i).get(w).clone(); + best_value[i + 1][w] = best_value[i][w].clone(); } else { // if we do, then we have to see if the value we gain by adding // the item, given the weight, is better than not adding the item - *best_value.get_mut(i + 1).get_mut(w) = - max(best_value.get(i).get(w).clone(), - best_value.get(i).get(w - xs[i].weight) + xs[i].value); + best_value[i + 1][w] = + max(best_value[i][w].clone(), + best_value[i][w - xs[i].weight] + xs[i].value); } } } @@ -104,12 +104,12 @@ fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: uint) -> Vec> { // we built up the solution space through a forward pass over the data, // now we have to traverse backwards to get the solution - for i in range(1, xs_len+1).rev() { + for i in (1..xs_len+1).rev() { // We can check if an item should be added to the knap-sack by comparing // best_value with and without this item. If best_value added this // item then so should we. - if best_value.get(i).get(left_weight) != best_value.get(i - 1).get(left_weight) { - result.push(xs[i - 1]); + if best_value[i][left_weight] != best_value[i - 1][left_weight] { + result.push(xs[i - 1].clone()); // we remove the weight of the object from the remaining weight // we can add to the bag left_weight -= xs[i - 1].weight; @@ -121,7 +121,7 @@ fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: uint) -> Vec> { fn main () { - let xs = knap_01_dp(items, 400); + let xs = knap_01_dp(ITEMS, 400); // Print the items. We have to reverse the order because we solved the // problem backward. @@ -130,11 +130,11 @@ fn main () { } // Print the sum of weights. - let weights = xs.iter().fold(0, |a, &b| a + b.weight); + let weights = xs.iter().fold(0, |a, b| a + b.weight); println!("Total Weight: {}", weights); // Print the sum of the values. - let values = xs.iter().fold(0, |a, &b| a + b.value); + let values = xs.iter().fold(0, |a, b| a + b.value); println!("Total Value: {}", values); } diff --git a/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia new file mode 100644 index 0000000000..b5b958ebfa --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia @@ -0,0 +1,28 @@ +using MathProgBase + +immutable KPDSupply{S<:String, T<:Integer} + item::S + weight::T + value::T + quant::T +end + +function solve{S<:String, T<:Integer}(gear::Array{KPDSupply{S,T},1}, + capacity::T) + w = map(x->x.weight, gear) + v = map(x->x.value, gear) + q = map(x->x.quant, gear) + sol = mixintprog(-v, w', '<', capacity, :Int, 0, q) + sol.status == :Optimal || error("This Problem could not be solved") + if all(q .== 1) + return gear[sol.sol .== 1.0] + else + pack = KPDSupply[] + s = int(sol.sol) + for (i, g) in enumerate(gear) + s[i] != 0 || continue + push!(pack, KPDSupply(g.item, g.weight, g.value, s[i])) + end + return pack + end +end diff --git a/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia new file mode 100644 index 0000000000..aa27e44f30 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia @@ -0,0 +1,32 @@ +gear = [KPDSupply("map", 9, 150, 1), + KPDSupply("compass", 13, 35, 1), + KPDSupply("water", 153, 200, 2), + KPDSupply("sandwich", 50, 60, 2), + KPDSupply("glucose", 15, 60, 2), + KPDSupply("tin", 68, 45, 3), + KPDSupply("banana", 27, 60, 3), + KPDSupply("apple", 39, 40, 3), + KPDSupply("cheese", 23, 30, 1), + KPDSupply("beer", 52, 10, 3), + KPDSupply("suntan cream", 11, 70, 1), + KPDSupply("camera", 32, 30, 1), + KPDSupply("T-shirt", 24, 15, 2), + KPDSupply("trousers", 48, 10, 2), + KPDSupply("umbrella", 73, 40, 1), + KPDSupply("waterproof trousers", 42, 70, 1), + KPDSupply("waterproof overclothes", 43, 75, 1), + KPDSupply("note-case", 22, 80, 1), + KPDSupply("sunglasses", 7, 20, 1), + KPDSupply("towel", 18, 12, 2), + KPDSupply("socks", 4, 50, 1), + KPDSupply("book", 30, 10, 2)] + +pack = solve(gear, 400) + +println("The hiker should pack:") +for s in pack + println(" ", s.quant, " ", s.item) +end +println() +println("Packed Weight: ", mapreduce(x->x.weight*x.quant, +, pack)) +println("Packed Value: ", mapreduce(x->x.value*x.quant, +, pack)) diff --git a/Task/Knapsack-problem-Bounded/REXX/knapsack-problem-bounded.rexx b/Task/Knapsack-problem-Bounded/REXX/knapsack-problem-bounded.rexx index e76c0ef877..8c2c5b49ed 100644 --- a/Task/Knapsack-problem-Bounded/REXX/knapsack-problem-bounded.rexx +++ b/Task/Knapsack-problem-Bounded/REXX/knapsack-problem-bounded.rexx @@ -1,171 +1,167 @@ -/*REXX pgm solves a knapsack problem (22 items +repeats, wt. restriction*/ -call @gen /*generate items &initializations*/ -call @sort /*sort items by decreasing weight*/ -call bOBJ /*build a list of choices. */ -call showOBJ /*display the list of choices. */ -call sim37 /*examine the possible choices. */ -call showBest /*show best choice (weight,value)*/ -exit /*stick a fork in it, we're done.*/ -/*────────────────────────────────@GEN subroutine───────────────────────*/ -@gen: @. = - @.1 = 'map 9 150' - @.2 = 'compass 13 35' - @.3 = 'water 153 200 2' - @.4 = 'sandwich 50 60 2' - @.5 = 'glucose 15 60 2' - @.6 = 'tin 68 45 3' - @.7 = 'banana 27 60 3' - @.8 = 'apple 39 40 3' - @.9 = 'cheese 23 30' - @.10 = 'beer 52 10 3' - @.11 = 'suntan_cream 11 70' - @.12 = 'camera 32 30' - @.13 = 'T-shirt 24 15 2' - @.14 = 'trousers 48 10 2' - @.15 = 'umbrella 73 40' - @.16 = 'waterproof_trousers 42 70' - @.17 = 'waterproof_overclothes 43 75' - @.18 = 'note-case 22 80' - @.19 = 'sunglasses 7 20' - @.20 = 'towel 18 12 2' - @.21 = 'socks 4 50' - @.22 = 'book 30 10 2' -highQ=0 /*max quantity specified (if any)*/ -maxWeight=400 /*the maximum weight for knapsack*/ -maxL=length('item') /*maximum width for table names. */ -maxL=length('knapsack items') /*maximum width for table names. */ -maxW=length('weight') /* " " " " weights*/ -maxV=length('value') /* " " " " values.*/ -maxQ=length('pieces') /* " " " " quant. */ -items=0; i.=; w.=0; v.=0; q.=0 /*initialize some stuff & things.*/ -Tw=0; Tv=0; Tq=0; m=maxWeight /* " more " " " */ -say; say 'maximum weight allowed for a knapsack: ' comma(maxWeight); say +/*REXX pgm solves a knapsack problem (22 items + repeats, weight restriction. */ +call @gen /*generate items and initializations. */ +call @sort /*sort items by decreasing their weight*/ +call bOBJ /*build a list of choices (objects). */ +call showOBJ /*display the list of choices (objects)*/ +call sim37 /*examine and find the possible choices*/ +call showBest /*display best choice (weight, value).*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────@GEN subroutine─────────────────────────────*/ +@gen: @.=; @.1 = 'map 9 150' + @.2 = 'compass 13 35' + @.3 = 'water 153 200 2' + @.4 = 'sandwich 50 60 2' + @.5 = 'glucose 15 60 2' + @.6 = 'tin 68 45 3' + @.7 = 'banana 27 60 3' + @.8 = 'apple 39 40 3' + @.9 = 'cheese 23 30' + @.10 = 'beer 52 10 3' + @.11 = 'suntan_cream 11 70' + @.12 = 'camera 32 30' + @.13 = 'T-shirt 24 15 2' + @.14 = 'trousers 48 10 2' + @.15 = 'umbrella 73 40' + @.16 = 'waterproof_trousers 42 70' + @.17 = 'waterproof_overclothes 43 75' + @.18 = 'note-case 22 80' + @.19 = 'sunglasses 7 20' + @.20 = 'towel 18 12 2' + @.21 = 'socks 4 50' + @.22 = 'book 30 10 2' +highQ=0 /*maximum quantity specified (if any). */ +maxWeight=400 /*the maximum weight for the knapsack. */ +maxL=length('knapsack items') /* " " width for the table names*/ +maxW=length('weight') /* " " " " " weights. */ +maxV=length('value') /* " " " " " values. */ +maxQ=length('pieces') /* " " " " " quantity.*/ +items=0; i.=; w.=0; v.=0; q.=0 /*initialize some stuff and things. */ +Tw=0; Tv=0; Tq=0; m=maxWeight /* " more " " " */ +say; say 'maximum weight allowed for a knapsack: ' commas(maxWeight); say return -/*────────────────────────────────@SORT subroutine──────────────────────*/ -@sort: do j=1 while @.j\=='' /*process each choice and sort. */ - _=space(@.j); @.j=_ /*remove any superfluous blanks. */ - _wt=word(_, 2) /*choose first item (arbitrary). */ - do k=j+1 while @.k\=='' /*find a possible heavier item. */ +/*────────────────────────────────@SORT subroutine────────────────────────────*/ +@sort: do j=1 while @.j\=='' /*process each choice and sort the item*/ + _=space(@.j); @.j=_ /*remove any superfluous blanks. */ + _wt=word(_, 2) /*choose first item (arbitrary). */ + do k=j+1 while @.k\=='' /*find a possible heavier item. */ ?wt=word(@.k, 2) if ?wt>_wt then do; _=@.k; @.k=@.j; @.j=_; _wt=?wt; end end /*k*/ - end /*j*/ /* [↑] minimizes # combinations.*/ -obj=j-1 /*adjust for the DO loop index. */ + end /*j*/ /* [↑] minimizes the # of combinations*/ +obj=j-1 /*adjust for the DO loop index. */ return -/*────────────────────────────────BOBJ subroutine───────────────────────*/ -bOBJ: do j=1 for obj /*build a list of choices. */ - parse var @.j item w v q . /*parse original choice for table*/ - if w>maxWeight then iterate /*if the weight > maximum, ignore*/ - Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 /*add totals up (for alignment). */ - maxL=max(maxL, length(item)) /*find maximum width for item. */ +/*────────────────────────────────BOBJ subroutine─────────────────────────────*/ +bOBJ: do j=1 for obj /*build a list of choices (objects). */ + parse var @.j item w v q . /*parse the original choice for table. */ + if w>maxWeight then iterate /*Is the weight > maximum? Then ignore*/ + Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 /*add the totals up (for alignment). */ + maxL=max(maxL, length(item)) /*find the maximum width for an item. */ if q=='' then q=1 highQ=max(highQ, q) - items=items+1 /*bump the item counter. */ + items=items+1 /*bump the item counter. */ i.items=item; w.items=w; v.items=v; q.items=q - do k=2 to q; items=items+1 /*bump the item counter (pieces).*/ + do k=2 to q; items=items+1 /*bump the item counter (each piece). */ i.items=item; w.items=w; v.items=v; q.items=q Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 end /*k*/ end /*j*/ -maxW=max(maxW, length(comma(Tw))) /*find maximum width for weight. */ -maxV=max(maxV, length(comma(Tv))) /* " " " " value. */ -maxQ=max(maxQ, length(comma(Tq))) /* " " " " quantity*/ -maxL=maxL + maxL %4 + 4 /*extend width of name for table.*/ -return /* [↑] % is integer division.*/ -/*────────────────────────────────COMMA subroutine────────────────────────────────────────────────────────────*/ -comma: procedure; parse arg _,c,p,t; arg ,u; c=word(c ",",1); if u=='BLANK' then c=' '; o=word(p 3,1); p=abs(o) -t=word(t 999999999,1); if \datatype(p,'W')|\datatype(t,'W')|p==0|arg()>4 then return _; n=_'.9';#=123456789; k=0 -if o<0 then do; b=verify(_,' '); if b==0 then return _; e=length(_)-verify(reverse(_),' ')+1; end - else do; b=verify(n,#,"M"); e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end - do j=e to b by -p while k$ then call j? 1 -do j2 =j1 +(j1 \==0) to h; if w.j2 +w1 >m then iterate j1; w2=w1 +w.j2 ; v2=v1 +v.j2 ; if v2>$ then call j? 2 -do j3 =j2 +(j2 \==0) to h; if w.j3 +w2 >m then iterate j2; w3=w2 +w.j3 ; v3=v2 +v.j3 ; if v3>$ then call j? 3 -do j4 =j3 +(j3 \==0) to h; if w.j4 +w3 >m then iterate j3; w4=w3 +w.j4 ; v4=v3 +v.j4 ; if v4>$ then call j? 4 -do j5 =j4 +(j4 \==0) to h; if w.j5 +w4 >m then iterate j4; w5=w4 +w.j5 ; v5=v4 +v.j5 ; if v5>$ then call j? 5 -do j6 =j5 +(j5 \==0) to h; if w.j6 +w5 >m then iterate j5; w6=w5 +w.j6 ; v6=v5 +v.j6 ; if v6>$ then call j? 6 -do j7 =j6 +(j6 \==0) to h; if w.j7 +w6 >m then iterate j6; w7=w6 +w.j7 ; v7=v6 +v.j7 ; if v7>$ then call j? 7 -do j8 =j7 +(j7 \==0) to h; if w.j8 +w7 >m then iterate j7; w8=w7 +w.j8 ; v8=v7 +v.j8 ; if v8>$ then call j? 8 -do j9 =j8 +(j8 \==0) to h; if w.j9 +w8 >m then iterate j8; w9=w8 +w.j9 ; v9=v8 +v.j9 ; if v9>$ then call j? 9 -do j10=j9 +(j9 \==0) to h; if w.j10+w9 >m then iterate j9; w10=w9 +w.j10; v10=v9 +v.j10; if v10>$ then call j? 10 -do j11=j10+(j10\==0) to h; if w.j11+w10>m then iterate j10; w11=w10+w.j11; v11=v10+v.j11; if v11>$ then call j? 11 -do j12=j11+(j11\==0) to h; if w.j12+w11>m then iterate j11; w12=w11+w.j12; v12=v11+v.j12; if v12>$ then call j? 12 -do j13=j12+(j12\==0) to h; if w.j13+w12>m then iterate j12; w13=w12+w.j13; v13=v12+v.j13; if v13>$ then call j? 13 -do j14=j13+(j13\==0) to h; if w.j14+w13>m then iterate j13; w14=w13+w.j14; v14=v13+v.j14; if v14>$ then call j? 14 -do j15=j14+(j14\==0) to h; if w.j15+w14>m then iterate j14; w15=w14+w.j15; v15=v14+v.j15; if v15>$ then call j? 15 -do j16=j15+(j15\==0) to h; if w.j16+w15>m then iterate j15; w16=w15+w.j16; v16=v15+v.j16; if v16>$ then call j? 16 -do j17=j16+(j16\==0) to h; if w.j17+w16>m then iterate j16; w17=w16+w.j17; v17=v16+v.j17; if v17>$ then call j? 17 -do j18=j17+(j17\==0) to h; if w.j18+w17>m then iterate j17; w18=w17+w.j18; v18=v17+v.j18; if v18>$ then call j? 18 -do j19=j18+(j18\==0) to h; if w.j19+w18>m then iterate j18; w19=w18+w.j19; v19=v18+v.j19; if v19>$ then call j? 19 -do j20=j19+(j19\==0) to h; if w.j20+w19>m then iterate j19; w20=w19+w.j20; v20=v19+v.j20; if v20>$ then call j? 20 -do j21=j20+(j20\==0) to h; if w.j21+w20>m then iterate j20; w21=w20+w.j21; v21=v20+v.j21; if v21>$ then call j? 21 -do j22=j21+(j21\==0) to h; if w.j22+w21>m then iterate j21; w22=w21+w.j22; v22=v21+v.j22; if v22>$ then call j? 22 -do j23=j22+(j22\==0) to h; if w.j23+w22>m then iterate j22; w23=w22+w.j23; v23=v22+v.j23; if v23>$ then call j? 23 -do j24=j23+(j23\==0) to h; if w.j24+w23>m then iterate j23; w24=w23+w.j24; v24=v23+v.j24; if v24>$ then call j? 24 -do j25=j24+(j24\==0) to h; if w.j25+w24>m then iterate j24; w25=w24+w.j25; v25=v24+v.j25; if v25>$ then call j? 25 -do j26=j25+(j25\==0) to h; if w.j26+w25>m then iterate j25; w26=w25+w.j26; v26=v25+v.j26; if v26>$ then call j? 26 -do j27=j26+(j26\==0) to h; if w.j27+w26>m then iterate j26; w27=w26+w.j27; v27=v26+v.j27; if v27>$ then call j? 27 -do j28=j27+(j27\==0) to h; if w.j28+w27>m then iterate j27; w28=w27+w.j28; v28=v27+v.j28; if v28>$ then call j? 28 -do j29=j28+(j28\==0) to h; if w.j29+w28>m then iterate j28; w29=w28+w.j29; v29=v28+v.j29; if v29>$ then call j? 29 -do j30=j29+(j29\==0) to h; if w.j30+w29>m then iterate j29; w30=w29+w.j30; v30=v29+v.j30; if v30>$ then call j? 30 -do j31=j30+(j30\==0) to h; if w.j31+w30>m then iterate j30; w31=w30+w.j31; v31=v30+v.j31; if v31>$ then call j? 31 -do j32=j31+(j31\==0) to h; if w.j32+w31>m then iterate j31; w32=w31+w.j32; v32=v31+v.j32; if v32>$ then call j? 32 -do j33=j32+(j32\==0) to h; if w.j33+w32>m then iterate j32; w33=w32+w.j33; v33=v32+v.j33; if v33>$ then call j? 33 -do j34=j33+(j33\==0) to h; if w.j34+w33>m then iterate j33; w34=w33+w.j34; v34=v33+v.j34; if v34>$ then call j? 34 -do j35=j34+(j34\==0) to h; if w.j35+w34>m then iterate j34; w35=w34+w.j35; v35=v34+v.j35; if v35>$ then call j? 35 -do j36=j35+(j35\==0) to h; if w.j36+w35>m then iterate j35; w36=w35+w.j36; v36=v35+v.j36; if v36>$ then call j? 36 -do j37=j36+(j36\==0) to h; if w.j37+w36>m then iterate j36; w37=w36+w.j37; v37=v36+v.j37; if v37>$ then call j? 37 + do j1 =0 for h+1; w1= w.j1 ; v1= v.j1 ; if v1>$ then call j? 1 + do j2 =j1 +(j1 \==0) to h; if w.j2 +w1 >m then iterate j1; w2=w1 +w.j2 ; v2=v1 +v.j2 ; if v2>$ then call j? 2 + do j3 =j2 +(j2 \==0) to h; if w.j3 +w2 >m then iterate j2; w3=w2 +w.j3 ; v3=v2 +v.j3 ; if v3>$ then call j? 3 + do j4 =j3 +(j3 \==0) to h; if w.j4 +w3 >m then iterate j3; w4=w3 +w.j4 ; v4=v3 +v.j4 ; if v4>$ then call j? 4 + do j5 =j4 +(j4 \==0) to h; if w.j5 +w4 >m then iterate j4; w5=w4 +w.j5 ; v5=v4 +v.j5 ; if v5>$ then call j? 5 + do j6 =j5 +(j5 \==0) to h; if w.j6 +w5 >m then iterate j5; w6=w5 +w.j6 ; v6=v5 +v.j6 ; if v6>$ then call j? 6 + do j7 =j6 +(j6 \==0) to h; if w.j7 +w6 >m then iterate j6; w7=w6 +w.j7 ; v7=v6 +v.j7 ; if v7>$ then call j? 7 + do j8 =j7 +(j7 \==0) to h; if w.j8 +w7 >m then iterate j7; w8=w7 +w.j8 ; v8=v7 +v.j8 ; if v8>$ then call j? 8 + do j9 =j8 +(j8 \==0) to h; if w.j9 +w8 >m then iterate j8; w9=w8 +w.j9 ; v9=v8 +v.j9 ; if v9>$ then call j? 9 + do j10=j9 +(j9 \==0) to h; if w.j10+w9 >m then iterate j9; w10=w9 +w.j10; v10=v9 +v.j10; if v10>$ then call j? 10 + do j11=j10+(j10\==0) to h; if w.j11+w10>m then iterate j10; w11=w10+w.j11; v11=v10+v.j11; if v11>$ then call j? 11 + do j12=j11+(j11\==0) to h; if w.j12+w11>m then iterate j11; w12=w11+w.j12; v12=v11+v.j12; if v12>$ then call j? 12 + do j13=j12+(j12\==0) to h; if w.j13+w12>m then iterate j12; w13=w12+w.j13; v13=v12+v.j13; if v13>$ then call j? 13 + do j14=j13+(j13\==0) to h; if w.j14+w13>m then iterate j13; w14=w13+w.j14; v14=v13+v.j14; if v14>$ then call j? 14 + do j15=j14+(j14\==0) to h; if w.j15+w14>m then iterate j14; w15=w14+w.j15; v15=v14+v.j15; if v15>$ then call j? 15 + do j16=j15+(j15\==0) to h; if w.j16+w15>m then iterate j15; w16=w15+w.j16; v16=v15+v.j16; if v16>$ then call j? 16 + do j17=j16+(j16\==0) to h; if w.j17+w16>m then iterate j16; w17=w16+w.j17; v17=v16+v.j17; if v17>$ then call j? 17 + do j18=j17+(j17\==0) to h; if w.j18+w17>m then iterate j17; w18=w17+w.j18; v18=v17+v.j18; if v18>$ then call j? 18 + do j19=j18+(j18\==0) to h; if w.j19+w18>m then iterate j18; w19=w18+w.j19; v19=v18+v.j19; if v19>$ then call j? 19 + do j20=j19+(j19\==0) to h; if w.j20+w19>m then iterate j19; w20=w19+w.j20; v20=v19+v.j20; if v20>$ then call j? 20 + do j21=j20+(j20\==0) to h; if w.j21+w20>m then iterate j20; w21=w20+w.j21; v21=v20+v.j21; if v21>$ then call j? 21 + do j22=j21+(j21\==0) to h; if w.j22+w21>m then iterate j21; w22=w21+w.j22; v22=v21+v.j22; if v22>$ then call j? 22 + do j23=j22+(j22\==0) to h; if w.j23+w22>m then iterate j22; w23=w22+w.j23; v23=v22+v.j23; if v23>$ then call j? 23 + do j24=j23+(j23\==0) to h; if w.j24+w23>m then iterate j23; w24=w23+w.j24; v24=v23+v.j24; if v24>$ then call j? 24 + do j25=j24+(j24\==0) to h; if w.j25+w24>m then iterate j24; w25=w24+w.j25; v25=v24+v.j25; if v25>$ then call j? 25 + do j26=j25+(j25\==0) to h; if w.j26+w25>m then iterate j25; w26=w25+w.j26; v26=v25+v.j26; if v26>$ then call j? 26 + do j27=j26+(j26\==0) to h; if w.j27+w26>m then iterate j26; w27=w26+w.j27; v27=v26+v.j27; if v27>$ then call j? 27 + do j28=j27+(j27\==0) to h; if w.j28+w27>m then iterate j27; w28=w27+w.j28; v28=v27+v.j28; if v28>$ then call j? 28 + do j29=j28+(j28\==0) to h; if w.j29+w28>m then iterate j28; w29=w28+w.j29; v29=v28+v.j29; if v29>$ then call j? 29 + do j30=j29+(j29\==0) to h; if w.j30+w29>m then iterate j29; w30=w29+w.j30; v30=v29+v.j30; if v30>$ then call j? 30 + do j31=j30+(j30\==0) to h; if w.j31+w30>m then iterate j30; w31=w30+w.j31; v31=v30+v.j31; if v31>$ then call j? 31 + do j32=j31+(j31\==0) to h; if w.j32+w31>m then iterate j31; w32=w31+w.j32; v32=v31+v.j32; if v32>$ then call j? 32 + do j33=j32+(j32\==0) to h; if w.j33+w32>m then iterate j32; w33=w32+w.j33; v33=v32+v.j33; if v33>$ then call j? 33 + do j34=j33+(j33\==0) to h; if w.j34+w33>m then iterate j33; w34=w33+w.j34; v34=v33+v.j34; if v34>$ then call j? 34 + do j35=j34+(j34\==0) to h; if w.j35+w34>m then iterate j34; w35=w34+w.j35; v35=v34+v.j35; if v35>$ then call j? 35 + do j36=j35+(j35\==0) to h; if w.j36+w35>m then iterate j35; w36=w35+w.j36; v36=v35+v.j36; if v36>$ then call j? 36 + do j37=j36+(j36\==0) to h; if w.j37+w36>m then iterate j36; w37=w36+w.j37; v37=v36+v.j37; if v37>$ then call j? 37 end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end -return +return /* [↑] there is one END for each of the DO loops. */ diff --git a/Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous.clj b/Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous-1.clj similarity index 100% rename from Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous.clj rename to Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous-1.clj diff --git a/Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous-2.clj b/Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous-2.clj new file mode 100644 index 0000000000..7365409651 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous-2.clj @@ -0,0 +1,24 @@ +(def items + [{:name "beef" :weight 3.8 :price 36} + {:name "pork" :weight 5.4 :price 43} + {:name "ham" :weight 3.6 :price 90} + {:name "graves" :weight 2.4 :price 45} + {:name "flitch" :weight 4.0 :price 30} + {:name "brawn" :weight 2.5 :price 56} + {:name "welt" :weight 3.7 :price 67} + {:name "salami" :weight 3.0 :price 95} + {:name "sausage" :weight 5.9 :price 98}]) + +(defn per-kg [item] (/ (:price item) (:weight item))) + +(defn rob [items capacity] + (let [best-items (reverse (sort-by per-kg items))] + (loop [items best-items cap capacity total 0] + (let [item (first items)] + (if (< (:weight item) cap) + (do (println (str "Take all " (:name item))) + (recur (rest items) (- cap (:weight item)) (+ total (:price item)))) + (println (format "Take %.1f kg of %s\nTotal: %.2f monies" + cap (:name item) (+ total (* cap (per-kg item)))))))))) + +(rob items 15) diff --git a/Task/Knapsack-problem-Continuous/Eiffel/knapsack-problem-continuous.e b/Task/Knapsack-problem-Continuous/Eiffel/knapsack-problem-continuous.e new file mode 100644 index 0000000000..59631fdab0 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Eiffel/knapsack-problem-continuous.e @@ -0,0 +1,71 @@ +class + CONTINUOUS_KNAPSACK + +create + make + +feature + + make + local + tup: TUPLE [name: STRING; weight: REAL_64; price: REAL_64] + do + create tup + create items.make_filled (tup, 1, 9) + create sorted.make + sorted.extend (-36.0 / 3.8) + sorted.extend (-43.0 / 5.4) + sorted.extend (-90.0 / 3.6) + sorted.extend (-45.0 / 2.4) + sorted.extend (-30.0 / 4.0) + sorted.extend (-56.0 / 2.5) + sorted.extend (-67.0 / 3.7) + sorted.extend (-95.0 / 3.0) + sorted.extend (-98.0 / 5.9) + tup := ["beef", 3.8, 36.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["pork", 5.4, 43.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["ham", 3.6, 90.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["greaves", 2.4, 45.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["flitch", 4.0, 30.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["brawn", 2.5, 56.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["welt", 3.7, 67.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["salami", 3.0, 95.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + tup := ["sausage", 5.9, 98.0] + items [sorted.index_of (- tup.price / tup.weight, 1)] := tup + find_solution + end + + find_solution + -- Solution for the continuous Knapsack Problem. + local + maxW, value: REAL_64 + do + maxW := 15 + across + items as c + loop + if maxW - c.item.weight > 0 then + io.put_string ("Take all: " + c.item.name + ".%N") + value := value + c.item.price + maxW := maxW - c.item.weight + elseif maxW /= 0 then + io.put_string ("Take " + maxW.truncated_to_real.out + " kg off " + c.item.name + ".%N") + io.put_string ("The total value is " + (value + (c.item.price / c.item.weight) * maxW).truncated_to_real.out + ".") + maxW := 0 + end + end + end + + items: ARRAY [TUPLE [name: STRING; weight: REAL_64; price: REAL_64]] + + sorted: SORTED_TWO_WAY_LIST [REAL_64] + +end diff --git a/Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous.elixir b/Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous.elixir new file mode 100644 index 0000000000..ddbe8e50f0 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Elixir/knapsack-problem-continuous.elixir @@ -0,0 +1,34 @@ +defmodule KnapsackProblem do + def price_per_weight( items ), do: (for {name, weight, price} <-items, do: {name, weight, price / weight} ) + + def select( max_weight, items ) do + {_remains, selected_items} = List.foldr( List.keysort(items, 2), {max_weight, []}, &select_until/2 ) + selected_items + end + + def task( max_weight, items ) do + IO.puts "The robber takes the following to maximize the value" + for {name, weight} <- select( max_weight, price_per_weight(items) ), do: :io.fwrite("~.2f of ~s~n", [weight, name]) + end + + defp select_until( {name, weight, _price}, {remains, acc} ) when remains > 0 do + selected_weight = select_until_weight( weight, remains ) + {remains - selected_weight, [{name, selected_weight} | acc]} + end + defp select_until( _item, acc ), do: acc + + defp select_until_weight( weight, remains ) when weight < remains, do: weight + defp select_until_weight( _weight, remains ), do: remains +end + +items = [ {"beef", 3.8, 36}, + {"pork", 5.4, 43}, + {"ham", 3.6, 90}, + {"greaves", 2.4, 45}, + {"flitch", 4.0, 30}, + {"brawn", 2.5, 56}, + {"welt", 3.7, 67}, + {"salami", 3.0, 95}, + {"sausage", 5.9, 98} ] + +KnapsackProblem.task( 15, items ) diff --git a/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia b/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia new file mode 100644 index 0000000000..a8e54ef276 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia @@ -0,0 +1,29 @@ +immutable KPCSupply{S<:String, T<:Real} + item::S + weight::T + value::T + uvalue::T +end +Base.isless(a::KPCSupply, b::KPCSupply) = a.uvaluex.weight, +, sack) +v = mapreduce(x->x.value, +, sack) +println(@sprintf("%12s %4.1f %6.2f", + "Total", float(w), float(v))) diff --git a/Task/Knapsack-problem-Continuous/Perl-6/knapsack-problem-continuous.pl6 b/Task/Knapsack-problem-Continuous/Perl-6/knapsack-problem-continuous.pl6 index 9105706a4a..8eb0314057 100644 --- a/Task/Knapsack-problem-Continuous/Perl-6/knapsack-problem-continuous.pl6 +++ b/Task/Knapsack-problem-Continuous/Perl-6/knapsack-problem-continuous.pl6 @@ -15,10 +15,10 @@ class KnapsackItem { return True; } - method Str () { sprintf "%8s %1.2f %3.2f", - $.name, - $.weight, - $.price } + method gist () { sprintf "%8s %1.2f %3.2f", + $.name, + $.weight, + $.price } } my $max-w = 15; @@ -34,7 +34,7 @@ say "Item Portion Value"; welt 3.7 67 salami 3.0 95 sausage 5.9 98 > - ==> map { KnapsackItem.new($^a, $^b, $^c) } + ==> map({ KnapsackItem.new($^a, $^b, $^c) }) ==> sort *.ppw { my $last-one = .cut-maybe($max-w); diff --git a/Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-1.rexx b/Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-1.rexx index 82ed4bba81..fec34bdb58 100644 --- a/Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-1.rexx +++ b/Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-1.rexx @@ -1,47 +1,45 @@ -/*REXX program solves the (continuous) burglar's knapsack problem. */ -@.= /*═══════ name weight value ══════*/ - @.1 = 'flitch 4 30 ' - @.2 = 'beef 3.8 36 ' - @.3 = 'pork 5.4 43 ' - @.4 = 'greaves 2.4 45 ' - @.5 = 'brawn 2.5 56 ' - @.6 = 'welt 3.7 67 ' - @.7 = 'ham 3.6 90 ' - @.8 = 'salami 3 95 ' - @.9 = 'sausage 5.9 98 ' -parse arg maxW d . /*get possible args from the C.L.*/ -if maxW=='' | maxW==',' then maxW=15 /*burglar's knapsack max weight. */ -if d=='' | d==',' then d= 3 /*# of decimal digits in FORMAT. */ -wL=d+length('weight'); nL=d+length('total weight'); vL=d+length('value') +/*REXX program solves the (continuous) burglar's knapsack problem. */ +@.= /*═══════ name weight value ══════*/ + @.1 = 'flitch 4 30 ' + @.2 = 'beef 3.8 36 ' + @.3 = 'pork 5.4 43 ' + @.4 = 'greaves 2.4 45 ' + @.5 = 'brawn 2.5 56 ' + @.6 = 'welt 3.7 67 ' + @.7 = 'ham 3.6 90 ' + @.8 = 'salami 3 95 ' + @.9 = 'sausage 5.9 98 ' +parse arg maxW d . /*get possible arguments from the C.L. */ +if maxW=='' | maxW==',' then maxW=15 /*the burglar's knapsack maximum weight*/ +if d=='' | d==',' then d= 3 /*number of decimal digits in FORMAT. */ +wL=d+length('weight'); nL=d+length('total weight'); vL=d+length('value') totW=0; totV=0 - do #=1 while @.#\==''; parse var @.# n.# w.# v.# . - end /*#*/ /* [↑] assign to separate lists.*/ -#=#-1 /*#: number of items in @ list.*/ -call show 'unsorted item list' /*display header and the @ list.*/ -call sortD /*invoke using a descending sort.*/ + do #=1 while @.#\==''; parse var @.# n.# w.# v.# . + end /*#*/ /* [↑] assign item to separate lists. */ +#=#-1 /*#: is the number of items in @ list.*/ +call show 'unsorted item list' /*display the header and the @ list.*/ +call sortD /*invoke sort (which sorts descending).*/ call hdr "burglar's knapsack contents" - do j=1 for # while totW=maxW then f=(maxW-totW)/w.j /*calc fract*/ - totW=totW+w.j*f; totV=totV+v.j*f /*add──►tots*/ - call syf left(word('{all}',1+(f\==1)),5) n.j, w.j*f, v.j*f - end /*j*/ /*↑show item*/ -call sep; say /* [↓] $ supresses trailing Θs.*/ + do j=1 for # while totW=maxW then f=(maxW-totW)/w.j /*calculate fract.*/ + totW=totW+w.j*f; totV=totV+v.j*f /*add ───► totals.*/ + call syf left(word('{all}',1+(f\==1)),5) n.j, w.j*f, v.j*f + end /*j*/ /* [↑] show item.*/ +call sep; say; t='t' /* [↓] $ suppresses trailing zeroes.*/ call sy left('total weight',nL,'─'), $(format(totW,,d)) call sy left('total value',nL,'─'), , $(format(totV,,d)) -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one─liner subroutines──────────────────────*/ -hdr: say; say; say center(arg(1),50,'─'); say; call title; call sep; return -sep: call sy copies('═',nL), copies("═",wL), copies('═',vL); return -show: call hdr arg(1); do j=1 for #; call syf n.j,w.j,v.j; end; return -sy: say left('',9) left(arg(1),nL) right(arg(2),wL) right(arg(3),vL); return -syf: call sy arg(1), $(format(arg(2),,d)), $(format(arg(3),,d)); return -title: call sy center('item',nL), center("weight",wL), center('value',vL); return -$:x=arg(1);if pos(.,x)>1 then x=left(strip(strip(x,'T',0),,.),length(x));return x -/*──────────────────────────────────SORTD subroutine───────────────────────────*/ -sortD: do sort=2 to #; _n=n.sort; _w=w.sort; _v=v.sort /*descending. */ - do k=sort-1 by -1 to 1 while v.k/w.k<_v/_w /*order items.*/ - p=k+1; n.p=n.k; w.p=w.k; v.p=v.k /*shuffle 'em.*/ - end /*k*/ /*[↓] last one*/ - a=k+1; n.a=_n; w.a=_w; v.a=_v /*place item. */ - end /*sort*/ -return /* ↑ ↑ ↑ algorithm is OK for smallish arrays.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sortD: do s=2 to #; a=n.s; !=w.s; u=v.s /* [↓] this is a descending sort.*/ + do k=s-1 by -1 to 1 while v.k/w.k1 then x=left(strip(strip(x,'T',0),,.),length(x));return x diff --git a/Task/Knapsack-problem-Unbounded/Eiffel/knapsack-problem-unbounded.e b/Task/Knapsack-problem-Unbounded/Eiffel/knapsack-problem-unbounded.e new file mode 100644 index 0000000000..97d4d01c86 --- /dev/null +++ b/Task/Knapsack-problem-Unbounded/Eiffel/knapsack-problem-unbounded.e @@ -0,0 +1,82 @@ +class + KNAPSACK + +create + make + +feature + + make + do + create panacea; + panacea := [3000, 0.3, 0.025] + create ichor; + ichor := [1800, 0.2, 0.015] + create gold; + gold := [2500, 2.0, 0.002] + create sack; + sack := [0, 25.0, 0.25] + find_solution + end + +feature {NONE} + + panacea: TUPLE [value: INTEGER; weight: REAL_64; volume: REAL_64] + + ichor: TUPLE [value: INTEGER; weight: REAL_64; volume: REAL_64] + + gold: TUPLE [value: INTEGER; weight: REAL_64; volume: REAL_64] + + sack: TUPLE [value: INTEGER; weight: REAL_64; volume: REAL_64] + + find_solution + -- Solution for unbounded Knapsack Problem. + local + totalweight, totalvolume: REAL_64 + maxpanacea, maxichor, maxvalue, maxgold: INTEGER + n: ARRAY [INTEGER] + r: TUPLE [value: INTEGER; weight: REAL_64; volume: REAL_64] + do + maxpanacea := minimum (sack.weight / panacea.weight, sack.volume / panacea.volume).rounded + maxichor := minimum (sack.weight / ichor.weight, sack.volume / ichor.volume).rounded + maxgold := minimum (sack.weight / gold.weight, sack.volume / gold.volume).rounded + create n.make_filled (0, 1, 3) + create r + across + 0 |..| maxpanacea as p + loop + across + 0 |..| maxichor as i + loop + across + 0 |..| maxgold as g + loop + r.value := g.item * gold.value + i.item * ichor.value + p.item * panacea.value + r.weight := g.item * gold.weight + i.item * ichor.weight + p.item * panacea.weight + r.volume := g.item * gold.volume + i.item * ichor.volume + p.item * panacea.volume + if r.value > maxvalue and r.weight <= sack.weight and r.volume <= sack.volume then + maxvalue := r.value + totalweight := r.weight + totalvolume := r.volume + n [1] := p.item + n [2] := i.item + n [3] := g.item + end + end + end + end + io.put_string ("Maximum value achievable is " + maxValue.out + ".%N") + io.put_string ("This is achieved by carrying " + n [1].out + " panacea, " + n [2].out + " ichor and " + n [3].out + " gold.%N") + io.put_string ("The weight is " + totalweight.out + " and the volume is " + totalvolume.truncated_to_real.out + ".") + end + + minimum (a, b: REAL_64): REAL_64 + -- Smaller of 'a' and 'b'. + do + Result := a + if a > b then + Result := b + end + end + +end diff --git a/Task/Knapsack-problem-Unbounded/Perl-6/knapsack-problem-unbounded.pl6 b/Task/Knapsack-problem-Unbounded/Perl-6/knapsack-problem-unbounded.pl6 index b8b942dbf8..488d7f233d 100644 --- a/Task/Knapsack-problem-Unbounded/Perl-6/knapsack-problem-unbounded.pl6 +++ b/Task/Knapsack-problem-Unbounded/Perl-6/knapsack-problem-unbounded.pl6 @@ -24,15 +24,15 @@ for $panacea, $ichor, $gold -> $item { } for 0..%max_items - X 0..%max_items - X 0..%max_items - -> $p, $i, $g + X 0..%max_items + X 0..%max_items + -> ($p, $i, $g) { next if $panacea.volume * $p + $ichor.volume * $i + $gold.volume * $g > $maximum.volume; next if $panacea.weight * $p + $ichor.weight * $i + $gold.weight * $g > $maximum.weight; given $panacea.value * $p + $ichor.value * $i + $gold.value * $g { if $_ > $max_val { $max_val = $_; @solutions = (); } - when $max_val { @solutions.push: [$p,$i,$g] } + when $max_val { @solutions.push: $[$p,$i,$g] } } } diff --git a/Task/Knights-tour/REXX/knights-tour.rexx b/Task/Knights-tour/REXX/knights-tour.rexx index ca075c4d00..8b5ad6b7db 100644 --- a/Task/Knights-tour/REXX/knights-tour.rexx +++ b/Task/Knights-tour/REXX/knights-tour.rexx @@ -1,36 +1,36 @@ /*REXX program solves the knight's tour problem for a NxN chessboard.*/ parse arg N sRank sFile . /*boardsize, starting position. */ -if N=='' | N==',' then N=8 /*Boardsize specified? Default. */ -if sRank=='' then sRank=N /*starting rank given? Default. */ -if sFile=='' then sFile=1 /* " file " " */ -!=left('', 9*(n<18)) /*used for indentation of board. */ -NN=N**2; NxN='a ' N"x"N ' chessboard' /* [↓] r=Rank, f=File.*/ -@.=; do r=1 for N; do f=1 for N; @.r.f=' '; end /*f*/; end /*r*/ - /*[↑] zero the NxN chessboard.*/ -Kr = '2 1 -1 -2 -2 -1 1 2' /*legal "rank" move for a knight.*/ -Kf = '1 2 2 1 -1 -2 -2 -1' /* " "file" " " " " */ - do i=1 for words(Kr) /*legal knight moves*/ - Kr.i = word(Kr,i); Kf.i = word(Kf,i) - end /*i*/ /*for fast indexing.*/ +if N=='' | N==',' then N=8 /*Boardsize specified? Default. */ +if sRank=='' | sRank==',' then sRank=N /*starting rank given? Default. */ +if sFile=='' | sFile==',' then sFile=1 /* " file " " */ +NN=N**2; NxN='a ' N"x"N ' chessboard' /*[↓ ↓] r f = Rank and File.*/ +@.=; do r=1 for N; do f=1 for N; @.r.f=.; end /*f*/; end /*r*/ + /*[↑] create the NxN chessboard.*/ + Kr = '2 1 -1 -2 -2 -1 1 2' /*legal "rank" move for a knight.*/ + Kf = '1 2 2 1 -1 -2 -2 -1' /* " "file" " " " " */ +parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 /*parse by hand.*/ +parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 /* " " " */ @.sRank.sFile=1 /*the knight's starting position.*/ -if \move(2,sRank,sFile) & , - \(N==1) then say "No knight's tour solution for" NxN'.' - else say "A solution for the knight's tour on" NxN':' +if \move(2,sRank,sFile) & \(N==1), /* ◄═══ is there a NxN solution? */ + then say "No knight's tour solution for" NxN'.' + else say "A solution for the knight's tour on" NxN':' + /* [↓] display the chessboard. */ +!=left('', 9*(n<18)) /*used for indentation of board. */ _=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*/ /*done with a rank on chessboard.*/ - say ! L'│' /*show a rank of the chessboard.*/ - end /*r*/ /*80 cols can view 19x19 chessbrd*/ + do f=1 for N; L=L'│'centre(@.r.f, 3) /*preserve squareness.*/ + end /*f*/ /*done with a rank on chessboard.*/ + say ! translate(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 NN; parse arg #,rank,file; b=' ' - do t=1 for 8; nr=rank+Kr.t; nf=file+Kf.t - if @.nr.nf==b then do; @.nr.nf=# /*Kn move.*/ +move: procedure expose @. Kr. Kf. NN; parse arg #,rank,file + do t=1 for 8; nr=rank+Kr.t; nf=file+Kf.t /*location*/ + if @.nr.nf==. then do; @.nr.nf=# /*Kn move.*/ if #==NN then return 1 /*last mv?*/ if move(#+1,nr,nf) then return 1 /* " " */ - @.nr.nf=b /*undo the above move. */ + @.nr.nf=. /*undo the above move. */ end /*try different move. */ end /*t*/ /* [↑] all moves tried.*/ return 0 /*the tour not possible.*/ diff --git a/Task/Knights-tour/Rust/knights-tour.rust b/Task/Knights-tour/Rust/knights-tour.rust new file mode 100644 index 0000000000..28bb068a1f --- /dev/null +++ b/Task/Knights-tour/Rust/knights-tour.rust @@ -0,0 +1,103 @@ +use std::fmt; + +const SIZE: usize = 8; +const MOVES: [(i32, i32); 8] = [(2,1), (1,2), (-1,2), (-2,1), (-2,-1), (-1,-2), (1,-2), (2,-1)]; + +#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)] +struct Point { + x: i32, + y: i32 +} + +impl Point { + fn mov(&self, &(dx,dy): &(i32, i32)) -> Point { + Point { + x: self.x + dx, + y: self.y + dy + } + } +} + +struct Board { + field: [[i32;SIZE];SIZE] +} + +impl Board { + + fn new() -> Board { + return Board { + field: [[0; SIZE]; SIZE] + }; + } + + fn available(&self, p: Point) -> bool { + let valid = 0 <= p.x && p.x < SIZE as i32 + && 0 <= p.y && p.y < SIZE as i32; + return valid && self.field[p.x as usize][p.y as usize] == 0; + } + + // calculate the number of possible moves + fn count_degree(&self, p: Point) -> i32 { + let mut count = 0; + for dir in MOVES.iter() { + let next = p.mov(dir); + if self.available(next) { + count += 1; + } + } + return count; + } +} + +impl fmt::Display for Board { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + for row in self.field.iter() { + for x in row.iter(){ + try!(write!(f, "{:3} ", x)); + } + try!(write!(f, "\n")); + } + Ok(()) + } +} + +fn knights_tour(x: i32, y: i32) -> Option { + let mut board = Board::new(); + let mut p = Point {x: x, y: y}; + let mut step = 1; + board.field[p.x as usize][p.y as usize] = step; + step += 1; + + while step <= (SIZE * SIZE) as i32 { + // choose next square by Warnsdorf's rule + let mut candidates = vec![]; + for dir in MOVES.iter() { + let adj = p.mov(dir); + if board.available(adj) { + let degree = board.count_degree(adj); + candidates.push((degree, adj)); + } + } + match candidates.iter().min() { + Some(&(_, adj)) => // move to next square + p = adj, + None => // can't move + return None + }; + board.field[p.x as usize][p.y as usize] = step; + step += 1; + } + return Some(board); +} + +fn main() { + let (x, y) = (3, 1); + println!("Board size: {}", SIZE); + println!("Starting position: ({}, {})", x, y); + match knights_tour(x, y) { + Some(b) => + print!("{}", b), + None => + println!("Fail!") + } +} diff --git a/Task/Knights-tour/XSLT/knights-tour-1.xslt b/Task/Knights-tour/XSLT/knights-tour-1.xslt new file mode 100644 index 0000000000..306c5628ea --- /dev/null +++ b/Task/Knights-tour/XSLT/knights-tour-1.xslt @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Task/Knights-tour/XSLT/knights-tour-2.xslt b/Task/Knights-tour/XSLT/knights-tour-2.xslt new file mode 100644 index 0000000000..532b630972 --- /dev/null +++ b/Task/Knights-tour/XSLT/knights-tour-2.xslt @@ -0,0 +1,38 @@ + + + + + + + + Failed to find solution to Knight's Tour. + + + + + + + + + diff --git a/Task/Knights-tour/XSLT/knights-tour-3.xslt b/Task/Knights-tour/XSLT/knights-tour-3.xslt new file mode 100644 index 0000000000..19d2d4a2bd --- /dev/null +++ b/Task/Knights-tour/XSLT/knights-tour-3.xslt @@ -0,0 +1,5 @@ + + + + + diff --git a/Task/Knights-tour/XSLT/knights-tour-4.xslt b/Task/Knights-tour/XSLT/knights-tour-4.xslt new file mode 100644 index 0000000000..74c3a4a805 --- /dev/null +++ b/Task/Knights-tour/XSLT/knights-tour-4.xslt @@ -0,0 +1,8 @@ + + + + + + ... etc for 64 squares. + + diff --git a/Task/Knuth-shuffle/Eiffel/knuth-shuffle.e b/Task/Knuth-shuffle/Eiffel/knuth-shuffle.e index 92a77d5a7f..c0b504c561 100644 --- a/Task/Knuth-shuffle/Eiffel/knuth-shuffle.e +++ b/Task/Knuth-shuffle/Eiffel/knuth-shuffle.e @@ -1,7 +1,6 @@ class APPLICATION -inherit - ARGUMENTS + create make @@ -9,38 +8,48 @@ feature {NONE} -- Initialization make do - test:= <<1,2,3,4,5,6,7>> + test := <<1, 2>> io.put_string ("Initial: ") - across test as t loop io.put_string (t.item.out + " ") end - create testresult.make_empty - testresult:= shuffle (test) - io.put_string ("%NShuffled: ") - across testresult as t loop io.put_string (t.item.out + " ") end - + across + test as t + loop + io.put_string (t.item.out + " ") + end + test := shuffle (test) + io.new_line + io.put_string ("Shuffled: ") + across + test as t + loop + io.put_string (t.item.out + " ") + end end - test: ARRAY[INTEGER] - testresult: ARRAY[INTEGER] + test: ARRAY [INTEGER] - shuffle(ar:ARRAY[INTEGER]): ARRAY[INTEGER] - local - i,j:INTEGER - ith: INTEGER - random: V_RANDOM - do - create random - from - i:=ar.count - until - i=2 - loop - j:=random.bounded_item (1, i) - ith:= ar[i] - ar[i]:= ar[j] - ar[j]:= ith - random.forth - i:=i-1 + shuffle (ar: ARRAY [INTEGER]): ARRAY [INTEGER] + -- Array containing the same elements as 'ar' in a shuffled order. + require + more_than_one_element: ar.count > 1 + local + count, j, ith: INTEGER + random: V_RANDOM + do + create random + create Result.make_empty + Result.deep_copy (ar) + count := ar.count + across + 1 |..| count as c + loop + j := random.bounded_item (c.item, count) + ith := Result [c.item] + Result [c.item] := Result [j] + Result [j] := ith + random.forth + end + ensure + same_elements: across ar as a all Result.has (a.item) end end - Result:= ar - end + end diff --git a/Task/Knuth-shuffle/Elixir/knuth-shuffle.elixir b/Task/Knuth-shuffle/Elixir/knuth-shuffle.elixir new file mode 100644 index 0000000000..24ddd6ca53 --- /dev/null +++ b/Task/Knuth-shuffle/Elixir/knuth-shuffle.elixir @@ -0,0 +1,23 @@ +defmodule Knuth do + def shuffle( inputs ) do + n = length( inputs ) + {[], acc} = Enum.reduce( n..1, {inputs, []}, &random_move/2 ) + acc + end + + defp random_move( n, {inputs, acc} ) do + item = Enum.at( inputs, :random.uniform(n)-1 ) + {List.delete( inputs, item ), [item | acc]} + end +end + +:random.seed( :os.timestamp ) +seq = Enum.to_list( 0..19 ) +IO.inspect Knuth.shuffle( seq ) + +seq = [1,2,3] +Enum.reduce(1..100000, Map.new, fn _,acc -> + k = Knuth.shuffle(seq) + Dict.update(acc, k, 1, &(&1+1)) +end) +|> Enum.each(fn {k,v} -> IO.inspect {k,v} end) diff --git a/Task/Knuth-shuffle/Haskell/knuth-shuffle-1.hs b/Task/Knuth-shuffle/Haskell/knuth-shuffle-1.hs index b2a80bc637..293fb93e46 100644 --- a/Task/Knuth-shuffle/Haskell/knuth-shuffle-1.hs +++ b/Task/Knuth-shuffle/Haskell/knuth-shuffle-1.hs @@ -6,7 +6,7 @@ import Control.Arrow mkRands = mapM (randomRIO.(,)0 ). enumFromTo 1. pred replaceAt :: Int -> a -> [a] -> [a] -replaceAt i c = let (a,b) = splitAt i l in a++x:(drop 1 b) +replaceAt i c l = let (a,b) = splitAt i l in a++c:(drop 1 b) swapElems :: (Int, Int) -> [a] -> [a] swapElems (i,j) xs | i==j = xs diff --git a/Task/Knuth-shuffle/JavaScript/knuth-shuffle.js b/Task/Knuth-shuffle/JavaScript/knuth-shuffle.js index 7de9e0b8cc..f3b2804cf4 100644 --- a/Task/Knuth-shuffle/JavaScript/knuth-shuffle.js +++ b/Task/Knuth-shuffle/JavaScript/knuth-shuffle.js @@ -1,28 +1,25 @@ -function knuth_shuffle(a) { - var n = a.length, - r, - temp; - while (n > 1) { - r = Math.floor(n * Math.random()); - n -= 1; - temp = a[n]; - a[n] = a[r]; - a[r] = temp; +function knuthShuffle(arr) { + var rand, temp, i; + + for (i = arr.length - 1; i > 0; i -= 1) { + rand = Math.floor((i + 1) * Math.random());//get random between zero and i (inclusive) + temp = arr[rand];//swap i and the zero-indexed number + arr[rand] = arr[i]; + arr[i] = temp; } - return a; + return arr; } -var res, i, key; - -res = { +var res = { '1,2,3': 0, '1,3,2': 0, '2,1,3': 0, '2,3,1': 0, '3,1,2': 0, '3,2,1': 0 }; -for (i = 0; i < 100000; i++) { - res[knuth_shuffle([1,2,3]).join(',')] += 1; +for (var i = 0; i < 100000; i++) { + res[knuthShuffle([1,2,3]).join(',')] += 1; } -for (key in res) { + +for (var key in res) { print(key + "\t" + res[key]); } diff --git a/Task/Knuth-shuffle/Julia/knuth-shuffle-1.julia b/Task/Knuth-shuffle/Julia/knuth-shuffle-1.julia new file mode 100644 index 0000000000..8b69dba446 --- /dev/null +++ b/Task/Knuth-shuffle/Julia/knuth-shuffle-1.julia @@ -0,0 +1,7 @@ +function shuffle!(r::AbstractRNG, a::AbstractVector) + for i = length(a):-1:2 + j = rand(r, 1:i) + a[i], a[j] = a[j], a[i] + end + return a +end diff --git a/Task/Knuth-shuffle/Julia/knuth-shuffle-2.julia b/Task/Knuth-shuffle/Julia/knuth-shuffle-2.julia new file mode 100644 index 0000000000..4715c06198 --- /dev/null +++ b/Task/Knuth-shuffle/Julia/knuth-shuffle-2.julia @@ -0,0 +1,7 @@ +a = collect(1:20) +b = shuffle(a) + +print("Unshuffled Array:\n ") +println(a) +print("Shuffled Array:\n ") +println(b) diff --git a/Task/Knuth-shuffle/Rust/knuth-shuffle.rust b/Task/Knuth-shuffle/Rust/knuth-shuffle.rust index 5440c9fdd2..22a6bcb044 100644 --- a/Task/Knuth-shuffle/Rust/knuth-shuffle.rust +++ b/Task/Knuth-shuffle/Rust/knuth-shuffle.rust @@ -1,22 +1,21 @@ -use std::iter; -use std::rand; -use std::rand::Rng; -use std::vec; +use rand::Rng; + +extern crate rand; fn knuth_shuffle(v: &mut [T]) { - let mut rng = rand::rng(); + let mut rng = rand::thread_rng(); let l = v.len(); - for n in iter::range(0, l) { + for n in 0..l { let i = rng.gen_range(0, l - n); v.swap(i, l - n - 1); } } fn main() { - let mut v = vec::from_fn(10, |i| i); + let mut v: Vec<_> = (0..10).collect(); println!("before: {:?}", v); - knuth_shuffle(v); + knuth_shuffle(&mut v); println!("after: {:?}", v); } diff --git a/Task/Knuth-shuffle/Scheme/knuth-shuffle-1.ss b/Task/Knuth-shuffle/Scheme/knuth-shuffle-1.ss new file mode 100644 index 0000000000..ffdbefbb44 --- /dev/null +++ b/Task/Knuth-shuffle/Scheme/knuth-shuffle-1.ss @@ -0,0 +1,18 @@ +#!r6rs +(import (rnrs base (6)) + (srfi :27 random-bits)) + +(define (semireverse li n) + (define (continue front back n) + (cond + ((null? back) front) + ((zero? n) (cons (car back) (append front (cdr back)))) + (else (continue (cons (car back) front) (cdr back) (- n 1))))) + (continue '() li n)) + +(define (shuffle li) + (if (null? li) + () + (let + ((li-prime (semireverse li (random-integer (length li))))) + (cons (car li-prime) (shuffle (cdr li-prime)))))) diff --git a/Task/Knuth-shuffle/Scheme/knuth-shuffle-2.ss b/Task/Knuth-shuffle/Scheme/knuth-shuffle-2.ss new file mode 100644 index 0000000000..c0c7ac4937 --- /dev/null +++ b/Task/Knuth-shuffle/Scheme/knuth-shuffle-2.ss @@ -0,0 +1,22 @@ +#!r6rs +(import (rnrs base (6)) + (srfi :27 random-bits)) + +(define (vector-swap! vec i j) + (let + ((temp (vector-ref vec i))) + (vector-set! vec i (vector-ref vec j)) + (vector-set! vec j temp))) + +(define (countdown n) + (if (zero? n) + () + (cons n (countdown (- n 1))))) + +(define (vector-shuffle! vec) + (for-each + (lambda (i) + (let + ((j (random-integer i))) + (vector-swap! vec (- i 1) j))) + (countdown (vector-length vec)))) diff --git a/Task/Knuth-shuffle/Scheme/knuth-shuffle.ss b/Task/Knuth-shuffle/Scheme/knuth-shuffle.ss deleted file mode 100644 index 5982c3f245..0000000000 --- a/Task/Knuth-shuffle/Scheme/knuth-shuffle.ss +++ /dev/null @@ -1,10 +0,0 @@ -(define (swap vec i j) - (let ([tmp (vector-ref vec i)]) - (vector-set! vec i (vector-ref vec j)) - (vector-set! vec j tmp))) - -(define (shuffle vec) - (for ((i (in-range (- (vector-length vec) 1) 0 -1))) - (let ((r (random i))) - (swap vec i r))) - vec) diff --git a/Task/Knuths-algorithm-S/Julia/knuths-algorithm-s.julia b/Task/Knuths-algorithm-S/Julia/knuths-algorithm-s.julia new file mode 100644 index 0000000000..ca54a5cfc6 --- /dev/null +++ b/Task/Knuths-algorithm-S/Julia/knuths-algorithm-s.julia @@ -0,0 +1,35 @@ +function makesofn(n::Int) + buf = Any[] + i = 0 + function sofn(item) + i += 1 + if i <= n + push!(buf, item) + else + j = rand(1:i) + if j <= n + buf[j] = item + end + end + return buf + end + return sofn +end + + +nhist = zeros(Int, 10) + +for i in 1:10^5 + kas = makesofn(3) + for j in 0:8 + kas(j) + end + for k in kas(9) + nhist[k+1] += 1 + end +end + +println("Simulating sof3(0:9) 100000 times:") +for (i, c) in enumerate(nhist) + println(@sprintf " %2d => %5d" i-1 c) +end diff --git a/Task/Knuths-algorithm-S/REXX/knuths-algorithm-s.rexx b/Task/Knuths-algorithm-S/REXX/knuths-algorithm-s.rexx index f1f7e5b04c..cfbdac34d5 100644 --- a/Task/Knuths-algorithm-S/REXX/knuths-algorithm-s.rexx +++ b/Task/Knuths-algorithm-S/REXX/knuths-algorithm-s.rexx @@ -1,45 +1,41 @@ -/*REXX program using Knuth's algorithm S (random sampling n of M items).*/ -parse arg trials size . /*obtain the arguments from C.L. */ -if trials=='' then trials=100000 /*use default if not specified. */ -if size=='' then size=3 /* " " " " " */ -#.=0 /*a couple handfuls of counters. */ - do trials /*OK, let's light this candle. */ - call s_of_n_creator size /*create initial list of n items.*/ +/*REXX program using Knuth's algorithm S (a random sampling N of M items). */ +parse arg trials size . /*obtain optional arguments from the CL*/ +if trials=='' then trials=100000 /*Not specified? Then use the default.*/ +if size=='' then size=3 /* " " " " " " */ +#.=0 /*initialize an array of freq counters.*/ + do trials /*OK, now let's light this candle. */ + call SofN_creator size /*create initial list of N items. */ - do gener=0 for 10 /*and then call SofN for each dig*/ - call s_of_n gener /*call s_of_n with a single dig*/ + do gener=0 for 10 /*and then call SofN for each digit. */ + call SofN gener /*call SofN with a single decimal dig*/ end /*gener*/ - do count=1 for size /*let's see what s_of_n wroth. */ - _=!.count /*get a digit from the Nth item, */ - #._=#._+1 /* ... and count it, of course. */ + do count=1 for size /*let's examine what SofN generated. */ + _=!.count /*get a digit from the Nth item, and */ + #._=#._+1 /* ··· count it, of course. */ end /*count*/ end /*trials*/ -say "Using Knuth's algorihm S for" comma(trials) 'trials, and with size='comma(size)":" -say - do dig=0 to 9 /*show & tell time for frequency.*/ - say copies(' ',15) "frequency of the" dig 'digit is:' comma(#.dig) +say "Using Knuth's algorithm S for" commas(trials), + 'trials, and with size='commas(size)":"; say + do dig=0 to 9 /* [↓] display the frequency of a dig.*/ + say left('',15) "frequency of the" dig 'digit is:' commas(#.dig) end /*dig*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────S_OF_N_CREATOR subroutine───────────*/ -s_of_n_creator: parse arg item 1 items /*generate ITEM number of items*/ - do k=1 for item /*traipse through the 1st N items*/ - !.k=random(0,9) /*set the Kth item with rand dig.*/ - end /*k*/ -return /*out piddly work is done for now*/ -/*──────────────────────────────────S_OF_N subroutine───────────────────*/ -s_of_n: parse arg item; items=items+1 /*get "item", bump items counter.*/ -c=random(1,items) /*should we replace a prev item? */ -if c>size then return /*probability isn't good, skip it*/ -_=random(1,size) /*now, figure out which previous */ -!._=item /* ... item to replace with ITEM.*/ -return /*and back to the caller we go. */ -/*──────────────────────────────────COMMA subroutine────────────────────*/ -comma: procedure; parse arg _,c,p,t;arg ,cu;c=word(c ",",1) - if cu=='BLANK' then c=' '; o=word(p 3,1); p=abs(o); t=word(t 999999999,1) - if \datatype(p,'W') | \datatype(t,'W') | p==0 | arg()>4 then return _ - n=_'.9'; #=123456789; k=0; if o<0 then do; b=verify(_,' '); if b==0 then return _ - e=length(_)-verify(reverse(_),' ')+1; end; else do; b=verify(n,#,"M") - e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end - do j=e to b by -p while ksize then return /*probability isn't good, so skip it. */ +_=random(1, size) /*now, figure out which previous ··· */ +!._=item /* ··· item to replace with ITEM. */ +return +/*────────────────────────────────────────────────────────────────────────────*/ +commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M") + e=verify(n,#'0',,verify(n,#"0.",'M'))-4 + do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _ diff --git a/Task/LU-decomposition/00DESCRIPTION b/Task/LU-decomposition/00DESCRIPTION index 12b5e10f1a..f92b40d8fc 100644 --- a/Task/LU-decomposition/00DESCRIPTION +++ b/Task/LU-decomposition/00DESCRIPTION @@ -96,7 +96,7 @@ and then for L We see in the second formula that to get the l_{ij} below the diagonal, we have to divide by the diagonal element (pivot) u_{jj}, so we get problems when u_{jj} is either 0 or very small, which leads to numerical instability. -The solution to this problem is ''pivoting'' A, which means rearranging the rows of A, prior to the LU decomposition, in a way that the largest element of each column gets onto the diagonal of A. Rearranging the columns means to multiply A by a permutation matrix P: +The solution to this problem is ''pivoting'' A, which means rearranging the rows of A, prior to the LU decomposition, in a way that the largest element of each column gets onto the diagonal of A. Rearranging the rows means to multiply A by a permutation matrix P: :PA \Rightarrow A' diff --git a/Task/LU-decomposition/Go/lu-decomposition-2.go b/Task/LU-decomposition/Go/lu-decomposition-2.go index 4cefe791fa..7479a1c4ab 100644 --- a/Task/LU-decomposition/Go/lu-decomposition-2.go +++ b/Task/LU-decomposition/Go/lu-decomposition-2.go @@ -3,19 +3,8 @@ package main import "fmt" type matrix struct { - ele []float64 stride int -} - -func matrixFromRows(rows [][]float64) *matrix { - if len(rows) == 0 { - return &matrix{nil, 0} - } - m := &matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])} - for rx, row := range rows { - copy(m.ele[rx*m.stride:(rx+1)*m.stride], row) - } - return m + ele []float64 } func (m *matrix) print(heading string) { @@ -32,7 +21,7 @@ func (m1 *matrix) mul(m2 *matrix) (m3 *matrix, ok bool) { if m1.stride*m2.stride != len(m2.ele) { return nil, false } - m3 = &matrix{make([]float64, (len(m1.ele)/m1.stride)*m2.stride), m2.stride} + m3 = &matrix{m2.stride, make([]float64, (len(m1.ele)/m1.stride)*m2.stride)} for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.stride { for m2r0 := 0; m2r0 < m2.stride; m2r0++ { for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.stride { @@ -46,7 +35,7 @@ func (m1 *matrix) mul(m2 *matrix) (m3 *matrix, ok bool) { } func zero(rows, cols int) *matrix { - return &matrix{make([]float64, rows*cols), cols} + return &matrix{cols, make([]float64, rows*cols)} } func eye(n int) *matrix { @@ -114,15 +103,15 @@ func (a *matrix) lu() (l, u, p *matrix) { } func main() { - showLU(matrixFromRows([][]float64{ - {1, 3, 5}, - {2, 4, 7}, - {1, 1, 0}})) - showLU(matrixFromRows([][]float64{ - {11, 9, 24, 2}, - {1, 5, 2, 6}, - {3, 17, 18, 1}, - {2, 5, 7, 1}})) + showLU(&matrix{3, []float64{ + 1, 3, 5, + 2, 4, 7, + 1, 1, 0}}) + showLU(&matrix{4, []float64{ + 11, 9, 24, 2, + 1, 5, 2, 6, + 3, 17, 18, 1, + 2, 5, 7, 1}}) } func showLU(a *matrix) { diff --git a/Task/LU-decomposition/Go/lu-decomposition-3.go b/Task/LU-decomposition/Go/lu-decomposition-3.go index ec1406b7fa..5a132d64f1 100644 --- a/Task/LU-decomposition/Go/lu-decomposition-3.go +++ b/Task/LU-decomposition/Go/lu-decomposition-3.go @@ -3,25 +3,32 @@ package main import ( "fmt" - mat "github.com/skelterjohn/go.matrix" + "github.com/gonum/matrix/mat64" ) func main() { - showLU(mat.MakeDenseMatrixStacked([][]float64{ - {1, 3, 5}, - {2, 4, 7}, - {1, 1, 0}})) - showLU(mat.MakeDenseMatrixStacked([][]float64{ - {11, 9, 24, 2}, - {1, 5, 2, 6}, - {3, 17, 18, 1}, - {2, 5, 7, 1}})) + showLU(mat64.NewDense(3, 3, []float64{ + 1, 3, 5, + 2, 4, 7, + 1, 1, 0, + })) + fmt.Println() + showLU(mat64.NewDense(4, 4, []float64{ + 11, 9, 24, 2, + 1, 5, 2, 6, + 3, 17, 18, 1, + 2, 5, 7, 1, + })) } -func showLU(a *mat.DenseMatrix) { - fmt.Printf("\na:\n%v\n", a) - l, u, p := a.LU() - fmt.Printf("l:\n%v\n", l) - fmt.Printf("u:\n%v\n", u) - fmt.Printf("p:\n%v\n", p) +func showLU(a *mat64.Dense) { + fmt.Printf("a: %v\n\n", mat64.Formatted(a, mat64.Prefix(" "))) + var lu mat64.LU + lu.Factorize(a) + var l, u mat64.TriDense + l.LFrom(&lu) + u.UFrom(&lu) + fmt.Printf("l: %.5f\n\n", mat64.Formatted(&l, mat64.Prefix(" "))) + fmt.Printf("u: %.5f\n\n", mat64.Formatted(&u, mat64.Prefix(" "))) + fmt.Println("p:", lu.Pivot(nil)) } diff --git a/Task/LU-decomposition/Go/lu-decomposition-4.go b/Task/LU-decomposition/Go/lu-decomposition-4.go new file mode 100644 index 0000000000..ec1406b7fa --- /dev/null +++ b/Task/LU-decomposition/Go/lu-decomposition-4.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + + mat "github.com/skelterjohn/go.matrix" +) + +func main() { + showLU(mat.MakeDenseMatrixStacked([][]float64{ + {1, 3, 5}, + {2, 4, 7}, + {1, 1, 0}})) + showLU(mat.MakeDenseMatrixStacked([][]float64{ + {11, 9, 24, 2}, + {1, 5, 2, 6}, + {3, 17, 18, 1}, + {2, 5, 7, 1}})) +} + +func showLU(a *mat.DenseMatrix) { + fmt.Printf("\na:\n%v\n", a) + l, u, p := a.LU() + fmt.Printf("l:\n%v\n", l) + fmt.Printf("u:\n%v\n", u) + fmt.Printf("p:\n%v\n", p) +} diff --git a/Task/LZW-compression/Common-Lisp/lzw-compression-1.lisp b/Task/LZW-compression/Common-Lisp/lzw-compression-1.lisp index 4850c7f1b2..34c2e7a8e2 100644 --- a/Task/LZW-compression/Common-Lisp/lzw-compression-1.lisp +++ b/Task/LZW-compression/Common-Lisp/lzw-compression-1.lisp @@ -86,7 +86,7 @@ for k = (make-vector-with-elt (aref octets i) 't) for entry = (or (gethash k dictionary) (if (equalp k dictionary-size) - (coerce (list w (aref w 0)) '(vector octet)) + (vector-append1-new w (aref w 0)) (error "bad compresed entry at pos ~S" i))) do (vector-append result entry) (setf (gethash (make-vector-with-elt dictionary-size) dictionary) diff --git a/Task/LZW-compression/Eiffel/lzw-compression.e b/Task/LZW-compression/Eiffel/lzw-compression.e new file mode 100644 index 0000000000..6ae77a2b7b --- /dev/null +++ b/Task/LZW-compression/Eiffel/lzw-compression.e @@ -0,0 +1,112 @@ +class + APPLICATION + +create + make + +feature {NONE} + + make + local + test: LINKED_LIST [INTEGER] + do + create test.make + test := compress ("TOBEORNOTTOBEORTOBEORNOT") + across + test as t + loop + io.put_string (t.item.out + " ") + end + io.new_line + io.put_string (decompress (test)) + end + + decompress (compressed: LINKED_LIST [INTEGER]): STRING + --Decompressed version of 'compressed'. + local + dictsize, i, k: INTEGER + dictionary: HASH_TABLE [STRING, INTEGER] + w, entry: STRING + char: CHARACTER_8 + do + dictsize := 256 + create dictionary.make (300) + create entry.make_empty + create Result.make_empty + from + i := 0 + until + i > 256 + loop + char := i.to_character_8 + dictionary.put (char.out, i) + i := i + 1 + end + w := compressed.first.to_character_8.out + compressed.go_i_th (1) + compressed.remove + Result := w + from + k := 1 + until + k > compressed.count + loop + if attached dictionary.at (compressed [k]) as ata then + entry := ata + elseif compressed [k] = dictsize then + entry := w + w.at (1).out + else + io.put_string ("EXEPTION") + end + Result := Result + entry + dictsize := dictsize + 1 + dictionary.put (w + entry.at (1).out, dictsize) + w := entry + k := k + 1 + end + end + + compress (uncompressed: STRING): LINKED_LIST [INTEGER] + -- Compressed version of 'uncompressed'. + local + dictsize: INTEGER + dictionary: HASH_TABLE [INTEGER, STRING] + i: INTEGER + w, wc: STRING + char: CHARACTER_8 + do + dictsize := 256 + create dictionary.make (256) + create w.make_empty + from + i := 0 + until + i > 256 + loop + char := i.to_character_8 + dictionary.put (i, char.out) + i := i + 1 + end + create Result.make + from + i := 1 + until + i > uncompressed.count + loop + wc := w + uncompressed [i].out + if dictionary.has (wc) then + w := wc + else + Result.extend (dictionary.at (w)) + dictSize := dictSize + 1 + dictionary.put (dictSize, wc) + w := "" + uncompressed [i].out + end + i := i + 1 + end + if w.count > 0 then + Result.extend (dictionary.at (w)) + end + end + +end diff --git a/Task/LZW-compression/Elixir/lzw-compression.elixir b/Task/LZW-compression/Elixir/lzw-compression.elixir new file mode 100644 index 0000000000..f2aa401b8c --- /dev/null +++ b/Task/LZW-compression/Elixir/lzw-compression.elixir @@ -0,0 +1,48 @@ +defmodule LZW do + def encode(str), do: encode(to_char_list(str), init, 256, []) + + defp encode([h], d, _, out), do: Enum.reverse([Dict.get(d, [h]) | out]) + defp encode([h|t], d, free, out) do + val = Dict.get(d, [h]) + find_match(t, [h], val, d, free, out) + end + + defp find_match([h|t], l, lastval, d, free, out) do + case Dict.fetch(d, [h|l]) do + {:ok, val} -> find_match(t, [h|l], val, d, free, out) + :error -> + d1 = Dict.put(d, [h|l], free) + encode([h|t], d1, free+1, [lastval | out]) + end + end + defp find_match([], _, lastval, _, _, out), do: Enum.reverse([lastval | out]) + + defp init, do: init(255, Map.new) + + defp init(0, d), do: d + defp init(n, d), do: init(n-1, Dict.put(d,[n],n)) + + def decode([h|t]) do + d = init1(Map.new) + val = Dict.get(d, h) + decode(t, val, 256, d, val) + end + + defp decode([], _, _, _, l), do: Enum.reverse(l) |> to_string + defp decode([h|t], old, free, d, l) do + val = Dict.get(d, h) + add = [List.last(val) | old] + d1 = Dict.put(d, free, add) + decode(t, val, free+1, d1, val++l) + end + + defp init1(d), do: init1(255, d) + + defp init1(0, d), do: d + defp init1(n, d), do: init1(n-1, Dict.put(d, n, [n])) +end + +str = "TOBEORNOTTOBEORTOBEORNOT" +IO.inspect enc = LZW.encode(str) +IO.inspect dec = LZW.decode(enc) +IO.inspect str == dec diff --git a/Task/LZW-compression/PL-I/lzw-compression.pli b/Task/LZW-compression/PL-I/lzw-compression.pli new file mode 100644 index 0000000000..9435939787 --- /dev/null +++ b/Task/LZW-compression/PL-I/lzw-compression.pli @@ -0,0 +1,150 @@ +*process source xref attributes or(!); + lzwt: Proc Options(main); + + Dcl (LEFT,LENGTH,SUBSTR,TRANSLATE,TRIM,UNSPEC) Builtin; + Dcl SYSPRINT Print; + + Dcl str Char(50) Var Init('TOBEORNOTTOBEORTOBEORNOT'); + Dcl compressed Char(80) Var; + Dcl decompressed Char(80) Var; + + Dcl 1 dict(0:300), + 2 key Char(5) Var, + 2 inx Bin Fixed(16) Unsigned; + Dcl dict_size Bin Fixed(31) Init(256); + Dcl hi Bin Fixed(16) Unsigned Init(65535); + + Put Edit('str=',str)(Skip,a,a); + compressed = compress(str); + Put Edit(compressed)(Skip,a); + decompressed = decompress(compressed); + Put Edit('dec=',decompressed)(Skip,a,a); + If decompressed=str Then + Put Edit('decompression ok')(Skip,a); + Else + Put Edit('decompression not ok')(Skip,a); + + compress: Proc(s) Returns(Char(80) Var); + Dcl s Char(*) Var; + Dcl res Char(80) Var; + Dcl i Bin Fixed(31); + Dcl c Char(1); + Dcl w Char(5) Var; + Dcl wc Char(5) Var; + dict.key=''; + Dcl ii Bin Fixed(8) Unsigned; + Do i=0 To 255; + ii=i; + Unspec(c)=unspec(ii); + dict.key(i)=c; + dict.inx(i)=i; + End; + res='['; + w=''; + Do i=1 To length(s); + c=substr(s,i,1); + wc=w!!c; + If dicti(wc)^=hi Then Do; + w=wc; + End; + Else Do; + res=res!!trim(dicti(w))!!', '; + Call dict_add(wc,dict_size); + w=c; + End; + End; + If w^='' Then + res=res!!trim(dicti(w))!!', '; + substr(res,length(res)-1,1)=']'; + Return(res); + + dicti: Proc(needle) Returns(Bin Fixed(31)); + Dcl needle Char(*) Var; + Dcl i Bin Fixed(31); + Do i=1 To dict_size; + If dict.key(i)=needle Then + Return(i); + End; + Return(hi); + End; + + dict_add: Proc(needle,dict_size); + Dcl needle Char(*) Var; + Dcl dict_size Bin Fixed(31); + dict.key(dict_size)=needle; + dict.inx(dict_size)=dict_size; + dict_size+=1; + End; + + End; + + decompress: Proc(s) Returns(Char(80) Var); + Dcl s Char(80) Var; + Dcl ss Char(80) Var; + Dcl words(50) Char(5) Var; + Dcl wn Bin Fixed(31); + Dcl ww Bin Fixed(31); + Dcl c Char(1); + Dcl entry Char(5) Var; + Dcl w Char(5) Var; + Dcl res Char(80) Var; + ss=translate(s,' ','[],'); + Call mk_words(ss,words,wn); + dict.key=''; + dict.inx=hi; + Dcl i Bin Fixed(31); + Dcl ii Bin Fixed(8) Unsigned; + Dcl dict(0:300) Char(5) Var; + Dcl dict_size Bin Fixed(31); + Do i=0 To 255; + ii=i; + Unspec(c)=unspec(ii); + dict(i)=c; + End; + dict_size=256; + ww=words(1); + w=dict(ww); + res=w; + Do i=2 To wn; + ww=words(i); + Select; + When(dict(ww)^='') + entry=dict(ww); + When(ww=dict_size) + entry=w!!substr(w,1,1); + Otherwise + Put Edit('Bad compressed k: ',ww)(Skip,a,a); + End; + res=res!!entry; + dict(dict_size)=w!!substr(entry,1,1); + dict_size+=1; + w=entry; + End; + Return(res); + End; + + mk_words: Proc(st,arr,arrn); + Dcl st Char(*) Var; + Dcl sv Char(80) Var; + Dcl arr(*) Char(5) Var; + Dcl arrn Bin fixed(31); + Dcl elem Char(5) Var; + arrn=0; + sv=st!!' '; + elem=''; + Do While(length(sv)>0); + If left(sv,1)=' ' Then Do; + If elem>'' Then Do; + arrn+=1; + arr(arrn)=elem; + elem=''; + End; + End; + Else + elem=elem!!left(sv,1); + sv=substr(sv,2); + End; + End; + Return; + + End; diff --git a/Task/LZW-compression/Perl-6/lzw-compression.pl6 b/Task/LZW-compression/Perl-6/lzw-compression.pl6 index 382a381b14..9eb1dd9c33 100644 --- a/Task/LZW-compression/Perl-6/lzw-compression.pl6 +++ b/Task/LZW-compression/Perl-6/lzw-compression.pl6 @@ -1,4 +1,4 @@ -sub compress(Str $uncompressed --> List) { +sub compress(Str $uncompressed --> Seq) { my $dict-size = 256; my %dictionary = (.chr => .chr for ^$dict-size); diff --git a/Task/LZW-compression/REXX/lzw-compression.rexx b/Task/LZW-compression/REXX/lzw-compression.rexx index 09790ba09e..6ba58422e1 100644 --- a/Task/LZW-compression/REXX/lzw-compression.rexx +++ b/Task/LZW-compression/REXX/lzw-compression.rexx @@ -1,5 +1,5 @@ /* REXX --------------------------------------------------------------- -* 20.07.2014 Wakter Pachl translated from Java +* 20.07.2014 Walter Pachl translated from Java * 21.07.2014 WP allow for blanks in the string *--------------------------------------------------------------------*/ Parse Arg str diff --git a/Task/Langtons-ant/Chapel/langtons-ant.chapel b/Task/Langtons-ant/Chapel/langtons-ant.chapel new file mode 100644 index 0000000000..34198aaf69 --- /dev/null +++ b/Task/Langtons-ant/Chapel/langtons-ant.chapel @@ -0,0 +1,68 @@ +config const gridHeight: int = 100; +config const gridWidth: int = 100; + +class PBMWriter { + var imgDomain: domain(2); + var imgData: [imgDomain] int; + + proc PBMWriter( height: int, width: int ){ + imgDomain = { 1..#height, 1..#width }; + } + + proc this( i : int, j : int) ref : int{ + return this.imgData[ i, j ]; + } + + proc writeImage( fileName: string ){ + var file = open(fileName, iomode.cw); + var writingChannel = file.writer(); + writingChannel.write("P1\n", imgDomain.dim(1).size, " " ,imgDomain.dim(2).size,"\n"); + + for px in imgData { + writingChannel.write( px, " " ); + } + + writingChannel.write( "\n" ); + writingChannel.flush(); + writingChannel.close(); + } + +} + +enum Color { white, black }; + +inline proc nextDirection( position: 2*int, turnLeft: bool ): 2*int { + return ( (if turnLeft then 1 else -1 ) * position[2], (if turnLeft then -1 else 1 ) * position[1] ); +} + +proc <( left: 2*int, right: 2*int ){ + return left[1] < right[1] && left[2] < right[2]; +} + +proc <=( left: 2*int, right: 2*int ){ + return left[1] <= right[1] && left[2] <= right[2]; +} + +proc main{ + const gridDomain: domain(2) = {1..#gridHeight, 1..#gridWidth}; + var grid: [gridDomain] Color; + + var antPos = ( gridHeight / 2, gridWidth / 2 ); + var antDir = (1,0); // start up; + + while (0,0) < antPos && antPos <= (gridHeight, gridWidth ) { + var currColor = grid[ antPos ]; + grid[antPos] = if currColor == Color.white then Color.black else Color.white ; + + antDir = nextDirection( antDir, currColor == Color.black ); + antPos = antPos + antDir; + } + + var image = new PBMWriter( height = gridHeight, width = gridWidth ); + + for (i, j) in gridDomain { + image[i,j] = if grid[gridHeight-j+1,gridHeight-i+1] == Color.black then 0 else 1; + } + + image.writeImage( "output.png" ); +} diff --git a/Task/Langtons-ant/Elixir/langtons-ant.elixir b/Task/Langtons-ant/Elixir/langtons-ant.elixir new file mode 100644 index 0000000000..7a95e8f373 --- /dev/null +++ b/Task/Langtons-ant/Elixir/langtons-ant.elixir @@ -0,0 +1,29 @@ +defmodule Langtons do + def ant(sizex, sizey) do + {px, py} = {div(sizex,2), div(sizey,2)} # start position + move(HashSet.new, sizex, sizey, px, py, {1,0}, 0) + end + + defp move(plane, sx, sy, px, py, _, step) when px<0 or sx + Enum.map(0..sx, fn i -> + if Set.member?(plane, {i,j}), do: "#", else: "." + end) |> Enum.join |> IO.puts + end) + end +end + +Langtons.ant(100, 100) diff --git a/Task/Langtons-ant/Fortran/langtons-ant-1.f b/Task/Langtons-ant/Fortran/langtons-ant-1.f new file mode 100644 index 0000000000..1fbed93595 --- /dev/null +++ b/Task/Langtons-ant/Fortran/langtons-ant-1.f @@ -0,0 +1,48 @@ +program Langtons_Ant + implicit none + + integer, parameter :: csize = 100 + integer :: direction = 0, maxsteps = 20000 + integer :: i, x, y + logical :: cells(csize,csize) = .true. + logical :: cflag + + x = csize / 2; y = x + + do i = 1, maxsteps + cflag = cells(x,y) + if(cflag) then + direction = direction + 1 + if(direction == 4) direction = direction - 4 + else + direction = direction - 1 + if(direction == -1) direction = direction + 4 + end if + + cells(x,y) = .not. cells(x,y) + + select case(direction) + case(0) + y = y - 1 + case(1) + x = x + 1 + case(2) + y = y + 1 + case(3) + x = x - 1 + end select + + if(x < 1 .or. x > csize .or. y < 1 .or. y > csize) exit + end do + + do y = 1, csize + do x = 1, csize + if(cells(x,y)) then + write(*, "(a)", advance="no") "." + else + write(*, "(a)", advance="no") "#" + end if + end do + write(*,*) + end do +end program diff --git a/Task/Langtons-ant/Fortran/langtons-ant-2.f b/Task/Langtons-ant/Fortran/langtons-ant-2.f new file mode 100644 index 0000000000..6358c0283d --- /dev/null +++ b/Task/Langtons-ant/Fortran/langtons-ant-2.f @@ -0,0 +1,46 @@ + PROGRAM LANGTONSANT +C Langton's ant wanders across an initially all-white board, stepping one cell at a go. +C If the current cell is white, it becomes black and the ant turns right. +C If the current cell is black, it becomes white and the ant turns left. +C The ant advances one cell in its latest direction, and reconsiders. + INTEGER ENUFF + PARAMETER (ENUFF = 100) !Said to be so. + CHARACTER*1 CELL(ENUFF,ENUFF) !The work area. + COMPLEX WAY,PLACE !A direction and a position. + INTEGER X,Y,XN,Y1 !Integer versions. + INTEGER STEP !A counter. + CELL = "" !Clear for action. + PLACE = CMPLX(ENUFF/2,ENUFF/2) !Start at the middle. + WAY = (1,0) !Initial direction is +x. +Commence wandering. + DO STEP = 1,20000 !Enough to be going on with. + X = REAL(PLACE) !Change languages. + Y = AIMAG(PLACE) !Could mess about with EQUIVALENCE... + IF (X.LE.0 .OR. X.GT.ENUFF !Are we still + 1 .OR.Y.LE.0 .OR. Y.GT.ENUFF) THEN!Within bounds? + WRITE (6,1) STEP - 1,X,Y !No! Offer details. + 1 FORMAT ("Step ",I0," to (",I0,",",I0,") is out of bounds!") + EXIT !And wander no further. + END IF !But, if we're within bounds, + IF (CELL(X,Y).NE."#") THEN !Consider our position. + CELL(X,Y) = "#" !A blank cell becomes black. Ish. + WAY = WAY*(0,-1) !Turn right. + ELSE !Otherwise, + CELL(X,Y) = "+" !A black cell becomes white. Ish. + WAY = WAY*(0,+1) !Turn left. + END IF !So much for changing direction. + PLACE = PLACE + WAY !Advance one step. + END DO !On to the next step. +Consider the bounds... + DO Y1 = 1,ENUFF !Work up from the bottom. + IF (ANY(CELL(:,Y1).NE." ")) EXIT !The last line with a splot. + END DO !Subsequent lines would be blank. + DO XN = ENUFF,1,-1 !Work back from the right hand side. + IF (ANY(CELL(XN,:).NE." ")) EXIT !The last column with a splot. + END DO !Subsequent columns would be blank. +Cast forth the splotches. + DO Y = ENUFF,Y1,-1 !The topmost y-coordinate first! + WRITE (6,"(666A1)") CELL(1:XN,Y) !Roll a line's worth. + END DO !On to the next line. +Completed. + END diff --git a/Task/Langtons-ant/Fortran/langtons-ant.f b/Task/Langtons-ant/Fortran/langtons-ant.f deleted file mode 100644 index ae7b442824..0000000000 --- a/Task/Langtons-ant/Fortran/langtons-ant.f +++ /dev/null @@ -1,35 +0,0 @@ -program langtons_ant - implicit none - - integer, parameter :: dp = selected_real_kind(15,300) - real(kind=dp), parameter :: pi = 3.1415926535897932_dp - - integer, parameter :: grid_size = 100 - integer, dimension(:,:), allocatable :: grid - integer, dimension(3) :: ant = (/ grid_size/2, grid_size/2, 0 /) - integer :: i - - allocate(grid(1:grid_size, 1:grid_size)) - grid = 1 !Grid initially white - - do - grid(ant(1) , ant(2)) = -grid(ant(1) , ant(2)) ! Flip the color of the current square - ant(3) = modulo(ant(3) + grid(ant(1),ant(2)),4) ! Rotate the ant depending on the current square - ant(1) = ant(1) + nint( sin(ant(3) * pi / 2.0_dp) ) ! Move the ant in x - ant(2) = ant(2) + nint( cos(ant(3) * pi / 2.0_dp) ) ! Move the ant in y - - !exit if the ant is outside the grid - if (((ant(1) < 1) .or. (ant(1) > grid_size)) .or. ((ant(2) < 1) .or. (ant(2) > grid_size))) exit - - end do - - !Print out the final grid - open(unit=21, file="ant.dat") - do i = 1, grid_size - write(21,*) int(grid(:,i) + 1 / 2.0_dp) - end do - close(21) - - deallocate(grid) - -end program langtons_ant diff --git a/Task/Langtons-ant/JavaScript/langtons-ant-4.js b/Task/Langtons-ant/JavaScript/langtons-ant-4.js new file mode 100644 index 0000000000..4b71532e5f --- /dev/null +++ b/Task/Langtons-ant/JavaScript/langtons-ant-4.js @@ -0,0 +1,68 @@ +/////////////////// +// LODASH IMPORT // +/////////////////// + +// import all lodash functions to the main namespace, but isNaN not to cause conflicts +_.each(_.keys(_), k => window[k === 'isNaN' ? '_isNaN' : k] = _[k]); + +const +WORLD_WIDTH = 100, +WORLD_HEIGHT = 100, +PIXEL_SIZE = 4, +DIRTY_COLOR = '#000', +VIRGIN_COLOR = '#fff', +RUNS = 10000, +SPEED = 50, + +// up right down left +DIRECTIONS = [0, 1, 2, 3], + +displayWorld = (world) => each(world, (row, rowidx) => { + each(row, (cell, cellidx) => { + canvas.fillStyle = cell === 1 ? DIRTY_COLOR : VIRGIN_COLOR; + canvas.fillRect(rowidx * PIXEL_SIZE, cellidx * PIXEL_SIZE, PIXEL_SIZE, PIXEL_SIZE); + }); +}), + +moveAnt = (world, ant) => { + world[ant.x][ant.y] = world[ant.x][ant.y] === 1 ? 0 : 1; + ant.dir = DIRECTIONS[(4 + ant.dir + (world[ant.x][ant.y] === 0 ? 1 : -1)) % 4]; + switch (ant.dir) { + case DIRECTIONS[0]: + ant.y -= 1; + break; + case DIRECTIONS[1]: + ant.x -= 1; + break; + case DIRECTIONS[2]: + ant.y += 1; + break; + case DIRECTIONS[3]: + ant.x += 1; + break; + } + + return [world, ant]; +}, + +updateWorld = (world, ant, runs) => { + [world, ant] = moveAnt(world, ant); + displayWorld(world); + + if (runs > 0) setTimeout(partial(updateWorld, world, ant, --runs), SPEED); +}, + +canvas = document.getElementById('c').getContext('2d'); + +let +world = map(range(WORLD_HEIGHT), i => map(range(WORLD_WIDTH), partial(identity, 0))), +ant = { + x: WORLD_WIDTH / 2, + y: WORLD_HEIGHT / 2, + dir: DIRECTIONS[0] +}; + +canvas.canvas.width = WORLD_WIDTH * PIXEL_SIZE; +canvas.canvas.height = WORLD_HEIGHT * PIXEL_SIZE; + +updateWorld(world, ant, RUNS); diff --git a/Task/Langtons-ant/Pascal/langtons-ant.pascal b/Task/Langtons-ant/Pascal/langtons-ant.pascal new file mode 100644 index 0000000000..5fb169da04 --- /dev/null +++ b/Task/Langtons-ant/Pascal/langtons-ant.pascal @@ -0,0 +1,113 @@ +{$B- Early and safe resolution of If x <> 0 and 1/x...} +Program LangtonsAnt; Uses CRT; +{Perpetrated by R.N.McLean (whom God preserve), Victoria University, December MMXV.} + Var AsItWas: record mode: word; ta: word; end; + Var LastLine,LastCol: byte; + + Procedure Swap(var a,b: integer); {Oh for a compiler-recognised statement.} + var t: integer; {Such as A=:=B;} + Begin + t:=a; a:=b; b:=t; + End; + + var Stepwise: boolean; + Var Cell: Array[1..80,1..50] of byte; {The screen is of limited size, alas.} + Var x,y,Step: integer; {In the absence of complex numbers,} + Var dx,dy: integer; {And also of array action statements.} + + Procedure Croak(Gasp: string); {Exit message...} + Begin + GoToXY(1,12); TextColor(Yellow); {Reserve line twelve.} + WriteLn(Gasp,' on step ',Step,' to (',x,',',y,')'); + HALT; + End; + + Procedure Harken; {Waits for a keystroke.} + var ch: char; {The character. Should really be 16-bit.} + Begin + ch:=ReadKey; {Fancy keys evoke double characters. I don't care.} + if (ch = 'S') or (ch = 's') then Stepwise:=not Stepwise {Quick, slow, quick, quick, slow...} + else if ch = #27 then Croak('ESC!'); {Or perhaps, enough already!} + End; {Fancy keys will give a twostep.} + Procedure Waitabit; {Slows the action.} + Begin + if Stepwise or KeyPressed then Harken; {Perhaps a change while on the run.} + End; {of Waitabit.} + + Procedure Turn(way:integer); {(dx,dy)*(0,w) = (-w*dy,+w*dx)} + Begin + Swap(dx,dy); {In the absence of complex arithmetic,} + dx:=-way*dx; dy:=way*dy; {Do this in two stages.} + End; + + const Arrow: array[-1..+1,-1..+1] of integer {Only four entries are of interest.} + = ((1,27,3),(25,5,24),(7,26,9)); {For the four arrow symbols.} + Procedure ShowDirection(Enter,How: byte); {Show one.} + Begin + GoToXY(x,LastLine - y + 1); {(x,y) position, in Cartesian style.} + TextBackground(Enter); {The value in Cell[x,y] may have been changed.} + TextColor(How); + Writeln(chr(Arrow[dx,dy])); {Not an ASCII control character, but an arrow symbol.} + Waitabit; {Having gone to all this trouble.} + End; + Procedure ShowState; {Special usage for line two of the screen.} + Begin + GoToXY(1,2); TextBackground(LightGray); TextColor(Black); + Write(Step:5,' (',x:2,',',y:2,') '); + TextColor(Yellow); {Yellow indicates the direction in mind.} + Write(chr(Arrow[dx,dy])); {On *arrival* at a position.} + End; + + Var i,j: integer; {Steppers. No whole-array assault as in Cell:=LightGray;} + var Enter: byte; {Needed to remember the cell state on arrival.} + BEGIN + AsItWas.mode:=LastMode; {Grr. I might want to save the display content too!} + AsItWas.ta:=TextAttr; {Not just its colour and style.} + TextMode(C80+Font8x8); {Crazed gibberish gives less unsquare character cells, and 80x50 of them.} + LastLine:=Hi(WindMax); { + 1 omitted, as a write to the last line scrolls the screen up one...} + LastCol:=Lo(WindMax) + 1; {Counting starts at zero, even though GoToXY starts with one.} + x:=LastCol div 2; {Start somewhere middleish.} + y:=LastLine div 2; {Consider (x,y) as being (0,0) for axes.} + dx:=+1; dy:=0; {Initial direction.} + TextBackground(LightGray); {"White" is not valid for background colour.} + TextColor(Black); {This will show up on a light background.} + ClrScr; {Here we go.} + + WriteLn('Langton''s Ant, on x = 1:',LastCol,', y = 1:',LastLine); + ShowState; {Where we start.} + WriteLn; TextColor(Black); + WriteLn('Press a key for each step.'); {Some encouragement.} + WriteLn('"S" to pause each step or not.'); + WriteLn('ESC to quit.'); + + for i:=1 to LastLine do begin GoToXY(x,i); Write('|'); end; {Draw a y-axis.} + for i:=1 to LastCol do begin GoToXY(i,LastLine - y + 1); Write('-'); end; {And x.} + gotoxy(1,6); {Can't silence the cursor!} + + for i:=1 to LastCol do {Prepare the cells.} + for j:=1 to LastLine do {One by one.} + Cell[i,j]:=LightGray; {Cell:=LightGray. Sigh.} + + Stepwise:=true; {The action is of interest.} + for Step:=1 to 12000 do {Here we go.} + if (x <= 0) or (x > LastCol) or (y <= 0) or (y > LastCol) then Croak('Out of bounds') + else {We're in a cell.} + begin {So, inspect it.} + if Stepwise or (Step mod 10 = 0) then ShowState {On arrival.} + else if KeyPressed then Harken; {If we're not pausing, check for a key poke.} + Enter:=cell[x,y]; {This is what awaits the feet.} + if Stepwise then ShowDirection(Enter,Yellow); {Current direction, about to be changed.} + case cell[x,y] of {So, what to do?} + LightGray: begin Cell[x,y]:=Black; Turn(-1); end;{White. Make black and turn right.} + Black: begin Cell[x,y]:=LightGray; Turn(+1); end;{Black. Make white and turn left.} + end; {Having decided,} + if Stepwise then ShowDirection(Enter,Green); {Show the direction about to be stepped.} + GoToXY(x,LastLine - y + 1); {Screen location (column,line) for (x,y)} + TextBackground(Cell[x,y]); {Change the state I'm about to leave.} + Write(' '); {Foreground colour irrelevant for spaces.} + x:=x + dx; y:=y + dy; {Make the step!} + end; {On to consider our new position.} + + Croak('Finished'); {That was fun.} + + END. diff --git a/Task/Langtons-ant/Rust/langtons-ant.rust b/Task/Langtons-ant/Rust/langtons-ant.rust index a8af4354e5..3d70d8520a 100644 --- a/Task/Langtons-ant/Rust/langtons-ant.rust +++ b/Task/Langtons-ant/Rust/langtons-ant.rust @@ -1,76 +1,77 @@ struct Ant { - x: uint, - y: uint, - dir: Direction + x: usize, + y: usize, + dir: Direction } -impl Ant { - fn move(&mut self, vec: &mut Vec>) { +#[derive(Clone,Copy)] +enum Direction { + North, + East, + South, + West +} - let pointer = vec.get_mut(self.y).get_mut(self.x); - //change direction - match *pointer { - 0 => self.dir = self.dir.right(), - 1 => self.dir = self.dir.left(), - _ => fail!("Unexpected colour in grid") - } - //flip colour - //if it's 1 it's black - //if it's 0 it's white - *pointer ^= 1; +use Direction::*; - //move direction - match self.dir { - North => self.y -= 1, - South => self.y += 1, - East => self.x += 1, - West => self.x -= 1, - } +impl Ant { + fn mv(&mut self, vec: &mut Vec>) { + let pointer = &mut vec[self.y][self.x]; + //change direction + match *pointer { + 0 => self.dir = self.dir.right(), + 1 => self.dir = self.dir.left(), + _ => panic!("Unexpected colour in grid") + } + //flip colour + //if it's 1 it's black + //if it's 0 it's white + *pointer ^= 1; - } -} + //move direction + match self.dir { + North => self.y -= 1, + South => self.y += 1, + East => self.x += 1, + West => self.x -= 1, + } -enum Direction { - North, - East, - South, - West + } } impl Direction { - fn right(self) -> Direction { - match self { - North => East, - East => South, - South => West, - West => North, - } - } + fn right(self) -> Direction { + match self { + North => East, + East => South, + South => West, + West => North, + } + } - fn left(self) -> Direction { - //3 rights equal a left - self.right().right().right() - } + fn left(self) -> Direction { + //3 rights equal a left + self.right().right().right() + } } fn main(){ - //create a 100x100 grid using vectors - let mut grid: Vec> = Vec::from_elem(100, Vec::from_elem(100, 0u8)); - let mut ant = Ant { - x: 50, y: 50, dir: North - }; + //create a 100x100 grid using vectors + let mut grid: Vec> = vec![vec![0; 100]; 100]; + let mut ant = Ant { + x: 50, y: 50, dir: Direction::North + }; - while ant.x < 100 && ant.y < 100 { - ant.move(&mut grid); - } - for each in grid.iter() { - //construct string - //using iterator methods to quickly convert the vector - //to a string - let string = each.iter() - .map(|&x| String::from_byte(x+32)) - .fold(String::new(), |x, y| x+y) - .replace("!", "#"); - println!("{}", string); - } + while ant.x < 100 && ant.y < 100 { + ant.mv(&mut grid); + } + for each in grid.iter() { + //construct string + //using iterator methods to quickly convert the vector + //to a string + let string = each.iter() + .map(|&x| if x == 0 { " " } else { "#" }) + .fold(String::new(), |x, y| x+y); + println!("{}", string); + } } diff --git a/Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints.lisp b/Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints.lisp new file mode 100644 index 0000000000..9d56e057e3 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints.lisp @@ -0,0 +1,24 @@ +;; Sort criteria is by most significant digit with least digits used as a tie +;; breaker + +(defun largest-msd-with-less-digits (x y) + (flet ((first-digit (x) + (digit-char-p (aref x 0)))) + (cond ((> (first-digit x) + (first-digit y)) + t) + ((> (first-digit y) + (first-digit x)) + nil) + ((and (= (first-digit x) + (first-digit y)) + (> (length x) + (length y))) + nil) + (t t)))) + +(loop + :for input :in '((54 546 548 60) (1 34 3 98 9 76 45 4)) + :do (format t "~{~A~}~%" + (sort (mapcar #'write-to-string input) + #'largest-msd-with-less-digits))) diff --git a/Task/Largest-int-from-concatenated-ints/Elixir/largest-int-from-concatenated-ints.elixir b/Task/Largest-int-from-concatenated-ints/Elixir/largest-int-from-concatenated-ints.elixir new file mode 100644 index 0000000000..c21ff17612 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Elixir/largest-int-from-concatenated-ints.elixir @@ -0,0 +1,9 @@ +defmodule RC do + def largest_int(list) do + sorted = Enum.sort(list, fn x,y -> "#{x}#{y}" >= "#{y}#{x}" end) + Enum.join(sorted) + end +end + +IO.inspect RC.largest_int [1, 34, 3, 98, 9, 76, 45, 4] +IO.inspect RC.largest_int [54, 546, 548, 60] diff --git a/Task/Largest-int-from-concatenated-ints/Julia/largest-int-from-concatenated-ints.julia b/Task/Largest-int-from-concatenated-ints/Julia/largest-int-from-concatenated-ints.julia new file mode 100644 index 0000000000..51cef06e81 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Julia/largest-int-from-concatenated-ints.julia @@ -0,0 +1,18 @@ +function maxconcat{T<:Integer}(a::Array{T,1}) + b = map(string, a) + b = sort(b, lt=(x,y)->x*y < y*x, rev=true) + b = join(b, "") + try + b = parseint(b) + catch + b = parseint(BigInt, b) + end +end + +tests = {[1, 34, 3, 98, 9, 76, 45, 4], + [54, 546, 548, 60], + [1, 34, 3, 98, 9, 76, 45, 4, 54, 546, 548, 60]} + +for t in tests + println("Maxconcating ", t) + println(" ", maxconcat(t)) diff --git a/Task/Largest-int-from-concatenated-ints/Kotlin/largest-int-from-concatenated-ints.kotlin b/Task/Largest-int-from-concatenated-ints/Kotlin/largest-int-from-concatenated-ints.kotlin new file mode 100644 index 0000000000..9cbf899f2a --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Kotlin/largest-int-from-concatenated-ints.kotlin @@ -0,0 +1,19 @@ +import java.util.Comparator + +val SORTER = Comparator { x, y -> + val xy = (x.toString() + y).toInt() + val yx = (y.toString() + x).toInt() + return@Comparator xy.compareTo(yx) +} + +fun maxCat() { + fun findLargestSequence(array: Array): String { + return array.sortBy(SORTER).reverse().map { it.toString() }.join(separator = "") + } // Not using specialized IntArray as it does not have sortBy + + val source1 = arrayOf(1, 34, 3, 98, 9, 76, 45, 4) + println(findLargestSequence(source1)) + + val source2 = arrayOf(54, 546, 548, 60); + println(findLargestSequence(source2)) +} diff --git a/Task/Largest-int-from-concatenated-ints/VBScript/largest-int-from-concatenated-ints.vb b/Task/Largest-int-from-concatenated-ints/VBScript/largest-int-from-concatenated-ints.vb new file mode 100644 index 0000000000..9f331262ee --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/VBScript/largest-int-from-concatenated-ints.vb @@ -0,0 +1,24 @@ +Function largestint(list) + nums = Split(list,",") + Do Until IsSorted = True + IsSorted = True + For i = 0 To UBound(nums) + If i <> UBound(nums) Then + a = nums(i) + b = nums(i+1) + If CLng(a&b) < CLng(b&a) Then + tmpnum = nums(i) + nums(i) = nums(i+1) + nums(i+1) = tmpnum + IsSorted = False + End If + End If + Next + Loop + For j = 0 To UBound(nums) + largestint = largestint & nums(j) + Next +End Function + +WScript.StdOut.Write largestint(WScript.Arguments(0)) +WScript.StdOut.WriteLine diff --git a/Task/Last-Friday-of-each-month/00DESCRIPTION b/Task/Last-Friday-of-each-month/00DESCRIPTION index 2d440ae9c3..8b69bcdf21 100644 --- a/Task/Last-Friday-of-each-month/00DESCRIPTION +++ b/Task/Last-Friday-of-each-month/00DESCRIPTION @@ -21,4 +21,4 @@ Example of an expected output: ;Cf.: * [[Five weekends]] * [[Day of the week]] -* [[Find last sunday of each month]] +* [[Find the last Sunday of each month]] diff --git a/Task/Last-Friday-of-each-month/Befunge/last-friday-of-each-month.bf b/Task/Last-Friday-of-each-month/Befunge/last-friday-of-each-month.bf new file mode 100644 index 0000000000..89954db016 --- /dev/null +++ b/Task/Last-Friday-of-each-month/Befunge/last-friday-of-each-month.bf @@ -0,0 +1,6 @@ +":raeY",,,,,&>55+,:::45*:*%\"d"%!*\4%+!3v +v2++1**"I"5\+/*:*54\-/"d"\/4::-1::p53+g5< +>:00p5g4-+7%\:0\v>,"-",5g+:55+/68*+,55+%v +^<<_$$vv*86%+55:<^+*86%+55,+*86/+55:-1:<6 +>$$^@$<>+\55+/:#^_$>:#,_$"-",\:04-\-00g^8 +^<# #"#"##"#"##!` +76:+1g00,+55,+*< diff --git a/Task/Last-Friday-of-each-month/Elixir/last-friday-of-each-month.elixir b/Task/Last-Friday-of-each-month/Elixir/last-friday-of-each-month.elixir new file mode 100644 index 0000000000..5a5c340aa2 --- /dev/null +++ b/Task/Last-Friday-of-each-month/Elixir/last-friday-of-each-month.elixir @@ -0,0 +1,15 @@ +defmodule RC do + def lastFriday(year) do + Enum.map(1..12, fn month -> + lastday = :calendar.last_day_of_the_month(year, month) + daynum = :calendar.day_of_the_week(year, month, lastday) + friday = lastday - rem(daynum + 2, 7) + {year, month, friday} + end) + end +end + +y = String.to_integer(hd(System.argv)) +Enum.each(RC.lastFriday(y), fn {year, month, day} -> + :io.format "~4b-~2..0w-~2..0w~n", [year, month, day] +end) diff --git a/Task/Last-Friday-of-each-month/Haskell/last-friday-of-each-month.hs b/Task/Last-Friday-of-each-month/Haskell/last-friday-of-each-month.hs index fa92c41cae..8174d03341 100644 --- a/Task/Last-Friday-of-each-month/Haskell/last-friday-of-each-month.hs +++ b/Task/Last-Friday-of-each-month/Haskell/last-friday-of-each-month.hs @@ -1,26 +1,18 @@ -module Rosettatask - where import Data.Time.Calendar import Data.Time.Calendar.WeekDate -findFriday :: Day -> Day -findFriday date = head $ filter isFriday $ map toDate [0, -1 .. -7] - where - toDate :: Integer -> Day - toDate ago = addDays ago date - isFriday :: Day -> Bool - isFriday theDate = d == 5 - where - (_ , _ , d ) = toWeekDate theDate +findFriday date = head $ filter isFriday $ map toDate [-6 .. 0] + where + toDate ago = addDays ago date + isFriday theDate = let (_ , _ , day) = toWeekDate theDate + in day == 5 -fridayDates :: Integer -> [String] -fridayDates year = map ( showGregorian . findFriday ) lastDaysInMonth - where - lastDaysInMonth = map findLastDay [1 .. 12] - findLastDay month = fromGregorian year month ( gregorianMonthLength - year month ) +fridayDates year = map (showGregorian . findFriday) lastDaysInMonth + where + lastDaysInMonth = map findLastDay [1 .. 12] + findLastDay month = fromGregorian year month (gregorianMonthLength year month) main = do - putStrLn "Please enter a year!" - year <- getLine - mapM_ putStrLn $ fridayDates ( read year ) + putStrLn "Please enter a year!" + year <- getLine + mapM_ putStrLn $ fridayDates (read year) diff --git a/Task/Last-Friday-of-each-month/Julia/last-friday-of-each-month.julia b/Task/Last-Friday-of-each-month/Julia/last-friday-of-each-month.julia new file mode 100644 index 0000000000..cc5cd7a56f --- /dev/null +++ b/Task/Last-Friday-of-each-month/Julia/last-friday-of-each-month.julia @@ -0,0 +1,25 @@ +isdefined(:Date) || using Dates + +const wday = Dates.Fri +const lo = 1 +const hi = 12 + +print("\nThis script will print the last ", Dates.dayname(wday)) +println("s of each month of the year given.") +println("(Leave input empty to quit.)") + +while true + print("\nYear> ") + y = chomp(readline()) + 0 < length(y) || break + y = try + parseint(y) + catch + println("Sorry, but \"", y, "\" does not compute as a year.") + continue + end + println() + for m in Date(y, lo):Month(1):Date(y, hi) + println(" ", tolast(m, wday)) + end +end diff --git a/Task/Last-Friday-of-each-month/Logo/last-friday-of-each-month.logo b/Task/Last-Friday-of-each-month/Logo/last-friday-of-each-month.logo new file mode 100644 index 0000000000..19864dc702 --- /dev/null +++ b/Task/Last-Friday-of-each-month/Logo/last-friday-of-each-month.logo @@ -0,0 +1,45 @@ +; Determine if a Gregorian calendar year is leap +to leap? :year + output (and + equal? 0 modulo :year 4 + not member? modulo :year 400 [100 200 300] + ) +end + +; Convert Gregorian calendar date to a simple day count from +; RD 1 = January 1, 1 CE +to day_number :year :month :day + local "elapsed make "elapsed difference :year 1 + output (sum product 365 :elapsed + int quotient :elapsed 4 + minus int quotient :elapsed 100 + int quotient :elapsed 400 + int quotient difference product 367 :month 362 12 + ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2 + :day) +end + +; Find the day of the week from a day number, 0 = Sunday through 6 = Saturday +to day_of_week :day_number + output modulo :day_number 7 +end + +; Find the date of the last Friday of a given month +to last_friday :year :month + local "zero make "zero day_number :year :month 0 + local "last make "last day_number :year sum 1 :month 0 + local "wday make "wday day_of_week :last + local "friday make "friday sum :last remainder difference -2 :wday 7 + output difference :friday :zero +end + +local "year +make "year ifelse empty? :command.line 2012 :command.line + +repeat 12 [ + local "month make "month # + local "day make "day last_friday :year :month + if (less? :month 10) [make "month word "0 :month] + print reduce [(word ?1 "- ?2)] (list :year :month :day) +] +bye diff --git a/Task/Last-Friday-of-each-month/UNIX-Shell/last-friday-of-each-month-2.sh b/Task/Last-Friday-of-each-month/UNIX-Shell/last-friday-of-each-month-2.sh index ed7185cf10..074350c43f 100644 --- a/Task/Last-Friday-of-each-month/UNIX-Shell/last-friday-of-each-month-2.sh +++ b/Task/Last-Friday-of-each-month/UNIX-Shell/last-friday-of-each-month-2.sh @@ -1,70 +1,17 @@ #!/bin/sh -# Free code, no limit work -# $Id: lastfridays,v 1.1 2011/11/10 00:48:16 gilles Exp gilles $ +# usage: last_fridays [ year] -# usage : -# lastfridays 2012 # prints last fridays of months of year 2012 +year=${1:-`date +%Y`} # default to current year +month=1 +while [ 12 -ge $month ]; do + # Ensure 2 digits: if we try to strip off 2 characters but it still + # looks the same, that means there was only 1 char, so we'll pad it. + [ "$month" = "${month%??}" ] && month=0$month -debug=${debug:-false} -#debug=true + cal $month $year | awk '{print $6}' | grep . | tail -1 \ + | sed "s@^@$year-$month-@" -epoch_year_day() { - #set -x - x_epoch=`expr ${2:-0} '*' 86400 + 43200` - date --date="${1:-1970}-01-01 UTC $x_epoch seconds" +%s -} - -year_of_epoch() { - date --date="1970-01-01 UTC ${1:-0} seconds" +%Y -} -day_of_epoch() { - LC_ALL=C date --date="1970-01-01 UTC ${1:-0} seconds" +%A -} -date_of_epoch() { - date --date="1970-01-01 UTC ${1:-0} seconds" "+%Y-%m-%d" -} -month_of_epoch() { - date --date="1970-01-01 UTC ${1:-0} seconds" "+%m" -} - -last_fridays() { - year=${1:-2012} - - next_year=`expr $year + 1` - $debug && echo "next_year $next_year" - - current_year=$year - day=0 - previous_month=01 - - while test $current_year != $next_year; do - - $debug && echo "day $day" - - current_epoch=`epoch_year_day $year $day` - $debug && echo "current_epoch $current_epoch" - - current_year=`year_of_epoch $current_epoch` - - current_day=`day_of_epoch $current_epoch` - $debug && echo "current_day $current_day" - - test $current_day = 'Friday' && current_friday=`date_of_epoch $current_epoch` - $debug && echo "current_friday $current_friday" - - current_month=`month_of_epoch $current_epoch` - $debug && echo "current_month $current_month" - - # Change of month => previous friday is the last of month - test "$previous_month" != "$current_month" \ - && echo $previous_friday - - previous_month=$current_month - previous_friday=$current_friday - day=`expr $day + 1` - done -} - -# main -last_fridays ${1:-2012} + # Strip leading zeros to avoid octal interpretation + month=$(( 1 + ${month#0} )) +done diff --git a/Task/Last-Friday-of-each-month/UNIX-Shell/last-friday-of-each-month-3.sh b/Task/Last-Friday-of-each-month/UNIX-Shell/last-friday-of-each-month-3.sh new file mode 100644 index 0000000000..ed7185cf10 --- /dev/null +++ b/Task/Last-Friday-of-each-month/UNIX-Shell/last-friday-of-each-month-3.sh @@ -0,0 +1,70 @@ +#!/bin/sh + +# Free code, no limit work +# $Id: lastfridays,v 1.1 2011/11/10 00:48:16 gilles Exp gilles $ + +# usage : +# lastfridays 2012 # prints last fridays of months of year 2012 + +debug=${debug:-false} +#debug=true + +epoch_year_day() { + #set -x + x_epoch=`expr ${2:-0} '*' 86400 + 43200` + date --date="${1:-1970}-01-01 UTC $x_epoch seconds" +%s +} + +year_of_epoch() { + date --date="1970-01-01 UTC ${1:-0} seconds" +%Y +} +day_of_epoch() { + LC_ALL=C date --date="1970-01-01 UTC ${1:-0} seconds" +%A +} +date_of_epoch() { + date --date="1970-01-01 UTC ${1:-0} seconds" "+%Y-%m-%d" +} +month_of_epoch() { + date --date="1970-01-01 UTC ${1:-0} seconds" "+%m" +} + +last_fridays() { + year=${1:-2012} + + next_year=`expr $year + 1` + $debug && echo "next_year $next_year" + + current_year=$year + day=0 + previous_month=01 + + while test $current_year != $next_year; do + + $debug && echo "day $day" + + current_epoch=`epoch_year_day $year $day` + $debug && echo "current_epoch $current_epoch" + + current_year=`year_of_epoch $current_epoch` + + current_day=`day_of_epoch $current_epoch` + $debug && echo "current_day $current_day" + + test $current_day = 'Friday' && current_friday=`date_of_epoch $current_epoch` + $debug && echo "current_friday $current_friday" + + current_month=`month_of_epoch $current_epoch` + $debug && echo "current_month $current_month" + + # Change of month => previous friday is the last of month + test "$previous_month" != "$current_month" \ + && echo $previous_friday + + previous_month=$current_month + previous_friday=$current_friday + day=`expr $day + 1` + done +} + +# main +last_fridays ${1:-2012} diff --git a/Task/Last-letter-first-letter/Elixir/last-letter-first-letter.elixir b/Task/Last-letter-first-letter/Elixir/last-letter-first-letter.elixir new file mode 100644 index 0000000000..85a37b6a60 --- /dev/null +++ b/Task/Last-letter-first-letter/Elixir/last-letter-first-letter.elixir @@ -0,0 +1,38 @@ +defmodule LastLetter_FirstLetter do + def search(names) do + first = Enum.group_by(names, &String.first/1) + sequences = Enum.reduce(names, [], fn name,acc -> add_name(first, acc, [name]) end) + max = Enum.max_by(sequences, &length/1) |> length + max_seqs = Enum.filter(sequences, fn seq -> length(seq) == max end) + IO.puts "there are #{length(sequences)} possible sequences" + IO.puts "the longest is #{max} names long" + IO.puts "there are #{length(max_seqs)} such sequences. one is:" + hd(max_seqs) |> Enum.with_index |> + Enum.each(fn {name, idx} -> + :io.fwrite " ~2w ~s~n", [idx+1, name] + end) + end + + defp add_name(first, sequences, seq) do + last_letter = String.last(hd(seq)) + potentials = Dict.get(first, last_letter, []) -- seq + if potentials == [] do + [Enum.reverse(seq) | sequences] + else + Enum.reduce(potentials, sequences, fn name, acc -> add_name(first, acc, [name | seq]) end) + end + end +end + +names = ~w( +audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon +cresselia croagunk darmanitan deino emboar emolga exeggcute gabite +girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan +kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine +nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 +porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking +sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko +tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask +) + +LastLetter_FirstLetter.search(names) diff --git a/Task/Last-letter-first-letter/Mathematica/last-letter-first-letter.math b/Task/Last-letter-first-letter/Mathematica/last-letter-first-letter.math new file mode 100644 index 0000000000..174961cb21 --- /dev/null +++ b/Task/Last-letter-first-letter/Mathematica/last-letter-first-letter.math @@ -0,0 +1,21 @@ +longestChain[list_] := + NestWhileList[ + Append @@@ + Select[DeleteDuplicatesBy[ + Tuples[{#, list}], {#[[1, 1]], #[[2]]} &], ! MemberQ @@ # && + StringTake[#[[1, -1]], -1] == StringTake[#[[2]], 1] &] &, + List /@ list, # != {} &][[-2, 1]]; +Print[longestChain[{"audino", "bagon", "baltoy", "banette", "bidoof", + "braviary", "bronzor", "carracosta", "charmeleon", "cresselia", + "croagunk", "darmanitan", "deino", "emboar", "emolga", + "exeggcute", "gabite", "girafarig", "gulpin", "haxorus", + "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff", + "kangaskhan", "kricketune", "landorus", "ledyba", "loudred", + "lumineon", "lunatone", "machamp", "magnezone", "mamoswine", + "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir", + "poliwrath", "poochyena", "porygon2", "porygonz", "registeel", + "relicanth", "remoraid", "rufflet", "sableye", "scolipede", + "scrafty", "seaking", "sealeo", "silcoon", "simisear", "snivy", + "snorlax", "spoink", "starly", "tirtouga", "trapinch", "treecko", + "tyrogue", "vigoroth", "vulpix", "wailord", "wartortle", + "whismur", "wingull", "yamask"}]]; diff --git a/Task/Leap-year/360-Assembly/leap-year.360 b/Task/Leap-year/360-Assembly/leap-year.360 new file mode 100644 index 0000000000..43eca87b4a --- /dev/null +++ b/Task/Leap-year/360-Assembly/leap-year.360 @@ -0,0 +1,18 @@ +LPCK CSECT + USING LPCK,15 + STM 0,12,20(13) STORE CALLER REGS + LM 1,2,0(1) R1 -> CCYY, R2 -> DOUBLE-WORD WORK AREA + PACK 0(8,2),0(4,1) PACK CCYY INTO WORK AREA + CVB 0,0(2) CONVERT TO BINARY (R0 = CCYY) + SRDL 0,32 R0|R1 = CCYY + LA 2,100 R2 = 100 + DR 0,2 DIVIDE BY 100: R0 = YY, R1 = CC + LTR 0,0 YY = 0? + BZ A YES: R0|R1 = CC + SRDL 0,32 NO: R0|R1 = YY +A LA 2,4 R2 = 4 + DR 0,2 DIVIDE BY 4: R0 = REMAINDER, R1 = QUOTIENT + LR 15,0 LOAD REMAINDER: IF 0, THEN LEAP YEAR + LM 0,12,20(13) RESTORE REGS + BR 14 + END diff --git a/Task/Leap-year/AppleScript/leap-year.applescript b/Task/Leap-year/AppleScript/leap-year.applescript index 46c4a23d99..5abd9c77d4 100644 --- a/Task/Leap-year/AppleScript/leap-year.applescript +++ b/Task/Leap-year/AppleScript/leap-year.applescript @@ -1,8 +1,5 @@ on leap_year(y) - if (y mod 100 is equal to 0) then - return (y mod 400 is equal to 0) - end if - return (y mod 4 is equal to 0) + return year mod 4 is equal to 0 and (year mod 100 is not equal to 0 or year mod 400 is equal to 0) end leap_year leap_year(1900) diff --git a/Task/Leap-year/Batch-File/leap-year.bat b/Task/Leap-year/Batch-File/leap-year.bat new file mode 100644 index 0000000000..96710bbefe --- /dev/null +++ b/Task/Leap-year/Batch-File/leap-year.bat @@ -0,0 +1,29 @@ +@echo off + +::The Main Thing... +for %%x in (1900 2046 2012 1600 1800 2031 1952) do ( + call :leap %%x +) +echo. +pause +exit/b +::/The Main Thing... + +::The Function... +:leap +set year=%1 +set /a op1=%year%%%4 +set /a op2=%year%%%100 +set /a op3=%year%%%400 +if not "%op1%"=="0" (goto :no) +if not "%op2%"=="0" (goto :yes) +if not "%op3%"=="0" (goto :no) +:yes +echo. +echo %year% is a leap year. +goto :EOF +:no +echo. +echo %year% is NOT a leap year. +goto :EOF +::/The Function... diff --git a/Task/Leap-year/Befunge/leap-year.bf b/Task/Leap-year/Befunge/leap-year.bf new file mode 100644 index 0000000000..b3530dd4a8 --- /dev/null +++ b/Task/Leap-year/Befunge/leap-year.bf @@ -0,0 +1,5 @@ +0"2("*:3-:1-:2-:"^"-v< +v*%"d"\!%4::,,"is".:<| +>\45*:*%!+#v_ "ton"vv< +v"ear."+550<,,,,*84<$# +>"y pael a ">:#,_$:#@^ diff --git a/Task/Leap-year/Elixir/leap-year.elixir b/Task/Leap-year/Elixir/leap-year.elixir new file mode 100644 index 0000000000..25ea2855a4 --- /dev/null +++ b/Task/Leap-year/Elixir/leap-year.elixir @@ -0,0 +1,2 @@ +leap_year? = fn(year) -> :calendar.is_leap_year(year) end +IO.inspect for y <- 2000..2020, leap_year?.(y), do: y diff --git a/Task/Leap-year/Rust/leap-year.rust b/Task/Leap-year/Rust/leap-year.rust new file mode 100644 index 0000000000..b9d4c96e02 --- /dev/null +++ b/Task/Leap-year/Rust/leap-year.rust @@ -0,0 +1,7 @@ +fn is_leap(year: i32) -> bool { + if year % 100 == 0 { + year % 400 == 0 + } else { + year % 4 == 0 + } +} diff --git a/Task/Leap-year/UNIX-Shell/leap-year-3.sh b/Task/Leap-year/UNIX-Shell/leap-year-3.sh index d67e5d94dc..a11c9bf86b 100644 --- a/Task/Leap-year/UNIX-Shell/leap-year-3.sh +++ b/Task/Leap-year/UNIX-Shell/leap-year-3.sh @@ -1,3 +1,5 @@ -leap() { - cal 02 $1 | grep -q 29 +is_leap() { + local year=$(( 10#${1:?'Missing year'} )) + (( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) )) && return 0 + return 1 } diff --git a/Task/Leap-year/UNIX-Shell/leap-year-4.sh b/Task/Leap-year/UNIX-Shell/leap-year-4.sh new file mode 100644 index 0000000000..d67e5d94dc --- /dev/null +++ b/Task/Leap-year/UNIX-Shell/leap-year-4.sh @@ -0,0 +1,3 @@ +leap() { + cal 02 $1 | grep -q 29 +} diff --git a/Task/Leap-year/VBScript/leap-year.vb b/Task/Leap-year/VBScript/leap-year.vb new file mode 100644 index 0000000000..8ace6ef85d --- /dev/null +++ b/Task/Leap-year/VBScript/leap-year.vb @@ -0,0 +1,17 @@ +Function IsLeapYear(yr) + IsLeapYear = False + If yr Mod 4 = 0 And (yr Mod 400 = 0 Or yr Mod 100 <> 0) Then + IsLeapYear = True + End If +End Function + +'Testing the function. +arr_yr = Array(1900,1972,1997,2000,2001,2004) + +For Each yr In arr_yr + If IsLeapYear(yr) Then + WScript.StdOut.WriteLine yr & " is leap year." + Else + WScript.StdOut.WriteLine yr & " is NOT leap year." + End If +Next diff --git a/Task/Least-common-multiple/ALGOL-68/least-common-multiple.alg b/Task/Least-common-multiple/ALGOL-68/least-common-multiple.alg new file mode 100644 index 0000000000..43116a2b18 --- /dev/null +++ b/Task/Least-common-multiple/ALGOL-68/least-common-multiple.alg @@ -0,0 +1,15 @@ +BEGIN + PROC gcd = (INT m, n) INT : + BEGIN + INT a := ABS m, b := ABS n; + IF a=0 OR b=0 THEN 0 ELSE + WHILE b /= 0 DO INT t = b; b := a MOD b; a := t OD; + a + FI + END; + PROC lcm = (INT m, n) INT : ( m*n = 0 | 0 | ABS (m*n) % gcd (m, n)); + INT m=12, n=18; + printf (($gxg(0)3(xgxg(0))l$, + "The least common multiple of", m, "and", n, "is", lcm(m,n), + "and their greatest common divisor is", gcd(m,n))) +END diff --git a/Task/Least-common-multiple/ALGOL-W/least-common-multiple.alg b/Task/Least-common-multiple/ALGOL-W/least-common-multiple.alg new file mode 100644 index 0000000000..02e490f82b --- /dev/null +++ b/Task/Least-common-multiple/ALGOL-W/least-common-multiple.alg @@ -0,0 +1,9 @@ +begin + integer procedure gcd ( integer value a, b ) ; + if b = 0 then a else gcd( b, a rem abs(b) ); + + integer procedure lcm( integer value a, b ) ; + abs( a * b ) div gcd( a, b ); + + write( lcm( 15, 20 ) ); +end. diff --git a/Task/Least-common-multiple/Assembly/least-common-multiple..as b/Task/Least-common-multiple/Assembly/least-common-multiple..as new file mode 100644 index 0000000000..75f0178c33 --- /dev/null +++ b/Task/Least-common-multiple/Assembly/least-common-multiple..as @@ -0,0 +1,90 @@ +; lcm.asm: calculates the least common multiple +; of two positive integers +; +; nasm x86_64 assembly (linux) with libc +; assemble: nasm -felf64 lcm.asm; gcc lcm.o +; usage: ./a.out [number1] [number2] + + global main + extern printf ; c function: prints formatted output + extern strtol ; c function: converts strings to longs + + section .text + +main: + push rbp ; set up stack frame + + ; rdi contains argc + ; if less than 3, exit + cmp rdi, 3 + jl incorrect_usage + + ; push first argument as number + push rsi + mov rdi, [rsi+8] + mov rsi, 0 + mov rdx, 10 ; base 10 + call strtol + pop rsi + push rax + + ; push second argument as number + push rsi + mov rdi, [rsi+16] + mov rsi, 0 + mov rdx, 10 ; base 10 + call strtol + pop rsi + push rax + + ; pop arguments and call get_gcd + pop rdi + pop rsi + call get_gcd + + ; print value + mov rdi, print_number + mov rsi, rax + call printf + + ; exit + mov rax, 0 ; 0--exit success + pop rbp + ret + +incorrect_usage: + mov rdi, bad_use_string + ; rsi already contains argv + mov rsi, [rsi] + call printf + mov rax, 0 ; 0--exit success + pop rbp + ret + +bad_use_string: + db "Usage: %s [number1] [number2]",10,0 + +print_number: + db "%d",10,0 + +get_gcd: + push rbp ; set up stack frame + mov rax, 0 + jmp loop + +loop: + ; keep adding the first argument + ; to itself until a multiple + ; is found. then, return + add rax, rdi + push rax + mov rdx, 0 + div rsi + cmp rdx, 0 + pop rax + je gcd_found + jmp loop + +gcd_found: + pop rbp + ret diff --git a/Task/Least-common-multiple/Batch-File/least-common-multiple.bat b/Task/Least-common-multiple/Batch-File/least-common-multiple.bat new file mode 100644 index 0000000000..2359ed2b24 --- /dev/null +++ b/Task/Least-common-multiple/Batch-File/least-common-multiple.bat @@ -0,0 +1,18 @@ +@echo off +setlocal enabledelayedexpansion +set num1=12 +set num2=18 + +call :lcm %num1% %num2% +exit /b + +:lcm +if %2 equ 0 ( + set /a lcm = %num1%*%num2%/%1 + echo LCM = !lcm! + pause>nul + goto :EOF +) +set /a res = %1 %% %2 +call :lcm %2 %res% +goto :EOF diff --git a/Task/Least-common-multiple/C++/least-common-multiple.cpp b/Task/Least-common-multiple/C++/least-common-multiple-1.cpp similarity index 100% rename from Task/Least-common-multiple/C++/least-common-multiple.cpp rename to Task/Least-common-multiple/C++/least-common-multiple-1.cpp diff --git a/Task/Least-common-multiple/C++/least-common-multiple-2.cpp b/Task/Least-common-multiple/C++/least-common-multiple-2.cpp new file mode 100644 index 0000000000..00863dcc7b --- /dev/null +++ b/Task/Least-common-multiple/C++/least-common-multiple-2.cpp @@ -0,0 +1,26 @@ +#include +#include +#include + +using namespace std; + +int gcd(int a, int b) { + a = abs(a); + b = abs(b); + while (b != 0) { + tie(a, b) = make_tuple(b, a % b); + } + return a; +} + +int lcm(int a, int b) { + int c = gcd(a, b); + return c == 0 ? 0 : a / c * b; +} + +int main() { + cout << "The least common multiple of 12 and 18 is " << lcm(12, 18) + << " ,\n" + << "and the greatest common divisor " << gcd(12, 18) << " !" << endl; + return 0; +} diff --git a/Task/Least-common-multiple/Elixir/least-common-multiple.elixir b/Task/Least-common-multiple/Elixir/least-common-multiple.elixir new file mode 100644 index 0000000000..fc4c3c569c --- /dev/null +++ b/Task/Least-common-multiple/Elixir/least-common-multiple.elixir @@ -0,0 +1,8 @@ +defmodule RC do + def gcd(a,0), do: abs(a) + def gcd(a,b), do: gcd(b, rem(a,b)) + + def lcm(a,b), do: div(abs(a*b), gcd(a,b)) +end + +IO.puts RC.lcm(-12,15) diff --git a/Task/Least-common-multiple/Excel/least-common-multiple.excel b/Task/Least-common-multiple/Excel/least-common-multiple.excel new file mode 100644 index 0000000000..b9c6d96bab --- /dev/null +++ b/Task/Least-common-multiple/Excel/least-common-multiple.excel @@ -0,0 +1 @@ +=LCM(A1:J1) diff --git a/Task/Least-common-multiple/Fortran/least-common-multiple.f b/Task/Least-common-multiple/Fortran/least-common-multiple.f new file mode 100644 index 0000000000..b9b5538147 --- /dev/null +++ b/Task/Least-common-multiple/Fortran/least-common-multiple.f @@ -0,0 +1,14 @@ + integer function lcm(a,b) + integer:: a,b + lcm = a*b / gcd(a,b) + end function lcm + + integer function gcd(a,b) + integer :: a,b,t + do while (b/=0) + t = b + b = mod(a,b) + a = t + end do + gcd = abs(a) + end function gcd diff --git a/Task/Least-common-multiple/J/least-common-multiple.j b/Task/Least-common-multiple/J/least-common-multiple.j index 069d9a4de5..d3cfcc582a 100644 --- a/Task/Least-common-multiple/J/least-common-multiple.j +++ b/Task/Least-common-multiple/J/least-common-multiple.j @@ -4,7 +4,7 @@ 36 132 *./ 12 18 22 396 - 0 1 0 1 *. 0 0 1 1 NB. for boolean arguments (0 and 1) it is equivalent to "and" + 0 1 0 1 *. 0 0 1 1 NB. for truth valued arguments (0 and 1) it is equivalent to "and" 0 0 0 1 *./~ 0 1 0 0 diff --git a/Task/Least-common-multiple/PowerShell/least-common-multiple-1.psh b/Task/Least-common-multiple/PowerShell/least-common-multiple-1.psh new file mode 100644 index 0000000000..2fce8f4270 --- /dev/null +++ b/Task/Least-common-multiple/PowerShell/least-common-multiple-1.psh @@ -0,0 +1,16 @@ +function gcd ($a, $b) { + function pgcd ($n, $m) { + if($n -le $m) { + if($n -eq 0) {$m} + else{pgcd $n ($m-$n)} + } + else {pgcd $m $n} + } + $n = [Math]::Abs($a) + $m = [Math]::Abs($b) + (pgcd $n $m) +} +function lcm ($a, $b) { + [Math]::Abs($a*$b)/(gcd $a $b) +} +lcm 12 18 diff --git a/Task/Least-common-multiple/PowerShell/least-common-multiple-2.psh b/Task/Least-common-multiple/PowerShell/least-common-multiple-2.psh new file mode 100644 index 0000000000..12cba7a07e --- /dev/null +++ b/Task/Least-common-multiple/PowerShell/least-common-multiple-2.psh @@ -0,0 +1,16 @@ +function gcd ($a, $b) { + function pgcd ($n, $m) { + if($n -le $m) { + if($n -eq 0) {$m} + else{pgcd $n ($m%$n)} + } + else {pgcd $m $n} + } + $n = [Math]::Abs($a) + $m = [Math]::Abs($b) + (pgcd $n $m) +} +function lcm ($a, $b) { + [Math]::Abs($a*$b)/(gcd $a $b) +} +lcm 12 18 diff --git a/Task/Least-common-multiple/Ruby/least-common-multiple-1.rb b/Task/Least-common-multiple/Ruby/least-common-multiple-1.rb index 7f0a74f157..8d74841862 100644 --- a/Task/Least-common-multiple/Ruby/least-common-multiple-1.rb +++ b/Task/Least-common-multiple/Ruby/least-common-multiple-1.rb @@ -1,4 +1,2 @@ -irb(main):001:0> require 'rational' -=> true -irb(main):002:0> 12.lcm 18 +irb(main):001:0> 12.lcm 18 => 36 diff --git a/Task/Least-common-multiple/Ruby/least-common-multiple-2.rb b/Task/Least-common-multiple/Ruby/least-common-multiple-2.rb index d4b3daa320..626f5d21b6 100644 --- a/Task/Least-common-multiple/Ruby/least-common-multiple-2.rb +++ b/Task/Least-common-multiple/Ruby/least-common-multiple-2.rb @@ -1,10 +1,14 @@ +def gcd(m, n) + m, n = n, m % n until n.zero? + m.abs +end + def lcm(*args) args.inject(1) do |m, n| - next 0 if m == 0 or n == 0 - i = m - loop do - break i if i % n == 0 - i += m - end + return 0 if n.zero? + (m * n).abs / gcd(m, n) end end + +p lcm 12, 18, 22 +p lcm 15, 14, -6, 10, 21 diff --git a/Task/Least-common-multiple/TI-83-BASIC/least-common-multiple.ti-83 b/Task/Least-common-multiple/TI-83-BASIC/least-common-multiple.ti-83 index e2c78cc5bf..a8b3de8256 100644 --- a/Task/Least-common-multiple/TI-83-BASIC/least-common-multiple.ti-83 +++ b/Task/Least-common-multiple/TI-83-BASIC/least-common-multiple.ti-83 @@ -1,2 +1,2 @@ -lcm(12, 18) +lcm(12,18 36 diff --git a/Task/Least-common-multiple/VBScript/least-common-multiple.vb b/Task/Least-common-multiple/VBScript/least-common-multiple.vb new file mode 100644 index 0000000000..491b26470b --- /dev/null +++ b/Task/Least-common-multiple/VBScript/least-common-multiple.vb @@ -0,0 +1,30 @@ +Function LCM(a,b) + LCM = POS((a * b)/GCD(a,b)) +End Function + +Function GCD(a,b) + Do + If a Mod b > 0 Then + c = a Mod b + a = b + b = c + Else + GCD = b + Exit Do + End If + Loop +End Function + +Function POS(n) + If n < 0 Then + POS = n * -1 + Else + POS = n + End If +End Function + +i = WScript.Arguments(0) +j = WScript.Arguments(1) + +WScript.StdOut.Write "The LCM of " & i & " and " & j & " is " & LCM(i,j) & "." +WScript.StdOut.WriteLine diff --git a/Task/Left-factorials/00DESCRIPTION b/Task/Left-factorials/00DESCRIPTION index b14535784b..9dbd710359 100644 --- a/Task/Left-factorials/00DESCRIPTION +++ b/Task/Left-factorials/00DESCRIPTION @@ -2,9 +2,9 @@ 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''¡ +:::::::*   !''n''` +:::::::*   !n' +:::::::*   ''n''¡
This Rosetta Code task will be using this formula for ''left factorial'': : !n = \sum_{k=0}^{n-1} k! @@ -17,7 +17,8 @@ Display the left factorials for: 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]] +* 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] +* The Rosetta Code entry: [http://rosettacode.org/wiki/Permutations/Derangements permutations/derangements (subfactorials)] diff --git a/Task/Left-factorials/Common-Lisp/left-factorials.lisp b/Task/Left-factorials/Common-Lisp/left-factorials.lisp new file mode 100644 index 0000000000..8ae1bb5163 --- /dev/null +++ b/Task/Left-factorials/Common-Lisp/left-factorials.lisp @@ -0,0 +1,12 @@ +(defun fact (n) + (reduce #'* (loop for i from 1 to n collect i))) + +(defun left-fac (n) + (reduce #'+ (loop for i below n collect (fact i)))) + +(format t "0 -> 10~&") +(format t "~a~&" (loop for i upto 10 collect (left-fac i))) +(format t "20 -> 110 by 10~&") +(format t "~{~a~&~}" (loop for i from 20 upto 110 by 10 collect (left-fac i))) +(format t "1000 -> 10000 by 1000~&") +(format t "~{~a digits~&~}" (loop for i from 1000 upto 10000 by 1000 collect (length (format nil "~a" (left-fac i))))) diff --git a/Task/Left-factorials/Elixir/left-factorials.elixir b/Task/Left-factorials/Elixir/left-factorials.elixir new file mode 100644 index 0000000000..ca0c87ba18 --- /dev/null +++ b/Task/Left-factorials/Elixir/left-factorials.elixir @@ -0,0 +1,20 @@ +defmodule LeftFactorial do + def calc(0), do: 0 + def calc(n) do + {result, _factorial} = Enum.reduce(1..n, {0, 1}, fn i,{res, fact} -> + {res + fact, fact * i} + end) + result + end +end + +Enum.each(0..10, fn i -> + IO.puts "!#{i} = #{LeftFactorial.calc(i)}" +end) +Enum.each(Enum.take_every(20..110, 10), fn i -> + IO.puts "!#{i} = #{LeftFactorial.calc(i)}" +end) +Enum.each(Enum.take_every(1000..10000, 1000), fn i -> + digits = LeftFactorial.calc(i) |> to_char_list |> length + IO.puts "!#{i} has #{digits} digits" +end) diff --git a/Task/Left-factorials/PicoLisp/left-factorials-1.l b/Task/Left-factorials/PicoLisp/left-factorials-1.l new file mode 100644 index 0000000000..74e27decda --- /dev/null +++ b/Task/Left-factorials/PicoLisp/left-factorials-1.l @@ -0,0 +1,17 @@ +(de n! (N) + (cache '(NIL) N + (if (> 2 N) 1 + (* N (n! (dec N)))))) + +(de !n (Num) + (if (= Num 0) 1 + (sum n! (range 0 (dec Num))))) + +(de pril (List) (mapcar 'println List)) + +(prinl "0-10") +(pril (mapcar '!n (range 0 10))) +(prinl "20 - 110") +(pril (mapcar '!n (range 20 110 10))) +(prinl "length of 1000 - 10000") +(pril (mapcar 'length (mapcar '!n (range 1000 10000 1000)))) diff --git a/Task/Left-factorials/PicoLisp/left-factorials-2.l b/Task/Left-factorials/PicoLisp/left-factorials-2.l new file mode 100644 index 0000000000..2f7fc3d8b9 --- /dev/null +++ b/Task/Left-factorials/PicoLisp/left-factorials-2.l @@ -0,0 +1,34 @@ +0-10 +1 +1 +2 +4 +10 +34 +154 +874 +5914 +46234 +409114 +20 - 110 +128425485935180314 +9157958657951075573395300940314 +20935051082417771847631371547939998232420940314 +620960027832821612639424806694551108812720525606160920420940314 +141074930726669571000530822087000522211656242116439949000980378746128920420940314 +173639511802987526699717162409282876065556519849603157850853034644815111221599509216528920420940314 +906089587987695346534516804650290637694024830011956365184327674619752094289696314882008531991840922336528920420940314 +16695570072624210767034167688394623360733515163575864136345910335924039962404869510225723072235842668787507993136908442336528920420940314 +942786239765826579160595268206839381354754349601050974345395410407078230249590414458830117442618180732911203520208889371641659121356556442336528920420940314 +145722981061585297004706728001906071948635199234860720988658042536179281328615541936083296163475394237524337422204397431927131629058103519228197429698252556442336528920420940314 +1000 - 10000 +2565 +5733 +9128 +12670 +16322 +20062 +23875 +27749 +31678 +35656 diff --git a/Task/Left-factorials/PowerShell/left-factorials.psh b/Task/Left-factorials/PowerShell/left-factorials.psh new file mode 100644 index 0000000000..56e8520474 --- /dev/null +++ b/Task/Left-factorials/PowerShell/left-factorials.psh @@ -0,0 +1,26 @@ +function left-factorial ([BigInt]$n) { + [BigInt]$k, [BigInt]$fact = ([BigInt]::Zero), ([BigInt]::One) + [BigInt]$lfact = ([BigInt]::Zero) + while($k -lt $n){ + if($k -gt ([BigInt]::Zero)) { + $fact = [BigInt]::Multiply($fact, $k) + $lfact = [BigInt]::Add($lfact, $fact) + } else { + $lfact = ([BigInt]::One) + } + $k = [BigInt]::Add($k, [BigInt]::One) + } + $lfact +} +0..9 | foreach{ + "!$_ = $(left-factorial $_)" +} +for($i = 10; $i -le 110; $i += 10) { + "!$i = $(left-factorial $i)" +} +for($i = 1000; $i -le 10000; $i += 1000) { + $digits = [BigInt]::Log10($(left-factorial $i)) + $digits = [Math]::Floor($digits) + 1 + if($digits -gt 1) {"!$i has $digits digits"} + else {"!$i has $digits digit"} +} diff --git a/Task/Left-factorials/Run-BASIC/left-factorials.run b/Task/Left-factorials/Run-BASIC/left-factorials.run new file mode 100644 index 0000000000..5494588a19 --- /dev/null +++ b/Task/Left-factorials/Run-BASIC/left-factorials.run @@ -0,0 +1,20 @@ +a = lftFct(0,10,1) +a = lftFct(20,110,10) +a = lftFct(1000,10000,1000) + +function lftFct(f,t,s) +print :print "------ From ";f;" --To-> ";t;" Step ";s;" -------" +for i = f to t step s + lftFct = 1 + fct = 1 + for j = 1 to i-1 + fct = fct * j + lftFct = lftFct + fct + next j + if i >= 1000 then + print i;" ";len(str$(lftFct));" "digits" + else + print i;" ";lftFct + end if +next i +end function diff --git a/Task/Left-factorials/Scala/left-factorials.scala b/Task/Left-factorials/Scala/left-factorials.scala new file mode 100644 index 0000000000..6d6df6cf5a --- /dev/null +++ b/Task/Left-factorials/Scala/left-factorials.scala @@ -0,0 +1,20 @@ +object LeftFactorial extends App { + + // this part isn't really necessary, it just shows off Scala's ability + // to match the mathematical syntax: !n + implicit class RichInt(n:Int) { + def unary_!() = factorial.take(n).sum + } + + val factorial: Stream[BigInt] = 1 #:: factorial.zip(Stream.from(1)).map(n => n._2 * factorial(n._2 - 1)) + + for (n <- (0 to 10) ++ + (20 to 110 by 10); + value = !n) { + println(s"!${n} = ${value}") + } + for (n <- 1000 to 10000 by 1000; + length = (!n).toString.length) { + println(s"length !${n} = ${length}") + } +} diff --git a/Task/Letter-frequency/ALGOL-68/letter-frequency.alg b/Task/Letter-frequency/ALGOL-68/letter-frequency.alg new file mode 100644 index 0000000000..240514c7f7 --- /dev/null +++ b/Task/Letter-frequency/ALGOL-68/letter-frequency.alg @@ -0,0 +1,26 @@ +BEGIN + [0:max abs char]INT histogram; + FOR i FROM 0 TO max abs char DO histogram[i] := 0 OD; + FILE input file; + STRING input file name = "Letter_frequency.a68"; + IF open (input file, input file name, stand in channel) /= 0 THEN + put (stand error, ("Cannot open ", input file name, newline)); + stop + ELSE + on file end (input file, (REF FILE f) BOOL: (close (f); GOTO finished)) + FI; + DO + STRING s; + get (input file, (s, newline)); + FOR i TO UPB s DO + CHAR c = s[i]; + IF "A" <= c AND c <= "Z" OR "a" <= c AND c <= "z" THEN + histogram[ABS c] PLUSAB 1 + FI + OD + OD; + close (input file); +finished: + FOR i FROM ABS "A" TO ABS "Z" DO printf (($a3xg(0)l$, REPR i, histogram[i])) OD; + FOR i FROM ABS "a" TO ABS "z" DO printf (($a3xg(0)l$, REPR i, histogram[i])) OD +END diff --git a/Task/Letter-frequency/Elixir/letter-frequency.elixir b/Task/Letter-frequency/Elixir/letter-frequency.elixir new file mode 100644 index 0000000000..e7c900f15e --- /dev/null +++ b/Task/Letter-frequency/Elixir/letter-frequency.elixir @@ -0,0 +1,11 @@ +file = hd(System.argv) + +case File.read(file) do + {:ok, binary} -> String.upcase(binary) + |> String.codepoints + |> Enum.filter(fn c -> c =~ ~r/[A-Z]/ end) + |> Enum.reduce(Map.new, fn c,acc -> Dict.update(acc, c, 1, &(&1+1)) end) + |> Enum.sort_by(fn {_k,v} -> -v end) + |> Enum.each(fn {k,v} -> IO.puts "#{k} #{v}" end) + {:error, reason} -> IO.inspect reason +end diff --git a/Task/Letter-frequency/Java/letter-frequency-3.java b/Task/Letter-frequency/Java/letter-frequency-3.java new file mode 100644 index 0000000000..e17b3eb402 --- /dev/null +++ b/Task/Letter-frequency/Java/letter-frequency-3.java @@ -0,0 +1,7 @@ +public static Map countLetters(String filename) throws IOException { + return Files.lines(Paths.get(filename)) + .flatMapToInt(String::chars) + .filter(Character::isLetter) + .boxed() + .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); +} diff --git a/Task/Letter-frequency/REXX/letter-frequency-1.rexx b/Task/Letter-frequency/REXX/letter-frequency-1.rexx index 434b465a05..7aaec46e87 100644 --- a/Task/Letter-frequency/REXX/letter-frequency-1.rexx +++ b/Task/Letter-frequency/REXX/letter-frequency-1.rexx @@ -1,52 +1,42 @@ -/*REXX program counts the occurrences of all characters in a file, */ -/* {all Latin alphabet letters are uppercased for counting letters}. */ - -parse arg fileID . /*That's not a middle dot: · */ -if fileID=='' then fileID='JUNK.TXT' /*¿none specified? Use default.*/ -@.=0 /*wouldn't it be neat to use Θ ? */ -totChars=0 /*count of the total num of chars*/ -totLetters=0 /*count of the total num letters.*/ -indent=left('',20) /*used for indentation of output.*/ - - do j=1 while lines(fileID)\==0 /*read file until cows come home.*/ - rec=linein(fileID) /*get a line/record from the file*/ - - do k=1 for length(rec) /*examine/count each character. */ - totChars=totChars+1 /*bump the count of num of chars.*/ - c=substr(rec,k,1) /*peel off a character from input*/ - x=c2x(c) /*convert the character to hex. */ - @.x=@.x+1 /*bump the character's count. */ - if \datatype(c,'M') then iterate /*if not a letter, get next char*/ - totLetters=totLetters+1 /*bump the [Latin] letter count. */ - upper c /* ◄«««««««««««««««««««───uppercase a Latin character.*/ - x=c2x(c) /*convert uppCase letter ══► hex.*/ - @.up.x=@.up.x+1 /*bump the (Latin) letter's count*/ - end /*k*/ /*this program doesn't use π or Γ*/ - - end /*j*/ /*maybe we're ½ done by now, or ¬*/ - -w=length(totChars) /*used for right-aligning counts.*/ -say 'file ─────' fileId "───── has" j-1 'records.' ; say -say 'file ─────' fileId "───── has" totChars 'characters.' ; say - - do L=0 to 255 /*display none-zero letter counts*/ - y=d2x(L); if @.up.y==0 then iterate /*zero count? Then ignore letter*/ - c=d2c(L) /*C is the char version of a char*/ - say indent "(Latin) letter " c 'count:' right(@.up.y,w) - end /*L*/ /*in a rut, maybe it's a cañon. */ - -say; say 'file ─────' fileId "───── has" totLetters '(Latin) letters.'; say - - do m=0 to 255 /*display none-zero char counts. */ - y=d2x(m); if @.y==0 then iterate /*Zero count? Then ignore char.*/ - c=d2c(m) /*C is the char version of a char*/ - _=right(@.y,w) /*bad place for dithering: ░▒▓█ */ - - select /*make the character viewable. */ - when c<<' ' | m==255 then say indent "'"y"'x character count:" _ - when c==' ' then say indent "blank character count:" _ - otherwise say indent " " c 'character count:' _ - end /*select*/ /*I wish REXX had a Σ function.*/ - end /*m*/ /*255 isn't ∞, but sometimes ∙∙∙ */ - -say; say 'file ─────' fileId "───── has" totChars 'characters.' /*Ω*/ +/*REXX program counts the occurrences of all characters in a file, & note that*/ +/* all Latin alphabet letters are uppercased for counting {Latin} letters.*/ +/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ +abc = 'abcdefghijklmnopqrstuvwxyz' /*define an (Latin or English) alphabet*/ +abcU= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*define an uppercase version of [↑]. */ +parse arg fileID . /*this last char isn't a middle dot: · */ +if fileID=='' then fileID='JUNK.TXT' /*¿none specified? Then use the default*/ +totChars=0; totLetters=0 /*count of all chars and of all letters*/ +pad=left('',18); pad9=left('',18%2) /*used for the indentations of output. */ +@.=0 /*wouldn't it be neat to use Θ instead?*/ + do j=1 while lines(fileID)\==0 /*read the file 'til the cows come home*/ + rec=linein(fileID) /*get a line/record from the input file*/ + /* [↓] process all characters in REC.*/ + do k=1 for length(rec) /*examine/count each of the characters.*/ + totChars=totChars+1 /*bump count of number of characters. */ + c=substr(rec,k,1); @.c=@.c+1 /*Peel off a character; bump its count.*/ + if \datatype(c,'M') then iterate /*Not a Latin letter? Get next char.*/ + totLetters=totLetters+1 /*bump the count for [Latin] letters. */ + upper c /* ◄«««««««««««««««««««««««««««◄ uppercase a Latin character.*/ + @..c=@..c+1 /*bump the (Latin) letter's count. */ + end /*k*/ /*no Greek glyphs: π Γ Σ µ α ß Φ ε δ σ */ + end /*j*/ /*maybe we're ½ done by now, or maybe ¬*/ + LL= '(Latin) letter' +w=length(totChars) /*used for right─aligning the counts. */ +say 'file ─────' fileId "───── has" j-1 'records and has' totLetters LL"s."; say + do L=0 for 256; c=d2c(L) /*display all none─zero letter counts. */ + if @..c==0 then iterate /*A zero count? Then ignore character.*/ + say pad9 LL' ' c " (also" translate(c,abc,abcU)') count:' right(@..c,w) + end /*L*/ /*we may be in a rut, but not a cañyon.*/ + +say; say 'file ─────' fileId "───── has" totChars 'unique characters.' +say + do #=0 for 256; y=d2c(#) /*display all none─zero char counts. */ + if @.y==0 then iterate /*A zero count? Then ignore character.*/ + c=d2c(#); ch=c /*C is the character glyph of a char. */ + if c<<' ' | #==255 then ch= /*don't show control characters or null*/ + if c==' ' then ch='blank' /*show a blank's name.*/ + say pad right(ch,5) " ('"d2x(#,2)"'x character count:" right(@.c,w) + end /*#*/ /*255 isn't quite ∞, but sometimes ∙∙∙ */ +say /*not a good place for dithering: ░▒▓█ */ +say pad pad9 '☼ end─of─list ☼' /*show we are at the end of the list. */ + /*stick a fork in it, we're all done. ☻*/ diff --git a/Task/Letter-frequency/REXX/letter-frequency-2.rexx b/Task/Letter-frequency/REXX/letter-frequency-2.rexx index 9f35f4b744..3cea43ad49 100644 --- a/Task/Letter-frequency/REXX/letter-frequency-2.rexx +++ b/Task/Letter-frequency/REXX/letter-frequency-2.rexx @@ -35,20 +35,20 @@ do L=0 to 255 /* display nonzero letter counts */ c=d2c(l) /* the character in question */ if c.c>0 &, /* was found in the file */ - datatype(c,'M')>0 Then Do /* and is a latin letter */ + datatype(c,'M')>0 Then Do /* and is a Latin letter */ say indent "(Latin) letter " c 'count:' right(c.c,w) /* tell */ totLetters=totLetters+c.c /* increment number of letters */ End End say 'file -----' dsn "----- has" totLetters '(Latin) letters.' - say ' other charactes follow' + say ' other characters follow' other=0 do m=0 to 255 /* now for non-letters */ c=d2c(m) /* the character in question */ y=c2x(c) /* the hex representation */ if c.c>0 &, /* was found in the file */ - datatype(c,'M')=0 Then Do /* and is not a latin letter */ + datatype(c,'M')=0 Then Do /* and is not a Latin letter */ other=other+c.c /* increment count */ _=right(c.c,w) /* prepare output of count */ select /*make the character viewable. */ diff --git a/Task/Letter-frequency/Rust/letter-frequency.rust b/Task/Letter-frequency/Rust/letter-frequency.rust index 55cf1f4062..b9b1a1392f 100644 --- a/Task/Letter-frequency/Rust/letter-frequency.rust +++ b/Task/Letter-frequency/Rust/letter-frequency.rust @@ -1,21 +1,21 @@ -extern crate collections; +#![feature(io)] -use std::io::fs::File; -use std::io::BufferedReader; -use std::os; +use std::collections::HashMap; -fn main() { - let filename = match os::args().len() { - 1 => fail!("You must enter a filename to read line by line"), - _ => os::args()[1] - }; +use std::fs::File; +use std::io::{Read,BufReader}; +use std::env::args; - let file = File::open(&Path::new(filename)); - let mut reader = BufferedReader::new(file); +fn main() { + let filename = args().nth(1).expect("You must enter a filename to read line by line"); + let file = File::open(&filename).unwrap(); + let reader = BufReader::new(file); - let s = input.chars().fold(&mut collections::HashMap::new(), |m, x| { - let r = *m.find(&x).unwrap_or(&0u); m.insert(x, 1 + r); m + let s = reader.chars().map(|rc|rc.unwrap()).fold(&mut HashMap::new(), |m, x: char| { + let r = *m.get(&x).unwrap_or(&0); + m.insert(x, 1 + r); + m }).clone(); - println!("{}", s); + println!("{:?}", s); } diff --git a/Task/Letter-frequency/VBScript/letter-frequency.vb b/Task/Letter-frequency/VBScript/letter-frequency.vb new file mode 100644 index 0000000000..f5da031f08 --- /dev/null +++ b/Task/Letter-frequency/VBScript/letter-frequency.vb @@ -0,0 +1,24 @@ +filepath = "SPECIFY FILE PATH HERE" + +Set objfso = CreateObject("Scripting.FileSystemObject") +Set objdict = CreateObject("Scripting.Dictionary") +Set objfile = objfso.OpenTextFile(filepath,1) + +txt = objfile.ReadAll + +For i = 1 To Len(txt) + char = Mid(txt,i,1) + If objdict.Exists(char) Then + objdict.Item(char) = objdict.Item(char) + 1 + Else + objdict.Add char,1 + End If +Next + +For Each key In objdict.Keys + WScript.StdOut.WriteLine key & " = " & objdict.Item(key) +Next + +objfile.Close +Set objfso = Nothing +Set objdict = Nothing diff --git a/Task/Levenshtein-distance/AppleScript/levenshtein-distance.applescript b/Task/Levenshtein-distance/AppleScript/levenshtein-distance.applescript new file mode 100644 index 0000000000..f4c22b3c6c --- /dev/null +++ b/Task/Levenshtein-distance/AppleScript/levenshtein-distance.applescript @@ -0,0 +1,55 @@ +set dist to findLevenshteinDistance for "sunday" against "saturday" +to findLevenshteinDistance for s1 against s2 + script o + property l : s1 + property m : s2 + end script + if s1 = s2 then return 0 + set ll to length of s1 + set lm to length of s2 + if ll = 0 then return lm + if lm = 0 then return ll + + set v0 to {} + + repeat with i from 1 to (lm + 1) + set end of v0 to (i - 1) + end repeat + set item -1 of v0 to 0 + copy v0 to v1 + + repeat with i from 1 to ll + -- calculate v1 (current row distances) from the previous row v0 + + -- first element of v1 is A[i+1][0] + -- edit distance is delete (i+1) chars from s to match empty t + set item 1 of v1 to i + -- use formula to fill in the rest of the row + repeat with j from 1 to lm + if item i of o's l = item j of o's m then + set cost to 0 + else + set cost to 1 + end if + set item (j + 1) of v1 to min3 for ((item j of v1) + 1) against ((item (j + 1) of v0) + 1) by ((item j of v0) + cost) + end repeat + copy v1 to v0 + end repeat + return item (lm + 1) of v1 +end findLevenshteinDistance + +to min3 for anInt against anOther by theThird + if anInt < anOther then + if theThird < anInt then + return theThird + else + return anInt + end if + else + if theThird < anOther then + return theThird + else + return anOther + end if + end if +end min3 diff --git a/Task/Levenshtein-distance/Elixir/levenshtein-distance.elixir b/Task/Levenshtein-distance/Elixir/levenshtein-distance.elixir new file mode 100644 index 0000000000..e8028302fb --- /dev/null +++ b/Task/Levenshtein-distance/Elixir/levenshtein-distance.elixir @@ -0,0 +1,28 @@ +defmodule Levenshtein do + def distance(a, b) do + ta = String.downcase(a) |> to_char_list |> List.to_tuple + tb = String.downcase(b) |> to_char_list |> List.to_tuple + m = tuple_size(ta) + n = tuple_size(tb) + costs = Enum.reduce(0..m, %{}, fn i,acc -> Dict.put(acc, {i,0}, i) end) + cost2 = Enum.reduce(0..n, costs, fn j,acc -> Dict.put(acc, {0,j}, j) end) + cost3 = Enum.reduce(0..n-1, cost2, fn j, acc -> + Enum.reduce(0..m-1, acc, fn i, map -> + d = if elem(ta, i) == elem(tb, j) do + map[ {i,j} ] + else + Enum.min([ map[ {i , j+1} ] + 1, # deletion + map[ {i+1, j } ] + 1, # insertion + map[ {i , j } ] + 1 ]) # substitution + end + Dict.put(map, {i+1, j+1}, d) + end) + end) + cost3[ {m,n} ] + end +end + +words = ~w(kitten sitting saturday sunday rosettacode raisethysword) +Enum.each(Enum.chunk(words, 2), fn [a,b] -> + IO.puts "distance(#{a}, #{b}) = #{Levenshtein.distance(a,b)}" +end) diff --git a/Task/Levenshtein-distance/Limbo/levenshtein-distance.limbo b/Task/Levenshtein-distance/Limbo/levenshtein-distance.limbo new file mode 100644 index 0000000000..e9b534e81f --- /dev/null +++ b/Task/Levenshtein-distance/Limbo/levenshtein-distance.limbo @@ -0,0 +1,47 @@ +implement Levenshtein; + +include "sys.m"; sys: Sys; + print: import sys; +include "draw.m"; + + +Levenshtein: module { + init: fn(nil: ref Draw->Context, args: list of string); + # Export distance so that this module can be used as either a + # standalone program or as a library: + distance: fn(s, t: string): int; +}; + +init(nil: ref Draw->Context, args: list of string) +{ + sys = load Sys Sys->PATH; + if(!(len args % 2)) { + sys->fprint(sys->fildes(2), "Provide an even number of arguments!\n"); + raise "fail:usage"; + } + args = tl args; + + while(args != nil) { + (s, t) := (hd args, hd tl args); + args = tl tl args; + print("%s <-> %s => %d\n", s, t, distance(s, t)); + } +} + +distance(s, t: string): int +{ + if(s == "") + return len t; + if(t == "") + return len s; + if(s[0] == t[0]) + return distance(s[1:], t[1:]); + a := distance(s[1:], t); + b := distance(s, t[1:]); + c := distance(s[1:], t[1:]); + if(a > b) + a = b; + if(a > c) + a = c; + return a + 1; +} diff --git a/Task/Levenshtein-distance/MATLAB/levenshtein-distance.m b/Task/Levenshtein-distance/MATLAB/levenshtein-distance.m new file mode 100644 index 0000000000..d5620bd911 --- /dev/null +++ b/Task/Levenshtein-distance/MATLAB/levenshtein-distance.m @@ -0,0 +1,30 @@ +function score = levenshtein(s1, s2) +% score = levenshtein(s1, s2) +% +% Calculates the area under the ROC for a given set +% of posterior predictions and labels. Currently limited to two classes. +% +% s1: string +% s2: string +% score: levenshtein distance +% +% Author: Ben Hamner (ben@benhamner.com) +if length(s1) < length(s2) +score = levenshtein(s2, s1); +elseif isempty(s2) +score = length(s1); +else +previous_row = 0:length(s2); +for i=1:length(s1) +current_row = 0*previous_row; +current_row(1) = i; +for j=1:length(s2) +insertions = previous_row(j+1) + 1; +deletions = current_row(j) + 1; +substitutions = previous_row(j) + (s1(i) ~= s2(j)); +current_row(j+1) = min([insertions, deletions, substitutions]); +end +previous_row = current_row; +end +score = current_row(end); +end diff --git a/Task/Levenshtein-distance/Perl-6/levenshtein-distance.pl6 b/Task/Levenshtein-distance/Perl-6/levenshtein-distance.pl6 index 76dcdef3be..c623b62b8d 100644 --- a/Task/Levenshtein-distance/Perl-6/levenshtein-distance.pl6 +++ b/Task/Levenshtein-distance/Perl-6/levenshtein-distance.pl6 @@ -1,17 +1,17 @@ sub levenshtein_distance ( Str $s, Str $t --> Int ) { - my @s = *, $s.comb; - my @t = *, $t.comb; + my @s = *, |$s.comb; + my @t = *, |$t.comb; my @d; - @d[$_][ 0] = $_ for ^@s.end; - @d[ 0][$_] = $_ for ^@t.end; + @d[$_; 0] = $_ for ^@s.end; + @d[ 0; $_] = $_ for ^@t.end; - for 1..@s.end X 1..@t.end -> $i, $j { - @d[$i][$j] = @s[$i] eq @t[$j] - ?? @d[$i-1][$j-1] # No operation required when eq - !! ( @d[$i-1][$j ], # Deletion - @d[$i ][$j-1], # Insertion - @d[$i-1][$j-1], # Substitution + for 1..@s.end X 1..@t.end -> ($i, $j) { + @d[$i; $j] = @s[$i] eq @t[$j] + ?? @d[$i-1; $j-1] # No operation required when eq + !! ( @d[$i-1; $j ], # Deletion + @d[$i ; $j-1], # Insertion + @d[$i-1; $j-1], # Substitution ).min + 1; } diff --git a/Task/Levenshtein-distance/Python/levenshtein-distance-1.py b/Task/Levenshtein-distance/Python/levenshtein-distance-1.py index 9a6d7a053a..7d9e27ef83 100644 --- a/Task/Levenshtein-distance/Python/levenshtein-distance-1.py +++ b/Task/Levenshtein-distance/Python/levenshtein-distance-1.py @@ -1,4 +1,4 @@ -def levenshteinDistance(s1,s2): +def minimumEditDistance(s1,s2): if len(s1) > len(s2): s1,s2 = s2,s1 distances = range(len(s1) + 1) @@ -14,5 +14,5 @@ def levenshteinDistance(s1,s2): distances = newDistances return distances[-1] -print(levenshteinDistance("kitten","sitting")) -print(levenshteinDistance("rosettacode","raisethysword")) +print(minimumEditDistance("kitten","sitting")) +print(minimumEditDistance("rosettacode","raisethysword")) diff --git a/Task/Levenshtein-distance/Python/levenshtein-distance-2.py b/Task/Levenshtein-distance/Python/levenshtein-distance-2.py index e5feb1502b..222e78f1c0 100644 --- a/Task/Levenshtein-distance/Python/levenshtein-distance-2.py +++ b/Task/Levenshtein-distance/Python/levenshtein-distance-2.py @@ -1,13 +1,23 @@ ->>> from functools import lru_cache ->>> @lru_cache(maxsize=4095) -def ld(s, t): - if not s: return len(t) - if not t: return len(s) - if s[0] == t[0]: return ld(s[1:], t[1:]) - l1 = ld(s, t[1:]) - l2 = ld(s[1:], t) - l3 = ld(s[1:], t[1:]) - return 1 + min(l1, l2, l3) +def levenshteinDistance(str1, str2): + m = len(str1) + n = len(str2) + lensum = float(m + n) + d = [] + for i in range(m+1): + d.append([i]) + del d[0][0] + for j in range(n+1): + d[0].append(j) + for j in range(1,n+1): + for i in range(1,m+1): + if str1[i-1] == str2[j-1]: + d[i].insert(j,d[i-1][j-1]) + else: + minimum = min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+2) + d[i].insert(j, minimum) + ldist = d[-1][-1] + ratio = (lensum - ldist)/lensum + return {'distance':ldist, 'ratio':ratio} ->>> print( ld("kitten","sitting"),ld("rosettacode","raisethysword") ) -3 8 +print(levenshteinDistance("kitten","sitting")) +print(levenshteinDistance("rosettacode","raisethysword")) diff --git a/Task/Levenshtein-distance/Python/levenshtein-distance-3.py b/Task/Levenshtein-distance/Python/levenshtein-distance-3.py new file mode 100644 index 0000000000..e5feb1502b --- /dev/null +++ b/Task/Levenshtein-distance/Python/levenshtein-distance-3.py @@ -0,0 +1,13 @@ +>>> from functools import lru_cache +>>> @lru_cache(maxsize=4095) +def ld(s, t): + if not s: return len(t) + if not t: return len(s) + if s[0] == t[0]: return ld(s[1:], t[1:]) + l1 = ld(s, t[1:]) + l2 = ld(s[1:], t) + l3 = ld(s[1:], t[1:]) + return 1 + min(l1, l2, l3) + +>>> print( ld("kitten","sitting"),ld("rosettacode","raisethysword") ) +3 8 diff --git a/Task/Levenshtein-distance/Rust/levenshtein-distance.rust b/Task/Levenshtein-distance/Rust/levenshtein-distance.rust index 2839d7e8cc..206938727a 100644 --- a/Task/Levenshtein-distance/Rust/levenshtein-distance.rust +++ b/Task/Levenshtein-distance/Rust/levenshtein-distance.rust @@ -1,32 +1,31 @@ -// rust 0.8 - fn main() { - let x = levenshtein_distance("kitten", "sitting"); - println!("{}", x); + println!("{}", levenshtein_distance("kitten", "sitting")); + println!("{}", levenshtein_distance("saturday", "sunday")); + println!("{}", levenshtein_distance("rosettacode", "raisethysword")); } -fn levenshtein_distance(word1: &str, word2: &str) -> uint { - let word1_length = word1.len() + 1; - let word2_length = word2.len() + 1; +fn levenshtein_distance(word1: &str, word2: &str) -> usize { + let word1_length = word1.len() + 1; + let word2_length = word2.len() + 1; - let mut matrix = ~[~[0]]; + let mut matrix = vec![vec![0]]; - for i in range(1, word1_length) { matrix[0].push(i); } - for j in range(1, word2_length) { matrix.push(~[j]); } + for i in 1..word1_length { matrix[0].push(i); } + for j in 1..word2_length { matrix.push(vec![j]); } - for j in range(1, word2_length) { - for i in range(1, word1_length) { - let x: uint = if word1[i - 1] == word2[j - 1] { - matrix[j-1][i-1] - } - else { - let min_distance = [matrix[j][i-1], matrix[j-1][i], matrix[j-1][i-1]]; - *min_distance.iter().min().unwrap() + 1 - }; + for j in 1..word2_length { + for i in 1..word1_length { + let x: usize = if word1.chars().nth(i - 1) == word2.chars().nth(j - 1) { + matrix[j-1][i-1] + } + else { + let min_distance = [matrix[j][i-1], matrix[j-1][i], matrix[j-1][i-1]]; + *min_distance.iter().min().unwrap() + 1 + }; - matrix[j].push(x); + matrix[j].push(x); + } } - } - matrix[word2_length-1][word1_length-1] + matrix[word2_length-1][word1_length-1] } diff --git a/Task/Linear-congruential-generator/ALGOL-68/linear-congruential-generator.alg b/Task/Linear-congruential-generator/ALGOL-68/linear-congruential-generator.alg new file mode 100644 index 0000000000..0749347da7 --- /dev/null +++ b/Task/Linear-congruential-generator/ALGOL-68/linear-congruential-generator.alg @@ -0,0 +1,79 @@ +BEGIN +COMMENT + Algol 68 Genie checks for integer overflow whereas the reference + language leaves the result undefined so for portability we need to + see how wide a variable must be to hold the maximum possible value + before range reduction. This occurs in the BSD RNG when + rseed=2147483647 and is therefore 2147483647 * 1103515245 + 12345 = + 2369780942852710860, which itself is 19 decimal digits. Use + evironmental queries to determine the width needed. +COMMENT + MODE RANDINT = UNION (INT, LONG INT, LONG LONG INT); + RANDINT rseed := (int width > 18 | 0 |: + long int width > 18 | + LONG 0 | LONG LONG 0); + PROC srand = (INT x) VOID : + (rseed | (INT): rseed := x, + (LONG INT): rseed := LENG x | rseed := LENG LENG x); + PROC bsd rand = INT : + BEGIN + CASE rseed IN + (INT ri): + BEGIN + INT a = 1103515245, c = 12345, m1 = 2^16, m2 = 2^15; +COMMENT + That curious declaration is because 2^31 might overflow during + compilation but the MODE declaration for RANDINT guarantees that it + will not overflow at run-time. We assume that an INT is at least + 32 bits wide, otherwise a similar workaround would be needed for + the declaration of a. +COMMENT + INT result = (ri * a + c) MOD (m1 * m2); rseed := result; + result + END, + (LONG INT rli): + BEGIN + LONG INT a = LONG 1103515245, c = LONG 12345, m = LONG 2^31; + LONG INT result = (rli * a + c) MOD m; rseed := result; + SHORTEN result + END, + (LONG LONG INT rlli) : + BEGIN + LONG LONG INT a = LONG LONG 1103515245, + c = LONG LONG 12345, m = LONG LONG 2^31; + LONG LONG INT result = (rlli * a + c) MOD m; rseed := result; + SHORTEN SHORTEN result + END + ESAC + END; + PROC ms rand = INT : + BEGIN + CASE rseed IN + (INT ri): + BEGIN + INT a = 214013, c = 2531011, m1 = 2^15, m2 = 2^16; + INT result = (ri * a + c) MOD (m1 * m2); rseed := result; + result % m2 + END, + (LONG INT rli): + BEGIN + LONG INT a = LONG 214013, c = LONG 2531011, m = LONG 2^31, m2 = LONG 2^16; + LONG INT result = (rli * a + c) MOD m; rseed := result; + SHORTEN (result % m2) + END, + (LONG LONG INT rlli) : + BEGIN + LONG LONG INT a = LONG LONG 214013, + c = LONG LONG 2531011, m = LONG LONG 2^31, m2 = LONG LONG 2^16; + LONG LONG INT result = (rlli * a + c) MOD m; rseed := result; + SHORTEN SHORTEN (result % m2) + END + ESAC + END; + srand (0); + TO 10 DO printf (($g(0)l$, bsd rand)) OD; + print (newline); + srand (0); + TO 10 DO printf (($g(0)l$, ms rand)) OD; + srand (0) +END diff --git a/Task/Linear-congruential-generator/Befunge/linear-congruential-generator.bf b/Task/Linear-congruential-generator/Befunge/linear-congruential-generator.bf new file mode 100644 index 0000000000..12c1edbbd5 --- /dev/null +++ b/Task/Linear-congruential-generator/Befunge/linear-congruential-generator.bf @@ -0,0 +1,4 @@ +>025*>\::0\`288*::*:****+.55+,"iQ"5982156*:v +v $$_^#!\-1:\%***:*::*882 ++*"yf"3***+***+*< +>025*>\:488**:*/:0\`6"~7"+:*+01-2/-*+."O?+"55v +@ $$_^#!\-1:\%***:*::*882 ++***" ''4C"*+2**,+< diff --git a/Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator.lisp b/Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator-1.lisp similarity index 100% rename from Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator.lisp rename to Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator-1.lisp diff --git a/Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator-2.lisp b/Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator-2.lisp new file mode 100644 index 0000000000..45c1225c6d --- /dev/null +++ b/Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator-2.lisp @@ -0,0 +1,5 @@ +(defun linear-random (seed &key (times 1) (bounds (expt 2 31)) (multiplier 1103515245) (adder 12345) (divisor 1) (max 2147483647) (min 0)) + (loop for candidate = seed then (mod (+ (* multiplier candidate) adder) bounds) + for result = candidate then (floor (/ candidate divisor)) + when (and (< result max) (> result min)) collect result into valid-numbers + when (> (length valid-numbers) times) return result)) diff --git a/Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator-3.lisp b/Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator-3.lisp new file mode 100644 index 0000000000..ff9e2fe29f --- /dev/null +++ b/Task/Linear-congruential-generator/Common-Lisp/linear-congruential-generator-3.lisp @@ -0,0 +1,5 @@ +(format t "Count:~15tBSD:~30tMS:~%~{~{~a~15t~a~30t~a~%~}~}" + (loop for i from 0 upto 5 collect + (list i + (linear-random 0 :times i) + (linear-random 0 :times i :multiplier 214013 :adder 2531011 :max 32767 :divisor (expt 2 16))))) diff --git a/Task/Linear-congruential-generator/Elixir/linear-congruential-generator.elixir b/Task/Linear-congruential-generator/Elixir/linear-congruential-generator.elixir new file mode 100644 index 0000000000..a05272b798 --- /dev/null +++ b/Task/Linear-congruential-generator/Elixir/linear-congruential-generator.elixir @@ -0,0 +1,35 @@ +defmodule LCG do + def ms_seed(seed) do + Process.put(:ms_state, seed) + ms_rand + Process.put(:ms_seed, seed) + end + + def ms_rand do + state = Process.get(:ms_state) + state2 = rem(214013 * state + 2531011, 2147483648) + Process.put(:ms_state, state2) + div(state, 65536) + end + + def bsd_seed(seed) do + Process.put(:bsd_state, seed) + Process.put(:bsd_seed, seed) + end + + def bsd_rand do + state = Process.get(:bsd_state) + state2 = rem(1103515245 * state + 12345, 2147483648) + Process.put(:bsd_state, state2) + state2 + end +end + +Enum.each([0,1], fn i -> + IO.puts "\nRandom seed: #{i}\n BSD MS" + LCG.bsd_seed(i) + LCG.ms_seed(i) + Enum.each(1..10, fn _ -> + :io.format "~11w~8w~n", [LCG.bsd_rand, LCG.ms_rand] + end) +end) diff --git a/Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia b/Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia new file mode 100644 index 0000000000..ac955ae378 --- /dev/null +++ b/Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia @@ -0,0 +1,29 @@ +function lcg_maker{T<:Integer}(r::T, a::T, c::T, m::T, sh::T) + state = r + function lcg_rand() + state = mod(a*state + c, m) + return state >> sh + end + return lcg_rand +end + +snum = 10 +seed = 0 +bsd_rand = lcg_maker(seed, 1103515245, 12345, 2^31, 0) + +print("The first ", snum, " results for a BSD rand() seeded with ") +println(seed, ":") + +for i in 1:snum + println(@sprintf "%14d" bsd_rand()) +end + +ms_rand = lcg_maker(seed, 214013, 2531011, 2^31, 16) + +println() +print("The first ", snum, " results for a M\$ rand() seeded with ") +println(seed, ":") + +for i in 1:snum + println(@sprintf "%14d" ms_rand()) +end diff --git a/Task/Linear-congruential-generator/PowerShell/linear-congruential-generator.psh b/Task/Linear-congruential-generator/PowerShell/linear-congruential-generator.psh new file mode 100644 index 0000000000..b01f6aa0a7 --- /dev/null +++ b/Task/Linear-congruential-generator/PowerShell/linear-congruential-generator.psh @@ -0,0 +1,24 @@ +Function msstate{ + Param($current_seed) + Return (214013*$current_seed+2531011)%2147483648} + +Function randMS{ + Param($MSState) + Return [int]($MSState/65536)} + +Function randBSD{ + Param($BSDState) + Return (1103515245*$BSDState+12345)%2147483648} + +Write-Host "MS: seed=0" +$seed=0 #initialize seed +For($i=1;$i-le5;$i++){ + $seed = msstate($seed) + $rand = randMS($seed) + Write-Host $rand} + +Write-Host "BSD: seed=0" +$seed=0 #initialize seed +For($j=1;$j-le5;$j++){ + $seed = randBSD($seed) + Write-Host $seed} diff --git a/Task/Linear-congruential-generator/X86-Assembly/linear-congruential-generator-1.x86 b/Task/Linear-congruential-generator/X86-Assembly/linear-congruential-generator-1.x86 new file mode 100644 index 0000000000..d271fb18ff --- /dev/null +++ b/Task/Linear-congruential-generator/X86-Assembly/linear-congruential-generator-1.x86 @@ -0,0 +1,188 @@ +;x86-64 assembly code for Microsoft Windows +;Tested in windows 7 Enterprise Service Pack 1 64 bit +;With the AMD FX(tm)-6300 processor +;Assembled with NASM version 2.11.06 +;Linked to C library with gcc version 4.9.2 (x86_64-win32-seh-rev1, Built by MinGW-W64 project) + +;Assembled and linked with the following commands: +;nasm -f win64 .asm -o .obj +;gcc .obj -o + +;Takes number of iterations to run RNG loop as command line parameter. + +extern printf,puts,atoi,exit,time,malloc + +section .data +align 64 +errmsg_argnumber: db "There should be no more than one argument.",0 +align 64 +errmsg_noarg: db "Number of iterations was not specified.",0 +align 64 +errmsg_zeroiterations: db "Zero iterations of RNG loop specified.",0 + +align 64 +errmsg_timefail: db "Unable to retrieve calender time.",0 +align 64 +errmsg_mallocfail: db "Unable to allocate memory for array of random numbers.",0 + +align 64 +fmt_random: db "The %u number generated is %d",0xa,0xd,0 + +section .bss + +section .text +global main + +main: + +;check for argument +cmp rcx,1 +jle err_noarg + +;ensure that only one argument was entered +cmp rcx,2 +jg err_argnumber + + +;get number of times to iterate get_random +mov rcx,[rdx + 8] +call atoi + + +;ensure that number of iterations is greater than 0 +cmp rax,0 +jle err_zeroiterations +mov rcx,rax + + +;calculate space needed for an array containing the random numbers +shl rcx,2 + +;move size of array into r14 +mov r14,rcx + +;reserve memory for array of random numbers with malloc +call malloc + +cmp rax,0 +jz err_mallocfail + +;pointer to array in r15 +mov r15,rax + + +;seed the RNG using time() +xor rcx,rcx +call time + +;ensure that time returns valid output +cmp rax,-1 +jz err_timefail + +;calculate address of end of array in r14 +add r14,r15 + + +;pointer to array of random numbers in r15 +;address of end of array in r14 +;current address in array in rdi +;multiplier in rbx +;seed in rax +;current random number in rcx + + +;prepare random number generator + +mov rdi,r15 + +mov rbx,214013 + + +get_random: + +;multiply by 214013 and add 2561011 to get next state +mul ebx +add eax,2531011 + +;shr by 16 and AND with 0x7FFF to get current random number +mov ecx,eax +shr ecx,16 +and ecx,0x7fff + +;store random number in array +mov [rdi],ecx + +add rdi,4 +cmp rdi,r14 +jl get_random + + +;pointer to array of random numbers in r15 +;address of end of array in r14 +;current address in array in rdi +;array index in rsi + + +xor rsi,rsi +mov rdi,r15 + +print_random: + +mov rcx,fmt_random +mov rdx,rsi +mov r8d,[rdi] +call printf + +add rsi,1 +add rdi,4 +cmp rdi,r14 +jl print_random + +xor rcx,rcx +call exit + + +;;;;;;;;;;ERROR MESSAGES;;;;;;;;;;;;;;;; + +err_argnumber: + +mov rcx,errmsg_argnumber +call puts + +jmp exit_one + + +err_noarg: + +mov rcx,errmsg_noarg +call puts + +jmp exit_one + + +err_zeroiterations: + +mov rcx,errmsg_zeroiterations +call puts + +jmp exit_one + + +err_timefail: + +mov rcx,errmsg_timefail +call puts + +jmp exit_one + + +err_mallocfail: + +mov rcx,errmsg_mallocfail +call puts + + +exit_one: + +mov rcx,1 +call exit diff --git a/Task/Linear-congruential-generator/X86-Assembly/linear-congruential-generator-2.x86 b/Task/Linear-congruential-generator/X86-Assembly/linear-congruential-generator-2.x86 new file mode 100644 index 0000000000..5ece0123bc --- /dev/null +++ b/Task/Linear-congruential-generator/X86-Assembly/linear-congruential-generator-2.x86 @@ -0,0 +1,244 @@ +;x86-64 assembly code for Microsoft Windows +;Tested in windows 7 Enterprise Service Pack 1 64 bit +;With the AMD FX(tm)-6300 processor +;Assembled with NASM version 2.11.06 +;Linked to C library with gcc version 4.9.2 (x86_64-win32-seh-rev1, Built by MinGW-W64 project) + +;Assembled and linked with the following commands: +;nasm -f win64 .asm -o .obj +;gcc .obj -o + +;Takes number of iterations to run RNG loop as command line parameter. + +extern printf,puts,atoi,exit,time,_aligned_malloc + +section .data +align 64 +errmsg_argnumber: db "There should be no more than one argument.",0 +align 64 +errmsg_noarg: db "Number of iterations was not specified.",0 +align 64 +errmsg_zeroiterations: db "Zero iterations of RNG loop specified.",0 + +align 64 +errmsg_timefail: db "Unable to retrieve calender time.",0 +align 64 +errmsg_mallocfail: db "Unable to allocate memory for array of random numbers.",0 + +align 64 +fmt_random: db "The %u number generated is %d",0xa,0xd,0 + +align 16 +multiplier: dd 214013,17405,214013,69069 +align 16 +addend: dd 2531011, 10395331, 13737667, 1 +align 16 +mask: dd 0xffffffff,0,0xffffffff,0 +align 16 +masklo: dd 0x7fff,0x7fff,0x7fff,0x7fff + +section .bss + +section .text +global main + +main: + +;check for argument +cmp rcx,1 +jle err_noarg + +;ensure that only one argument was entered +cmp rcx,2 +jg err_argnumber + + +;get number of times to iterate get_random +mov rcx,[rdx + 8] +call atoi + + +;ensure that number of iterations is greater than 0 +cmp rax,0 +jle err_zeroiterations +mov rcx,rax + + +;calculate space needed for an array containing the random numbers +shl rcx,4 + +;move size of array into r14 +mov r14,rcx + +;16 byte alignment boundary +mov rdx,16 + +;reserve memory aligned to 16 byte boundary for array with _aligned_malloc +call _aligned_malloc + +cmp rax,0 +jz err_mallocfail + +;pointer to array in r15 +mov r15,rax + + +;seed the RNG using time() +xor rcx,rcx +call time + +;ensure that time returns valid output +cmp rax,-1 +jz err_timefail + + +;pointer to array of random numbers in r15 +;address of end of array at in r14 +;states stored in xmm0 + +;calculate address of end of array in r14 +add r14,r15 + +;load seed,seed+1,seed,seed+1 into xmm0 +lea rbx,[rax - 1] +shl rax,32 +or rax,rbx + +movq xmm0,rax +vpslldq xmm1,xmm0,8 +vpor xmm0,xmm0,xmm1 + + +;pointer to array of random numbers in r15 +;address of end of array in r14 +;current address in array in rdi +;current states in xmm0 +;multiplier in xmm1 +;addened in xmm2 +;mask in xmm3 +;masklo in xmm4 +;split seed in xmm5 +;current set of random numbers in xmm6 + +;prepare random number generator + +mov rdi,r15 + +vmovdqa xmm1,[multiplier] +vmovdqa xmm2,[addend] +vmovdqa xmm3,[mask] +vmovdqa xmm4,[masklo] + + +get_random: + +;arrange order of current states to 2,3,0,1 and store in split seed +vpshufd xmm5,xmm0,10110001b + +;multiply current states by multiplier +vpmulld xmm0,xmm0,xmm1 + +;set order of multiplier to 2,3,0,1 +vpshufd xmm1,xmm1,10110001b + +;multiply split seed by multiplier +vpmulld xmm5,xmm5,xmm1 + +;and current states with mask +vpand xmm0,xmm0,xmm3 + +;and current split seed with mask +vpand xmm5,xmm5,xmm3 + +;set order of split seed to 2,3,0,1 +vpshufd xmm5,xmm5,10110001b + +;or current states with split seed +vpor xmm0,xmm0,xmm5 + +;add adder to current states +vpaddd xmm0,xmm0,xmm2 + + +;shift vector right by two bytes +vpsrldq xmm6,xmm0,2 + +;and each state with 0x7fff +vpand xmm6,xmm6,xmm4 + +vmovdqa [rdi],xmm6 + +add rdi,16 +cmp rdi,r14 +jl get_random + + +;pointer to array of random numbers in r15 +;address of end of array in r14 +;current address in array in rdi +;array index in rsi + + +xor rsi,rsi +mov rdi,r15 + +print_random: + +mov rcx,fmt_random +mov rdx,rsi +mov r8d,[rdi] +call printf + +add rsi,1 +add rdi,4 +cmp rdi,r14 +jl print_random + +xor rcx,rcx +call exit + + +;;;;;;;;;;ERROR MESSAGES;;;;;;;;;;;;;;;; + +err_argnumber: + +mov rcx,errmsg_argnumber +call puts + +jmp exit_one + + +err_noarg: + +mov rcx,errmsg_noarg +call puts + +jmp exit_one + + +err_zeroiterations: + +mov rcx,errmsg_zeroiterations +call puts + +jmp exit_one + + +err_timefail: + +mov rcx,errmsg_timefail +call puts + +jmp exit_one + + +err_mallocfail: + +mov rcx,errmsg_mallocfail +call puts + + +exit_one: + +mov rcx,1 +call exit diff --git a/Task/List-comprehensions/00DESCRIPTION b/Task/List-comprehensions/00DESCRIPTION index 2971fddebc..0656c517fd 100644 --- a/Task/List-comprehensions/00DESCRIPTION +++ b/Task/List-comprehensions/00DESCRIPTION @@ -3,7 +3,7 @@ A [[wp:List_comprehension|list comprehension]] is a special syntax in some programming languages to describe lists. It is similar to the way mathematicians describe sets, with a ''set comprehension'', hence the name. Some attributes of a list comprehension are that: -# They should be distinct from (nested) for loops within the syntax of the language. +# They should be distinct from (nested) for loops and the use of map & filter functions within the syntax of the language. # They should return either a list or an iterator (something that returns successive members of a collection, in order). # The syntax has parts corresponding to that of [[wp:Set-builder_notation|set-builder notation]]. diff --git a/Task/List-comprehensions/ABAP/list-comprehensions.abap b/Task/List-comprehensions/ABAP/list-comprehensions.abap new file mode 100644 index 0000000000..eba22fd069 --- /dev/null +++ b/Task/List-comprehensions/ABAP/list-comprehensions.abap @@ -0,0 +1,47 @@ +CLASS lcl_pythagorean_triplet DEFINITION CREATE PUBLIC. + PUBLIC SECTION. + TYPES: BEGIN OF ty_triplet, + x TYPE i, + y TYPE i, + z TYPE i, + END OF ty_triplet, + tty_triplets TYPE STANDARD TABLE OF ty_triplet WITH NON-UNIQUE EMPTY KEY. + + CLASS-METHODS: + get_triplets + IMPORTING + n TYPE i + RETURNING + VALUE(r_triplets) TYPE tty_triplets. + + PRIVATE SECTION. + CLASS-METHODS: + _is_pythagorean + IMPORTING + i_triplet TYPE ty_triplet + RETURNING + VALUE(r_is_pythagorean) TYPE abap_bool. +ENDCLASS. + +CLASS lcl_pythagorean_triplet IMPLEMENTATION. + METHOD get_triplets. + DATA(triplets) = VALUE tty_triplets( FOR x = 1 THEN x + 1 WHILE x <= n + FOR y = x THEN y + 1 WHILE y <= n + FOR z = y THEN z + 1 WHILE z <= n + ( x = x y = y z = z ) ). + + LOOP AT triplets ASSIGNING FIELD-SYMBOL(). + IF _is_pythagorean( ) = abap_true. + INSERT INTO TABLE r_triplets. + ENDIF. + ENDLOOP. + ENDMETHOD. + + METHOD _is_pythagorean. + r_is_pythagorean = COND #( WHEN i_triplet-x * i_triplet-x + i_triplet-y * i_triplet-y = i_triplet-z * i_triplet-z THEN abap_true + ELSE abap_false ). + ENDMETHOD. +ENDCLASS. + +START-OF-SELECTION. + cl_demo_output=>display( lcl_pythagorean_triplet=>get_triplets( n = 20 ) ). diff --git a/Task/List-comprehensions/Fortran/list-comprehensions.f b/Task/List-comprehensions/Fortran/list-comprehensions.f index 6ae466c422..9aecfbc60a 100644 --- a/Task/List-comprehensions/Fortran/list-comprehensions.f +++ b/Task/List-comprehensions/Fortran/list-comprehensions.f @@ -20,7 +20,7 @@ program list_comprehension real, dimension(m) :: b logical, dimension(m) :: c integer, dimension(3, m) :: d - a = (/ ( ( cmplx(i,j), i=j,n), j=1,n) /) ! list comprehension, implicit do loop + a = [ ( ( cmplx(i,j), i=j,n), j=1,n) ] ! list comprehension, implicit do loop b = abs(a) c = (b .eq. int(b)) .and. (b .le. n) i = sum(merge(1,0,c)) diff --git a/Task/List-comprehensions/JavaScript/list-comprehensions.js b/Task/List-comprehensions/JavaScript/list-comprehensions-1.js similarity index 100% rename from Task/List-comprehensions/JavaScript/list-comprehensions.js rename to Task/List-comprehensions/JavaScript/list-comprehensions-1.js diff --git a/Task/List-comprehensions/JavaScript/list-comprehensions-2.js b/Task/List-comprehensions/JavaScript/list-comprehensions-2.js new file mode 100644 index 0000000000..7e34871a4a --- /dev/null +++ b/Task/List-comprehensions/JavaScript/list-comprehensions-2.js @@ -0,0 +1,33 @@ +select(nTuples(range(1, 100), 3), function ([x, y, z]) { + return x * x + y * y === z * z; +}); + +// nTuples(range(20), 3) --> [[1, 2, 3], [1, 2, 4] ... [17, 19, 20], [18, 19, 20]] (1140 tuples) +function nTuples(lst, n) { + var m = lst.length, + x = m ? [lst[0]] : null, + xs = m ? lst.slice(1) : null; + + return (!n || m < n) ? [] : ( + n === 1 ? lst.map(function (p) { + return [p]; + }) : ( + nTuples(xs, n - 1).map(function (t) { + return x.concat(t); + }).concat(nTuples(xs, n)) + ) + ) +} + +// range(1, 20) --> [1..20] +function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { + return m + i; + } + ) +} + +function select(lstSet, fnPredicate) { + return lstSet.filter(fnPredicate); +} diff --git a/Task/List-comprehensions/Julia/list-comprehensions.julia b/Task/List-comprehensions/Julia/list-comprehensions.julia new file mode 100644 index 0000000000..6b8ae26d2e --- /dev/null +++ b/Task/List-comprehensions/Julia/list-comprehensions.julia @@ -0,0 +1,2 @@ +const n = 20 +sort(filter(x -> x[1] < x[2] && x[1]^2 + x[2]^2 == x[3]^2, [(a, b, c) for a=1:n, b=1:n, c=1:n])) diff --git a/Task/List-comprehensions/MATLAB/list-comprehensions.m b/Task/List-comprehensions/MATLAB/list-comprehensions.m index 087966ca8e..2d7d080e00 100644 --- a/Task/List-comprehensions/MATLAB/list-comprehensions.m +++ b/Task/List-comprehensions/MATLAB/list-comprehensions.m @@ -1,4 +1,5 @@ - N = 100; - [a,b] = mesgrid(1:N, 1:N); - c = sqrt(a.^2 + b.^2); - [x,y] = find( c==fix(c) ); +N = 20 +[a,b] = meshgrid(1:N, 1:N); +c = sqrt(a.^2 + b.^2); +[x,y] = find(c == fix(c)); +disp([x, y, sqrt(x.^2 + y.^2)]) diff --git a/Task/Literals-Floating-point/ALGOL-W/literals-floating-point.alg b/Task/Literals-Floating-point/ALGOL-W/literals-floating-point.alg new file mode 100644 index 0000000000..a0e51ce5be --- /dev/null +++ b/Task/Literals-Floating-point/ALGOL-W/literals-floating-point.alg @@ -0,0 +1,24 @@ +begin + real r; long real lr; + % floating point literals have the following forms: % + % 1 - a digit sequence followed by "." followed by a digit sequence % + % 2 - a digit sequence followed by "." % + % 3 - "." followed by a digit sequence % + % 4 - one of the above, followed by "'" followed by an optional sign % + % folloed by a digit sequence % + % the literal can be followed by "L", indicating it is long real % + % the literal can be followed by "I", indicating it is imaginary % + % the literal can be followed by "LI" or "IL" indicating it is a long % + % imaginary number % + % an integer literal ( digit sequence ) can also be used where a % + % floating point literal is required % + % non-imaginary examples: % + r := 1.23; + r := 1.; + r := .9; + r := 1.23'5; + r := 1.'+4; + r := .9'-12; + r := 7; + lr := 5.4321L; +end. diff --git a/Task/Literals-Floating-point/Elixir/literals-floating-point.elixir b/Task/Literals-Floating-point/Elixir/literals-floating-point.elixir new file mode 100644 index 0000000000..ae3b97b501 --- /dev/null +++ b/Task/Literals-Floating-point/Elixir/literals-floating-point.elixir @@ -0,0 +1,20 @@ +iex(180)> 0.123 +0.123 +iex(181)> -123.4 +-123.4 +iex(182)> 1.23e4 +1.23e4 +iex(183)> 1.2e-3 +0.0012 +iex(184)> 1.23E4 +1.23e4 +iex(185)> 10_000.0 +1.0e4 +iex(186)> .5 +** (SyntaxError) iex:186: syntax error before: '.' + +iex(186)> 2. + 3 +** (CompileError) iex:186: invalid call 2.+(3) + +iex(187)> 1e4 +** (SyntaxError) iex:187: syntax error before: e4 diff --git a/Task/Literals-Integer/DCL/literals-integer.dcl b/Task/Literals-Integer/DCL/literals-integer.dcl new file mode 100644 index 0000000000..e1c6b12e66 --- /dev/null +++ b/Task/Literals-Integer/DCL/literals-integer.dcl @@ -0,0 +1,4 @@ +$ decimal1 = 123490 +$ decimal2 = %D123490 +$ octal = %O12370 +$ hex = %X1234AF0 diff --git a/Task/Literals-Integer/Elixir/literals-integer.elixir b/Task/Literals-Integer/Elixir/literals-integer.elixir new file mode 100644 index 0000000000..1a1ba533b7 --- /dev/null +++ b/Task/Literals-Integer/Elixir/literals-integer.elixir @@ -0,0 +1,10 @@ +1234 #=> 1234 +1_000_000 #=> 1000000 +0010 #=> 10 +0b111 #=> 7 +0o10 #=> 8 +0x1f #=> 31 + +0B10 #=> syntax error before: B10 +0X10 #=> syntax error before: X10 +0xFF #=> 255 diff --git a/Task/Literals-Integer/J/literals-integer-1.j b/Task/Literals-Integer/J/literals-integer-1.j index 64570316a4..50dbcfb8ea 100644 --- a/Task/Literals-Integer/J/literals-integer-1.j +++ b/Task/Literals-Integer/J/literals-integer-1.j @@ -1,2 +1,3 @@ - 10b123 16b123 8b123 20b123 2b123 1b123 0b123 100b123 99 0 -123 291 83 443 11 6 3 10203 99 0 + 10b123 16b123 8b123 20b123 2b123 1b123 0b123 100b123 99 0 0bsilliness +1 +123 291 83 443 11 6 3 10203 99 0 1 28 diff --git a/Task/Literals-String/ALGOL-W/literals-string.alg b/Task/Literals-String/ALGOL-W/literals-string.alg new file mode 100644 index 0000000000..72ef037f1c --- /dev/null +++ b/Task/Literals-String/ALGOL-W/literals-string.alg @@ -0,0 +1,20 @@ +begin + % String literals are enclosed in double-quotes in Algol W. % + % There isn't a separate character type but strings of lenghth one can % + % be used instead. % + % There are no escaping conventions used in string literals, except that % + % in order to have a double-quote character in a string, two double % + % quotes must be used. % + % Examples: % + + % write a single character % + write( "a" ); + + % write a double-quote character % + write( """" ); + + % write a multi-character string - note the "\" is not an escape % + % and a\nb will appear on the output, not a and b on separate lines % + write( "a\nb" ); + +end. diff --git a/Task/Literals-String/Elixir/literals-string-1.elixir b/Task/Literals-String/Elixir/literals-string-1.elixir new file mode 100644 index 0000000000..cc7b8e2386 --- /dev/null +++ b/Task/Literals-String/Elixir/literals-string-1.elixir @@ -0,0 +1,3 @@ +IO.puts "Begin String \n============" +str = "string" +str |> is_binary # true diff --git a/Task/Literals-String/Elixir/literals-string-2.elixir b/Task/Literals-String/Elixir/literals-string-2.elixir new file mode 100644 index 0000000000..0364733a1c --- /dev/null +++ b/Task/Literals-String/Elixir/literals-string-2.elixir @@ -0,0 +1 @@ +str |> String.codepoints diff --git a/Task/Literals-String/Elixir/literals-string-3.elixir b/Task/Literals-String/Elixir/literals-string-3.elixir new file mode 100644 index 0000000000..5419b6aa66 --- /dev/null +++ b/Task/Literals-String/Elixir/literals-string-3.elixir @@ -0,0 +1 @@ +str <> <<0>> diff --git a/Task/Literals-String/Elixir/literals-string-4.elixir b/Task/Literals-String/Elixir/literals-string-4.elixir new file mode 100644 index 0000000000..05a04e0a73 --- /dev/null +++ b/Task/Literals-String/Elixir/literals-string-4.elixir @@ -0,0 +1,3 @@ +?a # 97 +Code.eval_string("?b") # 98 +Code.eval_string("?ł") # 322 diff --git a/Task/Literals-String/Elixir/literals-string-5.elixir b/Task/Literals-String/Elixir/literals-string-5.elixir new file mode 100644 index 0000000000..f608ef0fc5 --- /dev/null +++ b/Task/Literals-String/Elixir/literals-string-5.elixir @@ -0,0 +1,4 @@ +IO.inspect "Begin Char List \n=============" +[115, 116, 114, 105, 110, 103] +ch = "hi" +'string #{ch}' diff --git a/Task/Literals-String/Elixir/literals-string-6.elixir b/Task/Literals-String/Elixir/literals-string-6.elixir new file mode 100644 index 0000000000..a72591da32 --- /dev/null +++ b/Task/Literals-String/Elixir/literals-string-6.elixir @@ -0,0 +1 @@ +'string #{ch}'++[0] diff --git a/Task/Literals-String/JavaScript/literals-string.js b/Task/Literals-String/JavaScript/literals-string.js new file mode 100644 index 0000000000..4e670eeffb --- /dev/null +++ b/Task/Literals-String/JavaScript/literals-string.js @@ -0,0 +1,8 @@ +(function () { + return "αβγδ 中间来点中文 🐫 אבגד" +})(); + + +(function() { + return "\u03b1\u03b2\u03b3\u03b4 \u4e2d\u95f4\u6765\u70b9\u4e2d\u6587 \ud83d\udc2b \u05d0\u05d1\u05d2\u05d3"; +})(); diff --git a/Task/Literals-String/Prolog/literals-string-1.pro b/Task/Literals-String/Prolog/literals-string-1.pro new file mode 100644 index 0000000000..87fa838393 --- /dev/null +++ b/Task/Literals-String/Prolog/literals-string-1.pro @@ -0,0 +1 @@ +'This is an "atom" and not a string.' diff --git a/Task/Literals-String/Prolog/literals-string-2.pro b/Task/Literals-String/Prolog/literals-string-2.pro new file mode 100644 index 0000000000..9679ff571b --- /dev/null +++ b/Task/Literals-String/Prolog/literals-string-2.pro @@ -0,0 +1 @@ +"This 'string' will fool you if you're in a standard Prolog environment." diff --git a/Task/Literals-String/Prolog/literals-string-3.pro b/Task/Literals-String/Prolog/literals-string-3.pro new file mode 100644 index 0000000000..37551f1346 --- /dev/null +++ b/Task/Literals-String/Prolog/literals-string-3.pro @@ -0,0 +1,2 @@ +?- [97, 98, 99] = "abc". +true. diff --git a/Task/Literals-String/Prolog/literals-string-4.pro b/Task/Literals-String/Prolog/literals-string-4.pro new file mode 100644 index 0000000000..5e42fd8cd5 --- /dev/null +++ b/Task/Literals-String/Prolog/literals-string-4.pro @@ -0,0 +1,2 @@ +?- 97 = 0'a. +true. diff --git a/Task/Literals-String/Prolog/literals-string-5.pro b/Task/Literals-String/Prolog/literals-string-5.pro new file mode 100644 index 0000000000..e659928771 --- /dev/null +++ b/Task/Literals-String/Prolog/literals-string-5.pro @@ -0,0 +1,4 @@ +?- [97, 98, 99] = "abc". +false. +?- [97, 98, 99] = `abc`. +true. diff --git a/Task/Literals-String/Prolog/literals-string-6.pro b/Task/Literals-String/Prolog/literals-string-6.pro new file mode 100644 index 0000000000..6754d97b22 --- /dev/null +++ b/Task/Literals-String/Prolog/literals-string-6.pro @@ -0,0 +1,13 @@ +test_qq_odbc :- + myodbc_connect_db(Conn), + odbc_query(Conn, {|odbc|| +select + P.image,D.description,D.meta_keywords,C.image,G.description +from + product P, product_description D, category C, category_description G, product_to_category J +where + P.product_id=D.product_id and + P.product_id=J.product_id and C.category_id=J.category_id and + C.category_id=G.category_id + |}, Row), + writeln(Row). diff --git a/Task/Literals-String/SQL/literals-string.sql b/Task/Literals-String/SQL/literals-string.sql new file mode 100644 index 0000000000..315d0f0dcf --- /dev/null +++ b/Task/Literals-String/SQL/literals-string.sql @@ -0,0 +1 @@ +SELECT 'The boy said ''hello''.'; diff --git a/Task/Logical-operations/ALGOL-W/logical-operations.alg b/Task/Logical-operations/ALGOL-W/logical-operations.alg new file mode 100644 index 0000000000..8135e12a0d --- /dev/null +++ b/Task/Logical-operations/ALGOL-W/logical-operations.alg @@ -0,0 +1,14 @@ +procedure booleanOperations( logical value a, b ) ; + begin + + % algol W has the usual "and", "or" and "not" operators % + write( a, " and ", b, ": ", a and b ); + write( a, " or ", b, ": ", a or b ); + write( " not ", a, ": ", not a ); + + % logical values can be compared with the = and not = operators % + % a not = b can be used for a xor b % + write( a, " xor ", b, ": ", a not = b ); + write( a, " equ ", b, ": ", a = b ); + + end booleanOperations ; diff --git a/Task/Logical-operations/Elixir/logical-operations-1.elixir b/Task/Logical-operations/Elixir/logical-operations-1.elixir new file mode 100644 index 0000000000..2a74086835 --- /dev/null +++ b/Task/Logical-operations/Elixir/logical-operations-1.elixir @@ -0,0 +1,6 @@ +iex(1)> true and false +false +iex(2)> false or true +true +iex(3)> not false +true diff --git a/Task/Logical-operations/Elixir/logical-operations-2.elixir b/Task/Logical-operations/Elixir/logical-operations-2.elixir new file mode 100644 index 0000000000..cf12f0c5b5 --- /dev/null +++ b/Task/Logical-operations/Elixir/logical-operations-2.elixir @@ -0,0 +1,14 @@ +(28)> nil || 23 +23 +iex(29)> [] || false +[] +iex(30)> nil && true +nil +iex(31)> 0 && 15 +15 +iex(32)> ! true +false +iex(33)> ! nil +true +iex(34)> ! 3.14 +false diff --git a/Task/Logical-operations/Julia/logical-operations.julia b/Task/Logical-operations/Julia/logical-operations.julia new file mode 100644 index 0000000000..2fb845b93f --- /dev/null +++ b/Task/Logical-operations/Julia/logical-operations.julia @@ -0,0 +1,14 @@ +function exerciselogic(a::Bool, b::Bool) + st = @sprintf " %5s" a + st *= @sprintf " %5s" b + st *= @sprintf " %5s" ~a + st *= @sprintf " %5s" a | b + st *= @sprintf " %5s" a & b + st *= @sprintf " %5s" a $ b +end + +println("Julia's logical operations on Bool:") +println(" a b not or and xor") +for a in [true, false], b in [true, false] + println(exerciselogic(a, b)) +end diff --git a/Task/Logical-operations/Rust/logical-operations.rust b/Task/Logical-operations/Rust/logical-operations.rust new file mode 100644 index 0000000000..d6fe4ea987 --- /dev/null +++ b/Task/Logical-operations/Rust/logical-operations.rust @@ -0,0 +1,13 @@ +fn boolean_ops(a: bool, b: bool) { + println!("{} and {} -> {}", a, b, a && b); + println!("{} or {} -> {}", a, b, a || b); + println!("{} xor {} -> {}", a, b, a ^ b); + println!("not {} -> {}\n", a, !a); +} + +fn main() { + boolean_ops(true, true); + boolean_ops(true, false); + boolean_ops(false, true); + boolean_ops(false, false) +} diff --git a/Task/Logical-operations/Self/logical-operations.self b/Task/Logical-operations/Self/logical-operations.self new file mode 100644 index 0000000000..1cc4b71d1e --- /dev/null +++ b/Task/Logical-operations/Self/logical-operations.self @@ -0,0 +1,4 @@ +true not = false. +( true && false ) = false. +( true ^^ false ) = true. "xor" +( true || false ) = true. "or" diff --git a/Task/Long-multiplication/360-Assembly/long-multiplication.360 b/Task/Long-multiplication/360-Assembly/long-multiplication.360 new file mode 100644 index 0000000000..89d69b45b4 --- /dev/null +++ b/Task/Long-multiplication/360-Assembly/long-multiplication.360 @@ -0,0 +1,273 @@ +LONGINT CSECT + USING LONGINT,R13 +SAVEAREA B PROLOG-SAVEAREA(R15) + DC 17F'0' + DC CL8'LONGINT' +PROLOG STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 + MVC XX(1),=C'1' + MVC LENXX,=H'1' xx=1 + LA R2,64 +LOOPII ST R2,RLOOPII do for 64 + MVC X-2(LL+2),XX-2 x=xx + MVC Y(1),=C'2' + MVC LENY,=H'1' y=2 + BAL R14,LONGMULT + MVC XX-2(LL+2),Z-2 xx=longmult(xx,2) xx=xx*2 + L R2,RLOOPII +ELOOPII BCT R2,LOOPII loop + MVC X-2(LL+2),XX-2 + MVC Y-2(LL+2),XX-2 + BAL R14,LONGMULT + MVC YY-2(LL+2),Z-2 yy=longmult(xx,xx) yy=xx*xx + XPRNT XX,LL output xx + XPRNT YY,LL output yy +RETURN L R13,4(0,R13) epilog + LM R14,R12,12(R13) + XR R15,R15 set return code + BR R14 return to caller +RLOOPII DS F +* +LONGMULT EQU * function longmult z=(x,y) + MVC LENSHIFT,=H'0' shift='' + MVC LENZ,=H'0' z='' + LH R6,LENX + LA R6,1(R6) from lenx + XR R8,R8 + BCTR R8,0 by -1 + LA R9,0 to 1 +LOOPI BXLE R6,R8,ELOOPI do i=lenx to 1 by -1 + LA R2,X + AR R2,R6 +i + BCTR R2,0 + MVC CI,0(R2) ci=substr(x,i,1) + IC R0,CI ni=integer(ci) + N R0,=X'0000000F' + STH R0,NI + MVC LENT,=H'0' t='' + SR R0,R0 + STH R0,CARRY carry=0 + LH R7,LENY + LA R7,1(R7) from lenx + XR R10,R10 + BCTR R10,0 by -1 + LA R11,0 to 1 +LOOPJ1 BXLE R7,R10,ELOOPJ1 do j=leny to 1 by -1 + LA R2,Y + AR R2,R7 +j + BCTR R2,0 + MVC CJ,0(R2) cj=substr(y,j,1) + IC R0,CJ + N R0,=X'0000000F' + STH R0,NJ nj=integer(cj) + LH R2,NI + MH R2,NJ + AH R2,CARRY + STH R2,NKR nkr=ni*nj+carry + LH R2,NKR + LA R1,10 + SRDA R2,32 + DR R2,R1 + STH R2,NK nk=nkr//10 + STH R3,CARRY carry=nkr/10 + LH R2,NK + O R2,=X'000000F0' + STC R2,CK ck=string(nk) + MVC TEMP,T + MVC T(1),CK + MVC T+1(LL-1),TEMP + LH R2,LENT + LA R2,1(R2) + STH R2,LENT t=ck!!t + B LOOPJ1 next j +ELOOPJ1 EQU * + LH R2,CARRY + O R2,=X'000000F0' + STC R2,CK ck=string(carry) + MVC TEMP,T + MVC T(1),CK + MVC T+1(LL-1),TEMP + LH R2,LENT + LA R2,1(R2) + STH R2,LENT t=ck!!t + LA R2,T + AH R2,LENT + LH R3,LENSHIFT + LA R4,SHIFT + LH R5,LENSHIFT + MVCL R2,R4 + LH R2,LENT + AH R2,LENSHIFT + STH R2,LENT t=t!!shift +IF1 LH R4,LENZ + CH R4,LENT if lenz>lent + BNH ELSE1 + LH R2,LENZ then + LA R2,1(R2) + STH R2,L l=lenz+1 + B EIF1 +ELSE1 LH R2,LENT else + LA R2,1(R2) + STH R2,L l=lent+1 +EIF1 EQU * + MVI TEMP,C'0' to + MVC TEMP+1(LL-1),TEMP + LA R2,TEMP + AH R2,L + SH R2,LENZ + LH R3,LENZ + LA R4,Z + LH R5,LENZ + MVCL R2,R4 + MVC LENZ,L + MVC Z,TEMP z=right(z,l,'0') + MVI TEMP,C'0' to + MVC TEMP+1(LL-1),TEMP + LA R2,TEMP + AH R2,L + SH R2,LENT + LH R3,LENT + LA R4,T + LH R5,LENT + MVCL R2,R4 + MVC LENT,L + MVC T,TEMP t=right(t,l,'0') + MVC LENW,=H'0' w='' + SR R0,R0 + STH R0,CARRY carry=0 + LH R7,L + LA R7,1(R7) from l + XR R10,R10 + BCTR R10,0 by -1 + LA R11,0 to 1 +LOOPJ2 BXLE R7,R10,ELOOPJ2 do j=l to 1 by -1 + LA R2,Z + AR R2,R7 +j + BCTR R2,0 + MVC CZ,0(R2) cz=substr(z,j,1) + IC R0,CZ + N R0,=X'0000000F' + STH R0,NZ nz=integer(cz) + LA R2,T + AR R2,R7 -j + BCTR R2,0 + MVC CT,0(R2) ct=substr(t,j,1) + IC R0,CT + N R0,=X'0000000F' + STH R0,NT nt=integer(ct) + LH R2,NZ + AH R2,NT + AH R2,CARRY + STH R2,NKR nkr=nz+nt+carry + LH R2,NKR + LA R1,10 + SRDA R2,32 + DR R2,R1 + STH R2,NK + STH R3,CARRY nk=nkr//10; carry=nkr/10 + LH R2,NK + O R2,=X'000000F0' + STC R2,CK ck=string(nk) + MVC TEMP,W + MVC W(1),CK + MVC W+1(LL-1),TEMP + LH R2,LENW + LA R2,1(R2) + STH R2,LENW w=ck!!w + B LOOPJ2 next j +ELOOPJ2 EQU * + LH R2,CARRY + O R2,=X'000000F0' + STC R2,CK ck=string(carry) + MVC Z(1),CK + MVC Z+1(LL-1),W + LH R2,LENW + LA R2,1(R2) + STH R2,LENZ z=ck!!w + LA R7,0 from 1 + LA R10,1 by 1 + LH R11,LENZ to lenz +LOOPJ3 BXH R7,R10,ELOOPJ3 do j=1 to lenz + LA R2,Z + AR R2,R7 j + BCTR R2,0 + MVC ZJ(1),0(R2) zj=substr(z,j,1) + CLI ZJ,C'0' if zj^='0' + BNE ELOOPJ3 then leave j + B LOOPJ3 next j +ELOOPJ3 EQU * +IF2 CH R7,LENZ if j>lenz + BNH EIF2 + LH R7,LENZ then j=lenz +EIF2 EQU * + LA R2,TEMP to + LH R3,LENZ + SR R3,R7 -j + LA R3,1(R3) + STH R3,LENTEMP + LA R4,Z from + AR R4,R7 +j + BCTR R4,0 + LR R5,R3 + MVCL R2,R4 + MVC Z-2(LL+2),TEMP-2 z=substr(z,j) + LA R2,SHIFT + AH R2,LENSHIFT + MVI 0(R2),C'0' + LH R3,LENSHIFT + LA R3,1(R3) + STH R3,LENSHIFT shift=shift!!'0' + MVC TEMP,Z + LA R2,TEMP + AH R2,LENZ + MVC 0(2,R2),=C' ' + B LOOPI next i +ELOOPI EQU * + MVI TEMP,C' ' + LA R2,Z + AH R2,LENZ + LH R3,=AL2(LL) + SH R3,LENZ + LA R4,TEMP + LH R5,=H'1' + ICM R5,8,=C' ' + MVCL R2,R4 z=clean(z) + BR R14 end function longmult +* +L DS H +NI DS H +NJ DS H +NK DS H +NZ DS H +NT DS H +CARRY DS H +NKR DS H +CI DS CL1 +CJ DS CL1 +CZ DS CL1 +CT DS CL1 +CK DS CL1 +ZJ DS CL1 +LENXX DS H +XX DS CL94 +LENYY DS H +YY DS CL94 +LENX DS H +X DS CL94 +LENY DS H +Y DS CL94 +LENZ DS H +Z DS CL94 +LENT DS H +T DS CL94 +LENW DS H +W DS CL94 +LENSHIFT DS H +SHIFT DS CL94 +LENTEMP DS H +TEMP DS CL94 +LL EQU 94 + YREGS + END LONGINT diff --git a/Task/Long-multiplication/Batch-File/long-multiplication.bat b/Task/Long-multiplication/Batch-File/long-multiplication.bat new file mode 100644 index 0000000000..5bdac10aae --- /dev/null +++ b/Task/Long-multiplication/Batch-File/long-multiplication.bat @@ -0,0 +1,37 @@ +@echo off +setlocal enabledelayedexpansion + +set num1=18446744073709551616 +set num2=18446744073709551616 + +set limit_a=-1&set limit_b=-1&set length=0 +for %%A in (1,2) do for /l %%B in (0,1,9) do set num%%A=!num%%A:%%B=%%B ! +for %%. in (!num1!) do set/a limit_a+=1&set a1=%%.!a1! +for %%. in (!num2!) do set/a limit_b+=1&set a2=%%.!a2! + +for /l %%a in (0,1,!limit_a!) do ( +for /l %%b in (0,1,!limit_b!) do ( + set/a pos=%%a+%%b + set/a next=!pos!+1 + set/a temp0=result!pos! + set/a result!pos!=!a1:~%%a,1!*!a2:~%%b,1! + if !temp0! equ 0 set/a length+=1 + if !pos! lss !length! set/a result!pos!+=!temp0! + + set/a temp0=result!pos! + set/a temp1=result!next! + + if !temp0! gtr 9 ( + set/a result!next!=!temp0!/10 + set temp2=!length! + if !temp1! equ 0 set/a length+=1 + if !next! lss !temp2! set/a result!next!+=!temp1! + set/a result!pos!=!temp0!%%10 + ) +) +) +for /l %%. in (0,1,!length!) do set product=!result%%.!!product! +echo.!product! +echo. +pause>nul +exit /b 0 diff --git a/Task/Long-multiplication/Pascal/long-multiplication.pascal b/Task/Long-multiplication/Pascal/long-multiplication.pascal new file mode 100644 index 0000000000..54024bee06 --- /dev/null +++ b/Task/Long-multiplication/Pascal/long-multiplication.pascal @@ -0,0 +1,137 @@ +Program TwoUp; Uses DOS, crt; +{Concocted by R.N.McLean (whom God preserve), Victoria university, NZ.} + Procedure Croak(gasp: string); + Begin + Writeln; + Write(Gasp); + HALT; + End; + + const BigBase = 10; {The base of big arithmetic.} + const BigEnuff = 333; {The most storage possible is 65532 bytes with Turbo Pascal.} + type BigNumberIndexer = word; {To access 0:BigEnuff BigNumberDigit data.} + type BigNumberDigit = byte; {The data.} + type BigNumberDigit2 = word; {Capable of digit*digit + carry. Like, 255*255 = 65025} + + type BigNumber = {All sorts of arrangements are possible.} + Record {Could include a sign indication.} + TopDigit: BigNumberDigit; {Finger the high-order digit.} + digit: array[0..BigEnuff] of byte; {The digits: note the "downto" in BigShow.} + end; {Could add fractional digits too. Endless, endless.} + + Procedure BigShow(var a: BigNumber); {Print the number.} + var i: integer; {A stepper.} + Begin + for i:=a.TopDigit downto 0 do {Thus high-order to low, as is the custom.} + if BigBase = 10 then write(a.digit[i]) {Constant following by the Turbo Pascal compiler} + else if BigBase = 100 then Write(a.digit[i] div 10,a.digit[i] mod 10) {Means that there will be no tests.} + else write(a.digit[i],','); {And dead code will be omitted.} + End; + + Procedure BigZero(var A: BigNumber); {A:=0;} + Begin; + A.TopDigit:=0; + A.Digit[0]:=0; + End; + Procedure BigOne(var A: BigNumber); {A:=1;} + Begin; + A.TopDigit:=0; + A.Digit[0]:=1; + End; + Function BigInt(n: longint): BigNumber; {A:=N;} + var l: BigNumberIndexer; + Begin + l:=0; + if n < 0 then croak('Negative integers are not yet considered.'); + repeat {At least one digit is to be placed.} + if l > BigEnuff then Croak('BigInt overflowed!'); {Oh dear.} + BigInt.Digit[l]:=N mod BigBase; {The low-order digit.} + n:=n div BigBase; {Shift down a digit.} + l:=l + 1; {Count in anticipation.} + until N = 0; {Still some number left?} + BigInt.TopDigit:=l - 1; {Went one too far.} + End; + + Function BigMult(a,b: BigNumber): BigNumber; {x:=BigMult(a,b);} +{Suppose the digits of A are a5,a4,a3,a2,a1,a0... + To multiply A and B. + a5 a4 a3 a2 a1 a0: six digits, d1 + x b4 b3 b2 b1 b0: five digits, d2 + --------------------------- + a5b0 a4b0 a3b0 a2b0 a1b0 a0b0 + a5b1 a4b1 a3b1 a2b1 a1b1 a0b1 + a5b2 a4b2 a3b2 a2b2 a1b2 a0b2 + a5b3 a4b3 a3b3 a2b3 a1b3 a0b3 + a5b4 a4b4 a3b4 a2b4 a1b4 a0b4 + ------------------------------------------------------- + carry 9 8 7 6 5 4 3 2 1 0: at least nine digits, + ------------------------------------------------------- = d1 + d2 - 1 + But the indices are also the powers, so the highest power is 9 = 5 + 4, +and a possible tenth for any carry.} + var X: BigNumber; {Scratchpad, so b:=BigMult(a,b); doesn't overwrite b as it goes...} + var d: BigNumberDigit; {A digit.} + var c: BigNumberDigit; {A carry.} + var dd: BigNumberDigit2; {A digit product.} + var i,j,l: BigNumberIndexer; {Steppers.} + Begin + if ((A.TopDigit = 0) and (A.Digit[0] = 0)) + or((B.TopDigit = 0) and (B.Digit[0] = 0)) then begin BigZero(BigMult); exit; end; + l:=A.TopDigit + B.TopDigit; {Minimal digit requirement. (Counting is from zero)} + if l > BigEnuff then Croak('BigMult will overflow.'); + for i:=l downto 0 do X.Digit[i]:=0; {Clear for action.} + for i:=0 to A.TopDigit do {Arbitrarily, choose A on the one hand.} + begin {Though there could be a better choice.} + d:=A.Digit[i]; {Select the digit.} + if d <> 0 then {What the hell. One in BigBase chance.} + begin {But not this time.} + l:=i; {Locate the power of BigBase.} + c:=0; {Start this digit's multiply pass.} + for j:=0 to B.TopDigit do {Stepping along B's digits.} + begin {One by one.} + dd:=BigNumberDigit2(B.Digit[j])*d + X.Digit[l] + c; {The deed.} + X.Digit[l]:=dd mod BigBase; {Place the new digit.} + c:=dd div BigBase; {And extract the carry.} + l:=l + 1; {Ready for the next power up.} + end; {Advance to it.} + if c > 0 then {The multiply done, place the carry.} + begin {Ah. We *will* use the next power up.} + if l > BigEnuff then Croak('BigMultX has overflowed.'); {Oh dear.} + X.Digit[l]:=c; {Thus as if BigMult..Digit[l] was zeroed.} + l:=l + 1; {Preserve the one-too-far for the last case} + end; {So much for a carry at the end of a pass.} + end; {So much for a non-zero digit.} + end; {On to another digit to multiply with.} + X.TopDigit:=l - 1; {Remember the one-too-far.} + BigMult:=X; {Deliver, possibly scragging A or B, or, both!} + End; {of BigMult.} + + Procedure BigPower(var X: BigNumber; P: longint); {Replaces X by X**P} + var A,W: BigNumber; {Scratchpads} + label up; + Begin {Each squaring doubles the power, melding nicely with binary reduction.} + if P <= 0 then Croak('Negative powers are not accommodated!'); + BigOne(A); {x**0 = 1} + W:=X; {Holds X**1, 2, 4, 8, etc.} +up:if P mod 2 = 1 then A:=BigMult(A,W); {Bit on, so include this order.} + P:=P div 2; {Halve the power contrariwise to W's doubling.} + if P > 0 then {Still some power to come?} + begin {Yes.} + W:=BigMult(W,W); {Step up to the next bit's power.} + goto up; {And see if it is "on".} + end; {Odd layout avoids multiply testing P > 0.} + X:=A; {The result.} + End; + + var X: BigNumber; + var p: longint; + BEGIN + ClrScr; + WriteLn('To calculate x = 2**64, then x*x via multi-digit long multiplication.'); + p:=64; {As per the specification.} + X:=BigInt(2); {Start with 2.} + BigPower(X,p); {First stage: 2**64} + Write ('x = 2**',p,' = '); BigShow(X); + WriteLn; + X:=BigMult(X,X); {Second stage.} + Write ('x*x = ');BigShow(X); {Can't have Write('x*x = ',BigShow(BigMult(X,X))), after all. Oh well.} + END. diff --git a/Task/Long-multiplication/Perl-6/long-multiplication.pl6 b/Task/Long-multiplication/Perl-6/long-multiplication.pl6 index 3adb503c77..cc3163ddac 100644 --- a/Task/Long-multiplication/Perl-6/long-multiplication.pl6 +++ b/Task/Long-multiplication/Perl-6/long-multiplication.pl6 @@ -1,9 +1,9 @@ sub num_to_groups ( $num ) { $num.flip.comb(/.**1..4/)».flip }; -sub groups_to_num ( @g ) { [~] @g.pop, @g.reverse».fmt('%04d') }; +sub groups_to_num ( @g ) { [~] flat @g.pop, @g.reverse».fmt('%04d') }; sub long_multiply ( Str $x, Str $y ) { my @group_sums; - for num_to_groups($x).pairs X num_to_groups($y).pairs -> $xp, $yp { + for flat num_to_groups($x).pairs X num_to_groups($y).pairs -> $xp, $yp { @group_sums[ $xp.key + $yp.key ] += $xp.value * $yp.value; } diff --git a/Task/Long-multiplication/PowerShell/long-multiplication.psh b/Task/Long-multiplication/PowerShell/long-multiplication-1.psh similarity index 100% rename from Task/Long-multiplication/PowerShell/long-multiplication.psh rename to Task/Long-multiplication/PowerShell/long-multiplication-1.psh diff --git a/Task/Long-multiplication/PowerShell/long-multiplication-2.psh b/Task/Long-multiplication/PowerShell/long-multiplication-2.psh new file mode 100644 index 0000000000..0e8b1ae05b --- /dev/null +++ b/Task/Long-multiplication/PowerShell/long-multiplication-2.psh @@ -0,0 +1,2 @@ +[BigInt]$n = [Math]::Pow(2,64) +[BigInt]::Multiply($n,$n) diff --git a/Task/Long-multiplication/REXX/long-multiplication-1.rexx b/Task/Long-multiplication/REXX/long-multiplication-1.rexx index 37eabdc4eb..ee1b963658 100644 --- a/Task/Long-multiplication/REXX/long-multiplication-1.rexx +++ b/Task/Long-multiplication/REXX/long-multiplication-1.rexx @@ -1,30 +1,27 @@ -/*REXX program performs long multiplication on two numbers (without 'E')*/ -numeric digits 100; d='.' /*be able to handle input numbers*/ -parse arg x y . /*accept the (possible) two nums.*/ -if x=='' then x=2**64 /*Not specified? Use the default*/ -if y=='' then y=x /* " " " " " */ -if x<0 && y<0 then sgn='-' /*only one argument is negative? */ - else sgn= /*no, then the sign is positive. */ -xx=x; x=strip(x,'T',d) /*remove any trailing decimal pt.*/ -yy=y; y=strip(y,'T',d) /* " " " " ".*/ -_=left(x,1); if _=='-' | _=='+' then x=substr(x,2) /*remove leading ±*/ -_=left(y,1); if _=='-' | _=='+' then y=substr(y,2) /* " " "*/ - /*[↑] above code for a Regina bug*/ - /*otherwise: x=abs(x) will do it*/ -dp=0; Lx=length(x); Ly=length(y) /*get the lengths of new X and Y.*/ -f=pos(d,x); if f\==0 then dp= Lx-f /*calculate size of dec fraction.*/ -f=pos(d,y); if f\==0 then dp=dp+Ly-f /* " " " " " */ -x=space(translate(x,,d),0) /*remove decimal point, if any. */ -y=space(translate(y,,d),0) /* " " " " " */ -Lx=length(x); Ly=length(y) /*get the lengths of new X and Y.*/ -numeric digits max(digits(),Lx+Ly) -p=0 /*the product so far. */ - do j=Ly by -1 for Ly /*almost like REXX does it,but no*/ - p=p+((x*substr(y,j,1))copies(0,Ly-j)) - end /*j*/ -say -f=length(p)-dp /*does product has enough digits?*/ -if f<0 then p=copies(0,abs(f)+1)p /*Neg? Add leading 0s for INSERT*/ -say ' built-in:' xx '*' yy '=' xx*yy -say 'long mult:' xx '*' yy '=' sgn ||strip(insert(d,p,length(p)-dp),'T',d) - /*stick a fork in it, we're done.*/ +/*REXX program performs long multiplication on two numbers (without the "E").*/ +numeric digits 3000 /*be able to handle gihugeic input #s. */ +parse arg x y . /*obtain the optional one or two #s. */ +if x=='' then x=2**64 /*Not specified? Then use the default.*/ +if y=='' then y=x /* " " " " " " */ +if x<0 && y<0 then sign='-' /*there only a single negative number? */ + else sign= /*no, then result sign must be positive*/ +xx=x; x=strip(x, 'T', .) /*remove any trailing decimal points. */ +yy=y; y=strip(y, 'T', .) /* " " " " ". */ +_=left(x,1); if _=='-' | _=='+' then x=substr(x,2) /*elide leading ± signs*/ +_=left(y,1); if _=='-' | _=='+' then y=substr(y,2) /* " " " " */ +dp=0; Lx=length(x); Ly=length(y) /*get the lengths of the new X and Y. */ +f=pos(., x); if f\==0 then dp= Lx-f /*calculate size of decimal fraction. */ +f=pos(., y); if f\==0 then dp=dp+Ly-f /* " " " " " */ +x=space(translate(x, , .), 0) /*remove decimal point if there is any.*/ +y=space(translate(y, , .), 0) /* " " " " " " " */ +Lx=length(x); Ly=length(y) /*get the lengths of the new X and Y. */ +numeric digits max(digits(), Lx+Ly) /*use a new decimal digits precision.*/ +$=0 /*P: is the product (so far). */ + do j=Ly by -1 for Ly /*almost like REXX does it, ··· but no.*/ + $=$ + ((x*substr(y, j, 1))copies(0, Ly-j) ) + end /*j*/ +f=length($)-dp /*does product has enough decimal digs?*/ +if f<0 then $=copies(0, abs(f)+1)$ /*Negative? Add leading 0s for INSERT.*/ +say ' built─in:' xx '*' yy '──►' xx*yy +say 'long mult:' xx '*' yy '──►' sign||strip(insert(.,$,length($)-dp),'T',.) + /*stick a fork in it, we're all done. */ diff --git a/Task/Longest-common-subsequence/C++/longest-common-subsequence-1.cpp b/Task/Longest-common-subsequence/C++/longest-common-subsequence-1.cpp index 6dcf3226f0..3f04c7ba85 100644 --- a/Task/Longest-common-subsequence/C++/longest-common-subsequence-1.cpp +++ b/Task/Longest-common-subsequence/C++/longest-common-subsequence-1.cpp @@ -50,11 +50,11 @@ class LCS { if (!it1->empty()) { auto dq2 = *it1; auto limit = threshold.end(); - for (auto it2 = dq2.begin(); it2 != dq2.end(); it2++) - { + for (auto it2 = dq2.begin(); it2 != dq2.end(); it2++) { // Each of the index1, index2 pairs considered here correspond to a match auto index2 = *it2; - // + + // // Note: The index2 values are monotonically decreasing, which allows the // thresholds to be updated in place. Montonicity allows a binary search, // implemented here by std::lower_bound() @@ -111,13 +111,13 @@ class LCS { } // - // Match() avoids incurring m*n comparisons by using the associative memory - // implemented by CHAR2INDEXES to achieve O(m+n) performance, where m and n - // are the input lengths. + // Match() avoids incurring m*n comparisons by using the associative + // memory implemented by CHAR2INDEXES to achieve O(m+n) performance, + // where m and n are the input lengths. // - // The symbol space is sparse in the case of records; so, the lookup time is - // at most O(log(m+n)). The lookup time can be assumed constant in the case - // of characters. + // The lookup time can be assumed constant in the case of characters. + // The symbol space is larger in the case of records; but the lookup + // time will be O(log(m+n)), at most. // void Match(CHAR2INDEXES& indexes, MATCHES& matches, const string& s1, const string& s2) { diff --git a/Task/Longest-common-subsequence/Elixir/longest-common-subsequence.elixir b/Task/Longest-common-subsequence/Elixir/longest-common-subsequence.elixir new file mode 100644 index 0000000000..f3f8326e86 --- /dev/null +++ b/Task/Longest-common-subsequence/Elixir/longest-common-subsequence.elixir @@ -0,0 +1,42 @@ +defmodule LCS do + def lcs_length(s,t) do + {l,_c} = lcs_length(s,t,Map.new) + l + end + + defp lcs_length([],t,cache), do: {0,Dict.put(cache,{[],t},0)} + defp lcs_length(s,[],cache), do: {0,Dict.put(cache,{s,[]},0)} + defp lcs_length([h|st]=s,[h|tt]=t,cache) do + {l,c} = lcs_length(st,tt,cache) + {l+1,Dict.put(c,{s,t},l+1)} + end + defp lcs_length([_sh|st]=s,[_th|tt]=t,cache) do + if Dict.has_key?(cache,{s,t}) do + {Dict.get(cache,{s,t}),cache} + else + {l1,c1} = lcs_length(s,tt,cache) + {l2,c2} = lcs_length(st,t,c1) + l = Enum.max([l1,l2]) + {l,Dict.put(c2,{s,t},l)} + end + end + + def lcs(s,t) do + {_,c} = lcs_length(s,t,Map.new) + lcs(s,t,c,[]) + end + + defp lcs([],_,_,acc), do: Enum.reverse(acc) + defp lcs(_,[],_,acc), do: Enum.reverse(acc) + defp lcs([h|st],[h|tt],cache,acc), do: lcs(st,tt,cache,[h|acc]) + defp lcs([_sh|st]=s,[_th|tt]=t,cache,acc) do + if Dict.get(cache,{s,tt}) > Dict.get(cache,{st,t}) do + lcs(s,tt,cache,acc) + else + lcs(st,t,cache,acc) + end + end +end + +IO.puts LCS.lcs('thisisatest','testing123testing') +IO.puts LCS.lcs('1234','1224533324') diff --git a/Task/Longest-common-subsequence/Groovy/longest-common-subsequence.groovy b/Task/Longest-common-subsequence/Groovy/longest-common-subsequence.groovy new file mode 100644 index 0000000000..9d6714cbaa --- /dev/null +++ b/Task/Longest-common-subsequence/Groovy/longest-common-subsequence.groovy @@ -0,0 +1,23 @@ +def lcs(xstr, ystr) { + if (xstr == "" || ystr == "") { + return ""; + } + + def x = xstr[0]; + def y = ystr[0]; + + def xs = xstr.size() > 1 ? xstr[1..-1] : ""; + def ys = ystr.size() > 1 ? ystr[1..-1] : ""; + + if (x == y) { + return (x + lcs(xs, ys)); + } + + def lcs1 = lcs(xstr, ys); + def lcs2 = lcs(xs, ystr); + + lcs1.size() > lcs2.size() ? lcs1 : lcs2; +} + +println(lcs("1234", "1224533324")); +println(lcs("thisisatest", "testing123testing")); diff --git a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-1.js b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-1.js index e7467651b5..827a808854 100644 --- a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-1.js +++ b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-1.js @@ -1,11 +1,11 @@ function lcs(a, b) { - var aSub = a.substr(0, a.length-1); - var bSub = b.substr(0, b.length-1); + var aSub = a.substr(0, a.length - 1); + var bSub = b.substr(0, b.length - 1); - if (a.length == 0 || b.length == 0) { - return ""; - } else if (a.charAt(a.length-1) == b.charAt(b.length-1)) { - return lcs(aSub, bSub) + a.charAt(a.length-1); + if (a.length === 0 || b.length === 0) { + return ''; + } else if (a.charAt(a.length - 1) === b.charAt(b.length - 1)) { + return lcs(aSub, bSub) + a.charAt(a.length - 1); } else { var x = lcs(a, bSub); var y = lcs(aSub, b); diff --git a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-2.js b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-2.js index c996c31f64..b63cd25d62 100644 --- a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-2.js +++ b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-2.js @@ -1,35 +1,13 @@ -function lcs(x,y){ - var s,i,j,m,n, - lcs=[],row=[],c=[], - left,diag,latch; - //make sure shorter string is the column string - if(mrow[j]){row[j] = left;} - } - } - } - i--,j--; - //row[j] now contains the length of the lcs - //recover the lcs from the table - while(i>-1&&j>-1){ - switch(c[i][j]){ - default: j--; - lcs.unshift(x[i]); - case (i&&c[i-1][j]): i--; - continue; - case (j&&c[i][j-1]): j--; - } - } - return lcs.join(''); -} +var longest = (xs, ys) => (xs.length > ys.length) ? xs : ys; + +var lcs = (xx, yy) => { + if (!xx.length || !yy.length) { return ''; } + + var x = xx[0], + y = yy[0]; + xs = xx.slice(1); + ys = yy.slice(1); + + return (x === y) ? lcs(xs, ys) : + longest(lcs(xx, ys), lcs(xs, yy)); +}; diff --git a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-3.js b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-3.js index 1bfdafe60c..c996c31f64 100644 --- a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-3.js +++ b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-3.js @@ -1,15 +1,35 @@ - var t=i; +function lcs(x,y){ + var s,i,j,m,n, + lcs=[],row=[],c=[], + left,diag,latch; + //make sure shorter string is the column string + if(mrow[j]){row[j] = left;} + } + } + } + i--,j--; + //row[j] now contains the length of the lcs + //recover the lcs from the table while(i>-1&&j>-1){ switch(c[i][j]){ - default:i--,j--; - continue; - case (i&&c[i-1][j]): - if(t!==i){lcs.unshift(x.substring(i+1,t+1));} - t=--i; + default: j--; + lcs.unshift(x[i]); + case (i&&c[i-1][j]): i--; continue; case (j&&c[i][j-1]): j--; - if(t!==i){lcs.unshift(x.substring(i+1,t+1));} - t=i; } } - if(t!==i){lcs.unshift(x.substring(i+1,t+1));} + return lcs.join(''); +} diff --git a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-4.js b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-4.js index ebae44922a..1bfdafe60c 100644 --- a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-4.js +++ b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-4.js @@ -1,27 +1,15 @@ -function lcs_greedy(x,y){ - var symbols = {}, - r=0,p=0,p1,L=0,idx, - m=x.length,n=y.length, - S = new Buffer(m p1)?(i++,p1):p; - if(idx===n){p=popsym(i);} - else{ - r=idx; - S[L++]=x.charCodeAt(i); + var t=i; + while(i>-1&&j>-1){ + switch(c[i][j]){ + default:i--,j--; + continue; + case (i&&c[i-1][j]): + if(t!==i){lcs.unshift(x.substring(i+1,t+1));} + t=--i; + continue; + case (j&&c[i][j-1]): j--; + if(t!==i){lcs.unshift(x.substring(i+1,t+1));} + t=i; } } - return S.toString('utf8',0,L); - - function popsym(index){ - var s = x[index], - pos = symbols[s]+1; - pos = y.indexOf(s,pos>r?pos:r); - if(pos===-1){pos=n;} - symbols[s]=pos; - return pos; - } -} + if(t!==i){lcs.unshift(x.substring(i+1,t+1));} diff --git a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-5.js b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-5.js new file mode 100644 index 0000000000..4d1cf6210e --- /dev/null +++ b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-5.js @@ -0,0 +1,42 @@ +function lcs_greedy(x,y){ + var p1, i, idx, + symbols = {}, + r = 0, + p = 0, + l = 0, + m = x.length, + n = y.length, + s = new Buffer((m < n) ? n : m); + + p1 = popsym(0); + + for (i = 0; i < m; i++) { + p = (r === p) ? p1 : popsym(i); + p1 = popsym(i + 1); + if (p > p1) { + i += 1; + idx = p1; + } else { + idx = p; + } + + if (idx === n) { + p = popsym(i); + } else { + r = idx; + s[l] = x.charCodeAt(i); + l += 1; + } + } + return s.toString('utf8', 0, l); + + function popsym(index) { + var s = x[index], + pos = symbols[s] + 1; + + pos = y.indexOf(s, ((pos > r) ? pos : r)); + if (pos === -1) { pos = n; } + symbols[s] = pos; + return pos; + } +} diff --git a/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-6.js b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-6.js new file mode 100644 index 0000000000..7608549e20 --- /dev/null +++ b/Task/Longest-common-subsequence/JavaScript/longest-common-subsequence-6.js @@ -0,0 +1 @@ +lcs_greedy('bcaaaade', 'deaaaabc'); // 'bc' instead of 'aaaa' diff --git a/Task/Longest-common-subsequence/Perl-6/longest-common-subsequence-1.pl6 b/Task/Longest-common-subsequence/Perl-6/longest-common-subsequence-1.pl6 index e37f629e11..0c7dbbc641 100644 --- a/Task/Longest-common-subsequence/Perl-6/longest-common-subsequence-1.pl6 +++ b/Task/Longest-common-subsequence/Perl-6/longest-common-subsequence-1.pl6 @@ -1,10 +1,10 @@ -sub lcs(Str $xstr, Str $ystr) { - return "" unless $xstr & $ystr; +say lcs("thisisatest", "testing123testing");sub lcs(Str $xstr, Str $ystr) { + return "" unless $xstr && $ystr; my ($x, $xs, $y, $ys) = $xstr.substr(0, 1), $xstr.substr(1), $ystr.substr(0, 1), $ystr.substr(1); return $x eq $y ?? $x ~ lcs($xs, $ys) - !! max({ $^a.chars }, lcs($xstr, $ys), lcs($xs, $ystr) ); + !! max(:by{ $^a.chars }, lcs($xstr, $ys), lcs($xs, $ystr) ); } say lcs("thisisatest", "testing123testing"); diff --git a/Task/Longest-increasing-subsequence/Erlang/longest-increasing-subsequence.erl b/Task/Longest-increasing-subsequence/Erlang/longest-increasing-subsequence.erl new file mode 100644 index 0000000000..5f8850c174 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Erlang/longest-increasing-subsequence.erl @@ -0,0 +1,115 @@ + %% @author Salvador Tamarit + +-module(longest_increasing_subsequence). + +-export([test_naive/0, test_patience/0]). + +% ************************************************** +% Interface to test the implementation +% ************************************************** + +test_naive() -> + test_gen(fun lis/1). + +test_patience() -> + test_gen(fun patience_lis/1). + +test_gen(F) -> + show_result(F([3,2,6,4,5,1])), + show_result(F([0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15])). + +show_result(Res) -> + io:format("~w\n", [Res]). + +% ************************************************** + +% ************************************************** +% Naive implementation +% ************************************************** + +lis(L) -> + maxBy( + fun(SS) -> length(SS) end, + [ lists:usort(SS) + ||  SS <- combos(L), + SS == lists:sort(SS)] + ). + +% ************************************************** + +% ************************************************** +% Patience sort implementation +% ************************************************** + +patience_lis(L) -> + patience_lis(L, []). + +patience_lis([H | T], Stacks) -> + NStacks = + case Stacks of + [] -> + [[{H,[]}]]; + _ -> + place_in_stack(H, Stacks, []) + end, + patience_lis(T, NStacks); +patience_lis([], Stacks) -> + case Stacks of + [] -> + []; + [_|_] -> + lists:reverse( recover_lis( get_previous(Stacks) ) ) + end. + +place_in_stack(E, [Stack = [{H,_} | _] | TStacks], PrevStacks) when H > E -> + PrevStacks ++ [[{E, get_previous(PrevStacks)} | Stack] | TStacks]; +place_in_stack(E, [Stack = [{H,_} | _] | TStacks], PrevStacks) when H =< E -> + place_in_stack(E, TStacks, PrevStacks ++ [Stack]); +place_in_stack(E, [], PrevStacks)-> + PrevStacks ++ [[{E, get_previous(PrevStacks)}]]. + +get_previous(Stack = [_|_]) -> + hd(lists:last(Stack)); +get_previous([]) -> + []. + +recover_lis({E,Prev}) -> + [E|recover_lis(Prev)]; +recover_lis([]) -> + []. + +% ************************************************** + +% ************************************************** +% Copied from http://stackoverflow.com/a/4762387/4162959 +% ************************************************** + +maxBy(F, L) -> + element( + 2, + lists:max([ {F(X), X} || X <- L]) + ). + +% ************************************************** + +% ************************************************** +% Copied from https://panduwana.wordpress.com/2010/04/21/combination-in-erlang/ +% ************************************************** + +combos(L) -> + lists:foldl( + fun(K, Acc) -> Acc++(combos(K, L)) end, + [[]], + lists:seq(1, length(L)) + ). + +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)). + +% ************************************************** 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 index 7c97191c24..bd9c0de1cc 100644 --- a/Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-2.pl6 +++ b/Task/Longest-increasing-subsequence/Perl-6/longest-increasing-subsequence-2.pl6 @@ -1,10 +1,10 @@ sub lis(@deck is copy) { - my @S = [@deck.shift() => Mu].item; + my @S = [@deck.shift() => Nil].item; for @deck -> $card { - if defined my $i = first { @S[$_][*-1].key > $card }, ^@S { - @S[$i].push: $card => @S[$i-1][*-1] // Mu + with first { @S[$_][*-1].key > $card }, ^@S -> $i { + @S[$i].push: $card => @S[$i-1][*-1] // Nil } else { - @S.push: [ $card => @S[*-1][*-1] // Mu ].item + @S.push: [ $card => @S[*-1][*-1] // Nil ].item } } reverse map *.key, ( diff --git a/Task/Longest-increasing-subsequence/PicoLisp/longest-increasing-subsequence-1.l b/Task/Longest-increasing-subsequence/PicoLisp/longest-increasing-subsequence-1.l new file mode 100644 index 0000000000..742c536043 --- /dev/null +++ b/Task/Longest-increasing-subsequence/PicoLisp/longest-increasing-subsequence-1.l @@ -0,0 +1,13 @@ +(de longinc (Lst) + (let (D NIL R NIL) + (for I Lst + (cond + ((< I (last D)) + (for (Y . X) D + (T (> X I) (set (nth D Y) I)) ) ) + ((< I (car R)) + (set R I) + (when D (set (cdr R) (last D))) ) + (T (when R (queue 'D (car R))) + (push 'R I) ) ) ) + (flip R) ) ) diff --git a/Task/Longest-increasing-subsequence/PicoLisp/longest-increasing-subsequence-2.l b/Task/Longest-increasing-subsequence/PicoLisp/longest-increasing-subsequence-2.l new file mode 100644 index 0000000000..1ff47ac8e8 --- /dev/null +++ b/Task/Longest-increasing-subsequence/PicoLisp/longest-increasing-subsequence-2.l @@ -0,0 +1,21 @@ +(de glutton (L) + (let N (pop 'L) + (maxi length + (recur (N L) + (ifn L + (list (list N)) + (mapcan + '((R) + (if (> (car R) N) + (list (cons N R) R) + (list (list N) R) ) ) + (recurse (car L) (cdr L)) ) ) ) ) ) ) + +(test (2 4 5) + (glutton (3 2 6 4 5 1))) + +(test (2 6 9 11 15) + (glutton (8 4 12 2 10 6 14 1 9 5 13 3 11 7 15))) + +(test (-31 0 83 782) + (glutton (4 65 2 -31 0 99 83 782 1)) ) diff --git a/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-1.py b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-1.py index 4e0b1167d4..140e2576b7 100644 --- a/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-1.py +++ b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-1.py @@ -1,10 +1,31 @@ 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) + """Returns the Longest Increasing Subsequence in the Given List/Array""" + P = [0 for i in range(N)] + M = [0 for i in range(N+1)] + L = 0 + for i in range(N): + lo = 1 + hi = L + while lo <= hi: + mid = (lo+hi)/2 + if X[M[mid]] < X[i]: + lo = mid+1 + else: + hi = mid-1 + + newL = lo + P[i] = M[newL-1] + M[newL] = i + + if newL > L: + L = newL + + S = [] + k = M[L] + for i in range L-1 to 0: + S.append(X[k]) + k = P[k] + return S 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]]: diff --git a/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-2.py b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-2.py index 1d48a6bc48..4e0b1167d4 100644 --- a/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-2.py +++ b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-2.py @@ -1,34 +1,11 @@ -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] +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, lis(d))) + 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-3.py b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-3.py new file mode 100644 index 0000000000..1d48a6bc48 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Python/longest-increasing-subsequence-3.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-string-challenge/00DESCRIPTION b/Task/Longest-string-challenge/00DESCRIPTION index 257f813d42..6534ba0039 100644 --- a/Task/Longest-string-challenge/00DESCRIPTION +++ b/Task/Longest-string-challenge/00DESCRIPTION @@ -1,8 +1,8 @@ '''Background''' -:This problem and challenge is inspired by one that used to be given as a challenge to students learning Icon. It was intended to be tried in Icon and another language the student was familiar with. The basic problem is quite simple the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code. +:This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code. -:The original programming challenge and some solutions can be found at [https://tapestry.tucson.az.us/twiki/bin/view/Main/LongestStringsPuzzle Unicon Programming TWiki / Longest Strings Puzzle]. (See notes on talk page if you have trouble with the site). +:The original programming challenge and some solutions can be found at [https://tapestry.tucson.az.us/twiki/bin/view/Main/LongestStringsPuzzle Unicon Programming TWiki / Longest Strings Puzzle]. (See notes on the talk page if you have trouble with the site). '''Basic problem statement:''' @@ -14,9 +14,9 @@ :Implement a solution to the basic problem that adheres to the spirit of the restrictions (see below). -:Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps show off the capabilities of your language in a creative way. Because there is potential for more variation between solutions, the description is key to helping others see what you've done. +:Describe how you circumvented or got around these 'restrictions' and met the 'spirit' of the challenge. Your supporting description may need to describe any challenges to interpreting the restrictions and how you made this interpretation. You should state any assumptions, warnings, or other relevant points. The central idea here is to make the task a bit more interesting by thinking outside of the box and perhaps by showing off the capabilities of your language in a creative way. Because there is potential for considerable variation between solutions, the description is key to helping others see what you've done. -:This task is likely to encourage multiple different types of solutions. They should be substantially different approaches. +:This task is likely to encourage a variety of different types of solutions. They should be substantially different approaches. Given the input:
a
@@ -27,7 +27,7 @@ ee
 f
 ggg
-The output should be (possibly rearranged): +the output should be (possibly rearranged):
ccc
 ddd
 ggg
@@ -43,11 +43,11 @@ An additional restriction became apparent in the discussion. '''Intent of Restrictions''' -:Because of the variety of languages on Rosetta and the wide variety of concepts used in them there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions. +:Because of the variety of languages on Rosetta Code and the wide variety of concepts used in them, there needs to be a bit of clarification and guidance here to get to the spirit of the challenge and the intent of the restrictions. -::The basic problem can be solved very conventionally and that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it. +::The basic problem can be solved very conventionally, but that's boring and pedestrian. The original intent here wasn't to unduly frustrate people with interpreting the restrictions, it was to get people to think outside of their particular box and have a bit of fun doing it. -::The guiding principle here should be that when using the language of your choice, try to solve this creatively showing off some of your language capabilities. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat' call out the fragment yourself and ask the reader if they can spot why. If you absolutely can't get around one of the restrictions, say why in your description. +::The guiding principle here should be to be creative in demonstrating some of the capabilities of the programming language being used. If you need to bend the restrictions a bit, explain why and try to follow the intent. If you think you've implemented a 'cheat', call out the fragment yourself and ask readers if they can spot why. If you absolutely can't get around one of the restrictions, explain why in your description. ::Now having said that, the restrictions require some elaboration. diff --git a/Task/Longest-string-challenge/ALGOL-68/longest-string-challenge.alg b/Task/Longest-string-challenge/ALGOL-68/longest-string-challenge.alg new file mode 100644 index 0000000000..2cefcd140c --- /dev/null +++ b/Task/Longest-string-challenge/ALGOL-68/longest-string-challenge.alg @@ -0,0 +1,38 @@ +BEGIN + INT bound = 1000000; CO Arbitrary upper limit on string lengths CO + INT max; CO Length of longest string CO + INT len; CO Length of string under examination CO + STRING buffer := ""; CO All characters read from stand in CO + STRING mask := bound * "0"; CO High water mark of string length seen so far CO +CO Standard boiler plate CO + on file end (stand in, (REF FILE f) BOOL: (close (f); GOTO finished)); + DO + STRING line; + read ((line, newline)); + buffer PLUSAB line + REPR 10; CO Concatenate string and newline CO + mask[UPB line] := "1" CO And set mask where character exists in line CO + OD; +finished: + buffer PLUSAB REPR 10; CO Guarantee there's a zero-length string at the end CO +CO + Scan backwards through mask looking for highest index used which is equal to the length + of the longest string with its terminating newline. +CO + FOR i FROM bound BY -1 TO 1 + DO + FROM ABS mask[i] TO ABS "0" DO max := i OD CO Exploit ABS "1" > ABS "0" CO + OD; + FROM 1 TO UPB buffer + DO CO Null loop if buffer is empty CO + VOID (char in string (REPR 10, len, buffer)); CO Pedantry and Algol68 Genie extension CO + FROM max TO len + DO CO Null loop if len < max CO + FOR i FROM 1 TO max + DO + printf (($a$, buffer[i])) CO Print string and newline CO + OD + OD; + buffer := buffer[len : UPB buffer]; CO Step over string CO + buffer := buffer[2 : UPB buffer] CO Step over newline CO + OD +END diff --git a/Task/Longest-string-challenge/Ruby/longest-string-challenge-2.rb b/Task/Longest-string-challenge/Ruby/longest-string-challenge-2.rb index 096445ed4d..088dba332d 100644 --- a/Task/Longest-string-challenge/Ruby/longest-string-challenge-2.rb +++ b/Task/Longest-string-challenge/Ruby/longest-string-challenge-2.rb @@ -1 +1,2 @@ -puts open("test.txt").each_line.group_by(&:size).max.last +h = $stdin.group_by(&:size) +puts h.max.last unless h.empty? diff --git a/Task/Longest-string-challenge/VBScript/longest-string-challenge.vb b/Task/Longest-string-challenge/VBScript/longest-string-challenge.vb new file mode 100644 index 0000000000..5556799963 --- /dev/null +++ b/Task/Longest-string-challenge/VBScript/longest-string-challenge.vb @@ -0,0 +1,25 @@ +'Read the input file. This assumes that the file is in the same +'directory as the script. +Set objfso = CreateObject("Scripting.FileSystemObject") +Set objfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ + "\input.txt",1) + +list = "" +previous_line = "" +l = Len(previous_line) + +Do Until objfile.AtEndOfStream + current_line = objfile.ReadLine + If Mid(current_line,l+1,1) <> "" Then + list = current_line & vbCrLf + previous_line = current_line + l = Len(previous_line) + ElseIf Mid(current_line,l,1) <> "" And Mid(current_line,(l+1),1) = "" Then + list = list & current_line & vbCrLf + End If +Loop + +WScript.Echo list + +objfile.Close +Set objfso = Nothing diff --git a/Task/Look-and-say-sequence/Elixir/look-and-say-sequence-1.elixir b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence-1.elixir new file mode 100644 index 0000000000..8522bbcdf4 --- /dev/null +++ b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence-1.elixir @@ -0,0 +1,23 @@ +defmodule LookAndSay do + def next(n) do + Enum.chunk_by(to_char_list(n), &(&1)) + |> Enum.map(fn cl=[h|_] -> Enum.concat(to_char_list(length cl), [h]) end) + |> Enum.concat + |> List.to_integer + end + + def sequence_from(n) do + Stream.iterate n, &(next/1) + end + + def main([start_str|_]) do + {start_val,_} = Integer.parse(start_str) + IO.inspect sequence_from(start_val) |> Enum.take 9 + end + + def main([]) do + main(["1"]) + end +end + +LookAndSay.main(System.argv) diff --git a/Task/Look-and-say-sequence/Elixir/look-and-say-sequence-2.elixir b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence-2.elixir new file mode 100644 index 0000000000..56949116d5 --- /dev/null +++ b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence-2.elixir @@ -0,0 +1,8 @@ +defmodule RC do + def look_and_say(n) do + Regex.replace(~r/(.)\1*/, to_string(n), fn x,y -> [to_string(String.length(x)),y] end) + |> String.to_integer + end +end + +IO.inspect Enum.reduce(1..9, [1], fn _,acc -> [RC.look_and_say(hd(acc)) | acc] end) |> Enum.reverse diff --git a/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir deleted file mode 100644 index 06780a0934..0000000000 --- a/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir +++ /dev/null @@ -1,24 +0,0 @@ -defmodule LookAndSay do - def next(n) do - Enum.chunk_by(to_char_list(n), &(&1)) - |> Enum.map(fn cl=[h|_] -> - Enum.concat(to_char_list(length cl), [h]) end) - |> Enum.concat - |> List.to_integer - end - - def sequence_from(n) do - Stream.iterate n, &(LookAndSay.next/1) - end - - def main([start_str|_]) do - {start_val,_} = Integer.parse(start_str) - :io.format("~w~n", [LookAndSay.sequence_from(start_val) |> Enum.take 9] ) - end - - def main([]) do - main(["1"]) - end -end - -LookAndSay.main(System.argv) diff --git a/Task/Look-and-say-sequence/Perl-6/look-and-say-sequence.pl6 b/Task/Look-and-say-sequence/Perl-6/look-and-say-sequence.pl6 index 17b06ac99b..c1618234f5 100644 --- a/Task/Look-and-say-sequence/Perl-6/look-and-say-sequence.pl6 +++ b/Task/Look-and-say-sequence/Perl-6/look-and-say-sequence.pl6 @@ -1,4 +1,4 @@ -my @look-and-say := ( +my @look-and-say = ( '1', *.comb(/(.)$0*/).map({ .chars ~ .substr(0,1) }).join ... diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-1.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-1.rb index 766c3d4c27..12cb68ab0a 100644 --- a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-1.rb +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-1.rb @@ -1,9 +1,8 @@ -def lookandsay(str) - str.gsub(/(.)\1*/) {$&.length.to_s + $1} +class String + def look_and_say + gsub(/(.)\1*/){|s| s.size.to_s + s[0]} + end end -num = "1" -10.times do - puts num - num = lookandsay(num) -end +ss = '1' +12.times {puts ss; ss = ss.look_and_say} diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-2.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-2.rb index e220375364..766c3d4c27 100644 --- a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-2.rb +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-2.rb @@ -1,8 +1,9 @@ def lookandsay(str) - str.chars.chunk{|c| c}.map{|c,x| [x.size, c]}.join + str.gsub(/(.)\1*/) {$&.length.to_s + $1} end -puts num = "1" -9.times do - puts num = lookandsay(num) +num = "1" +10.times do + puts num + num = lookandsay(num) end diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-3.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-3.rb index f7e5428903..e220375364 100644 --- a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-3.rb +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-3.rb @@ -1,17 +1,8 @@ -# Adding clusterization (http://apidock.com/rails/Enumerable/group_by) -module Enumerable - # clumps adjacent elements together - # >> [2,2,2,3,3,4,2,2,1].cluster - # => [[2, 2, 2], [3, 3], [4], [2, 2], [1]] - def cluster - cluster = [] - each do |element| - if cluster.last && cluster.last.last == element - cluster.last << element - else - cluster << [element] - end - end - cluster - end +def lookandsay(str) + str.chars.chunk{|c| c}.map{|c,x| [x.size, c]}.join +end + +puts num = "1" +9.times do + puts num = lookandsay(num) end diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-4.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-4.rb index 1a6ea151dd..f7e5428903 100644 --- a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-4.rb +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-4.rb @@ -1,10 +1,17 @@ -def print_sequence(input_sequence, seq=10) - return unless seq > 0 - puts input_sequence.join - result_array = input_sequence.cluster.map do |cluster| - [cluster.count, cluster.first] +# Adding clusterization (http://apidock.com/rails/Enumerable/group_by) +module Enumerable + # clumps adjacent elements together + # >> [2,2,2,3,3,4,2,2,1].cluster + # => [[2, 2, 2], [3, 3], [4], [2, 2], [1]] + def cluster + cluster = [] + each do |element| + if cluster.last && cluster.last.last == element + cluster.last << element + else + cluster << [element] + end + end + cluster end - print_sequence(result_array.flatten, seq-1) end - -print_sequence([1]) diff --git a/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-5.rb b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-5.rb new file mode 100644 index 0000000000..1a6ea151dd --- /dev/null +++ b/Task/Look-and-say-sequence/Ruby/look-and-say-sequence-5.rb @@ -0,0 +1,10 @@ +def print_sequence(input_sequence, seq=10) + return unless seq > 0 + puts input_sequence.join + result_array = input_sequence.cluster.map do |cluster| + [cluster.count, cluster.first] + end + print_sequence(result_array.flatten, seq-1) +end + +print_sequence([1]) diff --git a/Task/Look-and-say-sequence/Rust/look-and-say-sequence.rust b/Task/Look-and-say-sequence/Rust/look-and-say-sequence.rust index 96480dd312..8e96dd7d76 100644 --- a/Task/Look-and-say-sequence/Rust/look-and-say-sequence.rust +++ b/Task/Look-and-say-sequence/Rust/look-and-say-sequence.rust @@ -1,13 +1,11 @@ -use std::iter; - -fn next_sequence(in_seq: &[int]) -> ~[int] { +fn next_sequence(in_seq: &[i8]) -> Vec { assert!(!in_seq.is_empty()); - let mut result = ~[]; + let mut result = Vec::new(); let mut current_number = in_seq[0]; let mut current_runlength = 1; - for i in in_seq.slice_from(1).iter() { + for i in &in_seq[1..] { if current_number == *i { current_runlength += 1; } else { @@ -19,15 +17,14 @@ fn next_sequence(in_seq: &[int]) -> ~[int] { } result.push(current_runlength); result.push(current_number); - result } fn main() { - let mut seq = ~[1]; + let mut seq = vec![1]; - for i in iter::range(0, 10) { + for i in 0..10 { println!("Sequence {}: {:?}", i, seq); - seq = next_sequence(seq); + seq = next_sequence(&seq); } } diff --git a/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION b/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION index e3804f41b8..dd6399992f 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION +++ b/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION @@ -1,7 +1,11 @@ -Loop over multiple arrays (or lists or tuples or whatever they're called in your language) and print the ''i''th element of each. -Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. +Loop over multiple arrays (or lists or tuples or whatever they're called in +your language) and print the ''i''th element of each. +Use your language's "for each" loop if it has one, otherwise iterate +through the collection in order with some other loop. -For this example, loop over the arrays (a,b,c), (A,B,C) and (1,2,3) to produce the output +For this example, loop over the arrays (a,b,c), +(A,B,C) and (1,2,3) +to produce the output
aA1
 bB2
 cC3
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/ALGOL-68/loop-over-multiple-arrays-simultaneously.alg b/Task/Loop-over-multiple-arrays-simultaneously/ALGOL-68/loop-over-multiple-arrays-simultaneously.alg index 5dac9f5cef..8e60beb3be 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/ALGOL-68/loop-over-multiple-arrays-simultaneously.alg +++ b/Task/Loop-over-multiple-arrays-simultaneously/ALGOL-68/loop-over-multiple-arrays-simultaneously.alg @@ -1,4 +1,5 @@ -[]UNION(CHAR,INT) x=("a","b","c"), y=("A","B","C"), z=(1,2,3); +[]UNION(CHAR,INT) x=("a","b","c"), y=("A","B","C"), +z=(1,2,3); FOR i TO UPB x DO printf(($ggd$, x[i], y[i], z[i], $l$)) OD diff --git a/Task/Loop-over-multiple-arrays-simultaneously/ALGOL-W/loop-over-multiple-arrays-simultaneously.alg b/Task/Loop-over-multiple-arrays-simultaneously/ALGOL-W/loop-over-multiple-arrays-simultaneously.alg new file mode 100644 index 0000000000..b7bbbf7da2 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/ALGOL-W/loop-over-multiple-arrays-simultaneously.alg @@ -0,0 +1,11 @@ +begin + % declare the three arrays % + string(1) array a, b ( 1 :: 3 ); + integer array c ( 1 :: 3 ); + % initialise the arrays - have to do this element by element in Algol W % + a(1) := "a"; a(2) := "b"; a(3) := "c"; + b(1) := "A"; b(2) := "B"; b(3) := "C"; + c(1) := 1; c(2) := 2; c(3) := 3; + % loop over the arrays % + for i := 1 until 3 do write( i_w := 1, s_w := 0, a(i), b(i), c(i) ); +end. diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Ada/loop-over-multiple-arrays-simultaneously.ada b/Task/Loop-over-multiple-arrays-simultaneously/Ada/loop-over-multiple-arrays-simultaneously.ada index 3c92b38257..37fd041521 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Ada/loop-over-multiple-arrays-simultaneously.ada +++ b/Task/Loop-over-multiple-arrays-simultaneously/Ada/loop-over-multiple-arrays-simultaneously.ada @@ -7,6 +7,7 @@ procedure Array_Loop_Test is A3 : array (Array_Index) of Integer := (1, 2, 3); begin for Index in Array_Index'Range loop - Put_Line (A1 (Index) & A2 (Index) & Integer'Image (A3 (Index))(2)); + Put_Line (A1 (Index) & A2 (Index) & Integer'Image (A3 +(Index))(2)); end loop; end Array_Loop_Test; diff --git a/Task/Loop-over-multiple-arrays-simultaneously/AutoHotkey/loop-over-multiple-arrays-simultaneously-1.ahk b/Task/Loop-over-multiple-arrays-simultaneously/AutoHotkey/loop-over-multiple-arrays-simultaneously-1.ahk index 0fb4c2d65d..791732e607 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/AutoHotkey/loop-over-multiple-arrays-simultaneously-1.ahk +++ b/Task/Loop-over-multiple-arrays-simultaneously/AutoHotkey/loop-over-multiple-arrays-simultaneously-1.ahk @@ -10,8 +10,12 @@ MsgBox, % LoopMultiArrays() ;--------------------------------------------------------------------------- -LoopMultiArrays() { ; print the ith element of each +LoopMultiArrays() + + { ; print the ith element of each ;--------------------------------------------------------------------------- + + local Result StringSplit, List1_, List1, `, StringSplit, List2_, List2, `, diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Babel/loop-over-multiple-arrays-simultaneously-1.pb b/Task/Loop-over-multiple-arrays-simultaneously/Babel/loop-over-multiple-arrays-simultaneously-1.pb index 7eef2a9e5e..42b2d89733 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Babel/loop-over-multiple-arrays-simultaneously-1.pb +++ b/Task/Loop-over-multiple-arrays-simultaneously/Babel/loop-over-multiple-arrays-simultaneously-1.pb @@ -1,4 +1,5 @@ -main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3')) simul_array } +main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3')) +simul_array } simul_array!: { trans diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Babel/loop-over-multiple-arrays-simultaneously-2.pb b/Task/Loop-over-multiple-arrays-simultaneously/Babel/loop-over-multiple-arrays-simultaneously-2.pb index a6705de98a..a19e4eef20 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Babel/loop-over-multiple-arrays-simultaneously-2.pb +++ b/Task/Loop-over-multiple-arrays-simultaneously/Babel/loop-over-multiple-arrays-simultaneously-2.pb @@ -1,4 +1,5 @@ -main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3')) simul_array } +main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3')) +simul_array } simul_array!: {{ dup diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Befunge/loop-over-multiple-arrays-simultaneously.bf b/Task/Loop-over-multiple-arrays-simultaneously/Befunge/loop-over-multiple-arrays-simultaneously.bf new file mode 100644 index 0000000000..4047148f60 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Befunge/loop-over-multiple-arrays-simultaneously.bf @@ -0,0 +1,5 @@ +0 >:2g,:3g,:4gv +@_^#`2:+1,+55,< +abc +ABC +123 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/C++/loop-over-multiple-arrays-simultaneously-1.cpp b/Task/Loop-over-multiple-arrays-simultaneously/C++/loop-over-multiple-arrays-simultaneously-1.cpp index 0aae8dcf2e..bf99ac0a20 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/C++/loop-over-multiple-arrays-simultaneously-1.cpp +++ b/Task/Loop-over-multiple-arrays-simultaneously/C++/loop-over-multiple-arrays-simultaneously-1.cpp @@ -10,7 +10,8 @@ int main(int argc, char* argv[]) std::vector::const_iterator lIt = ls.begin(); std::vector::const_iterator uIt = us.begin(); std::vector::const_iterator nIt = ns.begin(); - for(; lIt != ls.end() && uIt != us.end() && nIt != ns.end(); + for(; lIt != ls.end() && uIt != us.end() && nIt != +ns.end(); ++lIt, ++uIt, ++nIt) { std::cout << *lIt << *uIt << *nIt << "\n"; diff --git a/Task/Loop-over-multiple-arrays-simultaneously/C++/loop-over-multiple-arrays-simultaneously-2.cpp b/Task/Loop-over-multiple-arrays-simultaneously/C++/loop-over-multiple-arrays-simultaneously-2.cpp index fae118b126..6608134d52 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/C++/loop-over-multiple-arrays-simultaneously-2.cpp +++ b/Task/Loop-over-multiple-arrays-simultaneously/C++/loop-over-multiple-arrays-simultaneously-2.cpp @@ -7,9 +7,11 @@ int main(int argc, char* argv[]) int ns[] = {1, 2, 3}; for(size_t li = 0, ui = 0, ni = 0; - li < sizeof(ls) && ui < sizeof(us) && ni < sizeof(ns) / sizeof(int); + li < sizeof(ls) && ui < sizeof(us) && ni +< sizeof(ns) / sizeof(int); ++li, ++ui, ++ni) { - std::cout << ls[li] << us[ui] << ns[ni] << "\n"; + std::cout << ls[li] << us[ui] << ns[ni] << + "\n"; } } diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Efene/loop-over-multiple-arrays-simultaneously.efene b/Task/Loop-over-multiple-arrays-simultaneously/Efene/loop-over-multiple-arrays-simultaneously.efene index 4a230e1cd1..6a6186e3af 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Efene/loop-over-multiple-arrays-simultaneously.efene +++ b/Task/Loop-over-multiple-arrays-simultaneously/Efene/loop-over-multiple-arrays-simultaneously.efene @@ -1,4 +1,5 @@ @public run = fn () { - lists.foreach(fn ((A, B, C)) { io.format("~s~n", [[A, B, C]]) }, lists.zip3("abc", "ABC", "123")) + lists.foreach(fn ((A, B, C)) { io.format("~s~n", [[A, B, C]]) }, +lists.zip3("abc", "ABC", "123")) } diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Ela/loop-over-multiple-arrays-simultaneously-1.ela b/Task/Loop-over-multiple-arrays-simultaneously/Ela/loop-over-multiple-arrays-simultaneously-1.ela index fea0bdf6f5..e1690a5d1e 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Ela/loop-over-multiple-arrays-simultaneously-1.ela +++ b/Task/Loop-over-multiple-arrays-simultaneously/Ela/loop-over-multiple-arrays-simultaneously-1.ela @@ -1,5 +1,6 @@ open console list imperative -xs = zipWith3 (\x y z -> show x ++ show y ++ show z) ['a','b','c'] ['A','B','C'] [1,2,3] +xs = zipWith3 (\x y z -> show x ++ show y ++ show z) ['a','b','c'] +['A','B','C'] [1,2,3] each writen xs diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Ela/loop-over-multiple-arrays-simultaneously-2.ela b/Task/Loop-over-multiple-arrays-simultaneously/Ela/loop-over-multiple-arrays-simultaneously-2.ela index c4fe4d16ec..5b7f9186be 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Ela/loop-over-multiple-arrays-simultaneously-2.ela +++ b/Task/Loop-over-multiple-arrays-simultaneously/Ela/loop-over-multiple-arrays-simultaneously-2.ela @@ -1 +1,2 @@ -xs = zipWith3 (\x -> (x++) >> (++)) "abc" "ABC" "123" +xs = zipWith3 (\x -> (x++) >> (++)) "abc" "ABC" + "123" diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-1.elixir b/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-1.elixir new file mode 100644 index 0000000000..b67b1845f2 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-1.elixir @@ -0,0 +1,5 @@ +l1 = ["a", "b", "c"] +l2 = ["A", "B", "C"] +l3 = ["1", "2", "3"] +IO.inspect List.zip([l1,l2,l3]) |> Enum.map(fn x-> Tuple.to_list(x) |> Enum.join end) +#=> ["aA1", "bB2", "cC3"] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-2.elixir b/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-2.elixir new file mode 100644 index 0000000000..21288b0032 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-2.elixir @@ -0,0 +1,5 @@ +l1 = 'abc' +l2 = 'ABC' +l3 = '123' +IO.inspect List.zip([l1,l2,l3]) |> Enum.map(fn x-> Tuple.to_list(x) end) +#=> ['aA1', 'bB2', 'cC3'] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-3.elixir b/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-3.elixir new file mode 100644 index 0000000000..2db15c7c36 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Elixir/loop-over-multiple-arrays-simultaneously-3.elixir @@ -0,0 +1,4 @@ +iex(1)> List.zip(['abc','ABCD','12345']) |> Enum.map(&Tuple.to_list(&1)) +['aA1', 'bB2', 'cC3'] +iex(2)> List.zip(['abcde','ABC','12']) |> Enum.map(&Tuple.to_list(&1)) +['aA1', 'bB2'] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Erlang/loop-over-multiple-arrays-simultaneously-1.erl b/Task/Loop-over-multiple-arrays-simultaneously/Erlang/loop-over-multiple-arrays-simultaneously-1.erl index 17daf8b99c..7d20ec2f5a 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Erlang/loop-over-multiple-arrays-simultaneously-1.erl +++ b/Task/Loop-over-multiple-arrays-simultaneously/Erlang/loop-over-multiple-arrays-simultaneously-1.erl @@ -1 +1,2 @@ -lists:zipwith3(fun(A,B,C)-> io:format("~s~n",[[A,B,C]]) end, "abc", "ABC", "123"). +lists:zipwith3(fun(A,B,C)-> +io:format("~s~n",[[A,B,C]]) end, "abc", "ABC", "123"). diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Erlang/loop-over-multiple-arrays-simultaneously-2.erl b/Task/Loop-over-multiple-arrays-simultaneously/Erlang/loop-over-multiple-arrays-simultaneously-2.erl index 7bc725a5d5..4c79efe43f 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Erlang/loop-over-multiple-arrays-simultaneously-2.erl +++ b/Task/Loop-over-multiple-arrays-simultaneously/Erlang/loop-over-multiple-arrays-simultaneously-2.erl @@ -1,2 +1,3 @@ -lists:foreach(fun({A,B,C}) -> io:format("~s~n",[[A,B,C]]) end, +lists:foreach(fun({A,B,C}) -> +io:format("~s~n",[[A,B,C]]) end, lists:zip3("abc", "ABC", "123")). diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Factor/loop-over-multiple-arrays-simultaneously.factor b/Task/Loop-over-multiple-arrays-simultaneously/Factor/loop-over-multiple-arrays-simultaneously.factor index 4a2b054bb2..70f622f0cc 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Factor/loop-over-multiple-arrays-simultaneously.factor +++ b/Task/Loop-over-multiple-arrays-simultaneously/Factor/loop-over-multiple-arrays-simultaneously.factor @@ -1 +1,2 @@ -"abc" "ABC" "123" [ [ write1 ] tri@ nl ] 3each +"abc" "ABC" "123" [ [ write1 ] tri@ nl ] +3each diff --git a/Task/Loop-over-multiple-arrays-simultaneously/GAP/loop-over-multiple-arrays-simultaneously.gap b/Task/Loop-over-multiple-arrays-simultaneously/GAP/loop-over-multiple-arrays-simultaneously.gap index bbb7688238..386154be07 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/GAP/loop-over-multiple-arrays-simultaneously.gap +++ b/Task/Loop-over-multiple-arrays-simultaneously/GAP/loop-over-multiple-arrays-simultaneously.gap @@ -1,6 +1,9 @@ -# The Loop function will apply some function to every tuple built by taking -# the i-th element of each list. If one of them is exhausted before the others, -# the loop continues at its begining. Only the longests lists will be precessed only once. +# The Loop function will apply some function to every tuple built by +taking +# the i-th element of each list. If one of them is exhausted before the +others, +# the loop continues at its begining. Only the longests lists will be +precessed only once. Loop := function(a, f) local i, j, m, n, v; n := Length(a); diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-1.hs b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-1.hs new file mode 100644 index 0000000000..e2e0318dd1 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-1.hs @@ -0,0 +1,2 @@ +{-# LANGUAGE ParallelListComp #-} +main = sequence [ putStrLn [x, y, z] | x <- "abd" | y <- "ABC" | z <- "123"] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-2.hs b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-2.hs new file mode 100644 index 0000000000..f5528dda01 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-2.hs @@ -0,0 +1,2 @@ +import Data.List +main = mapM putStrLn $ transpose ["abd", "ABC", "123"] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-3.hs b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-3.hs new file mode 100644 index 0000000000..107f6bc07a --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-3.hs @@ -0,0 +1,2 @@ +import Data.List +main = mapM putStrLn $ zipWith3 (\a b c -> [a,b,c]) "abc" "ABC" "123" diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-4.hs b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-4.hs new file mode 100644 index 0000000000..68b7a51842 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously-4.hs @@ -0,0 +1,2 @@ +import Control.Applicative +main = sequence $ getZipList $ (\x y z -> putStrLn [x, y, z]) <$> ZipList "abd" <*> ZipList "ABC" <*> ZipList "123" diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously.hs b/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously.hs deleted file mode 100644 index 3f191b94ff..0000000000 --- a/Task/Loop-over-multiple-arrays-simultaneously/Haskell/loop-over-multiple-arrays-simultaneously.hs +++ /dev/null @@ -1 +0,0 @@ -main = mapM_ putStrLn $ zipWith3 (\a b c -> [a,b,c]) "abc" "ABC" "123" diff --git a/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously.js b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-1.js similarity index 100% rename from Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously.js rename to Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-1.js diff --git a/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-2.js b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-2.js new file mode 100644 index 0000000000..258d757e4a --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-2.js @@ -0,0 +1,8 @@ +// --> [["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]] +var lstArrays = [ + 'a b c', + 'A B C', + '1 2 3' +].map(function (s) { + return s.split(' '); +}); diff --git a/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-3.js b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-3.js new file mode 100644 index 0000000000..c9bcecbb36 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-3.js @@ -0,0 +1,14 @@ +var lstOut = ['', '', '']; + +[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].forEach( + function (a) { + [0, 1, 2].forEach( + function (i) { + // side-effect on an array outside the function + lstOut[i] += a[i]; + } + ); + } +); + +// lstOut --> ["aA1", "bB2", "cC3"] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-4.js b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-4.js new file mode 100644 index 0000000000..5ec56ee3d8 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-4.js @@ -0,0 +1,15 @@ + [ + ["a", "b", "c"], + ["A", "B", "C"], + ["1", "2", "3"] + ].reduce( + function (a, e) { + return [ + a[0] + e[0], + a[1] + e[1], + a[2] + e[2] + ]; + }, ['', '', ''] // initial copy of the accumulator, passed to reduce() + ); + +// --> ["aA1", "bB2", "cC3"] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia index 4025dcaedf..681e51a6f6 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia +++ b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia @@ -1,4 +1,5 @@ -julia> map(println, ('a','b','c'),('A','B','C'),(1,2,3)) ; +julia> map(println, +('a','b','c'),('A','B','C'),(1,2,3)) ; aA1 bB2 cC3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia index 7e56a58d63..c28963bed7 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia +++ b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia @@ -1,4 +1,5 @@ -julia> for (i,j,k) in zip(('a','b','c'),('A','B','C'),(1,2,3)) +julia> for (i,j,k) in +zip(('a','b','c'),('A','B','C'),(1,2,3)) println(i,j,k) end aA1 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Logo/loop-over-multiple-arrays-simultaneously.logo b/Task/Loop-over-multiple-arrays-simultaneously/Logo/loop-over-multiple-arrays-simultaneously.logo index 64109d4df7..8779dc663f 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Logo/loop-over-multiple-arrays-simultaneously.logo +++ b/Task/Loop-over-multiple-arrays-simultaneously/Logo/loop-over-multiple-arrays-simultaneously.logo @@ -1,3 +1,5 @@ -show (map [(word ?1 ?2 ?3)] [a b c] [A B C] [1 2 3]) ; [aA1 bB2 cC3] +show (map [(word ?1 ?2 ?3)] [a b c] [A B C] [1 2 3]) + ; [aA1 bB2 cC3] -(foreach [a b c] [A B C] [1 2 3] [print (word ?1 ?2 ?3)]) ; as above, one per line +(foreach [a b c] [A B C] [1 2 3] [print (word ?1 ?2 ?3)]) ; as above, +one per line diff --git a/Task/Loop-over-multiple-arrays-simultaneously/MUMPS/loop-over-multiple-arrays-simultaneously-2.mumps b/Task/Loop-over-multiple-arrays-simultaneously/MUMPS/loop-over-multiple-arrays-simultaneously-2.mumps index ee9b3e5f8b..799bd21460 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/MUMPS/loop-over-multiple-arrays-simultaneously-2.mumps +++ b/Task/Loop-over-multiple-arrays-simultaneously/MUMPS/loop-over-multiple-arrays-simultaneously-2.mumps @@ -3,6 +3,7 @@ LOOPMULU S A(1)="a",A(2)="b",A(3)="c",A(4)="d" S B(1)="A",B(2)="B",B(3)="C",B(4)="D" S C(1)="1",C(2)="2",C(3)="3" - ; will error S %=$O(A("")) F Q:%="" W !,A(%),B(%),C(%) S %=$O(A(%)) + ; will error S %=$O(A("")) F Q:%="" W !,A(%),B(%),C(%) S +%=$O(A(%)) S %=$O(A("")) F Q:%="" W !,$G(A(%)),$G(B(%)),$G(C(%)) S %=$O(A(%)) K A,B,C,D,% diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Modula-3/loop-over-multiple-arrays-simultaneously.mod3 b/Task/Loop-over-multiple-arrays-simultaneously/Modula-3/loop-over-multiple-arrays-simultaneously.mod3 index 9a1009a25e..6db67dedc6 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Modula-3/loop-over-multiple-arrays-simultaneously.mod3 +++ b/Task/Loop-over-multiple-arrays-simultaneously/Modula-3/loop-over-multiple-arrays-simultaneously.mod3 @@ -11,6 +11,7 @@ VAR BEGIN FOR i := FIRST(ArrIdx) TO LAST(ArrIdx) DO - IO.Put(Fmt.Char(arr1[i]) & Fmt.Char(arr2[i]) & Fmt.Int(arr3[i]) & "\n"); + IO.Put(Fmt.Char(arr1[i]) & Fmt.Char(arr2[i]) & +Fmt.Int(arr3[i]) & "\n"); END; END MultiArray. diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Nemerle/loop-over-multiple-arrays-simultaneously-1.nemerle b/Task/Loop-over-multiple-arrays-simultaneously/Nemerle/loop-over-multiple-arrays-simultaneously-1.nemerle index 9f2aac4a99..10b077713d 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Nemerle/loop-over-multiple-arrays-simultaneously-1.nemerle +++ b/Task/Loop-over-multiple-arrays-simultaneously/Nemerle/loop-over-multiple-arrays-simultaneously-1.nemerle @@ -3,7 +3,8 @@ using System.Console; module LoopMultiple { - Zip3[T1, T2, T3] (x : list[T1], y : list[T2], z : list[T3]) : list[T1 * T2 * T3] + Zip3[T1, T2, T3] (x : list[T1], y : list[T2], z : list[T3]) : +list[T1 * T2 * T3] { |(x::xs, y::ys, z::zs) => (x, y, z)::Zip3(xs, ys, zs) |([], [], []) => [] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Nemerle/loop-over-multiple-arrays-simultaneously-2.nemerle b/Task/Loop-over-multiple-arrays-simultaneously/Nemerle/loop-over-multiple-arrays-simultaneously-2.nemerle index 159860bd77..b3adbdbd0c 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Nemerle/loop-over-multiple-arrays-simultaneously-2.nemerle +++ b/Task/Loop-over-multiple-arrays-simultaneously/Nemerle/loop-over-multiple-arrays-simultaneously-2.nemerle @@ -8,7 +8,8 @@ module LoopMult def second = array['A', 'B', 'C']; def third = array[1, 2, 3]; - when (first.Length == second.Length && second.Length == third.Length) + when (first.Length == second.Length && second.Length == +third.Length) foreach (i in [0 .. (first.Length - 1)]) WriteLine("{0}{1}{2}", first[i], second[i], third[i]); } diff --git a/Task/Loop-over-multiple-arrays-simultaneously/NewLISP/loop-over-multiple-arrays-simultaneously.newlisp b/Task/Loop-over-multiple-arrays-simultaneously/NewLISP/loop-over-multiple-arrays-simultaneously.newlisp index 6141dfeba6..5134a544a1 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/NewLISP/loop-over-multiple-arrays-simultaneously.newlisp +++ b/Task/Loop-over-multiple-arrays-simultaneously/NewLISP/loop-over-multiple-arrays-simultaneously.newlisp @@ -1 +1,2 @@ -(map println '(a b c) '(A B C) '(1 2 3)) +(map println '(a b c) '(A B C) '(1 2 +3)) diff --git a/Task/Loop-over-multiple-arrays-simultaneously/OCaml/loop-over-multiple-arrays-simultaneously-2.ocaml b/Task/Loop-over-multiple-arrays-simultaneously/OCaml/loop-over-multiple-arrays-simultaneously-2.ocaml index 956cad2fe8..f38f2450d6 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/OCaml/loop-over-multiple-arrays-simultaneously-2.ocaml +++ b/Task/Loop-over-multiple-arrays-simultaneously/OCaml/loop-over-multiple-arrays-simultaneously-2.ocaml @@ -3,7 +3,8 @@ let n_arrays_iter ~f = function | x::xs as al -> let len = Array.length x in let b = List.for_all (fun a -> Array.length a = len) xs in - if not b then invalid_arg "n_arrays_iter: arrays of different length"; + if not b then invalid_arg "n_arrays_iter: arrays of different +length"; for i = 0 to pred len do let ai = List.map (fun a -> a.(i)) al in f ai diff --git a/Task/Loop-over-multiple-arrays-simultaneously/OCaml/loop-over-multiple-arrays-simultaneously-3.ocaml b/Task/Loop-over-multiple-arrays-simultaneously/OCaml/loop-over-multiple-arrays-simultaneously-3.ocaml index be74ed02c6..01c29a93d1 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/OCaml/loop-over-multiple-arrays-simultaneously-3.ocaml +++ b/Task/Loop-over-multiple-arrays-simultaneously/OCaml/loop-over-multiple-arrays-simultaneously-3.ocaml @@ -1 +1,2 @@ -val n_arrays_iter : f:('a list -> unit) -> 'a array list -> unit +val n_arrays_iter : f:('a list -> unit) -> 'a +array list -> unit diff --git a/Task/Loop-over-multiple-arrays-simultaneously/PHP/loop-over-multiple-arrays-simultaneously.php b/Task/Loop-over-multiple-arrays-simultaneously/PHP/loop-over-multiple-arrays-simultaneously.php index 9fb99df6fe..9b8c84c1d6 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/PHP/loop-over-multiple-arrays-simultaneously.php +++ b/Task/Loop-over-multiple-arrays-simultaneously/PHP/loop-over-multiple-arrays-simultaneously.php @@ -1,6 +1,7 @@ $a = array('a', 'b', 'c'); $b = array('A', 'B', 'C'); -$c = array('1', '2', '3'); //These don't *have* to be strings, but it saves PHP from casting them later +$c = array('1', '2', '3'); //These don't *have* to be strings, but it +saves PHP from casting them later if ((sizeOf($a) !== sizeOf($b)) || (sizeOf($b) !== sizeOf($c))){ throw new Exception('All three arrays must be the same length'); diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-1.pl6 b/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-1.pl6 index 0f84b4d315..b6b8cf1e83 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-1.pl6 +++ b/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-1.pl6 @@ -1,3 +1,4 @@ -for Z Z 1, 2, 3 -> $x, $y, $z { +for Z Z 1, 2, 3 -> $x, +$y, $z { say $x, $y, $z; } diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-2.pl6 b/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-2.pl6 index fee17df671..45811ecbfa 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-2.pl6 +++ b/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-2.pl6 @@ -1,3 +1,4 @@ -for Z~ Z~ 1, 2, 3 -> $line { +for Z~ Z~ 1, 2, 3 -> +$line { say $line; } diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-3.pl6 b/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-3.pl6 index e1c3646c71..d857e1bcb3 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-3.pl6 +++ b/Task/Loop-over-multiple-arrays-simultaneously/Perl-6/loop-over-multiple-arrays-simultaneously-3.pl6 @@ -1 +1,2 @@ -.say for [Z~] [], [], [1,2,3] +.say for [Z~] [], [], +[1,2,3] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/PostScript/loop-over-multiple-arrays-simultaneously.ps b/Task/Loop-over-multiple-arrays-simultaneously/PostScript/loop-over-multiple-arrays-simultaneously.ps index 1c5cfdde42..9dce8d3838 100644 Binary files a/Task/Loop-over-multiple-arrays-simultaneously/PostScript/loop-over-multiple-arrays-simultaneously.ps and b/Task/Loop-over-multiple-arrays-simultaneously/PostScript/loop-over-multiple-arrays-simultaneously.ps differ diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-1.py b/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-1.py index 3362bac762..444f90a138 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-1.py +++ b/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-1.py @@ -1,4 +1,5 @@ ->>> print ( '\n'.join(''.join(x) for x in zip('abc', 'ABC', '123')) ) +>>> print ( '\n'.join(''.join(x) for x in +zip('abc', 'ABC', '123')) ) aA1 bB2 cC3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-2.py b/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-2.py index 9847001b52..c0b67515c3 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-2.py +++ b/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-2.py @@ -1,4 +1,5 @@ ->>> print ( '\n'.join(map(lambda *x: ''.join(x), 'abc', 'ABC', '123')) ) +>>> print ( '\n'.join(map(lambda *x: +''.join(x), 'abc', 'ABC', '123')) ) aA1 bB2 cC3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-4.py b/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-4.py index bee2484996..6aa02db8b6 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-4.py +++ b/Task/Loop-over-multiple-arrays-simultaneously/Python/loop-over-multiple-arrays-simultaneously-4.py @@ -1,5 +1,6 @@ >>> from itertools import zip_longest ->>> print ( '\n'.join(''.join(x) for x in zip_longest('abc', 'ABCD', '12345', fillvalue='#')) ) +>>> print ( '\n'.join(''.join(x) for x in zip_longest('abc', +'ABCD', '12345', fillvalue='#')) ) aA1 bB2 cC3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-1.rexx b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-1.rexx index 9674dbd5cb..cb73fe32bf 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-1.rexx +++ b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-1.rexx @@ -1,4 +1,5 @@ -/*REXX program shows how to simultaneously loop over multiple arrays.*/ +/*REXX program shows how to simultaneously loop over + multiple arrays.*/ x. = ' '; x.1 = "a"; x.2 = 'b'; x.3 = "c" y. = ' '; y.1 = "A"; y.2 = 'B'; y.3 = "C" z. = ' '; z.1 = "1"; z.2 = '2'; z.3 = "3" @@ -6,4 +7,5 @@ z. = ' '; z.1 = "1"; z.2 = '2'; z.3 = "3" do j=1 until output='' output = x.j || y.j || z.j say output - end /*j*/ /*stick a fork in it, we're done.*/ + end /*j*/ /*stick a fork in it, we're +done.*/ diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-2.rexx b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-2.rexx index 110d9b9473..56c342dffd 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-2.rexx +++ b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-2.rexx @@ -1,9 +1,12 @@ -/*REXX program shows how to simultaneously loop over multiple arrays.*/ +/*REXX program shows how to simultaneously loop over + multiple arrays.*/ x.=' '; x.1="a"; x.2='b'; x.3="c"; x.4='d' y.=' '; y.1="A"; y.2='B'; y.3="C"; -z.=' '; z.1= 1 ; z.2= 2 ; z.3= 3 ; z.4= 4; z.5= 5 +z.=' '; z.1= 1 ; z.2= 2 ; z.3= 3 ; z.4= 4; z.5= + 5 do j=1 until output='' output=x.j || y.j || z.j say output - end /*j*/ /*stick a fork in it, we're done.*/ + end /*j*/ /*stick a fork in it, we're +done.*/ diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-3.rexx b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-3.rexx index 67dd5db656..c8483d642b 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-3.rexx +++ b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-3.rexx @@ -1,8 +1,10 @@ -/*REXX program shows how to simultaneously loop over multiple lists.*/ +/*REXX program shows how to simultaneously loop over + multiple lists.*/ x = 'a b c d' y = 'A B C' z = 1 2 3 4 do j=1 until output='' output = word(x,j) || word(y,j) || word(z,j) say output - end /*j*/ /*stick a fork in it, we're done.*/ + end /*j*/ /*stick a fork in it, we're +done.*/ diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-4.rexx b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-4.rexx index d5f2e69be4..06b41905a6 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-4.rexx +++ b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-4.rexx @@ -1,7 +1,9 @@ -/*REXX program shows how to simultaneously loop over multiple lists.*/ +/*REXX program shows how to simultaneously loop over + multiple lists.*/ x = 'a b c d' y = 'A B C' z = 1 2 3 4 ..LAST do j=1 for max(words(x), words(y), words(z)) say word(x,j) || word(y,j) || word(z,j) - end /*j*/ /*stick a fork in it, we're done.*/ + end /*j*/ /*stick a fork in it, we're +done.*/ diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Racket/loop-over-multiple-arrays-simultaneously.rkt b/Task/Loop-over-multiple-arrays-simultaneously/Racket/loop-over-multiple-arrays-simultaneously.rkt index a18387a2b0..ec192b8a71 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Racket/loop-over-multiple-arrays-simultaneously.rkt +++ b/Task/Loop-over-multiple-arrays-simultaneously/Racket/loop-over-multiple-arrays-simultaneously.rkt @@ -1,6 +1,7 @@ #lang racket -(for ([i-1 '(a b c)] - [i-2 '(A B C)] - [i-3 '(1 2 3)]) - (printf "~a ~a ~a~n" i-1 i-2 i-3)) +(for ([x '(a b c)] ; list + [y #(A B C)] ; vector + [z "123"] + [i (in-naturals 1)]) ; 1, 2, ... infinitely + (printf "~s: ~s ~s ~s\n" i x y z)) diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Ruby/loop-over-multiple-arrays-simultaneously-3.rb b/Task/Loop-over-multiple-arrays-simultaneously/Ruby/loop-over-multiple-arrays-simultaneously-3.rb new file mode 100644 index 0000000000..895741125d --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Ruby/loop-over-multiple-arrays-simultaneously-3.rb @@ -0,0 +1,7 @@ +irb(main):001:0> ['a','b','c'].zip(['A','B'], [1,2,3,4]) {|a| puts a.join} +aA1 +bB2 +c3 +=> nil +irb(main):002:0> ['a','b','c'].zip(['A','B'], [1,2,3,4]) +=> [["a", "A", 1], ["b", "B", 2], ["c", nil, 3]] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Rust/loop-over-multiple-arrays-simultaneously.rust b/Task/Loop-over-multiple-arrays-simultaneously/Rust/loop-over-multiple-arrays-simultaneously.rust index 2e7729bfb4..b4811b875d 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Rust/loop-over-multiple-arrays-simultaneously.rust +++ b/Task/Loop-over-multiple-arrays-simultaneously/Rust/loop-over-multiple-arrays-simultaneously.rust @@ -1,5 +1,3 @@ -// rust 0.9-pre - fn main() { let a1 = ["a", "b", "c"]; let a2 = ["A", "B", "C"]; diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Salmon/loop-over-multiple-arrays-simultaneously-1.salmon b/Task/Loop-over-multiple-arrays-simultaneously/Salmon/loop-over-multiple-arrays-simultaneously-1.salmon index 0cd95b1b94..83943949cd 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Salmon/loop-over-multiple-arrays-simultaneously-1.salmon +++ b/Task/Loop-over-multiple-arrays-simultaneously/Salmon/loop-over-multiple-arrays-simultaneously-1.salmon @@ -1,4 +1,5 @@ -// First, we'll define a general-purpose zip() to zip any +// First, we'll define a general-purpose zip() to zip + any // number of lists together. function zip(...) { diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Salmon/loop-over-multiple-arrays-simultaneously-2.salmon b/Task/Loop-over-multiple-arrays-simultaneously/Salmon/loop-over-multiple-arrays-simultaneously-2.salmon index 147765e7c8..5db791ee3d 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Salmon/loop-over-multiple-arrays-simultaneously-2.salmon +++ b/Task/Loop-over-multiple-arrays-simultaneously/Salmon/loop-over-multiple-arrays-simultaneously-2.salmon @@ -1,4 +1,5 @@ -// First, we'll define a general-purpose zip() to zip any +// First, we'll define a general-purpose zip() to zip + any // number of lists together. function zip(...) { diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Standard-ML/loop-over-multiple-arrays-simultaneously.ml b/Task/Loop-over-multiple-arrays-simultaneously/Standard-ML/loop-over-multiple-arrays-simultaneously.ml index 6db5120840..4083d84b54 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Standard-ML/loop-over-multiple-arrays-simultaneously.ml +++ b/Task/Loop-over-multiple-arrays-simultaneously/Standard-ML/loop-over-multiple-arrays-simultaneously.ml @@ -2,7 +2,8 @@ * val combine_lists : string list list -> string list *) fun combine_lists nil = nil -| combine_lists (l1::ls) = List.foldl (ListPair.map (fn (x,y) => y ^ x)) l1 ls; +| combine_lists (l1::ls) = List.foldl (ListPair.map (fn (x,y) => y ^ + x)) l1 ls; (* ["a1Ax","b2By","c3Cz"] *) combine_lists[["a","b","c"],["1","2","3"],["A","B","C"],["x","y","z"]]; diff --git a/Task/Loop-over-multiple-arrays-simultaneously/SuperCollider/loop-over-multiple-arrays-simultaneously.supercollider b/Task/Loop-over-multiple-arrays-simultaneously/SuperCollider/loop-over-multiple-arrays-simultaneously.supercollider index 6bf43e3dc1..5ac19a31fb 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/SuperCollider/loop-over-multiple-arrays-simultaneously.supercollider +++ b/Task/Loop-over-multiple-arrays-simultaneously/SuperCollider/loop-over-multiple-arrays-simultaneously.supercollider @@ -1 +1,2 @@ -([\a,\b,\c]+++[\A,\B,\C]+++[1,2,3]).do({|array| array.do(_.post); "".postln }) +([\a,\b,\c]+++[\A,\B,\C]+++[1,2,3]).do({|array| +array.do(_.post); "".postln }) diff --git a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-2.txr b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-2.txr index 9e7f2543d8..86a17bafe7 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-2.txr +++ b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-2.txr @@ -1,4 +1,5 @@ -$ txr -e '(pprint (mappend (op list) "abc" "ABC" "123" (repeat "\n"))))' +$ txr -e '(pprint (mappend (op list) "abc" "ABC" "123" +(repeat "\n"))))' aA1 bB2 cC3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-3.txr b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-3.txr index 8c2139d138..aa3fc0aa5e 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-3.txr +++ b/Task/Loop-over-multiple-arrays-simultaneously/TXR/loop-over-multiple-arrays-simultaneously-3.txr @@ -1,4 +1,5 @@ -$ txr -e '(each ((x "abc") (y "ABC") (z "123")) (put-line `@x@y@z`))' +$ txr -e '(each ((x "abc") (y "ABC") (z "123")) +(put-line `@x@y@z`))' aA1 bB2 cC3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-2.sh b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-2.sh index bdfbee19ef..19c9848e81 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-2.sh +++ b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-2.sh @@ -1,6 +1,9 @@ -a=(a b c) -b=(A B C) -c=(1 2 3) -for ((i = 0; i < ${#a[@]}; i++)); do - echo "${a[$i]}${b[$i]}${c[$i]}" +A='a1 a2 a3' +B='b1 b2 b3' + +set -- $B +for a in $A +do + printf "$a $1\n" + shift done diff --git a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-3.sh b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-3.sh index 64ddd2b9aa..bdfbee19ef 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-3.sh +++ b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-3.sh @@ -1,8 +1,6 @@ -set -A a a b c -set -A b A B C -set -A c 1 2 3 -((i = 0)) -while ((i < ${#a[@]})); do +a=(a b c) +b=(A B C) +c=(1 2 3) +for ((i = 0; i < ${#a[@]}; i++)); do echo "${a[$i]}${b[$i]}${c[$i]}" - ((i++)) done diff --git a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-4.sh b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-4.sh index 2d09654dd9..64ddd2b9aa 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-4.sh +++ b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-4.sh @@ -1,6 +1,8 @@ -a=(a b c) -b=(A B C) -c=(1 2 3) -for ((i = 1; i <= $#a; i++)); do - echo "$a[$i]$b[$i]$c[$i]" +set -A a a b c +set -A b A B C +set -A c 1 2 3 +((i = 0)) +while ((i < ${#a[@]})); do + echo "${a[$i]}${b[$i]}${c[$i]}" + ((i++)) done diff --git a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-5.sh b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-5.sh index 6af0c281b1..2d09654dd9 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-5.sh +++ b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-5.sh @@ -1,8 +1,6 @@ -set a=(a b c) -set b=(A B C) -set c=(1 2 3) -@ i = 1 -while ( $i <= $#a ) - echo "$a[$i]$b[$i]$c[$i]" - @ i += 1 -end +a=(a b c) +b=(A B C) +c=(1 2 3) +for ((i = 1; i <= $#a; i++)); do + echo "$a[$i]$b[$i]$c[$i]" +done diff --git a/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-6.sh b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-6.sh new file mode 100644 index 0000000000..6af0c281b1 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/UNIX-Shell/loop-over-multiple-arrays-simultaneously-6.sh @@ -0,0 +1,8 @@ +set a=(a b c) +set b=(A B C) +set c=(1 2 3) +@ i = 1 +while ( $i <= $#a ) + echo "$a[$i]$b[$i]$c[$i]" + @ i += 1 +end diff --git a/Task/Loop-over-multiple-arrays-simultaneously/ZX-Spectrum-Basic/loop-over-multiple-arrays-simultaneously.zx b/Task/Loop-over-multiple-arrays-simultaneously/ZX-Spectrum-Basic/loop-over-multiple-arrays-simultaneously.zx index 545ed60203..e69242b61b 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/ZX-Spectrum-Basic/loop-over-multiple-arrays-simultaneously.zx +++ b/Task/Loop-over-multiple-arrays-simultaneously/ZX-Spectrum-Basic/loop-over-multiple-arrays-simultaneously.zx @@ -6,7 +6,8 @@ 60 IF szb > max THEN LET max = szb: REM now try b 70 IF szc > max THEN LET max = szc: REM or c 80 REM populate our arrays, and as a bonus we already have our demo loop -90 REM we might as well print as we populate showing the arrays in columns +90 REM we might as well print as we populate showing the arrays in +columns 100 FOR l = 1 TO max 110 IF l <= sza THEN READ a$(l): PRINT a$(l); 120 IF l <= szb THEN READ b$(l): PRINT b$(l); diff --git a/Task/Loops-Break/AppleScript/loops-break.applescript b/Task/Loops-Break/AppleScript/loops-break.applescript new file mode 100644 index 0000000000..ea3c69934c --- /dev/null +++ b/Task/Loops-Break/AppleScript/loops-break.applescript @@ -0,0 +1,9 @@ +repeat + set a to random number from 0 to 19 + if a is 10 then + log a + exit repeat + end if + set b to random number from 0 to 19 + log a & b +end repeat diff --git a/Task/Loops-Break/Ela/loops-break.ela b/Task/Loops-Break/Ela/loops-break.ela index 884cc68e0c..4e26b45d72 100644 --- a/Task/Loops-Break/Ela/loops-break.ela +++ b/Task/Loops-Break/Ela/loops-break.ela @@ -1,9 +1,12 @@ -open datetime random console +open datetime random monad io loop = loop' 1 - where loop' n t | r == t = writen (show r) - | else = writen (show r) `seq` loop' (n+1) t - where seed = toInt <| (ticks <| datetime.now()) * n - r = rnd seed 0 19 + where loop' n t = do + dt <- datetime.now + seed <- return <| toInt <| (ticks <| dt) * n + r <- return $ rnd seed 0 19 + putStrLn (show r) + if r <> t then loop' (n + 1) t else return () -loop 10 + +loop 10 ::: IO diff --git a/Task/Loops-Break/Elixir/loops-break.elixir b/Task/Loops-Break/Elixir/loops-break.elixir new file mode 100644 index 0000000000..8c460d4857 --- /dev/null +++ b/Task/Loops-Break/Elixir/loops-break.elixir @@ -0,0 +1,15 @@ +defmodule Loops do + def break do + :random.seed(:os.timestamp) + break(:random.uniform(20)-1) + end + + def break(10), do: IO.puts 10 + def break(r) do + IO.write r + IO.puts ",\t#{:random.uniform(20)-1}" + break(:random.uniform(20)-1) + end +end + +Loops.break diff --git a/Task/Loops-Break/Fortran/loops-break-2.f b/Task/Loops-Break/Fortran/loops-break-2.f index 0d955030d8..59bd0f0457 100644 --- a/Task/Loops-Break/Fortran/loops-break-2.f +++ b/Task/Loops-Break/Fortran/loops-break-2.f @@ -28,7 +28,7 @@ PROGRAM LOOPBREAK STOP END -C FORTRAN 77 does not have come with a random number generator, but it +C FORTRAN 77 does not come with a random number generator, but it C is easy enough to type "fortran 77 random number generator" into your C preferred search engine and to copy and paste what you find. The C following code is a slightly-modified version of: diff --git a/Task/Loops-Break/Fortran/loops-break-3.f b/Task/Loops-Break/Fortran/loops-break-3.f new file mode 100644 index 0000000000..84473a188a --- /dev/null +++ b/Task/Loops-Break/Fortran/loops-break-3.f @@ -0,0 +1,31 @@ + SUBROUTINE RANDU(IX,IY,YFL) +Copied from the IBM1130 Scientific Subroutines Package (1130-CM-02X): Programmer's Manual, page 60. +CAUTION! This routine's 32-bit variant is reviled by Prof. Knuth and many others for good reason! + IY = IX*899 + IF (IY) 5,6,6 + 5 IY = IY + 32767 + 1 + 6 YFL = IY + YFL = YFL/32767. + END + + FUNCTION IR19(IX) + CALL RANDU(IX,IY,YFL) + IX = IY + I = YFL*20 + IF (I - 20) 12,11,11 + 11 I = 19 + 12 IR19 = I + END + + IX = 1 +Commence the loop. + 10 I = IR19(IX) + WRITE (6,11) I + 11 FORMAT (I3) + IF (I - 10) 12,20,12 + 12 I = IR19(IX) + WRITE (6,11) I + GO TO 10 +Cease. + 20 CONTINUE + END diff --git a/Task/Loops-Break/GW-BASIC/loops-break.gw-basic b/Task/Loops-Break/GW-BASIC/loops-break.gw-basic new file mode 100644 index 0000000000..640bd401fb --- /dev/null +++ b/Task/Loops-Break/GW-BASIC/loops-break.gw-basic @@ -0,0 +1,5 @@ +10 NUM = 0 +20 WHILE NUM <> 10 +30 NUM = INT(RND * 20) +40 PRINT NUM +50 WEND diff --git a/Task/Loops-Break/JavaScript/loops-break.js b/Task/Loops-Break/JavaScript/loops-break-1.js similarity index 100% rename from Task/Loops-Break/JavaScript/loops-break.js rename to Task/Loops-Break/JavaScript/loops-break-1.js diff --git a/Task/Loops-Break/JavaScript/loops-break-2.js b/Task/Loops-Break/JavaScript/loops-break-2.js new file mode 100644 index 0000000000..19b1bfd51b --- /dev/null +++ b/Task/Loops-Break/JavaScript/loops-break-2.js @@ -0,0 +1,13 @@ +(function streamTillInitialTen() { + var nFirst = Math.floor(Math.random() * 20); + + console.log(nFirst); + + if (nFirst === 10) return true; + + console.log( + Math.floor(Math.random() * 20) + ); + + return streamTillInitialTen(); +})(); diff --git a/Task/Loops-Break/JavaScript/loops-break-3.js b/Task/Loops-Break/JavaScript/loops-break-3.js new file mode 100644 index 0000000000..d2ec01bcf8 --- /dev/null +++ b/Task/Loops-Break/JavaScript/loops-break-3.js @@ -0,0 +1,34 @@ +18 +10 +16 +10 +8 +0 +13 +3 +2 +14 +15 +17 +14 +7 +10 +8 +0 +2 +0 +2 +5 +16 +3 +16 +6 +7 +19 +0 +16 +9 +7 +11 +17 +10 diff --git a/Task/Loops-Break/JavaScript/loops-break-4.js b/Task/Loops-Break/JavaScript/loops-break-4.js new file mode 100644 index 0000000000..d361170756 --- /dev/null +++ b/Task/Loops-Break/JavaScript/loops-break-4.js @@ -0,0 +1,14 @@ +console.log( + (function streamTillInitialTen() { + var nFirst = Math.floor(Math.random() * 20); + + if (nFirst === 10) return [10]; + + return [ + nFirst, + Math.floor(Math.random() * 20) + ].concat( + streamTillInitialTen() + ); + })().join('\n') +); diff --git a/Task/Loops-Break/JavaScript/loops-break-5.js b/Task/Loops-Break/JavaScript/loops-break-5.js new file mode 100644 index 0000000000..45da2611f7 --- /dev/null +++ b/Task/Loops-Break/JavaScript/loops-break-5.js @@ -0,0 +1,9 @@ +17 +14 +3 +4 +13 +10 +15 +5 +10 diff --git a/Task/Loops-Break/Julia/loops-break.julia b/Task/Loops-Break/Julia/loops-break.julia new file mode 100644 index 0000000000..50cd5f9c19 --- /dev/null +++ b/Task/Loops-Break/Julia/loops-break.julia @@ -0,0 +1,10 @@ +while true + n = rand(0:19) + @printf "%4d" n + if n == 10 + println() + break + end + n = rand(0:19) + @printf "%4d\n" n +end diff --git a/Task/Loops-Break/Rust/loops-break.rust b/Task/Loops-Break/Rust/loops-break.rust index c6e587c30f..91bba217d6 100644 --- a/Task/Loops-Break/Rust/loops-break.rust +++ b/Task/Loops-Break/Rust/loops-break.rust @@ -1,14 +1,15 @@ -use std::rand; -use std::rand::Rng; +use rand::Rng; + +extern crate rand; fn main() { - let mut rng = rand::task_rng(); - loop { - let num = rng.gen_range(0, 20); - println!("{:d}", num); - if num == 10 { - break; + let mut rng = rand::thread_rng(); + loop { + let num = rng.gen_range(0, 20); + println!("{}", num); + if num == 10 { + break; + } + println!("{}", rng.gen_range(0, 20)); } - println!("{:d}", rng.gen_range(0, 20)); - } } diff --git a/Task/Loops-Break/Scilab/loops-break.scilab b/Task/Loops-Break/Scilab/loops-break.scilab new file mode 100644 index 0000000000..4815503854 --- /dev/null +++ b/Task/Loops-Break/Scilab/loops-break.scilab @@ -0,0 +1,8 @@ +while %T + a=int(rand()*20) // [0..19] + printf("%2d ",a) + if a==10 then break; end + b=int(rand()*20) + printf("%2d\n",b) +end +printf("\n") diff --git a/Task/Loops-Continue/360-Assembly/loops-continue.360 b/Task/Loops-Continue/360-Assembly/loops-continue.360 new file mode 100644 index 0000000000..bd62396aae --- /dev/null +++ b/Task/Loops-Continue/360-Assembly/loops-continue.360 @@ -0,0 +1,32 @@ +* Loops/Continue 12/08/2015 +LOOPCONT CSECT + USING LOOPCONT,R12 + LR R12,R15 +BEGIN LA R8,0 + SR R5,R5 + LA R6,1 + LA R7,10 +LOOPI BXH R5,R6,ELOOPI for i=1 to 10 + LA R3,MVC(R8) + XDECO R5,XDEC + MVC 0(4,R3),XDEC+8 + LA R8,4(R8) + LR R10,R5 + LA R1,5 + SRDA R10,32 + DR R10,R1 + LTR R10,R10 + BNZ COMMA + XPRNT MVC,80 + LA R8,0 + B NEXTI +COMMA LA R3,MVC(R8) + MVC 0(2,R3),=C', ' + LA R8,2(R8) +NEXTI B LOOPI next i +ELOOPI XR R15,R15 + BR R14 +MVC DC CL80' ' +XDEC DS CL16 + YREGS + END LOOPCONT diff --git a/Task/Loops-Continue/Ada/loops-continue.ada b/Task/Loops-Continue/Ada/loops-continue.ada index 2e676ec1d1..83cfebe195 100644 --- a/Task/Loops-Continue/Ada/loops-continue.ada +++ b/Task/Loops-Continue/Ada/loops-continue.ada @@ -10,8 +10,6 @@ begin goto Continue; end if; Put (","); - -- label must be followed by a statement. - <> - null; + <> --Ada 2012 no longer requires a statement after the label end loop; end Loop_Continue; diff --git a/Task/Loops-Continue/Ela/loops-continue-1.ela b/Task/Loops-Continue/Ela/loops-continue-1.ela index e64a878c29..211e6474f6 100644 --- a/Task/Loops-Continue/Ela/loops-continue-1.ela +++ b/Task/Loops-Continue/Ela/loops-continue-1.ela @@ -1,8 +1,13 @@ -open console imperative +open monad io -loop n | n > 10 = () - | else = rec write (show n) f `seq` loop (n+1) - where f | n % 5 == 0 = "\r\n" - | else = ", " +loop n = + if n > 10 then do + return () + else do + putStr (show n) + putStr f + loop (n + 1) + where f | n % 5 == 0 = "\r\n" + | else = ", " -loop 1 +_ = loop 1 ::: IO diff --git a/Task/Loops-Continue/Ela/loops-continue-2.ela b/Task/Loops-Continue/Ela/loops-continue-2.ela index 529a64ab30..f25e34cf38 100644 --- a/Task/Loops-Continue/Ela/loops-continue-2.ela +++ b/Task/Loops-Continue/Ela/loops-continue-2.ela @@ -1,8 +1,11 @@ -open console imperative +open monad io -loop [] = () -loop (x::xs) = rec (write << show) x c `seq` loop xs - where c | x % 5 == 0 = "\r\n" - | else = ", " +loop [] = return () +loop (x::xs) = do + putStr (show x) + putStr f + loop xs + where f | x % 5 == 0 = "\r\n" + | else = ", " -loop [1..10] +_ = loop [1..10] ::: IO diff --git a/Task/Loops-Continue/Elixir/loops-continue.elixir b/Task/Loops-Continue/Elixir/loops-continue.elixir new file mode 100644 index 0000000000..bdc5484708 --- /dev/null +++ b/Task/Loops-Continue/Elixir/loops-continue.elixir @@ -0,0 +1,10 @@ +defmodule Loops do + def continue do + Enum.each(1..10, fn i -> + IO.write i + IO.write if rem(i,5)==0, do: "\n", else: ", " + end) + end +end + +Loops.continue diff --git a/Task/Loops-Continue/Erlang/loops-continue.erl b/Task/Loops-Continue/Erlang/loops-continue.erl index b09cceea16..fde1c7bc0f 100644 --- a/Task/Loops-Continue/Erlang/loops-continue.erl +++ b/Task/Loops-Continue/Erlang/loops-continue.erl @@ -4,18 +4,18 @@ main() -> for_loop(1). - - for_loop(N) when N /= 5 , N <10 -> + +for_loop(N) when N /= 5 , N <10 -> io:format("~p, ",[N] ), - for_loop(N+1); + for_loop(N+1); for_loop(N) when N >=10-> - if N=:=10 -> + if N=:=10 -> io:format("~p\n",[N] ) end; - for_loop(N) -> - if N=:=5 -> +for_loop(N) -> + if N=:=5 -> io:format("~p\n",[N] ), for_loop(N+1) end. diff --git a/Task/Loops-Continue/Fortran/loops-continue-3.f b/Task/Loops-Continue/Fortran/loops-continue-3.f new file mode 100644 index 0000000000..79bda1f117 --- /dev/null +++ b/Task/Loops-Continue/Fortran/loops-continue-3.f @@ -0,0 +1,3 @@ + WRITE (6,1) (I,I = 1,10) + 1 FORMAT (4(1X,I0,","),1X,I0) + END diff --git a/Task/Loops-Continue/JavaScript/loops-continue.js b/Task/Loops-Continue/JavaScript/loops-continue-1.js similarity index 100% rename from Task/Loops-Continue/JavaScript/loops-continue.js rename to Task/Loops-Continue/JavaScript/loops-continue-1.js diff --git a/Task/Loops-Continue/JavaScript/loops-continue-2.js b/Task/Loops-Continue/JavaScript/loops-continue-2.js new file mode 100644 index 0000000000..b5567bce60 --- /dev/null +++ b/Task/Loops-Continue/JavaScript/loops-continue-2.js @@ -0,0 +1,11 @@ +function rng(n) { + return n ? rng(n - 1).concat(n) : []; +} + +console.log( + rng(10).reduce( + function (a, x) { + return a + x.toString() + (x % 5 ? ', ' : '\n'); + }, '' + ) +); diff --git a/Task/Loops-Continue/JavaScript/loops-continue-3.js b/Task/Loops-Continue/JavaScript/loops-continue-3.js new file mode 100644 index 0000000000..0865d3f81d --- /dev/null +++ b/Task/Loops-Continue/JavaScript/loops-continue-3.js @@ -0,0 +1,2 @@ +1, 2, 3, 4, 5 +6, 7, 8, 9, 10 diff --git a/Task/Loops-Continue/Julia/loops-continue.julia b/Task/Loops-Continue/Julia/loops-continue.julia new file mode 100644 index 0000000000..3bfbf64b7d --- /dev/null +++ b/Task/Loops-Continue/Julia/loops-continue.julia @@ -0,0 +1,8 @@ +for i in 1:10 + print(i) + if i%5 == 0 + println() + continue + end + print(", ") +end diff --git a/Task/Loops-Continue/Rust/loops-continue.rust b/Task/Loops-Continue/Rust/loops-continue.rust index 1463e3d6fe..986895a25c 100644 --- a/Task/Loops-Continue/Rust/loops-continue.rust +++ b/Task/Loops-Continue/Rust/loops-continue.rust @@ -1,12 +1,10 @@ -use std::iter::range_inclusive; - fn main() { - for i in range_inclusive(1, 10) { - print!("{:d}", i); - if i % 5 == 0 { - print("\n"); - continue; + for i in 1..10+1 { + print!("{}", i); + if i % 5 == 0 { + print!("\n"); + continue; + } + print!(", "); } - print(", "); - } } diff --git a/Task/Loops-Continue/Scilab/loops-continue.scilab b/Task/Loops-Continue/Scilab/loops-continue.scilab new file mode 100644 index 0000000000..c0924a3870 --- /dev/null +++ b/Task/Loops-Continue/Scilab/loops-continue.scilab @@ -0,0 +1,8 @@ +for i=1:10 + printf("%2d ",i) + if modulo(i,5)~=0 then + printf(", ") + continue + end + printf("\n") +end diff --git a/Task/Loops-Do-while/00DESCRIPTION b/Task/Loops-Do-while/00DESCRIPTION index 2bdec501ef..06410343d4 100644 --- a/Task/Loops-Do-while/00DESCRIPTION +++ b/Task/Loops-Do-while/00DESCRIPTION @@ -1,3 +1,6 @@ Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. + +;Reference: +* [[wp:Do while loop|Do while loop]] Wikipedia. diff --git a/Task/Loops-Do-while/ALGOL-W/loops-do-while.alg b/Task/Loops-Do-while/ALGOL-W/loops-do-while.alg new file mode 100644 index 0000000000..1753d299f4 --- /dev/null +++ b/Task/Loops-Do-while/ALGOL-W/loops-do-while.alg @@ -0,0 +1,11 @@ +begin + integer i; + i := 0; + while + begin + i := i + 1; + write( i ); + ( i rem 6 ) not = 0 + end + do begin end +end. diff --git a/Task/Loops-Do-while/Ela/loops-do-while.ela b/Task/Loops-Do-while/Ela/loops-do-while.ela index d4b6a3293b..0a71814359 100644 --- a/Task/Loops-Do-while/Ela/loops-do-while.ela +++ b/Task/Loops-Do-while/Ela/loops-do-while.ela @@ -1,5 +1,8 @@ -open console +open monad io -loop n | n % 6 == 0 = out () - | else = out `seq` loop (n+1) - where out = & writen n +loop n | n % 6 == 0 = do return () + | else = do + putStrLn (show n) + loop (n+1) + +_ = loop 10 ::: IO diff --git a/Task/Loops-Do-while/Elixir/loops-do-while.elixir b/Task/Loops-Do-while/Elixir/loops-do-while.elixir new file mode 100644 index 0000000000..d97479a221 --- /dev/null +++ b/Task/Loops-Do-while/Elixir/loops-do-while.elixir @@ -0,0 +1,10 @@ +defmodule Loops do + def do_while(n) do + n1 = n + 1 + IO.puts n1 + if rem(n1, 6) == 0, do: :ok, + else: do_while(n1) + end +end + +Loops.do_while(0) diff --git a/Task/Loops-Do-while/JavaScript/loops-do-while.js b/Task/Loops-Do-while/JavaScript/loops-do-while-1.js similarity index 100% rename from Task/Loops-Do-while/JavaScript/loops-do-while.js rename to Task/Loops-Do-while/JavaScript/loops-do-while-1.js diff --git a/Task/Loops-Do-while/JavaScript/loops-do-while-2.js b/Task/Loops-Do-while/JavaScript/loops-do-while-2.js new file mode 100644 index 0000000000..62d66e26eb --- /dev/null +++ b/Task/Loops-Do-while/JavaScript/loops-do-while-2.js @@ -0,0 +1,19 @@ +function doWhile(varValue, fnBody, fnTest) { + 'use strict'; + var d = fnBody(varValue); // a transformed value + + return fnTest(d) ? [d].concat( + doWhile(d, fnBody, fnTest) + ) : [d]; +} + +console.log( + doWhile(0, // initial value + function (x) { // Do body, returning transformed value + return x + 1; + }, + function (x) { // While condition + return x % 6; + } + ).join('\n') +); diff --git a/Task/Loops-Do-while/JavaScript/loops-do-while-3.js b/Task/Loops-Do-while/JavaScript/loops-do-while-3.js new file mode 100644 index 0000000000..b414108e81 --- /dev/null +++ b/Task/Loops-Do-while/JavaScript/loops-do-while-3.js @@ -0,0 +1,6 @@ +1 +2 +3 +4 +5 +6 diff --git a/Task/Loops-Do-while/JavaScript/loops-do-while-4.js b/Task/Loops-Do-while/JavaScript/loops-do-while-4.js new file mode 100644 index 0000000000..6a39b9997c --- /dev/null +++ b/Task/Loops-Do-while/JavaScript/loops-do-while-4.js @@ -0,0 +1,28 @@ +function range(m, n) { + 'use strict'; + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { + return m + i; + } + ); +} + +function takeWhile(lst, fnTest) { + 'use strict'; + var varHead = lst.length ? lst[0] : null; + + return varHead ? ( + fnTest(varHead) ? [varHead].concat( + takeWhile(lst.slice(1), fnTest) + ) : [] + ) : [] +} + +console.log( + takeWhile( + range(1, 100), + function (x) { + return x % 6; + } + ).join('\n') +); diff --git a/Task/Loops-Do-while/JavaScript/loops-do-while-5.js b/Task/Loops-Do-while/JavaScript/loops-do-while-5.js new file mode 100644 index 0000000000..8a1218a102 --- /dev/null +++ b/Task/Loops-Do-while/JavaScript/loops-do-while-5.js @@ -0,0 +1,5 @@ +1 +2 +3 +4 +5 diff --git a/Task/Loops-Do-while/Julia/loops-do-while.julia b/Task/Loops-Do-while/Julia/loops-do-while.julia new file mode 100644 index 0000000000..362312e9e2 --- /dev/null +++ b/Task/Loops-Do-while/Julia/loops-do-while.julia @@ -0,0 +1,8 @@ +i = 0 +while true + println(i) + i += 1 + if i%6 == 0 + break + end +end diff --git a/Task/Loops-Do-while/Rust/loops-do-while.rust b/Task/Loops-Do-while/Rust/loops-do-while.rust new file mode 100644 index 0000000000..5057405648 --- /dev/null +++ b/Task/Loops-Do-while/Rust/loops-do-while.rust @@ -0,0 +1,8 @@ +let mut x = 0; + +loop { + x += 1; + println!("{}", x); + + if x % 6 == 0 { break; } +} diff --git a/Task/Loops-Do-while/Scilab/loops-do-while.scilab b/Task/Loops-Do-while/Scilab/loops-do-while.scilab new file mode 100644 index 0000000000..2addd2af73 --- /dev/null +++ b/Task/Loops-Do-while/Scilab/loops-do-while.scilab @@ -0,0 +1,7 @@ +v=0 +while %T + v=v+1 + printf("%2d ",v) + if modulo(v,6)==0 then break; end +end +printf("\n") diff --git a/Task/Loops-Downward-for/360-Assembly/loops-downward-for.360 b/Task/Loops-Downward-for/360-Assembly/loops-downward-for.360 new file mode 100644 index 0000000000..60fe8b7380 --- /dev/null +++ b/Task/Loops-Downward-for/360-Assembly/loops-downward-for.360 @@ -0,0 +1,26 @@ +* Loops/Downward for 27/07/2015 +LOOPDOWN CSECT + USING LOOPDOWN,R12 + LR R12,R15 set base register +BEGIN EQU * +* fisrt loop with a BXLE BXLE: Branch on indeX Low or Equal + LH R2,=H'11' from 10 (R2=11) index + LH R4,=H'-1' step -1 (R4=-1) + LH R5,=H'-1' to 0 (R5=-1) +LOOPI BXLE R2,R4,ELOOPI R2=R2+R4 if R2<=R5 goto ELOOPI + XDECO R2,BUFFER edit R2 + XPRNT BUFFER,L'BUFFER print + B LOOPI +ELOOPI EQU * +* second loop with a BCT BCT: Branch on CounT + LA R2,10 index R2=10 + LA R3,11 counter R3=11 +LOOPJ XDECO R2,BUFFER edit R2 + XPRNT BUFFER,L'BUFFER print + BCTR R2,0 R2=R2-1 +ELOOPJ BCT R3,LOOPJ R3=R3-1 if R3<>0 goto LOOPI +RETURN XR R15,R15 set return code + BR R14 return to caller +BUFFER DC CL80' ' + YREGS + END LOOPDOWN diff --git a/Task/Loops-Downward-for/ALGOL-W/loops-downward-for.alg b/Task/Loops-Downward-for/ALGOL-W/loops-downward-for.alg new file mode 100644 index 0000000000..a8b2c36806 --- /dev/null +++ b/Task/Loops-Downward-for/ALGOL-W/loops-downward-for.alg @@ -0,0 +1,6 @@ +begin + for i := 10 step -1 until 0 do + begin + write( i ) + end +end. diff --git a/Task/Loops-Downward-for/AppleScript/loops-downward-for.applescript b/Task/Loops-Downward-for/AppleScript/loops-downward-for.applescript new file mode 100644 index 0000000000..22c5d03678 --- /dev/null +++ b/Task/Loops-Downward-for/AppleScript/loops-downward-for.applescript @@ -0,0 +1,3 @@ +repeat with i from 10 to 0 by -1 + log i +end repeat diff --git a/Task/Loops-Downward-for/Batch-File/loops-downward-for.bat b/Task/Loops-Downward-for/Batch-File/loops-downward-for.bat new file mode 100644 index 0000000000..cc4c99bd0b --- /dev/null +++ b/Task/Loops-Downward-for/Batch-File/loops-downward-for.bat @@ -0,0 +1,2 @@ +@echo off +for /l %%D in (10,-1,0) do echo %%D diff --git a/Task/Loops-Downward-for/Befunge/loops-downward-for.bf b/Task/Loops-Downward-for/Befunge/loops-downward-for.bf index ebd62701bb..82dbfb0ca0 100644 --- a/Task/Loops-Downward-for/Befunge/loops-downward-for.bf +++ b/Task/Loops-Downward-for/Befunge/loops-downward-for.bf @@ -1,2 +1,2 @@ 55+>:.:v - ^ -1_@ +@ ^ -1_ diff --git a/Task/Loops-Downward-for/Ela/loops-downward-for-1.ela b/Task/Loops-Downward-for/Ela/loops-downward-for-1.ela index 70d62c5b46..cea4668d81 100644 --- a/Task/Loops-Downward-for/Ela/loops-downward-for-1.ela +++ b/Task/Loops-Downward-for/Ela/loops-downward-for-1.ela @@ -1,3 +1,8 @@ -open console imperative +open monad io -each writen [10,9..0] +each [] = do return () +each (x::xs) = do + putStrLn $ show x + each xs + +each [10,9..0] ::: IO diff --git a/Task/Loops-Downward-for/Ela/loops-downward-for-2.ela b/Task/Loops-Downward-for/Ela/loops-downward-for-2.ela index f18f245256..25d6904e24 100644 --- a/Task/Loops-Downward-for/Ela/loops-downward-for-2.ela +++ b/Task/Loops-Downward-for/Ela/loops-downward-for-2.ela @@ -1,2 +1,8 @@ -each f (x::xs) = f x $ each f xs -each _ [] = () +open monad io + +countDown m n | n < m = do return () + | else = do + putStrLn $ show n + countDown m (n - 1) + +_ = countDown 0 10 ::: IO diff --git a/Task/Loops-Downward-for/Elixir/loops-downward-for.elixir b/Task/Loops-Downward-for/Elixir/loops-downward-for.elixir new file mode 100644 index 0000000000..307283263f --- /dev/null +++ b/Task/Loops-Downward-for/Elixir/loops-downward-for.elixir @@ -0,0 +1,13 @@ +iex(1)> Enum.each(10..0, fn i -> IO.puts i end) +10 +9 +8 +7 +6 +5 +4 +3 +2 +1 +0 +:ok diff --git a/Task/Loops-Downward-for/GML/loops-downward-for.gml b/Task/Loops-Downward-for/GML/loops-downward-for.gml index 18b1379de5..15116bdcbe 100644 --- a/Task/Loops-Downward-for/GML/loops-downward-for.gml +++ b/Task/Loops-Downward-for/GML/loops-downward-for.gml @@ -1,2 +1,2 @@ -for(i = 10; i >= 0; i += 1) +for(i = 10; i >= 0; i -= 1) show_message(string(i)) diff --git a/Task/Loops-Downward-for/JavaScript/loops-downward-for.js b/Task/Loops-Downward-for/JavaScript/loops-downward-for-1.js similarity index 100% rename from Task/Loops-Downward-for/JavaScript/loops-downward-for.js rename to Task/Loops-Downward-for/JavaScript/loops-downward-for-1.js diff --git a/Task/Loops-Downward-for/JavaScript/loops-downward-for-2.js b/Task/Loops-Downward-for/JavaScript/loops-downward-for-2.js new file mode 100644 index 0000000000..154e2e1795 --- /dev/null +++ b/Task/Loops-Downward-for/JavaScript/loops-downward-for-2.js @@ -0,0 +1 @@ +for (var i = 11; i--;) console.log(i); diff --git a/Task/Loops-Downward-for/JavaScript/loops-downward-for-3.js b/Task/Loops-Downward-for/JavaScript/loops-downward-for-3.js new file mode 100644 index 0000000000..f9b95b2543 --- /dev/null +++ b/Task/Loops-Downward-for/JavaScript/loops-downward-for-3.js @@ -0,0 +1,2 @@ +var i = 11; +while (i--) console.log(i); diff --git a/Task/Loops-Downward-for/JavaScript/loops-downward-for-4.js b/Task/Loops-Downward-for/JavaScript/loops-downward-for-4.js new file mode 100644 index 0000000000..c4ab068d7e --- /dev/null +++ b/Task/Loops-Downward-for/JavaScript/loops-downward-for-4.js @@ -0,0 +1,13 @@ +function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { + return m + i; + } + ); +} + +range(0, 10).reverse().forEach( + function (x) { + console.log(x); + } +); diff --git a/Task/Loops-Downward-for/JavaScript/loops-downward-for-5.js b/Task/Loops-Downward-for/JavaScript/loops-downward-for-5.js new file mode 100644 index 0000000000..a8d9c344c4 --- /dev/null +++ b/Task/Loops-Downward-for/JavaScript/loops-downward-for-5.js @@ -0,0 +1,7 @@ +console.log( + range(0, 10).reverse().map( + function (x) { + return x; + } + ).join('\n') +); diff --git a/Task/Loops-Downward-for/JavaScript/loops-downward-for-6.js b/Task/Loops-Downward-for/JavaScript/loops-downward-for-6.js new file mode 100644 index 0000000000..bb1e2c3af5 --- /dev/null +++ b/Task/Loops-Downward-for/JavaScript/loops-downward-for-6.js @@ -0,0 +1,3 @@ +console.log( + range(0, 10).reverse().join('\n') +); diff --git a/Task/Loops-Downward-for/Rust/loops-downward-for.rust b/Task/Loops-Downward-for/Rust/loops-downward-for.rust index d4074b270e..cd1f455b98 100644 --- a/Task/Loops-Downward-for/Rust/loops-downward-for.rust +++ b/Task/Loops-Downward-for/Rust/loops-downward-for.rust @@ -1,7 +1,5 @@ -// rust 0.9-pre - fn main() { - for i in std::iter::range_inclusive(0, 10).invert() { + for i in (1..10+1).rev() { println!("{}", i); } } diff --git a/Task/Loops-Downward-for/Scilab/loops-downward-for.scilab b/Task/Loops-Downward-for/Scilab/loops-downward-for.scilab new file mode 100644 index 0000000000..5e23e9b4b6 --- /dev/null +++ b/Task/Loops-Downward-for/Scilab/loops-downward-for.scilab @@ -0,0 +1,3 @@ +for i=10:-1:0 + printf("%d\n",i) +end diff --git a/Task/Loops-Downward-for/TI-83-BASIC/loops-downward-for.ti-83 b/Task/Loops-Downward-for/TI-83-BASIC/loops-downward-for.ti-83 index 0f341dccd5..e5460f0442 100644 --- a/Task/Loops-Downward-for/TI-83-BASIC/loops-downward-for.ti-83 +++ b/Task/Loops-Downward-for/TI-83-BASIC/loops-downward-for.ti-83 @@ -1,3 +1,3 @@ -:For(I,10,0,–1) - :Disp I +:For(I,10,0,-1 +:Disp I :End diff --git a/Task/Loops-For-with-a-specified-step/360-Assembly/loops-for-with-a-specified-step.360 b/Task/Loops-For-with-a-specified-step/360-Assembly/loops-for-with-a-specified-step.360 new file mode 100644 index 0000000000..38dd77dfcc --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/360-Assembly/loops-for-with-a-specified-step.360 @@ -0,0 +1,20 @@ +* Loops/For with a specified step 12/08/2015 +LOOPFORS CSECT + USING LOOPFORS,R12 + LR R12,R15 +BEGIN LA R3,MVC + SR R5,R5 index + LA R6,5 step 5 + LA R7,25 to 25 +LOOPI BXH R5,R6,ELOOPI for i=5 to 25 step 5 + XDECO R5,XDEC + MVC 0(4,R3),XDEC+8 + LA R3,4(R3) +NEXTI B LOOPI next i +ELOOPI XPRNT MVC,80 + XR R15,R15 + BR R14 +MVC DC CL80' ' +XDEC DS CL12 + YREGS + END LOOPFORS diff --git a/Task/Loops-For-with-a-specified-step/ALGOL-W/loops-for-with-a-specified-step.alg b/Task/Loops-For-with-a-specified-step/ALGOL-W/loops-for-with-a-specified-step.alg new file mode 100644 index 0000000000..d9ac4253bd --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/ALGOL-W/loops-for-with-a-specified-step.alg @@ -0,0 +1,3 @@ +begin + for i := 3 step 2 until 9 do write( i ) +end. diff --git a/Task/Loops-For-with-a-specified-step/Batch-File/loops-for-with-a-specified-step.bat b/Task/Loops-For-with-a-specified-step/Batch-File/loops-for-with-a-specified-step.bat new file mode 100644 index 0000000000..ee37bbdb8e --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Batch-File/loops-for-with-a-specified-step.bat @@ -0,0 +1,4 @@ +@echo off +for /l %%A in (1,2,10) do ( + echo %%A +) diff --git a/Task/Loops-For-with-a-specified-step/Befunge/loops-for-with-a-specified-step.bf b/Task/Loops-For-with-a-specified-step/Befunge/loops-for-with-a-specified-step.bf new file mode 100644 index 0000000000..f8916330b2 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Befunge/loops-for-with-a-specified-step.bf @@ -0,0 +1,2 @@ +1 >:.55+,v +@_^#`9:+2< diff --git a/Task/Loops-For-with-a-specified-step/Ela/loops-for-with-a-specified-step.ela b/Task/Loops-For-with-a-specified-step/Ela/loops-for-with-a-specified-step.ela index 8ec3797d33..6e26696e3a 100644 --- a/Task/Loops-For-with-a-specified-step/Ela/loops-for-with-a-specified-step.ela +++ b/Task/Loops-For-with-a-specified-step/Ela/loops-for-with-a-specified-step.ela @@ -1,6 +1,8 @@ -open console +open monad io -for m s n | n > m = () - | else = writen n $ for m s (n+s) +for m s n | n > m = do return () + | else = do + putStrLn (show n) + for m s (n+s) -for 10 2 0 +_ = for 10 2 0 ::: IO diff --git a/Task/Loops-For-with-a-specified-step/Elixir/loops-for-with-a-specified-step-1.elixir b/Task/Loops-For-with-a-specified-step/Elixir/loops-for-with-a-specified-step-1.elixir new file mode 100644 index 0000000000..f5b92d218f --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Elixir/loops-for-with-a-specified-step-1.elixir @@ -0,0 +1,7 @@ +defmodule Loops do + def for_step(n, step) do + IO.inspect Enum.take_every(1..n, step) + end +end + +Loops.for_step(20, 3) diff --git a/Task/Loops-For-with-a-specified-step/Elixir/loops-for-with-a-specified-step-2.elixir b/Task/Loops-For-with-a-specified-step/Elixir/loops-for-with-a-specified-step-2.elixir new file mode 100644 index 0000000000..70232493b6 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Elixir/loops-for-with-a-specified-step-2.elixir @@ -0,0 +1,2 @@ +iex(1)> Stream.iterate(1, &(&1+2)) |> Enum.take(10) +[1, 3, 5, 7, 9, 11, 13, 15, 17, 19] diff --git a/Task/Loops-For-with-a-specified-step/JavaScript/loops-for-with-a-specified-step.js b/Task/Loops-For-with-a-specified-step/JavaScript/loops-for-with-a-specified-step-1.js similarity index 100% rename from Task/Loops-For-with-a-specified-step/JavaScript/loops-for-with-a-specified-step.js rename to Task/Loops-For-with-a-specified-step/JavaScript/loops-for-with-a-specified-step-1.js diff --git a/Task/Loops-For-with-a-specified-step/JavaScript/loops-for-with-a-specified-step-2.js b/Task/Loops-For-with-a-specified-step/JavaScript/loops-for-with-a-specified-step-2.js new file mode 100644 index 0000000000..65780ab073 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/JavaScript/loops-for-with-a-specified-step-2.js @@ -0,0 +1,21 @@ +// range(iMax) +// range(iMin, iMax) +// range(iMin, iMax, dI) +function range() { + var lngArgs = arguments.length, + lngMore = lngArgs - 1; + + iMin = lngMore ? arguments[0] : 1; + iMax = arguments[lngMore ? 1 : 0]; + dI = lngMore > 1 ? arguments[2] : 1; + + return lngArgs ? Array.apply(null, Array( + Math.floor((iMax - iMin) / dI) + 1 + )).map(function (_, i) { + return iMin + (dI * i); + }) : []; +} + +console.log( + range(2, 8, 2).join(', ') + ', who do we appreciate ?' +); diff --git a/Task/Loops-For-with-a-specified-step/Maple/loops-for-with-a-specified-step.maple b/Task/Loops-For-with-a-specified-step/Maple/loops-for-with-a-specified-step.maple index bbbfe0a74b..4cc48b053c 100644 --- a/Task/Loops-For-with-a-specified-step/Maple/loops-for-with-a-specified-step.maple +++ b/Task/Loops-For-with-a-specified-step/Maple/loops-for-with-a-specified-step.maple @@ -1,3 +1,3 @@ -for i from 1 to 6 by 2 do +for i from 2 to 8 by 2 do i; end do; diff --git a/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step-1.rust b/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step-1.rust new file mode 100644 index 0000000000..e4e8c17d35 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step-1.rust @@ -0,0 +1,8 @@ +fn main() { + let mut i = 2; + while i <= 8 { + print!("{}, ", i); + i += 2; + } + println!("who do we appreciate?!"); +} diff --git a/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step-2.rust b/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step-2.rust new file mode 100644 index 0000000000..b149dd9f09 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step-2.rust @@ -0,0 +1,8 @@ +#![feature(step_by)] + +fn main() { + for i in (2..8+1).step_by(2) { + print!("{}", i); + } + println!("who do we appreciate?!"); +} diff --git a/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step.rust b/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step.rust deleted file mode 100644 index d5daf6a1db..0000000000 --- a/Task/Loops-For-with-a-specified-step/Rust/loops-for-with-a-specified-step.rust +++ /dev/null @@ -1,8 +0,0 @@ -use std::iter::range_step_inclusive; - -fn main() { - for i in range_step_inclusive(2, 8, 2) { - print!("{:d}, ", i); - } - println("who do we appreciate?!"); -} diff --git a/Task/Loops-For-with-a-specified-step/Scilab/loops-for-with-a-specified-step.scilab b/Task/Loops-For-with-a-specified-step/Scilab/loops-for-with-a-specified-step.scilab new file mode 100644 index 0000000000..35d38d6f41 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Scilab/loops-for-with-a-specified-step.scilab @@ -0,0 +1,3 @@ +for i=1:2:10 + printf("%d\n",i) +end diff --git a/Task/Loops-For-with-a-specified-step/TI-83-BASIC/loops-for-with-a-specified-step.ti-83 b/Task/Loops-For-with-a-specified-step/TI-83-BASIC/loops-for-with-a-specified-step.ti-83 new file mode 100644 index 0000000000..ba00750bf5 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/TI-83-BASIC/loops-for-with-a-specified-step.ti-83 @@ -0,0 +1,3 @@ +:For(I,0,100,5 +:Disp I +:End diff --git a/Task/Loops-For/00DESCRIPTION b/Task/Loops-For/00DESCRIPTION index 9dcb6e1a1d..a610234102 100644 --- a/Task/Loops-For/00DESCRIPTION +++ b/Task/Loops-For/00DESCRIPTION @@ -7,3 +7,6 @@ For this task, show how two loops may be nested within each other, with the numb *** **** ***** + +;Reference: +* [[wp:For loop|For loop]] Wikipedia. diff --git a/Task/Loops-For/360-Assembly/loops-for.360 b/Task/Loops-For/360-Assembly/loops-for.360 new file mode 100644 index 0000000000..295c7eecf4 --- /dev/null +++ b/Task/Loops-For/360-Assembly/loops-for.360 @@ -0,0 +1,23 @@ +LOOPFORC CSECT + USING LOOPFORC,R12 + LR R12,R15 set base register +BEGIN SR R2,R2 from 1 + LA R4,1 by 1 + LA R5,5 to 5 +LOOPI BXH R2,R4,ELOOPI i (R2) + LA R8,BUFFER-1 + SR R3,R3 from 1 + LA R6,1 by 1 + LR R7,R2 to i +LOOPJ BXH R3,R6,ELOOPJ j (R3) + LA R8,1(R8) + MVI 0(R8),C'*' + B LOOPJ +ELOOPJ XPRNT BUFFER,L'BUFFER + B LOOPI +ELOOPI EQU * +RETURN XR R15,R15 set return code + BR R14 return to caller +BUFFER DC CL80' ' + YREGS + END LOOPFORC diff --git a/Task/Loops-For/ALGOL-W/loops-for.alg b/Task/Loops-For/ALGOL-W/loops-for.alg new file mode 100644 index 0000000000..dde9d6b7da --- /dev/null +++ b/Task/Loops-For/ALGOL-W/loops-for.alg @@ -0,0 +1,10 @@ +begin + for i := 1 until 5 do + begin + write( "*" ); + for j := 2 until i do + begin + writeon( "*" ) + end j + end i +end. diff --git a/Task/Loops-For/Ela/loops-for-1.ela b/Task/Loops-For/Ela/loops-for-1.ela new file mode 100644 index 0000000000..58a4c363d9 --- /dev/null +++ b/Task/Loops-For/Ela/loops-for-1.ela @@ -0,0 +1,13 @@ +open monad io + +loop m n | n < m = do + loop' n 0 + putStrLn "" + loop m (n + 1) + | else = do return () + where loop' m n | n <= m = do + putStr "*" + loop' m (n + 1) + | else = do return () + +_ = loop 10 1 ::: IO diff --git a/Task/Loops-For/Ela/loops-for-2.ela b/Task/Loops-For/Ela/loops-for-2.ela new file mode 100644 index 0000000000..a7d3006fc1 --- /dev/null +++ b/Task/Loops-For/Ela/loops-for-2.ela @@ -0,0 +1,9 @@ +** +*** +**** +***** +****** +******* +******** +********* +********** diff --git a/Task/Loops-For/Ela/loops-for.ela b/Task/Loops-For/Ela/loops-for.ela deleted file mode 100644 index c43fbb77e2..0000000000 --- a/Task/Loops-For/Ela/loops-for.ela +++ /dev/null @@ -1,6 +0,0 @@ -open console - -loop m n | n < m = loop' n 0 $ writen "" $ loop m (n+1) - | else = () - where loop' m n | n <= m = write "*" $ loop' m (n+1) - | else = () diff --git a/Task/Loops-For/Elixir/loops-for.elixir b/Task/Loops-For/Elixir/loops-for.elixir new file mode 100644 index 0000000000..9ba88788bf --- /dev/null +++ b/Task/Loops-For/Elixir/loops-for.elixir @@ -0,0 +1,10 @@ +defmodule Loops do + def loops_for(n) do + Enum.each(1..n, fn i -> + Enum.each(1..i, fn _ -> IO.write "*" end) + IO.puts "" + end) + end +end + +Loops.loops_for(5) diff --git a/Task/Loops-For/Fortran/loops-for-4.f b/Task/Loops-For/Fortran/loops-for-4.f new file mode 100644 index 0000000000..97615abdce --- /dev/null +++ b/Task/Loops-For/Fortran/loops-for-4.f @@ -0,0 +1,3 @@ + DO 1 I = 1,5 + 1 WRITE (6,*) ("*", J = 1,I) + END diff --git a/Task/Loops-For/Fortran/loops-for-5.f b/Task/Loops-For/Fortran/loops-for-5.f new file mode 100644 index 0000000000..6b1fdf7159 --- /dev/null +++ b/Task/Loops-For/Fortran/loops-for-5.f @@ -0,0 +1,4 @@ + DO 1 I = 1,5 + 1 WRITE (6,2) (666, J = 1,I) + 2 FORMAT(5I1) + END diff --git a/Task/Loops-For/JavaScript/loops-for.js b/Task/Loops-For/JavaScript/loops-for-1.js similarity index 100% rename from Task/Loops-For/JavaScript/loops-for.js rename to Task/Loops-For/JavaScript/loops-for-1.js diff --git a/Task/Loops-For/JavaScript/loops-for-2.js b/Task/Loops-For/JavaScript/loops-for-2.js new file mode 100644 index 0000000000..ea12d52bc7 --- /dev/null +++ b/Task/Loops-For/JavaScript/loops-for-2.js @@ -0,0 +1,5 @@ +function range(i) { + return i ? range(i - 1).concat(i) : []; +} + +range(5) --> [1, 2, 3, 4, 5] diff --git a/Task/Loops-For/JavaScript/loops-for-3.js b/Task/Loops-For/JavaScript/loops-for-3.js new file mode 100644 index 0000000000..bf57002ace --- /dev/null +++ b/Task/Loops-For/JavaScript/loops-for-3.js @@ -0,0 +1,12 @@ +var s = ''; + +range(5).forEach( + function (line) { + range(line).forEach( + function () { s += '*'; } + ); + s += '\n'; + } +); + +console.log(s); diff --git a/Task/Loops-For/JavaScript/loops-for-4.js b/Task/Loops-For/JavaScript/loops-for-4.js new file mode 100644 index 0000000000..d00ff1924f --- /dev/null +++ b/Task/Loops-For/JavaScript/loops-for-4.js @@ -0,0 +1,7 @@ +console.log( + range(5).reduce( + function (a, n) { + return a + Array(n + 1).join('*') + '\n'; + }, '' + ) +); diff --git a/Task/Loops-For/JavaScript/loops-for-5.js b/Task/Loops-For/JavaScript/loops-for-5.js new file mode 100644 index 0000000000..15af0ca834 --- /dev/null +++ b/Task/Loops-For/JavaScript/loops-for-5.js @@ -0,0 +1,5 @@ +console.log( + range(5).map(function(a) { + return Array(a + 1).join('*'); + }).join('\n') +); diff --git a/Task/Loops-For/Julia/loops-for.julia b/Task/Loops-For/Julia/loops-for.julia new file mode 100644 index 0000000000..137cc8769b --- /dev/null +++ b/Task/Loops-For/Julia/loops-for.julia @@ -0,0 +1,6 @@ +for i in 1:5 + for j in 1:i + print("*") + end + println() +end diff --git a/Task/Loops-For/Rust/loops-for.rust b/Task/Loops-For/Rust/loops-for.rust new file mode 100644 index 0000000000..f1aa7c0f6d --- /dev/null +++ b/Task/Loops-For/Rust/loops-for.rust @@ -0,0 +1,7 @@ +for i in 0..5 { + for _ in 0..(i + 1) { + print!("*"); + } + + print!("\n"); +} diff --git a/Task/Loops-For/Scilab/loops-for.scilab b/Task/Loops-For/Scilab/loops-for.scilab new file mode 100644 index 0000000000..2a99fb19ba --- /dev/null +++ b/Task/Loops-For/Scilab/loops-for.scilab @@ -0,0 +1,7 @@ +for i=1:5 + s="" + for j=1:i + s=s+"*" + end + printf("%s\n",s) +end diff --git a/Task/Loops-For/Z80-Assembly/loops-for.z80 b/Task/Loops-For/Z80-Assembly/loops-for.z80 new file mode 100644 index 0000000000..eb150eb43f --- /dev/null +++ b/Task/Loops-For/Z80-Assembly/loops-for.z80 @@ -0,0 +1,41 @@ +org &4000 ; put code at memory address 0x4000 +wr_char equ &bb5a ; write ASCII character in register A to screen + ; (jumps into CPC ROM) + +; put registers on stack so we can return to BASIC later +push bc +push de +push hl + +ld b,5 ; loop from 5 to 1 + +row: + +push bc ; save outer loop variable + +; calculate inner loop limit (6 - outer loop variable) +ld a,6 +sub b +ld b,a + +column: + +ld a,42 ; asterisk in ASCII +call wr_char +djnz column ; decrement B, jump to label if non-zero + +pop bc ; restore outer loop + +; print carriage return/line feed +ld a,13 +call wr_char +ld a,10 +call wr_char + +djnz row + +; restore registers +pop hl +pop de +pop bc +ret ; return to BASIC interpreter diff --git a/Task/Loops-Foreach/AppleScript/loops-foreach.applescript b/Task/Loops-Foreach/AppleScript/loops-foreach.applescript new file mode 100644 index 0000000000..019305c9c6 --- /dev/null +++ b/Task/Loops-Foreach/AppleScript/loops-foreach.applescript @@ -0,0 +1,3 @@ +repeat with fruit in {"Apple", "Orange", "Banana"} + log contents of fruit +end repeat diff --git a/Task/Loops-Foreach/Batch-File/loops-foreach-1.bat b/Task/Loops-Foreach/Batch-File/loops-foreach-1.bat new file mode 100644 index 0000000000..8991d12d29 --- /dev/null +++ b/Task/Loops-Foreach/Batch-File/loops-foreach-1.bat @@ -0,0 +1,4 @@ +@echo off +for %%A in (This is a sample collection) do ( + echo %%A +) diff --git a/Task/Loops-Foreach/Batch-File/loops-foreach-2.bat b/Task/Loops-Foreach/Batch-File/loops-foreach-2.bat new file mode 100644 index 0000000000..8fb8a6cab8 --- /dev/null +++ b/Task/Loops-Foreach/Batch-File/loops-foreach-2.bat @@ -0,0 +1,5 @@ +@echo off +set "collection=This is a sample collection" +for %%A in (%collection%) do ( + echo %%A +) diff --git a/Task/Loops-Foreach/Ela/loops-foreach.ela b/Task/Loops-Foreach/Ela/loops-foreach.ela new file mode 100644 index 0000000000..ab0b12b99f --- /dev/null +++ b/Task/Loops-Foreach/Ela/loops-foreach.ela @@ -0,0 +1,6 @@ +open monad io + +each [] = do return () +each (x::xs) = do + putStrLn $ show x + each xs diff --git a/Task/Loops-Foreach/Elixir/loops-foreach.elixir b/Task/Loops-Foreach/Elixir/loops-foreach.elixir new file mode 100644 index 0000000000..ffd27c89ee --- /dev/null +++ b/Task/Loops-Foreach/Elixir/loops-foreach.elixir @@ -0,0 +1,9 @@ +iex(1)> list = [1,3.14,"abc",[3],{0,5}] +[1, 3.14, "abc", [3], {0, 5}] +iex(2)> Enum.each(list, fn x -> IO.inspect x end) +1 +3.14 +"abc" +[3] +{0, 5} +:ok diff --git a/Task/Loops-Foreach/Haxe/loops-foreach.haxe b/Task/Loops-Foreach/Haxe/loops-foreach.haxe index d8d8cca7d6..89ae6cdeb9 100644 --- a/Task/Loops-Foreach/Haxe/loops-foreach.haxe +++ b/Task/Loops-Foreach/Haxe/loops-foreach.haxe @@ -1 +1,4 @@ -for(i in 1...10) Sys.println(i); +var a = [1, 2, 3, 4]; + +for(i in a) + Sys.println(i); diff --git a/Task/Loops-Foreach/JavaScript/loops-foreach-1.js b/Task/Loops-Foreach/JavaScript/loops-foreach-1.js index 3a1da1884f..bf447ba218 100644 --- a/Task/Loops-Foreach/JavaScript/loops-foreach-1.js +++ b/Task/Loops-Foreach/JavaScript/loops-foreach-1.js @@ -1,3 +1,5 @@ -for (var a in o) { - print(o[a]); -} +"alpha beta gamma delta".split(' ').forEach( + function (x) { + console.log(x); + } +); diff --git a/Task/Loops-Foreach/JavaScript/loops-foreach-2.js b/Task/Loops-Foreach/JavaScript/loops-foreach-2.js index 3db0cad360..9215676aee 100644 --- a/Task/Loops-Foreach/JavaScript/loops-foreach-2.js +++ b/Task/Loops-Foreach/JavaScript/loops-foreach-2.js @@ -1,5 +1,5 @@ -for (var a in o) { - if (o.hasOwnProperty(a)) { - print(o[a]); - } -} +console.log("alpha beta gamma delta".split(' ').map( + function (x) { + return x.toUpperCase(x); + } +).join('\n')); diff --git a/Task/Loops-Foreach/JavaScript/loops-foreach-3.js b/Task/Loops-Foreach/JavaScript/loops-foreach-3.js index c7bce07c0d..d2b34b17f6 100644 --- a/Task/Loops-Foreach/JavaScript/loops-foreach-3.js +++ b/Task/Loops-Foreach/JavaScript/loops-foreach-3.js @@ -1,14 +1,7 @@ -h = {"one":1, "two":2, "three":3} -for (x in h) print(x); -/* -two -one -three -*/ - -for each (y in h) print(y); -/* -2 -1 -3 -*/ +console.log( + "alpha beta gamma delta".split(' ').reduce( + function (a, x, i, lst) { + return lst.length - i + '. ' + x + '\n' + a; + }, '' + ) +) diff --git a/Task/Loops-Foreach/JavaScript/loops-foreach-4.js b/Task/Loops-Foreach/JavaScript/loops-foreach-4.js index d56e40bfc7..3a1da1884f 100644 --- a/Task/Loops-Foreach/JavaScript/loops-foreach-4.js +++ b/Task/Loops-Foreach/JavaScript/loops-foreach-4.js @@ -1,14 +1,3 @@ -h = {"one":1, "two":2, "three":3} -for (x in h) print(x); -/* -two -one -three -*/ - -for (y of h) print(y); -/* -2 -1 -3 -*/ +for (var a in o) { + print(o[a]); +} diff --git a/Task/Loops-Foreach/JavaScript/loops-foreach-5.js b/Task/Loops-Foreach/JavaScript/loops-foreach-5.js new file mode 100644 index 0000000000..3db0cad360 --- /dev/null +++ b/Task/Loops-Foreach/JavaScript/loops-foreach-5.js @@ -0,0 +1,5 @@ +for (var a in o) { + if (o.hasOwnProperty(a)) { + print(o[a]); + } +} diff --git a/Task/Loops-Foreach/JavaScript/loops-foreach-6.js b/Task/Loops-Foreach/JavaScript/loops-foreach-6.js new file mode 100644 index 0000000000..c7bce07c0d --- /dev/null +++ b/Task/Loops-Foreach/JavaScript/loops-foreach-6.js @@ -0,0 +1,14 @@ +h = {"one":1, "two":2, "three":3} +for (x in h) print(x); +/* +two +one +three +*/ + +for each (y in h) print(y); +/* +2 +1 +3 +*/ diff --git a/Task/Loops-Foreach/JavaScript/loops-foreach-7.js b/Task/Loops-Foreach/JavaScript/loops-foreach-7.js new file mode 100644 index 0000000000..d56e40bfc7 --- /dev/null +++ b/Task/Loops-Foreach/JavaScript/loops-foreach-7.js @@ -0,0 +1,14 @@ +h = {"one":1, "two":2, "three":3} +for (x in h) print(x); +/* +two +one +three +*/ + +for (y of h) print(y); +/* +2 +1 +3 +*/ diff --git a/Task/Loops-Foreach/Rust/loops-foreach-1.rust b/Task/Loops-Foreach/Rust/loops-foreach-1.rust new file mode 100644 index 0000000000..d3eb9d5f3f --- /dev/null +++ b/Task/Loops-Foreach/Rust/loops-foreach-1.rust @@ -0,0 +1,4 @@ +let collection = vec![1,2,3,4,5]; +for elem in collection { + println!("{}", elem); +} diff --git a/Task/Loops-Foreach/Rust/loops-foreach-2.rust b/Task/Loops-Foreach/Rust/loops-foreach-2.rust new file mode 100644 index 0000000000..fbff14f5bf --- /dev/null +++ b/Task/Loops-Foreach/Rust/loops-foreach-2.rust @@ -0,0 +1,14 @@ +let mut collection = vec![1,2,3,4,5]; +for mut_ref in &mut collection { +// alternatively: +// for mut_ref in collection.iter_mut() { + *mut_ref *= 2; + println!("{}", *mut_ref); +} + +// immutable borrow +for immut_ref in &collection { +// alternatively: +// for immut_ref in collection.iter() { + println!("{}", *immut_ref); +} diff --git a/Task/Loops-Foreach/Scilab/loops-foreach.scilab b/Task/Loops-Foreach/Scilab/loops-foreach.scilab new file mode 100644 index 0000000000..8cce3e40fc --- /dev/null +++ b/Task/Loops-Foreach/Scilab/loops-foreach.scilab @@ -0,0 +1,3 @@ +for e=["a","b","c"] + printf("%s\n",e) +end diff --git a/Task/Loops-Foreach/Self/loops-foreach.self b/Task/Loops-Foreach/Self/loops-foreach.self new file mode 100644 index 0000000000..076c351951 --- /dev/null +++ b/Task/Loops-Foreach/Self/loops-foreach.self @@ -0,0 +1 @@ +aCollection do: [| :element | element printLine ]. diff --git a/Task/Loops-Infinite/ALGOL-W/loops-infinite.alg b/Task/Loops-Infinite/ALGOL-W/loops-infinite.alg new file mode 100644 index 0000000000..d019dc82f3 --- /dev/null +++ b/Task/Loops-Infinite/ALGOL-W/loops-infinite.alg @@ -0,0 +1,3 @@ +begin + for i := 1 step 0 until 2 do write( "SPAM" ) +end. diff --git a/Task/Loops-Infinite/ARM-Assembly/loops-infinite.arm b/Task/Loops-Infinite/ARM-Assembly/loops-infinite.arm new file mode 100644 index 0000000000..998150e893 --- /dev/null +++ b/Task/Loops-Infinite/ARM-Assembly/loops-infinite.arm @@ -0,0 +1,11 @@ +.global main + +main: + +loop: + ldr r0, =message + bl printf + b loop + +message: + .asciz "SPAM\n" diff --git a/Task/Loops-Infinite/DCL/loops-infinite.dcl b/Task/Loops-Infinite/DCL/loops-infinite.dcl new file mode 100644 index 0000000000..12b0290313 --- /dev/null +++ b/Task/Loops-Infinite/DCL/loops-infinite.dcl @@ -0,0 +1,3 @@ +$ loop: +$ write sys$output "SPAM" +$ goto loop diff --git a/Task/Loops-Infinite/Ela/loops-infinite-1.ela b/Task/Loops-Infinite/Ela/loops-infinite-1.ela index cc1e810476..07e5baf97a 100644 --- a/Task/Loops-Infinite/Ela/loops-infinite-1.ela +++ b/Task/Loops-Infinite/Ela/loops-infinite-1.ela @@ -1,3 +1,7 @@ -open console +open monad io -loop () = writen "SPAM" $ loop! +loop () = do + putStrLn "SPAM" + loop () + +loop () ::: IO diff --git a/Task/Loops-Infinite/Ela/loops-infinite-2.ela b/Task/Loops-Infinite/Ela/loops-infinite-2.ela index 5a4de58710..631ac33c81 100644 --- a/Task/Loops-Infinite/Ela/loops-infinite-2.ela +++ b/Task/Loops-Infinite/Ela/loops-infinite-2.ela @@ -1,5 +1,10 @@ -open console list +open monad io -loop () = writen "SPAM" :: (& loop!) +xs = "SPAM"::xs -take 10 <| loop! //prints SPAM only first 10 times +takeit 0 _ = do return () +takeit num (x::xs) = do + putStrLn x + takeit (num - 1) xs + +_ = takeit 10 xs ::: IO diff --git a/Task/Loops-Infinite/Elixir/loops-infinite-1.elixir b/Task/Loops-Infinite/Elixir/loops-infinite-1.elixir new file mode 100644 index 0000000000..28ac2eb8a8 --- /dev/null +++ b/Task/Loops-Infinite/Elixir/loops-infinite-1.elixir @@ -0,0 +1,8 @@ +defmodule Loops do + def infinite do + IO.puts "SPAM" + infinite + end +end + +Loops.infinite diff --git a/Task/Loops-Infinite/Elixir/loops-infinite-2.elixir b/Task/Loops-Infinite/Elixir/loops-infinite-2.elixir new file mode 100644 index 0000000000..ee60b5fd97 --- /dev/null +++ b/Task/Loops-Infinite/Elixir/loops-infinite-2.elixir @@ -0,0 +1 @@ +Stream.cycle(["SPAM"]) |> Enum.each(&IO.puts &1) diff --git a/Task/Loops-Infinite/Julia/loops-infinite.julia b/Task/Loops-Infinite/Julia/loops-infinite.julia new file mode 100644 index 0000000000..5475920aff --- /dev/null +++ b/Task/Loops-Infinite/Julia/loops-infinite.julia @@ -0,0 +1,3 @@ +while true + println("SPAM") +end diff --git a/Task/Loops-Infinite/Pure-Data/loops-infinite.pure b/Task/Loops-Infinite/Pure-Data/loops-infinite.pure new file mode 100644 index 0000000000..2263747938 --- /dev/null +++ b/Task/Loops-Infinite/Pure-Data/loops-infinite.pure @@ -0,0 +1,8 @@ +#N canvas 426 88 450 300 10; +#X obj 17 75 print; +#X msg 17 55 SPAM; +#X obj 17 35 metro 1; +#X msg 17 15 1; +#X connect 1 0 0 0; +#X connect 2 0 1 0; +#X connect 3 0 2 0; diff --git a/Task/Loops-Infinite/Rust/loops-infinite.rust b/Task/Loops-Infinite/Rust/loops-infinite.rust index 08ad7e48f4..1c56974551 100644 --- a/Task/Loops-Infinite/Rust/loops-infinite.rust +++ b/Task/Loops-Infinite/Rust/loops-infinite.rust @@ -1,5 +1,5 @@ fn main() { - loop { - println!("SPAM"); - } + loop { + println!("SPAM"); + } } diff --git a/Task/Loops-Infinite/Scilab/loops-infinite.scilab b/Task/Loops-Infinite/Scilab/loops-infinite.scilab new file mode 100644 index 0000000000..0597dd2c63 --- /dev/null +++ b/Task/Loops-Infinite/Scilab/loops-infinite.scilab @@ -0,0 +1,3 @@ +while %T + printf("SPAM\n") +end diff --git a/Task/Loops-Infinite/Self/loops-infinite.self b/Task/Loops-Infinite/Self/loops-infinite.self new file mode 100644 index 0000000000..522bd675ee --- /dev/null +++ b/Task/Loops-Infinite/Self/loops-infinite.self @@ -0,0 +1 @@ +['SPAM' printLine] loop diff --git a/Task/Loops-N-plus-one-half/00DESCRIPTION b/Task/Loops-N-plus-one-half/00DESCRIPTION index d05bd4e039..f07a044dfb 100644 --- a/Task/Loops-N-plus-one-half/00DESCRIPTION +++ b/Task/Loops-N-plus-one-half/00DESCRIPTION @@ -1,5 +1,5 @@ Quite often one needs loops which, in the last iteration, -execute only part of the loop body. +execute only part of the loop body. pas The goal of this task is to demonstrate the best way to do this. Write a loop which writes the comma-separated list diff --git a/Task/Loops-N-plus-one-half/360-Assembly/loops-n-plus-one-half.360 b/Task/Loops-N-plus-one-half/360-Assembly/loops-n-plus-one-half.360 new file mode 100644 index 0000000000..37b3baf808 --- /dev/null +++ b/Task/Loops-N-plus-one-half/360-Assembly/loops-n-plus-one-half.360 @@ -0,0 +1,23 @@ +* Loops/N plus one half 13/08/2015 +LOOPHALF CSECT USING LOOPHALF,R12 + LR R12,R15 +BEGIN LA R3,MVC + SR R5,R5 + LA R6,1 + LA R7,10 +LOOPI BXH R5,R6,ELOOPI for i=1 to 10 + XDECO R5,XDEC + MVC 0(4,R3),XDEC+8 + LA R3,4(R3) + CH R5,=H'10' + BNL NEXTI + MVC 0(2,R3),=C', ' + LA R3,2(R3) +NEXTI B LOOPI next i +ELOOPI XPRNT MVC,80 + XR R15,R15 + BR R14 +MVC DC CL80' ' +XDEC DS CL12 + YREGS + END LOOPHALF diff --git a/Task/Loops-N-plus-one-half/ALGOL-W/loops-n-plus-one-half.alg b/Task/Loops-N-plus-one-half/ALGOL-W/loops-n-plus-one-half.alg new file mode 100644 index 0000000000..ce5bda7aee --- /dev/null +++ b/Task/Loops-N-plus-one-half/ALGOL-W/loops-n-plus-one-half.alg @@ -0,0 +1,14 @@ +begin + integer i; + i := 0; + while + begin + i := i + 1; + writeon( i ); + i < 10 + end + do + begin + writeon( "," ) + end +end. diff --git a/Task/Loops-N-plus-one-half/Befunge/loops-n-plus-one-half-2.bf b/Task/Loops-N-plus-one-half/Befunge/loops-n-plus-one-half-2.bf index ab4a5c65d2..9caa2b0a85 100644 --- a/Task/Loops-N-plus-one-half/Befunge/loops-n-plus-one-half-2.bf +++ b/Task/Loops-N-plus-one-half/Befunge/loops-n-plus-one-half-2.bf @@ -1,3 +1,2 @@ -"0" v -1+>::"9"`#v_," ,",,> - >"01",,@ +1+>::68*+,8`#v_" ,",, + @,,,,", 10"< diff --git a/Task/Loops-N-plus-one-half/C++/loops-n-plus-one-half.cpp b/Task/Loops-N-plus-one-half/C++/loops-n-plus-one-half.cpp index 5afa63f6b7..4180f9725c 100644 --- a/Task/Loops-N-plus-one-half/C++/loops-n-plus-one-half.cpp +++ b/Task/Loops-N-plus-one-half/C++/loops-n-plus-one-half.cpp @@ -2,13 +2,9 @@ int main() { - for (int i = 1; ; i++) - { - std::cout << i; - if (i == 10) - break; - std::cout << ", "; - } - std::cout << std::endl; + int i; + for (i = 1; i<10 ; i++) + std::cout << i << ", "; + std::cout< Loops.n_plus_one_half diff --git a/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half.js b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-1.js similarity index 100% rename from Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half.js rename to Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-1.js diff --git a/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-2.js b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-2.js new file mode 100644 index 0000000000..2cc321ba8a --- /dev/null +++ b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-2.js @@ -0,0 +1,11 @@ +function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { + return m + i; + } + ); +} + +console.log( + range(1, 10).join(', ') +); diff --git a/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-3.js b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-3.js new file mode 100644 index 0000000000..f22ebfeee1 --- /dev/null +++ b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-3.js @@ -0,0 +1 @@ +1, 2, 3, 4, 5, 6, 7, 8, 9, 10 diff --git a/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-4.js b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-4.js new file mode 100644 index 0000000000..c93adaa241 --- /dev/null +++ b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-4.js @@ -0,0 +1,21 @@ +function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map(function (x, i) { + return m + i; + }); +} + +console.log( + (function (nFrom, nTo) { + var iLast = nTo - 1; + + return range(nFrom, nTo).reduce( + function (accumulator, n, i) { + return accumulator + + n.toString() + + + (i < iLast ? ', ' : ''); // conditional sub-expression + + }, '' + ) + })(1, 10) +); diff --git a/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-5.js b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-5.js new file mode 100644 index 0000000000..f22ebfeee1 --- /dev/null +++ b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-5.js @@ -0,0 +1 @@ +1, 2, 3, 4, 5, 6, 7, 8, 9, 10 diff --git a/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-6.js b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-6.js new file mode 100644 index 0000000000..1e5ee6b6d8 --- /dev/null +++ b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-6.js @@ -0,0 +1,4 @@ +var s=1, e=10 +for (var i=s; i<=e; i+=1) { + document.write( i==s ? '' : ', ', i ) +} diff --git a/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-7.js b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-7.js new file mode 100644 index 0000000000..1816ecb5e3 --- /dev/null +++ b/Task/Loops-N-plus-one-half/JavaScript/loops-n-plus-one-half-7.js @@ -0,0 +1,6 @@ +var s=1, e=10 +for (;; s+=1) { + document.write( s ) + if (s==e) break + document.write( ', ' ) +} diff --git a/Task/Loops-N-plus-one-half/Scilab/loops-n-plus-one-half.scilab b/Task/Loops-N-plus-one-half/Scilab/loops-n-plus-one-half.scilab new file mode 100644 index 0000000000..9a3c108afa --- /dev/null +++ b/Task/Loops-N-plus-one-half/Scilab/loops-n-plus-one-half.scilab @@ -0,0 +1,5 @@ +for i=1:10 + printf("%2d ",i) + if i<10 then printf(", "); end +end +printf("\n") diff --git a/Task/Loops-Nested/360-Assembly/loops-nested.360 b/Task/Loops-Nested/360-Assembly/loops-nested.360 new file mode 100644 index 0000000000..61f02f4861 --- /dev/null +++ b/Task/Loops-Nested/360-Assembly/loops-nested.360 @@ -0,0 +1,74 @@ +* Loop nested 12/08/2015 +LOOPNEST CSECT + USING LOOPNEST,R12 + LR R12,R15 +BEGIN LA R6,0 i + LA R8,1 + LA R9,20 +LOOPI1 BXH R6,R8,ELOOPI1 do i=1 to hbound(x,1) + LA R7,0 j + LA R10,1 + LA R11,20 +LOOPJ1 BXH R7,R10,ELOOPJ1 do j=1 to hbound(x,2) + L R5,RANDSEED n + M R4,=F'397204094' r4r5=n*const + D R4,=X'7FFFFFFF' r5=r5 div (2^31-1) + ST R4,RANDSEED r4=r5 mod (2^31-1) ; n=r4 + LR R5,R4 r5=n + LA R4,0 + D R4,=F'20' r5=n div nn; r4=n mod nn + LR R2,R4 r2=randint(nn) [0:nn-1] + LA R2,1(R2) randint(nn)+1 + LR R1,R6 i + BCTR R1,0 + MH R1,=H'20' + LR R5,R7 j + BCTR R5,0 + AR R1,R5 + SLA R1,2 + ST R2,X(R1) x(i,j)=randint(20)+1 + B LOOPJ1 +ELOOPJ1 B LOOPI1 +ELOOPI1 MVC MVCZ,=CL80' ' + LA R6,0 i + LA R8,1 + LA R9,20 +LOOPI2 BXH R6,R8,ELOOPI2 do i=1 to hbound(x,1) + LA R7,0 j + LA R10,1 + LA R11,20 +LOOPJ2 BXH R7,R10,ELOOPJ2 do j=1 to hbound(x,2) + LR R1,R6 + BCTR R1,0 + MH R1,=H'20' + LR R5,R7 + BCTR R5,0 + AR R1,R5 + SLA R1,2 + L R5,X(R1) x(i,j) + LR R2,R5 + LA R3,MVCZ + AH R3,MVCI + XDECO R2,XDEC + MVC 0(4,R3),XDEC+8 + LH R3,MVCI + LA R3,4(R3) + STH R3,MVCI + L R5,X(R1) + C R5,=F'20' if x(i,j)=20 + BE ELOOPI2 then exit + B LOOPJ2 +ELOOPJ2 XPRNT MVCZ,80 + MVC MVCI,=H'0' + MVC MVCZ,=CL80' ' + B LOOPI2 +ELOOPI2 XPRNT MVCZ,80 +RETURN XR R15,R15 + BR R14 +X DS 400F +MVCZ DS CL80 +MVCI DC H'0' +XDEC DS CL16 +RANDSEED DC F'16807' running n + YREGS + END LOOPNEST diff --git a/Task/Loops-Nested/Elixir/loops-nested.elixir b/Task/Loops-Nested/Elixir/loops-nested.elixir new file mode 100644 index 0000000000..fe2c0e9c93 --- /dev/null +++ b/Task/Loops-Nested/Elixir/loops-nested.elixir @@ -0,0 +1,24 @@ +defmodule Loops do + def nested do + :random.seed(:os.timestamp) + list = Enum.shuffle(1..20) |> Enum.chunk(5) + IO.inspect list, char_lists: :as_lists + try do + nested(list) + catch + :find -> IO.puts "done" + end + end + + def nested(list) do + Enum.each(list, fn row -> + Enum.each(row, fn x -> + IO.write "#{x} " + if x == 20, do: throw(:find) + end) + IO.puts "" + end) + end +end + +Loops.nested diff --git a/Task/Loops-Nested/Fortran/loops-nested-1.f b/Task/Loops-Nested/Fortran/loops-nested-1.f index 9e7f279f92..0481fcd4ae 100644 --- a/Task/Loops-Nested/Fortran/loops-nested-1.f +++ b/Task/Loops-Nested/Fortran/loops-nested-1.f @@ -35,10 +35,10 @@ PROGRAM LOOPNESTED 5000 FORMAT('A[', I2, '][', I2, '] is ', I2) END -C FORTRAN 77 does not have come with a random number generator, but it -C is easy enough to type "fortran 77 random number generator" into your -C preferred search engine and to copy and paste what you find. The -C following code is a slightly-modified version of: +C FORTRAN 77 does not come with a random number generator, but it is +C easy enough to type "fortran 77 random number generator" into your +C preferred search engine and to copy and paste what you find. +C The following code is a slightly-modified version of: C C http://www.tat.physik.uni-tuebingen.de/ C ~kley/lehre/ftn77/tutorial/subprograms.html diff --git a/Task/Loops-Nested/JavaScript/loops-nested.js b/Task/Loops-Nested/JavaScript/loops-nested-1.js similarity index 100% rename from Task/Loops-Nested/JavaScript/loops-nested.js rename to Task/Loops-Nested/JavaScript/loops-nested-1.js diff --git a/Task/Loops-Nested/JavaScript/loops-nested-2.js b/Task/Loops-Nested/JavaScript/loops-nested-2.js new file mode 100644 index 0000000000..260d4330d8 --- /dev/null +++ b/Task/Loops-Nested/JavaScript/loops-nested-2.js @@ -0,0 +1,43 @@ +var lst = [[2, 12, 10, 4], [18, 11, 9, 3], [14, 15, 7, 17], [6, 19, 8, 13], [1, + 20, 16, 5]]; + +var takeWhile = function (lst, fnTest) { + 'use strict'; + var varHead = lst.length ? lst[0] : null; + + return varHead ? ( + fnTest(varHead) ? [varHead].concat( + takeWhile(lst.slice(1), fnTest) + ) : [] + ) : [] + }, + + // The takeWhile function terminates when notTwenty(n) returns false + notTwenty = function (n) { + return n !== 20; + }, + + // Leftward groups containing no 20 + // takeWhile nested within takeWhile + lstChecked = takeWhile(lst, function (group) { + return takeWhile( + group, + notTwenty + ).length === 4; + }); + + +// Return the trail of numbers preceding 20 from a composable expression + +console.log( + // Numbers before 20 in a group in which it was found + lstChecked.concat( + takeWhile( + lst[lstChecked.length], notTwenty + ) + ) + // flattened + .reduce(function (a, x) { + return a.concat(x); + }).join('\n') +); diff --git a/Task/Loops-Nested/JavaScript/loops-nested-3.js b/Task/Loops-Nested/JavaScript/loops-nested-3.js new file mode 100644 index 0000000000..0b9327fa5b --- /dev/null +++ b/Task/Loops-Nested/JavaScript/loops-nested-3.js @@ -0,0 +1,21 @@ +2 +12 +10 +4 +18 +11 +9 +3 +14 +15 +7 +17 +6 +19 +8 +13 +6 +19 +8 +13 +1 diff --git a/Task/Loops-Nested/Julia/loops-nested.julia b/Task/Loops-Nested/Julia/loops-nested.julia new file mode 100644 index 0000000000..b02ec31ac5 --- /dev/null +++ b/Task/Loops-Nested/Julia/loops-nested.julia @@ -0,0 +1,17 @@ +M = [rand(1:20) for i in 1:5, j in 1:10] +R, C = size(M) + +println("The full matrix is:") +println(M, "\n") + +println("Find the first 20:") +for i in 1:R, j in 1:C + n = M[i,j] + @printf "%4d" n + if n == 20 + println() + break + elseif j == C + println() + end +end diff --git a/Task/Loops-Nested/Pascal/loops-nested.pascal b/Task/Loops-Nested/Pascal/loops-nested.pascal new file mode 100644 index 0000000000..5149d240c2 --- /dev/null +++ b/Task/Loops-Nested/Pascal/loops-nested.pascal @@ -0,0 +1,21 @@ +program LoopNested; +uses SysUtils; +const Ni=10; Nj=20; +var + tab: array[1..Ni,1..Nj] of Integer; + i, j: Integer; +label loopend; +begin + for i := 1 to Ni do + for j := 1 to Nj do + tab[i,j]:=random(20)+1; + for i := 1 to Ni do + begin + for j := 1 to Nj do + begin + WriteLn(tab[i,j]); + if tab[i,j]=20 then goto loopend + end + end; +loopend: +end. diff --git a/Task/Loops-Nested/Perl-6/loops-nested.pl6 b/Task/Loops-Nested/Perl-6/loops-nested.pl6 new file mode 100644 index 0000000000..e0d191b51a --- /dev/null +++ b/Task/Loops-Nested/Perl-6/loops-nested.pl6 @@ -0,0 +1,10 @@ +my @a = [ (1..20).roll(10) ] xx *; + +LINE: for @a -> @line { + for @line -> $elem { + print " $elem"; + last LINE if $elem == 20; + } + print "\n"; +} +print "\n"; diff --git a/Task/Loops-Nested/Rust/loops-nested.rust b/Task/Loops-Nested/Rust/loops-nested.rust index 6588a72044..6b9d0e43be 100644 --- a/Task/Loops-Nested/Rust/loops-nested.rust +++ b/Task/Loops-Nested/Rust/loops-nested.rust @@ -1,22 +1,21 @@ -// rust 0.9-pre +use rand::Rng; -use std::rand::Rng; +extern crate rand; fn main() { - let mut matrix = [[0u8, .. 10], .. 10]; - let mut rng = std::rand::os::OSRng::new(); + let mut matrix = [[0u8; 10]; 10]; + let mut rng = rand::thread_rng(); - for row in matrix.mut_iter() { - for item in row.mut_iter() { - *item = rng.gen_range(0u8, 21); + for row in matrix.iter_mut() { + for item in row.iter_mut() { + *item = rng.gen_range(0, 21); } } - 'outer: - for row in matrix.iter() { + 'outer: for row in matrix.iter() { for &item in row.iter() { print!("{:2} ", item); - if item == 20 { break 'outer; } + if item == 20 { break 'outer } } println!(""); } diff --git a/Task/Loops-Nested/Scilab/loops-nested.scilab b/Task/Loops-Nested/Scilab/loops-nested.scilab new file mode 100644 index 0000000000..c41d41b07e --- /dev/null +++ b/Task/Loops-Nested/Scilab/loops-nested.scilab @@ -0,0 +1,10 @@ +ni=3;nj=4 +t=int(rand(ni,nj)*20)+1 +for i=1:ni + for j=1:nj + printf("%2d ",t(i,j)) + if t(i,j)==11 then break; end + end + printf("\n") + if t(i,j)==11 then break; end +end diff --git a/Task/Loops-Nested/TI-83-BASIC/loops-nested.ti-83 b/Task/Loops-Nested/TI-83-BASIC/loops-nested.ti-83 new file mode 100644 index 0000000000..9a4bce7078 --- /dev/null +++ b/Task/Loops-Nested/TI-83-BASIC/loops-nested.ti-83 @@ -0,0 +1,18 @@ +PROGRAM:LOOP +(A,B)→dim([C]) +For(I,1,A) +For(J,1,B) +int(rand*20+1)→[C](I,J) +End +End +For(I,1,A) +For(J,1,B) +Disp [C](I,J) +If [C](I,J)=20 +Then +Stop +End +End +End + +3→A:4→B:prgmLOOP diff --git a/Task/Loops-While/ALGOL-W/loops-while.alg b/Task/Loops-While/ALGOL-W/loops-while.alg new file mode 100644 index 0000000000..26f95aba7d --- /dev/null +++ b/Task/Loops-While/ALGOL-W/loops-while.alg @@ -0,0 +1,9 @@ +begin + integer i; + i := 1024; + while i > 0 do + begin + write( i ); + i := i div 2 + end +end. diff --git a/Task/Loops-While/Elixir/loops-while.elixir b/Task/Loops-While/Elixir/loops-while.elixir new file mode 100644 index 0000000000..52840633e7 --- /dev/null +++ b/Task/Loops-While/Elixir/loops-while.elixir @@ -0,0 +1,9 @@ +defmodule Loops do + def while(0), do: :ok + def while(n) do + IO.puts n + while( div(n,2) ) + end +end + +Loops.while(1024) diff --git a/Task/Loops-While/JavaScript/loops-while-1.js b/Task/Loops-While/JavaScript/loops-while-1.js new file mode 100644 index 0000000000..fcd1de9fe0 --- /dev/null +++ b/Task/Loops-While/JavaScript/loops-while-1.js @@ -0,0 +1,5 @@ +var n = 1024; +while (n > 0) { + print(n); + n /= 2; +} diff --git a/Task/Loops-While/JavaScript/loops-while-2.js b/Task/Loops-While/JavaScript/loops-while-2.js new file mode 100644 index 0000000000..be118138a0 --- /dev/null +++ b/Task/Loops-While/JavaScript/loops-while-2.js @@ -0,0 +1,20 @@ +function loopWhile(varValue, fnDelta, fnTest) { + 'use strict'; + var d = fnDelta(varValue); + + return fnTest(d) ? [d].concat( + loopWhile(d, fnDelta, fnTest) + ) : []; +} + +console.log( + loopWhile( + 1024, + function (x) { + return Math.floor(x/2); + }, + function (x) { + return x > 0; + } + ).join('\n') +); diff --git a/Task/Loops-While/JavaScript/loops-while-3.js b/Task/Loops-While/JavaScript/loops-while-3.js new file mode 100644 index 0000000000..2539a1cd33 --- /dev/null +++ b/Task/Loops-While/JavaScript/loops-while-3.js @@ -0,0 +1,10 @@ +512 +256 +128 +64 +32 +16 +8 +4 +2 +1 diff --git a/Task/Loops-While/JavaScript/loops-while.js b/Task/Loops-While/JavaScript/loops-while.js deleted file mode 100644 index 966d7d484a..0000000000 --- a/Task/Loops-While/JavaScript/loops-while.js +++ /dev/null @@ -1,5 +0,0 @@ -var n = 1024; -while (n>0) { - print(n); - n/=2; -} diff --git a/Task/Loops-While/Julia/loops-while.julia b/Task/Loops-While/Julia/loops-while.julia new file mode 100644 index 0000000000..7c371bb031 --- /dev/null +++ b/Task/Loops-While/Julia/loops-while.julia @@ -0,0 +1,6 @@ +n = 1024 + +while n > 0 + println(n) + n >>= 1 +end diff --git a/Task/Loops-While/Neko/loops-while.neko b/Task/Loops-While/Neko/loops-while.neko index fad5cf0d10..fc781b39aa 100644 --- a/Task/Loops-While/Neko/loops-while.neko +++ b/Task/Loops-While/Neko/loops-while.neko @@ -1,6 +1,6 @@ -var a = 5; -var i = 0; +var i = 1024 -while(i < a) { - i = i + 1; +while(i > 0) { + $print(i + "\n"); + i = $idiv(i, 2) } diff --git a/Task/Loops-While/Rust/loops-while.rust b/Task/Loops-While/Rust/loops-while.rust index 2ba44ee978..dc7db4e220 100644 --- a/Task/Loops-While/Rust/loops-while.rust +++ b/Task/Loops-While/Rust/loops-while.rust @@ -1,5 +1,5 @@ fn main() { - let mut n = 1024i; + let mut n: i32 = 1024; while n > 0 { println!("{}", n); n /= 2; diff --git a/Task/Loops-While/Scilab/loops-while.scilab b/Task/Loops-While/Scilab/loops-while.scilab new file mode 100644 index 0000000000..23c4a07667 --- /dev/null +++ b/Task/Loops-While/Scilab/loops-while.scilab @@ -0,0 +1,5 @@ +i=1024 +while i>0 + printf("%4d\n",i) + i=int(i/2) +end diff --git a/Task/Lucas-Lehmer-test/Common-Lisp/lucas-lehmer-test.lisp b/Task/Lucas-Lehmer-test/Common-Lisp/lucas-lehmer-test.lisp new file mode 100644 index 0000000000..ead07ce7ed --- /dev/null +++ b/Task/Lucas-Lehmer-test/Common-Lisp/lucas-lehmer-test.lisp @@ -0,0 +1,16 @@ +(defun or-f (&optional a b) (or a b));necessary for reduce, as 'or' is implemented as a macro + +(defun prime-p (n) + (cond ((< n 4) (>= n 2)) + ((zerop (rem n 2)) nil) + (t (not (reduce #'or-f (mapcar (lambda (x) (zerop (rem n x))) (loop for i from 3 to (sqrt n) collect i))))))) + +(defun mersenne-p (p) + (or (= p 2) + (let ((mp (- 1 (expt 2 p)))) + (do ((n 3) (s 4)) + ((> n p) (zerop s)) + (incf n) + (setf s (rem (- (* s s) 2) mp)))))) + +(princ (remove-if-not #'mersenne-p (remove-if-not #'prime-p (loop for i to 5000 collect i)))) diff --git a/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.elixir b/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.elixir new file mode 100644 index 0000000000..e38483939e --- /dev/null +++ b/Task/Lucas-Lehmer-test/Elixir/lucas-lehmer-test.elixir @@ -0,0 +1,14 @@ +defmodule LucasLehmer do + use Bitwise + def test do + for p <- 2..1300, p==2 or s(bsl(1,p)-1, p-1)==0, do: IO.write "M#{p} " + end + + defp s(mp, 1), do: rem(4, mp) + defp s(mp, n) do + x = s(mp, n-1) + rem(x*x-2, mp) + end +end + +LucasLehmer.test diff --git a/Task/Lucas-Lehmer-test/PicoLisp/lucas-lehmer-test.l b/Task/Lucas-Lehmer-test/PicoLisp/lucas-lehmer-test.l index 4ab5fe6e55..79254e3d84 100644 --- a/Task/Lucas-Lehmer-test/PicoLisp/lucas-lehmer-test.l +++ b/Task/Lucas-Lehmer-test/PicoLisp/lucas-lehmer-test.l @@ -4,9 +4,10 @@ (and (> N 1) (bit? 1 N) - (for (D 3 T (+ D 2)) - (T (> D (sqrt N)) T) - (T (=0 (% N D)) NIL) ) ) ) ) + (let S (sqrt N) + (for (D 3 T (+ D 2)) + (T (> D S) T) + (T (=0 (% N D)) NIL) ) ) ) ) ) (de mersenne? (P) (or diff --git a/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-1.py b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-1.py index dd92a1ed34..11b2e52bf5 100644 --- a/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-1.py +++ b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-1.py @@ -27,7 +27,7 @@ def is_mersenne_prime ( p ): print (" Finding Mersenne primes in M[2..%d]:"%upb_prime) count=0 -for p in range(2, upb_prime+1): +for p in range(2, int(upb_prime+1)): if is_prime(p) and is_mersenne_prime(p): print("M%d"%p), stdout.flush() diff --git a/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-2.py b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-2.py index f6839cf8d9..3d97e97346 100644 --- a/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-2.py +++ b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-2.py @@ -35,8 +35,31 @@ def lucas_lehmer_fast(n): s = 4 for i in range(2, n): sqr = s*s - r = (sqr & m) + (sqr >> n) - if r >= m: - r -= m - s = r - 2 + s = (sqr & m) + (sqr >> n) + if s >= m: + s -= m + s -= 2 return s == 0 + +# test taken from the previous rosetta implementation + +from math import log +from sys import stdout + +precision = 20000 # maximum requested number of decimal places of 2 ** MP-1 # +long_bits_width = precision * log(10, 2) +upb_prime = int( long_bits_width - 1 ) / 2 # no unsigned # +# upb_count = 45 # find 45 mprimes if int was given enough bits # +upb_count = 15 # find 45 mprimes if int was given enough bits # + +print (" Finding Mersenne primes in M[2..%d]:"%upb_prime) + +count=0 +# for p in range(2, upb_prime+1): +for p in range(2, int(upb_prime+1)): + if lucas_lehmer_fast(p): + print("M%d"%p), + stdout.flush() + count += 1 + if count >= upb_count: break +print diff --git a/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-3.py b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-3.py new file mode 100644 index 0000000000..da9741a32c --- /dev/null +++ b/Task/Lucas-Lehmer-test/Python/lucas-lehmer-test-3.py @@ -0,0 +1,17 @@ +import gmpy2 as mp + +def lucas_lehmer(n): + if n == 2: + return True + if not mp.is_prime(n): + return False + two = mp.mpz(2) + m = two**n - 1 + s = two*two + for i in range(2, n): + sqr = s*s + s = (sqr & m) + (sqr >> n) + if s >= m: + s -= m + s -= two + return mp.is_zero(s) diff --git a/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx b/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx index 00d579512b..1c8b4c6363 100644 --- a/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx +++ b/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx @@ -1,56 +1,58 @@ -/*REXX program to use Lucas-Lehmer primality test for prime powers of 2.*/ -parse arg limit . /*get the optional arg from C.L. */ -if limit=='' then limit=1000 /*No argument? Then assume 1000.*/ -list= /*placeholder for the results. */ - /* [↓] only process up to LIMIT,*/ - do j=1 by 2 to limit /*···only so many hours in a day.*/ - power=j + (j==1) /*POWER ≡ J except for when J=1.*/ - if \isPrime(power) then iterate /*if not prime, then ignore it. */ - list=list Lucas_Lehmer2(power) /*add to list (···or maybe not).*/ +/*REXX program uses the Lucas─Lehmer primality test for prime powers of two.*/ +trace i +parse arg limit . /*get optional arguments from the C.L. */ +if limit=='' then limit=1000 /*No argument? Then assume the default*/ +list= /*placeholder for the results. */ + /* [↓] only process up to the LIMIT, */ + do j=1 by 2 to limit /*there're only so many hours in a day.*/ + power=j + (j==1) /*POWER ≡ J except for when J=1. */ + if \isPrime(power) then iterate /*if POWER isn't prime, then ignore it.*/ + $=Lucas_Lehmer2(power) /*did it pass the Lucas─Lehmer2 test? */ + if $\=='' then list=list $ /*Did the # pass? Then add to the list.*/ end /*j*/ -list=space(list) /*remove all extraneous blanks. */ -say; say center('list',60-3,"═") /*show a fancy-dancy header/title*/ +list=space(list) /*elide all extraneous blanks from list*/ +say; say center('list',60-3,"═") /*show a fancy─dancy header (title). */ say - do k=1 for words(list) /*show entries in list, 1/line. */ - say right(word(list,k),30) /*right-justify 'em to look nice.*/ + do k=1 for words(list) /*show entries in list, one per line. */ + say right(word(list,k),30) /*right─justify 'em to look pretty&nice*/ end /*k*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ISPRIME subroutine──────────────────*/ -isPrime: procedure; parse arg x /*get # to be tested*/ -if x<17 then return wordpos(x,'2 3 5 7 11 13')\==0 /*test special cases*/ -if x//2==0 then return 0 /*is it even? Not prime.*/ -if x//3==0 then return 0 /*divisible by three? Not prime.*/ -if right(x,1)==5 then return 0 /*right-most dig ≡ 5? Not prime.*/ -if x//7==0 then return 0 /*divisible by seven? Not prime.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────ISPRIME subroutine────────────────────────*/ +isPrime: procedure; parse arg x /*get number to be tested.*/ +if x<17 then return wordpos(x,'2 3 5 7 11 13')\==0 /*test for special cases. */ +if x//2==0 then return 0 /*is it even? Then not prime.*/ +if x//3==0 then return 0 /*divisible by three? " " " */ +if right(x,1)==5 then return 0 /*right-most dig ≡ 5? " " " */ +if x//7==0 then return 0 /*divisible by seven? " " " */ - do j=11 by 6 until j*j>x /*ensures J isn't divisible by 3.*/ - if x// j ==0 then return 0 /*is divisible by J ? */ - if x//(j+2)==0 then return 0 /* " " " J+2 ? ___*/ - end /*j*/ /* [↑] perform loop through √ x */ -return 1 /*indicate the number X is prime.*/ -/*──────────────────────────────────LUCAS_LEHMER2 subroutine────────────*/ -Lucas_Lehmer2: procedure; parse arg ? /*Lucas-Lehmer test on 2**? - 1 */ -if form()\=='SCIENTIFIC' then numeric form /*ensure correct # form.*/ -if ?==2 then s=0 /*handle the special even case.*/ + do j=11 by 6 until j*j>x /*ensures that J isn't divisible by 3. */ + if x// j ==0 then return 0 /*is it divisible by J ? */ + if x//(j+2)==0 then return 0 /* " " " " J+2 ? ___ */ + end /*j*/ /* [↑] perform loop through √ x */ +return 1 /*indicate the number X is prime. */ +/*──────────────────────────────────LUCAS_LEHMER2 subroutine──────────────────*/ +Lucas_Lehmer2: procedure; parse arg ? /*Lucas─Lehmer test on 2**? - 1 */ +numeric form /*ensure the correct REXX number form. */ +if ?==2 then s=0 /*handle special case for an even prime*/ else s=4 -q=2**? /*╔═════════════════════════════════════════════════════════════╗ - ║Compute a power of 2, using only 9 decimal digits. DIGITs ║ - ║of 1 million could be used, but that really gums up the whole║ - ║works. So, we start with the default of 9 digits, find the ║ - ║ten's exponent in the product (2**?), double it, and then add║ - ║6. 2 is all that's needed, but 6 is a lot safer.║ - ║The doubling is for the squaring of S (below, for s*s).║ - ╚═════════════════════════════════════════════════════════════╝*/ -if pos('E',q)\==0 then do /*is # in exponential notation?*/ +q=2**? /*╔═══════════════════════════════════════════════════════════════╗ + ║ Compute a power of two, using only 9 decimal digits. DIGITs ║ + ║ of 1 million could be used, but that really gums up the whole ║ + ║ works. So, we start with the default of 9 digits, find the ║ + ║ ten's exponent in the product (2**?), double it, and then add ║ + ║ 6. 2 is all that's needed, but 6 is a lot safer. ║ + ║ The doubling is for the squaring of S (below, for s*s). ║ + ╚═══════════════════════════════════════════════════════════════╝*/ +if pos('E',q)\==0 then do /*the number in exponential notation? */ parse var q 'E' tenpow numeric digits tenpow*2 + 6 end else numeric digits digits()*2 + 6 /* 9*2 + 6 */ q=2**?-1 - do ?-2 /*apply, rinse, repeat ··· */ - s=(s*s-2) // q /*remainder in REXX is: // */ - end /* [↑] compute the real McCoy. */ + do ?-2 /*apply, rinse, repeat ··· */ + s=(s*s-2) // q /*remainder in REXX is: // */ + end /* [↑] compute the real McCoy. */ -if s\==0 then return '' /*return nuttin' if not prime. */ - return 'M'? /*return modified (prime) number.*/ +if s\==0 then return '' /*return nuttin' if number isn't prime.*/ + return 'M'? /*return a "modified" (prime) number. */ diff --git a/Task/Ludic-numbers/ABAP/ludic-numbers.abap b/Task/Ludic-numbers/ABAP/ludic-numbers.abap new file mode 100644 index 0000000000..7d0d3a9542 --- /dev/null +++ b/Task/Ludic-numbers/ABAP/ludic-numbers.abap @@ -0,0 +1,87 @@ +CLASS lcl_ludic DEFINITION CREATE PUBLIC. + + PUBLIC SECTION. + TYPES: t_ludics TYPE SORTED TABLE OF i WITH UNIQUE KEY table_line. + TYPES: BEGIN OF t_triplet, + i1 TYPE i, + i2 TYPE i, + i3 TYPE i, + END OF t_triplet. + TYPES: t_triplets TYPE STANDARD TABLE OF t_triplet WITH EMPTY KEY. + + CLASS-METHODS: + ludic_up_to + IMPORTING i_int TYPE i + RETURNING VALUE(r_ludics) TYPE t_ludics, + get_triplets + IMPORTING i_ludics TYPE t_ludics + RETURNING VALUE(r_triplets) TYPE t_triplets. + + "RETURNING parameters (CallByValue) only used for readability of the demo + "in "Real Life" you should use EXPORTING (CallByRef) for tables + +ENDCLASS. + +cl_demo_output=>begin_section( 'First 25 Ludics' ). +cl_demo_output=>write( lcl_ludic=>ludic_up_to( 110 ) ). + +cl_demo_output=>begin_section( 'Ludics up to 1000' ). +cl_demo_output=>write( lines( lcl_ludic=>ludic_up_to( 1000 ) ) ). + +cl_demo_output=>begin_section( '2000th - 2005th Ludics' ). +DATA(ludics) = lcl_ludic=>ludic_up_to( 22000 ). +cl_demo_output=>write( VALUE lcl_ludic=>t_ludics( FOR i = 2000 WHILE i <= 2005 ( ludics[ i ] ) ) ). + +cl_demo_output=>begin_section( 'Triplets up to 250' ). +cl_demo_output=>write( lcl_ludic=>get_triplets( lcl_ludic=>ludic_up_to( 250 ) ) ). + +cl_demo_output=>display( ). + +CLASS lcl_ludic IMPLEMENTATION. + + METHOD ludic_up_to. + + r_ludics = VALUE #( FOR i = 2 WHILE i <= i_int ( i ) ). + + DATA(cursor) = 0. + + WHILE cursor < lines( r_ludics ). + + cursor = cursor + 1. + DATA(this_ludic) = r_ludics[ cursor ]. + DATA(remove_cursor) = cursor + this_ludic. + + WHILE remove_cursor <= lines( r_ludics ). + DELETE r_ludics INDEX remove_cursor. + remove_cursor = remove_cursor + this_ludic - 1. + ENDWHILE. + + ENDWHILE. + + INSERT 1 INTO TABLE r_ludics. "add one as the first Ludic number (per definition) + + ENDMETHOD. + + METHOD get_triplets. + + DATA(i) = 0. + WHILE i < lines( i_ludics ) - 2. + i = i + 1. + + DATA(this_ludic) = i_ludics[ i ]. + IF line_exists( i_ludics[ table_line = this_ludic + 2 ] ) + AND line_exists( i_ludics[ table_line = this_ludic + 6 ] ). + r_triplets = VALUE #( + BASE r_triplets + ( i1 = i_ludics[ table_line = this_ludic ] + i2 = i_ludics[ table_line = this_ludic + 2 ] + i3 = i_ludics[ table_line = this_ludic + 6 ] + ) + ). + ENDIF. + + ENDWHILE. + + ENDMETHOD. + +ENDCLASS. diff --git a/Task/Ludic-numbers/Eiffel/ludic-numbers-1.e b/Task/Ludic-numbers/Eiffel/ludic-numbers-1.e index 9c1bfacc10..6978c824d6 100644 --- a/Task/Ludic-numbers/Eiffel/ludic-numbers-1.e +++ b/Task/Ludic-numbers/Eiffel/ludic-numbers-1.e @@ -1,78 +1,89 @@ class LUDIC_NUMBERS -create make + +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 + + make (n: INTEGER) + -- Initialized arrays for find_ludic_numbers. + 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 + find_ludic_numbers end - ludic - end - ludic_numbers: ARRAY[INTEGER] -feature{NONE} - initial: ARRAY[INTEGER] + ludic_numbers: ARRAY [INTEGER] + +feature {NONE} - 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) + initial: ARRAY [INTEGER] + + find_ludic_numbers + -- Ludic numbers in array ludic_numbers. + local + count: INTEGER + new_array: ARRAY [INTEGER] + last: INTEGER + do + create new_array.make_from_array (initial) + last := initial.count + from + count := 1 + until + count > last + 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 - 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 + delete_i_elements (ar: ARRAY [INTEGER]): ARRAY [INTEGER] + --- Array with all multiples of 'ar[1]' deleted. + require + ar_not_empty: ar.count > 0 + local + s_array: ARRAY [INTEGER] + i, k: INTEGER + length: INTEGER + do + create s_array.make_empty + length := ar.count + from + i := 0 + k := 1 + until + i = length + loop + if (i) \\ (ar [1]) /= 0 then + s_array.force (ar [i + 1], k) + k := k + 1 + end + i := i + 1 end - i:= i+1 - end - if s_array.count=0 then - Result:= ar - else - Result:= s_array + if s_array.count = 0 then + Result := ar + else + Result := s_array + end + ensure + not_empty: not Result.is_empty 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 index a74e3f76c3..97628fef0b 100644 --- a/Task/Ludic-numbers/Eiffel/ludic-numbers-2.e +++ b/Task/Ludic-numbers/Eiffel/ludic-numbers-2.e @@ -1,32 +1,40 @@ 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 +create + make - 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 +feature - 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 + 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 + end + ludic: LUDIC_NUMBERS + end diff --git a/Task/Ludic-numbers/Elixir/ludic-numbers.elixir b/Task/Ludic-numbers/Elixir/ludic-numbers.elixir new file mode 100644 index 0000000000..f4a6c75984 --- /dev/null +++ b/Task/Ludic-numbers/Elixir/ludic-numbers.elixir @@ -0,0 +1,28 @@ +defmodule Ludic do + def numbers, do: numbers(100000) + + def numbers(n) when is_integer(n) do + [h|t] = Enum.to_list(1..n) + numbers(t, [h]) + end + + defp numbers(list, nums) when length(list) < hd(list), do: Enum.reverse(nums, list) + defp numbers(list, nums) do + h = hd(list) + ludic = Enum.with_index(list) |> + Enum.filter_map(fn{_,i} -> rem(i,h)!=0 end, fn{n,_} -> n end) + numbers(ludic, [h | nums]) + end + + def task do + IO.puts "First 25 : #{inspect numbers(200) |> Enum.take(25)}" + IO.puts "Below 1000: #{length(numbers(1000))}" + tuple = numbers(25000) |> List.to_tuple + IO.puts "2000..2005th: #{ inspect Enum.map(1999..2004, fn i -> elem(tuple, i) end) }" + ludic = numbers(250) + triple = for x<-ludic, Enum.member?(ludic, x+2), Enum.member?(ludic, x+6), do: [x, x+2, x+6] + IO.puts "Triples below 250: #{inspect triple, char_lists: :as_lists}" + end +end + +Ludic.task diff --git a/Task/Ludic-numbers/Fortran/ludic-numbers.f b/Task/Ludic-numbers/Fortran/ludic-numbers.f new file mode 100644 index 0000000000..02cf87729f --- /dev/null +++ b/Task/Ludic-numbers/Fortran/ludic-numbers.f @@ -0,0 +1,53 @@ +program ludic_numbers + implicit none + + integer, parameter :: nmax = 25000 + logical :: ludic(nmax) = .true. + integer :: i, j, n + + do i = 2, nmax / 2 + if (ludic(i)) then + n = 0 + do j = i+1, nmax + if(ludic(j)) n = n + 1 + if(n == i) then + ludic(j) = .false. + n = 0 + end if + end do + end if + end do + + write(*, "(a)", advance = "no") "First 25 Ludic numbers: " + n = 0 + do i = 1, nmax + if(ludic(i)) then + write(*, "(i0, 1x)", advance = "no") i + n = n + 1 + end if + if(n == 25) exit + end do + + write(*, "(/, a)", advance = "no") "Ludic numbers below 1000: " + write(*, "(i0)") count(ludic(:999)) + + write(*, "(a)", advance = "no") "Ludic numbers 2000 to 2005: " + n = 0 + do i = 1, nmax + if(ludic(i)) then + n = n + 1 + if(n >= 2000) then + write(*, "(i0, 1x)", advance = "no") i + if(n == 2005) exit + end if + end if + end do + + write(*, "(/, a)", advance = "no") "Ludic Triplets below 250: " + do i = 1, 243 + if(ludic(i) .and. ludic(i+2) .and. ludic(i+6)) then + write(*, "(a, 2(i0, 1x), i0, a, 1x)", advance = "no") "[", i, i+2, i+6, "]" + end if + end do + +end program diff --git a/Task/Ludic-numbers/Julia/ludic-numbers.julia b/Task/Ludic-numbers/Julia/ludic-numbers.julia new file mode 100644 index 0000000000..c0483354d8 --- /dev/null +++ b/Task/Ludic-numbers/Julia/ludic-numbers.julia @@ -0,0 +1,61 @@ +function ludic_filter{T<:Integer}(n::T) + 0 < n || throw(DomainError()) + slud = trues(n) + for i in 2:(n-1) + slud[i] || continue + x = 0 + for j in (i+1):n + slud[j] || continue + x += 1 + x %= i + x == 0 || continue + slud[j] = false + end + end + return slud +end + +ludlen = 10^5 +slud = ludic_filter(ludlen) +ludics = collect(1:ludlen)[slud] + +n = 25 +println("Generate and show here the first ", n, " ludic numbers.") +print(" ") +crwid = 76 +wid = 0 +for i in 1:(n-1) + s = @sprintf "%d, " ludics[i] + wid += length(s) + if crwid < wid + print("\n ") + wid = 0 + end + print(s) +end +println(ludics[n]) + +n = 10^3 +println() +println("How many ludic numbers are there less than or equal to ", n, "?") +println(" ", sum(slud[1:n])) + +lo = 2000 +hi = lo+5 +println() +println("Show the ", lo, "..", hi, "'th ludic numbers.") +for i in lo:hi + println(" Ludic(", i, ") = ", ludics[i]) +end + +n = 250 +println() +println("Show all triplets of ludic numbers < ", n) +for i = 1:n-7 + slud[i] || continue + j = i+2 + slud[j] || continue + k = i+6 + slud[k] || continue + println(" ", i, ", ", j, ", ", k) +end diff --git a/Task/Ludic-numbers/PL-SQL/ludic-numbers.sql b/Task/Ludic-numbers/PL-SQL/ludic-numbers.sql new file mode 100644 index 0000000000..c244471967 --- /dev/null +++ b/Task/Ludic-numbers/PL-SQL/ludic-numbers.sql @@ -0,0 +1,78 @@ +SET SERVEROUTPUT ON +DECLARE + c_limit CONSTANT PLS_INTEGER := 25000; + TYPE t_nums IS TABLE OF PLS_INTEGER INDEX BY PLS_INTEGER; + v_nums t_nums; + v_ludic t_nums; + v_count_ludic PLS_INTEGER; + v_count_pos PLS_INTEGER; + v_pos PLS_INTEGER; + v_next_ludic PLS_INTEGER; + + FUNCTION is_ludic(p_num PLS_INTEGER) RETURN BOOLEAN IS + BEGIN + FOR i IN 1..v_ludic.COUNT LOOP + EXIT WHEN v_ludic(i) > p_num; + IF v_ludic(i) = p_num THEN + RETURN TRUE; + END IF; + END LOOP; + RETURN FALSE; + END; + +BEGIN + FOR i IN 1..c_limit LOOP + v_nums(i) := i; + END LOOP; + + v_count_ludic := 1; + v_next_ludic := 1; + v_ludic(v_count_ludic) := v_next_ludic; + v_nums.DELETE(1); + + WHILE v_nums.COUNT > 0 LOOP + v_pos := v_nums.FIRST; + v_next_ludic := v_nums(v_pos); + v_count_ludic := v_count_ludic + 1; + v_ludic(v_count_ludic) := v_next_ludic; + v_count_pos := 0; + WHILE v_pos IS NOT NULL LOOP + IF MOD(v_count_pos, v_next_ludic) = 0 THEN + v_nums.DELETE(v_pos); + END IF; + v_pos := v_nums.NEXT(v_pos); + v_count_pos := v_count_pos + 1; + END LOOP; + END LOOP; + + dbms_output.put_line('Generate and show here the first 25 ludic numbers.'); + FOR i IN 1..25 LOOP + dbms_output.put(v_ludic(i) || ' '); + END LOOP; + dbms_output.put_line(''); + + dbms_output.put_line('How many ludic numbers are there less than or equal to 1000?'); + v_count_ludic := 0; + FOR i IN 1..v_ludic.COUNT LOOP + EXIT WHEN v_ludic(i) > 1000; + v_count_ludic := v_count_ludic + 1; + END LOOP; + dbms_output.put_line(v_count_ludic); + + dbms_output.put_line('Show the 2000..2005''th ludic numbers.'); + FOR i IN 2000..2005 LOOP + dbms_output.put(v_ludic(i) || ' '); + END LOOP; + dbms_output.put_line(''); + + dbms_output.put_line('A triplet is any three numbers x, x + 2, x + 6 where all three numbers are also ludic numbers.'); + dbms_output.put_line('Show all triplets of ludic numbers < 250 (Stretch goal)'); + FOR i IN 1..v_ludic.COUNT LOOP + EXIT WHEN (v_ludic(i)+6) >= 250; + IF is_ludic(v_ludic(i)+2) AND is_ludic(v_ludic(i)+6) THEN + dbms_output.put_line(v_ludic(i) || ', ' || (v_ludic(i)+2) || ', ' || (v_ludic(i)+6)); + END IF; + END LOOP; + +END; +/ diff --git a/Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 b/Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 index 2d3f9155b9..4832d6031f 100644 --- a/Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 +++ b/Task/Ludic-numbers/Perl-6/ludic-numbers.pl6 @@ -1,4 +1,4 @@ -constant ludic = gather { +constant @ludic = gather { my @taken = take 1; my @rotor; @@ -16,13 +16,13 @@ constant ludic = gather { } } -say ludic[^25]; -say "Number of Ludic numbers <= 1000: ", +(ludic ...^ * > 1000); -say "Ludic numbers 2000..2005: ", ludic[1999..2004]; +say @ludic[^25]; +say "Number of Ludic numbers <= 1000: ", +(@ludic ...^ * > 1000); +say "Ludic numbers 2000..2005: ", @ludic[1999..2004]; -my \l250 = set ludic ...^ * > 250; +my \l250 = set @ludic ...^ * > 250; say "Ludic triples < 250: ", gather - for l250.keys -> $a { + for l250.keys.sort -> $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/Python/ludic-numbers-1.py b/Task/Ludic-numbers/Python/ludic-numbers-1.py index c3356947f4..5e9d62e55d 100644 --- a/Task/Ludic-numbers/Python/ludic-numbers-1.py +++ b/Task/Ludic-numbers/Python/ludic-numbers-1.py @@ -5,7 +5,7 @@ def ludic(nmax=100000): yield lst[0] del lst[::lst[0]] -ludics = [l for i,l in zip(range(2005), ludic())] +ludics = [l for l in ludic()] print('First 25 ludic primes:') print(ludics[:25]) diff --git a/Task/Ludic-numbers/VBScript/ludic-numbers.vb b/Task/Ludic-numbers/VBScript/ludic-numbers.vb new file mode 100644 index 0000000000..a1a9f9c686 --- /dev/null +++ b/Task/Ludic-numbers/VBScript/ludic-numbers.vb @@ -0,0 +1,73 @@ +Set list = CreateObject("System.Collections.Arraylist") +Set ludic = CreateObject("System.Collections.Arraylist") + +'populate the list +For i = 1 To 25000 + list.Add i +Next + +'set 1 as the first ludic number +ludic.Add list(0) +list.RemoveAt(0) + +'variable to count ludic numbers <= 1000 +up_to_1k = 1 + +'determine the succeeding ludic numbers +For j = 2 To 2005 + If list.Count > 0 Then + If list(0) <= 1000 Then + up_to_1k = up_to_1k + 1 + End If + ludic.Add list(0) + Else + Exit For + End If + increment = list(0) - 1 + n = 0 + Do While n <= list.Count - 1 + list.RemoveAt(n) + n = n + increment + Loop +Next + +'the first 25 ludics +WScript.StdOut.WriteLine "First 25 Ludic Numbers:" +For k = 0 To 24 + If k < 24 Then + WScript.StdOut.Write ludic(k) & ", " + Else + WScript.StdOut.Write ludic(k) + End If +Next +WScript.StdOut.WriteBlankLines(2) + +'the number of ludics up to 1000 +WScript.StdOut.WriteLine "Ludics up to 1000: " +WScript.StdOut.WriteLine up_to_1k +WScript.StdOut.WriteBlankLines(1) + +'2000th - 2005th ludics +WScript.StdOut.WriteLine "The 2000th - 2005th Ludic Numbers:" +For k = 1999 To 2004 + If k < 2004 Then + WScript.StdOut.Write ludic(k) & ", " + Else + WScript.StdOut.Write ludic(k) + End If +Next +WScript.StdOut.WriteBlankLines(2) + +'triplets up to 250: x, x+2, and x+6 +WScript.StdOut.WriteLine "Ludic Triplets up to 250: " +triplets = "" +k = 0 +Do While ludic(k) + 6 <= 250 + x2 = ludic(k) + 2 + x6 = ludic(k) + 6 + If ludic.IndexOf(x2,1) > 0 And ludic.IndexOf(x6,1) > 0 Then + triplets = triplets & ludic(k) & ", " & x2 & ", " & x6 & vbCrLf + End If + k = k + 1 +Loop +WScript.StdOut.WriteLine triplets diff --git a/Task/Luhn-test-of-credit-card-numbers/00DESCRIPTION b/Task/Luhn-test-of-credit-card-numbers/00DESCRIPTION index 03d03ce103..e8ff41f40b 100644 --- a/Task/Luhn-test-of-credit-card-numbers/00DESCRIPTION +++ b/Task/Luhn-test-of-credit-card-numbers/00DESCRIPTION @@ -31,4 +31,4 @@ The task is to '''write a function/method/procedure/subroutine that will validat :1234567812345678 :1234567812345670 -Cf. [[SEDOLs|SEDOL]] +Cf. [[SEDOLs|SEDOL]], [[Calculate International Securities Identification Number|ISIN]] diff --git a/Task/Luhn-test-of-credit-card-numbers/ARM-Assembly/luhn-test-of-credit-card-numbers.arm b/Task/Luhn-test-of-credit-card-numbers/ARM-Assembly/luhn-test-of-credit-card-numbers.arm new file mode 100644 index 0000000000..e9d65afa49 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/ARM-Assembly/luhn-test-of-credit-card-numbers.arm @@ -0,0 +1,174 @@ +.text +.global _start +_start: + ldr r0, =example_numbers + bl test_number + + add r1, r0, #1 + bl length + add r0, r1, r0 + bl test_number + + add r1, r0, #1 + bl length + add r0, r1, r0 + bl test_number + + add r1, r0, #1 + bl length + add r0, r1, r0 + bl test_number + + mov r0, #0 + mov r7, #1 + swi 0 + +test_number: + push {r0, lr} + bl print_string + + bl luhn_test + cmp r0, #1 + ldreq r0, =valid_message + ldrne r0, =invalid_message + bl print_string + pop {r0, lr} + mov pc, lr + + + +print_string: + push {r0-r7, lr} + mov r1, r0 @ string to print + bl length + mov r2, r0 @ length of string + mov r0, #1 @ write to stdout + mov r7, #4 @ SYS_WRITE + swi 0 @ call system interupt + pop {r0-r7, lr} + mov pc, lr + +@ r0 address of credit card number string +@ returns result in r0 +luhn_test: + push {r1-r7, lr} + mov r1, r0 + bl isNumerical @ check if string is a number + cmp r0, #1 + bne .luhn_test_end @ exit if not number + mov r0, r1 + ldr r1, =reversed_string @ address to store reversed string + bl reverse @ reverse string + push {r0} + bl length @ get length of string + mov r4, r0 @ store string length in r4 + pop {r0} + mov r2, #0 @ string index + mov r6, #0 @ sum of odd digits + mov r7, #0 @ sum of even digits + .loadNext: + ldrb r3, [r1, r2] @ load byte into r3 + sub r3, #'0' @ convert letter to digit + and r5, r2, #1 @ test if index is even or odd + cmp r5, #0 + beq .odd_digit + bne .even_digit + .odd_digit: + add r6, r3 @ add digit to sum if odd + b .continue @ skip next step + .even_digit: + lsl r3, #1 @ multiply digit by 2 + cmp r3, #10 @ sum digits + subge r3, #10 @ get digit in 1s place + addge r3, #1 @ add 1 for the 10s place + add r7, r3 @ add digit sum to the total + + .continue: + add r2, #1 @ increment digit index + cmp r2, r4 @ check if at end of string + blt .loadNext + + add r0, r6, r7 @ add even and odd sum + mov r3, r0 @ copy sum to r3 + ldr r1, =429496730 @ (2^32-1)/10 + sub r0, r0, r0, lsr #30 @ divide by 10 + umull r2, r0, r1, r0 + mov r1, #10 + mul r0, r1 @ multiply the r0 by 10 to see if divisible + cmp r0, r3 @ compare with the original value in r3 + .luhn_test_end: + movne r0, #0 @ return false if invalid card number + moveq r0, #1 @ return true if valid card number + pop {r1-r7, lr} + mov pc, lr + +length: + push {r1-r2, lr} + mov r2, r0 @ start of string address + .loop: + ldrb r1, [r2], #1 @ load byte from address r2 and increment + cmp r1, #0 @ check for end of string + bne .loop @ load next byte if not 0 + sub r0, r2, r0 @ subtract end of string address from start + sub r0, #1 @ end of line from count + pop {r1-r2, lr} + mov pc, lr + +@ reverses a string +@ r0 address of string to reverse +@ r1 address to store reversed string +reverse: + push {r0-r5, lr} + push {r0, lr} + bl length @ get length of string to reverse + mov r3, r0 @ backword index + pop {r0, lr} + mov r4, #0 @ fowrard index + .reverse_next: + sub r3, #1 @ decrement backword index + ldrb r5, [r0, r3] @ load byte from original string at index + strb r5, [r1, r4] @ copy byte to reversed string + add r4, #1 @ increment fowrard index + cmp r3, #0 @ check if any characters are left + bge .reverse_next + + mov r5, #0 + strb r5, [r1, r4] @ write null byte to terminate reversed string + pop {r0-r5, lr} + mov pc, lr + +isNumerical: + push {r1, lr} + .isNumerical_checkNext: + ldrb r1, [r0], #1 + cmp r1, #0 + beq .isNumerical_true + cmp r1, #'0' + blt .isNumerical_false + cmp r1, #'9' + bgt .isNumerical_false + b .isNumerical_checkNext + .isNumerical_false: + mov r0, #0 + b .isNumerical_end + .isNumerical_true: + mov r0, #1 + .isNumerical_end: + pop {r1, lr} + mov pc, lr + + +.data +valid_message: + .asciz " valid card number\n" +invalid_message: + .asciz " invalid card number\n" + +reversed_string: + .space 32 + +example_numbers: + .asciz "49927398716" + .asciz "49927398717" + .asciz "1234567812345678" + .asciz "1234567812345670" diff --git a/Task/Luhn-test-of-credit-card-numbers/Batch-File/luhn-test-of-credit-card-numbers.bat b/Task/Luhn-test-of-credit-card-numbers/Batch-File/luhn-test-of-credit-card-numbers.bat new file mode 100644 index 0000000000..baedfb7b79 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Batch-File/luhn-test-of-credit-card-numbers.bat @@ -0,0 +1,33 @@ +@echo off +setlocal enabledelayedexpansion + +call :luhn 49927398716 +call :luhn 49927398717 +call :luhn 1234567812345678 +call :luhn 1234567812345670 +exit /b 0 + +:luhn +set input=%1 +set cnt=0 +set s1=0&set s2=0 +:digit_loop + set /a cnt-=1 + set /a isOdd=^(-%cnt%^)%%2 + + if !isodd! equ 1 ( + set /a s1+=!input:~%cnt%,1! + ) else ( + set /a twice=!input:~%cnt%,1!*2 + if !twice! geq 10 ( + set /a s2+=!twice:~0,1!+!twice:~1,1! + ) else ( + set /a s2+=!twice! + ) + ) + if "!input:~%cnt%!"=="!input!" ( + set /a sum=^(!s1!+!s2!^)%%10 + if !sum! equ 0 (echo !input! is valid.) else (echo !input! is not valid.) + goto :EOF + ) + goto digit_loop diff --git a/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers.cpp b/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-1.cpp similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers.cpp rename to Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-1.cpp diff --git a/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-2.cpp b/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-2.cpp new file mode 100644 index 0000000000..99052f5f5c --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/C++/luhn-test-of-credit-card-numbers-2.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +using namespace std; + +bool luhn( const string& id) +{ + static const int m[10] = {0,2,4,6,8,1,3,5,7,9}; // mapping for rule 3 + bool is_odd_dgt = false; + auto lambda = [&](int a, char c) {return a + ((is_odd_dgt = !is_odd_dgt) ? c-'0' : m[c-'0']);}; + int s = std::accumulate(id.rbegin(), id.rend(), 0, lambda); + return 0 == s%10; +} + +int main( ) +{ + auto t_cases = {"49927398716", "49927398717", "1234567812345678", "1234567812345670"}; + auto print = [](const string & s) {cout << s << ": " << luhn(s) << endl;}; + for_each(t_cases.begin(), t_cases.end(), print); + return 0; +} diff --git a/Task/Luhn-test-of-credit-card-numbers/Elixir/luhn-test-of-credit-card-numbers.elixir b/Task/Luhn-test-of-credit-card-numbers/Elixir/luhn-test-of-credit-card-numbers.elixir new file mode 100644 index 0000000000..74c7cc42cf --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Elixir/luhn-test-of-credit-card-numbers.elixir @@ -0,0 +1,18 @@ +defmodule Luhn do + def test(digits) do + to_char_list(digits) |> Enum.reverse |> Enum.map(&(&1-?0)) |> luhn_sum |> check + end + + defp luhn_sum([odd, even | rest]) when even >= 5, do: + odd + 2 * even - 10 + 1 + luhn_sum(rest) + defp luhn_sum([odd, even | rest]), do: + odd + 2 * even + luhn_sum(rest) + defp luhn_sum([odd]), do: odd + defp luhn_sum([]), do: 0 + + defp check(sum) when rem(sum,10)==0, do: :valid + defp check(_sum), do: :invalid +end + +numbers = ~w(49927398716 49927398717 1234567812345678 1234567812345670) +Enum.each(numbers, fn x -> IO.puts "#{x}: #{Luhn.test(x)}" end) diff --git a/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-3.js b/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-3.js index 1551f70682..d5f77db23e 100644 --- a/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-3.js +++ b/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-3.js @@ -1,11 +1,9 @@ -var luhn10 = function(a,b,c,d,e) { - for(d = +a[b = a.length-1], e=0; b--;) - c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c; - return !(d%10) -}; - -// returns true -luhn10('4111111111111111') - -// returns false -luhn10('4111111111111112') +function luhn(str){ + return str.split('').reduceRight(function(prev, curr, idx){ + prev = parseInt(prev, 10); + if ((idx + 1) % 2 !== 0) { + curr = (curr * 2).toString().split('').reduce(function(p, c){ return parseInt(p, 10) + parseInt(c, 10)}); + } + return prev + parseInt(curr, 10); + }) % 10 === 0; +} diff --git a/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-4.js b/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-4.js new file mode 100644 index 0000000000..1551f70682 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-4.js @@ -0,0 +1,11 @@ +var luhn10 = function(a,b,c,d,e) { + for(d = +a[b = a.length-1], e=0; b--;) + c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c; + return !(d%10) +}; + +// returns true +luhn10('4111111111111111') + +// returns false +luhn10('4111111111111112') diff --git a/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers.julia b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers.julia new file mode 100644 index 0000000000..ea6594a4dc --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers.julia @@ -0,0 +1,5 @@ +luhntest(x::Int) = (sum(digits(x)[1:2:end]) + sum(map(x -> sum(digits(x)), 2 * digits(x)[2:2:end]))) % 10 == 0 + +for card in [49927398716, 49927398717, 1234567812345678, 1234567812345670] + println(luhntest(card) ? "PASS " : "FAIL ", card) +end diff --git a/Task/Luhn-test-of-credit-card-numbers/MATLAB/luhn-test-of-credit-card-numbers.m b/Task/Luhn-test-of-credit-card-numbers/MATLAB/luhn-test-of-credit-card-numbers.m new file mode 100644 index 0000000000..71d63750e6 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/MATLAB/luhn-test-of-credit-card-numbers.m @@ -0,0 +1,13 @@ +function passed = luhn(num) +if nargin == 0 % evaluate test cases + testnum = [49927398716 49927398717 1234567812345678 1234567812345670]; + for num = testnum + disp([int2str(num) ': ' int2str(luhn(num))]) + end + return +end +% luhn function starts here +d = int2str(num) - '0'; % convert number into vector of digits +m = [2:2:8,1:2:9]; % rule 3: maps 1:9 to [2 4 6 8 1 3 5 7 9] +passed = ~mod(sum(d(end:-2:1)) + sum(m(d(end-1:-2:1))), 10); +end diff --git a/Task/Luhn-test-of-credit-card-numbers/REXX/luhn-test-of-credit-card-numbers-1.rexx b/Task/Luhn-test-of-credit-card-numbers/REXX/luhn-test-of-credit-card-numbers-1.rexx index f41356099a..910a1e25f2 100644 --- a/Task/Luhn-test-of-credit-card-numbers/REXX/luhn-test-of-credit-card-numbers-1.rexx +++ b/Task/Luhn-test-of-credit-card-numbers/REXX/luhn-test-of-credit-card-numbers-1.rexx @@ -1,18 +1,17 @@ -/*REXX program validates credit card numbers via the Luhn algorithm.*/ -cc. =; @@='the Luhn test for a credit card number.' /*literal*/ -cc.1 = 49927398716 /*sample credit card number one. */ -cc.2 = 49927398717 /* " " " " two. */ -cc.3 = 1234567812345678 /* " " " " three*/ -cc.4 = 1234567812345670 /* " " " " four.*/ - do k=1 while cc.k\=='' /*process all the credit card #s.*/ - say right(cc.k, 30) LuhnTest(cc.k) @@ /*see if valid.*/ - end /*k*/ /* [↑] show if it passed/flunked.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────LUHNTEST subroutine─────────────────*/ -LuhnTest: procedure; parse arg t; s=0 /*get credit card#, set S to zero*/ -t=reverse(left(0,length(t)//2)t) /*add leading 0 if needed,reverse*/ - do j=1 to length(t)-1 by 2; q=2*substr(t,j+1,1) - s=s + substr(t,j,1) + left(q,1) + substr(q,2,1,0) - end /*j*/ /* [↑] sum odd and even digits.*/ -if s//10==0 then return 'passed ' /*if ending in zero, then passed.*/ - else return 'flunked' /*if ¬ ending in 0, not so good.*/ +/*REXX program validates credit card numbers using the Luhn algorithm. */ +#.=; #.1=49927398716 /*the 1st sample credit card number. */ + #.2=49927398717 /* " 2nd " " " " */ + #.3=1234567812345678 /* " 3rd " " " " */ + #.4=1234567812345670 /* " 4th " " " " */ + do k=1 while #.k\=='' /*validate all the credit card numbers.*/ + say right(#.k,30) LuhnTest(#.k) ' the Luhn test for a credit card number.' + end /*k*/ /* [↑] show if number passed │ flunked*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +LuhnTest: procedure; parse arg x; $=0 /*get credit card number; zero $ sum. */ +y=reverse(left(0,length(x)//2)x) /*add leading zero if needed, reverse. */ + do j=1 to length(y)-1 by 2; _=2*substr(y,j+1,1) + $=$ + substr(y,j,1) + left(_,1) + substr(_,2,1,0) + end /*j*/ /* [↑] sum the odd and even digits.*/ +if $//10==0 then return ' passed' /*if ending in zero, then the # passed.*/ + else return 'flunked' /*if ¬ ending in 0, then not so good. */ diff --git a/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust b/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust index 70a0df843a..032a320f80 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust +++ b/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust @@ -1,48 +1,33 @@ -fn get_digits(i: &int) -> Vec { - let mut digits = Vec::new(); - let mut n = *i; - while n > 0 { - digits.push(n % 10); - n /= 10; - } - digits.reverse(); - return digits +fn get_digits(mut num: u64) -> Vec { + let mut digits = vec![]; + while num != 0 { + digits.push(num % 10); + num /= 10; + } + digits } -fn luhn_test(n: &int) -> bool { - let mut digits = get_digits(n); - - let mut i = 0; - let mut sum = 0; - - let is_odd = |x: int| x&1 == 1; - - digits.reverse(); - for n in digits.iter() { - i += 1; - if is_odd(i) { - // add directly to sum - sum += *n; - } else { - // get sum of digits of n*2 - let n_digits = get_digits(&(*n * 2)); - for n_digit in n_digits.iter() { - sum += *n_digit; - } - } - } +fn digit_sum(num: u64) -> u64 { + get_digits(num).into_iter().fold(0,|sum, dig| sum + dig) +} - return sum % 10 == 0; +fn luhn_test(n: u64) -> bool { + let mut sum = 0; + for (i,digit) in get_digits(n).into_iter().enumerate() { + sum += match i % 2 == 0 { + true => digit, + false => digit_sum(2*digit), + } + } + sum % 10 == 0 } fn main() { - let nos = [49927398716, 49927398717, 1234567812345678, 1234567812345670]; - for n in nos.iter() { - if luhn_test(n) { - println!("{} passes.", n); - continue - } - - println!("{} fails.", n); - } + let nums = [49927398716, 49927398717, 1234567812345678, 1234567812345670]; + for &n in &nums { + match luhn_test(n) { + true => println!("{} passes.", n), + false => println!("{} fails.", n), + } + } } diff --git a/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala b/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala index 8146fc337d..65d66b6be4 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala +++ b/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala @@ -1,18 +1,7 @@ object LuhnTest extends App { - def luhnTest1(number: String): Boolean = { - var (odd, sum) = (true, 0) - - for (int <- number.reverse.map { _.toString.toShort }) { - if (odd) sum += int else sum += (int * 2 % 10) + (int / 5) - odd = !odd - } - sum % 10 == 0 - } - - def luhnChecksum(number: String) = { // This function can be used for Check digit generation - (number.reverse.map { _.toString.toShort }.grouped(2) map - { t => t(0) + (if (t.length > 1) (t(1) * 2) % 10 + t(1) / 5 else 0) }).sum % 10 - } + val (validNumbers, invalidNumbers) = + (List("2621195162335", "49927398716", "1234567812345670", "4485284720134093"), + List("49927398717", "1234567812345678")) // Bonus function Compute check digit and assemble it to a valid number def luhnWithComputedCheckDigit(partialCardNumber: String): String = { @@ -20,19 +9,26 @@ object LuhnTest extends App { ((10 - luhnChecksum((partialCardNumber.toLong * 10).toString)) % 10).toString } - val (validNumbers, invalidNumbers) = - (List("49927398716", "1234567812345670"), List("49927398717", "1234567812345678")) + def luhnChecksum(number: Seq[Char]): Int = { + require(number.length <= 18, "Luhn code > 18 positions") + def doubler(digitPair: Seq[Short]) = { + digitPair.head + ( + if (digitPair.length > 1) + digitPair.last * 2 - (if (digitPair.last >= 5) 9 else 0) + else 0) + } + + number.reverse.map(_.toString.toShort).grouped(2).foldLeft(0)((acc, a) => acc + doubler(a)) % 10 + } // Valid number test - assert(validNumbers.forall(x => luhnChecksum(x) == 0), - "Correct number signaled as invalid") + assert(validNumbers.forall(x => luhnChecksum(x) == 0), "Correct number signaled as invalid") // Invalid number test - assert(invalidNumbers.forall(x => luhnChecksum(x) != 0), - "Incorrect number signaled as valid") + assert(invalidNumbers.forall(x => luhnChecksum(x) != 0), "Incorrect number signaled as valid") // Test Check digit computation, reuse the valid and invalid numbers assert((validNumbers ++ invalidNumbers. - map(s => luhnWithComputedCheckDigit(s.init /*make partial*/ ))).forall(x => luhnChecksum(x) == 0), + map(s => luhnWithComputedCheckDigit(s.init /*make partial*/))).forall(x => luhnChecksum(x) == 0), "Error in computed checkdigit") print("Successfully completed without errors.") diff --git a/Task/Luhn-test-of-credit-card-numbers/UNIX-Shell/luhn-test-of-credit-card-numbers.sh b/Task/Luhn-test-of-credit-card-numbers/UNIX-Shell/luhn-test-of-credit-card-numbers.sh index 231abf0839..1eb3fc4a77 100644 --- a/Task/Luhn-test-of-credit-card-numbers/UNIX-Shell/luhn-test-of-credit-card-numbers.sh +++ b/Task/Luhn-test-of-credit-card-numbers/UNIX-Shell/luhn-test-of-credit-card-numbers.sh @@ -1,36 +1,16 @@ -luhn() { - reverse $1 | { - while read odd; do - (( s1 += odd )) - read even - e=0 - for digit in $(digits $(( 2 * even)) ); do - (( e += digit )) - done - (( s2 += e )) - done - (( (s1+s2) % 10 == 0 )) - } -} - -reverse() { - local i digits=( $(digits $1) ) - for ((i=${#digits[@]}-1; i>=0; i--)); do - echo ${digits[i]} - done -} - -digits() { - local i - for ((i=0; i<${#1}; i++)); do - echo ${1:i:1} - done +function luhn { + typeset n p s t=('0123456789' '0516273849') + while ((-n<${#1})); do + p="${t[n--%2]%${1:n:1}*}" + ((s+=${#p})) + done + ((s%10)) } for c in 49927398716 49927398717 1234567812345678 1234567812345670; do if luhn $c; then - echo $c is valid - else echo $c is invalid + else + echo $c is valid fi done diff --git a/Task/MD4/Haskell/md4.hs b/Task/MD4/Haskell/md4.hs new file mode 100644 index 0000000000..f7495c0360 --- /dev/null +++ b/Task/MD4/Haskell/md4.hs @@ -0,0 +1,9 @@ +#!/usr/bin/env runhaskell + +import Data.ByteString.Char8 (pack) +import System.Environment (getArgs) +import Crypto.Hash + +main :: IO () +main = print . md4 . pack . unwords =<< getArgs + where md4 x = hash x :: Digest MD4 diff --git a/Task/MD4/Julia/md4.julia b/Task/MD4/Julia/md4.julia new file mode 100644 index 0000000000..59189dbebe --- /dev/null +++ b/Task/MD4/Julia/md4.julia @@ -0,0 +1,9 @@ +using Nettle + +msg = "Rosetta Code" + +h = HashState(MD4) +update!(h, msg) +h = hexdigest!(h) + +println("\"", msg, "\" => ", h) diff --git a/Task/MD5-Implementation/00DESCRIPTION b/Task/MD5-Implementation/00DESCRIPTION index 0f9369ed46..8c4ad42a89 100644 --- a/Task/MD5-Implementation/00DESCRIPTION +++ b/Task/MD5-Implementation/00DESCRIPTION @@ -23,4 +23,4 @@ In addition, intermediate outputs to aid in developing an implementation can be The MD5 Message-Digest Algorithm was developed by [[wp:RSA_SecurityRSA|RSA Data Security, Inc.]] in 1991. -{{alertbox|#ffff70|'''Warning'''
Rosetta Code is '''not''' a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been ''broken'' and should not be used applications requiring security. For these consider [[wp:SHA2|SHA2]] or the upcoming [[wp:SHA3|SHA3]].}} +{{alertbox|#ffff70|'''Warning'''
Rosetta Code is '''not''' a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been ''broken'' and should not be used in applications requiring security. For these consider [[wp:SHA2|SHA2]] or the upcoming [[wp:SHA3|SHA3]].}} diff --git a/Task/MD5-Implementation/C-sharp/md5-implementation-2.cs b/Task/MD5-Implementation/C-sharp/md5-implementation-2.cs index b0b0555f2a..052922a1d4 100644 --- a/Task/MD5-Implementation/C-sharp/md5-implementation-2.cs +++ b/Task/MD5-Implementation/C-sharp/md5-implementation-2.cs @@ -1,6 +1,6 @@ System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bs = System.Text.Encoding.UTF8.GetBytes(password); -bs = x.ComputeHash(bs); +bs = x.ComputeHash(bs); //this function is not in the above classdefinition System.Text.StringBuilder s = new System.Text.StringBuilder(); foreach (byte b in bs) { diff --git a/Task/MD5-Implementation/CoffeeScript/md5-implementation-1.coffee b/Task/MD5-Implementation/CoffeeScript/md5-implementation-1.coffee new file mode 100644 index 0000000000..69d7be612b --- /dev/null +++ b/Task/MD5-Implementation/CoffeeScript/md5-implementation-1.coffee @@ -0,0 +1,65 @@ +# Array sum helper function. +sum = (array) -> + array.reduce (x, y) -> x + y + +md5 = do -> + # Per-round shift amounts. + s = [738695, 669989, 770404, 703814] + s = (s[i >> 4] >> i % 4 * 5 & 31 for i in [0..63]) + + # Constants cache generated by sine. + K = (Math.floor 2**32 * Math.abs Math.sin i for i in [1..64]) + + # Bitwise left rotate helper function. + lrot = (x, y) -> + x << y | x >>> 32 - y; + + (input) -> + # Initialize values. + d0 = 0x10325476; + a0 = 0x67452301; + b0 = ~d0 + c0 = ~a0; + + # Convert the message to 32-bit words, little-endian. + M = + for i in [0...input.length] by 4 + sum (input.charCodeAt(i + j) << j*8 for j in [0..3]) + + # Pre-processing: append a 1 bit, then message length % 2^64. + len = input.length * 8 + M[len >> 5] |= 128 << len % 32 + M[(len + 64 >>> 9 << 4) + 14] = len + + # Process the message in chunks of 16 32-bit words. + for x in [0...M.length] by 16 + [A, B, C, D] = [a0, b0, c0, d0] + + # Main loop. + for i in [0..63] + if i < 16 + F = B & C | ~B & D + g = i + else if i < 32 + F = B & D | C & ~D + g = i * 5 + 1 + else if i < 48 + F = B ^ C ^ D + g = i * 3 + 5 + else + F = C ^ (B | ~D) + g = i * 7 + + [A, B, C, D] = + [D, B + lrot(A + F + K[i] + (M[x + g % 16] ? 0), s[i]), B, C] + + a0 += A + b0 += B + c0 += C + d0 += D + + # Convert the four words back to a string. + return ( + for x in [a0, b0, c0, d0] + (String.fromCharCode x >>> 8 * y & 255 for y in [0..3]).join '' + ).join '' diff --git a/Task/MD5-Implementation/CoffeeScript/md5-implementation-2.coffee b/Task/MD5-Implementation/CoffeeScript/md5-implementation-2.coffee new file mode 100644 index 0000000000..31dcc282bc --- /dev/null +++ b/Task/MD5-Implementation/CoffeeScript/md5-implementation-2.coffee @@ -0,0 +1,16 @@ +str2hex = do -> + hex = ['0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] + hex = (hex[x >> 4] + hex[x & 15] for x in [0..255]) + (str) -> + (hex[c.charCodeAt()] for c in str).join '' + +console.log str2hex md5 message for message in [ + "" + "a" + "abc" + "message digest" + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + "12345678901234567890123456789012345678901234567890123456789012345678901234567890" +] diff --git a/Task/MD5-Implementation/Go/md5-implementation.go b/Task/MD5-Implementation/Go/md5-implementation.go index 70f233faf2..250371cc44 100644 --- a/Task/MD5-Implementation/Go/md5-implementation.go +++ b/Task/MD5-Implementation/Go/md5-implementation.go @@ -3,6 +3,8 @@ package main import ( "fmt" "math" + "bytes" + "encoding/binary" ) type testCase struct { @@ -38,22 +40,17 @@ func init() { } func md5(s string) (r [16]byte) { - numBlocks := (len(s) + 72) >> 6 - padded := make([]byte, numBlocks<<6) - copy(padded, s) - padded[len(s)] = 0x80 - for i, messageLenBits := len(padded)-8, len(s)<<3; i < len(padded); i++ { - padded[i] = byte(messageLenBits) - messageLenBits >>= 8 + padded := bytes.NewBuffer([]byte(s)) + padded.WriteByte(0x80) + for padded.Len() % 64 != 56 { + padded.WriteByte(0) } + messageLenBits := uint64(len(s)) * 8 + binary.Write(padded, binary.LittleEndian, messageLenBits) var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476 var buffer [16]uint32 - for i := 0; i < numBlocks; i++ { - index := i << 6 - for j := 0; j < 64; j, index = j+1, index+1 { - buffer[j>>2] = (uint32(padded[index]) << 24) | (buffer[j>>2] >> 8) - } + for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { // read every 64 bytes a1, b1, c1, d1 := a, b, c, d for j := 0; j < 64; j++ { var f uint32 @@ -79,11 +76,6 @@ func md5(s string) (r [16]byte) { a, b, c, d = a+a1, b+b1, c+c1, d+d1 } - for i, n := range []uint32{a, b, c, d} { - for j := 0; j < 4; j++ { - r[i*4+j] = byte(n) - n >>= 8 - } - } + binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d}) return } diff --git a/Task/MD5-Implementation/Java/md5-implementation.java b/Task/MD5-Implementation/Java/md5-implementation-1.java similarity index 100% rename from Task/MD5-Implementation/Java/md5-implementation.java rename to Task/MD5-Implementation/Java/md5-implementation-1.java diff --git a/Task/MD5-Implementation/Java/md5-implementation-2.java b/Task/MD5-Implementation/Java/md5-implementation-2.java new file mode 100644 index 0000000000..92dcb54354 --- /dev/null +++ b/Task/MD5-Implementation/Java/md5-implementation-2.java @@ -0,0 +1,114 @@ +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +class MD5 +{ + + private static final int INIT_A = 0x67452301; + private static final int INIT_B = (int)0xEFCDAB89L; + private static final int INIT_C = (int)0x98BADCFEL; + private static final int INIT_D = 0x10325476; + + private static final int[] SHIFT_AMTS = { + 7, 12, 17, 22, + 5, 9, 14, 20, + 4, 11, 16, 23, + 6, 10, 15, 21 + }; + + private static final int[] TABLE_T = new int[64]; + static + { + for (int i = 0; i < 64; i++) + TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1))); + } + + public static byte[] computeMD5(byte[] message) + { + ByteBuffer padded = ByteBuffer.allocate((((message.length + 8) / 64) + 1) * 64).order(ByteOrder.LITTLE_ENDIAN); + padded.put(message); + padded.put((byte)0x80); + long messageLenBits = (long)message.length * 8; + padded.putLong(padded.capacity() - 8, messageLenBits); + + padded.rewind(); + + int a = INIT_A; + int b = INIT_B; + int c = INIT_C; + int d = INIT_D; + while (padded.hasRemaining()) { + // obtain a slice of the buffer from the current position, + // and view it as an array of 32-bit ints + IntBuffer chunk = padded.slice().order(ByteOrder.LITTLE_ENDIAN).asIntBuffer(); + int originalA = a; + int originalB = b; + int originalC = c; + int originalD = d; + for (int j = 0; j < 64; j++) + { + int div16 = j >>> 4; + int f = 0; + int bufferIndex = j; + switch (div16) + { + case 0: + f = (b & c) | (~b & d); + break; + + case 1: + f = (b & d) | (c & ~d); + bufferIndex = (bufferIndex * 5 + 1) & 0x0F; + break; + + case 2: + f = b ^ c ^ d; + bufferIndex = (bufferIndex * 3 + 5) & 0x0F; + break; + + case 3: + f = c ^ (b | ~d); + bufferIndex = (bufferIndex * 7) & 0x0F; + break; + } + int temp = b + Integer.rotateLeft(a + f + chunk.get(bufferIndex) + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]); + a = d; + d = c; + c = b; + b = temp; + } + + a += originalA; + b += originalB; + c += originalC; + d += originalD; + padded.position(padded.position() + 64); + } + + ByteBuffer md5 = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN); + for (int n : new int[]{a, b, c, d}) + { + md5.putInt(n); + } + return md5.array(); + } + + public static String toHexString(byte[] b) + { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < b.length; i++) + { + sb.append(String.format("%02X", b[i] & 0xFF)); + } + return sb.toString(); + } + + public static void main(String[] args) + { + String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }; + for (String s : testStrings) + System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\""); + return; + } + +} diff --git a/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 b/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 index aacdce9c14..912f014163 100644 --- a/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 +++ b/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 @@ -9,25 +9,29 @@ constant FGHI = -> \X, \Y, \Z { (X +& Y) +| (¬X +& Z) }, -> \X, \Y, \Z { X +^ Y +^ Z }, -> \X, \Y, \Z { Y +^ (X +| ¬Z) }; -constant S = (7, 12, 17, 22) xx 4, - (5, 9, 14, 20) xx 4, - (4, 11, 16, 23) xx 4, - (6, 10, 15, 21) xx 4; +constant S = flat (7, 12, 17, 22) xx 4, + (5, 9, 14, 20) xx 4, + (4, 11, 16, 23) xx 4, + (6, 10, 15, 21) xx 4; constant T = (floor(abs(sin($_ + 1)) * 2**32) for ^64); -constant k = ( $_ for ^16), - ((5*$_ + 1) % 16 for ^16), - ((3*$_ + 5) % 16 for ^16), - ((7*$_ ) % 16 for ^16); +constant k = flat ( $_ for ^16), + ((5*$_ + 1) % 16 for ^16), + ((3*$_ + 5) % 16 for ^16), + ((7*$_ ) % 16 for ^16); -sub little-endian($w, $n, *@v) { (@v X+> ($w X* ^$n)) X% (2 ** $w) } +sub little-endian($w, $n, *@v) { + my \step1 = ($w X* ^$n).eager; # temporary bug workaround + my \step2 = (@v X+> step1); + step2 X% (2 ** $w); +} sub md5-pad(Blob $msg) { my \bits = 8 * $msg.elems; - my @padded = $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64); - @padded.map({ :256[$^d,$^c,$^b,$^a] }), little-endian(32, 2, bits); + my @padded = flat $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64); + flat @padded.map({ :256[$^d,$^c,$^b,$^a] }), little-endian(32, 2, bits); } sub md5-block(@H is rw, @X) diff --git a/Task/MD5/ALGOL-68/md5.alg b/Task/MD5/ALGOL-68/md5.alg new file mode 100644 index 0000000000..696f0c9ec2 --- /dev/null +++ b/Task/MD5/ALGOL-68/md5.alg @@ -0,0 +1,150 @@ +# Based on wikipedia article pseudocode # + +# s specifies the per-round shift amounts # +[]INT s = (7,12,17,22, 7,12,17,22, 7,12,17,22, 7,12,17,22, + 5, 9,14,20, 5, 9,14,20, 5, 9,14,20, 5, 9,14,20, + 4,11,16,23, 4,11,16,23, 4,11,16,23, 4,11,16,23, + 6,10,15,21, 6,10,15,21, 6,10,15,21, 6,10,15,21); + +[]BITS k = (16rd76aa478, 16re8c7b756, 16r242070db, 16rc1bdceee, + 16rf57c0faf, 16r4787c62a, 16ra8304613, 16rfd469501, + 16r698098d8, 16r8b44f7af, 16rffff5bb1, 16r895cd7be, + 16r6b901122, 16rfd987193, 16ra679438e, 16r49b40821, + 16rf61e2562, 16rc040b340, 16r265e5a51, 16re9b6c7aa, + 16rd62f105d, 16r02441453, 16rd8a1e681, 16re7d3fbc8, + 16r21e1cde6, 16rc33707d6, 16rf4d50d87, 16r455a14ed, + 16ra9e3e905, 16rfcefa3f8, 16r676f02d9, 16r8d2a4c8a, + 16rfffa3942, 16r8771f681, 16r6d9d6122, 16rfde5380c, + 16ra4beea44, 16r4bdecfa9, 16rf6bb4b60, 16rbebfbc70, + 16r289b7ec6, 16reaa127fa, 16rd4ef3085, 16r04881d05, + 16rd9d4d039, 16re6db99e5, 16r1fa27cf8, 16rc4ac5665, + 16rf4292244, 16r432aff97, 16rab9423a7, 16rfc93a039, + 16r655b59c3, 16r8f0ccc92, 16rffeff47d, 16r85845dd1, + 16r6fa87e4f, 16rfe2ce6e0, 16ra3014314, 16r4e0811a1, + 16rf7537e82, 16rbd3af235, 16r2ad7d2bb, 16reb86d391); + +OP + = (BITS a, b) BITS: + BEGIN + BITS c = BIN (ABS (a AND 16rffff) + ABS (b AND 16rffff)); + BITS d = BIN (ABS (a SHR 16) + ABS (b SHR 16) + ABS (c SHR 16)); + (c AND 16rffff) OR (d SHL 16) + END; + +#[0:63]LONG INT k; +FOR i FROM 0 TO 63 DO + k[i] := ENTIER (ABS (sin(i+1)) * LONG INT(2)**32) +OD;# + +PROC md5 = (STRING intext) STRING: + BEGIN + # Initialize variables: # + BITS a0 := 16r67452301, + a1 := 16refcdab89, + a2 := 16r98badcfe, + a3 := 16r10325476; + + STRING text := intext; + + # Pre-processing: adding a single 1 bit # + text +:= REPR 128; + + # Pre-processing: padding with zeros + append "0" bit until message length in bits ≡ 448 (mod 512) # + WHILE ELEMS text MOD 64 ≠ 56 DO + text +:= REPR 0 + OD; + + # append original length in bits mod (2 pow 64) to message # + text +:= dec2asc (ELEMS intext * 8); + + # MD5 rounds # + # Process the message in successive 512-bit chunks: # + WHILE text ≠ "" DO + # for each 512-bit (64 byte) chunk of message # + []CHAR chunk = text[1:64]; text := text[65:]; + # break chunk into sixteen 32-bit words M[j], 0 <= j <= 15 # + [0:15]BITS m; + FOR j FROM 0 TO 15 DO + m[j] := BIN (ABS chunk[j*4+1]) OR + BIN (ABS chunk[j*4+2]) SHL 8 OR + BIN (ABS chunk[j*4+3]) SHL 16 OR + BIN (ABS chunk[j*4+4]) SHL 24 + OD; + INT g; + BITS a, b, c, d, f, dtemp; + + # Initialize hash value for this chunk # + a := a0; + b := a1; + c := a2; + d := a3; + FOR i FROM 0 TO 63 DO + IF 0 <= i AND i <= 15 THEN + f := (b AND c) OR ((NOT b) AND d); + g := i + ELIF 16 <= i AND i <= 31 THEN + f := (d AND b) OR ((NOT d) AND c); + g := (5×i + 1) MOD 16 + ELIF 32 <= i AND i <= 47 THEN + f := b XOR c XOR d; + g := (3×i + 5) MOD 16 + ELIF 48 <= i AND i <= 63 THEN + f := c XOR (b OR (NOT d)); + g := (7×i) MOD 16 + FI; + dtemp := d; + d := c; + c := b; + b := b + leftrotate ((a + f + k[1+i] + m[g]), s[1+i]); + a := dtemp + OD; + # Add this chunk's hash to result so far # + a0 := a0 + a; + a1 := a1 + b; + a2 := a2 + c; + a3 := a3 + d + OD; + revhex (a0) + revhex (a1) + revhex (a2) + revhex (a3) + END; + +PROC leftrotate = (BITS x, INT c) BITS: + (x SHL c) OR (x SHR (32-c)); + +# dec2asc: dec to 8 byte asc # +PROC dec2asc = (INT nn)STRING: + BEGIN + STRING h := ""; INT n := nn; + FOR i TO 8 DO + h +:= REPR (n MOD 256); + n ÷:= 256 + OD; + h + END; + + PROC revhex = (BITS x) STRING : + BEGIN # Convert to lowercase hexadecimal STRING # + PROC hexdig = (BITS x) CHAR: (REPR (ABS(x) <= 9 | ABS(x) + ABS("0") | ABS(x) - 10 + ABS("a"))); + hexdig (x SHR 4 AND 16rf) + + hexdig (x AND 16rf) + + hexdig (x SHR 12 AND 16rf) + + hexdig (x SHR 8 AND 16rf) + + hexdig (x SHR 20 AND 16rf) + + hexdig (x SHR 16 AND 16rf) + + hexdig (x SHR 28 AND 16rf) + + hexdig (x SHR 24 AND 16rf) + END; + +STRING testmsg = "The quick brown fox jumps over the lazy dog"; +STRING checksum = "9e107d9d372bb6826bd81d3542a419d6"; + +print ((testmsg, new line)); +print ((checksum, new line)); + +STRING test = md5 (testmsg); + +IF test = checksum THEN + print (("passed", new line)); + print ((test, new line)) +ELSE + print (("failed")) +FI diff --git a/Task/MD5/Common-Lisp/md5-1.lisp b/Task/MD5/Common-Lisp/md5-1.lisp index f908aca0a0..d8ed8e77a3 100644 --- a/Task/MD5/Common-Lisp/md5-1.lisp +++ b/Task/MD5/Common-Lisp/md5-1.lisp @@ -1,4 +1,14 @@ (ql:quickload 'ironclad) -(defun md5 (sequence) +(defun md5 (str) (ironclad:byte-array-to-hex-string - (ironclad:digest-sequence :md5 sequence))) + (ironclad:digest-sequence :md5 + (ironclad:ascii-string-to-byte-array str)))) +(defvar *tests* '("" + "a" + "abc" + "message digest" + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + "12345678901234567890123456789012345678901234567890123456789012345678901234567890")) +(dolist (msg *tests*) + (format T "~s: ~a~%" msg (md5 msg))) diff --git a/Task/MD5/Common-Lisp/md5-2.lisp b/Task/MD5/Common-Lisp/md5-2.lisp index ec4d1f175b..0ea993e72e 100644 --- a/Task/MD5/Common-Lisp/md5-2.lisp +++ b/Task/MD5/Common-Lisp/md5-2.lisp @@ -1,2 +1,10 @@ -CL-USER> (md5 "The quick brown fox jumped over the lazy dog's back") -"d65474514ed8865634bf8623391fe6d8" ; MD5 hash of the unicode version of the string. +(cffi:load-foreign-library "libcrypto.so") + +(cffi:defcfun ("MD5" MD5) :void (string :string) (len :int) (ptr :pointer)) + +(let ((string-to-convert "The quick brown fox jumped over the lazy dog's back") + (ptr (cffi:foreign-alloc :unsigned-char :count 16))) + (md5 string-to-convert (length string-to-convert) ptr) + (loop for i from 0 below 16 do + (format t "~a" (write-to-string (cffi:mem-ref ptr :unsigned-char i) :base 16))) + (cffi:foreign-free ptr)) diff --git a/Task/MD5/Common-Lisp/md5.lisp b/Task/MD5/Common-Lisp/md5.lisp deleted file mode 100644 index d8ed8e77a3..0000000000 --- a/Task/MD5/Common-Lisp/md5.lisp +++ /dev/null @@ -1,14 +0,0 @@ -(ql:quickload 'ironclad) -(defun md5 (str) - (ironclad:byte-array-to-hex-string - (ironclad:digest-sequence :md5 - (ironclad:ascii-string-to-byte-array str)))) -(defvar *tests* '("" - "a" - "abc" - "message digest" - "abcdefghijklmnopqrstuvwxyz" - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" - "12345678901234567890123456789012345678901234567890123456789012345678901234567890")) -(dolist (msg *tests*) - (format T "~s: ~a~%" msg (md5 msg))) diff --git a/Task/MD5/Haskell/md5.hs b/Task/MD5/Haskell/md5-1.hs similarity index 100% rename from Task/MD5/Haskell/md5.hs rename to Task/MD5/Haskell/md5-1.hs diff --git a/Task/MD5/Haskell/md5-2.hs b/Task/MD5/Haskell/md5-2.hs new file mode 100644 index 0000000000..984afc2949 --- /dev/null +++ b/Task/MD5/Haskell/md5-2.hs @@ -0,0 +1,9 @@ +#!/usr/bin/env runhaskell + +import Data.ByteString.Char8 (pack) +import System.Environment (getArgs) +import Crypto.Hash + +main :: IO () +main = print . md5 . pack . unwords =<< getArgs + where md5 x = hash x :: Digest MD5 diff --git a/Task/MD5/Julia/md5.julia b/Task/MD5/Julia/md5.julia new file mode 100644 index 0000000000..4d6c3c39aa --- /dev/null +++ b/Task/MD5/Julia/md5.julia @@ -0,0 +1,37 @@ +using Nettle + +function md5sum(s::String) + bytes2hex(md5_hash(s)) +end + +function Base.trunc(s::String, n::Integer) + 0 < n || throw(DomainError()) + len = length(s) + len > n || return s + 3 < n || return s[1:n] + return s[1:n-3]*"..." +end + +tests = ["" => "d41d8cd98f00b204e9800998ecf8427e", + "a" => "0cc175b9c0f1b6a831c399e269772661", + "abc" => "900150983cd24fb0d6963f7d28e17f72", + "message digest" => "f96b697d7cb7938d525a2f31aaf161d0", + "abcdefghijklmnopqrstuvwxyz" => "c3fcd3d76192e4007dfb496cca67e13b", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" => + "d174ab98d277d9f5a5611c2c9f419d9f", + "12345678901234567890123456789012345678901234567890123456789012345678901234567890" => + "57edf4a22be3c955ac49da2e2107b67a", + "foobad" => "3858f62230ac3c915f300c664312c63f"] + + +println("Testing Julia's MD5 hash against RFC 1321.") +for k in sort(collect(keys(tests)), by=(x)->length(x)) + mysum = md5sum(k) + print(@sprintf(" %15s => ", trunc(k, 15)), mysum) + if mysum == tests[k] + println(" MD5 OK") + else + println(" MD5 Bad") + println(" The sum should be ", tests[k]) + end +end diff --git a/Task/MD5/REXX/md5.rexx b/Task/MD5/REXX/md5.rexx index 9a0e926ea0..15ea1d9611 100644 --- a/Task/MD5/REXX/md5.rexx +++ b/Task/MD5/REXX/md5.rexx @@ -1,119 +1,117 @@ -/*REXX program to test the MD5 procedure as per the test suite in the */ -/*─── IETF RFC (1321) ─── The MD5 Message-Digest Algorithm. April 1992.*/ -msg.1 = /*────────────MD5 test suite [from above doc].*/ +/*REXX program tests the MD5 procedure as per the test suite in the */ +/*────── IETF RFC (1321) ────── The MD5 Message─Digest Algorithm. April 1992.*/ +msg.1 = /*─────MD5 test suite [from above doc].*/ msg.2 = 'a' msg.3 = 'abc' msg.4 = 'message digest' msg.5 = 'abcdefghijklmnopqrstuvwxyz' msg.6 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' msg.7 = 12345678901234567890123456789012345678901234567890123456789012345678901234567890 -msg.0 = 7 /* [↑] value doesn't need quotes*/ - do m=1 for msg.0 /*process each of the 7 messages.*/ - say ' in =' msg.m /*display the in message. */ - say 'out =' MD5(msg.m) /* " " out " */ - say /* " a blank like for a sep.*/ +msg.0 = 7 /* [↑] last value doesn't need quotes.*/ + do m=1 for msg.0 /*process each of the seven messages. */ + say ' in =' msg.m /*display the in message. */ + say 'out =' MD5(msg.m) /* " " out " */ + say /* " a blank like for a separator.*/ end /*m*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────MD5 subroutine──────────────────────*/ -MD5: procedure; parse arg !; numeric digits 20 /*insure enough digits.*/ -parse value '67452301'x 'efcdab89'x '98badcfe'x '10325476'x with a b c d -#=length(!) /*length of the message*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────MD5 subroutine────────────────────────────*/ +MD5: procedure; parse arg !; numeric digits 20 /*insure enough decimal digs.*/ +parse value '67452301'x 'efcdab89'x '98badcfe'x '10325476'x with a b c d +#=length(!) /*length of the input message*/ L=#*8 // 512; if L<448 then plus=448-L if L>448 then plus=960-L if L=448 then plus=512 - /* [↓] a little of this, ··· */ -$=!'80'x||copies("0"x,plus%8-1)reverse(right(d2c(8*#),4,'0'x))||"00000000"x - /* [↑] ··· and a little of that.*/ - do j=0 to length($)%64-1 /*process message (lots of steps)*/ - a_=a; b_=b; c_=c; d_=d /*save original values for later.*/ - chunk=j*64 /*calculate size of the chunks. */ - do k=1 for 16 /*process the message in chunks. */ - !.k=reverse(substr($,chunk+1+4*(k-1),4)) /*magic stuff.*/ + /* [↓] a little of this, ··· */ +$=!'80'x || copies("0"x,plus%8-1)reverse(right(d2c(8*#),4,'0'x)) || "00000000"x + /* [↑] ··· and a little of that.*/ + do j=0 to length($)%64-1 /*process the message (lots of steps).*/ + a_=a; b_=b; c_=c; d_=d /*save the original values for later.*/ + chunk=j*64 /*calculate the size of the chunks. */ + do k=1 for 16 /*process the message in chunks. */ + !.k=reverse(substr($,chunk+1+4*(k-1),4)) /*magic stuff.*/ end /*k*/ - a = .part1( a, b, c, d, 0, 7, 3614090360) /*────1───*/ - d = .part1( d, a, b, c, 1, 12, 3905402710) /*────2───*/ - c = .part1( c, d, a, b, 2, 17, 606105819) /*────3───*/ - b = .part1( b, c, d, a, 3, 22, 3250441966) /*────4───*/ - a = .part1( a, b, c, d, 4, 7, 4118548399) /*────5───*/ - d = .part1( d, a, b, c, 5, 12, 1200080426) /*────6───*/ - c = .part1( c, d, a, b, 6, 17, 2821735955) /*────7───*/ - b = .part1( b, c, d, a, 7, 22, 4249261313) /*────8───*/ - a = .part1( a, b, c, d, 8, 7, 1770035416) /*────9───*/ - d = .part1( d, a, b, c, 9, 12, 2336552879) /*───10───*/ - c = .part1( c, d, a, b, 10, 17, 4294925233) /*───11───*/ - b = .part1( b, c, d, a, 11, 22, 2304563134) /*───12───*/ - a = .part1( a, b, c, d, 12, 7, 1804603682) /*───13───*/ - d = .part1( d, a, b, c, 13, 12, 4254626195) /*───14───*/ - c = .part1( c, d, a, b, 14, 17, 2792965006) /*───15───*/ - b = .part1( b, c, d, a, 15, 22, 1236535329) /*───16───*/ - a = .part2( a, b, c, d, 1, 5, 4129170786) /*───17───*/ - d = .part2( d, a, b, c, 6, 9, 3225465664) /*───18───*/ - c = .part2( c, d, a, b, 11, 14, 643717713) /*───19───*/ - b = .part2( b, c, d, a, 0, 20, 3921069994) /*───20───*/ - a = .part2( a, b, c, d, 5, 5, 3593408605) /*───21───*/ - d = .part2( d, a, b, c, 10, 9, 38016083) /*───22───*/ - c = .part2( c, d, a, b, 15, 14, 3634488961) /*───23───*/ - b = .part2( b, c, d, a, 4, 20, 3889429448) /*───24───*/ - a = .part2( a, b, c, d, 9, 5, 568446438) /*───25───*/ - d = .part2( d, a, b, c, 14, 9, 3275163606) /*───26───*/ - c = .part2( c, d, a, b, 3, 14, 4107603335) /*───27───*/ - b = .part2( b, c, d, a, 8, 20, 1163531501) /*───28───*/ - a = .part2( a, b, c, d, 13, 5, 2850285829) /*───29───*/ - d = .part2( d, a, b, c, 2, 9, 4243563512) /*───30───*/ - c = .part2( c, d, a, b, 7, 14, 1735328473) /*───31───*/ - b = .part2( b, c, d, a, 12, 20, 2368359562) /*───32───*/ - a = .part3( a, b, c, d, 5, 4, 4294588738) /*───33───*/ - d = .part3( d, a, b, c, 8, 11, 2272392833) /*───34───*/ - c = .part3( c, d, a, b, 11, 16, 1839030562) /*───35───*/ - b = .part3( b, c, d, a, 14, 23, 4259657740) /*───36───*/ - a = .part3( a, b, c, d, 1, 4, 2763975236) /*───37───*/ - d = .part3( d, a, b, c, 4, 11, 1272893353) /*───38───*/ - c = .part3( c, d, a, b, 7, 16, 4139469664) /*───39───*/ - b = .part3( b, c, d, a, 10, 23, 3200236656) /*───40───*/ - a = .part3( a, b, c, d, 13, 4, 681279174) /*───41───*/ - d = .part3( d, a, b, c, 0, 11, 3936430074) /*───42───*/ - c = .part3( c, d, a, b, 3, 16, 3572445317) /*───43───*/ - b = .part3( b, c, d, a, 6, 23, 76029189) /*───44───*/ - a = .part3( a, b, c, d, 9, 4, 3654602809) /*───45───*/ - d = .part3( d, a, b, c, 12, 11, 3873151461) /*───46───*/ - c = .part3( c, d, a, b, 15, 16, 530742520) /*───47───*/ - b = .part3( b, c, d, a, 2, 23, 3299628645) /*───48───*/ - a = .part4( a, b, c, d, 0, 6, 4096336452) /*───49───*/ - d = .part4( d, a, b, c, 7, 10, 1126891415) /*───50───*/ - c = .part4( c, d, a, b, 14, 15, 2878612391) /*───51───*/ - b = .part4( b, c, d, a, 5, 21, 4237533241) /*───52───*/ - a = .part4( a, b, c, d, 12, 6, 1700485571) /*───53───*/ - d = .part4( d, a, b, c, 3, 10, 2399980690) /*───54───*/ - c = .part4( c, d, a, b, 10, 15, 4293915773) /*───55───*/ - b = .part4( b, c, d, a, 1, 21, 2240044497) /*───56───*/ - a = .part4( a, b, c, d, 8, 6, 1873313359) /*───57───*/ - d = .part4( d, a, b, c, 15, 10, 4264355552) /*───58───*/ - c = .part4( c, d, a, b, 6, 15, 2734768916) /*───59───*/ - b = .part4( b, c, d, a, 13, 21, 1309151649) /*───60───*/ - a = .part4( a, b, c, d, 4, 6, 4149444226) /*───61───*/ - d = .part4( d, a, b, c, 11, 10, 3174756917) /*───62───*/ - c = .part4( c, d, a, b, 2, 15, 718787259) /*───63───*/ - b = .part4( b, c, d, a, 9, 21, 3951481745) /*───64───*/ - a=.a(a_,a); b=.a(b_,b); c=.a(c_,c); d=.a(d_,d) + a = .part1( a, b, c, d, 0, 7, 3614090360) /*■■■■1■■■*/ + d = .part1( d, a, b, c, 1, 12, 3905402710) /*■■■■2■■■*/ + c = .part1( c, d, a, b, 2, 17, 606105819) /*■■■■3■■■*/ + b = .part1( b, c, d, a, 3, 22, 3250441966) /*■■■■4■■■*/ + a = .part1( a, b, c, d, 4, 7, 4118548399) /*■■■■5■■■*/ + d = .part1( d, a, b, c, 5, 12, 1200080426) /*■■■■6■■■*/ + c = .part1( c, d, a, b, 6, 17, 2821735955) /*■■■■7■■■*/ + b = .part1( b, c, d, a, 7, 22, 4249261313) /*■■■■8■■■*/ + a = .part1( a, b, c, d, 8, 7, 1770035416) /*■■■■9■■■*/ + d = .part1( d, a, b, c, 9, 12, 2336552879) /*■■■10■■■*/ + c = .part1( c, d, a, b, 10, 17, 4294925233) /*■■■11■■■*/ + b = .part1( b, c, d, a, 11, 22, 2304563134) /*■■■12■■■*/ + a = .part1( a, b, c, d, 12, 7, 1804603682) /*■■■13■■■*/ + d = .part1( d, a, b, c, 13, 12, 4254626195) /*■■■14■■■*/ + c = .part1( c, d, a, b, 14, 17, 2792965006) /*■■■15■■■*/ + b = .part1( b, c, d, a, 15, 22, 1236535329) /*■■■16■■■*/ + a = .part2( a, b, c, d, 1, 5, 4129170786) /*■■■17■■■*/ + d = .part2( d, a, b, c, 6, 9, 3225465664) /*■■■18■■■*/ + c = .part2( c, d, a, b, 11, 14, 643717713) /*■■■19■■■*/ + b = .part2( b, c, d, a, 0, 20, 3921069994) /*■■■20■■■*/ + a = .part2( a, b, c, d, 5, 5, 3593408605) /*■■■21■■■*/ + d = .part2( d, a, b, c, 10, 9, 38016083) /*■■■22■■■*/ + c = .part2( c, d, a, b, 15, 14, 3634488961) /*■■■23■■■*/ + b = .part2( b, c, d, a, 4, 20, 3889429448) /*■■■24■■■*/ + a = .part2( a, b, c, d, 9, 5, 568446438) /*■■■25■■■*/ + d = .part2( d, a, b, c, 14, 9, 3275163606) /*■■■26■■■*/ + c = .part2( c, d, a, b, 3, 14, 4107603335) /*■■■27■■■*/ + b = .part2( b, c, d, a, 8, 20, 1163531501) /*■■■28■■■*/ + a = .part2( a, b, c, d, 13, 5, 2850285829) /*■■■29■■■*/ + d = .part2( d, a, b, c, 2, 9, 4243563512) /*■■■30■■■*/ + c = .part2( c, d, a, b, 7, 14, 1735328473) /*■■■31■■■*/ + b = .part2( b, c, d, a, 12, 20, 2368359562) /*■■■32■■■*/ + a = .part3( a, b, c, d, 5, 4, 4294588738) /*■■■33■■■*/ + d = .part3( d, a, b, c, 8, 11, 2272392833) /*■■■34■■■*/ + c = .part3( c, d, a, b, 11, 16, 1839030562) /*■■■35■■■*/ + b = .part3( b, c, d, a, 14, 23, 4259657740) /*■■■36■■■*/ + a = .part3( a, b, c, d, 1, 4, 2763975236) /*■■■37■■■*/ + d = .part3( d, a, b, c, 4, 11, 1272893353) /*■■■38■■■*/ + c = .part3( c, d, a, b, 7, 16, 4139469664) /*■■■39■■■*/ + b = .part3( b, c, d, a, 10, 23, 3200236656) /*■■■40■■■*/ + a = .part3( a, b, c, d, 13, 4, 681279174) /*■■■41■■■*/ + d = .part3( d, a, b, c, 0, 11, 3936430074) /*■■■42■■■*/ + c = .part3( c, d, a, b, 3, 16, 3572445317) /*■■■43■■■*/ + b = .part3( b, c, d, a, 6, 23, 76029189) /*■■■44■■■*/ + a = .part3( a, b, c, d, 9, 4, 3654602809) /*■■■45■■■*/ + d = .part3( d, a, b, c, 12, 11, 3873151461) /*■■■46■■■*/ + c = .part3( c, d, a, b, 15, 16, 530742520) /*■■■47■■■*/ + b = .part3( b, c, d, a, 2, 23, 3299628645) /*■■■48■■■*/ + a = .part4( a, b, c, d, 0, 6, 4096336452) /*■■■49■■■*/ + d = .part4( d, a, b, c, 7, 10, 1126891415) /*■■■50■■■*/ + c = .part4( c, d, a, b, 14, 15, 2878612391) /*■■■51■■■*/ + b = .part4( b, c, d, a, 5, 21, 4237533241) /*■■■52■■■*/ + a = .part4( a, b, c, d, 12, 6, 1700485571) /*■■■53■■■*/ + d = .part4( d, a, b, c, 3, 10, 2399980690) /*■■■54■■■*/ + c = .part4( c, d, a, b, 10, 15, 4293915773) /*■■■55■■■*/ + b = .part4( b, c, d, a, 1, 21, 2240044497) /*■■■56■■■*/ + a = .part4( a, b, c, d, 8, 6, 1873313359) /*■■■57■■■*/ + d = .part4( d, a, b, c, 15, 10, 4264355552) /*■■■58■■■*/ + c = .part4( c, d, a, b, 6, 15, 2734768916) /*■■■59■■■*/ + b = .part4( b, c, d, a, 13, 21, 1309151649) /*■■■60■■■*/ + a = .part4( a, b, c, d, 4, 6, 4149444226) /*■■■61■■■*/ + d = .part4( d, a, b, c, 11, 10, 3174756917) /*■■■62■■■*/ + c = .part4( c, d, a, b, 2, 15, 718787259) /*■■■63■■■*/ + b = .part4( b, c, d, a, 9, 21, 3951481745) /*■■■64■■■*/ + a = .a(a_,a); b=.a(b_,b); c=.a(c_,c); d=.a(d_,d) end /*j*/ return c2x(reverse(a))c2x(reverse(b))c2x(reverse(c))c2x(reverse(d)) -/*─────────────────────────────────────subroutines────────────────────────────────*/ -.a: return right(d2c(c2d(arg(1)) + c2d(arg(2))), 4, '0'x) -.h: procedure; parse arg x,y,z; return bitxor(bitxor(x, y), z) -.i: return bitxor(arg(2), bitor(arg(1), bitxor(arg(3), 'ffffffff'x))) -.f: procedure; parse arg x,y,z - return bitor(bitand(x,y), bitand(bitxor(x, 'ffffffff'x), z)) -.g: procedure; parse arg x,y,z - return bitor(bitand(x,z), bitand(y, bitxor(z, 'ffffffff'x))) -.Lr: procedure; parse arg _,#; if #==0 then return _ /*left rotate.*/ - ?=x2b(c2x(_)); return x2c(b2x(right(? || left(?, #), length(?)))) +/*─────────────────────────────────────subroutines─────────────────────────────────────*/ +.a: return right(d2c(c2d(arg(1)) + c2d(arg(2))), 4, '0'x) +.h: return bitxor(bitxor(arg(1), arg(2)), arg(3)) +.i: return bitxor(arg(2), bitor(arg(1), bitxor(arg(3), 'ffffffff'x))) +.f: return bitor(bitand(arg(1),arg(2)), bitand(bitxor(arg(1), 'ffffffff'x), arg(3))) +.g: return bitor(bitand(arg(1),arg(3)), bitand(arg(2), bitxor(arg(3), 'ffffffff'x))) +.Lr: procedure; parse arg _,#; if #==0 then return _ /*left rotate.*/ + ?=x2b(c2x(_)); return x2c(b2x(right(? || left(?, #), length(?)))) .part1: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 return .a(.Lr(right(d2c(_+c2d(w)+c2d(.f(x,y,z))+c2d(!.n)),4,'0'x),m),x) .part2: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 return .a(.Lr(right(d2c(_+c2d(w)+c2d(.g(x,y,z))+c2d(!.n)),4,'0'x),m),x) .part3: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 return .a(.Lr(right(d2c(_+c2d(w)+c2d(.h(x,y,z))+c2d(!.n)),4,'0'x),m),x) -.part4: procedure expose !.; parse arg w,x,y,z,n,m; n=n+1 - return .a(.Lr(right(d2c(c2d(w)+c2d(.i(x,y,z))+c2d(!.n)+arg(7)),4,'0'x),m),x) +.part4: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 + return .a(.Lr(right(d2c(c2d(w)+c2d(.i(x,y,z))+c2d(!.n)+_),4,'0'x),m),x) diff --git a/Task/Machine-code/Common-Lisp/machine-code.lisp b/Task/Machine-code/Common-Lisp/machine-code.lisp index e02929112c..f4ee406189 100644 --- a/Task/Machine-code/Common-Lisp/machine-code.lisp +++ b/Task/Machine-code/Common-Lisp/machine-code.lisp @@ -23,9 +23,10 @@ (defparameter pointer (sb-alien:make-alien sb-alien:unsigned-char (length mmap))) -(defparameter callp (loop FOR i FROM 0 BELOW (length mmap) +(defparameter callp (loop for byte in mmap + for i from 0 do - (setf (sb-alien:deref pointer i) (elt mmap i)) + (setf (sb-alien:deref pointer i) byte) finally (return (sb-alien:cast pointer (function integer integer integer))))) diff --git a/Task/Machine-code/Racket/machine-code.rkt b/Task/Machine-code/Racket/machine-code.rkt new file mode 100644 index 0000000000..17f5d2d671 --- /dev/null +++ b/Task/Machine-code/Racket/machine-code.rkt @@ -0,0 +1,23 @@ +#lang racket/base + +(require ffi/unsafe) + +; set up access to racket internals +(define scheme-malloc-code + (get-ffi-obj 'scheme_malloc_code #f (_fun (len : _intptr) -> _pointer))) +(define scheme-free-code + (get-ffi-obj 'scheme_free_code #f (_fun _pointer -> _void))) + +(define opcodes '(139 68 36 4 3 68 36 8 195)) + +(define code (scheme-malloc-code 64)) + +(for ([byte opcodes] + [i (in-naturals)]) + (ptr-set! code _ubyte i byte)) + +(define function (cast code _pointer (_fun _ubyte _ubyte -> _ubyte))) + +(function 7 12) + +(scheme-free-code code) diff --git a/Task/Mad-Libs/AWK/mad-libs.awk b/Task/Mad-Libs/AWK/mad-libs.awk new file mode 100644 index 0000000000..ea8fb07835 --- /dev/null +++ b/Task/Mad-Libs/AWK/mad-libs.awk @@ -0,0 +1,34 @@ +# syntax: GAWK -f MAD_LIBS.AWK +BEGIN { + print("enter story:") +} +{ story_arr[++nr] = $0 + if ($0 ~ /^ *$/) { + exit + } + while ($0 ~ /[<>]/) { + L = index($0,"<") + R = index($0,">") + changes_arr[substr($0,L,R-L+1)] = "" + sub(//,"",$0) + } +} +END { + PROCINFO["sorted_in"] = "@ind_str_asc" + print("enter values for:") + for (i in changes_arr) { # prompt for replacement values + printf("%s ",i) + getline rec + sub(/ +$/,"",rec) + changes_arr[i] = rec + } + printf("\nrevised story:\n") + for (i=1; i<=nr; i++) { # print the story + for (j in changes_arr) { + gsub(j,changes_arr[j],story_arr[i]) + } + printf("%s\n",story_arr[i]) + } + exit(0) +} diff --git a/Task/Mad-Libs/Batch-File/mad-libs-1.bat b/Task/Mad-Libs/Batch-File/mad-libs-1.bat new file mode 100644 index 0000000000..0634580631 --- /dev/null +++ b/Task/Mad-Libs/Batch-File/mad-libs-1.bat @@ -0,0 +1,70 @@ +::Save this as MADLIBS.BAT + +@echo off +setlocal enabledelayedexpansion + %== Check if there is no arguments ==% +if "%~1"=="" ( + echo. + echo.[Mad Libs - Batch File Implementation] + echo. + echo.Usage: MADLIBS [file] + echo. + exit /b 1 +) +if not exist "%~f1" (echo.File not found.&exit /b 1) + +echo. + %== Read the text file ==% +echo.[Mad Libs - Batch File Implementation] +echo. +for /f "tokens=* eol=_" %%A in (%~sf1) do ( + set /a cnt+=1 + set "line!cnt!=%%A" +) + %== User input the missing parts ==% +for /l %%. in (1,1,!cnt!) do ( + call :proc_line "%%." +) + %== Display the edited story... ==% +echo. +echo.The Story: +echo. +for /l %%? in (1,1,!cnt!) do ( + echo. !line%%?! +) +echo. +exit /b 0 + + %== The main processor of the story ==% +:proc_line +set "str=!line%~1!" +:loop +if "!str!"=="" goto :EOF +for /f "tokens=1,* delims=<" %%M in ("!str!") do ( + for /f "tokens=1,* delims=>" %%X in ("%%M") do ( + if not "%%M"=="%%X" ( + set "temp_var=%%X" + if not "!temp_var: =!"=="" ( + set "input=" + set /p "input=Enter a value for [%%X]?" + call :subst_input + ) + ) + ) +) +set "str=!line%~1!" +for /f "tokens=1,* delims=<" %%M in ("!str!") do (set str=%%N) +goto loop + + %== This Substitutes the input to the blank ==% +:subst_input +set "chk_brack=!input:>=!" +set "chk_brack=!chk_brack:<=!" +set "chk_brack=!chk_brack:%%=!" +for /l %%. in (1,1,!cnt!) do ( + if "!line%%.: =!"==" =" set "line%%.= " + if "!chk_brack!"=="!input!" ( + call set "line%%.=%%line%%.:<%%X>=!input!%%" + ) else (set "line%%.=!line%%.:<%%X>=!") +) +goto :EOF diff --git a/Task/Mad-Libs/Batch-File/mad-libs-2.bat b/Task/Mad-Libs/Batch-File/mad-libs-2.bat new file mode 100644 index 0000000000..4daf2f84d6 --- /dev/null +++ b/Task/Mad-Libs/Batch-File/mad-libs-2.bat @@ -0,0 +1,145 @@ +#include +#include +#include + +#define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1) + +/* We create a dynamic string with a few functions which make modifying + * the string and growing a bit easier */ +typedef struct { + char *data; + size_t alloc; + size_t length; +} dstr; + +inline int dstr_space(dstr *s, size_t grow_amount) +{ + return s->length + grow_amount < s->alloc; +} + +int dstr_grow(dstr *s) +{ + s->alloc *= 2; + char *attempt = realloc(s->data, s->alloc); + + if (!attempt) return 0; + else s->data = attempt; + + return 1; +} + +dstr* dstr_init(const size_t to_allocate) +{ + dstr *s = malloc(sizeof(dstr)); + if (!s) goto failure; + + s->length = 0; + s->alloc = to_allocate; + s->data = malloc(s->alloc); + + if (!s->data) goto failure; + + return s; + +failure: + if (s->data) free(s->data); + if (s) free(s); + return NULL; +} + +void dstr_delete(dstr *s) +{ + if (s->data) free(s->data); + if (s) free(s); +} + +dstr* readinput(FILE *fd) +{ + static const size_t buffer_size = 4096; + char buffer[buffer_size]; + + dstr *s = dstr_init(buffer_size); + if (!s) goto failure; + + while (fgets(buffer, buffer_size, fd)) { + while (!dstr_space(s, buffer_size)) + if (!dstr_grow(s)) goto failure; + + strncpy(s->data + s->length, buffer, buffer_size); + s->length += strlen(buffer); + } + + return s; + +failure: + dstr_delete(s); + return NULL; +} + +void dstr_replace_all(dstr *story, const char *replace, const char *insert) +{ + const size_t replace_l = strlen(replace); + const size_t insert_l = strlen(insert); + char *start = story->data; + + while ((start = strstr(start, replace))) { + if (!dstr_space(story, insert_l - replace_l)) + if (!dstr_grow(story)) err("Failed to allocate memory"); + + if (insert_l != replace_l) { + memmove(start + insert_l, start + replace_l, story->length - + (start + replace_l - story->data)); + + /* Remember to null terminate the data so we can utilize it + * as we normally would */ + story->length += insert_l - replace_l; + story->data[story->length] = 0; + } + + memmove(start, insert, insert_l); + } +} + +void madlibs(dstr *story) +{ + static const size_t buffer_size = 128; + char insert[buffer_size]; + char replace[buffer_size]; + + char *start, + *end = story->data; + + while (start = strchr(end, '<')) { + if (!(end = strchr(start, '>'))) err("Malformed brackets in input"); + + /* One extra for current char and another for nul byte */ + strncpy(replace, start, end - start + 1); + replace[end - start + 1] = '\0'; + + printf("Enter value for field %s: ", replace); + + fgets(insert, buffer_size, stdin); + const size_t il = strlen(insert) - 1; + if (insert[il] == '\n') + insert[il] = '\0'; + + dstr_replace_all(story, replace, insert); + } + printf("\n"); +} + +int main(int argc, char *argv[]) +{ + if (argc < 2) return 0; + + FILE *fd = fopen(argv[1], "r"); + if (!fd) err("Could not open file: '%s\n", argv[1]); + + dstr *story = readinput(fd); fclose(fd); + if (!story) err("Failed to allocate memory"); + + madlibs(story); + printf("%s\n", story->data); + dstr_delete(story); + return 0; +} diff --git a/Task/Mad-Libs/Batch-File/mad-libs-3.bat b/Task/Mad-Libs/Batch-File/mad-libs-3.bat new file mode 100644 index 0000000000..f70982a677 --- /dev/null +++ b/Task/Mad-Libs/Batch-File/mad-libs-3.bat @@ -0,0 +1,48 @@ +#include +#include +using namespace std; + +int main() +{ + string story, input; + + //Loop + while(true) + { + //Get a line from the user + getline(cin, input); + + //If it's blank, break this loop + if(input == "\r") + break; + + //Add the line to the story + story += input; + } + + //While there is a '<' in the story + int begin; + while((begin = story.find("<")) != string::npos) + { + //Get the category from between '<' and '>' + int end = story.find(">"); + string cat = story.substr(begin + 1, end - begin - 1); + + //Ask the user for a replacement + cout << "Give me a " << cat << ": "; + cin >> input; + + //While there's a matching category + //in the story + while((begin = story.find("<" + cat + ">")) != string::npos) + { + //Replace it with the user's replacement + story.replace(begin, cat.length()+2, input); + } + } + + //Output the final story + cout << endl << story; + + return 0; +} diff --git a/Task/Mad-Libs/Fortran/mad-libs.f b/Task/Mad-Libs/Fortran/mad-libs.f new file mode 100644 index 0000000000..ac08a42313 --- /dev/null +++ b/Task/Mad-Libs/Fortran/mad-libs.f @@ -0,0 +1,239 @@ + MODULE MADLIB !Messing with COMMON is less convenient. + INTEGER MSG,KBD,INF !I/O unit numbers. + DATA MSG,KBD,INF/6,5,10/ !Output, input, some disc file. + INTEGER LSTASH,NSTASH,MSTASH !Prepare a common text stash. + PARAMETER (LSTASH = 246810, MSTASH = 6666) !LSTASH characters for MSTASH texts. + CHARACTER*(LSTASH) STASH !The pool. + INTEGER ISTASH(MSTASH + 1) !Fingers start positions, and thus end positions by extension. + DATA NSTASH,ISTASH(1)/0,1/ !Empty pool: no entries, first available character is at 1. + INTEGER MANYLINES,MANYTESTS !I also want some lists of texts. + PARAMETER (MANYLINES = 1234) !This is to hold the story. + INTEGER NSTORY,STORY(MANYLINES) !Fingering texts in the stash. + PARAMETER (MANYTESTS = 1234) !Likewise, some target/replacement texts. + INTEGER NTESTS,TARGET(MANYTESTS),REPLACEMENT(MANYTESTS) !Thus. + DATA NSTORY,NTESTS/0,0/ !No story lines, and no tests. + INTEGER STACKLIMIT !A recursion limit. + PARAMETER (STACKLIMIT = 28) !This should suffice. + + CONTAINS + SUBROUTINE CROAK(GASP) !A dying remark. + CHARACTER*(*) GASP !The last words. + WRITE (MSG,*) "Oh dear." !Shock. + WRITE (MSG,*) GASP !Aargh! + STOP "How sad." !Farewell, cruel world. + END SUBROUTINE CROAK !Farewell... + + SUBROUTINE SHOWSTASH(BLAH,I) !One might be wondering. + CHARACTER*(*) BLAH !An annotation. + INTEGER I !The desired stashed text. + WRITE (MSG,1) BLAH,I,STASH(ISTASH(I):ISTASH(I + 1) - 1) !Whee! + 1 FORMAT (A,': Text(',I0,')="',A,'"') !Hopefully, helpful. + END SUBROUTINE SHOWSTASH !Ah, debugging. + + INTEGER FUNCTION EATTEXT(IN) !Add a text to STASH and finger it. +Co-opts the as-yet unused space in STASH as its scratchpad. + INTEGER IN !Input from this I/O unit number. + INTEGER I,N,L !Fingers. + I = ISTASH(NSTASH + 1)!First available position in STASH. + N = LSTASH - I + 1 !Number of characters yet unused. + IF (N.LT.666) CALL CROAK("Insufficient STASH space remains!") + READ (IN,1,END = 66) L,STASH(I:I + MIN(L,N) - 1) !Calculated during the read. + 1 FORMAT (Q,A) !Obviously, Q = character count incoming, A = accept all of them. + L = I + MIN(L,N) - 1 !The last character read. + 10 IF (L.LT.I) GO TO 66 !A blank line! Deemed end-of-file. + IF (ICHAR(STASH(L:L)).LE.ICHAR(" ")) THEN !A trailing space? + L = L - 1 !Yes. Pull back. + GO TO 10 !And try again. + END IF !So much for trailing spaces. + IF (NSTASH.GE.MSTASH) CALL CROAK("Too many texts!") + NSTASH = NSTASH + 1 !Admit another text. + ISTASH(NSTASH + 1) = L + 1 !The start point of the following text. + EATTEXT = NSTASH !STASH(ISTASH(n):ISTASH(n + 1) - 1) has text n. + RETURN !All well. + 66 EATTEXT = 0 !Sez: "No text". + END FUNCTION EATTEXT !Rather odd side effects. + + INTEGER FUNCTION ADDSTASH(TEXT) !Appends an arbitrary text to the pool of stashed texts. + CHARACTER*(*) TEXT !The stuff. + INTEGER I !A finger. + IF (NSTASH.GE.MSTASH) CALL CROAK("The text pool is crowded!") !Alas. + I = ISTASH(NSTASH + 1) !First unused character. + IF (I + LEN(TEXT).GT.LSTASH) CALL CROAK("Overtexted!") !Alack. + STASH(I:I + LEN(TEXT) - 1) = TEXT !Place. + NSTASH = NSTASH + 1 !Count in another entry. + ISTASH(NSTASH + 1) = I + LEN(TEXT) !The new "first available" position. + ADDSTASH = NSTASH !Pass a finger back to the caller. + END FUNCTION ADDSTASH !Just an integer. + + INTEGER FUNCTION ANOTHER(TEXT) !Possibly add TEXT to the table of target texts. +Collects TARGET REPLACEMENT pairs (increasing NTESTS) as directed by INSPECT. + CHARACTER*(*) TEXT !The text of the target. + INTEGER I,IT !Steppers. + ANOTHER = 0 !Possibly, the text is already in the table. + DO I = 1,NTESTS !So, step through the known target texts. + IT = TARGET(I) !Finger a target text. + IF (TEXT.EQ.STASH(ISTASH(IT):ISTASH(IT + 1) - 1)) RETURN !Already have this one. + END DO !Otherwise, try the next. + IF (NTESTS.GE.MANYTESTS) CALL CROAK("Too many tests!") !Oh dear. + NTESTS = NTESTS + 1 !Count in another. + TARGET(NTESTS) = ADDSTASH(TEXT)!Stash its text and get a finger to it. + ANOTHER = NTESTS !My caller will want to know which test. + WRITE (MSG,1) TEXT !Now request the replacement text. + 1 FORMAT ("Enter your text for ",A,": ",$) !Obviously, the $ indicates "no new line". + REPLACEMENT(NTESTS) = EATTEXT(KBD) !Zero for "no text". + END FUNCTION ANOTHER !Produces entries for TARGET and REPLACEMENT. + + SUBROUTINE INSPECT(X) !Examine text number X for the special <...> sequence. +Calls for inspection of REPLACEMENT texts as well, should ANOTHER report a new entry. + INTEGER X !Fingers the text in STASH via ISTASH(X). + INTEGER MARK !Recalls where the < was found. + INTEGER IT,NEW !Fingers to entries in STASH. + INTEGER I !A stepper. + INTEGER SP,STACK(STACKLIMIT) !Prepare for some recursion. + SP = 1 !Start with the starter. + STACK(1) = X !Stack up. + DO WHILE(SP.GT.0) !While texts are yet uninspected, + IT = STACK(SP) !Finger one. + SP = SP - 1 !Working down the stack. + MARK = 0 !Uninitialised variables are bad. + DO I = ISTASH(IT),ISTASH(IT + 1) - 1!Step through the stashed text. + IF (STASH(I:I).EQ."<") THEN !Is it the starter? + MARK = I !Yes. Remember where it is. + ELSE IF (STASH(I:I).EQ.">") THEN !The ender? + IF (MARK.LE.0) CALL CROAK("A > with no preceeding apparition. + MARK = 0 !Be ready to check afresh for the next. + END IF !So much for that character. + END DO !On to the next. + END DO !So much for that stacked entry. + END SUBROUTINE INSPECT !WRITESTORY will rescan the story lines. + + SUBROUTINE READSTORY(IN)!Read and stash the lines. + INTEGER IN !Input from here. + INTEGER LINE !A finger to the story line. + 10 LINE = EATTEXT(IN) !So, grab a line. + IF (LINE.GT.0) THEN !A live line? + NSTORY = NSTORY + 1 !Yes.Count it in. + STORY(NSTORY) = LINE !Save it in the story list. + CALL INSPECT(LINE) !Look for trouble as well. + GO TO 10 !And go for the next line. + END IF !Oh for while (Line:=EatText(in)) > 0 do SaveAndInspect(Line); + END SUBROUTINE READSTORY!Simple enough, anyway. + + SUBROUTINE WRITESTORY(WIDTH) !Applying the replacements, with replacement replacement too. +Co-opts the as-yet unused space in STASH as its output scratchpad. +Can't rely on changing the index and bounds of a DO-loop on the fly. + INTEGER WIDTH + INTEGER LINE,IT,I,J !Steppers. + INTEGER L,L0,N !Fingers. + INTEGER TAIL,MARK,LAST !Scan choppers. + INTEGER SP,STACKI(STACKLIMIT),STACKL(STACKLIMIT) !Ah, recursion. + L0 = ISTASH(NSTASH + 1) !The first available place in the stash. + L = L0 - 1 !Syncopation for my output finger. + LL:DO LINE = 1,NSTORY !Step through the lines of the story. + SP = 0 !Start with the task in hand. + IT = STORY(LINE) !Finger the stashed line. + LAST = ISTASH(IT + 1) - 1 !Find its last character in STASH. + I = ISTASH(IT) !Find its first character in STASH. + TAIL = I - 1 !Syncopation. No text from this line yet. + IF (STASH(I:I).LE." ") THEN !The line starts with a space? + CALL BURP !Yes. Flush, so as to start a new paragraph. + ELSE IF (LINE.GT.1) THEN !Otherwise, the line is a continuation. + L = L + 1 !So, squeeze in a space as a separator. + STASH(L:L) = " " !Since its text follows on. + END IF !Now for the content of the line. + 666 II:DO WHILE(I.LE.LAST) !Step along its text. + IF (STASH(I:I).EQ."<") THEN !Trouble starter? + MARK = I !Yes. Remember where. + ELSE IF (STASH(I:I).EQ.">") THEN !The corresponding ender? + CALL APPEND(TAIL + 1,MARK - 1) !Waiting text up to the mark. + JJ:DO J = 1,NTESTS !Step through the target texts. + IT = TARGET(J) !Finger one. + IF (STASH(ISTASH(IT):ISTASH(IT + 1) - 1) !Its stashed text. + 1 .EQ.STASH(MARK:I)) THEN !Matches the suspect text? + IT = REPLACEMENT(J) !Yes! Finger the replacement text. + IF (IT.GT.0) THEN !Null replacements can be ignored. + IF (SP.GE.STACKLIMIT) CALL CROAK("StackOverflow!") !Always diff. messages. + SP = SP + 1 !Interrupt the current scan. + STACKI(SP) = I !Remember where we're up to, + STACKL(SP) = LAST !And the end of the text. + I = ISTASH(IT) - 1 !One will be added shortly, at JJ+1. + LAST = ISTASH(IT + 1) - 1 !Preempt the scan-in-progress. + END IF !To work along the replacement text. + EXIT JJ !Found the target, so the search is finished. + END IF !Otherwise, + END DO JJ !Try the next target text. + TAIL = I !Normal text resumes at TAIL + 1. + END IF !Enough analysis of that character from the story line. + I = I + 1 !The next to consider. + END DO II !Perhaps we've finished this text. + IF (SP.GT.0) THEN !Yes! But, were we interrupted in a previous scan? + CALL APPEND(TAIL + 1,LAST)!Yes! Roll the tail of the just-finished scan. + TAIL = STACKI(SP) !The stacked value of I was fingering a >. + LAST = STACKL(SP) !And this was the end of the text. + SP = SP - 1 !So we've recovered where the scan was. + I = TAIL + 1 !And this is the next to look at. + GO TO 666 !Proceed to do so. + END IF !But if all is unstacked, + CALL APPEND(TAIL + 1,LAST) !Don't forget the tail end. + END DO LL !On to the next story line. + CALL BURP !Any waiting text must be less than WIDTH. + CONTAINS !Some assistants, defined after usage... + SUBROUTINE APPEND(IST,LST) !Has access to L. + INTEGER IST,LST !To copy STASH(IST:LST) to the scratchpad. + INTEGER N !The number of characters to copy. + N = LST - IST + 1 !So find out. + IF (N.LE.0) RETURN !Avoid relying on zero-length action. + IF (L + N.GT.LSTASH) CALL CROAK("Out of stash!") !Oh dear. + STASH(L + 1:L + N) = STASH(IST:LST) !There they go. + L = L + N !Advance my oputput finger. + IF (L - L0 + 1.GE.WIDTH) CALL BURP !Enough to be going on with? + END SUBROUTINE APPEND !Few invocations, if with tricky parameters. + SUBROUTINE BURP !Flushes forth up to WIDTH characters. + INTEGER N,W,L1 !And slides any remnant back. + N = L - L0 + 1 !So, how many characters are waiting? + IF (N.LE.WIDTH) THEN !Too many for one line of output? + L1 = L !Nope. Roll the lot. + ELSE !Otherwise, a partial flush. + W = L0 + WIDTH - 1 !Last character that can be fitted into WIDTH. + DO L1 = W,L0,-1 !Look for a good split. + IF (STASH(L1:L1).LE." ") EXIT !Like, at a space. + END DO !Keep winding back. + IF (L1.LE.L0) L1 = W !No pleasing split found. Just roll a full width. + END IF !Ready to roll. + WRITE (MSG,"(A)") STASH(L0:L1) !Thus! + IF (N.LE.WIDTH) THEN !If the whole text was written, + L = L0 - 1 !Then there is no text in the scratchpad. + ELSE !If only L0:L1 were written of L0:L, + W = L0 + L - L1 - 1 !How far will the remaining text extend? + STASH(L0:W) = STASH(L1 + 1:L) !Shift it. + L = W !Finger the last used character position. + END IF !One trim is enough, even if the scracchpad contains multiple widths' worth.. + END SUBROUTINE BURP !Since I don't want to flush the lot. + END SUBROUTINE WRITESTORY !Just a sequence of lines. + END MODULE MADLIB !Enough of that. + + PROGRAM MADLIBBER !See, for example, https://en.wikipedia.org/wiki/Mad_Libs + USE MADLIB + WRITE (MSG,1) !It's polite to explain. + 10FORMAT ("Reads a story in template form, containing special ", + 1 "entries such as amongst the text.",/, + 2 "You will be invited to supply a replacement text for each " + 3 "such entry, as encountered,",/, + 4 "after which the story will be presented with your ", + 5 "substitutions made.",//, + 6 "Here goes... Reading file Madlib.txt",/) + OPEN(INF,STATUS="OLD",ACTION="READ",FORM="FORMATTED", + 1 FILE = "Madlib.txt") + CALL READSTORY(INF) + CLOSE(INF) + WRITE (MSG,*) + WRITE (MSG,*) " Righto!" + WRITE (MSG,*) + CALL WRITESTORY(66) + END diff --git a/Task/Mad-Libs/J/mad-libs-1.j b/Task/Mad-Libs/J/mad-libs-1.j new file mode 100644 index 0000000000..d6c23ac9f2 --- /dev/null +++ b/Task/Mad-Libs/J/mad-libs-1.j @@ -0,0 +1,14 @@ +require 'general/misc/prompt regex' + +madlib=:3 :0 + smoutput 'Please enter the story template' + smoutput 'See http://rosettacode.org/wiki/Mad_Libs for details' + t=.'' + while.#l=.prompt '' do. t=.t,l,LF end. + repl=. ~.'<[^<>]*>' rxall t + for_bef. repl do. + aft=. prompt (}.}:;bef),': ' + t=.t rplc bef, went for a walk in the park. +found a . decided to take it home. + +name: Jill +he or she: she +noun: rock +Jill went for a walk in the park. she +found a rock. Jill decided to take it home. diff --git a/Task/Mad-Libs/J/mad-libs.j b/Task/Mad-Libs/J/mad-libs.j deleted file mode 100644 index 48690d2b16..0000000000 --- a/Task/Mad-Libs/J/mad-libs.j +++ /dev/null @@ -1,59 +0,0 @@ -coclass 'AA' -NB. associative array - -create=: verb define - empty KEYS=: DATA =: '' -) - -destroy=: codestroy - -put=: dyad define NB. DATUM put KEY - DATA=: DATA , < x - KEYS=: KEYS , < y - EMPTY -) - -get=: verb define NB. get KEY - (KEYS (i. <) y) {:: DATA -) - -cocurrent'base' - -get =: dyad define NB. OBJECT get KEY - try. - get__x y - catch. - smoutput '?' ,~ ": y - RV =. 1!:1<1 - RV put__x y - RV - end. -) - -STORY =: 0 :0 - went for a walk in the park. -found a . decided to take it home. -) - -madlib =: verb define NB. madlib STORY - I =. y i. '<' - if. I = # y do. y return. end. NB. no substitutions - HEAD =. I {. y - TAIL =. I }. y - A =. }. (<;.1~ '<'&=) '<' , TAIL NB. the story is parsed by '<' - B =. (({. ; }.)~ >:@:i.&'>')&> A - NB.+-----------+------------------------------+ - NB.| | went for a walk in the park. | - NB.+-----------+------------------------------+ - NB.|| found a | - NB.+-----------+------------------------------+ - NB.| |. | - NB.+-----------+------------------------------+ - NB.| | decided to take it home. | - NB.+-----------+------------------------------+ - AA =. conew'AA' - create__AA'' - SUBSTITUTIONS =. AA&get&.> _ 1 {. B - codestroy__AA'' - HEAD , ; SUBSTITUTIONS ,. 0 1 }. B -) diff --git a/Task/Mad-Libs/Mathematica/mad-libs.math b/Task/Mad-Libs/Mathematica/mad-libs.math index 99510db2e4..fcee3a31df 100644 --- a/Task/Mad-Libs/Mathematica/mad-libs.math +++ b/Task/Mad-Libs/Mathematica/mad-libs.math @@ -1,14 +1,11 @@ -filename = InputString["Enter the filename of the story template: "]; -text = Import[filename]; -listofblanks = StringCases[text, RegularExpression["<[^>]+>"]] // Union; -listofanswers = {}; -Do[ - answer = InputString["Enter a/an: " <> listofblanks[[i]]]; - AppendTo[listofanswers, answer]; - , {i, 1, Length[listofblanks]} - ] -Do[ - text = StringReplace[text, listofblanks[[i]] -> listofanswers[[i]]] - , {i, 1, Length[listofblanks]} - ] -text +text = Import[ + InputString["Enter the filename of the story template:"]]; +answers = + AssociationMap[ + InputString[ + "Enter a" <> + If[StringMatchQ[#, + "<" ~~ Alternatives @@ Characters["aeiou"] ~~ ___], "n", ""] <> + " " <> StringTrim[#, "<" | ">"] <> ":"] &, + Union[StringCases[text, RegularExpression["<[^>]+>"]]]]; +Print[StringReplace[text, Normal[answers]]]; diff --git a/Task/Mad-Libs/Pascal/mad-libs.pascal b/Task/Mad-Libs/Pascal/mad-libs.pascal new file mode 100644 index 0000000000..45b1fef4c0 --- /dev/null +++ b/Task/Mad-Libs/Pascal/mad-libs.pascal @@ -0,0 +1,105 @@ +Program Madlib; Uses DOS, crt; {See, for example, https://en.wikipedia.org/wiki/Mad_Libs} +{Reads the lines of a story but which also contain sequences. For each value of xxx, + found as the lines of the story are read, a request is made for a replacement text. + The story is then written out with the corresponding replacements made.} +{Concocted by R.N.McLean (whom God preserve), Victoria university, NZ.} + Procedure Croak(gasp: string); {A dying message.} + Begin + Writeln(' Eurghfff...'); + Writeln(Gasp); + HALT; + End; + var inf: text; {Drivelstuff.} + const StoryLimit = 66;TableLimit = 65; {Big enough.} + var Story: array[1..StoryLimit] of string; {Otherwise, use a temporary disc file.} + var Target,Replacement: array[1..TableLimit] of string; + var StoryLines,TableCount: integer; {Usage.} + + Function Reading(var inf: text;var Aline: string): boolean; + Begin + Aline:=''; + Reading:=true; + if eoln(inf) then Reading:=false {Agh! Why can't the read statement return true/false?} + else ReadLn(inf,Aline); + if Aline = '' then Reading:=false; {Specified that a blank line ends the story.} + End; + + Procedure Inspect(text: string); Forward;{I'd rather have multi-pass compilation than deal with this.} + + Procedure Table(it: string); {Check it as a target, and obtain its replacement.} + var i: integer; {A stepper.} + Begin + for i:=1 to TableCount do if it = Target[i] then exit; {Already in the table?} + if TableCount >= TableLimit then Croak('Too many table entries!'); {No. Room for another?} + inc(TableCount); {Yes.} + Target[TableCount]:=it; {Include the < and > to preclude partial matches.} + write('Enter your text for ',it,': '); {Pretty please?} + readln(Replacement[TableCount]); {Thus.} + Inspect(Replacement[TableCount]); {Enable full utilisation.} + End; {of Table.} + + var InDeep: integer; {Counts inspection recursion.} + Procedure Inspect(text: string); {Look for <...> in text.} + var i: integer; {A stepper.} + var mark: integer; {Fingers the latest < in Aline.} + Begin + inc(InDeep); {Supply an opportunity, and fear the possibilities.} + if InDeep > 28 then Croak('Excessive recursion! Inspecting ' + text); + for i:=1 to Length(text) do {Now scan the line for trouble.} + if text[i] = '<' then mark:=i {Trouble starts here? Just mark its place.} + else if text[i] = '>' then {Trouble ends here?} + Table(copy(text,mark,i - mark + 1)); {Deal with it.} + dec(InDeep); {I'm done.} + End; {of Inspect.} + + Procedure Swallow(Aline: string); {Add a line to the story, and inspect it for <...>.} + Begin + if StoryLines >= StoryLimit then Croak('Too many lines in the story!'); {Suspicion forever.} + inc(StoryLines); {Otherwise, this is safe.} + Story[StoryLines]:=Aline; {So save another line.} + Inspect(Aline); {Look for any <...> inclusions.} + End; {of Swallow.} + + var Rolling: integer; {Counts rolling rolls.} + Procedure Roll(bumf: string); {Write a line, with amendments.} + var last,mark: integer; {Fingers for the scan.} + var hit: string; {Copied once.} + var i,it: integer; {Steppers.} + label hic; {Oh dear.} + Begin + inc(Rolling); {Here I go.} + if Rolling > 28 then Croak('Excessive recursion! Rolling ' + bumf); {Self-expansion is out.} + last:=0; {Where the previous text ended.} + for i:=1 to Length(bumf) do {Scan the text.} + if bumf[i] = '<' then mark:=i {Remember where a <...> starts.} + else if bumf[i] = '>' then {So that when the stopper is found,} + begin {It can be recognised.} + Write(copy(bumf,last + 1,mark - last - 1)); {Text up to the <.} + hit:=copy(bumf,mark,i - mark + 1); {Grab this once.} + for it:=1 to TableCount do {Search my table.} + if Target[it] = hit then {A match?} + begin {Yes!} + Roll(Replacement[it]); {Write this instead.} + goto hic; {There is no "exit loop" style statement.} + end; {"Exit" exits the procedure or function.} + hic:last:=i; {Advance the trailing finger.} + end; {On to the next character.} + Write(copy(bumf,last + 1,Length(bumf) - last)); {Text after the last >, possibly null.} + dec(Rolling); {I'm done.} + if Rolling <= 0 then WriteLn; {And if this is the first level, add a end-of-line.} + End; {of Roll.} + + var inname: string; {For a file name.} + var Aline: string; {A scratchpad.} + var i: integer; {A stepper.} + BEGIN + InDeep:=0; {No inspections yet.} + Rolling:=0; {No output.} + inname:=ParamStr(1); {Perhaps the file name is specified as a run-time parameter.} + if inname = '' then inname:='Madlib.txt'; {If not, this will do.} + Assign(inf,inname); Reset(inf); {Open the input file.} + StoryLines:=0; TableCount:=0; {Prepare the counters.} + while reading(inf,Aline) do Swallow(Aline); {Read and inspect the story.} + close(inf); {Finished with input.} + for i:=1 to StoryLines do Roll(Story[i]); {Write the amended story.} + END. diff --git a/Task/Mad-Libs/Perl-6/mad-libs.pl6 b/Task/Mad-Libs/Perl-6/mad-libs.pl6 index 3876ba0443..4dd57ad1d3 100644 --- a/Task/Mad-Libs/Perl-6/mad-libs.pl6 +++ b/Task/Mad-Libs/Perl-6/mad-libs.pl6 @@ -1,4 +1 @@ -my $story = slurp(@*ARGS.shift); -my %words; -$story.=subst(/ '<' (.*?) '>' /, { %words{$0} //= prompt "$0? " }, :g ); -say $story; +print S:g[ '<' (.*?) '>' ] = %.{$0} //= prompt "$0? " given slurp; diff --git a/Task/Mad-Libs/VBScript/mad-libs.vb b/Task/Mad-Libs/VBScript/mad-libs.vb new file mode 100644 index 0000000000..55bd4a576e --- /dev/null +++ b/Task/Mad-Libs/VBScript/mad-libs.vb @@ -0,0 +1,18 @@ +Function mad_libs(s) + Do + If InStr(1,s,"<") <> 0 Then + start_position = InStr(1,s,"<") + 1 + end_position = InStr(1,s,">") + parse_string = Mid(s,start_position,end_position-start_position) + WScript.StdOut.Write parse_string & "? " + input_string = WScript.StdIn.ReadLine + s = Replace(s,"<" & parse_string & ">",input_string) + Else + Exit Do + End If + Loop + mad_libs = s +End Function + +WScript.StdOut.Write mad_libs(" went for a walk in the park. found a . decided to take it home.") +WScript.StdOut.WriteLine diff --git a/Task/Magic-squares-of-odd-order/00DESCRIPTION b/Task/Magic-squares-of-odd-order/00DESCRIPTION index f78b189c75..67bfedf1c7 100644 --- a/Task/Magic-squares-of-odd-order/00DESCRIPTION +++ b/Task/Magic-squares-of-odd-order/00DESCRIPTION @@ -1,10 +1,10 @@ -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''). +A magic square is an   '''NxN'''   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. +The numbers are usually (but not always) the first   '''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%" +{| 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:150%" |- | '''8''' || '''1''' || '''6''' |- @@ -15,9 +15,11 @@ A magic square whose rows and columns add up to a magic number but whose main di ;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''. +For any odd   '''N''',   [[wp:Magic square#Method_for_constructing_a_magic_square_of_odd_order|generate a magic square]] with the integers   ''' 1''' ──► '''N''',   and show the results here. -You should demonstrate the generator by showing at least a magic square for N=5. +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/ALGOL-W/magic-squares-of-odd-order.alg b/Task/Magic-squares-of-odd-order/ALGOL-W/magic-squares-of-odd-order.alg new file mode 100644 index 0000000000..8e0d58eb6b --- /dev/null +++ b/Task/Magic-squares-of-odd-order/ALGOL-W/magic-squares-of-odd-order.alg @@ -0,0 +1,77 @@ +begin + % construct a magic square of odd order - as a procedure can't return an % + % array, the caller must supply one that is big enough % + logical procedure magicSquare( integer array square ( *, * ) + ; integer value order + ) ; + if not odd( order ) or order < 1 then begin + % can't make a magic square of the specified order % + false + end + else begin + % order is OK - construct the square using de la Loubère's % + % algorithm as in the wikipedia page % + + % ensure a row/col position is on the square % + integer procedure inSquare( integer value pos ) ; + if pos < 1 then order else if pos > order then 1 else pos; + % move "up" a row in the square % + integer procedure up ( integer value row ) ; inSquare( row - 1 ); + % move "accross right" in the square % + integer procedure right( integer value col ) ; inSquare( col + 1 ); + + integer row, col; + % initialise square % + for i := 1 until order do for j := 1 until order do square( i, j ) := 0; + + % initial position is the middle of the top row % + col := ( order + 1 ) div 2; + row := 1; + % construct square % + for i := 1 until ( order * order ) do begin + square( row, col ) := i; + if square( up( row ), right( col ) ) not = 0 then begin + % the up/right position is already taken, move down % + row := row + 1; + end + else begin + % can move up/right % + row := up( row ); + col := right( col ); + end + end for_i; + % sucessful result % + true + end magicSquare ; + + % prints the magic square % + procedure printSquare( integer array square ( *, * ) + ; integer value order + ) ; + begin + integer sum, w; + + % set integer width to accomodate the largest number in the square % + w := ( order * order ) div 10; + i_w := s_w := 1; + while w > 0 do begin i_w := i_w + 1; w := w div 10 end; + + for i := 1 until order do sum := sum + square( 1, i ); + write( "maqic square of order ", order, ": sum: ", sum ); + for i := 1 until order do begin + write( square( i, 1 ) ); + for j := 2 until order do writeon( square( i, j ) ) + end for_i + + end printSquare ; + + % test the magic square generation % + + integer array sq ( 1 :: 11, 1 :: 11 ); + + for i := 1, 3, 5, 7 do begin + if magicSquare( sq, i ) then printSquare( sq, i ) + else write( "can't generate square" ); + end for_i + +end. diff --git a/Task/Magic-squares-of-odd-order/Befunge/magic-squares-of-odd-order.bf b/Task/Magic-squares-of-odd-order/Befunge/magic-squares-of-odd-order.bf new file mode 100644 index 0000000000..fbc0ceab90 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Befunge/magic-squares-of-odd-order.bf @@ -0,0 +1,2 @@ +500p0>:::00g%00g\-1-\00g/2*+1+00g%00g*\:00g%v +@<$<_^#!-*:g00:,+9!%g00:+1.+1+%g00+1+*2/g00\< diff --git a/Task/Magic-squares-of-odd-order/Elixir/magic-squares-of-odd-order.elixir b/Task/Magic-squares-of-odd-order/Elixir/magic-squares-of-odd-order.elixir new file mode 100644 index 0000000000..2f3cd14324 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Elixir/magic-squares-of-odd-order.elixir @@ -0,0 +1,15 @@ +defmodule RC do + require Integer + def odd_magic_square(n) when Integer.is_odd(n) do + for i <- 0..n-1 do + for j <- 0..n-1 do + n * rem(i+j+1+div(n,2),n) + rem(i+2*j+2*n-5,n) + 1 + end + end + end +end + +Enum.each([3,5,9], fn n -> + IO.puts "\nSize #{n}, magic sum #{div(n*n+1,2)*n}" + Enum.each(RC.odd_magic_square(n), fn x -> IO.inspect x end) +end) diff --git a/Task/Magic-squares-of-odd-order/Fortran/magic-squares-of-odd-order.f b/Task/Magic-squares-of-odd-order/Fortran/magic-squares-of-odd-order.f new file mode 100644 index 0000000000..2705e99f60 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Fortran/magic-squares-of-odd-order.f @@ -0,0 +1,30 @@ +program Magic_Square + implicit none + + integer, parameter :: order = 15 + integer :: i, j + + write(*, "(a, i0)") "Magic Square Order: ", order + write(*, "(a)") "----------------------" + do i = 1, order + do j = 1, order + write(*, "(i4)", advance = "no") f1(order, i, j) + end do + write(*,*) + end do + write(*, "(a, i0)") "Magic number = ", f2(order) + +contains + +integer function f1(n, x, y) + integer, intent(in) :: n, x, y + + f1 = n * mod(x + y - 1 + n/2, n) + mod(x + 2*y - 2, n) + 1 +end function + +integer function f2(n) + integer, intent(in) :: n + + f2 = n * (1 + n * n) / 2 +end function +end program 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-1.hs similarity index 100% rename from Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order.hs rename to Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order-1.hs diff --git a/Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order-2.hs b/Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order-2.hs new file mode 100644 index 0000000000..01c88203f6 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Haskell/magic-squares-of-odd-order-2.hs @@ -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/Liberty-BASIC/magic-squares-of-odd-order.liberty b/Task/Magic-squares-of-odd-order/Liberty-BASIC/magic-squares-of-odd-order.liberty new file mode 100644 index 0000000000..359281f5fa --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Liberty-BASIC/magic-squares-of-odd-order.liberty @@ -0,0 +1,49 @@ +Dim m(1,1) + +Call magicSquare 5 +Call magicSquare 17 + +End + +Sub magicSquare n + ReDim m(n,n) + inc = 1 + count = 1 + row = 1 + col=(n+1)/2 + While count <= n*n + m(row,col) = count + count = count + 1 + If inc < n Then + inc = inc + 1 + row = row - 1 + col = col + 1 + If row <> 0 Then + If col > n Then col = 1 + Else + row = n + End If + Else + inc = 1 + row = row + 1 + End If + Wend + Call printSquare n +End Sub + +Sub printSquare n + 'Arbitrary limit to fit width of A4 paper + If n < 23 Then + Print n;" x ";n;" Magic Square --- "; + Print "Magic constant is ";Int((n*n+1)/2*n) + For row = 1 To n + For col = 1 To n + Print Using("####",m(row,col)); + Next col + Print + Print + Next row + Else + Notice "Magic Square will not fit on one sheet of paper." + End If +End Sub diff --git a/Task/Magic-squares-of-odd-order/Perl/magic-squares-of-odd-order.pl b/Task/Magic-squares-of-odd-order/Perl/magic-squares-of-odd-order.pl new file mode 100644 index 0000000000..eac5664bee --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Perl/magic-squares-of-odd-order.pl @@ -0,0 +1,25 @@ +sub magic_square { + my $n = shift; + my $i = 0; + my $j = $n / 2; + my @magic_square; + + for my $l ( 1 .. $n**2 ) { + $magic_square[$i][$j] = $l; + + if ( $magic_square[ ( $i - 1 ) % $n ][ ( $j + 1 ) % $n ] ) { + $i = ( $i + 1 ) % $n; + } + else { + $i = ( $i - 1 ) % $n; + $j = ( $j + 1 ) % $n; + } + } + return @magic_square; +} + +my $n = 7; + +for ( magic_square($n) ) { + printf '%8d' x $n . qq{\n}, @{$_}; +} 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 index 824dae647e..d065a8a711 100644 --- 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 @@ -1,18 +1,22 @@ -/*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.*/ +/*REXX pgm generates & displays magic squares (odd N will be a true magic sq.)*/ +parse arg N . /*obtain the optional argument from CL.*/ +if N=='' | N==',' then N=5 /*Not specified? Then use the default.*/ +NN=N*N; w=length(NN) /*W: width of largest number (output).*/ +r=1; c=(n+1) % 2 /*define the initial row and column.*/ +@.=. /*assign a default value for entire @.*/ + do j=1 for N*N /* [↓] filling uses the Siamese method*/ + if r<1 & c>N then do; r=r+2; c=c-1; end /*row is under, col is over ···*/ + if r<1 then r=N /*row is under, make row=last. */ + if r>N then r=1 /*row is over, make row=first.*/ + if c>N then c=1 /*col is over, make col=first.*/ + if @.r.c\==. then do; r=min(N,r+2); c=max(1,c-1); end /*at previous cell?*/ + @.r.c=j; r=r-1; c=c+1 /*assign # ───► cell; next row and col.*/ + end /*j*/ + /* [↓] display square with aligned #'s*/ + do r=1 for N; _= /*display one matrix row at a time. */ + do c=1 for N; _=_ right(@.r.c, w); end /*c*/ /*build a row. */ + say substr(_,2) /*display a row.*/ + end /*c*/ +say /* [↑] If an odd square, show magic #.*/ +if N//2 then say 'The magic number (or magic constant is): ' N * (NN+1) % 2 + /*stick a fork in it, we're all done. */ 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 index 4ab4fa8cc8..2df04f095c 100644 --- 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 @@ -1,6 +1,6 @@ fn main() { let n = 9; - let mut square = Vec::from_fn(n, |_| Vec::from_fn(n, |_| 0u)); + let mut square = vec![vec![0; n]; n]; 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; diff --git a/Task/Magic-squares-of-odd-order/Scala/magic-squares-of-odd-order.scala b/Task/Magic-squares-of-odd-order/Scala/magic-squares-of-odd-order.scala new file mode 100644 index 0000000000..2fa4665f71 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/Scala/magic-squares-of-odd-order.scala @@ -0,0 +1,60 @@ + def magicSquare( n:Int ) : Option[Array[Array[Int]]] = { + require(n % 2 != 0, "n must be an odd number") + + val a = Array.ofDim[Int](n,n) + + // Make the horizontal by starting in the middle of the row and then taking a step back every n steps + val ii = Iterator.continually(0 to n-1).flatten.drop(n/2).sliding(n,n-1).take(n*n*2).toList.flatten + + // Make the vertical component by moving up (subtracting 1) but every n-th step, step down (add 1) + val jj = Iterator.continually(n-1 to 0 by -1).flatten.drop(n-1).sliding(n,n-2).take(n*n*2).toList.flatten + + // Combine the horizontal and vertical components to create the path + val path = (ii zip jj) take (n*n) + + // Fill the array by following the path + for( i<-1 to (n*n); p=path(i-1) ) { a(p._1)(p._2) = i } + + Some(a) + } + + def output() : Unit = { + def printMagicSquare(n: Int): Unit = { + + val ms = magicSquare(n) + val magicsum = (n * n + 1) / 2 + + assert( + if( ms.isDefined ) { + val a = ms.get + a.forall(_.sum == magicsum) && + a.transpose.forall(_.sum == magicsum) && + (for(i<-0 until n) yield { a(i)(i) }).sum == magicsum + } + else { false } + ) + + if( ms.isDefined ) { + val a = ms.get + for (y <- 0 to n * 2; x <- 0 until n) (x, y) match { + case (0, 0) => print("╔════╤") + case (i, 0) if i == n - 1 => print("════╗\n") + case (i, 0) => print("════╤") + + case (0, j) if j % 2 != 0 => print("║ " + f"${ a(0)((j - 1) / 2) }%2d" + " │") + case (i, j) if j % 2 != 0 && i == n - 1 => print(" " + f"${ a(i)((j - 1) / 2) }%2d" + " ║\n") + case (i, j) if j % 2 != 0 => print(" " + f"${ a(i)((j - 1) / 2) }%2d" + " │") + + case (0, j) if j == (n * 2) => print("╚════╧") + case (i, j) if j == (n * 2) && i == n - 1 => print("════╝\n") + case (i, j) if j == (n * 2) => print("════╧") + + case (0, _) => print("╟────┼") + case (i, _) if i == n - 1 => print("────╢\n") + case (i, _) => print("────┼") + } + } + } + + printMagicSquare(7) + } diff --git a/Task/Magic-squares-of-odd-order/VBScript/magic-squares-of-odd-order.vb b/Task/Magic-squares-of-odd-order/VBScript/magic-squares-of-odd-order.vb new file mode 100644 index 0000000000..881966d744 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/VBScript/magic-squares-of-odd-order.vb @@ -0,0 +1,39 @@ +Sub magic_square(n) + Dim ms() + ReDim ms(n-1,n-1) + inc = 0 + count = 1 + row = 0 + col = Int(n/2) + Do While count <= n*n + ms(row,col) = count + count = count + 1 + If inc < n-1 Then + inc = inc + 1 + row = row - 1 + col = col + 1 + If row >= 0 Then + If col > n-1 Then + col = 0 + End If + Else + row = n-1 + End If + Else + inc = 0 + row = row + 1 + End If + Loop + For i = 0 To n-1 + For j = 0 To n-1 + If j = n-1 Then + WScript.StdOut.Write ms(i,j) + Else + WScript.StdOut.Write ms(i,j) & vbTab + End If + Next + WScript.StdOut.WriteLine + Next +End Sub + +magic_square(5) diff --git a/Task/Make-directory-path/Common-Lisp/make-directory-path.lisp b/Task/Make-directory-path/Common-Lisp/make-directory-path.lisp new file mode 100644 index 0000000000..38dcfe30d9 --- /dev/null +++ b/Task/Make-directory-path/Common-Lisp/make-directory-path.lisp @@ -0,0 +1 @@ +(ensure-directories-exist "your/path/name") diff --git a/Task/Make-directory-path/Elixir/make-directory-path.elixir b/Task/Make-directory-path/Elixir/make-directory-path.elixir new file mode 100644 index 0000000000..a6dbcb7f46 --- /dev/null +++ b/Task/Make-directory-path/Elixir/make-directory-path.elixir @@ -0,0 +1 @@ +File.mkdir_p("./path/to/dir") diff --git a/Task/Make-directory-path/Haskell/make-directory-path.hs b/Task/Make-directory-path/Haskell/make-directory-path.hs new file mode 100644 index 0000000000..ed27978298 --- /dev/null +++ b/Task/Make-directory-path/Haskell/make-directory-path.hs @@ -0,0 +1,7 @@ +import System.Directory (createDirectory, setCurrentDirectory) +import Data.List.Split (splitOn) + +main :: IO () +main = do + let path = splitOn "/" "path/to/dir" + mapM_ (\x -> createDirectory x >> setCurrentDirectory x) path diff --git a/Task/Make-directory-path/J/make-directory-path-1.j b/Task/Make-directory-path/J/make-directory-path-1.j new file mode 100644 index 0000000000..c50dff22a2 --- /dev/null +++ b/Task/Make-directory-path/J/make-directory-path-1.j @@ -0,0 +1,2 @@ +require 'general/dirutils' +pathcreate '/tmp/some/path/to/dir' diff --git a/Task/Make-directory-path/J/make-directory-path-2.j b/Task/Make-directory-path/J/make-directory-path-2.j new file mode 100644 index 0000000000..44910470cc --- /dev/null +++ b/Task/Make-directory-path/J/make-directory-path-2.j @@ -0,0 +1,17 @@ +pathcreate=: monad define + todir=. termsep_j_ jpathsep y + todirs=. }. ,each /\ <;.2 todir NB. base dirs + msk=. -.direxist todirs NB. 1 for each non-existing dir + msk=. 0 (i. msk i: 0)}msk + dircreate msk#todirs NB. create non-existing base dirs +) + +dircreate=: monad define + y=. boxxopen y + msk=. -.direxist y + if. ''-:$msk do. msk=. (#y)#msk end. + res=. 1!:5 msk#y + msk #inv ,res +) + +direxist=: 2 = ftype&>@:boxopen diff --git a/Task/Make-directory-path/Perl-6/make-directory-path.pl6 b/Task/Make-directory-path/Perl-6/make-directory-path.pl6 index 4fdb0d544b..b47cefce55 100644 --- a/Task/Make-directory-path/Perl-6/make-directory-path.pl6 +++ b/Task/Make-directory-path/Perl-6/make-directory-path.pl6 @@ -1 +1 @@ -mkdir 'path/to/dir' +mkpath 'path/to/dir' diff --git a/Task/Make-directory-path/Perl/make-directory-path.pl b/Task/Make-directory-path/Perl/make-directory-path.pl new file mode 100644 index 0000000000..5fb3c914ed --- /dev/null +++ b/Task/Make-directory-path/Perl/make-directory-path.pl @@ -0,0 +1,3 @@ +use File::Path qw(make_path); + +make_path('path/to/dir') diff --git a/Task/Make-directory-path/Seed7/make-directory-path-1.seed7 b/Task/Make-directory-path/Seed7/make-directory-path-1.seed7 new file mode 100644 index 0000000000..1fd23c97f7 --- /dev/null +++ b/Task/Make-directory-path/Seed7/make-directory-path-1.seed7 @@ -0,0 +1,7 @@ +$ include "seed7_05.s7i"; + include "cli_cmds.s7i"; + +const proc: main is func + begin + doMkdirCmd(argv(PROGRAM), TRUE); + end func; diff --git a/Task/Make-directory-path/Seed7/make-directory-path-2.seed7 b/Task/Make-directory-path/Seed7/make-directory-path-2.seed7 new file mode 100644 index 0000000000..54ab614118 --- /dev/null +++ b/Task/Make-directory-path/Seed7/make-directory-path-2.seed7 @@ -0,0 +1,10 @@ +$ include "seed7_05.s7i"; + include "cli_cmds.s7i"; + +const proc: main is func + local + var string: parameters is ""; + begin + parameters := join(argv(PROGRAM), " "); + doMkdir(parameters); + end func; diff --git a/Task/Man-or-boy-test/Ela/man-or-boy-test.ela b/Task/Man-or-boy-test/Ela/man-or-boy-test.ela index c3e1bfefaf..ce2eab8f94 100644 --- a/Task/Man-or-boy-test/Ela/man-or-boy-test.ela +++ b/Task/Man-or-boy-test/Ela/man-or-boy-test.ela @@ -1,9 +1,15 @@ -open list cell console +open monad io unsafe.cell unsafe.console -a k x1 x2 x3 x4 x5 | k <= 0 = x4! + x5! - | else = b! - where b () = m-- $ a (valueof m) b x1 x2 x3 x4 - m = ref k - m-- = m |> mutate (valueof m - 1) +liftM2 f m1 m2 = do + x1 <- m1 + x2 <- m2 + return (f x1 x2) -a 10 (\() -> 1) (\() -> --1) (\() -> --1) (\() -> 1) (\() -> 0) +a k x1 x2 x3 x4 x5 = do + r <- return $ ref k + let b = & do k <- return $ pred (valueof r) + a k b x1 x2 x3 x4 + if k <= 0 then liftM2 (+) x4 x5 else b + +_ = a 10 (!!1) (!! -1) (!! -1) (!!1) (!!0) >>= (putStr << show) ::: IO + where (!!) f = & return f ::: IO diff --git a/Task/Man-or-boy-test/JavaScript/man-or-boy-test-1.js b/Task/Man-or-boy-test/JavaScript/man-or-boy-test-1.js new file mode 100644 index 0000000000..e187b85415 --- /dev/null +++ b/Task/Man-or-boy-test/JavaScript/man-or-boy-test-1.js @@ -0,0 +1,15 @@ +function a(k, x1, x2, x3, x4, x5) { + function b() { + k -= 1; + return a(k, b, x1, x2, x3, x4); + } + return (k > 0) ? b() : x4() + x5(); +} + +// this uses lambda wrappers around the numeric arguments +function x(n) { + return function () { + return n; + }; +} +alert(a(10, x(1), x(-1), x(-1), x(1), x(0))); diff --git a/Task/Man-or-boy-test/JavaScript/man-or-boy-test-2.js b/Task/Man-or-boy-test/JavaScript/man-or-boy-test-2.js new file mode 100644 index 0000000000..521aab8167 --- /dev/null +++ b/Task/Man-or-boy-test/JavaScript/man-or-boy-test-2.js @@ -0,0 +1,6 @@ +var x = n => () => n; + +var a = (k, x1, x2, x3, x4, x5) => { + var b = () => return a(--k, b, x1, x2, x3, x4); //decrement k before use + return (k > 0) ? b() : x4() + x5(); +}; diff --git a/Task/Man-or-boy-test/JavaScript/man-or-boy-test.js b/Task/Man-or-boy-test/JavaScript/man-or-boy-test.js deleted file mode 100644 index 9ff08c67e5..0000000000 --- a/Task/Man-or-boy-test/JavaScript/man-or-boy-test.js +++ /dev/null @@ -1,15 +0,0 @@ -function a(k, x1, x2, x3, x4, x5) { - function b() { - k = k - 1; - return a(k, b, x1, x2, x3, x4); - } - return k <= 0 ? x4() + x5() : b(); -} - -// this uses lambda wrappers around the numeric arguments -function x(n) { - return function () { - return n; - }; -} -alert(a(10, x(1), x(-1), x(-1), x(1), x(0))); diff --git a/Task/Man-or-boy-test/Julia/man-or-boy-test.julia b/Task/Man-or-boy-test/Julia/man-or-boy-test.julia new file mode 100644 index 0000000000..47bf634b7b --- /dev/null +++ b/Task/Man-or-boy-test/Julia/man-or-boy-test.julia @@ -0,0 +1,6 @@ +function a(k, x1, x2, x3, x4, x5) + b = ()-> a(k-=1, b, x1, x2, x3, x4); + k <= 0 ? (x4() + x5()) : b(); +end + +println(a(10, ()->1, ()->-1, ()->-1, ()->1, ()->0)); diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-1.basic similarity index 100% rename from Task/Mandelbrot-set/BASIC/mandelbrot-set.basic rename to Task/Mandelbrot-set/BASIC/mandelbrot-set-1.basic diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-2.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-2.basic new file mode 100644 index 0000000000..0169237ea2 --- /dev/null +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-2.basic @@ -0,0 +1,34 @@ +fastgraphics + +graphsize 384,384 +refresh +kt=319 : m = 4.0 +xmin=2.1 : xmax=-0.6 : ymin=-1.35 : ymax=1.35 +dx=(xmax-xmin)/graphwidth : dy=(ymax-ymin)/graphheight + +for x=0 to graphwidth + jx = xmin+x*dx + for y=0 to graphheight + jy = ymin+y*dy + k = 0 : wx = 0.0 : wy = 0.0 + do + tx = wx*wx-(wy*wy+jx) + ty = 2.0*wx*wy+jy + wx = tx + wy = ty + r = wx*wx+wy*wy + k = k+1 + until r>m or k>kt + + if k>kt then + color black + else + if k<16 then color k*8,k*8,128+k*4 + if k>=16 and k<64 then color 128+k-16,128+k-16,192+k-16 + if k>=64 then color kt-k,128+(kt-k)/2,kt-k + end if + plot x,y + next y + refresh +next x +imgsave "Mandelbrot_BASIC-256.png", "PNG" diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-3.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-3.basic new file mode 100644 index 0000000000..991a28cc9d --- /dev/null +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-3.basic @@ -0,0 +1,22 @@ + sizex% = 300 : sizey% = 300 + maxiter% = 128 + VDU 23,22,sizex%;sizey%;8,8,16,128 + ORIGIN 0,sizey% + GCOL 1 + FOR X% = 0 TO 2*sizex%-2 STEP 2 + xi = X%/200 - 2 + FOR Y% = 0 TO sizey%-2 STEP 2 + yi = Y% / 200 + x = 0 + y = 0 + FOR I% = 1 TO maxiter% + IF x*x+y*y > 4 EXIT FOR + xt = xi + x*x-y*y + y = yi + 2*x*y + x = xt + NEXT + IF I%>maxiter% I%=0 + COLOUR 1,I%*15,I%*8,0 + PLOT X%,Y% : PLOT X%,-Y% + NEXT + NEXT X% diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-4.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-4.basic new file mode 100644 index 0000000000..c8cd216008 --- /dev/null +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-4.basic @@ -0,0 +1,55 @@ +nomainwin + +WindowWidth =440 +WindowHeight =460 + +open "Mandelbrot Set" for graphics_nsb_nf as #w + +#w "trapclose [quit]" +#w "down" + +for x0 = -2 to 1 step .0033 + for y0 = -1.5 to 1.5 step .0075 + x = 0 + y = 0 + + iteration = 0 + maxIteration = 255 + + while ( ( x *x +y *y) <=4) and ( iteration maxIteration then + c =iteration + else + c =0 + end if + + call pSet x0, y0, c + scan + next +next + +#w "flush" + +wait + +sub pSet x, y, c + xScreen = 10 +( x +2) /3 *400 + yScreen = 10 +( y +1.5) /3 *400 + if c =0 then + col$ ="red" + else + if c mod 2 =1 then col$ ="lightgray" else col$ ="white" + end if + #w "color "; col$ + #w "set "; xScreen; " "; yScreen +end sub + +[quit] +close #w +end diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-5.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-5.basic new file mode 100644 index 0000000000..07d7c6ccd5 --- /dev/null +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-5.basic @@ -0,0 +1,17 @@ +10 X1=59\Y1=21 +20 I1=-1.0\I2=1.0\R1=-2.0\R2=1.0 +30 S1=(R2-R1)/X1\S2=(I2-I1)/Y1 +40 FOR Y=0 TO Y1 +50 I3=I1+S2*Y +60 FOR X=0 TO X1 +70 R3=R1+S1*X\Z1=R3\Z2=I3 +80 FOR N=0 TO 30 +90 A=Z1*Z1\B=Z2*Z2 +100 IF A+B>4.0 GOTO 130 +110 Z2=2*Z1*Z2+I3\Z1=A-B+R3 +120 NEXT N +130 PRINT CHR$(62-N); +140 NEXT X +150 PRINT +160 NEXT Y +170 END diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-6.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-6.basic new file mode 100644 index 0000000000..5e57b1a33a --- /dev/null +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-6.basic @@ -0,0 +1,85 @@ +'Mandelbrot V4 for RunBasic +'Based on LibertyBasic solution +'copy the code and go to runbasic.com +'http://rosettacode.org/wiki/Mandelbrot_set#Liberty_BASIC +'May 2015 +' +WindowWidth = 320 'RunBasic max size 800 x 600 +WindowHeight = 320 +'print zone -2 to 1 (X) +'print zone -1.5 to 1.5 (Y) +a = -1.5 'graph -1.5 to -0.75, first "loop" +b = -0.75 'adjust for max processor time (y0 for loop below) + +'open "Mandelbrot Set" for graphics_nsb_nf as #w not used in RunBasic + +graphic #w, WindowWidth, WindowHeight +'#w "trapclose [quit]" not used in RunBasic +'#w "down" not used in RunBasic + +cls +'#w flush() +#w cls("black") +render #w + '#w flush() +input "OK, hit enter to continue"; guess +cls + +[man_calc] +'3/screen size 3/800 = 0.00375 ** 3/790 = 0.0037974 +'3/screen size (y) 3/600 = .005 ** 3/590 = 0.0050847 +'3/215 = .0139 .0068 = 3/440 +cc = 3/299 +' + for x0 = -2 to 1 step cc + for y0 = a to b step cc + x = 0 + y = 0 + + iteration = 0 + maxIteration = 255 + + while ( ( x *x +y *y) <=4) and ( iteration maxIteration then + c =iteration + else + c =0 + end if + + call pSet x0, y0, c + 'scan why scan? (wait for user input) with RunBasic ? + next +next + +'#w flush() 'what is flush? RunBasic uses the render command. +render #w + +input "OK, hit enter to continue"; guess +cls +a = a + 0.75 +b = b + 0.75 +if b > 1.6 then goto[quit] else goto[man_calc] + +sub pSet x, y, c + xScreen = 5+(x +2) /3 * 300 'need positive screen number + yScreen = 5+(y +1.5) /3 * 300 'and 5x5 boarder + if c =0 then + col$ ="red" + else + if c mod 2 =1 then col$ ="lightgray" else col$ ="white" + end if + #w "color "; col$ + #w "set "; xScreen; " "; yScreen +end sub + +[quit] +cls +render #w +print "All done, good bye." +end diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-7.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-7.basic new file mode 100644 index 0000000000..9080950f17 --- /dev/null +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-7.basic @@ -0,0 +1,29 @@ +GraphicsWindow.Show() +size = 500 +half = 250 +GraphicsWindow.Width = size * 1.5 +GraphicsWindow.Height = size +GraphicsWindow.Title = "Mandelbrot" +For px = 1 To size * 1.5 + x_0 = px/half - 2 + For py = 1 To size + y_0 = py/half - 1 + x = x_0 + y = y_0 + i = 0 + While(c <= 2 AND i<100) + x_1 = Math.Power(x, 2) - Math.Power(y, 2) + x_0 + y_1 = 2 * x * y + y_0 + c = Math.Power(Math.Power(x_1, 2) + Math.Power(y_1, 2), 0.5) + x = x_1 + y = y_1 + i = i + 1 + EndWhile + If i < 99 Then + GraphicsWindow.SetPixel(px, py, GraphicsWindow.GetColorFromRGB((255/25)*i, (255/25)*i, (255/5)*i)) + Else + GraphicsWindow.SetPixel(px, py, "black") + EndIf + c=0 + EndFor +EndFor diff --git a/Task/Mandelbrot-set/Befunge/mandelbrot-set.bf b/Task/Mandelbrot-set/Befunge/mandelbrot-set.bf new file mode 100644 index 0000000000..35d9f2d308 --- /dev/null +++ b/Task/Mandelbrot-set/Befunge/mandelbrot-set.bf @@ -0,0 +1,10 @@ +0>:00p58*`#@_0>:01p78vv$$< +@^+1g00,+55_v# !`\+*9<>4v$ +@v30p20"?~^"< ^+1g10,+*8<$ +@>p0\>\::*::882**02g*0v >^ +`*:*" d":+*:-*"[Z"+g3 < |< +v-*"[Z"+g30*g20**288\--\<# +>2**5#>8*:*/00g"P"*58*:*v^ +v*288 p20/**288:+*"[Z"+-<: +>*%03 p58*:*/01g"3"* v>::^ + \_^#!:-1\+-*2*:*85<^ diff --git a/Task/Mandelbrot-set/C++/mandelbrot-set.cpp b/Task/Mandelbrot-set/C++/mandelbrot-set.cpp index 11b93c8185..c20ae6a82b 100644 --- a/Task/Mandelbrot-set/C++/mandelbrot-set.cpp +++ b/Task/Mandelbrot-set/C++/mandelbrot-set.cpp @@ -21,8 +21,8 @@ template double cxmin, double cxmax, double cymin, double cymax,//the rect to draw in the complex plane unsigned int max_iterations) //the maximum number of iterations { - std::size_t const ixsize = get_first_dimension(ImageType); - std::size_t const iysize = get_first_dimension(ImageType); + std::size_t const ixsize = get_first_dimension(image); + std::size_t const iysize = get_first_dimension(image); for (std::size_t ix = 0; ix < ixsize; ++ix) for (std::size_t iy = 0; iy < iysize; ++iy) { diff --git a/Task/Mandelbrot-set/Dart/mandelbrot-set.dart b/Task/Mandelbrot-set/Dart/mandelbrot-set.dart index 912f8e6ef7..596617a8a7 100644 --- a/Task/Mandelbrot-set/Dart/mandelbrot-set.dart +++ b/Task/Mandelbrot-set/Dart/mandelbrot-set.dart @@ -2,8 +2,8 @@ class Complex { double _r,_i; Complex(this._r,this._i); - double get r() => _r; - double get i() => _i; + double get r => _r; + double get i => _i; String toString() => "($r,$i)"; Complex operator +(Complex other) => new Complex(r+other.r,i+other.i); @@ -22,7 +22,7 @@ void main() { String line=""; for(int x=0;x<70;x++) { Complex c=new Complex(start_x+step_x*x,start_y+step_y*y); - Complex z=new Complex(0,0); + Complex z=new Complex(0.0, 0.0); for(int i=0;i<100;i++) { z=z*(z)+c; if(z.abs()>2) { diff --git a/Task/Mandelbrot-set/Erlang/mandelbrot-set.erl b/Task/Mandelbrot-set/Erlang/mandelbrot-set.erl new file mode 100644 index 0000000000..dc082ea835 --- /dev/null +++ b/Task/Mandelbrot-set/Erlang/mandelbrot-set.erl @@ -0,0 +1,52 @@ + %% @author Salvador Tamarit + +-module(mandelbrot). + +-export([test/0]). + +magnitude(Z) -> + R = complex:real(Z), + I = complex:imaginary(Z), + R * R + I * I. + +mandelbrot(A, MaxI, Z, I) -> + case (I < MaxI) and (magnitude(Z) < 2.0) of + true -> + NZ = complex:add(complex:mult(Z, Z), A), + mandelbrot(A, MaxI, NZ, I + 1); + false -> + case I of + MaxI -> + $*; + _ -> + $ + end + end. + +test() -> + lists:map( + fun(S) -> io:format("~s",[S]) end, + [ + [ + begin + Z = complex:make(X, Y), + mandelbrot(Z, 50, Z, 1) + end + || X <- seq_float(-2, 0.5, 0.0315) + ] ++ "\n" + || Y <- seq_float(-1,1, 0.05) + ] ), + ok. + +% ************************************************** +% Copied from https://gist.github.com/andruby/241489 +% ************************************************** + +seq_float(Min, Max, Inc, Counter, Acc) when (Counter*Inc + Min) >= Max -> + lists:reverse([Max|Acc]); +seq_float(Min, Max, Inc, Counter, Acc) -> + seq_float(Min, Max, Inc, Counter+1, [Inc * Counter + Min|Acc]). +seq_float(Min, Max, Inc) -> + seq_float(Min, Max, Inc, 0, []). + +% ************************************************** diff --git a/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js b/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js index d1f7faf9b4..738a6a6047 100644 --- a/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js +++ b/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js @@ -1,69 +1,69 @@ -function Mandeliter( cx, cy, maxiter ){ - var - x = 0.0, - y = 0.0, - xx = 0, - yy = 0, - xy = 0; +function mandelIter(cx, cy, maxIter) { + var x = 0.0; + var y = 0.0; + var xx = 0; + var yy = 0; + var xy = 0; - var i = maxiter; - while( i-- && xx + yy <= 4 ){ + var i = maxIter; + while (i-- && xx + yy <= 4) { xy = x * y; xx = x * x; yy = y * y; x = xx - yy + cx; y = xy + xy + cy; } - return maxiter - i; + return maxIter - i; } -function Mandelbrot( width,height, xmin,xmax, ymin,ymax, iterations ){ - var canvas = document.createElement( 'canvas' ); - canvas.width = width; - canvas.height = height; +function mandelbrot(canvas, xmin, xmax, ymin, ymax, iterations) { + var width = canvas.width; + var height = canvas.height; - var ctx = canvas.getContext( '2d' ); - var img = ctx.getImageData( 0, 0, width, height ); + var ctx = canvas.getContext('2d'); + var img = ctx.getImageData(0, 0, width, height); var pix = img.data; - for( var ix = 0; ix < width; ++ix ) - for( var iy = 0; iy < height; ++iy ) - { + + for (var ix = 0; ix < width; ++ix) { + for (var iy = 0; iy < height; ++iy) { var x = xmin + (xmax - xmin) * ix / (width - 1); var y = ymin + (ymax - ymin) * iy / (height - 1); - var i = Mandeliter( x, y, iterations ); + var i = mandelIter(x, y, iterations); var ppos = 4 * (width * iy + ix); - if( i === iterations ) - { + + if (i > iterations) { pix[ppos] = 0; - pix[ppos+1] = 0; - pix[ppos+2] = 0; - } - else - { - var c = 3 * Math.log(i)/Math.log(iterations - 1.0); - if (c < 1) - { - pix[ppos] = 255*c; - pix[ppos+1] = 0; - pix[ppos+2] = 0; + pix[ppos + 1] = 0; + pix[ppos + 2] = 0; + } else { + var c = 3 * Math.log(i) / Math.log(iterations - 1.0); + + if (c < 1) { + pix[ppos] = 255 * c; + pix[ppos + 1] = 0; + pix[ppos + 2] = 0; } - else if( c < 2 ) - { + else if ( c < 2 ) { pix[ppos] = 255; - pix[ppos+1] = 255*(c-1); - pix[ppos+2] = 0; - } - else - { + pix[ppos + 1] = 255 * (c - 1); + pix[ppos + 2] = 0; + } else { pix[ppos] = 255; - pix[ppos+1] = 255; - pix[ppos+2] = 255*(c-2); + pix[ppos + 1] = 255; + pix[ppos + 2] = 255 * (c - 2); } } - pix[ ppos+3 ] = 255; + pix[ppos + 3] = 255; } - ctx.putImageData( img, 0,0 ); - document.body.insertBefore( canvas, document.body.childNodes[0] ); + } + + ctx.putImageData(img, 0, 0); } -Mandelbrot( 900,600, -2,1, -1,1, 1000 ); +var canvas = document.createElement('canvas'); +canvas.width = 900; +canvas.height = 600; + +document.body.insertBefore(canvas, document.body.childNodes[0]); + +mandelbrot(canvas, -2, 1, -1, 1, 1000); diff --git a/Task/Mandelbrot-set/Perl-6/mandelbrot-set.pl6 b/Task/Mandelbrot-set/Perl-6/mandelbrot-set.pl6 index 4898cb702a..e46b25e5cf 100644 --- a/Task/Mandelbrot-set/Perl-6/mandelbrot-set.pl6 +++ b/Task/Mandelbrot-set/Perl-6/mandelbrot-set.pl6 @@ -1,15 +1,14 @@ constant MAX_ITERATIONS = 50; -my $height = @*ARGS[0] // 31; -$height = $height % 2 ?? +$height !! 1+$height; -my $width = $height; +my $width = my $height = +(@*ARGS[0] // 30); -my $re = [ -2, 1/2 ]; -my $im = [-5/4, 5/4]; +sub cut(Range $r, Int $n where $n > 1) { + $r.min, * + ($r.max - $r.min) / ($n - 1) ... $r.max +} -my @re = $re.min, * + ($re.max - $re.min)/($height - 1) ... $re.max; -my @im = 1i «*« ($im.min, * + ($im.max - $im.min)/($width - 1) ... 0); +my @re = cut(-2 .. 1/2, $height); +my $im = [ cut( 0 .. 5/4, $width div 2 + 1) X* 1i ]; -my @color_map = map ~*.comb(/../).map({:16($_)}), < +constant @color_map = map ~*.comb(/../).map({:16($_)}), < 000000 0000fc 4000fc 7c00fc bc00fc fc00fc fc00bc fc007c fc0040 fc0000 fc4000 fc7c00 fcbc00 fcfc00 bcfc00 7cfc00 40fc00 00fc00 00fc40 00fc7c 00fcbc 00fcfc 00bcfc 007cfc 0040fc 7c7cfc 9c7cfc bc7cfc dc7cfc fc7cfc fc7cdc fc7cbc fc7c9c @@ -32,14 +31,27 @@ b4fcc4 b4fcd8 b4fce8 b4fcfc b4e8fc b4d8fc b4c4fc 000070 1c0070 380070 540070 2c402c 2c4030 2c4034 2c403c 2c4040 2c3c40 2c3440 2c3040 >; -sub Mandel (Complex $z) { 0, * **2 + $z ... *.abs > 2 } +sub mandelbrot( Complex $c ) { + my $im2 = $c.im**2; + return 0 if ($c.re + 1)**2 + $im2 < 1/16; + my $q = ($c.re - 1/4)**2 + $im2; + return 0 if $q*($q + ($c.re - 1/4)) < $im2/4; + my $z = 0i; + for ^MAX_ITERATIONS -> $i { + return $i + 1 if $z.re**2 + $z.im**2 > 4; + $z = $z * $z + $c; + } + return 0; +} + +my @promises = map -> $re { + start { [ mandelbrot($re + $_) for @$im ] } +}, @re; say "P3"; say "$width $height"; say "255"; -for @re -> $re { - say @color_map[.[^.end], .reverse] given - map { +Mandel($^z)[^MAX_ITERATIONS] % MAX_ITERATIONS }, - $re «+« @im; +for @promises».result { + say @color_map[(flat .reverse, .[1..*])[^$width]]; } diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-2.py b/Task/Mandelbrot-set/Python/mandelbrot-set-2.py index e615a9d35d..3149372f39 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-2.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-2.py @@ -3,11 +3,10 @@ def mandelbrot(z , c , n=40): if abs(z) > 1000: return float("nan") + elif n > 0: + return mandelbrot(z ** 2 + c, c, n - 1) else: - if n > 0: - return mandelbrot(z ** 2 + c, c, n - 1) - else: - return z ** 2 + c + return z ** 2 + c print("\n".join(["".join(["#" if not math.isnan(mandelbrot(0, x + 1j * y).real) else " " for x in [a * 0.02 for a in range(-80, 30)]]) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-3.py b/Task/Mandelbrot-set/Python/mandelbrot-set-3.py new file mode 100644 index 0000000000..d99e405c16 --- /dev/null +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-3.py @@ -0,0 +1,25 @@ +from pylab import * +from numpy import NaN + +def m(a): + z = 0 + for n in range(1, 100): + z = z**2 + a + if abs(z) > 2: + return n + return NaN + +X = arange(-2, .5, .002) +Y = arange(-1, 1, .002) +Z = zeros((len(Y), len(X))) + +for iy, y in enumerate(Y): + print (iy, "of", len(Y)) + for ix, x in enumerate(X): + Z[iy,ix] = m(x + 1j * y) + +imshow(Z, cmap = plt.cm.prism, interpolation = 'none', extent = (X.min(), X.max(), Y.min(), Y.max())) +xlabel("Re(c)") +ylabel("Im(c)") +savefig("mandelbrot_python.svg") +show() diff --git a/Task/Mandelbrot-set/REXX/mandelbrot-set.rexx b/Task/Mandelbrot-set/REXX/mandelbrot-set.rexx index bb1ea9f7ca..dcf2c794df 100644 --- a/Task/Mandelbrot-set/REXX/mandelbrot-set.rexx +++ b/Task/Mandelbrot-set/REXX/mandelbrot-set.rexx @@ -1,17 +1,18 @@ -/*REXX program generates and displays a Mandelbrot set as an ASCII image*/ -xsize = 59; minre = -2; maxre = +1; stepx = (maxre-minre)/xsize -ysize = 21; minim = -1; maxim = +1; stepy = (maxim-minim)/ysize +/*REXX program generates and displays a Mandelbrot set as an ASCII image. */ +xsize = 59; minre = -2; maxre = +1; stepx = (maxre-minre)/xsize +ysize = 21; minim = -1; maxim = +1; stepy = (maxim-minim)/ysize - do y=0 for ysize - im=minim+stepy*y - do x=0 for xsize - re=minre+stepx*x; zr=re; zi=im - do n=0 for 30 - a=zr*zr; b=zi*zi - if a+b>4 then leave - zi=2*zr*zi+im; zr=a-b+re - end /*n*/ - call charout ,d2c(62-n) /*display number as a char──►term*/ - end /*x*/ - say /*force last CHAROUTs to the term*/ - end /*y*/ /*stick a fork in it, we're done.*/ + do y=0 for ysize; im=minim+stepy*y + $= + do x=0 for xsize + re=minre+stepx*x; zr=re; zi=im + + do n=0 for 30; a=zr**2; b=zi**2 + if a+b>4 then leave + zi=2*zr*zi+im; zr=a-b+re + end /*n*/ + + $=$ || d2c(62-n) /*append number (as a char) to $ string*/ + end /*x*/ + say $ /*display a line of character output. */ + end /*y*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Map-range/CoffeeScript/map-range.coffee b/Task/Map-range/CoffeeScript/map-range.coffee new file mode 100644 index 0000000000..6313b58252 --- /dev/null +++ b/Task/Map-range/CoffeeScript/map-range.coffee @@ -0,0 +1,5 @@ +mapRange = (a1,a2,b1,b2,s) -> + t = b1 + ((s-a1)*(b2 - b1)/(a2-a1)) + +for s in [0..10] + console.log("#{s} maps to #{mapRange(0,10,-1,0,s)}") diff --git a/Task/Map-range/Elixir/map-range.elixir b/Task/Map-range/Elixir/map-range.elixir new file mode 100644 index 0000000000..5f2e9687fa --- /dev/null +++ b/Task/Map-range/Elixir/map-range.elixir @@ -0,0 +1,9 @@ +defmodule RC do + def map_range(a1 .. a2, b1 .. b2, s) do + b1 + (s - a1) * (b2 - b1) / (a2 - a1) + end +end + +Enum.each(0..10, fn s -> + :io.format "~2w map to ~7.3f~n", [s, RC.map_range(0..10, -1..0, s)] +end) diff --git a/Task/Map-range/Perl-6/map-range-1.pl6 b/Task/Map-range/Perl-6/map-range-1.pl6 index 56acf4ab34..39be10dbb7 100644 --- a/Task/Map-range/Perl-6/map-range-1.pl6 +++ b/Task/Map-range/Perl-6/map-range-1.pl6 @@ -1,8 +1,7 @@ -use v6; -# Author: P. Seebauer -sub the_function(Range $a, Range $b, $s ) { - my ($a1, $a2, $b1, $b2) = ($a, $b)».bounds; +sub the_function(Range $a, Range $b, $s) { + my ($a1, $a2) = $a.bounds; + my ($b1, $b2) = $b.bounds; return $b1 + (($s-$a1) * ($b2-$b1) / ($a2-$a1)); } -for ^11 -> $x {say "$x maps to {the_function(0..10,-1..0, $x)}"} +for ^11 -> $x { say "$x maps to {the_function(0..10, -1..0, $x)}" } diff --git a/Task/Map-range/Perl-6/map-range-2.pl6 b/Task/Map-range/Perl-6/map-range-2.pl6 index b0a9578f0c..c9dfd13b6b 100644 --- a/Task/Map-range/Perl-6/map-range-2.pl6 +++ b/Task/Map-range/Perl-6/map-range-2.pl6 @@ -1,5 +1,6 @@ sub getmapper(Range $a, Range $b) { - my ($a1, $a2, $b1, $b2) = ($a, $b)».bounds; + my ($a1, $a2) = $a.bounds; + my ($b1, $b2) = $b.bounds; return -> $s { $b1 + (($s-$a1) * ($b2-$b1) / ($a2-$a1)) } } diff --git a/Task/Map-range/REXX/map-range-1.rexx b/Task/Map-range/REXX/map-range-1.rexx index 3730129900..bd66eca1ba 100644 --- a/Task/Map-range/REXX/map-range-1.rexx +++ b/Task/Map-range/REXX/map-range-1.rexx @@ -1,12 +1,11 @@ -/*REXX program maps a number from one range to another range. */ - -rangeA = '0 10' -rangeB = '-1 0' - - do j=0 to 10 - say right(j,3) ' maps to ' mapRange(rangeA, rangeB, j) +/*REXX program maps a range of numbers from one range to another range. */ +rangeA = 0 10 /*or: rangeA = ' 0 10 ' */ +rangeB = -1 0 /*or: rangeB = " -1 0 " */ +parse var RangeA L H +inc=1 + do j=L to H by inc*(1-2*sign(H (SqMat $m, Int $n is copy where { $_ >= 0 }) { multi show (SqMat $m) { my $size = 1; - for ^$m X ^$m -> $i, $j { $size max= $m[$i][$j].Str.chars; } + for ^$m X ^$m -> ($i, $j) { $size max= $m[$i][$j].Str.chars; } say join "\n", $m».fmt("%{$size}s"); } diff --git a/Task/Matrix-multiplication/360-Assembly/matrix-multiplication.360 b/Task/Matrix-multiplication/360-Assembly/matrix-multiplication.360 new file mode 100644 index 0000000000..7595beb5af --- /dev/null +++ b/Task/Matrix-multiplication/360-Assembly/matrix-multiplication.360 @@ -0,0 +1,106 @@ +* Matrix multiplication 06/08/2015 +MATRIXRC CSECT Matrix multiplication + USING MATRIXRC,R13 +SAVEARA B STM-SAVEARA(R15) + DC 17F'0' +STM STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 + LA R7,1 i=1 +LOOPI1 CH R7,M do i=1 to m (R7) + BH ELOOPI1 + LA R8,1 j=1 +LOOPJ1 CH R8,P do j=1 to p (R8) + BH ELOOPJ1 + LR R1,R7 i + BCTR R1,0 + MH R1,P + LR R6,R8 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + LA R6,0 + ST R6,C(R1) c(i,j)=0 + LA R9,1 k=1 +LOOPK1 CH R9,N do k=1 to n (R9) + BH ELOOPK1 + LR R1,R7 i + BCTR R1,0 + MH R1,P + LR R6,R8 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R2,C(R1) R2=c(i,j) + LR R10,R1 R10=offset(i,j) + LR R1,R7 i + BCTR R1,0 + MH R1,N + LR R6,R9 k + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R3,A(R1) R3=a(i,k) + LR R1,R9 k + BCTR R1,0 + MH R1,P + LR R6,R8 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R4,B(R1) R4=b(k,j) + LR R15,R3 a(i,k) + MR R14,R4 a(i,k)*b(k,j) + LR R3,R15 + AR R2,R3 R2=R2+a(i,k)*b(k,j) + ST R2,C(R10) c(i,j)=c(i,j)+a(i,k)*b(k,j) + LA R9,1(R9) k=k+1 + B LOOPK1 +ELOOPK1 LA R8,1(R8) j=j+1 + B LOOPJ1 +ELOOPJ1 LA R7,1(R7) i=i+1 + B LOOPI1 +ELOOPI1 MVC Z,=CL80' ' clear buffer + LA R7,1 +LOOPI2 CH R7,M do i=1 to m + BH ELOOPI2 + LA R8,1 +LOOPJ2 CH R8,P do j=1 to p + BH ELOOPJ2 + LR R1,R7 i + BCTR R1,0 + MH R1,P + LR R6,R8 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R6,C(R1) c(i,j) + LA R3,Z + AH R3,IZ + XDECO R6,W + MVC 0(5,R3),W+7 output c(i,j) + LH R3,IZ + LA R3,5(R3) + STH R3,IZ + LA R8,1(R8) j=j+1 + B LOOPJ2 +ELOOPJ2 XPRNT Z,80 print buffer + MVC IZ,=H'0' + LA R7,1(R7) i=i+1 + B LOOPI2 +ELOOPI2 L R13,4(0,R13) + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8' a(4,2) +B DC F'1',F'2',F'3',F'4',F'5',F'6' b(2,3) +C DS 12F c(4,3) +N DC H'2' dim(a,2)=dim(b,1) +M DC H'4' dim(a,1) +P DC H'3' dim(b,2) +Z DS CL80 +IZ DC H'0' +W DS CL16 + YREGS + END MATRIXRC diff --git a/Task/Matrix-multiplication/BASIC/matrix-multiplication.basic b/Task/Matrix-multiplication/BASIC/matrix-multiplication.basic new file mode 100644 index 0000000000..6bf054166f --- /dev/null +++ b/Task/Matrix-multiplication/BASIC/matrix-multiplication.basic @@ -0,0 +1,24 @@ +Assume the matrices to be multiplied are a and b + IF (LEN(a,2) = LEN(b)) 'if valid dims + n = LEN(a,2) + m = LEN(a) + p = LEN(b,2) + + DIM ans(0 TO m - 1, 0 TO p - 1) + + FOR i = 0 TO m - 1 + FOR j = 0 TO p - 1 + FOR k = 0 TO n - 1 + ans(i, j) = ans(i, j) + (a(i, k) * b(k, j)) + NEXT k, j, i + + 'print answer + FOR i = 0 TO m - 1 + FOR j = 0 TO p - 1 + PRINT ans(i, j); + NEXT j + PRINT + NEXT i + ELSE + PRINT "invalid dimensions" + END IF diff --git a/Task/Matrix-multiplication/Erlang/matrix-multiplication.erl b/Task/Matrix-multiplication/Erlang/matrix-multiplication.erl new file mode 100644 index 0000000000..5d979f303e --- /dev/null +++ b/Task/Matrix-multiplication/Erlang/matrix-multiplication.erl @@ -0,0 +1,57 @@ +%% Multiplies two matrices. Usage example: +%% $ matrix:multiply([[1,2,3],[4,5,6]], [[4,4],[0,0],[1,4]]) +%% If the dimentions are incompatible, an error is thrown. +%% +%% The erl shell may encode the lists output as strings. In order to prevent such +%% behaviour, BEFORE running matrix:multiply, run shell:strings(false) to disable +%% auto-encoding. When finished, run shell:strings(true) to reset the defaults. + +-module(matrix). +-export([multiply/2]). + +transpose([[]|_]) -> + []; +transpose(B) -> + [lists:map(fun hd/1, B) | transpose(lists:map(fun tl/1, B))]. + + +red(Pair, Sum) -> + X = element(1, Pair), %gets X + Y = element(2, Pair), %gets Y + X * Y + Sum. + +%% Mathematical dot product. A x B = d +%% A, B = 1-dimension vector +%% d = scalar +dot_product(A, B) -> + lists:foldl(fun red/2, 0, lists:zip(A, B)). + + +%% Exposed function. Expected result is C = A x B. +multiply(A, B) -> + %% First transposes B, to facilitate the calculations (It's easier to fetch + %% row than column wise). + multiply_internal(A, transpose(B)). + + +%% This function does the actual multiplication, but expects the second matrix +%% to be transposed. +multiply_internal([Head | Rest], B) -> + % multiply each row by Y + Element = multiply_row_by_col(Head, B), + + % concatenate the result of this multiplication with the next ones + [Element | multiply_internal(Rest, B)]; + +multiply_internal([], B) -> + % concatenating and empty list to the end of a list, changes nothing. + []. + + +multiply_row_by_col(Row, [Col_Head | Col_Rest]) -> + Scalar = dot_product(Row, Col_Head), + + [Scalar | multiply_row_by_col(Row, Col_Rest)]; + +multiply_row_by_col(Row, []) -> + []. diff --git a/Task/Matrix-multiplication/Go/matrix-multiplication-1.go b/Task/Matrix-multiplication/Go/matrix-multiplication-1.go index 3d279e29da..e8ae47efdb 100644 --- a/Task/Matrix-multiplication/Go/matrix-multiplication-1.go +++ b/Task/Matrix-multiplication/Go/matrix-multiplication-1.go @@ -1,54 +1,23 @@ package main -import "fmt" +import ( + "fmt" -type Value float64 -type Matrix [][]Value - -func Multiply(m1, m2 Matrix) (m3 Matrix, ok bool) { - rows, cols, extra := len(m1), len(m2[0]), len(m2) - if len(m1[0]) != extra { return nil, false } - m3 = make(Matrix, rows) - for i := 0; i < rows; i++ { - m3[i] = make([]Value,cols) - for j := 0; j < cols; j++ { - for k := 0; k < extra; k++ { - m3[i][j] += m1[i][k] * m2[k][j] - } - } - } - return m3, true -} - -func (m Matrix) String() string { - rows := len(m) - cols := len(m[0]) - out := "[" - for r := 0; r < rows; r++ { - if r > 0 { out += ",\n " } - out += "[ " - for c := 0; c < cols; c++ { - if c > 0 { out += ", " } - out += fmt.Sprintf("%7.3f", m[r][c]) - } - out += " ]" - } - out += "]" - return out -} + "github.com/gonum/matrix/mat64" +) func main() { - A := Matrix{[]Value{1, 1, 1, 1}, - []Value{2, 4, 8, 16}, - []Value{3, 9, 27, 81}, - []Value{4, 16, 64, 256}} - B := Matrix{[]Value{ 4.0 , -3.0 , 4.0/3, -1.0/4 }, - []Value{-13.0/3, 19.0/4, -7.0/3, 11.0/24}, - []Value{ 3.0/2, -2.0 , 7.0/6, -1.0/4 }, - []Value{ -1.0/6, 1.0/4, -1.0/6, 1.0/24}} - P,ok := Multiply(A,B) - if !ok { panic("Invalid dimensions") } - fmt.Printf("Matrix A:\n%s\n\n", A) - fmt.Printf("Matrix B:\n%s\n\n", B) - fmt.Printf("Product of A and B:\n%s\n\n", P) + a := mat64.NewDense(2, 4, []float64{ + 1, 2, 3, 4, + 5, 6, 7, 8, + }) + b := mat64.NewDense(4, 3, []float64{ + 1, 2, 3, + 4, 5, 6, + 7, 8, 9, + 10, 11, 12, + }) + var m mat64.Dense + m.Mul(a, b) + fmt.Println(mat64.Formatted(&m)) } diff --git a/Task/Matrix-multiplication/Go/matrix-multiplication-2.go b/Task/Matrix-multiplication/Go/matrix-multiplication-2.go index d934b0f7bc..5bf3e59a91 100644 --- a/Task/Matrix-multiplication/Go/matrix-multiplication-2.go +++ b/Task/Matrix-multiplication/Go/matrix-multiplication-2.go @@ -1,89 +1,28 @@ package main -import "fmt" +import ( + "fmt" -type matrix struct { - ele []float64 - stride int -} - -func matrixFromRows(rows [][]float64) *matrix { - if len(rows) == 0 { - return &matrix{nil, 0} - } - m := &matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])} - for rx, row := range rows { - copy(m.ele[rx*m.stride:(rx+1)*m.stride], row) - } - return m -} - -func (m *matrix) print(heading string) { - if heading > "" { - fmt.Print("\n", heading, "\n") - } - for e := 0; e < len(m.ele); e += m.stride { - fmt.Printf("%6.3f ", m.ele[e:e+m.stride]) - fmt.Println() - } -} - -func (m1 *matrix) multiply(m2 *matrix) (m3 *matrix, ok bool) { - if m1.stride*m2.stride != len(m2.ele) { - return nil, false - } - m3 = &matrix{make([]float64, (len(m1.ele)/m1.stride)*m2.stride), m2.stride} - for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.stride { - for m2r0 := 0; m2r0 < m2.stride; m2r0++ { - for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.stride { - m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x] - m1x++ - } - m3x++ - } - } - return m3, true -} + mat "github.com/skelterjohn/go.matrix" +) func main() { - a := matrixFromRows([][]float64{ - {1, 1, 1, 1}, - {2, 4, 8, 16}, - {3, 9, 27, 81}, - {4, 16, 64, 256}, + a := mat.MakeDenseMatrixStacked([][]float64{ + {1, 2, 3, 4}, + {5, 6, 7, 8}, }) - b := matrixFromRows([][]float64{ - { - 4, - -3, - 4. / 3, - -1. / 4, - }, - { - -13. / 3, - 19. / 4, - -7. / 3, - 11. / 24, - }, - { - 3. / 2, - -2, - 7. / 6, - -1. / 4, - }, - { - -1. / 6, - 1. / 4, - -1. / 6, - 1. / 24, - }, + b := mat.MakeDenseMatrixStacked([][]float64{ + {1, 2, 3}, + {4, 5, 6}, + {7, 8, 9}, + {10, 11, 12}, }) - p, ok := a.multiply(b) - a.print("Matrix A:") - b.print("Matrix B:") - if !ok { - fmt.Println("not conformable for matrix multiplication") + fmt.Printf("Matrix A:\n%v\n", a) + fmt.Printf("Matrix B:\n%v\n", b) + p, err := a.TimesDense(b) + if err != nil { + fmt.Println(err) return } - p.print("Product of A and B:") + fmt.Printf("Product of A and B:\n%v\n", p) } diff --git a/Task/Matrix-multiplication/Go/matrix-multiplication-3.go b/Task/Matrix-multiplication/Go/matrix-multiplication-3.go index 713bd78617..bbb03fb3c7 100644 --- a/Task/Matrix-multiplication/Go/matrix-multiplication-3.go +++ b/Task/Matrix-multiplication/Go/matrix-multiplication-3.go @@ -1,50 +1,60 @@ package main -import ( - "fmt" +import "fmt" - mat "github.com/skelterjohn/go.matrix" -) +type Value float64 +type Matrix [][]Value + +func Multiply(m1, m2 Matrix) (m3 Matrix, ok bool) { + rows, cols, extra := len(m1), len(m2[0]), len(m2) + if len(m1[0]) != extra { + return nil, false + } + m3 = make(Matrix, rows) + for i := 0; i < rows; i++ { + m3[i] = make([]Value, cols) + for j := 0; j < cols; j++ { + for k := 0; k < extra; k++ { + m3[i][j] += m1[i][k] * m2[k][j] + } + } + } + return m3, true +} + +func (m Matrix) String() string { + rows := len(m) + cols := len(m[0]) + out := "[" + for r := 0; r < rows; r++ { + if r > 0 { + out += ",\n " + } + out += "[ " + for c := 0; c < cols; c++ { + if c > 0 { + out += ", " + } + out += fmt.Sprintf("%7.3f", m[r][c]) + } + out += " ]" + } + out += "]" + return out +} func main() { - a := mat.MakeDenseMatrixStacked([][]float64{ - {1, 1, 1, 1}, - {2, 4, 8, 16}, - {3, 9, 27, 81}, - {4, 16, 64, 256}, - }) - b := mat.MakeDenseMatrixStacked([][]float64{ - { - 4, - -3, - 4. / 3, - -1. / 4, - }, - { - -13. / 3, - 19. / 4, - -7. / 3, - 11. / 24, - }, - { - 3. / 2, - -2, - 7. / 6, - -1. / 4, - }, - { - -1. / 6, - 1. / 4, - -1. / 6, - 1. / 24, - }, - }) - p, err := a.TimesDense(b) - fmt.Printf("Matrix A:\n%v\n", a) - fmt.Printf("Matrix B:\n%v\n", b) - if err != nil { - fmt.Println(err) - return + A := Matrix{[]Value{1, 2, 3, 4}, + []Value{5, 6, 7, 8}} + B := Matrix{[]Value{1, 2, 3}, + []Value{4, 5, 6}, + []Value{7, 8, 9}, + []Value{10, 11, 12}} + P, ok := Multiply(A, B) + if !ok { + panic("Invalid dimensions") } - fmt.Printf("Product of A and B:\n%v\n", p) + fmt.Printf("Matrix A:\n%s\n\n", A) + fmt.Printf("Matrix B:\n%s\n\n", B) + fmt.Printf("Product of A and B:\n%s\n\n", P) } diff --git a/Task/Matrix-multiplication/Go/matrix-multiplication-4.go b/Task/Matrix-multiplication/Go/matrix-multiplication-4.go new file mode 100644 index 0000000000..15b88440db --- /dev/null +++ b/Task/Matrix-multiplication/Go/matrix-multiplication-4.go @@ -0,0 +1,56 @@ +package main + +import "fmt" + +type matrix struct { + stride int + ele []float64 +} + +func (m *matrix) print(heading string) { + if heading > "" { + fmt.Print("\n", heading, "\n") + } + for e := 0; e < len(m.ele); e += m.stride { + fmt.Printf("%8.3f ", m.ele[e:e+m.stride]) + fmt.Println() + } +} + +func (m1 *matrix) multiply(m2 *matrix) (m3 *matrix, ok bool) { + if m1.stride*m2.stride != len(m2.ele) { + return nil, false + } + m3 = &matrix{m2.stride, make([]float64, (len(m1.ele)/m1.stride)*m2.stride)} + for m1c0, m3x := 0, 0; m1c0 < len(m1.ele); m1c0 += m1.stride { + for m2r0 := 0; m2r0 < m2.stride; m2r0++ { + for m1x, m2x := m1c0, m2r0; m2x < len(m2.ele); m2x += m2.stride { + m3.ele[m3x] += m1.ele[m1x] * m2.ele[m2x] + m1x++ + } + m3x++ + } + } + return m3, true +} + +func main() { + a := matrix{4, []float64{ + 1, 2, 3, 4, + 5, 6, 7, 8, + }} + b := matrix{3, []float64{ + 1, 2, 3, + 4, 5, 6, + 7, 8, 9, + 10, 11, 12, + }} + p, ok := a.multiply(&b) + a.print("Matrix A:") + b.print("Matrix B:") + if !ok { + fmt.Println("not conformable for matrix multiplication") + return + } + p.print("Product of A and B:") +} diff --git a/Task/Matrix-multiplication/Perl-6/matrix-multiplication-1.pl6 b/Task/Matrix-multiplication/Perl-6/matrix-multiplication-1.pl6 index d4d3b23915..2678b29629 100644 --- a/Task/Matrix-multiplication/Perl-6/matrix-multiplication-1.pl6 +++ b/Task/Matrix-multiplication/Perl-6/matrix-multiplication-1.pl6 @@ -1,6 +1,6 @@ sub mmult(@a,@b) { my @p; - for ^@a X ^@b[0] -> $r, $c { + for ^@a X ^@b[0] -> ($r, $c) { @p[$r][$c] += @a[$r][$_] * @b[$_][$c] for ^@b; } @p; diff --git a/Task/Matrix-multiplication/Perl-6/matrix-multiplication-2.pl6 b/Task/Matrix-multiplication/Perl-6/matrix-multiplication-2.pl6 index 8bea3988d2..ce04afc575 100644 --- a/Task/Matrix-multiplication/Perl-6/matrix-multiplication-2.pl6 +++ b/Task/Matrix-multiplication/Perl-6/matrix-multiplication-2.pl6 @@ -1,7 +1,11 @@ -sub mmult(@a,@b) { - for ^@a -> $r {[ - for ^@b[0] -> $c { - [+] (@a[$r][^@b] Z* @b[^@b]»[$c]) +sub mmult(\a,\b) { + [ + for ^a -> \r { + [ + for ^b[0] -> \c { + [+] a[r;^b] Z* b[^b;c] + } + ] } - ]} + ] } diff --git a/Task/Matrix-multiplication/PowerShell/matrix-multiplication.psh b/Task/Matrix-multiplication/PowerShell/matrix-multiplication.psh new file mode 100644 index 0000000000..49ab23d852 --- /dev/null +++ b/Task/Matrix-multiplication/PowerShell/matrix-multiplication.psh @@ -0,0 +1,31 @@ +function array-mult($A, $B) { + $C = @() + if($n -gt 0) { + $C = 0..($n-1)| foreach{@(0)} + 0..($n-1)| foreach{ + $i = $_ + $C[$i] = 0..($n-1)| foreach{ + $j = $_ + $((0..($n-1) | foreach{ + $k = $_ + $A[$i][$k]*$B[$k][$j] + } | measure -Sum).Sum) + } + } + } + $C +} +function show($a) { + if($a.Count -gt 0) { + $n = $a.Count - 1 + 0..$n | foreach{ "$($a[$_][0..$n])" } + } +} +$A = @(@(1,2),@(3,4)) +$B = @(@(5,6),@(7,8)) +$I = @(@(1,0),@(0,1)) +$C = array-mult $A $B +$D = array-mult $A $I +show $C +" " +show $D diff --git a/Task/Matrix-multiplication/REXX/matrix-multiplication.rexx b/Task/Matrix-multiplication/REXX/matrix-multiplication.rexx index 1b3e966be9..0da25b7ab9 100644 --- a/Task/Matrix-multiplication/REXX/matrix-multiplication.rexx +++ b/Task/Matrix-multiplication/REXX/matrix-multiplication.rexx @@ -1,39 +1,37 @@ -/*REXX program multiplies 2 matrixes together, shows matrixes and result*/ -x. = /*the beginnings of the A matrix.*/ -x.1 = 1 2 /*╔═════════════════════════════╗*/ -x.2 = 3 4 /*║As none of the values haven't║*/ -x.3 = 5 6 /*║a sign, quotes aren't needed.║*/ -x.4 = 7 8 /*╚═════════════════════════════╝*/ - do r=1 while x.r\=='' /*build the "A" matric from X. #s*/ - do c=1 while x.r\==''; parse var x.r a.r.c x.r; end - end /*r*/ -Arows=r-1 /*adjust number of rows (DO loop)*/ -Acols=c-1 /* " " " cols " " */ -y. = /*the beginnings of the B matrix.*/ -y.1 = 1 2 3 -y.2 = 4 5 6 - do r=1 while y.r\=='' /*build the "B" matric from Y. #s*/ - do c=1 while y.r\==''; parse var y.r b.r.c y.r; end - end -Brows=r-1 /*adjust number of rows (DO loop)*/ -Bcols=c-1 /* " " " cols " " */ -c.=0; L=0 /*L is max width of an element.*/ - do i =1 for Arows /*multiply matrix A & B ──► C */ - do j =1 for Bcols +/*REXX program multiplies two matrices together, displays matrices and result.*/ +x.=; x.1=1 2 /*╔═══════════════════════════════════╗*/ + x.2=3 4 /*║ As none of the matrix values have ║*/ + x.3=5 6 /*║ a sign, quotes aren't needed. ║*/ + x.4=7 8 /*╚═══════════════════════════════════╝*/ + do r=1 while x.r\=='' /*build the "A" matrix from X. numbers.*/ + do c=1 while x.r\==''; parse var x.r a.r.c x.r; end + end /*r*/ +Arows=r-1 /*adjust the number of rows (DO loop).*/ +Acols=c-1 /* " " " " cols " " .*/ +y.=; y.1=1 2 3 + y.2=4 5 6 + do r=1 while y.r\=='' /*build the "B" matrix from Y. numbers.*/ + do c=1 while y.r\==''; parse var y.r b.r.c y.r; end + end /*r*/ +Brows=r-1 /*adjust the number of rows (DO loop).*/ +Bcols=c-1 /* " " " " cols " " */ +c.=0; w=0 /*W is max width of an matrix element.*/ + do i=1 for Arows /*multiply matrix A and B ───► C */ + do j=1 for Bcols do k=1 for Acols - c.i.j = c.i.j + a.i.k * b.k.j; L=max(L,length(c.i.j)) + c.i.j = c.i.j + a.i.k * b.k.j; w=max(w, length(c.i.j)) end /*k*/ end /*j*/ end /*i*/ -call showMatrix 'A', Arows, Acols /*display matrix A ───► terminal.*/ -call showMatrix 'B', Brows, Bcols /* " " B ───► " */ -call showMatrix 'C', Arows, Bcols /* " " C ───► " */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SHOWMATRIX subroutine───────────────*/ -showMatrix: parse arg mat,rows,cols; say -say center(mat 'matrix',cols*(L+1)+4,"─") - do r =1 for rows; _= - do c=1 for cols; _=_ right(value(mat'.'r'.'c),L); end; say _ - end /*r*/ +call showMatrix 'A', Arows, Acols /*display matrix A ───► the terminal.*/ +call showMatrix 'B', Brows, Bcols /* " " B ───► " " */ +call showMatrix 'C', Arows, Bcols /* " " C ───► " " */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +showMatrix: parse arg mat,rows,cols; say +say center(mat 'matrix', cols*(w+1)+4, "─") + do r =1 for rows; _= + do c=1 for cols; _=_ right(value(mat'.'r'.'c), w); end; say _ + end /*r*/ return diff --git a/Task/Matrix-multiplication/VBScript/matrix-multiplication.vb b/Task/Matrix-multiplication/VBScript/matrix-multiplication.vb new file mode 100644 index 0000000000..f86de4287d --- /dev/null +++ b/Task/Matrix-multiplication/VBScript/matrix-multiplication.vb @@ -0,0 +1,19 @@ +Dim matrix1(2,2) +matrix1(0,0) = 3 : matrix1(0,1) = 7 : matrix1(0,2) = 4 +matrix1(1,0) = 5 : matrix1(1,1) = -2 : matrix1(1,2) = 9 +matrix1(2,0) = 8 : matrix1(2,1) = -6 : matrix1(2,2) = -5 +Dim matrix2(2,2) +matrix2(0,0) = 9 : matrix2(0,1) = 2 : matrix2(0,2) = 1 +matrix2(1,0) = -7 : matrix2(1,1) = 3 : matrix2(1,2) = -10 +matrix2(2,0) = 4 : matrix2(2,1) = 5 : matrix2(2,2) = -6 + +Call multiply_matrix(matrix1,matrix2) + +Sub multiply_matrix(arr1,arr2) + For i = 0 To UBound(arr1) + For j = 0 To 2 + WScript.StdOut.Write (arr1(i,j) * arr2(i,j)) & vbTab + Next + WScript.StdOut.WriteLine + Next +End Sub diff --git a/Task/Matrix-transposition/Elixir/matrix-transposition.elixir b/Task/Matrix-transposition/Elixir/matrix-transposition.elixir new file mode 100644 index 0000000000..ce832b9beb --- /dev/null +++ b/Task/Matrix-transposition/Elixir/matrix-transposition.elixir @@ -0,0 +1,9 @@ +m = [[1, 1, 1, 1], + [2, 4, 8, 16], + [3, 9, 27, 81], + [4, 16, 64, 256], + [5, 25,125, 625]] + +transpose = fn(m)-> List.zip(m) |> Enum.map(&Tuple.to_list(&1)) end + +IO.inspect transpose.(m) diff --git a/Task/Matrix-transposition/Go/matrix-transposition-1.go b/Task/Matrix-transposition/Go/matrix-transposition-1.go index 7c5451ca5d..ef2acadb3e 100644 --- a/Task/Matrix-transposition/Go/matrix-transposition-1.go +++ b/Task/Matrix-transposition/Go/matrix-transposition-1.go @@ -1,35 +1,17 @@ package main -import "fmt" +import ( + "fmt" -type row []float64 -type matrix []row + "github.com/gonum/matrix/mat64" +) func main() { - m := matrix{ - {1, 2, 3}, - {4, 5, 6}, - } - printMatrix(m) - t := transpose(m) - printMatrix(t) -} - -func printMatrix(m matrix) { - for _, s := range m { - fmt.Println(s) - } -} - -func transpose(m matrix) matrix { - r := make(matrix, len(m[0])) - for x, _ := range r { - r[x] = make(row, len(m)) - } - for y, s := range m { - for x, e := range s { - r[x][y] = e - } - } - return r + m := mat64.NewDense(2, 3, []float64{ + 1, 2, 3, + 4, 5, 6, + }) + fmt.Println(mat64.Formatted(m)) + fmt.Println() + fmt.Println(mat64.Formatted(m.T())) } diff --git a/Task/Matrix-transposition/Go/matrix-transposition-2.go b/Task/Matrix-transposition/Go/matrix-transposition-2.go index e8f14e7514..818b73ad31 100644 --- a/Task/Matrix-transposition/Go/matrix-transposition-2.go +++ b/Task/Matrix-transposition/Go/matrix-transposition-2.go @@ -1,51 +1,19 @@ package main -import "fmt" +import ( + "fmt" -type matrix struct { - ele []float64 - stride int -} - -// construct new matrix from slice of slices -func matrixFromRows(rows [][]float64) *matrix { - if len(rows) == 0 { - return &matrix{nil, 0} - } - m := &matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])} - for rx, row := range rows { - copy(m.ele[rx*m.stride:(rx+1)*m.stride], row) - } - return m -} + mat "github.com/skelterjohn/go.matrix" +) func main() { - m := matrixFromRows([][]float64{ + m := mat.MakeDenseMatrixStacked([][]float64{ {1, 2, 3}, {4, 5, 6}, }) - m.print("original:") - m.transpose().print("transpose:") -} - -func (m *matrix) print(heading string) { - if heading > "" { - fmt.Print("\n", heading, "\n") - } - for e := 0; e < len(m.ele); e += m.stride { - fmt.Println(m.ele[e : e+m.stride]) - } -} - -func (m *matrix) transpose() *matrix { - r := &matrix{make([]float64, len(m.ele)), len(m.ele) / m.stride} - rx := 0 - for _, e := range m.ele { - r.ele[rx] = e - rx += r.stride - if rx >= len(r.ele) { - rx -= len(r.ele) - 1 - } - } - return r + fmt.Println("original:") + fmt.Println(m) + m = m.Transpose() + fmt.Println("transpose:") + fmt.Println(m) } diff --git a/Task/Matrix-transposition/Go/matrix-transposition-3.go b/Task/Matrix-transposition/Go/matrix-transposition-3.go index 22fd55b44e..7c5451ca5d 100644 --- a/Task/Matrix-transposition/Go/matrix-transposition-3.go +++ b/Task/Matrix-transposition/Go/matrix-transposition-3.go @@ -2,72 +2,34 @@ package main import "fmt" -type matrix struct { - ele []float64 - stride int -} - -// construct new matrix from slice of slices -func matrixFromRows(rows [][]float64) *matrix { - if len(rows) == 0 { - return &matrix{nil, 0} - } - m := &matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])} - for rx, row := range rows { - copy(m.ele[rx*m.stride:(rx+1)*m.stride], row) - } - return m -} +type row []float64 +type matrix []row func main() { - m := matrixFromRows([][]float64{ + m := matrix{ {1, 2, 3}, {4, 5, 6}, - }) - m.print("original:") - m.transposeInPlace() - m.print("transpose:") + } + printMatrix(m) + t := transpose(m) + printMatrix(t) } -func (m *matrix) print(heading string) { - if heading > "" { - fmt.Print("\n", heading, "\n") - } - for e := 0; e < len(m.ele); e += m.stride { - fmt.Println(m.ele[e : e+m.stride]) +func printMatrix(m matrix) { + for _, s := range m { + fmt.Println(s) } } -func (m *matrix) transposeInPlace() { - h := len(m.ele) / m.stride - for start := range m.ele { - next := start - i := 0 - for { - i++ - next = (next%h)*m.stride + next/h - if next <= start { - break - } - } - if next < start || i == 1 { - continue - } - - next = start - tmp := m.ele[next] - for { - i = (next%h)*m.stride + next/h - if i == start { - m.ele[next] = tmp - } else { - m.ele[next] = m.ele[i] - } - next = i - if next <= start { - break - } +func transpose(m matrix) matrix { + r := make(matrix, len(m[0])) + for x, _ := range r { + r[x] = make(row, len(m)) + } + for y, s := range m { + for x, e := range s { + r[x][y] = e } } - m.stride = h + return r } diff --git a/Task/Matrix-transposition/Go/matrix-transposition-4.go b/Task/Matrix-transposition/Go/matrix-transposition-4.go index 818b73ad31..e8f14e7514 100644 --- a/Task/Matrix-transposition/Go/matrix-transposition-4.go +++ b/Task/Matrix-transposition/Go/matrix-transposition-4.go @@ -1,19 +1,51 @@ package main -import ( - "fmt" +import "fmt" - mat "github.com/skelterjohn/go.matrix" -) +type matrix struct { + ele []float64 + stride int +} + +// construct new matrix from slice of slices +func matrixFromRows(rows [][]float64) *matrix { + if len(rows) == 0 { + return &matrix{nil, 0} + } + m := &matrix{make([]float64, len(rows)*len(rows[0])), len(rows[0])} + for rx, row := range rows { + copy(m.ele[rx*m.stride:(rx+1)*m.stride], row) + } + return m +} func main() { - m := mat.MakeDenseMatrixStacked([][]float64{ + m := matrixFromRows([][]float64{ {1, 2, 3}, {4, 5, 6}, }) - fmt.Println("original:") - fmt.Println(m) - m = m.Transpose() - fmt.Println("transpose:") - fmt.Println(m) + m.print("original:") + m.transpose().print("transpose:") +} + +func (m *matrix) print(heading string) { + if heading > "" { + fmt.Print("\n", heading, "\n") + } + for e := 0; e < len(m.ele); e += m.stride { + fmt.Println(m.ele[e : e+m.stride]) + } +} + +func (m *matrix) transpose() *matrix { + r := &matrix{make([]float64, len(m.ele)), len(m.ele) / m.stride} + rx := 0 + for _, e := range m.ele { + r.ele[rx] = e + rx += r.stride + if rx >= len(r.ele) { + rx -= len(r.ele) - 1 + } + } + return r } diff --git a/Task/Matrix-transposition/Go/matrix-transposition-5.go b/Task/Matrix-transposition/Go/matrix-transposition-5.go new file mode 100644 index 0000000000..30c235a753 --- /dev/null +++ b/Task/Matrix-transposition/Go/matrix-transposition-5.go @@ -0,0 +1,61 @@ +package main + +import "fmt" + +type matrix struct { + stride int + ele []float64 +} + +func main() { + m := matrix{3, []float64{ + 1, 2, 3, + 4, 5, 6, + }} + m.print("original:") + m.transposeInPlace() + m.print("transpose:") +} + +func (m *matrix) print(heading string) { + if heading > "" { + fmt.Print("\n", heading, "\n") + } + for e := 0; e < len(m.ele); e += m.stride { + fmt.Println(m.ele[e : e+m.stride]) + } +} + +func (m *matrix) transposeInPlace() { + h := len(m.ele) / m.stride + for start := range m.ele { + next := start + i := 0 + for { + i++ + next = (next%h)*m.stride + next/h + if next <= start { + break + } + } + if next < start || i == 1 { + continue + } + + next = start + tmp := m.ele[next] + for { + i = (next%h)*m.stride + next/h + if i == start { + m.ele[next] = tmp + } else { + m.ele[next] = m.ele[i] + } + next = i + if next <= start { + break + } + } + } + m.stride = h +} diff --git a/Task/Matrix-transposition/Perl-6/matrix-transposition-1.pl6 b/Task/Matrix-transposition/Perl-6/matrix-transposition-1.pl6 index 42d7b1d34c..e89a2f2d09 100644 --- a/Task/Matrix-transposition/Perl-6/matrix-transposition-1.pl6 +++ b/Task/Matrix-transposition/Perl-6/matrix-transposition-1.pl6 @@ -1,13 +1,13 @@ sub transpose(@m) { my @t; - for ^@m X ^@m[0] -> $x, $y { @t[$y][$x] = @m[$x][$y] } + for ^@m X ^@m[0] -> ($x, $y) { @t[$y][$x] = @m[$x][$y] } return @t; } # creates a random matrix my @a; -for (^10).pick X (^10).pick -> $x, $y { @a[$x][$y] = (^100).pick; } +for (^10).pick X (^10).pick -> ($x, $y) { @a[$x][$y] = (^100).pick; } say "original: "; .perl.say for @a; diff --git a/Task/Matrix-transposition/Perl-6/matrix-transposition-2.pl6 b/Task/Matrix-transposition/Perl-6/matrix-transposition-2.pl6 index e7a5896dba..03af3ef144 100644 --- a/Task/Matrix-transposition/Perl-6/matrix-transposition-2.pl6 +++ b/Task/Matrix-transposition/Perl-6/matrix-transposition-2.pl6 @@ -1,10 +1,10 @@ sub transpose (@m) { - @m[0].keys.map: {[ @m».[$_] ]}; + ([ @m[*;$_] ] for ^@m[0]); } -my @a = [< a b c d e >], - [< f g h i j >], - [< k l m n o >], - [< p q r s t >]; +my @a = < a b c d e >, + < f g h i j >, + < k l m n o >, + < p q r s t >; .say for @a.&transpose; diff --git a/Task/Matrix-transposition/PowerShell/matrix-transposition.psh b/Task/Matrix-transposition/PowerShell/matrix-transposition.psh new file mode 100644 index 0000000000..39b37e13c3 --- /dev/null +++ b/Task/Matrix-transposition/PowerShell/matrix-transposition.psh @@ -0,0 +1,23 @@ +function transpose($a) { + if($a.Count -gt 0) { + $n = $a.Count - 1 + foreach($i in 0..$n) { + $j = 0 + while($j -lt $i) { + $a[$i][$j], $a[$j][$i] = $a[$j][$i], $a[$i][$j] + $j++ + } + } + } + $a +} +function show($a) { + if($a.Count -gt 0) { + $n = $a.Count - 1 + 0..$n | foreach{ "$($a[$_][0..$n])" } + } +} +$a = @(@(2, 4, 7),@(3, 5, 9),@(4, 1, 6)) +show $a +"" +show (transpose $a) diff --git a/Task/Matrix-transposition/VBScript/matrix-transposition.vb b/Task/Matrix-transposition/VBScript/matrix-transposition.vb new file mode 100644 index 0000000000..bed6d47ca7 --- /dev/null +++ b/Task/Matrix-transposition/VBScript/matrix-transposition.vb @@ -0,0 +1,31 @@ +'create and display the initial matrix +WScript.StdOut.WriteLine "Initial Matrix:" +x = 4 : y = 6 : n = 1 +Dim matrix() +ReDim matrix(x,y) +For i = 0 To y + For j = 0 To x + matrix(j,i) = n + If j < x Then + WScript.StdOut.Write n & vbTab + Else + WScript.StdOut.Write n + End If + n = n + 1 + Next + WScript.StdOut.WriteLine +Next + +'display the trasposed matrix +WScript.StdOut.WriteBlankLines(1) +WScript.StdOut.WriteLine "Transposed Matrix:" +For i = 0 To x + For j = 0 To y + If j < y Then + WScript.StdOut.Write matrix(i,j) & vbTab + Else + WScript.StdOut.Write matrix(i,j) + End If + Next + WScript.StdOut.WriteLine +Next diff --git a/Task/Maximum-triangle-path-sum/00DESCRIPTION b/Task/Maximum-triangle-path-sum/00DESCRIPTION index 2c05aded4c..790127cb21 100644 --- a/Task/Maximum-triangle-path-sum/00DESCRIPTION +++ b/Task/Maximum-triangle-path-sum/00DESCRIPTION @@ -5,7 +5,9 @@ Starting from the top of a pyramid of numbers like this, you can walk down going 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. +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. diff --git a/Task/Maximum-triangle-path-sum/AutoHotkey/maximum-triangle-path-sum-1.ahk b/Task/Maximum-triangle-path-sum/AutoHotkey/maximum-triangle-path-sum-1.ahk new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Maximum-triangle-path-sum/AutoHotkey/maximum-triangle-path-sum-2.ahk b/Task/Maximum-triangle-path-sum/AutoHotkey/maximum-triangle-path-sum-2.ahk new file mode 100644 index 0000000000..f7cdd95318 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/AutoHotkey/maximum-triangle-path-sum-2.ahk @@ -0,0 +1,39 @@ +data :=[ +(join ltrim + 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 +)] + +i := data.MaxIndex() +row := Ceil((Sqrt(8*i+1) - 1) / 2) +path:=[] + +loop % row { + path[i] := data[i] + i-- +} + +while i { + row := Ceil((Sqrt(8*i+1) - 1) / 2) + path[i] := data[i] "+" (data[i+row] > data[i+row+1] ? path[i+row] : path[i+row+1]) + data[i] += data[i+row] > data[i+row+1] ? data[i+row] : data[i+row+1] + i -- +} + +MsgBox % data[1] "`n" path[1] diff --git a/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp b/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp index 880efae094..c4206cd013 100644 --- a/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp +++ b/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp @@ -24,20 +24,14 @@ int main( int argc, char* argv[] ) 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; + const int size = sizeof( triangle ) / sizeof( int ); + const int tn = static_cast(sqrt(2.0 * size)); + assert(tn * (tn + 1) == 2 * size); // size should be a triangular number + + // walk backward by rows, replacing each element with max attainable therefrom + for (int n = tn - 1; n > 0; --n) // n is size of row, note we do not process last row + for (int k = (n * (n-1)) / 2; k < (n * (n+2)) / 2; ++k) + triangle[k] += std::max(triangle[k + n], triangle[k + n + 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/Elixir/maximum-triangle-path-sum.elixir b/Task/Maximum-triangle-path-sum/Elixir/maximum-triangle-path-sum.elixir new file mode 100644 index 0000000000..221968d8cf --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Elixir/maximum-triangle-path-sum.elixir @@ -0,0 +1,36 @@ +defmodule Maximum do + def triangle_path(text) do + String.split(text, "\n", trim: true) + |> Enum.map(fn line -> String.split(line) |> Enum.map(&String.to_integer(&1)) end) + |> Enum.reduce([], fn x,total -> + Enum.chunk([0]++total++[0], 2, 1) + |> Enum.map(&Enum.max(&1)) + |> Enum.zip(x) + |> Enum.map(fn{a,b} -> a+b end) + end) + |> Enum.max + end +end + +text = """ + 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 +""" + +IO.puts Maximum.triangle_path(text) 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 index 0e169a5267..97b30830e2 100644 --- 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 @@ -1,2 +1,2 @@ -padTri=: 0 ". [: ];._2 ] NB. parse triangle and pad with zeros +padTri=: 0 ". ];._2 NB. parse triangle and (implicitly) 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-3.j b/Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-3.j new file mode 100644 index 0000000000..471a7a4ba2 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/J/maximum-triangle-path-sum-3.j @@ -0,0 +1 @@ +maxsum=: ((] + #@] {. [)2 >./\ ])/ diff --git a/Task/Maximum-triangle-path-sum/Lua/maximum-triangle-path-sum.lua b/Task/Maximum-triangle-path-sum/Lua/maximum-triangle-path-sum.lua new file mode 100644 index 0000000000..a1689da003 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Lua/maximum-triangle-path-sum.lua @@ -0,0 +1,52 @@ +local triangleSmall = { + { 55 }, + { 94, 48 }, + { 95, 30, 96 }, + { 77, 71, 26, 67 }, +} + +local triangleLarge = { + { 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 }, +}; + +function solve(triangle) + + -- Get total number of rows in triangle. + local nRows = table.getn(triangle) + + -- Start at 2nd-to-last row and work up to the top. + for row = nRows-1, 1, -1 do + + -- For each value in row, add the max of the 2 children beneath it. + for i = 1, row do + local child1 = triangle[row+1][i] + local child2 = triangle[row+1][i+1] + triangle[row][i] = triangle[row][i] + math.max(child1, child2) + end + + end + + -- The top of the triangle now holds the answer. + return triangle[1][1]; + +end + +print(solve(triangleSmall)) +print(solve(triangleLarge)) diff --git a/Task/Maximum-triangle-path-sum/PL-I/maximum-triangle-path-sum.pli b/Task/Maximum-triangle-path-sum/PL-I/maximum-triangle-path-sum.pli new file mode 100644 index 0000000000..b0bc64ce34 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/PL-I/maximum-triangle-path-sum.pli @@ -0,0 +1,42 @@ +*process source xref attributes or(!); + triang: Proc Options(Main); + Dcl nn(18,18) Bin Fixed(31); + Dcl (rows,i,j) Bin Fixed(31); + Dcl (p,k,kn) Bin Fixed(31); + Call f_r(1 ,' 55 '); + Call f_r(2 ,' 94 48 '); + Call f_r(3 ,' 95 30 96 '); + Call f_r(4 ,' 77 71 26 67 '); + Call f_r(5 ,' 97 13 76 38 45 '); + Call f_r(6 ,' 07 36 79 16 37 68 '); + Call f_r(7 ,' 48 07 09 18 70 26 06 '); + Call f_r(8 ,' 18 72 79 46 59 79 29 90 '); + Call f_r(9 ,' 20 76 87 11 32 07 07 49 18 '); + Call f_r(10,' 27 83 58 35 71 11 25 57 29 85 '); + Call f_r(11,' 14 64 36 96 27 11 58 56 92 18 55 '); + Call f_r(12,' 02 90 03 60 48 49 41 46 33 36 47 23 '); + Call f_r(13,' 92 50 48 02 36 59 42 79 72 20 82 77 42 '); + Call f_r(14,' 56 78 38 80 39 75 02 71 66 66 01 03 55 72 '); + Call f_r(15,' 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 '); + Call f_r(16,' 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 '); + Call f_r(17,' 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 '); + Call f_r(18,' 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93'); + rows=hbound(nn,1); + + do r=rows by -1 to 2; + p=r-1; /*traipse through triangle rows. */ + do k=1 to p; + kn=k+1; /*re-calculate the previous row. */ + nn(p,k)=max(nn(r,k),nn(r,kn))+nn(p,k); /*replace previous nn */ + end; + end; + Put Edit('maximum path sum:',nn(1,1))(Skip,a,f(5)); /*display result*/ + f_r: Proc(r,vl); + /* fill row r with r values */ + Dcl r Bin Fixed(31); + Dcl vl Char(*); + Dcl vla Char(100) Var; + vla=' '!!trim(vl); + get string(vla) Edit((nn(r,j) Do j=1 To r))(f(3)); + End; + End; diff --git a/Task/Maximum-triangle-path-sum/PicoLisp/maximum-triangle-path-sum.l b/Task/Maximum-triangle-path-sum/PicoLisp/maximum-triangle-path-sum.l new file mode 100644 index 0000000000..72d934bb35 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/PicoLisp/maximum-triangle-path-sum.l @@ -0,0 +1,12 @@ +(de maxpath (Lst) + (let (Lst (reverse Lst) R (car Lst)) + (for I (cdr Lst) + (setq R + (mapcar + + + (maplist + '((L) + (and (cdr L) (max (car L) (cadr L))) ) + R ) + I ) ) ) + (car R) ) ) 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 index 7870d1ac39..e51dc1779d 100644 --- 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 @@ -5,9 +5,8 @@ def solve(tri): tri.append([max(t0[i], t0[i+1]) + t for i,t in enumerate(t1)]) return tri[0][0] -def main(): - data = """\ - 55 + +data = """ 55 94 48 95 30 96 77 71 26 67 @@ -26,6 +25,4 @@ def main(): 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() +print solve([map(int, row.split()) for row in data.splitlines()]) 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 index 682fe5fc2a..7584599158 100644 --- a/Task/Maximum-triangle-path-sum/Ruby/maximum-triangle-path-sum.rb +++ b/Task/Maximum-triangle-path-sum/Ruby/maximum-triangle-path-sum.rb @@ -18,9 +18,9 @@ 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 +ar = triangle.each_line.map{|line| line.split.map(&:to_i)} +puts ar.inject([]){|res,x| + maxes = [0, *res, 0].each_cons(2).map(&:max) + x.zip(maxes).map{|a,b| a+b} +}.max +# => 1320 diff --git a/Task/Maximum-triangle-path-sum/Rust/maximum-triangle-path-sum.rust b/Task/Maximum-triangle-path-sum/Rust/maximum-triangle-path-sum.rust new file mode 100644 index 0000000000..cf2162a1f6 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Rust/maximum-triangle-path-sum.rust @@ -0,0 +1,49 @@ +use std::cmp::max; + +fn max_path(vector: &mut Vec>) -> u32 { + + while vector.len() > 1 { + + let last = vector.pop().unwrap(); + let ante = vector.pop().unwrap(); + + let mut new: Vec = Vec::new(); + + for (i, value) in ante.iter().enumerate() { + new.push(max(last[i], last[i+1]) + value); + }; + + vector.push(new); + }; + + vector[0][0] +} + +fn main() { + let mut 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"; + + let mut vector = data.split("\n").map(|x| x.split(" ").map(|s: &str| s.parse::().unwrap()) + .collect::>()).collect::>>(); + + let max_value = max_path(&mut vector); + + println!("{}", max_value); + //=> 7273 +} diff --git a/Task/Maximum-triangle-path-sum/VBScript/maximum-triangle-path-sum.vb b/Task/Maximum-triangle-path-sum/VBScript/maximum-triangle-path-sum.vb new file mode 100644 index 0000000000..c3feee1e3c --- /dev/null +++ b/Task/Maximum-triangle-path-sum/VBScript/maximum-triangle-path-sum.vb @@ -0,0 +1,25 @@ +'Solution derived from http://stackoverflow.com/questions/8002252/euler-project-18-approach. + +Set objfso = CreateObject("Scripting.FileSystemObject") +Set objinfile = objfso.OpenTextFile(objfso.GetParentFolderName(WScript.ScriptFullName) &_ + "\triangle.txt",1,False) + +row = Split(objinfile.ReadAll,vbCrLf) + +For i = UBound(row) To 0 Step -1 + row(i) = Split(row(i)," ") + If i < UBound(row) Then + For j = 0 To UBound(row(i)) + If (row(i)(j) + row(i+1)(j)) > (row(i)(j) + row(i+1)(j+1)) Then + row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j)) + Else + row(i)(j) = CInt(row(i)(j)) + CInt(row(i+1)(j+1)) + End If + Next + End If +Next + +WScript.Echo row(0)(0) + +objinfile.Close +Set objfso = Nothing diff --git a/Task/Maze-generation/Befunge/maze-generation.bf b/Task/Maze-generation/Befunge/maze-generation.bf new file mode 100644 index 0000000000..b429a9df95 --- /dev/null +++ b/Task/Maze-generation/Befunge/maze-generation.bf @@ -0,0 +1,6 @@ +45*28*10p00p020p030p006p0>20g30g00g*+::"P"%\"P"/6+gv>$\1v@v1::\+g02+*g00+g03-\< +0_ 1!%4+1\-\0!::\-\2%2:p+2%\1-*20g+\1+4%::v^ +#| +2%\1-*30g+\1\40g1-:v0+v2?1#+:00g%!55+*>:#0>#,_^>:!|>\#%"P"v#:*+*g00g0<>1 +02!:++`\0\`-1g01:\+`\< !46v3<^$$<^1,g2+1%2/2,g1+1:30p\:20p:v^3g +0#$g#<1#<-#<`#<\#<0#<^#_^/>#1+#4<>"P"%\"P"/6+g:2%^!>,1-:#v_$55+^|$$ "JH" $$>#<0 +::"P"%\"P"/6+g40p\40g+\:#^"P"%#\<^ ::$_,#!0#:<*"|"<^," _"<:g000 <> /6+g4/2%+#^_ diff --git a/Task/Maze-generation/C/maze-generation.c b/Task/Maze-generation/C/maze-generation.c new file mode 100644 index 0000000000..a3e1685141 --- /dev/null +++ b/Task/Maze-generation/C/maze-generation.c @@ -0,0 +1,146 @@ +#include +#include +#include +#include + +#define DOUBLE_SPACE 1 + +#if DOUBLE_SPACE +# define SPC " " +#else +# define SPC " " +#endif + +wchar_t glyph[] = L""SPC"│││─┘┐┤─└┌├─┴┬┼"SPC"┆┆┆┄╯╮ ┄╰╭ ┄"; + +typedef unsigned char byte; +enum { N = 1, S = 2, W = 4, E = 8, V = 16 }; + +byte **cell; +int w, h, avail; +#define each(i, x, y) for (i = x; i <= y; i++) + +int irand(int n) +{ + int r, rmax = n * (RAND_MAX / n); + while ((r = rand()) >= rmax); + return r / (RAND_MAX/n); +} + +void show() +{ + int i, j, c; + each(i, 0, 2 * h) { + each(j, 0, 2 * w) { + c = cell[i][j]; + if (c > V) printf("\033[31m"); + printf("%lc", glyph[c]); + if (c > V) printf("\033[m"); + } + putchar('\n'); + } +} + +inline int max(int a, int b) { return a >= b ? a : b; } +inline int min(int a, int b) { return b >= a ? a : b; } + +static int dirs[4][2] = {{-2, 0}, {0, 2}, {2, 0}, {0, -2}}; +void walk(int x, int y) +{ + int i, t, x1, y1, d[4] = { 0, 1, 2, 3 }; + + cell[y][x] |= V; + avail--; + + for (x1 = 3; x1; x1--) + if (x1 != (y1 = irand(x1 + 1))) + i = d[x1], d[x1] = d[y1], d[y1] = i; + + for (i = 0; avail && i < 4; i++) { + x1 = x + dirs[ d[i] ][0], y1 = y + dirs[ d[i] ][1]; + + if (cell[y1][x1] & V) continue; + + /* break walls */ + if (x1 == x) { + t = (y + y1) / 2; + cell[t][x+1] &= ~W, cell[t][x] &= ~(E|W), cell[t][x-1] &= ~E; + } else if (y1 == y) { + t = (x + x1)/2; + cell[y-1][t] &= ~S, cell[y][t] &= ~(N|S), cell[y+1][t] &= ~N; + } + walk(x1, y1); + } +} + +int solve(int x, int y, int tox, int toy) +{ + int i, t, x1, y1; + + cell[y][x] |= V; + if (x == tox && y == toy) return 1; + + each(i, 0, 3) { + x1 = x + dirs[i][0], y1 = y + dirs[i][1]; + if (cell[y1][x1]) continue; + + /* mark path */ + if (x1 == x) { + t = (y + y1)/2; + if (cell[t][x] || !solve(x1, y1, tox, toy)) continue; + + cell[t-1][x] |= S, cell[t][x] |= V|N|S, cell[t+1][x] |= N; + } else if (y1 == y) { + t = (x + x1)/2; + if (cell[y][t] || !solve(x1, y1, tox, toy)) continue; + + cell[y][t-1] |= E, cell[y][t] |= V|E|W, cell[y][t+1] |= W; + } + return 1; + } + + /* backtrack */ + cell[y][x] &= ~V; + return 0; +} + +void make_maze() +{ + int i, j; + int h2 = 2 * h + 2, w2 = 2 * w + 2; + byte **p; + + p = calloc(sizeof(byte*) * (h2 + 2) + w2 * h2 + 1, 1); + + p[1] = (byte*)(p + h2 + 2) + 1; + each(i, 2, h2) p[i] = p[i-1] + w2; + p[0] = p[h2]; + cell = &p[1]; + + each(i, -1, 2 * h + 1) cell[i][-1] = cell[i][w2 - 1] = V; + each(j, 0, 2 * w) cell[-1][j] = cell[h2 - 1][j] = V; + each(i, 0, h) each(j, 0, 2 * w) cell[2*i][j] |= E|W; + each(i, 0, 2 * h) each(j, 0, w) cell[i][2*j] |= N|S; + each(j, 0, 2 * w) cell[0][j] &= ~N, cell[2*h][j] &= ~S; + each(i, 0, 2 * h) cell[i][0] &= ~W, cell[i][2*w] &= ~E; + + avail = w * h; + walk(irand(2) * 2 + 1, irand(h) * 2 + 1); + + /* reset visited marker (it's also used by path finder) */ + each(i, 0, 2 * h) each(j, 0, 2 * w) cell[i][j] &= ~V; + solve(1, 1, 2 * w - 1, 2 * h - 1); + + show(); +} + +int main(int c, char **v) +{ + setlocale(LC_ALL, ""); + if (c < 2 || (w = atoi(v[1])) <= 0) w = 16; + if (c < 3 || (h = atoi(v[2])) <= 0) h = 8; + + make_maze(); + + return 0; +} diff --git a/Task/Maze-generation/Elixir/maze-generation.elixir b/Task/Maze-generation/Elixir/maze-generation.elixir new file mode 100644 index 0000000000..aeb3e04db8 --- /dev/null +++ b/Task/Maze-generation/Elixir/maze-generation.elixir @@ -0,0 +1,30 @@ +defmodule Maze do + def generate(w, h) do + :random.seed(:os.timestamp) + (for i <- 1..w, j <- 1..h, do: {i,j}) |> + Enum.each(fn{i,j} -> Process.put({:vis, i, j}, true) end) + walk(:random.uniform(w), :random.uniform(h)) + print(w, h) + end + + defp walk(x, y) do + Process.put({:vis, x, y}, false) + Enum.each(Enum.shuffle([[x-1,y], [x,y+1], [x+1,y], [x,y-1]]), fn [i,j] -> + if Process.get({:vis, i, j}) do + if i == x, do: Process.put({:hor, x, max(y, j)}, "+ "), + else: Process.put({:ver, max(x, i), y}, " ") + walk(i, j) + end + end) + end + + defp print(w, h) do + Enum.each(1..h, fn j -> + IO.puts (Enum.map(1..w, fn i -> Process.get({:hor, i, j}, "+---") end) |> Enum.join) <> "+" + IO.puts (Enum.map(1..w, fn i -> Process.get({:ver, i, j}, "| ") end) |> Enum.join) <> "|" + end) + IO.puts String.duplicate("+---", w) <> "+" + end +end + +Maze.generate(20, 10) diff --git a/Task/Maze-generation/JavaScript/maze-generation-1.js b/Task/Maze-generation/JavaScript/maze-generation-1.js index 73a6b18ab7..03c16f44cc 100644 --- a/Task/Maze-generation/JavaScript/maze-generation-1.js +++ b/Task/Maze-generation/JavaScript/maze-generation-1.js @@ -2,7 +2,7 @@ function maze(x,y) { var n=x*y-1; if (n<0) {alert("illegal maze dimensions");return;} var horiz =[]; for (var j= 0; j> 1 walk(maze, neigh, visited) end end maze end -neighbors(c,b,d=2) = filter(check(b),map(m->c+d*m, {[0,1],[-1,0],[0,-1],[1,0]})) +neighbors(c,b,d=2)=filter(check(b),map(m->c+d*m, Any[[0,1],[-1,0],[0,-1],[1,0]])) check(bound) = cell -> all([1,1] .<= cell .<= [bound...]) maze(w, h) = walk([i%2|j%2 for i=1:2w+1,j=1:2h+1], 2*[rand(1:w),rand(1:h)]) -pprint(maze) = print(mapslices(x-> [join(x)], maze, [2])) +pprint(matrix) = for i = 1:size(matrix,1) println(join(matrix[i,:])) end -function mprint(maze, wall = CharString("╹╸┛╺┗━┻╻┃┓┫┏┣┳╋"...)) +function printmaze(maze, wall = convert(UTF32String, "╹╸┛╺┗━┻╻┃┓┫┏┣┳╋")) + h,w = size(maze) pprint([ maze[i,j] == 0 ? ' ' : - wall[sum(c-> 2.0^.5(3c[1]+c[2]+3), + wall[Int(sum(c-> 2.0^.5(3c[1]+c[2]+3), filter(x -> maze[x...] != 0, - neighbors([i,j],[size(maze)...],1)) .- {[i,j]})] - for i = 1:2:size(maze,1), j = 1:size(maze,2)]) + neighbors([i,j],[h,w],1)) .- Any[[i,j]]))] + for i = 1:2:h, j = 1:w]) end diff --git a/Task/Maze-generation/PHP/maze-generation.php b/Task/Maze-generation/PHP/maze-generation.php new file mode 100644 index 0000000000..5f29db1ccb --- /dev/null +++ b/Task/Maze-generation/PHP/maze-generation.php @@ -0,0 +1,246 @@ +x = $x; + $this->y = $y; + $this->r = $r; + $this->b = $b; + $this->c = $c; + $this->f = hexrgb($f); + $this->m = hexrgb($m); + $this->e = hexrgb($e); + $this->s = hexrgb($s); + } + +// Checks if cell is a closed room + + function isroom($x, $y) + { + return((empty($this->H[$x][$y]) + && empty($this->V[$x][$y]) + && empty($this->H[$x][$y+1]) + && empty($this->V[$x+1][$y])) ? true : false); + } + +// Save the stack as solution path + + function save(&$x, &$y, &$m) + { + if ($this->r == 1 && $x == $this->x - 1 && $y == $this->y - 1) + { + $this->r = $m; + array_push($this->r, array($x, $y)); + } + } + +// Dig the maze + + function dig() + { + $x = 0; + $y = 0; + $cc = $this->x * $this->y; + $v = 1; + $m = array(); + while ($v < $cc) + { + $c = ''; + if ($y > 0 && $this->isroom($x, $y - 1)) + $c .= 'N'; + if ($y < $this->y - 1 && $this->isroom($x, $y + 1)) + $c .= 'S'; + if ($x < $this->x - 1 && $this->isroom($x + 1, $y)) + $c .= 'E'; + if ($x > 0 && $this->isroom($x - 1, $y)) + $c .= 'W'; + if ($c) + { + $v++; + array_push($m, array($x, $y)); + $d = $c[rand(0, strlen($c) - 1)]; + if ($d == 'N') + $this->H[$x][$y--] = true; + if ($d == 'S') + $this->H[$x][$y++ + 1] = true; + if ($d == 'E') + $this->V[$x++ + 1][$y] = true; + if ($d == 'W') + $this->V[$x--][$y] = true; + } + else + list($x, $y) = array_pop($m); + $this->save($x, $y, $m); + } + $this->save($x, $y, $m); + $this->V[0][0] = 1; + $this->V[$this->x][$this->y - 1] = 1; + } + +// Draw the maze full grid + + function grid(&$m) + { + for ($y = 0; $y <= $this->y; ++$y) + { + imagefilledrectangle($this->i, 0, $y * ($this->c + $this->b), + $this->b + $this->x * ($this->c + $this->b) - 1, + $this->b + $y * ($this->c + $this->b) - 1, + $m); + } + for ($x = 0; $x <= $this->x; ++$x) + { + imagefilledrectangle($this->i, $x * ($this->c + $this->b), 0, + $this->b + $x * ($this->c + $this->b) - 1, + $this->b + $this->y * ($this->c + $this->b) - 1, + $m); + } + } + +// Breaks the horizontal walls + + function line($x, $y, &$f) + { + imagefilledrectangle($this->i, + $x * ($this->c + $this->b) + $this->b, + $y * ($this->c + $this->b), + $x * ($this->c + $this->b) + $this->b + $this->c - 1, + $y * ($this->c + $this->b) + $this->b, + $f); + } + +// Breaks the vertical walls + + function col($x, $y, &$f) + { + imagefilledrectangle($this->i, + $x * ($this->c + $this->b), + $y * ($this->c + $this->b) + $this->b, + $x * ($this->c + $this->b) + $this->b, + $y * ($this->c + $this->b) + $this->b + $this->c - 1, + $f); + } + +// Breaks the walls + + function dot(&$f) + { + for ($x = 0; $x <= $this->x; ++$x) + { + for ($y = 0; $y <= $this->y; ++$y) + { + if (isset($this->H[$x][$y])) + $this->line($x, $y, $f); + if (isset($this->V[$x][$y])) + $this->col($x, $y, $f); + } + } + } + +// Fill color cell + + function cellfill(&$x, &$y, &$c) + { + imagefilledrectangle($this->i, + $x * ($this->c + $this->b) + $this->b, + $y * ($this->c + $this->b) + $this->b, + $x * ($this->c + $this->b) + $this->b + $this->c - 1, + $y * ($this->c + $this->b) + $this->b + $this->c - 1, + $c); + } + +// Draw solution + + function path() + { + $l = count($this->r); + for ($i = 0; $i < $l; ++$i) + { + list($x, $y) = $this->r[$i]; + $r = ($this->e[0] * ($l - $i) + $this->s[0] * $i) / $l; + $g = ($this->e[1] * ($l - $i) + $this->s[1] * $i) / $l; + $b = ($this->e[2] * ($l - $i) + $this->s[2] * $i) / $l; + if (!isset($c[$r][$g][$b])) + $c[$r][$g][$b] = imagecolorallocate($this->i, $r, $g, $b); + $this->cellfill($x, $y, $c[$r][$g][$b]); + if (isset($ox, $oy)) + { + if ($ox - $x == -1) + $this->col($x, $y, $c[$r][$g][$b]); + if ($oy - $y == -1) + $this->line($x, $y, $c[$r][$g][$b]); + if ($ox - $x == 1) + $this->col($ox, $oy, $c[$r][$g][$b]); + if ($oy - $y == 1) + $this->line($ox, $oy, $c[$r][$g][$b]); + } + if ($i == 0) + $this->col(0, 0, $c[$r][$g][$b]); + if ($i == $l - 1) + $this->col($x + 1, $y, $c[$r][$g][$b]); + $ox = $x; + $oy = $y; + } + } + +// Call digger and make rendering + + function __destruct() + { + $this->dig(); + $this->i = imagecreatetruecolor( + $this->b + $this->x * ($this->c + $this->b), + $this->b + $this->y * ($this->c + $this->b)); + $f = rgbc($this->i, $this->f); + $m = rgbc($this->i, $this->m); + unset($this->f, $this->m); + imagefill($this->i, 0, 0, $f); + $this->grid($m); + $this->dot($f); + unset($f, $m, $this->H, $this->V); + if ($this->r) + $this->path(); + unset($this->r, $this->e, $this->s); + header('content-disposition:inline;filename="maze.png"'); + header('cache-control:no-store,no-cache,must-revalidate'); + header('content-type:image/png'); + imagepng($this->i, NULL, 9, PNG_ALL_FILTERS); + imagedestroy($this->i); + } +} diff --git a/Task/Maze-generation/PL-I/maze-generation.pli b/Task/Maze-generation/PL-I/maze-generation.pli index 664a1aede1..0b76dc6586 100644 --- a/Task/Maze-generation/PL-I/maze-generation.pli +++ b/Task/Maze-generation/PL-I/maze-generation.pli @@ -1,7 +1,7 @@ *process source attributes xref or(!); mgg: Proc Options(main); /* REXX *************************************************************** - * 04.09.2013 Walter Pachl translated from REXX version 2 + * 04.09.2013 Walter Pachl translated from REXX version 3 **********************************************************************/ Dcl (MIN,MOD,RANDOM,REPEAT,SUBSTR) Builtin; Dcl SYSIN STREAM INPUT; diff --git a/Task/Maze-generation/Perl-6/maze-generation.pl6 b/Task/Maze-generation/Perl-6/maze-generation.pl6 index 93da856219..7bfc626ec9 100644 --- a/Task/Maze-generation/Perl-6/maze-generation.pl6 +++ b/Task/Maze-generation/Perl-6/maze-generation.pl6 @@ -17,8 +17,8 @@ constant mapping = :OPEN(' '), :TODO< x >, :TRIED< · >; -enum Code (mapping.map: *.key); -my @code = mapping.map: *.value; +enum Sym (mapping.map: *.key); +my @ch = mapping.map: *.value; enum Direction ; @@ -28,13 +28,13 @@ sub gen_maze ( $X, $start_y = (^$Y).pick * 2 + 1 ) { my @maze; - push @maze, [ ES, -N, (ESW, EW) xx $X - 1, SW ]; - push @maze, [ (NS, TODO) xx $X, NS ]; + push @maze, $[ flat ES, -N, (ESW, EW) xx $X - 1, SW ]; + push @maze, $[ flat (NS, TODO) xx $X, NS ]; for 1 ..^ $Y { - push @maze, [ NES, EW, (NESW, EW) xx $X - 1, NSW ]; - push @maze, [ (NS, TODO) xx $X, NS ]; + push @maze, $[ flat NES, EW, (NESW, EW) xx $X - 1, NSW ]; + push @maze, $[ flat (NS, TODO) xx $X, NS ]; } - push @maze, [ NE, (EW, NEW) xx $X - 1, -NS, NW ]; + push @maze, $[ flat NE, (EW, NEW) xx $X - 1, -NS, NW ]; @maze[$start_y][$start_x] = OPEN; my @stack; @@ -75,12 +75,12 @@ sub gen_maze ( $X, sub display (@maze) { for @maze -> @y { - for @y -> $w, $c { - print @code[abs $w]; - if $c >= 0 { print @code[$c] x 3 } - else { print ' ', @code[abs $c], ' ' } + for @y.rotor(2) -> ($w, $c) { + print @ch[abs $w]; + if $c >= 0 { print @ch[$c] x 3 } + else { print ' ', @ch[abs $c], ' ' } } - say @code[@y[*-1]]; + say @ch[@y[*-1]]; } } diff --git a/Task/Maze-generation/Python/maze-generation.py b/Task/Maze-generation/Python/maze-generation.py index 67664264e9..8f92e9e4ec 100644 --- a/Task/Maze-generation/Python/maze-generation.py +++ b/Task/Maze-generation/Python/maze-generation.py @@ -1,23 +1,23 @@ from random import shuffle, randrange def make_maze(w = 16, h = 8): - vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] - ver = [["| "] * w + ['|'] for _ in range(h)] + [[]] - hor = [["+--"] * w + ['+'] for _ in range(h + 1)] + vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)] + ver = [["| "] * w + ['|'] for _ in range(h)] + [[]] + hor = [["+--"] * w + ['+'] for _ in range(h + 1)] - def walk(x, y): - vis[y][x] = 1 + def walk(x, y): + vis[y][x] = 1 - d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] - shuffle(d) - for (xx, yy) in d: - if vis[yy][xx]: continue - if xx == x: hor[max(y, yy)][x] = "+ " - if yy == y: ver[y][max(x, xx)] = " " - walk(xx, yy) + d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)] + shuffle(d) + for (xx, yy) in d: + if vis[yy][xx]: continue + if xx == x: hor[max(y, yy)][x] = "+ " + if yy == y: ver[y][max(x, xx)] = " " + walk(xx, yy) - walk(randrange(w), randrange(h)) - for (a, b) in zip(hor, ver): - print(''.join(a + ['\n'] + b)) + walk(randrange(w), randrange(h)) + for (a, b) in zip(hor, ver): + print(''.join(a + ['\n'] + b)) make_maze() diff --git a/Task/Maze-generation/REXX/maze-generation-1.rexx b/Task/Maze-generation/REXX/maze-generation-1.rexx index 0bfa15dce4..fe213b74ab 100644 --- a/Task/Maze-generation/REXX/maze-generation-1.rexx +++ b/Task/Maze-generation/REXX/maze-generation-1.rexx @@ -98,5 +98,5 @@ if right(_,2)=='·┤' then _=translate(_, '|', "┤") when le=='·' & ri=='~' & up=='│' & dw=='│' then _=overlay('├',_,k) otherwise nop end /*select*/ - end /*k*/ + end /*k*/ return diff --git a/Task/Maze-solving/Perl-6/maze-solving.pl6 b/Task/Maze-solving/Perl-6/maze-solving.pl6 index 0f0549201f..bab371218c 100644 --- a/Task/Maze-solving/Perl-6/maze-solving.pl6 +++ b/Task/Maze-solving/Perl-6/maze-solving.pl6 @@ -17,8 +17,8 @@ constant mapping = :OPEN(' '), :TODO< x >, :TRIED< · >; -enum Code (mapping.map: *.key); -my @code = mapping.map: *.value; +enum Sym (mapping.map: *.key); +my @ch = mapping.map: *.value; enum Direction ; @@ -28,13 +28,13 @@ sub gen_maze ( $X, $start_y = (^$Y).pick * 2 + 1 ) { my @maze; - push @maze, [ ES, -N, (ESW, EW) xx $X - 1, SW ]; - push @maze, [ (NS, TODO) xx $X, NS ]; + push @maze, $[ flat ES, -N, (ESW, EW) xx $X - 1, SW ]; + push @maze, $[ flat (NS, TODO) xx $X, NS ]; for 1 ..^ $Y { - push @maze, [ NES, EW, (NESW, EW) xx $X - 1, NSW ]; - push @maze, [ (NS, TODO) xx $X, NS ]; + push @maze, $[ flat NES, EW, (NESW, EW) xx $X - 1, NSW ]; + push @maze, $[ flat (NS, TODO) xx $X, NS ]; } - push @maze, [ NE, (EW, NEW) xx $X - 1, -NS, NW ]; + push @maze, $[ flat NE, (EW, NEW) xx $X - 1, -NS, NW ]; @maze[$start_y][$start_x] = OPEN; my @stack; @@ -75,12 +75,12 @@ sub gen_maze ( $X, sub display (@maze) { for @maze -> @y { - for @y -> $w, $c { - print @code[abs $w]; - if $c >= 0 { print @code[$c] x 3 } - else { print ' ', @code[abs $c], ' ' } + for @y.rotor(2) -> ($w, $c) { + print @ch[abs $w]; + if $c >= 0 { print @ch[$c] x 3 } + else { print ' ', @ch[abs $c], ' ' } } - say @code[@y[*-1]]; + say @ch[@y[*-1]]; } } @@ -95,14 +95,14 @@ sub solve (@maze is copy, @from = [1, 1], @to = [@maze[0] - 2, @maze - 2]) { loop { my $dir = pick_direction([$x,$y]); if $dir { - ($x, $y) = move($dir, [$x,$y]); + ($x, $y) = move($dir, [$x,$y]); return @maze if $x == $xto and $y == $yto; } else { @maze[$y][$x] = -TRIED; - ($x,$y) = @stack.pop[]; + ($x,$y) = @stack.pop; @maze[$y][$x] = -TRIED; - ($x,$y) = @stack.pop[]; + ($x,$y) = @stack.pop; } } @@ -118,10 +118,10 @@ sub solve (@maze is copy, @from = [1, 1], @to = [@maze[0] - 2, @maze - 2]) { sub move ($dir, @cur) { my ($x,$y) = @cur; given $dir { - when Up { for ^2 { push @stack, [$x,$y--]; drop-crumb $x,$y,S; } } - when Down { for ^2 { push @stack, [$x,$y++]; drop-crumb $x,$y,N; } } - when Left { for ^2 { push @stack, [$x--,$y]; drop-crumb $x,$y,E; } } - when Right { for ^2 { push @stack, [$x++,$y]; drop-crumb $x,$y,W; } } + when Up { for ^2 { push @stack, $[$x,$y--]; drop-crumb $x,$y,S; } } + when Down { for ^2 { push @stack, $[$x,$y++]; drop-crumb $x,$y,N; } } + when Left { for ^2 { push @stack, $[$x--,$y]; drop-crumb $x,$y,E; } } + when Right { for ^2 { push @stack, $[$x++,$y]; drop-crumb $x,$y,W; } } } $x,$y; } diff --git a/Task/Memory-layout-of-a-data-structure/Mercury/memory-layout-of-a-data-structure-2.mercury b/Task/Memory-layout-of-a-data-structure/Mercury/memory-layout-of-a-data-structure-2.mercury index f611f8f9fe..7849246af2 100644 --- a/Task/Memory-layout-of-a-data-structure/Mercury/memory-layout-of-a-data-structure-2.mercury +++ b/Task/Memory-layout-of-a-data-structure/Mercury/memory-layout-of-a-data-structure-2.mercury @@ -21,13 +21,17 @@ main(!IO) :- write_string(to_string(Com2), !IO), nl(!IO), write_string("Com1 DTR is ", !IO), - ( rs232_is_set(Com1, data_terminal_ready) -> - write_string("set.", !IO), nl(!IO) - ; write_string("clear.", !IO), nl(!IO) ), + ( if rs232_is_set(Com1, data_terminal_ready) then + write_string("set.", !IO), nl(!IO) + else + write_string("clear.", !IO), nl(!IO) + ), write_string("Com2 DSR is ", !IO), - ( rs232_is_clear(Com2, data_set_ready) -> - write_string("clear.", !IO), nl(!IO) - ; write_string("set.", !IO), nl(!IO) ). + ( if rs232_is_clear(Com2, data_set_ready) then + write_string("clear.", !IO), nl(!IO) + else + write_string("set.", !IO), nl(!IO) + ). :- end_module rs232_main. diff --git a/Task/Menu/00DESCRIPTION b/Task/Menu/00DESCRIPTION index 2afd5fbcca..57c6f6e097 100644 --- a/Task/Menu/00DESCRIPTION +++ b/Task/Menu/00DESCRIPTION @@ -1,10 +1,10 @@ -Given a list containing a number of strings of which one is to be selected and a prompt string, create a function that: +Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: -* Print a textual menu formatted as an index value followed by its corresponding string for each item in the list. -* Prompt the user to enter a number. -* Return the string corresponding to the index number. +* prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; +* prompts the user to enter a number; +* returns the string corresponding to the selected index number. -The function should reject input that is not an integer or is an out of range integer index by recreating the whole menu before asking again for a number. The function should return an empty string if called with an empty list. +The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the four phrases: “fee fie”, “huff and puff”, “mirror mirror” and “tick tock” in a list. diff --git a/Task/Menu/Batch-File/menu.bat b/Task/Menu/Batch-File/menu.bat new file mode 100644 index 0000000000..1692ec96c9 --- /dev/null +++ b/Task/Menu/Batch-File/menu.bat @@ -0,0 +1,28 @@ +@echo off +setlocal enabledelayedexpansion + +::The Main Thing... +set choices="fee fie","huff and puff","mirror mirror","tick tock" +set "quest=Which is from the three pigs?" +call :select +pause>nul +exit /b 0 +::/The Main Thing. + +::The Function... +:select +set number=0 +for %%A in (%choices%) do set tmpvar=%%A&set /a number+=1&set opt!number!=!tmpvar:"=! +:tryagain +cls&echo. +for /l %%A in (1,1,%number%) do echo. Option %%A - !opt%%A! +echo. +set /p input=%quest% +for /l %%A in (1,1,%number%) do ( + if !input! equ %%A echo.&echo.You chose option %%A - !opt%%A!&goto :EOF +) +echo. +echo.Invalid Input. Please try again... +pause>nul +goto tryagain +::/The Function. diff --git a/Task/Menu/J/menu-1.j b/Task/Menu/J/menu-1.j index fdd92500cb..4f398a1152 100644 --- a/Task/Menu/J/menu-1.j +++ b/Task/Menu/J/menu-1.j @@ -1,4 +1,4 @@ -require'misc' +require 'general/misc/prompt' NB. in older versions of J this was: require'misc' showMenu =: i.@# smoutput@,&":&> ' '&,&.> makeMsg =: 'Choose a number 0..' , ': ',~ ":@<:@# errorMsg =: [ smoutput bind 'Please choose a valid number!' diff --git a/Task/Menu/TI-83-BASIC/menu.ti-83 b/Task/Menu/TI-83-BASIC/menu.ti-83 index f2d51401bb..9e9954b1da 100644 --- a/Task/Menu/TI-83-BASIC/menu.ti-83 +++ b/Task/Menu/TI-83-BASIC/menu.ti-83 @@ -1,17 +1,5 @@ -PROGRAM:MENU -:"FEE FIE"→Str0 -:"HUFF AND PUFF"→Str1 -:"MIRROR MIRROR"→Str2 -:"TICK TOCK"→Str3 -:Menu("CHOOSE",Str0,A,Str1,B,Str2,C,Str3,D) -:Lbl A -:Disp Str0 -:Stop -:Lbl B -:Disp Str1 -:Stop -:Lbl C -:Disp Str2 -:Stop -:Lbl D -:Disp Str3 + 1:FEE FIE + 2:HUFF AND PUFF + 3:MIRROR MIRROR + 4:TICK TOCK +? [flashing cursor] diff --git a/Task/Menu/VBScript/menu.vb b/Task/Menu/VBScript/menu.vb new file mode 100644 index 0000000000..05bd563a9c --- /dev/null +++ b/Task/Menu/VBScript/menu.vb @@ -0,0 +1,25 @@ +Do + WScript.StdOut.Write "1. fee fie" & vbCrLf + WScript.StdOut.Write "2. huff puff" & vbCrLf + WScript.StdOut.Write "3. mirror mirror" & vbCrLf + WScript.StdOut.Write "4. tick tock" & vbCrLf + WScript.StdOut.Write "Please Enter Your Choice: " & vbCrLf + choice = WScript.StdIn.ReadLine + Select Case choice + Case "1" + WScript.StdOut.Write "fee fie" & vbCrLf + Exit Do + Case "2" + WScript.StdOut.Write "huff puff" & vbCrLf + Exit Do + Case "3" + WScript.StdOut.Write "mirror mirror" & vbCrLf + Exit Do + Case "4" + WScript.StdOut.Write "tick tock" & vbCrLf + Exit Do + Case Else + WScript.StdOut.Write choice & " is an invalid choice. Please try again..." &_ + vbCrLf & vbCrLf + End Select +Loop diff --git a/Task/Metaprogramming/ALGOL-68/metaprogramming.alg b/Task/Metaprogramming/ALGOL-68/metaprogramming.alg new file mode 100644 index 0000000000..915306eaf2 --- /dev/null +++ b/Task/Metaprogramming/ALGOL-68/metaprogramming.alg @@ -0,0 +1,131 @@ +# This example uses ALGOL 68 user defined operators to add a COBOL-style # +# "INSPECT statement" to ALGOL 68 # +# # +# The (partial) syntax of the COBOL INSPECT is: # +# INSPECT string-variable REPLACING ALL string BY string # +# or INSPECT string-variable REPLACING LEADING string BY string # +# or INSPECT string-variable REPLACING FIRST string BY string # +# # +# Because "BY" is a reserved bold word in ALGOL 68, we use "WITH" instead # +# # +# We define unary operators INSPECT, ALL, LEADING and FIRST # +# and binary operators REPLACING and WITH # +# We choose the priorities of REPLACING and WITH so that parenthesis is not # +# needed to ensure the correct interpretation of the "statement" # +# # +# We also provide a unary DISPLAY operator for a partial COBOL DISPLAY # +# statement # + +# INSPECTEE is returned by the INSPECT unary operator # +MODE INSPECTEE = STRUCT( REF STRING item, INT option ); + +# INSPECTTOREPLACE is returned by the binary REPLACING operator # +MODE INSPECTTOREPLACE + = STRUCT( REF STRING item, INT option, STRING to replace ); +# REPLACEMENT is returned by the unary ALL, LEADING and FIRST operators # +MODE REPLACEMENT = STRUCT( INT option, STRING replace ); + +# REPLACING option codes, these are the option values for a REPLACEMENT # +INT replace all = 1; +INT replace leading = 2; +INT replace first = 3; + +OP INSPECT = ( REF STRING s )INSPECTEE: ( s, 0 ); +OP ALL = ( STRING replace )REPLACEMENT: ( replace all, replace ); +OP LEADING = ( STRING replace )REPLACEMENT: ( replace leading, replace ); +OP FIRST = ( STRING replace )REPLACEMENT: ( replace first, replace ); +OP ALL = ( CHAR replace )REPLACEMENT: ( replace all, replace ); +OP LEADING = ( CHAR replace )REPLACEMENT: ( replace leading, replace ); +OP FIRST = ( CHAR replace )REPLACEMENT: ( replace first, replace ); + +OP REPLACING = ( INSPECTEE inspected, REPLACEMENT replace )INSPECTTOREPLACE: + ( item OF inspected + , option OF replace + , replace OF replace + ); + +OP WITH = ( INSPECTTOREPLACE inspected, CHAR replace with )REF STRING: + BEGIN + STRING with := replace with; + inspected WITH with + END; # WITH # + +OP WITH = ( INSPECTTOREPLACE inspected, STRING replace with )REF STRING: + BEGIN + + STRING to replace = to replace OF inspected; + INT pos := 0; + STRING rest := item OF inspected; + STRING result := ""; + + IF option OF inspected = replace all + THEN + # replace all occurances of "to replace" with "replace with" # + WHILE string in string( to replace, pos, rest ) + DO + result +:= rest[ 1 : pos - 1 ] + replace with; + rest := rest[ pos + UPB to replace : ] + OD + + ELIF option OF inspected = replace leading + THEN + # replace leading occurances of "to replace" with "replace with" # + WHILE IF string in string( to replace, pos, rest ) + THEN + pos = 1 + ELSE + FALSE + FI + DO + result +:= replace with; + rest := rest[ UPB to replace : ] + OD + + ELIF option OF inspected = replace first + THEN + # replace first occurance of "to replace" with "replace with" # + IF string in string( to replace, pos, rest ) + THEN + result +:= rest[ 1 : pos - 1 ] + replace with; + rest := rest[ pos + UPB to replace : ] + FI + + ELSE + # unsupported replace option # + write( ( newline, "*** unsupported INSPECT REPLACING...", newline ) ); + stop + FI; + + result +:= rest; + item OF inspected := result + END; # WITH # + +OP DISPLAY = ( STRING s )VOID: write( ( s, newline ) ); + + +PRIO REPLACING = 2, WITH = 1; + + + + +main: ( + + # test the INSPECT and DISPLAY "verbs" # + + STRING text := "some text"; + DISPLAY text; + + INSPECT text REPLACING FIRST "e" WITH "bbc"; + DISPLAY text; + + INSPECT text REPLACING ALL "b" WITH "X"; + DISPLAY text; + + INSPECT text REPLACING ALL "text" WITH "some"; + DISPLAY text; + + INSPECT text REPLACING LEADING "som" WITH "k"; + DISPLAY text + + +) diff --git a/Task/Metaprogramming/Perl-6/metaprogramming-2.pl6 b/Task/Metaprogramming/Perl-6/metaprogramming-2.pl6 index dcb230a5ca..03a9294d1c 100644 --- a/Task/Metaprogramming/Perl-6/metaprogramming-2.pl6 +++ b/Task/Metaprogramming/Perl-6/metaprogramming-2.pl6 @@ -1,7 +1,7 @@ -use MONKEY_TYPING; # Needed to do runtime augmentation of a base class. +use MONKEY-TYPING; # Needed to do runtime augmentation of a base class. -augment class Any { - method nsort { self.list.sort: {$^a.lc.subst(/(\d+)/,->$/{0~$0.chars.chr~$0},:g)~"\x0"~$^a} } +augment class List { + method nsort { self.list.sort: {$^a.lc.subst(/(\d+)/, -> $/ {0 ~ $0.chars.chr ~ $0 }, :g) ~ "\x0" ~ $^a} } }; say ~.nsort; diff --git a/Task/Metaprogramming/Perl-6/metaprogramming-3.pl6 b/Task/Metaprogramming/Perl-6/metaprogramming-3.pl6 index 25ed0cefd9..a4aed44433 100644 --- a/Task/Metaprogramming/Perl-6/metaprogramming-3.pl6 +++ b/Task/Metaprogramming/Perl-6/metaprogramming-3.pl6 @@ -1,2 +1,2 @@ -macro addem($a,$b) { "($a + $b)" } -say addem(3,4); # 7 +say "Foo = $foo\n"; # normal double quotes +say Q:qq 【Foo = $foo\n】; # a more explicit derivation, new quotes diff --git a/Task/Metronome/Common-Lisp/metronome.lisp b/Task/Metronome/Common-Lisp/metronome.lisp new file mode 100644 index 0000000000..e28bb71bd7 --- /dev/null +++ b/Task/Metronome/Common-Lisp/metronome.lisp @@ -0,0 +1,64 @@ +(ql:quickload '(cl-openal cl-alc)) + +(defparameter *short-max* (- (expt 2 15) 1)) +(defparameter *2-pi* (* 2 pi)) + +(defun make-sin (period) + "Create a generator for a sine wave of the given PERIOD." + (lambda (x) + (sin (* *2-pi* (/ x period))))) + +(defun make-tone (length frequency sampling-frequency) + "Create a vector containing sound information of the given LENGTH, +FREQUENCY, and SAMPLING-FREQUENCY." + (let ((data (make-array (truncate (* length sampling-frequency)) + :element-type '(signed-byte 16))) + (generator (make-sin (/ sampling-frequency frequency)))) + (dotimes (i (length data)) + (setf (aref data i) + (truncate (* *short-max* (funcall generator i))))) + data)) + +(defun internal-time-ms () + "Get the process's real time in ms." + (* 1000 (/ (get-internal-real-time) internal-time-units-per-second))) + +(defun spin-wait (next-real-time) + "Wait until the process's real time has reached the given time." + (loop while (< (internal-time-ms) next-real-time))) + +(defun upload (buffer data sampling-frequency) + "Upload the given vector DATA to a BUFFER at the given SAMPLING-FREQUENCY." + (cffi:with-pointer-to-vector-data (data-ptr data) + (al:buffer-data buffer :mono16 data-ptr (* 2 (length data)) + sampling-frequency))) + +(defun metronome (beats/minute pattern &optional (sampling-frequency 44100)) + "Play a metronome until interrupted." + (let ((ms/beat (/ 60000 beats/minute))) + (alc:with-device (device) + (alc:with-context (context device) + (alc:make-context-current context) + (al:with-buffer (low-buffer) + (al:with-buffer (high-buffer) + (al:with-source (source) + (al:source source :gain 0.5) + (flet ((play-it (buffer) + (al:source source :buffer buffer) + (al:source-play source)) + (upload-it (buffer time frequency) + (upload buffer + (make-tone time frequency sampling-frequency) + sampling-frequency))) + (upload-it low-buffer 0.1 440) + (upload-it high-buffer 0.15 880) + (let ((next-scheduled-tone (internal-time-ms))) + (loop + (loop for symbol in pattern do + (spin-wait next-scheduled-tone) + (incf next-scheduled-tone ms/beat) + (case symbol + (l (play-it low-buffer)) + (h (play-it high-buffer))) + (princ symbol)) + (terpri))))))))))) diff --git a/Task/Metronome/Python/metronome.py b/Task/Metronome/Python/metronome.py new file mode 100644 index 0000000000..9844d13782 --- /dev/null +++ b/Task/Metronome/Python/metronome.py @@ -0,0 +1,17 @@ +#lang Python +import time + +def main(bpm = 72, bpb = 4): + sleep = 60.0 / bpm + counter = 0 + while True: + counter += 1 + if counter % bpb: + print 'tick' + else: + print 'TICK' + time.sleep(sleep) + + + +main() diff --git a/Task/Middle-three-digits/Batch-File/middle-three-digits.bat b/Task/Middle-three-digits/Batch-File/middle-three-digits.bat new file mode 100644 index 0000000000..e0df706b81 --- /dev/null +++ b/Task/Middle-three-digits/Batch-File/middle-three-digits.bat @@ -0,0 +1,46 @@ +@echo off +setlocal enabledelayedexpansion + + %== Initialization ==% +set "numbers=123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0" + + %== The Main Thing ==% +for %%N in (%numbers%) do ( + call :middle3 %%N +) +echo. +pause +exit /b 0 + %==/The Main Thing ==% + + %== The Procedure ==% +:middle3 + + set str=%1 + %== Making sure that str is positive ==% + if !str! lss 0 set /a str*=-1 + + %== Alternative for finding the string length ==% + %== But this has a limit of 1000 characters ==% + set leng=0&if not "!str!"=="" for /l %%. in (0,1,1000) do if not "!str:~%%.,1!"=="" set /a leng+=1 + + if !leng! lss 3 ( + echo.%~1: [ERROR] Input too small. + goto :EOF + ) + + set /a "test2=leng %% 2,trimmer=(leng - 3) / 2" + + if !test2! equ 0 ( + echo.%~1: [ERROR] Even number of digits. + goto :EOF + ) + + %== Passed the tests. Now, really find the middle 3 digits... ==% + if !trimmer! equ 0 ( + echo.%~1: !str! + ) else ( + echo.%~1: !str:~%trimmer%,-%trimmer%! + ) + goto :EOF + %==/The Procedure ==% diff --git a/Task/Middle-three-digits/Befunge/middle-three-digits.bf b/Task/Middle-three-digits/Befunge/middle-three-digits.bf new file mode 100644 index 0000000000..e4bc62dd20 --- /dev/null +++ b/Task/Middle-three-digits/Befunge/middle-three-digits.bf @@ -0,0 +1 @@ +&55+/55+::**%.@ diff --git a/Task/Middle-three-digits/Burlesque/middle-three-digits.blq b/Task/Middle-three-digits/Burlesque/middle-three-digits.blq new file mode 100644 index 0000000000..fe8a2e6f2d --- /dev/null +++ b/Task/Middle-three-digits/Burlesque/middle-three-digits.blq @@ -0,0 +1,7 @@ +blsq ) {123 12345 1234567 987654321 -10001 -123}{XX{~-}{L[3.>}w!m]\[}m[uN +123 +234 +345 +654 +000 +123 diff --git a/Task/Middle-three-digits/DCL/middle-three-digits.dcl b/Task/Middle-three-digits/DCL/middle-three-digits.dcl new file mode 100644 index 0000000000..4ae1280b2d --- /dev/null +++ b/Task/Middle-three-digits/DCL/middle-three-digits.dcl @@ -0,0 +1,15 @@ +$ list = "123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0" +$ i = 0 +$ loop: +$ number = f$element( i, ",", list ) +$ if number .eqs. "," then $ exit +$ abs_number = number - "-" +$ len = f$length( abs_number ) +$ if len .lt. 3 .or. .not. len +$ then +$ write sys$output f$fao( "!9SL: ", f$integer( number )), "has no middle three" +$ else +$ write sys$output f$fao( "!9SL: ", f$integer( number )), f$extract( ( len - 3 ) / 2, 3, abs_number ) +$ endif +$ i = i + 1 +$ goto loop diff --git a/Task/Middle-three-digits/Eiffel/middle-three-digits.e b/Task/Middle-three-digits/Eiffel/middle-three-digits.e new file mode 100644 index 0000000000..8a650301e6 --- /dev/null +++ b/Task/Middle-three-digits/Eiffel/middle-three-digits.e @@ -0,0 +1,61 @@ +class + APPLICATION + +create + make + +feature + + make + -- Test of middle_three_digits. + local + test_1, test_2: ARRAY [INTEGER] + do + test_1 := <<123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345>> + test_2 := <<1, 2, -1, -10, 2002, -2002, 0>> + across + test_1 as t + loop + io.put_string ("The middle three digits of " + t.item.out + " are: %T ") + io.put_string (middle_three_digits (t.item) + "%N") + end + across + test_2 as t + loop + io.put_string ("The middle three digits of " + t.item.out + " are: %T") + io.put_string (middle_three_digits (t.item) + "%N") + end + end + + middle_three_digits (n: INTEGER): STRING + -- The middle three digits of 'n'. + local + k, i: INTEGER + in: STRING + do + create in.make_empty + in := n.out + if n < 0 then + in.prune ('-') + end + create Result.make_empty + if in.count < 3 then + io.put_string (" Not enough digits. ") + elseif in.count \\ 2 = 0 then + io.put_string (" Even number of digits. ") + else + i := (in.count - 3) // 2 + from + k := i + 1 + until + k > i + 3 + loop + Result.extend (in.at (k)) + k := k + 1 + end + end + ensure + length_is_three: Result.count = 3 or Result.count = 0 + end + +end diff --git a/Task/Middle-three-digits/Elixir/middle-three-digits.elixir b/Task/Middle-three-digits/Elixir/middle-three-digits.elixir new file mode 100644 index 0000000000..8c73afc776 --- /dev/null +++ b/Task/Middle-three-digits/Elixir/middle-three-digits.elixir @@ -0,0 +1,30 @@ +defmodule Middle do + def three(num) do + n = num |> abs |> to_string + + case {n,String.length(n) > 2,even?(n)} do + {n, true, false} -> + cut(n) + {_, false, _} -> + raise "Number must have at least three digits" + {_, _, true} -> + raise "Number must have an odd number of digits" + end + end + + defp even?(n), do: rem(String.length(n),2) == 0 + defp cut(n), do: String.slice(n,(div(String.length(n),2) - 1),3) +end + +valids = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345] +Enum.each(valids, fn n -> :io.format "~10w : ~s~n", [n, Middle.three(n)] end) + +errors = [1, 2, -1, -10, 2002, -2002, 0] +Enum.each(errors, fn n -> + :io.format "~10w : ", [n] + try do + IO.puts Middle.three(n) + rescue + e -> IO.puts e.message + end +end) diff --git a/Task/Middle-three-digits/Julia/middle-three-digits.julia b/Task/Middle-three-digits/Julia/middle-three-digits.julia index 1ad00a891e..979bb3028a 100644 --- a/Task/Middle-three-digits/Julia/middle-three-digits.julia +++ b/Task/Middle-three-digits/Julia/middle-three-digits.julia @@ -1,22 +1,12 @@ function middle(i) s = string(abs(i)) l = length(s) - mid = int((l+1)/2) + mid = round(Int,(l+1)/2) l < 3 ? "error: not enough digits" : iseven(l) ? "error: number of digits is even" : - join((s[mid-1],s[mid],s[mid+1])) -end - -function dummy(x,y,z=5) - """ - A dummy docstring over two lines - for text coloration. - """ - print("this is just some text to show text", 1.0, 3) - # and comment coloration - // and comment coloration 2 + s[mid-1:mid+1] end julia> diff --git a/Task/Middle-three-digits/Logo/middle-three-digits.logo b/Task/Middle-three-digits/Logo/middle-three-digits.logo new file mode 100644 index 0000000000..fd75d149ca --- /dev/null +++ b/Task/Middle-three-digits/Logo/middle-three-digits.logo @@ -0,0 +1,19 @@ +to middle3digits :n + if [less? :n 0] [make "n minus :n] + local "len make "len count :n + if [less? :len 3] [(throw "error [Number must have at least 3 digits])] + if [equal? 0 modulo :len 2] [(throw "error [Number must have odd number of digits])] + while [greater? count :n 3] [ + make "n butlast butfirst :n + ] + output :n +end + +foreach [123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 + 1 2 -1 -10 2002 -2002 0] [ + type sentence (word ? ": char 9) runresult [if [less? count ? 7] [char 9]] + make "mid runresult [catch "error [middle3digits ?]] + print ifelse [empty? :mid] [item 2 error] [:mid] +] + +bye diff --git a/Task/Middle-three-digits/NewLISP/middle-three-digits.newlisp b/Task/Middle-three-digits/NewLISP/middle-three-digits.newlisp new file mode 100644 index 0000000000..a0a06beda5 --- /dev/null +++ b/Task/Middle-three-digits/NewLISP/middle-three-digits.newlisp @@ -0,0 +1,11 @@ +(define (middle3 x) + (if (even? (length x)) + (println "You entered " x ". I need an odd number of digits, not " (length x) ".") + (if (< (length x) 3) + (println "You entered " x ". Sorry, but I need 3 or more digits.") + (println "The middle 3 digits of " x " are " ((- (/ (- (length x) 1) 2) 1) 3 (string (abs x))) ".") + ) + ) +) + +(map middle3 lst) diff --git a/Task/Middle-three-digits/PowerShell/middle-three-digits.psh b/Task/Middle-three-digits/PowerShell/middle-three-digits.psh new file mode 100644 index 0000000000..a075b3f05e --- /dev/null +++ b/Task/Middle-three-digits/PowerShell/middle-three-digits.psh @@ -0,0 +1,24 @@ +function middle3($inp){ + + $str = [Math]::abs($inp) + + $leng = "$str".length + + if ($leng -lt 3){ + Write-host $inp": [ERROR] too short." + Return + } + if (($leng % 2) -eq 0){ + Write-host $inp": [ERROR] even number of digits." + } else { + $trimmer = ($leng - 3) / 2 + $ans = "$str".subString($trimmer,3) + + Write-host $inp": $ans" + } + Return +} + +$sample = 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0 + +foreach ($x in $sample){middle3 $x} diff --git a/Task/Middle-three-digits/REXX/middle-three-digits-2.rexx b/Task/Middle-three-digits/REXX/middle-three-digits-2.rexx index 1374170062..e991938bba 100644 --- a/Task/Middle-three-digits/REXX/middle-three-digits-2.rexx +++ b/Task/Middle-three-digits/REXX/middle-three-digits-2.rexx @@ -1,16 +1,17 @@ -/*REXX program returns the 3 middle digits of a number (or an error). */ -n ='123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345', - '2 -1 -10 2002 -2002 0 abc 1e3 -17e-3 1234567. 1237654.00', +/*REXX program returns the three middle digits of a number (or an error msg).*/ +n= '123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345', + '2 -1 -10 2002 -2002 0 abc 1e3 -17e-3 1234567. 1237654.00', '1234567890123456789012345678901234567890123456789012345678901234567' - do j=1 for words(n); z=word(n,j) /* [↓] format the output nicely.*/ - say 'middle 3 digits of' right(z,max(15,length(z))) '──►' middle3(z) + do j=1 for words(n); #=word(n,j) /* [↓] format the output number nicely*/ + say 'middle 3 digits of' right(z, max(15, length(#))) '──►' middle3(#) end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────MIDDLE3 subroutine──────────────────*/ -middle3: procedure; arg x; numeric digits 1e5; er=' ***error!*** ' -if datatype(x,'N') then x=abs(x); L=length(x) -if \datatype(x,'W') then return er "arg isn't an integer" -if L<3 then return er "arg is less than three digits" -if L//2==0 then return er "arg isn't an odd number of digits" +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +middle3: procedure; parse arg x; numeric digits 1e6; er=' ***error!*** ' +if pos(.,x)\==0 then x=x/1 /*normalize it, contains decimal point.*/ +if datatype(x,'N') then x=abs(x); L=length(x) +if \datatype(x,'W') then return er "argument isn't an integer." +if L<3 then return er "argument is less than three digits." +if L//2==0 then return er "argument isn't an odd number of digits." return substr(x, (L-3)%2+1, 3) diff --git a/Task/Middle-three-digits/Rust/middle-three-digits.rust b/Task/Middle-three-digits/Rust/middle-three-digits.rust index afd57b6673..0a1373f0cb 100644 --- a/Task/Middle-three-digits/Rust/middle-three-digits.rust +++ b/Task/Middle-three-digits/Rust/middle-three-digits.rust @@ -1,18 +1,16 @@ -// rust 0.8 - -fn middle_three_digits(x: int) -> Result<~str, ~str> { - let s = x.abs().to_str(); +fn middle_three_digits(x: i32) -> Result { + let s: String = x.abs().to_string(); let len = s.len(); if len < 3 { - Err(~"Too short") + Err("Too short".into()) } else if len % 2 == 0 { - Err(~"Even number of digits") + Err("Even number of digits".into()) } else { - Ok(s.slice(len/2 - 1, len/2 + 2).to_owned()) + Ok(s[len/2 - 1 .. len/2 + 2].to_owned()) } } -fn print_result(x: int) { +fn print_result(x: i32) { print!("middle_three_digits({}) returned: ", x); match middle_three_digits(x) { Ok(s) => println!("Success, {}", s), diff --git a/Task/Middle-three-digits/VBScript/middle-three-digits.vb b/Task/Middle-three-digits/VBScript/middle-three-digits.vb new file mode 100644 index 0000000000..b3d57a38fa --- /dev/null +++ b/Task/Middle-three-digits/VBScript/middle-three-digits.vb @@ -0,0 +1,21 @@ +'http://rosettacode.org/wiki/Middle_three_digits + +Function mid3n(n) + 'Remove the number's sign. + n = CStr(Abs(n)) + If Len(n) < 3 Or Len(n) Mod 2 = 0 Then + mid3n = "Invalid: Either the length of n < 3 or an even number." + ElseIf Round(Len(n)/2) > Len(n)/2 Then + mid3n = Mid(n,Round(Len(n)/2)-1,3) + Else + mid3n = Mid(n,Round(Len(n)/2),3) + End If +End Function + +'Calling the function. +arrn = Array(123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,_ + 1,2,-1,-10,2002,-2002,0) +For Each n In arrn + WScript.StdOut.Write n & ": " & mid3n(n) + WScript.StdOut.WriteLine +Next diff --git a/Task/Minesweeper-game/J/minesweeper-game-1.j b/Task/Minesweeper-game/J/minesweeper-game-1.j index b564708dd9..f9ddc934bf 100644 --- a/Task/Minesweeper-game/J/minesweeper-game-1.j +++ b/Task/Minesweeper-game/J/minesweeper-game-1.j @@ -58,7 +58,10 @@ coinsert 'mineswpeng' NB. insert game engine locale in copath Tiles=: ' 12345678**.?' -create=: ] startgame@[ smoutput bind Instructions +create=: verb define + smoutput Instructions + startgame y +) destroy=: codestroy quit=: destroy diff --git a/Task/Minesweeper-game/Perl-6/minesweeper-game.pl6 b/Task/Minesweeper-game/Perl-6/minesweeper-game.pl6 index 24e1cbf105..891ed367e3 100644 --- a/Task/Minesweeper-game/Perl-6/minesweeper-game.pl6 +++ b/Task/Minesweeper-game/Perl-6/minesweeper-game.pl6 @@ -3,46 +3,47 @@ enum Tile-Type ; class Tile { has Tile-Type $.type; has $.face is rw; - method Str { $.face // '.' } + method Str { with $!face { ~$!face } else { '.' } } } class Field { - has Tile @!grid; - has Int $!width; - has Int $!height; - has Int $!mine-spots is rw; - has Int $!empty-spots is rw; + has @.grid; + has Int $.width; + has Int $.height; + has Int $.mine-spots; + has Int $.empty-spots; - method new (Int $width, Int $height, Num $mines-ratio=0.1) { + method new (Int $height, Int $width, Rat $mines-ratio=0.1) { - my $mine-spots = $width*$height*$mines-ratio; + my $mine-spots = round $width*$height*$mines-ratio; my $empty-spots = $width*$height - $mine-spots; my @grid; - for ^$width X ^$height -> $i, $j { - @grid[$i][$j] = Tile.new(type => Empty); + for ^$height X ^$width -> ($y, $x) { + @grid[$y][$x] = Tile.new(type => Empty); } - for (^$width).pick($mine-spots) Z (^$height).pick($mine-spots) -> $i, $j { - @grid[$i][$j] = Tile.new( type => Mine); + for (^$height).pick($mine-spots) Z (^$width).pick($mine-spots) -> ($y, $x) { + @grid[$y][$x] = Tile.new( type => Mine); } - self.bless(*, :$width, :$height, :@grid, :$mine-spots, :$empty-spots); + self.bless(:$height, :$width, :@grid, :$mine-spots, :$empty-spots); } - method open( $i, $j) { - return if @!grid[$i][$j].face.defined; + method open( $y, $x) { + return if @!grid[$y][$x].face.defined; - self.end-game("KaBoom") if @!grid[$i][$j].type ~~ Mine; + self.end-game("KaBoom") if @!grid[$y][$x].type ~~ Mine; - my @neighbors = gather take [$i+.[0],$j+.[1]] - if 0 <= $i + .[0] < $!width && 0 <= $j + .[1] < $!height - for [-1,-1],[+0,-1],[+1,-1], - [-1,+0],( ),[+1,+0], - [-1,+1],[+0,+1],[+1,+1]; + my @neighbors = gather do + take [$y+.[0],$x+.[1]] + if 0 <= $y + .[0] < $!height && 0 <= $x + .[1] < $!width + for [-1,-1],[+0,-1],[+1,-1], + [-1,+0], [+1,+0], + [-1,+1],[+0,+1],[+1,+1]; - my $mines = [+] @neighbors.map: { @!grid[.[0]][.[1]].type ~~ Mine }; + my $mines = +@neighbors.grep: { @!grid[.[0]][.[1]].type ~~ Mine }; $!empty-spots--; - @!grid[$i][$j].face = $mines > 0 ?? $mines !! ' '; + @!grid[$y][$x].face = $mines || ' '; if $mines == 0 { self.open(.[0], .[1]) for @neighbors; @@ -51,53 +52,60 @@ class Field { } method end-game(Str $msg ) { - for ^$!width X ^$!height -> $i, $j { - @!grid[$i][$j].face = '*' if @!grid[$i][$j].type ~~ Mine + for ^$!height X ^$!width -> ($y, $x) { + @!grid[$y][$x].face = '*' if @!grid[$y][$x].type ~~ Mine } die $msg; } - method mark ( $i, $j) { - if !@!grid[$i][$j].face.defined { - @!grid[$i][$j].face = "⚐"; - $!mine-spots-- if @!grid[$i][$j].type ~~ Mine; - }elsif !@!grid[$i][$j].face eq "⚐" { - undefine @!grid[$i][$j].face; - $!mine-spots++ if @!grid[$i][$j].type ~~ Mine; + method mark ( $y, $x) { + if !@!grid[$y][$x].face.defined { + @!grid[$y][$x].face = "⚐"; + $!mine-spots-- if @!grid[$y][$x].type ~~ Mine; + } + elsif !@!grid[$y][$x].face eq "⚐" { + undefine @!grid[$y][$x].face; + $!mine-spots++ if @!grid[$y][$x].type ~~ Mine; } self.end-game("You won") if $!mine-spots == 0; } - method Str { - [~] '┌', '─' xx $!height, "┐\n", - join '', do for ^$!width -> $i { - '│', @!grid[$i][*], "│\n"; - }, '└', '─' xx $!height, '┘'; - } + constant @digs = |('a'..'z') xx *; - method valid ($i, $j) { - 0 <= $i < $!width && 0 <= $j < $!height + method Str { + [~] flat ' ', @digs[^$!width], "\n", + ' ┌', '─' xx $!width, "┐\n", + join '', do for ^$!height -> $y { + $y, '│', @!grid[$y][*], "│\n"; }, + ' └', '─' xx $!width, '┘'; + } + + method valid ($y, $x) { + 0 <= $y < $!height && 0 <= $x < $!width } } +sub a2n($a) { $a.ord > 64 ?? $a.ord % 32 - 1 !! +$a } + my $f = Field.new(6,10); loop { - say $f; - my ($c,$x,$y) = prompt("[open|mark] x y: ").split(/\s+/); - try { - given $c { - when !$f.valid($y,$x) { say "invalid coordinates" } - when 'open' { $f.open($y,$x) } - when 'mark' { $f.mark($y,$x) } - default {say "invalid cmd" } - } - CATCH { - say "$!: end of game."; - return; - } + say ~$f; + my @w = prompt("[open loc|mark loc|loc]: ").words; + last unless @w; + unshift @w, 'open' if @w < 2; + my ($x,$y) = $0, $1 if @w[1] ~~ /()()|$1=$0=/; + $x = a2n($x); + given @w[0] { + when !$f.valid($y,$x) { say "invalid coordinates" } + when /^o/ { $f.open($y,$x) } + when /^m/ { $f.mark($y,$x) } + default { say "invalid cmd" } + } + CATCH { + say "$_: end of game."; + last; } - last if $!; } -say $f; +say ~$f; diff --git a/Task/Modular-exponentiation/00DESCRIPTION b/Task/Modular-exponentiation/00DESCRIPTION index 2ef185c14d..4f4d3941a8 100644 --- a/Task/Modular-exponentiation/00DESCRIPTION +++ b/Task/Modular-exponentiation/00DESCRIPTION @@ -3,6 +3,6 @@ Find the last 40 decimal digits of a^b, where * a = 2988348162058574136915891421498819466320163312926952423791023078876139 * b = 2351399303373464486466122544523690094744975233415544072992656881240319 -A computer is too slow to find the entire value of a^b. Instead, the program must use a fast algorithm for modular exponentiation: a^b \mod m. +A computer is too slow to find the entire value of a^b. Instead, the program must use a fast algorithm for [[wp:Modular exponentiation|modular exponentiation]]: a^b \mod m. The algorithm must work for any integers a, b, m where b \ge 0 and m > 0. diff --git a/Task/Modular-exponentiation/ALGOL-68/modular-exponentiation.alg b/Task/Modular-exponentiation/ALGOL-68/modular-exponentiation.alg new file mode 100644 index 0000000000..695cd0e7de --- /dev/null +++ b/Task/Modular-exponentiation/ALGOL-68/modular-exponentiation.alg @@ -0,0 +1,23 @@ +BEGIN + PR precision=1000 PR + MODE LLI = LONG LONG INT; CO For brevity CO + PROC mod power = (LLI base, exponent, modulus) LLI : + BEGIN + LLI result := 1, b := base, e := exponent; + IF exponent < 0 + THEN + put (stand error, (("Negative exponent", exponent, newline))) + ELSE + WHILE e > 0 + DO + (ODD e | result := (result * b) MOD modulus); + e OVERAB 2; b := (b * b) MOD modulus + OD + FI; + result + END; + LLI a = 2988348162058574136915891421498819466320163312926952423791023078876139; + LLI b = 2351399303373464486466122544523690094744975233415544072992656881240319; + LLI m = 10000000000000000000000000000000000000000; + printf (($"Last 40 digits = ", 40dl$, mod power (a, b, m))) +END diff --git a/Task/Modular-exponentiation/OCaml/modular-exponentiation.ocaml b/Task/Modular-exponentiation/OCaml/modular-exponentiation.ocaml new file mode 100644 index 0000000000..3e087e8ffd --- /dev/null +++ b/Task/Modular-exponentiation/OCaml/modular-exponentiation.ocaml @@ -0,0 +1,6 @@ +let a = Z.of_string "2988348162058574136915891421498819466320163312926952423791023078876139" in +let b = Z.of_string "2351399303373464486466122544523690094744975233415544072992656881240319" in +let m = Z.pow (Z.of_int 10) 40 in +Z.powm a b m +|> Z.to_string +|> print_endline diff --git a/Task/Modular-inverse/ALGOL-68/modular-inverse.alg b/Task/Modular-inverse/ALGOL-68/modular-inverse.alg new file mode 100644 index 0000000000..ddc2a3a150 --- /dev/null +++ b/Task/Modular-inverse/ALGOL-68/modular-inverse.alg @@ -0,0 +1,35 @@ +BEGIN + PROC modular inverse = (INT a, m) INT : + BEGIN + PROC extended gcd = (INT x, y) []INT : +CO + Algol 68 allows us to return three INTs in several ways. A [3]INT + is used here but it could just as well be a STRUCT. +CO + BEGIN + INT v := 1, a := 1, u := 0, b := 0, g := x, w := y; + WHILE w>0 + DO + INT q := g % w, t := a - q * u; + a := u; u := t; + t := b - q * v; + b := v; v := t; + t := g - q * w; + g := w; w := t + OD; + a PLUSAB (a < 0 | u | 0); + (a, b, g) + END; + [] INT egcd = extended gcd (a, m); + (egcd[3] > 1 | 0 | egcd[1] MOD m) + END; + printf (($"42 ^ -1 (mod 2017) = ", g(0)$, modular inverse (42, 2017))) +CO + Note that if ϕ(m) is known, then a^-1 = a^(ϕ(m)-1) mod m which + allows an alternative implementation in terms of modular + exponentiation but, in general, this requires the factorization of + m. If m is prime the factorization is trivial and ϕ(m) = m-1. + 2017 is prime which may, or may not, be ironic within the context + of the Rosetta Code conditions. +CO +END diff --git a/Task/Modular-inverse/Batch-File/modular-inverse.bat b/Task/Modular-inverse/Batch-File/modular-inverse.bat new file mode 100644 index 0000000000..93f74fafee --- /dev/null +++ b/Task/Modular-inverse/Batch-File/modular-inverse.bat @@ -0,0 +1,43 @@ +@echo off +setlocal enabledelayedexpansion + %== Calls the "function" ==% +call :ModInv 42 2017 result +echo !result! +call :ModInv 40 1 result +echo !result! +call :ModInv 52 -217 result +echo !result! +call :ModInv -486 217 result +echo !result! +call :ModInv 40 2018 result +echo !result! +pause>nul +exit /b 0 + + %== The "function" ==% +:ModInv + set a=%1 + set b=%2 + + if !b! lss 0 (set /a b=-b) + if !a! lss 0 (set /a a=b - ^(-a %% b^)) + + set t=0&set nt=1&set r=!b!&set /a nr=a%%b + + :while_loop + if !nr! neq 0 ( + set /a q=r/nr + set /a tmp=nt + set /a nt=t - ^(q*nt^) + set /a t=tmp + + set /a tmp=nr + set /a nr=r - ^(q*nr^) + set /a r=tmp + goto while_loop + ) + + if !r! gtr 1 (set %3=-1&goto :EOF) + if !t! lss 0 set /a t+=b + set %3=!t! + goto :EOF diff --git a/Task/Modular-inverse/Bracmat/modular-inverse.bracmat b/Task/Modular-inverse/Bracmat/modular-inverse.bracmat new file mode 100644 index 0000000000..2e81c19389 --- /dev/null +++ b/Task/Modular-inverse/Bracmat/modular-inverse.bracmat @@ -0,0 +1,16 @@ +( ( mod-inv + = a b b0 x0 x1 q + . !arg:(?a.?b) + & ( !b:1 + | (!b.0.1):(?b0.?x0.?x1) + & whl + ' ( !a:>1 + & div$(!a.!b):?q + & (!b.mod$(!a.!b)):(?a.?b) + & (!x1+-1*!q*!x0.!x0):(?x0.?x1) + ) + & (!x:>0|!x1+!b0) + ) + ) +& out$(mod-inv$(42.2017)) +}; diff --git a/Task/Modular-inverse/PHP/modular-inverse.php b/Task/Modular-inverse/PHP/modular-inverse.php new file mode 100644 index 0000000000..ef0a5838e1 --- /dev/null +++ b/Task/Modular-inverse/PHP/modular-inverse.php @@ -0,0 +1,16 @@ + 1) return -1; + if ($t < 0) $t += $n; + return $t; +} + printf("%d\n", invmod(42, 2017)); +?> diff --git a/Task/Modular-inverse/Pascal/modular-inverse.pascal b/Task/Modular-inverse/Pascal/modular-inverse.pascal new file mode 100644 index 0000000000..f892027bc6 --- /dev/null +++ b/Task/Modular-inverse/Pascal/modular-inverse.pascal @@ -0,0 +1,24 @@ +// increments e step times until bal is greater than t +// repeats until bal = 1 (mod = 1) and returns count +// bal will not be greater than t + e + +function modInv(e, t : integer) : integer; + var + d : integer; + bal, count, step : integer; + begin + d := 0; + if e < t then + begin + count := 1; + bal := e; + repeat + step := ((t-bal) DIV e)+1; + bal := bal + step * e; + count := count + step; + bal := bal - t; + until bal = 1; + d := count; + end; + modInv := d; + end; diff --git a/Task/Modular-inverse/PowerShell/modular-inverse.psh b/Task/Modular-inverse/PowerShell/modular-inverse.psh new file mode 100644 index 0000000000..63e71b03fe --- /dev/null +++ b/Task/Modular-inverse/PowerShell/modular-inverse.psh @@ -0,0 +1,23 @@ +function invmod($a,$n){ + if ([int]$n -lt 0) {$n = -$n} + if ([int]$a -lt 0) {$a = $n - ((-$a) % $n)} + + $t = 0 + $nt = 1 + $r = $n + $nr = $a % $n + while ($nr -ne 0) { + $q = [Math]::truncate($r/$nr) + $tmp = $nt + $nt = $t - $q*$nt + $t = $tmp + $tmp = $nr + $nr = $r - $q*$nr + $r = $tmp + } + if ($r -gt 1) {return -1} + if ($t -lt 0) {$t += $n} + return $t +} + +invmod 42 2017 diff --git a/Task/Modular-inverse/Scala/modular-inverse.scala b/Task/Modular-inverse/Scala/modular-inverse.scala new file mode 100644 index 0000000000..23c7268fc9 --- /dev/null +++ b/Task/Modular-inverse/Scala/modular-inverse.scala @@ -0,0 +1,15 @@ +def gcdExt(u: Int, v: Int): (Int, Int, Int) = { + @tailrec + def aux(a: Int, b: Int, x: Int, y: Int, x1: Int, x2: Int, y1: Int, y2: Int): (Int, Int, Int) = { + if(b == 0) (x, y, a) else { + val (q, r) = (a / b, a % b) + aux(b, r, x2 - q * x1, y2 - q * y1, x, x1, y, y1) + } + } + aux(u, v, 1, 0, 0, 1, 1, 0) +} + +def modInv(a: Int, m: Int): Option[Int] = { + val (i, j, g) = gcdExt(a, m) + if (g == 1) Option(if (i < 0) i + m else i) else Option.empty +} diff --git a/Task/Monte-Carlo-methods/C++/monte-carlo-methods.cpp b/Task/Monte-Carlo-methods/C++/monte-carlo-methods.cpp new file mode 100644 index 0000000000..06bdaf0aaf --- /dev/null +++ b/Task/Monte-Carlo-methods/C++/monte-carlo-methods.cpp @@ -0,0 +1,21 @@ +#include +#include +#include +#include + +using namespace std; +int main(){ + int jmax=1000; // maximum value of HIT number. (Length of output file) + int imax=1000; // maximum value of random numbers for producing HITs. + double x,y; // Coordinates + int hit; // storage variable of number of HITs + srand(time(0)); + for (int j=0;j + x = :random.uniform + y = :random.uniform + :math.sqrt(x*x + y*y) <= 1 + end) + 4 * count / n + end +end + +Enum.each([1000, 10000, 100000, 1000000, 10000000], fn n -> + :io.format "~8w samples: PI = ~f~n", [n, MonteCarlo.pi(n)] +end) diff --git a/Task/Monte-Carlo-methods/J/monte-carlo-methods-1.j b/Task/Monte-Carlo-methods/J/monte-carlo-methods-1.j index 98d202644c..add2e3e53e 100644 --- a/Task/Monte-Carlo-methods/J/monte-carlo-methods-1.j +++ b/Task/Monte-Carlo-methods/J/monte-carlo-methods-1.j @@ -1,3 +1,3 @@ piMC=: monad define "0 - 4* y%~ +/ 1>: %:+/*: <:+: (2,y) ?@$ 0 + 4* y%~ +/ 1>: %: +/ *: <: +: (2,y) ?@$ 0 ) diff --git a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-1.pl6 b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-1.pl6 index 2b2c50251d..b5fbc11ea8 100644 --- a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-1.pl6 +++ b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-1.pl6 @@ -1,4 +1,4 @@ -my @random_distances := ([+] rand**2 xx 2) xx *; +my @random_distances = ([+] rand**2 xx 2) xx *; sub approximate_pi(Int $n) { 4 * @random_distances[^$n].grep(* < 1) / $n diff --git a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-2.pl6 b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-2.pl6 index e5e73c32ba..ed8a4ddf56 100644 --- a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-2.pl6 +++ b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-2.pl6 @@ -1,2 +1,2 @@ -my @pi := ([\+] 4 * (1 > [+] rand**2 xx 2) xx *) Z/ 1 .. *; +my @pi = ([\+] 4 * (1 > [+] rand**2 xx 2) xx *) Z/ 1 .. *; say @pi[10, 1000, 10_000]; diff --git a/Task/Monte-Carlo-methods/REXX/monte-carlo-methods.rexx b/Task/Monte-Carlo-methods/REXX/monte-carlo-methods.rexx index 2b6f83b8c8..7287daebeb 100644 --- a/Task/Monte-Carlo-methods/REXX/monte-carlo-methods.rexx +++ b/Task/Monte-Carlo-methods/REXX/monte-carlo-methods.rexx @@ -1,33 +1,32 @@ -/*REXX program computes pi÷4 using the Monte Carlo algorithm. */ -parse arg times chunks . /*does user want a specific num? */ -if times=='' then times=1000000000 /*one billion should do it. */ -if chunks=='' then chunks=10000 /*do Monte Carlo in 10k chunks. */ -limit=10000-1 /*REXX random gens only integers.*/ -limitSq=limit**2 /*···so, instead of 1, use lim**2*/ -!=0 /*number of "pi hits" so far. */ -accur=0 /*accuracy of the Monte Carlo pi.*/ -if 1=='f1'x then piChar='pi' /*if EBCDIC, then use literal. */ - else piChar='e3'x /*if ASCII, then use pi symbol.*/ +/*REXX program computes pi ÷ 4 using the Monte Carlo algorithm. */ +parse arg times chunks . /*does user want a specific number? */ +if times=='' then times=1000000000 /*one billion should do it, me thinks. */ +if chunks=='' then chunks=10000 /*do Monte Carlo in 10,000 chunks. */ +limit=10000-1 /*REXX random generates only integers. */ +limitSq=limit**2 /*··· so, instead of one, use limit**2.*/ +!=0 /*the number of "pi hits" (so far). */ +accur=0 /*accuracy of Monte Carlo pi (so far). */ +if 1=='f1'x then piChar='pi' /*if EBCDIC, then use literal. */ + else piChar='e3'x /* " ASCII, " " pi glyph, */ -pi=3.14159265358979323846264338327950288419716939937511 /*da real McCoy*/ -numeric digits length(pi) /*at least, we'll use these digs.*/ -say 'real pi='pi"+" /*might was well brag about it. */ -say /*just for the eyeballs. */ +pi=3.14159265358979323846264338327950288419716939937511 /*this, da real McCoy*/ +numeric digits length(pi) /*this program uses these decimal digs.*/ +say 'real pi='pi"+" /*we might as well brag about it. */ +say /*a blank line, just for the eyeballs. */ do j=1 for times%chunks - do chunks /*do Monte Carlo, chunk-at-a-time*/ + do chunks /*do Monte Carlo, one chunk-at-a-time.*/ if random(0,limit)**2 + random(0,limit)**2 <=limitSq then !=!+1 end /*chunks*/ - reps=chunks*j /*compute number of repetitions. */ - piX=4*!/reps /*let's see how this puppy does. */ - _=compare(piX,pi) /*compare apples & ···crabapples.*/ - if _<=accur then iterate /*if not better accuracy, pout. */ - say right(comma(reps),20) 'repetitions: Monte Carlo' piChar, - "is accurate to" _-1 'places.' /*subtract 1 for dec point.*/ - accur=_ /*use this accuracy for baseline.*/ + reps=chunks*j /*compute the number of repetitions. */ + piX=4*!/reps /*let's see how this puppy does so far.*/ + _=compare(piX,pi) /*compare apples and ··· crabapples. */ + if _<=accur then iterate /*if not better accuracy, keep going. */ + say right(commas(reps),20) 'repetitions: Monte Carlo' piChar, + "is accurate to" _-1 'places.' /*subtract one for decimal point.*/ + accur=_ /*use this accuracy for the baseline. */ end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*────────────────────────────────COMMA subroutine────────────────────────────────────────────────────────────────────────────────────*/ -comma: procedure; parse arg _,c,p,t; arg ,cu; c=word(c ",",1); if cu=='BLANK' then c=' '; o=word(p 3,1); p=abs(o); t=word(t 999999999,1) -if \datatype(p,'W') | \datatype(t,'W') | p==0 | arg()>4 then return _; n=_'.9'; #=123456789; k=0; if o<0 then do; b=verify(_,' ') -if b==0 then return _; e=length(_) - verify(reverse(_),' ') + 1; end; else do; -b=verify(n,#,"M"); e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end; do j=e to b by -p while k 1000000 && numTasks < maxTasks ) do numTasks += 1; +const tasks = 1..#numTasks; +const games_per_task = games / numTasks ; +const remaining_games = games % numTasks ; + +var wins_by_stay: [tasks] int; + +coforall task in tasks { + + var rand = new RandomStream(); + + for game in 1..#games_per_task { + var player_door = (rand.getNext() * 1000): int % doors ; + var winning_door = (rand.getNext() * 1000): int % doors ; + if player_door == winning_door then + wins_by_stay[ task ] += 1; + } + + if task == tasks.last then { + for game in 1..#remaining_games { + var player_door = (rand.getNext() * 1000): int % doors ; + var winning_door = (rand.getNext() * 1000): int % doors ; + if player_door == winning_door then + wins_by_stay[ task ] += 1; + } + } + +} + +var total_by_stay = + reduce wins_by_stay; + +var total_by_switch = games - total_by_stay; +var percent_by_stay = ((total_by_stay: real) / games) * 100; +var percent_by_switch = ((total_by_switch: real) / games) * 100; + +writeln( "Wins by staying: ", total_by_stay, " or ", percent_by_stay, "%" ); +writeln( "Wins by switching: ", total_by_switch, " or ", percent_by_switch, "%" ); +if ( total_by_stay > total_by_switch ){ + writeln( "Staying is the superior method." ); +} else if( total_by_stay < total_by_switch ){ + writeln( "Switching is the superior method." ); +} else { + writeln( "Both methods are equal." ); +} diff --git a/Task/Monty-Hall-problem/Elixir/monty-hall-problem.elixir b/Task/Monty-Hall-problem/Elixir/monty-hall-problem.elixir new file mode 100644 index 0000000000..7dbfe16b39 --- /dev/null +++ b/Task/Monty-Hall-problem/Elixir/monty-hall-problem.elixir @@ -0,0 +1,24 @@ +defmodule MontyHall do + def simulate(n) do + :random.seed(:os.timestamp) + {stay, switch} = simulate(n, 0, 0) + :io.format "Staying wins ~w times (~.3f%)~n", [stay, 100 * stay / n] + :io.format "Switching wins ~w times (~.3f%)~n", [switch, 100 * switch / n] + end + + defp simulate(0, stay, switch), do: {stay, switch} + defp simulate(n, stay, switch) do + doors = Enum.shuffle([:goat, :goat, :car]) + guess = :random.uniform(3) - 1 + [choice] = [0,1,2] -- [guess, shown(doors, guess)] + if Enum.at(doors, choice) == :car, do: simulate(n-1, stay, switch+1), + else: simulate(n-1, stay+1, switch) + end + + defp shown(doors, guess) do + [i, j] = Enum.shuffle([0,1,2] -- [guess]) + if Enum.at(doors, i) == :goat, do: i, else: j + end +end + +MontyHall.simulate(10000) diff --git a/Task/Monty-Hall-problem/Julia/monty-hall-problem-1.julia b/Task/Monty-Hall-problem/Julia/monty-hall-problem-1.julia new file mode 100644 index 0000000000..538dae752a --- /dev/null +++ b/Task/Monty-Hall-problem/Julia/monty-hall-problem-1.julia @@ -0,0 +1,20 @@ +function play_mh_literal{T<:Integer}(ncur::T=3, ncar::T=1) + ncar < ncur || throw(DomainError()) + curtains = shuffle(collect(1:ncur)) + cars = curtains[1:ncar] + goats = curtains[(ncar+1):end] + pick = rand(1:ncur) + isstickwin = pick in cars + deleteat!(curtains, findin(curtains, pick)) + if !isstickwin + deleteat!(goats, findin(goats, pick)) + end + if length(goats) > 0 # reveal goat + deleteat!(curtains, findin(curtains, shuffle(goats)[1])) + else # no goats, so reveal car + deleteat!(curtains, rand(1:(ncur-1))) + end + pick = shuffle(curtains)[1] + isswitchwin = pick in cars + return (isstickwin, isswitchwin) +end diff --git a/Task/Monty-Hall-problem/Julia/monty-hall-problem-2.julia b/Task/Monty-Hall-problem/Julia/monty-hall-problem-2.julia new file mode 100644 index 0000000000..63cfa2c18c --- /dev/null +++ b/Task/Monty-Hall-problem/Julia/monty-hall-problem-2.julia @@ -0,0 +1,11 @@ +function play_mh_clean{T<:Integer}(ncur::T=3, ncar::T=1) + ncar < ncur || throw(DomainError()) + pick = rand(1:ncur) + isstickwin = pick <= ncar + pick = rand(1:(ncur-2)) + if isstickwin # remove initially picked car from consideration + pick += 1 + end + isswitchwin = pick <= ncar + return (isstickwin, isswitchwin) +end diff --git a/Task/Monty-Hall-problem/Julia/monty-hall-problem-3.julia b/Task/Monty-Hall-problem/Julia/monty-hall-problem-3.julia new file mode 100644 index 0000000000..2f4c46b411 --- /dev/null +++ b/Task/Monty-Hall-problem/Julia/monty-hall-problem-3.julia @@ -0,0 +1,44 @@ +function mh_results{T<:Integer}(ncur::T, ncar::T, + nruns::T, play_mh::Function) + stickwins = 0 + switchwins = 0 + for i in 1:nruns + (isstickwin, isswitchwin) = play_mh(ncur, ncar) + if isstickwin + stickwins += 1 + end + if isswitchwin + switchwins += 1 + end + end + return (stickwins/nruns, switchwins/nruns) +end + +function mh_analytic{T<:Integer}(ncur::T, ncar::T) + stickodds = ncar/ncur + switchodds = (ncar - stickodds)/(ncur-2) + return (stickodds, switchodds) +end + +function show_odds{T<:Real}(a::T, b::T) + @sprintf " %.1f %.1f %.2f" 100.0*a 100*b 1.0*b/a +end + +function show_simulation{T<:Integer}(ncur::T, ncar::T, nruns::T) + println() + print("Simulating a ", ncur, " door, ", ncar, " car ") + println("Monty Hall problem with ", nruns, " runs.\n") + + println(" Solution Stick Switch Improvement") + + (a, b) = mh_results(ncur, ncar, nruns, play_mh_literal) + println(@sprintf("%10s: ", "Literal"), show_odds(a, b)) + + (a, b) = mh_results(ncur, ncar, nruns, play_mh_clean) + println(@sprintf("%10s: ", "Clean"), show_odds(a, b)) + + (a, b) = mh_analytic(ncur, ncar) + println(@sprintf("%10s: ", "Analytic"), show_odds(a, b)) + println() + return nothing +end diff --git a/Task/Monty-Hall-problem/Julia/monty-hall-problem-4.julia b/Task/Monty-Hall-problem/Julia/monty-hall-problem-4.julia new file mode 100644 index 0000000000..b493922af4 --- /dev/null +++ b/Task/Monty-Hall-problem/Julia/monty-hall-problem-4.julia @@ -0,0 +1,3 @@ +for i in 3:5, j in 1:(i-2) + show_simulation(i, j, 10^5) +end diff --git a/Task/Monty-Hall-problem/Perl-6/monty-hall-problem.pl6 b/Task/Monty-Hall-problem/Perl-6/monty-hall-problem.pl6 index 7979c301b2..3edf9d3bd1 100644 --- a/Task/Monty-Hall-problem/Perl-6/monty-hall-problem.pl6 +++ b/Task/Monty-Hall-problem/Perl-6/monty-hall-problem.pl6 @@ -5,15 +5,18 @@ sub play (Strategy $strategy, Int :$doors = 3) returns Prize { # Call the door with a car behind it door 0. Number the # remaining doors starting from 1. - my Prize @doors = Car, Goat xx $doors - 1; + my Prize @doors = flat Car, Goat xx $doors - 1; # The player chooses a door. my Prize $initial_pick = @doors.splice(@doors.keys.pick,1)[0]; # Of the n doors remaining, the host chooses n - 1 that have # goats behind them and opens them, removing them from play. - @doors.splice($_,1) - for pick @doors.elems - 1, grep { @doors[$_] == Goat }, keys @doors; + while @doors > 1 { + @doors.splice($_,1) + when Goat + given @doors.keys.pick; + } # If the player stays, they get their initial pick. Otherwise, # they get whatever's behind the remaining door. diff --git a/Task/Morse-code/Ada/morse-code-1.ada b/Task/Morse-code/Ada/morse-code-1.ada index 536ce71a86..5a0dcf8531 100644 --- a/Task/Morse-code/Ada/morse-code-1.ada +++ b/Task/Morse-code/Ada/morse-code-1.ada @@ -28,7 +28,7 @@ private 'G' => (3, "--. "), 'H' => (4, ".... "), 'I' => (2, ".. "), 'J' => (4, ".--- "), 'K' => (3, "-.- "), 'L' => (4, ".-.. "), 'M' => (2, "-- "), 'N' => (2, "-. "), 'O' => (3, "--- "), - 'P' => (4, "--.- "), 'Q' => (4, "--.- "), 'R' => (3, ".-. "), + 'P' => (4, ".--. "), 'Q' => (4, "--.- "), 'R' => (3, ".-. "), 'S' => (3, "... "), 'T' => (1, "- "), 'U' => (3, "..- "), 'V' => (4, "...- "), 'W' => (3, ".-- "), 'X' => (4, "-..- "), 'Y' => (4, "-.-- "), 'Z' => (4, "--.. "), '1' => (5, ".----"), diff --git a/Task/Morse-code/Elixir/morse-code.elixir b/Task/Morse-code/Elixir/morse-code.elixir new file mode 100644 index 0000000000..b4846280bf --- /dev/null +++ b/Task/Morse-code/Elixir/morse-code.elixir @@ -0,0 +1,26 @@ +defmodule Morse do + @morse %{"!" => "---.", "\"" => ".-..-.", "$" => "...-..-", "'" => ".----.", + "(" => "-.--.", ")" => "-.--.-", "+" => ".-.-.", "," => "--..--", + "-" => "-....-", "." => ".-.-.-", "/" => "-..-.", + "0" => "-----", "1" => ".----", "2" => "..---", "3" => "...--", + "4" => "....-", "5" => ".....", "6" => "-....", "7" => "--...", + "8" => "---..", "9" => "----.", + ":" => "---...", ";" => "-.-.-.", "=" => "-...-", "?" => "..--..", + "@" => ".--.-.", + "A" => ".-", "B" => "-...", "C" => "-.-.", "D" => "-..", + "E" => ".", "F" => "..-.", "G" => "--.", "H" => "....", + "I" => "..", "J" => ".---", "K" => "-.-", "L" => ".-..", + "M" => "--", "N" => "-.", "O" => "---", "P" => ".--.", + "Q" => "--.-", "R" => ".-.", "S" => "...", "T" => "-", + "U" => "..-", "V" => "...-", "W" => ".--", "X" => "-..-", + "Y" => "-.--", "Z" => "--..", + "[" => "-.--.", "]" => "-.--.-", "_" => "..--.-" } + def code(text) do + String.upcase(text) + |> String.codepoints + |> Enum.map(fn c -> Dict.get(@morse, c, " ") end) + |> Enum.join(" ") + end +end + +IO.puts Morse.code("Hello, World!") diff --git a/Task/Morse-code/Go/morse-code.go b/Task/Morse-code/Go/morse-code.go new file mode 100644 index 0000000000..5827cb760f --- /dev/null +++ b/Task/Morse-code/Go/morse-code.go @@ -0,0 +1,153 @@ +// Command morse translates an input string into morse code, +// showing the output on the console, and playing it as sound. +// Only works on ubuntu. +package main + +import ( + "flag" + "fmt" + "log" + "regexp" + "strings" + "syscall" + "time" + "unicode" +) + +// A key represents an action on the morse key. +// It's either on or off, for the given duration. +type key struct { + duration int + on bool + sym string // for debug output +} + +var ( + runeToKeys = map[rune][]key{} + interCharGap = []key{{1, false, ""}} + punctGap = []key{{7, false, " / "}} + charGap = []key{{3, false, " "}} + wordGap = []key{{7, false, " / "}} +) + +const rawMorse = ` +A:.- J:.--- S:... 1:.---- .:.-.-.- ::---... +B:-... K:-.- T:- 2:..--- ,:--..-- ;:-.-.-. +C:-.-. L:.-.. U:..- 3:...-- ?:..--.. =:-...- +D:-.. M:-- V:...- 4:....- ':.----. +:.-.-. +E:. N:-. W:.-- 5:..... !:-.-.-- -:-....- +F:..-. O:--- X:-..- 6:-.... /:-..-. _:..--.- +G:--. P:.--. Y:-.-- 7:--... (:-.--. ":.-..-. +H:.... Q:--.- Z:--.. 8:---.. ):-.--.- $:...-..- +I:.. R:.-. 0:----- 9:----. &:.-... @:.--.-. +` + +func init() { + // Convert the rawMorse table into a map of morse key actions. + r := regexp.MustCompile("([^ ]):([.-]+)") + for _, m := range r.FindAllStringSubmatch(rawMorse, -1) { + c := m[1][0] + keys := []key{} + for i, dd := range m[2] { + if i > 0 { + keys = append(keys, interCharGap...) + } + if dd == '.' { + keys = append(keys, key{1, true, "."}) + } else if dd == '-' { + keys = append(keys, key{3, true, "-"}) + } else { + log.Fatalf("found %c in morse for %c", dd, c) + } + runeToKeys[rune(c)] = keys + runeToKeys[unicode.ToLower(rune(c))] = keys + } + } +} + +// MorseKeys translates an input string into a series of keys. +func MorseKeys(in string) ([]key, error) { + afterWord := false + afterChar := false + result := []key{} + for _, c := range in { + if unicode.IsSpace(c) { + afterWord = true + continue + } + morse, ok := runeToKeys[c] + if !ok { + return nil, fmt.Errorf("can't translate %c to morse", c) + } + if unicode.IsPunct(c) && afterChar { + result = append(result, punctGap...) + } else if afterWord { + result = append(result, wordGap...) + } else if afterChar { + result = append(result, charGap...) + } + result = append(result, morse...) + afterChar = true + afterWord = false + } + return result, nil +} + +func main() { + var ditDuration time.Duration + flag.DurationVar(&ditDuration, "d", 40*time.Millisecond, "length of dit") + flag.Parse() + in := "hello world." + if len(flag.Args()) > 1 { + in = strings.Join(flag.Args(), " ") + } + keys, err := MorseKeys(in) + if err != nil { + log.Fatalf("failed to translate: %s", err) + } + for _, k := range keys { + if k.on { + if err := note(true); err != nil { + log.Fatalf("failed to play note: %s", err) + } + } + fmt.Print(k.sym) + time.Sleep(ditDuration * time.Duration(k.duration)) + if k.on { + if err := note(false); err != nil { + log.Fatalf("failed to stop note: %s", err) + } + } + } + fmt.Println() +} + +// Implement sound on ubuntu. Needs permission to access /dev/console. + +var consoleFD uintptr + +func init() { + fd, err := syscall.Open("/dev/console", syscall.O_WRONLY, 0) + if err != nil { + log.Fatalf("failed to get console device: %s", err) + } + consoleFD = uintptr(fd) +} + +const KIOCSOUND = 0x4B2F +const clockTickRate = 1193180 +const freqHz = 600 + +// note either starts or stops a note. +func note(on bool) error { + arg := uintptr(0) + if on { + arg = clockTickRate / freqHz + } + _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg) + if errno != 0 { + return errno + } + return nil + +} diff --git a/Task/Morse-code/Lua/morse-code-1.lua b/Task/Morse-code/Lua/morse-code-1.lua new file mode 100644 index 0000000000..885705b494 --- /dev/null +++ b/Task/Morse-code/Lua/morse-code-1.lua @@ -0,0 +1,93 @@ +local M = {} + +-- module-local variables +local BUZZER = pio.PB_10 +local dit_length, dah_length, word_length + +-- module-local functions +local buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap + +buzz = function(duration) + pio.pin.output(BUZZER) + pio.pin.setlow(BUZZER) + tmr.delay(tmr.SYS_TIMER, duration) + pio.pin.sethigh(BUZZER) + pio.pin.input(BUZZER) +end + +dah = function() + buzz(dah_length) +end + +dit = function() + buzz(dit_length) +end + +init = function(baseline) + dit_length = baseline + dah_length = 2 * baseline + word_length = 4 * baseline +end + +inter_element_gap = function() + pause(dit_length) +end + +medium_gap = function() + pause(word_length) +end + +pause = function(duration) + tmr.delay(tmr.SYS_TIMER, duration) +end + +sequence = function(codes) + if codes then + for _,f in ipairs(codes) do + f() + inter_element_gap() + end + short_gap() + end +end + +short_gap = function() + pause(dah_length) +end + +local morse = { + a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit }, + d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit }, + g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit }, + j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit }, + m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah }, + p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit }, + s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah }, + v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah }, + y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit }, + + ["0"] = { dah, dah, dah, dah, dah }, ["1"] = { dit, dah, dah, dah, dah }, + ["2"] = { dit, dit, dah, dah, dah }, ["3"] = { dit, dit, dit, dah, dah }, + ["4"] = { dit, dit, dit, dit, dah }, ["5"] = { dit, dit, dit, dit, dit }, + ["6"] = { dah, dit, dit, dit, dit }, ["7"] = { dah, dah, dit, dit, dit }, + ["8"] = { dah, dah, dah, dit, dit }, ["9"] = { dah, dah, dah, dah, dit }, + + [" "] = { medium_gap } +} + +-- public interface +M.beep = function(message) + message = message:lower() + for _,ch in ipairs { message:byte(1, #message) } do + sequence(morse[string.char(ch)]) + end +end + +M.set_dit = function(duration) + init(duration) +end + +-- initialization code +init(50000) + +return M diff --git a/Task/Morse-code/Lua/morse-code-2.lua b/Task/Morse-code/Lua/morse-code-2.lua new file mode 100644 index 0000000000..1dbaa82a2a --- /dev/null +++ b/Task/Morse-code/Lua/morse-code-2.lua @@ -0,0 +1,2 @@ +morse = require 'morse' +morse.beep "I am the very model of a modern major-general." diff --git a/Task/Morse-code/Perl-6/morse-code.pl6 b/Task/Morse-code/Perl-6/morse-code.pl6 index 0f71f34ca9..911890b37d 100644 --- a/Task/Morse-code/Perl-6/morse-code.pl6 +++ b/Task/Morse-code/Perl-6/morse-code.pl6 @@ -1,5 +1,5 @@ my %m = ' ', '_ _ ', -< +|< ! ---. " .-..-. $ ...-..- @@ -58,7 +58,7 @@ my %m = ' ', '_ _ ', >.map: -> $c, $m is copy { $m.=subst(rx/'-'/, 'BGAAACK!!! ', :g); $m.=subst(rx/'.'/, 'buck ', :g); - $c => $m ~ '_ '; + $c => $m ~ '_'; } say prompt("Gimme a string: ").uc.comb.map: { %m{$_} // " " } diff --git a/Task/Move-to-front-algorithm/Elixir/move-to-front-algorithm.elixir b/Task/Move-to-front-algorithm/Elixir/move-to-front-algorithm.elixir new file mode 100644 index 0000000000..514ec2d77f --- /dev/null +++ b/Task/Move-to-front-algorithm/Elixir/move-to-front-algorithm.elixir @@ -0,0 +1,26 @@ +defmodule MoveToFront do + @table Enum.to_list(?a..?z) + + def encode(text), do: encode(to_char_list(text), @table, []) + + defp encode([], _, output), do: Enum.reverse(output) + defp encode([h|t], table, output) do + i = Enum.find_index(table, &(&1 == h)) + encode(t, move2front(table, i), [i | output]) + end + + def decode(indices), do: decode(indices, @table, []) + + defp decode([], _, output), do: Enum.reverse(output) |> to_string + defp decode([h|t], table, output) do + decode(t, move2front(table, h), [Enum.at(table, h) | output]) + end + + def move2front(table, i), do: [Enum.at(table,i) | List.delete_at(table, i)] +end + +Enum.each(["broood", "bananaaa", "hiphophiphop"], fn word -> + IO.inspect word + IO.inspect enc = MoveToFront.encode(word) + IO.puts "#{word == MoveToFront.decode(enc)}\n" +end) 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 index 09b8e32b01..e712486fc7 100644 --- a/Task/Move-to-front-algorithm/JavaScript/move-to-front-algorithm.js +++ b/Task/Move-to-front-algorithm/JavaScript/move-to-front-algorithm.js @@ -18,3 +18,14 @@ var decodeMTF = function (numList) { return acc; }, init).word; }; + +//test our algorithms +var words = ['broood', 'bananaaa', 'hiphophiphop']; +var encoded = words.map(encodeMTF); +var decoded = encoded.map(decodeMTF); + +//print results +console.log("from encoded:"); +console.log(encoded); +console.log("from decoded:"); +console.log(decoded); 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 index 30ea5b4a1f..8682258266 100644 --- 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 @@ -2,7 +2,7 @@ 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); + @sym[0 .. take (@sym ... $c).end] .= rotate(-1); } } diff --git a/Task/Move-to-front-algorithm/PowerShell/move-to-front-algorithm.psh b/Task/Move-to-front-algorithm/PowerShell/move-to-front-algorithm.psh new file mode 100644 index 0000000000..72c3f1f08c --- /dev/null +++ b/Task/Move-to-front-algorithm/PowerShell/move-to-front-algorithm.psh @@ -0,0 +1,75 @@ +Function Test-MTF +{ + [CmdletBinding()] + Param + ( + [Parameter(Mandatory=$true,Position=0)] + [string]$word, + + [Parameter(Mandatory=$false)] + [string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz' + ) + Begin + { + Function Encode + { + Param + ( + [Parameter(Mandatory=$true,Position=0)] + [string]$word, + + [Parameter(Mandatory=$false)] + [string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz' + ) + foreach ($letter in $word.ToCharArray()) + { + $index = $SymbolTable.IndexOf($letter) + + $prop = [ordered]@{ + Input = $letter + Output = [int]$index + SymbolTable = $SymbolTable + } + New-Object PSobject -Property $prop + $SymbolTable = $SymbolTable.Remove($index,1).Insert(0,$letter) + } + } + Function Decode + { + Param + ( + [Parameter(Mandatory=$true,Position=0)] + [int[]]$index, + + [Parameter(Mandatory=$false)] + [string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz' + ) + foreach ($i in $index) + { + #Write-host $i -ForegroundColor Red + $letter = $SymbolTable.Chars($i) + + $prop = [ordered]@{ + Input = $i + Output = $letter + SymbolTable = $SymbolTable + } + New-Object PSObject -Property $prop + $SymbolTable = $SymbolTable.Remove($i,1).Insert(0,$letter) + } + } + } + Process + { + #Encoding + Write-Host "Encoding $word" -NoNewline + $Encoded = (Encode -word $word).output + Write-Host -NoNewline ": $($Encoded -join ',')" + + #Decoding + Write-Host "`nDecoding $($Encoded -join ',')" -NoNewline + $Decoded = (Decode -index $Encoded).output -join '' + Write-Host -NoNewline ": $Decoded`n" + } + End{} +} diff --git a/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx index 8c1ef8c50d..ba2fc87b03 100644 --- a/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx +++ b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx @@ -1,21 +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*/ +/*REXX program demonstrates move─to─front algorithm encode/decode symbol table*/ +parse arg xxx; if xxx='' then xxx='broood bananaaa hiphophiphop' /*default*/ + one=1 /*(offset) for task's requirement.*/ + do j=1 for words(xxx); x=word(xxx,j) /*process one word at a time. */ + @='abcdefghijklmnopqrstuvwxyz'; @@=@ /*symbol table: lowercase alphabet*/ + $= /*set the decode string to a null.*/ + do k=1 for length(x); z=substr(x,k,1) /*encrypt a symbol in the word. */ + _=pos(z,@); if _==0 then iterate /*symbol position in symbol table.*/ + $=$ _-one; @=z || delstr(@,_,1) /*adjust the symbol table string. */ + end /*k*/ /* [↑] move─to─front encoding. */ - @='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*/ + @=@@ /*symbol table: lowercase alphabet*/ + != /*set the encode string to a null.*/ + do m=1 for words($); n=word($,m)+one /*decode the sequence table string*/ + y=substr(@,n,1); !=! || y /*the decode symbol of the word. */ + @=y || delstr(@,n,1) /*rebuild the symbol table string.*/ + end /*m*/ /* [↑] move─to─front decoding. */ - 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.*/ + say 'word: ' left(x,20) "encoding:" left($,35) word('wrong OK',1+(!==x)) + end /*j*/ /*all done encoding/decoding the words.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Move-to-front-algorithm/VBScript/move-to-front-algorithm.vb b/Task/Move-to-front-algorithm/VBScript/move-to-front-algorithm.vb new file mode 100644 index 0000000000..bd075524f1 --- /dev/null +++ b/Task/Move-to-front-algorithm/VBScript/move-to-front-algorithm.vb @@ -0,0 +1,49 @@ +Function mtf_encode(s) + 'create the array list and populate it with the initial symbol position + Set symbol_table = CreateObject("System.Collections.ArrayList") + For j = 97 To 122 'a to z in decimal. + symbol_table.Add Chr(j) + Next + output = "" + For i = 1 To Len(s) + char = Mid(s,i,1) + If i = Len(s) Then + output = output & symbol_table.IndexOf(char,0) + symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) + symbol_table.Insert 0,char + Else + output = output & symbol_table.IndexOf(char,0) & " " + symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) + symbol_table.Insert 0,char + End If + Next + mtf_encode = output +End Function + +Function mtf_decode(s) + 'break the function argument into an array + code = Split(s," ") + 'create the array list and populate it with the initial symbol position + Set symbol_table = CreateObject("System.Collections.ArrayList") + For j = 97 To 122 'a to z in decimal. + symbol_table.Add Chr(j) + Next + output = "" + For i = 0 To UBound(code) + char = symbol_table(code(i)) + output = output & char + If code(i) <> 0 Then + symbol_table.RemoveAt(symbol_table.LastIndexOf(char)) + symbol_table.Insert 0,char + End If + Next + mtf_decode = output +End Function + +'Testing the functions +wordlist = Array("broood","bananaaa","hiphophiphop") +For Each word In wordlist + WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_ + mtf_decode(mtf_encode(word)) & "." + WScript.StdOut.WriteBlankLines(1) +Next diff --git a/Task/Multifactorial/00DESCRIPTION b/Task/Multifactorial/00DESCRIPTION index ff4f4d8fe1..3ed32b6cea 100644 --- a/Task/Multifactorial/00DESCRIPTION +++ b/Task/Multifactorial/00DESCRIPTION @@ -1,15 +1,16 @@ -The factorial of a number, written as n! is defined as n! = n(n-1)(n-2)...(2)(1) +The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1). -A generalization of this is the [http://mathworld.wolfram.com/Multifactorial.html multifactorials] where: +[http://mathworld.wolfram.com/Multifactorial.html Multifactorials] generalize factorials as follows: : n! = n(n-1)(n-2)...(2)(1) : n!! = n(n-2)(n-4)... : n!! ! = n(n-3)(n-6)... : n!! !! = n(n-4)(n-8)... : n!! !! ! = n(n-5)(n-10)... -: Where the products are for positive integers. -If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (The number of exclamation marks) then the task is to +In all cases, the terms in the products are positive integers. + +If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: # Write a function that given n and the degree, calculates the multifactorial. -# Use the function to generate and display here a table of the first 1..10 members of the first five degrees of multifactorial. +# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial. '''Note:''' The [[wp:Factorial#Multifactorials|wikipedia entry on multifactorials]] gives a different formula. This task uses the [http://mathworld.wolfram.com/Multifactorial.html Wolfram mathworld definition]. diff --git a/Task/Multifactorial/ALGOL-68/multifactorial.alg b/Task/Multifactorial/ALGOL-68/multifactorial.alg new file mode 100644 index 0000000000..4dbd59e898 --- /dev/null +++ b/Task/Multifactorial/ALGOL-68/multifactorial.alg @@ -0,0 +1,24 @@ +BEGIN + INT highest degree = 5; + INT largest number = 10; +CO Recursive implementation of multifactorial function CO + PROC multi fact = (INT n, deg) INT : + (n <= deg | n | n * multi fact(n - deg, deg)); +CO Iterative implementation of multifactorial function CO + PROC multi fact i = (INT n, deg) INT : + BEGIN + INT result := n, nn := n; + WHILE (nn >= deg + 1) DO + result TIMESAB nn - deg; + nn MINUSAB deg + OD; + result + END; +CO Print out multifactorials CO + FOR i TO highest degree DO + printf (($l, "Degree ", g(0), ":"$, i)); + FOR j TO largest number DO + printf (($xg(0)$, multi fact (j, i))) + OD + OD +END diff --git a/Task/Multifactorial/Elixir/multifactorial.elixir b/Task/Multifactorial/Elixir/multifactorial.elixir new file mode 100644 index 0000000000..e86697c99d --- /dev/null +++ b/Task/Multifactorial/Elixir/multifactorial.elixir @@ -0,0 +1,10 @@ +defmodule RC do + def multifactorial(n,d) do + List.foldl(:lists.seq(n,1,-d), 1, fn x,p -> x*p end) + end +end + +Enum.each(1..5, fn d -> + multifac = Enum.map(1..10, fn n -> RC.multifactorial(n,d) end) + IO.puts "Degree #{d}: #{inspect multifac}" +end) diff --git a/Task/Multifactorial/Julia/multifactorial.julia b/Task/Multifactorial/Julia/multifactorial.julia new file mode 100644 index 0000000000..ede7324527 --- /dev/null +++ b/Task/Multifactorial/Julia/multifactorial.julia @@ -0,0 +1,18 @@ +function multifact{T<:Integer,U<:Integer}(n::T, k::U) + -1 ", lab), a) +end diff --git a/Task/Multifactorial/REXX/multifactorial.rexx b/Task/Multifactorial/REXX/multifactorial.rexx index 15ef9e4f9b..01dfe9f0c9 100644 --- a/Task/Multifactorial/REXX/multifactorial.rexx +++ b/Task/Multifactorial/REXX/multifactorial.rexx @@ -1,21 +1,21 @@ -/*REXX pgm calculates K-fact (multifactorial) of non-negative integers.*/ -numeric digits 1000 /*lets get ka-razy with precision*/ -parse arg num deg . /*allow user to specify num & deg*/ -if num=='' | num==',' then num=15 /*Not specified? Then use default*/ -if deg=='' | deg==',' then deg=10 /* " " " " " */ -say '═══showing multiple factorials (1 ──►' deg") for numbers 1 ──►" num +/*REXX program calculates K-fact (multifactorial) of non-negative integers. */ +numeric digits 1000 /*get ka-razy with the decimal digits. */ +parse arg num deg . /*get optional arguments from the C.L. */ +if num=='' | num==',' then num=15 /*Not specified? Then use the default.*/ +if deg=='' | deg==',' then deg=10 /* " " " " " " */ +say '═══showing multiple factorials (1 ──►' deg") for numbers 1 ──►" num say - do d=1 for deg /*the factorializing (º) of !'s. */ - _= /*the list of factorials so far. */ - do f=1 for num /* ◄── do a ! from 1 to num.*/ - _=_ Kfact(f,d) /*construct a list of factorials.*/ - end /*f*/ /*(above) D can default to 1.*/ + do d=1 for deg /*the factorializing (degree) of !'s.*/ + _= /*the list of factorials (so far). */ + do f=1 for num /* ◄── perform a ! from 1 ───► number.*/ + _=_ Kfact(f, d) /*build a list of factorial products. */ + end /*f*/ /*(above) D can default to unity. */ - say right('n'copies("!", d),1+deg) right('['d"]",2+length(num))':' _ + say right('n'copies("!", d),1+deg) right('['d"]", 2+length(num))':' _ end /*d*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────KFACT subroutine────────────────────*/ -Kfact: procedure; !=1; do j=arg(1) to 2 by -word(arg(2) 1, 1) - !=!*j - end /*j*/ -return ! +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +Kfact: procedure; !=1; do j=arg(1) to 2 by -word(arg(2) 1, 1) + !=!*j + end /*j*/ + return ! diff --git a/Task/Multifactorial/VBScript/multifactorial.vb b/Task/Multifactorial/VBScript/multifactorial.vb new file mode 100644 index 0000000000..369434da99 --- /dev/null +++ b/Task/Multifactorial/VBScript/multifactorial.vb @@ -0,0 +1,25 @@ +Function multifactorial(n,d) + If n = 0 Then + multifactorial = 1 + Else + For i = n To 1 Step -d + If i = n Then + multifactorial = n + Else + multifactorial = multifactorial * i + End If + Next + End If +End Function + +For j = 1 To 5 + WScript.StdOut.Write "Degree " & j & ": " + For k = 1 To 10 + If k = 10 Then + WScript.StdOut.Write multifactorial(k,j) + Else + WScript.StdOut.Write multifactorial(k,j) & " " + End If + Next + WScript.StdOut.WriteLine +Next diff --git a/Task/Multiple-distinct-objects/Elixir/multiple-distinct-objects.elixir b/Task/Multiple-distinct-objects/Elixir/multiple-distinct-objects.elixir new file mode 100644 index 0000000000..00666e38ca --- /dev/null +++ b/Task/Multiple-distinct-objects/Elixir/multiple-distinct-objects.elixir @@ -0,0 +1 @@ +randoms = for _ <- 1..10, do: :random.uniform(1000) diff --git a/Task/Multiple-distinct-objects/Forth/multiple-distinct-objects.fth b/Task/Multiple-distinct-objects/Forth/multiple-distinct-objects.fth new file mode 100644 index 0000000000..af59e16bb0 --- /dev/null +++ b/Task/Multiple-distinct-objects/Forth/multiple-distinct-objects.fth @@ -0,0 +1,23 @@ +include FMS-SI.f +include FMS-SILib.f + + +\ create a list of VAR objects the right way +\ each: returns a unique object reference +o{ 0 0 0 } dup p: o{ 0 0 0 } +dup each: drop . 10774016 +dup each: drop . 10786896 +dup each: drop . 10786912 + + +\ create a list of VAR objects the wrong way +\ each: returns the same object reference +var x +object-list2 list +x list add: +x list add: +x list add: +list p: o{ 0 0 0 } +list each: drop . 1301600 +list each: drop . 1301600 +list each: drop . 1301600 diff --git a/Task/Multiple-regression/Emacs-Lisp/multiple-regression.l b/Task/Multiple-regression/Emacs-Lisp/multiple-regression.l new file mode 100644 index 0000000000..42395e675b --- /dev/null +++ b/Task/Multiple-regression/Emacs-Lisp/multiple-regression.l @@ -0,0 +1,5 @@ +(setq X1 '[0 1 2 3 4 5 6 7 8 9 10]) +(setq X2 '[0 1 1 3 3 7 6 7 3 9 8]) +(setq Y '[1 6 17 34 57 86 121 162 209 262 321]) +(calc-eval + (format "fit(a*X1+b*X2+c,[X1,X2],[a,b,c],[%s %s %s])" X1 X2 Y)) diff --git a/Task/Multiple-regression/Go/multiple-regression-1.go b/Task/Multiple-regression/Go/multiple-regression-1.go new file mode 100644 index 0000000000..db3a3dfe0f --- /dev/null +++ b/Task/Multiple-regression/Go/multiple-regression-1.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + + "github.com/gonum/matrix/mat64" +) + +func givens() (x, y *mat64.Dense) { + height := []float64{1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, + 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83} + weight := []float64{52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, + 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46} + degree := 2 + x = Vandermonde(height, degree) + y = mat64.NewDense(len(weight), 1, weight) + return +} + +func Vandermonde(a []float64, degree int) *mat64.Dense { + x := mat64.NewDense(len(a), degree+1, nil) + for i := range a { + for j, p := 0, 1.; j <= degree; j, p = j+1, p*a[i] { + x.Set(i, j, p) + } + } + return x +} + +func main() { + x, y := givens() + fmt.Printf("%.4f\n", mat64.Formatted(mat64.QR(x).Solve(y))) +} diff --git a/Task/Multiple-regression/Go/multiple-regression-2.go b/Task/Multiple-regression/Go/multiple-regression-2.go new file mode 100644 index 0000000000..bc507fe498 --- /dev/null +++ b/Task/Multiple-regression/Go/multiple-regression-2.go @@ -0,0 +1,46 @@ +package main + +import ( + "fmt" + + "github.com/skelterjohn/go.matrix" +) + +func givens() (x, y *matrix.DenseMatrix) { + height := []float64{1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, + 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83} + weight := []float64{52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, + 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46} + m := len(height) + n := 3 + y = matrix.MakeDenseMatrix(weight, m, 1) + x = matrix.Zeros(m, n) + for i := 0; i < m; i++ { + ip := float64(1) + for j := 0; j < n; j++ { + x.Set(i, j, ip) + ip *= height[i] + } + } + return +} + +func main() { + x, y := givens() + n := x.Cols() + q, r := x.QR() + qty, err := q.Transpose().Times(y) + if err != nil { + fmt.Println(err) + return + } + c := make([]float64, n) + for i := n - 1; i >= 0; i-- { + c[i] = qty.Get(i, 0) + for j := i + 1; j < n; j++ { + c[i] -= c[j] * r.Get(i, j) + } + c[i] /= r.Get(i, i) + } + fmt.Println(c) +} diff --git a/Task/Multiple-regression/Go/multiple-regression.go b/Task/Multiple-regression/Go/multiple-regression.go deleted file mode 100644 index ec53d338ca..0000000000 --- a/Task/Multiple-regression/Go/multiple-regression.go +++ /dev/null @@ -1,45 +0,0 @@ -package main - -import ( - "code.google.com/p/gomatrix/matrix" - "fmt" -) - -func givens() (x, y *matrix.DenseMatrix) { - height := []float64{1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, - 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83} - weight := []float64{52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, - 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46} - m := len(height) - n := 3 - y = matrix.MakeDenseMatrix(weight, m, 1) - x = matrix.Zeros(m, n) - for i := 0; i < m; i++ { - ip := float64(1) - for j := 0; j < n; j++ { - x.Set(i, j, ip) - ip *= height[i] - } - } - return -} - -func main() { - x, y := givens() - n := x.Cols() - q, r := x.QR() - qty, err := q.Transpose().Times(y) - if err != nil { - fmt.Println(err) - return - } - c := make([]float64, n) - for i := n - 1; i >= 0; i-- { - c[i] = qty.Get(i, 0) - for j := i + 1; j < n; j++ { - c[i] -= c[j] * r.Get(i, j) - } - c[i] /= r.Get(i, i) - } - fmt.Println(c) -} diff --git a/Task/Multiple-regression/Python/multiple-regression-1.py b/Task/Multiple-regression/Python/multiple-regression-1.py new file mode 100644 index 0000000000..19da20db58 --- /dev/null +++ b/Task/Multiple-regression/Python/multiple-regression-1.py @@ -0,0 +1,11 @@ +import numpy as np + +height = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, + 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83] +weight = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, + 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46] + +X = np.mat(height**np.arange(3)[:, None]) +y = np.mat(weight) + +print(y * X.T * (X*X.T).I) diff --git a/Task/Multiple-regression/Python/multiple-regression-2.py b/Task/Multiple-regression/Python/multiple-regression-2.py new file mode 100644 index 0000000000..58487b1873 --- /dev/null +++ b/Task/Multiple-regression/Python/multiple-regression-2.py @@ -0,0 +1,11 @@ +import numpy as np + +height = [1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, + 1.65, 1.68, 1.70, 1.73, 1.75, 1.78, 1.80, 1.83] +weight = [52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, + 61.29, 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46] + +X = np.array(height)[:, None]**range(3) +y = weight + +print(np.linalg.lstsq(X, y)[0]) diff --git a/Task/Multiple-regression/Python/multiple-regression.py b/Task/Multiple-regression/Python/multiple-regression.py deleted file mode 100644 index 97d6df5fbb..0000000000 --- a/Task/Multiple-regression/Python/multiple-regression.py +++ /dev/null @@ -1,9 +0,0 @@ -import numpy as np -from numpy.random import random - -n=100; k=10 -y = np.mat(random((1,n))) -X = np.mat(random((k,n))) - -b= y * X.T * np.linalg.inv(X*X.T) -print(b) diff --git a/Task/Multiplication-tables/360-Assembly/multiplication-tables.360 b/Task/Multiplication-tables/360-Assembly/multiplication-tables.360 new file mode 100644 index 0000000000..6fc3821bda --- /dev/null +++ b/Task/Multiplication-tables/360-Assembly/multiplication-tables.360 @@ -0,0 +1,60 @@ +* 12*12 multiplication table 14/08/2015 +MULTTABL CSECT + USING MULTTABL,R12 + LR R12,R15 + LA R10,0 buffer pointer + LA R3,BUFFER + MVC 0(4,R3),=C' | ' + LA R10,4(R10) + LA R5,12 + LA R4,1 i=1 +LOOPN LA R3,BUFFER do i=1 to 12 + AR R3,R10 + XDECO R4,XDEC i + MVC 0(4,R3),XDEC+8 output i + LA R10,4(R10) + LA R4,1(R4) + BCT R5,LOOPN end i + XPRNT BUFFER,52 + XPRNT PORT,52 border + LA R5,12 + LA R4,1 i=1 (R4) +LOOPI LA R10,0 do i=1 to 12 + MVC BUFFER,=CL52' ' + LA R3,BUFFER + AR R3,R10 + XDECO R4,XDEC + MVC 0(2,R3),XDEC+10 + LA R10,2(R10) + LA R3,BUFFER + AR R3,R10 + MVC 0(2,R3),=C'| ' + LA R10,2(R10) + LA R7,12 + LA R6,1 j=1 (R6) +LOOPJ CR R6,R4 do j=1 to 12 + BNL MULT + LA R3,BUFFER + AR R3,R10 + MVC 0(4,R3),=C' ' + LA R10,4(R10) + B NEXTJ +MULT LR R9,R4 i + MR R8,R6 i*j in R8R9 + LA R3,BUFFER + AR R3,R10 + XDECO R9,XDEC + MVC 0(4,R3),XDEC+8 + LA R10,4(R10) +NEXTJ LA R6,1(R6) + BCT R7,LOOPJ end j +ELOOPJ XPRNT BUFFER,52 + LA R4,1(R4) + BCT R5,LOOPI end i +ELOOPI XR R15,R15 + BR R14 +BUFFER DC CL52' ' +XDEC DS CL12 +PORT DC C'--+-------------------------------------------------' + YREGS + END MULTTABL diff --git a/Task/Multiplication-tables/ALGOL-W/multiplication-tables.alg b/Task/Multiplication-tables/ALGOL-W/multiplication-tables.alg new file mode 100644 index 0000000000..2c025ae351 --- /dev/null +++ b/Task/Multiplication-tables/ALGOL-W/multiplication-tables.alg @@ -0,0 +1,14 @@ +begin + % print a school style multiplication table % + i_w := 3; s_w := 0; % set output formating % + write( " " ); + for i := 1 until 12 do writeon( " ", i ); + write( " +" ); + for i := 1 until 12 do writeon( "----" ); + for i := 1 until 12 do begin + write( i, "|" ); + for j := 1 until i - 1 do writeon( " " ); + for j := i until 12 do writeon( " ", i * j ); + end; + +end. diff --git a/Task/Multiplication-tables/Batch-File/multiplication-tables.bat b/Task/Multiplication-tables/Batch-File/multiplication-tables.bat new file mode 100644 index 0000000000..2ef233ccc3 --- /dev/null +++ b/Task/Multiplication-tables/Batch-File/multiplication-tables.bat @@ -0,0 +1,47 @@ +@echo off +setlocal enabledelayedexpansion + +::The Main Thing... +cls +set colum=12&set row=12 +call :multable +echo. +pause +exit /b 0 +::/The Main Thing. + +::The Functions... +:multable + echo. + for /l %%. in (1,1,%colum%) do ( + call :numstr %%. + set firstline=!firstline!!space!%%. + set seconline=!seconline!----- + ) + echo !firstline! + echo !seconline! + + ::The next lines here until the "goto :EOF" prints the products... + + for /l %%X in (1,1,%row%) do ( + for /l %%Y in (1,1,%colum%) do ( + if %%Y lss %%X (set "line%%X=!line%%X! ") else ( + set /a ans=%%X*%%Y + call :numstr !ans! + set "line%%X=!line%%X!!space!!ans!" + ) + ) + echo.!line%%X! ^| %%X + ) + goto :EOF + +:numstr + ::This function returns the number of whitespaces to be applied on each numbers. + set cnt=0&set proc=%1&set space= + :loop + set currchar=!proc:~%cnt%,1! + if not "!currchar!"=="" set /a cnt+=1&goto loop + set /a numspaces=5-!cnt! + for /l %%A in (1,1,%numspaces%) do set "space=!space! " +goto :EOF +::/The Functions. diff --git a/Task/Multiplication-tables/C++/multiplication-tables.cpp b/Task/Multiplication-tables/C++/multiplication-tables.cpp index 90334eaddd..f2499f4a55 100644 --- a/Task/Multiplication-tables/C++/multiplication-tables.cpp +++ b/Task/Multiplication-tables/C++/multiplication-tables.cpp @@ -3,39 +3,39 @@ #include // for log10() #include // for max() -size_t get_table_column_width(const int min, const int max) +size_t table_column_width(const int min, const int max) { unsigned int abs_max = std::max(max*max, min*min); // abs_max is the largest absolute value we might see. // If we take the log10 and add one, we get the string width // of the largest possible absolute value. - // Add one for a little whitespace guarantee. - size_t colwidth = 1 + std::log10(abs_max) + 1; + // Add one more for a little whitespace guarantee. + size_t colwidth = 2 + std::log10(abs_max); // If only one of them is less than 0, then some will - // be negative. - bool has_negative_result = (min < 0) && (max > 0); - - // If some values may be negative, then we need to add some space + // be negative. If some values may be negative, then we need to add some space // for a sign indicator (-) - if(has_negative_result) - colwidth++; - + if (min < 0 && max > 0) + ++colwidth; return colwidth; } +struct Writer_ +{ + decltype(std::setw(1)) fmt_; + Writer_(size_t w) : fmt_(std::setw(w)) {} + template Writer_& operator()(const T_& info) { std::cout << fmt_ << info; return *this; } +}; + void print_table_header(const int min, const int max) { - size_t colwidth = get_table_column_width(min, max); + Writer_ write(table_column_width(min, max)); // table corner - std::cout << std::setw(colwidth) << " "; - + write(" "); for(int col = min; col <= max; ++col) - { - std::cout << std::setw(colwidth) << col; - } + write(col); // End header with a newline and blank line. std::cout << std::endl << std::endl; @@ -43,22 +43,18 @@ void print_table_header(const int min, const int max) void print_table_row(const int num, const int min, const int max) { - size_t colwidth = get_table_column_width(min, max); + Writer_ write(table_column_width(min, max)); // Header column - std::cout << std::setw(colwidth) << num; + write(num); // Spacing to ensure only the top half is printed for(int multiplicand = min; multiplicand < num; ++multiplicand) - { - std::cout << std::setw(colwidth) << " "; - } + write(" "); // Remaining multiplicands for the row. for(int multiplicand = num; multiplicand <= max; ++multiplicand) - { - std::cout << std::setw(colwidth) << num * multiplicand; - } + write(num * multiplicand); // End row with a newline and blank line. std::cout << std::endl << std::endl; @@ -71,9 +67,7 @@ void print_table(const int min, const int max) // Table body for(int row = min; row <= max; ++row) - { print_table_row(row, min, max); - } } int main() diff --git a/Task/Multiplication-tables/DCL/multiplication-tables.dcl b/Task/Multiplication-tables/DCL/multiplication-tables.dcl new file mode 100644 index 0000000000..7b9f22fe98 --- /dev/null +++ b/Task/Multiplication-tables/DCL/multiplication-tables.dcl @@ -0,0 +1,26 @@ +$ max = 12 +$ h = f$fao( "!4* " ) +$ r = 0 +$ loop1: +$ o = "" +$ c = 0 +$ loop2: +$ if r .eq. 0 then $ h = h + f$fao( "!4SL", c ) +$ p = r * c +$ if c .ge. r +$ then +$ o = o + f$fao( "!4SL", p ) +$ else +$ o = o + f$fao( "!4* " ) +$ endif +$ c = c + 1 +$ if c .le. max then $ goto loop2 +$ if r .eq. 0 +$ then +$ write sys$output h +$ n = 4 * ( max + 2 ) +$ write sys$output f$fao( "!''n*-" ) +$ endif +$ write sys$output f$fao( "!4SL", r ) + o +$ r = r + 1 +$ if r .le. max then $ goto loop1 diff --git a/Task/Multiplication-tables/Elixir/multiplication-tables.elixir b/Task/Multiplication-tables/Elixir/multiplication-tables.elixir new file mode 100644 index 0000000000..80f089a8e6 --- /dev/null +++ b/Task/Multiplication-tables/Elixir/multiplication-tables.elixir @@ -0,0 +1,16 @@ +defmodule RC do + def multiplication_tables(n) do + IO.write " X |" + Enum.each(1..n, fn i -> :io.fwrite("~4B", [i]) end) + IO.puts "\n---+" <> String.duplicate("----", n) + Enum.each(1..n, fn j -> + :io.fwrite("~2B |", [j]) + Enum.each(1..n, fn i -> + if i n --> [n] +function range(m, n) { + return Array.apply( + null, Array(n - m + 1) + ).map(function (x, i) { + return m + i; + }); +} + +// ' 1' .. ' 144' +// n --> n --> s +function cell(n, w) { + return Array(w - n.toString().length + 1).join(' ') + n; +} + + +// Heading and table +// n --> n --> n --> s +(function (m, n, colWidth) { + + // 1.. 12 + var lstRange = range(m, n), + + // 5 space column widths + pad = function (x) { return cell(x || ' ', colWidth) }, + + // x 1 2 3 4 5 6 7 8 9 10 11 12 + lstTable = [['x'].concat(lstRange)].concat( + + lstRange.map(function (iRow, i, lst) { + + // multiplier + return [iRow].concat( + + // gap to left (triangle of numbers only) + Array.apply(null, Array(i)).concat( + + // products + lst.slice(i).map(function (x) { + return x * iRow; + }) + ) + ); + }) + ); + + // Stringified table of padded lines + // [[s]] --> s + return lstTable.map(function (row) { + return row.map(pad).join(''); + }).join('\n'); + +})(1, 12, 5); diff --git a/Task/Multiplication-tables/Julia/multiplication-tables.julia b/Task/Multiplication-tables/Julia/multiplication-tables.julia new file mode 100644 index 0000000000..12d20704a5 --- /dev/null +++ b/Task/Multiplication-tables/Julia/multiplication-tables.julia @@ -0,0 +1,12 @@ +println(" X | 1 2 3 4 5 6 7 8 9 10 11 12") +println("---+------------------------------------------------") + +for i=1:12, j=0:12 + if j == 0 + @printf("%2d | ", i) + elseif i <= j + @printf("%3d%c", i * j, j == 12 ? '\n' : ' ') + else + print(" ") + end +end diff --git a/Task/Multiplication-tables/REXX/multiplication-tables.rexx b/Task/Multiplication-tables/REXX/multiplication-tables.rexx index 61a1f15c57..222e8936dd 100644 --- a/Task/Multiplication-tables/REXX/multiplication-tables.rexx +++ b/Task/Multiplication-tables/REXX/multiplication-tables.rexx @@ -1,83 +1,60 @@ -/*REXX program displays a 12x12 multiplication boxed grid table, grid */ -/* will be displayed in "boxing" characters for ASCII or EBCDIC.*/ -parse arg high . /*get optional grid size from CL.*/ -if high=='' then high=12 /*not specified? Use default. */ -ebcdic= 'f0'==1 /*is this an EBCDIC machine? */ - -if ebcdic then do /*══════════EBCDIC═══════════════*/ - bar='fa'x /*vertical bar. */ - dash='bf'x /*horizontal dash. */ - bj ='cb'x /*bottom junction. */ - tj ='cc'x /* top junction. */ - cj ='8f'x /*center junction (cross). */ - lj ='eb'x /* left junction. */ - rj ='ec'x /* right junction. */ - tlc='ac'x /*top left corner. */ - trc='bc'x /*top right corner. */ - blc='ab'x /*bottom left corner. */ - brc='bb'x /*bottom right corner. */ - end - else do /*══════════ASCII════════════════*/ - bar='b3'x /*vertical bar. */ - dash='c4'x /*horizontal dash. */ - bj ='c1'x /*bottom junction. */ - tj ='c2'x /* top junction. */ - cj ='c5'x /*center junction (cross). */ - lj ='c3'x /* left junction. */ - rj ='b4'x /* right junction. */ - tlc='da'x /*top left corner. */ - trc='bf'x /*top right corner. */ - blc='c0'x /*bottom left corner. */ - brc='d9'x /*bottom right corner. */ - end - -cell=cj || copies(dash,5) /*define the top of the cell. */ -sep=copies(cell,high+1)rj /*build the table separator. */ -sepL=length(sep) /*length of separator line. */ -width=length(cell)-1 /*width of the table cells. */ -size=width-1 /*width for table numbers. */ -box.=left('',width) /*construct all the cells. */ - - do j=0 to high /*step through zero to H (12). */ - _=right(j,size-1)'x ' /*build "label"/border number. */ - box.0.j=_ /*build top label cell. */ - box.j.0=_ /*build left label cell. */ - end /*j*/ - -box.0.0=centre('times',width) /*redefine box.0.0 with 'X'. */ - - do row=1 for high /*step through 1 to H (12). */ - do col=row to high /*step through row to H (12). */ - box.row.col=right(row*col,size)' ' /*build a mult. cell. */ +/*REXX program displays a NxN multiplication table (in a boxed grid). */ +parse arg high . /*get optional grid size from the C.L. */ +if high=='' then high=12 /*Not specified? Then use the default.*/ + bar = '│' ; dash = '─' /*(vertical) bar; horizontal bar (dash)*/ + bj = '┴' ; tj = '┬' /*bottom and top junctions (or tees).*/ + cj = '┼' /*center junction (or cross). */ + lj = '├' ; rj = '┤' /*left and right junctions (or tees).*/ + tlc = '┌' ; trc = '┐' /* top left and right corners. */ + blc = '└' ; brc = '┘' /*bottom " " " " */ + /* [↑] define stuff to hold box glyphs*/ +cell = cj || copies(dash, 5) /*define the top of the cell. */ +sep = copies(cell, high+1)rj /*build the table separator. */ +sepL = length(sep) /*length of the separator line. */ +width= length(cell)-1 /*width of the table cells. */ +size = width-1 /*width for the table numbers. */ +box. = left('', width) /*construct all the cells. */ + + do j=0 to high /*step through zero ───► high. */ + _=right(j, size-1)'x ' /*build the "label" (border) number. */ + box.0.j=_ /*build the top label cell. */ + box.j.0=_ /*build the left label cell. */ + end /*j*/ + +box.0.0=centre('times', width) /*redefine box.0.0 with 'X'. */ + + do row=1 for high /*step through one ───► high. */ + do col=row to high /*step through row ───► high. */ + box.row.col=right(row*col, size)' ' /*build a multiplication cell. */ end /*col*/ end /*row*/ - do row=0 to high /*step through all the lines. */ - asep=sep /*allow use of a modified sep. */ + do row=0 to high /*step through all the lines. */ + asep=sep /*allow use of a modified separator. */ if row==0 then do - asep=overlay(tlc,asep,1) /*make a better tlc. */ - asep=overlay(trc,asep,sepL) /*make a better trc. */ - asep=translate(asep,tj,cj) /*make a better tj. */ + asep=overlay(tlc, asep, 1) /*make a better tlc. */ + asep=overlay(trc, asep, sepL) /*make a better trc. */ + asep=translate(asep, tj ,cj) /*make a better tj. */ end - else asep=overlay(lj,asep,1) /*make a better lj. */ + else asep=overlay(lj, asep ,1) /*make a better lj. */ - say asep /*display a table grid line. */ - if row==0 then call buildLine 00 /*display a blank grid line. */ - call buildLine row /*build one line of the grid. */ - if row==0 then call buildLine 00 /*display a blank grid line. */ + say asep /*display a table grid line. */ + if row==0 then call buildLine 00 /*display a blank grid line. */ + call buildLine row /*build one line of the grid. */ + if row==0 then call buildLine 00 /*display a blank grid line. */ end /*row*/ -asep=sep /*allow use of a modified sep. */ -asep=overlay(blc,asep,1) /*make a better bot left corner.*/ -asep=overlay(brc,asep,sepL) /*make a better bot right corner.*/ -asep=translate(asep,bj,cj) /*make a better bot junction. */ -say asep /*display a table grid line. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────BUILDLINE subroutine────────────────*/ -buildLine: w=; parse arg arow /*start with a blank cell. */ - - do col=0 to high /*step through 0 to H (12). */ - w=w||bar||box.arow.col /*build one cell at a time. */ +asep=sep /*allow use of a modified separator. */ +asep=overlay(blc, asep, 1) /*make a better bottom left corner. */ +asep=overlay(brc, asep, sepL) /*make a better bottom right corner. */ +asep=translate(asep, bj, cj) /*make a better bottom junction. */ +say asep /*display a table grid line. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +buildLine: w=; parse arg arow /*start with a blank cell. */ + + do col=0 to high /*step through zero ───► high. */ + w=w||bar||box.arow.col /*build one cell at a time. */ end /*col*/ -say w || bar /*finish building the last cell. */ +say w || bar /*finish building the last cell. */ return diff --git a/Task/Multiplication-tables/Ruby/multiplication-tables.rb b/Task/Multiplication-tables/Ruby/multiplication-tables.rb index 5740be2903..533d536d7f 100644 --- a/Task/Multiplication-tables/Ruby/multiplication-tables.rb +++ b/Task/Multiplication-tables/Ruby/multiplication-tables.rb @@ -1,10 +1,11 @@ def multiplication_table(n) - puts " " + ((" %3d" * n) % (1..n).to_a) + puts " |" + (" %3d" * n) % [*1..n] + puts "----+" + "----" * n 1.upto(n) do |x| - print "%3d " % x + print "%3d |" % x 1.upto(x-1) {|y| print " "} x.upto(n) {|y| print " %3d" % (x*y)} - puts "" + puts end end diff --git a/Task/Multiplication-tables/Scilab/multiplication-tables.scilab b/Task/Multiplication-tables/Scilab/multiplication-tables.scilab new file mode 100644 index 0000000000..8a6768a241 --- /dev/null +++ b/Task/Multiplication-tables/Scilab/multiplication-tables.scilab @@ -0,0 +1,22 @@ + nmax=12, xx=3 + s= blanks(xx)+" |" + for j=1:nmax + s=s+part(blanks(xx)+string(j),$-xx:$) + end + printf("%s\n",s) + s=strncpy("-----",xx)+" +" + for j=1:nmax + s=s+" "+strncpy("-----",xx) + end + printf("%s\n",s) + for i=1:nmax + s=part(blanks(xx)+string(i),$-xx+1:$)+" |" + for j = 1:nmax + if j >= i then + s=s+part(blanks(xx)+string(i*j),$-xx:$) + else + s=s+blanks(xx+1) + end + end + printf("%s\n",s) + end diff --git a/Task/Multisplit/Elixir/multisplit.elixir b/Task/Multisplit/Elixir/multisplit.elixir new file mode 100644 index 0000000000..07b7045adc --- /dev/null +++ b/Task/Multisplit/Elixir/multisplit.elixir @@ -0,0 +1,2 @@ +iex(1)> Regex.split(~r/==|!=|=/, "a!====b=!=c") +["a", "", "", "b", "", "c"] diff --git a/Task/Multisplit/VBScript/multisplit.vb b/Task/Multisplit/VBScript/multisplit.vb new file mode 100644 index 0000000000..6f9784db2b --- /dev/null +++ b/Task/Multisplit/VBScript/multisplit.vb @@ -0,0 +1,27 @@ +Function multisplit(s,sep) + arr_sep = Split(sep,"|") + For i = 0 To UBound(arr_sep) + arr_s = Split(s,arr_sep(i)) + s = Join(arr_s,",") + Next + multisplit = s +End Function + +Function multisplit_extra(s,sep) + Set dict_sep = CreateObject("Scripting.Dictionary") + arr_sep = Split(sep,"|") + For i = 0 To UBound(arr_sep) + dict_sep.Add i,"(" & arr_sep(i) & ")" + arr_s = Split(s,arr_sep(i)) + s = Join(arr_s,i) + Next + For Each key In dict_sep.Keys + s = Replace(s,key,dict_sep.Item(key)) + Next + multisplit_extra = s +End Function + +WScript.StdOut.Write "Standard: " & multisplit("a!===b=!=c","!=|==|=") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Extra Credit: " & multisplit_extra("a!===b=!=c","!=|==|=") +WScript.StdOut.WriteLine diff --git a/Task/Mutual-recursion/ALGOL-W/mutual-recursion.alg b/Task/Mutual-recursion/ALGOL-W/mutual-recursion.alg new file mode 100644 index 0000000000..039bdf4376 --- /dev/null +++ b/Task/Mutual-recursion/ALGOL-W/mutual-recursion.alg @@ -0,0 +1,18 @@ +begin + % define mutually recursive funtions F and M that compute the elements % + % of the Hofstadter Female and Male sequences % + + integer procedure F ( integer value n ) ; + if n = 0 then 1 else n - M( F( n - 1 ) ); + + integer procedure M ( integer value n ) ; + if n = 0 then 0 else n - F( M( n - 1 ) ); + + % print the first few elements of the sequences % + i_w := 2; s_w := 1; % set I/O formatting % + write( "F: " ); + for i := 0 until 20 do writeon( F( i ) ); + write( "M: " ); + for i := 0 until 20 do writeon( M( i ) ); + +end. diff --git a/Task/Mutual-recursion/Eiffel/mutual-recursion.e b/Task/Mutual-recursion/Eiffel/mutual-recursion.e new file mode 100644 index 0000000000..2e3e57811e --- /dev/null +++ b/Task/Mutual-recursion/Eiffel/mutual-recursion.e @@ -0,0 +1,47 @@ +class + APPLICATION + +create + make + +feature + + make + -- Test of the mutually recursive functions Female and Male. + do + across + 0 |..| 19 as c + loop + io.put_string (Female (c.item).out + " ") + end + io.new_line + across + 0 |..| 19 as c + loop + io.put_string (Male (c.item).out + " ") + end + end + + Female (n: INTEGER): INTEGER + -- Female sequence of the Hofstadter Female and Male sequences. + require + n_not_negative: n >= 0 + do + Result := 1 + if n /= 0 then + Result := n - Male (Female (n - 1)) + end + end + + Male (n: INTEGER): INTEGER + -- Male sequence of the Hofstadter Female and Male sequences. + require + n_not_negative: n >= 0 + do + Result := 0 + if n /= 0 then + Result := n - Female (Male (n - 1)) + end + end + +end diff --git a/Task/Mutual-recursion/Elixir/mutual-recursion.elixir b/Task/Mutual-recursion/Elixir/mutual-recursion.elixir index a83682a6af..8f2a943c0d 100644 --- a/Task/Mutual-recursion/Elixir/mutual-recursion.elixir +++ b/Task/Mutual-recursion/Elixir/mutual-recursion.elixir @@ -4,3 +4,6 @@ defmodule MutualRecursion do def m(0), do: 0 def m(n), do: n - f(m(n - 1)) end + +IO.inspect Enum.map(0..19, fn n -> MutualRecursion.f(n) end) +IO.inspect Enum.map(0..19, fn n -> MutualRecursion.m(n) end) diff --git a/Task/Mutual-recursion/JavaScript/mutual-recursion-1.js b/Task/Mutual-recursion/JavaScript/mutual-recursion-1.js new file mode 100644 index 0000000000..56ee98e6e4 --- /dev/null +++ b/Task/Mutual-recursion/JavaScript/mutual-recursion-1.js @@ -0,0 +1,19 @@ +function f(num) { + return (num === 0) ? 1 : num - m(f(num - 1)); +} + +function m(num) { + return (num === 0) ? 0 : num - f(m(num - 1)); +} + +function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { return m + i; } + ); +} + +var a = range(0, 19); + +//return a new array of the results and join with commas to print +console.log(a.map(function (n) { return f(n); }).join(', ')); +console.log(a.map(function (n) { return m(n); }).join(', ')); diff --git a/Task/Mutual-recursion/JavaScript/mutual-recursion-2.js b/Task/Mutual-recursion/JavaScript/mutual-recursion-2.js new file mode 100644 index 0000000000..dad2b8b75e --- /dev/null +++ b/Task/Mutual-recursion/JavaScript/mutual-recursion-2.js @@ -0,0 +1,14 @@ +var f = num => (num === 0) ? 1 : num - m(f(num - 1)); +var m = num => (num === 0) ? 0 : num - f(m(num - 1)); + +function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { return m + i; } + ); +} + +var a = range(0, 19); + +//return a new array of the results and join with commas to print +console.log(a.map(n => f(n)).join(', ')); +console.log(a.map(n => m(n)).join(', ')); diff --git a/Task/Mutual-recursion/JavaScript/mutual-recursion.js b/Task/Mutual-recursion/JavaScript/mutual-recursion.js deleted file mode 100644 index 4b9ea0239b..0000000000 --- a/Task/Mutual-recursion/JavaScript/mutual-recursion.js +++ /dev/null @@ -1,19 +0,0 @@ -function F(n) -{ - return n === 0 ? 1 : n - M(F(n - 1)); -} - -function M(n) -{ - return n === 0 ? 0 : n - F(M(n - 1)); -} - -var - out = {F: [], M: []}, - i; -for (i = 0; i < 20; i++) -{ - out.F.push(F(i)); - out.M.push(M(i)); -} -print(out.F + "\n" + out.M); diff --git a/Task/Mutual-recursion/REXX/mutual-recursion-1.rexx b/Task/Mutual-recursion/REXX/mutual-recursion-1.rexx index 1b2e0ffd81..6a99aa0e5a 100644 --- a/Task/Mutual-recursion/REXX/mutual-recursion-1.rexx +++ b/Task/Mutual-recursion/REXX/mutual-recursion-1.rexx @@ -1,11 +1,10 @@ -/*REXX program shows mutual recursion (via Hofstadter Male & Female seq)*/ -parse arg lim .; if lim='' then lim=40; pad=left('',20) +/*REXX program shows mutual recursion (via Hofstadter Male & Female sequence).*/ +parse arg lim .; if lim='' then lim=40; w=length(lim); pad=left('',20) - do j=0 to lim; jj=Jw(j); ff=F(j); mm=M(j) - say pad 'F('jj") =" Jw(ff) pad 'M('jj") =" Jw(mm) - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────F, M, Jw subroutines────────────*/ -F: procedure; parse arg n; if n==0 then return 1; return n-M(F(n-1)) -M: procedure; parse arg n; if n==0 then return 0; return n-F(M(n-1)) -Jw: return right(arg(1),length(lim)) /*right justifies # for nice look*/ + do j=0 to lim; jj=right(j,w); ff=right(F(j),w); mm=right(M(j),w) + say pad 'F('jj") =" ff pad 'M('jj") =" mm + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ +F: procedure; parse arg n; if n==0 then return 1; return n - M(F(n-1)) +M: procedure; parse arg n; if n==0 then return 0; return n - F(M(n-1)) diff --git a/Task/Mutual-recursion/REXX/mutual-recursion-2.rexx b/Task/Mutual-recursion/REXX/mutual-recursion-2.rexx index e97c3c1a44..0e448d55a3 100644 --- a/Task/Mutual-recursion/REXX/mutual-recursion-2.rexx +++ b/Task/Mutual-recursion/REXX/mutual-recursion-2.rexx @@ -1,15 +1,14 @@ -/*REXX program shows mutual recursion (via Hofstadter Male & Female seq)*/ -parse arg lim .; if lim=='' then lim=99 /*get or assume LIM.*/ -hm.=; hm.0=0; hf.=; hf.0=1; Js=; Fs=; Ms= +/*REXX program shows mutual recursion (via Hofstadter Male & Female sequence).*/ +parse arg lim .; if lim=='' then lim=40 /*assume the default for LIM? */ +w=length(lim); $m.=; $m.0=0; $f.=; $f.0=1; Js=; Fs=; Ms= - do j=0 to lim; ff=F(j); mm=M(j) - Js=Js jW(j); Fs=Fs jw(ff); Ms=Ms jW(mm) - end /*j*/ -say 'Js=' Js -say 'Fs=' Fs -say 'Ms=' Ms -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one─liner subroutines──────────────────────────────*/ -F: procedure expose hm. hf.; parse arg n; if hf.n=='' then hf.n=n-M(F(n-1)); return hf.n -M: procedure expose hm. hf.; parse arg n; if hm.n=='' then hm.n=n-F(M(n-1)); return hm.n -Jw: return right(arg(1),length(lim)) /*right justifies # for nice look*/ + do j=0 to lim + Js=Js right(j,w); Fs=Fs right(F(j),w); Ms=Ms right(M(j),w) + end /*j*/ +say 'Js=' Js /*display the list of Js to the term.*/ +say 'Fs=' Fs /* " " " " Fs " " " */ +say 'Ms=' Ms /* " " " " Ms " " " */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────────────*/ +F: procedure expose $m. $f.; parse arg n; if $f.n=='' then $f.n=n-M(F(n-1)); return $f.n +M: procedure expose $m. $f.; parse arg n; if $m.n=='' then $m.n=n-F(M(n-1)); return $m.n diff --git a/Task/Mutual-recursion/REXX/mutual-recursion-3.rexx b/Task/Mutual-recursion/REXX/mutual-recursion-3.rexx index a2490c5973..f43762a430 100644 --- a/Task/Mutual-recursion/REXX/mutual-recursion-3.rexx +++ b/Task/Mutual-recursion/REXX/mutual-recursion-3.rexx @@ -1,18 +1,17 @@ -/*REXX program shows mutual recursion (via Hofstadter Male & Female seq)*/ +/*REXX program shows mutual recursion (via Hofstadter Male & Female sequence).*/ /*If LIM is negative, only show a single result for the abs(lim) entry.*/ -parse arg lim .; if lim=='' then lim=99; aLim=abs(lim) -parse var lim . hm. hf. Js Fs Ms; hm.0=0; hf.0=1 +parse arg lim .; if lim=='' then lim=99; aLim=abs(lim) +w=length(aLim); $m.=; $m.0=0; $f.=; $f.0=1; Js=; Fs=; Ms= - do j=0 to Alim; ff=F(j); mm=M(j) - Js=Js jW(j); Fs=Fs jw(ff); Ms=Ms jW(mm) - end + do j=0 to Alim + Js=Js right(j,w); Fs=Fs right(F(j),w); Ms=Ms right(M(j),w) + end /*j*/ -if lim>0 then say 'Js=' Js; else say 'J('aLim")=" word(Js,aLim+1) -if lim>0 then say 'Fs=' Fs; else say 'F('aLim")=" word(Fs,aLim+1) -if lim>0 then say 'Ms=' Ms; else say 'M('aLim")=" word(Ms,aLim+1) -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one─liner subroutines──────────────────────────────*/ -F: procedure expose hm. hf.; parse arg n; if hf.n=='' then hf.n=n-M(F(n-1)); return hf.n -M: procedure expose hm. hf.; parse arg n; if hm.n=='' then hm.n=n-F(M(n-1)); return hm.n -Jw: return right(arg(1),length(lim)) /*right justifies # for nice look*/ +if lim>0 then say 'Js=' Js; else say 'J('aLim")=" word(Js,aLim+1) +if lim>0 then say 'Fs=' Fs; else say 'F('aLim")=" word(Fs,aLim+1) +if lim>0 then say 'Ms=' Ms; else say 'M('aLim")=" word(Ms,aLim+1) +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────────────*/ +F: procedure expose $m. $f.; parse arg n; if $f.n=='' then $f.n=n-M(F(n-1)); return $f.n +M: procedure expose $m. $f.; parse arg n; if $m.n=='' then $m.n=n-F(M(n-1)); return $m.n diff --git a/Task/Mutual-recursion/Rust/mutual-recursion.rust b/Task/Mutual-recursion/Rust/mutual-recursion.rust index c2dcdeed57..b77e2d7017 100644 --- a/Task/Mutual-recursion/Rust/mutual-recursion.rust +++ b/Task/Mutual-recursion/Rust/mutual-recursion.rust @@ -1,11 +1,11 @@ -fn f(n: int) -> int { +fn f(n: u32) -> u32 { match n { 0 => 1, _ => n - m(f(n - 1)) } } -fn m(n: int) -> int { +fn m(n: u32) -> u32 { match n { 0 => 0, _ => n - f(m(n - 1)) @@ -13,12 +13,12 @@ fn m(n: int) -> int { } fn main() { - for i in range(0, 20).map(f) { + for i in (0..20).map(f) { print!("{} ", i); } - println!("") + println!(""); - for i in range(0, 20).map(m) { + for i in (0..20).map(m) { print!("{} ", i); } println!("") diff --git a/Task/N-queens-problem/360-Assembly/n-queens-problem.360 b/Task/N-queens-problem/360-Assembly/n-queens-problem.360 new file mode 100644 index 0000000000..ee4c98c659 --- /dev/null +++ b/Task/N-queens-problem/360-Assembly/n-queens-problem.360 @@ -0,0 +1,110 @@ +* N-queens problem 04/09/2015 +NQUEENS PROLOG + LA R9,1 n=1 +LOOPN CH R9,L do n=1 to l + BH ELOOPN if n>l then exit loop + SR R8,R8 m=0 + LA R10,1 i=1 + LR R5,R9 n + SLA R5,1 n*2 + BCTR R5,0 r=2*n-1 +E40 CR R10,R9 if i>n + BH E80 then goto e80 + LR R11,R10 j=i +E50 LR R1,R10 i + SLA R1,1 i*2 + LA R6,A-2(R1) r6=@a(i) + LR R1,R11 j + SLA R1,1 j*2 + LA R7,A-2(R1) r7=@a(j) + MVC Z,0(R6) z=a(i) + MVC Y,0(R7) y=a(j) + LR R3,R10 i + SH R3,Y -y + AR R3,R9 p=i-y+n + LR R4,R10 i + AH R4,Y +y + BCTR R4,0 q=i+y-1 + MVC 0(2,R6),Y a(i)=y + MVC 0(2,R7),Z a(j)=z + LR R1,R3 p + SLA R1,1 p*2 + LH R2,U-2(R1) u(p) + LTR R2,R2 if u(p)<>0 + BNE E60 then goto e60 + LR R1,R4 q + AR R1,R5 q+r + SLA R1,1 (q+r)*2 + LH R2,U-2(R1) u(q+r) + C R2,=F'0' if u(q+r)<>0 + BNE E60 then goto e60 + LR R1,R10 i + SLA R1,1 i*2 + STH R11,S-2(R1) s(i)=j + LA R0,1 r0=1 + LR R1,R3 p + SLA R1,1 p*2 + STH R0,U-2(R1) u(p)=1 + LR R1,R4 q + AR R1,R5 q+r + SLA R1,1 (q+r)*2 + STH R0,U-2(R1) u(q+r)=1 + LA R10,1(R10) i=i+1 + B E40 goto e40 +E60 LA R11,1(R11) j=j+1 + CR R11,R9 if j<=n + BNH E50 then goto e50 +E70 BCTR R11,0 j=j-1 + CR R11,R10 if j=i + BE E90 goto e90 + LR R1,R10 i + SLA R1,1 i*2 + LA R6,A-2(R1) r6=@a(i) + LR R1,R11 j + SLA R1,1 j*2 + LA R7,A-2(R1) r7=@a(j) + MVC Z,0(R6) z=a(i) + MVC 0(2,R6),0(R7) a(i)=a(j) + MVC 0(2,R7),Z a(j)=z; + B E70 goto e70 +E80 LA R8,1(R8) m=m+1 +E90 BCTR R10,0 i=i-1 + LTR R10,R10 if i=0 + BZ ZERO then goto zero + LR R1,R10 i + SLA R1,1 i*2 + LH R2,A-2(R1) r2=a(i) + LR R3,R10 i + SR R3,R2 -a(i) + AR R3,R9 p=i-a(i)+n + LR R4,R10 i + AR R4,R2 +a(i) + BCTR R4,0 q=i+a(i)-1 + LR R1,R10 i + SLA R1,1 i*2 + LH R11,S-2(R1) j=s(i) + LA R0,0 r0=0 + LR R1,R3 p + SLA R1,1 p*2 + STH R0,U-2(R1) u(p)=0 + LR R1,R4 q + AR R1,R5 q+r + SLA R1,1 (q+r)*2 + STH R0,U-2(R1) u(q+r)=0 + B E60 goto e60 +ZERO XDECO R9,PG+0 edit n + XDECO R8,PG+12 edit m + XPRNT PG,24 print buffer + LA R9,1(R9) n=n+1 + B LOOPN loop do n +ELOOPN EPILOG +L DC H'12' input value +A DC H'01',H'02',H'03',H'04',H'05',H'06' + DC H'07',H'08',H'09',H'10',H'11',H'12' +U DC 46H'0' +S DS 12H +Z DS H +Y DS H +PG DS CL24 buffer + YREGS + END NQUEENS diff --git a/Task/N-queens-problem/ATS/n-queens-problem.ats b/Task/N-queens-problem/ATS/n-queens-problem.ats new file mode 100644 index 0000000000..de8698ba68 --- /dev/null +++ b/Task/N-queens-problem/ATS/n-queens-problem.ats @@ -0,0 +1,80 @@ +(* ****** ****** *) +// +// Solving N-queen puzzle +// +(* ****** ****** *) +// +// How to test: +// ./queens +// How to compile: +// patscc -DATS_MEMALLOC_LIBC -o queens queens.dats +// +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +// +#include +"share/HATS/atspre_staload_libats_ML.hats" +// +(* ****** ****** *) + +fun +solutions(N:int) = let +// +fun +show +( + board: list0(int) +) : void = +( + list0_foreach + ( list0_reverse(board) + , lam(n) => ((N).foreach()(lam(i) => print_string(if i = n then " Q" else " _")); print_newline()) + ) ; + print_newline() +) +// +fun +safe +( + i: int, j: int, k: int, xs: list0(int) +) : bool = +( + case+ xs of + | nil0() => true + | cons0(x, xs) => x != i && x != j && x != k && safe(i, j+1, k-1, xs) +) +// +fun +loop +( + col: int, xs: list0(int) +) : void = +(N).foreach() +( +lam(i) => +if +safe(i, i+1, i-1, xs) +then let + val xs = cons0(i, xs) +in + if col = N then show(xs) else loop(col+1, xs) +end // end of [then] +) +// +in + loop(1, nil0()) +end // end of [solutions] + +(* ****** ****** *) + +val () = solutions(8) + +(* ****** ****** *) + +implement main0() = () + +(* ****** ****** *) + +(* end of [queens.dats] *) diff --git a/Task/N-queens-problem/Ada/n-queens-problem.ada b/Task/N-queens-problem/Ada/n-queens-problem-1.ada similarity index 100% rename from Task/N-queens-problem/Ada/n-queens-problem.ada rename to Task/N-queens-problem/Ada/n-queens-problem-1.ada diff --git a/Task/N-queens-problem/Ada/n-queens-problem-2.ada b/Task/N-queens-problem/Ada/n-queens-problem-2.ada new file mode 100644 index 0000000000..95e25cf355 --- /dev/null +++ b/Task/N-queens-problem/Ada/n-queens-problem-2.ada @@ -0,0 +1,49 @@ +with Ada.Text_IO; +use Ada.Text_IO; + +procedure CountQueens is + function Queens (N : Integer) return Long_Integer is + A : array (0 .. N) of Integer; + U : array (0 .. 2 * N - 1) of Boolean := (others => true); + V : array (0 .. 2 * N - 1) of Boolean := (others => true); + M : Long_Integer := 0; + + procedure Sub (I: Integer) is + K, P, Q: Integer; + begin + if N = I then + M := M + 1; + else + for J in I .. N - 1 loop + P := I + A (J); + Q := I + N - 1 - A (J); + if U (P) and then V (Q) then + U (P) := false; + V (Q) := false; + K := A (I); + A (I) := A (J); + A (J) := K; + Sub (I + 1); + U (P) := true; + V (Q) := true; + K := A (I); + A (I) := A (J); + A (J) := K; + end if; + end loop; + end if; + end Sub; + begin + for I in 0 .. N - 1 loop + A (I) := I; + end loop; + Sub (0); + return M; + end Queens; +begin + for N in 1 .. 16 loop + Put (Integer'Image (N)); + Put (" "); + Put_Line (Long_Integer'Image (Queens (N))); + end loop; +end CountQueens; diff --git a/Task/N-queens-problem/C/n-queens-problem-4.c b/Task/N-queens-problem/C/n-queens-problem-4.c new file mode 100644 index 0000000000..113b40fdcc --- /dev/null +++ b/Task/N-queens-problem/C/n-queens-problem-4.c @@ -0,0 +1,69 @@ +#include +#define MAXN 31 + +int nqueens(int n) +{ + int q0,q1; + int cols[MAXN], diagl[MAXN], diagr[MAXN], posibs[MAXN]; // Our backtracking 'stack' + int num=0; + // + // The top level is two fors, to save one bit of symmetry in the enumeration by forcing second queen to + // be AFTER the first queen. + // + for (q0=0; q0>1 | bit1)>>1; + + // The variable posib contains the bitmask of possibilities we still have to try in a given row ... + int posib = ~(cols[0] | diagl[0] | diagr[0]); + + while (d >= 0) { + while(posib) { + int bit = posib & -posib; // The standard trick for getting the rightmost bit in the mask + int ncols= cols[d] | bit; + int ndiagl = (diagl[d] | bit) << 1; + int ndiagr = (diagr[d] | bit) >> 1; + int nposib = ~(ncols | ndiagl | ndiagr); + posib^=bit; // Eliminate the tried possibility. + + // The following is the main additional trick here, as recognizing solution can not be done using stack level (d), + // since we save the depth+backtrack time at the end of the enumeration loop. However by noticing all coloumns are + // filled (comparison to -1) we know a solution was reached ... + // Notice also that avoiding an if on the ncols==-1 comparison is more efficient! + num += ncols==-1; + + if (nposib) { + if (posib) { // This if saves stack depth + backtrack operations when we passed the last possibility in a row. + posibs[d++] = posib; // Go lower in stack .. + } + cols[d] = ncols; + diagl[d] = ndiagl; + diagr[d] = ndiagr; + posib = nposib; + } + } + posib = posibs[--d]; // backtrack ... + } + } + } + return num*2; +} + + +main(int ac , char **av) +{ + if(ac != 2) { + printf("usage: nq n\n"); + return 1; + } + int n = atoi(av[1]); + if(n<1 || n > MAXN) { + printf("n must be between 2 and 31!\n"); + } + printf("Number of solution for %d is %d\n",n,nqueens(n)); +} diff --git a/Task/N-queens-problem/Common-Lisp/n-queens-problem-2.lisp b/Task/N-queens-problem/Common-Lisp/n-queens-problem-2.lisp index 8e419d80a3..9d6c0f4772 100644 --- a/Task/N-queens-problem/Common-Lisp/n-queens-problem-2.lisp +++ b/Task/N-queens-problem/Common-Lisp/n-queens-problem-2.lisp @@ -1,45 +1,40 @@ -(defun queens (nmax) - (let ((a (make-array `(,nmax))) - (s (make-array `(,nmax))) - (u (make-array `(,(- (* 4 nmax) 2)) :initial-element 0)) - y z i j p q r m (v nil)) - (dotimes (i nmax) (setf (aref a i) i)) - (loop for n from 1 to nmax do - (tagbody - (setf m 0 i 0 r (1- (* 2 n))) - (go L40) - L30 - (setf (aref s i) j (aref u p) 1 (aref u (+ q r)) 1) - (incf i) - L40 - (if (>= i n) (go L80)) +(defun queens1 (n) + (let ((a (make-array n)) + (s (make-array n)) + (u (make-array (list (- (* 4 n) 2)) :initial-element t)) + y z (i 0) j p q (r (1- (* 2 n))) (m 0)) + (dotimes (i n) (setf (aref a i) i)) + (tagbody + L1 + (if (>= i n) (go L5)) (setf j i) - L50 + L2 (setf y (aref a j) z (aref a i)) - (setf p (+ (- i y) (1- n)) q (+ i y)) + (setf p (+ (- i y) n -1) q (+ i y)) (setf (aref a i) y (aref a j) z) - (if (and (zerop (aref u p)) (zerop (aref u (+ q r)))) (go L30)) - L60 + (when (and (aref u p) (aref u (+ q r))) + (setf (aref s i) j (aref u p) nil (aref u (+ q r)) nil) + (incf i) + (go L1)) + L3 (incf j) - (if (< j n) (go L50)) - L70 + (if (< j n) (go L2)) + L4 (decf j) - (if (= j i) (go L90)) + (if (= j i) (go L6)) (rotatef (aref a i) (aref a j)) - (go L70) - L80 + (go L4) + L5 (incf m) - L90 + L6 (decf i) - (if (minusp i) (go L100)) - (setf p (+ (- i (aref a i)) (1- n)) q (+ i (aref a i)) j (aref s i)) - (setf (aref u p) 0 (aref u (+ q r)) 0) - (go L60) - L100 - ;(princ n) (princ " ") (princ m) (terpri) - (push (cons n m) v) - )) (reverse v))) + (if (minusp i) (go L7)) + (setf p (+ (- i (aref a i)) n -1) q (+ i (aref a i)) j (aref s i)) + (setf (aref u p) t (aref u (+ q r)) t) + (go L3) + L7) + m)) -> (queens 14) +> (loop for n from 1 to 14 collect (cons n (queens1 n))) ((1 . 1) (2 . 0) (3 . 0) (4 . 2) (5 . 10) (6 . 4) (7 . 40) (8 . 92) (9 . 352) (10 . 724) (11 . 2680) (12 . 14200) (13 . 73712) (14 . 365596)) diff --git a/Task/N-queens-problem/Common-Lisp/n-queens-problem-3.lisp b/Task/N-queens-problem/Common-Lisp/n-queens-problem-3.lisp new file mode 100644 index 0000000000..656aa21b9e --- /dev/null +++ b/Task/N-queens-problem/Common-Lisp/n-queens-problem-3.lisp @@ -0,0 +1,21 @@ +(defun queens2 (n) + (let ((a (make-array n)) + (u (make-array (+ n n -1) :initial-element t)) + (v (make-array (+ n n -1) :initial-element t)) + (m 0)) + (dotimes (i n) (setf (aref a i) i)) + (labels ((sub (i) + (if (= i n) + ;(push (copy-seq a) s) + (incf m) + (loop for k from i below n do + (let ((p (+ i (aref a k))) + (q (+ (- i (aref a k)) n -1))) + (when (and (aref u p) (aref v q)) + (setf (aref u p) nil (aref v q) nil) + (rotatef (aref a i) (aref a k)) + (sub (1+ i)) + (setf (aref u p) t (aref v q) t) + (rotatef (aref a i) (aref a k)))))))) + (sub 0)) + m)) diff --git a/Task/N-queens-problem/Dart/n-queens-problem.dart b/Task/N-queens-problem/Dart/n-queens-problem.dart index 55d5f5a512..cd40e0e638 100644 --- a/Task/N-queens-problem/Dart/n-queens-problem.dart +++ b/Task/N-queens-problem/Dart/n-queens-problem.dart @@ -29,9 +29,9 @@ printQueens(List q) { StringBuffer sb = new StringBuffer(); for (int j=0; j + iadd = x + (len = length(row)) + isub = if (y = x-len) < 0, do: y + 2*n - 1, else: y + if elem(add, iadd) and elem(sub, isub) do + solve(n, [x|row], put_elem(add,iadd,false), put_elem(sub,isub,false)) + else + 0 + end + end) |> Enum.sum + end + + def print(n, row) do + IO.puts frame = "+-" <> String.duplicate("--", n) <> "+" + Enum.each(row, fn x -> + line = Enum.map_join(0..n-1, fn i -> if x==i, do: "Q ", else: ". " end) + IO.puts "| #{line}|" + end) + IO.puts frame + end +end + +Enum.each(1..6, fn n -> + IO.puts " #{n} Queen : #{RC.queen(n)}" +end) diff --git a/Task/N-queens-problem/J/n-queens-problem.j b/Task/N-queens-problem/J/n-queens-problem-1.j similarity index 100% rename from Task/N-queens-problem/J/n-queens-problem.j rename to Task/N-queens-problem/J/n-queens-problem-1.j diff --git a/Task/N-queens-problem/J/n-queens-problem-2.j b/Task/N-queens-problem/J/n-queens-problem-2.j new file mode 100644 index 0000000000..f96b02d8d3 --- /dev/null +++ b/Task/N-queens-problem/J/n-queens-problem-2.j @@ -0,0 +1,2 @@ + $queenst 8 +92 8 diff --git a/Task/N-queens-problem/J/n-queens-problem-3.j b/Task/N-queens-problem/J/n-queens-problem-3.j new file mode 100644 index 0000000000..a8a63e4c03 --- /dev/null +++ b/Task/N-queens-problem/J/n-queens-problem-3.j @@ -0,0 +1,2 @@ + {.queenst 8 +0 4 7 5 2 6 1 3 diff --git a/Task/N-queens-problem/PHP/n-queens-problem.php b/Task/N-queens-problem/PHP/n-queens-problem.php index 23dd00be3e..1b85c61274 100644 --- a/Task/N-queens-problem/PHP/n-queens-problem.php +++ b/Task/N-queens-problem/PHP/n-queens-problem.php @@ -65,6 +65,7 @@ function findRotation($p, $boardX,$solutions){ // This is a function which will render the board function renderBoard($p,$boardX) { +$img = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAYAAAA6GuKaAAAABmJLR0QA/wD/AP+gvaeTAAAGFUlEQVRYhe2YXWibVRjHf2lqP9JmaRi4YW1IalY3rbZsaddMgsquBm676b6KyNDhLiaUeSEMvPNCcNuNyJjgLiboCnoxKFlv6lcHy7AtMhhaWTVZWhisjDTEtEuW5PHiPWnfvH2TvNk6vekfDm/O+Z/zPP/3PM/5eAMb2MAG/nfYn4LNVuBj4ENgB/Ar8Ogp+KkJbwLfqvKGgbMBPwKiK+Oq3aqNdcebQEEnqAC8ruO7KBVcLF012KiKuhpFv0/prNlU239qw0x0pdBJFXt30NJDjx9Uu1Ub1TSYdq4UutcNfI61oW0Bflb8T6quRzUbNafPFdbm4zcmTucV91kZO18o/osy/GeKnzcRVFWDMT2shO4X4IL6/UqZPv2GpxHFcReUvVo1lMAYunKh+UTxeeB5A/cMkFF8RtX1eF6NE2XHTIN+ltekoHGmf0HLqe9V3Qb8ZWK4Xjf+HQP3KtCgfjeouh7v6PzWsxZ6f98De1kbjbIovumoCfcp2gzkgb8p3cJOUjpTJ3WcTfXPq/Gfmtge1Y01RaV9+jv1fAsYMnAu3XgfENJxfUoU6tmn40Kqf9Gvi1IMKX96/zWJnlLP4i7wrIEvzkQeeFfXvltnt07Vi3iX1RcyzuSzrO46ev81YS+rYcqjbUVFfIl2CSryS4ATcKCF3biQHIpf0rU/UnaKuMLqAhXlv2a4Dc4FOKi4bwyiBTgBvGYyRlT7CUPbI1b334MmY9zlhFVKjwQQ09ULaDNTNKYPbx54j9L81aNP8XldW3G8W9kt6LiY8m8Ksy1Hj0mgA+3eXYeWd2eBRkpf2A4MoO3JOYPdHPA2sMtgu07ZOavsFnegvPL72PiItWEroB0axtwtmPStxOeUHbNxH1USVe1qOm3SVkA7NIwX+1phU3YKJpyZX8swW4y1FOMsVotG1UUI1mbrH9ZeL/UQi3b0C7dS/2W0LbIsqi1E0K6PL5oRdrudHTt22Px+Pz6fD6/XS3NzM21tbSt9FhcXWVpaIhqN2mKxGLOzs8zMzJDP581MQukHw2OLPgt8VRQZDAbZv38/wWCQnTt30tKyGoRUKsWDBw/IZrOkUimcTicNDQ1s3rwZp9O50i+dTjM9Pc2NGzcIh8NEIhH9S3xuQVNV2IArp06dkoWFBRERefjwoUxMTMi5c+fk8OHD0tPTIy6Xq2Keulwu6enpkSNHjsj58+dlYmJCMpmMiIgsLCzIxYsXBe1UfNIFvoL6M2fO/Hn58uXC4OCgtLa2PsniXClOp1MGBwfl0qVLhdOnT/+BtcjX9FYe4Pe+vj6Hy+Vat9lIJpMyOTm5BLwExNfL7gpCodAFeQoIhUIXqntfhaVwFHH9+nXp7+8vuFyuWv8vKYtkMlmYnJwse+F/Urzi9/ulqanJ6gFhqTQ1NeW7u7sF6Fx3xd3d3bdERNLptITDYRkeHpZgMCgOh6MmkQ6HQ/bs2SPDw8MSDoclnU6LiMju3buvlHG9BlYX1F5gfGhoiEAgwL59+9i+fTsAuVyOWCxGPB4nHo+TSCTIZrMkEgncbjeNjY243W46OjrweDx4vV7q67WsnJmZYWxsjGvXrjE+Pm5Zj1XRX3d2dg7Nz8/bs9ksAFu2bGHXrl0EAgG2bduG1+vF4/HgdDrZtGkTdrudXC5HKpUilUpx9+5dYrEYd+7cYXp6mqmpKe7fvw9AQ0MDXV1d3L59+2Xgd4uaKqO3t/cnEZFkMikjIyNy9OhRaW9vf6Jcbm9vl2PHjsnIyIgkk0kRETl06NAHVvRYnenA8ePHJ4PBIAcOHGDr1q0AxONxbt68yezsLNFolLm5ORKJBMvLy6TTaVpaWmhubl5JD5/Ph9/vZ2BgAI/HA8C9e/cYHR3l6tWry2NjY88Bi+slGqAHOFVXVxfq7e3tGhgYqAsGgwQCAfH5fLbGxsaqBjKZDNFoVKampmyRSIRIJFK4devWn4VC4TpwEfjNipDHPdlagADaf3X9NpvthY6Ojk6Px+Mq3vLsdjv5fJ7FxUWWl5eJx+OJubm5mIjMon1O/Yr2N0G6VufrdhwrtAJtaN9+bWihzqB9pNYsbgMbeAz8C3N/JQD4H5KCAAAAAElFTkSuQmCC'; echo "
ItemValueWeight
"; for ($y = 0; $y < $boardX; ++$y) { echo ''; @@ -72,7 +73,7 @@ function renderBoard($p,$boardX) { if (($x+$y) & 1) { $cellCol = '#9C661F';} else {$cellCol = '#FCE6C9';} - if ($p[$y] == 1 << $x) { echo "";} + if ($p[$y] == 1 << $x) { echo "";} else { echo "";} } echo ''; diff --git a/Task/N-queens-problem/Perl-6/n-queens-problem.pl6 b/Task/N-queens-problem/Perl-6/n-queens-problem.pl6 index ab785edb6c..5ac790e3f3 100644 --- a/Task/N-queens-problem/Perl-6/n-queens-problem.pl6 +++ b/Task/N-queens-problem/Perl-6/n-queens-problem.pl6 @@ -1,30 +1,24 @@ -sub MAIN($N = 8) { +sub MAIN(\N = 8) { sub collision(@field, $row) { for ^$row -> $i { my $distance = @field[$i] - @field[$row]; - return 1 if $distance == any(0, $row - $i, $i - $row); + return True if $distance == any(0, $row - $i, $i - $row); } - 0; + False; } sub search(@field is rw, $row) { - if $row == $N { - return @field; - } else { - for ^$N -> $i { - @field[$row] = $i; - if !collision(@field, $row) { - my @r = search(@field, $row + 1) and return @r; - } - } + return @field if $row == N; + for ^N -> $i { + @field[$row] = $i; + return search(@field, $row + 1) || next + unless collision(@field, $row); } - Nil; + () } - for 0 .. $N / 2 { - if my @f = search [$_], 1 { - say ~@f; + for 0 .. N / 2 { + if search [$_], 1 -> @f { + say @f; last; } } } -# output: -0 4 7 5 2 6 1 3 diff --git a/Task/N-queens-problem/Python/n-queens-problem-5.py b/Task/N-queens-problem/Python/n-queens-problem-5.py index 81b2282462..f7d7633fb1 100644 --- a/Task/N-queens-problem/Python/n-queens-problem-5.py +++ b/Task/N-queens-problem/Python/n-queens-problem-5.py @@ -3,18 +3,21 @@ def queens(n): up = [True]*(2*n - 1) down = [True]*(2*n - 1) def sub(i): - nonlocal a, up, down - for k in range(i, n): - j = a[k] - p = i + j - q = i - j + n - 1 - if up[p] and down[q]: - if i == n - 1: - yield tuple(a) - else: + if i == n: + yield tuple(a) + else: + for k in range(i, n): + j = a[k] + p = i + j + q = i - j + n - 1 + if up[p] and down[q]: up[p] = down[q] = False a[i], a[k] = a[k], a[i] yield from sub(i + 1) up[p] = down[q] = True a[i], a[k] = a[k], a[i] yield from sub(0) + +#Count solutions for n=8: +sum(1 for p in queens(8)) +92 diff --git a/Task/N-queens-problem/Python/n-queens-problem-6.py b/Task/N-queens-problem/Python/n-queens-problem-6.py new file mode 100644 index 0000000000..bf6b25cd22 --- /dev/null +++ b/Task/N-queens-problem/Python/n-queens-problem-6.py @@ -0,0 +1,31 @@ +def queens_lex(n): + a = list(range(n)) + up = [True]*(2*n - 1) + down = [True]*(2*n - 1) + def sub(i): + if i == n: + yield tuple(a) + else: + for k in range(i, n): + a[i], a[k] = a[k], a[i] + j = a[i] + p = i + j + q = i - j + n - 1 + if up[p] and down[q]: + up[p] = down[q] = False + yield from sub(i + 1) + up[p] = down[q] = True + x = a[i] + for k in range(i + 1, n): + a[k - 1] = a[k] + a[n - 1] = x + yield from sub(0) + +next(queens(31)) +(0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20) + +next(queens_lex(31)) +(0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20) + +#Compare to A065188 +#1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, ... diff --git a/Task/N-queens-problem/Ruby/n-queens-problem.rb b/Task/N-queens-problem/Ruby/n-queens-problem-1.rb similarity index 100% rename from Task/N-queens-problem/Ruby/n-queens-problem.rb rename to Task/N-queens-problem/Ruby/n-queens-problem-1.rb diff --git a/Task/N-queens-problem/Ruby/n-queens-problem-2.rb b/Task/N-queens-problem/Ruby/n-queens-problem-2.rb new file mode 100644 index 0000000000..d5a71304c3 --- /dev/null +++ b/Task/N-queens-problem/Ruby/n-queens-problem-2.rb @@ -0,0 +1,40 @@ +class Queen + def initialize(num=8) + @num = num + end + + def solve(out=true) + @out = out + @row = *0...@num + @frame = "+-" + "--" * @num + "+" + @count = 0 + add = Array.new(2 * @num - 1, true) + sub = Array.new(2 * @num - 1, true) + _solve([], add, sub) + @count + end + + def _solve(row, add, sub) + y = row.size + if y == @num + print_out(row) if @out + @count += 1 + else + (@row-row).each do |x| + next unless add[x+y] and sub[x-y] + add[x+y] = sub[x-y] = false + _solve(row+[x], add, sub) + add[x+y] = sub[x-y] = true + end + end + end + + def print_out(row) + puts @frame + row.each do |i| + line = @num.times.map {|j| j==i ? "Q " : ". "}.join + puts "| #{line}|" + end + puts @frame + end +end diff --git a/Task/N-queens-problem/Ruby/n-queens-problem-3.rb b/Task/N-queens-problem/Ruby/n-queens-problem-3.rb new file mode 100644 index 0000000000..77defea95b --- /dev/null +++ b/Task/N-queens-problem/Ruby/n-queens-problem-3.rb @@ -0,0 +1,9 @@ +(1..6).each do |n| + puzzle = Queen.new(n) + puts " #{n} Queen : #{puzzle.solve}" +end + +(7..12).each do |n| + puzzle = Queen.new(n) + puts " #{n} Queen : #{puzzle.solve(false)}" # no display +end diff --git a/Task/N-queens-problem/Rust/n-queens-problem.rust b/Task/N-queens-problem/Rust/n-queens-problem.rust index d6d26d3bfd..4a2eab5301 100644 --- a/Task/N-queens-problem/Rust/n-queens-problem.rust +++ b/Task/N-queens-problem/Rust/n-queens-problem.rust @@ -1,44 +1,33 @@ -// rustc 0.10-pre, 24th Feb -static side: i8 = 8; -static queens: i8 = 8; //change side and queens to modify parameters +const N: usize = 8; -fn place(mut board: [i8,..side*side], ix:i8) -> Option<[i8,..side*side]> { - if board[ix] == 0 { - return None - }; - board[ix] = -1; - let i1 = ix/side; - let j1 = ix % side; - for k in range(1,side) { - let mut loc :i8 = i1 * side + k; - board[loc] = 0; - loc = k * side + j1; - board[loc] = 0; - loc = (i1-k) * side + (j1-k); - if loc / side == i1 -k && loc % side == j1 - k && loc != ix && loc >= 0 { board[loc] = 0 }; - loc = loc + 2 * k; - if loc / side == i1 - k && loc % side == j1 + k && loc != ix && loc >= 0 { board[loc] = 0}; - loc = loc + 2 * side * k; - if loc / side == i1 + k && loc % side == j1 + k && loc != ix && loc < side*side { board[loc] = 0}; - loc = loc - 2 * k; - if loc / side == i1 + k && loc % side == j1 - k && loc != ix && loc < side*side { board[loc] = 0}; - } - Some(board) -} - -fn tryplace(b : [i8,..side*side],ix:i8, nq: i8, mut score: u32) -> u32 { - if nq == queens { return score + 1 } - for ind in range(ix, side*side) { - score = match place(b, ind) { - Some(b2) => tryplace(b2, ind+1, nq+1, score), - None() => score - }; - } - return score +fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) { + if row == N { + *count += 1; + for r in board.iter() { + println!("{}", r.iter().map(|&x| if x {"x"} else {"."}.to_string()).collect::>().join(" ")) + } + println!(""); + return + } + for i in 0..N { + let mut ok: bool = true; + for j in 0..row { + if board[j][i] + || i+j >= row && board[j][i+j-row] + || i+row < N+j && board[j][i+row-j] + { ok = false } + } + if ok { + board[row][i] = true; + try(&mut board, row+1, &mut count); + board[row][i] = false; + } + } } fn main() { - let b : [i8, ..side*side] = [1,..side*side]; - let score = tryplace(b, 0, 0, 0); - println!("{}", score) + let mut board: [[bool; N]; N] = [[false; N]; N]; + let mut count: i64 = 0; + try (&mut board, 0, &mut count); + println!("Found {} solutions", count) } diff --git a/Task/Named-parameters/JavaScript/named-parameters.js b/Task/Named-parameters/JavaScript/named-parameters-1.js similarity index 100% rename from Task/Named-parameters/JavaScript/named-parameters.js rename to Task/Named-parameters/JavaScript/named-parameters-1.js diff --git a/Task/Named-parameters/JavaScript/named-parameters-2.js b/Task/Named-parameters/JavaScript/named-parameters-2.js new file mode 100644 index 0000000000..5fd74dad1a --- /dev/null +++ b/Task/Named-parameters/JavaScript/named-parameters-2.js @@ -0,0 +1,12 @@ +let + example = // The member name in the object can either be the same as the parameter (as in bar, grill), + // or a different parameter name as in the case of member foo being assigned to parameter a here. + ({foo: a=0, bar=1, grill='pork chops'}={}) => ( + console.log('foo is ',a,', bar is ',bar,', and grill is '+grill)); + +example(); +// foo is 0 , bar is 1 , and grill is pork chops +example({grill: "lamb kebab", bar: 3.14}); +// foo is 0 , bar is 3.14 , and grill is lamb kebab +example({foo:null}); +// foo is , bar is 1 , and grill is pork chops diff --git a/Task/Named-parameters/PHP/named-parameters.php b/Task/Named-parameters/PHP/named-parameters.php new file mode 100644 index 0000000000..9dd8543a14 --- /dev/null +++ b/Task/Named-parameters/PHP/named-parameters.php @@ -0,0 +1,8 @@ +function named($args) { + $args += ["gbv" => 2, + "motor" => "away", + "teenage" => "fbi"]; + echo $args["gbv"] . " men running " . $args['motor'] . " from the " . $args['teenage']; +} + +named(["teenage" => "cia", "gbv" => 10]); diff --git a/Task/Narcissist/Befunge/narcissist.bf b/Task/Narcissist/Befunge/narcissist.bf new file mode 100644 index 0000000000..fee4ccbb67 --- /dev/null +++ b/Task/Narcissist/Befunge/narcissist.bf @@ -0,0 +1 @@ +900:0g~>:::0>`#0\#:5#:5#:+#<#~-#g*#0\#:5#+8#1+#\-#!*#-_$$"E"-!>_9-!.@ diff --git a/Task/Narcissist/Mathematica/narcissist.math b/Task/Narcissist/Mathematica/narcissist.math new file mode 100644 index 0000000000..6b11a1f372 --- /dev/null +++ b/Task/Narcissist/Mathematica/narcissist.math @@ -0,0 +1,3 @@ +prog = "prog = ``;\nPrint[InputString[] == \n ToString[StringForm[prog, ToString[prog, InputForm]]]];"; +Print[InputString[] == + ToString[StringForm[prog, ToString[prog, InputForm]]]]; diff --git a/Task/Narcissist/Perl-6/narcissist.pl6 b/Task/Narcissist/Perl-6/narcissist.pl6 index 436e6426b3..94a217370f 100644 --- a/Task/Narcissist/Perl-6/narcissist.pl6 +++ b/Task/Narcissist/Perl-6/narcissist.pl6 @@ -1 +1 @@ -eval my $self = q{say slurp() eq q[eval my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}} +EVAL my $self = q{say slurp() eq q[EVAL my $self = q{]~$self~q[}]~10.chr ?? q{Beautiful!} !! q{Not my type.}} diff --git a/Task/Narcissist/REXX/narcissist-1.rexx b/Task/Narcissist/REXX/narcissist-1.rexx index 1fa0b6365f..c9c2784586 100644 --- a/Task/Narcissist/REXX/narcissist-1.rexx +++ b/Task/Narcissist/REXX/narcissist-1.rexx @@ -1 +1 @@ -/*REXX*/ say arg(1)=sourceline(1) +/*REXX*/ say arg(1)=sourceline(1) diff --git a/Task/Narcissist/REXX/narcissist-2.rexx b/Task/Narcissist/REXX/narcissist-2.rexx index a150942f80..7599269f61 100644 --- a/Task/Narcissist/REXX/narcissist-2.rexx +++ b/Task/Narcissist/REXX/narcissist-2.rexx @@ -1 +1 @@ -/*REXX*/ say word('reject accept',1+(arg(1)=sourceline(1))) +/*REXX*/ say word('reject accept',1+(arg(1)=sourceline(1))) diff --git a/Task/Narcissistic-decimal-number/00DESCRIPTION b/Task/Narcissistic-decimal-number/00DESCRIPTION index 6e0acf7d98..5b7842826c 100644 --- a/Task/Narcissistic-decimal-number/00DESCRIPTION +++ b/Task/Narcissistic-decimal-number/00DESCRIPTION @@ -1,7 +1,9 @@ -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. +A [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic decimal number] is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n. -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. +Narcissistic (decimal) numbers are sometimes called   '''Armstrong'''   numbers, named after Michael F. Armstrong. -The task is to generate and show here, the first 25 narcissistic integer numbers. +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 number. + +The task is to generate and show here the first 25 narcissistic decimal numbers. Note: 0^1 = 0, the first in the series. diff --git a/Task/Narcissistic-decimal-number/Elixir/narcissistic-decimal-number.elixir b/Task/Narcissistic-decimal-number/Elixir/narcissistic-decimal-number.elixir new file mode 100644 index 0000000000..b47cdf9464 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Elixir/narcissistic-decimal-number.elixir @@ -0,0 +1,32 @@ +defmodule RC do + def narcissistic(m) do + Enum.reduce(1..10, [0], fn digits,acc -> + digitPowers = List.to_tuple(for i <- 0..9, do: power(i, digits)) + Enum.reduce(power(10, digits-1) .. power(10, digits)-1, acc, fn n,result -> + sum = divsum(n, digitPowers, 0) + if n == sum do + if length(result) == m-1, do: throw Enum.reverse(result, [n]) + [n | result] + else + result + end + end) + end) + end + + defp divsum(0, _, sum), do: sum + defp divsum(n, digitPowers, sum) do + divsum(div(n,10), digitPowers, sum+elem(digitPowers,rem(n,10))) + end + + defp power(n, m), do: power(n, m, 1) + + defp power(_, 0, pow), do: pow + defp power(n, m, pow), do: power(n, m-1, pow*n) +end + +try do + RC.narcissistic(25) +catch + x -> IO.inspect x +end diff --git a/Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number.java b/Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number-1.java similarity index 100% rename from Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number.java rename to Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number-1.java diff --git a/Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number-2.java b/Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number-2.java new file mode 100644 index 0000000000..8f84b1558d --- /dev/null +++ b/Task/Narcissistic-decimal-number/Java/narcissistic-decimal-number-2.java @@ -0,0 +1,26 @@ +import java.util.stream.IntStream; +public class NarcissisticNumbers { + static int numbersToCalculate = 25; + static int numbersCalculated = 0; + + public static void main(String[] args) { + IntStream.iterate(0, n -> n + 1).limit(Integer.MAX_VALUE).boxed().forEach(i -> { + int length = i.toString().length(); + int addedDigits = 0; + + for (int count = 0; count < length; count++) { + int value = Integer.parseInt(String.valueOf(i.toString().charAt(count))); + addedDigits += Math.pow(value, length); + } + + if (i == addedDigits) { + numbersCalculated++; + System.out.print(addedDigits + " "); + } + + if (numbersCalculated == numbersToCalculate) { + System.exit(0); + } + }); + } +} diff --git a/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number.js b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number.js new file mode 100644 index 0000000000..d1d5bdf23f --- /dev/null +++ b/Task/Narcissistic-decimal-number/JavaScript/narcissistic-decimal-number.js @@ -0,0 +1,24 @@ +function isNarc(x) { + var str = x.toString(), + i, + sum = 0, + l = str.length; + if (x < 0) { + return false; + } else { + for (i = 0; i < l; i++) { + sum += Math.pow(str.charAt(i), l); + } + } + return sum == x; +} +function main(){ + var n = []; + for (var x = 0, count = 0; count < 25; x++){ + if (isNarc(x)){ + n.push(x); + count++; + } + } + return n.join(' '); +} diff --git a/Task/Narcissistic-decimal-number/Julia/narcissistic-decimal-number.julia b/Task/Narcissistic-decimal-number/Julia/narcissistic-decimal-number.julia new file mode 100644 index 0000000000..f749866f99 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Julia/narcissistic-decimal-number.julia @@ -0,0 +1,16 @@ +function isnarcissist{T<:Integer}(n::T, b::Int=10) + -1 < n || return false + d = digits(n, b) + m = length(d) + n == mapreduce((x)->x^m, +, d) +end + +goal = 25 +ncnt = 0 +println("Finding the first ", goal, " Narcissistic numbers:") +for i in 0:typemax(1) + isnarcissist(i) || continue + ncnt += 1 + println(@sprintf " %2d %7d" ncnt i) + ncnt < goal || break +end diff --git a/Task/Narcissistic-decimal-number/Mathematica/narcissistic-decimal-number.math b/Task/Narcissistic-decimal-number/Mathematica/narcissistic-decimal-number.math new file mode 100644 index 0000000000..9b71666f0b --- /dev/null +++ b/Task/Narcissistic-decimal-number/Mathematica/narcissistic-decimal-number.math @@ -0,0 +1,6 @@ +narc[1] = 0; +narc[n_] := + narc[n] = + NestWhile[# + 1 &, narc[n - 1] + 1, + Plus @@ (IntegerDigits[#]^IntegerLength[#]) != # &]; +narc /@ Range[25] diff --git a/Task/Narcissistic-decimal-number/PL-I/narcissistic-decimal-number-1.pli b/Task/Narcissistic-decimal-number/PL-I/narcissistic-decimal-number-1.pli new file mode 100644 index 0000000000..9e445dbd62 --- /dev/null +++ b/Task/Narcissistic-decimal-number/PL-I/narcissistic-decimal-number-1.pli @@ -0,0 +1,52 @@ + narn: Proc Options(main); + Dcl (j,k,l,nn,n,sum) Dec Fixed(15)init(0); + Dcl s Char(15) Var; + Dcl p(15) Pic'9' Based(addr(s)); + Dcl (ms,msa,ela) Dec Fixed(15); + Dcl tim Char(12); + n=30; + ms=milliseconds(); + Do j=0 By 1 Until(nn=n); + s=dec2str(j); + l=length(s); + sum=left(s,1)**l; + Do k=2 To l; + sum=sum+substr(s,k,1)**l; + If sum>j Then Leave; + End; + If sum=j Then Do + nn=nn+1; + msa=milliseconds(); + ela=msa-ms; + /*Put Skip Data(ms,msa,ela);*/ + ms=msa; /*yyyymmddhhmissmis*/ + tim=translate('ij:kl:mn.opq',datetime(),'abcdefghijklmnopq'); + Put Edit(nn,' narcissistic:',j,ela,tim) + (Skip,f(9),a,f(12),f(15),x(2),a(12)); + End; + End; + dec2str: Proc(x) Returns(char(16) var); + Dcl x Dec Fixed(15); + Dcl ds Pic'(14)z9'; + ds=x; + Return(trim(ds)); + End; + milliseconds: Proc Returns(Dec Fixed(15)); + Dcl c17 Char(17); + dcl 1 * Def C17, + 2 * char(8), + 2 hh Pic'99', + 2 mm Pic'99', + 2 ss Pic'99', + 2 ms Pic'999'; + Dcl result Dec Fixed(15); + c17=datetime(); + result=(((hh*60+mm)*60)+ss)*1000+ms; + /* + Put Edit(translate('ij:kl:mn.opq',datetime(),'abcdefghijklmnopq'), + result) + (Skip,a(12),F(15)); + */ + Return(result); + End + End; diff --git a/Task/Narcissistic-decimal-number/PL-I/narcissistic-decimal-number-2.pli b/Task/Narcissistic-decimal-number/PL-I/narcissistic-decimal-number-2.pli new file mode 100644 index 0000000000..f2997e51c5 --- /dev/null +++ b/Task/Narcissistic-decimal-number/PL-I/narcissistic-decimal-number-2.pli @@ -0,0 +1,57 @@ +*process source xref attributes or(!); + narn3: Proc Options(main); + Dcl (i,j,k,l,nn,n,sum) Dec Fixed(15)init(0); + Dcl s Char(15) Var; + dcl t Char(15); + Dcl p9(15) Pic'9' Based(addr(t)); + Dcl (ms,msa,ela) Dec Fixed(15); + Dcl tim Char(12); + n=30; + Dcl power(0:9,1:9) Dec Fixed(15); + Do i=0 To 9; + Do j=1 To 9; + Power(i,j)=i**j; + End; + End; + ms=milliseconds(); + Do j=0 By 1 Until(nn=n); + s=dec2str(j); + t=s; + l=length(s); + sum=power(p9(1),l); + Do k=2 To l; + sum=sum+power(p9(k),l); + If sum>j Then Leave; + End; + If sum=j Then Do; + nn=nn+1; + msa=milliseconds(); + ela=msa-ms; + ms=msa; /*yyyymmddhhmissmis*/ + tim=translate('ij:kl:mn.opq',datetime(),'abcdefghijklmnopq'); + Put Edit(nn,' narcissistic:',j,ela,tim) + (Skip,f(9),a,f(12),f(15),x(2),a(12)); + End; + End; + + dec2str: Proc(x) Returns(char(15) var); + Dcl x Dec Fixed(15); + Dcl ds Pic'(14)z9'; + ds=x; + Return(trim(ds)); + End; + + milliseconds: Proc Returns(Dec Fixed(15)); + Dcl c17 Char(17); + dcl 1 * Def C17, + 2 * char(8), + 2 hh Pic'99', + 2 mm Pic'99', + 2 ss Pic'99', + 2 ms Pic'999'; + Dcl result Dec Fixed(15); + c17=datetime(); + result=(((hh*60+mm)*60)+ss)*1000+ms; + Return(result); + End; + End; diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx index acd1771aac..bcc854f385 100644 --- a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx @@ -1,15 +1,17 @@ -/*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.*/ +/*REXX pgm generates and displays a number of narcissistic (Armstrong) numbers*/ +numeric digits 39 /*be able to handle largest Armstrong #*/ +parse arg N .; if N=='' then N=25 /*obtain the number of narcissistic #'s*/ +N=min(N,89) /*there are only 89 narcissistic #s. */ +#=0 /*number of narcissistic numbers so far*/ + do j=0 until #==N; L=length(j) /*get length of the J decimal number.*/ + $=left(j,1)**L /*1st digit in J raised to the L pow.*/ + + do k=2 for L-1 until $>j /*perform for each decimal digit in J.*/ + $=$ + substr(j,k,1)**L /*add digit raised to power to the sum.*/ + end /*k*/ /* [↑] calculate the rest of the sum. */ + + if $\==j then iterate /*does the sum equal to J? No, skip it*/ + #=#+1 /*bump count of narcissistic numbers. */ + say right(#,9) ' narcissistic:' j /*display index and narcissistic number*/ + end /*j*/ /* [↑] this list starts at 0 (zero).*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx index 235a315ab5..082ab32d02 100644 --- a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx @@ -1,20 +1,22 @@ -/*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.*/ +/*REXX pgm generates and displays a number of narcissistic (Armstrong) numbers*/ +numeric digits 39 /*be able to handle largest Armstrong #*/ +parse arg N .; if N=='' then N=25 /*obtain the number of narcissistic #'s*/ +N=min(N,89) /*there are only 89 narcissistic #s. */ + do w=1 for 39 /*generate tables: digits ^ L power. */ + do i=0 for 10; @.w.i=i**w; end /*build table of ten digits ^ L power. */ + end /*w*/ /* [↑] table is a fixed (limited) size*/ +#=0 /*number of narcissistic numbers so far*/ + do j=0 until #==N; L=length(j) /*get length of the J decimal number.*/ + _=left(j,1) /*select the first decimal digit to sum*/ + $=@.L._ /*sum of the J dec. digits ^ L (so far)*/ + + do k=2 for L-1 until $>j /*perform for each decimal digit in J.*/ + _=substr(j,k,1) /*select the next decimal digit to sum.*/ + $=$+@.L._ /*add dec. digit raised to power to sum*/ + end /*k*/ /* [↑] calculate the rest of the sum. */ + + if $\==j then iterate /*does the sum equal to J? No, skip it*/ + #=#+1 /*bump count of narcissistic numbers. */ + say right(#,9) ' narcissistic:' j /*display index and narcissistic number*/ + end /*j*/ /* [↑] this list starts at 0 (zero).*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx index eb7faccb0c..5bcf2bb4c5 100644 --- a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx @@ -1,27 +1,28 @@ -/*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'. */ +/*REXX pgm generates and displays a number of narcissistic (Armstrong) numbers*/ +numeric digits 39 /*be able to handle largest Armstrong #*/ +parse arg N .; if N=='' then N=25 /*obtain the number of narcissistic #'s*/ +N=min(N,89) /*there are only 89 narcissistic #s. */ +@.=0 /*set default for the @ stemmed array. */ +#=0 /*number of narcissistic numbers so far*/ + do w=0 for 39+1 /*generate tables: digits ^ L power. */ + if w<10 then call tell w /*display the 1st 1─digit dec. numbers.*/ + do i=1 for 9; @.w.i=i**w; end /*build table of ten digits ^ L power. */ + end /*w*/ /* [↑] table is a fixed (limited) size*/ + /* [↓] skip the 2─digit dec. numbers. */ + do j=100; L=length(j) /*get length of the J decimal number.*/ + parse var j _1 2 _2 3 m '' -1 _R /*get 1st, 2nd, middle, last dec. digit*/ + $=@.L._1 + @.L._2 + @.L._R /*sum of the J decimal digs^L (so far).*/ + + do k=3 for L-3 until $>j /*perform for other decimal digits in J*/ + parse var m _ +1 m /*get next dec. dig in J, start at 3rd.*/ + $=$ + @.L._ /*add dec. digit raised to pow to sum. */ + end /*k*/ /* [↑] calculate the rest of the sum. */ + + if $==j then call tell j /*does the sum equal to J? Show the #*/ + end /*j*/ /* [↑] the J loop list starts at 100*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +tell: #=#+1 /*bump the counter for narcissistic #s.*/ +say right(#,9) ' narcissistic:' arg(1) /*display index and narcissistic number*/ +if #==N then exit /*stick a fork in it, we're all done. */ +return /*return to invoker & keep on truckin'.*/ diff --git a/Task/Narcissistic-decimal-number/VBScript/narcissistic-decimal-number.vb b/Task/Narcissistic-decimal-number/VBScript/narcissistic-decimal-number.vb new file mode 100644 index 0000000000..72595ba930 --- /dev/null +++ b/Task/Narcissistic-decimal-number/VBScript/narcissistic-decimal-number.vb @@ -0,0 +1,17 @@ +Function Narcissist(n) + i = 0 + j = 0 + Do Until j = n + sum = 0 + For k = 1 To Len(i) + sum = sum + CInt(Mid(i,k,1)) ^ Len(i) + Next + If i = sum Then + Narcissist = Narcissist & i & ", " + j = j + 1 + End If + i = i + 1 + Loop +End Function + +WScript.StdOut.Write Narcissist(25) diff --git a/Task/Natural-sorting/Fortran/natural-sorting-1.f b/Task/Natural-sorting/Fortran/natural-sorting-1.f new file mode 100644 index 0000000000..12d5762093 --- /dev/null +++ b/Task/Natural-sorting/Fortran/natural-sorting-1.f @@ -0,0 +1,365 @@ + MODULE STASHTEXTS !Using COMMON is rather more tedious. + INTEGER MSG,KBD !I/O unit numbers. + DATA MSG,KBD/6,5/ !Output, input. + + INTEGER LSTASH,NSTASH,MSTASH !Prepare a common text stash. + PARAMETER (LSTASH = 2468, MSTASH = 234) !LSTASH characters for MSTASH texts. + INTEGER ISTASH(MSTASH + 1) !Index to start positions. + CHARACTER*(LSTASH) STASH !One pool. + DATA NSTASH,ISTASH(1)/0,1/ !Which is empty. + CONTAINS + SUBROUTINE CROAK(GASP) !A dying remark. + CHARACTER*(*) GASP !The last words. + WRITE (MSG,*) "Oh dear." !Shock. + WRITE (MSG,*) GASP !Aargh! + STOP "How sad." !Farewell, cruel world. + END SUBROUTINE CROAK !Farewell... + + SUBROUTINE UPCASE(TEXT) !In the absence of an intrinsic... +Converts any lower case letters in TEXT to upper case... +Concocted yet again by R.N.McLean (whom God preserve) December MM. +Converting from a DO loop evades having both an iteration counter to decrement and an index variable to adjust. + CHARACTER*(*) TEXT !The stuff to be modified. +c CHARACTER*26 LOWER,UPPER !Tables. a-z may not be contiguous codes. +c PARAMETER (LOWER = "abcdefghijklmnopqrstuvwxyz") +c PARAMETER (UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ") +CAREFUL!! The below relies on a-z and A-Z being contiguous, as is NOT the case with EBCDIC. + INTEGER I,L,IT !Fingers. + L = LEN(TEXT) !Get a local value, in case LEN engages in oddities. + I = L !Start at the end and work back.. + 1 IF (I.LE.0) RETURN !Are we there yet? Comparison against zero should not require a subtraction. +c IT = INDEX(LOWER,TEXT(I:I)) !Well? +c IF (IT .GT. 0) TEXT(I:I) = UPPER(IT:IT) !One to convert? + IT = ICHAR(TEXT(I:I)) - ICHAR("a") !More symbols precede "a" than "A". + IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A")) !In a-z? Convert! + I = I - 1 !Back one. + GO TO 1 !Inspect.. + END SUBROUTINE UPCASE !Easy. + + SUBROUTINE SHOWSTASH(BLAH,I) !One might be wondering. + CHARACTER*(*) BLAH !An annotation. + INTEGER I !The desired stashed text. + IF (I.LE.0 .OR. I.GT.NSTASH) THEN !Paranoia rules. + WRITE (MSG,1) BLAH,I !And is not always paranoid. + 1 FORMAT (A,': Text(',I0,') is not in the stash!') !Hopefully, helpful. + ELSE !But surely I will only be asked for what I have. + WRITE (MSG,2) BLAH,I,STASH(ISTASH(I):ISTASH(I + 1) - 1) !Whee! + 2 FORMAT (A,': Text(',I0,')=>',A,'<') !Hopefully, informative. + END IF !So, it is shown. + END SUBROUTINE SHOWSTASH !Ah, debugging. + + INTEGER FUNCTION STASHIN(L2) !Assimilate the text ending at L2. +Careful: furrytran regards "blah" and "blah " as equal, so, compare lengths first. + INTEGER L2 !The text to add is at ISTASH(NSTASH + 1):L2. + INTEGER I,L1 !Assistants. + L1 = ISTASH(NSTASH + 1)!Where the scratchpad starts. + L = L2 - L1 + 1 !The length of the text. +Check to see if I already have stashed this exact text. + DO I = 1,NSTASH !Search my existing texts. + IF (L.EQ.ISTASH(I + 1) - ISTASH(I)) THEN !Matching lengths? + IF (STASH(L1:L2) !Yes. Does the scratchpad + 1 .EQ.STASH(ISTASH(I):ISTASH(I + 1) - 1)) THEN !Match the stashed text? + STASHIN = I !Yes! I already have this exact text. + RETURN !And there is no need to duplicate it. + END IF !So much for matching text, furrytran style. + END IF !This time, trailing space differences will count. + END DO !On to the next stashed text. +Can't find it. Assimilate the scratchpad. No text is moved, just extend the fingers. + IF (NSTASH.GE.MSTASH) CALL CROAK("The text pool is crowded!") !Alas. + IF (L2.GT.LSTASH) CALL CROAK("Overtexted!") !Alack. + NSTASH = NSTASH + 1 !Count in another entry. + ISTASH(NSTASH + 1) = L2 + 1 !The new "first available" position. + STASHIN = NSTASH !Fingered for the caller. + END FUNCTION STASHIN !Rather than assimilating a supplied text. + END MODULE STASHTEXTS !Others can extract text as they wish. + + MODULE BADCHARACTER !Some characters are not for glyphs but for action. + CHARACTER*1 BS,HT,LF,VT,FF,CR !Nicknames for a bunch of troublemakers. + CHARACTER*6 BADC,GOODC !I want a system. + INTEGER*1 IBADC(6) !Initialisation syntax is restricive. + PARAMETER (GOODC="btnvfr") !Mnemonics. + EQUIVALENCE (BADC(1:1),BS),(BADC(2:2),HT),(BADC(3:3),LF),!Match the names + 1 (BADC(4:4),VT),(BADC(5:5),FF),(BADC(6:6),CR), !To their character. + 2 (IBADC,BADC) !Alas, a PARAMETER style is rejected. + DATA IBADC/8,9,10,11,12,13/ !ASCII encodements. + PRIVATE IBADC !Keep this quiet. + END MODULE BADCHARACTER !They can disrupt layout. + + MODULE COMPOUND !Stores entries, each of multiple parts, each part a text and a number. + USE STASHTEXTS !Gain access to the text repository. + INTEGER LENTRY,NENTRY,MENTRY !Entry counting. + PARAMETER (MENTRY = 28) !Should be enough for the test runs. + INTEGER TENTRY(MENTRY) !Each entry has a source text somewhere in STASH. + INTEGER IENTRY(MENTRY + 1) !This fingers its first part in PARTT and PARTI. + INTEGER MPART,NPART !Now for the pool of parts. + PARAMETER (MPART = 120) !Should suffice. + INTEGER PARTT(MPART) !A part's text number in STASH. + INTEGER PARTI(MPART) !A part's number, itself. + DATA NENTRY,NPART,IENTRY(1)/0,0,1/ !There are no entries, with no parts either. + CONTAINS !The fun begins. + INTEGER FUNCTION ADDENTRY(X) !Create an entry holding X. +Chops X into many parts, alternating ,,... +Converts the pieces' texts to upper case, as they will be used as a sort key later. + CHARACTER*(*) X !The text. + INTEGER BORED,GRIST,NUMERIC !Might as well supply some mnemonics. + PARAMETER (BORED = 0, GRIST = 1, NUMERIC = 2) !For nearly arbitrary integers. + INTEGER I,STATE,D !For traipsing through the text. + INTEGER L1,L2 !Bounds of the scratchpad in STASH. + CHARACTER*1 C !Save on some typing. +Create a new entry. First, save its source text exactly as supplied. + IF (NENTRY.GE.MENTRY) CALL CROAK("Too many entries!") !Perhaps I can't. + NENTRY = NENTRY + 1 !Another entry. + L2 = ISTASH(NSTASH + 1) - 1 !Find my scratchpad. + STASH(L2 + 1:L2 + LEN(X)) = X !Place the text as it stands. + TENTRY(NENTRY) = STASHIN(L2 + LEN(X)) !Find a finger to it in my text stash. + CALL SHOWSTASH("Entering",TENTRY(NENTRY)) !Ah, debugging. + ADDENTRY = NENTRY !I shall return this. +Contemplate the text of the entry. Leading spaces, multiple spaces, numeric portions... + STATE = BORED !As if in leading space stuff. + L2 = ISTASH(NSTASH + 1) - 1 !Syncopation for text piece placement. + N = 0 !A number may be encountered. + DO I = 1,LEN(X) !Step through the text. + C = X(I:I) !Grab a character. + IF (C.LE." ") THEN !A space, or somesuch. + SELECT CASE(STATE) !What were we doing? + CASE(BORED) !Ignoring spaces. + !Do nothing with this one too. + CASE(GRIST) !We were in stuff. + CALL ONESPACE !So accept one space only. + CASE(NUMERIC) !We were in a number. + CALL ADDPART !So, the number has been ended. + STATE = BORED !But the space wot did it is ignored. + CASE DEFAULT !This should never happen. + CALL CROAK("Confused state!") !So this shouldn't. + END SELECT !So much for encountering spaceish stuff. + ELSE IF ("0".LE.C .AND. C.LE."9") THEN !A digit? + D = ICHAR(C) - ICHAR("0") !Yes. Convert to a numerical digit. + N = N*10 + D !Assimilate into a proper number. + STATE = NUMERIC !Perhaps more digits follow. + ELSE !All other characters are accepted as they stand. + IF (STATE.EQ.NUMERIC) CALL ADDPART !A number has just ended. + L2 = L2 + 1 !Starting a new pair's text. + STASH(L2:L2) = C !With this. + STATE = GRIST !And anticipating more to come. + END IF !Types are: spaceish, grist, digits. + END DO !On to the next character. + CALL ADDPART !Ended by the end-of-text. + IENTRY(NENTRY + 1) = NPART + 1 !Thus be able to find an entry's last part. + CONTAINS !Odd assistants. + SUBROUTINE ONESPACE !Places a space, then declares BORED. + L2 = L2 + 1 !Advance one. + STASH(L2:L2) = " " !An actual blank. + STATE = BORED !Any subsequent spaces are to be ignored. + END SUBROUTINE ONESPACE!Skipping them. + SUBROUTINE ADDPART !Augment the paired PARTT and PARTI. + IF (NPART.GE.MPART) CALL CROAK("Too many parts!") !If space remains. + NPART = NPART + 1 !So, another part. + IF (STASH(L2:L2).EQ." ") L2 = L2 - 1 !A trailing space trimmed. BORED means at most only one. + L1 = ISTASH(NSTASH + 1) !My scratchpad starts after the last stashed text. + CALL UPCASE(STASH(L1:L2)) !Simplify the text to be a sort key part. + IF (IENTRY(NENTRY).EQ.NPART) CALL LIBRARIAN !The first part of an entry? + PARTT(NPART) = STASHIN(L2) !Finger the text part. + PARTI(NPART) = N !Save the numerical value. + L2 = ISTASH(NSTASH + 1) - 1 !The text may not have been a newcomer. + N = 0 !Ready for another number. + END SUBROUTINE ADDPART !Always paired, even if no number was found. + SUBROUTINE LIBRARIAN !Adjusts names starting "The ..." or "An ..." or "A ...", library style. + CHARACTER*4 ARTICLE(3) !By chance, three, by happy chance, lengths 1, 2, 3! + PARAMETER (ARTICLE = (/"A","AN","THE"/)) !These each have trailing space. + INTEGER I !A stepper. + DO I = 1,3 !So step through the known articles. + IF (L1 + I.GT.L2) RETURN !Insufficient text? Give up. + IF (STASH(L1:L1 + I).EQ.ARTICLE(I)(1:I + 1)) THEN !Starts with this one? + STASH(L1:L2 - I - 1) = STASH(L1 + I + 1:L2) !Yes! Shift the rest back over it. + STASH(L2 - I:L2 + 1) = ", "//ARTICLE(I)(1:I) !Place the article at the end. + L2 = L2 + 1 !One more, for the comma. + RETURN !Done! + END IF !But if that article didn't match, + END DO !Try the next. + END SUBROUTINE LIBRARIAN !Ah, catalogue order. Blah, The. + END FUNCTION ADDENTRY !That was fun! + + SUBROUTINE SHOWENTRY(BLAH,E) !Ah, debugging. + CHARACTER*(*) BLAH !With distinguishing mark. + INTEGER E,P !Entry and part fingering. + INTEGER L1,L2 !Fingers. + L1 = ISTASH(TENTRY(E)) !The source text is stashed as text #TENTRY(E). + L2 = ISTASH(TENTRY(E) + 1) - 1 !ISTASH(i) is where in STASH text #i starts. + WRITE (MSG,1) BLAH,E,IENTRY(E),IENTRY(E + 1) - 1,STASH(L1:L2) + 1 FORMAT (/,A," Entry(",I0,")=Pt ",I0," to ",I0,", text >",A,"<") + DO P = IENTRY(E),IENTRY(E + 1) - 1 !Step through the part list. + L1 = ISTASH(PARTT(P)) !Find the text of the part. + L2 = ISTASH(PARTT(P) + 1) - 1 !Saved in STASH. + WRITE (MSG,2) P,PARTT(P),PARTI(P),STASH(L1:L2) !The text is of variable length, + 2 FORMAT ("Part(",I0,") = text#",I0,", N = ",I0," >",A,"<") !So present it *after* the number. + END DO !On to the next part. + END SUBROUTINE SHOWENTRY !Shows entry = , , ... + + INTEGER FUNCTION ENTRYORDER(E1,E2) !Report on the order of entries E1 and E2. +Chug through the parts list of the two entries, for each part comparing the text, then the number. + INTEGER E1,E2 !Finger entries via TENTRY(i) and IENTRY(i)... + INTEGER T1,T2 !Fingers texts in STASH. + INTEGER I1,N1,I2,N2 !Fingers and counts. + INTEGER I,D !A stepper and a difference. +c CALL SHOWENTRY("E1",E1) +c CALL SHOWENTRY("E2",E2) + P1 = IENTRY(E1) !Finger the first parts + P2 = IENTRY(E2) !Of the two entries. +Compare the text part of the two parts. + 10 T1 = PARTT(P1) !So, what is the number of the text, + T2 = PARTT(P2) !Safely stored in STASH. + IF (T1.NE.T2) THEN !Inspect text only if the text parts differ. + I1 = ISTASH(T1) !Where its text is stashed. + N1 = ISTASH(T1 + 1) - I1 !Thus the length of that text. + I2 = ISTASH(T2) !First character of the other text. + N2 = ISTASH(T2 + 1) - I2 !Thus its length. + DO I = 1,MIN(N1,N2) !Step along both texts while they have characters to match. + D = ICHAR(STASH(I2:I2)) - ICHAR(STASH(I1:I1)) !The difference. + IF (D.NE.0) GO TO 666 !Is there a difference? + I1 = I1 + 1 !No. + I2 = I2 + 1 !Advance to the next character for both. + END DO !And try again. +Can't compare character pairs beyond the shorter of the two texts. + D = N2 - N1 !Very well, which text is the shorter? + IF (D.NE.0) GO TO 666 !No difference in length? + END IF !So much for the text comparison. +Compare the numeric part. + D = PARTI(P2) - PARTI(P1) !Righto, compare the numeric side. + IF (D.NE.0) GO TO 666 !A difference here? +Can't find any difference between those two parts. + P1 = P1 + 1 !Move on to the next part. + P2 = P2 + 1 !For both entries. + N1 = IENTRY(E1 + 1) - P1 !Knowing where the next entry's parts start + N2 = IENTRY(E2 + 1) - P2 !Means knowing where an entry's parts end. + IF (N1.GT.0 .AND. N2.GT.0) GO TO 10 !At least one for both, so compare the next pair. + D = N2 - N1 !Thus, the shorter precedes the longer. +Conclusion. + 666 ENTRYORDER = D !Zero sez "equal". + END FUNCTION ENTRYORDER !That was a struggle. + + SUBROUTINE ORDERENTRY(LIST,N) +Crank up a Comb sort of the entries fingered by LIST. Working backwards, just for fun. +Caution: the H*10/13 means that H ought not be INTEGER*2. Otherwise, use H/1.3. + INTEGER LIST(*) !This is an index to the items being compared. + INTEGER T !In the absence of a SWAP(a,b). Same type as LIST. + INTEGER N !The number of entries. + INTEGER I,H !Tools. H ought not be a small integer. + LOGICAL CURSE !Annoyance. + H = N - 1 !Last - First, and not +1. + IF (H.LE.0) RETURN !Ha ha. + 1 H = MAX(1,H*10/13) !The special feature. + IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. + CURSE = .FALSE. !So far, so good. + DO I = N - H,1,-1 !If H = 1, this is a BubbleSort. + IF (ENTRYORDER(LIST(I),LIST(I + H)).LT.0) THEN !One compare. + T=LIST(I); LIST(I)=LIST(I+H); LIST(I+H)=T !One swap. + CURSE = .TRUE. !One curse. + END IF !One test. + END DO !One loop. + IF (CURSE .OR. H.GT.1) GO TO 1 !Work remains? + END SUBROUTINE ORDERENTRY + + CHARACTER*44 FUNCTION ENTRYTEXT(E) !Ad-hoc extraction of an entry's source text. + INTEGER E !The desired entry's number. + INTEGER P !A stage in the dereferencing. + P = TENTRY(E) !Entry E's source text is #P. + ENTRYTEXT = STASH(ISTASH(P):ISTASH(P + 1) - 1) !Stashed here. + END FUNCTION ENTRYTEXT !Fixed size only, with trailing spaces. + + CHARACTER*44 FUNCTION ENTRYTEXTCHAR(E) !The same, but with nasty characters defanged. + USE BADCHARACTER !Just so. + INTEGER E !The desired entry's number. + INTEGER P !A stage in the dereferencing. + CHARACTER*44 TEXT !A scratchpad, to avoid confusing the compiler. + INTEGER I,L,H !Fingers. + CHARACTER*1 C !A waystation. + L = 0 !No text has been extracted. + P = TENTRY(E) !Entry E's source text is #P. + DO I = ISTASH(P),ISTASH(P + 1) - 1 !Step along the stash.. + C = STASH(I:I) !Grab a character. + H = INDEX(BADC,C) !Scan the shit list. + IF (H.LE.0) THEN !One of the troublemakers? + CALL PUT(C) !No. Just copy it. + ELSE !Otherwise, + CALL PUT("!") !Place a context changer. + CALL PUT(GOODC(H:H)) !Place the corresponding mnemonic. + END IF !So much for that character. + END DO !On to the next. + ENTRYTEXTCHAR = TEXT(1:MIN(L,44)) !Protect against overflow. + CONTAINS !A trivial assistant. + SUBROUTINE PUT(C) !But too messy to have in-line. + CHARACTER*1 C !The character of the moment. + L = L + 1 !Advance to place it. + IF (L.LE.44) TEXT(L:L) = C !If within range. + END SUBROUTINE PUT !Simple enough. + END FUNCTION ENTRYTEXTCHAR !On output, the troublemakers make trouble. + + SUBROUTINE ORDERENTRYTEXT(LIST,N) +Crank up a Comb sort of the entries fingered by LIST. Working backwards, just for fun. +Caution: the H*10/13 means that H ought not be INTEGER*2. Otherwise, use H/1.3. + INTEGER LIST(*) !This is an index to the items being compared. + INTEGER T !In the absence of a SWAP(a,b). Same type as LIST. + INTEGER N !The number of entries. + INTEGER I,H !Tools. H ought not be a small integer. + LOGICAL CURSE !Annoyance. + H = N - 1 !Last - First, and not +1. + IF (H.LE.0) RETURN !Ha ha. + 1 H = MAX(1,H*10/13) !The special feature. + IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. + CURSE = .FALSE. !So far, so good. + DO I = N - H,1,-1 !If H = 1, this is a BubbleSort. + IF (ENTRYTEXT(LIST(I)).GT.ENTRYTEXT(LIST(I+H))) THEN !One compare. + T=LIST(I); LIST(I)=LIST(I+H); LIST(I+H)=T !One swap. + CURSE = .TRUE. !One curse. + END IF !One test. + END DO !One loop. + IF (CURSE .OR. H.GT.1) GO TO 1 !Work remains? + END SUBROUTINE ORDERENTRYTEXT + END MODULE COMPOUND !Accepts, stores, lists and sorts the content. + + PROGRAM MR NATURAL !Presents a list in sorted order. + USE COMPOUND !Stores text in a complicated way. + USE BADCHARACTER !Some characters wreck the layout. + INTEGER I,ITEM(30),PLAIN(30) !Two sets of indices. + I = 0 !An array must have equal-length items, so trailing spaces would result. + I=I+1;ITEM(I) = ADDENTRY("ignore leading spaces: 2-2") + I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2-1") + I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2+0") + I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2+1") + I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2-2") + I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2-1") + I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2+0") + I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2+1") + I=I+1;ITEM(I) = ADDENTRY("Equiv."//" "//"spaces: 3-3") + I=I+1;ITEM(I) = ADDENTRY("Equiv."//CR//"spaces: 3-2") !CR can't appear as itself. + I=I+1;ITEM(I) = ADDENTRY("Equiv."//FF//"spaces: 3-1") !As it is used to mark line endings. + I=I+1;ITEM(I) = ADDENTRY("Equiv."//VT//"spaces: 3+0") !And if typed in an editor, + I=I+1;ITEM(I) = ADDENTRY("Equiv."//LF//"spaces: 3+1") !It is acted upon there and then. + I=I+1;ITEM(I) = ADDENTRY("Equiv."//HT//"spaces: 3+2") !So, name instead of value. + I=I+1;ITEM(I) = ADDENTRY("cASE INDEPENDENT: 3-2") + I=I+1;ITEM(I) = ADDENTRY("caSE INDEPENDENT: 3-1") + I=I+1;ITEM(I) = ADDENTRY("casE INDEPENDENT: 3+0") + I=I+1;ITEM(I) = ADDENTRY("case INDEPENDENT: 3+1") + I=I+1;ITEM(I) = ADDENTRY("foo100bar99baz0.txt") + I=I+1;ITEM(I) = ADDENTRY("foo100bar10baz0.txt") + I=I+1;ITEM(I) = ADDENTRY("foo1000bar99baz10.txt") + I=I+1;ITEM(I) = ADDENTRY("foo1000bar99baz9.txt") + I=I+1;ITEM(I) = ADDENTRY("The Wind in the Willows") + I=I+1;ITEM(I) = ADDENTRY("The 40th step more") + I=I+1;ITEM(I) = ADDENTRY("The 39 steps") + I=I+1;ITEM(I) = ADDENTRY("Wanda") +c I=I+1;ITEM(I) = ADDENTRY("A Dinosaur Grunts: Fortran Emerges") +c I=I+1;ITEM(I) = ADDENTRY("The Joy of Text Twiddling with Fortran") +c I=I+1;ITEM(I) = ADDENTRY("An Aversion to Unused Trailing Spaces") + WRITE (MSG,*) "nEntry=",NENTRY !Reach into the compound storage area. + PLAIN = ITEM !Copy the list of entries. + CALL ORDERENTRY(ITEM,NENTRY) !"Natural" order. + CALL ORDERENTRYTEXT(PLAIN,NENTRY) !Plain text order. + WRITE (MSG,1) "Character","'Natural'" !Provide a heading. + 1 FORMAT (2("Entry|Text ",A9," Order",24X)) !Usual trickery. + DO I = 1,NENTRY !Step through the lot. + WRITE (MSG,2) PLAIN(I),ENTRYTEXTCHAR(PLAIN(I)), !Plain order, + 1 ITEM(I), ENTRYTEXTCHAR(ITEM(I)) !Followed by natural order. + 2 FORMAT (2(I5,"|",A44)) !This follows function ENTRYTEXT. + END DO !On to the next. + END !A handy hint from Mr. Natural: "At home or at work, get the right tool for the job!" diff --git a/Task/Natural-sorting/Fortran/natural-sorting-2.f b/Task/Natural-sorting/Fortran/natural-sorting-2.f new file mode 100644 index 0000000000..7cf6cf6e55 --- /dev/null +++ b/Task/Natural-sorting/Fortran/natural-sorting-2.f @@ -0,0 +1,325 @@ + MODULE ASSISTANCE + INTEGER MSG,KBD !I/O unit numbers. + DATA MSG,KBD/6,5/ !Output, input. + CONTAINS + SUBROUTINE CROAK(GASP) !A dying remark. + CHARACTER*(*) GASP !The last words. + WRITE (MSG,*) "Oh dear." !Shock. + WRITE (MSG,*) GASP !Aargh! + STOP "How sad." !Farewell, cruel world. + END SUBROUTINE CROAK !Farewell... + + SUBROUTINE UPCASE(TEXT) !In the absence of an intrinsic... +Converts any lower case letters in TEXT to upper case... +Concocted yet again by R.N.McLean (whom God preserve) December MM. +Converting from a DO loop evades having both an iteration counter to decrement and an index variable to adjust. + CHARACTER*(*) TEXT !The stuff to be modified. +c CHARACTER*26 LOWER,UPPER !Tables. a-z may not be contiguous codes. +c PARAMETER (LOWER = "abcdefghijklmnopqrstuvwxyz") +c PARAMETER (UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ") +CAREFUL!! The below relies on a-z and A-Z being contiguous, as is NOT the case with EBCDIC. + INTEGER I,L,IT !Fingers. + L = LEN(TEXT) !Get a local value, in case LEN engages in oddities. + I = L !Start at the end and work back.. + 1 IF (I.LE.0) RETURN !Are we there yet? Comparison against zero should not require a subtraction. +c IT = INDEX(LOWER,TEXT(I:I)) !Well? +c IF (IT .GT. 0) TEXT(I:I) = UPPER(IT:IT) !One to convert? + IT = ICHAR(TEXT(I:I)) - ICHAR("a") !More symbols precede "a" than "A". + IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A")) !In a-z? Convert! + I = I - 1 !Back one. + GO TO 1 !Inspect.. + END SUBROUTINE UPCASE !Easy. + + INTEGER FUNCTION LSTNB(TEXT) !Sigh. Last Not Blank. +Concocted yet again by R.N.McLean (whom God preserve) December MM. +Code checking reveals that the Compaq compiler generates a copy of the string and then finds the length of that when using the latter-day intrinsic LEN_TRIM. Madness! +Can't DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ') !Control chars. regarded as spaces. +Curse the morons who think it good that the compiler MIGHT evaluate logical expressions fully. +Crude GO TO rather than a DO-loop, because compilers use a loop counter as well as updating the index variable. +Comparison runs of GNASH showed a saving of ~3% in its mass-data reading through the avoidance of DO in LSTNB alone. +Crappy code for character comparison of varying lengths is avoided by using ICHAR which is for single characters only. +Checking the indexing of CHARACTER variables for bounds evoked astounding stupidities, such as calculating the length of TEXT(L:L) by subtracting L from L! +Comparison runs of GNASH showed a saving of ~25-30% in its mass data scanning for this, involving all its two-dozen or so single-character comparisons, not just in LSTNB. + CHARACTER*(*),INTENT(IN):: TEXT !The bumf. If there must be copy-in, at least there need not be copy back. + INTEGER L !The length of the bumf. + L = LEN(TEXT) !So, what is it? + 1 IF (L.LE.0) GO TO 2 !Are we there yet? + IF (ICHAR(TEXT(L:L)).GT.ICHAR(" ")) GO TO 2 !Control chars are regarded as spaces also. + L = L - 1 !Step back one. + GO TO 1 !And try again. + 2 LSTNB = L !The last non-blank, possibly zero. + RETURN !Unsafe to use LSTNB as a variable. + END FUNCTION LSTNB !Compilers can bungle it. + END MODULE ASSISTANCE + + MODULE BADCHARACTER !Some characters are not for glyphs but for action. + CHARACTER*1 BS,HT,LF,VT,FF,CR !Nicknames for a bunch of troublemakers. + CHARACTER*6 BADC,GOODC !I want a system. + INTEGER*1 IBADC(6) !Initialisation syntax is restricive. + PARAMETER (GOODC="btnvfr") !Mnemonics. + EQUIVALENCE (BADC(1:1),BS),(BADC(2:2),HT),(BADC(3:3),LF),!Match the names + 1 (BADC(4:4),VT),(BADC(5:5),FF),(BADC(6:6),CR), !To their character. + 2 (IBADC,BADC) !Alas, a PARAMETER style is rejected. + DATA IBADC/8,9,10,11,12,13/ !ASCII encodements. + PRIVATE IBADC !Keep this quiet. + CONTAINS + CHARACTER*44 FUNCTION DEFANG(THIS) !Ad-hoc text conversion with nasty characters defanged. + CHARACTER*(*) THIS !The text. + CHARACTER*44 TEXT !A scratchpad, to avoid confusing the compiler. + INTEGER I,L,H !Fingers. + CHARACTER*1 C !A waystation. + L = 0 !No text has been extracted. + DO I = 1,LEN(THIS) !Step along the stash.. + C = THIS(I:I) !Grab a character. + H = INDEX(BADC,C) !Scan the shit list. + IF (H.LE.0) THEN !One of the troublemakers? + CALL PUT(C) !No. Just copy it. + ELSE !Otherwise, + CALL PUT("!") !Place a context changer. + CALL PUT(GOODC(H:H)) !Place the corresponding mnemonic. + END IF !So much for that character. + END DO !On to the next. + DEFANG = TEXT(1:MIN(L,44)) !Protect against overflow. + CONTAINS !A trivial assistant. + SUBROUTINE PUT(C) !But too messy to have in-line. + CHARACTER*1 C !The character of the moment. + L = L + 1 !Advance to place it. + IF (L.LE.44) TEXT(L:L) = C !If within range. + END SUBROUTINE PUT !Simple enough. + END FUNCTION DEFANG !On output, the troublemakers make trouble. + END MODULE BADCHARACTER !They can disrupt layout. + + MODULE COMPOUND !Stuff to store the text entries, and to sort lists. + USE ASSISTANCE + INTEGER LENTRY,NENTRY,MENTRY !Size information. + PARAMETER (LENTRY = 66, MENTRY = 666) !Should suffice. + INTEGER ENTRYLENGTH(MENTRY) !Lengths for the entries. + CHARACTER*(LENTRY) ENTRYTEXT(MENTRY) !Their texts. + CHARACTER*(LENTRY) ENTRYKEY(MENTRY) !Comparison keys. + CONTAINS !The details. + INTEGER FUNCTION ADDENTRY(X) !Create an entry holding X. + CHARACTER*(*) X !The text to be stashed. + INTEGER L !It may have trailing space stuff. + L = LSTNB(X) !Thus, LEN(X) won't do. + IF (L.GT.LENTRY) CALL CROAK("Over-long text!") !Even though any trailing spaces have been lost. + IF (NENTRY.GE.MENTRY) CALL CROAK("Too many entries!") !Perhaps I can't. + NENTRY = NENTRY + 1 !Righto, another one. + ENTRYTEXT(NENTRY)(1:L) = X(1:L)!Place. Trailing spaces will not be supplied. + ENTRYLENGTH(NENTRY) = L !But I won't be looking where they won't be. + ADDENTRY = NENTRY !The caller needn't keep count. + END FUNCTION ADDENTRY !That was simple. + + INTEGER FUNCTION TEXTORDER(E1,E2) !Compare the texts as they stand. + INTEGER E1,E2 !Finger the entries holding the texts. + IF (ENTRYTEXT(E1)(1:ENTRYLENGTH(E1)) !If the text of entry E1 + 1 .LT.ENTRYTEXT(E2)(1:ENTRYLENGTH(E2))) THEN !Precedes that of E2, + TEXTORDER = +1 !Then the order is good. + ELSE IF (ENTRYTEXT(E1)(1:ENTRYLENGTH(E1)) !ENTRYLENGTH means no trailing spaces. + 1 .GT.ENTRYTEXT(E2)(1:ENTRYLENGTH(E2))) THEN !Accordingly, no "x" = "x " accommodation. + TEXTORDER = -1 !So, reversed order. + ELSE !Otherwise, + TEXTORDER = 0 !They're equal. + END IF !So, decided. + END FUNCTION TEXTORDER !Thus use the character collation sequence. + + INTEGER FUNCTION NATURALORDER(E1,E2) !Compares the texts in "natural" order. + INTEGER E1,E2 !Pity this couldn't be an array of two values. + CHARACTER*4 ARTICLE(3) !By chance, three, by happy chance, lengths 1, 2, 3! + PARAMETER (ARTICLE = (/"A","AN","THE"/)) !These each have trailing space. + INTEGER DONE,BORED,GRIST,NUMERIC !Might as well supply some mnemonics. + PARAMETER (DONE=-1,BORED=0,GRIST=1,NUMERIC=2) !For nearly arbitrary integers. + INTEGER WOT(2) !Collect the two entry numbers. + INTEGER L(2),LST(2) !Scan text with finger L, ending with LST. + INTEGER N !Counter for comparisons. + INTEGER DCOUNT(2) !Counts the number of digits for L(is) onwards. + INTEGER STATE(2) !The scans vary in mood. + INTEGER TAIL(2) !The LIBRARIAN may discover an ARTICLE and put it in the TAIL. + INTEGER D !A difference. + CHARACTER*1 C(2) !Character pairs ascertained one-by-one by ANOTHER. + WOT(1) = E1 !Alright, + WOT(2) = E2 !Into an array to play. + L = 0 !Syncopation to start the scan. + LST = ENTRYLENGTH(WOT) !End markers. + STATE = BORED !So far, and no matter what the librarian discovers. + DCOUNT = 0 !Nor have any digits been counted. + CALL LIBRARIAN !Assess the start of the texts. + N = 0 !No comparisons so far. +Chug along the texts, character by character. + 10 CALL ANOTHER !Grab one from each text. + N = N + 1 !Count another compare. + ENTRYKEY(WOT)(N:N) = C !Place the characters being compared. + D = ICHAR(C(2)) - ICHAR(C(1)) !Their difference. + IF (D.NE.0) GO TO 666 !A decision yet? + L = L + 1 !No. Advance both fingers. + IF (ANY(STATE.NE.DONE)) GO TO 10 !And try again. + 666 NATURALORDER = D !The decision. + RETURN !Despite the lack of an END, this is the end of the function. + CONTAINS !Which however contains some assistants, defined after use. + SUBROUTINE CRUSH(C) !Reduces annoying variation. + CHARACTER*1 C !The victim. + IF (C.LE." ") THEN !Spaceish? + C = " " !Yes. Standardise. + ELSE !For all others, + CALL UPCASE(C) !Simplify. + END IF !Righto, ready to compare. + END SUBROUTINE CRUSH !This should do the deed in place. + + SUBROUTINE ANOTHER !The entry's text may be followed by an article in the tail. +Claws along the text strings, looking for the next character pair to report for matching. + INTEGER IS !Steps through the two texts. + INTEGER L2 !A second finger, for probing ahead and the TAIL. + CHARACTER*1 D !Potentially a digit character. + EE:DO IS = 1,2 !Dealing with both texts in the same way. + 10 L2 = L(IS) - LST(IS) !Compare the finger to the end-of-text. + IF (L2.GT.0) THEN !Perhaps we have reached the tail. + IF (TAIL(IS).GT.0 .AND. L2.LE.TAIL(IS)) THEN !Yes. What about the possible tail? + C(IS) = ARTICLE(TAIL(IS))(L2:L2) !Still wagging. + ELSE !But if no tail (or the tail is exhausted) + C(IS) = CHAR(0) !Empty space. + STATE(IS) = DONE !Declare this. + END IF !So much for the librarian's tail. + CYCLE EE !On to the next text. + END IF !But if we have text yet to scan, + C(IS) = ENTRYTEXT(WOT(IS))(L(IS):L(IS)) !Grab the character. + CALL CRUSH(C(IS)) !Simplify. + IF (C(IS).EQ." ") THEN !So, what have we received? + IF (STATE(IS).EQ.BORED) THEN !A space. Are we ignoring them? + L(IS) = L(IS) + 1 !Yes. Advance in hope. + GO TO 10 !And try again. + END IF !So much for another space. + STATE(IS) = BORED !If we weren't in spaces, we are now. + ELSE IF (C(IS).GE."0" .AND. C(IS).LE."9") THEN !A digit? + STATE(IS) = NUMERIC !Double trouble might ensue. + ELSE !For all other characters, + STATE(IS) = GRIST !We have grist. + END IF !So much for the character. + END DO EE !On to the next text. +Comparing digit sequences is to be done as numbers. "007" vs "70" is to become vs. "070" by length matching. + IF (ALL(STATE.EQ.NUMERIC)) THEN !If we're comparing a digit to a digit, + IF (ALL(DCOUNT.EQ.0)) THEN !I want to align the comparison from the right. + DD:DO IS = 1,2 !So I need to determine how many digits follow in both. + 20 DCOUNT(IS) = DCOUNT(IS) + 1 !Count one more. + L2 = L(IS) + DCOUNT(IS) !Finger the next position. + IF (L2.GT.LST(IS)) CYCLE DD !If we're off the end, we're done. + D = ENTRYTEXT(WOT(IS))(L2:L2) !Otherwise, grab the character. + IF (D.LT."0" .OR. D.GT."9") CYCLE DD !Not a digit: done counting. + GO TO 20 !Otherwise, keep on looking. + END DO DD !On to the other text. + END IF !Righto, I now know how many digits are in each sequence. +Choose the shorter, and notionally insert a leading zero for it to be matched against the longer's digit.. + IF (DCOUNT(1).LT.DCOUNT(2)) THEN !Righto, if the first has fewer digits, + DCOUNT(2) = DCOUNT(2) - 1 !Then only the second's digit will be used up. + L(1) = L(1) - 1 !Step back to re-encounter this next time. + C(1) = "0" !And create a leading zero from nothing. + ELSE IF (DCOUNT(2).LT.DCOUNT(1)) THEN !Likewise if the other way around. + DCOUNT(1) = DCOUNT(1) - 1 !The scan will consume this side's digit. + L(2) = L(2) - 1 !The next time here (if there is one) + C(2) = "0" !Will find a reduced difference in length. + ELSE !But if both have the same number of digits remaining, + DCOUNT = DCOUNT - 1 !They are used in parallel. + END IF !Perhaps even equal digit remnants. + END IF !Thus, arbitrary-size numbers are allowed, as they're never numbers. + END SUBROUTINE ANOTHER !Characters are announced in array C, moods in array STATE. + + SUBROUTINE LIBRARIAN !Looks for texts starting "The ..." or "An ..." or "A ...", library style. +Checks the starts of the two texts, skipping leading spaceish stuff. + INTEGER IS,A,I !Steppers. + CHARACTER*1 C !A character to mess with. + EE:DO IS = 1,2 !Two texts to inspect. + TAIL(IS) = 0 !Nothing special found. + 10 L(IS) = L(IS) + 1 !Advance one. + IF (L(IS).GT.LST(IS)) CYCLE EE !Run out of text? + IF (ENTRYTEXT(WOT(IS))(L(IS):L(IS)).LE." ") GO TO 10 !Scoot through leading space stuff. + AA:DO A = 1,3 !Now step through the known articles. + DO I = 0,A !Character by character thereof, with one trailing space. + IF (L(IS) + I.GT.LST(IS)) CYCLE EE !Have I a character to probe? + C = ENTRYTEXT(WOT(IS))(L(IS) + I:L(IS) + I) !Yes. Grab it. + CALL CRUSH(C) !Simplify. + IF (C.NE.ARTICLE(A)(1 + I:1 + I)) CYCLE AA !Mismatch? Try another. + END DO !On to the next character of ARTICLE(A). + TAIL(IS) = A !A match! + L(IS) = L(IS) + I !Finger the first character after the space. + CYCLE EE !Finished with this text. Also, BORED. + END DO AA !Try the next article.. + END DO EE !Try the next text. + END SUBROUTINE LIBRARIAN !Ah, catalogue order. Blah, The. + END FUNCTION NATURALORDER !Not natural to a computer. + + SUBROUTINE ORDERENTRY(LIST,N,WOTORDER) !Sorts the list according to the ordering function. +Crank up a Comb sort of the entries fingered by LIST. Working backwards, just for fun. +Caution: the H*10/13 means that H ought not be INTEGER*2. Otherwise, use H/1.3. + INTEGER LIST(*) !This is an index to the items being compared. + INTEGER T !In the absence of a SWAP(a,b). Same type as LIST. + INTEGER N !The number of entries. + EXTERNAL WOTORDER !A function to compare two entries. + INTEGER WOTORDER !Returns an integer result, on principle. + INTEGER I,H !Tools. H ought not be a small integer. + LOGICAL CURSE !Annoyance. + H = N - 1 !Last - First, and not +1. + IF (H.LE.0) RETURN !Ha ha. + 1 H = MAX(1,H*10/13) !The special feature. + IF (H.EQ.9 .OR. H.EQ.10) H = 11 !A twiddle. + CURSE = .FALSE. !So far, so good. + DO I = N - H,1,-1 !If H = 1, this is a BubbleSort. + IF (WOTORDER(LIST(I),LIST(I + H)) .LT. 0) THEN !One compare. + T=LIST(I); LIST(I)=LIST(I+H); LIST(I+H)=T !One swap. + CURSE = .TRUE. !One curse. + END IF !One test. + END DO !One loop. + IF (CURSE .OR. H.GT.1) GO TO 1 !Work remains? + END SUBROUTINE ORDERENTRY!Fast enough, and simple. + END MODULE COMPOUND !Enough. + + PROGRAM MR NATURAL !Presents a list in sorted order. + USE ASSISTANCE !Often needed. + USE COMPOUND !Deals with text in a complicated way. + USE BADCHARACTER !Some characters wreck the layout. + INTEGER ITEM(30),FANCY(30)!Two sets of indices. + INTEGER I,IT,TI !Assistants. + I = 0 !An array must have equal-length items, so trailing spaces would result. + I=I+1;ITEM(I) = ADDENTRY("ignore leading spaces: 2-2") + I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2-1") + I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2+0") + I=I+1;ITEM(I) = ADDENTRY(" ignore leading spaces: 2+1") + I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2-2") + I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2-1") + I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2+0") + I=I+1;ITEM(I) = ADDENTRY("ignore m.a.s spaces: 2+1") + I=I+1;ITEM(I) = ADDENTRY("Equiv."//" "//"spaces: 3-3") + I=I+1;ITEM(I) = ADDENTRY("Equiv."//CR//"spaces: 3-2") !CR can't appear as itself. + I=I+1;ITEM(I) = ADDENTRY("Equiv."//FF//"spaces: 3-1") !As it is used to mark line endings. + I=I+1;ITEM(I) = ADDENTRY("Equiv."//VT//"spaces: 3+0") !And if typed in an editor, + I=I+1;ITEM(I) = ADDENTRY("Equiv."//LF//"spaces: 3+1") !It is acted upon there and then. + I=I+1;ITEM(I) = ADDENTRY("Equiv."//HT//"spaces: 3+2") !So, name instead of value. + I=I+1;ITEM(I) = ADDENTRY("cASE INDEPENDENT: 3-2") + I=I+1;ITEM(I) = ADDENTRY("caSE INDEPENDENT: 3-1") + I=I+1;ITEM(I) = ADDENTRY("casE INDEPENDENT: 3+0") + I=I+1;ITEM(I) = ADDENTRY("case INDEPENDENT: 3+1") + I=I+1;ITEM(I) = ADDENTRY("foo100bar99baz0.txt") + I=I+1;ITEM(I) = ADDENTRY("foo100bar10baz0.txt") + I=I+1;ITEM(I) = ADDENTRY("foo1000bar99baz10.txt") + I=I+1;ITEM(I) = ADDENTRY("foo1000bar99baz9.txt") + I=I+1;ITEM(I) = ADDENTRY("The Wind in the Willows") + I=I+1;ITEM(I) = ADDENTRY("The 40th step more") + I=I+1;ITEM(I) = ADDENTRY("The 39 steps") + I=I+1;ITEM(I) = ADDENTRY("Wanda") +c I=I+1;ITEM(I) = ADDENTRY("A Dinosaur Grunts: Fortran Emerges") +c I=I+1;ITEM(I) = ADDENTRY("The Joy of Text Twiddling with Fortran") +c I=I+1;ITEM(I) = ADDENTRY("An Abundance of Storage Enables Waste") +c I=I+1;ITEM(I) = ADDENTRY("Theory Versus Practice: The Chasm") + WRITE (MSG,*) "nEntry=",NENTRY !Reach into the compound storage area. + FANCY = ITEM !Copy the list of entries. + ENTRYKEY = "" !To be written to by NATURALORDER. + CALL ORDERENTRY(FANCY,NENTRY,NATURALORDER) !"Natural" order. + CALL ORDERENTRY(ITEM,NENTRY,TEXTORDER) !Plain text order. + WRITE (MSG,1) "Character","'Natural'","N.Key" !Provide a heading. + 1 FORMAT (3("Entry|Text ",A9," Order",16X)) !Usual trickery. + DO I = 1,NENTRY !Step through the lot. + IT = ITEM(I) !Saving on some typing. + TI = FANCY(I) !Presenting two lists, line by line. + WRITE (MSG,2) IT,DEFANG(ENTRYTEXT(IT)(1:ENTRYLENGTH(IT))) !Plain order, + 1 ,TI,DEFANG(ENTRYTEXT(TI)(1:ENTRYLENGTH(TI))) !Followed by natural order. + 2 ,TI,ENTRYKEY(TI) !Already defanged. + 2 FORMAT (3(I5,"|",A36)) !This follows function ENTRYTEXT. + END DO !On to the next. + END !A handy hint from Mr. Natural: "At home or at work, get the right tool for the job!" diff --git a/Task/Natural-sorting/Pascal/natural-sorting.pascal b/Task/Natural-sorting/Pascal/natural-sorting.pascal new file mode 100644 index 0000000000..2eb5b22212 --- /dev/null +++ b/Task/Natural-sorting/Pascal/natural-sorting.pascal @@ -0,0 +1,244 @@ +Program Natural; Uses DOS, crt; {Simple selection.} +{Demonstrates a "natural" order of sorting text with nameish parts.} + + Const null=#0; BS=#8; HT=#9; LF=#10{0A}; VT=#11{0B}; FF=#12{0C}; CR=#13{0D}; + + Procedure Croak(gasp: string); + Begin + WriteLn(Gasp); + HALT; + End; + + Function Space(n: integer): string; {Can't use n*" " either.} + var text: string; {A scratchpad.} + var i: integer; {A stepper.} + Begin + if n > 255 then n:=255 {A value parameter,} + else if n < 0 then n:=0; {So this just messes with my copy.} + for i:=1 to n do text[i]:=' '; {Place some spaces.} + text[0]:=char(n); {Place the length thereof.} + Space:=text; {Take that.} + End; {of Space.} + + Function DeFang(x: string): string; {Certain character codes cause action.} + var text: string; {A scratchpad, as using DeFang directly might imply recursion.} + var i: integer; {A stepper.} + var c: char; {Reduce repetition.} + Begin {I hope that appending is recognised by the compiler...} + text:=''; {Scrub the scratchpad.} + for i:=1 to Length(x) do {Step through the source text.} + begin {Inspecting each character.} + c:=char(x[i]); {Grab it.} + if c > CR then text:=text + c {Deemed not troublesome.} + else if c < BS then text:=text + c {Lacks an agreed alternative, and may not cause trouble.} + else text:=text + '!' + copy('btnvfr',ord(c) - ord(BS) + 1,1); {The alternative codes.} + end; {On to the next.} + DeFang:=text; {Alas, the "escape" convention lengthens the text.} + End; {of DeFang.} {But that only mars the layout, rather than ruining it.} + + Const mEntry = 66; {Sufficient for demonstrations.} + Type EntryList = array[0..mEntry] of integer; {Identifies texts by their index.} + var EntryText: array[1..mEntry] of string; {Inbto this array.} + var nEntry: integer; {The current number.} + Function AddEntry(x: string): integer; {Add another text to the collection.} + Begin {Could extend to checking for duplicates via a sorted list...} + if nEntry >= mEntry then Croak('Too many entries!'); {Perhaps not!} + inc(nEntry); {So, another.} + EntryText[nEntry]:=x; {Placed.} + AddEntry:=nEntry; {The caller will want to know where.} + End; {of AddEntry.} + + Function TextOrder(i,j: integer): boolean; {This is easy.} + Begin {But despite being only one statement, and simple at that,} + TextOrder:=EntryText[i] <= EntryText[j]; {Begin...End is insisted upon.} + End; {of TextOrder.} + + Function NaturalOrder(e1,e2: integer): boolean;{Not so easy.} + const Article: array[1..3] of string[4] = ('A ','AN ','THE '); {Each with its trailing space.} + Function Crush(var c: char): char; {Suppresses divergence.} + Begin {To simplify comparisons.} + if c <= ' ' then Crush:=' ' {Crush the fancy control characters.} + else Crush:=UpCase(c); {Also crush a < A or a > A or a = A questions.} + End; {of Crush.} + var Wot: array[1..2] of integer; {Which text is being fingered.} + var Tail: array[1..2] of integer; {Which article has been found at the start.} + var l,lst: array[1..2] of integer; {Finger to the current point, and last character.} + Procedure Librarian; {Initial inspection of the texts.} + var Blocked: boolean; {Further progress may be obstructed.} + var a,is,i: integer; {Odds and ends.} + label Hic; {For escaping the search when a match is complete.} + Begin {There are two texts to inspect.} + for is:=1 to 2 do {Treat them alike.} + begin {This is the first encounter.} + l[is]:=1; {So start the scan with the first character.} + Tail[is]:=0; {No articles found.} + while (l[is] <= lst[is]) and (EntryText[wot[is]][l[is]] <= ' ') do inc(l[is]); {Leading spaceish.} + for a:=1 to 3 do {Try to match an article at the start of the text.} + begin {Each article's text has a trailing space to be matched also.} + i:=0; {Start a for-loop, but with early escape in mind.} + Repeat {Compare successive characters, for i:=0 to a...} + if l[is] + i > lst[is] then Blocked:=true {Probed past the end of text?} + else Blocked:=Crush(EntryText[wot[is]][l[is] + i]) <> Article[a][i + 1]; {No. Compare capitals.} + inc(i); {Stepping on to the next character.} + Until Blocked or (i > a); {Conveniently, Length(Article[a]) = a.} + if not Blocked then {Was a mismatch found?} + begin {No!} + Tail[is]:=a; {So, identify the discovery.} + l[is]:=l[is] + i; {And advance the scan to whatever follows.} + goto Hic; {Escape so as to consider the other text.} + end; {Since two texts are being considered separately.} + end; {Sigh. no "Next a" or similar syntax.} + Hic:dec(l[is]); {Backstep one, ready to advance later.} + end; {Likewise, no "for is:=1 to 2 do ... Next is" syntax.} + End; {of Librarian.} + var c: array[1..2] of string[1]; {Selected by Advance for comparison.} + var d: integer; {Their difference.} + type moody = (Done,Bored,Grist,Numeric); {Might as well have some mnemonics.} + var Mood: array[1..2] of moody; {As the scan proceeds, moods vary.} + var depth: array[1..2] of integer; {Digit depth.} + Procedure Another; {Choose a pair of characters to compare.} + {Digit sequences are special! But periods are ignored, also signs, avoiding confusion over "+6" and " 6".} + var is: integer; {Selects from one text or the other.} + var ll: integer; {Looks past the text into any Article.} + var d: char; {Possibly a digit.} + Begin + for is:=1 to 2 do {Same treatment for both texts.} + begin {Find the next character, and taste it.} + repeat {If already bored, slog through any following spaces.} + inc(l[is]); {So, advance one character onwards.} + ll:=l[is] - lst[is]; {Compare to the end of the normal text.} + if ll <= 0 then c[is]:=Crush(EntryText[wot[is]][l[is]]) {Still in the normal text.} + else if Tail[is] <= 0 then c[is]:='' {Perhaps there is no tail.} + else if ll <= 2 then c[is]:=copy(', ',ll,1) {If there is, this is the junction.} + else if ll <= 2 + Tail[is] then c[is]:=copy(Article[Tail[is]],ll - 2,1) {And this the tail.} + else c[is]:=''; {Actually, the copy would do this.} + until not ((c[is] = ' ') and (Mood[is] = Bored)); {Thus pass multiple enclosed spaces, but not the first.} + if length(c[is]) <= 0 then Mood[is]:=Done {Perhaps we ran off the end, even of the tail.} + else if c[is] = ' ' then Mood[is]:=Bored {The first taste of a space induces boredom.} + else if ('0' <= c[is]) and (c[is] <= '9') then Mood[is]:=Numeric {Paired, evokes special attention.} + else Mood[is]:=Grist; {All else is grist for my comparisons.} + end; {Switch to the next text.} +{Comparing digit sequences is to be done as if numbers. "007" vs "70" is to become vs. "070" by length matching.} + if (Mood[1] = Numeric) and (Mood[2] = Numeric) then {Are both texts yielding a digit?} + begin {Yes. Special treatment impends.} + if (Depth[1] = 0) and (Depth[2] = 0) then {Do I already know how many digits impend?} + for is:=1 to 2 do {No. So for each text,} + repeat {Keep looking until I stop seeing digits.} + inc(Depth[is]); {I am seeing a digit, so there will be one to count.} + ll:=l[is] + Depth[is]; {Finger the next position.} + if ll > lst[is] then d:=null {And if not off the end,} + else d:=EntryText[wot[is]][ll]; {Grab a potential digit.} + until (d < '0') or (d > '9'); {If it is one, probe again.} + if Depth[1] < Depth[2] then {Righto, if the first sequence has fewer digits,} + begin {Supply a free zero.} + dec(Depth[2]); {The second's digit will be consumed.} + dec(l[1]); {The first's will be re-encountered.} + c[1]:='0'; {Here is the zero} + end {For the comparison.} + else if Depth[2] < Depth[1] then {But if the second has fewer digits to come,} + begin {Don't dig into them yet.} + dec(Depth[1]); {The first's digit will be used.} + dec(l[2]); {But the second's seen again.} + c[2]:='0'; {After this has been used} + end {In the comparison.} + else {But if both have the same number of digits remaining,} + begin {Then the comparison is aligned.} + dec(Depth[1]); {So this digit will be used.} + dec(Depth[2]); {As will this.} + end; {In the comparison.} + end; {Thus, arbitrary-size numbers are allowed, as they're never numbers.} + End; {of Another.} {Possibly, the two characters will be the same, and another pair will be requested.} + Begin {of NaturalOrder.} + Wot[1]:=e1; Wot[2]:=e2; {Make the two texts accessible via indexing.} + lst[1]:=Length(EntryText[e1]); {The last character of the first text.} + lst[2]:=Length(EntryText[e2]); {And of the second. Saves on repetition.} + Mood[1]:=Bored; Mood[2]:=Bored; {Behave as if we have already seen a space.} + depth[1]:=0; depth[2]:=0; {And, no digits in concert have been seen.} + Librarian; {Start the inspection.} + repeat {Chug along, until a difference is found.} + Another; {To do so, choose another pair of characters to compare.} + d:=Length(c[2]) - Length(c[1]); {If one text has run out, favour the shorter.} + if (d = 0) and (Length(c[1]) > 0) then d:=ord(c[2][1]) - ord(c[1][1]); {Otherwise, their difference.} + until (d <> 0) or ((Mood[1] = Done) and (Mood[2] = Done)); {Well? Are we there yet?} + NaturalOrder:=d >= 0; {And so, does e1's text precede e2's?} + End; {of NatualOrder.} + + var TextSort: boolean; {Because I can't pass a function as a parameter,} + Function InOrder(i,j: integer): boolean; {I can only use one function.} + Begin {Which messes with a selector.} + if TextSort then InOrder:=TextOrder(i,j) {So then,} + else InOrder:=NaturalOrder(i,j); {Which is it to be?} + End; {of InOrder.} + Procedure OrderEntry(var List: EntryList); {Passing a ordinary array is not Pascalish, damnit.} +{Crank up a Comb sort of the entries fingered by List. Working backwards, just for fun.} +{Caution: the H*10/13 means that H ought not be INTEGER*2. Otherwise, use H/1.3.} + var t: integer; {Same type as the elements of List.} + var N,i,h: integer; {Odds and ends.} + var happy: boolean; {To be attained.} + Begin + N:=List[0]; {Extract the count.} + h:=N - 1; {"Last" - "First", and not +1.} + if h <= 0 then exit; {Ha ha.} + Repeat {Start the pounding.} + h:=LongInt(h)*10 div 13; {Beware overflow, or, use /1.3.} + if h <= 0 then h:=1; {No "max" function, damnit.} + if (h = 9) or (h = 10) then h:=11; {A fiddle.} + happy:=true; {No disorder seen.} + for i:=N - h downto 1 do {So, go looking. If h = 1, this is a Bubblesort.} + if not InOrder(List[i],List[i + h]) then {How about this pair?} + begin {Alas.} + t:=List[i]; List[i]:=List[i + h]; List[i + h]:=t;{No Swap(a,b), damnit.} + happy:=false; {Disorder has been discovered.} + end; {On to the next comparison.} + Until happy and (h = 1); {No suspicion remains?} + End; {of OrderEntry.} + + var Item,Fancy: EntryList; {Two lists of entry indices.} + var i: integer; {A stepper.} + var t1: string; {A scratchpad.} + BEGIN + nEntry:=0; {No entries are stored.} + i:=0; {Start a stepper.} + inc(i);Item[i]:=AddEntry('ignore leading spaces: 2-2'); + inc(i);Item[i]:=AddEntry(' ignore leading spaces: 2-1'); + inc(i);Item[i]:=AddEntry(' ignore leading spaces: 2+0'); + inc(i);Item[i]:=AddEntry(' ignore leading spaces: 2+1'); + inc(i);Item[i]:=AddEntry('ignore m.a.s spaces: 2-2'); + inc(i);Item[i]:=AddEntry('ignore m.a.s spaces: 2-1'); + inc(i);Item[i]:=AddEntry('ignore m.a.s spaces: 2+0'); + inc(i);Item[i]:=AddEntry('ignore m.a.s spaces: 2+1'); + inc(i);Item[i]:=AddEntry('Equiv.'+' '+'spaces: 3-3'); + inc(i);Item[i]:=AddEntry('Equiv.'+CR+'spaces: 3-2'); {CR can't appear as itself.} + inc(i);Item[i]:=AddEntry('Equiv.'+FF+'spaces: 3-1'); {As it is used to mark line endings.} + inc(i);Item[i]:=AddEntry('Equiv.'+VT+'spaces: 3+0'); {And if typed in an editor,} + inc(i);Item[i]:=AddEntry('Equiv.'+LF+'spaces: 3+1'); {It is acted upon there and then.} + inc(i);Item[i]:=AddEntry('Equiv.'+HT+'spaces: 3+2'); {So, name instead of value.} + inc(i);Item[i]:=AddEntry('cASE INDEPENDENT: 3-2'); + inc(i);Item[i]:=AddEntry('caSE INDEPENDENT: 3-1'); + inc(i);Item[i]:=AddEntry('casE INDEPENDENT: 3+0'); + inc(i);Item[i]:=AddEntry('case INDEPENDENT: 3+1'); + inc(i);Item[i]:=AddEntry('foo100bar99baz0.txt'); + inc(i);Item[i]:=AddEntry('foo100bar10baz0.txt'); + inc(i);Item[i]:=AddEntry('foo1000bar99baz10.txt'); + inc(i);Item[i]:=AddEntry('foo1000bar99baz9.txt'); + inc(i);Item[i]:=AddEntry('The Wind in the Willows'); + inc(i);Item[i]:=AddEntry('The 40th step more'); + inc(i);Item[i]:=AddEntry('The 39 steps'); + inc(i);Item[i]:=AddEntry('Wanda'); + {inc(i);Item[i]:=AddEntry('The Worth of Wirth''s Way');} + Item[0]:=nEntry; {Complete the EntryList protocol.} + for i:=0 to nEntry do Fancy[i]:=Item[i]; {Sigh. Fancy:=Item.} + + TextSort:=true; OrderEntry(Item); {Plain text ordering.} + + TextSort:=false; OrderEntry(Fancy); {Natural order.} + + WriteLn(' Text order Natural order'); + for i:=1 to nEntry do + begin + t1:=DeFang(EntryText[Item[i]]); + WriteLn(Item[i]:3,'|',t1,Space(30 - length(t1)),' ', + Fancy[i]:3,'|',DeFang(EntryText[Fancy[i]])); + end; + + END. diff --git a/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences-1.julia b/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences-1.julia new file mode 100644 index 0000000000..662a908f7a --- /dev/null +++ b/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences-1.julia @@ -0,0 +1,33 @@ +iscontseq(n::Integer) = count_zeros(n) == leading_zeros(n) + trailing_zeros(n) +iscontseq(n::BigInt) = !ismatch(r"0", rstrip(bin(n), '0')) + +function makeint2seq(n::Integer) + const idex = collect(1:n) + function int2seq(m::Integer) + d = digits(m, 2, n) + idex[d .== 1] + end + return int2seq +end + +immutable NCSubSeq{T<:Integer} + n::T +end + +type NCSubState{T<:Integer} + m::T + m2s::Function +end + +Base.length(a::NCSubSeq) = 2^a.n - div(a.n*(a.n+1), 2) - 1 +Base.start(a::NCSubSeq) = NCSubState(5, makeint2seq(a.n)) +Base.done(a::NCSubSeq, as::NCSubState) = 2^a.n-3 < as.m + +function Base.next(a::NCSubSeq, as::NCSubState) + s = as.m2s(as.m) + as.m += 1 + while iscontseq(as.m) + as.m += 1 + end + return (s, as) +end diff --git a/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences-2.julia b/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences-2.julia new file mode 100644 index 0000000000..e823f3efa7 --- /dev/null +++ b/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences-2.julia @@ -0,0 +1,29 @@ +n = 4 +print("Testing NCSubSeq for ", n, " items:\n ") +for a in NCSubSeq(n) + print(" ", a) +end +println() + +s = "Rosetta" +cs = split(s, "") +m = 10 +n = length(NCSubSeq(length(s))) - m +println() +println("The first and last ", m, " NC sub-sequences of \"", s, "\":") +for (i,a) in enumerate(NCSubSeq(length(cs))) + i <= m || n < i || continue + println(@sprintf "%6d %s" i join(cs[a], "")) + i == m || continue + println(" .. ......") +end + +t = {} +append!(t, collect(1:10)) +append!(t, collect(20:10:40)) +append!(t, big(50):50:200) +println() +println("Numbers of NC sub-sequences of a given length:") +for i in t + println(@sprintf("%7d => ", i), length(NCSubSeq(i))) +end diff --git a/Task/Non-continuous-subsequences/Perl-6/non-continuous-subsequences.pl6 b/Task/Non-continuous-subsequences/Perl-6/non-continuous-subsequences.pl6 index 0228a7d25e..1b7890db87 100644 --- a/Task/Non-continuous-subsequences/Perl-6/non-continuous-subsequences.pl6 +++ b/Task/Non-continuous-subsequences/Perl-6/non-continuous-subsequences.pl6 @@ -1,11 +1,7 @@ sub non_continuous_subsequences ( *@list ) { - powerset(@list).grep: { 1 != all( .[ 0 ^.. .end] Z- .[0 ..^ .end] ) } + @list.combinations.grep: { 1 != all( .[ 0 ^.. .end] Z- .[0 ..^ .end] ) } } -sub powerset ( *@list ) { - reduce( -> @L, $n { [ @L, @L.map: {[ .list, $n ]} ] }, [[]], @list ); -} - -say ~ non_continuous_subsequences( 1..3 )».perl; -say ~ non_continuous_subsequences( 1..4 )».perl; -say ~ non_continuous_subsequences( ^4 ).map: {[[.list]].perl}; +say non_continuous_subsequences( 1..3 )».gist; +say non_continuous_subsequences( 1..4 )».gist; +say non_continuous_subsequences( ^4 ).map: {[[.list]].gist}; diff --git a/Task/Non-continuous-subsequences/REXX/non-continuous-subsequences.rexx b/Task/Non-continuous-subsequences/REXX/non-continuous-subsequences.rexx index 7723033ca1..c7162987ee 100644 --- a/Task/Non-continuous-subsequences/REXX/non-continuous-subsequences.rexx +++ b/Task/Non-continuous-subsequences/REXX/non-continuous-subsequences.rexx @@ -1,33 +1,33 @@ -/*REXX program to list non-continuous subsequences (NCS), given a seq.*/ -parse arg list /*the the list from the CL.*/ -if list='' then list=1 2 3 4 5 /*Specified? Use default. */ -say 'list=' space(list); say /*show list to the terminal*/ -w=words(list) ; #=0 /*# words in list; # of NCS*/ -$=left(123456789,w) /*build a string of digits.*/ -tail=right($,max(0,w-2)) /*construct a "fast" tail. */ +/*REXX program lists non-continuous subsequences (NCS), given a sequence. */ +parse arg list /*obtain the list from the C.L. */ +if list='' then list=1 2 3 4 5 /*Not specified? Use the default*/ +say 'list=' space(list); say /*display the list to terminal. */ +w=words(list) ; #=0 /*W: words in list; # of NCS. */ +$=left(123456789,w) /*build a string of decimal digs.*/ +tail=right($,max(0,w-2)) /*construct a "fast" tail. */ - do j=13 to left($,1) || tail /*step through the list. */ - if verify(j,$)\==0 then iterate /*Not one of the chosen? */ - f=left(j,1) /*the first digit of j. */ - NCS=0 /*not non-continuous subseq*/ - do k=2 to length(j); _=substr(j,k,1) /*pick off a single digit. */ - if _ <= f then iterate j /*if next digit ≤ then skip*/ - if _ \== f+1 then NCS=1 /*it's OK as of now. */ - f=_ /*we now got a new next dig*/ + do j=13 to left($,1) || tail /*step through the list. */ + if verify(j,$)\==0 then iterate /*Not one of the chosen? */ + f=left(j,1) /*use the 1st decimal digit of J.*/ + NCS=0 /*not non-continuous subsequence.*/ + do k=2 to length(j); _=substr(j,k,1) /*pick off a single decimal digit*/ + if _ <= f then iterate j /*if next digit ≤, then skip it.*/ + if _ \== f+1 then NCS=1 /*it's OK as of now. */ + f=_ /*now have a new next decimal dig*/ end /*k*/ - if \NCS then iterate /*¬OK? Then skip this num.*/ - #=#+1 /*Eureka! We found one. */ - x= /*the beginning of the NCS.*/ - do m=1 for length(j) /*build a thingy to display*/ - x=x word(list,substr(j,m,1)) /*pick off a number to show*/ + if \NCS then iterate /*not OK? Then skip this number.*/ + #=#+1 /*Eureka! We found onea digit.*/ + x= /*the beginning of the NCS. */ + do m=1 for length(j) /*build a sequence string to show*/ + x=x word(list,substr(j,m,1)) /*pick off a number to display. */ end /*m*/ - say 'a non-continuous subsequence: ' x /*show a non-cont. subseq. */ - end /*j*/ + say 'a non-continuous subsequence: ' x /*show non─continous subsequence.*/ + end /*j*/ -if #==0 then #='no' /*make it more gooder Eng. */ +if #==0 then #='no' /*make it more gooder Anglesh. */ say; say # "non-continuous subsequence"s(#) 'were found.' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────S subroutine───────────────────────*/ -s: if arg(1)==1 then return ''; return word(arg(2) 's',1) /*plurals.*/ +exit /*stick a fork in it, we're done.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +s: if arg(1)==1 then return ''; return word(arg(2) 's',1) /*plurals.*/ diff --git a/Task/Non-decimal-radices-Convert/ALGOL-W/non-decimal-radices-convert.alg b/Task/Non-decimal-radices-Convert/ALGOL-W/non-decimal-radices-convert.alg new file mode 100644 index 0000000000..3f19a03562 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/ALGOL-W/non-decimal-radices-convert.alg @@ -0,0 +1,66 @@ +begin + % returns with numberInBase set to the number n converted to a string in % + % the specified base. Number must be non-negative and base must be in % + % range 2 to 36 % + procedure convertToBase( integer value n + ; integer value base + ; string(32) result numberInBase + ) ; + begin + string(36) baseDigits; + integer val, strPos; + + assert( n >= 0 and base >= 2 and base <= 36 ); + + baseDigits := "0123456789abcdefghijklmnopqrstuvwxyz"; + numberInBase := " "; + val := n; + strPos := 31; + while + begin + % a(b//c) is the substring of a starting at b with length c. % + % The first character is at position 0. The length must be % + % an integer literal so it is known at compile time. % + numberInBase( strPos // 1 ) := baseDigits( val rem base // 1 ); + val := val div base; + strPos := strPos - 1; + val > 0 + end + do begin end + end convertToBase ; + + % returns the string numberInBase converted to an integer assuming % + % numberInBase ia a string in the specified base % + % base must be in range 2 to 36, invalid digits will cause the program % + % to crash, spaces are ignored % + integer procedure convertFromBase( string(32) value numberInBase + ; integer value base + ) ; + begin + string(36) baseDigits; + integer val, cPos; + + assert( base >= 2 and base <= 36 ); + + baseDigits := "0123456789abcdefghijklmnopqrstuvwxyz"; + val := 0; + for strPos := 0 until 31 do begin + string(1) c; + c := numberInBase( strPos // 1 ); + if c not = " " then begin + cPos := 0; + while baseDigits( cPos // 1 ) not = c do cPos := cPos + 1; + val := ( val * base ) + cPos; + end + end; + val + end convertFromBase ; + + % test the procedures % + string(32) baseNumber; + i_w := 3; % set integer output width % + for i := 2 until 36 do begin + convertToBase( 35, i, baseNumber ); + write( 35, i, baseNumber, " ", convertFromBase( baseNumber, i ) ); + end +end. diff --git a/Task/Non-decimal-radices-Convert/Common-Lisp/non-decimal-radices-convert.lisp b/Task/Non-decimal-radices-Convert/Common-Lisp/non-decimal-radices-convert-1.lisp similarity index 100% rename from Task/Non-decimal-radices-Convert/Common-Lisp/non-decimal-radices-convert.lisp rename to Task/Non-decimal-radices-Convert/Common-Lisp/non-decimal-radices-convert-1.lisp diff --git a/Task/Non-decimal-radices-Convert/Common-Lisp/non-decimal-radices-convert-2.lisp b/Task/Non-decimal-radices-Convert/Common-Lisp/non-decimal-radices-convert-2.lisp new file mode 100644 index 0000000000..b386c8fc7d --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Common-Lisp/non-decimal-radices-convert-2.lisp @@ -0,0 +1,5 @@ +(defun decimal-to-base-n (number &key (base 16)) + (format nil (format nil "~~~dr" base) number)) + +(defun base-n-to-decimal (number &key (base 16)) + (read-from-string (format nil "#~dr~d" base number))) diff --git a/Task/Non-decimal-radices-Convert/Elixir/non-decimal-radices-convert.elixir b/Task/Non-decimal-radices-Convert/Elixir/non-decimal-radices-convert.elixir new file mode 100644 index 0000000000..17187e63d0 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Elixir/non-decimal-radices-convert.elixir @@ -0,0 +1,6 @@ +iex(1)> String.to_integer("ffff", 16) +65535 +iex(2)> Integer.to_string(255, 2) +"11111111" +iex(3)> String.to_integer("NonDecimalRadices", 36) +188498506820338115928429652 diff --git a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx new file mode 100644 index 0000000000..bc81c530d7 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx @@ -0,0 +1,37 @@ +/*REXX pgm converts integers from one base to another (base 2 ──► 90). */ +@abc = 'abcdefghijklmnopqrstuvwxyz' /*the lowercase (Latin) alphabet.*/ +parse upper var @abc @abcU /*uppercase a version of @abc. */ +@@ = 0123456789 || @abc || @abcU /*prefix 'em with numeric digits.*/ +@@ = @@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/ + /* [↑] all chars must be viewable*/ +numeric digits 3000 /*what da hey, support gihugeics.*/ +maxB=length(@@) /*max base (radix) supported here*/ +parse arg x toB inB 1 ox . 1 sigX 2 x2 . /*get: 3 args, origX, sign···*/ +if pos(sigX,"+-")\==0 then x=x2 /*Does X have a leading sign? */ + else sigX= /*Nope. No leading sign for X. */ +if x=='' then call erm /*if no X number, issue error.*/ +if toB=='' | toB=="," then toB=10 /*if skipped, assume default (10)*/ +if inB=='' | inB=="," then inB=10 /* " " " " " */ +if inB<2 | inb>maxB | \datatype(inB,'W') then call erb 'inBase ' inB +if toB<2 | toB>maxB | \datatype(toB,'W') then call erb 'toBase ' toB +#=0 /*result of converted X (base 10)*/ + do j=1 for length(x) /*convert X, base inB ──► base 10*/ + ?=substr(x,j,1) /*pick off a numeral/digit from X*/ + _=pos(?, @@) /*calculate this numeral's value.*/ + if _==0 | _>inB then call erd x /*_ character an illegal numeral?*/ + #=#*inB+_-1 /*build a new number, dig by dig.*/ + end /*j*/ /* [↑] this also verifies digits*/ +y= /*the value of X in base B. */ + do while # >= toB /*convert #, base 10 ──► base toB*/ + y=substr(@@, (#//toB)+1, 1)y /*construct the output number. */ + #=#%toB /*··· and whittle # down also. */ + end /*while*/ /* [↑] process leaves a residual*/ + /* [↓] Y is the residual*/ +y=sigX || substr(@@, #+1, 1)y /*prepend the sign if it existed.*/ +say ox "(base" inB')' center('is',20) y "(base" toB')' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one─liner subroutines───────────────*/ +erb: call ser 'illegal' arg(1)", it must be in the range: 2──►"maxB +erd: call ser 'illegal digit/numeral ['?"] in: " x +erm: call ser 'no argument specified.' +ser: say; say '***error!***'; say arg(1); exit 13 diff --git a/Task/Non-decimal-radices-Input/00DESCRIPTION b/Task/Non-decimal-radices-Input/00DESCRIPTION index b9e2c554ce..ff3fea9c56 100644 --- a/Task/Non-decimal-radices-Input/00DESCRIPTION +++ b/Task/Non-decimal-radices-Input/00DESCRIPTION @@ -4,6 +4,6 @@ This task requires parsing of such a string (which may be assumed to contain not The solutions may assume that the base of the number in the string is known. In particular, if your language has a facility to guess the base of a number by looking at a prefix (e.g. "0x" for hexadecimal) or other distinguishing syntax as it parses it, please show that. -The reverse operation is in task [[Common number base formatting]] +The reverse operation is in task [[Non-decimal radices/Output]] -For general number base conversion, see [[Number base conversion]]. +For general number base conversion, see [[Non-decimal radices/Convert]]. diff --git a/Task/Non-decimal-radices-Input/Elixir/non-decimal-radices-input.elixir b/Task/Non-decimal-radices-Input/Elixir/non-decimal-radices-input.elixir new file mode 100644 index 0000000000..9fda6e44e2 --- /dev/null +++ b/Task/Non-decimal-radices-Input/Elixir/non-decimal-radices-input.elixir @@ -0,0 +1,10 @@ +iex(1)> String.to_integer("1000") +1000 +iex(2)> String.to_integer("1000",2) +8 +iex(3)> String.to_integer("1000",8) +512 +iex(4)> String.to_integer("1000",16) +4096 +iex(5)> String.to_integer("ffff",16) +65535 diff --git a/Task/Non-decimal-radices-Output/Elixir/non-decimal-radices-output.elixir b/Task/Non-decimal-radices-Output/Elixir/non-decimal-radices-output.elixir new file mode 100644 index 0000000000..70cc8d6773 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Elixir/non-decimal-radices-output.elixir @@ -0,0 +1 @@ +Enum.each(0..32, fn i -> :io.format "~2w :~6.2B, ~2.8B, ~2.16B~n", [i,i,i,i] end) diff --git a/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia b/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia new file mode 100644 index 0000000000..7ccea25bb9 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia @@ -0,0 +1,6 @@ +hi = 50 +println("Primes \u2264 ", hi, " written in common bases.") +println(" bin oct dec hex") +for i in primes(hi) + println(@sprintf("%8s %4s %2s %2s", bin(i), oct(i), dec(i), hex(i))) +end diff --git a/Task/Nth-root/Bracmat/nth-root.bracmat b/Task/Nth-root/Bracmat/nth-root.bracmat new file mode 100644 index 0000000000..441044285c --- /dev/null +++ b/Task/Nth-root/Bracmat/nth-root.bracmat @@ -0,0 +1,29 @@ +( ( root + = n a d x0 x1 d2 rnd 10-d + . ( rnd { For 'rounding' rational numbers = keep number of digits within bounds. } + = N r + . !arg:(?N.?r) + & div$(!N*!r+1/2.1)*!r^-1 + ) + & !arg:(?n,?a,?d) + & !a*!n^-1:?x0 + & 10^(-1*!d):?10-d + & whl + ' ( ( rnd$(((!n+-1)*!x0+!a*!x0^(1+-1*!n))*!n^-1.10^!d) + . !x0 + ) + : (?x0.?x1) + & (!x0+-1*!x1)^2:~ ((n - 1) * prev + x / :math.pow(prev, (n-1))) / n end + fixed_point(f, x, precision, f.(x)) + end + + defp fixed_point(_, guess, tolerance, next) when abs(guess - next) < tolerance, do: next + defp fixed_point(f, _, tolerance, next), do: fixed_point(f, next, tolerance, f.(next)) +end + +Enum.each([{2, 2}, {4, 81}, {10, 1024}, {1/2, 7}], fn {n, x} -> + IO.puts "#{n} root of #{x} is #{RC.nth_root(n, x)}" +end) diff --git a/Task/Nth-root/Excel/nth-root.excel b/Task/Nth-root/Excel/nth-root.excel new file mode 100644 index 0000000000..d7ed309405 --- /dev/null +++ b/Task/Nth-root/Excel/nth-root.excel @@ -0,0 +1 @@ +=A1^(1/B1) diff --git a/Task/Nth-root/PowerShell/nth-root.psh b/Task/Nth-root/PowerShell/nth-root.psh new file mode 100644 index 0000000000..ba02865fed --- /dev/null +++ b/Task/Nth-root/PowerShell/nth-root.psh @@ -0,0 +1,39 @@ +#NoTeS: This sample code does not validate inputs +# Thus, if there are errors the 'scary' red-text +# error messages will appear. +# +# This code will not work properly in floating point values of n, +# and negative values of A. +# +# Supports negative values of n by reciprocating the root. + +$epsilon=1E-10 #Sample Epsilon (Precision) + +function power($x,$e){ #As I said in the comment + $ret=1 + for($i=1;$i -le $e;$i++){ + $ret*=$x + } + return $ret +} +function root($y,$n){ #The main Function + if (0+$n -lt 0){$tmp=-$n} else {$tmp=$n} #This checks if n is negative. + $ans=1 + + do{ + $d = ($y/(power $ans ($tmp-1)) - $ans)/$tmp + $ans+=$d + } while ($d -lt -$epsilon -or $d -gt $epsilon) + + if (0+$n -lt 0){return 1/$ans} else {return $ans} +} + +#Sample Inputs +root 625 2 +root 2401 4 +root 2 -2 +root 1.23456789E-20 34 +root 9.87654321E20 10 #Quite slow here, I admit... + +((root 5 2)+1)/2 #Extra: Computes the golden ratio +((root 5 2)-1)/2 diff --git a/Task/Nth/Batch-File/nth.bat b/Task/Nth/Batch-File/nth.bat new file mode 100644 index 0000000000..0d4ebc5423 --- /dev/null +++ b/Task/Nth/Batch-File/nth.bat @@ -0,0 +1,21 @@ +@echo off +::Main thing... +call :Nth 0 25 +call :Nth 250 265 +call :Nth 1000 1025 +pause +exit /b + +::The subroutine +:Nth +setlocal enabledelayedexpansion +for /l %%n in (%~1,1,%~2) do ( + set curr_num=%%n + set "out=%%nth" + if !curr_num:~-1!==1 (set "out=%%nst") + if !curr_num:~-1!==2 (set "out=%%nnd") + if !curr_num:~-1!==3 (set "out=%%nrd") + set "range_output=!range_output! !out!" +) +echo."!range_output:~1!" +goto :EOF diff --git a/Task/Nth/Befunge/nth.bf b/Task/Nth/Befunge/nth.bf new file mode 100644 index 0000000000..734e1d0818 --- /dev/null +++ b/Task/Nth/Befunge/nth.bf @@ -0,0 +1,12 @@ +0>55*:>1-\:0\`!v +#v$#$<^:\+*8"}"_ + >35*:>1-\:0\`!v +#v$#$<^:\+*2"}"_ +5< v$_v#!::-<0*5 +@v <,*>#81#4^# _ + +>>:0\>:55+%68*v: +tsnr |:/+ 55\+<, +htdd >$>:#,_$:vg +v"d"\*!`3:%+55<9 +>%55+/1-!!*:8g,^ diff --git a/Task/Nth/C++/nth.cpp b/Task/Nth/C++/nth.cpp new file mode 100644 index 0000000000..24b4b2b5c8 --- /dev/null +++ b/Task/Nth/C++/nth.cpp @@ -0,0 +1,41 @@ +#include +#include + +using namespace std; + +string Suffix(int num) +{ + switch (num % 10) + { + case 1 : if(num % 100 != 11) return "st"; + break; + case 2 : if(num % 100 != 12) return "nd"; + break; + case 3 : if(num % 100 != 13) return "rd"; + } + + return "th"; +} + +int main() +{ + cout << "Set [0,25]:" << endl; + for (int i = 0; i < 26; i++) + cout << i << Suffix(i) << " "; + + cout << endl; + + cout << "Set [250,265]:" << endl; + for (int i = 250; i < 266; i++) + cout << i << Suffix(i) << " "; + + cout << endl; + + cout << "Set [1000,1025]:" << endl; + for (int i = 1000; i < 1026; i++) + cout << i << Suffix(i) << " "; + + cout << endl; + + return 0; +} diff --git a/Task/Nth/Elixir/nth.elixir b/Task/Nth/Elixir/nth.elixir new file mode 100644 index 0000000000..8270171d1d --- /dev/null +++ b/Task/Nth/Elixir/nth.elixir @@ -0,0 +1,20 @@ +defmodule RC do + def ordinalize(n) do + num = abs(n) + ordinal = if rem(num, 100) in 4..20 do + "th" + else + case rem(num, 10) do + 1 -> "st" + 2 -> "nd" + 3 -> "rd" + _ -> "th" + end + end + "#{n}#{ordinal}" + end +end + +Enum.each([0..25, 250..265, 1000..1025], fn range -> + Enum.map(range, fn n -> RC.ordinalize(n) end) |> Enum.join(" ") |> IO.puts +end) diff --git a/Task/Nth/J/nth-1.j b/Task/Nth/J/nth-1.j index 5105f8989a..c9270e1e63 100644 --- a/Task/Nth/J/nth-1.j +++ b/Task/Nth/J/nth-1.j @@ -1,3 +1,2 @@ -suf=: (;:'th st nd rd th'){::~4<.10 10(* 1&~:)~/@#:] - -nth=: [:;:inv (":,suf)each +suf=: (;:'th st nd rd th') {::~ 4 <. 10 10 (* 1&~:)~/@#: ] +nth=: [: ;:inv (": , suf)each diff --git a/Task/Nth/JavaScript/nth-1.js b/Task/Nth/JavaScript/nth-1.js new file mode 100644 index 0000000000..453cc48a15 --- /dev/null +++ b/Task/Nth/JavaScript/nth-1.js @@ -0,0 +1,24 @@ +console.log(function () { + + var lstSuffix = 'th st nd rd th th th th th th'.split(' '), + + fnOrdinalForm = function (n) { + return n.toString() + ( + 11 <= n % 100 && 13 >= n % 100 ? + "th" : lstSuffix[n % 10] + ); + }, + + range = function (m, n) { + return Array.apply( + null, Array(n - m + 1) + ).map(function (x, i) { + return m + i; + }); + }; + + return [[0, 25], [250, 265], [1000, 1025]].map(function (tpl) { + return range.apply(null, tpl).map(fnOrdinalForm).join(' '); + }).join('\n\n'); + +}()); diff --git a/Task/Nth/JavaScript/nth-2.js b/Task/Nth/JavaScript/nth-2.js new file mode 100644 index 0000000000..17f05c7fb3 --- /dev/null +++ b/Task/Nth/JavaScript/nth-2.js @@ -0,0 +1,5 @@ +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 + +250th 251st 252nd 253rd 254th 255th 256th 257th 258th 259th 260th 261st 262nd 263rd 264th 265th + +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/Julia/nth-1.julia b/Task/Nth/Julia/nth-1.julia new file mode 100644 index 0000000000..52fea395b5 --- /dev/null +++ b/Task/Nth/Julia/nth-1.julia @@ -0,0 +1,12 @@ +function sprintfordinal{T<:Integer}(n::T) + const sfixes = ["st", "nd", "rd"] + 0 <= n || throw(ArgumentError("number to be formatted must be ≥ 0, got $n")) + u = n%10 + t = div(n, 10)%10 + if 3 < u || u == 0 || t == 1 + sf = "th" + else + sf = sfixes[u] + end + @sprintf "%d%s" n sf +end diff --git a/Task/Nth/Julia/nth-2.julia b/Task/Nth/Julia/nth-2.julia new file mode 100644 index 0000000000..e8de2a3961 --- /dev/null +++ b/Task/Nth/Julia/nth-2.julia @@ -0,0 +1,24 @@ +println("Tests of ordinal formatting of integers.") +for (i, n) in enumerate(0:25) + if (i-1)%10 == 0 + print("\n ") + end + print(@sprintf("%7s", sprintfordinal(n))) +end +println() + +for (i, n) in enumerate(250:265) + if (i-1)%10 == 0 + print("\n ") + end + print(@sprintf("%7s", sprintfordinal(n))) +end +println() + +for (i, n) in enumerate(1000:1025) + if (i-1)%10 == 0 + print("\n ") + end + print(@sprintf("%7s", sprintfordinal(n))) +end +println() diff --git a/Task/Nth/PowerShell/nth.psh b/Task/Nth/PowerShell/nth.psh new file mode 100644 index 0000000000..ae4c6e03a1 --- /dev/null +++ b/Task/Nth/PowerShell/nth.psh @@ -0,0 +1,14 @@ +function nth($inp){ + $suffix = "th" + + switch($inp % 10){ + 1{$suffix="st"} + 2{$suffix="nd"} + 3{$suffix="rd"} + } + return "$inp$suffix " +} + +0..25 | %{Write-host -nonewline (nth "$_")};"" +250..265 | %{Write-host -nonewline (nth "$_")};"" +1000..1025 | %{Write-host -nonewline (nth "$_")};"" diff --git a/Task/Nth/Python/nth.py b/Task/Nth/Python/nth-1.py similarity index 100% rename from Task/Nth/Python/nth.py rename to Task/Nth/Python/nth-1.py diff --git a/Task/Nth/Python/nth-2.py b/Task/Nth/Python/nth-2.py new file mode 100644 index 0000000000..15b7642466 --- /dev/null +++ b/Task/Nth/Python/nth-2.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 + +def ord(n): + try: + s = ['st', 'nd', 'rd'][(n-1)%10] + if (n-10)%100//10: + return str(n)+s + except IndexError: + pass + return str(n)+'th' + +if __name__ == '__main__': + print(*(ord(n) for n in range(26))) + print(*(ord(n) for n in range(250,266))) + print(*(ord(n) for n in range(1000,1026))) diff --git a/Task/Nth/Rust/nth.rust b/Task/Nth/Rust/nth.rust index 68905617d0..f6245eca0f 100644 --- a/Task/Nth/Rust/nth.rust +++ b/Task/Nth/Rust/nth.rust @@ -1,4 +1,4 @@ -fn nth(num: int) -> String { +fn nth(num: i32) -> String { format!("{}{}", num, match (num % 10, num % 100) { (1, 11) => "th", (1, _) => "st", @@ -12,13 +12,13 @@ fn nth(num: int) -> String { fn main() { let ranges = vec![ - (0i, 26i), - (250i, 266i), - (1000i, 1026i) + (0, 26), + (250, 266), + (1000, 1026) ]; for &(s, e) in ranges.iter() { println!("[{}, {}) :", s, e); - for i in range(s, e) { + for i in s..e { print!("{}, ", nth(i)); } println!(""); diff --git a/Task/Null-object/ALGOL-W/null-object.alg b/Task/Null-object/ALGOL-W/null-object.alg new file mode 100644 index 0000000000..c4a517d708 --- /dev/null +++ b/Task/Null-object/ALGOL-W/null-object.alg @@ -0,0 +1,10 @@ +begin + % declare a record type - will be accessed via references % + record R( integer f1, f2, f3 ); + % declare a reference to a R instance % + reference(R) refR; + % assign null to the reference % + refR := null; + % test for a null reference - will write "refR is null" % + if refR = null then write( "refR is null" ) else write( "not null" ); +end. diff --git a/Task/Null-object/Elixir/null-object-1.elixir b/Task/Null-object/Elixir/null-object-1.elixir new file mode 100644 index 0000000000..ad08a42819 --- /dev/null +++ b/Task/Null-object/Elixir/null-object-1.elixir @@ -0,0 +1,4 @@ +iex(1)> nil == :nil +true +iex(2)> is_nil(nil) +true diff --git a/Task/Null-object/Elixir/null-object-2.elixir b/Task/Null-object/Elixir/null-object-2.elixir new file mode 100644 index 0000000000..60c61df943 --- /dev/null +++ b/Task/Null-object/Elixir/null-object-2.elixir @@ -0,0 +1,2 @@ +iex(3)> if nil, do: "not execute" +nil diff --git a/Task/Null-object/Ruby/null-object.rb b/Task/Null-object/Ruby/null-object.rb index f9e33b886d..92fa2f6664 100644 --- a/Task/Null-object/Ruby/null-object.rb +++ b/Task/Null-object/Ruby/null-object.rb @@ -5,3 +5,6 @@ # It recognizes as the local variable even if it isn't executed. object = 1 if false puts "object is nil" if object.nil? + +# nil itself is an object: +puts nil.class # => NilClass diff --git a/Task/Null-object/Rust/null-object.rust b/Task/Null-object/Rust/null-object.rust new file mode 100644 index 0000000000..3a930251b5 --- /dev/null +++ b/Task/Null-object/Rust/null-object.rust @@ -0,0 +1,20 @@ +// If an option may return null - or nothing - in Rust, it's wrapped +// in an Optional which may return either the type of object specified +// in <> or None. We can check this using .is_some() and .is_none() on +// the Option. + +fn check_number(num: &Option) { + if num.is_none() { + println!("Number is: None"); + } else { + println!("Number is: {}", num.unwrap()); + } +} + +fn main() { + let mut possible_number: Option = None; + check_number(&possible_number); + + possible_number = Some(31); + check_number(&possible_number); +} diff --git a/Task/Number-names/Batch-File/number-names.bat b/Task/Number-names/Batch-File/number-names.bat new file mode 100644 index 0000000000..8e20d651cd --- /dev/null +++ b/Task/Number-names/Batch-File/number-names.bat @@ -0,0 +1,76 @@ +::Number Names Task from Rosetta Code Wiki +::Batch File Implementation + +@echo off +setlocal enabledelayedexpansion + +if "%~1"=="iterate" goto num_name + +::Define the words +set "small=One Two Three Four Five Six Seven Eight Nine Ten" +set "small=%small% Eleven Twelve Thirteen Fourteen Fifteen Sixteen Seventeen Eighteen Nineteen" +set "decade=Twenty Thirty Forty Fifty Sixty Seventy Eighty Ninety" +set "big=Thousand Million Billion" + +::Seperating each word... +set cnt=0 +for %%X in (%small%) do (set /a "cnt+=1"&set small!cnt!=%%X) +set cnt=0 +for %%Y in (%decade%) do (set decade!cnt!=%%Y&set /a "cnt+=1") +set cnt=0 +for %%Z in (%big%) do (set big!cnt!=%%Z&set /a "cnt+=1") + +::The Main Thing +for %%. in (42,27,1090,230000,1001100,-40309,0,123456789) do ( + set input=%%. + if %%. lss 0 (set /a input*=-1) + if !input! equ 0 (set TotalOut=Zero) else ( + call :num_word %%. + ) + echo "!TotalOut!" +) +exit /b +::/The Main Thing + +::The Procedure +:num_word + set outP= + set unit=0 + set num=!input! +:num_loop +set /a tmpLng1 = num %% 100 +set /a tmpLng2 = tmpLng1 %% 10 +set /a tmpNum1 = tmpLng1/10 - 2 + +if !tmpLng1! geq 1 if !tmpLng1! leq 19 ( + set "outP=!small%tmpLng1%! !outP!" +) +if !tmpLng1! geq 20 if !tmpLng1! leq 99 ( + if !tmpLng2! equ 0 ( + set "outP=!decade%tmpNum1%! !outP!" + ) else ( + set "outP=!decade%tmpNum1%!-!small%tmpLng2%! !outP!" + ) +) + +set /a tmpLng1 = (num %% 1000)/100 +if not !tmpLng1! equ 0 ( + set "outP=!small%tmpLng1%! Hundred !outP!" +) + +set /a num/=1000 +if !num! lss 1 goto :break_loop + +set /a tmpLng1 = num %% 1000 +if not !tmpLng1! equ 0 ( + set "outP=!big%unit%! !outP!" +) +set /a unit+=1 +goto :num_loop + +:break_loop +set "TotalOut=!outP!" +if %1 lss 0 set "TotalOut=Negative !outP!" + +set TotalOut=%TotalOut:~0,-1% +goto :EOF diff --git a/Task/Number-names/Erlang/number-names.erl b/Task/Number-names/Erlang/number-names.erl new file mode 100644 index 0000000000..817f7a7afe --- /dev/null +++ b/Task/Number-names/Erlang/number-names.erl @@ -0,0 +1,77 @@ +-module(nr2eng). +-import(lists, [foreach/2, seq/2, append/2]). +-import(string, [strip/3, str/2]). +-export([start/0]). + +sym(1) -> "one"; +sym(2) -> "two"; +sym(3) -> "three"; +sym(4) -> "four"; +sym(5) -> "five"; +sym(6) -> "six"; +sym(7) -> "seven"; +sym(8) -> "eight"; +sym(9) -> "nine"; +sym(10) -> "ten"; +sym(11) -> "eleven"; +sym(12) -> "twelve"; +sym(13) -> "thirteen"; +sym(20) -> "twenty"; +sym(30) -> "thirty"; +sym(40) -> "forty"; +sym(50) -> "fifty"; +sym(100) -> "hundred"; +sym(1000) -> "thousand"; +sym(1000*1000) -> "million"; +sym(1000*1000*1000) -> "billion"; +sym(_) -> "". + +next(1000) -> 100; +next(100) -> 10; +next(10) -> 1; +next(X) -> X div 1000. + +concat(PRE, "") -> + PRE; +concat(PRE, POST) -> + PRE++" "++POST. +concat("", _, POST) -> + POST; +concat(PRE, SYM, "") -> + PRE++" "++SYM; +concat(PRE, SYM, POST) -> + PRE++" "++SYM++" "++POST. + +nr2eng(0, _) -> + ""; +nr2eng(NR, 1) -> + sym(NR); +nr2eng(NR, 10) when NR =< 20 -> + case sym(NR) of + "" -> strip(sym(NR-10), right, $t) ++ "teen"; + _ -> sym(NR) + end; +nr2eng(NR, 10) -> + concat( + case sym((NR div 10)*10) of + "" -> strip(sym(NR div 10), right, $t) ++ "ty"; + _ -> sym((NR div 10)*10) + end, + nr2eng(NR rem 10, 1)); +nr2eng(NR, B) -> + PRE = nr2eng(NR div B, next(B)), + POST = nr2eng(NR rem B, next(B)), + AND = str(POST, "and"), + COMMA = if + POST == "" -> ""; + AND == 0 -> " and"; + B >= 1000 -> ","; + true -> "" + end, + concat(PRE, sym(B)++COMMA, POST). + +start() -> + lists:foreach( + fun (X) -> io:fwrite("~p ~p ~n", [X, nr2eng(X, 1000000000)]) + end, + append(seq(1, 2000), [123123, 43234234])). diff --git a/Task/Number-names/Julia/number-names-1.julia b/Task/Number-names/Julia/number-names-1.julia new file mode 100644 index 0000000000..6c9ed17b68 --- /dev/null +++ b/Task/Number-names/Julia/number-names-1.julia @@ -0,0 +1,78 @@ +const stext = ["one", "two", "three", "four", "five", + "six", "seven", "eight", "nine"] +const teentext = ["eleven", "twelve", "thirteen", "fourteen", + "fifteen", "sixteen", "seventeen", + "eighteen", "nineteen"] +const tenstext = ["ten", "twenty", "thirty", "forty", "fifty", + "sixty", "seventy", "eighty", "ninety"] +const ordstext = ["million", "billion", "trillion", + "quadrillion", "quintillion", "sextillion", + "septillion", "octillion", "nonillion", + "decillion", "undecillion", "duodecillion", + "tredecillion", "quattuordecillion", "quindecillion", + "sexdecillion", "septendecillion", "octodecillion", + "novemdecillion", "vigintillion"] + +function normalize_digits!{T<:Integer}(a::Array{T,1}) + while 0 < length(a) && a[end] == 0 + pop!(a) + end + return length(a) +end + +function digits2text!{T<:Integer}(d::Array{T,1}, use_short_scale=true) + ndig = normalize_digits!(d) + 0 < ndig || return "" + if ndig < 7 + s = "" + if 3 < ndig + t = digits2text!(d[1:3]) + s = digits2text!(d[4:end])*" thousand" + 0 < length(t) || return s + if contains(t, "and") + return s*" "*t + else + return s*" and "*t + end + end + if ndig == 3 + s *= stext[pop!(d)]*" hundred" + ndig = normalize_digits!(d) + 0 < ndig || return s + s *= " and " + end + 1 < ndig || return s*stext[pop!(d)] + j, i = d + j != 0 || return s*tenstext[i] + i != 1 || return s*teentext[j] + return s*tenstext[i]*"-"*stext[j] + end + s = digits2text!(d[1:6]) + d = d[7:end] + dgrp = use_short_scale ? 3 : 6 + ord = 0 + while(dgrp < length(d)) + ord += 1 + t = digits2text!(d[1:dgrp]) + d = d[(dgrp+1):end] + 0 < length(t) || continue + t = t*" "*ordstext[ord] + if length(s) == 0 + s = t + else + s = t*" "*s + end + end + ord += 1 + t = digits2text!(d)*" "*ordstext[ord] + 0 < length(s) || return t + return t*" "*s +end + +function num2text{T<:Integer}(n::T, use_short_scale=true) + -1 < n || return "minus "*num2text(-n, use_short_scale) + 0 < n || return "zero" + toobig = use_short_scale ? big(10)^66 : big(10)^126 + n < toobig || return "too big to say" + return digits2text!(digits(n, 10), use_short_scale) +end diff --git a/Task/Number-names/Julia/number-names-2.julia b/Task/Number-names/Julia/number-names-2.julia new file mode 100644 index 0000000000..1100d01725 --- /dev/null +++ b/Task/Number-names/Julia/number-names-2.julia @@ -0,0 +1,53 @@ +function wrap{T<:String,U<:Integer}(str::T, width::U=70, indent::U=4) + sdent = " "^(indent-1) + s = sdent + llen = indent + for t in split(str, " ") + s *= " "*t + llen += length(t) + 1 + width < llen || continue + s *= "\n"*sdent + llen = indent + end + return rstrip(s) +end + +println("Testing num2text") +println() +println("Some easy ones to start with") +println() +tests = [-1:21, 100, 101, 10000, 10001, 1000000, 1010101] +for i in tests + println(@sprintf("%8d is %s", i, num2text(i))) +end + +println() +println("Some larger numbers") +println() +println("The largest signed literal integer (short-scale)") +i = typemax(1) +println(" ", i, " is") +println(wrap(num2text(i))) +println() +println("The largest signed literal integer (long-scale)") +println(" ", i, " is") +println(wrap(num2text(i, false))) +println() +println("The largest unsigned integer (short-scale)") +i = typemax(Uint128) +println(" ", i, " is") +println(wrap(num2text(i))) +println() +println("50! (short-scale)") +i = factorial(big(50)) +println(" ", i, " is") +println(wrap(num2text(i))) +println() +println("51! (short-scale)") +i = factorial(big(51)) +println(" ", i, " is") +println(wrap(num2text(i))) +println() +println("51! (long-scale)") +println(" ", i, " is") +println(wrap(num2text(i, false))) diff --git a/Task/Number-names/Perl-6/number-names.pl6 b/Task/Number-names/Perl-6/number-names.pl6 index 4d910380df..fab77c6ca8 100644 --- a/Task/Number-names/Perl-6/number-names.pl6 +++ b/Task/Number-names/Perl-6/number-names.pl6 @@ -13,7 +13,7 @@ sub int-name ($num) { if $num eq '0' { return @I[0] } my $m = 0; return join ', ', reverse gather for $num.flip.comb(/\d ** 1..3/) { - my ($i,$x,$c) = .comb; + my ($i,$x,$c) = .comb».Int; if $i or $x or $c { take join ' ', gather { if $c { take @C[$c] } diff --git a/Task/Number-names/Scala/number-names.scala b/Task/Number-names/Scala/number-names-1.scala similarity index 100% rename from Task/Number-names/Scala/number-names.scala rename to Task/Number-names/Scala/number-names-1.scala diff --git a/Task/Number-names/Scala/number-names-2.scala b/Task/Number-names/Scala/number-names-2.scala new file mode 100644 index 0000000000..ac9f826496 --- /dev/null +++ b/Task/Number-names/Scala/number-names-2.scala @@ -0,0 +1,26 @@ +import scala.collection.immutable.TreeMap + +val NUMBERS = TreeMap( + 1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four", 5 -> "five", 6 -> "six", 7 -> "seven", 8 -> "eight", 9 -> "nine", + 10 -> "ten", 11 -> "eleven", 12 -> "twelve", 13 -> "thirteen", 14 -> "fourteen", 15 -> "fifteen", 16 -> "sixteen", + 17 -> "seventeen", 18 -> "eighteen", 19 -> "nineteen", 20 -> "twenty", 30 -> "thirty", 40 -> "forty", + 50 -> "fifty", 60 -> "sixty", 70 -> "seventy", 80 -> "eighty", 90 -> "ninety" +) + +val HUNDREDS = TreeMap( + 100l -> "hundred", 1000l -> "thousand", 1000000l -> "million", 1000000000l -> "billion", 1000000000000l -> "trillion" +) + +def numberToString(number: Long) : String = { + if (HUNDREDS.to(number).nonEmpty) { + val (h, hundreds) = HUNDREDS.to(number).last + val remainder = number % h + numberToString(number / h) + hundreds + {if (remainder > 0) {if (remainder < 100) " and " else ", "} + numberToString(remainder) else " "} + } else if (NUMBERS.to(number.toInt).nonEmpty) { + val (n, word) = NUMBERS.to(number.toInt).last + val remainder = number - n + word + {if (remainder > 0 && remainder < 10) "-" else " "} + numberToString(remainder) + } else { + "" + } +} diff --git a/Task/Number-reversal-game/Batch-File/number-reversal-game.bat b/Task/Number-reversal-game/Batch-File/number-reversal-game.bat new file mode 100644 index 0000000000..4e2dcba542 --- /dev/null +++ b/Task/Number-reversal-game/Batch-File/number-reversal-game.bat @@ -0,0 +1,70 @@ +:: +::Number Reversal Game Task from Rosetta Code Wiki +::Batch File Implementation +:: +::Please do not open this from command prompt. +::Directly Open the Batch File to play... +:: + +@echo off +setlocal enabledelayedexpansion +title Number Reversal Game + +:begin +set score=0 + +::The ascending list of 9 digits +set list=123456789 + + +::Generating a random set of 9 digits... +set cyc=9 +:gen +set /a tmp1=%random%%%%cyc% +set n%cyc%=!list:~%tmp1%,1! +set tmp2=!n%cyc%! +set list=!list:%tmp2%=! +if not %cyc%==2 ( + set /a cyc-=1 + goto :gen +) +set /a n1=%list% + +::Display the Game +cls +echo. +echo ***Number Reversal Game*** +:loopgame +echo. +echo Current arrangement: %n1%%n2%%n3%%n4%%n5%%n6%%n7%%n8%%n9% +set /p move=How many digits from the left should I reverse? + +::Reverse digits according to the player's input +::NOTE: The next command uses the fact that in Batch File, +::The output for the division operation is only the integer part of the quotient. +set /a lim=(%move%+1)/2 + +set cyc2=1 +:reverse +set /a tmp4=%move%-%cyc2%+1 +set tmp5=!n%cyc2%! +set n%cyc2%=!n%tmp4%! +set n%tmp4%=%tmp5% +if not %cyc2%==%lim% ( + set /a cyc2+=1 + goto :reverse +) + +::Increment the number of moves took by the player +set /a score+=1 + +::IF already won... +if %n1%%n2%%n3%%n4%%n5%%n6%%n7%%n8%%n9%==123456789 ( + echo. + echo Set: %n1%%n2%%n3%%n4%%n5%%n6%%n7%%n8%%n9% DONE^^! + echo You took %score% moves to arrange the numbers in ascending order. + pause>nul + exit +) else ( +goto :loopgame +) diff --git a/Task/Number-reversal-game/Eiffel/number-reversal-game.e b/Task/Number-reversal-game/Eiffel/number-reversal-game.e new file mode 100644 index 0000000000..3af2c6da76 --- /dev/null +++ b/Task/Number-reversal-game/Eiffel/number-reversal-game.e @@ -0,0 +1,104 @@ +class + APPLICATION + +create + make + +feature {NONE} + + make + -- Plays Number Reversal Game. + local + count: INTEGER + do + initialize_game + io.put_string ("Let's play the number reversal game.%N") + across + numbers as ar + loop + io.put_string (ar.item.out + "%T") + end + from + until + is_sorted (numbers, 1, numbers.count) + loop + io.put_string ("%NHow many numbers should be reversed?%N") + io.read_integer + reverse_array (io.last_integer) + across + numbers as ar + loop + io.put_string (ar.item.out + "%T") + end + count := count + 1 + end + io.put_string ("%NYou needed " + count.out + " reversals.") + end + +feature {NONE} + + initialize_game + -- Array with numbers from 1 to 9 in a random unsorted order. + local + random: V_RANDOM + item, i: INTEGER + do + create random + create numbers.make_empty + from + i := 1 + until + numbers.count = 9 and not is_sorted (numbers, 1, numbers.count) + loop + item := random.bounded_item (1, 9) + if not numbers.has (item) then + numbers.force (item, i) + i := i + 1 + end + random.forth + end + end + + numbers: ARRAY [INTEGER] + + reverse_array (upper: INTEGER) + -- Array numbers with first element up to nth element reversed. + require + upper_positive: upper > 0 + ar_not_void: numbers /= Void + local + i, j: INTEGER + new_array: ARRAY [INTEGER] + do + create new_array.make_empty + new_array.deep_copy (numbers) + from + i := 1 + j := upper + until + i > j + loop + new_array [i] := numbers [j] + new_array [j] := numbers [i] + i := i + 1 + j := j - 1 + end + numbers := new_array + end + + is_sorted (ar: ARRAY [INTEGER]; l, r: INTEGER): BOOLEAN + -- Is Array 'ar' sorted in ascending order? + require + ar_not_empty: not ar.is_empty + do + Result := True + across + 1 |..| (r - 1) as c + loop + if ar [c.item] > ar [c.item + 1] then + Result := False + end + end + end + +end diff --git a/Task/Number-reversal-game/PHP/number-reversal-game.php b/Task/Number-reversal-game/PHP/number-reversal-game.php new file mode 100644 index 0000000000..fafe84a423 --- /dev/null +++ b/Task/Number-reversal-game/PHP/number-reversal-game.php @@ -0,0 +1,55 @@ +class ReversalGame { + private $numbers; + + public function __construct() { + $this->initialize(); + } + + public function play() { + $i = 0; + $moveCount = 0; + while (true) { + echo json_encode($this->numbers) . "\n"; + echo "Please enter an index to reverse from 2 to 9. Enter 99 to quit\n"; + $i = intval(rtrim(fgets(STDIN), "\n")); + if ($i == 99) { + break; + } + if ($i < 2 || $i > 9) { + echo "Invalid input\n"; + } else { + $moveCount++; + $this->reverse($i); + if ($this->isSorted()) { + echo "Congratulations you solved this in $moveCount moves!\n"; + break; + } + } + + } + } + + private function reverse($position) { + array_splice($this->numbers, 0, $position, array_reverse(array_slice($this->numbers, 0, $position))); + } + + private function isSorted() { + for ($i = 0; $i < count($this->numbers) - 1; ++$i) { + if ($this->numbers[$i] > $this->numbers[$i + 1]) { + return false; + } + } + return true; + } + + private function initialize() { + $this->numbers = range(1, 9); + while ($this->isSorted()) { + shuffle($this->numbers); + } + } + +} + +$game = new ReversalGame(); +$game->play(); diff --git a/Task/Number-reversal-game/REXX/number-reversal-game.rexx b/Task/Number-reversal-game/REXX/number-reversal-game.rexx index d215c6cc66..5d7e8f315b 100644 --- a/Task/Number-reversal-game/REXX/number-reversal-game.rexx +++ b/Task/Number-reversal-game/REXX/number-reversal-game.rexx @@ -1,22 +1,29 @@ -/*REXX program game: reverse a jumbled set of numerals until in order.*/ +/*REXX pgm (a game): reverse a jumbled set of numerals until they're in order.*/ +signal on halt /*allows the CBLF to HALT the program.*/ +___=copies('─',9) /*a fence used for computer's messages.*/ +say ___ "This game will show you nine random unique digits (1 ──► 9), and you'll" +say ___ "enter one of those digits which will reverse all the digits up to (and" +say ___ "including) that digit. The game's objective is to get all the" +say ___ "digits in ascending order with the fewest tries. Here are your digits:" +ok=123456789 /*the result that the string should be.*/ +$= + do until length($)==9 /*build a random unique numeric string.*/ + _=random(1,9); if pos(_,$)\==0 then iterate /*only use a dig once.*/ + $=$ || _ /*construct a string. */ + if $==ok then $= /*string can't be in order, start over.*/ + end /*until ··· */ -say "This game will show you nine random unique digits (1 ──► 9 inclusive), and" -say "you'll enter one of those digits which will reverse the digits up to (and" -say "including) that digit. The game's objective is to get all the digits in" -say "ascending order with the fewest tries. Here're your digits:"; say -$='' - do until length($)==9 /*generate random numeric string.*/ - _=random(1,9); if pos(_,$)\==0 then iterate /*no repeats.*/ - $=$ || _ - end /*until*/ - - do score=1 until $==123456789 /*keep truckin' until all ordered*/ - say $ left('',30) 'please enter a digit:' /*issue a prompt to user.*/ - parse pull ? 2 . /*get one digit from the gamer. */ - g=pos(?,$) /*full validation of input digit.*/ - if g==0 then say 'oops, invalid digit!' ? - else $=reverse(left($,g))substr($,g+1) + do score=1 until $==ok /* [↓] display the digs and the prompt*/ + say; say ___ $ right('please enter a digit (or Quit):', 50) + pull x .; ?=left(x,1) /*get a decimal digit (maybe) from CBLF*/ + if abbrev('QUIT',x,1) then signal halt + if length(x)>1 then do; say ___ 'oops, invalid input! ' x; iterate; end + if x=='' then iterate /*try again, CBLF didn't enter anything*/ + g=pos(?,$) /*validate if the input digit is legal.*/ + if g==0 then say ___ 'oops, invalid digit! ' ? + else $=reverse(left($, g))substr($, g+1) end /*score*/ -say center(' Congratulations! ',79,"═"); say 'Your score was' score - /*stick a fork in it, we're done.*/ +say; say ___ $; say; say center(' Congratulations! ',70,"═"); say +say ___ 'Your score was' score; exit /*stick a fork in it, we're all done. */ +halt: say ___ 'quitting.'; exit /* " " " " " " " " */ diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Perl-6/numerical-integration-gauss-legendre-quadrature.pl6 b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Perl-6/numerical-integration-gauss-legendre-quadrature.pl6 index afcbfc2353..47442c638d 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Perl-6/numerical-integration-gauss-legendre-quadrature.pl6 +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Perl-6/numerical-integration-gauss-legendre-quadrature.pl6 @@ -36,7 +36,7 @@ sub legendre-root(Int $n, Int $k) { sub weight(Int $n, $r) { 2 / ((1 - $r**2) * legendre-prime($n, $r)**2) } sub nodes(Int $n) { - gather { + flat gather { take 0 => weight($n, 0) if $n !%% 2; for 1 .. $n div 2 { my $r = legendre-root($n, $_); @@ -52,4 +52,4 @@ sub quadrature(Int $n, &f, $a, $b, :@nodes = nodes($n)) { } say "Gauss-Legendre $_.fmt('%2d')-point quadrature ∫₋₃⁺³ exp(x) dx ≈ ", - quadrature($_, &exp, -3, +3) for 5 .. 10, 20; + quadrature($_, &exp, -3, +3) for flat 5 .. 10, 20; diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx index 075df68956..104650614f 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx @@ -1,58 +1,49 @@ -/*REXX pgm does numerical integration using Gauss─Legendre Quadrature. */ -parse arg digs .; if digs=='' then digs=70 /*assume the DIGS default?*/ -numeric digits digs*2+5 /*use higher working DIGs.*/ -times=digs%2; b=3; a=-b; bma=b-a; bmaH=bma/2; tiny='1E-' || (digs*2) -trueV=exp(b)-exp(a); bpa=b+a; bpaH=bpa/2; oldZ= -numeric digits digs+15; pi=pi(); !.=. /*use lower working DIGITs*/ -say ' step ' center("iterative value",digs+5) ' difference' /*show hdr*/ -sep='──────' copies('─' ,digs+5) '─────────────'; say sep +/*REXX pgm does numerical integration using Gauss─Legendre Quadrature (GLQ).*/ +pi=pi(); digs=length(pi); numeric digits digs; reps=digs%2 +!.=.; b=3; a=-b; bma=b-a; bmaH=bma/2; tiny='1E-' || digs +trueV=exp(b)-exp(a); bpa=b+a; bpaH=bpa/2 +say ' step ' center("iterative value",digs+3) ' difference' /*show hdr*/ +sep='──────' copies('─' ,digs+3) '─────────────'; say sep - do step=1 for times; p0z=1; p0.1=1; step_=step + .5 - p1z=2; p1.1=1; p1.2=0; r.=0 -/*█*/ do k=2 to step; km=k-1 -/*█*/ do L=1 for p1z; T.L=p1.L -/*█*/ end /*L*/ -/*█*/ T.L=0; TT.=0 -/*█*/ do L=1 for p0z; L2=L+2; TT.L2=p0.L -/*█*/ end /*L*/ + do #=1 until dif>0; p0z=1; p0.1=1; p1z=2; p1.1=1; p1.2=0; ##=#+.5; r.=0 + if #\==1 then say center(#, 6) z' ' Ndif /*don't display if not computed.*/ + +/*█*/ do k=2 to #; km=k-1; do y=1 for p1z; T.y=p1.y; end /*y*/ +/*█*/ T.y=0; TT.=0; do L=1 for p0z; _=L+2; TT._=p0.L; end /*L*/ /*█*/ -/*█*/ kkm=k+km; do j=1 for p1z+1; T.j=(kkm*T.j-km*TT.j)/k ; end /*j*/ -/*█*/ p0z=p1z; do j=1 for p0z; p0.j=p1.j ; end /*j*/ -/*█*/ p1z=p1z+1; do j=1 for p1z; p1.j= T.j ; end /*j*/ +/*█*/ kkm=k+km; do j=1 for p1z+1; T.j=(kkm*T.j-km*TT.j)/k ; end /*j*/ +/*█*/ p0z=p1z; do n=1 for p0z; p0.n=p1.n ; end /*n*/ +/*█*/ p1z=p1z+1; do p=1 for p1z; p1.p= T.p ; end /*p*/ /*█*/ end /*k*/ - /*▓*/ do !=1 for step - /*▓*/ x=cos(pi*(!-.25)/step_) - /*▓*/ do times%2 until abs(dx).5 then ix=ix+sign(x) x=x-ix; z=1; _=1; do j=1 until p==z; p=z; _=_*x/j; z=z+_; end if z\==0 then z=z*e()**ix; return z diff --git a/Task/Numerical-integration/BASIC/numerical-integration.basic b/Task/Numerical-integration/BASIC/numerical-integration.basic index 0d4f493b97..53eff00ac3 100644 --- a/Task/Numerical-integration/BASIC/numerical-integration.basic +++ b/Task/Numerical-integration/BASIC/numerical-integration.basic @@ -19,8 +19,8 @@ END FUNCTION FUNCTION midRect(a, b, n) h = (b - a) / n sum = 0 - FOR x = a TO b - h STEP h - sum = sum + (h / 2) * (f(x) + f(x + h)) + FOR x = a + h / 2 TO b - h / 2 STEP h + sum = sum + h * (f(x)) NEXT x midRect = sum END FUNCTION @@ -40,7 +40,7 @@ FUNCTION simpson(a, b, n) sum2 = 0 FOR i = 0 TO n-1 - sum1 = sum + f(a + h * i + h / 2) + sum1 = sum1 + f(a + h * i + h / 2) NEXT i FOR i = 1 TO n - 1 diff --git a/Task/Numerical-integration/Elixir/numerical-integration.elixir b/Task/Numerical-integration/Elixir/numerical-integration.elixir new file mode 100644 index 0000000000..0ffa3837ba --- /dev/null +++ b/Task/Numerical-integration/Elixir/numerical-integration.elixir @@ -0,0 +1,36 @@ +defmodule Numerical do + @funs ~w(leftrect midrect rightrect trapezium simpson)a + + def leftrect(f, left,_right), do: f.(left) + def midrect(f, left, right), do: f.((left+right)/2) + def rightrect(f,_left, right), do: f.(right) + def trapezium(f, left, right), do: (f.(left)+f.(right))/2 + def simpson(f, left, right), do: (f.(left) + 4*f.((left+right)/2.0) + f.(right)) / 6.0 + + def integrate(f, a, b, steps) when is_integer(steps) do + delta = (b - a) / steps + Enum.each(@funs, fn fun -> + total = Enum.reduce(0..steps-1, 0, fn i, acc -> + left = a + delta * i + acc + apply(Numerical, fun, [f, left, left+delta]) + end) + :io.format "~10s : ~.6f~n", [fun, total * delta] + end) + end +end + +f1 = fn x -> x * x * x end +IO.puts "f(x) = x^3, where x is [0,1], with 100 approximations." +Numerical.integrate(f1, 0, 1, 100) + +f2 = fn x -> 1 / x end +IO.puts "\nf(x) = 1/x, where x is [1,100], with 1,000 approximations. " +Numerical.integrate(f2, 1, 100, 1000) + +f3 = fn x -> x end +IO.puts "\nf(x) = x, where x is [0,5000], with 5,000,000 approximations." +Numerical.integrate(f3, 0, 5000, 5_000_000) + +f4 = fn x -> x end +IO.puts "\nf(x) = x, where x is [0,6000], with 6,000,000 approximations." +Numerical.integrate(f4, 0, 6000, 6_000_000) diff --git a/Task/Numerical-integration/Go/numerical-integration.go b/Task/Numerical-integration/Go/numerical-integration.go index b0b8b7b1c3..603df51a2c 100644 --- a/Task/Numerical-integration/Go/numerical-integration.go +++ b/Task/Numerical-integration/Go/numerical-integration.go @@ -39,35 +39,35 @@ var methods = []method{ } func rectLeft(t spec) float64 { - parts := make([]float64, t.n) + var a adder r := t.upper - t.lower nf := float64(t.n) x0 := t.lower - for i := range parts { + for i := 0; i < t.n; i++ { x1 := t.lower + float64(i+1)*r/nf // x1-x0 better than r/nf. // (with r/nf, the represenation error accumulates) - parts[i] = t.f(x0) * (x1 - x0) + a.add(t.f(x0) * (x1 - x0)) x0 = x1 } - return sum(parts) + return a.total() } func rectRight(t spec) float64 { - parts := make([]float64, t.n) + var a adder r := t.upper - t.lower nf := float64(t.n) x0 := t.lower - for i := range parts { + for i := 0; i < t.n; i++ { x1 := t.lower + float64(i+1)*r/nf - parts[i] = t.f(x1) * (x1 - x0) + a.add(t.f(x1) * (x1 - x0)) x0 = x1 } - return sum(parts) + return a.total() } func rectMid(t spec) float64 { - parts := make([]float64, t.n) + var a adder r := t.upper - t.lower nf := float64(t.n) // there's a tiny gloss in the x1-x0 trick here. the correct way @@ -77,80 +77,72 @@ func rectMid(t spec) float64 { // reuse the midpoint x's, knowing that they will average out just // as well. we just need one extra point, so we use lower-.5. x0 := t.lower - .5*r/nf - for i := range parts { + for i := 0; i < t.n; i++ { x1 := t.lower + (float64(i)+.5)*r/nf - parts[i] = t.f(x1) * (x1 - x0) + a.add(t.f(x1) * (x1 - x0)) x0 = x1 } - return sum(parts) + return a.total() } func trap(t spec) float64 { - parts := make([]float64, t.n) + var a adder r := t.upper - t.lower nf := float64(t.n) x0 := t.lower f0 := t.f(x0) - for i := range parts { + for i := 0; i < t.n; i++ { x1 := t.lower + float64(i+1)*r/nf f1 := t.f(x1) - parts[i] = (f0 + f1) * .5 * (x1 - x0) + a.add((f0 + f1) * .5 * (x1 - x0)) x0, f0 = x1, f1 } - return sum(parts) + return a.total() } func simpson(t spec) float64 { - parts := make([]float64, 2*t.n+1) + var a adder r := t.upper - t.lower nf := float64(t.n) // similar to the rectangle midpoint logic explained above, // we play a little loose with the values used for dx and dx0. dx0 := r / nf - parts[0] = t.f(t.lower) * dx0 - parts[1] = t.f(t.lower+dx0*.5) * dx0 * 4 + a.add(t.f(t.lower) * dx0) + a.add(t.f(t.lower+dx0*.5) * dx0 * 4) x0 := t.lower + dx0 for i := 1; i < t.n; i++ { x1 := t.lower + float64(i+1)*r/nf xmid := (x0 + x1) * .5 dx := x1 - x0 - parts[2*i] = t.f(x0) * dx * 2 - parts[2*i+1] = t.f(xmid) * dx * 4 + a.add(t.f(x0) * dx * 2) + a.add(t.f(xmid) * dx * 4) x0 = x1 } - parts[2*t.n] = t.f(t.upper) * dx0 - return sum(parts) / 6 + a.add(t.f(t.upper) * dx0) + return a.total() / 6 } -// sum a list of numbers avoiding loss of precision func sum(v []float64) float64 { - if len(v) == 0 { - return 0 + var a adder + for _, e := range v { + a.add(e) } - var parts []float64 - for _, x := range v { - var i int - for _, p := range parts { - sum := p + x - var err float64 - if math.Abs(x) < math.Abs(p) { - err = x - (sum - p) - } else { - err = p - (sum - x) - } - if err != 0 { - parts[i] = err - i++ - } - x = sum - } - parts = append(parts[:i], x) - } - var sum float64 - for _, x := range parts { - sum += x - } - return sum + return a.total() +} + +type adder struct { + sum, e float64 +} + +func (a *adder) total() float64 { + return a.sum + a.e +} + +func (a *adder) add(x float64) { + sum := a.sum + x + e := sum - a.sum + a.e += a.sum - (sum - e) + (x - e) + a.sum = sum } func main() { diff --git a/Task/Numerical-integration/Perl-6/numerical-integration-1.pl6 b/Task/Numerical-integration/Perl-6/numerical-integration-1.pl6 index 5ddbfe73ed..eeb58ba3a2 100644 --- a/Task/Numerical-integration/Perl-6/numerical-integration-1.pl6 +++ b/Task/Numerical-integration/Perl-6/numerical-integration-1.pl6 @@ -1,21 +1,21 @@ sub leftrect(&f, $a, $b, $n) { my $h = ($b - $a) / $n; - $h * [+] do f($_) for $a, *+$h ... $b-$h; + $h * [+] do f($_) for $a, $a+$h ... $b-$h; } sub rightrect(&f, $a, $b, $n) { my $h = ($b - $a) / $n; - $h * [+] do f($_) for $a+$h, *+$h ... $b; + $h * [+] do f($_) for $a+$h, $a+$h+$h ... $b; } sub midrect(&f, $a, $b, $n) { my $h = ($b - $a) / $n; - $h * [+] do f($_) for $a+$h/2, *+$h ... $b-$h/2; + $h * [+] do f($_) for $a+$h/2, $a+$h+$h/2 ... $b-$h/2; } sub trapez(&f, $a, $b, $n) { my $h = ($b - $a) / $n; - $h / 2 * [+] f($a), f($b), do f($_) * 2 for $a+$h, *+$h ... $b-$h; + $h / 2 * [+] f($a), f($b), |do f($_) * 2 for $a+$h, $a+$h+$h ... $b-$h; } sub simpsons(&f, $a, $b, $n) { @@ -33,7 +33,7 @@ sub simpsons(&f, $a, $b, $n) { sub tryem($f, $a, $b, $n, $exact) { say "\n$f\n in [$a..$b] / $n"; - eval "my &f = $f; + EVAL "my &f = $f; say ' exact result: ', $exact; say ' rectangle method left: ', leftrect &f, $a, $b, $n; say ' rectangle method right: ', rightrect &f, $a, $b, $n; @@ -46,6 +46,6 @@ tryem '{ $_ ** 3 }', 0, 1, 100, 0.25; tryem '1 / *', 1, 100, 1000, log(100); -tryem '{$_}', 0, 5_000, 10_000, 12_500_000; +tryem '*.self', 0, 5_000, 5_000_000, 12_500_000; -tryem '{$_}', 0, 6_000, 12_000, 18_000_000; +tryem '*.self', 0, 6_000, 6_000_000, 18_000_000; diff --git a/Task/Numerical-integration/Perl-6/numerical-integration-2.pl6 b/Task/Numerical-integration/Perl-6/numerical-integration-2.pl6 index 3bce51a0b3..8d505eae03 100644 --- a/Task/Numerical-integration/Perl-6/numerical-integration-2.pl6 +++ b/Task/Numerical-integration/Perl-6/numerical-integration-2.pl6 @@ -3,7 +3,7 @@ exact result: 0.25 rectangle method left: 0.245025 rectangle method right: 0.255025 - rectangle method mid: 0.2499875 + rectangle method mid: 0.249988 composite trapezoidal rule: 0.250025 quadratic simpsons rule: 0.25 @@ -16,20 +16,20 @@ composite trapezoidal rule: 0.250025 composite trapezoidal rule: 4.60598605751468 quadratic simpsons rule: 4.60517038495714 -{$_} - in [0..5000] / 10000 +*.self + in [0..5000] / 5000000 exact result: 12500000 - rectangle method left: 12498750 - rectangle method right: 12501250 + rectangle method left: 12499997.5 + rectangle method right: 12500002.5 rectangle method mid: 12500000 composite trapezoidal rule: 12500000 quadratic simpsons rule: 12500000 -{$_} - in [0..6000] / 12000 +*.self + in [0..6000] / 6000000 exact result: 18000000 - rectangle method left: 17998500 - rectangle method right: 18001500 + rectangle method left: 17999997 + rectangle method right: 18000003 rectangle method mid: 18000000 composite trapezoidal rule: 18000000 quadratic simpsons rule: 18000000 diff --git a/Task/Numerical-integration/REXX/numerical-integration.rexx b/Task/Numerical-integration/REXX/numerical-integration.rexx index eded3e6baa..d335c8ce13 100644 --- a/Task/Numerical-integration/REXX/numerical-integration.rexx +++ b/Task/Numerical-integration/REXX/numerical-integration.rexx @@ -1,59 +1,47 @@ -/*REXX program numerically integrates using five different methods. */ -numeric digits 20 /*use twenty digits precision. */ +/*REXX program does numerical integration using five different algorithms.*/ +numeric digits 20 /*use twenty decimal digits precision. */ - do test=1 for 4 /*perform the test suite. */ - if test==1 then do; L=0; H= 1; i= 100; end - if test==2 then do; L=1; H= 100; i= 1000; end - if test==3 then do; L=0; H=5000; i=5000000; end - if test==4 then do; L=0; H=6000; i=5000000; end - say - say center('test' test,79,'─') /*display a header for the test. */ - say ' left_rectangular('L","H','i") = " left_rect(L,H,i) - say ' midpoint_rectangular('L","H','i") = " midpoint_rect(L,H,i) - say ' right_rectangular('L","H','i") = " right_rect(L,H,i) - say ' simpson('L","H','i") = " simpson(L,H,i) - say ' trapezoid('L","H','i") = " trapezoid(L,H,i) - end /*test*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────LEFT_RECT subroutine────────────────*/ -left_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n -sum=0 - do x=a by h for n - sum=sum+f(x) - end /*x*/ -return sum*h -/*──────────────────────────────────MIDPOINT_RECT subroutine────────────*/ -midpoint_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n -sum=0 - do x=a+h/2 by h for n - sum=sum+f(x) - end /*x*/ -return sum*h -/*──────────────────────────────────RIGHT_RECT subroutine───────────────*/ -right_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n -sum=0 - do x=a+h by h for n - sum=sum+f(x) - end /*x*/ -return sum*h -/*──────────────────────────────────SIMPSON subroutine──────────────────*/ -simpson: procedure expose test; parse arg a,b,n; h=(b-a)/n -sum1=f(a+h/2) -sum2=0; do x=1 to n-1 - sum1=sum1+f(a+h*x+h*.5) - sum2=sum2+f(a+x*h) - end /*x*/ + do test=1 for 4 /*perform the 4 different test suites. */ + if test==1 then do; L=0; H= 1; i= 100; end + if test==2 then do; L=1; H= 100; i= 1000; end + if test==3 then do; L=0; H=5000; i=5000000; end + if test==4 then do; L=0; H=6000; i=5000000; end + say + say center('test' test,65,'─') /*display a header for the test suite. */ + say ' left rectangular('L", "H', 'i") ──► " left_rect(L, H, i) + say ' midpoint rectangular('L", "H', 'i") ──► " midpoint_rect(L, H, i) + say ' right rectangular('L", "H', 'i") ──► " right_rect(L, H, i) + say ' Simpson('L", "H', 'i") ──► " Simpson(L, H, i) + say ' trapezium('L", "H', 'i") ──► " trapezium(L, H, i) + end /*test*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +f: if test==1 then return arg(1)**3 + if test==2 then return 1/arg(1) + return arg(1) +/*────────────────────────────────────────────────────────────────────────────*/ +left_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n +$=0 + do x=a by h for n; $=$+f(x); end /*x*/ +return $*h/1 /*return the number with no trailing 0s*/ +/*────────────────────────────────────────────────────────────────────────────*/ +midpoint_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n +$=0 + do x=a+h/2 by h for n; $=$+f(x); end /*x*/ +return $*h/1 /*return the number with no trailing 0s*/ +/*────────────────────────────────────────────────────────────────────────────*/ +right_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n +$=0 + do x=a+h by h for n; $=$+f(x); end /*x*/ +return $*h/1 /*return the number with no trailing 0s*/ +/*────────────────────────────────────────────────────────────────────────────*/ +Simpson: procedure expose test; parse arg a,b,n; h=(b-a)/n +$=f(a+h/2) +@=0; do x=1 for n-1; $=$+f(a+h*x+h*.5); @=@+f(a+x*h); end /*x*/ -return h*(f(a)+f(b)+4*sum1+2*sum2)/6 -/*──────────────────────────────────TRAPEZOID subroutine────────────────*/ -trapezoid: procedure expose test; parse arg a,b,n; h=(b-a)/n -sum=0 - do x=a to b by h - sum=sum+h*(f(x)+f(x+h))*.5 - end /*x*/ -return sum -/*──────────────────────────────────F subroutine────────────────────────*/ -f: procedure expose test; parse arg z -if test==1 then return z**3 -if test==2 then return 1/z - return z +return h*(f(a) + f(b) + 4*$ + 2*@)/6 /*return the number with no trailing 0s*/ +/*────────────────────────────────────────────────────────────────────────────*/ +trapezium: procedure expose test; parse arg a,b,n; h=(b-a)/n +$=0 + do x=a by h for n; $=$+(f(x)+f(x+h)); end /*x*/ +return $*h/2 /*return the number with no trailing 0s*/ diff --git a/Task/Numerical-integration/Rust/numerical-integration.rust b/Task/Numerical-integration/Rust/numerical-integration.rust new file mode 100644 index 0000000000..6046cac939 --- /dev/null +++ b/Task/Numerical-integration/Rust/numerical-integration.rust @@ -0,0 +1,20 @@ +fn integral(f: F, range: std::ops::Range, n_steps: u32) -> f64 + where F: Fn(f64) -> f64 +{ + let step_size = (range.end - range.start)/n_steps as f64; + + let mut integral = (f(range.start) + f(range.end))/2.; + let mut pos = range.start + step_size; + while pos < range.end { + integral += f(pos); + pos += step_size; + } + integral * step_size +} + +fn main() { + println!("{}", integral(|x| x.powi(3), 0.0..1.0, 100)); + println!("{}", integral(|x| 1.0/x, 1.0..100.0, 1000)); + println!("{}", integral(|x| x, 0.0..5000.0, 5_000_000)); + println!("{}", integral(|x| x, 0.0..6000.0, 6_000_000)); +} diff --git a/Task/Object-serialization/Objective-C/object-serialization.m b/Task/Object-serialization/Objective-C/object-serialization.m index 1d9b843433..d6b6aecd64 100644 --- a/Task/Object-serialization/Objective-C/object-serialization.m +++ b/Task/Object-serialization/Objective-C/object-serialization.m @@ -14,7 +14,7 @@ @implementation Animal - (instancetype) initWithName: (NSString*)name andLegs: (NSInteger)legs { if ((self = [super init])) { - animalName = [name retain]; + animalName = name; numberOfLegs = legs; } return self; @@ -29,10 +29,10 @@ - (void) encodeWithCoder: (NSCoder*)coder [coder encodeObject: animalName forKey: @"Animal.name"]; [coder encodeInt: numberOfLegs forKey: @"Animal.legs"]; } -- (id) initWithCoder: (NSCoder*)coder +- (instancetype) initWithCoder: (NSCoder*)coder { if ((self = [super init])) { - animalName = [[coder decodeObjectForKey: @"Animal.name"] retain]; + animalName = [coder decodeObjectForKey: @"Animal.name"]; numberOfLegs = [coder decodeIntForKey: @"Animal.legs"]; } return self; @@ -85,7 +85,7 @@ - (void) encodeWithCoder: (NSCoder*)coder [coder encodeBool: numberOfLegs forKey: @"Mammal.hasFur"]; [coder encodeObject: eatenList forKey: @"Mammal.eaten"]; } -- (id) initWithCoder: (NSCoder*)coder +- (instancetype) initWithCoder: (NSCoder*)coder { if ((self = [super initWithCoder: coder])) { hasFur = [coder decodeBoolForKey: @"Mammal.hasFur"]; diff --git a/Task/Old-lady-swallowed-a-fly/Batch-File/old-lady-swallowed-a-fly.bat b/Task/Old-lady-swallowed-a-fly/Batch-File/old-lady-swallowed-a-fly.bat new file mode 100644 index 0000000000..1c857c5f6f --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Batch-File/old-lady-swallowed-a-fly.bat @@ -0,0 +1,46 @@ +@echo off +setlocal enabledelayedexpansion + + %== An "ugly" pseudo-array ===% +set pseudo=^ +fly/@^ +spider/That_wiggled_and_jiggled_and_tickled_inside_her,@^ +bird/How_absurd,_to_swallow_a_bird,@^ +cat/Imagine_that._She_swallowed_a_cat,@^ +dog/What_a_hog_to_swallow_a_dog,@^ +goat/She_just_opened_her_throat_and_swallowed_that_goat,@^ +cow/I_don't_know_how_she_swallowed_that_cow,@^ +horse/She's_dead_of_course... + + %== Counting and seperating... ===% +set str=!pseudo! +:count +if "!str!"=="" goto print_song +for /f "tokens=1,* delims=@" %%A in ("!str!") do ( + set /a cnt+=1 + for /f "tokens=1,2 delims=/" %%C in ("%%A") do ( + set animal!cnt!=%%C + set comment!cnt!=%%D + ) + set str=%%B +) +goto count + + %== Print the song ===% +:print_song +for /l %%i in (1,1,!cnt!) do ( + echo There was an old lady who swallowed a !animal%%i!. + if not "!comment%%i!"=="" echo !comment%%i:_= ! + if %%i equ !cnt! goto done + + for /l %%j in (%%i,-1,2) do ( + set/a prev=%%j-1 + call set prev_animal=%%animal!prev!%% + echo She swallowed the !animal%%j! to catch the !prev_animal!. + ) + echo I don't know why she swallowed the fly. + echo Perhaps she'll die. + echo. +) +:done +pause>nul&exit/b 0 diff --git a/Task/Old-lady-swallowed-a-fly/Befunge/old-lady-swallowed-a-fly.bf b/Task/Old-lady-swallowed-a-fly/Befunge/old-lady-swallowed-a-fly.bf new file mode 100644 index 0000000000..e7512548bf --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Befunge/old-lady-swallowed-a-fly.bf @@ -0,0 +1,9 @@ +055*46*146*1->00p 36268>5\:4\:2v >\#%"O"/#:3#:+#< g48*- >1-:!#v_\1+::"O"%\"O"/v +>-#2:#\8#1`#:|#-1:-1\7_^#`g00:+<>\#%"O"/#::$#<3#$+g48*-v^\,+*+ 55!:*!!-"|":g+3< + >$ 36 26 58 49 81 36 26 10 \1-:#^\_^#:-1\+<00_@#:>#<$< +DI know an old lady who swallowed a F.|I don't know why she swallowed the 8.|Pe +rhaps she'll die.||5.|She swallowed the / to catch the $fly0. To swallow a 'spi +derS.|That wriggled and jiggled and tickled inside her%Bird/.|Quite absurd$Cat- +.|Fancy that$Dog-.|What a hog$Pig7.|Her mouth was so big%Goat=.|She just opened + her throat$Cow3.|I don't know how'Donkey6.|It was rather wonky&Horse:.|She's d +ead, of course!| diff --git a/Task/Old-lady-swallowed-a-fly/Go/old-lady-swallowed-a-fly.go b/Task/Old-lady-swallowed-a-fly/Go/old-lady-swallowed-a-fly.go new file mode 100644 index 0000000000..41207371f2 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Go/old-lady-swallowed-a-fly.go @@ -0,0 +1,36 @@ +package main + +import "fmt" + +var name, lyric, animals = 0, 1, [][]string{ + {"fly", "I don't know why she swallowed a fly. Perhaps she'll die."}, + {"spider", "That wiggled and jiggled and tickled inside her."}, + {"bird", "How absurd, to swallow a bird."}, + {"cat", "Imagine that, she swallowed a cat."}, + {"dog", "What a hog, to swallow a dog."}, + {"goat", "She just opened her throat and swallowed that goat."}, + {"cow", "I don't know how she swallowed that cow."}, + {"horse", "She's dead, of course."}, +} + +func main() { + for i, animal := range animals { + fmt.Printf("There was an old lady who swallowed a %s,\n", animal[name]) + + if i > 0 { + fmt.Println(animal[lyric]) + } + + //Swallowing the last animal signals her death, cutting the lyrics short + if i+1 == len(animals) { + break + } + + for i > 0 { + fmt.Printf("She swallowed the %s to catch the %s,\n", animals[i][name], animals[i-1][name]) + i-- + } + + fmt.Println(animals[0][lyric] + "\n") + } +} diff --git a/Task/Old-lady-swallowed-a-fly/Liberty-BASIC/old-lady-swallowed-a-fly.liberty b/Task/Old-lady-swallowed-a-fly/Liberty-BASIC/old-lady-swallowed-a-fly.liberty new file mode 100644 index 0000000000..a781ebf5ad --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Liberty-BASIC/old-lady-swallowed-a-fly.liberty @@ -0,0 +1,45 @@ +'[RC] Old lady swallowed a fly +'http://rosettacode.org/wiki/Old_lady_swallowed_a_fly +'lyrics +'http://www.timmyabell.com/music/lyrics/ol/oldlady.htm + +animalList$="fly spider bird cat dog goat cow horse" +reason$(1)="I don't know why she swallowed the fly," +reason$(2)="That wriggled and jiggled and tickled inside her." +reason$(3)="How absurd to swallow a bird!" +reason$(4)="Imagine that, to swallow a cat!" +reason$(5)="My, what a hog, to swallow a dog!" +reason$(6)="Just opened her throat and swallowed a goat!" +reason$(7)="I wonder how she swallowed a cow?!" +reason$(8)="She's dead, of course!!" + +i=0 +while 1 + i=i+1 + animal$ = word$(animalList$, i) + if animal$ ="" then exit while + verse$ = "I know an old lady who " + verse2$ = "swallowed a " +animal$ + print verse$ +verse2$+"," + print reason$(i) + if i = 8 then end + '-------------- + animals$=animal$+" "+animals$ + animal2$="*" + j=1 + while 1 + j=j+1 + animal2$ = word$(animals$, j) + if animal2$ ="" then exit while + reason$="She swallowed the "+animal$+" to catch the "+animal2$+"," + animal$ = animal2$ + print reason$ + if animal2$ = "fly" then print reason$(1) + if animal2$ = "spider" then print reason$(2) + wend + '-------------- + print "I guess she'll die." + print +wend + +end diff --git a/Task/Old-lady-swallowed-a-fly/Logo/old-lady-swallowed-a-fly.logo b/Task/Old-lady-swallowed-a-fly/Logo/old-lady-swallowed-a-fly.logo new file mode 100644 index 0000000000..0b3b5df8cf --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Logo/old-lady-swallowed-a-fly.logo @@ -0,0 +1,35 @@ +make "data [ +; animal inc comment + [fly 2 [I don't know why she swallowed that fly]] + [spider 2 [That wriggled and jiggled and tickled inside her]] + [bird 1 [Quite absurd, to swallow a bird]] + [cat 1 [How about that, to swallow a cat]] + [dog 1 [What a hog, to swallow a dog]] + [pig 1 [Her mouth was so big to swallow a pig]] + [goat 1 [She just opened her throat to swallow a goat.]] + [cow 1 [I don't know how she swallowed a cow.]] + [donkey 1 [It was rather wonky to swallow a donkey]] + [horse 0 [She's dead, of course!]] +] + +foreach :data [ + local "i make "i # + (local "animal "include "comment) + (foreach [animal include comment] ? "make) + print se [There was an old lady who swallowed a] :animal + print :comment + if greater? :include 0 [ + if greater? :i 1 [ + repeat difference :i 1 [ + local "j make "j difference :i repcount + print (se [She swallowed the] (first item sum 1 :j :data) + [to catch the] (first item :j :data)) + if greater? item 2 item :j :data 1 [print item 3 item :j :data] + ] + ] + print [Perhaps she'll die] + print " + ] +] + +bye diff --git a/Task/Old-lady-swallowed-a-fly/Mathematica/old-lady-swallowed-a-fly.math b/Task/Old-lady-swallowed-a-fly/Mathematica/old-lady-swallowed-a-fly.math new file mode 100644 index 0000000000..dc9955d07a --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Mathematica/old-lady-swallowed-a-fly.math @@ -0,0 +1,17 @@ +animals = {"fly", "spider", "bird", "cat", "dog", "goat", "cow", + "horse"}; +notes = {"", "That wiggled and jiggled and tickled inside her.\n", + "How absurd, to swallow a bird.\n", + "Imagine that. She swallowed a cat.\n", + "What a hog to swallow a dog.\n", + "She just opened her throat and swallowed that goat.\n", + "I don't know how she swallowed that cow.\n", + "She's dead, of course.", + "I don't know why she swallowed that fly.\nPerhaps she'll die.\n\n\ +"}; +Print[StringJoin @@ ("There was an old lady who swallowed a " <> + animals[[#]] <> ".\n" <> notes[[#]] <> + If[# == 8, "", + StringJoin @@ ("She swallowed the " <> animals[[#]] <> + " to catch the " <> animals[[# - 1]] <> ".\n" & /@ + Range[#, 2, -1]) <> notes[[9]]] & /@ Range[8])]; diff --git a/Task/Old-lady-swallowed-a-fly/PowerShell/old-lady-swallowed-a-fly.psh b/Task/Old-lady-swallowed-a-fly/PowerShell/old-lady-swallowed-a-fly.psh new file mode 100644 index 0000000000..cc976de08a --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/PowerShell/old-lady-swallowed-a-fly.psh @@ -0,0 +1,26 @@ +$arr=@() +$arr+="fly/" +$srr+="spider/That wiggled and jiggled and tickled inside her," +$arr+="bird/How absurd, to swallow a bird," +$arr+="cat/Imagine that. She swallowed a cat," +$arr+="dog/What a hog to swallow a dog," +$arr+="goat/She just opened her throat and swallowed that goat," +$arr+="cow/I don't know how she swallowed that cow," +$arr+="horse/She's dead of course!" + +$leng=$arr.length +$animals=@() +for($i=0;$i -lt $leng;$i++){ + $split=$arr[$i] -split "/" + $animals+=$split[0] + $comment=$split[1] + write-host "I know an old lady who swallowed a" $animals[$i] + if($comment){write-host "$comment"} + if($i -eq $leng-1){break} + for($j=$i;$j -ge 1;$j--){ + write-host "She swallowed the" $animals[$j] "to catch the" $animals[$j-1] + } + write-host "I don't know why she swallowed the fly." + write-host "Perhaps she'll die." + write-host "" +} diff --git a/Task/Old-lady-swallowed-a-fly/UNIX-Shell/old-lady-swallowed-a-fly.sh b/Task/Old-lady-swallowed-a-fly/UNIX-Shell/old-lady-swallowed-a-fly.sh new file mode 100644 index 0000000000..94d3e18226 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/UNIX-Shell/old-lady-swallowed-a-fly.sh @@ -0,0 +1,29 @@ +animals=(fly spider bird cat dog pig goat cow donkey horse) +comments=("I don't know why she swallowed that fly" + "That wriggled and jiggled and tickled inside her" + "Quite absurd, to swallow a bird" + "How about that, to swallow a cat" + "What a hog, to swallow a dog" + "Her mouth was so big to swallow a pig" + "She just opened her throat to swallow a goat." + "I don't know how she swallowed a cow." + "It was rather wonky to swallow a donkey" + "She's dead, of course!") +include=(2 2 1 1 1 1 1 1 1 0) + +for (( i=0; i<${#animals[@]}; ++i )); do + echo "There was an old lady who swallowed a ${animals[i]}" + echo "${comments[i]}" + if (( include[i] )); then + if (( i )); then + for (( j=i-1; j>=0; --j )); do + echo "She swallowed the ${animals[j+1]} to catch the ${animals[j]}" + if (( include[j] > 1 )); then + echo "${comments[j]}" + fi + done + fi + echo "Perhaps she'll die" + echo + fi +done diff --git a/Task/One-dimensional-cellular-automata/Batch-File/one-dimensional-cellular-automata.bat b/Task/One-dimensional-cellular-automata/Batch-File/one-dimensional-cellular-automata.bat new file mode 100644 index 0000000000..ee53f5e934 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Batch-File/one-dimensional-cellular-automata.bat @@ -0,0 +1,58 @@ +@echo off +setlocal enabledelayedexpansion + +::THE MAIN THING +call :one-dca __###__##_#_##_###__######_###_#####_#__##_____#_#_#######__ +pause>nul +exit /b +::/THE MAIN THING + +::THE PROCESSOR +:one-dca +echo.&set numchars=0&set proc=%1 + +::COUNT THE NUMBER OF CHARS +set bef=%proc:_=_,% +set bef=%bef:#=#,% +set bef=%bef:~0,-1% +for %%x in (%bef%) do set /a numchars+=1 + +set /a endchar=%numchars%-1 +:nextgen +echo. ^| %proc% ^| +set currnum=0 +set newgen= +:editeachchar + set neigh=0 + set /a testnum2=%currnum%+1 + set /a testnum1=%currnum%-1 + if %currnum%==%endchar% ( + set testchar=!proc:~%testnum1%,1! + if !testchar!==# (set neigh=1) + ) else ( + if %currnum%==0 ( + set testchar=%proc:~1,1% + if !testchar!==# (set neigh=1) + ) else ( + set testchar1=!proc:~%testnum1%,1! + set testchar2=!proc:~%testnum2%,1! + if !testchar1!==# (set /a neigh+=1) + if !testchar2!==# (set /a neigh+=1) + ) + ) + if %neigh%==0 (set newgen=%newgen%_) + if %neigh%==1 ( + set testchar=!proc:~%currnum%,1! + set newgen=%newgen%!testchar! + ) + if %neigh%==2 ( + set testchar=!proc:~%currnum%,1! + if !testchar!==# (set newgen=%newgen%_) else (set newgen=%newgen%#) + ) +if %currnum%==%endchar% (goto :cond) else (set /a currnum+=1&goto :editeachchar) + +:cond +if %proc%==%newgen% (echo.&echo ...The sample is now stable.&goto :EOF) +set proc=%newgen% +goto :nextgen +::/THE (LLLLLLOOOOOOOOOOOOONNNNNNNNGGGGGG.....) PROCESSOR diff --git a/Task/One-dimensional-cellular-automata/Eiffel/one-dimensional-cellular-automata.e b/Task/One-dimensional-cellular-automata/Eiffel/one-dimensional-cellular-automata.e new file mode 100644 index 0000000000..ac7b150b3f --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Eiffel/one-dimensional-cellular-automata.e @@ -0,0 +1,72 @@ +class + APPLICATION + +create + make + +feature + + make + -- First 10 states of the cellular automata. + local + r: RANDOM + automata: STRING + do + create r.make + create automata.make_empty + across + 1 |..| 10 as c + loop + if r.double_item < 0.5 then + automata.append ("0") + else + automata.append ("1") + end + r.forth + end + across + 1 |..| 10 as c + loop + io.put_string (automata + "%N") + automata := update (automata) + end + end + + update (s: STRING): STRING + -- Next state of the cellular automata 's'. + require + enough_states: s.count > 1 + local + i: INTEGER + do + create Result.make_empty + -- Dealing with the left border. + if s [1] = '1' and s [2] = '1' then + Result.append ("1") + else + Result.append ("0") + end + -- Dealing with the middle cells. + from + i := 2 + until + i = s.count + loop + if (s [i] = '0' and (s [i - 1] = '0' or (s [i - 1] = '1' and s [i + 1] = '0'))) or ((s [i] = '1') and ((s [i - 1] = '1' and s [i + 1] = '1') or (s [i - 1] = '0' and s [i + 1] = '0'))) then + Result.append ("0") + else + Result.append ("1") + end + i := i + 1 + end + -- Dealing with the right border. + if s [s.count] = '1' and s [s.count - 1] = '1' then + Result.append ("1") + else + Result.append ("0") + end + ensure + has_same_length: s.count = Result.count + end + +end diff --git a/Task/One-dimensional-cellular-automata/Elixir/one-dimensional-cellular-automata.elixir b/Task/One-dimensional-cellular-automata/Elixir/one-dimensional-cellular-automata.elixir new file mode 100644 index 0000000000..7e2de6e342 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Elixir/one-dimensional-cellular-automata.elixir @@ -0,0 +1,21 @@ +defmodule RC do + def run(list, gen \\ 0) do + print(list, gen) + next = evolve(list) + if next == list, do: print(next, gen+1), else: run(next, gen+1) + end + + defp evolve(list), do: evolve(Enum.concat([[0], list, [0]]), []) + + defp evolve([a,b,c], next), do: Enum.reverse([life(a,b,c) | next]) + defp evolve([a,b,c|rest], next), do: evolve([b,c|rest], [life(a,b,c) | next]) + + defp life(a,b,c), do: (if a+b+c == 2, do: 1, else: 0) + + defp print(list, gen) do + str = "Generation #{gen}: " + IO.puts Enum.reduce(list, str, fn x,s -> s <> if x==0, do: ".", else: "#" end) + end +end + +RC.run([0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]) diff --git a/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata.julia b/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata.julia new file mode 100644 index 0000000000..47e4cb3877 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata.julia @@ -0,0 +1,35 @@ +function next_gen(a::BitArray{1}, isperiodic=false) + b = copy(a) + if isperiodic + ncnt = [a[end], a[1:end-1]] + [a[2:end], a[1]] + else + ncnt = [false, a[1:end-1]] + [a[2:end], false] + end + b[ncnt .== 0] = false + b[ncnt .== 2] = ~b[ncnt .== 2] + return b +end + +function show_gen(a::BitArray{1}) + s = join([i ? "\u2588" : " " for i in a], "") + s = "\u25ba"*s*"\u25c4" +end + +hi = 70 +a = randbool(hi) +b = falses(hi) +println("A 1D Cellular Atomaton with ", hi, " cells and empty bounds.") +while any(a) && any(a .!= b) + println(" ", show_gen(a)) + b = copy(a) + a = next_gen(a) +end +a = randbool(hi) +b = falses(hi) +println() +println("A 1D Cellular Atomaton with ", hi, " cells and periodic bounds.") +while any(a) && any(a .!= b) + println(" ", show_gen(a)) + b = copy(a) + a = next_gen(a, true) +end diff --git a/Task/One-dimensional-cellular-automata/REXX/one-dimensional-cellular-automata.rexx b/Task/One-dimensional-cellular-automata/REXX/one-dimensional-cellular-automata.rexx index 0d8deb404a..80864463d9 100644 --- a/Task/One-dimensional-cellular-automata/REXX/one-dimensional-cellular-automata.rexx +++ b/Task/One-dimensional-cellular-automata/REXX/one-dimensional-cellular-automata.rexx @@ -1,15 +1,15 @@ -/*REXX pgm displays generations of one-dimensional cellular automata. */ -arg $ limit .; if $=='' | $==',' then $=001110110101010 /*default*/ - if limit=='' then limit=40 /*default*/ - - do gen=0 to limit - say ' generation' right(gen,length(limit)) ' ' translate($,'#·',10) - @='·' /*next gener.*/ - do j=2 to length($); x=substr($,j-1,3) /*get a cell.*/ - if x==011 | x==101 | x==110 then @=overlay(1,@,j) /*cell lives.*/ - else @=overlay(0,@,j) /*cell dies.*/ - end /*j*/ - if $==@ then do; say right('repeats',40); leave; end /*it repeats?*/ - $=@ /*now use the next gen of cells. */ - end /*gen*/ - /*stick a fork in it, we're done.*/ +/*REXX program displays N generations of one-dimensional cellular automata.*/ +parse arg $ gens .; if $=='' | $==',' then $=001110110101010 /*use default?*/ + if gens=='' then gens=40 /* " " */ + L=length($)-1 /*adjusted len*/ + do #=0 for gens /*process gens*/ + say " generation" right(#,length(gens)) ' ' translate($,"#·",10) + @=0 /*+ generation*/ + do j=2 for L; x=substr($,j-1,3) /*obtain cell.*/ + if x==011 | x==101 | x==110 then @=overlay(1,@,j) /*cell lives. */ + else @=overlay(0,@,j) /*cell death. */ + end /*j*/ + if $==@ then do; say right('repeats',40); leave; end /*it repeats? */ + $=@ /*now use the next generation of cells.*/ + end /*#*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/One-of-n-lines-in-a-file/ALGOL-68/one-of-n-lines-in-a-file.alg b/Task/One-of-n-lines-in-a-file/ALGOL-68/one-of-n-lines-in-a-file.alg new file mode 100644 index 0000000000..605bfed549 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/ALGOL-68/one-of-n-lines-in-a-file.alg @@ -0,0 +1,15 @@ +BEGIN + INT max lines = 10; CO Should be read from a file. CO + [max lines]INT stats; + FOR i TO max lines DO stats[i] := 0 OD; + first random (42); CO Should have rather more entropy! CO + PROC one of n = (INT n) INT : + BEGIN + INT result := 1; + FOR i TO n DO (random < 1/i | result := i) OD; + result + END; + TO 1000000 DO stats[one of n (max lines)] +:= 1 OD; + print (("Line Number times chosen", newline)); + FOR i TO max lines DO printf (($g(0)7xg(0)l$, i, stats[i])) OD +END diff --git a/Task/One-of-n-lines-in-a-file/Eiffel/one-of-n-lines-in-a-file-1.e b/Task/One-of-n-lines-in-a-file/Eiffel/one-of-n-lines-in-a-file-1.e new file mode 100644 index 0000000000..52b6a0b1fc --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Eiffel/one-of-n-lines-in-a-file-1.e @@ -0,0 +1,33 @@ +class + APPLICATION + +create + make + +feature + + make + -- Simulates one_of_n_lines a 1000000 times. + local + t: INTEGER + simulator: ARRAY [INTEGER] + do + create simulator.make_filled (0, 1, 10) + create one.make + across + 1 |..| 1000000 as c + loop + t := one.one_of_n_lines (10) + simulator [t] := simulator [t] + 1 + end + across + simulator as s + loop + io.put_integer (s.item) + io.new_line + end + end + + one: ONE_OF_N_LINES + +end diff --git a/Task/One-of-n-lines-in-a-file/Eiffel/one-of-n-lines-in-a-file-2.e b/Task/One-of-n-lines-in-a-file/Eiffel/one-of-n-lines-in-a-file-2.e new file mode 100644 index 0000000000..e8efec59f5 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Eiffel/one-of-n-lines-in-a-file-2.e @@ -0,0 +1,39 @@ +class + ONE_OF_N_LINES + +create + make + +feature {NONE} + + r: RANDOM + +feature + + make + do + create r.make + end + + one_of_n_lines (n: INTEGER): INTEGER + -- A integer between 1 and 'n', denoting a line. + require + n_is_positive: n > 0 + local + p: REAL_64 + do + across + 1 |..| n as c + loop + p := r.double_item + if p < (1 / c.item) then + Result := c.item + end + r.forth + end + ensure + Result_in_file: Result <= n + Result_is_positive: Result > 0 + end + +end diff --git a/Task/One-of-n-lines-in-a-file/Forth/one-of-n-lines-in-a-file.fth b/Task/One-of-n-lines-in-a-file/Forth/one-of-n-lines-in-a-file.fth new file mode 100644 index 0000000000..59a3e25eb4 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Forth/one-of-n-lines-in-a-file.fth @@ -0,0 +1,13 @@ +require random.fs + +: frnd + rnd 0 d>f [ s" MAX-U" environment? drop 0 d>f 1/f ] fliteral f* ; +: u>f 0 d>f ; +: one_of_n ( u1 -- u2 ) + 1 swap 1+ 2 ?do frnd i u>f 1/f f< if drop i then loop ; + +create hist 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , does> swap cells + ; +: simulate 1000000 0 do 1 10 one_of_n 1- hist +! loop ; +: .hist cr 10 0 do i 1+ 2 .r ." : " i hist @ . cr loop ; + +simulate .hist bye diff --git a/Task/One-of-n-lines-in-a-file/Julia/one-of-n-lines-in-a-file.julia b/Task/One-of-n-lines-in-a-file/Julia/one-of-n-lines-in-a-file.julia new file mode 100644 index 0000000000..bb00488c65 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Julia/one-of-n-lines-in-a-file.julia @@ -0,0 +1,22 @@ +const N = 10 +const GOAL = 10^6 + +function oneofn{T<:Integer}(n::T) + 0 < n || error("n = ", n, ", but it should be positive.") + oon = 1 + for i in 2:n + rand(1:i) == 1 || continue + oon = i + end + return oon +end + +nhist = zeros(Int, N) +for i in 1:GOAL + nhist[oneofn(N)] += 1 +end + +println("Simulating oneofn(", N, ") ", GOAL, " times:") +for i in 1:N + println(@sprintf " %2d => %6d" i nhist[i]) +end diff --git a/Task/One-of-n-lines-in-a-file/Liberty-BASIC/one-of-n-lines-in-a-file.liberty b/Task/One-of-n-lines-in-a-file/Liberty-BASIC/one-of-n-lines-in-a-file.liberty new file mode 100644 index 0000000000..561a1fbf9a --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Liberty-BASIC/one-of-n-lines-in-a-file.liberty @@ -0,0 +1,18 @@ +DIM chosen(10) + +FOR i = 1 TO 10000'00 + c = oneofN(10) + chosen(c) = chosen(c) + 1 +NEXT + +FOR i = 1 TO 10 + PRINT i, chosen(i) +NEXT + +end + +FUNCTION oneofN(n) + FOR i = 1 TO n + IF RND(1) < 1/i THEN oneofN = i + NEXT +END FUNCTION diff --git a/Task/One-of-n-lines-in-a-file/REXX/one-of-n-lines-in-a-file.rexx b/Task/One-of-n-lines-in-a-file/REXX/one-of-n-lines-in-a-file.rexx index a640e0dd62..745f99f70e 100644 --- a/Task/One-of-n-lines-in-a-file/REXX/one-of-n-lines-in-a-file.rexx +++ b/Task/One-of-n-lines-in-a-file/REXX/one-of-n-lines-in-a-file.rexx @@ -1,15 +1,15 @@ -/*REXX pgm simulates reading a ten-line file and make randomness counts.*/ -N=10 /*number of lines in pseudo-file.*/ -#.=0 /*zero all the (ten) buckets. */ - do 1000000 /*perform one million trials. */ +/*REXX program simulates reading a ten─line file, count selection randomness.*/ +N=10 /*the number of lines in pseudo-file. */ +@.=0 /*zero all the (ten) "buckets". */ + do 1000000 /*perform main loop one million times.*/ ?=1 - do k=1 for N /*N is the # of lines in the file*/ - if random(0,99999)/100000<1/k then ?=k /*the critera.*/ + do k=1 for N /*N is the number of lines in the file*/ + if random(0,99999) / 100000 < 1/k then ?=k /*the criteria*/ end /*k*/ - #.?=#.?+1 /*add it to the bucket counters. */ + @.?=@.?+1 /*bump the count in a particular bucket*/ end /*1000000*/ - do j=1 for N /*display the randomness counts. */ - say "number of times line" right(j,2) "was selected:" right(#.j,9) + do j=1 for N /*display randomness counts (buckets). */ + say "number of times line" right(j,2) "was selected:" right(@.j,9) end /*j*/ - /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/One-of-n-lines-in-a-file/VBScript/one-of-n-lines-in-a-file.vb b/Task/One-of-n-lines-in-a-file/VBScript/one-of-n-lines-in-a-file.vb new file mode 100644 index 0000000000..58c5c84afc --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/VBScript/one-of-n-lines-in-a-file.vb @@ -0,0 +1,19 @@ +Dim chosen(10) + +For j = 1 To 1000000 + c = one_of_n(10) + chosen(c) = chosen(c) + 1 +Next + +For k = 1 To 10 + WScript.StdOut.WriteLine k & ". " & chosen(k) +Next + +Function one_of_n(n) + Randomize + For i = 1 To n + If Rnd(1) < 1/i Then + one_of_n = i + End If + Next +End Function diff --git a/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.julia b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.julia new file mode 100644 index 0000000000..724a287bc9 --- /dev/null +++ b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-1.julia @@ -0,0 +1,18 @@ +function order_disjoint{T<:AbstractArray}(m::T, n::T) + rlen = length(n) + rdis = zeros(Int, rlen) + for (i, e) in enumerate(n) + j = findfirst(m, e) + while j in rdis && j != 0 + j = findnext(m, e, j+1) + end + rdis[i] = j + end + if 0 in rdis + throw(DomainError()) + end + sort!(rdis) + p = copy(m) + p[rdis] = n + return p +end diff --git a/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.julia b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.julia new file mode 100644 index 0000000000..fb88b51ce4 --- /dev/null +++ b/Task/Order-disjoint-list-items/Julia/order-disjoint-list-items-2.julia @@ -0,0 +1,24 @@ +testm = {["the", "cat", "sat", "on", "the", "mat"], + ["the", "cat", "sat", "on", "the", "mat"], + ["A", "B", "C", "A", "B", "C", "A", "B", "C"], + ["A", "B", "C", "A", "B", "D", "A", "B", "E"], + ["A", "B"], + ["A", "B"], + ["A", "B", "B", "A"], + } + +testn = {["mat", "cat"], + ["cat", "mat"], + ["C", "A", "C", "A"], + ["E", "A", "D", "A"], + ["B"], + ["B", "A"], + ["B", "A"], + } + +for i in 1:length(testm) + m = join(testm[i], " ") + n = join(testn[i], " ") + p = join(order_disjoint(testm[i], testn[i]), " ") + println(" (", m, ", ", n, ") => ", p) +end diff --git a/Task/Order-disjoint-list-items/Mathematica/order-disjoint-list-items.math b/Task/Order-disjoint-list-items/Mathematica/order-disjoint-list-items.math new file mode 100644 index 0000000000..30af35c692 --- /dev/null +++ b/Task/Order-disjoint-list-items/Mathematica/order-disjoint-list-items.math @@ -0,0 +1,19 @@ +order[m_, n_] := + ReplacePart[m, + MapThread[ + Rule, {Position[m, Alternatives @@ n][[;; Length[n]]], n}]]; +Print[StringRiffle[ + order[{"the", "cat", "sat", "on", "the", "mat"}, {"mat", + "cat"}]]]; +Print[StringRiffle[ + order[{"the", "cat", "sat", "on", "the", "mat"}, {"cat", + "mat"}]]]; +Print[StringRiffle[ + order[{"A", "B", "C", "A", "B", "C", "A", "B", "C"}, {"C", "A", + "C", "A"}]]]; +Print[StringRiffle[ + order[{"A", "B", "C", "A", "B", "D", "A", "B", "E"}, {"E", "A", + "D", "A"}]]]; +Print[StringRiffle[order[{"A", "B"}, {"B"}]]]; +Print[StringRiffle[order[{"A", "B"}, {"B", "A"}]]]; +Print[StringRiffle[order[{"A", "B", "B", "A"}, {"B", "A"}]]]; diff --git a/Task/Order-disjoint-list-items/PowerShell/order-disjoint-list-items.psh b/Task/Order-disjoint-list-items/PowerShell/order-disjoint-list-items.psh new file mode 100644 index 0000000000..dd8f50c65f --- /dev/null +++ b/Task/Order-disjoint-list-items/PowerShell/order-disjoint-list-items.psh @@ -0,0 +1,46 @@ +function sublistsort($M, $N) { + $arr = $M.Split(' ') + $array = $N.Split(' ') | group + $Count = @($array |foreach {$_.Count}) + $ip, $i = @(), 0 + $arr | foreach{ + $name = "$_" + $j = $array.Name.IndexOf($name) + if($j -gt -1){ + $k = $Count[$j] - 1 + if($k -ge 0) { + $ip += @($i) + $Count[$j] = $k + } + } + $i++ + } + $i = 0 + $N.Split(' ') | foreach{ $arr[$ip[$i++]] = "$_"} + [pscustomobject]@{ + "M" = "$M " + "N" = "$N " + "M'" = "$($arr)" + } +} +$M1 = 'the cat sat on the mat' +$N1 = 'mat cat' +$M2 = 'the cat sat on the mat' +$N2 = 'cat mat' +$M3 = 'A B C A B C A B C' +$N3 = 'C A C A' +$M4 = 'A B C A B D A B E' +$N4 = 'E A D A' +$M5 = 'A B' +$N5 = 'B' +$M6 = 'A B' +$N6 = 'B A' +$M7 = 'A B B A' +$N7 = 'B A' +sublistsort $M1 $N1 +sublistsort $M2 $N2 +sublistsort $M3 $N3 +sublistsort $M4 $N4 +sublistsort $M5 $N5 +sublistsort $M6 $N6 +sublistsort $M7 $N7 diff --git a/Task/Order-two-numerical-lists/00DESCRIPTION b/Task/Order-two-numerical-lists/00DESCRIPTION index 60acaa9d6b..d3e246d49e 100644 --- a/Task/Order-two-numerical-lists/00DESCRIPTION +++ b/Task/Order-two-numerical-lists/00DESCRIPTION @@ -5,3 +5,5 @@ The order is determined by [[wp:Lexicographical order#Ordering of sequences of v If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. If the second list or both run out of elements the result is false. + +Note: further clarification of lexicographical ordering is expounded on the talk page [[Talk:Order_two_numerical_lists#Lexicographic_order|here]] and [[Talk:Order_two_numerical_lists#Is_the_task_statement_consistent.3F|here]]. diff --git a/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists-1.julia b/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists-1.julia new file mode 100644 index 0000000000..eea7010d86 --- /dev/null +++ b/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists-1.julia @@ -0,0 +1,14 @@ +function isallreal{T<:AbstractArray}(a::T) + all(map(x->isa(x, Real), a)) +end + +function islexfirst{T<:AbstractArray,U<:AbstractArray}(a::T, b::U) + isallreal(a) && isallreal(b) || throw(DomainError()) + for i in 1:min(length(a), length(b)) + x = a[i] + y = b[i] + x != y || continue + return x < y + end + return length(a) < length(b) +end diff --git a/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists-2.julia b/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists-2.julia new file mode 100644 index 0000000000..4f2e63ea37 --- /dev/null +++ b/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists-2.julia @@ -0,0 +1,15 @@ +tests = {[1, 2, 3], + primes(10), + 0:2:6, + [-Inf, 0.0, Inf], + [π, e, φ, catalan], + [2015, 5], + [-sqrt(50.0), 50.0^2], + } + +println("Testing islexfirst:") +for (a, b) in combinations(tests, 2) + tres = islexfirst(a, b) ? " is " : " is not " + tres *= "lexically prior to\n " + println("\n ", a, tres, b) +end diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-2.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-2.ocaml index ea0311db2a..5cc425f69b 100644 --- a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-2.ocaml +++ b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-2.ocaml @@ -1,8 +1,2 @@ -let rec ordered_lists = function - | x1::tl1, x2::tl2 -> - (match compare x1 x2 with - | 0 -> ordered_lists (tl1, tl2) - | 1 -> false - | _ -> true) - | [], _ -> true - | _ -> false +# [|1;2;1;3;2|] < [|1;2;0;4;4;0;0;0|];; +- : bool = true diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-3.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-3.ocaml index aa68337432..ea0311db2a 100644 --- a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-3.ocaml +++ b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-3.ocaml @@ -1,20 +1,8 @@ -(* copy-paste the code of ordered_lists here *) - -let make_num_list p n = - let rec aux acc = - if Random.int p = 0 then acc - else aux (Random.int n :: acc) - in - aux [] - -let print_num_list lst = - List.iter (Printf.printf " %d") lst; - print_newline() - -let () = - Random.self_init(); - let lst1 = make_num_list 8 5 in - let lst2 = make_num_list 8 5 in - print_num_list lst1; - print_num_list lst2; - Printf.printf "ordered: %B\n" (ordered_lists (lst1, lst2)) +let rec ordered_lists = function + | x1::tl1, x2::tl2 -> + (match compare x1 x2 with + | 0 -> ordered_lists (tl1, tl2) + | 1 -> false + | _ -> true) + | [], _ -> true + | _ -> false diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-4.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-4.ocaml index 5155e1f36d..aa68337432 100644 --- a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-4.ocaml +++ b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-4.ocaml @@ -1 +1,20 @@ -val ordered_lists : 'a list * 'a list -> bool +(* copy-paste the code of ordered_lists here *) + +let make_num_list p n = + let rec aux acc = + if Random.int p = 0 then acc + else aux (Random.int n :: acc) + in + aux [] + +let print_num_list lst = + List.iter (Printf.printf " %d") lst; + print_newline() + +let () = + Random.self_init(); + let lst1 = make_num_list 8 5 in + let lst2 = make_num_list 8 5 in + print_num_list lst1; + print_num_list lst2; + Printf.printf "ordered: %B\n" (ordered_lists (lst1, lst2)) diff --git a/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-5.ocaml b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-5.ocaml new file mode 100644 index 0000000000..5155e1f36d --- /dev/null +++ b/Task/Order-two-numerical-lists/OCaml/order-two-numerical-lists-5.ocaml @@ -0,0 +1 @@ +val ordered_lists : 'a list * 'a list -> bool diff --git a/Task/Order-two-numerical-lists/VBScript/order-two-numerical-lists.vb b/Task/Order-two-numerical-lists/VBScript/order-two-numerical-lists.vb new file mode 100644 index 0000000000..949685709c --- /dev/null +++ b/Task/Order-two-numerical-lists/VBScript/order-two-numerical-lists.vb @@ -0,0 +1,33 @@ +Function order_list(arr1,arr2) + order_list = "FAIL" + n1 = UBound(arr1): n2 = UBound(arr2) + n = 0 : p = 0 + If n1 > n2 Then + max = n2 + Else + max = n1 + End If + For i = 0 To max + If arr1(i) > arr2(i) Then + n = n + 1 + ElseIf arr1(i) = arr2(i) Then + p = p + 1 + End If + Next + If (n1 < n2 And n = 0) Or _ + (n1 = n2 And n = 0 And p - 1 <> n1) Or _ + (n1 > n2 And n = 0 And p = n2) Then + order_list = "PASS" + End If +End Function + +WScript.StdOut.WriteLine order_list(Array(-1),Array(0)) +WScript.StdOut.WriteLine order_list(Array(0),Array(0)) +WScript.StdOut.WriteLine order_list(Array(0),Array(-1)) +WScript.StdOut.WriteLine order_list(Array(0),Array(0,-1)) +WScript.StdOut.WriteLine order_list(Array(0),Array(0,0)) +WScript.StdOut.WriteLine order_list(Array(0),Array(0,1)) +WScript.StdOut.WriteLine order_list(Array(0,-1),Array(0)) +WScript.StdOut.WriteLine order_list(Array(0,0),Array(0)) +WScript.StdOut.WriteLine order_list(Array(0,0),Array(1)) +WScript.StdOut.WriteLine order_list(Array(1,2,1,3,2),Array(1,2,0,4,4,0,0,0)) diff --git a/Task/Ordered-words/Elixir/ordered-words.elixir b/Task/Ordered-words/Elixir/ordered-words.elixir new file mode 100644 index 0000000000..c68007c01f --- /dev/null +++ b/Task/Ordered-words/Elixir/ordered-words.elixir @@ -0,0 +1,8 @@ +File.read!("unixdict.txt") +|> String.split +|> Enum.filter(fn word -> String.codepoints(word) |> Enum.sort |> Enum.join == word end) +|> Enum.group_by(fn word -> String.length(word) end) +|> Enum.max_by(fn {length,_words} -> length end) +|> elem(1) +|> Enum.sort +|> Enum.each(fn word -> IO.puts word end) diff --git a/Task/Ordered-words/Julia/ordered-words-1.julia b/Task/Ordered-words/Julia/ordered-words-1.julia new file mode 100644 index 0000000000..5a21dccf58 --- /dev/null +++ b/Task/Ordered-words/Julia/ordered-words-1.julia @@ -0,0 +1,8 @@ +function isordered{T<:String}(w::T) + p = '\0' + for c in w + p <= c || return false + p = c + end + return true +end diff --git a/Task/Ordered-words/Julia/ordered-words-2.julia b/Task/Ordered-words/Julia/ordered-words-2.julia new file mode 100644 index 0000000000..c73bc5b2a1 --- /dev/null +++ b/Task/Ordered-words/Julia/ordered-words-2.julia @@ -0,0 +1,20 @@ +maxlen = 0 +wlst = String[] +WL = open("ordered_words.txt", "r") + +for w in eachline(WL) + w = chomp(w) + wlen = length(w) + wlen>=maxlen && isordered(w) || continue + if wlen > maxlen + maxlen = wlen + wlst = [w] + else + push!(wlst, w) + end +end +close(WL) + +for w in wlst + println(" ", w) +end diff --git a/Task/Ordered-words/REXX/ordered-words.rexx b/Task/Ordered-words/REXX/ordered-words.rexx index dd7ac6fb92..528ccaefe1 100644 --- a/Task/Ordered-words/REXX/ordered-words.rexx +++ b/Task/Ordered-words/REXX/ordered-words.rexx @@ -1,27 +1,27 @@ -/*REXX program lists (longest) ordered words from a supplied dictionary.*/ -ifid = 'UNIXDICT.TXT' /*filename of the word dictionary*/ -@.= /*placeholder for list of words. */ -mL=0 /*maximum length of ordered words*/ -call linein ifid, 1, 0 /*point to the first word in dict*/ - /* [↑] in case the file is open.*/ - do j=1 while lines(ifid)\==0 /*keep reading until exhausted. */ - x=linein(ifid); w=length(x) /*get a word and also its length.*/ - if w bool { let mut prev = '\x00'; @@ -12,12 +13,12 @@ fn is_ordered(s: &str) -> bool { return true; } -fn find_longest_ordered_words(dict: ~[&str]) -> ~[~str] { - let mut result = ~[]; +fn find_longest_ordered_words(dict: Vec) -> Vec { + let mut result = Vec::new(); let mut longest_length = 0; - for &s in dict.iter() { - if is_ordered(s) { + for s in dict.into_iter() { + if is_ordered(&s) { let n = s.len(); if n > longest_length { longest_length = n; @@ -33,12 +34,11 @@ fn find_longest_ordered_words(dict: ~[&str]) -> ~[~str] { } fn main() { - let raw = std::io::File::open(&Path::new("unixdict.txt")).read_to_end(); - let lines:~[&str] = std::str::from_utf8(raw).lines_any().collect(); + let lines = BufReader::new(File::open("unixdict.txt").unwrap()).lines().map(|l|l.unwrap()).collect(); let longest_ordered = find_longest_ordered_words(lines); for s in longest_ordered.iter() { - println(s.to_str()); + println!("{}", s.to_string()); } } diff --git a/Task/Ordered-words/VBScript/ordered-words.vb b/Task/Ordered-words/VBScript/ordered-words.vb new file mode 100644 index 0000000000..ed7c5101ff --- /dev/null +++ b/Task/Ordered-words/VBScript/ordered-words.vb @@ -0,0 +1,34 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") +Set infile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) & "\" &_ + "unixdict.txt",1) +list = "" +length = 0 + +Do Until inFile.AtEndOfStream + line = infile.ReadLine + If IsOrdered(line) Then + If Len(line) > length Then + length = Len(line) + list = line & vbCrLf + ElseIf Len(line) = length Then + list = list & line & vbCrLf + End If + End If +Loop + +WScript.StdOut.Write list + +Function IsOrdered(word) + IsOrdered = True + prev_val = 0 + For i = 1 To Len(word) + If i = 1 Then + prev_val = Asc(Mid(word,i,1)) + ElseIf Asc(Mid(word,i,1)) >= prev_val Then + prev_val = Asc(Mid(word,i,1)) + Else + IsOrdered = False + Exit For + End If + Next +End Function diff --git a/Task/Palindrome-detection/Dart/palindrome-detection.dart b/Task/Palindrome-detection/Dart/palindrome-detection.dart new file mode 100644 index 0000000000..4a7c1e7509 --- /dev/null +++ b/Task/Palindrome-detection/Dart/palindrome-detection.dart @@ -0,0 +1,7 @@ +bool isPolindrome(String s){ + for(int i = 0; i < s.length/2;i++){ + if(s[i] != s[(s.length-1) -i]) + return false; + } + return true; +} diff --git a/Task/Palindrome-detection/Ela/palindrome-detection-1.ela b/Task/Palindrome-detection/Ela/palindrome-detection-1.ela index c4076aee14..4019a9ebf7 100644 --- a/Task/Palindrome-detection/Ela/palindrome-detection-1.ela +++ b/Task/Palindrome-detection/Ela/palindrome-detection-1.ela @@ -1,4 +1,4 @@ open list string isPalindrome xs = xs == reverse xs -isPalindrome <| string.toList "ingirumimusnocteetconsumimurigni" +isPalindrome <| toList "ingirumimusnocteetconsumimurigni" diff --git a/Task/Palindrome-detection/GML/palindrome-detection.gml b/Task/Palindrome-detection/GML/palindrome-detection-1.gml similarity index 100% rename from Task/Palindrome-detection/GML/palindrome-detection.gml rename to Task/Palindrome-detection/GML/palindrome-detection-1.gml diff --git a/Task/Palindrome-detection/GML/palindrome-detection-2.gml b/Task/Palindrome-detection/GML/palindrome-detection-2.gml new file mode 100644 index 0000000000..888a8e882d --- /dev/null +++ b/Task/Palindrome-detection/GML/palindrome-detection-2.gml @@ -0,0 +1,10 @@ +//Remove everything except for letters and digits and convert the string to lowercase. source is what will be compared to str. +var str = string_lower(string_lettersdigits(string_replace(argument0," ",""))), source = ""; + +//Loop through and store each character of str in source. +for (var i = string_length(str); i > 0; i--) { + source += string_char_at(str,i); +} + +//Return if it is a palindrome. +return source == str; diff --git a/Task/Palindrome-detection/JavaScript/palindrome-detection-1.js b/Task/Palindrome-detection/JavaScript/palindrome-detection-1.js index 6cff555cd5..f66de94f99 100644 --- a/Task/Palindrome-detection/JavaScript/palindrome-detection-1.js +++ b/Task/Palindrome-detection/JavaScript/palindrome-detection-1.js @@ -1,9 +1,5 @@ -function reverseString(str){ - return str.split("").reverse().join(""); -} - function isPalindrome(str) { - return str == reverseString(str); + return str === str.split("").reverse().join(""); } -alert(isPalindrome("ingirumimusnocteetconsumimurigni")); +console.log(isPalindrome("ingirumimusnocteetconsumimurigni")); diff --git a/Task/Palindrome-detection/JavaScript/palindrome-detection-2.js b/Task/Palindrome-detection/JavaScript/palindrome-detection-2.js index dbc200473b..53322310c1 100644 --- a/Task/Palindrome-detection/JavaScript/palindrome-detection-2.js +++ b/Task/Palindrome-detection/JavaScript/palindrome-detection-2.js @@ -1,17 +1 @@ -function reverseStr(s) { - var i, o = ''; - for (i = s.length - 1; i >= 0; o += s[i--]); - return o; -}; - -function isPalindrome(str) { - var s = str.toLowerCase().replace(/[^a-z]/g, ''); - return (reverseStr(s) === s); -}; - -isPalindrome('A man, a plan, a canoe, pasta, heros, rajahs, ' + - 'a coloratura, maps, snipe, percale, macaroni, ' + - 'a gag, a banana bag, a tan, a tag, ' + - 'a banana bag again (or a camel), a crepe, pins, ' + - 'Spam, a rut, a Rolo, cash, a jar, sore hats, ' + - 'a peon, a canal – Panama!'); +var isPal = str => str === str.split("").reverse().join(""); diff --git a/Task/Palindrome-detection/NewLISP/palindrome-detection.newlisp b/Task/Palindrome-detection/NewLISP/palindrome-detection.newlisp new file mode 100644 index 0000000000..2ea9a6d630 --- /dev/null +++ b/Task/Palindrome-detection/NewLISP/palindrome-detection.newlisp @@ -0,0 +1,4 @@ +(define (palindrome? s) + (setq r s) + (reverse r) ; Reverse is destructive. + (= s r)) diff --git a/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx b/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx index fd37c2b663..91eef6a4da 100644 --- a/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx +++ b/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx @@ -1,21 +1,12 @@ -/*REXX pgm checks if phrase is palindromic; ignores blanks, case, punct.*/ -parse arg y /*get (optional) phrase from C.L.*/ - -if y='' then y='In girum imus nocte et consumimur igni.' /*[↓] translation.*/ +/*REXX pgm checks if phrase is palindromic; ignores the case of the letters. */ +parse arg y /*get (optional) phrase from the C.L. */ +if y='' then y='In girum imus nocte et consumimur igni' /*[↓] translation.*/ /*We walk around in the night and we are burnt by the fire (of love).*/ - say 'string = ' y -say -if isPal(y) then say 'The string is palindromic.' - else say "The string isn't palindromic." -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ISPAL subroutine────────────────────*/ -isPal: procedure; arg x; z= /*uppercases the value of arg X.*/ - - do j=1 for length(x) /*process the whole of the string*/ - _=substr(x,j,1) /*extract just a single character*/ - if datatype(_,'U') then z=z || _ /*Letter? Then append it to Z. */ - end /*j*/ - -return z==reverse(z) /*returns 1 if exactly equal, */ - /* " 0 if not equal. */ +if isTpal(y) then say 'The string is a true palindrome.' + else if isPal(y) then say 'The string is an inexact palindrome.' + else say "The string isn't palindromic." +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +isTpal: return reverse(arg(1))==arg(1) +isPal: return isTpal(translate(space(x,0))) diff --git a/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx b/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx index 7791016fa2..2290bc48c9 100644 --- a/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx +++ b/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx @@ -1,23 +1,12 @@ -/*REXX pgm checks if phrase is palindromic; ignores blanks, case, punct.*/ -parse arg y /*get (optional) phrase from C.L.*/ - -if y='' then y='In girum imus nocte et consumimur igni.' /*[↓] translation.*/ - /*We walk around in the night and we are burnt by the fire (of love).*/ - -say 'string = ' y -say -if isPal(y) then say 'The string is palindromic.' - else say "The string isn't palindromic." -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ISPAL subroutine────────────────────*/ -isPal: procedure; arg x; z= /*uppercases the value of arg X.*/ - /* [↓] more letters from ··· */ -$='ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜáíóúñÑαßΓπΣσµτΦΘΩδφε' /*··· codepage 437.*/ - - do j=1 for length(x) /*process the whole of the string*/ - _=substr(x,j,1) /*extract just a single character*/ - if datatype(_,'U') | pos(_,$)\==0 then z=z||_ /*append if letter.*/ - end /*j*/ - -return z==reverse(z) /*returns 1 if exactly equal, */ - /* " 0 if not equal. */ +/*Check whether a string is a palindrome */ +parse pull string +select + when palindrome(string) then say string 'is an exact palindrome.' + when palindrome(compress(upper(string))) then say string 'is an inexact palindrome.' + otherwise say string 'is not palindromic.' + end +exit 0 + +palindrome: procedure +parse arg string +return string==reverse(string) diff --git a/Task/Pangram-checker/360-Assembly/pangram-checker.360 b/Task/Pangram-checker/360-Assembly/pangram-checker.360 new file mode 100644 index 0000000000..449a14f95d --- /dev/null +++ b/Task/Pangram-checker/360-Assembly/pangram-checker.360 @@ -0,0 +1,38 @@ +* Pangram RC 11/08/2015 +PANGRAM CSECT + USING PANGRAM,R12 + LR R12,R15 +BEGIN LA R9,SENTENCE + LA R6,4 +LOOPI LA R10,ALPHABET loop on sentences + LA R7,26 +LOOPJ LA R5,0 loop on letters + LR R11,R9 + LA R8,60 +LOOPK MVC BUFFER+1(1),0(R10) loop in sentence + CLC 0(1,R10),0(R11) if alphabet[j=sentence[i] + BNE NEXTK + LA R5,1 found +NEXTK LA R11,1(R11) next character + BCT R8,LOOPK + LTR R5,R5 if found + BNZ NEXTJ + MVI BUFFER,C'?' not found + B PRINT +NEXTJ LA R10,1(R10) next letter + BCT R7,LOOPJ + MVC BUFFER(2),=CL2'OK' +PRINT MVC BUFFER+3(60),0(R9) + XPRNT BUFFER,80 +NEXTI LA R9,60(R9) next sentence + BCT R6,LOOPI +RETURN XR R15,R15 + BR R14 +ALPHABET DC CL26'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +SENTENCE DC CL60'THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.' + DC CL60'THE FIVE BOXING WIZARDS DUMP QUICKLY.' + DC CL60'HEAVY BOXES PERFORM WALTZES AND JIGS.' + DC CL60'PACK MY BOX WITH FIVE DOZEN LIQUOR JUGS.' +BUFFER DC CL80' ' + YREGS + END PANGRAM diff --git a/Task/Pangram-checker/Batch-File/pangram-checker.bat b/Task/Pangram-checker/Batch-File/pangram-checker.bat new file mode 100644 index 0000000000..6f54f583d1 --- /dev/null +++ b/Task/Pangram-checker/Batch-File/pangram-checker.bat @@ -0,0 +1,30 @@ +@echo off +setlocal enabledelayedexpansion + + %===The Main Thing===% +call :pangram "The quick brown fox jumps over the lazy dog." +call :pangram "The quick brown fox jumped over the lazy dog." +echo. +pause +exit /b 0 + + %===The Function===% +:pangram +set letters=abcdefgihjklmnopqrstuvwxyz +set cnt=0 +set inp=%~1 +set str=!inp: =! + +:loop +set chr=!str:~%cnt%,1! +if "!letters!"=="" ( + echo %1 is a pangram^^! + goto :EOF +) +if "!chr!"=="" ( + echo %1 is not a pangram. + goto :EOF +) +set letters=!letters:%chr%=! +set /a cnt+=1 +goto loop diff --git a/Task/Pangram-checker/Elixir/pangram-checker.elixir b/Task/Pangram-checker/Elixir/pangram-checker.elixir new file mode 100644 index 0000000000..65849d18f2 --- /dev/null +++ b/Task/Pangram-checker/Elixir/pangram-checker.elixir @@ -0,0 +1,11 @@ +defmodule Pangram do + def checker(str) do + unused = Enum.to_list(?a..?z) -- to_char_list(String.downcase(str)) + Enum.empty?(unused) + end +end + +text = "The quick brown fox jumps over the lazy dog." +IO.puts "#{Pangram.checker(text)}\t#{text}" +text = (Enum.to_list(?A..?Z) -- 'Test') |> to_string +IO.puts "#{Pangram.checker(text)}\t#{text}" diff --git a/Task/Pangram-checker/JavaScript/pangram-checker.js b/Task/Pangram-checker/JavaScript/pangram-checker-1.js similarity index 100% rename from Task/Pangram-checker/JavaScript/pangram-checker.js rename to Task/Pangram-checker/JavaScript/pangram-checker-1.js diff --git a/Task/Pangram-checker/JavaScript/pangram-checker-2.js b/Task/Pangram-checker/JavaScript/pangram-checker-2.js new file mode 100644 index 0000000000..cbc94e2fae --- /dev/null +++ b/Task/Pangram-checker/JavaScript/pangram-checker-2.js @@ -0,0 +1,36 @@ +var _ = require("underscore"); + +// Curried mixin function +// Utility Methods +_.mixin({ + checkAToZ: function(s) { + return function(letter) { + if (s.indexOf(letter) != -1) { return true}; + } + } +}); + +_.mixin({ + toLower: function(str) { + return str.toLowerCase(); + } +}); + +_.mixin({ + isPangram: function(lstr) { + var letters = "zqxjkvbpygfwmucldrhsnioate".split(''); + return _.every(letters, _.checkAToZ(lstr)); + } +}); + + +var panGramStr = "The quick brown fox jumps over the lazy dog"; +var IsPanGram = function(panGramStr) { + return _.chain(panGramStr).toLower().isPangram().value(); +}; + +console.log("Result IsPanGram - \"", panGramStr,"\" - " , IsPanGram.call(this,panGramStr)); +console.log("Result IsPanGram - \"", "the World","\" - ", IsPanGram.call(this, "the World")); + +// Result IsPanGram - " The quick brown fox jumps over the lazy dog " - true +// Result IsPanGram - " the World " - false diff --git a/Task/Pangram-checker/Julia/pangram-checker.julia b/Task/Pangram-checker/Julia/pangram-checker.julia new file mode 100644 index 0000000000..99de27e99e --- /dev/null +++ b/Task/Pangram-checker/Julia/pangram-checker.julia @@ -0,0 +1,25 @@ +function makepangramchecker{T<:String}(a::T) + abet = sort(unique(split(uppercase(a), ""))) + alen = length(abet) + function ispangram{T<:String}(s::T) + alen <= length(s) || return false + ps = filter(c->(c in abet), unique(split(uppercase(s), ""))) + return length(ps) == alen + end +end + +tests = ["Pack my box with five dozen liquor jugs.", + "The quick brown fox jumps over a lazy dog.", + "The quick brown fox jumps\u2323over the lazy dog.", + "The five boxing wizards jump quickly.", + "This sentence contains A-Z but not the whole alphabet."] + +isenglishpang = makepangramchecker("abcdefghijklmnopqrstuvwxyz") + +for s in tests + print("The sentence \"", s, "\" is ") + if !isenglishpang(s) + print("not ") + end + println("a pangram.") +end diff --git a/Task/Pangram-checker/Mathematica/pangram-checker.math b/Task/Pangram-checker/Mathematica/pangram-checker-1.math similarity index 100% rename from Task/Pangram-checker/Mathematica/pangram-checker.math rename to Task/Pangram-checker/Mathematica/pangram-checker-1.math diff --git a/Task/Pangram-checker/Mathematica/pangram-checker-2.math b/Task/Pangram-checker/Mathematica/pangram-checker-2.math new file mode 100644 index 0000000000..df3c8a90ef --- /dev/null +++ b/Task/Pangram-checker/Mathematica/pangram-checker-2.math @@ -0,0 +1,5 @@ +pangramQ[msg_] := + Function[If[# === {}, Print["The string is a pangram!"], + Print["The string is not a pangram. It's missing the letters " <> + ToString[#]]]][ + Complement[CharacterRange["a", "z"], Characters[ToLowerCase[msg]]]] diff --git a/Task/Pangram-checker/REXX/pangram-checker.rexx b/Task/Pangram-checker/REXX/pangram-checker.rexx index 80e9c1a15c..ba981090bf 100644 --- a/Task/Pangram-checker/REXX/pangram-checker.rexx +++ b/Task/Pangram-checker/REXX/pangram-checker.rexx @@ -1,16 +1,16 @@ -/*REXX program to check if an entered string (sentence) is a pangram. */ -abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +/*REXX program checks to see if an entered string (sentence) is a pangram. */ +@abc = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*a list of all (Latin) capital letters*/ - do forever /*keep prompting until a null or blank(s). */ - say; say '───── Please enter a pangramic sentence:'; say - pull y /*this also uppercases the Y variable. */ - if y='' then leave /*if nothing entered, then we're done. */ - ?=verify(abc,y) /*see if all (Latin) letters are present. */ + do forever; say /*keep promoting 'til null (or blanks).*/ + say '───── Please enter a pangramic sentence:'; say + pull y /*this also uppercases the Y variable.*/ + if y='' then leave /*if nothing entered, then we're done.*/ + ?=verify(@abc,y) /*Are all the (Latin) letters present? */ - if ?==0 then say 'Sentence is a pangram.' - else say "Sentence isn't a pangram, missing:" substr(abc,?,1) + if ?==0 then say 'Sentence is a pangram.' + else say "Sentence isn't a pangram, missing:" substr(@abc,?,1) say end /*forever*/ say '───── PANGRAM program ended. ─────' - /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Pangram-checker/TI-83-BASIC/pangram-checker.ti-83 b/Task/Pangram-checker/TI-83-BASIC/pangram-checker.ti-83 new file mode 100644 index 0000000000..28249da63d --- /dev/null +++ b/Task/Pangram-checker/TI-83-BASIC/pangram-checker.ti-83 @@ -0,0 +1,7 @@ +:Prompt Str1 +:For(L,1,26 +:If not(inString(Str1,sub("ABCDEFGHIJKLMNOPQRSTUVWXYZ",L,1)) +:L=28 +:End +:If L<28 +:Disp "IS A PANGRAM" diff --git a/Task/Pangram-checker/Tcl/pangram-checker.tcl b/Task/Pangram-checker/Tcl/pangram-checker.tcl index 2a81912bf7..a2f5bd52e0 100644 --- a/Task/Pangram-checker/Tcl/pangram-checker.tcl +++ b/Task/Pangram-checker/Tcl/pangram-checker.tcl @@ -4,6 +4,5 @@ proc pangram? {sentence} { [llength [lsort -unique $letters]] == 26 } } - puts [pangram? "This is a sentence"]; # ==> false puts [pangram? "The quick brown fox jumps over the lazy dog."]; # ==> true diff --git a/Task/Paraffins/Haskell/paraffins-1.hs b/Task/Paraffins/Haskell/paraffins-1.hs new file mode 100644 index 0000000000..ccedb67c94 --- /dev/null +++ b/Task/Paraffins/Haskell/paraffins-1.hs @@ -0,0 +1,44 @@ +-- polynomial utils +a `nmul` n = map (*n) a +a `ndiv` n = map (`div` n) a + +instance (Integral a) => Num [a] where + (+) = zipWith (+) + negate = map negate + a * b = foldr f undefined b where + f x z = (a `nmul` x) + (0 : z) + abs _ = undefined + signum _ = undefined + fromInteger n = fromInteger n : repeat 0 + +-- replace x in polynomial with x^n +repl a n = concatMap (: replicate (n-1) 0) a + +-- S2: (a^2 + b)/2 +cycleIndexS2 a b = (a*a + b)`ndiv` 2 + +-- S4: (a^4 + 6 a^2 b + 8 a c + 3 b^2 + 6 d) / 24 +cycleIndexS4 a b c d = ((a ^ 4) + + (a ^ 2 * b) `nmul` 6 + + (a * c) `nmul` 8 + + (b ^ 2) `nmul` 3 + + d `nmul` 6) `ndiv` 24 + + +a598 = x1 +-- A000598: A(x) = 1 + (1/6)*x*(A(x)^3 + 3*A(x)*A(x^2) + 2*A(x^3)) +x1 = 1 : ((x1^3) + ((x2*x1)`nmul` 3) + (x3`nmul`2)) `ndiv` 6 +x2 = x1`repl`2 +x3 = x1`repl`3 +x4 = x1`repl`4 + +-- A000678 = x CycleIndex(S4, A000598(x)) +a678 = 0 : cycleIndexS4 x1 x2 x3 x4 + +-- A000599 = CycleIndex(S2, A000598(x) - 1) +a599 = cycleIndexS2 (0 : tail x1) (0 : tail x2) + +-- A000602 = A000678(x) - A000599(x) + A000599(x^2) +a602 = a678 - a599 + x2 + +main = mapM_ print $ take 200 $ zip [0 ..] a602 diff --git a/Task/Paraffins/Haskell/paraffins.hs b/Task/Paraffins/Haskell/paraffins-2.hs similarity index 100% rename from Task/Paraffins/Haskell/paraffins.hs rename to Task/Paraffins/Haskell/paraffins-2.hs diff --git a/Task/Paraffins/Python/paraffins.py b/Task/Paraffins/Python/paraffins-1.py similarity index 100% rename from Task/Paraffins/Python/paraffins.py rename to Task/Paraffins/Python/paraffins-1.py diff --git a/Task/Paraffins/Python/paraffins-2.py b/Task/Paraffins/Python/paraffins-2.py new file mode 100644 index 0000000000..e80d359283 --- /dev/null +++ b/Task/Paraffins/Python/paraffins-2.py @@ -0,0 +1,113 @@ +from itertools import count, chain, tee, islice, cycle +from fractions import Fraction +from sys import setrecursionlimit +setrecursionlimit(5000) + +def frac(a,b): return a//b if a%b == 0 else Fraction(a,b) + +# infinite polynomial class +class Poly: + def __init__(self, gen = None): + self.gen, self.source = (None, gen) if type(gen) is Poly \ + else (gen, None) + + def __iter__(self): + # We're essentially tee'ing it everytime the iterator + # is, well, iterated. This may be excessive. + return Poly(self) + + def getsource(self): + if self.gen == None: + s = self.source + s.getsource() + s.gen, self.gen = tee(s.gen, 2) + + def next(self): + self.getsource() + return next(self.gen) + + __next__ = next + + # Overload "<<" as stream input operator. Hey, C++ does it. + def __lshift__(self, a): self.gen = a + + # The other operators are pretty much what one would expect + def __neg__(self): return Poly(-x for x in self) + + def __sub__(a, b): return a + (-b) + + def __rsub__(a, n): + a = Poly(a) + def gen(): + yield(n - next(a)) + for x in a: yield(-x) + return Poly(gen()) + + def __add__(a, b): + if type(b) is Poly: + return Poly(x + y for (x,y) in zip(a,b)) + + a = Poly(a) + def gen(): + yield(next(a) + b) + for x in a: yield(x) + + return Poly(gen()) + + def __radd__(a,b): + return a + b + + def __mul__(a,b): + if not type(b) is Poly: + return Poly(x*b for x in a) + + def gen(): + s = Poly(cycle([0])) + for y in b: + s += y*a + yield(next(s)) + + return Poly(gen()) + + def __rmul__(a,b): return a*b + + def __truediv__(a,b): + if not type(b) is Poly: + return Poly(frac(x, b) for x in a) + + a, b = Poly(a), Poly(b) + def gen(): + r, bb = a,next(b) + while True: + aa = next(r) + q = frac(aa, bb) + yield(q) + r -= q*b + + return Poly(gen()) + + def repl(self, n): + def gen(): + for x in self: + yield(x) + for i in range(n-1): yield(0) + return Poly(gen()) + + def __pow__(self, n): + return Poly(self) if n == 1 else self * self**(n-1) + +def S2(a,b): return (a*a + b)/2 +def S4(a,b,c,d): return a**4/24 + a**2*b/4 + a*c/3 + b**2/8 + d/4 + +x1 = Poly() +x2 = x1.repl(2) +x3 = x1.repl(3) +x4 = x1.repl(4) +x1 << chain([1], (x1**3 + 3*x1*x2 + 2*x3)/6) + +a598 = x1 +a678 = Poly(chain([0], S4(x1, x2, x3, x4))) +a599 = S2(x1 - 1, x2 - 1) +a602 = a678 - a599 + x2 + +for n,x in zip(count(0), islice(a602, 500)): print(n,x) diff --git a/Task/Parallel-calculations/Common-Lisp/parallel-calculations-1.lisp b/Task/Parallel-calculations/Common-Lisp/parallel-calculations-1.lisp new file mode 100644 index 0000000000..93127ce60a --- /dev/null +++ b/Task/Parallel-calculations/Common-Lisp/parallel-calculations-1.lisp @@ -0,0 +1,25 @@ +(ql:quickload '(lparallel)) + +(setf lparallel:*kernel* (lparallel:make-kernel 4)) ;; Configure for your system. + +(defun factor (n &optional (acc '())) + (when (> n 1) + (loop with max-d = (isqrt n) + for d = 2 then (if (evenp d) (1+ d) (+ d 2)) do + (cond ((> d max-d) (return (cons (list n 1) acc))) + ((zerop (rem n d)) + (return (factor (truncate n d) + (if (eq d (caar acc)) + (cons + (list (caar acc) (1+ (cadar acc))) + (cdr acc)) + (cons (list d 1) acc))))))))) + +(defun max-minimum-factor (numbers) + (lparallel:pmap-reduce + (lambda (n) (cons n (apply #'min (mapcar #'car (factor n))))) + (lambda (a b) (if (> (cdr a) (cdr b)) a b)) + numbers)) + +(defun print-max-factor (pair) + (format t "~a has the largest miniumum factor ~a~%" (car pair) (cdr pair))) diff --git a/Task/Parallel-calculations/Common-Lisp/parallel-calculations-2.lisp b/Task/Parallel-calculations/Common-Lisp/parallel-calculations-2.lisp new file mode 100644 index 0000000000..86ff502bc4 --- /dev/null +++ b/Task/Parallel-calculations/Common-Lisp/parallel-calculations-2.lisp @@ -0,0 +1,2 @@ +CL-USER> (print-max-factor (max-minimum-factor '(12757923 12878611 12878893 12757923 15808973 15780709 197622519))) +12878893 has the largest miniumum factor 47 diff --git a/Task/Parametric-polymorphism/Objective-C/parametric-polymorphism.m b/Task/Parametric-polymorphism/Objective-C/parametric-polymorphism.m new file mode 100644 index 0000000000..eee805078a --- /dev/null +++ b/Task/Parametric-polymorphism/Objective-C/parametric-polymorphism.m @@ -0,0 +1,16 @@ +@interface Tree : NSObject { + T value; + Tree *left; + Tree *right; +} + +- (void)replaceAll:(T)v; +@end + +@implementation Tree +- (void)replaceAll:(id)v { + value = v; + [left replaceAll:v]; + [right replaceAll:v]; +} +@end diff --git a/Task/Parametric-polymorphism/Rust/parametric-polymorphism.rust b/Task/Parametric-polymorphism/Rust/parametric-polymorphism.rust index c0979ba65c..b8bad93171 100644 --- a/Task/Parametric-polymorphism/Rust/parametric-polymorphism.rust +++ b/Task/Parametric-polymorphism/Rust/parametric-polymorphism.rust @@ -5,38 +5,42 @@ struct TreeNode { } impl TreeNode { - fn my_map(&self, f: |t: &T| -> U) -> TreeNode { - TreeNode{value: f(&self.value), - left: - match self.left { - None => None, - Some(ref n) => Some(box() n.my_map(|n| f(n))), - }, - right: - match self.right { - None => None, - Some(ref n) => Some(box() n.my_map(|n| f(n))), - },} + fn my_map(&self, f: &F) -> TreeNode where + F: Fn(&T) -> U { + TreeNode { + value: f(&self.value), + left: match self.left { + None => None, + Some(ref n) => Some(Box::new(n.my_map(f))), + }, + right: match self.right { + None => None, + Some(ref n) => Some(Box::new(n.my_map(f))), + }, + } } } fn main() { - let root = - TreeNode{value: 3i, - left: - Some(box() TreeNode{value: 55i, - left: None, - right: None,}), - right: - Some(box() TreeNode{value: 234i, - left: - Some(box() TreeNode{value: 0i, - left: None, - right: - None,}), - right: None,}),}; - root.my_map(|x| { println!("{}" , x)}); + let root = TreeNode { + value: 3, + left: Some(Box::new(TreeNode { + value: 55, + left: None, + right: None, + })), + right: Some(Box::new(TreeNode { + value: 234, + left: Some(Box::new(TreeNode { + value: 0, + left: None, + right: None, + })), + right: None, + })), + }; + root.my_map(&|x| { println!("{}" , x)}); println!("---------------"); - let new_root = root.my_map(|x| *x as f64 * 333.333f64); - new_root.my_map(|x| { println!("{}" , x) }); + let new_root = root.my_map(&|x| *x as f64 * 333.333f64); + new_root.my_map(&|x| { println!("{}" , x) }); } diff --git a/Task/Parametrized-SQL-statement/Clojure/parametrized-sql-statement.clj b/Task/Parametrized-SQL-statement/Clojure/parametrized-sql-statement.clj new file mode 100644 index 0000000000..dfec19f0f3 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Clojure/parametrized-sql-statement.clj @@ -0,0 +1,10 @@ +(require '[clojure.java.jdbc :as sql]) +; Using h2database for this simple example. +(def db {:classname "org.h2.Driver" + :subprotocol "h2:file" + :subname "db/my-dbname"}) + +(sql/update! db :players {:name "Smith, Steve" :score 42 :active true} ["jerseyNum = ?" 99]) + +; As an alternative to update!, use execute! +(sql/execute! db ["UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?" "Smith, Steve" 42 true 99]) diff --git a/Task/Parse-an-IP-Address/Haskell/parse-an-ip-address.hs b/Task/Parse-an-IP-Address/Haskell/parse-an-ip-address.hs new file mode 100644 index 0000000000..2dcbd683bc --- /dev/null +++ b/Task/Parse-an-IP-Address/Haskell/parse-an-ip-address.hs @@ -0,0 +1,113 @@ +import Data.List (isInfixOf) +import Numeric (showHex) +import Data.Char (isDigit) + +data IPChunk = IPv6Chunk String | IPv4Chunk (String, String) | + IPv6WithPort [IPChunk] String | IPv6NoPort [IPChunk] | + IPv4WithPort IPChunk String | IPv4NoPort IPChunk | + IPInvalid | IPZeroSection | IPUndefinedWithPort String | + IPUndefinedNoPort + +instance Show IPChunk where + show (IPv6Chunk a) = a + show (IPv4Chunk (a,b)) = a ++ b + show (IPv6WithPort a p) = "IPv6 " ++ concatMap show a ++ " port " ++ p + show (IPv6NoPort a) = "IPv6 " ++ concatMap show a ++ " no port" + show (IPv4WithPort a p) = "IPv4 " ++ show a ++ " port " ++ p + show (IPv4NoPort a) = "IPv4 " ++ show a + show IPInvalid = "Invalid IP address" + +isIPInvalid IPInvalid = True +isIPInvalid _ = False + +isIPZeroSection IPZeroSection = True +isIPZeroSection _ = False + +splitOn _ [] = [] +splitOn x xs = let (a, b) = break (== x) xs in a : splitOn x (drop 1 b) + +count x = length . filter (== x) + +between a b x = x >= a && x <= b + +none f = all (not . f) + +parse1 [] = IPInvalid +parse1 "::" = IPUndefinedNoPort +parse1 ('[':':':':':']':':':ps) = if portIsValid ps then IPUndefinedWithPort ps else IPInvalid +parse1 ('[':xs) = if "]:" `isInfixOf` xs + then let (a, b) = break (== ']') xs in + if tail b == ":" then IPInvalid else IPv6WithPort (map chunk (splitOn ':' a)) (drop 2 b) + else IPInvalid +parse1 xs + | count ':' xs <= 1 && count '.' xs == 3 = + let (a, b) = break (== ':') xs in case b of + "" -> IPv4NoPort (chunk a) + (':':ps) -> IPv4WithPort (chunk a) ps + _ -> IPInvalid + | count ':' xs > 1 && count '.' xs <= 3 = + IPv6NoPort (map chunk (splitOn ':' xs)) + +chunk [] = IPZeroSection +chunk xs + | '.' `elem` xs = case splitOn '.' xs of + [a,b,c,d] -> let [e,f,g,h] = map read [a,b,c,d] + in if all (between 0 255) [e,f,g,h] + then let [i,j,k,l] = map (\n -> fill 2 $ showHex n "") [e,f,g,h] + in IPv4Chunk (i ++ j, k ++ l) + else IPInvalid + | ':' `notElem` xs && between 1 4 (length xs) && all (`elem` "0123456789abcdef") xs = IPv6Chunk (fill 4 xs) + | otherwise = IPInvalid + +fill n xs = replicate (n - length xs) '0' ++ xs + +parse2 IPInvalid = IPInvalid +parse2 (IPUndefinedWithPort p) = IPv6WithPort (replicate 8 zeroChunk) p +parse2 IPUndefinedNoPort = IPv6NoPort (replicate 8 zeroChunk) +parse2 a = case a of + IPv6WithPort xs p -> if none isIPInvalid xs && portIsValid p + then let ys = complete xs + in if countChunks ys == 8 + then IPv6WithPort ys p + else IPInvalid + else IPInvalid + IPv6NoPort xs -> if none isIPInvalid xs + then let ys = complete xs + in if countChunks ys == 8 + then IPv6NoPort ys + else IPInvalid + else IPInvalid + IPv4WithPort (IPv4Chunk a) p -> if portIsValid p + then IPv4WithPort (IPv4Chunk a) p + else IPInvalid + IPv4NoPort (IPv4Chunk a) -> IPv4NoPort (IPv4Chunk a) + _ -> IPInvalid + +zeroChunk = IPv6Chunk "0000" + +portIsValid a = all isDigit a && between 0 65535 (read a) + +complete xs = case break isIPZeroSection xs of + (_, [IPZeroSection]) -> [] + (ys, []) -> ys + ([], (IPZeroSection:IPZeroSection:ys)) -> if any isIPZeroSection ys || countChunks ys > 7 + then [] + else replicate (8 - countChunks ys) zeroChunk ++ ys + (ys, (IPZeroSection:zs)) -> if any isIPZeroSection zs || countChunks ys + countChunks zs > 7 + then [] + else ys ++ replicate (8 - countChunks ys - countChunks zs) zeroChunk ++ zs + _ -> [] + +countChunks xs = foldl f 0 xs + where f n (IPv4Chunk _) = n + 2 + f n (IPv6Chunk _) = n + 1 + +ip = parse2 . parse1 + +main = mapM_ (putStrLn . show . ip) + ["127.0.0.1", -- loop back + "127.0.0.1:80", -- loop back +port + "::1", -- loop back + "[::1]:80", -- loop back +port + "2605:2700:0:3::4713:93e3", -- Rosetta Code + "[2605:2700:0:3::4713:93e3]:80"] -- Rosetta Code diff --git a/Task/Parse-an-IP-Address/VBScript/parse-an-ip-address.vb b/Task/Parse-an-IP-Address/VBScript/parse-an-ip-address.vb new file mode 100644 index 0000000000..83fc441ff8 --- /dev/null +++ b/Task/Parse-an-IP-Address/VBScript/parse-an-ip-address.vb @@ -0,0 +1,87 @@ +Function parse_ip(addr) + 'ipv4 pattern + Set ipv4_pattern = New RegExp + ipv4_pattern.Global = True + ipv4_pattern.Pattern = "(\d{1,3}\.){3}\d{1,3}" + 'ipv6 pattern + Set ipv6_pattern = New RegExp + ipv6_pattern.Global = True + ipv6_pattern.Pattern = "([0-9a-fA-F]{0,4}:){2}[0-9a-fA-F]{0,4}" + 'test if address is ipv4 + If ipv4_pattern.Test(addr) Then + port = Split(addr,":") + octet = Split(port(0),".") + ipv4_hex = "" + For i = 0 To UBound(octet) + If octet(i) <= 255 And octet(i) >= 0 Then + ipv4_hex = ipv4_hex & Right("0" & Hex(octet(i)),2) + Else + ipv4_hex = "Erroneous Address" + Exit For + End If + Next + parse_ip = "Test Case: " & addr & vbCrLf &_ + "Address: " & ipv4_hex & vbCrLf + If UBound(port) = 1 Then + If port(1) <= 65535 And port(1) >= 0 Then + parse_ip = parse_ip & "Port: " & port(1) & vbCrLf + Else + parse_ip = parse_ip & "Port: Invalid" & vbCrLf + End If + End If + End If + 'test if address is ipv6 + If ipv6_pattern.Test(addr) Then + parse_ip = "Test Case: " & addr & vbCrLf + port_v6 = "Port: " + ipv6_hex = "" + 'check and extract port information if any + If InStr(1,addr,"[") Then + 'extract the port + port_v6 = port_v6 & Mid(addr,InStrRev(addr,"]")+2,Len(addr)-Len(Mid(addr,1,InStrRev(addr,"]")+1))) + 'extract the address + addr = Mid(addr,InStrRev(addr,"[")+1,InStrRev(addr,"]")-(InStrRev(addr,"[")+1)) + End If + word = Split(addr,":") + word_count = 0 + For i = 0 To UBound(word) + If word(i) = "" Then + If i < UBound(word) Then + If Int((7-(i+1))/2) = 1 Then + k = 1 + ElseIf UBound(word) < 6 Then + k = Int((7-(i+1))/2) + ElseIf UBound(word) >= 6 Then + k = Int((7-(i+1))/2)-1 + End If + For j = 0 To k + ipv6_hex = ipv6_hex & "0000" + word_count = word_count + 1 + Next + Else + For j = 0 To (7-word_count) + ipv6_hex = ipv6_hex & "0000" + Next + End If + Else + ipv6_hex = ipv6_hex & Right("0000" & word(i),4) + word_count = word_count + 1 + End If + Next + parse_ip = parse_ip & "Address: " & ipv6_hex &_ + vbCrLf & port_v6 & vbCrLf + End If + 'test if the address in invalid + If ipv4_pattern.Test(addr) = False And ipv6_pattern.Test(addr) = False Then + parse_ip = "Test Case: " & addr & vbCrLf &_ + "Address: Invalid Address" & vbCrLf + End If +End Function + +'Testing the function +ip_arr = Array("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","RosettaCode") + +For n = 0 To UBound(ip_arr) + WScript.StdOut.Write parse_ip(ip_arr(n)) & vbCrLf +Next diff --git a/Task/Parsing-RPN-calculator-algorithm/JavaScript/parsing-rpn-calculator-algorithm-1.js b/Task/Parsing-RPN-calculator-algorithm/JavaScript/parsing-rpn-calculator-algorithm-1.js new file mode 100644 index 0000000000..783dd2cc04 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/JavaScript/parsing-rpn-calculator-algorithm-1.js @@ -0,0 +1,18 @@ +var e = '3 4 2 * 1 5 - 2 3 ^ ^ / +' +var s=[], e=e.split(' ') +for (var i in e) { + var t=e[i], n=+t + if (n == t) + s.push(n) + else { + var o2=s.pop(), o1=s.pop() + switch (t) { + case '+': s.push(o1+o2); break; + case '-': s.push(o1-o2); break; + case '*': s.push(o1*o2); break; + case '/': s.push(o1/o2); break; + case '^': s.push(Math.pow(o1,o2)); break; + } + } + document.write(t, ': ', s, '
') +} diff --git a/Task/Parsing-RPN-calculator-algorithm/JavaScript/parsing-rpn-calculator-algorithm-2.js b/Task/Parsing-RPN-calculator-algorithm/JavaScript/parsing-rpn-calculator-algorithm-2.js new file mode 100644 index 0000000000..37896d80ac --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/JavaScript/parsing-rpn-calculator-algorithm-2.js @@ -0,0 +1,33 @@ +var e = '3 4 2 * 1 5 - 2 3 ^ ^ / +' +eval: { + document.write(e, '
') + var s=[], e=e.split(' ') + for (var i in e) { + var t=e[i], n=+t + if (!t) continue + if (n == t) + s.push(n) + else { + if ('+-*/^'.indexOf(t) == -1) { + document.write(t, ': ', s, '
', 'Unknown operator!
') + break eval + } + if (s.length<2) { + document.write(t, ': ', s, '
', 'Insufficient operands!
') + break eval + } + var o2=s.pop(), o1=s.pop() + switch (t) { + case '+': s.push(o1+o2); break + case '-': s.push(o1-o2); break + case '*': s.push(o1*o2); break + case '/': s.push(o1/o2); break + case '^': s.push(Math.pow(o1,o2)) + } + } + document.write(t, ': ', s, '
') + } + if (s.length>1) { + document.write('Insufficient operators!
') + } +} diff --git a/Task/Parsing-RPN-calculator-algorithm/Mathematica/parsing-rpn-calculator-algorithm.math b/Task/Parsing-RPN-calculator-algorithm/Mathematica/parsing-rpn-calculator-algorithm.math new file mode 100644 index 0000000000..98d847d280 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Mathematica/parsing-rpn-calculator-algorithm.math @@ -0,0 +1,12 @@ +calc[rpn_] := + Module[{tokens = StringSplit[rpn], steps}, + steps = FoldList[ + Switch[#2, _?DigitQ, Append[#, FromDigits[#2]], "^", + Append[#[[;; -3]], #[[-2]]^#[[-1]]], "*", + Append[#[[;; -3]], #[[-2]] #[[-1]]], "/", + Append[#[[;; -3]], #[[-2]]/#[[-1]]], "+", + Append[#[[;; -3]], #[[-2]] + #[[-1]]], "-", + Append[#[[;; -3]], #[[-2]] - #[[-1]]]] &, {}, tokens][[2 ;;]]; + Grid[Transpose[{# <> ":" & /@ tokens, + StringRiffle[ToString[#, InputForm] & /@ #] & /@ steps}]]]; +Print[calc["3 4 2 * 1 5 - 2 3 ^ ^ / +"]]; diff --git a/Task/Parsing-RPN-calculator-algorithm/Perl-6/parsing-rpn-calculator-algorithm.pl6 b/Task/Parsing-RPN-calculator-algorithm/Perl-6/parsing-rpn-calculator-algorithm.pl6 index 2e9d5f4341..e3c0342f6a 100644 --- a/Task/Parsing-RPN-calculator-algorithm/Perl-6/parsing-rpn-calculator-algorithm.pl6 +++ b/Task/Parsing-RPN-calculator-algorithm/Perl-6/parsing-rpn-calculator-algorithm.pl6 @@ -2,7 +2,7 @@ my $proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +'; class RPN is Array { - method binop(&infix:) { self.push: self.pop Rop self.pop } + method binop(&op) { self.push: self.pop R[&op] self.pop } method run($p) { for $p.words { diff --git a/Task/Parsing-RPN-calculator-algorithm/Scala/parsing-rpn-calculator-algorithm.scala b/Task/Parsing-RPN-calculator-algorithm/Scala/parsing-rpn-calculator-algorithm.scala new file mode 100644 index 0000000000..212c1eac3b --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Scala/parsing-rpn-calculator-algorithm.scala @@ -0,0 +1,40 @@ +object RPN { + val PRINT_STACK_CONTENTS: Boolean = true + + def main(args: Array[String]): Unit = { + val result = evaluate("3 4 2 * 1 5 - 2 3 ^ ^ / +".split(" ").toList) + println("Answer: " + result) + } + + def evaluate(tokens: List[String]): Double = { + import scala.collection.mutable.Stack + val stack: Stack[Double] = new Stack[Double] + for (token <- tokens) { + if (isOperator(token)) token match { + case "+" => stack.push(stack.pop + stack.pop) + case "-" => val x = stack.pop; stack.push(stack.pop - x) + case "*" => stack.push(stack.pop * stack.pop) + case "/" => val x = stack.pop; stack.push(stack.pop / x) + case "^" => val x = stack.pop; stack.push(math.pow(stack.pop, x)) + case _ => throw new RuntimeException( s""""$token" is not an operator""") + } + else stack.push(token.toDouble) + + if (PRINT_STACK_CONTENTS) { + print("Input: " + token) + print(" Stack: ") + for (element <- stack.seq.reverse) print(element + " "); + println("") + } + } + + stack.pop + } + + def isOperator(token: String): Boolean = { + token match { + case "+" => true; case "-" => true; case "*" => true; case "/" => true; case "^" => true + case _ => false + } + } +} diff --git a/Task/Parsing-RPN-to-infix-conversion/ALGOL-68/parsing-rpn-to-infix-conversion.alg b/Task/Parsing-RPN-to-infix-conversion/ALGOL-68/parsing-rpn-to-infix-conversion.alg new file mode 100644 index 0000000000..a54dbdc217 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/ALGOL-68/parsing-rpn-to-infix-conversion.alg @@ -0,0 +1,231 @@ +# rpn to infix - parses an RPN expression and generates the equivalent # +# infix expression # +PROC rpn to infix = ( STRING rpn )STRING: +BEGIN + + # we parse the string backwards using recursive descent # + INT rpn pos := UPB rpn; + BOOL had error := FALSE; + + # mode to hold nodes of the parse tree # + MODE NODE = STRUCT( INT op + , UNION( REF NODE, STRING ) left + , REF NODE right + ); + + REF NODE nil node = NIL; + + + # op codes # + INT error = 1; + INT factor = 2; + INT add = 3; + INT sub = 4; + INT mul = 5; + INT div = 6; + INT pwr = 7; + + []STRING op name = ( "error", "factor", "+", "-", "*", "/", "^" ); + []BOOL right associative + = ( FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE ); + []INT priority = ( 1, 1, 2, 2, 3, 3, 4 ); + + + + # returns TRUE if we have reached the end of the rpn string, # + # FALSE otherwise # + PROC at end = BOOL: rpn pos < LWB rpn; + + # positions to the previous character, if there is one # + PROC next = VOID: rpn pos -:= 1; + + # skip spaces in the rpn string # + PROC skip spaces = VOID: + WHILE have( " " ) + DO + next + OD # skip spaces # ; + + # returns TRUE if the rpn character at rpn pos is c, # + # FALSE if the character is not c or there is no character # + # at rpn pos # + PROC have = ( CHAR c )BOOL: + IF at end + THEN + # no character at rpn pos # + FALSE + ELSE + # have a character - check it is the required one # + rpn[ rpn pos ] = c + FI # have # ; + + # gets an operand from the rpn string # + # an operand is either a number or a sub-expression # + PROC get operand = ( STRING rpn, STRING operand name )REF NODE: + BEGIN + + # handle the operator or operand, if there is one # + + skip spaces; + + print( ( ( "parsing " + + operand name + + " from: " + + IF at end THEN "" ELSE rpn[ LWB rpn : rpn pos ] FI + ) + , newline + ) + ); + + REF NODE result := + IF at end + THEN + # no operand # + had error := TRUE; + HEAP NODE := ( error, "!! Missing operand !!", NIL ) + ELIF have( "+" ) + THEN + # addition # + next; + HEAP NODE right := get operand( rpn, "+ right operand" ); + HEAP NODE left := get operand( rpn, "+ left operand" ); + HEAP NODE := ( add, left, right ) + ELIF have( "-" ) + THEN + # subtraction # + next; + HEAP NODE right := get operand( rpn, "- right operand" ); + HEAP NODE left := get operand( rpn, "- left operand" ); + HEAP NODE := ( sub, left, right ) + ELIF have( "*" ) + THEN + # multiplication # + next; + HEAP NODE right := get operand( rpn, "* right operand" ); + HEAP NODE left := get operand( rpn, "* left operand" ); + HEAP NODE := ( mul, left, right ) + ELIF have( "/" ) + THEN + # division # + next; + HEAP NODE right := get operand( rpn, "/ right operand" ); + HEAP NODE left := get operand( rpn, "/ left operand" ); + HEAP NODE := ( div, left, right ) + ELIF have( "^" ) + THEN + # exponentiation # + next; + HEAP NODE right := get operand( rpn, "^ right operand" ); + HEAP NODE left := get operand( rpn, "^ left operand" ); + HEAP NODE := ( pwr, left, right ) + ELSE + # must be an operand # + STRING value := ""; + + WHILE NOT at end + AND NOT have( " " ) + DO + rpn[ rpn pos ] +=: value; + next + OD; + + HEAP NODE := ( factor, value, NIL ) + FI; + + print( ( operand name + ": " + TOSTRING result, newline ) ); + + result + END # get operand # ; + + + # converts the parse tree to a string with apppropriate parenthesis # + OP TOSTRING = ( REF NODE operand )STRING: + BEGIN + + # converts a node of the parse tree to a string, inserting # + # parenthesis if necessary # + PROC possible parenthesis = ( INT op, REF NODE expr )STRING: + IF op OF expr = error + OR op OF expr = factor + THEN + # operand is an error/factor - parenthisis not needed # + TOSTRING expr + ELIF priority( op OF expr ) < priority( op ) + THEN + # the expression is a higher precedence operator than the # + # one we are building the expression for - need parenthesis # + ( "( " + TOSTRING expr + " )" ) + ELIF right associative[ op OF operand ] + AND op OF left( operand ) = op OF operand + THEN + # right associative operator # + ( "( " + TOSTRING expr + " )" ) + ELSE + # lower precedence expression - parenthesis not needed # + TOSTRING expr + FI # possible parenthesis # ; + + # gets the left branch of a node, which must be a node # + PROC left = ( REF NODE operand )REF NODE: + CASE left OF operand + IN ( REF NODE o ): o + , ( STRING s ): HEAP NODE := ( error, s, NIL ) + ESAC # left # ; + + IF had error + THEN + # an error occured parsing the expression # + "Invalid expression" + ELIF operand IS nil node + THEN + # no operand? # + "" + ELIF op OF operand = error + OR op OF operand = factor + THEN + # error parsing the expression # + # or a factor # + CASE left OF operand + IN ( REF NODE o ): "Error: String expected: (" + TOSTRING o + ")" + , ( STRING s ): s + ESAC + ELSE + # general operand # + ( possible parenthesis( op OF operand, left( operand ) ) + + " " + op name[ op OF operand ] + " " + + possible parenthesis( op OF operand, right OF operand ) + ) + FI + END # TOSTRING # ; + + STRING result = TOSTRING get operand( rpn, "expression" ); + + # ensure there are no more tokens in the string # + skip spaces; + IF at end + THEN + # OK - there was only one expression # + result + ELSE + # extraneous tokens # + ( "Error - unexpected text before expression: (" + + rpn[ LWB rpn : rpn pos ] + + ")" + ) + FI +END # rpn to infix # ; + + + +main: ( + + # test the RPN to Infix comnverter # + STRING rpn; + + rpn := "3 4 2 * 1 5 - 2 3 ^ ^ / +"; + print( ( rpn, ": ", rpn to infix( rpn ), newline, newline ) ); + + rpn := "1 2 + 3 4 + ^ 5 6 + ^"; + print( ( rpn, ": ", rpn to infix( rpn ), newline ) ) + +) diff --git a/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp b/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp new file mode 100644 index 0000000000..b2eb5a992b --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp @@ -0,0 +1,78 @@ +#include +#include +#include +#include +#include + +using namespace std; + +struct Entry_ +{ + string expr_; + string op_; +}; + +bool PrecedenceLess(const string& lhs, const string& rhs, bool assoc) +{ + static const map KNOWN({ { "+", 1 }, { "-", 1 }, { "*", 2 }, { "/", 2 }, { "^", 3 } }); + static const set ASSOCIATIVE({ "+", "*" }); + return (KNOWN.count(lhs) ? KNOWN.find(lhs)->second : 0) < (KNOWN.count(rhs) ? KNOWN.find(rhs)->second : 0) + (assoc && !ASSOCIATIVE.count(rhs) ? 1 : 0); +} +void Parenthesize(Entry_* old, const string& token, bool assoc) +{ + if (!old->op_.empty() && PrecedenceLess(old->op_, token, assoc)) + old->expr_ = '(' + old->expr_ + ')'; +} + +void AddToken(stack* stack, const string& token) +{ + if (token.find_first_of("0123456789") != string::npos) + stack->push(Entry_({ token, string() })); // it's a number, no operator + else + { // it's an operator + if (stack->size() < 2) + throw exception("Stack underflow"); + auto rhs = stack->top(); + Parenthesize(&rhs, token, false); + stack->pop(); + auto lhs = stack->top(); + Parenthesize(&lhs, token, true); + stack->top().expr_ = lhs.expr_ + ' ' + token + ' ' + rhs.expr_; + stack->top().op_ = token; + } +} + + +string ToInfix(const string& src) +{ + stack stack; + for (auto start = src.begin(), p = src.begin(); ; ++p) + { + if (p == src.end() || *p == ' ') + { + if (p > start) + AddToken(&stack, string(start, p)); + if (p == src.end()) + break; + start = p + 1; + } + } + if (stack.size() != 1) + throw exception("Incomplete expression"); + return stack.top().expr_; +} + +int main(void) +{ + try + { + cout << ToInfix("3 4 2 * 1 5 - 2 3 ^ ^ / +") << "\n"; + cout << ToInfix("1 2 + 3 4 + ^ 5 6 + ^") << "\n"; + return 0; + } + catch (...) + { + cout << "Failed\n"; + return -1; + } +} diff --git a/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java b/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java index 52fcd3111d..ef4e19f0b2 100644 --- a/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java +++ b/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java @@ -35,7 +35,7 @@ public String toString() { Stack expr = new Stack<>(); - for (String token : postfix.split("\\s")) { + for (String token : postfix.split("\\s+")) { char c = token.charAt(0); int idx = Expression.ops.indexOf(c); if (idx != -1 && token.length() == 1) { diff --git a/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java b/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java index 52ff0e667b..f7ebb06ee7 100644 --- a/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java +++ b/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java @@ -14,11 +14,16 @@ static String infixToPostfix(String infix) { Stack s = new Stack<>(); for (String token : infix.split("\\s")) { + if (token.isEmpty()) + continue; char c = token.charAt(0); int idx = ops.indexOf(c); - if (idx != -1 && token.length() == 1) { + + // check for operator + if (idx != -1) { if (s.isEmpty()) s.push(idx); + else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; @@ -29,13 +34,17 @@ static String infixToPostfix(String infix) { } s.push(idx); } - } else if (c == '(') { - s.push(-2); - } else if (c == ')') { + } + else if (c == '(') { + s.push(-2); // -2 stands for '(' + } + else if (c == ')') { + // until '(' on stack, pop operators. while (s.peek() != -2) sb.append(ops.charAt(s.pop())).append(' '); s.pop(); - } else { + } + else { sb.append(token).append(' '); } } diff --git a/Task/Parsing-Shunting-yard-algorithm/Mathematica/parsing-shunting-yard-algorithm.math b/Task/Parsing-Shunting-yard-algorithm/Mathematica/parsing-shunting-yard-algorithm.math new file mode 100644 index 0000000000..c3159f8267 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Mathematica/parsing-shunting-yard-algorithm.math @@ -0,0 +1,32 @@ +rpn[str_] := + StringRiffle[ + ToString /@ + Module[{in = StringSplit[str], stack = {}, out = {}, next}, + While[in != {}, next = in[[1]]; in = in[[2 ;;]]; + Which[DigitQ[next], AppendTo[out, next], LetterQ[next], + AppendTo[stack, next], next == ",", + While[stack[[-1]] != "(", AppendTo[out, stack[[-1]]]; + stack = stack[[;; -2]]], next == "^", AppendTo[stack, "^"], + next == "*", + While[stack != {} && MatchQ[stack[[-1]], "^" | "*" | "/"], + AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]]; + AppendTo[stack, "*"], next == "/", + While[stack != {} && MatchQ[stack[[-1]], "^" | "*" | "/"], + AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]]; + AppendTo[stack, "/"], next == "+", + While[stack != {} && + MatchQ[stack[[-1]], "^" | "*" | "/" | "+" | "-"], + AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]]; + AppendTo[stack, "+"], next == "-", + While[stack != {} && + MatchQ[stack[[-1]], "^" | "*" | "/" | "+" | "-"], + AppendTo[out, stack[[-1]]]; stack = stack[[;; -2]]]; + AppendTo[stack, "-"], next == "(", AppendTo[stack, "("], + next == ")", + While[stack[[-1]] =!= "(", AppendTo[out, stack[[-1]]]; + stack = stack[[;; -2]]]; stack = stack[[;; -2]]; + If[StringQ[stack[[-1]]], AppendTo[out, stack[[-1]]]; + stack = stack[[;; -2]]]]]; + While[stack != {}, AppendTo[out, stack[[-1]]]; + stack = stack[[;; -2]]]; out]]; +Print[rpn["3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"]]; diff --git a/Task/Partial-function-application/JavaScript/partial-function-application-1.js b/Task/Partial-function-application/JavaScript/partial-function-application-1.js new file mode 100644 index 0000000000..d66bdac40c --- /dev/null +++ b/Task/Partial-function-application/JavaScript/partial-function-application-1.js @@ -0,0 +1,20 @@ +var f1 = function (x) { return x * 2; }, + f2 = function (x) { return x * x; }, + + fs = function (f, s) { + return function (s) { + return s.map(f); + } + }, + + fsf1 = fs(f1), + fsf2 = fs(f2); + +// Test + [ + fsf1([0, 1, 2, 3]), + fsf2([0, 1, 2, 3]), + + fsf1([2, 4, 6, 8]), + fsf2([2, 4, 6, 8]) + ] diff --git a/Task/Partial-function-application/JavaScript/partial-function-application-2.js b/Task/Partial-function-application/JavaScript/partial-function-application-2.js new file mode 100644 index 0000000000..d2aadb58a0 --- /dev/null +++ b/Task/Partial-function-application/JavaScript/partial-function-application-2.js @@ -0,0 +1,21 @@ +var f1 = function (x) { return x * 2; }, + f2 = function (x) { return x * x; }, + + fs = function (f) { + return function () { + return Array.prototype.slice.call( + arguments + ).map(f); + } + }, + + fsf1 = fs(f1), + fsf2 = fs(f2); + +// Test alternative approach, with arbitrary numbers of arguments + [ + fsf1(0, 1, 2, 3, 4), + fsf2(0, 1, 2), + fsf1(2, 4, 6, 8, 10, 12), + fsf2(2, 4, 6, 8) + ] diff --git a/Task/Partial-function-application/Perl-6/partial-function-application.pl6 b/Task/Partial-function-application/Perl-6/partial-function-application.pl6 index 542d72f1b9..f80d2c393c 100644 --- a/Task/Partial-function-application/Perl-6/partial-function-application.pl6 +++ b/Task/Partial-function-application/Perl-6/partial-function-application.pl6 @@ -3,9 +3,9 @@ sub fs ( Code $f, @s ) { @s.map: { .$f } } sub f1 ( $n ) { $n * 2 } sub f2 ( $n ) { $n ** 2 } -my &fsf1 := &fs.assuming: f => &f1; -my &fsf2 := &fs.assuming: f => &f2; +my &fsf1 := &fs.assuming(&f1); +my &fsf2 := &fs.assuming(&f2); -for [1..3], [2, *+2 ... 8] X &fsf1, &fsf2 -> $s, $f { - say ~ $f.($s); +for [1..3], [2, 4 ... 8] X &fsf1, &fsf2 -> ($s, $f) { + say $f.($s); } diff --git a/Task/Partial-function-application/REXX/partial-function-application.rexx b/Task/Partial-function-application/REXX/partial-function-application.rexx index 3c8f4957cb..daee855bf4 100644 --- a/Task/Partial-function-application/REXX/partial-function-application.rexx +++ b/Task/Partial-function-application/REXX/partial-function-application.rexx @@ -1,24 +1,23 @@ -/*REXX program demonstrates a method of partial function application. */ -s=; do a=0 to 3 /*build 1st series, low integers.*/ - s=strip(s a) /*append to the integer to S list*/ +/*REXX program demonstrates a method of a partial function application. */ +s=; do a=0 to 3 /*build 1st series of some low integers*/ + s=strip(s a) /*append to the integer to the S list*/ end /*a*/ -call fs 'f1',s; say 'for f1: series=' s", result=" result -call fs 'f2',s; say 'for f2: series=' s", result=" result +call fs 'f1',s; say 'for f1: series=' s", result=" result +call fs 'f2',s; say 'for f2: series=' s", result=" result -s=; do b=2 to 8 by 2 /*build 2nd series, low even ints*/ - s=strip(s b) /*append to the integer to S list*/ +s=; do b=2 to 8 by 2 /*build 2nd series, low even integers. */ + s=strip(s b) /*append to the integer to the S list*/ end /*b*/ -call fs 'f1',s; say 'for f1: series=' s", result=" result -call fs 'f2',s; say 'for f2: series=' s", result=" result -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────F1 subroutine───────────────────────*/ -f1: return arg(1)*2 -/*──────────────────────────────────F2 subroutine───────────────────────*/ +call fs 'f1',s; say 'for f1: series=' s", result=" result +call fs 'f2',s; say 'for f2: series=' s", result=" result +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +f1: return arg(1)* 2 f2: return arg(1)**2 -/*──────────────────────────────────FS subroutine───────────────────────*/ -fs: procedure; arg f,s; $=; do j=1 for words(s); z=word(s,j) +/*────────────────────────────────────────────────────────────────────────────*/ +fs: procedure; arg f,s; $=; do j=1 for words(s); z=word(s,j) interpret '$=$' f"("z')' end /*j*/ -return strip($) + return strip($) diff --git a/Task/Pascals-triangle/Batch-File/pascals-triangle.bat b/Task/Pascals-triangle/Batch-File/pascals-triangle.bat new file mode 100644 index 0000000000..08d17c7e5d --- /dev/null +++ b/Task/Pascals-triangle/Batch-File/pascals-triangle.bat @@ -0,0 +1,39 @@ +@echo off +setlocal enabledelayedexpansion + +::The Main Thing... +cls +echo. +set row=15 +call :pascal +echo. +pause +exit /b 0 +::/The Main Thing. + +::The Functions... +:pascal + set /a prev=%row%-1 + for /l %%I in (0,1,%prev%) do ( + set c=1&set r= + for /l %%K in (0,1,%row%) do ( + if not !c!==0 ( + call :numstr !c! + set r=!r!!space!!c! + ) + set /a c=!c!*^(%%I-%%K^)/^(%%K+1^) + ) + echo !r! + ) +goto :EOF + +:numstr + ::This function returns the number of whitespaces to be applied on each numbers. + set cnt=0&set proc=%1&set space= + :loop + set currchar=!proc:~%cnt%,1! + if not "!currchar!"=="" set /a cnt+=1&goto loop + set /a numspaces=5-!cnt! + for /l %%A in (1,1,%numspaces%) do set "space=!space! " +goto :EOF +::/The Functions. diff --git a/Task/Pascals-triangle/Befunge/pascals-triangle.bf b/Task/Pascals-triangle/Befunge/pascals-triangle.bf new file mode 100644 index 0000000000..d33fa4ceee --- /dev/null +++ b/Task/Pascals-triangle/Befunge/pascals-triangle.bf @@ -0,0 +1,3 @@ +0" :swor fo rebmuN">:#,_&> 55+, v +v01*p00-1:g00.:<1p011p00:\-1_v#:< +>g:1+10p/48*,:#^_$ 55+,1+\: ^>$$@ diff --git a/Task/Pascals-triangle/C++/pascals-triangle.cpp b/Task/Pascals-triangle/C++/pascals-triangle-1.cpp similarity index 100% rename from Task/Pascals-triangle/C++/pascals-triangle.cpp rename to Task/Pascals-triangle/C++/pascals-triangle-1.cpp diff --git a/Task/Pascals-triangle/C++/pascals-triangle-2.cpp b/Task/Pascals-triangle/C++/pascals-triangle-2.cpp new file mode 100644 index 0000000000..ea3c7b54de --- /dev/null +++ b/Task/Pascals-triangle/C++/pascals-triangle-2.cpp @@ -0,0 +1,85 @@ +// Compile with -std=c++11 +#include +#include +using namespace std; +void print_vector(vector dummy){ + for (vector::iterator i = dummy.begin(); i != dummy.end(); ++i) + cout<<*i<<" "; + cout<> dummy){ + for (vector>::iterator i = dummy.begin(); i != dummy.end(); ++i) + print_vector(*i); + cout<> dynamic_triangle(int dummy){ + vector> result; + if (dummy > 0){ // if the argument is 0 or negative exit immediately + vector row; + // The first row + row.push_back(1); + result.push_back(row); + // The second row + if (dummy > 1){ + row.clear(); + row.push_back(1); row.push_back(1); + result.push_back(row); + } + // The other rows + if (dummy > 2){ + for (int i = 2; i < dummy; i++){ + row.clear(); + row.push_back(1); + for (int j = 1; j < i; j++) + row.push_back(result.back().at(j - 1) + result.back().at(j)); + row.push_back(1); + result.push_back(row); + } + } + } + return result; +} +vector> static_triangle(int dummy){ + vector> result; + if (dummy > 0){ // if the argument is 0 or negative exit immediately + vector row; + result.resize(dummy); // This should work faster than consecutive push_back()s + // The first row + row.resize(1); + row.at(0) = 1; + result.at(0) = row; + // The second row + if (result.size() > 1){ + row.resize(2); + row.at(0) = 1; row.at(1) = 1; + result.at(1) = row; + } + // The other rows + if (result.size() > 2){ + for (int i = 2; i < result.size(); i++){ + row.resize(i + 1); // This should work faster than consecutive push_back()s + row.front() = 1; + for (int j = 1; j < row.size() - 1; j++) + row.at(j) = result.at(i - 1).at(j - 1) + result.at(i - 1).at(j); + row.back() = 1; + result.at(i) = row; + } + } + } + return result; +} +int main(){ + vector> triangle; + int n; + cout<>n; + // Call the dynamic function + triangle = dynamic_triangle(n); + cout< +#include +using namespace std; +class pascal_triangle{ + vector> data; // This is the actual data + void print_row(vector dummy){ + for (vector::iterator i = dummy.begin(); i != dummy.end(); ++i) + cout<<*i<<" "; + cout< 0){ // if the argument is 0 or negative exit immediately + vector row; + data.resize(dummy); // Theoretically this should work faster than consecutive push_back()s + // The first row + row.resize(1); + row.at(0) = 1; + data.at(0) = row; + // The second row + if (data.size() > 1){ + row.resize(2); + row.at(0) = 1; row.at(1) = 1; + data.at(1) = row; + } + // The other rows + if (data.size() > 2){ + for (int i = 2; i < data.size(); i++){ + row.resize(i + 1); // Theoretically this should work faster than consecutive push_back()s + row.front() = 1; + for (int j = 1; j < row.size() - 1; j++) + row.at(j) = data.at(i - 1).at(j - 1) + data.at(i - 1).at(j); + row.back() = 1; + data.at(i) = row; + } + } + } + } + ~pascal_triangle(){ + for (vector>::iterator i = data.begin(); i != data.end(); ++i) + i->clear(); // I'm not sure about the necessity of this loop! + data.clear(); + } + void print_row(int dummy){ + if (dummy < data.size()) + for (vector::iterator i = data.at(dummy).begin(); i != data.at(dummy).end(); ++i) + cout<<*i<<" "; + cout< get_row(int dummy){ + vector result; + if (dummy < data.size()) + result = data.at(dummy); + return result; + } +}; +int main(){ + int n; + cout<>n; + pascal_triangle myptri(n); + cout< Enum.map(fn {a,b} -> a+b end) + triangle(n-1,new_list) + end +end + +Pascal.triangle(8) diff --git a/Task/Pascals-triangle/K/pascals-triangle.k b/Task/Pascals-triangle/K/pascals-triangle.k index f805474ed5..ec8b2e6e01 100644 --- a/Task/Pascals-triangle/K/pascals-triangle.k +++ b/Task/Pascals-triangle/K/pascals-triangle.k @@ -1,6 +1,5 @@ - pascal:{(x-1){1_ +':0,x,0}\1} - - pascal 6 +pascal:{(x-1){+':x,0}\1} +pascal 6 (1 1 1 1 2 1 diff --git a/Task/Pascals-triangle/Perl-6/pascals-triangle-1.pl6 b/Task/Pascals-triangle/Perl-6/pascals-triangle-1.pl6 index a372200df4..9acb990be6 100644 --- a/Task/Pascals-triangle/Perl-6/pascals-triangle-1.pl6 +++ b/Task/Pascals-triangle/Perl-6/pascals-triangle-1.pl6 @@ -1,3 +1,3 @@ -sub pascal { [1], { [0, @^p Z+ @^p, 0] } ... * } +sub pascal { [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... * } .say for pascal[^10]; diff --git a/Task/Pascals-triangle/Perl-6/pascals-triangle-2.pl6 b/Task/Pascals-triangle/Perl-6/pascals-triangle-2.pl6 index e4268d40ac..0464addaf9 100644 --- a/Task/Pascals-triangle/Perl-6/pascals-triangle-2.pl6 +++ b/Task/Pascals-triangle/Perl-6/pascals-triangle-2.pl6 @@ -1,3 +1,3 @@ -constant Pascal = [1], { [0, @^p Z+ @^p, 0] } ... *; +constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *; -.say for Pascal[^10]; +.say for @pascal[^10]; diff --git a/Task/Pascals-triangle/Perl-6/pascals-triangle-3.pl6 b/Task/Pascals-triangle/Perl-6/pascals-triangle-3.pl6 index 93051a4eb5..1fed227b16 100644 --- a/Task/Pascals-triangle/Perl-6/pascals-triangle-3.pl6 +++ b/Task/Pascals-triangle/Perl-6/pascals-triangle-3.pl6 @@ -1,7 +1,7 @@ -multi pascal (1) { [1] } -multi pascal (Int $n where 2..*) { +multi sub pascal (1) { $[1] } +multi sub pascal (Int $n where 2..*) { my @rows = pascal $n - 1; - @rows, [0, @rows[*-1][] Z+ @rows[*-1][], 0 )]; + |@rows, [0, |@rows[*-1] Z+ |@rows[*-1], 0 ]; } .say for pascal 10; diff --git a/Task/Pascals-triangle/Perl-6/pascals-triangle-4.pl6 b/Task/Pascals-triangle/Perl-6/pascals-triangle-4.pl6 index 06777c0c75..d091ba8a18 100644 --- a/Task/Pascals-triangle/Perl-6/pascals-triangle-4.pl6 +++ b/Task/Pascals-triangle/Perl-6/pascals-triangle-4.pl6 @@ -1,7 +1,7 @@ sub pascal ($n where $n >= 1) { say my @last = 1; for 1 .. $n - 1 -> $row { - @last = 1, map({ @last[$_] + @last[$_ + 1] }, 0 .. $row - 2), 1; + @last = 1, |map({ @last[$_] + @last[$_ + 1] }, 0 .. $row - 2), 1; say @last; } } diff --git a/Task/Pascals-triangle/Perl/pascals-triangle-1.pl b/Task/Pascals-triangle/Perl/pascals-triangle-1.pl index f0a2f9ee6b..22659d3654 100644 --- a/Task/Pascals-triangle/Perl/pascals-triangle-1.pl +++ b/Task/Pascals-triangle/Perl/pascals-triangle-1.pl @@ -1,7 +1,8 @@ -sub pascal +sub pascal { my $rows = shift; my @next = (1); for my $n (1 .. $rows) { print "@next\n"; @next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1); } +} diff --git a/Task/Pascals-triangle/REXX/pascals-triangle.rexx b/Task/Pascals-triangle/REXX/pascals-triangle.rexx index 72da471edc..e9329f0d12 100644 --- a/Task/Pascals-triangle/REXX/pascals-triangle.rexx +++ b/Task/Pascals-triangle/REXX/pascals-triangle.rexx @@ -1,28 +1,25 @@ -/*REXX program to display Pascal's triangle, neatly centered/formatted.*/ -/*AKA: Yang Hui's ▲, Khayyam-Pascal ▲, Kyayyam ▲, Tartaglia's ▲ */ -numeric digits 1000 /*let's be able to handle big ▲. */ -arg nn .; if nn=='' then nn=10; n=abs(nn) -a. = 1 /*if NN < 0, output is to a file.*/ -mx = !(n-1) / !(n%2) / !(n-1-n%2) /*MX =biggest number in triangle.*/ -w = length(mx) /* W =width of biggest number. */ -line. = 1 - - do row=1 for n; prev=row-1 - a.row.1 = 1 - do j=2 to row-1; jm=j-1 - a.row.j = a.prev.jm + a.prev.j - line.row = line.row right(a.row.j,w) - end /*j*/ - - if row\==1 then line.row=line.row right(1,w) /*append the last "1".*/ - end /*row*/ - -width=length(line.n) /*width of last line in triangle.*/ - - do L=1 for n /*show lines in Pascal's triangle*/ - if nn>0 then say center(line.L,width) /*either SAY or write.*/ - else call lineout 'PASCALS.'n, center(line.L,width) - end /*L*/ -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────! (factorial) subroutine─────────*/ -!: procedure; arg x;!=1;do j=2 to x;!=!*j;end;return ! /*calc. factorial*/ +/*REXX program displays Pascal's triangle (centered/formatted); also known as:*/ +/*────────── Yang Hui's, Khayyam─Pascal, Kyayyam, and/or Tartaglia's triangle.*/ +numeric digits 3000 /*be able to handle gihugeic triangles.*/ +parse arg nn .; if nn=='' then nn=10 /*use default if NN wasn't specified.*/ +N=abs(nn) /*N is the number of rows in triangle.*/ +@.=1; $.=@. /*default value for rows and for lines.*/ +w=length(!(N-1) / !(N%2) / !(N-1-N%2)) /*W is the width of the biggest number*/ + /* [↓] build rows of Pascals' triangle*/ + do r=1 for N; rm=r-1 /*Note: the first column is always 1.*/ + do c=2 to rm; cm=c-1 /*build the rest of the columns in row.*/ + @.r.c= @.rm.cm + @.rm.c /*assign value to a specific row & col.*/ + $.r = $.r right(@.r.c, w) /*and construct a line for output (row)*/ + end /*c*/ /* [↑] C is the column being built.*/ + if r\==1 then $.r=$.r right(1, w) /*for most rows, append a trailing "1".*/ + end /*r*/ /* [↑] R is the row being built.*/ + /* [↑] WIDTH: for nicely looking line.*/ +width=length($.N) /*width of the last (output) line (row)*/ + /*if NN<0, output is written to a file.*/ + do r=1 for N /*show│write lines (rows) of triangle. */ + if nn>0 then say center($.r, width) /*SAY, or*/ + else call lineout 'PASCALS.'n, center($.r, width) /*write. */ + end /*r*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────! subroutine (factorial)─────────────────*/ +!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end; return ! diff --git a/Task/Pascals-triangle/VBScript/pascals-triangle.vb b/Task/Pascals-triangle/VBScript/pascals-triangle.vb new file mode 100644 index 0000000000..8d1ffa347e --- /dev/null +++ b/Task/Pascals-triangle/VBScript/pascals-triangle.vb @@ -0,0 +1,14 @@ +Pascal_Triangle(WScript.Arguments(0)) +Function Pascal_Triangle(n) + Dim values(100) + values(1) = 1 + WScript.StdOut.Write values(1) + WScript.StdOut.WriteLine + For row = 2 To n + For i = row To 1 Step -1 + values(i) = values(i) + values(i-1) + WScript.StdOut.Write values(i) & " " + Next + WScript.StdOut.WriteLine + Next +End Function diff --git a/Task/Pattern-matching/Bracmat/pattern-matching-1.bracmat b/Task/Pattern-matching/Bracmat/pattern-matching-1.bracmat index fa25d8776d..9cf6f6b8e9 100644 --- a/Task/Pattern-matching/Bracmat/pattern-matching-1.bracmat +++ b/Task/Pattern-matching/Bracmat/pattern-matching-1.bracmat @@ -1,4 +1,4 @@ - ( balance +( ( balance = a x b y c zd . !arg : ( B @@ -20,7 +20,7 @@ | !arg ) & ( ins - = X tree a m z + = C X tree a m z . !arg:(?X.?tree) & !tree:(?C.?a,?m,?z) & ( !X:nul +nul +set /a newline=%cnt%%%60 +if %newline%==59 ( +echo. +nul || ( + echo [Invalid Input...]&echo.&goto %1 +) +if /i "!you_bet!"=="%cpu_bet%" (echo [Bet something different...]&echo.&goto %1) +for %%i in ("t=T" "h=H") do set "you_bet=!you_bet:%%~i!" +goto :EOF diff --git a/Task/Penneys-game/Julia/penneys-game-1.julia b/Task/Penneys-game/Julia/penneys-game-1.julia new file mode 100644 index 0000000000..d93c43df43 --- /dev/null +++ b/Task/Penneys-game/Julia/penneys-game-1.julia @@ -0,0 +1,32 @@ +const SLEN = 3 + +autobet() = randbool(SLEN) +function autobet(ob::BitArray{1}) + rlen = length(ob) + 2 < rlen || return ~ob + 3 < rlen || return [~ob[2], ob[1:2]] + opt = falses(rlen) + opt[1] = true + opt[end-1:end] = true + ob != opt || return ~opt + return opt +end +autobet(ob::Array{Bool,1}) = autobet(convert(BitArray{1}, ob)) + +function pgencode{T<:String}(a::T) + b = uppercase(a) + 0 < length(b) || return trues(0) + !ismatch(r"[^HT]+", b) || error(@sprintf "%s is not a HT sequence" a) + b = split(b, "") + b .== "H" +end +pgdecode(a::BitArray{1}) = join([i ? "H" : "T" for i in a], "") + +function humanbet() + b = "" + while length(b) != SLEN || ismatch(r"[^HT]+", b) + print("Your bet? ") + b = uppercase(chomp(readline())) + end + return b +end diff --git a/Task/Penneys-game/Julia/penneys-game-2.julia b/Task/Penneys-game/Julia/penneys-game-2.julia new file mode 100644 index 0000000000..c410572ea5 --- /dev/null +++ b/Task/Penneys-game/Julia/penneys-game-2.julia @@ -0,0 +1,14 @@ +println("Playing Penney's Game Against the computer.") + +if randbool() + mach = autobet() + println(@sprintf "The computer bet first, chosing %s." pgdecode(mach)) + println("Now you can bet.") + human = pgencode(humanbet()) +else + println("You bet first.") + human = pgencode(humanbet()) + mach = autobet(human) +end +print(@sprintf "You bet %s " pgdecode(human)) +println(@sprintf "and the computer bet %s." pgdecode(mach)) diff --git a/Task/Penneys-game/Julia/penneys-game-3.julia b/Task/Penneys-game/Julia/penneys-game-3.julia new file mode 100644 index 0000000000..f78a1995ff --- /dev/null +++ b/Task/Penneys-game/Julia/penneys-game-3.julia @@ -0,0 +1,17 @@ +pg = randbool(SLEN) +pgtail = copy(pg) +while pgtail != mach && pgtail != human + push!(pg, randbool()) + pgtail = [pgtail[2:end], pg[end]] +end + +println(@sprintf("This game lasted %d turns yielding\n %s", + length(pg), pgdecode(pg))) + +if human == mach + println("so you and the computer tied.") +elseif pgtail == mach + println("so the computer won.") +else + println("so you won.") +end diff --git a/Task/Penneys-game/Perl/penneys-game.pl b/Task/Penneys-game/Perl/penneys-game.pl new file mode 100644 index 0000000000..cc19956ee5 --- /dev/null +++ b/Task/Penneys-game/Perl/penneys-game.pl @@ -0,0 +1,110 @@ +#!usr/bin/perl +use 5.020; +use strict; +use warnings; + +#Choose who goes first +binaryRand() == 0 ? flipCoin(userFirst()) : flipCoin(compFirst()); + +#Return a randomly generated 1 or 0 +sub binaryRand +{ + return int(rand(2)); +} +#Converts 1's and 0's to H's and T's, respectively. +sub convert +{ + my $randNum = binaryRand(); + if($randNum == 0) + { + return "T" + } + else + { + return "H"; + } +} + +#Prompts for and returns a user's sequence of 3 +sub uSeq +{ + print("Please enter a sequence of 3 of \"H\" and \"T\". EG: HHT\n>"); + my $uString = ; + + while(1) + { + #Make it uppercase and validate input + chomp($uString); + $uString = uc $uString; + #Check length and content (H's and T's only!) + if(length $uString == 3 && (substr($uString, 0, 1) =~ /[HT]/ && + substr($uString, 1, 1) =~ /[HT]/ && + substr($uString, 2, 1) =~ /[HT]/)) + { + last; + } + else + { + print("Error, try again. \n"); + print("Please enter a sequence of 3 of \"H\" and \"T\". EG: HHT\n"); + $uString = ; + } + } + return $uString; +} + +#Returns an array with two elements: [0] user's seq, [1] random computer seq. +sub compFirst +{ + my $cSeq; + #Randomly draw a sequence of 3 + for(my $i = 0; $i < 3; $i++) + { + $cSeq = $cSeq . convert(); + } + + print("The computer guesses first:\ncomp- $cSeq\n"); + my $uSeq = uSeq(); + print("user- $uSeq\n"); + my @seqArr = ($uSeq, $cSeq); + return @seqArr; +} + +#Returns an array with two elements: [0] user's seq, [1] optimal computer seq. +sub userFirst +{ + print("The user quesses first:\n"); + my $uSeq = uSeq(); + my $cSeq; + #Generate the optimal sequence based on $uSeq + my $middle = substr($uSeq, 1, 1); + $middle eq "H" ? $cSeq = "T" : $cSeq = "H"; + $cSeq = $cSeq . substr($uSeq, 0, 2); + + print("user- $uSeq\ncomp- $cSeq\n"); + my @seqArr = ($uSeq, $cSeq); + return @seqArr; +} + +#Flips a coin, checking both sequences against the contents of the given array +sub flipCoin +{ + my ($uSeq, $cSeq) = @_; + my $coin; + while(1) + { + $coin = $coin . convert(); + if($coin =~ m/$uSeq/) + { + print("The sequence of tosses was: $coin\n"); + say("The player wins! "); + last; + } + elsif($coin =~ m/$cSeq/) + { + print("The sequence of tosses was: $coin\n"); + say("The computer wins! "); + last; + } + } +} diff --git a/Task/Percentage-difference-between-images/AutoHotkey/percentage-difference-between-images.ahk b/Task/Percentage-difference-between-images/AutoHotkey/percentage-difference-between-images.ahk index 70e25eb648..39adbb0824 100644 --- a/Task/Percentage-difference-between-images/AutoHotkey/percentage-difference-between-images.ahk +++ b/Task/Percentage-difference-between-images/AutoHotkey/percentage-difference-between-images.ahk @@ -75,8 +75,8 @@ height := Gdip_GetImageHeight(pBitmapFile1) DllCall("BitBlt", "Uint", mDCo, "int", 0, "int", 0, "int", width, "int", height, "Uint", mDCi, "int", 0, "int", 0, "Uint", 0x40000000 | 0x00CC0020) DllCall("SelectObject", "Uint", mDCo, "Uint", oBM) -DllCall("ReleaseDC", "Uint", 0, "Uint", mDCi) -DllCall("ReleaseDC", "Uint", 0, "Uint", mDCo) +DllCall("DeleteDC", "Uint", 0, "Uint", mDCi) +DllCall("DeleteDC", "Uint", 0, "Uint", mDCo) Gdip_DisposeImage(pBitmapFile1) DllCall("DeleteObject", "Uint", hBMi) disposables.hBitmaps._insert(hBMo) diff --git a/Task/Percentage-difference-between-images/JavaScript/percentage-difference-between-images.js b/Task/Percentage-difference-between-images/JavaScript/percentage-difference-between-images.js new file mode 100644 index 0000000000..e68ddd70d3 --- /dev/null +++ b/Task/Percentage-difference-between-images/JavaScript/percentage-difference-between-images.js @@ -0,0 +1,39 @@ +function getImageData(url, callback) { + var img = document.createElement('img'); + var canvas = document.createElement('canvas'); + + img.onload = function () { + canvas.width = img.width; + canvas.height = img.height; + var ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0); + callback(ctx.getImageData(0, 0, img.width, img.height)); + }; + + img.src = url; +} + +function compare(firstImage, secondImage, callback) { + getImageData(firstImage, function (img1) { + getImageData(secondImage, function (img2) { + if (img1.width !== img2.width || img1.height != img2.height) { + callback(NaN); + return; + } + + var diff = 0; + + for (var i = 0; i < img1.data.length / 4; i++) { + diff += Math.abs(img1.data[4 * i + 0] - img2.data[4 * i + 0]) / 255; + diff += Math.abs(img1.data[4 * i + 1] - img2.data[4 * i + 1]) / 255; + diff += Math.abs(img1.data[4 * i + 2] - img2.data[4 * i + 2]) / 255; + } + + callback(100 * diff / (img1.width * img1.height * 3)); + }); + }); +} + +compare('Lenna50.jpg', 'Lenna100.jpg', function (result) { + console.log(result); +}); diff --git a/Task/Percolation-Mean-run-density/00DESCRIPTION b/Task/Percolation-Mean-run-density/00DESCRIPTION index 04cc0d1d16..2d1fe38c08 100644 --- a/Task/Percolation-Mean-run-density/00DESCRIPTION +++ b/Task/Percolation-Mean-run-density/00DESCRIPTION @@ -1,11 +1,11 @@ {{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 +value being 1 is p; the probability of a value being 0 is therefore 1-p. +Define a run of 1s as being a group of consecutive 1s in the vector bounded +either by the limits of the vector or by a 0. Let the number of such runs in a given vector of length n be R_n. -The following vector has R_{10} = 3 +For example, the following vector has R_{10} = 3
 [1 1 0 0 0 1 0 1 1 1]
  ^^^       ^   ^^^^^
@@ -22,7 +22,7 @@ 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
+Show your output here.
 
 ;See also
 * [http://mathworld.wolfram.com/s-Run.html s-Run] on Wolfram mathworld.
diff --git a/Task/Percolation-Site-percolation/Haskell/percolation-site-percolation.hs b/Task/Percolation-Site-percolation/Haskell/percolation-site-percolation.hs
new file mode 100644
index 0000000000..7c80bcc4a8
--- /dev/null
+++ b/Task/Percolation-Site-percolation/Haskell/percolation-site-percolation.hs
@@ -0,0 +1,83 @@
+{-# LANGUAGE OverloadedStrings #-}
+import           Control.Monad
+import           Control.Monad.Random
+import           Data.Array.Unboxed
+import           Data.List
+import           Formatting
+
+type Field = UArray (Int, Int) Char
+
+-- Start percolating some seepage through a field.
+-- Recurse to continue percolation with spreading seepage.
+percolateR :: [(Int, Int)] -> Field -> (Field, [(Int,Int)])
+percolateR [] f = (f, [])
+percolateR seep f = percolateR
+                       (concat $ fmap neighbors validSeep)
+                       (f // map (\p -> (p,'.')) validSeep) where
+    neighbors p@(r,c) = [(r-1,c), (r+1,c), (r, c-1), (r, c+1)]
+    ((rLo,cLo),(rHi,cHi)) = bounds f
+    validSeep = filter (\p@(r,c) -> r >= rLo &&
+                                    r <= rHi &&
+                                    c >= cLo &&
+                                    c <= cHi &&
+                                    f!p == ' ') $ nub $ sort seep
+
+-- Percolate a field;  Return the percolated field.
+percolate :: Field -> Field
+percolate start =
+    let ((_,_),(_,cHi)) = bounds start
+        (final, _) = percolateR [(0,c) | c <- [0..cHi]] start
+    in final
+
+-- Generate a random field.
+randomField :: Int -> Int -> Double -> Rand StdGen Field
+randomField rows cols threshold = do
+    rnd <- replicateM rows (replicateM cols $ getRandomR (0.0, 1.0))
+    return $ array ((0,0), (rows-1, cols-1))
+                    [((r,c), if rnd !! r !! c < threshold then ' '
+                             else '#')
+                     | r <- [0..rows-1], c <- [0..cols-1] ]
+
+-- Assess whether or not percolation reached bottom of field.
+leaky :: Field -> Bool
+leaky f = '.' `elem` [f!(rHi,c) | c <- [cLo..cHi]] where
+               ((_,cLo),(rHi,cHi)) = bounds f
+
+-- Run test once; Return bool indicating success or failure.
+oneTest :: Int -> Int -> Double -> Rand StdGen Bool
+oneTest rows cols threshold =
+    leaky <$> percolate <$> randomField rows cols threshold
+
+-- Run test multple times; Return the number of tests that pass
+multiTest :: Int -> Int -> Int -> Double -> Rand StdGen Double
+multiTest repeats rows cols threshold = do
+    x <- replicateM repeats $ oneTest rows cols threshold
+    let leakyCount = length $ filter (==True) x
+    return $ fromIntegral leakyCount / fromIntegral repeats
+
+showField :: Field -> IO ()
+showField a =   mapM_ print [ [ a!(r,c) | c <- [cLo..cHi]] | r <- [rLo..rHi]]
+              where ((rLo,cLo),(rHi,cHi)) = bounds a
+
+main :: IO ()
+main = do
+  g <- getStdGen
+  let (startField, g2) = runRand (randomField 15 15 0.6) g
+  putStrLn "Unpercolated field with 0.6 threshold."
+  putStrLn ""
+  showField startField
+
+  putStrLn ""
+  putStrLn "Same field after percolation."
+  putStrLn ""
+  showField $ percolate startField
+
+  putStrLn ""
+  putStrLn "Results of running percolation test 10000 times with thresholds ranging from 0.0 to 1.0 ."
+  let d = 10
+  let ns = [0..10]
+  let tests = sequence [multiTest 10000 15 15 v
+                           | n <- ns,
+                             let v = fromIntegral n / fromIntegral d ]
+  let results = zip ns (evalRand tests g2)
+  mapM_ print [format ("p=" % int % "/" % int % " -> " % fixed 4) n d r | (n,r) <- results]
diff --git a/Task/Percolation-Site-percolation/J/percolation-site-percolation-1.j b/Task/Percolation-Site-percolation/J/percolation-site-percolation-1.j
new file mode 100644
index 0000000000..a5132280c0
--- /dev/null
+++ b/Task/Percolation-Site-percolation/J/percolation-site-percolation-1.j
@@ -0,0 +1,6 @@
+groups=:[: +/\ 2 . [ +&* [ * [: ; groups@[ <@(* * 2 < >./)/. +
+percolate=: ooze/\.@|.^:2^:_@(* (1 + # {. 1:))
+
+trial=: percolate@([ >: ]?@$0:)
+simulate=: %@[ * [: +/ (2 e. {:)@trial&15 15"0@#
diff --git a/Task/Percolation-Site-percolation/J/percolation-site-percolation-2.j b/Task/Percolation-Site-percolation/J/percolation-site-percolation-2.j
new file mode 100644
index 0000000000..ba613f62c7
--- /dev/null
+++ b/Task/Percolation-Site-percolation/J/percolation-site-percolation-2.j
@@ -0,0 +1,16 @@
+   ,.'  P THRU';(, 100&simulate)"0 (i.%<:)11
+┌────────┐
+│  P THRU│
+├────────┤
+│  0    0│
+│0.1    0│
+│0.2    0│
+│0.3    0│
+│0.4 0.01│
+│0.5 0.09│
+│0.6 0.61│
+│0.7 0.97│
+│0.8    1│
+│0.9    1│
+│  1    1│
+└────────┘
diff --git a/Task/Percolation-Site-percolation/J/percolation-site-percolation-3.j b/Task/Percolation-Site-percolation/J/percolation-site-percolation-3.j
new file mode 100644
index 0000000000..b0581ccd57
--- /dev/null
+++ b/Task/Percolation-Site-percolation/J/percolation-site-percolation-3.j
@@ -0,0 +1,16 @@
+   1j1 #"1 ' .#'{~ percolate 0.6>:?15 15$0
+# #   # # #       #   #     #
+#   # # #   # # #   # # # # #
+# # #   # #   #     #       #
+    #   # #   # # #     # # #
+#     .       #   # # # # #
+#       # # # # # # # #     #
+# #   # # # # # #   # # # # #
+  # # # # #     #   #   # # #
+.                   #   #
+  .   .           # #   #   #
+. . .   .   # # # # # # # # #
+. . . .   # #       # # # # #
+. . .     #     .   # #   #
+. . . .     . . .     # #   .
+  .   . . .   . . . .   # #
diff --git a/Task/Percolation-Site-percolation/J/percolation-site-percolation.j b/Task/Percolation-Site-percolation/J/percolation-site-percolation-4.j
similarity index 100%
rename from Task/Percolation-Site-percolation/J/percolation-site-percolation.j
rename to Task/Percolation-Site-percolation/J/percolation-site-percolation-4.j
diff --git a/Task/Perfect-numbers/Eiffel/perfect-numbers.e b/Task/Perfect-numbers/Eiffel/perfect-numbers.e
new file mode 100644
index 0000000000..e5f5acf9c5
--- /dev/null
+++ b/Task/Perfect-numbers/Eiffel/perfect-numbers.e
@@ -0,0 +1,41 @@
+class
+	APPLICATION
+
+create
+	make
+
+feature
+
+	make
+		do
+			io.put_string ("  6 is perfect...%T")
+			io.put_boolean (is_perfect_number (6))
+			io.new_line
+			io.put_string (" 77 is perfect...%T")
+			io.put_boolean (is_perfect_number (77))
+			io.new_line
+			io.put_string ("128 is perfect...%T")
+			io.put_boolean (is_perfect_number (128))
+			io.new_line
+			io.put_string ("496 is perfect...%T")
+			io.put_boolean (is_perfect_number (496))
+		end
+
+	is_perfect_number (n: INTEGER): BOOLEAN
+			-- Is 'n' a perfect number?
+		require
+			n_positive: n > 0
+		local
+			sum: INTEGER
+		do
+			across
+				1 |..| (n - 1) as c
+			loop
+				if n \\ c.item = 0 then
+					sum := sum + c.item
+				end
+			end
+			Result := sum = n
+		end
+
+end
diff --git a/Task/Perfect-numbers/Elixir/perfect-numbers.elixir b/Task/Perfect-numbers/Elixir/perfect-numbers.elixir
index b33fae77f7..0bdab4aa5c 100644
--- a/Task/Perfect-numbers/Elixir/perfect-numbers.elixir
+++ b/Task/Perfect-numbers/Elixir/perfect-numbers.elixir
@@ -1,3 +1,8 @@
-def is_perfect(x) do
-  [1 | lc x inlist :lists.seq(2, div(n, 2)), rem(n, x) == 0, do: x] |> :lists.sum() == n
+defmodule RC do
+  def is_perfect(1), do: false
+  def is_perfect(n) when n > 1 do
+    (for i <- 1..div(n,2), rem(n,i)==0, do: i) |> Enum.sum == n
+  end
 end
+
+IO.inspect (for i <- 1..10000, RC.is_perfect(i), do: i)
diff --git a/Task/Perfect-numbers/JavaScript/perfect-numbers.js b/Task/Perfect-numbers/JavaScript/perfect-numbers-1.js
similarity index 100%
rename from Task/Perfect-numbers/JavaScript/perfect-numbers.js
rename to Task/Perfect-numbers/JavaScript/perfect-numbers-1.js
diff --git a/Task/Perfect-numbers/JavaScript/perfect-numbers-2.js b/Task/Perfect-numbers/JavaScript/perfect-numbers-2.js
new file mode 100644
index 0000000000..a054739deb
--- /dev/null
+++ b/Task/Perfect-numbers/JavaScript/perfect-numbers-2.js
@@ -0,0 +1,19 @@
+(function (nFrom, nTo) {
+
+  function perfect(n) {
+    return n === range(1, n - 1).reduce(
+      function (a, x) {
+        return n % x ? a : a + x;
+      }, 0
+    );
+  }
+
+  function range(m, n) {
+    return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
+      return m + i;
+    });
+  }
+
+  return range(nFrom, nTo).filter(perfect);
+
+})(1, 10000);
diff --git a/Task/Perfect-numbers/JavaScript/perfect-numbers-3.js b/Task/Perfect-numbers/JavaScript/perfect-numbers-3.js
new file mode 100644
index 0000000000..e15308fdaa
--- /dev/null
+++ b/Task/Perfect-numbers/JavaScript/perfect-numbers-3.js
@@ -0,0 +1 @@
+[6, 28, 496, 8128]
diff --git a/Task/Perfect-numbers/JavaScript/perfect-numbers-4.js b/Task/Perfect-numbers/JavaScript/perfect-numbers-4.js
new file mode 100644
index 0000000000..6280c69286
--- /dev/null
+++ b/Task/Perfect-numbers/JavaScript/perfect-numbers-4.js
@@ -0,0 +1,23 @@
+(function (nFrom, nTo) {
+
+  function perfect(n) {
+    var lows = range(1, Math.floor(Math.sqrt(n))).filter(function (x) {
+      return (n % x) === 0;
+    });
+
+    return n > 1 && lows.concat(lows.map(function (x) {
+      return n / x;
+    })).reduce(function (a, x) {
+      return a + x;
+    }, 0) / 2 === n;
+  }
+
+  function range(m, n) {
+    return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
+      return m + i;
+    });
+  }
+
+  return range(nFrom, nTo).filter(perfect)
+
+})(1, 10000);
diff --git a/Task/Perfect-numbers/JavaScript/perfect-numbers-5.js b/Task/Perfect-numbers/JavaScript/perfect-numbers-5.js
new file mode 100644
index 0000000000..e15308fdaa
--- /dev/null
+++ b/Task/Perfect-numbers/JavaScript/perfect-numbers-5.js
@@ -0,0 +1 @@
+[6, 28, 496, 8128]
diff --git a/Task/Perfect-numbers/Perl/perfect-numbers-6.pl b/Task/Perfect-numbers/Perl/perfect-numbers-6.pl
new file mode 100644
index 0000000000..029ac99ba3
--- /dev/null
+++ b/Task/Perfect-numbers/Perl/perfect-numbers-6.pl
@@ -0,0 +1,5 @@
+use ntheory qw/forprimes is_mersenne_prime/;
+use Math::GMP qw/:constant/;
+forprimes {
+  print "$_\t", (2**$_-1)*2**($_-1),"\n"  if is_mersenne_prime($_);
+} 7_000_000;
diff --git a/Task/Perfect-numbers/PicoLisp/perfect-numbers.l b/Task/Perfect-numbers/PicoLisp/perfect-numbers-1.l
similarity index 100%
rename from Task/Perfect-numbers/PicoLisp/perfect-numbers.l
rename to Task/Perfect-numbers/PicoLisp/perfect-numbers-1.l
diff --git a/Task/Perfect-numbers/PicoLisp/perfect-numbers-2.l b/Task/Perfect-numbers/PicoLisp/perfect-numbers-2.l
new file mode 100644
index 0000000000..5913d16c6b
--- /dev/null
+++ b/Task/Perfect-numbers/PicoLisp/perfect-numbers-2.l
@@ -0,0 +1,7 @@
+(de faster (N)
+   (let (C 1  Stop (sqrt N))
+      (for (I 2 (<= I Stop) (inc I))
+         (and
+            (=0 (% N I))
+            (inc 'C (+ (/ N I) I)) ) )
+      (= C N) ) )
diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx
index 0c086e0f96..c7d01d47b7 100644
--- a/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx
+++ b/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx
@@ -13,7 +13,7 @@ exit                                   /*stick a fork in it, we're done.*/
 /*──────────────────────────────────ISPERFECT subroutine────────────────*/
 isPerfect: procedure;  parse arg x     /*get the number to be tested.   */
 if x<6  then return 0                  /*perfect numbers can't be < six.*/
-s=1                                    /*the first factor of  X.        */
+s=1                                    /*the first factor of  X.       _*/
              do j=2  while  j*j<=x     /*starting at 2, find factors ≤√X*/
              if x//j\==0  then iterate /*J isn't a factor of X, so skip.*/
              s = s + j + x%j           /*··· add it and the other factor*/
diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx
index 13ff32c004..3bc5111b0b 100644
--- a/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx
+++ b/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx
@@ -20,7 +20,7 @@ if x==6  then return 1                 /*handle special case of  six.   */
       end   /*DO until*/               /*wash, rinse, repeat ···        */
 
 if r\==1  then return 0                /*Digital root ¬1? Then ¬perfect.*/
-s=1                                    /*the first factor of  X.        */
+s=1                                    /*the first factor of  X.       _*/
              do j=2  while  j*j<=x     /*starting at 2, find factors ≤√X*/
              if x//j\==0  then iterate /*J isn't a factor of X, so skip.*/
              s = s + j + x%j           /*··· add it and the other factor*/
diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx
index 0281c09285..47b81074dc 100644
--- a/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx
+++ b/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx
@@ -22,7 +22,7 @@ if x==6  then return 1                 /*handle special case  of  six.  */
 
 if r\==1  then return 0                /*is dig root ¬1?  Then ¬perfect.*/
 
-s = 3 + x%2                            /*the first three factors of  X. */
+s = 3 + x%2                            /*the first 3 factors of X.     _*/
              do j=3  while  j*j<=x     /*starting at 3, find factors ≤√X*/
              if x//j\==0  then iterate /*J isn't a factor of X, so skip.*/
              s = s + j + x%j           /*··· add it and the other factor*/
diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx
index bb53706bc6..3f795ea23d 100644
--- a/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx
+++ b/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx
@@ -24,7 +24,7 @@ if @.x==0  then return 0               /*Didn't pass Lucas-Lehmer test? */
 s = 3 + x%2                            /*we know the following factors: */
                                        /*  1      ('cause Mama said so.)*/
                                        /*  2      ('cause it's even.)   */
-                                       /* x÷2         "     "    "      */
+                                       /* x÷2         "     "    "     _*/
              do j=3  while  j*j<=x     /*starting at 3, find factors ≤√X*/
              if x//j\==0  then iterate /*J  divides  X  evenly,  so ... */
              s = s + j + x%j           /*··· add it and the other factor*/
diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-7.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-7.rexx
index 3da41e0bcc..ba48347f36 100644
--- a/Task/Perfect-numbers/REXX/perfect-numbers-7.rexx
+++ b/Task/Perfect-numbers/REXX/perfect-numbers-7.rexx
@@ -37,7 +37,7 @@ if r\==1  then return 0                /*Digital root ¬1? Then ¬perfect.*/
 s = 3 + x%2                            /*we know the following factors: */
                                        /*  1      ('cause Mama said so.)*/
                                        /*  2      ('cause it's even.)   */
-                                       /* x÷2     (   "     "    "  )   */
+                                       /* x÷2     (   "     "    "  )  _*/
              do j=3  while  j*j<=x     /*starting at 3, find factors ≤√X*/
              if x//j\==0  then iterate /*J  divides  X  evenly,  so ... */
              s = s + j + x%j           /*··· add it and the other factor*/
diff --git a/Task/Perfect-numbers/VBScript/perfect-numbers.vb b/Task/Perfect-numbers/VBScript/perfect-numbers.vb
new file mode 100644
index 0000000000..9f6190c7d7
--- /dev/null
+++ b/Task/Perfect-numbers/VBScript/perfect-numbers.vb
@@ -0,0 +1,17 @@
+Function IsPerfect(n)
+	IsPerfect = False
+	i = n - 1
+	sum = 0
+	Do While i > 0
+		If n Mod i = 0 Then
+			sum = sum + i
+		End If
+		i = i - 1
+	Loop
+	If sum = n Then
+		IsPerfect = True
+	End If
+End Function
+
+WScript.StdOut.Write IsPerfect(CInt(WScript.Arguments(0)))
+WScript.StdOut.WriteLine
diff --git a/Task/Permutation-test/Elixir/permutation-test.elixir b/Task/Permutation-test/Elixir/permutation-test.elixir
new file mode 100644
index 0000000000..e91d3abce7
--- /dev/null
+++ b/Task/Permutation-test/Elixir/permutation-test.elixir
@@ -0,0 +1,28 @@
+defmodule Permutation do
+  def statistic(ab, a) do
+    sumab = Enum.sum(ab)
+    suma  = Enum.sum(a)
+    suma / length(a) - (sumab - suma) / (length(ab) - length(a))
+  end
+
+  def test(a, b) do
+    ab = a ++ b
+    tobs = statistic(ab, a)
+    {under, count} = Enum.reduce(comb(ab, length(a)), {0,0}, fn perm, {under, count} ->
+      if statistic(ab, perm) <= tobs, do: {under+1, count+1},
+                                    else: {under  , count+1}
+    end)
+    under * 100.0 / count
+  end
+
+  defp comb(_, 0), do: [[]]
+  defp comb([], _), do: []
+  defp comb([h|t], m) do
+    (for l <- comb(t, m-1), do: [h|l]) ++ comb(t, m)
+  end
+end
+
+treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97]
+controlGroup   = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
+under = Permutation.test(treatmentGroup, controlGroup)
+:io.fwrite "under = ~.2f%, over = ~.2f%~n", [under, 100-under]
diff --git a/Task/Permutation-test/Julia/permutation-test-1.julia b/Task/Permutation-test/Julia/permutation-test-1.julia
new file mode 100644
index 0000000000..4841ff5aa4
--- /dev/null
+++ b/Task/Permutation-test/Julia/permutation-test-1.julia
@@ -0,0 +1,27 @@
+delta_mean{T<:Real}(a::Array{T,1}, b::Array{T,1}) = mean(a) - mean(b)
+
+function bifurcate{T<:Integer}(a::AbstractVector, sel::Array{T,1})
+    x = a[sel]
+    asel = trues(length(a))
+    asel[sel] = false
+    y = a[asel]
+    return (x, y)
+end
+
+function perm_sig_test{T<:Real}(treat::Array{T,1}, control::Array{T,1})
+    base_effect = delta_mean(treat, control)
+    pool = [treat, control]
+    tlen = length(treat)
+    plen = length(pool)
+    better = 0
+    worse = 0
+    for s in combinations(1:plen, tlen)
+        (t, c) = bifurcate(pool, s)
+        if base_effect < delta_mean(t, c)
+            better += 1
+        else
+            worse += 1
+        end
+    end
+    return (better, worse)
+end
diff --git a/Task/Permutation-test/Julia/permutation-test-2.julia b/Task/Permutation-test/Julia/permutation-test-2.julia
new file mode 100644
index 0000000000..b3ef8745e7
--- /dev/null
+++ b/Task/Permutation-test/Julia/permutation-test-2.julia
@@ -0,0 +1,17 @@
+treat = [85, 88, 75, 66, 25, 29, 83, 39, 97]
+control = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]
+
+(better, worse) = perm_sig_test(treat, control)
+
+tot = better + worse
+
+println("Permutation test using the following data:")
+println("Treated:  ", treat)
+println("Control:  ", control)
+
+println()
+println("There are ", tot, " different permuted groups of these data.")
+print(@sprintf("%8d, %5.2f%% ", better, 100better/tot))
+println("showed better than actual results.")
+print(@sprintf("%8d, %5.2f%% ", worse, 100worse/tot))
+println("showed equalivalent or worse results.")
diff --git a/Task/Permutation-test/Perl-6/permutation-test.pl6 b/Task/Permutation-test/Perl-6/permutation-test.pl6
index 329a994422..fb2c58400e 100644
--- a/Task/Permutation-test/Perl-6/permutation-test.pl6
+++ b/Task/Permutation-test/Perl-6/permutation-test.pl6
@@ -1,28 +1,17 @@
-proto combine (Int, @) {*}
-
-multi combine (0,  @)  { [] }
-multi combine ($,  []) { () }
-multi combine ($n, [$head, *@tail]) {
-    gather {
-	take [$head, @$_] for combine($n-1, @tail);
-	take [ @$_ ]      for combine($n  , @tail);
-    }
-}
-
 sub stats ( @test, @all ) {
-    (([+] @test) / +@test ) - ([+] @all, (@test X* -1)) / (@all - @test)
+    (([+] @test) / +@test ) - ([+] flat @all, (@test X* -1)) / (@all - @test)
 }
 
 
-my @treated = <85 88 75 66 25 29 83 39 97>;
-my @control = <68 41 10 49 16 65 32 92 28 98>;
-my @all = @treated, @control;
+my int @treated = <85 88 75 66 25 29 83 39 97>;
+my int @control = <68 41 10 49 16 65 32 92 28 98>;
+my int @all = flat @treated, @control;
 
 my $base = stats( @treated, @all );
 
 my @trials = 0, 0, 0;
 
-map { @trials[ 1 + ( stats( $_, @all ) <=> $base ) ]++ }, combine( +@treated, @all );
+@trials[ 1 + ( stats( $_, @all ) <=> $base ) ]++ for @all.combinations(+@treated);
 
 say 'Counts: <, =, > ', @trials;
 say 'Less than    : %', 100 * @trials[0] / [+] @trials;
diff --git a/Task/Permutation-test/REXX/permutation-test.rexx b/Task/Permutation-test/REXX/permutation-test.rexx
index 457bf88cc6..6701427568 100644
--- a/Task/Permutation-test/REXX/permutation-test.rexx
+++ b/Task/Permutation-test/REXX/permutation-test.rexx
@@ -1,30 +1,30 @@
-/*REXX program does a permutation test on  N + M  subjects (volunteers):*/
-                                  /*       ↑   ↑                        */
-                                  /*       │   │                        */
-                                  /*       │   └─────control  population*/
-                                  /*       └────────treatment population*/
+/*REXX program performs a permutation test on  N + M  subjects  (volunteers): */
+                                      /*       ↑   ↑                          */
+                                      /*       │   │                          */
+                                      /*       │   └─────control  population. */
+                                      /*       └────────treatment population. */
 n=9
 data=85 88 75 66 25 29 83 39 97         68 41 10 49 16 65 32 92 28 98
 w=words(data);    m=w-n
-say 'volunteer population given treatment:'   right(n,length(w))
-say ' control  population given a placebo:'   right(m,length(w))
+say 'volunteer population given treatment:'      right(n,length(w))
+say ' control  population given a placebo:'      right(m,length(w))
 say
-say 'treatment population efficacy % (percentages):'   subword(data,1,n)
-say ' control  population placebo  % (percentages):'   subword(data,n+1)
+say 'treatment population efficacy % (percentages):'     subword(data,1,n)
+say ' control  population placebo  % (percentages):'     subword(data,n+1)
 say
                      do v= 0  for w         ;    #.v=word(data,v+1) ;  end
 treat=0;             do i= 0  to n-1        ;    treat=treat+#.i    ;  end
-total=1;             do j=19  to m+1  by -1 ;    total=total*j      ;  end
-                     do k= 9  to  1   by -1 ;    total=total/k      ;  end
+  tot=1;             do j=19  to m+1  by -1 ;    tot=tot*j          ;  end
+                     do k= 9  to  1   by -1 ;    tot=tot/k          ;  end
 gt=picker(n+m, n, 0)
-le=total-gt
-say "<= "   format(100*le/total,,3)'%'   le     /*show 3 decimal places.*/
-say " > "   format(100*gt/total,,3)'%'   gt
-exit                                   /*stick a fork in it, we're done.*/
-/*──────────────────────────────────PICKER subroutine───────────────────*/
-picker:  procedure expose #. treat;      parse arg it,rest,eff
-if rest==0  then return eff>treat
-if it>rest  then q=picker(it-1, rest, eff)
-            else q=0
-itP=it-1
-return picker(itP, rest-1, eff+#.itP) + q
+le=tot-gt
+say "<= "  format(100*le/tot,,3)'%' le /*display number with 3 decimal places.*/
+say " > "  format(100*gt/tot,,3)'%' gt /*   "       "     "  "    "       "   */
+exit                                   /*stick a fork in it,  we're all done. */
+/*────────────────────────────────────────────────────────────────────────────*/
+picker:  procedure expose #. treat;                   parse arg it,rest,eff
+         if rest==0  then return  eff>treat
+         if it>rest  then q=picker(it-1, rest, eff)
+                     else q=0
+         itP=it-1
+         return picker(itP, rest-1, eff+#.itP) + q
diff --git a/Task/Permutations-Derangements/00DESCRIPTION b/Task/Permutations-Derangements/00DESCRIPTION
index 0862dc11d3..0f6d0b3b09 100644
--- a/Task/Permutations-Derangements/00DESCRIPTION
+++ b/Task/Permutations-Derangements/00DESCRIPTION
@@ -18,3 +18,4 @@ As an optional stretch goal:
 ;Cf.
 * [[Anagrams/Deranged anagrams]]
 * [[Best shuffle]]
+* [[Left_factorials]]
diff --git a/Task/Permutations-Derangements/Elixir/permutations-derangements.elixir b/Task/Permutations-Derangements/Elixir/permutations-derangements.elixir
new file mode 100644
index 0000000000..ab5c26cf96
--- /dev/null
+++ b/Task/Permutations-Derangements/Elixir/permutations-derangements.elixir
@@ -0,0 +1,29 @@
+defmodule Permutation do
+  def derangements(n) do
+    list = Enum.to_list(1..n)
+    Enum.filter(permutation(list), fn perm ->
+      Enum.zip(list, perm) |> Enum.all?(fn {a,b} -> a != b end)
+    end)
+  end
+
+  def subfact(0), do: 1
+  def subfact(1), do: 0
+  def subfact(n), do: (n-1) * (subfact(n-1) + subfact(n-2))
+
+  def permutation([]), do: [[]]
+  def permutation(list) do
+    for x <- list, y <- permutation(list -- [x]), do: [x|y]
+  end
+end
+
+IO.puts "derangements for n = 4"
+Enum.each(Permutation.derangements(4), &IO.inspect &1)
+
+IO.puts "\nNumber of derangements"
+IO.puts " n    derange   subfact"
+Enum.each(0..9, fn n ->
+  :io.format "~2w :~9w,~9w~n", [n, length(Permutation.derangements(n)), Permutation.subfact(n)]
+end)
+Enum.each(10..20, fn n ->
+  :io.format "~2w :~19w~n", [n, Permutation.subfact(n)]
+end)
diff --git a/Task/Permutations-Rank-of-a-permutation/Julia/permutations-rank-of-a-permutation.julia b/Task/Permutations-Rank-of-a-permutation/Julia/permutations-rank-of-a-permutation.julia
new file mode 100644
index 0000000000..06f2b83357
--- /dev/null
+++ b/Task/Permutations-Rank-of-a-permutation/Julia/permutations-rank-of-a-permutation.julia
@@ -0,0 +1,25 @@
+nobjs = 4
+a = collect(1:nobjs)
+println("All permutations of ", nobjs, " objects:")
+for i in 1:factorial(nobjs)
+    p = nthperm(a, i)
+    prank = nthperm(p)
+    print(@sprintf("%5d => ", i))
+    println(p, " (", prank, ")")
+end
+
+nobjs = 12
+nsamp = 4
+ptaken = Int[]
+println()
+println(nsamp, " random permutations of ", nobjs, " objects:")
+for i in 1:nsamp
+    p = randperm(nobjs)
+    prank = nthperm(p)
+    while prank in ptaken
+        p = randperm(nobjs)
+        prank = nthperm(p)
+    end
+    push!(ptaken, prank)
+    println("         ", p, " (", prank, ")")
+end
diff --git a/Task/Permutations-by-swapping/00DESCRIPTION b/Task/Permutations-by-swapping/00DESCRIPTION
index 19e14d9df5..2143cfe176 100644
--- a/Task/Permutations-by-swapping/00DESCRIPTION
+++ b/Task/Permutations-by-swapping/00DESCRIPTION
@@ -1,4 +1,6 @@
-Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. Show the permutations and signs of three items, in order of generation ''here''.
+Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
+Also generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd.
+Show the permutations and signs of three items, in order of generation ''here''.
 
 Such data are of use in generating the [[Matrix arithmetic|determinant]] of a square matrix and any functions created should bear this in mind.
 
@@ -7,6 +9,7 @@ Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutati
 ;References:
 * [[wp:Steinhaus–Johnson–Trotter algorithm|Steinhaus–Johnson–Trotter algorithm]]
 * [http://www.cut-the-knot.org/Curriculum/Combinatorics/JohnsonTrotter.shtml Johnson-Trotter Algorithm Listing All Permutations]
+* [http://stackoverflow.com/a/29044942/10562 Correction to] Heap's algorithm as presented in Wikipedia and widely distributed.
 
 ;Cf.:
 * [[Matrix arithmetic]]
diff --git a/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp b/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp
index d51f677e4b..5a096cb111 100644
--- a/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp
+++ b/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp
@@ -1,121 +1,62 @@
-/*
-The following code generates the permutations of the first 4 natural numbers.
-The permutations are displayed in lexical order, smallest to largest, with appropriate signs
-*/
-
 #include 
-#include 
+#include 
 
-//factorial function
-long
-fact(int size)
-{
-	int i;
-	long tmp = 1;
+using namespace std;
 
-	if(size<=1)
-		return 1;
-	else
-		for(i = size;i > 0;i--)
-			tmp *= i;
-	return tmp;
+vector UpTo(int n, int offset = 0)
+{
+	vector retval(n);
+	for (int ii = 0; ii < n; ++ii)
+		retval[ii] = ii + offset;
+	return retval;
 }
 
-
-//function to display the permutations.
-void
-Permutations(int N)
+struct JohnsonTrotterState_
 {
-	//indicates sign
-	short sign = 1;
-
-	//Tracks when to change sign.
-	unsigned short change_sign = 0;
-
-	//loop variables
-	short i = 0,j = 0,k = 0;
-
-	//iterations
-	long loops = fact(N);
-
-	//Array of pointers to hold the digits
-	int **Index_Nos_ptr = new int*[N];
-
-	//Repetition of each digit (Master copy)
-	int *Digit_Rep_Master = new int[N];
-
-	//Repetition of each digit (Local copy)
-	int *Digit_Rep_Local = new int[N];
-
-	//Index for Index_Nos_ptr
-	int *Element_Num = new int[N];
-
-
-	//Initialization
-	for(i = 0;i < N;i++){
-		//Allocate memory to hold the subsequent digits in the form of a LUT
-	            //For N = N, memory required for LUT = N(N+1)/2
-		Index_Nos_ptr[i] = new int[N-i];
-
-		//Initialise the repetition value of each digit (Master and Local)
-		//Each digit repeats for (i-1)!, where 1 is the position of the digit
-		Digit_Rep_Local[i] = Digit_Rep_Master[i] = fact(N-i-1);
-
-		//Initialise index values to access the arrays
-		Element_Num[i] = N-i-1;
-
-		//Initialise the arrays with the required digits
-		for(j = 0;j < N-i;j++)
-			*(Index_Nos_ptr[i] +j) = N-j-1;
-	}
-
-	while(loops-- > 0){
-		std::cout << "Perm: [";
-		for(i = 0;i < N;i++){
-			//Print from MSD to LSD
-			std::cout << " " << *(Index_Nos_ptr[i] + Element_Num[i]);
-
-			//Decrement the repetition count for each digit
-			if(--Digit_Rep_Local[i] <= 0){
-				//Refill the repitition factor
-				Digit_Rep_Local[i] = Digit_Rep_Master[i];
-
-				//And the index to access the required digit is also 0...
-				if(Element_Num[i] <= 0 && i != 0){
-					//Reset the index
-					Element_Num[i] = N-i-1;
-
-					//Update the numbers held in Index_Nos_ptr[]
-					for(j = 0,k = 0;j <= N-i;j++){
-						//Exclude the preceeding digit (from the previous array) already printed.
-						if(j != Element_Num[i-1]){
-							*(Index_Nos_ptr[i]+k)= *(Index_Nos_ptr[i-1]+j);
-							k++;
-						}
-					}
-				}else
-					//Decrement the index value so as to print the appropriate digit
-					//in the same array
-					Element_Num[i]--;
-			}
+	vector values_;
+	vector positions_;	// size is n+1, first element is not used
+	vector directions_;
+	int sign_;
+
+	JohnsonTrotterState_(int n) : values_(UpTo(n, 1)), positions_(UpTo(n + 1, -1)), directions_(n + 1, false), sign_(1) {}
+
+	int LargestMobile() const	// returns 0 if no mobile integer exists
+	{
+		for (int r = values_.size(); r > 0; --r)
+		{
+			const int loc = positions_[r] + (directions_[r] ? 1 : -1);
+			if (loc >= 0 && loc < values_.size() && values_[loc] < r)
+				return r;
 		}
-		std::cout<<"]  Sign: "<< sign <<"\n";
-
-		if(!(change_sign-- > 0)){
-			//Update the sign value.
-			sign = -sign;
-
-			change_sign = 1;
-		}
-
+		return 0;
 	}
 
-}
+	bool IsComplete() const { return LargestMobile() == 0; }
+
+	void operator++()	// implement Johnson-Trotter algorithm
+	{
+		const int r = LargestMobile();
+		const int rLoc = positions_[r];
+		const int lLoc = rLoc + (directions_[r] ? 1 : -1);
+		const int l = values_[lLoc];
+		// do the swap
+		swap(values_[lLoc], values_[rLoc]);
+		swap(positions_[l], positions_[r]);
+		sign_ = -sign_;
+		// change directions
+		for (auto pd = directions_.begin() + r + 1; pd != directions_.end(); ++pd)
+			*pd = !*pd;
+	}
+};
 
-int
-main()
+int main(void)
 {
-	Permutations(4);
-	getch();
-	return 0;
+	JohnsonTrotterState_ state(4);
+	do
+	{
+		for (auto v : state.values_)
+			cout << v << " ";
+		cout << "\n";
+		++state;
+	} while (!state.IsComplete());
 }
diff --git a/Task/Permutations-by-swapping/Clojure/permutations-by-swapping.clj b/Task/Permutations-by-swapping/Clojure/permutations-by-swapping.clj
new file mode 100644
index 0000000000..1a055e0fb8
--- /dev/null
+++ b/Task/Permutations-by-swapping/Clojure/permutations-by-swapping.clj
@@ -0,0 +1,5 @@
+(defn permutations [a-set]
+  (cond (empty? a-set) '(())
+        (empty? (rest a-set)) (list (apply list a-set))
+        :else (for [x a-set y (permutations (remove #{x} a-set))]
+                (cons x y))))
diff --git a/Task/Permutations-by-swapping/Elixir/permutations-by-swapping.elixir b/Task/Permutations-by-swapping/Elixir/permutations-by-swapping.elixir
new file mode 100644
index 0000000000..1c23c9f142
--- /dev/null
+++ b/Task/Permutations-by-swapping/Elixir/permutations-by-swapping.elixir
@@ -0,0 +1,40 @@
+defmodule Permutation do
+  def by_swap(n) do
+    p = Enum.to_list(0..-n) |> List.to_tuple
+    by_swap(n, p, 1)
+  end
+
+  defp by_swap(n, p, s) do
+    IO.puts "Perm: #{inspect for i <- 1..n, do: abs(elem(p,i))}  Sign: #{s}"
+    k = 0 |> step_up(n, p) |> step_down(n, p)
+    if k > 0 do
+      pk = elem(p,k)
+      i = if pk>0, do: k+1, else: k-1
+      p = Enum.reduce(1..n, p, fn i,acc ->
+        if abs(elem(p,i)) > abs(pk), do: put_elem(acc, i, -elem(acc,i)), else: acc
+      end)
+      pi = elem(p,i)
+      p = put_elem(p,i,pk) |> put_elem(k,pi)            # swap
+      by_swap(n, p, -s)
+    end
+  end
+
+  defp step_up(k, n, p) do
+    Enum.reduce(2..n, k, fn i,acc ->
+      if elem(p,i)<0 and abs(elem(p,i))>abs(elem(p,i-1)) and abs(elem(p,i))>abs(elem(p,acc)),
+        do: i, else: acc
+    end)
+  end
+
+  defp step_down(k, n, p) do
+    Enum.reduce(1..n-1, k, fn i,acc ->
+      if elem(p,i)>0 and abs(elem(p,i))>abs(elem(p,i+1)) and abs(elem(p,i))>abs(elem(p,acc)),
+        do: i, else: acc
+    end)
+  end
+end
+
+Enum.each(3..4, fn n ->
+  Permutation.by_swap(n)
+  IO.puts ""
+end)
diff --git a/Task/Permutations-by-swapping/Perl-6/permutations-by-swapping.pl6 b/Task/Permutations-by-swapping/Perl-6/permutations-by-swapping.pl6
index 0d0afdecb0..69279e1eec 100644
--- a/Task/Permutations-by-swapping/Perl-6/permutations-by-swapping.pl6
+++ b/Task/Permutations-by-swapping/Perl-6/permutations-by-swapping.pl6
@@ -1,4 +1,4 @@
-sub insert($x, @xs) { [@xs[0..$_-1], $x, @xs[$_..*]] for 0..+@xs }
+sub insert($x, @xs) { ([flat @xs[0 ..^ $_], $x, @xs[$_ .. *]] for 0 .. +@xs) }
 sub order($sg, @xs) { $sg > 0 ?? @xs !! @xs.reverse }
 
 multi perms([]) {
@@ -6,7 +6,7 @@ multi perms([]) {
 }
 
 multi perms([$x, *@xs]) {
-    perms(@xs).map({ order($_.value, insert($x, $_.key)) }) Z=> (+1,-1) xx *
+    perms(@xs).map({ |order($_.value, insert($x, $_.key)) }) Z=> |(+1,-1) xx *
 }
 
 .say for perms([0..2]);
diff --git a/Task/Permutations-by-swapping/PowerShell/permutations-by-swapping.psh b/Task/Permutations-by-swapping/PowerShell/permutations-by-swapping.psh
new file mode 100644
index 0000000000..1d8585c2c0
--- /dev/null
+++ b/Task/Permutations-by-swapping/PowerShell/permutations-by-swapping.psh
@@ -0,0 +1,42 @@
+function permutation ($array) {
+    function sign($A) {
+        $size = $A.Count
+        $sign = 1
+        for($i = 0; $i -lt $size; $i++) {
+            for($j = $i+1; $j -lt $size ; $j++) {
+                if($A[$j] -lt $A[$i]) { $sign *= -1}
+            }
+        }
+        $sign
+    }
+    function generate($n, $A, $i1, $i2, $cnt) {
+        if($n -eq 1) {
+            if($cnt -gt 0) {
+                "$A -- swapped positions: $i1 $i2 -- sign = $(sign $A)`n"
+            } else {
+                "$A -- sign = $(sign $A)`n"
+            }
+        }
+        else{
+            for( $i = 0; $i -lt ($n - 1); $i += 1) {
+                generate ($n - 1) $A $i1 $i2 $cnt
+                if($n % 2 -eq 0){
+                    $i1, $i2 = $i, ($n-1)
+                    $A[$i1], $A[$i2] = $A[$i2], $A[$i1]
+                    $cnt = 1
+                }
+                else{
+                    $i1, $i2 = 0, ($n-1)
+                    $A[$i1], $A[$i2] = $A[$i2], $A[$i1]
+                    $cnt = 1
+                }
+            }
+            generate ($n - 1) $A $i1 $i2 $cnt
+        }
+    }
+    $n = $array.Count
+    if($n -gt 0) {
+        (generate $n $array  0 ($n-1) 0)
+    } else {$array}
+}
+permutation @(1,2,3,4)
diff --git a/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx b/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx
index 880fbdf3be..340c8ae4fd 100644
--- a/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx
+++ b/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx
@@ -1,60 +1,53 @@
-/*REXX pgm generates all permutations of N different objects by swapping*/
-parse arg things bunch inbetween names /*get optional arguments from CL.*/
-things=p(things 4)                     /*use the default for  THINGS ?  */
-bunch =p(bunch things)                 /* "   "     "     "   BUNCH  ?  */
-    /*╔════════════════════════════════════════════════════════════════╗
-      ║         things  (optional)   defaults to 4.                    ║
-      ║          bunch  (optional)   defaults to THINGS.               ║
-      ║      inbetween  (optional)   defaults to a  [null].            ║
-      ║          names  (optional)   defaults to digits (and letters). ║
-      ╚════════════════════════════════════════════════════════════════╝*/
-upper inbetween;  if inbetween=='NONE' | inbetween="NULL"  then inbetween=
-call permSets things, bunch, inbetween, names
-exit                                   /*stick a fork in it, we're done.*/
-/*──────────────────────────────────one─liner subrlutines───────────────*/
-!: procedure;  !=1;       do j=2  to arg(1);  !=!*j;  end;        return !
-p: return word(arg(1), 1)              /*pick the first word from a list*/
-/*──────────────────────────────────GETONE subroutine───────────────────*/
-getOne: if length(z)==y  then return  substr(z,arg(1),1)
-                         else return  sep||word(translate(z,,','), arg(1))
-/*──────────────────────────────────PERMSETS subroutine─────────────────*/
-permSets: procedure; parse arg x,y,between,uSyms /*X things Y at a time.*/
-sep=;           !.=0                   /*X   can't be > length(@0abcs). */
-@abc = 'abcdefghijklmnopqrstuvwxyz';   parse upper var  @abc  @abcU
-@abcS= @abcU || @abc;   @0abcS=123456789 || @abcS
-z=                                     /*set  Z  to a null value.       */
-     do i=1  for x                     /*build a list of (perm) symbols.*/
-     _=p(word(uSyms,i)  p(substr(@0abcS,i,1) k))  /*get or gen a symbol.*/
-     if length(_)\==1   then sep=','   /*if not 1st char, then use SEP. */
-     z=z || sep || _                   /*append it to the symbol list.  */
+/*REXX program generates all permutations of N different objects by swapping. */
+parse arg things bunch .               /*get optional arguments from the C.L. */
+things = p(things 4)                   /*should use the default for  THINGS ? */
+bunch  = p(bunch things)               /*   "    "   "     "     "   BUNCH  ? */
+call permSets things, bunch            /*invoke permutations by swapping sub. */
+exit                                   /*stick a fork in it,  we're all done. */
+/*──────────────────────────────────one─liner subroutines─────────────────────*/
+!:  procedure;  !=1;        do j=2  to arg(1);  !=!*j;  end;         return !
+c:  return substr(arg(1),arg(2),1)     /*pick a single character from a string*/
+p:  return word(arg(1), 1)             /*pick 1st word (or number) from a list*/
+/*──────────────────────────────────PERMSETS subroutine───────────────────────*/
+permSets: procedure; parse arg x,y     /*take   X  things   Y   at a time.    */
+!.=0;     pad=left('',x*y)             /*Note:  X  can't be > length(@0abcs). */
+@abc ='abcdefghijklmnopqrstuvwxyz';   @abcU=@abc;  upper @abcU   /*build syms.*/
+@abcS=@abcU || @abc;   @0abcS=123456789 || @abcS                 /*···and more*/
+z=                                     /*define Z to be a null value for start*/
+     do i=1  for x                     /*build list of (permutation) symbols. */
+     z=z || c(@0abcS,i)                /*append the char to the symbol list.  */
      end   /*i*/
-#=1
-if sep\==''  then z=strip(z, 'L', ",") /*strip leading commas from  Z.  */
-!.z=1;  q=z;  s=1;  times=!(x)%!(x-y)  /*calculate TIMES using factorial*/
-w=max(length(z),length('permute'))     /*maximum width of Z and PERMUTE.*/
-say  center('permutations for '   x   ' with '    y    "at a time",60,'═')
+#=1                                    /*the number of permutations  (so far).*/
+!.z=1;  q=z;  s=1;  times=!(x)% !(x-y) /*calculate (#) TIMES  using factorial.*/
+w=max(length(z), length('permute'))    /*maximum width of  Z and also PERMUTE.*/
+say center('permutations for '   x   ' things taken '   y   " at a time",60,'═')
 say
-say   'permutation'    center("permute",w,'─')    'sign'
-say   '───────────'    center("───────",w,'─')    '────'
-say   center(#,11)     center(z        ,w)        right(s,4)
+say   pad    'permutation'    center("permute",w,'─')     'sign'
+say   pad    '───────────'    center("───────",w,'─')     '────'
+say   pad    center(#,11)     center(z        ,w)       right(s, 4-1)
 
-    do step=1   until  #==times
-           do   k=1    for x-1
-             do m=k+1  to  x           /*method doesn't use adjaceny.   */
-             ?=
-                 do n=1  for x         /*build a new permutation by swap*/
-                 if n\==k & n\==m  then               ?=? || getOne(n)
-                                   else if n==k  then ?=? || getOne(m)
-                                                 else ?=? || getOne(k)
-                 end   /*n*/
-             if sep\==''  then ?=strip(?,'L',sep)
-             z=?                       /*save this permute for next swap*/
-             if !.?  then iterate m    /*if defined before, try next one*/
-             #=#+1;  s=-s;  say  center(#,11)    center(?,w)    right(s,4)
-             !.?=1
-             iterate step
-             end       /*m*/
-           end         /*k*/
-    end                /*step*/
-
-return
+    do $=1   until  #==times           /*perform permutation until # of times.*/
+      do   k=1    for x-1              /*step thru things for  things-1 times.*/
+        do m=k+1  to  x                /*this method doesn't use adjacency.   */
+        ?=                             /*begin this with a blank (null) slate.*/
+            do n=1  for x              /*build the new permutation by swapping*/
+            if n\==k & n\==m  then               ? =   ? ||  c(z, n)
+                              else if n==k  then ? =   ? ||  c(z, m)
+                                            else ? =   ? ||  c(z, k)
+            end   /*n*/
+        z=?                            /*save this permutation for next swap. */
+        if !.?  then iterate m         /*if defined before, then try next 'un.*/
+        _=0                            /* [↓]  count number of swapped symbols*/
+            do d=1  for x  while $\==1;   _=_+(c(?,d)\==c(prev,d));   end  /*d*/
+        if _>2  then do;         _=z
+                     a=$//x+1;   q=q+_ /* [← ↓]  this swapping tries adjacency*/
+                     b=q//x+1;   if b==a  then b=a+1;   if b>x  then b=a-1
+                     z=overlay(c(z,b), overlay(c(z,a), _, b),  a)
+                     iterate $         /*now, try this particular permutation.*/
+                     end
+        #=#+1;  s=-s;    say pad   center(#,11)     center(?,w)     right(s,4-1)
+        !.?=1;  prev=?;      iterate $ /*now, try another swapped permutation.*/
+        end   /*m*/
+      end     /*k*/
+    end       /*$*/
+return                                 /*we're all finished with permutating. */
diff --git a/Task/Permutations/Clojure/permutations.clj b/Task/Permutations/Clojure/permutations-1.clj
similarity index 100%
rename from Task/Permutations/Clojure/permutations.clj
rename to Task/Permutations/Clojure/permutations-1.clj
diff --git a/Task/Permutations/Clojure/permutations-2.clj b/Task/Permutations/Clojure/permutations-2.clj
new file mode 100644
index 0000000000..6e41e875c6
--- /dev/null
+++ b/Task/Permutations/Clojure/permutations-2.clj
@@ -0,0 +1,35 @@
+(defn- iter-perm [v]
+  (let [len (count v),
+	j (loop [i (- len 2)]
+	     (cond (= i -1) nil
+		   (< (v i) (v (inc i))) i
+		   :else (recur (dec i))))]
+    (when j
+      (let [vj (v j),
+	    l (loop [i (dec len)]
+		(if (< vj (v i)) i (recur (dec i))))]
+	(loop [v (assoc v j (v l) l vj), k (inc j), l (dec len)]
+	  (if (< k l)
+	    (recur (assoc v k (v l) l (v k)) (inc k) (dec l))
+	    v))))))
+
+
+(defn- vec-lex-permutations [v]
+  (when v (cons v (lazy-seq (vec-lex-permutations (iter-perm v))))))
+
+(defn lex-permutations
+  "Fast lexicographic permutation generator for a sequence of numbers"
+  [c]
+  (lazy-seq
+   (let [vec-sorted (vec (sort c))]
+     (if (zero? (count vec-sorted))
+       (list [])
+       (vec-lex-permutations vec-sorted)))))
+
+(defn permutations
+  "All the permutations of items, lexicographic by index"
+  [items]
+  (let [v (vec items)]
+    (map #(map v %) (lex-permutations (range (count v))))))
+
+(println (permutations [1 2 3]))
diff --git a/Task/Permutations/Eiffel/permutations.e b/Task/Permutations/Eiffel/permutations.e
index f944ecd054..3a0fa50f1d 100644
--- a/Task/Permutations/Eiffel/permutations.e
+++ b/Task/Permutations/Eiffel/permutations.e
@@ -1,34 +1,47 @@
-permute(a: ARRAY[INTEGER]; k: INTEGER)
-	require
-		 ar_not_void: a.count>=1
-		 k_valid_index: k>0
-	local
-		i,t: INTEGER
-	do
-	if k=a.count then
-		across a as ar loop io.put_string (ar.item.out)  end
-		io.put_string ("%N")
-	else
-		from
-			i:= k
-		until
-			i> a.count
-		loop
-			t:= a[k]
-			a[k]:= a[i]
-			a[i]:= t
-			permute(a,k+1)
-			t:= a[k]
-			a[k]:= a[i]
-			a[i]:= t
-			i:= i+1
+class
+	APPLICATION
+
+create
+	make
+
+feature {NONE}
+
+	make
+		do
+			test := <<2, 5, 1>>
+			permute (test, 1)
+		end
+
+	test: ARRAY [INTEGER]
+
+	permute (a: ARRAY [INTEGER]; k: INTEGER)
+			-- All permutations of 'a'.
+		require
+			count_positive: a.count > 0
+			k_valid_index: k > 0
+		local
+			t: INTEGER
+		do
+			if k = a.count then
+				across
+					a as ar
+				loop
+					io.put_integer (ar.item)
+				end
+				io.new_line
+			else
+				across
+					k |..| a.count as c
+				loop
+					t := a [k]
+					a [k] := a [c.item]
+					a [c.item] := t
+					permute (a, k + 1)
+					t := a [k]
+					a [k] := a [c.item]
+					a [c.item] := t
+				end
+			end
 		end
-	end
-make
-	do
-			test:= << 2,5,1>>
-			permute(test, 1)
-	end
-	test: ARRAY[INTEGER]
 
 end
diff --git a/Task/Permutations/Elixir/permutations.elixir b/Task/Permutations/Elixir/permutations.elixir
new file mode 100644
index 0000000000..b275df3036
--- /dev/null
+++ b/Task/Permutations/Elixir/permutations.elixir
@@ -0,0 +1,8 @@
+defmodule RC do
+  def permute([]), do: [[]]
+  def permute(list) do
+    for x <- list, y <- permute(list -- [x]), do: [x|y]
+  end
+end
+
+IO.inspect RC.permute([1, 2, 3])
diff --git a/Task/Permutations/Fortran/permutations-2.f b/Task/Permutations/Fortran/permutations-2.f
index 9aca8ed593..4015ec0000 100644
--- a/Task/Permutations/Fortran/permutations-2.f
+++ b/Task/Permutations/Fortran/permutations-2.f
@@ -1,41 +1,27 @@
-      program nptest
-      integer n,i,a
-      logical nextp
-      external nextp
-      parameter(n=4)
-      dimension a(n)
-      do i=1,n
-      a(i)=i
-      enddo
-   10 print *,(a(i),i=1,n)
-      if(nextp(n,a)) go to 10
-      end
-
-      function nextp(n,a)
-      integer n,a,i,j,k,t
-      logical nextp
-      dimension a(n)
-      i=n-1
-   10 if(a(i).lt.a(i+1)) go to 20
-      i=i-1
-      if(i.eq.0) go to 20
-      go to 10
-   20 j=i+1
-      k=n
-   30 t=a(j)
-      a(j)=a(k)
-      a(k)=t
-      j=j+1
-      k=k-1
-      if(j.lt.k) go to 30
-      j=i
-      if(j.ne.0) go to 40
-      nextp=.false.
-      return
-   40 j=j+1
-      if(a(j).lt.a(i)) go to 40
-      t=a(i)
-      a(i)=a(j)
-      a(j)=t
-      nextp=.true.
-      end
+program allperm
+    implicit none
+    integer :: n, i
+    integer, allocatable :: a(:)
+    read *, n
+    allocate(a(n))
+    a = [ (i, i = 1, n) ]
+    call perm(1)
+    deallocate(a)
+contains
+    recursive subroutine perm(i)
+        integer :: i, j, t
+        if (i == n) then
+            print *, a
+        else
+            do j = i, n
+                t = a(i)
+                a(i) = a(j)
+                a(j) = t
+                call perm(i + 1)
+                t = a(i)
+                a(i) = a(j)
+                a(j) = t
+            end do
+        end if
+    end subroutine
+end program
diff --git a/Task/Permutations/Fortran/permutations-3.f b/Task/Permutations/Fortran/permutations-3.f
new file mode 100644
index 0000000000..9aca8ed593
--- /dev/null
+++ b/Task/Permutations/Fortran/permutations-3.f
@@ -0,0 +1,41 @@
+      program nptest
+      integer n,i,a
+      logical nextp
+      external nextp
+      parameter(n=4)
+      dimension a(n)
+      do i=1,n
+      a(i)=i
+      enddo
+   10 print *,(a(i),i=1,n)
+      if(nextp(n,a)) go to 10
+      end
+
+      function nextp(n,a)
+      integer n,a,i,j,k,t
+      logical nextp
+      dimension a(n)
+      i=n-1
+   10 if(a(i).lt.a(i+1)) go to 20
+      i=i-1
+      if(i.eq.0) go to 20
+      go to 10
+   20 j=i+1
+      k=n
+   30 t=a(j)
+      a(j)=a(k)
+      a(k)=t
+      j=j+1
+      k=k-1
+      if(j.lt.k) go to 30
+      j=i
+      if(j.ne.0) go to 40
+      nextp=.false.
+      return
+   40 j=j+1
+      if(a(j).lt.a(i)) go to 40
+      t=a(i)
+      a(i)=a(j)
+      a(j)=t
+      nextp=.true.
+      end
diff --git a/Task/Permutations/Julia/permutations.julia b/Task/Permutations/Julia/permutations.julia
new file mode 100644
index 0000000000..de66009352
--- /dev/null
+++ b/Task/Permutations/Julia/permutations.julia
@@ -0,0 +1,11 @@
+term = "RCode"
+i = 0
+pcnt = factorial(length(term))
+print("All the permutations of ", term, " (", pcnt, "):\n    ")
+for p in permutations(split(term, ""))
+    print(join(p), " ")
+    i += 1
+    i %= 12
+    i != 0 || print("\n    ")
+end
+println()
diff --git a/Task/Permutations/PowerShell/permutations.psh b/Task/Permutations/PowerShell/permutations.psh
new file mode 100644
index 0000000000..66ac072886
--- /dev/null
+++ b/Task/Permutations/PowerShell/permutations.psh
@@ -0,0 +1,26 @@
+function permutation ($array) {
+    function generate($n, $array, $A) {
+        if($n -eq 1) {
+            $array[$A] -join ' '
+        }
+        else{
+            for( $i = 0; $i -lt ($n - 1); $i += 1) {
+                generate ($n - 1) $array $A
+                if($n % 2 -eq 0){
+                    $i1, $i2 = $i, ($n-1)
+                    $A[$i1], $A[$i2] = $A[$i2], $A[$i1]
+                }
+                else{
+                    $i1, $i2 = 0, ($n-1)
+                    $A[$i1], $A[$i2] = $A[$i2], $A[$i1]
+                }
+            }
+            generate ($n - 1) $array $A
+        }
+    }
+    $n = $array.Count
+    if($n -gt 0) {
+        (generate $n $array (0..($n-1)))
+    } else {$array}
+}
+permutation @('A','B','C')
diff --git a/Task/Permutations/Python/permutations.py b/Task/Permutations/Python/permutations-1.py
similarity index 100%
rename from Task/Permutations/Python/permutations.py
rename to Task/Permutations/Python/permutations-1.py
diff --git a/Task/Permutations/Python/permutations-2.py b/Task/Permutations/Python/permutations-2.py
new file mode 100644
index 0000000000..becf838fee
--- /dev/null
+++ b/Task/Permutations/Python/permutations-2.py
@@ -0,0 +1,26 @@
+def perm1(n):
+    a = list(range(n))
+    def sub(i):
+        if i == n - 1:
+            yield tuple(a)
+        else:
+            for k in range(i, n):
+                a[i], a[k] = a[k], a[i]
+                yield from sub(i + 1)
+                a[i], a[k] = a[k], a[i]
+    yield from sub(0)
+
+def perm2(n):
+    a = list(range(n))
+    def sub(i):
+        if i == n - 1:
+            yield tuple(a)
+        else:
+            for k in range(i, n):
+                a[i], a[k] = a[k], a[i]
+                yield from sub(i + 1)
+            x = a[i]
+            for k in range(i + 1, n):
+                a[k - 1] = a[k]
+            a[n - 1] = x
+    yield from sub(0)
diff --git a/Task/Permutations/Python/permutations-3.py b/Task/Permutations/Python/permutations-3.py
new file mode 100644
index 0000000000..a583d1e402
--- /dev/null
+++ b/Task/Permutations/Python/permutations-3.py
@@ -0,0 +1,15 @@
+for u in perm1(3): print(u)
+(0, 1, 2)
+(0, 2, 1)
+(1, 0, 2)
+(1, 2, 0)
+(2, 1, 0)
+(2, 0, 1)
+
+for u in perm2(3): print(u)
+(0, 1, 2)
+(0, 2, 1)
+(1, 0, 2)
+(1, 2, 0)
+(2, 0, 1)
+(2, 1, 0)
diff --git a/Task/Permutations/Python/permutations-4.py b/Task/Permutations/Python/permutations-4.py
new file mode 100644
index 0000000000..22827e2e30
--- /dev/null
+++ b/Task/Permutations/Python/permutations-4.py
@@ -0,0 +1,39 @@
+def nextperm(a):
+    n = len(a)
+    i = n - 1
+    while i > 0 and a[i - 1] > a[i]:
+        i -= 1
+    j = i
+    k = n - 1
+    while j < k:
+        a[j], a[k] = a[k], a[j]
+        j += 1
+        k -= 1
+    if i == 0:
+        return False
+    else:
+        j = i
+        while a[j] < a[i - 1]:
+            j += 1
+        a[i - 1], a[j] = a[j], a[i - 1]
+        return True
+
+def perm3(n):
+    if type(n) is int:
+        if n < 1:
+            return []
+        a = list(range(n))
+    else:
+        a = sorted(n)
+    u = [tuple(a)]
+    while nextperm(a):
+        u.append(tuple(a))
+    return u
+
+for p in perm3(3): print(p)
+(0, 1, 2)
+(0, 2, 1)
+(1, 0, 2)
+(1, 2, 0)
+(2, 0, 1)
+(2, 1, 0)
diff --git a/Task/Pernicious-numbers/00DESCRIPTION b/Task/Pernicious-numbers/00DESCRIPTION
index 4b0169e942..acb086296a 100644
--- a/Task/Pernicious-numbers/00DESCRIPTION
+++ b/Task/Pernicious-numbers/00DESCRIPTION
@@ -1,12 +1,14 @@
-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. +A   ''[[wp:Pernicious number|pernicious number]]''   is a positive integer whose   [[population count]]   is a prime. -;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). +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 therefore   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]]. +* 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/Befunge/pernicious-numbers.bf b/Task/Pernicious-numbers/Befunge/pernicious-numbers.bf new file mode 100644 index 0000000000..91124a3d08 --- /dev/null +++ b/Task/Pernicious-numbers/Befunge/pernicious-numbers.bf @@ -0,0 +1,5 @@ +55*00p1>:"ZOA>/"***7-*>\:2>/\v +>8**`!#^_$@\<(^v^)>/#2^#\<2 2 +^+**"X^yYo":+1<_:.48*,00v|: <% +v".D}Tx"$,+55_^#!p00:-1g * + : * * + ^^ ! % 2 $ <^ <^ diff --git a/Task/Pernicious-numbers/Eiffel/pernicious-numbers.e b/Task/Pernicious-numbers/Eiffel/pernicious-numbers.e new file mode 100644 index 0000000000..3cdfa4b600 --- /dev/null +++ b/Task/Pernicious-numbers/Eiffel/pernicious-numbers.e @@ -0,0 +1,100 @@ +class + APPLICATION + +create + make + +feature + + make + -- Test of is_pernicious_number. + local + test: LINKED_LIST [INTEGER] + i: INTEGER + do + create test.make + from + i := 1 + until + test.count = 25 + loop + if is_pernicious_number (i) then + test.extend (i) + end + i := i + 1 + end + across + test as t + loop + io.put_string (t.item.out + " ") + end + io.new_line + across + 888888877 |..| 888888888 as c + loop + if is_pernicious_number (c.item) then + io.put_string (c.item.out + " ") + end + end + end + + is_pernicious_number (n: INTEGER): BOOLEAN + -- Is 'n' a pernicious_number? + require + positiv_input: n > 0 + do + Result := is_prime (count_population (n)) + end + +feature{NONE} + + count_population (n: INTEGER): INTEGER + -- Population count of 'n'. + require + positiv_input: n > 0 + local + j: INTEGER + math: DOUBLE_MATH + do + create math + j := math.log_2 (n).ceiling + 1 + across + 0 |..| j as c + loop + if n.bit_test (c.item) then + Result := Result + 1 + end + end + end + + is_prime (n: INTEGER): BOOLEAN + --Is 'n' a prime number? + require + positiv_input: n > 0 + local + i: INTEGER + max: REAL_64 + math: DOUBLE_MATH + do + create math + if n = 2 then + Result := True + elseif n <= 1 or n \\ 2 = 0 then + Result := False + else + Result := True + max := math.sqrt (n) + from + i := 3 + until + i > max + loop + if n \\ i = 0 then + Result := False + end + i := i + 2 + end + end + end + +end diff --git a/Task/Pernicious-numbers/Elixir/pernicious-numbers-1.elixir b/Task/Pernicious-numbers/Elixir/pernicious-numbers-1.elixir new file mode 100644 index 0000000000..ecbd5de390 --- /dev/null +++ b/Task/Pernicious-numbers/Elixir/pernicious-numbers-1.elixir @@ -0,0 +1,41 @@ +defmodule SieveofEratosthenes do + def init(lim) do + find_primes(2,lim,(2..lim)) + end + + def find_primes(count,lim,nums) when (count * count) > lim do + nums + end + + def find_primes(count,lim,nums) when (count * count) <= lim do + e = Enum.reject(nums,&(rem(&1,count) == 0 and &1 > count)) + find_primes(count+1,lim,e) + end +end + +defmodule PerniciousNumbers do + def take(n) do + primes = SieveofEratosthenes.init(100) + Stream.iterate(1,&(&1+1)) + |> Stream.filter(&(pernicious?(&1,primes))) + |> Enum.take(n) + |> IO.inspect + end + + def between(a..b) do + primes = SieveofEratosthenes.init(100) + a..b + |> Stream.filter(&(pernicious?(&1,primes))) + |> Enum.to_list + |> IO.inspect + end + + def ones(num) do + num + |> Integer.to_string(2) + |> String.codepoints + |> Enum.count(fn n -> n == "1" end) + end + + def pernicious?(n,primes), do: Enum.member?(primes,ones(n)) +end diff --git a/Task/Pernicious-numbers/Elixir/pernicious-numbers-2.elixir b/Task/Pernicious-numbers/Elixir/pernicious-numbers-2.elixir new file mode 100644 index 0000000000..e57f3c93ca --- /dev/null +++ b/Task/Pernicious-numbers/Elixir/pernicious-numbers-2.elixir @@ -0,0 +1,2 @@ +PerniciousNumbers.take(25) +PerniciousNumbers.between(888_888_877..888_888_888) diff --git a/Task/Pernicious-numbers/Fortran/pernicious-numbers.f b/Task/Pernicious-numbers/Fortran/pernicious-numbers.f new file mode 100644 index 0000000000..72827c287f --- /dev/null +++ b/Task/Pernicious-numbers/Fortran/pernicious-numbers.f @@ -0,0 +1,55 @@ +program pernicious + implicit none + + integer :: i, n + + i = 1 + n = 0 + do + if(isprime(popcnt(i))) then + write(*, "(i0, 1x)", advance = "no") i + n = n + 1 + if(n == 25) exit + end if + i = i + 1 + end do + + write(*,*) + do i = 888888877, 888888888 + if(isprime(popcnt(i))) write(*, "(i0, 1x)", advance = "no") i + end do + +contains + +function popcnt(x) + integer :: popcnt + integer, intent(in) :: x + integer :: i + + popcnt = 0 + do i = 0, 31 + if(btest(x, i)) popcnt = popcnt + 1 + end do + +end function + +function isprime(number) + logical :: isprime + integer, intent(in) :: number + integer :: i + + if(number == 2) then + isprime = .true. + else if(number < 2 .or. mod(number,2) == 0) then + isprime = .false. + else + isprime = .true. + do i = 3, int(sqrt(real(number))), 2 + if(mod(number,i) == 0) then + isprime = .false. + exit + end if + end do + end if +end function +end program diff --git a/Task/Pernicious-numbers/Julia/pernicious-numbers.julia b/Task/Pernicious-numbers/Julia/pernicious-numbers.julia new file mode 100644 index 0000000000..eea1d0f55e --- /dev/null +++ b/Task/Pernicious-numbers/Julia/pernicious-numbers.julia @@ -0,0 +1,19 @@ +ispernicious(n::Int) = isprime(count_ones(n)) + +pcnt = 0 +i = 0 +print(" ") +while pcnt < 25 + i += 1 + ispernicious(i) || continue + pcnt += 1 + print(i, " ") +end +println() + +print(" ") +for i in 888888877:888888888 + ispernicious(i) || continue + print(i, " ") +end +println() diff --git a/Task/Pernicious-numbers/PL-I/pernicious-numbers.pli b/Task/Pernicious-numbers/PL-I/pernicious-numbers.pli new file mode 100644 index 0000000000..379d5c91d4 --- /dev/null +++ b/Task/Pernicious-numbers/PL-I/pernicious-numbers.pli @@ -0,0 +1,28 @@ +pern: procedure options (main); + declare (i, n) fixed binary (31); + + n = 3; + do i = 1 to 25, 888888877 to 888888888; + if i = 888888877 then do; n = i ; put skip; end; + do while ( ^is_prime ( tally(bit(n), '1'b) ) ); + n = n + 1; + end; + put edit( trim(n), ' ') (a); + n = n + 1; + end; + +is_prime: procedure (n) returns (bit(1)); + declare n fixed (15); + declare i fixed (10); + + 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 to sqrt(n) by 2; + if mod(n, i) = 0 then return ('0'b); + end; + return ('1'b); +end is_prime; + +end pern; diff --git a/Task/Pernicious-numbers/VBScript/pernicious-numbers.vb b/Task/Pernicious-numbers/VBScript/pernicious-numbers.vb new file mode 100644 index 0000000000..95f6e5c0a3 --- /dev/null +++ b/Task/Pernicious-numbers/VBScript/pernicious-numbers.vb @@ -0,0 +1,64 @@ +'check if the number is pernicious +Function IsPernicious(n) + IsPernicious = False + bin_num = Dec2Bin(n) + sum = 0 + For h = 1 To Len(bin_num) + sum = sum + CInt(Mid(bin_num,h,1)) + Next + If IsPrime(sum) Then + IsPernicious = True + End If +End Function + +'prime number validation +Function IsPrime(n) + If n = 2 Then + IsPrime = True + ElseIf n <= 1 Or n Mod 2 = 0 Then + IsPrime = False + Else + IsPrime = True + For i = 3 To Int(Sqr(n)) Step 2 + If n Mod i = 0 Then + IsPrime = False + Exit For + End If + Next + End If +End Function + +'decimal to binary converter +Function Dec2Bin(n) + q = n + Dec2Bin = "" + Do Until q = 0 + Dec2Bin = CStr(q Mod 2) & Dec2Bin + q = Int(q / 2) + Loop +End Function + +'display the first 25 pernicious numbers +c = 0 +WScript.StdOut.Write "First 25 Pernicious Numbers:" +WScript.StdOut.WriteLine +For k = 1 To 100 + If IsPernicious(k) Then + WScript.StdOut.Write k & ", " + c = c + 1 + End If + If c = 25 Then + Exit For + End If +Next +WScript.StdOut.WriteBlankLines(2) + +'display the pernicious numbers between 888,888,877 to 888,888,888 (inclusive) +WScript.StdOut.Write "Pernicious Numbers between 888,888,877 to 888,888,888 (inclusive):" +WScript.StdOut.WriteLine +For l = 888888877 To 888888888 + If IsPernicious(l) Then + WScript.StdOut.Write l & ", " + End If +Next +WScript.StdOut.WriteLine diff --git a/Task/Phrase-reversals/ALGOL-68/phrase-reversals.alg b/Task/Phrase-reversals/ALGOL-68/phrase-reversals.alg new file mode 100644 index 0000000000..5d2e3b4803 --- /dev/null +++ b/Task/Phrase-reversals/ALGOL-68/phrase-reversals.alg @@ -0,0 +1,55 @@ +# reverses the characters in str from start pos to end pos # +PROC in place reverse = ( REF STRING str, INT start pos, INT end pos )VOID: + BEGIN + INT fpos := start pos, epos := end pos; + WHILE fpos < epos + DO + CHAR c := str[ fpos ]; + str[ fpos ] := str[ epos ]; + str[ epos ] := c; + fpos +:= 1; + epos -:= 1 + OD + END; # in place reverse # + +STRING original phrase := "rosetta code phrase reversal"; + +STRING whole reversed := original phrase; +in place reverse( whole reversed, LWB whole reversed, UPB whole reversed ); + +# reverse the individual words # +STRING words reversed := original phrase; +INT start pos := LWB words reversed; + +WHILE + # skip leading spaces # + WHILE IF start pos <= UPB words reversed + THEN words reversed[ start pos ] = " " + ELSE FALSE + FI + DO start pos +:= 1 + OD; + start pos <= UPB words reversed +DO + # have another word, find it # + INT end pos := start pos; + WHILE IF end pos <= UPB words reversed + THEN words reversed[ end pos ] /= " " + ELSE FALSE + FI + DO end pos +:= 1 + OD; + in place reverse( words reversed, start pos, end pos - 1 ); + start pos := end pos + 1 +OD; + +# reversing the reversed words in the same order as the original will # +# reverse the order of the words # +STRING order reversed := words reversed; +in place reverse( order reversed, LWB order reversed, UPB order reversed ); + +print( ( original phrase, ": whole reversed -> ", whole reversed, newline + , original phrase, ": words reversed -> ", words reversed, newline + , original phrase, ": order reversed -> ", order reversed, newline + ) + ) diff --git a/Task/Phrase-reversals/Batch-File/phrase-reversals.bat b/Task/Phrase-reversals/Batch-File/phrase-reversals.bat new file mode 100644 index 0000000000..37a7a96c39 --- /dev/null +++ b/Task/Phrase-reversals/Batch-File/phrase-reversals.bat @@ -0,0 +1,49 @@ +@echo off +setlocal enabledelayedexpansion + %=== The Main Thing... ===% +set "inp=Rosetta Code phrase reversal" +call :reverse_string "!inp!" rev1 +call :reverse_order "!inp!" rev2 +call :reverse_words "!inp!" rev3 +cls +echo.Original: !inp! +echo.Reversed: !rev1! +echo.Reversed Order: !rev2! +echo.Reversed Words: !rev3! +pause>nul +exit /b 0 + %=== /The Main Thing... ===% + + %=== Reverse the Order Function ===% +:reverse_order +set var1=%2 +set %var1%=&set word=&set str1=%1 +:process1 +for /f "tokens=1,*" %%A in (%str1%) do (set str1=%%B&set word=%%A) +set %var1%=!word! !%var1%!&set str1="!str1!" +if not !str1!=="" goto process1 +goto :EOF + %=== /Reverse the Order Function ===% + + %=== Reverse the Whole String Function ===% +:reverse_string +set var2=%2 +set %var2%=&set cnt=0&set str2=%~1 +:process2 +set char=!str2:~%cnt%,1!&set %var2%=!char!!%var2%! +if not "!char!"=="" set /a cnt+=1&goto process2 +goto :EOF + %=== /Reverse the Whole String Function ===% + + %=== Reverse each Words Function ===% +:reverse_words +set var3=%2 +set %var3%=&set word=&set str3=%1 +:process3 +for /f "tokens=1,*" %%A in (%str3%) do (set str3=%%B&set word=%%A) +call :reverse_string "%word%" revs +set %var3%=!%var3%! !revs!&set str3="!str3!" +if not !str3!=="" goto process3 +set %var3%=!%var3%:~1,1000000! +goto :EOF + %=== /Reverse each Words Function ===% diff --git a/Task/Phrase-reversals/C++/phrase-reversals.cpp b/Task/Phrase-reversals/C++/phrase-reversals.cpp index 93cff86dcb..28b7e43c6b 100644 --- a/Task/Phrase-reversals/C++/phrase-reversals.cpp +++ b/Task/Phrase-reversals/C++/phrase-reversals.cpp @@ -1,37 +1,22 @@ #include +#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 ) ; -} +#include +#include -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 +int main() { + std::string s = "rosetta code phrase reversal"; + std::cout << "Input : " << s << '\n' + << "Input reversed : " << std::string(s.rbegin(), s.rend()) << '\n' ; + std::istringstream is(s); + std::vector words(std::istream_iterator(is), {}); 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 << " " ; - } + for(auto w : words) + std::cout << std::string(w.rbegin(), w.rend()) << ' '; + std::cout << '\n' + << "Original word order reversed : " ; + reverse_copy(words.begin(), words.end(), std::ostream_iterator(std::cout, " ")); std::cout << '\n' ; - return 0 ; } diff --git a/Task/Phrase-reversals/Clojure/phrase-reversals.clj b/Task/Phrase-reversals/Clojure/phrase-reversals.clj new file mode 100644 index 0000000000..0dda62dc07 --- /dev/null +++ b/Task/Phrase-reversals/Clojure/phrase-reversals.clj @@ -0,0 +1,10 @@ +(use '[clojure.string :only (join split)]) +(def phrase "rosetta code phrase reversal") +(defn str-reverse [s] (apply str (reverse s))) + +; Reverse string +(str-reverse phrase) +; Words reversed +(join " " (map str-reverse (split phrase #" "))) +; Word order reversed +(apply str (interpose " " (reverse (split phrase #" ")))) diff --git a/Task/Phrase-reversals/Elixir/phrase-reversals.elixir b/Task/Phrase-reversals/Elixir/phrase-reversals.elixir new file mode 100644 index 0000000000..49a2421ff1 --- /dev/null +++ b/Task/Phrase-reversals/Elixir/phrase-reversals.elixir @@ -0,0 +1,5 @@ +str = "rosetta code phrase reversal" + +IO.puts String.reverse(str) +IO.puts String.split(str) |> Enum.map(&String.reverse(&1)) |> Enum.join(" ") +IO.puts String.split(str) |> Enum.reverse |> Enum.join(" ") diff --git a/Task/Phrase-reversals/Emacs-Lisp/phrase-reversals.l b/Task/Phrase-reversals/Emacs-Lisp/phrase-reversals.l new file mode 100644 index 0000000000..e7d05572a6 --- /dev/null +++ b/Task/Phrase-reversals/Emacs-Lisp/phrase-reversals.l @@ -0,0 +1,19 @@ +(defun reverse-sep (words sep) + (mapconcat 'identity (reverse (split-string words sep) ) sep) ) + +(defun reverse-chars (line) + (reverse-sep line "") ) + +(defun reverse-words (line) + (reverse-sep line " ") ) + +(progn + (setq line "rosetta code phrase reversal") + + (insert (format "%s\n" (reverse-chars line) )) + + (insert (format "%s\n" + (mapconcat 'identity (mapcar #'reverse-chars + (split-string line) ) " ") )) + + (insert (format "%s\n" (reverse-words line) ))) diff --git a/Task/Phrase-reversals/JavaScript/phrase-reversals.js b/Task/Phrase-reversals/JavaScript/phrase-reversals.js new file mode 100644 index 0000000000..cba97f6c00 --- /dev/null +++ b/Task/Phrase-reversals/JavaScript/phrase-reversals.js @@ -0,0 +1,13 @@ +(function (p) { + return [ + p.split('').reverse().join(''), + + p.split(' ').map(function (x) { + return x.split('').reverse().join(''); + }).join(' '), + + p.split(' ').reverse().join(' ') + + ].join('\n'); + +})('rosetta code phrase reversal'); diff --git a/Task/Phrase-reversals/Julia/phrase-reversals.julia b/Task/Phrase-reversals/Julia/phrase-reversals.julia new file mode 100644 index 0000000000..6991eafbde --- /dev/null +++ b/Task/Phrase-reversals/Julia/phrase-reversals.julia @@ -0,0 +1,16 @@ +s = "rosetta code phrase reversal" + +println("The original phrase.") +println(" ", s) + +println("Reverse the string.") +t = reverse(s) +println(" ", t) + +println("Reverse each individual word in the string.") +t = join(map(reverse, split(s, " ")), " ") +println(" ", t) + +println("Reverse the order of each word of the phrase.") +t = join(reverse(split(s, " ")), " ") +println(" ", t) diff --git a/Task/Phrase-reversals/PL-I/phrase-reversals.pli b/Task/Phrase-reversals/PL-I/phrase-reversals.pli new file mode 100644 index 0000000000..bdb285ec32 --- /dev/null +++ b/Task/Phrase-reversals/PL-I/phrase-reversals.pli @@ -0,0 +1,21 @@ +reverser: procedure options (main); /* 19 August 2015 */ + declare (phrase, r, word) character (100) varying; + declare (start, end) fixed binary; + + phrase = 'rosetta code phrase reversal'; + put ('The original phrase is: ' || phrase); + + put skip list ( '1. ' || reverse(phrase) ); + + start = 1; r = ''; put skip edit ('2. ') (a); + do until ( end > length(phrase) ); + end = index(phrase, ' ', start); /* Find end of the next word.*/ + if end = 0 then end = length(phrase) + 1; /* We're at the last word. */ + word = substr(phrase, start, end-start); + put edit ( reverse(word), ' ' ) (a); /* Append reversed word. */ + r = word || ' ' || r; /* Prepend normal word. */ + start = end+1; + end; + put skip list ('3. ' || r); + +end reverser; diff --git a/Task/Phrase-reversals/Perl/phrase-reversals.pl b/Task/Phrase-reversals/Perl/phrase-reversals.pl index 157404e13d..a8efc99d92 100644 --- a/Task/Phrase-reversals/Perl/phrase-reversals.pl +++ b/Task/Phrase-reversals/Perl/phrase-reversals.pl @@ -1,9 +1,10 @@ -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)); +use feature 'say'; +my $s = "rosetta code phrase reversal"; -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; +say "0. Input : ", $s; +say "1. String reversed : ", scalar reverse $s; +say "2. Each word reversed : ", join " ", reverse split / /, reverse $s; +say "3. Word-order reversed : ", join " ", reverse split / /,$s; + +# Or, using a regex: +say "2. Each word reversed : ", $s =~ s/[^ ]+/reverse $&/gre; diff --git a/Task/Phrase-reversals/PowerShell/phrase-reversals.psh b/Task/Phrase-reversals/PowerShell/phrase-reversals.psh new file mode 100644 index 0000000000..73882ef94f --- /dev/null +++ b/Task/Phrase-reversals/PowerShell/phrase-reversals.psh @@ -0,0 +1,13 @@ +function reverse($a, $sep = "") { + if($a.Length -gt 0) { + $a = $a[($a.Length -1)..0] -join $sep + } + $a +} +$line = "rosetta code phrase reversal" +$task1 = reverse $line +$task2 = ($line -split " " | foreach{ reverse $_ }) -join " " +$task3 = reverse ($line -split " ") " " +$task1 +$task2 +$task3 diff --git a/Task/Phrase-reversals/VBScript/phrase-reversals.vb b/Task/Phrase-reversals/VBScript/phrase-reversals.vb new file mode 100644 index 0000000000..226252d481 --- /dev/null +++ b/Task/Phrase-reversals/VBScript/phrase-reversals.vb @@ -0,0 +1,38 @@ +Phrase = "rosetta code phrase reversal" + +WScript.StdOut.Write "Original String : " & Phrase +WScript.StdOut.WriteLine +WScript.StdOut.Write "Reverse String : " & RevString(Phrase) +WScript.StdOut.WriteLine +WScript.StdOut.Write "Reverse String Each Word : " & RevStringEachWord(Phrase) +WScript.StdOut.WriteLine +WScript.StdOut.Write "Reverse Phrase : " & RevPhrase(Phrase) +WScript.StdOut.WriteLine + +Function RevString(s) + x = Len(s) + For i = 1 To Len(s) + RevString = RevString & Mid(s,x,1) + x = x - 1 + Next +End Function + +Function RevStringEachWord(s) + arr = Split(s," ") + For i = 0 To UBound(arr) + RevStringEachWord = RevStringEachWord & RevString(arr(i)) + If i < UBound(arr) Then + RevStringEachWord = RevStringEachWord & " " + End If + Next +End Function + +Function RevPhrase(s) + arr = Split(s," ") + For i = UBound(arr) To LBound(arr) Step -1 + RevPhrase = RevPhrase & arr(i) + If i > LBound(arr) Then + RevPhrase = RevPhrase & " " + End If + Next +End Function diff --git a/Task/Pi/Common-Lisp/pi.lisp b/Task/Pi/Common-Lisp/pi.lisp new file mode 100644 index 0000000000..6918eb507f --- /dev/null +++ b/Task/Pi/Common-Lisp/pi.lisp @@ -0,0 +1,25 @@ +(defun pi-spigot () + (labels + ((g (q r t1 k n l) + (cond + ((< (- (+ (* 4 q) r) t1) + (* n t1)) + (princ n) + (g (* 10 q) + (* 10 (- r (* n t1))) + t1 + k + (- (floor (/ (* 10 (+ (* 3 q) r)) + t1)) + (* 10 n)) + l)) + (t + (g (* q k) + (* (+ (* 2 q) r) l) + (* t1 l) + (+ k 1) + (floor (/ (+ (* q (+ (* 7 k) 2)) + (* r l)) + (* t1 l))) + (+ l 2)))))) + (g 1 0 1 1 3 3))) diff --git a/Task/Pi/Elixir/pi.elixir b/Task/Pi/Elixir/pi.elixir new file mode 100644 index 0000000000..5a75eae7c2 --- /dev/null +++ b/Task/Pi/Elixir/pi.elixir @@ -0,0 +1,17 @@ +defmodule Pi do + def calc, do: calc(1,0,1,1,3,3,0) + + defp calc(q,r,t,k,n,l,c) when c==50 do + IO.write "\n" + calc(q,r,t,k,n,l,0) + end + defp calc(q,r,t,k,n,l,c) when (4*q + r - t) < n*t do + IO.write n + calc(q*10, 10*(r-n*t), t, k, div(10*(3*q+r), t) - 10*n, l, c+1) + end + defp calc(q,r,t,k,_n,l,c) do + calc(q*k, (2*q+r)*l, t*l, k+1, div(q*7*k+2+r*l, t*l), l+2, c) + end +end + +Pi.calc diff --git a/Task/Pi/Mathematica/pi.math b/Task/Pi/Mathematica/pi.math index 63349acf16..8d0ec93e00 100644 --- a/Task/Pi/Mathematica/pi.math +++ b/Task/Pi/Mathematica/pi.math @@ -1 +1,3 @@ -N[Pi, 1000000!] +WriteString[$Output, "3."]; +For[i = -1, True, i--, + WriteString[$Output, RealDigits[Pi, 10, 1, i][[1, 1]]]; Pause[.05]]; diff --git a/Task/Pi/REXX/pi.rexx b/Task/Pi/REXX/pi.rexx index 70b206f1c6..b06c2c3401 100644 --- a/Task/Pi/REXX/pi.rexx +++ b/Task/Pi/REXX/pi.rexx @@ -1,22 +1,23 @@ -/*REXX program spits out digits of pi (one at a time) until Ctrl-Break.*/ -arg digs .; if digs=='' then digs=1e6 /*allow the specification of digs*/ -fn = 'PI_DIGITS.OUT' /*file used for output: PI digits*/ -numeric digits digs /*big digs, the slower the spits.*/ -pi=0; s=16; r=4; v=5; vs=v*v; g=239; gg=g*g; j=1; spit=0; old= -call time 'Reset' /*reset the REXX wall-clock timer*/ - /*───calculate PI with increasing*/ - do n=1 by 2 /*───accuracy (up to DIGS digits)*/ - pi=pi + s/(n*v) - r/(n*g) /*───using John Machin's formula.*/ - if pi==old then leave /*have exceeded DIGITS accuracy. */ - s=-s; r=-r; v=v*vs; g=g*gg /*set some variable for shortcuts*/ - if n\==1 then do j=spit+1 to compare(pi,old) /*spit out some π digs.*/ - spit=substr(pi,j,1) /*obtain a digit of π to spit out*/ - call charout ,spit /*spit out one (new) digit of pi.*/ - call charout fn,spit /* ···and also echo it to a file.*/ - end /*j*/ - spit=j-1 /*adjust for DO index increment.*/ - old=pi /*use the "OLD" value next time. */ - end /*n*/ +/*REXX program spits out digits of π (pi) (one at a time) until Ctrl-Break.*/ +parse arg digs . /*obtain optional argument from the CL.*/ +if digs=='' | digs=="," then digs=1e6 /*Not specified? Then use one million.*/ +fn = 'PI_DIGITS.OUT' /*fileID used for output: the π digits.*/ +numeric digits digs /*with bigger digs, spitting is slower.*/ +call time 'Reset' /*reset the wall-clock (elapsed) timer.*/ +signal on halt /*───► HALT when Ctrl─Break is pressed.*/ +pi=0; s=16; r=4; v=5; vv=v*v; g=239; gg=g*g; spit=0; old= -say; say n%2+1 'iterations took' format(time("Elapsed"),,2) 'seconds.' - /*stick a fork in it, we're done.*/ + do n=1 by 2 /*calculate π with increasing accuracy */ + pi=pi + s/(n*v) - r/(n*g) /* ··· using John Machin's formula.*/ + if pi==old then leave /*have we exceeded the DIGITS accuracy?*/ + s=-s; r=-r; v=v*vv; g=g*gg /*compute some variables for shortcuts.*/ + do j=spit+1 to compare(pi,old) /*spit out some (new) digits of π (pi)*/ + parse var pi =(j) spit +1 /*equivalent to: spit=substr(pi,j,1) */ + call charout ,spit /*display one (new) decimal digit of π.*/ + call charout fn,spit /*··· and also write π digit to a file.*/ + end /*j*/ /* [↑] 0, 1, or 2 decimal dig are spit*/ + spit=j-1 /*adjust for DO loop index increment.*/ + old=pi /*use "OLD" value for the next COMPARE.*/ + end /*n*/ +say /*stick a fork in it, we're all done. */ +halt: say n%2+1 'iterations took' format(time("Elapsed"),,2) 'seconds.' diff --git a/Task/Pick-random-element/Batch-File/pick-random-element.bat b/Task/Pick-random-element/Batch-File/pick-random-element.bat new file mode 100644 index 0000000000..f81bab298c --- /dev/null +++ b/Task/Pick-random-element/Batch-File/pick-random-element.bat @@ -0,0 +1,16 @@ +@echo off +setlocal enabledelayedexpansion + + ::Initializing the pseudo-array... +set "pseudo=Alpha Beta Gamma Delta Epsilon" +set cnt=0 & for %%P in (!pseudo!) do ( + set /a cnt+=1 + set "pseudo[!cnt!]=%%P" +) + ::Do the random thing... +set /a rndInt=%random% %% cnt +1 + + ::Print the element corresponding to rndint... +echo.!pseudo[%rndInt%]! +pause +exit /b diff --git a/Task/Pick-random-element/Elixir/pick-random-element.elixir b/Task/Pick-random-element/Elixir/pick-random-element.elixir index 2b1d1b66f0..eca6382f5b 100644 --- a/Task/Pick-random-element/Elixir/pick-random-element.elixir +++ b/Task/Pick-random-element/Elixir/pick-random-element.elixir @@ -1,11 +1,12 @@ defmodule Random do - def init() do - :random.seed(:erlang.now()) + def init do + :random.seed(:erlang.now) end def pick_element(list) do - Enum.at(list, :random.uniform(Enum.count(list)) - 1) + Enum.at(list, :random.uniform(length(list)) - 1) end end -Random.init() -IO.puts Random.pick_element(1..20) +Random.init +list = Enum.to_list(1..20) +IO.puts Random.pick_element(list) diff --git a/Task/Pick-random-element/Fortran/pick-random-element.f b/Task/Pick-random-element/Fortran/pick-random-element.f new file mode 100644 index 0000000000..11e27657d4 --- /dev/null +++ b/Task/Pick-random-element/Fortran/pick-random-element.f @@ -0,0 +1,11 @@ +program pick_random + implicit none + + integer :: i + integer :: a(10) = (/ (i, i = 1, 10) /) + real :: r + + call random_seed + call random_number(r) + write(*,*) a(int(r*size(a)) + 1) +end program diff --git a/Task/Pick-random-element/NewLISP/pick-random-element.newlisp b/Task/Pick-random-element/NewLISP/pick-random-element.newlisp new file mode 100644 index 0000000000..3dab83b4c0 --- /dev/null +++ b/Task/Pick-random-element/NewLISP/pick-random-element.newlisp @@ -0,0 +1,2 @@ +(define (pick-random-element R) + (nth (rand (length R)) R)) diff --git a/Task/Pick-random-element/PureBasic/pick-random-element.purebasic b/Task/Pick-random-element/PureBasic/pick-random-element-1.purebasic similarity index 100% rename from Task/Pick-random-element/PureBasic/pick-random-element.purebasic rename to Task/Pick-random-element/PureBasic/pick-random-element-1.purebasic diff --git a/Task/Pick-random-element/PureBasic/pick-random-element-2.purebasic b/Task/Pick-random-element/PureBasic/pick-random-element-2.purebasic new file mode 100644 index 0000000000..463a724b2e --- /dev/null +++ b/Task/Pick-random-element/PureBasic/pick-random-element-2.purebasic @@ -0,0 +1,12 @@ +Define.i +OpenConsole() + +a$="One" +#TAB$+ "Two" +#TAB$+ "Three" +#TAB$+ "Four" +#TAB$+ "Five" +#TAB$+ + "Six" +#TAB$+ "Seven"+#TAB$+ "Eight" +#TAB$+ "Nine" +#TAB$+ "Ten" +#TAB$ + +Print("Source list: "+#TAB$+a$+#CRLF$+"Random list: "+#TAB$) + +For i=1 To CountString(a$,#TAB$) + Print(StringField(a$,Random(CountString(a$,#TAB$),1),#TAB$)+#TAB$) +Next +Input() diff --git a/Task/Pick-random-element/Ruby/pick-random-element.rb b/Task/Pick-random-element/Ruby/pick-random-element.rb new file mode 100644 index 0000000000..ccab5f1694 --- /dev/null +++ b/Task/Pick-random-element/Ruby/pick-random-element.rb @@ -0,0 +1,4 @@ +irb(main):001:0> %w(north east south west).sample +=> "west" +irb(main):002:0> (1..100).to_a.sample(2) +=> [17, 79] diff --git a/Task/Pick-random-element/VBScript/pick-random-element.vb b/Task/Pick-random-element/VBScript/pick-random-element.vb new file mode 100644 index 0000000000..eaaf650339 --- /dev/null +++ b/Task/Pick-random-element/VBScript/pick-random-element.vb @@ -0,0 +1,6 @@ +Function pick_random(arr) + Set objRandom = CreateObject("System.Random") + pick_random = arr(objRandom.Next_2(0,UBound(arr)+1)) +End Function + +WScript.Echo pick_random(Array("a","b","c","d","e","f")) diff --git a/Task/Pig-the-dice-game-Player/Haskell/pig-the-dice-game-player-1.hs b/Task/Pig-the-dice-game-Player/Haskell/pig-the-dice-game-player-1.hs new file mode 100644 index 0000000000..b07b949d03 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/Haskell/pig-the-dice-game-player-1.hs @@ -0,0 +1,75 @@ +{-# LANGUAGE ViewPatterns #-} + +module Main where + +import System.Random (randomRIO) +import Text.Printf (printf) + +data PInfo = PInfo { stack :: Int + , score :: Int + , rolls :: Int + , next :: Bool + , won :: Bool + , name :: String + } + +type Strategy = [PInfo] -> IO () + +roll :: [PInfo] -> IO [PInfo] +roll (pinfo:xs) = do + face <- randomRIO (1, 6) + case (face, face + stack pinfo + score pinfo) of + (1,_) -> do + printf "%s rolled 1 - stack is being resetted\n\n" (name pinfo) + return $ pinfo { stack = 0, rolls = 0, next = True } : xs + (_,x) | x >= 100 -> do + printf "%s rolled %i - stack is now %i + score %i => %i - I won!\n" (name pinfo) face (face + stack pinfo) (score pinfo) x + return $ pinfo { won = True } : xs + (_,_) -> do + printf "%s rolled %i - stack is now %i\n" (name pinfo) face (face + (stack pinfo)) + return $ pinfo { stack = face + (stack pinfo), rolls = 1 + (rolls pinfo) } : xs + +hold :: [PInfo] -> IO [PInfo] +hold (pinfo:xs) = do + let score' = stack pinfo + score pinfo + printf "%s holds - score is now %i\n\n" (name pinfo) score' + return $ pinfo { score = score', stack = 0, rolls = 0, next = True } : xs + + +logic :: Strategy -> Strategy -> Strategy +logic _ _ ((won -> True) : xs) = return () +logic _ strat2 (p@(next -> True) : xs) = strat2 $ xs ++ [p { next = False }] +logic strat1 _ (pinfo : xs) = strat1 (pinfo : xs) + +strat1 :: Strategy +strat1 (pinfo:xs) + | stack pinfo < 20 = roll (pinfo:xs) >>= logic strat1 strat2 + | otherwise = hold (pinfo:xs) >>= logic strat1 strat2 + +strat2 :: Strategy +strat2 (pinfo:xs) + | rolls pinfo < 4 = roll (pinfo:xs) >>= logic strat2 strat3 + | otherwise = hold (pinfo:xs) >>= logic strat2 strat3 + +strat3 :: Strategy +strat3 (pinfo:xs) + | rolls pinfo < 3 && score pinfo < 60 = roll (pinfo:xs) >>= logic strat3 strat4 + | stack pinfo < 20 = roll (pinfo:xs) >>= logic strat3 strat4 + | otherwise = hold (pinfo:xs) >>= logic strat3 strat4 + +strat4 :: Strategy +strat4 (pinfo:xs) | score pinfo > 75 = roll (pinfo:xs) >>= logic strat4 strat1 +strat4 (pinfo:xs) = do + chance <- randomRIO (0, 3) :: IO Int + case chance of + 0 -> hold (pinfo:xs) >>= logic strat4 strat1 + _ -> roll (pinfo:xs) >>= logic strat4 strat1 + +main :: IO () +main = do + let pInfo = PInfo 0 0 0 False False "" + p1 = pInfo { name = "Peter" } + p2 = pInfo { name = "Mia" } + p3 = pInfo { name = "Liz" } + p4 = pInfo { name = "Stephen" } + strat1 [p1, p2, p3, p4] diff --git a/Task/Pig-the-dice-game-Player/Haskell/pig-the-dice-game-player-2.hs b/Task/Pig-the-dice-game-Player/Haskell/pig-the-dice-game-player-2.hs new file mode 100644 index 0000000000..7a65edc364 --- /dev/null +++ b/Task/Pig-the-dice-game-Player/Haskell/pig-the-dice-game-player-2.hs @@ -0,0 +1,20 @@ +-- add this to the top +import Control.Concurrent.ParallelIO.Global (parallel, stopGlobalPool) +import Data.List (sort, group) + +-- replace "logic _ _ ((won -> True) : xs) = return ()" with + logic _ _ (p@(won -> True) : xs) = return $ name p + +-- replace strat1 [p1, p2, p3, p4] in main with + let lists = replicate 100000 [p1, p2, p3, p4] + results <- parallel $ map strat1 lists + stopGlobalPool + print $ map length $ group $ sort results + +-- replace type Strategy = [PInfo] -> IO () with + type Strategy = [PInfo] -> IO String + +-- comment every printf in "roll" and "hold" + +-- compile with +-- ghc FILENAME.hs -O2 -threaded -with-rtsopts="-N4" -o dice diff --git a/Task/Pig-the-dice-game/Haskell/pig-the-dice-game.hs b/Task/Pig-the-dice-game/Haskell/pig-the-dice-game.hs new file mode 100644 index 0000000000..468b89f9ec --- /dev/null +++ b/Task/Pig-the-dice-game/Haskell/pig-the-dice-game.hs @@ -0,0 +1,39 @@ +import System.Random (randomRIO) + +data Score = Score { stack :: Int, score :: Int } + +main :: IO () +main = loop (Score 0 0) (Score 0 0) + +loop :: Score -> Score -> IO () +loop p1 p2 = do + putStrLn $ "\nPlayer 1 ~ " ++ show (score p1) + p1' <- askPlayer p1 + if (score p1') >= 100 + then putStrLn "P1 won!" + else do + putStrLn $ "\nPlayer 2 ~ " ++ show (score p2) + p2' <- askPlayer p2 + if (score p2') >= 100 + then putStrLn "P2 won!" + else loop p1' p2' + + +askPlayer :: Score -> IO Score +askPlayer (Score stack score) = do + putStr "\n(h)old or (r)oll? " + answer <- getChar + roll <- randomRIO (1,6) + case (answer, roll) of + ('h', _) -> do + putStrLn $ " => Score = " ++ show (stack + score) + return $ Score 0 (stack + score) + ('r', 1) -> do + putStrLn $ " => 1 => Sorry - stack was resetted" + return $ Score 0 score + ('r', _) -> do + putStr $ " => " ++ show roll ++ " => current stack = " ++ show (stack + roll) + askPlayer $ Score (stack + roll) score + _ -> do + putStrLn "\nInvalid input - please try again." + askPlayer $ Score stack score diff --git a/Task/Pig-the-dice-game/J/pig-the-dice-game-1.j b/Task/Pig-the-dice-game/J/pig-the-dice-game-1.j index cf4bb41164..1ff584370a 100644 --- a/Task/Pig-the-dice-game/J/pig-the-dice-game-1.j +++ b/Task/Pig-the-dice-game/J/pig-the-dice-game-1.j @@ -1,4 +1,4 @@ -require'misc' +require'general/misc/prompt' NB. was require'misc' in j6 status=:3 :0 'pid cur tot'=. y @@ -10,7 +10,7 @@ status=:3 :0 getmove=:3 :0 whilst.1~:+/choice do. - choice=.'HRQ' e. prompt ' Roll the dice or Hold or Quit? [R or H or Q]: ' + choice=.'HRQ' e. prompt '..Roll the dice or Hold or Quit? [R or H or Q]: ' end. choice#'HRQ' ) @@ -21,21 +21,14 @@ pigsim=:3 :0 scores=.y#0 while.100>>./scores do. for_player.=i.y do. - pid=.1+I.player - smoutput 'begining of turn for player ',":pid + smoutput 'begining of turn for player ',":pid=.1+I.player current=. 0 whilst. (1 ~: roll) *. 'R' = move do. status pid, current, player+/ .*scores - move=. getmove'' - roll=. 1+?6 - if.'R'=move do. - smoutput 'rolled a ',":roll - current=. (1~:roll)*current+roll - end. - end. + if.'R'=move=. getmove'' do. + smoutput 'rolled a ',":roll=. 1+?6 + current=. (1~:roll)*current+roll end. end. scores=. scores+(current*player)+100*('Q'e.move)*-.player - smoutput 'player scores now: ',":scores - end. - end. + smoutput 'player scores now: ',":scores end. end. smoutput 'player ',(":1+I.scores>:100),' wins' ) diff --git a/Task/Pig-the-dice-game/J/pig-the-dice-game-2.j b/Task/Pig-the-dice-game/J/pig-the-dice-game-2.j index b5d783fdc7..e3d4dcfb89 100644 --- a/Task/Pig-the-dice-game/J/pig-the-dice-game-2.j +++ b/Task/Pig-the-dice-game/J/pig-the-dice-game-2.j @@ -2,26 +2,26 @@ 2 player game of pig begining of turn for player 1 player 1 potential: 0 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 3 player 1 potential: 3 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 6 player 1 potential: 9 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 4 player 1 potential: 13 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 6 player 1 potential: 19 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 2 player 1 potential: 21 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: H +..Roll the dice or Hold or Quit? [R or H or Q]: H player scores now: 21 0 begining of turn for player 2 player 2 potential: 0 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 3 player 2 potential: 3 total: 0 Roll the dice or Hold or Quit? [R or H or Q]: R @@ -30,33 +30,33 @@ player 2 potential: 9 total: 0 Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 4 player 2 potential: 13 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 6 player 2 potential: 19 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 3 player 2 potential: 22 total: 0 - Roll the dice or Hold or Quit? [R or H or Q]: H +..Roll the dice or Hold or Quit? [R or H or Q]: H player scores now: 21 22 begining of turn for player 1 player 1 potential: 0 total: 21 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R ... - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 6 player 1 potential: 22 total: 62 - Roll the dice or Hold or Quit? [R or H or Q]: H +..Roll the dice or Hold or Quit? [R or H or Q]: H player scores now: 84 90 begining of turn for player 2 player 2 potential: 0 total: 90 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 6 player 2 potential: 6 total: 90 - Roll the dice or Hold or Quit? [R or H or Q]: R +..Roll the dice or Hold or Quit? [R or H or Q]: R rolled a 6 player 2 potential: 12 total: 90 - Roll the dice or Hold or Quit? [R or H or Q]: H +..Roll the dice or Hold or Quit? [R or H or Q]: H player scores now: 84 102 player 2 wins diff --git a/Task/Pig-the-dice-game/Julia/pig-the-dice-game.julia b/Task/Pig-the-dice-game/Julia/pig-the-dice-game.julia new file mode 100644 index 0000000000..b8843949ba --- /dev/null +++ b/Task/Pig-the-dice-game/Julia/pig-the-dice-game.julia @@ -0,0 +1,57 @@ +type PigPlayer + name::String + score::Int + strat::Function +end + +function PigPlayer(a::String) + PigPlayer(a, 0, pig_manual) +end + +function scoreboard(pps::Array{PigPlayer,1}) + join(map(x->@sprintf("%s has %d", x.name, x.score), pps), " | ") +end + +function pig_manual(pps::Array{PigPlayer,1}, pdex::Integer, pot::Integer) + pname = pps[pdex].name + print(pname, " there is ", @sprintf("%3d", pot), " in the pot. ") + print(" to continue rolling? ") + return chomp(readline()) == "" +end + +function pig_round(pps::Array{PigPlayer,1}, pdex::Integer) + pot = 0 + rcnt = 0 + while pps[pdex].strat(pps, pdex, pot) + rcnt += 1 + roll = rand(1:6) + if roll == 1 + return (0, rcnt, false) + else + pot += roll + end + end + return (pot, rcnt, true) +end + +function pig_game(pps::Array{PigPlayer,1}, winscore::Integer=100) + pnum = length(pps) + pdex = pnum + println("Playing a game of Pig the Dice.") + while(pps[pdex].score < winscore) + pdex = rem1(pdex+1, pnum) + println(scoreboard(pps)) + println(pps[pdex].name, " is now playing.") + (pot, rcnt, ispotwon) = pig_round(pps, pdex) + print(pps[pdex].name, " played ", rcnt, " rolls ") + if ispotwon + println("and scored ", pot, " points.") + pps[pdex].score += pot + else + println("and butsted.") + end + end + println(pps[pdex].name, " won, scoring ", pps[pdex].score, " points.") +end + +pig_game([PigPlayer("Alice"), PigPlayer("Bob")]) diff --git a/Task/Pig-the-dice-game/Pascal/pig-the-dice-game.pascal b/Task/Pig-the-dice-game/Pascal/pig-the-dice-game.pascal new file mode 100644 index 0000000000..738df02b10 --- /dev/null +++ b/Task/Pig-the-dice-game/Pascal/pig-the-dice-game.pascal @@ -0,0 +1,109 @@ +program Pig; + +const + WinningScore = 100; + +type + DieRoll = 1..6; + Score = integer; + Player = record + Name: string; + Points: score; + Victory: Boolean + end; + +{ Assume a 2-player game. } +var Player1, Player2: Player; + +function RollTheDie: DieRoll; + { Return a random number 1 thru 6. } + begin + RollTheDie := random(6) + 1 + end; + +procedure TakeTurn (var P: Player); + { Play a round of Pig. } + var + Answer: char; + Roll: DieRoll; + NewPoints: Score; + KeepPlaying: Boolean; + begin + NewPoints := 0; + writeln ; + writeln('It''s your turn, ', P.Name, '!'); + writeln('So far, you have ', P.Points, ' points in all.'); + writeln ; + { Keep playing until the user rolls a 1 or chooses not to roll. } + write('Do you want to roll the die (y/n)? '); + readln(Answer); + KeepPlaying := upcase(Answer) = 'Y'; + while KeepPlaying do + begin + Roll := RollTheDie; + if Roll = 1 then + begin + NewPoints := 0; + KeepPlaying := false; + writeln('Oh no! You rolled a 1! No new points after all.') + end + else + begin + NewPoints := NewPoints + Roll; + write('You rolled a ', Roll:1, '. '); + writeln('That makes ', NewPoints, ' new points so far.'); + writeln ; + write('Roll again (y/n)? '); + readln(Answer); + KeepPlaying := upcase(Answer) = 'Y' + end + end; + { Update the player's score and check for a winner. } + writeln ; + if NewPoints = 0 then + writeln(P.Name, ' still has ', P.Points, ' points.') + else + begin + P.Points := P.Points + NewPoints; + writeln(P.Name, ' now has ', P.Points, ' points total.'); + P.Victory := P.Points >= WinningScore + end + end; + +procedure Congratulate(Winner: Player); + begin + writeln ; + write('Congratulations, ', Winner.Name, '! '); + writeln('You won with ', Winner.Points, ' points.'); + writeln + end; + +begin + { Greet the players and initialize their data. } + writeln('Let''s play Pig!'); + + writeln ; + write('Player 1, what is your name? '); + readln(Player1.Name); + Player1.Points := 0; + Player1.Victory := false; + + writeln ; + write('Player 2, what is your name? '); + readln(Player2.Name); + Player2.Points := 0; + Player2.Victory := false; + + { Take turns until there is a winner. } + randomize; + repeat + TakeTurn(Player1); + if not Player1.Victory then TakeTurn(Player2) + until Player1.Victory or Player2.Victory; + + { Announce the winner. } + if Player1.Victory then + Congratulate(Player1) + else + Congratulate(Player2) +end. diff --git a/Task/Pig-the-dice-game/Perl-6/pig-the-dice-game.pl6 b/Task/Pig-the-dice-game/Perl-6/pig-the-dice-game.pl6 index 44d868f642..6082e86869 100644 --- a/Task/Pig-the-dice-game/Perl-6/pig-the-dice-game.pl6 +++ b/Task/Pig-the-dice-game/Perl-6/pig-the-dice-game.pl6 @@ -2,7 +2,7 @@ constant DIE = 1..6; sub MAIN (Int :$players = 2, Int :$goal = 100) { my @safe = 0 xx $players; - for ^$players xx * -> $player { + for |^$players xx * -> $player { say "\nOK, player #$player is up now."; my $safe = @safe[$player]; my $ante = 0; diff --git a/Task/Pinstripe-Display/J/pinstripe-display.j b/Task/Pinstripe-Display/J/pinstripe-display.j index 5b8af8e730..9afbb33700 100644 --- a/Task/Pinstripe-Display/J/pinstripe-display.j +++ b/Task/Pinstripe-Display/J/pinstripe-display.j @@ -1,4 +1,5 @@ load'viewmat' - size=.2{.".wd'qm' NB. J6 - size=. getscreenwh_jgtk_ '' NB. J7 + NB. size=. 2{.".wd'qm' NB. J6 + NB. size=. getscreenwh_jgtk_ '' NB. J7 + size=. 3{".wd'qscreen' NB. J8 'rgb'viewmat- (4<.@%~{:size)# ({.size) $&> 1 2 3 4#&.> <0 1 diff --git a/Task/Pinstripe-Display/Lua/pinstripe-display.lua b/Task/Pinstripe-Display/Lua/pinstripe-display.lua new file mode 100644 index 0000000000..102207333e --- /dev/null +++ b/Task/Pinstripe-Display/Lua/pinstripe-display.lua @@ -0,0 +1,18 @@ +function love.load() + WIDTH = love.window.getWidth() + ROW_HEIGHT = math.floor(love.window.getHeight()/4) + love.graphics.setBackgroundColor({0,0,0}) + love.graphics.setLineWidth(1) + love.graphics.setLineStyle("rough") +end + +function love.draw() + for j = 0, 3 do + for i = 0, WIDTH, (j+1)*2 do + love.graphics.setColor({255,255,255}) + for h = 0, j do + love.graphics.line(i+h, j*ROW_HEIGHT, i+h, (j+1)*ROW_HEIGHT) + end + end + end +end diff --git a/Task/Pinstripe-Display/Mathematica/pinstripe-display.math b/Task/Pinstripe-Display/Mathematica/pinstripe-display.math new file mode 100644 index 0000000000..4281f7e2ed --- /dev/null +++ b/Task/Pinstripe-Display/Mathematica/pinstripe-display.math @@ -0,0 +1,10 @@ +color[y_] := {White, Black}[[Mod[y, 2] + 1]]; +Graphics[Join[{Thickness[1/408]}, + Flatten[{color[#], Line[{{# - 1/2, 408}, {# - 1/2, 307}}]} & /@ + Range[408]], {Thickness[1/204]}, + Flatten[{color[#], Line[{{2 # - 1, 306}, {2 # - 1, 205}}]} & /@ + Range[204]], {Thickness[1/136]}, + Flatten[{color[#], Line[{{3 # - 3/2, 204}, {3 # - 3/2, 103}}]} & /@ + Range[136]], {Thickness[1/102]}, + Flatten[{color[#], Line[{{4 # - 2, 102}, {4 # - 2, 1}}]} & /@ + Range[102]]], ImageSize -> {408, 408}] diff --git a/Task/Playing-cards/Julia/playing-cards-1.julia b/Task/Playing-cards/Julia/playing-cards-1.julia new file mode 100644 index 0000000000..be9a8d1c98 --- /dev/null +++ b/Task/Playing-cards/Julia/playing-cards-1.julia @@ -0,0 +1,25 @@ +type DeckDesign{T<:Integer,U<:String} + rlen::T + slen::T + ranks::Array{U,1} + suits::Array{U,1} + hlen::T +end + +type Deck{T<:Integer} + cards::Array{T,1} + design::DeckDesign +end + +Deck(n::Integer, des::DeckDesign) = Deck([n], des) + +function pokerlayout() + r = [map(string, 2:10), "J", "Q", "K", "A"] + r = map(utf8, r) + s = ["\u2663", "\u2666", "\u2665", "\u2660"] + DeckDesign(13, 4, r, s, 5) +end + +function fresh(des::DeckDesign) + Deck(collect(1:des.rlen*des.slen), des) +end diff --git a/Task/Playing-cards/Julia/playing-cards-2.julia b/Task/Playing-cards/Julia/playing-cards-2.julia new file mode 100644 index 0000000000..43de428946 --- /dev/null +++ b/Task/Playing-cards/Julia/playing-cards-2.julia @@ -0,0 +1,14 @@ +Base.isempty(d::Deck) = isempty(d.cards) +Base.empty!(d::Deck) = empty!(d.cards) +Base.length(d::Deck) = length(d.cards) +Base.endof(d::Deck) = endof(d.cards) +Base.shuffle!(d::Deck) = shuffle!(d.cards) +Base.sort!(d::Deck) = sort!(d.cards) +Base.getindex(d::Deck, r) = Deck(getindex(d.cards, r), d.design) +Base.size(d::Deck) = (d.design.rlen, d.design.slen) +function Base.print(d::Deck) + sz = size(d) + r = map(x->d.design.ranks[ind2sub(sz, x)[1]], d.cards) + s = map(x->d.design.suits[ind2sub(sz, x)[2]], d.cards) + join(r.*s, " ") +end diff --git a/Task/Playing-cards/Julia/playing-cards-3.julia b/Task/Playing-cards/Julia/playing-cards-3.julia new file mode 100644 index 0000000000..8002c6cd7e --- /dev/null +++ b/Task/Playing-cards/Julia/playing-cards-3.julia @@ -0,0 +1,25 @@ +function deal!{T<:Integer}(d::Deck, hlen::T) + if hlen < length(d) + hand = Deck(d.cards[1:hlen], d.design) + d.cards = d.cards[hlen+1:end] + else + hand = d + empty!(d) + end + return hand +end + +function deal!(d::Deck) + deal!(d, d.design.hlen) +end + +function pretty(d::Deck) + s = "" + llen = d.design.rlen + dlen = length(d) + for i in 1:llen:dlen + j = min(i+llen-1, dlen) + s *= print(d[i:j])*"\n" + end + chop(s) +end diff --git a/Task/Playing-cards/Julia/playing-cards-4.julia b/Task/Playing-cards/Julia/playing-cards-4.julia new file mode 100644 index 0000000000..b60fd7c86b --- /dev/null +++ b/Task/Playing-cards/Julia/playing-cards-4.julia @@ -0,0 +1,20 @@ +d = fresh(pokerlayout()) +println("A new poker deck:") +println(pretty(d)) + +shuffle!(d) +println() +println("The deck shuffled:") +println(pretty(d)) + +n = 4 +println() +println("Deal ", n, " hands:") +for i in 1:n + h = deal!(d) + println(pretty(h)) +end + +println() +println("And now the deck contains:") +println(pretty(d)) diff --git a/Task/Playing-cards/Lua/playing-cards.lua b/Task/Playing-cards/Lua/playing-cards-1.lua similarity index 100% rename from Task/Playing-cards/Lua/playing-cards.lua rename to Task/Playing-cards/Lua/playing-cards-1.lua diff --git a/Task/Playing-cards/Lua/playing-cards-2.lua b/Task/Playing-cards/Lua/playing-cards-2.lua new file mode 100644 index 0000000000..e72fb815a0 --- /dev/null +++ b/Task/Playing-cards/Lua/playing-cards-2.lua @@ -0,0 +1,58 @@ +local tPlayers = {} -- cards of players +local tBoard = {} -- cards in a board +local nPlayers = 5 -- number of players + +local tDeck = { +'2d', '3d', '4d', '5d', '6d', '7d', '8d', '9d', 'Td', 'Jd', 'Qd', 'Kd', 'Ad', -- DIAMONDS +'2s', '3s', '4s', '5s', '6s', '7s', '8s', '9s', 'Ts', 'Js', 'Qs', 'Ks', 'As', -- SPADES +'2h', '3h', '4h', '5h', '6h', '7h', '8h', '9h', 'Th', 'Jh', 'Qh', 'Kh', 'Ah', -- HEARTS +'2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c', 'Tc', 'Jc', 'Qc', 'Kc', 'Ac'} -- CLUBS + +local function shuffle() -- Fisher–Yates shuffle + i = #tDeck + while i > 1 do + i = i - 1 + j = math.random(1, i) + tDeck[j], tDeck[i] = tDeck[i], tDeck[j] + end + return tDeck +end + +local function cardTransfer(to, amount, from) + for f = 1, amount do + table.insert(to, #to+1, from[#from]) + from[#from] = nil + end +end + +----||EXAMPLE OF USE||---- +print('FRESH DECK \n', table.concat(tDeck, ' '), '\n') + +shuffle() + +print('SHUFFLED DECK \n', table.concat(tDeck, ' '), '\n') + +for a = 1, nPlayers do + tPlayers[a] = {} + cardTransfer(tPlayers[a], 2, tDeck) +end + +cardTransfer(tBoard, 5, tDeck) + +print('BOARD\n', table.concat(tBoard, ' '), '\n') + +for b = 1, nPlayers do + print('PLAYER #'..b..': ', table.concat(tPlayers[b], ' ')) +end + +print('\nREMAINING\n', table.concat(tDeck, ' '), '\n') + +for c = 1, #tPlayers do + for d = 1, #tPlayers[c] do + cardTransfer(tDeck, d, tPlayers[c]) + end +end + +cardTransfer(tDeck, 5, tBoard) + +print('ALL CARDS IN THE DECK\n', table.concat(tDeck, ' '), '\n') diff --git a/Task/Playing-cards/Lua/playing-cards-3.lua b/Task/Playing-cards/Lua/playing-cards-3.lua new file mode 100644 index 0000000000..004ab2f133 --- /dev/null +++ b/Task/Playing-cards/Lua/playing-cards-3.lua @@ -0,0 +1,20 @@ +FRESH DECK +2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac + +SHUFFLED DECK +7c 3d 8h 7h 7s 9c 8c Ks 8s 2s 5s 8d 2h 3h Jc 6h Td Ts Jh Tc 6s Kd 7d 4h 4d 5d Qd 5h 5c Kh 9d 2d Ah 6d 3c Js 9h Qh 4c 3s As Kc Qs Ad Th 4s Jd Ac Qc 2c 9s 6c + +BOARD +Kc As 3s 4c Qh + +PLAYER #1: 6c 9s +PLAYER #2: 2c Qc +PLAYER #3: Ac Jd +PLAYER #4: 4s Th +PLAYER #5: Ad Qs + +REMAINING +7c 3d 8h 7h 7s 9c 8c Ks 8s 2s 5s 8d 2h 3h Jc 6h Td Ts Jh Tc 6s Kd 7d 4h 4d 5d Qd 5h 5c Kh 9d 2d Ah 6d 3c Js 9h + +ALL CARDS IN THE DECK +7c 3d 8h 7h 7s 9c 8c Ks 8s 2s 5s 8d 2h 3h Jc 6h Td Ts Jh Tc 6s Kd 7d 4h 4d 5d Qd 5h 5c Kh 9d 2d Ah 6d 3c Js 9h 9s 6c Qc 2c Jd Ac Th 4s Qs Ad Qh 4c 3s As Kc diff --git a/Task/Playing-cards/REXX/playing-cards-2.rexx b/Task/Playing-cards/REXX/playing-cards-2.rexx index 92f3fb6326..fe219d44c8 100644 --- a/Task/Playing-cards/REXX/playing-cards-2.rexx +++ b/Task/Playing-cards/REXX/playing-cards-2.rexx @@ -1,36 +1,36 @@ -/*REXX pgm shows methods (subroutines) to build/shuffle/deal a card deck*/ -call buildDeck ; say ' new deck:' newDeck /*new 52-card deck*/ -call shuffleDeck; say 'shuffled deck:' theDeck /*shuffled deck. */ -call dealHands 5,4 /*5 cards, 4 hands*/ +/*REXX pgm shows a method to build/shuffle/deal a standard 52─card deck.*/ +box = build(); say ' box of cards:' box /*a new box of 52─cards.*/ +deck=shuffle(); say 'shuffled deck:' deck /*randomly shuffled deck*/ +call deal 5, 4 /* ◄═════════════════════════════════ 5 cards, 4 hands*/ say; say; say right('[north]' hand.1,50) say; say '[west]' hand.4 right('[east]' hand.2,60) say; say right('[south]' hand.3,50) -say; say; say; say 'remainder of deck:' theDeck +say; say; say; say 'remainder of deck: ' deck exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────BUILDDECK subroutine────────────────*/ -buildDeck: _=''; ranks='A 2 3 4 5 6 7 8 9 10 J Q K' /*ranks. */ -if 1=='f1'x then suits='h d c s' /*EBCDIC?*/ - else suits='♥ ♦ ♣ ♠' /*ASCII. */ - do s=1 for words(suits) - do r=1 for words(ranks) - _=_ word(ranks,r)word(suits,s) - end /*dealR*/ - end; /*dealS*/ newDeck=_ -return -/*──────────────────────────────────SHUFFLEDECK subroutine──────────────*/ -shuffleDeck: theDeck=''; _=newDeck; #cards=words(_) +/*──────────────────────────────────BUILD subroutine────────────────────*/ +build: _=; ranks= "A 2 3 4 5 6 7 8 9 10 J Q K" /*ranks. */ +if 5=='f5'x then suits= "h d c s" /*EBCDIC? */ + else suits= "♥ ♦ ♣ ♠" /*ASCII. */ +#ranks=words(ranks); do s=1 for words(suits); @=word(suits,s) + do r=1 for #ranks + _=_ word(ranks,r)@ + end /*s*/ + end /*r*/ +return _ +/*──────────────────────────────────SHUFFLE subroutine──────────────────*/ +shuffle: y=; _=box; #cards=words(_) /*define REXX vars.*/ do shuffler=1 for #cards /*shuffle all the cards in deck. */ - r=random(1,#cards+1-shuffler) /*random # decreases each time. */ - theDeck=theDeck word(_,r) /*sufffled deck, 1 card at-a-time*/ - _=delword(_,r,1) /*delete the just-chosen card. */ + ?=random(1,#cards+1-shuffler) /*each shuffle, random# decreases*/ + y=y word(_, ?) /*shuffled deck, 1 card at─a─time*/ + _=delword(_, ?, 1) /*delete the just─chosen card. */ end /*shuffler*/ -return -/*──────────────────────────────────DEALHANDS subroutine────────────────*/ -dealHands: parse arg numberOfCards,hands; hand.='' - do numberOfCards /*deal the hand to the players. */ - do player=1 for hands /*deal a card to the players. */ - hand.player=hand.player subword(theDeck,1,1) /*deal top card.*/ - theDeck=subword(theDeck,2 ) /*diminish deck, remove one card.*/ - end /*player*/ - end /*numberOfCards*/ +return y +/*──────────────────────────────────DEAL subroutine─────────────────────*/ +deal: parse arg #cards, hands; hand.= + do #cards /*deal the hand to the players. */ + do player=1 for hands /*deal some cards to the players.*/ + hand.player=hand.player word(deck, 1) /*deal top card.*/ + deck=subword(deck, 2) /*diminish deck, remove one card.*/ + end /*player*/ + end /*#cards*/ return diff --git a/Task/Playing-cards/Ruby/playing-cards.rb b/Task/Playing-cards/Ruby/playing-cards.rb index 0162624fb6..df555e34ba 100644 --- a/Task/Playing-cards/Ruby/playing-cards.rb +++ b/Task/Playing-cards/Ruby/playing-cards.rb @@ -1,52 +1,47 @@ class Card - # class constants - Suits = ["Clubs","Hearts","Spades","Diamonds"] - Pips = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"] - - # class variables (private) - @@suit_value = Hash[ Suits.each_with_index.to_a ] - @@pip_value = Hash[ Pips.each_with_index.to_a ] - - attr_reader :pip, :suit - - def initialize(pip,suit) - @pip = pip - @suit = suit - end - - def to_s - "#{@pip} #{@suit}" - end - - # allow sorting an array of Cards: first by suit, then by value - def <=>(card) - (@@suit_value[@suit] <=> @@suit_value[card.suit]).nonzero? or \ - @@pip_value[@pip] <=> @@pip_value[card.pip] - end + # class constants + SUITS = %i[ Clubs Hearts Spades Diamonds ] + PIPS = %i[ 2 3 4 5 6 7 8 9 10 Jack Queen King Ace ] + + # class variables (private) + @@suit_value = Hash[ SUITS.each_with_index.to_a ] + @@pip_value = Hash[ PIPS.each_with_index.to_a ] + + attr_reader :pip, :suit + + def initialize(pip,suit) + @pip = pip + @suit = suit + end + + def to_s + "#{@pip} #{@suit}" + end + + # allow sorting an array of Cards: first by suit, then by value + def <=>(other) + (@@suit_value[@suit] <=> @@suit_value[other.suit]).nonzero? or + @@pip_value[@pip] <=> @@pip_value[other.pip] + end end class Deck - def initialize - @deck = [] - for suit in Card::Suits - for pip in Card::Pips - @deck << Card.new(pip,suit) - end - end - end - - def to_s - "[#{@deck.join(", ")}]" - end - - def shuffle! - @deck.shuffle! - self - end - - def deal(*args) - @deck.shift(*args) - end + def initialize + @deck = Card::SUITS.product(Card::PIPS).map{|suit,pip| Card.new(pip,suit)} + end + + def to_s + "[#{@deck.join(", ")}]" + end + + def shuffle! + @deck.shuffle! + self + end + + def deal(*args) + @deck.shift(*args) + end end deck = Deck.new.shuffle! diff --git a/Task/Playing-cards/Rust/playing-cards.rust b/Task/Playing-cards/Rust/playing-cards.rust index b64fe3aa27..83c25f41bc 100644 --- a/Task/Playing-cards/Rust/playing-cards.rust +++ b/Task/Playing-cards/Rust/playing-cards.rust @@ -1,125 +1,63 @@ -use std::fmt; -use std::rand::{task_rng, Rng}; - -#[deriving(Clone)] -enum Pip { - Ace, - Two, - Three, - Four, - Five, - Six, - Seven, - Eight, - Nine, - Ten, - Jack, - Queen, - King -} +extern crate rand; -impl fmt::Show for Pip { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let name = match *self { - Ace => "Ace", - Two => "Two", - Three => "Three", - Four => "Four", - Five => "Five", - Six => "Six", - Seven => "Seven", - Eight => "Eight", - Nine => "Nine", - Ten => "Ten", - Jack => "Jack", - Queen => "Queen", - King => "King" - }; - - write!(f, "{}", name) - } -} - -#[deriving(Clone)] -enum Suit { - Spades, - Hearts, - Diamonds, - Clubs -} +use std::fmt; +use rand::Rng; +use Pip::*; +use Suit::*; -impl fmt::Show for Suit { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let name = match *self { - Spades => "Spades", - Hearts => "Hearts", - Diamonds => "Diamonds", - Clubs => "Clubs" - }; +#[derive(Copy, Clone, Debug)] +enum Pip { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King } - write!(f, "{}", name) - } -} +#[derive(Copy, Clone, Debug)] +enum Suit { Spades, Hearts, Diamonds, Clubs } -#[deriving(Clone)] struct Card { pip: Pip, suit: Suit } -impl Card { - fn new(pip: Pip, suit: Suit) -> Card { - Card {pip: pip, suit: suit} - } -} - -impl fmt::Show for Card { +impl fmt::Display for Card { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{} of {}", self.pip, self.suit) + write!(f, "{:?} of {:?}", self.pip, self.suit) } } -#[deriving(Clone)] struct Deck(Vec); impl Deck { fn new() -> Deck { let mut cards:Vec = Vec::with_capacity(52); - for suit in [Spades, Hearts, Diamonds, Clubs].iter() { - for pip in [Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King].iter() { - cards.push(Card::new(*pip, *suit)); + for &suit in &[Spades, Hearts, Diamonds, Clubs] { + for &pip in &[Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King] { + cards.push( Card{pip: pip, suit: suit} ); } } Deck(cards) } fn deal(&mut self) -> Option { - let &Deck(ref mut cards) = self; - cards.pop() + self.0.pop() } fn shuffle(&mut self) { - let &Deck(ref mut cards) = self; - let mut rng = task_rng(); - - rng.shuffle(cards.as_mut_slice()); + rand::thread_rng().shuffle(&mut self.0) } } -impl fmt::Show for Deck { +impl fmt::Display for Deck { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let &Deck(ref cards) = self; - - let mut text = String::new(); - let mut i = 0; - for card in cards.iter() { - text.push_str(format!("{}", card).as_slice()); - i += 1; - if i < cards.capacity() { - text.push_str("\n"); - } + for card in self.0.iter() { + writeln!(f, "{}", card); } + write!(f, "") + } +} - write!(f, "{}", text) +fn main() { + let mut deck = Deck::new(); + deck.shuffle(); + //println!("{}", deck); + for _ in 0..5 { + println!("{}", deck.deal().unwrap()); } } diff --git a/Task/Plot-coordinate-pairs/Go/plot-coordinate-pairs.go b/Task/Plot-coordinate-pairs/Go/plot-coordinate-pairs.go new file mode 100644 index 0000000000..264c55122f --- /dev/null +++ b/Task/Plot-coordinate-pairs/Go/plot-coordinate-pairs.go @@ -0,0 +1,30 @@ +package main + +import ( + "fmt" + "log" + "os/exec" +) + +var ( + x = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} + y = []float64{2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0} +) + +func main() { + g := exec.Command("gnuplot", "-persist") + w, err := g.StdinPipe() + if err != nil { + log.Fatal(err) + } + if err = g.Start(); err != nil { + log.Fatal(err) + } + fmt.Fprintln(w, "unset key; plot '-'") + for i, xi := range x { + fmt.Fprintf(w, "%d %f\n", xi, y[i]) + } + fmt.Fprintln(w, "e") + w.Close() + g.Wait() +} diff --git a/Task/Pointers-and-references/Perl-6/pointers-and-references.pl6 b/Task/Pointers-and-references/Perl-6/pointers-and-references.pl6 index 3fa7a6c443..ba2ce3a8e0 100644 --- a/Task/Pointers-and-references/Perl-6/pointers-and-references.pl6 +++ b/Task/Pointers-and-references/Perl-6/pointers-and-references.pl6 @@ -9,5 +9,5 @@ my @bar = 1,2,3; # deref @bar name to array container, then set its values @bar»++; # deref @bar name to array container, then increment each value with a hyper @bar.say; # deref @bar name to array container, then call say on that, giving 2 3 4 -@bar := (1,2,3); # bind name directly to a Parcel +@bar := (1,2,3); # bind name directly to a List @bar»++; # ERROR, parcels are not mutable diff --git a/Task/Polymorphic-copy/00DESCRIPTION b/Task/Polymorphic-copy/00DESCRIPTION index b97ab4f7b4..6ffbf54195 100644 --- a/Task/Polymorphic-copy/00DESCRIPTION +++ b/Task/Polymorphic-copy/00DESCRIPTION @@ -1,8 +1,15 @@ -An object is [[polymorphism|polymorphic]] when its specific type may vary. The types a specific value may take, is called ''class''. +An object is [[polymorphism|polymorphic]] when its specific type may vary. +The types a specific value may take, is called ''class''. It is trivial to copy an object if its type is known: int x; int y = x; -Here x is not polymorphic, so y is declared of same type (''int'') as x. But if the specific type of x were unknown, then y could not be declared of any specific type. +Here x is not polymorphic, so y is declared of same type (''int'') as x. +But if the specific type of x were unknown, then y could not be declared of any specific type. -The task: let a polymorphic object contain an instance of some specific type S derived from a type T. The type T is known. The type S is possibly unknown until [[run time]]. The objective is to create an exact copy of such polymorphic object (not to create a [[reference]], nor a pointer to). Let further the type T have a method overridden by S. This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S. +The task: let a polymorphic object contain an instance of some specific type S derived from a type T. +The type T is known. +The type S is possibly unknown until [[run time]]. +The objective is to create an exact copy of such polymorphic object (not to create a [[reference]], nor a pointer to). +Let further the type T have a method overridden by S. +This method is to be called on the copy to demonstrate that the specific type of the copy is indeed S. diff --git a/Task/Polymorphic-copy/Delphi/polymorphic-copy-1.delphi b/Task/Polymorphic-copy/Delphi/polymorphic-copy-1.delphi new file mode 100644 index 0000000000..0528a3e4a1 --- /dev/null +++ b/Task/Polymorphic-copy/Delphi/polymorphic-copy-1.delphi @@ -0,0 +1,33 @@ +program PolymorphicCopy; + +type + T = class + function Name:String; virtual; + function Clone:T; virtual; + end; + + S = class(T) + function Name:String; override; + function Clone:T; override; + end; + +function T.Name :String; begin Exit('T') end; +function T.Clone:T; begin Exit(T.Create)end; + +function S.Name :String; begin Exit('S') end; +function S.Clone:T; begin Exit(S.Create)end; + +procedure Main; +var + Original, Clone :T; +begin + Original := S.Create; + Clone := Original.Clone; + + WriteLn(Original.Name); + WriteLn(Clone.Name); +end; + +begin + Main; +end. diff --git a/Task/Polymorphic-copy/Delphi/polymorphic-copy-2.delphi b/Task/Polymorphic-copy/Delphi/polymorphic-copy-2.delphi new file mode 100644 index 0000000000..ef9c0bf37c --- /dev/null +++ b/Task/Polymorphic-copy/Delphi/polymorphic-copy-2.delphi @@ -0,0 +1,2 @@ +S +S diff --git a/Task/Polymorphic-copy/Forth/polymorphic-copy.fth b/Task/Polymorphic-copy/Forth/polymorphic-copy-1.fth similarity index 100% rename from Task/Polymorphic-copy/Forth/polymorphic-copy.fth rename to Task/Polymorphic-copy/Forth/polymorphic-copy-1.fth diff --git a/Task/Polymorphic-copy/Forth/polymorphic-copy-2.fth b/Task/Polymorphic-copy/Forth/polymorphic-copy-2.fth new file mode 100644 index 0000000000..2f6754be7f --- /dev/null +++ b/Task/Polymorphic-copy/Forth/polymorphic-copy-2.fth @@ -0,0 +1,25 @@ +include FMS-SI.f + +:class T + ivar container \ can contain an object of any type + :m put ( obj -- ) container ! ;m + :m init: self self put ;m \ initially container holds self + :m print ." class is T" ;m + :m print-container container @ print ;m +;class + +:class S class dfa @ + obj1 heap: dup >r swap move r> ; + +T obj-t \ instantiate a T object +obj-t print-container \ class is T + +S obj-s \ instantiate an S object +obj-s ecopy obj-t put \ make an exact copy of S object and store in T object + +obj-t print-container \ class is S diff --git a/Task/Polymorphic-copy/Go/polymorphic-copy.go b/Task/Polymorphic-copy/Go/polymorphic-copy.go index d8529afbb4..51b7254598 100644 --- a/Task/Polymorphic-copy/Go/polymorphic-copy.go +++ b/Task/Polymorphic-copy/Go/polymorphic-copy.go @@ -37,8 +37,8 @@ func (x t) identify() string { } // the same method on s. although s already satisfied i, calls to identify -// will now find this method rather than the one defined on t. in a sense -// it "overrides" the method of the "base class." +// will now find this method rather than the one defined on t. +// in a sense it "overrides" the method of the "base class." func (x s) identify() string { return "I'm an s!" } diff --git a/Task/Polymorphism/ALGOL-68/polymorphism.alg b/Task/Polymorphism/ALGOL-68/polymorphism.alg new file mode 100644 index 0000000000..acf04a3823 --- /dev/null +++ b/Task/Polymorphism/ALGOL-68/polymorphism.alg @@ -0,0 +1,95 @@ +# Algol 68 provides for polymorphic operators but not procedures # + +# define the CIRCLE and POINT modes # +MODE POINT = STRUCT( REAL x, y ); +MODE CIRCLE = STRUCT( REAL x, y, r ); + + +# PRINT operator # +OP PRINT = ( POINT p )VOID: print( ( "Point(", x OF p, ",", y OF p, ")" ) ); +OP PRINT = ( CIRCLE c )VOID: print( ( "Circle(", r OF c, " @ ", x OF c, ",", y OF c, ")" ) ); + +# getters # +OP XCOORD = ( POINT p )REAL: x OF p; +OP YCOORD = ( POINT p )REAL: y OF p; + +OP XCOORD = ( CIRCLE c )REAL: x OF c; +OP YCOORD = ( CIRCLE c )REAL: y OF c; +OP RADIUS = ( CIRCLE c )REAL: r OF c; + +# setters # +# the setters are dyadic operators so need a priority - we make them lowest # +# priority, like PLUSAB etc. # +# They could have the same names as the getters but this seems clearer? # +PRIO SETXCOORD = 1 + , SETYCOORD = 1 + , SETRADIUS = 1 + ; +# the setters return the POINT/CIRCLE being modified so we can write e.g. # +# "PRINT ( p SETXCOORD 3 )" # +OP SETXCOORD = ( REF POINT p, REAL x )REF POINT: ( x OF p := x; p ); +OP SETYCOORD = ( REF POINT p, REAL y )REF POINT: ( y OF p := y; p ); + +OP SETXCOORD = ( REF CIRCLE c, REAL x )REF CIRCLE: ( x OF c := x; c ); +OP SETYCOORD = ( REF CIRCLE c, REAL y )REF CIRCLE: ( y OF c := y; c ); +OP SETRADIUS = ( REF CIRCLE c, REAL r )REF CIRCLE: ( r OF c := r; c ); + +# operands of an operator are not automatically coerced from INT to REAL so # +# we also need these operators # +OP SETXCOORD = ( REF POINT p, INT x )REF POINT: ( x OF p := x; p ); +OP SETYCOORD = ( REF POINT p, INT y )REF POINT: ( y OF p := y; p ); + +OP SETXCOORD = ( REF CIRCLE c, INT x )REF CIRCLE: ( x OF c := x; c ); +OP SETYCOORD = ( REF CIRCLE c, INT y )REF CIRCLE: ( y OF c := y; c ); +OP SETRADIUS = ( REF CIRCLE c, INT r )REF CIRCLE: ( r OF c := r; c ); + +# copy constructors # +# A copy constructor is not needed as assignment will generate a copy # +# e.g.: "POINT pa, pb; pa := ...; pb := pa; ..." will make pb a copy of pa # + +# assignment # +# It is not possible to redefine the assignment "operator" in Algol 68 but # +# assignment is automatically provided so no code need be written for e.g. # +# "CIRCLE c1 := ...." # + +# destructors # +# Algol 68 does not include destructors. A particular postlude could, # +# in theory be provided if specific cleanup was requried, but this would # +# occur at the end of the program, not at the end of the lifetime of the # +# object. # + +# default constructor # +# Algol 68 automatically provides generators HEAP and LOC, which will # +# create new objects of the specified MODE, e.g. HEAP CIRCLE will create a # +# new CIRCLE. HEAP allocates apace on the heap, LOC allocates in on the # +# stack (so the new item disappears when the enclosing block procedure or # +# operator finishes) # + +# a suitable "display" (value list enclosed in "(" and ")") can be cast to # +# the relevent MODE, allowing us to write e.g.: # +# "POINT( 3.1, 2.2 )" where we need a new item. # + +# "constructors" with other than all the fields in the correct order could # +# be provided as procedures but each would need a distinct name # +# e.g. # +PROC new circle at the origin = ( REAL r )REF CIRCLE: + ( ( HEAP CIRCLE SETRADIUS r ) SETXCOORD 0 ) SETYCOORD 0; +PROC new point at the origin = REF POINT: + ( HEAP POINT SETXCOORD 0 ) SETYCOORD 0; + + +# examples of use # + +BEGIN + + CIRCLE c1 := CIRCLE( 1.1, 2.4, 4.1 ); + POINT p1 := new point at the origin; + + PRINT c1; newline( stand out ); + + # move c1 so it is centred on p1 # + ( c1 SETXCOORD XCOORD p1 ) SETYCOORD YCOORD p1; + + PRINT c1; newline( stand out ) + +END diff --git a/Task/Polymorphism/Forth/polymorphism.fth b/Task/Polymorphism/Forth/polymorphism-1.fth similarity index 100% rename from Task/Polymorphism/Forth/polymorphism.fth rename to Task/Polymorphism/Forth/polymorphism-1.fth diff --git a/Task/Polymorphism/Forth/polymorphism-2.fth b/Task/Polymorphism/Forth/polymorphism-2.fth new file mode 100644 index 0000000000..cd091aa227 --- /dev/null +++ b/Task/Polymorphism/Forth/polymorphism-2.fth @@ -0,0 +1,50 @@ +include FMS-SI.f + +:class point + ivar x \ instance variable + ivar y + :m print x ? y ? ;m \ define print method + :m get ( -- x y ) x @ y @ ;m + :m put ( x y -- ) y ! x ! ;m + :m copy ( -- point-obj2 ) + self get heap> point dup >r put r> ;m +;class + +point p1 \ instantiate object p1 +23 5 p1 put +p1 print +p1 copy value p2 \ copy constructor +p2 print +p2 circle dup >r put r> ;m +;class + +circle c1 +4 5 2 c1 put +c1 print +c1 copy value c2 +c2 print +c2 print_point + procedure, pass :: copy_point + !overloaded assignment operator + generic, public :: assignment(=) => copy_point end type point type, extends(point) :: circle @@ -17,8 +20,20 @@ module geom procedure, public :: get_r procedure, public :: set_r procedure, public :: print => print_circle + procedure, pass :: copy_circle + !overloaded assignment operator + generic, public :: assignment(=) => copy_circle end type circle + ! constructor interface + interface circle + module procedure circle_constructor + end interface circle + ! constructor interface + interface point + module procedure point_constructor + end interface point + contains real(8) function get_x(this) @@ -64,18 +79,51 @@ subroutine print_circle(this) write(*,'(3(a,f0.4),a)') 'Circle(',this%x,', ',this%y,'; ',this%r,')' end subroutine print_circle + subroutine copy_point(this, rhs) + class(point), intent(inout) :: this + type(point), intent(in) :: rhs + this%x = rhs%x + this%y = rhs%y + end subroutine copy_point + + subroutine copy_circle(this, rhs) + class(circle), intent(inout) :: this + type(circle), intent(in) :: rhs + this%x = rhs%x + this%y = rhs%y + this%r = rhs%r + end subroutine copy_circle + +! non-default constructor to init private components + type(point) function point_constructor(x,y) + real(8), intent(in) :: x,y + point_constructor%x = x + point_constructor%y = y + end function point_constructor +! non-default constructor to init private components + type(circle) function circle_constructor(x,y,r) + real(8), intent(in) :: x,y,r + circle_constructor%x = x + circle_constructor%y = y + circle_constructor%r = r + end function circle_constructor + end module geom program inh use geom - type(point) :: p - type(circle) :: c + type(point) :: p, p_copy + type(circle) :: c, c_copy p = point(2.0d0, 3.0d0) call p%print + p_copy = p + call p_copy%print c = circle(3.0d0, 4.0d0, 5.0d0) call c%print + c_copy = c + call c_copy%print end program inh diff --git a/Task/Polymorphism/Self/polymorphism.self b/Task/Polymorphism/Self/polymorphism.self new file mode 100644 index 0000000000..42f6da3cc0 --- /dev/null +++ b/Task/Polymorphism/Self/polymorphism.self @@ -0,0 +1,21 @@ +traits point = (| + parent* = traits clonable. + printString = ('Point(', x asString, ':', y asString, ')'). + |) + +point = (| + parent* = traits point. + x <- 0. + y <- 0 + |) + +traits circle = (| + parent* = traits clonable. + printString = ('Circle(', center asString, ',', r asString, ')'). + |) + +circle = (| + parent* = traits circle. + center <- point copy. + r <- 0 + |) diff --git a/Task/Polynomial-long-division/Julia/polynomial-long-division.julia b/Task/Polynomial-long-division/Julia/polynomial-long-division.julia new file mode 100644 index 0000000000..f37663d1dc --- /dev/null +++ b/Task/Polynomial-long-division/Julia/polynomial-long-division.julia @@ -0,0 +1,8 @@ +using Polynomials + +p = Poly([-42,0,-12,1]) +q = Poly([-3,1]) + +d, r = divrem(p,q) + +println(p, " divided by ", q, " is ", d, " with remainder ", r, ".") diff --git a/Task/Polynomial-long-division/Perl-6/polynomial-long-division.pl6 b/Task/Polynomial-long-division/Perl-6/polynomial-long-division.pl6 index a1d416e2ed..5c1a5432ab 100644 --- a/Task/Polynomial-long-division/Perl-6/polynomial-long-division.pl6 +++ b/Task/Polynomial-long-division/Perl-6/polynomial-long-division.pl6 @@ -1,8 +1,8 @@ sub poly_long_div ( @n is copy, @d ) { - return [0], @n if +@n < +@d; + return [0], |@n if +@n < +@d; my @q = gather while +@n >= +@d { - @n = @n Z- ( ( @d X* take ( @n[0] / @d[0] ) ), 0 xx * ); + @n = @n Z- flat ( ( @d X* take ( @n[0] / @d[0] ) ), 0 xx * ); @n.shift; } diff --git a/Task/Polynomial-regression/Emacs-Lisp/polynomial-regression.l b/Task/Polynomial-regression/Emacs-Lisp/polynomial-regression.l new file mode 100644 index 0000000000..9109ddb1ff --- /dev/null +++ b/Task/Polynomial-regression/Emacs-Lisp/polynomial-regression.l @@ -0,0 +1,4 @@ +(setq x '[0 1 2 3 4 5 6 7 8 9 10]) +(setq y '[1 6 17 34 57 86 121 162 209 262 321]) +(calc-eval + (format "fit(a*x^2+b*x+c,[x],[a,b,c],[%s %s])" x y)) diff --git a/Task/Polynomial-regression/Go/polynomial-regression-1.go b/Task/Polynomial-regression/Go/polynomial-regression-1.go new file mode 100644 index 0000000000..f88f93ccef --- /dev/null +++ b/Task/Polynomial-regression/Go/polynomial-regression-1.go @@ -0,0 +1,40 @@ +package main + +import ( + "fmt" + + "github.com/gonum/matrix/mat64" +) + +var ( + x = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + y = []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321} + + degree = 2 +) + +func main() { + a := Vandermonde(x, 2) + b := mat64.NewDense(11, 1, y) + c := mat64.NewDense(3, 1, nil) + + qr := new(mat64.QR) + qr.Factorize(a) + + err := c.SolveQR(qr, false, b) + if err != nil { + fmt.Println(err) + } else { + fmt.Printf("%.3f\n", mat64.Formatted(c)) + } +} + +func Vandermonde(a []float64, degree int) *mat64.Dense { + x := mat64.NewDense(len(a), degree+1, nil) + for i := range a { + for j, p := 0, 1.; j <= degree; j, p = j+1, p*a[i] { + x.Set(i, j, p) + } + } + return x +} diff --git a/Task/Polynomial-regression/Go/polynomial-regression-2.go b/Task/Polynomial-regression/Go/polynomial-regression-2.go new file mode 100644 index 0000000000..80389a0359 --- /dev/null +++ b/Task/Polynomial-regression/Go/polynomial-regression-2.go @@ -0,0 +1,41 @@ +package main + +import ( + "fmt" + + "github.com/skelterjohn/go.matrix" +) + +var xGiven = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +var yGiven = []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321} +var degree = 2 + +func main() { + m := len(yGiven) + n := degree + 1 + y := matrix.MakeDenseMatrix(yGiven, m, 1) + x := matrix.Zeros(m, n) + for i := 0; i < m; i++ { + ip := float64(1) + for j := 0; j < n; j++ { + x.Set(i, j, ip) + ip *= xGiven[i] + } + } + + q, r := x.QR() + qty, err := q.Transpose().Times(y) + if err != nil { + fmt.Println(err) + return + } + c := make([]float64, n) + for i := n - 1; i >= 0; i-- { + c[i] = qty.Get(i, 0) + for j := i + 1; j < n; j++ { + c[i] -= c[j] * r.Get(i, j) + } + c[i] /= r.Get(i, i) + } + fmt.Println(c) +} diff --git a/Task/Polynomial-regression/Go/polynomial-regression.go b/Task/Polynomial-regression/Go/polynomial-regression.go deleted file mode 100644 index f1003df554..0000000000 --- a/Task/Polynomial-regression/Go/polynomial-regression.go +++ /dev/null @@ -1,40 +0,0 @@ -package main - -import ( - "code.google.com/p/gomatrix/matrix" - "fmt" -) - -var xGiven = []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} -var yGiven = []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321} -var degree = 2 - -func main() { - m := len(yGiven) - n := degree + 1 - y := matrix.MakeDenseMatrix(yGiven, m, 1) - x := matrix.Zeros(m, n) - for i := 0; i < m; i++ { - ip := float64(1) - for j := 0; j < n; j++ { - x.Set(i, j, ip) - ip *= xGiven[i] - } - } - - q, r := x.QR() - qty, err := q.Transpose().Times(y) - if err != nil { - fmt.Println(err) - return - } - c := make([]float64, n) - for i := n - 1; i >= 0; i-- { - c[i] = qty.Get(i, 0) - for j := i + 1; j < n; j++ { - c[i] -= c[j] * r.Get(i, j) - } - c[i] /= r.Get(i, i) - } - fmt.Println(c) -} diff --git a/Task/Polynomial-regression/PARI-GP/polynomial-regression-3.pari b/Task/Polynomial-regression/PARI-GP/polynomial-regression-3.pari new file mode 100644 index 0000000000..4a9293087c --- /dev/null +++ b/Task/Polynomial-regression/PARI-GP/polynomial-regression-3.pari @@ -0,0 +1,2 @@ +lsf(X,Y,n)=my(M=matrix(#X,n,i,j,X[i]^(j-1))); Polrev(matsolve(M~*M,M~*Y~) +lsf([0..10], [1,6,17,34,57,86,121,162,209,262,321], 3) diff --git a/Task/Polynomial-regression/Perl/polynomial-regression.pl b/Task/Polynomial-regression/Perl/polynomial-regression.pl new file mode 100644 index 0000000000..47ad2fe9a0 --- /dev/null +++ b/Task/Polynomial-regression/Perl/polynomial-regression.pl @@ -0,0 +1,115 @@ +#!bin/usr/perl +use strict; +use warnings; +use 5.020; + +#This is a script to calculate an equation for a given set of coordinates. +#Input will be taken in sets of x and y. It can handle a grand total of 26 pairs. +#For matrix functions, we depend on the Math::MatrixReal package. +use Math::MatrixReal; + +=pod +Step 1: Get each x coordinate all at once (delimited by " ") and each for y at once +on the next prompt in the same format (delimited by " "). +=cut +sub getPairs() { + my $buffer = ; + chomp($buffer); + return split(" ", $buffer); +} +say("Please enter the values for the x coordinates, each delimited by a space. \(Ex: 0 1 2 3\)"); +my @x = getPairs(); +say("Please enter the values for the y coordinates, each delimited by a space. \(Ex: 0 1 2 3\)"); +my @y = getPairs(); +#This whole thing depends on the number of x's being the same as the number of y's +my $pairs = scalar(@x); + + +=pod +Step 2: Devise the base equation of our polynomial using the following idea +There is some polynomial of degree n (n == number of pairs - 1) such that +f(x)=ax^n + bx^(n-1) + ... yx + z +=cut +#Create an array of coefficients and their degrees with the format ("coefficent degree") +my @alphabet; +my @degrees; +for(my $alpha = "a", my $degree = $pairs - 1; $degree >= 0; $degree--, $alpha++) { + push(@alphabet, "$alpha"); + push(@degrees, "$degree"); +} + + +=pod +Step 3: Using the array of coeffs and their degrees, set up individual equations solving for +each coordinate pair. Why put it in this format? It interfaces witht he Math::MatrixReal package better this way. +=cut +my @coeffs; +for(my $count = 0; $count < $pairs; $count++) { + my $buffer = "[ "; + foreach (@degrees) { + $buffer .= (($x[$count] ** $_) . " "); + } + push(@coeffs, ($buffer . "]")); +} +my $row; +foreach (@coeffs) { + $row .= ("$_\n"); +} + + +=pod +Step 4: We now have rows of x's raised to powers. With this in mind, we create a coefficient matrix. +=cut +my $matrix = Math::MatrixReal->new_from_string($row); +my $buffMatrix = $matrix->new_from_string($row); + + +=pod +Step 5: Now that we've gotten the matrix to do what we want it to do, we need to calculate the various determinants of the matrices +=cut +my $coeffDet = $matrix->det(); + + +=pod +Step 6: Now that we have the determinant of the coefficient matrix, we need to find the determinants of the coefficient matrix with each column (1 at a time) replaced with the y values. +=cut +#NOTE: Unlike in Perl, matrix indices start at 1, not 0. +for(my $rows = my $column = 1; $column <= $pairs; $column++) { + #Reassign the values in the current column to the y values + foreach (@y) { + $buffMatrix->assign($rows, $column, $_); + $rows++; + } + #Find the values for the variables a, b, ... y, z in the original polynomial + #To round the difference of the determinants, I had to get creative + my $buffDet = $buffMatrix->det() / $coeffDet; + my $tempDet = int(abs($buffDet) + .5); + $alphabet[$column - 1] = $buffDet >= 0 ? $tempDet : 0 - $tempDet; + #Reset the buffer matrix and the row counter + $buffMatrix = $matrix->new_from_string($row); + $rows = 1; +} + + +=pod +Step 7: Now that we've found the values of a, b, ... y, z of the original polynomial, it's time to form our polynomial! +=cut +my $polynomial; +for(my $i = 0; $i < $pairs-1; $i++) { + if($alphabet[$i] == 0) { + next; + } + if($alphabet[$i] == 1) { + $polynomial .= ($degrees[$i] . " + "); + } + if($degrees[$i] == 1) { + $polynomial .= ($alphabet[$i] . "x" . " + "); + } + else { + $polynomial .= ($alphabet[$i] . "x^" . $degrees[$i] . " + "); + } +} +#Now for the last piece of the poly: the y-intercept. +$polynomial .= $alphabet[scalar(@alphabet)-1]; + +print("An approximating polynomial for your dataset is $polynomial.\n"); diff --git a/Task/Power-set/Ada/power-set-1.ada b/Task/Power-set/Ada/power-set-1.ada new file mode 100644 index 0000000000..22f8156055 --- /dev/null +++ b/Task/Power-set/Ada/power-set-1.ada @@ -0,0 +1,10 @@ +package Power_Set is + + type Set is array (Positive range <>) of Positive; + Empty_Set: Set(1 .. 0); + + generic + with procedure Visit(S: Set); + procedure All_Subsets(S: Set); -- calles Visit once for each subset of S + +end Power_Set; diff --git a/Task/Power-set/Ada/power-set-2.ada b/Task/Power-set/Ada/power-set-2.ada new file mode 100644 index 0000000000..951f255bd9 --- /dev/null +++ b/Task/Power-set/Ada/power-set-2.ada @@ -0,0 +1,20 @@ +package body Power_Set is + + procedure All_Subsets(S: Set) is + + procedure Visit_Sets(Unmarked: Set; Marked: Set) is + Tail: Set := Unmarked(Unmarked'First+1 .. Unmarked'Last); + begin + if Unmarked = Empty_Set then + Visit(Marked); + else + Visit_Sets(Tail, Marked & Unmarked(Unmarked'First)); + Visit_Sets(Tail, Marked); + end if; + end Visit_Sets; + + begin + Visit_Sets(S, Empty_Set); + end All_Subsets; + +end Power_Set; diff --git a/Task/Power-set/Ada/power-set-3.ada b/Task/Power-set/Ada/power-set-3.ada new file mode 100644 index 0000000000..8fb42043e1 --- /dev/null +++ b/Task/Power-set/Ada/power-set-3.ada @@ -0,0 +1,28 @@ +with Ada.Text_IO, Ada.Command_Line, Power_Set; + +procedure Print_Power_Set is + + procedure Print_Set(Items: Power_Set.Set) is + First: Boolean := True; + begin + Ada.Text_IO.Put("{ "); + for Item of Items loop + if First then + First := False; -- no comma needed + else + Ada.Text_IO.Put(", "); -- comma, to separate the items + end if; + Ada.Text_IO.Put(Ada.Command_Line.Argument(Item)); + end loop; + Ada.Text_IO.Put_Line(" }"); + end Print_Set; + + procedure Print_All_Subsets is new Power_Set.All_Subsets(Print_Set); + + Set: Power_Set.Set(1 .. Ada.Command_Line.Argument_Count); +begin + for I in Set'Range loop -- initialize set + Set(I) := I; + end loop; + Print_All_Subsets(Set); -- do the work +end; diff --git a/Task/Power-set/Ada/power-set.ada b/Task/Power-set/Ada/power-set.ada deleted file mode 100644 index 8552023ac0..0000000000 --- a/Task/Power-set/Ada/power-set.ada +++ /dev/null @@ -1,42 +0,0 @@ -with Ada.Text_IO, Ada.Command_Line; - -procedure Power_Set is - - type List is array (Positive range <>) of Positive; - Empty: List(1 .. 0); - - procedure Print_All_Subsets(Set: List; Printable: List:= Empty) is - - procedure Print_Set(Items: List) is - First: Boolean := True; - begin - Ada.Text_IO.Put("{ "); - for Item of Items loop - if First then - First := False; -- no comma needed - else - Ada.Text_IO.Put(", "); -- comma, to separate the items - end if; - Ada.Text_IO.Put(Ada.Command_Line.Argument(Item)); - end loop; - Ada.Text_IO.Put_Line(" }"); - end Print_Set; - - Tail: List := Set(Set'First+1 .. Set'Last); - - begin - if Set = Empty then - Print_Set(Printable); - else - Print_All_Subsets(Tail, Printable & Set(Set'First)); - Print_All_Subsets(Tail, Printable); - end if; - end Print_All_Subsets; - - Set: List(1 .. Ada.Command_Line.Argument_Count); -begin - for I in Set'Range loop -- initialize set - Set(I) := I; - end loop; - Print_All_Subsets(Set); -- do the work -end Power_Set; diff --git a/Task/Power-set/C++/power-set-2.cpp b/Task/Power-set/C++/power-set-2.cpp index d16caef8b4..bb67cc84d0 100644 --- a/Task/Power-set/C++/power-set-2.cpp +++ b/Task/Power-set/C++/power-set-2.cpp @@ -1,25 +1,34 @@ -#include #include +#include -template std::set powerset(const Set& s, size_t n) +template +auto powerset(const S& s) { - typedef typename Set::const_iterator SetCIt; - typedef typename std::set::const_iterator PowerSetCIt; - std::set res; - if(n > 0) { - std::set ps = powerset(s, n-1); - for(PowerSetCIt ss = ps.begin(); ss != ps.end(); ss++) - for(SetCIt el = s.begin(); el != s.end(); el++) { - Set subset(*ss); - subset.insert(*el); - res.insert(subset); - } - res.insert(ps.begin(), ps.end()); - } else - res.insert(Set()); - return res; + std::set ret; + ret.emplace(); + for (auto&& e: s) { + std::set rs; + for (auto x: ret) { + x.insert(e); + rs.insert(x); + } + ret.insert(begin(rs), end(rs)); + } + return ret; } -template std::set powerset(const Set& s) + +int main() { - return powerset(s, s.size()); + std::set s = {2, 3, 5, 7}; + auto pset = powerset(s); + + for (auto&& subset: pset) { + std::cout << "{ "; + char const* prefix = ""; + for (auto&& e: subset) { + std::cout << prefix << e; + prefix = ", "; + } + std::cout << " }\n"; + } } diff --git a/Task/Power-set/C++/power-set-3.cpp b/Task/Power-set/C++/power-set-3.cpp new file mode 100644 index 0000000000..d16caef8b4 --- /dev/null +++ b/Task/Power-set/C++/power-set-3.cpp @@ -0,0 +1,25 @@ +#include +#include + +template std::set powerset(const Set& s, size_t n) +{ + typedef typename Set::const_iterator SetCIt; + typedef typename std::set::const_iterator PowerSetCIt; + std::set res; + if(n > 0) { + std::set ps = powerset(s, n-1); + for(PowerSetCIt ss = ps.begin(); ss != ps.end(); ss++) + for(SetCIt el = s.begin(); el != s.end(); el++) { + Set subset(*ss); + subset.insert(*el); + res.insert(subset); + } + res.insert(ps.begin(), ps.end()); + } else + res.insert(Set()); + return res; +} +template std::set powerset(const Set& s) +{ + return powerset(s, s.size()); +} diff --git a/Task/Power-set/Common-Lisp/power-set-1.lisp b/Task/Power-set/Common-Lisp/power-set-1.lisp index 189040c4f0..4f7968422b 100644 --- a/Task/Power-set/Common-Lisp/power-set-1.lisp +++ b/Task/Power-set/Common-Lisp/power-set-1.lisp @@ -1,8 +1,4 @@ -(defun power-set (s) - (reduce #'(lambda (item ps) - (append (mapcar #'(lambda (e) (cons item e)) - ps) - ps)) - s - :from-end t - :initial-value '(()))) +(defun powerset (s) + (if s (mapcan (lambda (x) (list (cons (car s) x) x)) + (powerset (cdr s))) + '(()))) diff --git a/Task/Power-set/Common-Lisp/power-set-2.lisp b/Task/Power-set/Common-Lisp/power-set-2.lisp index 3c8dde6d8f..189040c4f0 100644 --- a/Task/Power-set/Common-Lisp/power-set-2.lisp +++ b/Task/Power-set/Common-Lisp/power-set-2.lisp @@ -1,6 +1,8 @@ -(defun powerset (l) - (if (null l) - (list nil) - (let ((prev (powerset (cdr l)))) - (append (mapcar #'(lambda (elt) (cons (car l) elt)) prev) - prev)))) +(defun power-set (s) + (reduce #'(lambda (item ps) + (append (mapcar #'(lambda (e) (cons item e)) + ps) + ps)) + s + :from-end t + :initial-value '(()))) diff --git a/Task/Power-set/Common-Lisp/power-set-3.lisp b/Task/Power-set/Common-Lisp/power-set-3.lisp index a725ce72ea..3c8dde6d8f 100644 --- a/Task/Power-set/Common-Lisp/power-set-3.lisp +++ b/Task/Power-set/Common-Lisp/power-set-3.lisp @@ -1,3 +1,6 @@ -(defun powerset (xs) - (loop for i below (expt 2 (length xs)) collect - (loop for j below i for x in xs if (logbitp j i) collect x))) +(defun powerset (l) + (if (null l) + (list nil) + (let ((prev (powerset (cdr l)))) + (append (mapcar #'(lambda (elt) (cons (car l) elt)) prev) + prev)))) diff --git a/Task/Power-set/Common-Lisp/power-set-4.lisp b/Task/Power-set/Common-Lisp/power-set-4.lisp index 5a4d13b71d..a725ce72ea 100644 --- a/Task/Power-set/Common-Lisp/power-set-4.lisp +++ b/Task/Power-set/Common-Lisp/power-set-4.lisp @@ -1,5 +1,3 @@ -(defun power-set (list) - (let ((pow-set (list nil))) - (dolist (element (reverse list) pow-set) - (dolist (set pow-set) - (push (cons element set) pow-set))))) +(defun powerset (xs) + (loop for i below (expt 2 (length xs)) collect + (loop for j below i for x in xs if (logbitp j i) collect x))) diff --git a/Task/Power-set/Common-Lisp/power-set-5.lisp b/Task/Power-set/Common-Lisp/power-set-5.lisp new file mode 100644 index 0000000000..5a4d13b71d --- /dev/null +++ b/Task/Power-set/Common-Lisp/power-set-5.lisp @@ -0,0 +1,5 @@ +(defun power-set (list) + (let ((pow-set (list nil))) + (dolist (element (reverse list) pow-set) + (dolist (set pow-set) + (push (cons element set) pow-set))))) diff --git a/Task/Power-set/D/power-set-1.d b/Task/Power-set/D/power-set-1.d index cb3417dd44..7c33ecb429 100644 --- a/Task/Power-set/D/power-set-1.d +++ b/Task/Power-set/D/power-set-1.d @@ -1,16 +1,27 @@ -T[][] powerSet(T)(in T[] s) pure nothrow @safe { - auto r = new typeof(return)(1, 0); - foreach (e; s) { - typeof(return) rs; - foreach (x; r) - rs ~= x ~ [e]; - r ~= rs; - } - return r; +import std.algorithm; +import std.range; + +auto powerSet(R)(R r) +{ + return + (1L< + r.enumerate + .filter!(t => (1< t[1]) + ); } -void main() { - import std.stdio; +unittest +{ + int[] emptyArr; + assert(emptyArr.powerSet.equal!equal([emptyArr])); + assert(emptyArr.powerSet.powerSet.equal!(equal!equal)([[], [emptyArr]])); +} - [1, 2, 3].powerSet.writeln; +void main(string[] args) +{ + import std.stdio; + args[1..$].powerSet.each!writeln; } diff --git a/Task/Power-set/D/power-set-2.d b/Task/Power-set/D/power-set-2.d index 1215f156ac..8179fbfd48 100644 --- a/Task/Power-set/D/power-set-2.d +++ b/Task/Power-set/D/power-set-2.d @@ -1,37 +1,42 @@ -auto powerSet(T)(T[] xs) pure nothrow @safe { - static struct Result { - T[] xsLocal, output; - size_t len; - size_t bits; +import std.range; - this(T[] xs_) pure nothrow @safe { - this.xsLocal = xs_; - this.output.length = xs_.length; - this.len = 1U << xs_.length; - } +struct PowerSet(R) + if (isRandomAccessRange!R) +{ + R r; + size_t position; - @property empty() const pure nothrow @safe { - return bits == len; - } + struct PowerSetItem + { + R r; + size_t position; - void popFront() pure nothrow @safe { bits++; } - @property save() pure nothrow @safe { return this; } + private void advance() + { + while (!(position & 1)) + { + r.popFront(); + position >>= 1; + } + } - T[] front() pure nothrow @safe { - size_t pos = 0; - foreach (immutable size_t i; 0 .. xsLocal.length) - if (bits & (1 << i)) - output[pos++] = xsLocal[i]; - return output[0 .. pos]; - } - } + @property bool empty() { return position == 0; } + @property auto front() + { + advance(); + return r.front; + } + void popFront() + { + advance(); + r.popFront(); + position >>= 1; + } + } - return Result(xs); + @property bool empty() { return position == (1 << r.length); } + @property PowerSetItem front() { return PowerSetItem(r.save, position); } + void popFront() { position++; } } -version (power_set2_main) { - void main() { - import std.stdio; - [1, 2, 3].powerSet.writeln; - } -} +auto powerSet(R)(R r) { return PowerSet!R(r); } diff --git a/Task/Power-set/Elixir/power-set.elixir b/Task/Power-set/Elixir/power-set.elixir new file mode 100644 index 0000000000..1af6a26213 --- /dev/null +++ b/Task/Power-set/Elixir/power-set.elixir @@ -0,0 +1,29 @@ +defmodule RC do + use Bitwise + def powerset1(list) do + n = length(list) + max = round(:math.pow(2,n)) + for i <- 0..max-1, do: (for pos <- 0..n-1, band(i, bsl(1, pos)) != 0, do: Enum.at(list, pos) ) + end + + def powerset2([]), do: [[]] + def powerset2([h|t]) do + pt = powerset2(t) + (for x <- pt, do: [h|x]) ++ pt + end + + def powerset3([]), do: [[]] + def powerset3([h|t]) do + pt = powerset3(t) + powerset3(h, pt, pt) + end + + defp powerset3(_, [], acc), do: acc + defp powerset3(x, [h|t], acc), do: powerset3(x, t, [[x|h] | acc]) +end + +IO.inspect RC.powerset1([1,2,3]) +IO.inspect RC.powerset2([1,2,3]) +IO.inspect RC.powerset3([1,2,3]) +IO.inspect RC.powerset1([]) +IO.inspect RC.powerset1(["one"]) diff --git a/Task/Power-set/Julia/power-set.julia b/Task/Power-set/Julia/power-set.julia index 19a2c77785..e76d4ca229 100644 --- a/Task/Power-set/Julia/power-set.julia +++ b/Task/Power-set/Julia/power-set.julia @@ -1,7 +1,7 @@ -function powerset (x) - result = {{}} - for i in x, j = 1:length(result) - push!(result, [result[j],i]) - end - result +function powerset{T}(x::Vector{T}) + result = Vector{T}[[]] + for elem in x, j in eachindex(result) + push!(result, [result[j] ; elem]) + end + result end diff --git a/Task/Power-set/Maple/power-set.maple b/Task/Power-set/Maple/power-set.maple index c042354261..2de30ec751 100644 --- a/Task/Power-set/Maple/power-set.maple +++ b/Task/Power-set/Maple/power-set.maple @@ -1,3 +1 @@ -with(combinat): - -powerset({1,2,3,4}); +combinat:-powerset({1,2,3,4}); diff --git a/Task/Power-set/Perl/power-set-1.pl b/Task/Power-set/Perl/power-set-1.pl index 9a53bbc995..1e787bf00a 100644 --- a/Task/Power-set/Perl/power-set-1.pl +++ b/Task/Power-set/Perl/power-set-1.pl @@ -1,14 +1,8 @@ -use Set::Object qw(set); - -sub powerset { - my $p = Set::Object->new( set() ); - foreach my $i (shift->elements) { - $p->insert( map { set($_->elements, $i) } $p->elements ); - } - return $p; +use Algorithm::Combinatorics "subsets"; +my @S = ("a","b","c"); +my @PS; +my $iter = subsets(\@S); +while (my $p = $iter->next) { + push @PS, "[@$p]" } - -my $set = set(1, 2, 3); -my $powerset = powerset($set); - -print $powerset->as_string, "\n"; +say join(" ",@PS); diff --git a/Task/Power-set/Perl/power-set-10.pl b/Task/Power-set/Perl/power-set-10.pl new file mode 100644 index 0000000000..a7e912522e --- /dev/null +++ b/Task/Power-set/Perl/power-set-10.pl @@ -0,0 +1,21 @@ +use strict; +use warnings; +sub powerset(&@) { + my $callback = shift; + my $bitmask = ''; + my $bytes = @_/8; + { + my @indices = grep vec($bitmask, $_, 1), 0..$#_; + $callback->( @_[@indices] ); + ++vec($bitmask, $_, 8) and last for 0 .. $bytes; + redo if @indices != @_; + } +} + +print "powerset of empty set:\n"; +powerset { print "[@_]\n" }; +print "powerset of set {1,2,3,4}:\n"; +powerset { print "[@_]\n" } 1..4; +my $i = 0; +powerset { ++$i } 1..9; +print "The powerset of a nine element set contains $i elements.\n"; diff --git a/Task/Power-set/Perl/power-set-2.pl b/Task/Power-set/Perl/power-set-2.pl index 14835dd1be..53adc449dd 100644 --- a/Task/Power-set/Perl/power-set-2.pl +++ b/Task/Power-set/Perl/power-set-2.pl @@ -1,6 +1,4 @@ -package Set { - sub new { bless { map {$_ => undef} @_[1..$#_] }, shift; } - sub elements { sort keys %{shift()} } - sub as_string { 'Set(' . join(' ', sort keys %{shift()}) . ')' } - # ...more set methods could be defined here... -} +use ntheory "vecextract"; +my @S=("a","b","c"); +my @PS = map { "[".join(" ",vecextract(\@S,$_))."]" } 0..2**scalar(@S)-1; +say join(" ",@PS); diff --git a/Task/Power-set/Perl/power-set-3.pl b/Task/Power-set/Perl/power-set-3.pl index fc22e29c83..99b1aed6e7 100644 --- a/Task/Power-set/Perl/power-set-3.pl +++ b/Task/Power-set/Perl/power-set-3.pl @@ -1,11 +1,7 @@ -use List::Util qw(reduce); - -sub powerset { - @{( reduce { [@$a, map { Set->new($_->elements, $b) } @$a ] } - [Set->new()], shift->elements )}; +use ntheory "forcomb"; +my @S=("a","b","c"); +for $k (0..@S) { + # Iterate over each $#S+1,$k combination. + forcomb { print "[@S[@_]] " } @S,$k; } - -my $set = Set->new(1, 2, 3); -my @subsets = powerset($set); - -print $_->as_string, "\n" for @subsets; +print "\n"; diff --git a/Task/Power-set/Perl/power-set-4.pl b/Task/Power-set/Perl/power-set-4.pl index 90f5ed87c2..9a53bbc995 100644 --- a/Task/Power-set/Perl/power-set-4.pl +++ b/Task/Power-set/Perl/power-set-4.pl @@ -1,3 +1,14 @@ +use Set::Object qw(set); + sub powerset { - @_ ? map { $_, [$_[0], @$_] } powerset(@_[1..$#_]) : []; + my $p = Set::Object->new( set() ); + foreach my $i (shift->elements) { + $p->insert( map { set($_->elements, $i) } $p->elements ); + } + return $p; } + +my $set = set(1, 2, 3); +my $powerset = powerset($set); + +print $powerset->as_string, "\n"; diff --git a/Task/Power-set/Perl/power-set-5.pl b/Task/Power-set/Perl/power-set-5.pl index f9cea5d06c..14835dd1be 100644 --- a/Task/Power-set/Perl/power-set-5.pl +++ b/Task/Power-set/Perl/power-set-5.pl @@ -1,5 +1,6 @@ -use List::Util qw(reduce); - -sub powerset { - @{( reduce { [@$a, map([@$_, $b], @$a)] } [[]], @_ )} +package Set { + sub new { bless { map {$_ => undef} @_[1..$#_] }, shift; } + sub elements { sort keys %{shift()} } + sub as_string { 'Set(' . join(' ', sort keys %{shift()}) . ')' } + # ...more set methods could be defined here... } diff --git a/Task/Power-set/Perl/power-set-6.pl b/Task/Power-set/Perl/power-set-6.pl index 3d2864f0fb..fc22e29c83 100644 --- a/Task/Power-set/Perl/power-set-6.pl +++ b/Task/Power-set/Perl/power-set-6.pl @@ -1,8 +1,11 @@ -my @set = (1, 2, 3); -my @powerset = powerset(@set); +use List::Util qw(reduce); -sub set_to_string { - "{" . join(", ", map { ref $_ ? set_to_string(@$_) : $_ } @_) . "}" +sub powerset { + @{( reduce { [@$a, map { Set->new($_->elements, $b) } @$a ] } + [Set->new()], shift->elements )}; } -print set_to_string(@powerset), "\n"; +my $set = Set->new(1, 2, 3); +my @subsets = powerset($set); + +print $_->as_string, "\n" for @subsets; diff --git a/Task/Power-set/Perl/power-set-7.pl b/Task/Power-set/Perl/power-set-7.pl index a7e912522e..90f5ed87c2 100644 --- a/Task/Power-set/Perl/power-set-7.pl +++ b/Task/Power-set/Perl/power-set-7.pl @@ -1,21 +1,3 @@ -use strict; -use warnings; -sub powerset(&@) { - my $callback = shift; - my $bitmask = ''; - my $bytes = @_/8; - { - my @indices = grep vec($bitmask, $_, 1), 0..$#_; - $callback->( @_[@indices] ); - ++vec($bitmask, $_, 8) and last for 0 .. $bytes; - redo if @indices != @_; - } +sub powerset { + @_ ? map { $_, [$_[0], @$_] } powerset(@_[1..$#_]) : []; } - -print "powerset of empty set:\n"; -powerset { print "[@_]\n" }; -print "powerset of set {1,2,3,4}:\n"; -powerset { print "[@_]\n" } 1..4; -my $i = 0; -powerset { ++$i } 1..9; -print "The powerset of a nine element set contains $i elements.\n"; diff --git a/Task/Power-set/Perl/power-set-8.pl b/Task/Power-set/Perl/power-set-8.pl new file mode 100644 index 0000000000..f9cea5d06c --- /dev/null +++ b/Task/Power-set/Perl/power-set-8.pl @@ -0,0 +1,5 @@ +use List::Util qw(reduce); + +sub powerset { + @{( reduce { [@$a, map([@$_, $b], @$a)] } [[]], @_ )} +} diff --git a/Task/Power-set/Perl/power-set-9.pl b/Task/Power-set/Perl/power-set-9.pl new file mode 100644 index 0000000000..3d2864f0fb --- /dev/null +++ b/Task/Power-set/Perl/power-set-9.pl @@ -0,0 +1,8 @@ +my @set = (1, 2, 3); +my @powerset = powerset(@set); + +sub set_to_string { + "{" . join(", ", map { ref $_ ? set_to_string(@$_) : $_ } @_) . "}" +} + +print set_to_string(@powerset), "\n"; diff --git a/Task/Power-set/PowerShell/power-set.psh b/Task/Power-set/PowerShell/power-set.psh new file mode 100644 index 0000000000..e5b0eda86a --- /dev/null +++ b/Task/Power-set/PowerShell/power-set.psh @@ -0,0 +1,34 @@ +function power-set ($array) { + if($array) { + $n = $array.Count + function state($set, $i){ + if($i -gt -1) { + state $set ($i-1) + state ($set+@($array[$i])) ($i-1) + } else { + "$($set | sort)" + } + } + $set = state @() ($n-1) + $power = 0..($set.Count-1) | foreach{@(0)} + $i = 0 + $set | sort | foreach{$power[$i++] = $_.Split()} + $power | sort {$_.Count} + } else {@()} + +} +$OFS = " " +$setA = power-set @(1,2,3,4) +"number of sets in setA: $($setA.Count)" +"sets in setA:" +$OFS = ", " +$setA | foreach{"{"+"$_"+"}"} +$setB = @() +"number of sets in setB: $($setB.Count)" +"sets in setB:" +$setB | foreach{"{"+"$_"+"}"} +$setC = @(@(), @(@())) +"number of sets in setC: $($setC.Count)" +"sets in setC:" +$setC | foreach{"{"+"$_"+"}"} +$OFS = " " diff --git a/Task/Power-set/REXX/power-set.rexx b/Task/Power-set/REXX/power-set.rexx index 5b4f33cccf..8635fb47c7 100644 --- a/Task/Power-set/REXX/power-set.rexx +++ b/Task/Power-set/REXX/power-set.rexx @@ -1,29 +1,30 @@ -/*REXX program to display a power set, items may be anything (no blanks)*/ -parse arg S /*let user specify the set. */ -if S='' then S='one two three four' /*None specified? Use default*/ -N=words(S) /*number of items in the list.*/ -ps='{}' /*start with a null power set.*/ - do chunk=1 for N /*traipse through the items. */ - ps=ps combN(N,chunk) /*N items, a CHUNK at a time. */ +/*REXX pgm displays a power set, items may be anything (but can't have blanks)*/ +parse arg S /*allow the user specify optional set. */ +if S='' then S='one two three four' /*None specified? Then use the default*/ +N=words(S) /*the number of items in the list (set)*/ +@='{}' /*start process with a null power set. */ + do chunk=1 for N /*traipse through the items in the set.*/ + @=@ combN(N,chunk) /*take N items, a CHUNK at a time. */ end /*chunk*/ -w=words(ps) - do k=1 for w /*show combinations, one/line.*/ - say right(k,length(w)) word(ps,k) +w=length(2**N) /*the number of items in the power set.*/ + do k=1 for words(@) /* [↓] show combinations, one per line*/ + say right(k,w) word(@,k) /*display a single combination to term.*/ end /*k*/ -exit /*stick a fork in it, we done.*/ -/*─────────────────────────────────────$COMBN subroutine────────────────*/ -combN: procedure expose $ S; parse arg x,y; $= -!.=0; base=x+1; bbase=base-y; ym=y-1; do p=1 for y; !.p=p; end - do j=1; L= - do d=1 for y; _=!.d; L=L','word(S,_); end - $=$ '{'strip(L,'L',",")'}' - !.y=!.y+1; if !.y==base then if .combU(ym) then leave +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +combN: procedure expose S; parse arg x,y; base=x+1; bbase=base-y; !.=0 + do p=1 for y; !.p=p; end /*p*/ +$= + do j=1; L= + do d=1 for y; L=L','word(S,!.d) + end /*d*/ + $=$ '{'strip(L,'L',",")'}' + !.y=!.y+1; if !.y==base then if .combU(y-1) then leave end /*j*/ -return strip($) /*return with partial powerset*/ - -.combU: procedure expose !. y bbase; parse arg d; if d==0 then return 1 -p=!.d; do u=d to y; !.u=p+1 - if !.u==bbase+u then return .combU(u-1) - p=!.u - end /*u*/ +return strip($) /*return with a partial powerset chunk.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +.combU: procedure expose !. y bbase; parse arg d; if d==0 then return 1; p=!.d + do u=d to y; !.u=p+1; if !.u==bbase+u then return .combU(u-1) + p=!.u + end /*u*/ return 0 diff --git a/Task/Power-set/Ruby/power-set.rb b/Task/Power-set/Ruby/power-set.rb index 9276428bb6..63d12db81a 100644 --- a/Task/Power-set/Ruby/power-set.rb +++ b/Task/Power-set/Ruby/power-set.rb @@ -1,6 +1,6 @@ # Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/ # See the link if you want a shorter version. -This was intended to show the reader how the method works. +# This was intended to show the reader how the method works. class Array # Adds a power_set method to every array, i.e.: [1, 2].power_set def power_set diff --git a/Task/Power-set/TXR/power-set-1.txr b/Task/Power-set/TXR/power-set-1.txr index 57386f68b9..869aff51ed 100644 --- a/Task/Power-set/TXR/power-set-1.txr +++ b/Task/Power-set/TXR/power-set-1.txr @@ -1,4 +1,2 @@ (defun power-set (s) - (reduce-right - (op append (mapcar (op cons @@1) @2) @2) - s '(()))) + (mappend* (op comb s) (range 0 (length s)))) diff --git a/Task/Power-set/TXR/power-set-2.txr b/Task/Power-set/TXR/power-set-2.txr index 87d792ae10..62a99a7f35 100644 --- a/Task/Power-set/TXR/power-set-2.txr +++ b/Task/Power-set/TXR/power-set-2.txr @@ -1,7 +1,5 @@ @(do (defun power-set (s) - (reduce-right - (op append (mapcar (op cons @@1) @2) @2) - s '(())))) + (mappend* (op comb s) (range 0 (length s))))) @(bind pset @(power-set *args*)) @(output) @ (repeat) diff --git a/Task/Power-set/TXR/power-set-3.txr b/Task/Power-set/TXR/power-set-3.txr index 656f0a00e1..a9c85d5880 100644 --- a/Task/Power-set/TXR/power-set-3.txr +++ b/Task/Power-set/TXR/power-set-3.txr @@ -1,7 +1,6 @@ @(do (defun power-set (s) - (reduce-right - (op append (mapcar (op cons @@1) @2) @2) - s '(()))) + (mappend* (op comb s) (range 0 (length s)))) (prinl (power-set "abc")) + (prinl (power-set "b")) (prinl (power-set "")) (prinl (power-set #(1 2 3)))) diff --git a/Task/Power-set/VBScript/power-set.vb b/Task/Power-set/VBScript/power-set.vb new file mode 100644 index 0000000000..dde661a4be --- /dev/null +++ b/Task/Power-set/VBScript/power-set.vb @@ -0,0 +1,33 @@ +Function Dec2Bin(n) + q = n + Dec2Bin = "" + Do Until q = 0 + Dec2Bin = CStr(q Mod 2) & Dec2Bin + q = Int(q / 2) + Loop + Dec2Bin = Right("00000" & Dec2Bin,6) +End Function + +Function PowerSet(s) + arrS = Split(s,",") + PowerSet = "{" + For i = 0 To 2^(UBound(arrS)+1)-1 + If i = 0 Then + PowerSet = PowerSet & "{}," + Else + binS = Dec2Bin(i) + PowerSet = PowerSet & "{" + c = 0 + For j = Len(binS) To 1 Step -1 + If CInt(Mid(binS,j,1)) = 1 Then + PowerSet = PowerSet & arrS(c) & "," + End If + c = c + 1 + Next + PowerSet = Mid(PowerSet,1,Len(PowerSet)-1) & "}," + End If + Next + PowerSet = Mid(PowerSet,1,Len(PowerSet)-1) & "}" +End Function + +WScript.StdOut.Write PowerSet("1,2,3,4") diff --git a/Task/Price-fraction/Eiffel/price-fraction-1.e b/Task/Price-fraction/Eiffel/price-fraction-1.e new file mode 100644 index 0000000000..d9900c9844 --- /dev/null +++ b/Task/Price-fraction/Eiffel/price-fraction-1.e @@ -0,0 +1,31 @@ +class + APPLICATION + +create + make + +feature + + make + --Tests the price_adjusted feature. + local + i: REAL + do + create price_fraction.initialize + from + i := 5 + until + i = 100 + loop + io.put_string ("Given: ") + io.put_real (i / 100) + io.put_string ("%TAdjusted:") + io.put_real (price_fraction.adjusted_price (i / 100)) + io.new_line + i := i + 5 + end + end + + price_fraction: PRICE_FRACTION + +end diff --git a/Task/Price-fraction/Eiffel/price-fraction-2.e b/Task/Price-fraction/Eiffel/price-fraction-2.e new file mode 100644 index 0000000000..980c71a491 --- /dev/null +++ b/Task/Price-fraction/Eiffel/price-fraction-2.e @@ -0,0 +1,41 @@ +class + PRICE_FRACTION + +create + initialize + +feature + + initialize + -- Initializes limit and price to the given values. + do + limit := <<0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01>> + price := <<0.10, 0.18, 0.26, 0.32, 0.38, 0.44, 0.50, 0.54, 0.58, 0.62, 0.66, 0.70, 0.74, 0.78, 0.81, 0.86, 0.90, 0.94, 0.98, 1.00>> + end + + adjusted_price (n: REAL): REAL + -- Adjusted price according to the given price values. + local + i: INTEGER + found: BOOLEAN + do + from + i := 1 + until + i > limit.count or found + loop + if n <= limit [i] then + Result := (price [i]) + found := True + end + i := i + 1 + end + end + +feature {NONE} + + limit: ARRAY [REAL] + + price: ARRAY [REAL] + +end diff --git a/Task/Price-fraction/Elixir/price-fraction.elixir b/Task/Price-fraction/Elixir/price-fraction.elixir new file mode 100644 index 0000000000..18ef71970f --- /dev/null +++ b/Task/Price-fraction/Elixir/price-fraction.elixir @@ -0,0 +1,16 @@ +defmodule Price do + @table [ {0.06, 0.10}, {0.11, 0.18}, {0.16, 0.26}, {0.21, 0.32}, {0.26, 0.38}, + {0.31, 0.44}, {0.36, 0.50}, {0.41, 0.54}, {0.46, 0.58}, {0.51, 0.62}, + {0.56, 0.66}, {0.61, 0.70}, {0.66, 0.74}, {0.71, 0.78}, {0.76, 0.82}, + {0.81, 0.86}, {0.86, 0.90}, {0.91, 0.94}, {0.96, 0.98}, {1.01, 1.00} ] + + def fraction(value) when value in 0..1 do + {_, standard_value} = Enum.find(@table, fn {upper_limit, _} -> value < upper_limit end) + standard_value + end +end + +val = for i <- 0..100, do: i/100 +Enum.each(val, fn x -> + :io.format "~5.2f ->~5.2f~n", [x, Price.fraction(x)] +end) diff --git a/Task/Price-fraction/Julia/price-fraction.julia b/Task/Price-fraction/Julia/price-fraction.julia new file mode 100644 index 0000000000..42a01ca865 --- /dev/null +++ b/Task/Price-fraction/Julia/price-fraction.julia @@ -0,0 +1,15 @@ +const PFCUT = [6:5:101]//100 +const PFVAL = [10:8:26, 32:6:50, 54:4:98, 100]//100 + +function pricefraction{T<:FloatingPoint}(a::T) + zero(T) <= a || error("a = ", a, ", but it must be >= 0.") + a <= one(T) || error("a = ", a, ", but it must be <= 1.") + convert(T, PFVAL[findfirst(a .< PFCUT)]) +end + +test = [0.:0.05:1., 0.51, 0.56, 0.61, rand(), rand(), rand(), rand()] + +println("Testing the price fraction function") +for t in test + println(@sprintf " %.4f -> %.4f" t pricefraction(t)) +end diff --git a/Task/Price-fraction/Rust/price-fraction.rust b/Task/Price-fraction/Rust/price-fraction.rust index 42af7ff761..5c9e898e89 100644 --- a/Task/Price-fraction/Rust/price-fraction.rust +++ b/Task/Price-fraction/Rust/price-fraction.rust @@ -1,36 +1,48 @@ -fn fix_price(n: f64) -> f64 { - let ranges: Vec<(f64, f64, f64)> = vec![ - (0.00, 0.06, 0.10), - (0.06, 0.11, 0.18), - (0.11, 0.16, 0.26), - (0.16, 0.21, 0.32), - (0.21, 0.26, 0.38), - (0.26, 0.31, 0.44), - (0.31, 0.36, 0.50), - (0.36, 0.41, 0.54), - (0.41, 0.46, 0.58), - (0.46, 0.51, 0.62), - (0.51, 0.56, 0.66), - (0.56, 0.61, 0.70), - (0.61, 0.66, 0.74), - (0.66, 0.71, 0.78), - (0.71, 0.76, 0.82), - (0.76, 0.81, 0.86), - (0.81, 0.86, 0.90), - (0.86, 0.91, 0.94), - (0.91, 0.96, 0.98), - (0.96, 1.01, 1.00) - ]; - for &(b, e, a) in ranges.iter() { - if n >= b && n < e { return a; } +fn fix_price(num: f64) -> f64 { + match num { + 0.96...1.00 => 1.00, + 0.91...0.96 => 0.98, + 0.86...0.91 => 0.94, + 0.81...0.86 => 0.90, + 0.76...0.81 => 0.86, + 0.71...0.76 => 0.82, + 0.66...0.71 => 0.78, + 0.61...0.66 => 0.74, + 0.56...0.61 => 0.70, + 0.51...0.56 => 0.66, + 0.46...0.51 => 0.62, + 0.41...0.46 => 0.58, + 0.36...0.41 => 0.54, + 0.31...0.36 => 0.50, + 0.26...0.31 => 0.44, + 0.21...0.26 => 0.38, + 0.16...0.21 => 0.32, + 0.11...0.16 => 0.26, + 0.06...0.11 => 0.18, + 0.00...0.06 => 0.10, + // panics on invalid value + _ => unreachable!(), } - 1.00 } fn main() { let mut n: f64 = 0.04; - while n <= 1.01 { - println!("{} => {}", n, fix_price(n)); - n += 0.05; + while n <= 1.00 { + println!("{:.2} => {}", n, fix_price(n)); + n += 0.04; + } +} + +// and a unit test to check that we haven't forgotten a branch, use 'cargo test' to execute test. +// +// typically this could be included in the match as those check for exhaustiveness already +// by explicitly listing all remaining ranges / values instead of a catch-all underscore (_) +// but f64::NaN, f64::INFINITY and f64::NEG_INFINITY can't be matched like this +#[test] +fn exhaustiveness_check() { + let mut input_price = 0.; + while input_price <= 1. { + fix_price(input_price); + input_price += 0.01; } } diff --git a/Task/Price-fraction/VBScript/price-fraction.vb b/Task/Price-fraction/VBScript/price-fraction.vb new file mode 100644 index 0000000000..bdbb748036 --- /dev/null +++ b/Task/Price-fraction/VBScript/price-fraction.vb @@ -0,0 +1,48 @@ +Function pf(p) + If p < 0.06 Then + pf = 0.10 + ElseIf p < 0.11 Then + pf = 0.18 + ElseIf p < 0.16 Then + pf = 0.26 + ElseIf p < 0.21 Then + pf = 0.32 + ElseIf p < 0.26 Then + pf = 0.38 + ElseIf p < 0.31 Then + pf = 0.44 + ElseIf p < 0.36 Then + pf = 0.50 + ElseIf p < 0.41 Then + pf = 0.54 + ElseIf p < 0.46 Then + pf = 0.58 + ElseIf p < 0.51 Then + pf = 0.62 + ElseIf p < 0.56 Then + pf = 0.66 + ElseIf p < 0.61 Then + pf = 0.70 + ElseIf p < 0.66 Then + pf = 0.74 + ElseIf p < 0.71 Then + pf = 0.78 + ElseIf p < 0.76 Then + pf = 0.82 + ElseIf p < 0.81 Then + pf = 0.86 + ElseIf p < 0.86 Then + pf = 0.90 + ElseIf p < 0.91 Then + pf = 0.94 + ElseIf p < 0.96 Then + pf = 0.98 + Else + pf = 1.00 + End If +End Function + +WScript.Echo pf(0.7388727) +WScript.Echo pf(0.8593103) +WScript.Echo pf(0.826687) +WScript.Echo pf(0.3444635) diff --git a/Task/Primality-by-trial-division/Eiffel/primality-by-trial-division.e b/Task/Primality-by-trial-division/Eiffel/primality-by-trial-division.e new file mode 100644 index 0000000000..c4f338fb47 --- /dev/null +++ b/Task/Primality-by-trial-division/Eiffel/primality-by-trial-division.e @@ -0,0 +1,56 @@ +class + APPLICATION + +create + make + +feature + + make + -- Tests the feature is_prime. + do + io.put_boolean (is_prime (1)) + io.new_line + io.put_boolean (is_prime (2)) + io.new_line + io.put_boolean (is_prime (3)) + io.new_line + io.put_boolean (is_prime (4)) + io.new_line + io.put_boolean (is_prime (97)) + io.new_line + io.put_boolean (is_prime (15589)) + io.new_line + end + + is_prime (n: INTEGER): BOOLEAN + -- Is 'n' a prime number? + require + positiv_input: n > 0 + local + i: INTEGER + max: REAL_64 + math: DOUBLE_MATH + do + create math + if n = 2 then + Result := True + elseif n <= 1 or n \\ 2 = 0 then + Result := False + else + Result := True + max := math.sqrt (n) + from + i := 3 + until + i > max + loop + if n \\ i = 0 then + Result := False + end + i := i + 2 + end + end + end + +end diff --git a/Task/Primality-by-trial-division/Elixir/primality-by-trial-division.elixir b/Task/Primality-by-trial-division/Elixir/primality-by-trial-division.elixir new file mode 100644 index 0000000000..da0677b8de --- /dev/null +++ b/Task/Primality-by-trial-division/Elixir/primality-by-trial-division.elixir @@ -0,0 +1,11 @@ +defmodule RC do + def is_prime(2), do: true + def is_prime(n) when n<2 or rem(n,2)==0, do: false + def is_prime(n), do: is_prime(n,3) + + def is_prime(n,k) when n N 1) (bit? 1 N) - (for (D 3 T (+ D 2)) - (T (> D (sqrt N)) T) - (T (=0 (% N D)) NIL) ) ) ) ) + (let S (sqrt N) + (for (D 3 T (+ D 2)) + (T (> D S) T) + (T (=0 (% N D)) NIL) ) ) ) ) ) diff --git a/Task/Primality-by-trial-division/PowerShell/primality-by-trial-division.psh b/Task/Primality-by-trial-division/PowerShell/primality-by-trial-division.psh index 26adcd03d5..9ed6dd5a61 100644 --- a/Task/Primality-by-trial-division/PowerShell/primality-by-trial-division.psh +++ b/Task/Primality-by-trial-division/PowerShell/primality-by-trial-division.psh @@ -1,7 +1,10 @@ function isPrime ($n) { - if ($n -eq 1) { - return $false - } else { - return (@(2..[Math]::Sqrt($n) | Where-Object { $n % $_ -eq 0 }).Length -eq 0) + if ($n -eq 1) {$false} + elseif ($n -eq 2) {$true} + elseif ($n -eq 3) {$true} + else{ + $m = [Math]::Floor([Math]::Sqrt($n)) + (@(2..$m | where {($_ -lt $n) -and ($n % $_ -eq 0) }).Count -eq 0) } } +1..15 | foreach{"isPrime $_ : $(isPrime $_)"} diff --git a/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-1.rb b/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-1.rb index 36d39a158f..6ee6e219da 100644 --- a/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-1.rb +++ b/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-1.rb @@ -4,8 +4,8 @@ def prime(a) elsif a <= 1 || a % 2 == 0 false else - divisors = Enumerable::Enumerator.new(3..Math.sqrt(a), :step, 2) - # this also creates an enumerable object: divisors = (3..Math.sqrt(a)).step(2) - !divisors.any? { |d| a % d == 0 } + divisors = (3..Math.sqrt(a)).step(2) + divisors.none? { |d| a % d == 0 } end end +p (1..50).select{|i| prime(i)} diff --git a/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-2.rb b/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-2.rb index 21a87fed84..1b5712863f 100644 --- a/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-2.rb +++ b/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-2.rb @@ -1,8 +1,10 @@ - def prime?(value, generator = Prime::Generator23.new) - return false if value < 2 - for num in generator - q,r = value.divmod num - return true if q < num - return false if r == 0 - end +require "prime" +def prime?(value, generator = Prime::Generator23.new) + return false if value < 2 + for num in generator + q,r = value.divmod num + return true if q < num + return false if r == 0 end +end +p (1..50).select{|i| prime?(i)} diff --git a/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-3.rb b/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-3.rb index 59ad3451d2..114bc9b5db 100644 --- a/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-3.rb +++ b/Task/Primality-by-trial-division/Ruby/primality-by-trial-division-3.rb @@ -1,10 +1,11 @@ def primes(limit) (enclose = lambda { |primes| primes.last.succ.upto(limit) do |trial_pri| - if primes.find { |pri| (trial_pri % pri).zero? }.nil? + if primes.none? { |pri| (trial_pri % pri).zero? } return enclose.call(primes << trial_pri) end end primes }).call([2]) end +p primes(50) diff --git a/Task/Primality-by-trial-division/Rust/primality-by-trial-division.rust b/Task/Primality-by-trial-division/Rust/primality-by-trial-division.rust index e2496cc94a..0b6c61b65b 100644 --- a/Task/Primality-by-trial-division/Rust/primality-by-trial-division.rust +++ b/Task/Primality-by-trial-division/Rust/primality-by-trial-division.rust @@ -1,14 +1,12 @@ fn is_prime(n: u64) -> bool { if n == 2 { return true; } - if n % 2 == 0 || n < 3 { return false; } - for i in range(3u64, ((n as f64).sqrt() as u64) + 1) { - if n % i == 0 { return false; } - } - true + if n < 3 { return false; } + let sqrt_limit = (n as f64).sqrt() as u64; + (3..sqrt_limit+1).step_by(2).find(|i| n % i == 0).is_none() } fn main() { - for i in range(1u64, 30u64) { + for i in 1..30 { if is_prime(i) { println!("{} is prime!", i); } diff --git a/Task/Primality-by-trial-division/VBScript/primality-by-trial-division.vb b/Task/Primality-by-trial-division/VBScript/primality-by-trial-division.vb new file mode 100644 index 0000000000..b29557baae --- /dev/null +++ b/Task/Primality-by-trial-division/VBScript/primality-by-trial-division.vb @@ -0,0 +1,21 @@ +Function IsPrime(n) + If n = 2 Then + IsPrime = True + ElseIf n <= 1 Or n Mod 2 = 0 Then + IsPrime = False + Else + IsPrime = True + For i = 3 To Int(Sqr(n)) Step 2 + If n Mod i = 0 Then + IsPrime = False + Exit For + End If + Next + End If +End Function + +For n = 1 To 50 + If IsPrime(n) Then + WScript.StdOut.Write n & " " + End If +Next diff --git a/Task/Prime-decomposition/00DESCRIPTION b/Task/Prime-decomposition/00DESCRIPTION index 5c796a1614..9ce1a9b86a 100644 --- a/Task/Prime-decomposition/00DESCRIPTION +++ b/Task/Prime-decomposition/00DESCRIPTION @@ -4,11 +4,14 @@ which when all multiplied together, are equal to that number. Example: 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} -Write a function which returns an [[array]] or [[Collections|collection]] which contains the prime decomposition of a given number, n, greater than 1. +Write a function which returns an [[Arrays|array]] or [[Collections|collection]] which contains the prime decomposition of a given number, n, greater than 1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). -If you would like to test code from this task, you may use code from [[Primality by Trial Division|trial division]] or the [[Sieve of Eratosthenes]]. +If you would like to test code from this task, you may use code from [[Primality by trial division|trial division]] or the [[Sieve of Eratosthenes]]. Note: The program must not be limited by the word size of your computer or some other artificial limit; it should work for any number regardless of size (ignoring the physical limits of RAM etc). + +See also: +* [[Factors of an integer]] diff --git a/Task/Prime-decomposition/360-Assembly/prime-decomposition.360 b/Task/Prime-decomposition/360-Assembly/prime-decomposition.360 new file mode 100644 index 0000000000..954e3a1366 --- /dev/null +++ b/Task/Prime-decomposition/360-Assembly/prime-decomposition.360 @@ -0,0 +1,76 @@ +PRIMEDE CSECT + USING PRIMEDE,R13 + B 80(R15) skip savearea + DC 17F'0' savearea + DC CL8'PRIMEDE' + STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 end prolog + LA R2,0 + LA R3,1023 + LA R4,1024 + MR R2,R4 + ST R3,N n=1023*1024 + LA R5,WBUFFER + LA R6,0 + L R1,N n + XDECO R1,0(R5) + LA R5,12(R5) + MVC 0(3,R5),=C' : ' + LA R5,3(R5) + LA R0,2 + ST R0,I i=2 +WHILE1 EQU * do while(i<=n/2) + L R2,N + SRA R2,1 + L R4,I + CR R4,R2 i<=n/2 + BH EWHILE1 +WHILE2 EQU * do while(n//i=0) + L R3,N + LA R2,0 + D R2,I + LTR R2,R2 n//i=0 + BNZ EWHILE2 + ST R3,N n=n/i + ST R3,M m=n + L R1,I i + XDECO R1,WDECO + MVC 0(5,R5),WDECO+7 + LA R5,5(R5) + MVI OK,X'01' ok + B WHILE2 +EWHILE2 EQU * + L R4,I + CH R4,=H'2' if i=2 then + BNE NE2 + LA R0,3 + ST R0,I i=3 + B EIFNE2 +NE2 L R2,I else + LA R2,2(R2) + ST R2,I i=i+2 +EIFNE2 B WHILE1 +EWHILE1 EQU * + CLI OK,X'01' if ^ok then + BE NOTPRIME + MVC 0(7,R5),=C'[prime]' + LA R5,7(R5) + B EPRIME +NOTPRIME L R1,M m + XDECO R1,WDECO + MVC 0(5,R5),WDECO+7 +EPRIME XPRNT WBUFFER,80 put + L R13,4(0,R13) epilog + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +N DS F +I DS F +M DS F +OK DC X'00' +WBUFFER DC CL80' ' +WDECO DS CL16 + YREGS + END PRIMEDE diff --git a/Task/Prime-decomposition/Eiffel/prime-decomposition.e b/Task/Prime-decomposition/Eiffel/prime-decomposition.e index d523b57238..aac35fcff7 100644 --- a/Task/Prime-decomposition/Eiffel/prime-decomposition.e +++ b/Task/Prime-decomposition/Eiffel/prime-decomposition.e @@ -1,37 +1,39 @@ class PRIME_DECOMPOSITION + feature - factor(p: INTEGER): ARRAY[INTEGER] - require - p_positive: p>0 - local - div,i: INTEGER - next:INTEGER - rest: INTEGER - d: ARRAY[INTEGER] - do - create d.make_empty - if p= 1 then - d.force (1, 1) - Result:= d - end - div:= 2 - next:= 3 - rest:=p - from - i:=1 - until rest=1 - loop + + factor (p: INTEGER): ARRAY [INTEGER] + -- Prime decomposition of 'p'. + require + p_positive: p > 0 + local + div, i, next, rest: INTEGER + do + create Result.make_empty + if p = 1 then + Result.force (1, 1) + end + div := 2 + next := 3 + rest := p from - until rest\\div/=0 + i := 1 + until + rest = 1 loop - d.force( div, i) - rest := (rest/div).floor - i:= i+1 + from + until + rest \\ div /= 0 + loop + Result.force (div, i) + rest := (rest / div).floor + i := i + 1 + end + div := next + next := next + 2 end - div := next - next:= next+2 + ensure + is_divisor: across Result as r all p \\ r.item = 0 end + is_prime: across Result as r all prime (r.item) end end - Result:= d - end -end diff --git a/Task/Prime-decomposition/Elixir/prime-decomposition.elixir b/Task/Prime-decomposition/Elixir/prime-decomposition.elixir new file mode 100644 index 0000000000..5d1de881c5 --- /dev/null +++ b/Task/Prime-decomposition/Elixir/prime-decomposition.elixir @@ -0,0 +1,15 @@ +defmodule Prime do + def decomposition(n), do: decomposition(n, 2, []) + + defp decomposition(n, k, acc) when n < k*k, do: Enum.reverse(acc, [n]) + defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc]) + defp decomposition(n, k, acc), do: decomposition(n, k+1, acc) +end + +prime = Stream.iterate(2, &(&1+1)) |> + Stream.filter(fn n-> length(Prime.decomposition(n)) == 1 end) |> + Enum.take(17) +mersenne = Enum.map(prime, fn n -> {n, round(:math.pow(2,n)) - 1} end) +Enum.each(mersenne, fn {n,m} -> + :io.format "~3s :~20w = ~s~n", ["M#{n}", m, Prime.decomposition(m) |> Enum.join(" x ")] +end) diff --git a/Task/Prime-decomposition/PowerShell/prime-decomposition.psh b/Task/Prime-decomposition/PowerShell/prime-decomposition.psh new file mode 100644 index 0000000000..73f27afabd --- /dev/null +++ b/Task/Prime-decomposition/PowerShell/prime-decomposition.psh @@ -0,0 +1,32 @@ +function eratosthenes ($n) { + if($n -gt 1){ + $prime = @(1..($n+1) | foreach{$true}) + $prime[1] = $false + $m = [Math]::Floor([Math]::Sqrt($n)) + function multiple($i) { + for($j = $i*$i; $j -le $n; $j += $i) { + $prime[$j] = $false + } + } + multiple 2 + for($i = 3; $i -le $m; $i += 2) { + if($prime[$i]) {multiple $i} + } + 1..$n | where{$prime[$_]} + } else { + Write-Error "$n is not greater than 1" + } +} +function prime-decomposition ($n) { + $array = eratosthenes $n + $prime = @() + foreach($p in $array) { + while($n%$p -eq 0) { + $n /= $p + $prime += @($p) + } + } + $prime +} +"$(prime-decomposition 12)" +"$(prime-decomposition 100)" diff --git a/Task/Prime-decomposition/REXX/prime-decomposition.rexx b/Task/Prime-decomposition/REXX/prime-decomposition.rexx index f295d6cc0d..cc1a6b2481 100644 --- a/Task/Prime-decomposition/REXX/prime-decomposition.rexx +++ b/Task/Prime-decomposition/REXX/prime-decomposition.rexx @@ -1,48 +1,43 @@ -/*REXX pgm finds the prime factors of a (or some) positive integer(s).*/ -numeric digits 1000 /*handle 1,000 digits for powers.*/ -parse arg bot top step base add /*get optional arguments from CL.*/ -if bot=='' then do;bot=1;top=100;end /*no BOT? Then use the default.*/ -if top=='' then top=bot /* " TOP? " " " " */ -if step=='' then step=1 /* " STEP? " " " " */ -if add =='' then add=-1 /* " ADD? " " " " */ -w=length(top) /*get max width (pretty display).*/ -if base\=='' then w=length(base**top) /*will we be testing powers?. */ -@.=left('',7); @.0='{unity}'; @.1='[prime]' /*literals: (¬)prime*/ -numeric digits max(9,w+1) /*maybe increase the precision. */ -p=0 /*P is the number of primes found*/ - do n=bot to top by step /*process single number or range.*/ - ?=n; if base\=='' then ?=base**n+add /*do a "Mercenne" test?*/ - f=factr(?); #=words(f) /*get prime factors; # of factors*/ - if #==1 then p=p+1 /*N is prime? Bump prime counter*/ - say right(?,w) right('('#")",9) 'prime factors: ' @.# f +/*REXX program performs prime decomposition for a range of positive integer(s)*/ +numeric digits 1000 /*handle thousand digits for the powers*/ +parse arg bot top step base add /*get optional arguments from the C.L. */ +if bot=='' then do;bot=1;top=100;end /*no BOT given? Then use the default.*/ +if top=='' then top=bot /* " TOP? " " " " " */ +if step=='' then step=1 /* " STEP? " " " " " */ +if add =='' then add=-1 /* " ADD? " " " " " */ +w=length(top) /*get maximum width for aligned display*/ +if base\=='' then w=length(base**top) /*will be testing powers of two later? */ +@.=left('',7); @.0='{unity}'; @.1='[prime]' /*literals: prime (or not)*/ +numeric digits max(9,w+1) /*maybe increase the digits precision. */ +#=0 /*P: is the number of primes found. */ + do n=bot to top by step /*process a single number or a range.*/ + ?=n; if base\=='' then ?=base**n+add /*do a "Mercenne" test? */ + pf=factr(?); f=words(pf) /*get prime factors; number of factors.*/ + if f==1 then #=#+1 /*Is N prime? Then bump prime counter.*/ + say right(?,w) right('('f")",9) 'prime factors: ' @.f pf +iterate end /*n*/ -say /* [↓] if multiple numbers, show.*/ -if top-bot+1\==1 then say right(p,w+9+1) 'primes found.' /*show cnt.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FACTR subroutine────────────────────*/ -factr: procedure; parse arg x 1 z,list /*sets X&Z to arg1, LIST to null.*/ -if x==1 then return '' /*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 √ 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 √ 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*/ +say +ps='primes'; if p==1 then ps='prime' /*setup for proper English in sentence.*/ +say right(#,w+9+1) ps 'found.' /*display the number of primes found. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +factr: procedure; parse arg x 1 z 1 d,$ /*set X and Z to argument; $ to null*/ +if x==1 then return '' /*handle the special case of X equal 1.*/ + do while z//2==0; $=$ 2; z=z%2; end /*append all the 2 factors.*/ + do while z//3==0; $=$ 3; z=z%3; end /* " " " 3 " */ + do while z//5==0; $=$ 5; z=z%5; end /* " " " 5 " */ + do while z//7==0; $=$ 7; z=z%7; end /* " " " 7 " */ + /* ___ */ +q=1; do while q<=x; q=q*4; end /*these 2 lines compute √ X */ +r=0; do while q>1; q=q%4; _=d-r-q; r=r%2; if _>=0 then do; d=_;r=r+q;end; end + + do j=11 by 6 to r /*insure that J isn't divisible by 3.*/ + parse var j '' -1 _ /*obtain the last decimal digit of J. */ + if _\==5 then do while z//j==0; $=$ j; z=z%j; end /*maybe reduce*/ + if _ ==3 then iterate /*if next Y is divisible by 5, skip.*/ + y=j+2; do while z//y==0; $=$ y; z=z%y; end /*maybe reduce*/ + end /*j*/ + /* [↓] The $ list has a leading blank.*/ +if z==1 then return $ /*if residual=unity, then don't append.*/ + return $ z /*return $ with appended residual. */ diff --git a/Task/Prime-decomposition/TI-83-BASIC/prime-decomposition.ti-83 b/Task/Prime-decomposition/TI-83-BASIC/prime-decomposition.ti-83 new file mode 100644 index 0000000000..b5a590ac8f --- /dev/null +++ b/Task/Prime-decomposition/TI-83-BASIC/prime-decomposition.ti-83 @@ -0,0 +1,50 @@ +::prgmPREMIER +Disp "FACTEURS PREMIER" +Prompt N +If N<1:Stop +ClrList L1,L2 +0→K +iPart(√(N))→L +N→M +For(I,2,L) +0→J +While fPart(M/I)=0 +J+1→J +M/I→M +End +If J≠0 +Then +K+1→K +I→L1(K) +J→L2(K) +I→Z:prgmVSTR +" "+Str0→Str1 +If J≠1 +Then +J→Z:prgmVSTR +Str1+"^"+Str0→Str1 +End +Disp Str1 +End +If M=1:Stop +End +If M≠1 +Then +If M≠N +Then +M→Z:prgmVSTR +" "+Str0→Str1 +Disp Str1 +Else +Disp "PREMIER" +End +End +::prgmVSTR +{Z,Z}→L5 +{1,2}→L6 +LinReg(ax+b)L6,L5,Y€₀ +Equ►String(Y₀,Str0) +length(Str0)→O +sub(Str0,4,O-3)→Str0 +ClrList L5,L6 +DelVar Y€ diff --git a/Task/Prime-decomposition/VBScript/prime-decomposition.vb b/Task/Prime-decomposition/VBScript/prime-decomposition.vb new file mode 100644 index 0000000000..3a11ed9c6c --- /dev/null +++ b/Task/Prime-decomposition/VBScript/prime-decomposition.vb @@ -0,0 +1,43 @@ +Function PrimeFactors(n) + arrP = Split(ListPrimes(n)," ") + divnum = n + Do Until divnum = 1 + 'The -1 is to account for the null element of arrP + For i = 0 To UBound(arrP)-1 + If divnum = 1 Then + Exit For + ElseIf divnum Mod arrP(i) = 0 Then + divnum = divnum/arrP(i) + PrimeFactors = PrimeFactors & arrP(i) & " " + End If + Next + Loop +End Function + +Function IsPrime(n) + If n = 2 Then + IsPrime = True + ElseIf n <= 1 Or n Mod 2 = 0 Then + IsPrime = False + Else + IsPrime = True + For i = 3 To Int(Sqr(n)) Step 2 + If n Mod i = 0 Then + IsPrime = False + Exit For + End If + Next + End If +End Function + +Function ListPrimes(n) + ListPrimes = "" + For i = 1 To n + If IsPrime(i) Then + ListPrimes = ListPrimes & i & " " + End If + Next +End Function + +WScript.StdOut.Write PrimeFactors(CInt(WScript.Arguments(0))) +WScript.StdOut.WriteLine diff --git a/Task/Priority-queue/C-sharp/priority-queue.cs b/Task/Priority-queue/C-sharp/priority-queue-1.cs similarity index 100% rename from Task/Priority-queue/C-sharp/priority-queue.cs rename to Task/Priority-queue/C-sharp/priority-queue-1.cs diff --git a/Task/Priority-queue/C-sharp/priority-queue-2.cs b/Task/Priority-queue/C-sharp/priority-queue-2.cs new file mode 100644 index 0000000000..3add9e65e9 --- /dev/null +++ b/Task/Priority-queue/C-sharp/priority-queue-2.cs @@ -0,0 +1,121 @@ +namespace PriorityQ { + using KeyT = UInt32; + using System; + using System.Collections.Generic; + using System.Linq; + class Tuple { // for DotNet 3.5 without Tuple's + public K Item1; public V Item2; + public Tuple(K k, V v) { Item1 = k; Item2 = v; } + public override string ToString() { + return "(" + Item1.ToString() + ", " + Item2.ToString() + ")"; + } + } + class MinHeapPQ { + private struct HeapEntry { + public KeyT k; public V v; + public HeapEntry(KeyT k, V v) { this.k = k; this.v = v; } + } + private List pq; + private MinHeapPQ() { this.pq = new List(); } + private bool mt { get { return pq.Count == 0; } } + private int sz { + get { + var cnt = pq.Count; + return (cnt == 0) ? 0 : cnt - 1; + } + } + private Tuple pkmn { + get { + if (pq.Count == 0) return null; + else { + var mn = pq[0]; + return new Tuple(mn.k, mn.v); + } + } + } + private void psh(KeyT k, V v) { // add extra very high item if none + if (pq.Count == 0) pq.Add(new HeapEntry(UInt32.MaxValue, v)); + var i = pq.Count; pq.Add(pq[i - 1]); // copy bottom item... + for (var ni = i >> 1; ni > 0; i >>= 1, ni >>= 1) { + var t = pq[ni - 1]; + if (t.k > k) pq[i - 1] = t; else break; + } + pq[i - 1] = new HeapEntry(k, v); + } + private void siftdown(KeyT k, V v, int ndx) { + var cnt = pq.Count - 1; var i = ndx; + for (var ni = i + i + 1; ni < cnt; ni = ni + ni + 1) { + var oi = i; var lk = pq[ni].k; var rk = pq[ni + 1].k; + var nk = k; + if (k > lk) { i = ni; nk = lk; } + if (nk > rk) { ni += 1; i = ni; } + if (i != oi) pq[oi] = pq[i]; else break; + } + pq[i] = new HeapEntry(k, v); + } + private void rplcmin(KeyT k, V v) { + if (pq.Count > 1) siftdown(k, v, 0); + } + private void dltmin() { + var lsti = pq.Count - 2; + if (lsti <= 0) pq.Clear(); + else { + var lkv = pq[lsti]; + pq.RemoveAt(lsti); siftdown(lkv.k, lkv.v, 0); + } + } + private void reheap(int i) { + var lfti = i + i + 1; + if (lfti < sz) { + var rghti = lfti + 1; reheap(lfti); reheap(rghti); + var ckv = pq[i]; siftdown(ckv.k, ckv.v, i); + } + } + private void bld(IEnumerable> sq) { + var sqm = from e in sq + select new HeapEntry(e.Item1, e.Item2); + pq = sqm.ToList(); + var sz = pq.Count; + if (sz > 0) { + var lkv = pq[sz - 1]; + pq.Add(new HeapEntry(KeyT.MaxValue, lkv.v)); + reheap(0); + } + } + private IEnumerable> sq() { + return from e in pq + where e.k != KeyT.MaxValue + select new Tuple(e.k, e.v); } + private void adj(Func> f) { + var cnt = pq.Count - 1; + for (var i = 0; i < cnt; ++i) { + var e = pq[i]; + var r = f(e.k, e.v); + pq[i] = new HeapEntry(r.Item1, r.Item2); + } + reheap(0); + } + public static MinHeapPQ empty { get { return new MinHeapPQ(); } } + public static bool isEmpty(MinHeapPQ pq) { return pq.mt; } + public static int size(MinHeapPQ pq) { return pq.sz; } + public static Tuple peekMin(MinHeapPQ pq) { return pq.pkmn; } + public static MinHeapPQ push(KeyT k, V v, MinHeapPQ pq) { + pq.psh(k, v); return pq; } + public static MinHeapPQ replaceMin(KeyT k, V v, MinHeapPQ pq) { + pq.rplcmin(k, v); return pq; } + public static MinHeapPQ deleteMin(MinHeapPQ pq) { pq.dltmin(); return pq; } + public static MinHeapPQ merge(MinHeapPQ pq1, MinHeapPQ pq2) { + return fromSeq(pq1.sq().Concat(pq2.sq())); } + public static MinHeapPQ adjust(Func> f, MinHeapPQ pq) { + pq.adj(f); return pq; } + public static MinHeapPQ fromSeq(IEnumerable> sq) { + var pq = new MinHeapPQ(); pq.bld(sq); return pq; } + public static Tuple, MinHeapPQ> popMin(MinHeapPQ pq) { + var rslt = pq.pkmn; if (rslt == null) return null; + pq.dltmin(); return new Tuple, MinHeapPQ>(rslt, pq); } + public static IEnumerable> toSeq(MinHeapPQ pq) { + for (; !pq.mt; pq.dltmin()) yield return pq.pkmn; } + public static IEnumerable> sort(IEnumerable> sq) { + return toSeq(fromSeq(sq)); } + } +} diff --git a/Task/Priority-queue/C-sharp/priority-queue-3.cs b/Task/Priority-queue/C-sharp/priority-queue-3.cs new file mode 100644 index 0000000000..7b2472f7c0 --- /dev/null +++ b/Task/Priority-queue/C-sharp/priority-queue-3.cs @@ -0,0 +1,23 @@ + static void Main(string[] args) { + Tuple[] ins = { new Tuple(3u, "Clear drains"), + new Tuple(4u, "Feed cat"), + new Tuple(5u, "Make tea"), + new Tuple(1u, "Solve RC tasks"), + new Tuple(2u, "Tax return") }; + + var spq = ins.Aggregate(MinHeapPQ.empty, (pq, t) => MinHeapPQ.push(t.Item1, t.Item2, pq)); + foreach (var e in MinHeapPQ.toSeq(spq)) Console.WriteLine(e); Console.WriteLine(); + + foreach (var e in MinHeapPQ.sort(ins)) Console.WriteLine(e); Console.WriteLine(); + + var npq = MinHeapPQ.fromSeq(ins); + foreach (var e in MinHeapPQ.toSeq(MinHeapPQ.merge(npq, npq))) + Console.WriteLine(e); Console.WriteLine(); + + var npq = MinHeapPQ.fromSeq(ins); + foreach (var e in MinHeapPQ.toSeq(MinHeapPQ.merge(npq, npq))) + Console.WriteLine(e); + + foreach (var e in MinHeapPQ.toSeq(MinHeapPQ.adjust((k, v) => new Tuple(6u - k, v), npq))) + Console.WriteLine(e); Console.WriteLine(); + } diff --git a/Task/Priority-queue/Common-Lisp/priority-queue.lisp b/Task/Priority-queue/Common-Lisp/priority-queue.lisp new file mode 100644 index 0000000000..93671bedee --- /dev/null +++ b/Task/Priority-queue/Common-Lisp/priority-queue.lisp @@ -0,0 +1,32 @@ +;priority-queue's are implemented with association lists +(defun make-pq (alist) + (sort (copy-alist alist) (lambda (a b) (< (car a) (car b))))) +; +;Will change the state of pq +; +(define-modify-macro insert-pq (pair) + (lambda (pq pair) (sort-alist (cons pair pq)))) + +(define-modify-macro remove-pq-aux () cdr) + +(defmacro remove-pq (pq) + `(let ((aux (copy-alist ,pq))) + (REMOVE-PQ-AUX ,pq) + (car aux))) +; +;Will not change the state of pq +; +(defun insert-pq-non-destructive (pair pq) + (sort-alist (cons pair pq))) + +(defun remove-pq-non-destructive (pq) + (cdr pq)) +;testing +(defparameter a (make-pq '((1 . "Solve RC tasks") (3 . "Clear drains") (2 . "Tax return") (5 . "Make tea")))) +(format t "~a~&" a) +(insert-pq a '(4 . "Feed cat")) +(format t "~a~&" a) +(format t "~a~&" (remove-pq a)) +(format t "~a~&" a) +(format t "~a~&" (remove-pq a)) +(format t "~a~&" a) diff --git a/Task/Priority-queue/F-Sharp/priority-queue-1.fs b/Task/Priority-queue/F-Sharp/priority-queue-1.fs new file mode 100644 index 0000000000..5bf49bb898 --- /dev/null +++ b/Task/Priority-queue/F-Sharp/priority-queue-1.fs @@ -0,0 +1,103 @@ +[] +module PriorityQ = + +// type 'a treeElement = Element of uint32 * 'a + type 'a treeElement = struct val k:uint32 val v:'a new(k,v) = { k=k;v=v } end + + type 'a tree = Node of uint32 * 'a treeElement * 'a tree list + + type 'a heap = 'a tree list + + [] + [] + type 'a outerheap = | HeapEmpty | HeapNotEmpty of 'a treeElement * 'a heap + + let empty = HeapEmpty + + let isEmpty = function | HeapEmpty -> true | _ -> false + + let inline private rank (Node(r,_,_)) = r + + let inline private root (Node(_,x,_)) = x + + exception Empty_Heap + + let peekMin = function | HeapEmpty -> None + | HeapNotEmpty(min, _) -> Some (min.k, min.v) + + let rec private findMin heap = + match heap with | [] -> raise Empty_Heap //guarded so should never happen + | [node] -> root node,[] + | topnode::heap' -> + let min,subheap = findMin heap' in let rtn = root topnode + match subheap with + | [] -> if rtn.k > min.k then min,[] else rtn,[] + | minnode::heap'' -> + let rmn = root minnode + if rtn.k <= rmn.k then rtn,heap + else rmn,minnode::topnode::heap'' + + let private mergeTree (Node(r,kv1,ts1) as tree1) (Node (_,kv2,ts2) as tree2) = + if kv1.k > kv2.k then Node(r+1u,kv2,tree1::ts2) + else Node(r+1u,kv1,tree2::ts1) + + let rec private insTree (newnode: 'a tree) heap = + match heap with + | [] -> [newnode] + | topnode::heap' -> if (rank newnode) < (rank topnode) then newnode::heap + else insTree (mergeTree newnode topnode) heap' + + let push k v = let kv = treeElement(k,v) in let nn = Node(0u,kv,[]) + function | HeapEmpty -> HeapNotEmpty(kv,[nn]) + | HeapNotEmpty(min,heap) -> let nmin = if k > min.k then min else kv + HeapNotEmpty(nmin,insTree nn heap) + + let rec private merge' heap1 heap2 = //doesn't guaranty minimum tree node as head!!! + match heap1,heap2 with + | _,[] -> heap1 + | [],_ -> heap2 + | topheap1::heap1',topheap2::heap2' -> + match compare (rank topheap1) (rank topheap2) with + | -1 -> topheap1::merge' heap1' heap2 + | 1 -> topheap2::merge' heap1 heap2' + | _ -> insTree (mergeTree topheap1 topheap2) (merge' heap1' heap2') + + let merge oheap1 oheap2 = match oheap1,oheap2 with + | _,HeapEmpty -> oheap1 + | HeapEmpty,_ -> oheap2 + | HeapNotEmpty(min1,heap1),HeapNotEmpty(min2,heap2) -> + let min = if min1.k > min2.k then min2 else min1 + HeapNotEmpty(min,merge' heap1 heap2) + + let rec private removeMinTree = function + | [] -> raise Empty_Heap // will never happen as already guarded + | [node] -> node,[] + | t::ts -> let t',ts' = removeMinTree ts + if (root t).k <= (root t').k then t,ts else t',t::ts' + + let deleteMin = + function | HeapEmpty -> HeapEmpty + | HeapNotEmpty(_,heap) -> + match heap with + | [] -> HeapEmpty // should never occur: non empty heap with no elements + | [Node(_,_,heap')] -> match heap' with + | [] -> HeapEmpty + | _ -> let min,_ = findMin heap' + HeapNotEmpty(min,heap') + | _::_ -> let Node(_,_,ts1),ts2 = removeMinTree heap + let nheap = merge' (List.rev ts1) ts2 in let min,_ = findMin nheap + HeapNotEmpty(min,nheap) + + let replaceMin k v pq = push k v (deleteMin pq) + + let fromSeq sq = Seq.fold (fun pq (k, v) -> push k v pq) empty sq + + let popMin pq = match peekMin pq with + | None -> None + | Some(kv) -> Some(kv, deleteMin pq) + + let toSeq pq = Seq.unfold popMin pq + + let sort sq = sq |> fromSeq |> toSeq + + let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq diff --git a/Task/Priority-queue/F-Sharp/priority-queue-2.fs b/Task/Priority-queue/F-Sharp/priority-queue-2.fs new file mode 100644 index 0000000000..a12ee622e4 --- /dev/null +++ b/Task/Priority-queue/F-Sharp/priority-queue-2.fs @@ -0,0 +1,133 @@ +[] +module PriorityQ = + + type HeapEntry<'V> = struct val k:uint32 val v:'V new(k,v) = {k=k;v=v} end + [] + [] + type PQ<'V> = + | Mt + | Br of HeapEntry<'V> * PQ<'V> * PQ<'V> + + let empty = Mt + + let isEmpty = function | Mt -> true + | _ -> false + + // Return number of elements in the priority queue. + // /O(log(n)^2)/ + let rec size = function + | Mt -> 0 + | Br(_, ll, rr) -> + let n = size rr + // rest n p q, where n = size ll, and size ll - size rr = 0 or 1 + // returns 1 + size ll - size rr. + let rec rest n pl pr = + match pl with + | Mt -> 1 + | Br(_, pll, plr) -> + match pr with + | Mt -> 2 + | Br(_, prl, prr) -> + let nm1 = n - 1 in let d = nm1 >>> 1 + if (nm1 &&& 1) = 0 + then rest d pll prl // subtree sizes: (d or d+1), d; d, d + else rest d plr prr // subtree sizes: d+1, (d or d+1); d+1, d + 2 * n + rest n ll rr + + let peekMin = function | Br(kv, _, _) -> Some(kv.k, kv.v) + | _ -> None + + let rec push wk wv = + function | Mt -> Br(HeapEntry(wk, wv), Mt, Mt) + | Br(vkv, ll, rr) -> + if wk <= vkv.k then + Br(HeapEntry(wk, wv), push vkv.k vkv.v rr, ll) + else Br(vkv, push wk wv rr, ll) + + let inline private siftdown wk wv pql pqr = + let rec sift pl pr = + match pl with + | Mt -> Br(HeapEntry(wk, wv), Mt, Mt) + | Br(vkvl, pll, plr) -> + match pr with + | Mt -> if wk <= vkvl.k then Br(HeapEntry(wk, wv), pl, Mt) + else Br(vkvl, Br(HeapEntry(wk, wv), Mt, Mt), Mt) + | Br(vkvr, prl, prr) -> + if wk <= vkvl.k && wk <= vkvr.k then Br(HeapEntry(wk, wv), pl, pr) + elif vkvl.k <= vkvr.k then Br(vkvl, sift pll plr, pr) + else Br(vkvr, pl, sift prl prr) + sift pql pqr + + let replaceMin wk wv = function | Mt -> Mt + | Br(_, ll, rr) -> siftdown wk wv ll rr + + let deleteMin = function + | Mt -> Mt + | Br(_, ll, Mt) -> ll + | Br(vkv, ll, rr) -> + let rec leftrem = function | Mt -> vkv, Mt // should never happen + | Br(kvd, Mt, _) -> kvd, Mt + | Br(vkv, Br(kvd, _, _), Mt) -> + kvd, Br(vkv, Mt, Mt) + | Br(vkv, pl, pr) -> let kvd, pqd = leftrem pl + kvd, Br(vkv, pr, pqd) + let (kvd, pqd) = leftrem ll + siftdown kvd.k kvd.v rr pqd; + + let adjust f pq = + let rec adj = function + | Mt -> Mt + | Br(vkv, ll, rr) -> let nk, nv = f vkv.k vkv.v + siftdown nk nv (adj ll) (adj rr) + adj pq + + let fromSeq sq = + if Seq.isEmpty sq then Mt + else let nmrtr = sq.GetEnumerator() + let rec build lvl = if lvl = 0 || not (nmrtr.MoveNext()) then Mt + else let ck, cv = nmrtr.Current + let lft = lvl >>> 1 + let rght = (lvl - 1) >>> 1 + siftdown ck cv (build lft) (build rght) + build (sq |> Seq.length) + + let merge (pq1:PQ<_>) (pq2:PQ<_>) = // merges without using a sequence + match pq1 with + | Mt -> pq2 + | _ -> + match pq2 with + | Mt -> pq1 + | _ -> + let rec zipper lvl pq rest = + if lvl = 0 then Mt, pq, rest else + let lft = lvl >>> 1 in let rght = (lvl - 1) >>> 1 + match pq with + | Mt -> + match rest with + | [] | Mt :: _ -> Mt, pq, [] // Mt in list never happens + | Br(kv, ll, Mt) :: tl -> + let pl, pql, rstl = zipper lft ll tl + let pr, pqr, rstr = zipper rght pql rstl + siftdown kv.k kv.v pl pr, pqr, rstr + | Br(kv, ll, rr) :: tl -> + let pl, pql, rstl = zipper lft ll (rr :: tl) + let pr, pqr, rstr = zipper rght pql rstl + siftdown kv.k kv.v pl pr, pqr, rstr + | Br(kv, ll, Mt) -> + let pl, pql, rstl = zipper lft ll rest + let pr, pqr, rstr = zipper rght pql rstl + siftdown kv.k kv.v pl pr, pqr, rstr + | Br(kv, ll, rr) -> + let pl, pql, rstl = zipper lft ll (rr :: rest) + let pr, pqr, rstr = zipper rght pql rstl + siftdown kv.k kv.v pl pr, pqr, rstr + let sz = size pq1 + size pq2 + let pq, _, _ = zipper sz pq1 [pq2] in pq + + let popMin pq = match peekMin pq with + | None -> None + | Some(kv) -> Some(kv, deleteMin pq) + + let toSeq pq = Seq.unfold popMin pq + + let sort sq = sq |> fromSeq |> toSeq diff --git a/Task/Priority-queue/F-Sharp/priority-queue-3.fs b/Task/Priority-queue/F-Sharp/priority-queue-3.fs new file mode 100644 index 0000000000..b9d49ef02c --- /dev/null +++ b/Task/Priority-queue/F-Sharp/priority-queue-3.fs @@ -0,0 +1,84 @@ +[] +module PriorityQ = + + type HeapEntry<'T> = struct val k:uint32 val v:'T new(k,v) = { k=k;v=v } end + type MinHeapTree<'T> = ResizeArray> + + let empty<'T> = MinHeapTree>() + + let isEmpty (pq: MinHeapTree<_>) = pq.Count = 0 + + let size (pq: MinHeapTree<_>) = let cnt = pq.Count + if cnt = 0 then 0 else cnt - 1 + + let peekMin (pq:MinHeapTree<_>) = if pq.Count > 1 then let kv = pq.[0] + Some (kv.k, kv.v) else None + + let push k v (pq:MinHeapTree<_>) = + if pq.Count = 0 then pq.Add(HeapEntry(0xFFFFFFFFu,v)) //add an extra entry so there's always a right max node + let mutable nxtlvl = pq.Count in let mutable lvl = nxtlvl <<< 1 //1 past index of value added times 2 + pq.Add(pq.[nxtlvl - 1]) //copy bottom entry then do bubble up while less than next level up + while ((lvl <- lvl >>> 1); nxtlvl <- nxtlvl >>> 1; nxtlvl <> 0) do + let t = pq.[nxtlvl - 1] in if t.k > k then pq.[lvl - 1] <- t else lvl <- lvl <<< 1; nxtlvl <- 0 //causes loop break + pq.[lvl - 1] <- HeapEntry(k,v); pq + + let inline private siftdown k v ndx (pq: MinHeapTree<_>) = + let mutable i = ndx in let mutable ni = i in let cnt = pq.Count - 1 + while (ni <- ni + ni + 1; ni < cnt) do + let lk = pq.[ni].k in let rk = pq.[ni + 1].k in let oi = i + let k = if k > lk then i <- ni; lk else k in if k > rk then ni <- ni + 1; i <- ni + if i <> oi then pq.[oi] <- pq.[i] else ni <- cnt //causes loop break + pq.[i] <- HeapEntry(k,v) + + let replaceMin k v (pq:MinHeapTree<_>) = siftdown k v 0 pq; pq + + let deleteMin (pq:MinHeapTree<_>) = + let lsti = pq.Count - 2 + if lsti <= 0 then pq.Clear(); pq else + let lstkv = pq.[lsti] + pq.RemoveAt(lsti) + siftdown lstkv.k lstkv.v 0 pq; pq + + let adjust f (pq:MinHeapTree<_>) = //adjust all the contents using the function, then re-heapify + let cnt = pq.Count - 1 + let rec adj i = + let lefti = i + i + 1 in let righti = lefti + 1 + let ckv = pq.[i] in let (nk, nv) = f ckv.k ckv.v + if righti < cnt then adj righti + if lefti < cnt then adj lefti; siftdown nk nv i pq + else pq.[i] <- HeapEntry(nk, nv) + adj 0; pq + + let fromSeq sq = + if Seq.isEmpty sq then empty + else let pq = new MinHeapTree<_>(sq |> Seq.map (fun (k, v) -> HeapEntry(k, v))) + let sz = pq.Count in let lkv = pq.[sz - 1] + pq.Add(HeapEntry(UInt32.MaxValue, lkv.v)) + let rec build i = + let lefti = i + i + 1 + if lefti < sz then + let righti = lefti + 1 in build lefti; build righti + let ckv = pq.[i] in siftdown ckv.k ckv.v i pq + build 0; pq + + let merge (pq1:MinHeapTree<_>) (pq2:MinHeapTree<_>) = + if pq2.Count = 0 then pq1 else + if pq1.Count = 0 then pq2 else + let pq = empty + pq.AddRange(pq1); pq.RemoveAt(pq.Count - 1) + pq.AddRange(pq2) + let sz = pq.Count - 1 + let rec build i = + let lefti = i + i + 1 + if lefti < sz then + let righti = lefti + 1 in build lefti; build righti + let ckv = pq.[i] in siftdown ckv.k ckv.v i pq + build 0; pq + + let popMin pq = match peekMin pq with + | None -> None + | Some(kv) -> Some(kv, deleteMin pq) + + let toSeq pq = Seq.unfold popMin pq + + let sort sq = sq |> fromSeq |> toSeq diff --git a/Task/Priority-queue/F-Sharp/priority-queue-4.fs b/Task/Priority-queue/F-Sharp/priority-queue-4.fs new file mode 100644 index 0000000000..f1a4d19092 --- /dev/null +++ b/Task/Priority-queue/F-Sharp/priority-queue-4.fs @@ -0,0 +1,19 @@ +> let testseq = [| (3u, "Clear drains"); + (4u, "Feed cat"); + (5u, "Make tea"); + (1u, "Solve RC tasks"); + (2u, "Tax return") |] |> Array.toSeq + let testpq = testseq |> MinHeap.fromSeq + testseq |> Seq.fold (fun pq (k, v) -> MinHeap.push k v pq) MinHeap.empty + |> MinHeap.toSeq |> Seq.iter (printfn "%A") // test slow build + printfn "" + testseq |> MinHeap.fromSeq |> MinHeap.toSeq // test fast build + |> Seq.iter (printfn "%A") + printfn "" + testseq |> MinHeap.sort |> Seq.iter (printfn "%A") // convenience function + printfn "" + MinHeap.merge testpq testpq // test merge + |> MinHeap.toSeq |> Seq.iter (printfn "%A") + printfn "" + testpq |> MinHeap.adjust (fun k v -> uint32 (MinHeap.size testpq) - k, v) + |> MinHeap.toSeq |> Seq.iter (printfn "%A") // test adjust;; diff --git a/Task/Priority-queue/Haskell/priority-queue-2.hs b/Task/Priority-queue/Haskell/priority-queue-2.hs index db1392ee9b..23e5b8b1c9 100644 --- a/Task/Priority-queue/Haskell/priority-queue-2.hs +++ b/Task/Priority-queue/Haskell/priority-queue-2.hs @@ -1,43 +1,3 @@ -data MinHeap a = Nil | MinHeap { v::a, cnt::Int, l::MinHeap a, r::MinHeap a } - deriving (Show, Eq) +import qualified Data.Set as S -hPush :: (Ord a) => a -> MinHeap a -> MinHeap a -hPush x Nil = MinHeap {v = x, cnt = 1, l = Nil, r = Nil} -hPush x h = if x < vv -- insert element, try to keep the tree balanced - then if hLength (l h) <= hLength (r h) - then MinHeap { v=x, cnt=cc, l=hPush vv ll, r=rr } - else MinHeap { v=x, cnt=cc, l=ll, r=hPush vv rr } - else if hLength (l h) <= hLength (r h) - then MinHeap { v=vv, cnt=cc, l=hPush x ll, r=rr } - else MinHeap { v=vv, cnt=cc, l=ll, r=hPush x rr } - where (vv, cc, ll, rr) = (v h, 1 + cnt h, l h, r h) - -hPop :: (Ord a) => MinHeap a -> (a, MinHeap a) -hPop h = (v h, pq) where -- just pop, heed not the tree balance - pq | l h == Nil = r h - | r h == Nil = l h - | v (l h) <= v (r h) = let (vv,hh) = hPop (l h) in - MinHeap {v = vv, cnt = hLength hh + hLength (r h), - l = hh, r = r h} - | otherwise = let (vv,hh) = hPop (r h) in - MinHeap {v = vv, cnt = hLength hh + hLength (l h), - l = l h, r = hh} - -hLength :: (Ord a) => MinHeap a -> Int -hLength Nil = 0 -hLength h = cnt h - -hFromList :: (Ord a) => [a] -> MinHeap a -hFromList = foldl (flip hPush) Nil - -hToList :: (Ord a) => MinHeap a -> [a] -hToList = unfoldr f where - f Nil = Nothing - f h = Just $ hPop h - -main = mapM_ print $ hToList $ hFromList [ - (3, "Clear drains"), - (4, "Feed cat"), - (5, "Make tea"), - (1, "Solve RC tasks"), - (2, "Tax return")] +main = print (S.toList (S.fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")])) diff --git a/Task/Priority-queue/Haskell/priority-queue-3.hs b/Task/Priority-queue/Haskell/priority-queue-3.hs new file mode 100644 index 0000000000..db1392ee9b --- /dev/null +++ b/Task/Priority-queue/Haskell/priority-queue-3.hs @@ -0,0 +1,43 @@ +data MinHeap a = Nil | MinHeap { v::a, cnt::Int, l::MinHeap a, r::MinHeap a } + deriving (Show, Eq) + +hPush :: (Ord a) => a -> MinHeap a -> MinHeap a +hPush x Nil = MinHeap {v = x, cnt = 1, l = Nil, r = Nil} +hPush x h = if x < vv -- insert element, try to keep the tree balanced + then if hLength (l h) <= hLength (r h) + then MinHeap { v=x, cnt=cc, l=hPush vv ll, r=rr } + else MinHeap { v=x, cnt=cc, l=ll, r=hPush vv rr } + else if hLength (l h) <= hLength (r h) + then MinHeap { v=vv, cnt=cc, l=hPush x ll, r=rr } + else MinHeap { v=vv, cnt=cc, l=ll, r=hPush x rr } + where (vv, cc, ll, rr) = (v h, 1 + cnt h, l h, r h) + +hPop :: (Ord a) => MinHeap a -> (a, MinHeap a) +hPop h = (v h, pq) where -- just pop, heed not the tree balance + pq | l h == Nil = r h + | r h == Nil = l h + | v (l h) <= v (r h) = let (vv,hh) = hPop (l h) in + MinHeap {v = vv, cnt = hLength hh + hLength (r h), + l = hh, r = r h} + | otherwise = let (vv,hh) = hPop (r h) in + MinHeap {v = vv, cnt = hLength hh + hLength (l h), + l = l h, r = hh} + +hLength :: (Ord a) => MinHeap a -> Int +hLength Nil = 0 +hLength h = cnt h + +hFromList :: (Ord a) => [a] -> MinHeap a +hFromList = foldl (flip hPush) Nil + +hToList :: (Ord a) => MinHeap a -> [a] +hToList = unfoldr f where + f Nil = Nothing + f h = Just $ hPop h + +main = mapM_ print $ hToList $ hFromList [ + (3, "Clear drains"), + (4, "Feed cat"), + (5, "Make tea"), + (1, "Solve RC tasks"), + (2, "Tax return")] diff --git a/Task/Priority-queue/Haskell/priority-queue-4.hs b/Task/Priority-queue/Haskell/priority-queue-4.hs new file mode 100644 index 0000000000..150433484a --- /dev/null +++ b/Task/Priority-queue/Haskell/priority-queue-4.hs @@ -0,0 +1,124 @@ +data MinHeap kv = MinHeapEmpty + | MinHeapLeaf !kv + | MinHeapNode !kv {-# UNPACK #-} !Int !(MinHeap a) !(MinHeap a) + deriving (Show, Eq) + +emptyPQ :: MinHeap kv +emptyPQ = MinHeapEmpty + +isEmptyPQ :: PriorityQ kv -> Bool +isEmptyPQ Mt = True +isEmptyPQ _ = False + +sizePQ :: (Ord kv) => MinHeap kv -> Int +sizePQ MinHeapEmpty = 0 +sizePQ (MinHeapLeaf _) = 1 +sizePQ (MinHeapNode _ cnt _ _) = cnt + +peekMinPQ :: MinHeap kv -> Maybe kv +peekMinPQ MinHeapEmpty = Nothing +peekMinPQ (MinHeapLeaf v) = Just v +peekMinPQ (MinHeapNode v _ _ _) = Just v + +pushPQ :: (Ord kv) => kv -> MinHeap kv -> MinHeap kv +pushPQ kv pq = insert kv 0 pq where -- insert element, keeping the tree balanced + insert kv _ MinHeapEmpty = MinHeapLeaf kv + insert kv _ (MinHeapLeaf vv) = if kv <= vv + then MinHeapNode kv 2 (MinHeapLeaf vv) MinHeapEmpty + else MinHeapNode vv 2 (MinHeapLeaf kv) MinHeapEmpty + insert kv msk (MinHeapNode vv cc ll rr) = if kv <= vv + then if nmsk >= 0 + then MinHeapNode kv nc (insert vv nmsk ll) rr + else MinHeapNode kv nc ll (insert vv nmsk rr) + else if nmsk >= 0 + then MinHeapNode vv nc (insert kv nmsk ll) rr + else MinHeapNode vv nc ll (insert kv nmsk rr) + where nc = cc + 1 + nmsk = if msk /= 0 then msk `shiftL` 1 -- walk path to next + else let s = floor $ (log $ fromIntegral nc) / log 2 in + (nc `shiftL` ((finiteBitSize cc) - s)) .|. 1 --never 0 again + +siftdown :: (Ord kv) => kv -> Int -> MinHeap kv -> MinHeap kv -> MinHeap kv +siftdown kv cnt lft rght = replace cnt lft rght where + replace cc ll rr = case rr of -- adj to put kv in current left/right + MinHeapEmpty -> -- means left is a MinHeapLeaf + case ll of { (MinHeapLeaf vl) -> + if kv <= vl + then MinHeapNode kv 2 ll MinHeapEmpty + else MinHeapNode vl 2 (MinHeapLeaf kv) MinHeapEmpty } + MinHeapLeaf vr -> + case ll of + MinHeapLeaf vl -> if vl <= vr + then if kv <= vl then MinHeapNode kv cc ll rr + else MinHeapNode vl cc (MinHeapLeaf kv) rr + else if kv <= vr then MinHeapNode kv cc ll rr + else MinHeapNode vr cc ll (MinHeapLeaf kv) + MinHeapNode vl ccl lll rrl -> if vl <= vr + then if kv <= vl then MinHeapNode kv cc ll rr + else MinHeapNode vl cc (replace ccl lll rrl) rr + else if kv <= vr then MinHeapNode kv cc ll rr + else MinHeapNode vr cc ll (MinHeapLeaf kv) + MinHeapNode vr ccr llr rrr -> case ll of + (MinHeapNode vl ccl lll rrl) -> -- right is node, so is left + if vl <= vr then + if kv <= vl then MinHeapNode kv cc ll rr + else MinHeapNode vl cc (replace ccl lll rrl) rr + else if kv <= vr then MinHeapNode kv cc ll rr + else MinHeapNode vr cc ll (replace ccr llr rrr) + +replaceMinPQ :: (Ord kv) => a -> MinHeap kv -> MinHeap kv +replaceMinPQ _ MinHeapEmpty = MinHeapEmpty +replaceMinPQ kv (MinHeapLeaf _) = MinHeapLeaf kv +replaceMinPQ kv (MinHeapNode _ cc ll rr) = siftdown kv cc ll rr where + +deleteMinPQ :: (Ord kv) => MinHeap kv -> MinHeap kv +deleteMinPQ MinHeapEmpty = MinHeapEmpty -- remove min keeping tree balanced +deleteMinPQ pq = let (dkv, npq) = delete 0 pq in + replaceMinPQ dkv npq where + delete _ (MinHeapLeaf vv) = (vv, MinHeapEmpty) + delete msk (MinHeapNode vv cc ll rr) = + if rr == MinHeapEmpty -- means left is MinHeapLeaf + then case ll of (MinHeapLeaf vl) -> (vl, MinHeapLeaf vv) + else if nmsk >= 0 -- means only deal with left + then let (dv, npq) = delete nmsk ll in + (dv, MinHeapNode vv (cc - 1) npq rr) + else let (dv, npq) = delete nmsk rr in + (dv, MinHeapNode vv (cc - 1) ll npq) + where nmsk = if msk /= 0 then msk `shiftL` 1 -- walk path to last + else let s = floor $ (log $ fromIntegral cc) / log 2 in + (cc `shiftL` ((finiteBitSize cc) - s)) .|. 1 --never 0 again + +adjustPQ :: (Ord kv) => (kv -> kv) -> MinHeap kv -> MinHeap kv +adjustPQ f pq = adjust pq where -- applies function to every element and reheapifies + adjust MinHeapEmpty = MinHeapEmpty + adjust (MinHeapLeaf v) = MinHeapLeaf (f v) + adjust (MinHeapNode vv cc ll rr) = siftdown (f vv) cc (adjust ll) (adjust rr) + +fromListPQ :: (Ord kv) => [kv] -> MinHeap kv +-- fromListPQ = foldl (flip pushPQ) MinHeapEmpty -- O(n log n) time; slow +fromListPQ [] = MinHeapEmpty -- O(n) time using "adjust id" which is O(n) +fromListPQ xs = let (_, pq) = build 1 xs in pq where + sz = length xs + szd2 = sz `div` 2 + build _ [] = ([], MinHeapEmpty) + build lvl (x:xs') = if lvl > szd2 then (xs', MinHeapLeaf x) + else let nlvl = lvl + lvl in + let (xrl, pql) = build nlvl xs' in + let (xrr, pqr) = if nlvl >= sz + then (xrl, MinHeapEmpty) -- no right leaf + else build (nlvl + 1) xrl in + let cnt = sizePQ pql + sizePQ pqr + 1 in + (xrr, siftdown x cnt pql pqr) + +popMinPQ :: (Ord kv) => MinHeap kv -> Maybe (kv, MinHeap kv) +popMinPQ pq = case peekMinPQ pq of + Nothing -> Nothing + Just v -> Just (v, deleteMinPQ pq) + +toListPQ :: (Ord kv) => MinHeap kv -> [kv] +toListPQ = unfoldr f where + f MinHeapEmpty = Nothing + f pq = popMinPQ pq + +sortPQ :: (Ord kv) => [kv] -> [kv] +sortPQ ls = toListPQ $ fromListPQ ls diff --git a/Task/Priority-queue/Haskell/priority-queue-5.hs b/Task/Priority-queue/Haskell/priority-queue-5.hs new file mode 100644 index 0000000000..f647c6f228 --- /dev/null +++ b/Task/Priority-queue/Haskell/priority-queue-5.hs @@ -0,0 +1,104 @@ +data PriorityQ k v = Mt + | Br !k v !(PriorityQ k v) !(PriorityQ k v) + deriving (Eq, Ord, Read, Show) + +emptyPQ :: PriorityQ k v +emptyPQ = Mt + +isEmptyPQ :: PriorityQ k v -> Bool +isEmptyPQ Mt = True +isEmptyPQ _ = False + +-- The size function isn't from the ML code, but an implementation was +-- suggested by Bertram Felgenhauer on Haskell Cafe, so it is included. + +-- Return number of elements in the priority queue. +-- /O(log(n)^2)/ +sizePQ :: PriorityQ k v -> Int +sizePQ Mt = 0 +sizePQ (Br _ _ pl pr) = 2 * n + rest n pl pr where + n = sizePQ pr + -- rest n p q, where n = sizePQ q, and sizePQ p - sizePQ q = 0 or 1 + -- returns 1 + sizePQ p - sizePQ q. + rest :: Int -> PriorityQ k v -> PriorityQ k v -> Int + rest 0 Mt _ = 1 + rest 0 _ _ = 2 + rest n (Br _ _ ll lr) (Br _ _ rl rr) = case r of + 0 -> rest d ll rl -- subtree sizes: (d or d+1), d; d, d + 1 -> rest d lr rr -- subtree sizes: d+1, (d or d+1); d+1, d + where m1 = n - 1 + d = m1 `shiftR` 1 + r = m1 .&. 1 + +peekMinPQ :: PriorityQ k v -> Maybe (k, v) +peekMinPQ Mt = Nothing +peekMinPQ (Br k v _ _) = Just (k, v) + +pushPQ :: Ord k => k -> v -> PriorityQ k v -> PriorityQ k v +pushPQ wk wv Mt = Br wk wv Mt Mt +pushPQ wk wv (Br vk vv pl pr) + | wk <= vk = Br wk wv (pushPQ vk vv pr) pl + | otherwise = Br vk vv (pushPQ wk wv pr) pl + +siftdown :: Ord k => k -> v -> PriorityQ k v -> PriorityQ k v -> PriorityQ k v +siftdown wk wv Mt _ = Br wk wv Mt Mt +siftdown wk wv (pl @ (Br vk vv _ _)) Mt + | wk <= vk = Br wk wv pl Mt + | otherwise = Br vk vv (Br wk wv Mt Mt) Mt +siftdown wk wv (pl @ (Br vkl vvl pll plr)) (pr @ (Br vkr vvr prl prr)) + | wk <= vkl && wk <= vkr = Br wk wv pl pr + | vkl <= vkr = Br vkl vvl (siftdown wk wv pll plr) pr + | otherwise = Br vkr vvr pl (siftdown wk wv prl prr) + +replaceMinPQ :: Ord k => k -> v -> PriorityQ k v -> PriorityQ k v +replaceMinPQ wk wv Mt = Mt +replaceMinPQ wk wv (Br _ _ pl pr) = siftdown wk wv pl pr + +deleteMinPQ :: (Ord k) => PriorityQ k v -> PriorityQ k v +deleteMinPQ Mt = Mt +deleteMinPQ (Br _ _ pr Mt) = pr +deleteMinPQ (Br _ _ pl pr) = let (k, v, npl) = leftrem pl in + siftdown k v pr npl where + leftrem (Br k v Mt Mt) = (k, v, Mt) + leftrem (Br vk vv (Br k v _ _) Mt) = (k, v, Br vk vv Mt Mt) + leftrem (Br vk vv pl pr) = let (k, v, npl) = leftrem pl in + (k, v, Br vk vv pr npl) + +-- the following function has been added to the ML code to apply a function +-- to all the entries in the queue and reheapify in O(n) time +adjustPQ :: (Ord k) => (k -> v -> (k, v)) -> PriorityQ k v -> PriorityQ k v +adjustPQ f pq = adjust pq where -- applies function to every element and reheapifies + adjust Mt = Mt + adjust (Br vk vv pl pr) = let (k, v) = f vk vv in + siftdown k v (adjust pl) (adjust pr) + +fromListPQ :: (Ord k) => [(k, v)] -> PriorityQ k v +-- fromListPQ = foldl (flip pushPQ) Mt -- O(n log n) time; slow +fromListPQ [] = Mt -- O(n) time using adjust-from-bottom which is O(n) +fromListPQ xs = let (pq, _) = build (length xs) xs in pq where + build 0 xs = (Mt, xs) + build lvl ((k, v):xs') = let (pl, xrl) = build (lvl `shiftR` 1) xs' + (pr, xrr) = build ((lvl - 1) `shiftR` 1) xrl in + (siftdown k v pl pr, xrr) + +-- the following function has been added to merge two queues in O(m + n) time +-- where m and n are the sizes of the two queues +mergePQ :: (Ord k) => PriorityQ k v -> PriorityQ k v -> PriorityQ k v +mergePQ pq1 Mt = pq1 -- from concatenated "dumb" list +mergePQ Mt pq2 = pq2 -- in O(m + n) time where m,n are sizes pq1,pq2 +mergePQ pq1 pq2 = fromListPQ (zipper pq1 $ zipper pq2 []) where + zipper (Br wk wv Mt _) appndlst = (wk, wv) : appndlst + zipper (Br wk wv pl Mt) appndlst = (wk, wv) : zipper pl appndlst + zipper (Br wk wv pl pr) appndlst = (wk, wv) : zipper pl (zipper pr appndlst) + +popMinPQ :: (Ord k) => PriorityQ k v -> Maybe ((k, v), PriorityQ k v) +popMinPQ pq = case peekMinPQ pq of + Nothing -> Nothing + Just kv -> Just (kv, deleteMinPQ pq) + +toListPQ :: (Ord k) => PriorityQ k v -> [(k, v)] +toListPQ Mt = [] -- unfoldr popMinPQ +toListPQ pq @ (Br vk vv _ _) = (vk, vv) : (toListPQ $ deleteMinPQ pq) + +sortPQ :: (Ord k) => [(k, v)] -> [(k, v)] +sortPQ ls = toListPQ $ fromListPQ ls diff --git a/Task/Priority-queue/Haskell/priority-queue-6.hs b/Task/Priority-queue/Haskell/priority-queue-6.hs new file mode 100644 index 0000000000..2af9e1676c --- /dev/null +++ b/Task/Priority-queue/Haskell/priority-queue-6.hs @@ -0,0 +1,18 @@ +testList = [ (3, "Clear drains"), + (4, "Feed cat"), + (5, "Make tea"), + (1, "Solve RC tasks"), + (2, "Tax return") ] + +testPQ = fromListPQ testList + +main = do -- slow build + mapM_ print $ toListPQ $ foldl (\pq (k, v) -> pushPQ k v pq) emptyPQ testList + putStrLn "" -- fast build + mapM_ print $ toListPQ $ fromListPQ testList + putStrLn "" -- combined fast sort + mapM_ print $ sortPQ testList + putStrLn "" -- test merge + mapM_ print $ toListPQ $ mergePQ testPQ testPQ + putStrLn "" -- test adjust + mapM_ print $ toListPQ $ adjustPQ (\x y -> (x * (-1), y)) testPQ diff --git a/Task/Priority-queue/Julia/priority-queue.julia b/Task/Priority-queue/Julia/priority-queue.julia new file mode 100644 index 0000000000..0d49dfc3b4 --- /dev/null +++ b/Task/Priority-queue/Julia/priority-queue.julia @@ -0,0 +1,19 @@ +using Base.Collections + +test = ["Clear drains" 3; + "Feed cat" 4; + "Make tea" 5; + "Solve RC tasks" 1; + "Tax return" 2] + +task = PriorityQueue(Base.Order.Reverse) +for i in 1:size(test)[1] + enqueue!(task, test[i,1], test[i,2]) +end + +println("Tasks, completed according to priority:") +while !isempty(task) + (t, p) = peek(task) + dequeue!(task) + println(" \"", t, "\" has priority ", p) +end diff --git a/Task/Priority-queue/OCaml/priority-queue-2.ocaml b/Task/Priority-queue/OCaml/priority-queue-2.ocaml index d1857271fb..503e230985 100644 --- a/Task/Priority-queue/OCaml/priority-queue-2.ocaml +++ b/Task/Priority-queue/OCaml/priority-queue-2.ocaml @@ -12,7 +12,7 @@ let () = 1, "Solve RC tasks"; 2, "Tax return"; ] in - let pq = List.fold_right PQSet.add tasks PQSet.empty in + let pq = PQSet.of_list tasks in let rec aux pq' = if not (PQSet.is_empty pq') then begin let prio, name as task = PQSet.min_elt pq' in diff --git a/Task/Priority-queue/Perl-6/priority-queue-1.pl6 b/Task/Priority-queue/Perl-6/priority-queue-1.pl6 new file mode 100644 index 0000000000..81d6f83343 --- /dev/null +++ b/Task/Priority-queue/Perl-6/priority-queue-1.pl6 @@ -0,0 +1,11 @@ +class PriorityQueue { + has @!tasks; + + method insert (Int $priority where * >= 0, $task) { + @!tasks[$priority].push: $task; + } + + method get { @!tasks.first(?*).shift } + + method is-empty { ?none @!tasks } +} diff --git a/Task/Priority-queue/Perl-6/priority-queue-2.pl6 b/Task/Priority-queue/Perl-6/priority-queue-2.pl6 new file mode 100644 index 0000000000..44ad511117 --- /dev/null +++ b/Task/Priority-queue/Perl-6/priority-queue-2.pl6 @@ -0,0 +1,16 @@ +my $pq = PriorityQueue.new; + +for ( + 3, 'Clear drains', + 4, 'Feed cat', + 5, 'Make tea', + 9, 'Sleep', + 3, 'Check email', + 1, 'Solve RC tasks', + 9, 'Exercise', + 2, 'Do taxes' +) -> $priority, $task { + $pq.insert( $priority, $task ); +} + +say $pq.get until $pq.is-empty; diff --git a/Task/Priority-queue/Perl-6/priority-queue.pl6 b/Task/Priority-queue/Perl-6/priority-queue.pl6 deleted file mode 100644 index fb0a8d2e03..0000000000 --- a/Task/Priority-queue/Perl-6/priority-queue.pl6 +++ /dev/null @@ -1,29 +0,0 @@ -class PriorityQueue { - has @!tasks is rw; - - method insert ( Int $priority where { $priority >= 0 }, $task ) { - @!tasks[$priority] //= []; - @!tasks[$priority].push: $task; - } - - method get { @!tasks.first({$^_}).shift } - - method is_empty { !?@!tasks.first({$^_}) } -} - -my $pq = PriorityQueue.new; - -for ( - 3, 'Clear drains', - 4, 'Feed cat', - 5, 'Make tea', - 9, 'Sleep', - 3, 'Check email', - 1, 'Solve RC tasks', - 9, 'Exercise', - 2, 'Do taxes' -) -> $priority, $task { - $pq.insert( $priority, $task ); -} - -say $pq.get until $pq.is_empty; diff --git a/Task/Priority-queue/R/priority-queue-1.r b/Task/Priority-queue/R/priority-queue-1.r index b46f02c265..dc8d056b25 100644 --- a/Task/Priority-queue/R/priority-queue-1.r +++ b/Task/Priority-queue/R/priority-queue-1.r @@ -1,5 +1,5 @@ PriorityQueue <- function() { - keys <<- values <<- NULL + keys <- values <- NULL insert <- function(key, value) { temp <- c(keys, key) ord <- order(temp) diff --git a/Task/Priority-queue/REXX/priority-queue.rexx b/Task/Priority-queue/REXX/priority-queue-1.rexx similarity index 100% rename from Task/Priority-queue/REXX/priority-queue.rexx rename to Task/Priority-queue/REXX/priority-queue-1.rexx diff --git a/Task/Priority-queue/REXX/priority-queue-2.rexx b/Task/Priority-queue/REXX/priority-queue-2.rexx new file mode 100644 index 0000000000..c3e491f869 --- /dev/null +++ b/Task/Priority-queue/REXX/priority-queue-2.rexx @@ -0,0 +1,42 @@ +/*REXX pgm implements a priority queue; with insert/show/delete top task*/ +n=0 +task.=0 /* for the sake of task.0done.* */ +say '------ inserting tasks.'; call ins_task 3 'Clear drains' + call ins_task 4 'Feed cat' + call ins_task 5 'Make tea' + call ins_task 1 'Solve RC tasks' + call ins_task 2 'Tax return' + call ins_task 6 'Relax' + call ins_task 6 'Enjoy' +say '------ Showing tasks.'; call show_tasks +say '------ Show and delete top task.' +todo=n /* tasks to be done */ +do While todo>0 + Say top() + End +exit + +ins_task: procedure expose n task. +n=n+1 +Parse Arg task.0pri.n task.0txt.n +Return + +show_tasks: procedure expose task. n +do i=1 To n + Say task.0pri.i task.0txt.i + End +Return + +top: procedure expose n task. todo /* get top task and mark it 'done' */ +high=0 +Do i=1 To n + If task.0pri.i>high &, + task.0done.i=0 Then Do + j=i + high=task.0pri.i + End + End +res=task.0pri.j task.0txt.j +task.0done.j=1 +todo=todo-1 +return res diff --git a/Task/Probabilistic-choice/Julia/probabilistic-choice.julia b/Task/Probabilistic-choice/Julia/probabilistic-choice.julia new file mode 100644 index 0000000000..2cb0942bd7 --- /dev/null +++ b/Task/Probabilistic-choice/Julia/probabilistic-choice.julia @@ -0,0 +1,29 @@ +p = [1/i for i in 5:11] +plen = length(p) +q = [0.0, [sum(p[1:i]) for i = 1:plen]] +plab = [char(i) for i in 0x05d0:(0x05d0+plen)] +hi = 10^6 +push!(p, 1.0 - sum(p)) +plen += 1 + +accum = zeros(Int, plen) + +for i in 1:hi + accum[sum(rand() .>= q)] += 1 +end + +r = accum/hi + +println("Rates at which items are selected (", hi, " trials).") +println(" Item Expected Actual") +for i in 1:plen + println(@sprintf(" \u2067%s %8.6f %8.6f", plab[i], p[i], r[i])) +end + +println() +println("Rates at which items are selected (", hi, " trials).") +println(" Item Count Expected Actual") +for i in 1:plen + println(@sprintf(" %s yields %6d %8.6f %8.6f", + plab[i], accum[i], p[i], r[i])) +end diff --git a/Task/Probabilistic-choice/PL-I/probabilistic-choice.pli b/Task/Probabilistic-choice/PL-I/probabilistic-choice.pli new file mode 100644 index 0000000000..606926aa51 --- /dev/null +++ b/Task/Probabilistic-choice/PL-I/probabilistic-choice.pli @@ -0,0 +1,45 @@ + probch: Proc Options(main); + Dcl prob(8) Dec Float(15) Init((1/5.0), /* aleph */ + (1/6.0), /* beth */ + (1/7.0), /* gimel */ + (1/8.0), /* daleth */ + (1/9.0), /* he */ + (1/10.0), /* waw */ + (1/11.0), /* zayin */ + (1759/27720));/* heth */ + Dcl what(8) Char(6) Init('aleph ','beth ','gimel ','daleth', + 'he ','waw ','zayin ','heth '); + Dcl ulim(0:8) Dec Float(15) Init((9)0); + Dcl i Bin Fixed(31); + Dcl ifloat Dec Float(15); + Dcl one Dec Float(15) Init(1); + Dcl num Dec Float(15) Init(1759); + Dcl denom Dec Float(15) Init(27720); + Dcl x Dec Float(15) Init(0); + Dcl pr Dec Float(15) Init(0); + Dcl (n,nn) Bin Fixed(31); + Dcl cnt(8) Bin Fixed(31) Init((8)0); + nn=1000000; + Do i=1 To 8; + ifloat=i+4; + If i<8 Then + prob(i)=one/ifloat; + Else + prob(i)=num/denom; + Ulim(i)=ulim(i-1)+prob(i); + /* Put Skip list(i,prob(i),ulim(i));*/ + End; + Do n=1 To nn; + x=random(); + Do i=1 To 8; + If x; -my @P = 1 «/« (5 .. 11), 1759/27720; +my @P = (1 X/ 5 .. 11), 1759/27720; my @cP = [\+] @P; my @results; -for ^TRIALS { - @results[ - first { @cP[$_] > state $ = rand }, ^@P; - ]++; -} +@results[ + first-index { $_ > state $ = rand }, @cP +]++ for ^TRIALS; say 'Event Occurred Expected Difference'; for ^@results { diff --git a/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx b/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx index b7b425d24f..fd4dbac1ab 100644 --- a/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx +++ b/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx @@ -1,32 +1,32 @@ -/*REXX pg shows results of probabilistic choices (gen rand#s per prob.) */ -parse arg trials digits seed . /*obtain some optional arguments.*/ +/*REXX program shows results of probabilistic choices, gen random #s per prob.*/ +parse arg trials digits seed . /*obtain the optional arguments from CL*/ if trials=='' | trials==',' then trials=1000000 if digits=='' | digits==',' then digits=15; digits=max(10,digits) -if seed\=='' then call random ,,seed /*for repeatability*/ +if seed\=='' then call random ,,seed /*for repeatability.*/ names='aleph beth gimel daleth he waw zayin heth ──totals───►' cells=words(names) - 1; high=100000; s=0; !.=0 _=4 do n=1 for 7; _=_+1; prob.n=1/_; Hprob.n=prob.n*high; s=s+prob.n - end /*n*/ /* [↑] determine probabilities. */ + end /*n*/ /* [↑] determine the probabilities. */ prob.8=1759/27720; Hprob.8=prob.8*high; s=s+prob.8; prob.9=s; !.9=trials - do j=1 for trials; r=random(1,high) /*generate X number of random #s.*/ - do k=1 for cells /*now, for each cell, compute %s.*/ - if r<=Hprob.k then !.k=!.k+1 /*for each range, bump da counter*/ + do j=1 for trials; r=random(1,high) /*generate X number of random numbers.*/ + do k=1 for cells /*for each cell, compute percentages. */ + if r<=Hprob.k then !.k=!.k+1 /*for each range, bump the counter. */ end /*k*/ end /*j*/ w=digits+6; d=max(length(trials), length('count')) + 4 -say center('name',15,'─') center('count',d,'─') center('target %',w,'─'), - center('actual %',w,'─') /*display a formatted header line*/ - - do i=1 for cells+1 /*show for each cell and totals. */ +say centr('name',15) centr('count',d) centr('target %') centr('actual %') + /* [↑] display a formatted header line*/ + do i=1 for cells+1 /*show for each of the cells and totals*/ say ' ' left(word(names,i) , 12), right(!.i , d-2) ' ', left(format(prob.i *100, d), w-2), left(format(!.i/trials*100, d), w-2) - if i==8 then say center('',15,'─') center('',d,'─'), - center('', w,'─') center('',w,'─') + if i==8 then say centr(,15) centr(,d) centr() centr() end /*i*/ - /*stick a fork in it, we're done.*/ +exit /*stick a fork in it, we are all done.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +centr: return center(arg(1), word(arg(2) w,1), '─') diff --git a/Task/Probabilistic-choice/VBScript/probabilistic-choice.vb b/Task/Probabilistic-choice/VBScript/probabilistic-choice.vb new file mode 100644 index 0000000000..0263dd1084 --- /dev/null +++ b/Task/Probabilistic-choice/VBScript/probabilistic-choice.vb @@ -0,0 +1,32 @@ +item = Array("aleph","beth","gimel","daleth","he","waw","zayin","heth") +prob = Array(1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720) +Dim cnt(7) + +'Terminate script if sum of probabilities <> 1. +sum = 0 +For i = 0 To UBound(prob) + sum = sum + prob(i) +Next + +If sum <> 1 Then + WScript.Quit +End If + +For trial = 1 To 1000000 + r = Rnd(1) + p = 0 + For i = 0 To UBound(prob) + p = p + prob(i) + If r < p Then + cnt(i) = cnt(i) + 1 + Exit For + End If + Next +Next + +WScript.StdOut.Write "item" & vbTab & "actual" & vbTab & vbTab & "theoretical" +WScript.StdOut.WriteLine +For i = 0 To UBound(item) + WScript.StdOut.Write item(i) & vbTab & FormatNumber(cnt(i)/1000000,6) & vbTab & FormatNumber(prob(i),6) + WScript.StdOut.WriteLine +Next diff --git a/Task/Problem-of-Apollonius/Elixir/problem-of-apollonius.elixir b/Task/Problem-of-Apollonius/Elixir/problem-of-apollonius.elixir new file mode 100644 index 0000000000..e25a58926e --- /dev/null +++ b/Task/Problem-of-Apollonius/Elixir/problem-of-apollonius.elixir @@ -0,0 +1,33 @@ +defmodule Circle do + def apollonius(c1, c2, c3, s1, s2, s3) do + {x1, y1, r1} = c1 + {w12, w13, w14} = calc(c1, c2, s1, s2) + {u22, u23, u24} = calc(c2, c3, s2, s3) + {w22, w23, w24} = {u22 - w12, u23 - w13, u24 - w14} + + p = -w23 / w22 + q = w24 / w22 + m = -w12 * p - w13 + n = w14 - w12 * q + + a = n*n + q*q - 1 + b = 2*m*n - 2*n*x1 + 2*p*q - 2*q*y1 + 2*s1*r1 + c = x1*x1 + m*m - 2*m*x1 + p*p + y1*y1 - 2*p*y1 - r1*r1 + + d = b*b - 4*a*c + rs = (-b - :math.sqrt(d)) / (2*a) + {m + n*rs, p + q*rs, rs} + end + + defp calc({x1, y1, r1}, {x2, y2, r2}, s1, s2) do + v1 = x2 - x1 + {(y2 - y1) / v1, (x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2) / (2*v1), (s2*r2 - s1*r1) / v1} + end +end + +c1 = {0, 0, 1} +c2 = {2, 4, 2} +c3 = {4, 0, 1} + +IO.inspect Circle.apollonius(c1, c2, c3, 1, 1, 1) +IO.inspect Circle.apollonius(c1, c2, c3, -1, -1, -1) diff --git a/Task/Problem-of-Apollonius/Julia/problem-of-apollonius.julia b/Task/Problem-of-Apollonius/Julia/problem-of-apollonius.julia new file mode 100644 index 0000000000..b50064af21 --- /dev/null +++ b/Task/Problem-of-Apollonius/Julia/problem-of-apollonius.julia @@ -0,0 +1,55 @@ +using Polynomials + +immutable Point{T<:Real} + x::T + y::T +end + +immutable Circle{T<:Real} + c::Point{T} + r::T +end +Circle{T<:Real}(x::T, y::T, r::T) = Circle(Point(x,y), r) + +function apollonius{T<:Real}(ap::Array{Circle{T},1}, + enc::Array{Int,1}=Int[]) + length(ap) == 3 || error("This Apollonius problem needs 3 circles.") + x = map(u->u.c.x, ap) + y = map(u->u.c.y, ap) + r = map(u->u in enc ? -1 : 1, 1:3) .* map(u->u.r, ap) + a = 2x[1] - 2x[2:3] + b = 2y[1] - 2y[2:3] + c = 2r[1] - 2r[2:3] + d = (x[1]^2 + y[1]^2 - r[1]^2) + d -= (map(u->u^2, x) + map(u->u^2, y) - map(u->u^2, r))[2:3] + u = Poly([-det(hcat(b,d)), det(hcat(b,c))]/det(hcat(a,b))) + v = Poly([det(hcat(a,d)), -det(hcat(a,c))]/det(hcat(a,b))) + w = Poly([r[1], 1.0])^2 + s = (u - x[1])^2 + (v - y[1])^2 - w + r = filter(x->imag(x)==0 && 09; 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)i -/*──────────────────────────────────TELL subroutine─────────────────────*/ -tell: parse arg _,a b c; say _ left(a/1,w) left(b/1,w) left(c/1,w); return - /*dividing by 1 reformats #s to W*/ +/*REXX program solves the problem of Apollonius, named after the Greek */ +/*──────────────── Apollonius of Perga [Pergæus] (circa 262 BC ──► 190 BC).*/ +w=20; numeric digits w-5 /*the width used to display the numbers*/ + c1.x=0; c1.y=0; c1.r=1 + c2.x=4; c2.y=0; c2.r=1 + c3.x=2; c3.y=4; c3.r=2 +call tell 'external tangent:', Apollonius( 1, 1, 1) +call tell 'internal tangent:', Apollonius(-1, -1, -1) +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +Apollonius: parse arg s1,s2,s3 /*could be an internal/external tangent*/ + numeric digits digits()*3 /*reduce rounding by using 3 times digs*/ + x1=c1.x; x2=c2.x; x3=c3.x + y1=c1.y; y2=c2.y; y3=c3.y + r1=c1.r; r2=c2.r; r3=c3.r + va=2*x2-2*x1; vb=2*y2-2*y1 + vc=x1*x1-x2*x2+y1*y1-y2*y2-r1*r1+r2*r2 + vd=2*s2*r2-2*s1*r1; ve=2*x3-2*x2; vf=2*y3-2*y2 + vg=x2*x2-x3*x3+y2*y2-y3*y3-r2*r2+r3*r3; vh=2*s3*r3-2*s2*r2 + vj=vb/va; vk=vc/va; vm=vd/va; vn=vf/ve-vj + vp=vg/ve-vk; vr=vh/ve-vm; p=-vp/vn; q =vr/vn + m=-vj*p-vk; n=vm-vj*q; a=n*n+q*q-1 + b=2*m*n-2*n*x1+2*p*q-2*q*y1+2*s1*r1 + c=x1*x1+m*m-2*m*x1+p*p+y1*y1-2*p*y1-r1*r1 + _=b*b-4*a*c; $.r=(-b-sqrt(_))/(a+a); $.x=m+n*$.r; $.y=p+q*$.r + numeric digits digits()%3 /*reset DIGITS to the original.*/ + return $.x $.y $.r /*return with 3 args, normalized.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +tell: parse arg _,a b c; say _ left(a/1,w) left(b/1,w) left(c/1,w); return + /*dividing by 1 normalizes the numbers.*/ diff --git a/Task/Problem-of-Apollonius/Ruby/problem-of-apollonius.rb b/Task/Problem-of-Apollonius/Ruby/problem-of-apollonius.rb index d473c86a71..f4208fc673 100644 --- a/Task/Problem-of-Apollonius/Ruby/problem-of-apollonius.rb +++ b/Task/Problem-of-Apollonius/Ruby/problem-of-apollonius.rb @@ -5,9 +5,9 @@ def initialize(x, y, r) attr_reader :x, :y, :r def self.apollonius(c1, c2, c3, s1=1, s2=1, s3=1) - x1, y1, r1 = [c1.x, c1.y, c1.r] - x2, y2, r2 = [c2.x, c2.y, c2.r] - x3, y3, r3 = [c3.x, c3.y, c3.r] + x1, y1, r1 = c1.x, c1.y, c1.r + x2, y2, r2 = c2.x, c2.y, c2.r + x3, y3, r3 = c3.x, c3.y, c3.r v11 = 2*x2 - 2*x1 v12 = 2*y2 - 2*y1 @@ -41,14 +41,17 @@ def self.apollonius(c1, c2, c3, s1=1, s2=1, s3=1) xs = m + n*rs ys = p + q*rs - return self.new(xs, ys, rs) + self.new(xs, ys, rs) end -end + def to_s + "Circle: x=#{@x}, y=#{@y}, r=#{@r}" + end +end -p c1 = Circle.new(0, 0, 1) -p c2 = Circle.new(2, 4, 2) -p c3 = Circle.new(4, 0, 1) +puts c1 = Circle.new(0, 0, 1) +puts c2 = Circle.new(2, 4, 2) +puts c3 = Circle.new(4, 0, 1) -p Circle.apollonius(c1, c2, c3) -p Circle.apollonius(c1, c2, c3, -1, -1, -1) +puts Circle.apollonius(c1, c2, c3) +puts Circle.apollonius(c1, c2, c3, -1, -1, -1) diff --git a/Task/Problem-of-Apollonius/VBA/problem-of-apollonius.vba b/Task/Problem-of-Apollonius/VBA/problem-of-apollonius.vba new file mode 100644 index 0000000000..9160392e1f --- /dev/null +++ b/Task/Problem-of-Apollonius/VBA/problem-of-apollonius.vba @@ -0,0 +1,196 @@ +Option Explicit +Option Base 0 + +Private Const intBase As Integer = 0 + +Private Type tPoint + X As Double + Y As Double +End Type +Private Type tCircle + Centre As tPoint + Radius As Double +End Type + +Private Sub sApollonius() + Dim Circle1 As tCircle + Dim Circle2 As tCircle + Dim Circle3 As tCircle + Dim CTanTanTan(intBase + 0 to intBase + 7) As tCircle + + With Circle1 + With .Centre + .X = 0 + .Y = 0 + End With + .Radius = 1 + End With + + With Circle2 + With .Centre + .X = 4 + .Y = 0 + End With + .Radius = 1 + End With + + With Circle3 + With .Centre + .X = 2 + .Y = 4 + End With + .Radius = 2 + End With + + Call fApollonius(Circle1,Circle2,Circle3,CTanTanTan())) + +End Sub + +Public Function fApollonius(ByRef C1 As tCircle, _ + ByRef C2 As tCircle, _ + ByRef C3 As tCircle, _ + ByRef CTanTanTan() As tCircle) As Boolean +' Solves the Problem of Apollonius (finding a circle tangent to three other circles in the plane) +' (x_s - x_1)^2 + (y_s - y_1)^2 = (r_s - Tan_1 * r_1)^2 +' (x_s - x_2)^2 + (y_s - y_2)^2 = (r_s - Tan_2 * r_2)^2 +' (x_s - x_3)^2 + (y_s - y_3)^2 = (r_s - Tan_3 * r_3)^2 +' x_s = M + N * r_s +' y_s = P + Q * r_s + +' Parameters: +' C1, C2, C3 (circles in the problem) +' Tan1 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle1 (C1) +' Tan2 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle2 (C2) +' Tan3 := An indication if the solution should be externally or internally tangent (+1/-1) to Circle3 (C3) + + Dim Tangent(intBase + 0 To intBase + 7, intBase + 0 To intBase + 2) As Integer + Dim lgTangent As Long + Dim Tan1 As Integer + Dim Tan2 As Integer + Dim Tan3 As Integer + + Dim v11 As Double + Dim v12 As Double + Dim v13 As Double + Dim v14 As Double + Dim v21 As Double + Dim v22 As Double + Dim v23 As Double + Dim v24 As Double + Dim w12 As Double + Dim w13 As Double + Dim w14 As Double + Dim w22 As Double + Dim w23 As Double + Dim w24 As Double + + Dim p As Double + Dim Q As Double + Dim M As Double + Dim N As Double + + Dim A As Double + Dim b As Double + Dim c As Double + Dim D As Double + + 'Check if circle centers are colinear + If fColinearPoints(C1.Centre, C2.Centre, C3.Centre) Then + fApollonius = False + Exit Function + End If + + Tangent(intBase + 0, intBase + 0) = -1 + Tangent(intBase + 0, intBase + 1) = -1 + Tangent(intBase + 0, intBase + 2) = -1 + + Tangent(intBase + 1, intBase + 0) = -1 + Tangent(intBase + 1, intBase + 1) = -1 + Tangent(intBase + 1, intBase + 2) = 1 + + Tangent(intBase + 2, intBase + 0) = -1 + Tangent(intBase + 2, intBase + 1) = 1 + Tangent(intBase + 2, intBase + 2) = -1 + + Tangent(intBase + 3, intBase + 0) = -1 + Tangent(intBase + 3, intBase + 1) = 1 + Tangent(intBase + 3, intBase + 2) = 1 + + Tangent(intBase + 4, intBase + 0) = 1 + Tangent(intBase + 4, intBase + 1) = -1 + Tangent(intBase + 4, intBase + 2) = -1 + + Tangent(intBase + 5, intBase + 0) = 1 + Tangent(intBase + 5, intBase + 1) = -1 + Tangent(intBase + 5, intBase + 2) = 1 + + Tangent(intBase + 6, intBase + 0) = 1 + Tangent(intBase + 6, intBase + 1) = 1 + Tangent(intBase + 6, intBase + 2) = -1 + + Tangent(intBase + 7, intBase + 0) = 1 + Tangent(intBase + 7, intBase + 1) = 1 + Tangent(intBase + 7, intBase + 2) = 1 + + For lgTangent = LBound(Tangent) To UBound(Tangent) + Tan1 = Tangent(lgTangent, intBase + 0) + Tan2 = Tangent(lgTangent, intBase + 1) + Tan3 = Tangent(lgTangent, intBase + 2) + + v11 = 2 * (C2.Centre.X - C1.Centre.X) + v12 = 2 * (C2.Centre.Y - C1.Centre.Y) + v13 = (C1.Centre.X * C1.Centre.X) _ + - (C2.Centre.X * C2.Centre.X) _ + + (C1.Centre.Y * C1.Centre.Y) _ + - (C2.Centre.Y * C2.Centre.Y) _ + - (C1.Radius * C1.Radius) _ + + (C2.Radius * C2.Radius) + v14 = 2 * (Tan2 * C2.Radius - Tan1 * C1.Radius) + + v21 = 2 * (C3.Centre.X - C2.Centre.X) + v22 = 2 * (C3.Centre.Y - C2.Centre.Y) + v23 = (C2.Centre.X * C2.Centre.X) _ + - (C3.Centre.X * C3.Centre.X) _ + + (C2.Centre.Y * C2.Centre.Y) _ + - (C3.Centre.Y * C3.Centre.Y) _ + - (C2.Radius * C2.Radius) _ + + (C3.Radius * C3.Radius) + v24 = 2 * ((Tan3 * C3.Radius) - (Tan2 * C2.Radius)) + + w12 = v12 / v11 + w13 = v13 / v11 + w14 = v14 / v11 + + w22 = (v22 / v21) - w12 + w23 = (v23 / v21) - w13 + w24 = (v24 / v21) - w14 + + p = -w23 / w22 + Q = w24 / w22 + M = -(w12 * p) - w13 + N = w14 - (w12 * Q) + + A = (N * N) + (Q * Q) - 1 + b = 2 * ((M * N) - (N * C1.Centre.X) + (p * Q) - (Q * C1.Centre.Y) + (Tan1 * C1.Radius)) + c = (C1.Centre.X * C1.Centre.X) _ + + (M * M) _ + - (2 * M * C1.Centre.X) _ + + (p * p) _ + + (C1.Centre.Y * C1.Centre.Y) _ + - (2 * p * C1.Centre.Y) _ + - (C1.Radius * C1.Radius) + + 'Find a root of a quadratic equation (requires the circle centers not to be e.g. colinear) + D = (b * b) - (4 * A * c) + + With CTanTanTan(lgTangent) + .Radius = (-b - VBA.Sqr(D)) / (2 * A) + .Centre.X = M + (N * .Radius) + .Centre.Y = p + (Q * .Radius) + End With + + Next lgTangent + + fApollonius = True + +End Function diff --git a/Task/Program-name/ALGOL-68/program-name.alg b/Task/Program-name/ALGOL-68/program-name.alg new file mode 100644 index 0000000000..1839c246c1 --- /dev/null +++ b/Task/Program-name/ALGOL-68/program-name.alg @@ -0,0 +1,3 @@ +BEGIN + print ((program idf, newline)) +END diff --git a/Task/Program-name/Julia/program-name.julia b/Task/Program-name/Julia/program-name.julia new file mode 100644 index 0000000000..38548edcc2 --- /dev/null +++ b/Task/Program-name/Julia/program-name.julia @@ -0,0 +1,2 @@ +prog = basename(Base.source_path()) +println("This program file is \"", prog, "\".") diff --git a/Task/Program-name/Liberty-BASIC/program-name-1.liberty b/Task/Program-name/Liberty-BASIC/program-name-1.liberty new file mode 100644 index 0000000000..7756cef189 --- /dev/null +++ b/Task/Program-name/Liberty-BASIC/program-name-1.liberty @@ -0,0 +1,41 @@ +nSize = _MAX_PATH + 2 +lpFilename$ = space$(nSize); chr$(0) + + calldll #kernel32, "GetModuleFileNameA", _ + hModule as ulong, _ + lpFilename$ as ptr, _ + nSize as ulong, _ + result as ulong +lpFilename$ = left$(lpFilename$,result) + +print "Path to LB exe" +print lpFilename$ +print "current program file (:last one on LRU list)" +print getLastLRU$(lbPath$) +end + +Function getLastLRU$(lbPath$) + open lbPath$+"lbasic404.ini" for input as #1 + while not(eof(#1)) + line input #1, a$ + if instr(a$, "recent files")<>0 then [readRecentFiles] + wend + getLastLRU$ = "* Failed: Recent files section not found *" + close #1 + exit function + +[readRecentFiles] + nRecent = val(word$(a$,1)) + 'print "nRecentFiles", nRecent + for i = 1 to nRecent + if eof(#1) then + getLastLRU$ = "* Failed: File ended while in recent files section *" + close #1 + exit function + end if + line input #1, a$ + 'print i, a$ + next + close #1 + getLastLRU$ = a$ +end function diff --git a/Task/Program-name/Liberty-BASIC/program-name-2.liberty b/Task/Program-name/Liberty-BASIC/program-name-2.liberty new file mode 100644 index 0000000000..4cf31db50b --- /dev/null +++ b/Task/Program-name/Liberty-BASIC/program-name-2.liberty @@ -0,0 +1,4 @@ +Path to LB exe +C:\progs\Liberty BASIC v4.04\liberty.exe +current program file (:last one on LRU list) +C:\progs\Liberty BASIC v4.04\untitled.bas diff --git a/Task/Program-name/PowerShell/program-name.psh b/Task/Program-name/PowerShell/program-name.psh new file mode 100644 index 0000000000..51f09945bc --- /dev/null +++ b/Task/Program-name/PowerShell/program-name.psh @@ -0,0 +1,3 @@ +# write this in file +$MyInvocation.MyCommand.Name +# launch with <.\program> diff --git a/Task/Program-name/Rust/program-name-1.rust b/Task/Program-name/Rust/program-name-1.rust index e8b5c77505..e995cac189 100644 --- a/Task/Program-name/Rust/program-name-1.rust +++ b/Task/Program-name/Rust/program-name-1.rust @@ -1,5 +1,3 @@ -// rust 0.8 - fn main() { - println!("Program: {}", std::os::args()[0]); + println!("Program: {}", std::env::args().next().unwrap()); } diff --git a/Task/Program-termination/Befunge/program-termination.bf b/Task/Program-termination/Befunge/program-termination.bf new file mode 100644 index 0000000000..29368684ef --- /dev/null +++ b/Task/Program-termination/Befunge/program-termination.bf @@ -0,0 +1 @@ +_@ diff --git a/Task/Program-termination/Elixir/program-termination-1.elixir b/Task/Program-termination/Elixir/program-termination-1.elixir new file mode 100644 index 0000000000..d54a3b5e05 --- /dev/null +++ b/Task/Program-termination/Elixir/program-termination-1.elixir @@ -0,0 +1 @@ +if rcode != :ok, do: System.halt(1) diff --git a/Task/Program-termination/Elixir/program-termination-2.elixir b/Task/Program-termination/Elixir/program-termination-2.elixir new file mode 100644 index 0000000000..339bc86548 --- /dev/null +++ b/Task/Program-termination/Elixir/program-termination-2.elixir @@ -0,0 +1,3 @@ +exit(:normal) +# or +exit(:shutdown) diff --git a/Task/Program-termination/REXX/program-termination.rexx b/Task/Program-termination/REXX/program-termination-1.rexx similarity index 100% rename from Task/Program-termination/REXX/program-termination.rexx rename to Task/Program-termination/REXX/program-termination-1.rexx diff --git a/Task/Program-termination/REXX/program-termination-2.rexx b/Task/Program-termination/REXX/program-termination-2.rexx new file mode 100644 index 0000000000..fd6b47bb65 --- /dev/null +++ b/Task/Program-termination/REXX/program-termination-2.rexx @@ -0,0 +1,6 @@ +Parse Version v +Say v +Call sub +Say 'Back from sub' +Exit +sub: diff --git a/Task/Pythagorean-triples/Eiffel/pythagorean-triples.e b/Task/Pythagorean-triples/Eiffel/pythagorean-triples.e index 57823906ac..90061b8098 100644 --- a/Task/Pythagorean-triples/Eiffel/pythagorean-triples.e +++ b/Task/Pythagorean-triples/Eiffel/pythagorean-triples.e @@ -1,37 +1,47 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - do - Perimeter:= 100 - from - until - Perimeter>1000000 - loop - pyt_tri(3,4,5) - io.put_string ("There are " +total.out + " triples, below " + Perimeter.out + ". Of which " + prim.out+ " are primitives.%N") - Perimeter:= Perimeter*10 + local + perimeter: INTEGER + do + perimeter := 100 + from + until + perimeter > 1000000 + loop + total := 0 + primitive_triples := 0 + count_pythagorean_triples (3, 4, 5, perimeter) + io.put_string ("There are " + total.out + " triples, below " + perimeter.out + ". Of which " + primitive_triples.out + " are primitives.%N") + perimeter := perimeter * 10 + end end - end - - pyt_tri(a, b, c: INTEGER) - local - p: INTEGER - do - p:= a+b+c - if p<= Perimeter then - prim:= prim+1 - total := total + Perimeter // p - pyt_tri (a+2*(-b+c), 2*(a+c)-b, 2*(a-b+c)+c) - pyt_tri (a+2*(b+c), 2*(a+c)+b, 2*(a+b+c)+c) - pyt_tri (-a+2*(b+c), 2*(-a+c)+b, 2*(-a+b+c)+c) + + count_pythagorean_triples (a, b, c, perimeter: INTEGER) + -- Total count of pythagorean triples and total count of primitve triples below perimeter. + local + p: INTEGER + do + p := a + b + c + if p <= perimeter then + primitive_triples := primitive_triples + 1 + total := total + perimeter // p + count_pythagorean_triples (a + 2 * (- b + c), 2 * (a + c) - b, 2 * (a - b + c) + c, perimeter) + count_pythagorean_triples (a + 2 * (b + c), 2 * (a + c) + b, 2 * (a + b + c) + c, perimeter) + count_pythagorean_triples (- a + 2 * (b + c), 2 * (- a + c) + b, 2 * (- a + b + c) + c, perimeter) + end end - end -Perimeter:INTEGER -prim: INTEGER -total: INTEGER + +feature {NONE} + + primitive_triples: INTEGER + + total: INTEGER + end diff --git a/Task/Pythagorean-triples/Elixir/pythagorean-triples.elixir b/Task/Pythagorean-triples/Elixir/pythagorean-triples.elixir new file mode 100644 index 0000000000..37f15202b4 --- /dev/null +++ b/Task/Pythagorean-triples/Elixir/pythagorean-triples.elixir @@ -0,0 +1,14 @@ +defmodule RC do + def count_triples(limit), do: count_triples(limit,3,4,5) + + defp count_triples(limit, a, b, c) when limit<(a+b+c), do: {0,0} + defp count_triples(limit, a, b, c) do + {p1, t1} = count_triples(limit, a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c) + {p2, t2} = count_triples(limit, a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c) + {p3, t3} = count_triples(limit,-a+2*b+2*c,-2*a+b+2*c,-2*a+2*b+3*c) + {1+p1+p2+p3, div(limit, a+b+c)+t1+t2+t3} + end +end + +list = for n <- 1..8, do: Enum.reduce(1..n, 1, fn(_,acc)->10*acc end) +Enum.each(list, fn n -> IO.inspect {n, RC.count_triples(n)} end) diff --git a/Task/Pythagorean-triples/Julia/pythagorean-triples.julia b/Task/Pythagorean-triples/Julia/pythagorean-triples.julia new file mode 100644 index 0000000000..8e4f8f6130 --- /dev/null +++ b/Task/Pythagorean-triples/Julia/pythagorean-triples.julia @@ -0,0 +1,37 @@ +function primitiven{T<:Integer}(m::T) + 1 < m || return T[] + m != 2 || return T[1] + !isprime(m) || return T[2:2:m-1] + rp = trues(m-1) + if isodd(m) + rp[1:2:m-1] = false + end + for p in keys(factor(m)) + rp[p:p:m-1] = false + end + T[1:m-1][rp] +end + +function pythagoreantripcount{T<:Integer}(plim::T) + primcnt = 0 + fullcnt = 0 + 11 < plim || return (primcnt, fullcnt) + for m in 2:plim + p = 2m^2 + p+2m <= plim || break + for n in primitiven(m) + q = p + 2m*n + q <= plim || break + primcnt += 1 + fullcnt += div(plim, q) + end + end + return (primcnt, fullcnt) +end + +println("Counting Pythagorian Triplets within perimeter limits:") +println(" Limit All Primitive") +for om in 1:10 + (pcnt, fcnt) = pythagoreantripcount(10^om) + println(@sprintf " 10^%02d %11d %9d" om fcnt pcnt) +end diff --git a/Task/Pythagorean-triples/PowerShell/pythagorean-triples.psh b/Task/Pythagorean-triples/PowerShell/pythagorean-triples.psh new file mode 100644 index 0000000000..0cc87cbc06 --- /dev/null +++ b/Task/Pythagorean-triples/PowerShell/pythagorean-triples.psh @@ -0,0 +1,50 @@ +function triples($p) { + if($p -gt 4) { + # ai + bi + ci = pi <= p + # ai < bi < ci --> 3ai < pi <= p and ai + 2bi < pi <= p + $pa = [Math]::Floor($p/3) + 1..$pa | foreach { + $ai = $_ + $pb = [Math]::Floor(($p-$ai)/2) + ($ai+1)..$pb | foreach { + $bi = $_ + $pc = $p-$ai-$bi + ($bi+1)..$pc | where { + $ci = $_ + $pi = $ai + $bi + $ci + $ci*$ci -eq $ai*$ai + $bi*$bi + } | + foreach { + [pscustomobject]@{ + a = "$ai" + b = "$bi" + c = "$ci" + p = "$pi" + } + } + } + } + } + else { + Write-Error "$p is not greater than 4" + } +} +function gcd ($a, $b) { + function pgcd ($n, $m) { + if($n -le $m) { + if($n -eq 0) {$m} + else{pgcd $n ($m%$n)} + } + else {pgcd $m $n} + } + $n = [Math]::Abs($a) + $m = [Math]::Abs($b) + (pgcd $n $m) +} +$triples = (triples 100) + +$coprime = $triples | +where {((gcd $_.a $_.b) -eq 1) -and ((gcd $_.a $_.c) -eq 1) -and ((gcd $_.b $_.c) -eq 1)} + +"There are $(($triples).Count) Pythagorean triples with perimeter no larger than 100 + and $(($coprime).Count) of them are coprime." diff --git a/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx b/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx index bba6601872..081b0f2fe6 100644 --- a/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx +++ b/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx @@ -1,30 +1,28 @@ -/*REXX pgm counts number of Pythagorean triples that exist given a max */ -/* perimeter of N, and also counts how many of them are primitives.*/ -trips=0; prims=0 /*zero # of triples, primatives. */ -parse arg N .; if N=='' then n=100 /*get "N". If none, then assume.*/ +/*REXX program counts number of Pythagorean triples that exist given a max */ +/*────────── perimeter of N, and also counts how many of them are primitives.*/ +trips=0; prims=0 /*set the number of triples, primitives*/ +parse arg N .; if N=='' then n=100 /*N specified? No, then use default. */ - do a=3 to N%3; aa=a*a /*limit side to 1/3 of perimeter.*/ + do a=3 to N%3; aa=a*a /*limit side to 1/3 of the perimeter.*/ - do b=a+1 /*triangle can't be isosceles. */ - ab=a+b /*compute partial perimeter. */ - if ab>=N then iterate a /*a+b≥perimeter? Try different A*/ - aabb=aa+b*b /*compute sum of a² + b² (cheat)*/ + do b=a+1 /*the triangle can't be isosceles. */ + ab=a+b /*compute a partial perimeter (2 sides)*/ + if ab>=N then iterate a /*is a+b ≥ perimeter? Try different A*/ + aabb=aa+b*b /*compute the sum of a²+b² (shortcut)*/ - do c=b+1 /*3rd side: also compute c² */ - if ab+c>N then iterate a /*a+b+c > perimeter? Try diff A.*/ - cc=c*c /*compute C². */ - if cc > aabb then iterate b /*c² > a²+b² ? Try different B.*/ - if cc\==aabb then iterate /*c² ¬= a²+b² ? Try different C.*/ - trips=trips+1 /*eureka. We found a prim triple*/ - prims=prims+(gcd(a,b)==1) /*is this triple a primitive? */ - end /*a*/ + do c=b+1 /*compute the value of the third side. */ + if ab+c>N then iterate a /*is a+b+c > perimeter? Try diff. A.*/ + cc=c*c /*compute the value of C². */ + if cc > aabb then iterate b /*is c² > a²+b² ? Try a different B.*/ + if cc\==aabb then iterate /*is c² ¬= a²+b² ? Try a different C.*/ + trips=trips+1 /*eureka. We found a Pythagorean triple*/ + prims=prims+(gcd(a,b)==1) /*is this triple a primitive triple? */ + end /*c*/ end /*b*/ - end /*c*/ + end /*a*/ -say 'max perimeter =' N, /*show a single line of output. */ - left('',7) "Pythagorean triples =" trips, /*left('',7)≡7 blanks.*/ - left('',7) 'primitives =' prims -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────GCD subroutine──────────────────────*/ -gcd: procedure; parse arg x,y - do until y==0; parse value x//y y with y x; end; return x +_=left('',7) /*for padding the output with 7 blanks.*/ +say 'max perimeter =' N _ "Pythagorean triples =" trips _ 'primitives =' prims +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────────────*/ +gcd: procedure; parse arg x,y; do until y==0; parse value x//y y with y x; end; return x diff --git a/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx b/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx index 8299d48898..febaf6e480 100644 --- a/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx +++ b/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx @@ -1,36 +1,36 @@ -/*REXX pgm counts number of Pythagorean triples that exist given a max */ -/* perimeter of N, and also counts how many of them are primitives.*/ -@.=0; trips=0; prims=0 /*zero some REXX variables. */ -parse arg N .; if N=='' then N=100 /*get "N". If none, then assume.*/ +/*REXX program counts number of Pythagorean triples that exist given a max */ +/*REXX program counts number of Pythagorean triples that exist given a max */ +/*────────── perimeter of N, and also counts how many of them are primitives.*/ +@.=0; trips=0; prims=0 /*define some REXX variables to zero. */ +parse arg N .; if N=='' then n=100 /*N specified? No, then use default. */ - do a=3 to N%3; aa=a*a /*limit side to 1/3 of perimeter.*/ - aEven= a//2==0 /*set var to 1 if A is even.*/ + do a=3 to N%3; aa=a*a /*limit side to 1/3 of the perimeter.*/ + aEven= a//2==0 /*set variable to 1 if A is even. */ - do b=a+1 by 1+aEven /*triangle can't be isosceles. */ - ab=a+b /*compute partial perimeter. */ - if ab>=N then iterate a /*a+b≥perimeter? Try different A*/ - aabb=aa+b*b /*compute sum of a² + b² (cheat)*/ + do b=a+1 by 1+aEven /*the triangle can't be isosceles. */ + ab=a+b /*compute a partial perimeter (2 sides)*/ + if ab>=N then iterate a /*is a+b ≥ perimeter? Try different A*/ + aabb=aa+b*b /*compute the sum of a²+b² (shortcut)*/ - do c=b+1 /*C is the third side of triangle*/ - if aEven then if c//2==0 then iterate - if ab+c>n then iterate a /*a+b+c > perimeter? Try diff A.*/ - cc=c*c /*compute C². */ - if cc > aabb then iterate b /*c² > a²+b² ? Try different B.*/ - if cc\==aabb then iterate /*c² ¬= a²+b² ? Try different C.*/ - if @.a.b.c then iterate /*Is this a duplicate? Try again*/ - trips=trips+1 /*eureka. We found a prim triple*/ - prims=prims+1 /*count this primitive triple. */ + do c=b+1 /*compute the value of the third side. */ + if aEven then if c//2==0 then iterate + if ab+c>n then iterate a /*a+b+c > perimeter? Try different A.*/ + cc=c*c /*compute the value of C². */ + if cc > aabb then iterate b /*is c² > a²+b² ? Try a different B.*/ + if cc\==aabb then iterate /*is c² ¬= a²+b² ? Try a different C.*/ + if @.a.b.c then iterate /*Is this a duplicate? Then try again.*/ + trips=trips+1 /*Eureka! We found a Pythagorean triple*/ + prims=prims+1 /*count this also as a primitive triple*/ - do m=2; am=a*m; bm=b*m; cm=c*m /*gen non-primitives.*/ - if am+bm+cm>N then leave /*is this multiple a triple ? */ - trips=trips+1 /*yuppers, then we found another.*/ - if m//2 then @.am.bm.cm=1 /*don't mark if an even multiple.*/ - end /*m*/ - end /*d*/ - end /*b*/ - end /*a*/ + do m=2; am=a*m; bm=b*m; cm=c*m /*generate non-primitives.*/ + if am+bm+cm>N then leave /*is this multiple Pythagorean triple? */ + trips=trips+1 /*Eureka! We found a Pythagorean triple*/ + @.am.bm.cm=1 /*mark Pythagorean triangle as a triple*/ + end /*m*/ + end /*c*/ + end /*b*/ + end /*a*/ -say 'max perimeter =' N, /*show a single line of output. */ - left('',7) "Pythagorean triples =" trips, /*left('',7)≡7 blanks.*/ - left('',7) 'primitives =' prims - /*stick a fork in it, we're done.*/ +_=left('',7) /*for padding the output with 7 blanks.*/ +say 'max perimeter =' N _ "Pythagorean triples =" trips _ 'primitives =' prims + /*stick a fork in it, we're all done. */ diff --git a/Task/Pythagorean-triples/Ruby/pythagorean-triples.rb b/Task/Pythagorean-triples/Ruby/pythagorean-triples.rb index 093ebdde7f..52a9e9bf47 100644 --- a/Task/Pythagorean-triples/Ruby/pythagorean-triples.rb +++ b/Task/Pythagorean-triples/Ruby/pythagorean-triples.rb @@ -2,17 +2,17 @@ class PythagoranTriplesCounter def initialize(limit) @limit = limit @total = 0 - @primatives = 0 + @primitives = 0 generate_triples(3, 4, 5) end - attr_reader :total, :primatives + attr_reader :total, :primitives private def generate_triples(a, b, c) perim = a + b + c return if perim > @limit - @primatives += 1 + @primitives += 1 @total += @limit / perim generate_triples( a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c) @@ -24,6 +24,6 @@ def generate_triples(a, b, c) perim = 10 while perim <= 100_000_000 c = PythagoranTriplesCounter.new perim - p [perim, c.total, c.primatives] + p [perim, c.total, c.primitives] perim *= 10 end diff --git a/Task/Pythagorean-triples/VBScript/pythagorean-triples.vb b/Task/Pythagorean-triples/VBScript/pythagorean-triples.vb new file mode 100644 index 0000000000..9091371355 --- /dev/null +++ b/Task/Pythagorean-triples/VBScript/pythagorean-triples.vb @@ -0,0 +1,36 @@ +For i=1 To 8 + WScript.StdOut.WriteLine triples(10^i) +Next + +Function triples(pmax) + prim=0 : count=0 : nmax=Sqr(pmax)/2 : n=1 + Do While n <= nmax + m=n+1 : p=2*m*(m+n) + Do While p <= pmax + If gcd(m,n)=1 Then + prim=prim+1 + count=count+Int(pmax/p) + End If + m=m+2 + p=2*m*(m+n) + Loop + n=n+1 + Loop + triples = "Max Perimeter: " & pmax &_ + ", Total: " & count &_ + ", Primitive: " & prim +End Function + +Function gcd(a,b) + c = a : d = b + Do + If c Mod d > 0 Then + e = c Mod d + c = d + d = e + Else + gcd = d + Exit Do + End If + Loop +End Function diff --git a/Task/QR-decomposition/00DESCRIPTION b/Task/QR-decomposition/00DESCRIPTION index 3c8c23f246..64c2e1ba50 100644 --- a/Task/QR-decomposition/00DESCRIPTION +++ b/Task/QR-decomposition/00DESCRIPTION @@ -1,4 +1,4 @@ -Any rectangular m \times n matrix \mathit A can be decomposed to a product of a orthogonal matrix \mathit Q and a upper (right) triangular matrix \mathit R, as described in [[wp:QR decomposition|QR decomposition]]. +Any rectangular m \times n matrix \mathit A can be decomposed to a product of an orthogonal matrix \mathit Q and an upper (right) triangular matrix \mathit R, as described in [[wp:QR decomposition|QR decomposition]]. '''Task''' diff --git a/Task/QR-decomposition/Go/qr-decomposition-1.go b/Task/QR-decomposition/Go/qr-decomposition-1.go new file mode 100644 index 0000000000..94a93f2c4f --- /dev/null +++ b/Task/QR-decomposition/Go/qr-decomposition-1.go @@ -0,0 +1,107 @@ +package main + +import ( + "fmt" + "math" + + "github.com/skelterjohn/go.matrix" +) + +func sign(s float64) float64 { + if s > 0 { + return 1 + } else if s < 0 { + return -1 + } + return 0 +} + +func unitVector(n int) *matrix.DenseMatrix { + vec := matrix.Zeros(n, 1) + vec.Set(0, 0, 1) + return vec +} + +func householder(a *matrix.DenseMatrix) *matrix.DenseMatrix { + m := a.Rows() + s := sign(a.Get(0, 0)) + e := unitVector(m) + u := matrix.Sum(a, matrix.Scaled(e, a.TwoNorm()*s)) + v := matrix.Scaled(u, 1/u.Get(0, 0)) + // (error checking skipped in this solution) + prod, _ := v.Transpose().TimesDense(v) + β := 2 / prod.Get(0, 0) + + prod, _ = v.TimesDense(v.Transpose()) + return matrix.Difference(matrix.Eye(m), matrix.Scaled(prod, β)) +} + +func qr(a *matrix.DenseMatrix) (q, r *matrix.DenseMatrix) { + m := a.Rows() + n := a.Cols() + q = matrix.Eye(m) + + last := n - 1 + if m == n { + last-- + } + for i := 0; i <= last; i++ { + // (copy is only for compatibility with an older version of gomatrix) + b := a.GetMatrix(i, i, m-i, n-i).Copy() + x := b.GetColVector(0) + h := matrix.Eye(m) + h.SetMatrix(i, i, householder(x)) + q, _ = q.TimesDense(h) + a, _ = h.TimesDense(a) + } + return q, a +} + +func main() { + // task 1: show qr decomp of wp example + a := matrix.MakeDenseMatrixStacked([][]float64{ + {12, -51, 4}, + {6, 167, -68}, + {-4, 24, -41}}) + q, r := qr(a) + fmt.Println("q:\n", q) + fmt.Println("r:\n", r) + + // task 2: use qr decomp for polynomial regression example + x := matrix.MakeDenseMatrixStacked([][]float64{ + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}) + y := matrix.MakeDenseMatrixStacked([][]float64{ + {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}}) + fmt.Println("\npolyfit:\n", polyfit(x, y, 2)) +} + +func polyfit(x, y *matrix.DenseMatrix, n int) *matrix.DenseMatrix { + m := x.Cols() + a := matrix.Zeros(m, n+1) + for i := 0; i < m; i++ { + for j := 0; j <= n; j++ { + a.Set(i, j, math.Pow(x.Get(0, i), float64(j))) + } + } + return lsqr(a, y.Transpose()) +} + +func lsqr(a, b *matrix.DenseMatrix) *matrix.DenseMatrix { + q, r := qr(a) + n := r.Cols() + prod, _ := q.Transpose().TimesDense(b) + return solveUT(r.GetMatrix(0, 0, n, n), prod.GetMatrix(0, 0, n, 1)) +} + +func solveUT(r, b *matrix.DenseMatrix) *matrix.DenseMatrix { + n := r.Cols() + x := matrix.Zeros(n, 1) + for k := n - 1; k >= 0; k-- { + sum := 0. + for j := k + 1; j < n; j++ { + sum += r.Get(k, j) * x.Get(j, 0) + } + x.Set(k, 0, (b.Get(k, 0)-sum)/r.Get(k, k)) + } + return x +} diff --git a/Task/QR-decomposition/Go/qr-decomposition-2.go b/Task/QR-decomposition/Go/qr-decomposition-2.go new file mode 100644 index 0000000000..edddab5bb9 --- /dev/null +++ b/Task/QR-decomposition/Go/qr-decomposition-2.go @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + + "github.com/gonum/matrix/mat64" +) + +func main() { + // task 1: show qr decomp of wp example + a := mat64.NewDense(3, 3, []float64{ + 12, -51, 4, + 6, 167, -68, + -4, 24, -41, + }) + var qr mat64.QR + qr.Factorize(a) + var q, r mat64.Dense + q.QFromQR(&qr) + r.RFromQR(&qr) + fmt.Printf("q: %.3f\n\n", mat64.Formatted(&q, mat64.Prefix(" "))) + fmt.Printf("r: %.3f\n\n", mat64.Formatted(&r, mat64.Prefix(" "))) + + // task 2: use qr decomp for polynomial regression example + x := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + y := []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321} + a = Vandermonde(x, 2) + b := mat64.NewDense(11, 1, y) + qr.Factorize(a) + var f mat64.Dense + f.SolveQR(&qr, false, b) + fmt.Printf("polyfit: %.3f\n", + mat64.Formatted(&f, mat64.Prefix(" "))) +} + +func Vandermonde(a []float64, degree int) *mat64.Dense { + x := mat64.NewDense(len(a), degree+1, nil) + for i := range a { + for j, p := 0, 1.; j <= degree; j, p = j+1, p*a[i] { + x.Set(i, j, p) + } + } + return x +} diff --git a/Task/QR-decomposition/Go/qr-decomposition.go b/Task/QR-decomposition/Go/qr-decomposition.go deleted file mode 100644 index 3959bda84c..0000000000 --- a/Task/QR-decomposition/Go/qr-decomposition.go +++ /dev/null @@ -1,106 +0,0 @@ -package main - -import ( - "code.google.com/p/gomatrix/matrix" - "fmt" - "math" -) - -func sign(s float64) float64 { - if s > 0 { - return 1 - } else if s < 0 { - return -1 - } - return 0 -} - -func unitVector(n int) *matrix.DenseMatrix { - vec := matrix.Zeros(n, 1) - vec.Set(0, 0, 1) - return vec -} - -func householder(a *matrix.DenseMatrix) *matrix.DenseMatrix { - m := a.Rows() - s := sign(a.Get(0, 0)) - e := unitVector(m) - u := matrix.Sum(a, matrix.Scaled(e, a.TwoNorm()*s)) - v := matrix.Scaled(u, 1/u.Get(0, 0)) - // (error checking skipped in this solution) - prod, _ := v.Transpose().TimesDense(v) - β := 2 / prod.Get(0, 0) - - prod, _ = v.TimesDense(v.Transpose()) - return matrix.Difference(matrix.Eye(m), matrix.Scaled(prod, β)) -} - -func qr(a *matrix.DenseMatrix) (q, r *matrix.DenseMatrix) { - m := a.Rows() - n := a.Cols() - q = matrix.Eye(m) - - last := n - 1 - if m == n { - last-- - } - for i := 0; i <= last; i++ { - // (copy is only for compatibility with an older version of gomatrix) - b := a.GetMatrix(i, i, m-i, n-i).Copy() - x := b.GetColVector(0) - h := matrix.Eye(m) - h.SetMatrix(i, i, householder(x)) - q, _ = q.TimesDense(h) - a, _ = h.TimesDense(a) - } - return q, a -} - -func main() { - // task 1: show qr decomp of wp example - a := matrix.MakeDenseMatrixStacked([][]float64{ - {12, -51, 4}, - {6, 167, -68}, - {-4, 24, -41}}) - q, r := qr(a) - fmt.Println("q:\n", q) - fmt.Println("r:\n", r) - - // task 2: use qr decomp for polynomial regression example - x := matrix.MakeDenseMatrixStacked([][]float64{ - {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}) - y := matrix.MakeDenseMatrixStacked([][]float64{ - {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}}) - fmt.Println("\npolyfit:\n", polyfit(x, y, 2)) -} - -func polyfit(x, y *matrix.DenseMatrix, n int) *matrix.DenseMatrix { - m := x.Cols() - a := matrix.Zeros(m, n+1) - for i := 0; i < m; i++ { - for j := 0; j <= n; j++ { - a.Set(i, j, math.Pow(x.Get(0, i), float64(j))) - } - } - return lsqr(a, y.Transpose()) -} - -func lsqr(a, b *matrix.DenseMatrix) *matrix.DenseMatrix { - q, r := qr(a) - n := r.Cols() - prod, _ := q.Transpose().TimesDense(b) - return solveUT(r.GetMatrix(0, 0, n, n), prod.GetMatrix(0, 0, n, 1)) -} - -func solveUT(r, b *matrix.DenseMatrix) *matrix.DenseMatrix { - n := r.Cols() - x := matrix.Zeros(n, 1) - for k := n - 1; k >= 0; k-- { - sum := 0. - for j := k + 1; j < n; j++ { - sum += r.Get(k, j) * x.Get(j, 0) - } - x.Set(k, 0, (b.Get(k, 0)-sum)/r.Get(k, k)) - } - return x -} diff --git a/Task/QR-decomposition/Python/qr-decomposition.py b/Task/QR-decomposition/Python/qr-decomposition.py new file mode 100644 index 0000000000..2a1fdd4670 --- /dev/null +++ b/Task/QR-decomposition/Python/qr-decomposition.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 + +import numpy as np + +def qr(A): + m, n = A.shape + Q = np.eye(m) + for i in range(n - (m == n)): + H = np.eye(m) + H[i:, i:] = make_householder(A[i:, i]) + Q = np.dot(Q, H) + A = np.dot(H, A) + return Q, A + +def make_householder(a): + v = a / (a[0] + np.copysign(np.linalg.norm(a), a[0])) + v[0] = 1 + H = np.eye(a.shape[0]) + H -= (2 / np.dot(v, v)) * np.dot(v[:, None], v[None, :]) + return H + +# task 1: show qr decomp of wp example +a = np.array((( + (12, -51, 4), + ( 6, 167, -68), + (-4, 24, -41), +))) + +q, r = qr(a) +print('q:\n', q.round(6)) +print('r:\n', r.round(6)) + +# task 2: use qr decomp for polynomial regression example +def polyfit(x, y, n): + return lsqr(x[:, None]**np.arange(n + 1), y.T) + +def lsqr(a, b): + q, r = qr(a) + _, n = r.shape + return np.linalg.solve(r[:n, :], np.dot(q.T, b)[:n]) + +x = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) +y = np.array((1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)) + +print('\npolyfit:\n', polyfit(x, y, 2)) diff --git a/Task/Quaternion-type/ALGOL-W/quaternion-type.alg b/Task/Quaternion-type/ALGOL-W/quaternion-type.alg new file mode 100644 index 0000000000..975eaf5e2e --- /dev/null +++ b/Task/Quaternion-type/ALGOL-W/quaternion-type.alg @@ -0,0 +1,101 @@ +begin + % Quaternion record type % + record Quaternion ( real a, b, c, d ); + + % returns the norm of the specified quaternion % + real procedure normQ ( reference(Quaternion) value q ) ; + sqrt( (a(q) * a(q)) + (b(q) * b(q)) + (c(q) * c(q)) + (d(q) * d(q)) ); + + % returns the negative of the specified quaternion % + reference(Quaternion) procedure negQ ( reference(Quaternion) value q ) ; + Quaternion( - a(q), - b(q), - c(q), - d(q) ); + + % returns the conjugate of the specified quaternion % + reference(Quaternion) procedure conjQ ( reference(Quaternion) value q ) ; + Quaternion( a(q), - b(q), - c(q), - d(q) ); + + % returns the sum of a real and a quaternion % + reference(Quaternion) procedure addRQ ( real value r + ; reference(Quaternion) value q + ) ; + Quaternion( r + a(q), b(q), c(q), d(q) ); + + % returns the sum of a quaternion and a real % + reference(Quaternion) procedure addQR ( reference(Quaternion) value q + ; real value r + ) ; + Quaternion( r + a(q), b(q), c(q), d(q) ); + + % returns the sum of the specified quaternions % + reference(Quaternion) procedure addQQ ( reference(Quaternion) value q1 + ; reference(Quaternion) value q2 + ) ; + Quaternion( a(q1) + a(q2), b(q1) + b(q2), c(q1) + c(q2), d(q1) + d(q2) ); + + % returns the specified quaternion multiplied by a real % + reference(Quaternion) procedure mulQR ( reference(Quaternion) value q + ; real value r + ) ; + Quaternion( r * a(q), r * b(q), r * c(q), r * d(q) ); + + % returns a real multiplied by the specified quaternion % + reference(Quaternion) procedure mulRQ ( real value r + ; reference(Quaternion) value q + ) ; + mulQR( q, r ); + + % returns the Quaternion product of the specified quaternions % + reference(Quaternion) procedure mulQQ( reference(Quaternion) value q1 + ; reference(Quaternion) value q2 + ) ; + Quaternion( (a(q1) * a(q2)) - (b(q1) * b(q2)) - (c(q1) * c(q2)) - (d(q1) * d(q2)) + , (a(q1) * b(q2)) + (b(q1) * a(q2)) + (c(q1) * d(q2)) - (d(q1) * c(q2)) + , (a(q1) * c(q2)) - (b(q1) * d(q2)) + (c(q1) * a(q2)) + (d(q1) * b(q2)) + , (a(q1) * d(q2)) + (b(q1) * c(q2)) - (c(q1) * b(q2)) + (d(q1) * a(q2)) + ); + + % returns true if the two quaternions are equal, false otherwise % + logical procedure equalQ( reference(Quaternion) value q1 + ; reference(Quaternion) value q2 + ) ; + a(q1) = a(q2) and b(q1) = b(q2) and c(q1) = c(q2) and d(q1) = d(q2); + + % writes a quaternion % + procedure writeonQ( reference(Quaternion) value q ) ; + writeon( "(", a(q), ", ", b(q), ", ", c(q), ", ", d(q), ")" ); + + + % test q1q2 = q2q1 % + reference(Quaternion) q, q1, q2; + + q := Quaternion( 1, 2, 3, 4 ); + q1 := Quaternion( 2, 3, 4, 5 ); + q2 := Quaternion( 3, 4, 5, 6 ); + + % set output format % + s_w := 0; r_format := "A"; r_w := 5; r_d := 1; + + write( " q:" );writeonQ( q ); + write( " q1:" );writeonQ( q1 ); + write( " q2:" );writeonQ( q2 ); + write( "norm q:" );writeon( normQ( q ) ); + write( "norm q1:" );writeon( normQ( q1 ) ); + write( "norm q2:" );writeon( normQ( q2 ) ); + + write( " conj q:" );writeonQ( conjQ( q ) ); + write( " - q:" );writeonQ( negQ( q ) ); + write( " 7 + q:" );writeonQ( addRQ( 7, q ) ); + write( " q + 9:" );writeonQ( addQR( q, 9 ) ); + write( " q + q1:" );writeonQ( addQQ( q, q1 ) ); + write( " 3 * q:" );writeonQ( mulRQ( 3, q ) ); + write( " q * 4:" );writeonQ( mulQR( q, 4 ) ); + + % check that q1q2 not = q2q1 % + if equalQ( mulQQ( q1, q2 ), mulQQ( q2, q1 ) ) + then write( "q1q2 = q2q1 ??" ) + else write( "q1q2 <> q2q1" ); + + write( " q1q2:" );writeonQ( mulQQ( q1, q2 ) ); + write( " q2q1:" );writeonQ( mulQQ( q2, q1 ) ); + +end. diff --git a/Task/Quaternion-type/Common-Lisp/quaternion-type.lisp b/Task/Quaternion-type/Common-Lisp/quaternion-type.lisp new file mode 100644 index 0000000000..fe1fa31d10 --- /dev/null +++ b/Task/Quaternion-type/Common-Lisp/quaternion-type.lisp @@ -0,0 +1,77 @@ +(defclass quaternion () ((a :accessor q-a :initarg :a :type real) + (b :accessor q-b :initarg :b :type real) + (c :accessor q-c :initarg :c :type real) + (d :accessor q-d :initarg :d :type real)) + (:default-initargs :a 0 :b 0 :c 0 :d 0)) + +(defun make-q (&optional (a 0) (b 0) (c 0) (d 0)) + (make-instance 'quaternion :a a :b b :c c :d d)) + +(defgeneric sum (x y)) + +(defmethod sum ((x quaternion) (y quaternion)) + (make-q (+ (q-a x) (q-a y)) + (+ (q-b x) (q-b y)) + (+ (q-c x) (q-c y)) + (+ (q-d x) (q-d y)))) + +(defmethod sum ((x quaternion) (y real)) + (make-q (+ (q-a x) y) (q-b x) (q-c x) (q-d x))) + +(defmethod sum ((x real) (y quaternion)) + (make-q (+ (q-a y) x) (q-b y) (q-c y) (q-d y))) + +(defgeneric sub (x y)) + +(defmethod sub ((x quaternion) (y quaternion)) + (make-q (- (q-a x) (q-a y)) + (- (q-b x) (q-b y)) + (- (q-c x) (q-c y)) + (- (q-d x) (q-d y)))) + +(defmethod sub ((x quaternion) (y real)) + (make-q (- (q-a x) y) + (q-b x) + (q-c x) + (q-d x))) + +(defmethod sub ((x real) (y quaternion)) + (make-q (- (q-a y) x) + (q-b y) + (q-c y) + (q-d y))) + +(defgeneric mul (x y)) + +(defmethod mul ((x quaternion) (y real)) + (make-q (* (q-a x) y) + (* (q-b x) y) + (* (q-c x) y) + (* (q-d x) y))) + +(defmethod mul ((x real) (y quaternion)) + (make-q (* (q-a y) x) + (* (q-b y) x) + (* (q-c y) x) + (* (q-d y) x))) + +(defmethod mul ((x quaternion) (y quaternion)) + (make-q (- (* (q-a x) (q-a y)) (* (q-b x) (q-b y)) (* (q-c x) (q-c y)) (* (q-d x) (q-d y))) + (- (+ (* (q-a x) (q-b y)) (* (q-b x) (q-a y)) (* (q-c x) (q-d y))) (* (q-d x) (q-c y))) + (- (+ (* (q-a x) (q-c y)) (* (q-c x) (q-a y)) (* (q-d x) (q-b y))) (* (q-b x) (q-d y))) + (- (+ (* (q-a x) (q-d y)) (* (q-b x) (q-c y)) (* (q-d x) (q-a y))) (* (q-c x) (q-b y))))) + +(defmethod norm ((x quaternion)) + (+ (sqrt (q-a x)) (sqrt (q-b x)) (sqrt (q-c x)) (sqrt (q-d x)))) + +(defmethod print-object ((x quaternion) stream) + (format stream "~@f~@fi~@fj~@fk" (q-a x) (q-b x) (q-c x) (q-d x))) + +(defvar q (make-q 0 1 0 0)) +(defvar q1 (make-q 0 0 1 0)) +(defvar q2 (make-q 0 0 0 1)) +(defvar r 7) +(format t "q+q1+q2 = ~a~&" (reduce #'sum (list q q1 q2))) +(format t "r*(q+q1+q2) = ~a~&" (mul r (reduce #'sum (list q q1 q2)))) +(format t "q*q1*q2 = ~a~&" (reduce #'mul (list q q1 q2))) +(format t "q-q1-q2 = ~a~&" (reduce #'sub (list q q1 q2))) diff --git a/Task/Quaternion-type/Mercury/quaternion-type-1.mercury b/Task/Quaternion-type/Mercury/quaternion-type-1.mercury new file mode 100644 index 0000000000..1825a13f23 --- /dev/null +++ b/Task/Quaternion-type/Mercury/quaternion-type-1.mercury @@ -0,0 +1,38 @@ +:- module quaternion. + +:- interface. + +:- import_module float. + +:- type quaternion + ---> q( w :: float, + i :: float, + j :: float, + k :: float ). + +% conversion +:- func r(float) = quaternion is det. + +% operations +:- func norm(quaternion) = float is det. +:- func -quaternion = quaternion is det. +:- func conjugate(quaternion) = quaternion is det. +:- func quaternion + quaternion = quaternion is det. +:- func quaternion * quaternion = quaternion is det. + +:- implementation. + +:- import_module math. + +% conversion +r(W) = q(W, 0.0, 0.0, 0.0). + +% operations +norm(q(W, I, J, K)) = math.sqrt(W*W + I*I + J*J + K*K). +-q(W, I, J, K) = q(-W, -I, -J, -K). +conjugate(q(W, I, J, K)) = q(W, -I, -J, -K). +q(W0, I0, J0, K0) + q(W1, I1, J1, K1) = q(W0+W1, I0+I1, J0+J1, K0+K1). +q(W0, I0, J0, K0) * q(W1, I1, J1, K1) = q(W0*W1 - I0*I1 - J0*J1 - K0*K1, + W0*I1 + I0*W1 + J0*K1 - K0*J1, + W0*J1 - I0*K1 + J0*W1 + K0*I1, + W0*K1 + I0*J1 - J0*I1 + K0*W1 ). diff --git a/Task/Quaternion-type/Mercury/quaternion-type-2.mercury b/Task/Quaternion-type/Mercury/quaternion-type-2.mercury new file mode 100644 index 0000000000..de29885af2 --- /dev/null +++ b/Task/Quaternion-type/Mercury/quaternion-type-2.mercury @@ -0,0 +1,76 @@ +:- module test_quaternion. + +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module quaternion. + +:- import_module exception. +:- import_module float. +:- import_module list. +:- import_module string. + +:- func to_string(quaternion) = string is det. + +main(!IO) :- + Q = q(1.0, 2.0, 3.0, 4.0), + Q1 = q(2.0, 3.0, 4.0, 5.0), + Q2 = q(3.0, 4.0, 5.0, 6.0), + R = 7.0, + QR = r(R), + + io.print("Q = ", !IO), io.print(to_string(Q), !IO), io.nl(!IO), + io.print("Q1 = ", !IO), io.print(to_string(Q1), !IO), io.nl(!IO), + io.print("Q2 = ", !IO), io.print(to_string(Q2), !IO), io.nl(!IO), + io.print("R = ", !IO), io.print(R, !IO), io.nl(!IO), + io.nl(!IO), + + io.print("1. The norm of a quaternion.\n", !IO), + io.print("norm(Q) = ", !IO), io.print(norm(Q), !IO), io.nl(!IO), + io.nl(!IO), + + io.print("2. The negative of a quaternion.\n", !IO), + io.print("-Q = ", !IO), io.print(to_string(-Q), !IO), io.nl(!IO), + io.nl(!IO), + + io.print("3. The conjugate of a quaternion.\n", !IO), + io.print("conjugate(Q) = ", !IO), io.print(to_string(conjugate(Q)), !IO), + io.nl(!IO), + io.nl(!IO), + + io.print("4. Addition of a real number and a quaternion.\n", !IO), + ( Q + QR = QR + Q -> io.print("Addition is commutative.\n", !IO) + ; io.print("Addition is not commutative.\n", !IO) ), + io.print("Q + R = ", !IO), io.print(to_string(Q + QR), !IO), io.nl(!IO), + io.print("R + Q = ", !IO), io.print(to_string(QR + Q), !IO), io.nl(!IO), + io.nl(!IO), + + io.print("5. Addition of two quaternions.\n", !IO), + ( Q1 + Q2 = Q2 + Q1 -> io.print("Addition is commutative.\n", !IO) + ; io.print("Addition is not commutative.\n", !IO) ), + io.print("Q1 + Q2 = ", !IO), io.print(to_string(Q1 + Q2), !IO), io.nl(!IO), + io.print("Q2 + Q1 = ", !IO), io.print(to_string(Q2 + Q1), !IO), io.nl(!IO), + io.nl(!IO), + + io.print("6. Multiplication of a real number and a quaternion.\n", !IO), + ( Q * QR = QR * Q -> io.print("Multiplication is commutative.\n", !IO) + ; io.print("Multiplication is not commutative.\n", !IO) ), + io.print("Q * R = ", !IO), io.print(to_string(Q * QR), !IO), io.nl(!IO), + io.print("R * Q = ", !IO), io.print(to_string(QR * Q), !IO), io.nl(!IO), + io.nl(!IO), + + io.print("7. Multiplication of two quaternions.\n", !IO), + ( Q1 * Q2 = Q2 * Q1 -> io.print("Multiplication is commutative.\n", !IO) + ; io.print("Multiplication is not commutative.\n", !IO) ), + io.print("Q1 * Q2 = ", !IO), io.print(to_string(Q1 * Q2), !IO), io.nl(!IO), + io.print("Q2 * Q1 = ", !IO), io.print(to_string(Q2 * Q1), !IO), io.nl(!IO), + io.nl(!IO). + +to_string(q(I, J, K, W)) = string.format("q(%f, %f, %f, %f)", + [f(I), f(J), f(K), f(W)]). +:- end_module test_quaternion. diff --git a/Task/Quaternion-type/OCaml/quaternion-type-1.ocaml b/Task/Quaternion-type/OCaml/quaternion-type-1.ocaml index 9333faeb40..8c2c790e70 100644 --- a/Task/Quaternion-type/OCaml/quaternion-type-1.ocaml +++ b/Task/Quaternion-type/OCaml/quaternion-type-1.ocaml @@ -1,49 +1,64 @@ -type quaternion = float * float * float * float +type quaternion = {a: float; b: float; c: float; d: float} -let q a b c d = (a, b, c, d) +let norm q = sqrt (q.a**2.0 +. + q.b**2.0 +. + q.c**2.0 +. + q.d**2.0 ) -let to_real (r, _, _, _) = r -let imag (_, i, j, k) = (i, j, k) +let floatneg r = ~-. r (* readability *) -let quaternion_of_scalar s = (s, 0.0, 0.0, 0.0) +let negative q = + {a = floatneg q.a; + b = floatneg q.b; + c = floatneg q.c; + d = floatneg q.d } -let to_list (a, b, c, d) = [a; b; c; d] -let of_list = function [a; b; c; d] -> (a, b, c, d) - | _ -> invalid_arg "of_list" +let conjugate q = + {a = q.a; + b = floatneg q.b; + c = floatneg q.c; + d = floatneg q.d } -let ( + ) = ( +. ) -let ( - ) = ( -. ) -let ( * ) = ( *. ) -let ( / ) = ( /. ) +let addrq r q = {q with a = q.a +. r} -let addr (a, b, c, d) r = (a+r, b, c, d) -let mulr (a, b, c, d) r = (a*r, b*r, c*r, d*r) +let addq q1 q2 = + {a = q1.a +. q2.a; + b = q1.b +. q2.b; + c = q1.c +. q2.c; + d = q1.d +. q2.d } -let add (a, b, c, d) (p, q, r, s) = (a+p, b+q, c+r, d+s) +let multrq r q = + {a = q.a *. r; + b = q.b *. r; + c = q.c *. r; + d = q.d *. r } -let sub (a, b, c, d) (p, q, r, s) = (a-p, b-q, c-r, d-s) +let multq q1 q2 = + {a = q1.a*.q2.a -. q1.b*.q2.b -. q1.c*.q2.c -. q1.d*.q2.d; + b = q1.a*.q2.b +. q1.b*.q2.a +. q1.c*.q2.d -. q1.d*.q2.c; + c = q1.a*.q2.c -. q1.b*.q2.d +. q1.c*.q2.a +. q1.d*.q2.b; + d = q1.a*.q2.d +. q1.b*.q2.c -. q1.c*.q2.b +. q1.d*.q2.a } -let mul (a, b, c, d) (p, q, r, s) = - ( a*p - b*q - c*r - d*s, - a*q + b*p + c*s - d*r, - a*r - b*s + c*p + d*q, - a*s + b*r - c*q + d*p ) +let qmake a b c d = {a;b;c;d} (* readability omitting a= b=... *) -let norm2 (a, b, c, d) = - ( a * a + - b * b + - c * c + - d * d ) +let qstring q = + Printf.sprintf "(%g, %g, %g, %g)" q.a q.b q.c q.d ;; -let norm q = sqrt(norm2 q) +(* test data *) +let q = qmake 1.0 2.0 3.0 4.0 +let q1 = qmake 2.0 3.0 4.0 5.0 +let q2 = qmake 3.0 4.0 5.0 6.0 +let r = 7.0 -let conj (a, b, c, d) = (a, -. b, -. c, -. d) -let neg (a, b, c, d) = (-. a, -. b, -. c, -. d) - -let unit ((a, b, c, d) as q) = - let n = norm q in - (a/n, b/n, c/n, d/n) - -let reciprocal ((a, b, c, d) as q) = - let n2 = norm2 q in - (a/n2, b/n2, c/n2, d/n2) +let () = (* written strictly to spec *) + let pf = Printf.printf in + pf "starting with data q=%s, q1=%s, q2=%s, r=%g\n" (qstring q) (qstring q1) (qstring q2) r; + pf "1. norm of q = %g \n" (norm q) ; + pf "2. negative of q = %s \n" (qstring (negative q)); + pf "3. conjugate of q = %s \n" (qstring (conjugate q)); + pf "4. adding r to q = %s \n" (qstring (addrq r q)); + pf "5. adding q1 and q2 = %s \n" (qstring (addq q1 q2)); + pf "6. multiply r and q = %s \n" (qstring (multrq r q)); + pf "7. multiply q1 and q2 = %s \n" (qstring (multq q1 q2)); + pf "8. instead q2 * q1 = %s \n" (qstring (multq q2 q1)); + pf "\n"; diff --git a/Task/Quaternion-type/OCaml/quaternion-type-2.ocaml b/Task/Quaternion-type/OCaml/quaternion-type-2.ocaml index f11050fa11..d02cc259ca 100644 --- a/Task/Quaternion-type/OCaml/quaternion-type-2.ocaml +++ b/Task/Quaternion-type/OCaml/quaternion-type-2.ocaml @@ -1,18 +1,11 @@ -type quaternion = float * float * float * float - -val q : float -> float -> float -> float -> quaternion -val to_real : quaternion -> float -val imag : quaternion -> float * float * float -val quaternion_of_scalar : float -> quaternion -val to_list : quaternion -> float list -val of_list : float list -> quaternion -val addr : quaternion -> float -> quaternion -val mulr : quaternion -> float -> quaternion -val add : quaternion -> quaternion -> quaternion -val sub : quaternion -> quaternion -> quaternion -val mul : quaternion -> quaternion -> quaternion -val norm : quaternion -> float -val conj : quaternion -> quaternion -val neg : quaternion -> quaternion -val unit : quaternion -> quaternion -val reciprocal : quaternion -> quaternion +type quaternion = { a : float; b : float; c : float; d : float; } +val norm : quaternion -> float = +val floatneg : float -> float = +val negative : quaternion -> quaternion = +val conjugate : quaternion -> quaternion = +val addrq : float -> quaternion -> quaternion = +val addq : quaternion -> quaternion -> quaternion = +val multrq : float -> quaternion -> quaternion = +val multq : quaternion -> quaternion -> quaternion = +val qmake : float -> float -> float -> float -> quaternion = +val qstring : quaternion -> string = diff --git a/Task/Quaternion-type/REXX/quaternion-type.rexx b/Task/Quaternion-type/REXX/quaternion-type.rexx index 6e652d4654..331299b6c3 100644 --- a/Task/Quaternion-type/REXX/quaternion-type.rexx +++ b/Task/Quaternion-type/REXX/quaternion-type.rexx @@ -1,48 +1,45 @@ -/*REXX program to perform simple operations of quaternion type numbers.*/ - q = 1 2 3 4 ; q1 = 2 3 4 5 - r = 7 ; q2 = 3 4 5 6 -call quatShow q , 'q' -call quatShow q1 , 'q1' -call quatShow q2 , 'q2' -call quatShow r , 'r' -call quatShow quatNorm(q) , 'norm q' , "task 1:" -call quatShow quatNeg(q) , 'negative q' , "task 2:" -call quatShow quatConj(q) , 'conjugate q' , "task 3:" -call quatShow quatAdd( r, q ) , 'addition r+q' , "task 4:" -call quatShow quatAdd(q1, q2 ) , 'addition q1+q2' , "task 5:" -call quatShow quatMul( q, r ) , 'multiplication q*r' , "task 6:" -call quatShow quatMul(q1, q2 ) , 'multiplication q1*q2' , "task 7:" -call quatShow quatMul(q2, q1 ) , 'multiplication q2*q1' , "task 8:" -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────QUATADD─────────────────────────────*/ -quatAdd: procedure; parse arg x,y; call quatXY 2 -return x.1+y.1 x.2+y.2 x.3+y.3 x.4+y.4 -/*──────────────────────────────────QUATCONJ────────────────────────────*/ -quatConj: procedure; parse arg x; call quatXY -return x.1 (-x.2) (-x.3) (-x.4) -/*──────────────────────────────────QUATMUL─────────────────────────────*/ -quatMul: procedure; parse arg x,y; call quatXY y -return x.1*y.1-x.2*y.2-x.3*y.3-x.4*y.4 x.1*y.2+x.2*y.1+x.3*y.4-x.4*y.3, - x.1*y.3-x.2*y.4+x.3*y.1+x.4*y.2 x.1*y.4+x.2*y.3-x.3*y.2+x.4*y.1 -/*──────────────────────────────────QUATNEG─────────────────────────────*/ -quatNeg: procedure; parse arg x; call quatXY -return -x.1 (-x.2) (-x.3) (-x.4) -/*──────────────────────────────────QUATNORM────────────────────────────*/ -quatNorm: procedure; parse arg x; call quatXY -return sqrt(x.1**2 + x.2**2 + x.3**2 + x.4**2) -/*──────────────────────────────────QUATSHOW────────────────────────────*/ -quatShow: procedure; parse arg x; call quatXY; quat= - do m=1 for 4; _=x.m; if _==0 then iterate; if _ >=0 then _='+'_ - if m\==1 then _=_||substr('~ijk',m,1) ; quat=strip(quat || _,,'+') - end /*m*/ -say left(arg(3),9) right(arg(2),20) ' ──► ' quat -return quat -/*──────────────────────────────────QUATXY──────────────────────────────*/ -quatXY: do n=1 for 4; x.n=word(word(x,n) 0,1)/1; end /*n*/ -if arg()==1 then do m=1 for 4; y.m=word(word(y,m) 0,1)/1; end /*m*/ -return -/*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure;parse arg x;if x=0 then return 0;d=digits();numeric digits 11 -m.=11;numeric form;p=d+d%4+2;parse value format(x,2,1,,0) 'E0' with g 'E' _ . -g=g*.5'E'_%2; do j=0 while p>9; m.j=p; p=p%2+1; end; 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 +/*REXX pgm performs some operations on quaternion type numbers and shows results*/ + q = 1 2 3 4 ; q1 = 2 3 4 5 + r = 7 ; q2 = 3 4 5 6 +call qShow q , 'q' +call qShow q1 , 'q1' +call qShow q2 , 'q2' +call qShow r , 'r' +call qShow qNorm(q) , 'norm q' , "task 1:" +call qShow qNeg(q) , 'negative q' , "task 2:" +call qShow qConj(q) , 'conjugate q' , "task 3:" +call qShow qAdd( r, q ) , 'addition r+q' , "task 4:" +call qShow qAdd(q1, q2 ) , 'addition q1+q2' , "task 5:" +call qShow qMul( q, r ) , 'multiplication q*r' , "task 6:" +call qShow qMul(q1, q2 ) , 'multiplication q1*q2' , "task 7:" +call qShow qMul(q2, q1 ) , 'multiplication q2*q1' , "task 8:" +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────*/ +qConj: procedure; parse arg x; call qXY; return x.1 (-x.2) (-x.3) (-x.4) +qNeg: procedure; parse arg x; call qXY; return -x.1 (-x.2) (-x.3) (-x.4) +/*──────────────────────────────────────────────────────────────────────────────*/ +qAdd: procedure; parse arg x,y; call qXY 2; return x.1+y.1 x.2+y.2 x.3+y.3 x.4+y.4 +/*──────────────────────────────────────────────────────────────────────────────*/ +qMul: procedure; parse arg x,y; call qXY y + return x.1*y.1-x.2*y.2-x.3*y.3-x.4*y.4 x.1*y.2+x.2*y.1+x.3*y.4-x.4*y.3, + x.1*y.3-x.2*y.4+x.3*y.1+x.4*y.2 x.1*y.4+x.2*y.3-x.3*y.2+x.4*y.1 +/*──────────────────────────────────────────────────────────────────────────────*/ +qNorm: procedure; parse arg x; call qXY; return sqrt(x.1**2+x.2**2+x.3**2+x.4**2) +/*──────────────────────────────────────────────────────────────────────────────*/ +qShow: procedure; parse arg x; call qXY; $= + do m=1 for 4; _=x.m; if _==0 then iterate; if _>=0 then _='+'_ + if m\==1 then _=_ || substr('~ijk',m,1); $=strip($ || _,,'+') + end /*m*/ + say left(arg(3),9) right(arg(2),20) ' ──► ' $ + return $ +/*──────────────────────────────────────────────────────────────────────────────*/ +qXY: do n=1 for 4; x.n=word(word(x,n) 0,1)/1; end /*n*/ + if arg()==1 then do m=1 for 4; y.m=word(word(y,m) 0,1)/1; end /*m*/ + return +/*──────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0. */ diff --git a/Task/Queue-Definition/C/queue-definition-1.c b/Task/Queue-Definition/C/queue-definition-1.c index c91306c380..d13e87f1ed 100644 --- a/Task/Queue-Definition/C/queue-definition-1.c +++ b/Task/Queue-Definition/C/queue-definition-1.c @@ -25,7 +25,9 @@ void enqueue(queue q, DATA n) { if (q->tail >= q->alloc) q->tail = 0; q->buf[q->tail++] = n; - if (q->tail == q->head) { /* needs more room */ + + // Fixed bug where it failed to resizes + if (q->tail == q->alloc) { /* needs more room */ q->buf = realloc(q->buf, sizeof(DATA) * q->alloc * 2); if (q->head) { memcpy(q->buf + q->head + q->alloc, q->buf + q->head, diff --git a/Task/Queue-Definition/Elixir/queue-definition.elixir b/Task/Queue-Definition/Elixir/queue-definition.elixir new file mode 100644 index 0000000000..6c86bb2b6d --- /dev/null +++ b/Task/Queue-Definition/Elixir/queue-definition.elixir @@ -0,0 +1,12 @@ +defmodule Queue do + def new, do: {Queue, [], []} + + def push({Queue, input, output}, x), do: {Queue, [x|input], output} + + def pop({Queue, [], []}), do: (raise RuntimeError, message: "empty Queue") + def pop({Queue, input, []}), do: pop({Queue, [], Enum.reverse(input)}) + def pop({Queue, input, [h|t]}), do: {h, {Queue, input, t}} + + def empty?({Queue, [], []}), do: true + def empty?({Queue, _, _}), do: false +end diff --git a/Task/Queue-Definition/Julia/queue-definition.julia b/Task/Queue-Definition/Julia/queue-definition.julia new file mode 100644 index 0000000000..d7fd7ba884 --- /dev/null +++ b/Task/Queue-Definition/Julia/queue-definition.julia @@ -0,0 +1,24 @@ +type Queue{T} + a::Array{T,1} +end + +Queue() = Queue(Any[]) +Queue(a::DataType) = Queue(a[]) +Queue(a) = Queue(typeof(a)[]) + +Base.isempty(q::Queue) = isempty(q.a) + +function Base.pop!{T}(q::Queue{T}) + !isempty(q) || error("queue must be non-empty") + pop!(q.a) +end + +function Base.push!{T}(q::Queue{T}, x::T) + unshift!(q.a, x) + return q +end + +function Base.push!{T}(q::Queue{Any}, x::T) + unshift!(q.a, x) + return q +end diff --git a/Task/Queue-Usage/PowerShell/queue-usage.psh b/Task/Queue-Usage/PowerShell/queue-usage.psh new file mode 100644 index 0000000000..33e1b32e85 --- /dev/null +++ b/Task/Queue-Usage/PowerShell/queue-usage.psh @@ -0,0 +1,26 @@ +[System.Collections.ArrayList]$queue = @() +# isEmpty? +if ($queue.Count -eq 0) { + "isEmpty? result : the queue is empty" +} else { + "isEmpty? result : the queue is not empty" +} +"the queue contains : $queue" +$queue += 1 # push +"push result : $queue" +$queue += 2 # push +$queue += 3 # push +"push result : $queue" + +$queue.RemoveAt(0) # pop +"pop result : $queue" + +$queue.RemoveAt(0) # pop +"pop result : $queue" + +if ($queue.Count -eq 0) { + "isEmpty? result : the queue is empty" +} else { + "isEmpty? result : the queue is not empty" +} +"the queue contains : $queue" diff --git a/Task/Quickselect-algorithm/Common-Lisp/quickselect-algorithm.lisp b/Task/Quickselect-algorithm/Common-Lisp/quickselect-algorithm.lisp new file mode 100644 index 0000000000..570d15f77a --- /dev/null +++ b/Task/Quickselect-algorithm/Common-Lisp/quickselect-algorithm.lisp @@ -0,0 +1,13 @@ +(defun quickselect (n _list) + (let* ((ys (remove-if (lambda (x) (< (car _list) x)) (cdr _list))) + (zs (remove-if-not (lambda (x) (< (car _list) x)) (cdr _list))) + (l (length ys)) + ) + (cond ((< n l) (quickselect n ys)) + ((> n l) (quickselect (- n l 1) zs)) + (t (car _list))) + ) + ) + +(defparameter a '(9 8 7 6 5 0 1 2 3 4)) +(format t "~a~&" (mapcar (lambda (x) (quickselect x a)) (loop for i from 0 below (length a) collect i))) diff --git a/Task/Quickselect-algorithm/Erlang/quickselect-algorithm.erl b/Task/Quickselect-algorithm/Erlang/quickselect-algorithm.erl new file mode 100644 index 0000000000..272541f2b6 --- /dev/null +++ b/Task/Quickselect-algorithm/Erlang/quickselect-algorithm.erl @@ -0,0 +1,26 @@ + %% @author Salvador Tamarit + +-module(quickselect). + +-export([test/0]). + + +test() -> + V = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4], + lists:map( + fun(I) -> quickselect(I,V) end, + lists:seq(0, length(V) - 1) + ). + +quickselect(K, [X | Xs]) -> + {Ys, Zs} = + lists:partition(fun(E) -> E < X end, Xs), + L = length(Ys), + if + K < L -> + quickselect(K, Ys); + K > L -> + quickselect(K - L - 1, Zs); + true -> + X + end. diff --git a/Task/Quickselect-algorithm/REXX/quickselect-algorithm-1.rexx b/Task/Quickselect-algorithm/REXX/quickselect-algorithm-1.rexx new file mode 100644 index 0000000000..08ac4a8dc7 --- /dev/null +++ b/Task/Quickselect-algorithm/REXX/quickselect-algorithm-1.rexx @@ -0,0 +1,30 @@ +/*REXX pgm sorts a list (which may be numbers) using quick select algorithm.*/ +parse arg list; if list='' then list=9 8 7 6 5 0 1 2 3 4 /*use the default?*/ + do #=1 for words(list); @.#=word(list,#) /*assign item──►@.*/ + end /*#*/ /* [↑] #: number of items in the list*/ +#=#-1 /*adjust number of items in the list. */ + do j=1 for # /*show 1 ──► # of items place and value*/ + say right('item',20) right(j,length(#))", value: " qSel(1,#,j) + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────QPART subroutine──────────────────────────*/ +qPart: procedure expose @.; parse arg L 1 ?,R,X; xVal = @.X +parse value @.X @.R with @.R @.X /*swap the two names items (X and R). */ + do k=L to R-1 /*process the left side of the list. */ + if @.k>xVal then iterate /*when an item > item #X, then skip it.*/ + parse value @.? @.k with @.k @.? /*swap the two named items (? and K). */ + ?=?+1 /*bump the item number (point to next)*/ + end /*k*/ +parse value @.R @.? with @.? @.R /*swap the two named items (R and ?). */ +return ? /*return item num.*/ +/*──────────────────────────────────QSEL subroutine───────────────────────────*/ +qSel: procedure expose @.; parse arg L,R,z; if L==R then return @.L /*one?*/ + do forever /*keep searching until we're all done. */ + new=qPart(L, R, (L+R)%2) /*partition the list into roughly ½. */ + dist=new-L+1 /*calculate the pivot distance less L+1*/ + if dist==z then return @.new /*we're all done with this pivot part. */ + else if zxVal then iterate /*when an item > item #X, then skip it.*/ + call swap ?,k /*swap the two named items (? and K). */ + ?=?+1 /*bump item number we're working with. */ + end /*k*/ +call swap R,? /*swap the two named items (R and ?). */ +return ? /*return item num.*/ +/*──────────────────────────────────QSEL subroutine───────────────────────────*/ +qSel: procedure expose @.; parse arg L,R,z; if L==R then return @.L /*one?*/ + do forever /*keep searching until we're all done. */ + new=qPart(L, R, (L+R)%2) /*partition the list into roughly ½. */ + dist=new-L+1 /*calculate the pivot distance less L+1*/ + if dist==z then return @.new /*we're all done with this pivot part. */ + else if zpVal 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 zSee the nostalgia note under Fortran. + +'''Next to the Quines presented here, many other versions can be found on the [http://www.nyx.net/~gthompso/quine.htm Quine] page.''' diff --git a/Task/Quine/AWK/quine-1.awk b/Task/Quine/AWK/quine-1.awk new file mode 100644 index 0000000000..8e1935f5bf --- /dev/null +++ b/Task/Quine/AWK/quine-1.awk @@ -0,0 +1 @@ +BEGIN{c="BEGIN{c=%c%s%c;printf(c,34,c,34);}";printf(c,34,c,34);} diff --git a/Task/Quine/AWK/quine-2.awk b/Task/Quine/AWK/quine-2.awk new file mode 100644 index 0000000000..908b960a36 --- /dev/null +++ b/Task/Quine/AWK/quine-2.awk @@ -0,0 +1 @@ +BEGIN{c="BEGIN{c=%c%s%c;printf c,34,c,34}";printf c,34,c,34} diff --git a/Task/Quine/Haskell/quine-6.hs b/Task/Quine/Haskell/quine-6.hs new file mode 100644 index 0000000000..ef71c47ca6 --- /dev/null +++ b/Task/Quine/Haskell/quine-6.hs @@ -0,0 +1 @@ +main = putStrLn $ (++) <*> show $ "main = putStrLn $ (++) <*> show $ " diff --git a/Task/Quine/Logo/quine.logo b/Task/Quine/Logo/quine.logo new file mode 100644 index 0000000000..78c7faf3c4 --- /dev/null +++ b/Task/Quine/Logo/quine.logo @@ -0,0 +1,6 @@ +make "a [ 116 121 112 101 32 34 124 109 97 107 101 32 34 97 32 91 124 10 102 111 114 101 97 99 104 32 58 97 32 91 32 116 121 112 101 32 119 111 114 100 32 34 124 32 124 32 63 32 93 10 112 114 105 110 116 32 34 124 32 93 124 10 102 111 114 101 97 99 104 32 58 97 32 91 32 116 121 112 101 32 99 104 97 114 32 63 32 93 10 98 121 101 10 ] +type "|make "a [| +foreach :a [ type word "| | ? ] +print "| ]| +foreach :a [ type char ? ] +bye diff --git a/Task/Quine/NewLISP/quine.newlisp b/Task/Quine/NewLISP/quine.newlisp new file mode 100644 index 0000000000..870627ddc1 --- /dev/null +++ b/Task/Quine/NewLISP/quine.newlisp @@ -0,0 +1 @@ +(lambda (s) (print (list s (list 'quote s)))) diff --git a/Task/Quine/Prolog/quine-3.pro b/Task/Quine/Prolog/quine-3.pro new file mode 100644 index 0000000000..412ebf5ae8 --- /dev/null +++ b/Task/Quine/Prolog/quine-3.pro @@ -0,0 +1,111 @@ +% Tested with SWI-Prolog version 7.1.37 +:- initialization(main). + +before(Lines) :- Lines = [ + "% Tested with SWI-Prolog version 7.1.37", + ":- initialization(main).", + "", + "before(Lines) :- Lines = [" +]. + +after(Lines) :- Lines = [ + "].", + "", + "% replaces quotes by harmless ats", + "% replaces backslashes by harmless slashes", + "% replaces linebreaks by harmless sharps", + "maskCode(34, 64).", + "maskCode(92, 47).", + "maskCode(10, 35).", + "maskCode(X, X).", + "", + "% Encodes dangerous characters in a string", + "encode(D, S) :- ", + " string_codes(D, DC),", + " maplist(maskCode, DC, SC),", + " string_codes(S, SC).", + "", + "decode(S, D) :- ", + " string_codes(S, SC),", + " maplist(maskCode, DC, SC),", + " string_codes(D, DC).", + "", + "% writes each entry indented by two spaces,", + "% enclosed in quotes and separated by commas,", + "% with a newline between the list entries.", + "mkStringList([],@@).", + "mkStringList([Single],Out) :-", + " atomics_to_string([@ /@@, Single, @/@@], Out).", + "", + "mkStringList([H|T], Res) :-", + " mkStringList(T, TailRes),", + " atomics_to_string([@ /@@, H, @/@,/n@, TailRes], Res).", + "", + "quine(Q) :- ", + " before(BeforeEncoded),", + " after(AfterEncoded),", + " maplist(decode, BeforeEncoded, BeforeDecoded),", + " maplist(decode, AfterEncoded, AfterDecoded),", + " atomic_list_concat(BeforeDecoded, @/n@, B),", + " atomic_list_concat(AfterDecoded, @/n@, A),", + " mkStringList(BeforeEncoded, BeforeData),", + " mkStringList(AfterEncoded, AfterData),", + " Center = @/n]./n/nafter(Lines) :- Lines = [/n@,", + " atomic_list_concat([", + " B, @/n@, BeforeData, ", + " Center, ", + " AfterData, @/n@, A, @/n@", + " ], Q).", + "", + "main :- (quine(Q), write(Q);true),halt.", + "% line break in the end of file is important" +]. + +% replaces quotes by harmless ats +% replaces backslashes by harmless slashes +% replaces linebreaks by harmless sharps +maskCode(34, 64). +maskCode(92, 47). +maskCode(10, 35). +maskCode(X, X). + +% Encodes dangerous characters in a string +encode(D, S) :- + string_codes(D, DC), + maplist(maskCode, DC, SC), + string_codes(S, SC). + +decode(S, D) :- + string_codes(S, SC), + maplist(maskCode, DC, SC), + string_codes(D, DC). + +% writes each entry indented by two spaces, +% enclosed in quotes and separated by commas, +% with a newline between the list entries. +mkStringList([],""). +mkStringList([Single],Out) :- + atomics_to_string([" \"", Single, "\""], Out). + +mkStringList([H|T], Res) :- + mkStringList(T, TailRes), + atomics_to_string([" \"", H, "\",\n", TailRes], Res). + +quine(Q) :- + before(BeforeEncoded), + after(AfterEncoded), + maplist(decode, BeforeEncoded, BeforeDecoded), + maplist(decode, AfterEncoded, AfterDecoded), + atomic_list_concat(BeforeDecoded, "\n", B), + atomic_list_concat(AfterDecoded, "\n", A), + mkStringList(BeforeEncoded, BeforeData), + mkStringList(AfterEncoded, AfterData), + Center = "\n].\n\nafter(Lines) :- Lines = [\n", + atomic_list_concat([ + B, "\n", BeforeData, + Center, + AfterData, "\n", A, "\n" + ], Q). + +main :- (quine(Q), write(Q);true),halt. +% line break in the end of file is important diff --git a/Task/Quine/Racket/quine.rkt b/Task/Quine/Racket/quine-1.rkt similarity index 100% rename from Task/Quine/Racket/quine.rkt rename to Task/Quine/Racket/quine-1.rkt diff --git a/Task/Quine/Racket/quine-2.rkt b/Task/Quine/Racket/quine-2.rkt new file mode 100644 index 0000000000..e646601507 --- /dev/null +++ b/Task/Quine/Racket/quine-2.rkt @@ -0,0 +1,3 @@ +#lang racket +((λ(x)(printf "#lang racket\n(~a\n ~s)" x x)) + "(λ(x)(printf \"#lang racket\\n(~a\\n ~s)\" x x))") diff --git a/Task/Quine/Rust/quine-1.rust b/Task/Quine/Rust/quine-1.rust index 88df728796..8e71d160ec 100644 --- a/Task/Quine/Rust/quine-1.rust +++ b/Task/Quine/Rust/quine-1.rust @@ -1,59 +1,7 @@ -fn main() -{ - let q = 34u8; - let p = 44u8; - let l = [ - "fn main()", - "{", - " let q = 34u8;", - " let p = 44u8;", - " let l = [", - " ", - " ];", - " let mut i = 0;", - " while i < 5", - " {", - " println(l[i]);", - " i+=1;", - " }", - " i = 0;", - " while i < l.len()", - " {", - " print(l[5]);", - " print((q as char).to_str());", - " print(l[i]);", - " print((q as char).to_str());", - " println((p as char).to_str());", - " i+=1;", - " }", - " i = 6;", - " while i < l.len()", - " {", - " println(l[i]);", - " i+=1;", - " }", - "}", - ]; - let mut i = 0; - while i < 5 - { - println(l[i]); - i+=1; - } - i = 0; - while i < l.len() - { - print(l[5]); - print((q as char).to_str()); - print(l[i]); - print((q as char).to_str()); - println((p as char).to_str()); - i+=1; - } - i = 6; - while i < l.len() - { - println(l[i]); - i+=1; - } +fn main() { + let x = "fn main() {\n let x = "; + let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}\n"; + print!("{}{:?}; + let y = {:?}; + {}", x, x, y, y) } diff --git a/Task/Quine/Rust/quine-2.rust b/Task/Quine/Rust/quine-2.rust index 1c84e334c8..88df728796 100644 --- a/Task/Quine/Rust/quine-2.rust +++ b/Task/Quine/Rust/quine-2.rust @@ -1,8 +1,59 @@ -extern crate debug; -fn main() { - let x = "extern crate debug;\nfn main() {\n let x = "; - let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}"; - print!("{}{:?}; - let y = {:?}; - {}", x, x, y, y) +fn main() +{ + let q = 34u8; + let p = 44u8; + let l = [ + "fn main()", + "{", + " let q = 34u8;", + " let p = 44u8;", + " let l = [", + " ", + " ];", + " let mut i = 0;", + " while i < 5", + " {", + " println(l[i]);", + " i+=1;", + " }", + " i = 0;", + " while i < l.len()", + " {", + " print(l[5]);", + " print((q as char).to_str());", + " print(l[i]);", + " print((q as char).to_str());", + " println((p as char).to_str());", + " i+=1;", + " }", + " i = 6;", + " while i < l.len()", + " {", + " println(l[i]);", + " i+=1;", + " }", + "}", + ]; + let mut i = 0; + while i < 5 + { + println(l[i]); + i+=1; + } + i = 0; + while i < l.len() + { + print(l[5]); + print((q as char).to_str()); + print(l[i]); + print((q as char).to_str()); + println((p as char).to_str()); + i+=1; + } + i = 6; + while i < l.len() + { + println(l[i]); + i+=1; + } } diff --git a/Task/RIPEMD-160/Haskell/ripemd-160.hs b/Task/RIPEMD-160/Haskell/ripemd-160.hs new file mode 100644 index 0000000000..b66268d9be --- /dev/null +++ b/Task/RIPEMD-160/Haskell/ripemd-160.hs @@ -0,0 +1,12 @@ +import Data.Char (ord) +import Crypto.Hash.RIPEMD160 (hash) +import Data.ByteString (unpack, pack) +import Text.Printf (printf) + +main = putStrLn $ -- output to terminal + concatMap (printf "%02x") $ -- to hex string + unpack $ -- to array of Word8 + hash $ -- RIPEMD-160 hash to ByteString + pack $ -- to ByteString + map (fromIntegral.ord) -- to array of Word8 + "Rosetta Code" diff --git a/Task/RIPEMD-160/Julia/ripemd-160.julia b/Task/RIPEMD-160/Julia/ripemd-160.julia new file mode 100644 index 0000000000..3ca8c08da9 --- /dev/null +++ b/Task/RIPEMD-160/Julia/ripemd-160.julia @@ -0,0 +1,53 @@ +using Nettle + +function ripemdsum(s::String) + bytes2hex(ripemd160_hash(s)) +end + +mes = ["", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] + +h = ASCIIString[] +for s in mes + push!(h, ripemdsum(s)) +end +push!(h, ripemdsum("1234567890"^8)) +push!(h, ripemdsum("a"^10^6)) + +t = ["9c1185a5c5e9fc54612808977ee8f548b2258d31", + "0bdc9d2d256b3ee9daae347be6f4dc835a467ffe", + "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc", + "5d0689ef49d2fae572b881b123a85ffa21595f36", + "f71c27109c692c1b56bbdceb5b9d2865b3708dbc", + "12a053384a9c0c88e405a06c27dcf49ada62eb2b", + "b0e20b6e3116640286ed3a87a5713079b21f5189", + "9b752e45573d4b39f4dbd3323cab82bf63326bfb", + "52783243c1697bdbe16d37f97f68f08325dc1528"] + +lab = ["\"\" (empty string)", "\"a\"", "\"abc\"", + "\"message digest\"", "\"a...z\"", + "\"abcdbcde...nopq\"", "\"A...Za...z0...9\"", + "8 times \"1234567890\"", "1 million times \"a\""] + +isok = t .== h + +println("Testing Julia's RIPEMD-160 hash against its test vectors.") +for i in 1:length(h) + print(@sprintf(" %20s => ", lab[i]), h[i], " ") + if isok[i] + println('\u263a') + else + println('\u26a0') + end +end + +if all(isok) + println("The function passes for all test vectors.\n") +else + println("The function fid not pass for all test vectors.\n") +end + +msg = "Rosetta Code" +h = ripemdsum(msg) +println(msg, " => ", h) diff --git a/Task/RSA-code/ALGOL-68/rsa-code.alg b/Task/RSA-code/ALGOL-68/rsa-code.alg new file mode 100644 index 0000000000..518ac645d6 --- /dev/null +++ b/Task/RSA-code/ALGOL-68/rsa-code.alg @@ -0,0 +1,73 @@ +COMMENT + First cut. Doesn't yet do blocking and deblocking. Also, as + encryption and decryption are identical operations but for the + reciprocal exponents used, only one has been implemented below. + + A later release will address these issues. +COMMENT + +BEGIN + PR precision=1000 PR + MODE LLI = LONG LONG INT; CO For brevity CO + PROC mod power = (LLI base, exponent, modulus) LLI : + BEGIN + LLI result := 1, b := base, e := exponent; + IF exponent < 0 + THEN + put (stand error, (("Negative exponent", exponent, newline))) + ELSE + WHILE e > 0 + DO + (ODD e | result := (result * b) MOD modulus); + e OVERAB 2; b := (b * b) MOD modulus + OD + FI; + result + END; + PROC modular inverse = (LLI a, m) LLI : + BEGIN + PROC extended gcd = (LLI x, y) []LLI : + BEGIN + LLI v := 1, a := 1, u := 0, b := 0, g := x, w := y; + WHILE w>0 + DO + LLI q := g % w, t := a - q * u; + a := u; u := t; + t := b - q * v; + b := v; v := t; + t := g - q * w; + g := w; w := t + OD; + a PLUSAB (a < 0 | u | 0); + (a, b, g) + END; + [] LLI egcd = extended gcd (a, m); + (egcd[3] > 1 | 0 | egcd[1] MOD m) + END; + PROC number to string = (LLI number) STRING : + BEGIN + [] CHAR map = (blank + "ABCDEFGHIJKLMNOPQRSTUVWXYZ")[@0]; + LLI local number := number; + INT length := SHORTEN SHORTEN ENTIER long long log(number) + 1; + (ODD length | length PLUSAB 1); + [length % 2] CHAR text; + FOR i FROM length % 2 BY -1 TO 1 + DO + INT index = SHORTEN SHORTEN (local number MOD 100); + text[i] := (index > 26 | "?" | map[index]); + local number := local number % 100 + OD; + text + END; +CO The parameters of a particular RSA cryptosystem CO + LLI p = 3490529510847650949147849619903898133417764638493387843990820577; + LLI q = 32769132993266709549961988190834461413177642967992942539798288533; + LLI n = p * q; + LLI phi n = (p-1) * (q-1); + LLI e = 9007; + LLI d = modular inverse (e, phi n); +CO A ciphertext CO + LLI cipher text = 96869613754622061477140922254355882905759991124574319874695120930816298225145708356931476622883989628013391990551829945157815154; +CO Print out the corresponding plain text CO + print (number to string (mod power (ciphertext, d, n))) +END diff --git a/Task/RSA-code/Mathematica/rsa-code.math b/Task/RSA-code/Mathematica/rsa-code.math new file mode 100644 index 0000000000..76193ac721 --- /dev/null +++ b/Task/RSA-code/Mathematica/rsa-code.math @@ -0,0 +1,20 @@ +toNumPlTxt[s_] := FromDigits[ToCharacterCode[s], 256]; +fromNumPlTxt[plTxt_] := FromCharacterCode[IntegerDigits[plTxt, 256]]; +enc::longmess = "Message '``' is too long for n = ``."; +enc[n_, _, mess_] /; + toNumPlTxt[mess] >= n := (Message[enc::longmess, mess, n]; $Failed); +enc[n_, e_, mess_] := PowerMod[toNumPlTxt[mess], e, n]; +dec[n_, d_, en_] := fromNumPlTxt[PowerMod[en, d, n]]; +text = "The cake is a lie!"; +n = 9516311845790656153499716760847001433441357; +e = 65537; +d = 5617843187844953170308463622230283376298685; +en = enc[n, e, text]; +de = dec[n, d, en]; +Print["Text: '" <> text <> "'"]; +Print["n = " <> IntegerString[n]]; +Print["e = " <> IntegerString[e]]; +Print["d = " <> IntegerString[d]]; +Print["Numeric plaintext: " <> IntegerString[toNumPlTxt[text]]]; +Print["Encoded: " <> IntegerString[en]]; +Print["Decoded: '" <> de <> "'"]; diff --git a/Task/Random-number-generator--device-/C-sharp/random-number-generator--device-.cs b/Task/Random-number-generator--device-/C-sharp/random-number-generator--device--1.cs similarity index 100% rename from Task/Random-number-generator--device-/C-sharp/random-number-generator--device-.cs rename to Task/Random-number-generator--device-/C-sharp/random-number-generator--device--1.cs diff --git a/Task/Random-number-generator--device-/C-sharp/random-number-generator--device--2.cs b/Task/Random-number-generator--device-/C-sharp/random-number-generator--device--2.cs new file mode 100644 index 0000000000..ee7fb62fc7 --- /dev/null +++ b/Task/Random-number-generator--device-/C-sharp/random-number-generator--device--2.cs @@ -0,0 +1,26 @@ +const long m = 2147483647L; +const long a = 48271L; +const long q = 44488L; +const long r = 3399L; +static long r_seed = 12345678L; + +public static byte gen() +{ + long hi = r_seed / q; + long lo = r_seed - q * hi; + long t = a * lo - r * hi; + if (t > 0) + r_seed = t; + else + r_seed = t + m; + return (byte)r_seed; +} + +public static void ParkMiller(byte[] arr) +{ + byte[] arr = new byte[10900000]; + for (int i = 0; i < arr.Length; i++) + { + arr[i] = gen(); + } +} diff --git a/Task/Random-number-generator--device-/C-sharp/random-number-generator--device--3.cs b/Task/Random-number-generator--device-/C-sharp/random-number-generator--device--3.cs new file mode 100644 index 0000000000..58ad592c53 --- /dev/null +++ b/Task/Random-number-generator--device-/C-sharp/random-number-generator--device--3.cs @@ -0,0 +1 @@ + Math.random2(-(Math.random()),Math.random(); diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--5.c b/Task/Random-number-generator--device-/C/random-number-generator--device--5.c index 58ad592c53..80c3924f4f 100644 --- a/Task/Random-number-generator--device-/C/random-number-generator--device--5.c +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--5.c @@ -1 +1,10 @@ - Math.random2(-(Math.random()),Math.random(); +#include +#include + +int main() +{ + std::random_device rd; + std::uniform_int_distribution dist; // long is guaranteed to be 32 bits + + std::cout << "Random Number: " << dist(rd) << std::endl; +} diff --git a/Task/Random-number-generator--device-/Haskell/random-number-generator--device-.hs b/Task/Random-number-generator--device-/Haskell/random-number-generator--device-.hs index c7e5078fe4..4f432daf6a 100644 --- a/Task/Random-number-generator--device-/Haskell/random-number-generator--device-.hs +++ b/Task/Random-number-generator--device-/Haskell/random-number-generator--device-.hs @@ -1,4 +1,4 @@ -#!/usr/bin/runhaskell +#!/usr/bin/env runhaskell import System.Entropy import Data.Binary.Get diff --git a/Task/Random-number-generator--device-/Julia/random-number-generator--device-.julia b/Task/Random-number-generator--device-/Julia/random-number-generator--device-.julia new file mode 100644 index 0000000000..e4cbe6fa7a --- /dev/null +++ b/Task/Random-number-generator--device-/Julia/random-number-generator--device-.julia @@ -0,0 +1,15 @@ +const rdev = "/dev/random" +rstream = try + open(rdev, "r") +catch + false +end + +if isa(rstream, IOStream) + b = readbytes(rstream, 4) + close(rstream) + i = reinterpret(Int32, b)[1] + println("A hardware random number is: ", i) +else + println("The hardware random number stream, ", rdev, ", was unavailable.") +end diff --git a/Task/Random-number-generator--included-/Fortran/random-number-generator--included-.f b/Task/Random-number-generator--included-/Fortran/random-number-generator--included-.f new file mode 100644 index 0000000000..48f835ab4a --- /dev/null +++ b/Task/Random-number-generator--included-/Fortran/random-number-generator--included-.f @@ -0,0 +1,22 @@ +program rosetta_random + implicit none + + integer, parameter :: rdp = kind(1.d0) + real(rdp) :: num + integer, allocatable :: seed(:) + integer :: un,n, istat + + call random_seed(size = n) + allocate(seed(n)) + + ! Seed with the OS random number generator + open(newunit=un, file="/dev/urandom", access="stream", & + form="unformatted", action="read", status="old", iostat=istat) + if (istat == 0) then + read(un) seed + close(un) + end if + call random_seed (put=seed) + call random_number(num) + write(*,'(E24.16)') num +end program rosetta_random diff --git a/Task/Random-number-generator--included-/TI-83-BASIC/random-number-generator--included-.ti-83 b/Task/Random-number-generator--included-/TI-83-BASIC/random-number-generator--included-.ti-83 new file mode 100644 index 0000000000..b0db35b27b --- /dev/null +++ b/Task/Random-number-generator--included-/TI-83-BASIC/random-number-generator--included-.ti-83 @@ -0,0 +1 @@ +rand diff --git a/Task/Random-number-generator--included-/UNIX-Shell/random-number-generator--included-.sh b/Task/Random-number-generator--included-/UNIX-Shell/random-number-generator--included-.sh index a55a9efbc8..0abddfcdc7 100644 --- a/Task/Random-number-generator--included-/UNIX-Shell/random-number-generator--included-.sh +++ b/Task/Random-number-generator--included-/UNIX-Shell/random-number-generator--included-.sh @@ -1 +1 @@ -number=`awk 'BEGIN{print int(rand()*10+1)}'` # Get a random number + echo $RANDOM diff --git a/Task/Random-numbers/DWScript/random-numbers.dw b/Task/Random-numbers/DWScript/random-numbers.dw index 653491f60e..f121f22983 100644 --- a/Task/Random-numbers/DWScript/random-numbers.dw +++ b/Task/Random-numbers/DWScript/random-numbers.dw @@ -2,4 +2,4 @@ var values : array [0..999] of Float; var i : Integer; for i := values.Low to values.High do - values := RandG(1, 0.5); + values[i] := RandG(1, 0.5); diff --git a/Task/Random-numbers/REXX/random-numbers.rexx b/Task/Random-numbers/REXX/random-numbers.rexx index 6408fe7ad5..fa370e73ed 100644 --- a/Task/Random-numbers/REXX/random-numbers.rexx +++ b/Task/Random-numbers/REXX/random-numbers.rexx @@ -1,38 +1,45 @@ -/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=½.*/ -numeric digits 20 /*greater precision than 9 digits*/ -parse arg n seed . /*allow specification of N & seed*/ -if n=='' | n==',' then n=1000 /*N: is the size of the array.*/ -if seed\=='' then call random ,,seed /*SEED: for repeatable random #'s*/ -newMean=1 /*desired new mean|arithmetic avg*/ -sd=1/2 /*desired new standard deviation.*/ - do g=1 for n /*gen N uniform random #'s (0,1].*/ - #.g = random(1,1e5) / 1e5 /*RANDOM bif generates integers.*/ - end /*g*/ /* [↑] rand integers──►fractions*/ +/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard deviation.=½.*/ +numeric digits 20 /*the default decimal digit precision=9*/ +parse arg n seed . /*allow specification of N and the seed*/ +if n=='' | n==',' then n=1000 /*N: is the size of the array. */ +if seed\=='' then call random ,,seed /*SEED: for repeatable random numbers. */ +newMean=1 /*the desired new mean|arithmetic avg. */ +sd=1/2 /*the desired new standard deviation. */ + do g=1 for n /*generate N uniform random #'s (0,1].*/ + #.g = random(1,1e5) / 1e5 /*REXX's RANDOM BIF generates integers.*/ + end /*g*/ /* [↑] rand integers ──► fractions. */ say ' old mean=' mean() -say 'old standard deviation=' stddev() -call pi; pi2=pi+pi /*define pi and also 2*pi. */ +say 'old standard deviation=' stdDev() +call pi; pi2=pi+pi /*define pi and also 2 * pi. */ say - do j=1 to n-1 by 2; m=j+1 /*step through iterations by two.*/ - _=sd * sqrt(ln(#.j) * -2) /*calculate used-twice expression*/ - #.j=_ * cos(pi2*#.m) + newMean /*utilize the Box─Muller method.*/ - #.m=_ * sin(pi2*#.m) + newMean /*random number must be: (0,1] */ + do j=1 to n-1 by 2; m=j+1 /*step through the iterations by two. */ + _=sd * sqrt(ln(#.j) * -2) /*calculate the used-twice expression.*/ + #.j=_ * cos(pi2*#.m) + newMean /*utilize the Box─Muller method. */ + #.m=_ * sin(pi2*#.m) + newMean /*random number must be: (0,1] */ end /*j*/ say ' new mean=' mean() -say 'new standard deviation=' stddev() -exit /*stick a fork in it, we're done.*/ +say 'new standard deviation=' stdDev() +exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────subroutines──────────────────────────────────────────────────────────────────────*/ mean: _=0; do k=1 for n; _=_+#.k; end; return _/n -stddev: _avg=mean(); _=0; do k=1 for n; _=_+(#.k-_avg)**2; end; return sqrt(_/n) +stdDev: _avg=mean(); _=0; do k=1 for n; _=_+(#.k-_avg)**2; end; return sqrt(_/n) e: e =2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e /*digs overkill*/ pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi /* " " */ r2r: return arg(1) // (2*pi()) /*normalize ang*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits 11; numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2; do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end; numeric digits d; return g/1 -cos: procedure; parse arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9); if a=pi then return -1; pi2=pi+pi - if a=pi*.5|a=pi2 then return 0; if a=pi/3 then return .5; if a=pi2/3 then return -.5; return .sincos(1,1,-1) sin: procedure; parse arg x;x=r2r(x);numeric fuzz min(5,digits()-3);if abs(x)=pi then return 0;return .sincos(x,x,1) .sincos:parse arg z,_,i; x=x*x; p=z; do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z ln: procedure; parse arg x,f; call e; ig= x>1.5; is=1-2*(ig\==1); ii=0; xx=x; return .ln_comp() .ln_comp: do while ig&xx>1.5|\ig&xx<.5;_=e;do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end xx=izz;ii=ii+is*2**k;end;x=x*e**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end; return z+ii + +cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi=pi*.5 + numeric fuzz min(6,digits()-3); if a=pi() then return -1 + if a=hpi | a=hpi*3 then return 0; if a=pi()/3 then return .5 + if a=pi()*2/3 then return -.5; return .sinCos(1,1,-1) + +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Random-numbers/Rust/random-numbers-1.rust b/Task/Random-numbers/Rust/random-numbers-1.rust new file mode 100644 index 0000000000..626dc20f42 --- /dev/null +++ b/Task/Random-numbers/Rust/random-numbers-1.rust @@ -0,0 +1,11 @@ +extern crate rand; +use rand::distributions::{Normal, IndependentSample}; + +fn main() { + let mut rands = [0.0; 1000]; + let normal = Normal::new(1.0, 0.5); + let mut rng = rand::thread_rng(); + for num in rands.iter_mut() { + *num = normal.ind_sample(&mut rng); + } +} diff --git a/Task/Random-numbers/Rust/random-numbers-2.rust b/Task/Random-numbers/Rust/random-numbers-2.rust new file mode 100644 index 0000000000..037ca16001 --- /dev/null +++ b/Task/Random-numbers/Rust/random-numbers-2.rust @@ -0,0 +1,10 @@ +extern crate rand; +use rand::distributions::{Normal, IndependentSample}; + +fn main() { + let rands: Vec<_> = { + let normal = Normal::new(1.0, 0.5); + let mut rng = rand::thread_rng(); + (0..1000).map(|_| normal.ind_sample(&mut rng)).collect() + }; +} diff --git a/Task/Random-numbers/Rust/random-numbers.rust b/Task/Random-numbers/Rust/random-numbers.rust deleted file mode 100644 index 13baecd5d4..0000000000 --- a/Task/Random-numbers/Rust/random-numbers.rust +++ /dev/null @@ -1,12 +0,0 @@ -use std::rand; -use std::rand::distributions::{Normal, IndependentSample}; - -fn main() { - let mut rands = [0.0, ..1000]; - let normal = Normal::new(1.0, 0.5); - - for i in range(0, 1000) { - let v = normal.ind_sample(&mut rand::task_rng()); - rands[i] = v; - } -} diff --git a/Task/Range-expansion/Elixir/range-expansion.elixir b/Task/Range-expansion/Elixir/range-expansion.elixir new file mode 100644 index 0000000000..3ef5f11c66 --- /dev/null +++ b/Task/Range-expansion/Elixir/range-expansion.elixir @@ -0,0 +1,12 @@ +defmodule RC do + def expansion(range) do + Enum.flat_map(String.split(range, ","), fn part -> + case Regex.scan(~r/^(-?\d+)-(-?\d+)$/, part) do + [[_,a,b]] -> Enum.to_list(String.to_integer(a) .. String.to_integer(b)) + [] -> [String.to_integer(part)] + end + end) + end +end + +IO.inspect RC.expansion("-6,-3--1,3-5,7-11,14,15,17-20") diff --git a/Task/Range-expansion/Java/range-expansion.java b/Task/Range-expansion/Java/range-expansion.java index 13ef108949..95227577c4 100644 --- a/Task/Range-expansion/Java/range-expansion.java +++ b/Task/Range-expansion/Java/range-expansion.java @@ -1,66 +1,65 @@ import java.util.*; -import java.util.regex.*; -class Range implements Enumeration { - private int clower, cupper; - private int value; - private boolean inrange; - private Scanner ps = null; - private String ss; +class RangeExpander implements Iterator, Iterable { - private static String del = "\\s*,\\s*"; + private static final Pattern TOKEN_PATTERN = Pattern.compile("([+-]?\\d+)-([+-]?\\d+)"); - public Range(String s) { - ss = s; - reset(); - } + private final Iterator tokensIterator; - public boolean hasMoreElements() { - return (inrange && (value >= clower && value <= cupper)) || ps.hasNext(); - } + private boolean inRange; + private int upperRangeEndpoint; + private int nextRangeValue; - public Object nextElement() throws NoSuchElementException { - if (!hasMoreElements()) - throw new NoSuchElementException(); - if (inrange && (value >= clower && value <= cupper)) { - value++; - return value-1; + public RangeExpander(String range) { + String[] tokens = range.split("\\s*,\\s*"); + this.tokensIterator = Arrays.asList(tokens).iterator(); } - inrange = false; - String n = ps.next(); - if (n.matches("[+-]?\\d+-[+-]?\\d+")) { - Scanner ls = new Scanner(n); - ls.findInLine("([+-]?\\d+)-([+-]?\\d+)"); - MatchResult r = ls.match(); - clower = Integer.parseInt(r.group(1)); - cupper = Integer.parseInt(r.group(2)); - value = clower+1; - inrange = true; - ls.close(); - return clower; + + @Override + public boolean hasNext() { + return hasNextRangeValue() || this.tokensIterator.hasNext(); + } + + private boolean hasNextRangeValue() { + return this.inRange && this.nextRangeValue <= this.upperRangeEndpoint; + } + + @Override + public Integer next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + + if (hasNextRangeValue()) { + return this.nextRangeValue++; + } + + String token = this.tokensIterator.next(); + + Matcher matcher = TOKEN_PATTERN.matcher(token); + if (matcher.find()) { + this.inRange = true; + this.upperRangeEndpoint = Integer.valueOf(matcher.group(2)); + this.nextRangeValue = Integer.valueOf(matcher.group(1)); + return this.nextRangeValue++; + } + + this.inRange = false; + return Integer.valueOf(token); } - return Integer.parseInt(n); - } - public void reset() { - if (ps != null) - ps.close(); - ps = new Scanner(ss).useDelimiter(del); - inrange = false; - } + @Override + public Iterator iterator() { + return this; + } - protected void finalize() throws Throwable { - ps.close(); - super.finalize(); - } } -class rangexp { - public static void main(String[] args) { - Range r = new Range("-6,-3--1,3-5,7-11,14,15,17-20"); - while (r.hasMoreElements()) { - System.out.print(r.nextElement() + " "); +class RangeExpanderTest { + public static void main(String[] args) { + RangeExpander re = new RangeExpander("-6,-3--1,3-5,7-11,14,15,17-20"); + for (int i : re) { + System.out.print(i + " "); + } } - System.out.println(); - } } diff --git a/Task/Range-expansion/Julia/range-expansion.julia b/Task/Range-expansion/Julia/range-expansion.julia index 5c95b09ded..fa52a7529c 100644 --- a/Task/Range-expansion/Julia/range-expansion.julia +++ b/Task/Range-expansion/Julia/range-expansion.julia @@ -1,5 +1,5 @@ -slurp(s) = readcsv(IOBuffer(s*",")) +slurp(s) = readcsv(IOBuffer(s)) -conv(s) = colon(map(int,(match(r"^(-?\d+)-(-?\d+)$", s).captures))...) +conv(s)= colon(map(x->parse(Int,x),match(r"^(-?\d+)-(-?\d+)$", s).captures)...) -expand(s) = mapreduce(x -> isa(x,Number)? int(x): conv(x), vcat, slurp(s)) +expand(s) = mapreduce(x -> isa(x,Number)? Int(x) : conv(x), vcat, slurp(s)) diff --git a/Task/Range-expansion/PowerShell/range-expansion.psh b/Task/Range-expansion/PowerShell/range-expansion.psh new file mode 100644 index 0000000000..5763ceee83 --- /dev/null +++ b/Task/Range-expansion/PowerShell/range-expansion.psh @@ -0,0 +1,22 @@ +function range-expansion($array) { + function expansion($arr) { + if($arr) { + $arr = $arr.Split(',') + $arr | foreach{ + $a = $_ + $b, $c, $d, $e = $a.Split('-') + switch($a) { + $b {return $a} + "-$c" {return $a} + "$b-$c" {return "$(([Int]$b)..([Int]$c))"} + "-$c-$d" {return "$(([Int]$("-$c"))..([Int]$d))"} + "-$c--$e" {return "$(([Int]$("-$c"))..([Int]$("-$e")))"} + } + } + } else {""} + } + $OFS = ", " + "$(expansion $array)" + $OFS = " " +} +range-expansion "-6,-3--1,3-5,7-11,14,15,17-20" diff --git a/Task/Range-expansion/Ruby/range-expansion.rb b/Task/Range-expansion/Ruby/range-expansion.rb index 727d9cde37..42b80cdf1e 100644 --- a/Task/Range-expansion/Ruby/range-expansion.rb +++ b/Task/Range-expansion/Ruby/range-expansion.rb @@ -1,11 +1,11 @@ def range_expand(rng) - rng.split(',').collect do |part| + rng.split(',').flat_map do |part| if part =~ /^(-?\d+)-(-?\d+)$/ ($1.to_i .. $2.to_i).to_a else Integer(part) end - end.flatten + end end p range_expand('-6,-3--1,3-5,7-11,14,15,17-20') diff --git a/Task/Range-expansion/Rust/range-expansion.rust b/Task/Range-expansion/Rust/range-expansion.rust new file mode 100644 index 0000000000..d3850e7a1f --- /dev/null +++ b/Task/Range-expansion/Rust/range-expansion.rust @@ -0,0 +1,26 @@ +use std::str::FromStr; + +// Precondition: range doesn't contain multibyte UTF-8 characters +fn range_expand(range : &str) -> Vec { + range.split(',').flat_map(|item| { + match i32::from_str(item) { + Ok(n) => n..n+1, + _ => { + let dashpos= + match item.rfind("--") { + Some(p) => p, + None => item.rfind('-').unwrap(), + }; + let rstart=i32::from_str( + unsafe{ item.slice_unchecked(0,dashpos)} ).unwrap(); + let rend=i32::from_str( + unsafe{ item.slice_unchecked(dashpos+1,item.len()) } ).unwrap(); + rstart..rend+1 + }, + } + }).collect() +} + +fn main() { + println!("{:?}", range_expand("-6,-3--1,3-5,7-11,14,15,17-20")); +} diff --git a/Task/Range-extraction/Elixir/range-extraction.elixir b/Task/Range-extraction/Elixir/range-extraction.elixir new file mode 100644 index 0000000000..c17041bc2c --- /dev/null +++ b/Task/Range-extraction/Elixir/range-extraction.elixir @@ -0,0 +1,30 @@ +defmodule RC do + def range_extract(list) do + max = Enum.max(list) + 2 + sorted = Enum.sort([max|list]) + canidate_number = hd(sorted) + current_number = hd(sorted) + extract(tl(sorted), canidate_number, current_number, []) + end + + defp extract([], _, _, range), do: Enum.reverse(range) |> Enum.join(",") + defp extract([next|rest], canidate, current, range) when current+1 >= next do + extract(rest, canidate, next, range) + end + defp extract([next|rest], canidate, current, range) when canidate == current do + extract(rest, next, next, [to_string(current)|range]) + end + defp extract([next|rest], canidate, current, range) do + seperator = if canidate+1 == current, do: ",", else: "-" + str = "#{canidate}#{seperator}#{current}" + extract(rest, next, next, [str|range]) + end +end + +list = [ + 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39 +] +IO.inspect RC.range_extract(list) diff --git a/Task/Range-extraction/Emacs-Lisp/range-extraction-1.l b/Task/Range-extraction/Emacs-Lisp/range-extraction-1.l new file mode 100644 index 0000000000..6bd0c971e2 --- /dev/null +++ b/Task/Range-extraction/Emacs-Lisp/range-extraction-1.l @@ -0,0 +1,15 @@ +(require 'gnus-range) +(defun rangext (lst) + (mapconcat (lambda (item) + (if (consp item) + (if (= (+ 1 (car item) ) (cdr item) ) + (format "%d,%d" (car item) (cdr item) ) + (format "%d-%d" (car item) (cdr item) )) + (format "%d" item))) + (gnus-compress-sequence lst) + ",")) + +(insert (rangext '(0 1 2 4 6 7 8 11 12 14 + 15 16 17 18 19 20 21 22 23 24 + 25 27 28 29 30 31 32 33 35 36 + 37 38 39) )) diff --git a/Task/Range-extraction/Emacs-Lisp/range-extraction-2.l b/Task/Range-extraction/Emacs-Lisp/range-extraction-2.l new file mode 100644 index 0000000000..c9290fdd9e --- /dev/null +++ b/Task/Range-extraction/Emacs-Lisp/range-extraction-2.l @@ -0,0 +1,27 @@ +(setq max-lisp-eval-depth 10000) + +(defun ab (a ls) + (if ls (if (= (+ a 1) (car ls) ) + (abc a (car ls) (cdr ls) ) + (format "%d,%s" a (ab (car ls) (cdr ls) ))) + (format "%d" a) )) + +(defun abc (a b ls) + (if ls (if (= (+ b 1) (car ls) ) + (abcd a (car ls) (cdr ls) ) + (format "%d,%d,%s" a b (ab (car ls) (cdr ls) ))) + (format "%d,%d" a b) )) + +(defun abcd (a c ls) + (if ls (if (= (+ c 1) (car ls) ) + (abcd a (car ls) (cdr ls) ) + (format "%d-%d,%s" a c (ab (car ls) (cdr ls) ))) + (format "%d-%d" a c) )) + +(defun rangext (ls) + (if ls (ab (car ls) (cdr ls) ) "")) + +(insert (rangext '(0 1 2 4 6 7 8 11 12 14 + 15 16 17 18 19 20 21 22 23 24 + 25 27 28 29 30 31 32 33 35 36 + 37 38 39) )) diff --git a/Task/Range-extraction/Emacs-Lisp/range-extraction.l b/Task/Range-extraction/Emacs-Lisp/range-extraction.l deleted file mode 100644 index e20def1f3f..0000000000 --- a/Task/Range-extraction/Emacs-Lisp/range-extraction.l +++ /dev/null @@ -1,12 +0,0 @@ -(require 'gnus-range) -(defun rangext (lst) - (mapconcat (lambda (item) - (if (consp item) - (format "%d-%d" (car item) (cdr item)) - (format "%d" item))) - (gnus-compress-sequence lst) - ",")) -(rangext '(0 1 2 4 6 7 8 11 12 14 - 15 16 17 18 19 20 21 22 23 24 - 25 27 28 29 30 31 32 33 35 36 - 37 38 39)) diff --git a/Task/Range-extraction/J/range-extraction-1.j b/Task/Range-extraction/J/range-extraction-1.j index 1e1f3e271e..ec5053dd29 100644 --- a/Task/Range-extraction/J/range-extraction-1.j +++ b/Task/Range-extraction/J/range-extraction-1.j @@ -1,4 +1,3 @@ -require 'strings' fmt=: [: ;@(8!:0) [`]`({. ; (',-' {~ 2 < #) ; {:)@.(2 <. #) group=: <@fmt;.1~ 1 ~: 0 , 2 -~/\ ] extractRange=: ',' joinstring group diff --git a/Task/Range-extraction/J/range-extraction-3.j b/Task/Range-extraction/J/range-extraction-3.j index b6d173dfe7..b871b73dd3 100644 --- a/Task/Range-extraction/J/range-extraction-3.j +++ b/Task/Range-extraction/J/range-extraction-3.j @@ -1,2 +1,2 @@ - extractRange i.101 -0-100 + extractRange (-6, 3, 2, 1), 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20 +-6,-3-1,3-5,7-11,14,15,17-20 diff --git a/Task/Range-extraction/J/range-extraction-4.j b/Task/Range-extraction/J/range-extraction-4.j index 76b7e3f267..b6d173dfe7 100644 --- a/Task/Range-extraction/J/range-extraction-4.j +++ b/Task/Range-extraction/J/range-extraction-4.j @@ -1,2 +1,2 @@ - extractRange (-. p:) i.101 -0,1,4,6,8-10,12,14-16,18,20-22,24-28,30,32-36,38-40,42,44-46,48-52,54-58,60,62-66,68-70,72,74-78,80-82,84-88,90-96,98-100 + extractRange i.101 +0-100 diff --git a/Task/Range-extraction/J/range-extraction-5.j b/Task/Range-extraction/J/range-extraction-5.j index 2209fcc703..76b7e3f267 100644 --- a/Task/Range-extraction/J/range-extraction-5.j +++ b/Task/Range-extraction/J/range-extraction-5.j @@ -1,2 +1,2 @@ - extractRange 2}. (-. p:) i.101 -4,6,8-10,12,14-16,18,20-22,24-28,30,32-36,38-40,42,44-46,48-52,54-58,60,62-66,68-70,72,74-78,80-82,84-88,90-96,98-100 + extractRange (-. p:) i.101 +0,1,4,6,8-10,12,14-16,18,20-22,24-28,30,32-36,38-40,42,44-46,48-52,54-58,60,62-66,68-70,72,74-78,80-82,84-88,90-96,98-100 diff --git a/Task/Range-extraction/J/range-extraction-6.j b/Task/Range-extraction/J/range-extraction-6.j new file mode 100644 index 0000000000..2209fcc703 --- /dev/null +++ b/Task/Range-extraction/J/range-extraction-6.j @@ -0,0 +1,2 @@ + extractRange 2}. (-. p:) i.101 +4,6,8-10,12,14-16,18,20-22,24-28,30,32-36,38-40,42,44-46,48-52,54-58,60,62-66,68-70,72,74-78,80-82,84-88,90-96,98-100 diff --git a/Task/Range-extraction/Julia/range-extraction.julia b/Task/Range-extraction/Julia/range-extraction.julia new file mode 100644 index 0000000000..9c871b02c9 --- /dev/null +++ b/Task/Range-extraction/Julia/range-extraction.julia @@ -0,0 +1,18 @@ +function sprintfrange{T<:Integer}(a::Array{T,1}) + len = length(a) + 0 < len || return "" + dropme = falses(len) + dropme[2:end-1] = Bool[a[i-1]==a[i]-1 && a[i+1]==a[i]+1 for i in 2:(len-1)] + s = [string(i) for i in a] + s[dropme] = "X" + s = join(s, ",") + replace(s, r",[,X]+,", "-") +end + +testa = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39] + +println("Testing range-style formatting.") +println(" ", testa, "\n =>\n ", sprintfrange(testa)) diff --git a/Task/Range-extraction/NetRexx/range-extraction.netrexx b/Task/Range-extraction/NetRexx/range-extraction-1.netrexx similarity index 100% rename from Task/Range-extraction/NetRexx/range-extraction.netrexx rename to Task/Range-extraction/NetRexx/range-extraction-1.netrexx diff --git a/Task/Range-extraction/NetRexx/range-extraction-2.netrexx b/Task/Range-extraction/NetRexx/range-extraction-2.netrexx new file mode 100644 index 0000000000..166b4a8cde --- /dev/null +++ b/Task/Range-extraction/NetRexx/range-extraction-2.netrexx @@ -0,0 +1,76 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +runSample(arg) +return + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +-- Compact a list of numbers by reducing ranges +method compact(expanded) public static + nums = expanded.changestr(',', ' ').space -- remove possible commas & clean up the string + rezult = '' + + RANGE = 0 + FIRST = nums.word(1) -- set starting value + loop i_ = 2 to nums.words -- each word in the string is a number to examine + LOCAL = nums.word(i_) + if LOCAL - FIRST - RANGE == 1 then do + -- inside a range + RANGE = RANGE + 1 + end + else do + -- not inside a range + if RANGE \= 0 then do + -- we have a range of numbers so collect this and reset + rezult = rezult || FIRST || delim(RANGE) || FIRST + RANGE || ',' + RANGE = 0 + end + else do + -- just collect this number + rezult = rezult || FIRST || ',' + end + FIRST = LOCAL -- bump new starting value + end + end i_ + + if RANGE \= 0 then do + -- terminating value is a range + rezult = rezult || FIRST || delim(RANGE) || FIRST + RANGE + end + else do + -- terminating value is a single number + rezult = rezult || FIRST + end + + return rezult.space(1, ',') -- format and return result string + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +-- determine if the range delimiter should be a comma or dash +method delim(range) private static + if range == 1 then dlm = ',' + else dlm = '-' + return dlm + +-- ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ +-- sample driver +method runSample(arg) public static + +parse arg userInput +td = 0 +if userInput.words > 0 then do + -- use input from command line + td[0] = td[0] + 1; r_ = td[0]; td[r_] = userInput + end +else do + -- use canned test data + td[0] = td[0] + 1; r_ = td[0]; td[r_] = ' -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20' + td[0] = td[0] + 1; r_ = td[0]; td[r_] = ' 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39' + td[0] = td[0] + 1; r_ = td[0]; td[r_] = ' -4, -3, -2, 0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39' + end + +loop r_ = 1 to td[0] + say 'Original: ' td[r_].changestr(',', ' ').space(1, ',') + say 'Compacted:' compact(td[r_]) + say + end r_ +return diff --git a/Task/Range-extraction/PowerShell/range-extraction.psh b/Task/Range-extraction/PowerShell/range-extraction.psh new file mode 100644 index 0000000000..62cd7ec8dc --- /dev/null +++ b/Task/Range-extraction/PowerShell/range-extraction.psh @@ -0,0 +1,30 @@ +function range-extraction($arr) { + if($arr.Count -gt 2) { + $a, $b, $c, $arr = $arr + $d = $e = $c + if((($a + 1) -eq $b) -and (($b + 1) -eq $c)) { + $test = $true + while($arr -and $test) { + $d = $e + $e, $arr = $arr + $test = ($d+1) -eq $e + } + if($test){"$a-$e"} + elseif((-not $arr) -and $test){"$a-$d"} + elseif(-not $arr){"$a-$d,$e"} + else{"$a-$d," + (range-extraction (@($e)+$arr))} + } + elseif(($b + 1) -eq $c) {"$a," + (range-extraction (@($b, $c)+$arr))} + else {"$a,$b," + (range-extraction (@($c)+$arr))} + } else { + switch($arr.Count) { + 0 {""} + 1 {"$arr"} + 2 {"$($arr[0]),$($arr[1])"} + } + } +} +range-extraction @(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, +15, 16, 17, 18, 19, 20, 21, 22, 23, 24, +25, 27, 28, 29, 30, 31, 32, 33, 35, 36, +37, 38, 39) diff --git a/Task/Range-extraction/REXX/range-extraction-1.rexx b/Task/Range-extraction/REXX/range-extraction-1.rexx index aaffa7d94a..c7e64a2ab2 100644 --- a/Task/Range-extraction/REXX/range-extraction-1.rexx +++ b/Task/Range-extraction/REXX/range-extraction-1.rexx @@ -1,20 +1,19 @@ -/*REXX program creates a range extraction from a list of integers. */ +/*REXX program creates a range extraction from a list of numbers (can be neg.)*/ old=0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 -w=words(old) /*number of integers in the list.*/ -new= /*new list, possibly with ranges.*/ - do j=1 to w; x=word(old,j) /*get the Jth number in the list.*/ - new=new',' x /*append Jth number to new list.*/ - inc=1 /*start with an increment of one.*/ - do k=j+1 to w; y=word(old,k) /*get the Kth number in the list.*/ - if y\=x+inc then leave /*is this number ¬> prev by inc? */ - inc=inc+1; g=y /*increase range, assign g (good)*/ +#=words(old) /*number of integers in the number list*/ +new= /*the new list, possibly with ranges. */ + do j=1 to #; x=word(old,j) /*obtain Jth number in the old list. */ + new=new',' x /*append " " to " new " */ + inc=1 /*start with an increment of one (1). */ + do k=j+1 to #; y=word(old,k) /*get the Kth number in the number list*/ + if y\=x+inc then leave /*is this number not > previous by inc?*/ + inc=inc+1; g=y /*increase the range, assign G (good).*/ end /*k*/ - if k-1=j | g=x+1 then iterate /*range= 0|1? Then keep truckin'*/ - new=new'-'g /*indicate a range of numbers. */ - j=k-1 /*changing the J DO loop index.*/ + if k-1=j | g=x+1 then iterate /*Is the range=0│1? Then keep truckin'*/ + new=new'-'g; j=k-1 /*indicate a range of #s; change index*/ end /*j*/ -new=space(substr(new, 2), 0) /*elide leading comma, all blanks*/ -say 'old:' old /*show the old range of numbers. */ -say 'new:' new /* " " new list " " */ - /*stick a fork in it, we're done.*/ +new=space(substr(new, 2), 0) /*elide leading comma, also all blanks.*/ +say 'old:' old /*display the old range of numbers. */ +say 'new:' new /* " " new list " " */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Range-extraction/REXX/range-extraction-2.rexx b/Task/Range-extraction/REXX/range-extraction-2.rexx index ca4b8679a6..69162f64a0 100644 --- a/Task/Range-extraction/REXX/range-extraction-2.rexx +++ b/Task/Range-extraction/REXX/range-extraction-2.rexx @@ -1,20 +1,19 @@ -/*REXX program creates a range extraction from a list of integers. */ +/*REXX program creates a range extraction from a list of numbers (can be neg.)*/ old=0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 -w=words(old); j=0 /*number of integers in the list.*/ -new= /*new list, possibly with ranges.*/ - do while j prev by inc? */ - inc=inc+1; g=y /*increase range, assign g (good)*/ - end /*k*/ - if k-1=j | g=x+1 then iterate /*range= 0|1? Then keep truckin'*/ - new=new'-'g /*indicate a range of numbers. */ - j=k-1 /*which number to examine next. */ - end /*while*/ +#=words(old); j=0 /*number of integers in the number list*/ +new= /*the new list, possibly with ranges. */ + do while j<#; j=j+1; x=word(old,j) /*get the Jth number in the number list*/ + new=new',' x /*append " " to " new " */ + inc=1 /*start with an increment of one (1). */ + do k=j+1 to #; y=word(old,k) /*get the Kth number in the number list*/ + if y\=x+inc then leave /*is this number not > previous by inc?*/ + inc=inc+1; g=y /*increase the range, assign G (good).*/ + end /*k*/ + if k-1=j | g=x+1 then iterate /*Is the range=0│1? Then keep truckin'*/ + new=new'-'g; j=k-1 /*indicate a range of numbers; change J*/ + end /*while*/ -new=space(substr(new, 2), 0) /*elide leading comma, all blanks*/ -say 'old:' old /*show the old range of numbers. */ -say 'new:' new /* " " new list " " */ - /*stick a fork in it, we're done.*/ +new=space(substr(new, 2), 0) /*elide leading comma, also all blanks.*/ +say 'old:' old /*display the old range of numbers. */ +say 'new:' new /* " " new list " " */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Range-extraction/VBScript/range-extraction.vb b/Task/Range-extraction/VBScript/range-extraction.vb new file mode 100644 index 0000000000..726098cbc7 --- /dev/null +++ b/Task/Range-extraction/VBScript/range-extraction.vb @@ -0,0 +1,41 @@ +Function Range_Extraction(list) + num = Split(list,",") + For i = 0 To UBound(num) + startnum = CInt(num(i)) + sum = startnum + Do While i <= UBound(num) + If sum = CInt(num(i)) Then + If i = UBound(num) Then + If startnum <> CInt(num(i)) Then + If startnum + 1 = CInt(num(i)) Then + Range_Extraction = Range_Extraction & startnum & "," & num(i) & "," + Else + Range_Extraction = Range_Extraction & startnum & "-" & num(i) & "," + End If + Else + Range_Extraction = Range_Extraction & startnum & "," + End If + Exit Do + Else + i = i + 1 + sum = sum + 1 + End If + Else + If startnum = CInt(num(i-1)) Then + Range_Extraction = Range_Extraction & startnum & "," + Else + If startnum + 1 = CInt(num(i-1)) Then + Range_Extraction = Range_Extraction & startnum & "," & num(i-1) & "," + Else + Range_Extraction = Range_Extraction & startnum & "-" & num(i-1) & "," + End If + End If + i = i - 1 + Exit Do + End If + Loop + Next + Range_Extraction = Left(Range_Extraction,Len(Range_Extraction)-1) +End Function + +WScript.StdOut.Write Range_Extraction("0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,35,36,37,38,39") diff --git a/Task/Ranking-methods/Julia/ranking-methods-1.julia b/Task/Ranking-methods/Julia/ranking-methods-1.julia new file mode 100644 index 0000000000..a2587b2c36 --- /dev/null +++ b/Task/Ranking-methods/Julia/ranking-methods-1.julia @@ -0,0 +1,3 @@ +function ties{T<:Real}(a::Array{T,1}) + unique(a[2:end][a[2:end] .== a[1:end-1]]) +end diff --git a/Task/Ranking-methods/Julia/ranking-methods-2.julia b/Task/Ranking-methods/Julia/ranking-methods-2.julia new file mode 100644 index 0000000000..d67f97a6a6 --- /dev/null +++ b/Task/Ranking-methods/Julia/ranking-methods-2.julia @@ -0,0 +1,8 @@ +function rankstandard{T<:Real}(a::Array{T,1}) + r = collect(1:length(a)) + 1 < r[end] || return r + for i in ties(a) + r[a.==i] = r[a.==i][1] + end + return r +end diff --git a/Task/Ranking-methods/Julia/ranking-methods-3.julia b/Task/Ranking-methods/Julia/ranking-methods-3.julia new file mode 100644 index 0000000000..6097f57a54 --- /dev/null +++ b/Task/Ranking-methods/Julia/ranking-methods-3.julia @@ -0,0 +1,3 @@ +function rankmodified{T<:Real}(a::Array{T,1}) + indexin(a, a) +end diff --git a/Task/Ranking-methods/Julia/ranking-methods-4.julia b/Task/Ranking-methods/Julia/ranking-methods-4.julia new file mode 100644 index 0000000000..57ae7b571d --- /dev/null +++ b/Task/Ranking-methods/Julia/ranking-methods-4.julia @@ -0,0 +1,3 @@ +function rankdense{T<:Real}(a::Array{T,1}) + indexin(a, unique(a)) +end diff --git a/Task/Ranking-methods/Julia/ranking-methods-5.julia b/Task/Ranking-methods/Julia/ranking-methods-5.julia new file mode 100644 index 0000000000..bdae0f88fa --- /dev/null +++ b/Task/Ranking-methods/Julia/ranking-methods-5.julia @@ -0,0 +1,3 @@ +function rankordinal{T<:Real}(a::Array{T,1}) + collect(1:length(a)) +end diff --git a/Task/Ranking-methods/Julia/ranking-methods-6.julia b/Task/Ranking-methods/Julia/ranking-methods-6.julia new file mode 100644 index 0000000000..4db89217b5 --- /dev/null +++ b/Task/Ranking-methods/Julia/ranking-methods-6.julia @@ -0,0 +1,8 @@ +function rankfractional{T<:Real}(a::Array{T,1}) + r = float64(collect(1:length(a))) + 1.0 < r[end] || return r + for i in ties(a) + r[a.==i] = mean(r[a.==i]) + end + return r +end diff --git a/Task/Ranking-methods/Julia/ranking-methods-7.julia b/Task/Ranking-methods/Julia/ranking-methods-7.julia new file mode 100644 index 0000000000..a96135bba5 --- /dev/null +++ b/Task/Ranking-methods/Julia/ranking-methods-7.julia @@ -0,0 +1,21 @@ +scores = [44, 42, 42, 41, 41, 41, 39] +names = ["Solomon", "Jason", "Errol", "Garry", + "Bernard", "Barry", "Stephen"] + +srank = rankstandard(scores) +mrank = rankmodified(scores) +drank = rankdense(scores) +orank = rankordinal(scores) +frank = rankfractional(scores) + +println(" Name Score Std Mod Den Ord Frac") +for i in 1:length(scores) + print(@sprintf(" %-7s", names[i])) + print(@sprintf("%5d ", scores[i])) + print(@sprintf("%5d", srank[i])) + print(@sprintf("%5d", mrank[i])) + print(@sprintf("%5d", drank[i])) + print(@sprintf("%5d", orank[i])) + print(@sprintf("%7.2f", frank[i])) + println() +end diff --git a/Task/Ranking-methods/REXX/ranking-methods.rexx b/Task/Ranking-methods/REXX/ranking-methods.rexx new file mode 100644 index 0000000000..b827c3f629 --- /dev/null +++ b/Task/Ranking-methods/REXX/ranking-methods.rexx @@ -0,0 +1,49 @@ +/************************** +44 Solomon 1 1 1 1 1 +42 Jason 2 3 2 2 2.5 +42 Errol 2 3 2 3 2.5 +41 Garry 4 6 3 4 5 +41 Bernard 4 6 3 5 5 +41 Barry 4 6 3 6 5 +39 Stephen 7 7 4 7 7 +**************************/ +Do i=1 To 7 + Parse Value sourceline(i+1) With rank.i name.i . + /* say rank.i name.i */ + End +pool=0 +crank=0 +Do i=1 To 7 + If rank.i<>crank Then Do + pool=pool+1 + lo.pool=i + hi.pool=i + n.pool=1 + ii.pool=i + End + Else Do + n.pool=n.pool+1 + hi.pool=i + ii.pool=ii.pool+i + End + crank=rank.i + pool.i=pool + End +/* +Do j=1 To pool + Say 'pool' j n.j lo.j hi.j + End +*/ +cp=0 +r=0 +cnt.=0 +Do i=1 To 7 + p=pool.i + If p<>cp Then + r=r+1 + res=rank.i left(name.i,8) lo.p hi.p r i ii.p/n.p + If res=sourceline(i+1) Then cnt.ok=cnt.ok+1 + Say res + cp=p + End +Say cnt.ok 'correct lines' diff --git a/Task/Ray-casting-algorithm/Fortran/ray-casting-algorithm-3.f b/Task/Ray-casting-algorithm/Fortran/ray-casting-algorithm-3.f index ef7ed600e0..2e64c2932e 100644 --- a/Task/Ray-casting-algorithm/Fortran/ray-casting-algorithm-3.f +++ b/Task/Ray-casting-algorithm/Fortran/ray-casting-algorithm-3.f @@ -20,7 +20,7 @@ program Pointpoly polys(3) = create_polygon(pts, (/ 1,5, 5,4, 4,8, 8,7, 7,3, 3,2, 2,5 /) ) polys(4) = create_polygon(pts, (/ 11,12, 12,10, 10,13, 13,14, 14,9, 9,11 /) ) - names = (/ "square", "square hole", "strange", "exagon" /) + names = (/ "square", "square hole", "strange", "hexagon" /) p = (/ point(5,5), point(5, 8), point(-10, 5), point(0,5), point(10,5), & point(8,5), point(10,10) /) diff --git a/Task/Ray-casting-algorithm/Perl/ray-casting-algorithm-2.pl b/Task/Ray-casting-algorithm/Perl/ray-casting-algorithm-2.pl index 6feac4d077..1a72789cc1 100644 --- a/Task/Ray-casting-algorithm/Perl/ray-casting-algorithm-2.pl +++ b/Task/Ray-casting-algorithm/Perl/ray-casting-algorithm-2.pl @@ -10,7 +10,7 @@ sub create_polygon for(my $i = 0; $i < $#$sides; $i += 2) { push @poly, [ $pts->[$sides->[$i]-1], $pts->[$sides->[$i+1]-1] ]; } - @poly; + \@poly; } my @pts = ( point(0,0), point(10,0), point(10,10), point(0,10), @@ -18,20 +18,22 @@ sub create_polygon point(0,5), point(10,5), point(3,0), point(7,0), point(7,10), point(3,10) ); -my @squared = create_polygon(\@pts, [ 1,2, 2,3, 3,4, 4,1 ] ); -my @squaredhole = create_polygon(\@pts, [ 1,2, 2,3, 3,4, 4,1, 5,6, 6,7, 7,8, 8,5 ] ); -my @strange = create_polygon(\@pts, [ 1,5, 5,4, 4,8, 8,7, 7,3, 3,2, 2,5 ] ); -my @exagon = create_polygon(\@pts, [ 11,12, 12,10, 10,13, 13,14, 14,9, 9,11 ]) ; +my %pgs = ( + squared => create_polygon(\@pts, [ 1,2, 2,3, 3,4, 4,1 ] ), + squaredhole => create_polygon(\@pts, [ 1,2, 2,3, 3,4, 4,1, 5,6, 6,7, 7,8, 8,5 ] ), + strange => create_polygon(\@pts, [ 1,5, 5,4, 4,8, 8,7, 7,3, 3,2, 2,5 ] ), + exagon => create_polygon(\@pts, [ 11,12, 12,10, 10,13, 13,14, 14,9, 9,11 ]) , +); my @p = ( point(5,5), point(5, 8), point(-10, 5), point(0,5), point(10,5), & point(8,5), point(10,10) ); -foreach my $pol ( qw(squared squaredhole strange exagon) ) { +foreach my $pol ( sort keys %pgs ) { no strict 'refs'; print "$pol\n"; - my @rp = @{$pol}; + my $rp = $pgs{$pol}; foreach my $tp ( @p ) { print "\t($tp->[0],$tp->[1]) " . - ( point_in_polygon($tp, \@rp) ? "INSIDE" : "OUTSIDE" ) . "\n"; + ( point_in_polygon($tp, $rp) ? "INSIDE" : "OUTSIDE" ) . "\n"; } } diff --git a/Task/Ray-casting-algorithm/Python/ray-casting-algorithm-1.py b/Task/Ray-casting-algorithm/Python/ray-casting-algorithm-1.py index 95dfe0db14..c8c57bfbd5 100644 --- a/Task/Ray-casting-algorithm/Python/ray-casting-algorithm-1.py +++ b/Task/Ray-casting-algorithm/Python/ray-casting-algorithm-1.py @@ -47,8 +47,8 @@ def ispointinside(p, poly): for edge in poly.edges )) def polypp(poly): - print "\n Polygon(name='%s', edges=(" % poly.name - print ' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))' + print ("\n Polygon(name='%s', edges=(" % poly.name) + print (' ', ',\n '.join(str(e) for e in poly.edges) + '\n ))') if __name__ == '__main__': polys = [ @@ -91,12 +91,12 @@ def polypp(poly): Pt(x=10, y=5), Pt(x=8, y=5), Pt(x=10, y=10)) - print "\n TESTING WHETHER POINTS ARE WITHIN POLYGONS" + print ("\n TESTING WHETHER POINTS ARE WITHIN POLYGONS") for poly in polys: polypp(poly) - print ' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) - for p in testpoints[:3]) - print ' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) - for p in testpoints[3:6]) - print ' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) - for p in testpoints[6:]) + print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) + for p in testpoints[:3])) + print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) + for p in testpoints[3:6])) + print (' ', '\t'.join("%s: %s" % (p, ispointinside(p, poly)) + for p in testpoints[6:])) diff --git a/Task/Ray-casting-algorithm/REXX/ray-casting-algorithm.rexx b/Task/Ray-casting-algorithm/REXX/ray-casting-algorithm.rexx index 9af49f411d..e2e2636cff 100644 --- a/Task/Ray-casting-algorithm/REXX/ray-casting-algorithm.rexx +++ b/Task/Ray-casting-algorithm/REXX/ray-casting-algorithm.rexx @@ -1,49 +1,52 @@ -/*REXX program to see if a horizontal ray from pt P intersects a polygon*/ -call points 5 5, 5 8, -10 5, 0 5, 10 5, 8 5, 10 10 -call polygon 0 0, 10 0, 10 10, 0 10 ; call test 'square' -call polygon 0 0, 10 0, 10 10, 0 10, 2.5 2.5, 7.5 2.5, 7.5 7.5, 2.5 7.5 ; call test 'square hole' -call polygon 0 0, 2.5 2.5, 0 10, 2.5 7.5, 7.5 7.5, 10 10, 10 0 ; call test 'irregular' -call polygon 3 0, 7 0, 10 5, 7 10, 3 10, 0 5 ; call test 'exagon' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────IN_OUT subroutine────────────────────*/ -in_out: procedure expose point. poly. /*note: // is division remainder.*/ -parse arg p; #=0; do side=1 to poly.0 by 2; #=#+ray_intersect(p,side) +/*REXX pgm checks to see if a horizontal ray from point P intersects a polygon*/ +call points 5 5, 5 8, -10 5, 0 5, 10 5, 8 5, 10 10 +A=2.5; B=7.5 /*◄───for shorter args*/ +call poly 0 0, 10 0, 10 10, 0 10 ; call test 'square' +call poly 0 0, 10 0, 10 10, 0 10, A A, B A, B B, A B ; call test 'square hole +call poly 0 0, A A, 0 10, A B, B B, 10 10, 10 0 ; call test 'irregular' +call poly 3 0, 7 0, 10 5, 7 10, 3 10, 0 5 ; call test 'hexagon' +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +in_out: procedure expose point. poly.; parse arg p; #=0 + do side=1 to poly.0 by 2; #=#+ray_intersect(p,side) end /*side*/ -return #//2 /*odd=inside, return 1; else 0.*/ -/*──────────────────────────────────POINTS subroutine───────────────────*/ -points: n=0; v='POINT.'; do j=1 for arg(); n=n+1 - call value v||n'.X', word(arg(j),1) - call value v||n'.Y', word(arg(j),2) - end /*j*/ -call value v'0',n /*define number of points.*/ -return -/*──────────────────────────────────POLYGON subroutine──────────────────*/ -polygon: n=0; v='POLY.'; parse arg Fx Fy + return #//2 /*ODD is inside. EVEN is outside. */ +/*────────────────────────────────────────────────────────────────────────────*/ +points: n=0; v='POINT.'; do j=1 for arg(); n=n+1; _=arg(j); parse var _ xx yy + call value v||n'.X',xx + call value v||n'.Y',yy + end /*j*/ + call value v'0',n /*define the number of points.*/ + return +/*────────────────────────────────────────────────────────────────────────────*/ +poly: n=0; v='POLY.'; parse arg Fx Fy /* [↓] process the X,Y points*/ - do j=1 for arg(); _=arg(j); n=n+1 - call value v||n'.X', word(_,1); call value v||n'.Y', word(_,2) - if n//2 then iterate - n=n+1 - call value v||n'.X', word(_,1); call value v||n'.Y', word(_,2) - end /*j*/ -n=n+1 -call value v||n".X", Fx; call value v||n".Y", Fy; call value v'0',n -return /*POLY.0 is # of segments/sides.*/ -/*──────────────────────────────────RAY_INTERSECT subroutine────────────*/ -ray_intersect: procedure expose point. poly.; parse arg ?,s; sp=s+1 -epsilon = '1e'||(digits()%2); infinity = '1e'||(digits()*2) -Px=point.?.x; Py=point.?.y -Ax=poly.s.x; Bx=poly.sp.x ; Ay=poly.s.y; By=poly.sp.y -if Ay>By then parse value Ax Ay Bx By with Bx By Ax Ay -if Py=Ay | Py=By then Py=Py+epsilon -if PyBy | Px>max(Ax,Bx) then return 0 -if Px=m_red -/*──────────────────────────────────TEST procedure──────────────────────*/ -test: say; do k=1 for point.0 /*traipse through each test point*/ - say ' ['arg(1)"] point:" right(point.k.x','point.k.y, 9), - " is " word('outside inside', in_out(k)+1) - end /*k*/ -return + do j=1 for arg(); n=n+1; _=arg(j); parse var _ xx yy + call value v||n'.X', word(_,1); call value v||n'.Y', word(_,2) + if n//2 then iterate + n=n+1 + call value v||n'.X', word(_,1); call value v||n'.Y', word(_,2) + end /*j*/ + n=n+1 + call value v||n".X", Fx; call value v||n".Y", Fy; call value v'0',n + return /*POLY.0 is number of segments/sides.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +ray_intersect: procedure expose point. poly.; parse arg ?,s; sp=s+1 + epsilon='1e' || (digits()%2); infinity='1e' || (digits() *2) + Px=point.?.x; Ax=poly.s.x; Ay=poly.s.y + Py=point.?.y; Bx=poly.sp.x; By=poly.sp.y /* [↓] do a swap*/ + if Ay>By then parse value Ax Ay Bx By with Bx By Ax Ay + if Py=Ay | Py=By then Py=Py+epsilon + if PyBy | Px>max(Ax,Bx) then return 0 + if Px=m_red +/*────────────────────────────────────────────────────────────────────────────*/ +test: say; do k=1 for point.0; say right(' ['arg(1)"] point:",30), + right(point.k.x', 'point.k.y, 9) " is ", + word('outside inside', in_out(k)+1) + end /*k*/ + return diff --git a/Task/Ray-casting-algorithm/Scala/ray-casting-algorithm.scala b/Task/Ray-casting-algorithm/Scala/ray-casting-algorithm.scala new file mode 100644 index 0000000000..8397fd1a45 --- /dev/null +++ b/Task/Ray-casting-algorithm/Scala/ray-casting-algorithm.scala @@ -0,0 +1,46 @@ +case class Figure(name: String, edges: ((Double, Double), (Double, Double))*) {} + +object Ray_casting extends App { + import Math._ + import Double._ + + val figures = Array(Figure("Square", ((0.0, 0.0), (10.0, 0.0)), + ((10.0, 0.0), (10.0, 10.0)), ((10.0, 10.0), (0.0, 10.0)), + ((0.0, 10.0), (0.0, 0.0))), + Figure("Square hole", ((0.0, 0.0), (10.0, 0.0)), ((10.0, 0.0), (10.0, 10.0)), + ((10.0, 10.0), (0.0, 10.0)), ((0.0, 10.0), (0.0, 0.0)), + ((2.5, 2.5), (7.5, 2.5)), ((7.5, 2.5), (7.5, 7.5)), + ((7.5, 7.5), (2.5, 7.5)), ((2.5, 7.5), (2.5, 2.5))), + Figure("Strange", ((0.0, 0.0), (2.5, 2.5)), ((2.5, 2.5), (0.0, 10.0)), + ((0.0, 10.0), (2.5, 7.5)), ((2.5, 7.5), (7.5, 7.5)), + ((7.5, 7.5), (10.0, 10.0)), ((10.0, 10.0), (10.0, 0.0)), + ((10.0, 0), (2.5, 2.5))), + Figure("Exagon", ((3.0, 0.0), (7.0, 0.0)), ((7.0, 0.0), (10.0, 5.0)), + ((10.0, 5.0), (7.0, 10.0)), ((7.0, 10.0), (3.0, 10.0)), + ((3.0, 10.0), (0.0, 5.0)), ((0.0, 5.0), (3.0, 0.0)))) + + val points = Array((5.0, 5.0), (5.0, 8.0), (-10.0, 5.0), (0.0, 5.0), (10.0, 5.0), (8.0, 5.0), (10.0, 10.0)) + + figures foreach { f => + println("Is point inside figure " + f.name + '?') + points foreach { p => println(" " + p + ": " + contains(f, p)) } + println + } + + private def raySegI(p: (Double, Double), e: ((Double, Double), (Double, Double))): Boolean = { + val epsilon = 0.00001 + if (e._1._2 > e._2._2) + return raySegI(p, (e._2, e._1)) + if (p._2 == e._1._2 || p._2 == e._2._2) + return raySegI((p._1, p._2 + epsilon), e) + if (p._2 > e._2._2 || p._2 < e._1._2 || p._1 > max(e._1._1, e._2._1)) + return false + if (p._1 < min(e._1._1, e._2._1)) + return true + val blue = if (abs(e._1._1 - p._1) > MinValue) (p._2 - e._1._2) / (p._1 - e._1._1) else MaxValue + val red = if (abs(e._1._1 - e._2._1) > MinValue) (e._2._2 - e._1._2) / (e._2._1 - e._1._1) else MaxValue + blue >= red + } + + private def contains(f: Figure, p: (Double, Double)) = f.edges.count(raySegI(p, _)) % 2 != 0 +} diff --git a/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-1.lisp b/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-1.lisp new file mode 100644 index 0000000000..69179b972d --- /dev/null +++ b/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-1.lisp @@ -0,0 +1,10 @@ +;config-file.txt +;lisp comments works normally as it would in lisp +#S(config-file +:fullname "Foo Barber" +:favoritefruit "banana" +:needspeeling t +:seedsremoved nil +:otherfamily '("Rhu Barber" "Harry Barber") +;:will "not be read" +) diff --git a/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-2.lisp b/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-2.lisp new file mode 100644 index 0000000000..c0b04865a9 --- /dev/null +++ b/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-2.lisp @@ -0,0 +1,9 @@ +;config-file.lisp +(defstruct config-file :fullname :favoritefruit :needspeeling :seedsremoved :otherfamily) +(with-open-file (in "config-file.txt") + (defvar contents (read in)) + (format t "~a~%" contents) + ;reading the config-file into a structure gives us + ;some helper functions to access individualy each element + (format t "Fullname: ~a~%" (config-file-fullname contents)) + (format t "Contents is a config-file? ~a~%" (config-file-p contents))) diff --git a/Task/Read-a-configuration-file/DCL/read-a-configuration-file.dcl b/Task/Read-a-configuration-file/DCL/read-a-configuration-file.dcl new file mode 100644 index 0000000000..e8191ec45d --- /dev/null +++ b/Task/Read-a-configuration-file/DCL/read-a-configuration-file.dcl @@ -0,0 +1,18 @@ +$ open input config.ini +$ loop: +$ read /end_of_file = done input line +$ line = f$edit( line, "trim" ) ! removes leading and trailing spaces or tabs +$ if f$length( line ) .eq. 0 then $ goto loop +$ first_character = f$extract( 0, 1, line ) +$ if first_character .eqs. "#" .or. first_character .eqs. ";" then $ goto loop +$ equal_sign_offset = f$locate( "=", line ) +$ length_of_line = f$length( line ) +$ if equal_sign_offset .ne. length_of_line then $ line = f$extract( 0, equal_sign_offset, line ) + " " + f$extract( equal_sign_offset + 1, length_of_line, line ) +$ option_name = f$element( 0, " ", line ) +$ parameter_data = line - option_name - " " +$ if parameter_data .eqs. "" then $ parameter_data = "true" +$ 'option_name = parameter_data +$ show symbol 'option_name +$ goto loop +$ done: +$ close input diff --git a/Task/Read-a-configuration-file/VBScript/read-a-configuration-file.vb b/Task/Read-a-configuration-file/VBScript/read-a-configuration-file.vb new file mode 100644 index 0000000000..28c2b71036 --- /dev/null +++ b/Task/Read-a-configuration-file/VBScript/read-a-configuration-file.vb @@ -0,0 +1,38 @@ +Set ofso = CreateObject("Scripting.FileSystemObject") +Set config = ofso.OpenTextFile(ofso.GetParentFolderName(WScript.ScriptFullName)&"\config.txt",1) + +config_out = "" + +Do Until config.AtEndOfStream + line = config.ReadLine + If Left(line,1) <> "#" And Len(line) <> 0 Then + config_out = config_out & parse_var(line) & vbCrLf + End If +Loop + +WScript.Echo config_out + +Function parse_var(s) + 'boolean false + If InStr(s,";") Then + parse_var = Mid(s,InStr(1,s,";")+2,Len(s)-InStr(1,s,";")+2) & " = FALSE" + 'boolean true + ElseIf UBound(Split(s," ")) = 0 Then + parse_var = s & " = TRUE" + 'multiple parameters + ElseIf InStr(s,",") Then + var = Left(s,InStr(1,s," ")-1) + params = Split(Mid(s,InStr(1,s," ")+1,Len(s)-InStr(1,s," ")+1),",") + n = 1 : tmp = "" + For i = 0 To UBound(params) + parse_var = parse_var & var & "(" & n & ") = " & LTrim(params(i)) & vbCrLf + n = n + 1 + Next + 'single var and paramater + Else + parse_var = Left(s,InStr(1,s," ")-1) & " = " & Mid(s,InStr(1,s," ")+1,Len(s)-InStr(1,s," ")+1) + End If +End Function + +config.Close +Set ofso = Nothing diff --git a/Task/Read-a-file-line-by-line/C-sharp/read-a-file-line-by-line-1.cs b/Task/Read-a-file-line-by-line/C-sharp/read-a-file-line-by-line-1.cs index 3e4de15795..b6c5abf382 100644 --- a/Task/Read-a-file-line-by-line/C-sharp/read-a-file-line-by-line-1.cs +++ b/Task/Read-a-file-line-by-line/C-sharp/read-a-file-line-by-line-1.cs @@ -1,2 +1,2 @@ -foreach (string readLine in File.ReadLines("FileName") +foreach (string readLine in File.ReadLines("FileName")) DoSomething(readLine); diff --git a/Task/Read-a-file-line-by-line/DCL/read-a-file-line-by-line.dcl b/Task/Read-a-file-line-by-line/DCL/read-a-file-line-by-line.dcl new file mode 100644 index 0000000000..6df871c7e2 --- /dev/null +++ b/Task/Read-a-file-line-by-line/DCL/read-a-file-line-by-line.dcl @@ -0,0 +1,6 @@ +$ open input input.txt +$ loop: +$ read /end_of_file = done input line +$ goto loop +$ done: +$ close input diff --git a/Task/Read-a-file-line-by-line/Elixir/read-a-file-line-by-line.elixir b/Task/Read-a-file-line-by-line/Elixir/read-a-file-line-by-line.elixir new file mode 100644 index 0000000000..7b84c51f3a --- /dev/null +++ b/Task/Read-a-file-line-by-line/Elixir/read-a-file-line-by-line.elixir @@ -0,0 +1,23 @@ + defmodule FileReader do + # Create a File.Stream and inspect each line + def by_line(path) do + File.stream!(path) + |> Stream.map(&(IO.inspect(&1))) + |> Stream.run + end + + def bin_line(path) do + # Build the stream in binary instead for performance increase + case File.open(path) do + # File returns a tuple, {:ok,file}, if successful + {:ok, file} -> + IO.binstream(file, :line) + |> Stream.map(&(IO.inspect(&1))) + |> Stream.run + # And returns {:error,reason} if unsuccessful + {:error,reason} -> + # Use Erlang's format_error to return an error string + :file.format_error(reason) + end + end + end diff --git a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-4.rexx b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-4.rexx new file mode 100644 index 0000000000..13e6ad18ab --- /dev/null +++ b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-4.rexx @@ -0,0 +1,11 @@ +/* Also works with Regina if you state OPTIONS AREXX_BIFS ; OPTIONS AREXX_SEMANTICS */ +filename='file.txt' +contents='' +IF Open(filehandle,filename,'READ') THEN DO UNTIL EOF(filehandle) + line=ReadLn(filehandle) + SAY line + contents=contents || line || '0a'x + END +ELSE EXIT 20 +CALL Close(filehandle) +EXIT 0 diff --git a/Task/Read-a-file-line-by-line/Rust/read-a-file-line-by-line.rust b/Task/Read-a-file-line-by-line/Rust/read-a-file-line-by-line.rust index a2a9b733c4..8535a66b3b 100644 --- a/Task/Read-a-file-line-by-line/Rust/read-a-file-line-by-line.rust +++ b/Task/Read-a-file-line-by-line/Rust/read-a-file-line-by-line.rust @@ -1,10 +1,9 @@ -use std::io::BufferedReader; -use std::io::File; +use std::io::{BufReader,BufRead}; +use std::fs::File; fn main() { - let path = Path::new("file.txt"); - let mut file = BufferedReader::new(File::open(&path)); - for line in file.lines() { + let file = File::open("file.txt").unwrap(); + for line in BufReader::new(file).lines() { println!("{}", line.unwrap()); } } diff --git a/Task/Read-a-file-line-by-line/VBScript/read-a-file-line-by-line.vb b/Task/Read-a-file-line-by-line/VBScript/read-a-file-line-by-line.vb new file mode 100644 index 0000000000..8ccbeea511 --- /dev/null +++ b/Task/Read-a-file-line-by-line/VBScript/read-a-file-line-by-line.vb @@ -0,0 +1,8 @@ +FilePath = "" +Set objFSO = CreateObject("Scripting.FileSystemObject") +Set objFile = objFSO.OpenTextFile(FilePath,1) +Do Until objFile.AtEndOfStream + WScript.Echo objFile.ReadLine +Loop +objFile.Close +Set objFSO = Nothing diff --git a/Task/Read-a-specific-line-from-a-file/D/read-a-specific-line-from-a-file-1.d b/Task/Read-a-specific-line-from-a-file/D/read-a-specific-line-from-a-file-1.d new file mode 100644 index 0000000000..dcfd8748d5 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/D/read-a-specific-line-from-a-file-1.d @@ -0,0 +1,6 @@ +void main() { + import std.stdio, std.file, std.string; + auto file_lines = readText("input.txt").splitLines(); + //file_lines becomes an array of strings, each line is one element + writeln((file_lines.length > 6) ? file_lines[6] : "line not found"); +} diff --git a/Task/Read-a-specific-line-from-a-file/D/read-a-specific-line-from-a-file.d b/Task/Read-a-specific-line-from-a-file/D/read-a-specific-line-from-a-file-2.d similarity index 100% rename from Task/Read-a-specific-line-from-a-file/D/read-a-specific-line-from-a-file.d rename to Task/Read-a-specific-line-from-a-file/D/read-a-specific-line-from-a-file-2.d diff --git a/Task/Read-a-specific-line-from-a-file/VBScript/read-a-specific-line-from-a-file.vb b/Task/Read-a-specific-line-from-a-file/VBScript/read-a-specific-line-from-a-file.vb new file mode 100644 index 0000000000..c3782d2ef8 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/VBScript/read-a-specific-line-from-a-file.vb @@ -0,0 +1,18 @@ +Function read_line(filepath,n) + Set objFSO = CreateObject("Scripting.FileSystemObject") + Set objFile = objFSO.OpenTextFile(filepath,1) + arrLines = Split(objFile.ReadAll,vbCrLf) + If UBound(arrLines) >= n-1 Then + If arrLines(n-1) <> "" Then + read_line = arrLines(n-1) + Else + read_line = "Line " & n & " is null." + End If + Else + read_line = "Line " & n & " does not exist." + End If + objFile.Close + Set objFSO = Nothing +End Function + +WScript.Echo read_line("c:\temp\input.txt",7) diff --git a/Task/Read-entire-file/AppleScript/read-entire-file.applescript b/Task/Read-entire-file/AppleScript/read-entire-file.applescript new file mode 100644 index 0000000000..34dc2f0630 --- /dev/null +++ b/Task/Read-entire-file/AppleScript/read-entire-file.applescript @@ -0,0 +1,9 @@ +set pathToTextFile to ((path to desktop folder as string) & "testfile.txt") + +-- short way: open, read and close in one step +set fileContent to read file pathToTextFile + +-- long way: open a file reference, read content and close access +set fileRef to open for access pathToTextFile +set fileContent to read fileRef +close access fileRef diff --git a/Task/Read-entire-file/AutoIt/read-entire-file.autoit b/Task/Read-entire-file/AutoIt/read-entire-file.autoit new file mode 100644 index 0000000000..ba2be77f36 --- /dev/null +++ b/Task/Read-entire-file/AutoIt/read-entire-file.autoit @@ -0,0 +1,3 @@ +$fileOpen = FileOpen("file.txt") +$fileRead = FileRead($fileOpen) +FileClose($fileOpen) diff --git a/Task/Read-entire-file/C++/read-entire-file.cpp b/Task/Read-entire-file/C++/read-entire-file.cpp index 22dcb7f898..544740280d 100644 --- a/Task/Read-entire-file/C++/read-entire-file.cpp +++ b/Task/Read-entire-file/C++/read-entire-file.cpp @@ -3,16 +3,21 @@ #include #include -int main( ) { - std::ifstream infile( "sample.txt" ) ; - if ( infile ) { - std::string fileData( ( std::istreambuf_iterator ( infile ) ) , - std::istreambuf_iterator ( ) ) ; - infile.close( ) ; ; - return 0 ; +int main( ) +{ + if (std::ifstream infile("sample.txt")) + { + // construct string from iterator range + std::string fileData(std::istreambuf_iterator(infile), std::istreambuf_iterator()); + + cout << "File has " << fileData.size() << "chars\n"; + + // don't need to manually close the ifstream; it will release the file when it goes out of scope + return 0; } - else { - std::cout << "file not found!\n" ; - return 1 ; + else + { + std::cout << "file not found!\n"; + return 1; } } diff --git a/Task/Read-entire-file/Elixir/read-entire-file.elixir b/Task/Read-entire-file/Elixir/read-entire-file.elixir new file mode 100644 index 0000000000..97590b28ec --- /dev/null +++ b/Task/Read-entire-file/Elixir/read-entire-file.elixir @@ -0,0 +1,23 @@ +defmodule FileReader do + # Read in the file + def read(path) do + case File.read(path) do + {:ok, body} -> + IO.inspect body + {:error,reason} -> + :file.format_error(reason) + end + end + + # Open the file path, then read in the file + def bit_read(path) do + case File.open(path) do + {:ok, file} -> + # :all can be replaced with :line, or with a positive integer to specify the number of characters to read. + IO.read(file,:all) + |> IO.inspect + {:error,reason} -> + :file.format_error(reason) + end + end +end diff --git a/Task/Read-entire-file/J/read-entire-file-1.j b/Task/Read-entire-file/J/read-entire-file-1.j index b6661bda94..803c469a08 100644 --- a/Task/Read-entire-file/J/read-entire-file-1.j +++ b/Task/Read-entire-file/J/read-entire-file-1.j @@ -1 +1,2 @@ - var=: 1!:1<'foo.txt' + require 'files' NB. not needed for J7 & later + var=: freads 'foo.txt' diff --git a/Task/Read-entire-file/J/read-entire-file-2.j b/Task/Read-entire-file/J/read-entire-file-2.j index 8d8a4c19f9..f07141988c 100644 --- a/Task/Read-entire-file/J/read-entire-file-2.j +++ b/Task/Read-entire-file/J/read-entire-file-2.j @@ -1,2 +1,2 @@ - require'jmf' + require 'jmf' JCHAR map_jmf_ 'var';'foo.txt' diff --git a/Task/Read-entire-file/Kotlin/read-entire-file.kotlin b/Task/Read-entire-file/Kotlin/read-entire-file.kotlin new file mode 100644 index 0000000000..a069cfdc05 --- /dev/null +++ b/Task/Read-entire-file/Kotlin/read-entire-file.kotlin @@ -0,0 +1,3 @@ +fun readText() { + val string = File("unixdict.txt").readText(charset = Charsets.UTF_8) +} diff --git a/Task/Read-entire-file/Python/read-entire-file-3.py b/Task/Read-entire-file/Python/read-entire-file-3.py new file mode 100644 index 0000000000..a430ff9069 --- /dev/null +++ b/Task/Read-entire-file/Python/read-entire-file-3.py @@ -0,0 +1,2 @@ +with open(filename) as f: + data = f.read() diff --git a/Task/Read-entire-file/Q/read-entire-file.q b/Task/Read-entire-file/Q/read-entire-file.q new file mode 100644 index 0000000000..a3e96d07f0 --- /dev/null +++ b/Task/Read-entire-file/Q/read-entire-file.q @@ -0,0 +1,4 @@ +q)file:read0`:file.txt +"First line of file" +"Second line of file" +"" diff --git a/Task/Read-entire-file/REXX/read-entire-file.rexx b/Task/Read-entire-file/REXX/read-entire-file-1.rexx similarity index 100% rename from Task/Read-entire-file/REXX/read-entire-file.rexx rename to Task/Read-entire-file/REXX/read-entire-file-1.rexx diff --git a/Task/Read-entire-file/REXX/read-entire-file-2.rexx b/Task/Read-entire-file/REXX/read-entire-file-2.rexx new file mode 100644 index 0000000000..f4522107eb --- /dev/null +++ b/Task/Read-entire-file/REXX/read-entire-file-2.rexx @@ -0,0 +1,16 @@ +/*REXX program reads a file and stores it as a continuous character str.*/ +Parse Version v +iFID = 'st.in' /*name of the input file. */ +If left(v,11)='REXX-Regina' |, + left(v,11)='REXX-ooRexx' Then Do + len=chars(iFid) /*size of the file */ + v = charin(iFid,,len) /*read entire file */ + End +Else Do /* for other Rexx Interpreters */ + v='' + Do while chars(iFid)>0 /* read the file chunk by chunk */ + v=v||charin(iFid,,500) + End + End +say 'v='v +say 'length(v)='length(v) diff --git a/Task/Read-entire-file/Rust/read-entire-file.rust b/Task/Read-entire-file/Rust/read-entire-file.rust index e81008b18a..4b2886cc1b 100644 --- a/Task/Read-entire-file/Rust/read-entire-file.rust +++ b/Task/Read-entire-file/Rust/read-entire-file.rust @@ -1,13 +1,15 @@ -// -*- rust v1.0-alpha -*- -use std::io::File; +use std::fs::File; +use std::io::Read; fn main() { - let mut file = File::open(&Path::new("somefile.txt")); - - // returns Vector of Bytes (Vec) - let contents = file.read_to_end().unwrap(); + let mut file = File::open("somefile.txt").unwrap(); - // To print the contents of the file - let filestr = String::from_utf8(contents).unwrap(); - println!("{}", filestr); + let mut contents: Vec = Vec::new(); + // Returns amount of bytes read and append the result to the buffer + let result = file.read_to_end(&mut contents).unwrap(); + println!("Read {} bytes", result); + + // To print the contents of the file + let filestr = String::from_utf8(contents).unwrap(); + println!("{}", filestr); } diff --git a/Task/Real-constants-and-functions/00META.yaml b/Task/Real-constants-and-functions/00META.yaml index a4efa5b7bb..436ab291c7 100644 --- a/Task/Real-constants-and-functions/00META.yaml +++ b/Task/Real-constants-and-functions/00META.yaml @@ -1,4 +1,5 @@ --- category: - Arithmetic operations +- Simple note: Basic language learning diff --git a/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions.logtalk b/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions.logtalk new file mode 100644 index 0000000000..b08941a9fa --- /dev/null +++ b/Task/Real-constants-and-functions/Logtalk/real-constants-and-functions.logtalk @@ -0,0 +1,16 @@ +:- object(constants_and_functions). + + :- public(show/0). + show :- + write('e = '), E is e, write(E), nl, + write('pi = '), PI is pi, write(PI), nl, + write('sqrt(2) = '), SQRT is sqrt(2), write(SQRT), nl, + % only base e logorithm is avaialable as a standard built-in function + write('log(2) = '), LOG is log(2), write(LOG), nl, + write('exp(2) = '), EXP is exp(2), write(EXP), nl, + write('abs(-1) = '), ABS is abs(-1), write(ABS), nl, + write('floor(-3.4) = '), FLOOR is floor(-3.4), write(FLOOR), nl, + write('ceiling(-3.4) = '), CEILING is ceiling(-3.4), write(CEILING), nl, + write('2 ** -3.4 = '), POWER is 2 ** -3.4, write(POWER), nl. + +:- end_object. diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx index 391ef85d96..60530b123b 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx @@ -1,36 +1,27 @@ -/*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure; r= /*returns principal SQRT of args.*/ - do j=1 for arg() /*process each argument specified*/ - a=arg(j) /*extract the argument specified*/ - do k=1 for words(a) /*process each number specified. */ - r=r sqrt_(word(a,k)) /*calculate sqrt, add to results.*/ - end /*k*/ /* [↑] process each # in Nth arg*/ - end /*j*/ /* [↑] process each #s in args. */ -return r /*return list of SQRTs calculated*/ -/*──────────────────────────────────SQRT_ subroutine────────────────────*/ -sqrt_: procedure; parse arg x; if x=0 then return 0 /*handle 0*/ -if pos(',',x)\==0 then x=space(translate(x,,","),0) /*elide comma.*/ -if \datatype(x,'N') then return '[n/a]' /*not numberic? not applicable*/ -ox=x /*save the original value of X. */ -x=abs(x) /*just use positive value of X. */ -d=digits() /*get the current precision. */ -m.=11 /*technique uses just enough digs*/ -numeric digits m. /*use "small" precision at first.*/ -numeric form /*force scientific form of number*/ -parse value format(x,2,1,,0) 'E0' with g 'E' _ . /*get X's exponent.*/ -g=g * .5'E'_ % 2 /*1st guesstimate for square root*/ -p=d + d%4 + 2 /*# of iterations (calculations).*/ - /*Note: to insure enough accuracy*/ - /*for the result, the precsion */ - /*during the SQRT calcuations is */ - /*increased by two extra digits. */ - do j=0 while p>9; m.j=p; p=p%2+1 /*compute the sizes of precision.*/ - end /*j*/ /* [↑] precisions stored in M. */ - /* [↓] da rubber meets da road. */ - do k=j+5 to 0 by -1 /*compute √ with increasing digs.*/ - numeric digits m.k /*each iteration, increase digits*/ - g=(g+x/g) * .5 /*do the nitty-gritty calculation*/ - end /*k*/ /* [↑] .5* is faster than /2 */ - /* [↓] normalize√──►original dig*/ -numeric digits d /*restore the original precision.*/ -return (g/1)left('i',ox<0) /*normalize, add possible suffix.*/ +/*──────────────────────────────────SQRT subroutine───────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0 /*handle 0 case.*/ +if \datatype(x,'N') then return '[n/a]' /*Not Applicable ───if not numeric.*/ +i=; if x<0 then do; x=-x; i='i'; end /*handle complex numbers if X is < 0.*/ +d=digits() /*get the current numeric precision. */ +m.=9 /*technique uses just enough digits. */ +h=d+6 /*use extra decimal digits for accuracy*/ +numeric digits 9 /*use "small" precision at first. */ +numeric form /*force scientific form of the number. */ +if fuzz()\==0 then numeric fuzz 0 /*just in case invoker has a FUZZ set.*/ +parse value format(x,2,1,,0) 'E0' with g 'E' _ . /*get the X's exponent.*/ + g=(g * .5) || 'e' || (_ % 2) /*1st guesstimate for the square root. */ + /* g= g * .5 'e' (_ % 2) */ /*a shorter & concise version of above.*/ + /*Note: to insure enough accuracy for */ + /* the result, the precision during */ + /* the SQRT calculations is increased */ + /* by two extra decimal digits. */ + do j=0 while h>9; m.j=h; h=h%2+1 /*compute the sizes (digs) of precision*/ + end /*j*/ /* [↑] precisions are stored in M. */ + /*now, we start to do the heavy lifting*/ + do k=j+5 to 0 by -1 /*compute the √ with increasing digs.*/ + numeric digits m.k /*each iteration, increase the digits. */ + g=(g+x/g) * .5 /*perform the nitty-gritty calculations*/ + end /*k*/ /* [↑] * .5 is faster than / 2 */ + /* [↓] normalize √ ──► original digits*/ +numeric digits d /* [↓] make answer complex if X < 0. */ +return (g/1)i /*normalize, and add possible I suffix.*/ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx index 053f669bd0..1ac457905c 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx @@ -1,13 +1,26 @@ -/*┌────────────────────────────────────────────────────────────────────┐ -┌─┘ √ └─┐ -│ While the above REXX code seems like it's doing a lot of extra work, │ -│ it saves a substantial amount of processing time when the precision │ -│ (DIGITs) is a lot greater than the default (which is nine digits). │ -│ │ -│ Indeed, when computing square roots in the hundreds (even thousands) │ -│ of digits, this technique reduces the amount of CPU processing time │ -│ by keeping the length of the computations to a minimum (due to a large │ -│ precision), while the accuracy at the beginning isn't important for │ -│ calculating the (first) guesstimate (the running square root guess). │ -└─┐ √ ┌─┘ - └────────────────────────────────────────────────────────────────────┘*/ + ╔════════════════════════════════════════════════════════════════════╗ +╔═╝ __ ╚═╗ +║ √ ║ +║ ║ +║ While the above REXX code seems like it's doing a lot of extra work, ║ +║ it saves a substantial amount of processing time when the precision ║ +║ (DIGITs) is a lot greater than the default (default is nine digits). ║ +║ ║ +║ Indeed, when computing square roots in the hundreds (even thousands) ║ +║ of digits, this technique reduces the amount of CPU processing time ║ +║ by keeping the length of the computations to a minimum (due to a large ║ +║ precision), while the accuracy at the beginning isn't important for ║ +║ calculating the (first) guesstimate (the running square root guess). ║ +║ ║ +║ Each iteration of K (approximately) doubles the number of digits, ║ +║ but takes almost four times longer to compute (actually, around 3.8). ║ +║ ║ +║ The REXX code could be streamlined (pruned) by removing the ║ +║ The NUMERIC FUZZ 0 statement can be removed if it is known ║ +║ that it is already set to zero. (which is the default). ║ +║ ║ +║ Also, the NUMERIC FORM statement can be removed if it is known ║ +║ that the form is SCIENTIFIC (which is the default). ║ +║ __ ║ +╚═╗ √ ╔═╝ + ╚════════════════════════════════════════════════════════════════════╝ diff --git a/Task/Record-sound/00DESCRIPTION b/Task/Record-sound/00DESCRIPTION index 4ce6b6715e..f5c02ea13d 100644 --- a/Task/Record-sound/00DESCRIPTION +++ b/Task/Record-sound/00DESCRIPTION @@ -1,6 +1,7 @@ {{omit from|AWK}} {{omit from|Brlcad}} {{omit from|HTML}} +{{omit from|LFE}} {{omit from|Logtalk}} {{omit from|Lotus 123 Macro Scripting}} {{omit from|Maxima}} diff --git a/Task/Record-sound/Common-Lisp/record-sound.lisp b/Task/Record-sound/Common-Lisp/record-sound.lisp new file mode 100644 index 0000000000..80e3bce4ce --- /dev/null +++ b/Task/Record-sound/Common-Lisp/record-sound.lisp @@ -0,0 +1,11 @@ +(defun record (n) + (with-open-file (in "/dev/dsp" :element-type '(unsigned-byte 8)) + (loop repeat n collect (read-byte in)) + ) + ) +(defun play (byte-list) + (with-open-file (out "/dev/dsp" :direction :output :element-type '(unsigned-byte 8) :if-exists :append) + (mapcar (lambda (b) (write-byte b out)) byte-list) + ) + ) +(play (record 65536)) diff --git a/Task/Reduced-row-echelon-form/360-Assembly/reduced-row-echelon-form.360 b/Task/Reduced-row-echelon-form/360-Assembly/reduced-row-echelon-form.360 new file mode 100644 index 0000000000..9e3c8fc02c --- /dev/null +++ b/Task/Reduced-row-echelon-form/360-Assembly/reduced-row-echelon-form.360 @@ -0,0 +1,158 @@ +* reduced row echelon form 27/08/2015 +RREF CSECT + USING RREF,R12 + LR R12,R15 + LA R10,1 lead=1 + LA R7,1 +LOOPR CH R7,NROWS do r=1 to nrows + BH ELOOPR + CH R10,NCOLS if lead>=ncols + BNL ELOOPR + LR R8,R7 i=r +WHILE LR R1,R8 do while m(i,lead)=0 + BCTR R1,0 + MH R1,NCOLS + LR R6,R10 lead + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R6,M(R1) m(i,lead) + LTR R6,R6 + BNZ EWHILE m(i,lead)<>0 + LA R8,1(R8) i=i+1 + CH R8,NROWS if i=nrows + BNE EIF + LR R8,R7 i=r + LA R10,1(R10) lead=lead+1 + CH R10,NCOLS if lead=ncols + BE ELOOPR +EIF B WHILE +EWHILE LA R9,1 +LOOPJ1 CH R9,NCOLS do j=1 to ncols + BH ELOOPJ1 + LR R1,R7 r + BCTR R1,0 + MH R1,NCOLS + LR R6,R9 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + LA R3,M(R1) R3=@m(r,j) + LR R1,R8 i + BCTR R1,0 + MH R1,NCOLS + LR R6,R9 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + LA R4,M(R1) R4=@m(i,j) + L R2,0(R3) + MVC 0(2,R3),0(R4) swap m(i,j),m(r,j) + ST R2,0(R4) + LA R9,1(R9) j=j+1 + B LOOPJ1 +ELOOPJ1 LR R1,R7 r + BCTR R1,0 + MH R1,NCOLS + LR R6,R10 lead + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R11,M(R1) n=m(r,lead) + CH R11,=H'1' if n^=1 + BE ELOOPJ2 + LA R9,1 +LOOPJ2 CH R9,NCOLS do j=1 to ncols + BH ELOOPJ2 + LR R1,R7 r + BCTR R1,0 + MH R1,NCOLS + LR R6,R9 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + LA R5,M(R1) R5=@m(i,j) + L R2,0(R5) m(r,j) + LR R1,R11 n + SRDA R2,32 + DR R2,R1 m(r,j)/n + ST R3,0(R5) m(r,j)=m(r,j)/n + LA R9,1(R9) j=j+1 + B LOOPJ2 +ELOOPJ2 LA R8,1 +LOOPI3 CH R8,NROWS do i=1 to nrows + BH ELOOPI3 + CR R8,R7 if i^=r + BE ELOOPJ3 + LR R1,R8 i + BCTR R1,0 + MH R1,NCOLS + LR R6,R10 lead + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R11,M(R1) n=m(i,lead) + LA R9,1 +LOOPJ3 CH R9,NCOLS do j=1 to ncols + BH ELOOPJ3 + LR R1,R8 i + BCTR R1,0 + MH R1,NCOLS + LR R6,R9 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + LA R4,M(R1) R4=@m(i,j) + L R5,0(R4) m(i,j) + LR R1,R7 r + BCTR R1,0 + MH R1,NCOLS + LR R6,R9 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R3,M(R1) m(r,j) + MR R2,R11 m(r,j)*n + SR R5,R3 m(i,j)-m(r,j)*n + ST R5,0(R4) m(i,j)=m(i,j)-m(r,j)*n + LA R9,1(R9) j=j+1 + B LOOPJ3 +ELOOPJ3 LA R8,1(R8) i=i+1 + B LOOPI3 +ELOOPI3 LA R10,1(R10) lead=lead+1 + LA R7,1(R7) r=r+1 + B LOOPR +ELOOPR LA R8,1 +LOOPI4 CH R8,NROWS do i=1 to nrows + BH ELOOPI4 + SR R10,R10 pgi=0 + LA R9,1 +LOOPJ4 CH R9,NCOLS do j=1 to ncols + BH ELOOPJ4 + LR R1,R8 i + BCTR R1,0 + MH R1,NCOLS + LR R6,R9 j + BCTR R6,0 + AR R1,R6 + SLA R1,2 + L R6,M(R1) m(i,j) + LA R3,PG + AR R3,R10 + XDECO R6,0(R3) edit m(i,j) + LA R10,12(10) pgi=pgi+12 + LA R9,1(R9) j=j+1 + B LOOPJ4 +ELOOPJ4 XPRNT PG,48 print m(i,j) + LA R8,1(R8) i=i+1 + B LOOPI4 +ELOOPI4 XR R15,R15 + BR R14 +NROWS DC H'3' +NCOLS DC H'4' +M DC F'1',F'2',F'-1',F'-4' + DC F'2',F'3',F'-1',F'-11' + DC F'-2',F'0',F'-3',F'22' +PG DC CL48' ' + YREGS + END RREF diff --git a/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-3.j b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-3.j new file mode 100644 index 0000000000..08118d8381 --- /dev/null +++ b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-3.j @@ -0,0 +1,37 @@ +mat=:".;._2]0 :0 + 1 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0 0 + 1 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0 + 1 0 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 + 0 1 0 0 0 0 1 0 0 0 0 0 0 0 _1 0 0 0 + 0 1 0 0 0 0 0 0 1 0 0 _1 0 0 0 0 0 0 + 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 _1 0 + 0 0 1 0 0 0 1 0 0 0 0 0 _1 0 0 0 0 0 + 0 0 1 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 + 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 _1 0 0 + 0 0 0 1 0 0 0 0 0 1 0 0 _1 0 0 0 0 0 + 0 0 0 0 1 0 0 1 0 0 0 0 0 _1 0 0 0 0 + 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 _1 0 + 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 _1 0 0 + 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 + 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 + 0 0 0 0 0 1 0 0 0 0 1 0 0 0 _1 0 0 0 +) + gauss_jordan mat +1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.435897 +0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.307692 +0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.512821 +0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0.717949 +0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0.487179 +0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0.205128 +0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0.282051 +0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0.333333 +0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 +0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0.512821 +0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0.641026 +0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0.717949 +0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0.769231 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0.512821 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0.820513 diff --git a/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx b/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx index ac2998b223..e183ed50b1 100644 --- a/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx +++ b/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx @@ -1,65 +1,47 @@ -/*REXX program to perform Reduced Row Echelon Form (RREF) on a matrix).*/ -cols = 0 /*maximum columns in any row. */ -maxW = 0 /*maximum width of any element. */ - @. = /*matrix to be constructed. */ -mat. = -mat.1 = ' 1 2 -1 -4 ' /*a few extra blanks can't hurt. */ -mat.2 = ' 2 3 -1 -11 ' -mat.3 = ' -2 0 -3 22 ' - - do r=1 until mat.r==''; _=mat.r /*build @.row.col from mat.X */ - do c=1 until _=''; parse var _ @.r.c _ - maxW = max(maxW, length(@.r.c)) +/*REXX program performs Reduced Row Echelon Form (RREF) on a matrix). */ +cols=0; w=0; @.=0 /*max cols in a row; max width; matrix.*/ +mat.=; mat.1= ' 1 2 -1 -4 ' + mat.2= ' 2 3 -1 -11 ' + mat.3= ' -2 0 -3 22 ' + do r=1 until mat.r==''; _=mat.r /*build @.row.col from mat.X */ + do c=1 until _=''; parse var _ @.r.c _ + w=max(w, length(@.r.c)) /*get max width of an element.*/ end /*c*/ - cols = max(cols, c) /*remember the max number of cols*/ - end /*r*/ - -rows = r - 1 /*adjust the row count (from DO).*/ -maxW = maxW + 1 /*bump the max width, better view*/ -call showMat 'original matrix' /*show the original matrix. */ - ! = 1 /*set the pointer to one. */ -/*═══════════════════════════════════Reduced Row Echelon Form on matrix.*/ - do r=1 for rows while cols>! /*start to do the heavy lifting. */ + cols=max(cols,c) /*remember max number of cols.*/ + end /*r*/ +rows=r-1 /*adjust the row count (from DO loop).*/ +w=w+1 /*bump maximum width for a better view.*/ +call showMat 'original matrix' /*display the original matrix to screen*/ +!=1 /*set the working column pointer to 1.*/ + /* ┌───────────────────────────────◄── Reduced Row Echelon Form on matrix.*/ + do r=1 for rows while cols>! /*begin to perform the heavy lifting. */ j=r - do while @.j.!==0; j=j+1 - if j==rows then do - j=r - !=!+1; if cols==! then leave r - end - end /*while*/ - - do w=1 for cols while j\==r /*swap rows J,R (but not if same)*/ - parse value @.r.w @.j.w with @.j.w @.w.w - end /*w*/ + do while @.j.!==0; j=j+1 + if j==rows then do; j=r; !=!+1; if cols==! then leave r; end + end /*while*/ + /* [↓] swap rows J,R (but not if same)*/ + do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._; end ?=@.r.! - do d=1 for cols while ?\=1 /*divide row J by @.r.p──unless≡1*/ - @.r.d = @.r.d / ? - end /*d*/ - - do k=1 for rows; ?=@.k.! /*sub (row K) *@.r.s from row K */ - if k==r | ?=0 then iterate /*skip if row k is the same as R */ - do s=1 for cols /*perform for the rest of the row*/ - @.k.s=@.k.s - ? * @.r.s - end /*s*/ - end /*k*/ - !=!+1 - end /*r*/ - -call showMat 'matrix RREF' /*show reduced row echelon form. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SHOWMAT subroutine──────────────────*/ -showMat: parse arg title; say -say center(title, 3+(cols+1)*maxW, '─'); say /*build a pretty title.*/ + do d=1 for cols while ?\=1; @.r.d=@.r.d/?; end /*d*/ + /* [↑] divide row J by @.r.p ──unless≡1*/ + do k=1 for rows; ?=@.k.! /*subtract (row K) @.r.s from row K.*/ + if k==r | ?=0 then iterate /*skip if row K is the same as row R.*/ + do s=1 for cols; @.k.s=@.k.s - ?*@.r.s; end /*s*/ + end /*k*/ /* [+] for the rest of numbers in row.*/ + !=!+1 /*bump the column pointer. */ + end /*r*/ - do r=1 for rows; _= - do c=1 for cols - if @.r.c=='' then do; say; say '*** error! ***'; say - say "matrix element isn't defined:" - say 'row' row", column" c'.'; say - exit 13 - end - _=_ right(@.r.c, maxW) - end /*c*/ - say _ - end /*r*/ +call showMat 'matrix RREF' /*display the reduced row echelon form.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +showMat: parse arg title; say; say center(title, 3+(cols+1)*w, '─'); say + do r=1 for rows; _= + do c=1 for cols + if @.r.c=='' then do; say "***error!*** matrix element isn't defined:" + say 'row' row", column" c'.'; exit 13 + end + _=_ right(@.r.c,w) + end /*c*/ + say _ /*display a row of the matrix to screen*/ + end /*r*/ return diff --git a/Task/Regular-expressions/ABAP/regular-expressions.abap b/Task/Regular-expressions/ABAP/regular-expressions.abap new file mode 100644 index 0000000000..bfa1b7fdc9 --- /dev/null +++ b/Task/Regular-expressions/ABAP/regular-expressions.abap @@ -0,0 +1,11 @@ +DATA: text TYPE string VALUE 'This is a Test'. + +FIND FIRST OCCURRENCE OF REGEX 'is' IN text. +IF sy-subrc = 0. + cl_demo_output=>write( 'Regex matched' ). +ENDIF. + +REPLACE ALL OCCURRENCES OF REGEX '[t|T]est' IN text WITH 'Regex'. + +cl_demo_output=>write( text ). +cl_demo_output=>display( diff --git a/Task/Regular-expressions/Elixir/regular-expressions-1.elixir b/Task/Regular-expressions/Elixir/regular-expressions-1.elixir new file mode 100644 index 0000000000..be0adad09e --- /dev/null +++ b/Task/Regular-expressions/Elixir/regular-expressions-1.elixir @@ -0,0 +1,2 @@ +str = "This is a string" +if str =~ ~r/string$/, do: IO.inspect "str ends with 'string'" diff --git a/Task/Regular-expressions/Elixir/regular-expressions-2.elixir b/Task/Regular-expressions/Elixir/regular-expressions-2.elixir new file mode 100644 index 0000000000..43689e4c52 --- /dev/null +++ b/Task/Regular-expressions/Elixir/regular-expressions-2.elixir @@ -0,0 +1,2 @@ +str =~ ~r/this/ # => false +str =~ ~r/this/i # => true diff --git a/Task/Regular-expressions/Elixir/regular-expressions-3.elixir b/Task/Regular-expressions/Elixir/regular-expressions-3.elixir new file mode 100644 index 0000000000..1b6e7c9620 --- /dev/null +++ b/Task/Regular-expressions/Elixir/regular-expressions-3.elixir @@ -0,0 +1,2 @@ +str1 = ~r/a/ |> Regex.replace(str,"another") +str2 = str1 |> String.replace(~r/another/,"even another") diff --git a/Task/Regular-expressions/Elixir/regular-expressions-4.elixir b/Task/Regular-expressions/Elixir/regular-expressions-4.elixir new file mode 100644 index 0000000000..8ab320020d --- /dev/null +++ b/Task/Regular-expressions/Elixir/regular-expressions-4.elixir @@ -0,0 +1 @@ +str3 = ~r/another/ |> Regex.replace(str2, fn x -> "#{String.upcase(x)}" end) diff --git a/Task/Regular-expressions/Emacs-Lisp/regular-expressions.l b/Task/Regular-expressions/Emacs-Lisp/regular-expressions.l new file mode 100644 index 0000000000..0ce3b82ad8 --- /dev/null +++ b/Task/Regular-expressions/Emacs-Lisp/regular-expressions.l @@ -0,0 +1,18 @@ +(defun match (word str) + (setq pos (string-match word str) ) + (if pos + (progn + (insert (format "%s found at position %d in: %s\n" word pos str) ) + (setq regex (format "^.+%s" word) ) + (setq str (replace-regexp-in-string regex (format "left %s" word) str) ) + (setq regex (format "%s.+$" word) ) + (setq str (replace-regexp-in-string regex (format "%s right" word) str) ) + (insert (format "result: %s\n" str) )) + (insert (format "%s not found in: %s\n" word str) ))) + +(setq str1 "before center after" str2 "before centre after") + +(progn + (match "center" str1) + (insert "\n") + (match "center" str2) ) diff --git a/Task/Regular-expressions/JavaScript/regular-expressions-1.js b/Task/Regular-expressions/JavaScript/regular-expressions-1.js index d978f6dc2d..4990eac970 100644 --- a/Task/Regular-expressions/JavaScript/regular-expressions-1.js +++ b/Task/Regular-expressions/JavaScript/regular-expressions-1.js @@ -1,7 +1,7 @@ var subject = "Hello world!"; // Two different ways to create the RegExp object -// Both examples use the exact same pattern... matching "hello" +// Both examples use the exact same pattern... matching "hello " var re_PatternToMatch = /Hello (World)/i; // creates a RegExp literal with case-insensitivity var re_PatternToMatch2 = new RegExp("Hello (World)", "i"); diff --git a/Task/Regular-expressions/VBScript/regular-expressions.vb b/Task/Regular-expressions/VBScript/regular-expressions.vb new file mode 100644 index 0000000000..390859af48 --- /dev/null +++ b/Task/Regular-expressions/VBScript/regular-expressions.vb @@ -0,0 +1,9 @@ +text = "I need more coffee!!!" +Set regex = New RegExp +regex.Global = True +regex.Pattern = "\s" +If regex.Test(text) Then + WScript.StdOut.Write regex.Replace(text,vbCrLf) +Else + WScript.StdOut.Write "No matching pattern" +End If diff --git a/Task/Remove-duplicate-elements/Elixir/remove-duplicate-elements.elixir b/Task/Remove-duplicate-elements/Elixir/remove-duplicate-elements.elixir new file mode 100644 index 0000000000..d1f0f2b7ab --- /dev/null +++ b/Task/Remove-duplicate-elements/Elixir/remove-duplicate-elements.elixir @@ -0,0 +1,28 @@ +defmodule RC do + # hash table approach + def uniq1(list) do + Enum.reduce(list, HashSet.new, fn x, set -> Set.put(set, x) end) + |> Set.to_list + end + + # Sort approach + def uniq2(list), do: Enum.sort(list) |> uniq2([]) + + defp uniq2([], uniq), do: Enum.reverse(uniq) + defp uniq2([h|t], uniq) when h==hd(uniq), do: uniq2(t, uniq) + defp uniq2([h|t], uniq) , do: uniq2(t, [h | uniq]) + + # Go through the list approach + def uniq3(list), do: uniq3(list, []) + + defp uniq3([], uniq), do: Enum.reverse(uniq) + defp uniq3([h|t], uniq) do + if Enum.member?(uniq, h), do: uniq3(t, uniq), else: uniq3(t, [h | uniq]) + end +end + +list = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant'] +IO.inspect Enum.uniq(list) +IO.inspect RC.uniq1(list) +IO.inspect RC.uniq2(list) +IO.inspect RC.uniq3(list) diff --git a/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-1.hs b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-1.hs new file mode 100644 index 0000000000..11c90b26f0 --- /dev/null +++ b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-1.hs @@ -0,0 +1,3 @@ + print $ unique [4, 5, 4, 2, 3, 3, 4] + +[4,5,2,3] diff --git a/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-2.hs b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-2.hs new file mode 100644 index 0000000000..31836128c7 --- /dev/null +++ b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-2.hs @@ -0,0 +1,4 @@ +import qualified Data.Set as Set + +unique :: Ord a => [a] -> [a] +unique = Set.toList . Set.fromList diff --git a/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-3.hs b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-3.hs new file mode 100644 index 0000000000..2758faa4c1 --- /dev/null +++ b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-3.hs @@ -0,0 +1,8 @@ +import Data.Set + +unique :: Ord a => [a] -> [a] +unique = loop empty + where + loop s [] = [] + loop s (x : xs) | member x s = loop s xs + | otherwise = x : loop (insert x s) xs diff --git a/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-4.hs b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-4.hs new file mode 100644 index 0000000000..39b466b47c --- /dev/null +++ b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-4.hs @@ -0,0 +1,5 @@ +import Data.List + +unique :: Eq a => [a] -> [a] +unique [] = [] +unique (x : xs) = x : unique (filter (x /=) xs) diff --git a/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-5.hs b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-5.hs new file mode 100644 index 0000000000..a0f26aa46a --- /dev/null +++ b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements-5.hs @@ -0,0 +1,3 @@ +import Data.List +Data.List.nub :: Eq a => [a] -> [a] +Data.List.Unique.unique :: Ord a => [a] -> [a] diff --git a/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements.hs b/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements.hs deleted file mode 100644 index 84409b2ef9..0000000000 --- a/Task/Remove-duplicate-elements/Haskell/remove-duplicate-elements.hs +++ /dev/null @@ -1,2 +0,0 @@ -values = [1,2,3,2,3,4] -unique = List.nub values diff --git a/Task/Remove-duplicate-elements/JavaScript/remove-duplicate-elements-3.js b/Task/Remove-duplicate-elements/JavaScript/remove-duplicate-elements-3.js new file mode 100644 index 0000000000..c22471a924 --- /dev/null +++ b/Task/Remove-duplicate-elements/JavaScript/remove-duplicate-elements-3.js @@ -0,0 +1,3 @@ +Array.prototype.unique = function() { + return this.sort().reduce( (a,e) => e === a[a.length-1] ? a : (a.push(e), a), [] ) +} diff --git a/Task/Remove-duplicate-elements/JavaScript/remove-duplicate-elements-4.js b/Task/Remove-duplicate-elements/JavaScript/remove-duplicate-elements-4.js new file mode 100644 index 0000000000..5044e87825 --- /dev/null +++ b/Task/Remove-duplicate-elements/JavaScript/remove-duplicate-elements-4.js @@ -0,0 +1,3 @@ +Array.prototype.unique = function() { + return [... new Set(this)] +} diff --git a/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml new file mode 100644 index 0000000000..d1581794d3 --- /dev/null +++ b/Task/Remove-duplicate-elements/OCaml/remove-duplicate-elements-3.ocaml @@ -0,0 +1 @@ +List.sort_uniq compare [1;2;3;2;3;4] diff --git a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-1.rexx b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-1.rexx index 7814224902..1605f95983 100644 --- a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-1.rexx +++ b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-1.rexx @@ -1,12 +1,12 @@ -/*REXX program to remove duplicate elements (items) in a list. */ +/*REXX program removes any duplicate elements (items) that are in a list. */ $= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' say 'original list:' $ -say right(words($),13) ' words in the original list.'; say +say right(words($),17,'─') 'words in the original list.'; say +z=; @.= /*initialize the NEW list and index list*/ + do j=1 for words($); y=word($,j) /*process the words (items) in the list.*/ + if @.y=='' then z=z y; @.y=. /*Not duplicated? Add to Z list, @ array*/ + end /*j*/ - do j=words($) by -1 to 1; y=word($,j) /*process words in the list, */ - _=wordpos(y, $, j+1); if _\==0 then $=delword($, _, 1) /*del if dup.*/ - end /*j*/ - -say 'modified list:' space($) -say right(words($),13) ' words in the modified list.' - /*stick a fork in it, we're done.*/ +say 'modified list:' space(z) +say right(words(z),17,'─') 'words in the modified list.' + /*stick a fork in it, we're all done. */ diff --git a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-2.rexx b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-2.rexx index 47a9f05de7..7814224902 100644 --- a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-2.rexx +++ b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-2.rexx @@ -1,13 +1,12 @@ /*REXX program to remove duplicate elements (items) in a list. */ -old= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' -say 'original list:' old -say right(words(old),13) ' words in the original list.'; say -new= /*start with a clean slate. */ +$= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' +say 'original list:' $ +say right(words($),13) ' words in the original list.'; say - do j=1 for words(old); _=word(old,j) /*process the words in old list. */ - if wordpos(_,new)==0 then new=new _ /*Doesn't exist? Then add to list*/ + do j=words($) by -1 to 1; y=word($,j) /*process words in the list, */ + _=wordpos(y, $, j+1); if _\==0 then $=delword($, _, 1) /*del if dup.*/ end /*j*/ -say 'modified list:' space(new) -say right(words(new),13) ' words in the modified list.' +say 'modified list:' space($) +say right(words($),13) ' words in the modified list.' /*stick a fork in it, we're done.*/ diff --git a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-3.rexx b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-3.rexx index 598aba2103..47a9f05de7 100644 --- a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-3.rexx +++ b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-3.rexx @@ -1,28 +1,13 @@ -/* REXX ************************************************************ -* 26.11.2012 Walter Pachl -* added: show multiple occurrences -**********************************************************************/ -old='2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5', - '3 2 0 4.4 2' -say 'old list='old -say 'words in the old list=' words(old) -new='' -found.=0 -count.=0 -Do While old<>'' - Parse Var old w old - If found.w=0 Then Do - new=new w - found.w=1 - End - count.w=count.w+1 - End -say 'new list='strip(new) -say 'words in the new list=' words(new) -Say 'Multiple occurrences:' -Say 'occ word' -Do While new<>'' - Parse Var new w new - If count.w>1 Then - Say right(count.w,3) w - End +/*REXX program to remove duplicate elements (items) in a list. */ +old= '2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5 3 2 0 4.4 2' +say 'original list:' old +say right(words(old),13) ' words in the original list.'; say +new= /*start with a clean slate. */ + + do j=1 for words(old); _=word(old,j) /*process the words in old list. */ + if wordpos(_,new)==0 then new=new _ /*Doesn't exist? Then add to list*/ + end /*j*/ + +say 'modified list:' space(new) +say right(words(new),13) ' words in the modified list.' + /*stick a fork in it, we're done.*/ diff --git a/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-4.rexx b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-4.rexx new file mode 100644 index 0000000000..598aba2103 --- /dev/null +++ b/Task/Remove-duplicate-elements/REXX/remove-duplicate-elements-4.rexx @@ -0,0 +1,28 @@ +/* REXX ************************************************************ +* 26.11.2012 Walter Pachl +* added: show multiple occurrences +**********************************************************************/ +old='2 3 5 7 11 13 17 19 cats 222 -100.2 +11 1.1 +7 7. 7 5 5', + '3 2 0 4.4 2' +say 'old list='old +say 'words in the old list=' words(old) +new='' +found.=0 +count.=0 +Do While old<>'' + Parse Var old w old + If found.w=0 Then Do + new=new w + found.w=1 + End + count.w=count.w+1 + End +say 'new list='strip(new) +say 'words in the new list=' words(new) +Say 'Multiple occurrences:' +Say 'occ word' +Do While new<>'' + Parse Var new w new + If count.w>1 Then + Say right(count.w,3) w + End diff --git a/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-3.rb b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-3.rb index 58a0709b89..49fdd03576 100644 --- a/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-3.rb +++ b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-3.rb @@ -10,6 +10,5 @@ def unique(array) return pure end - unique ["hi","hey","hello","hi","hey","heyo"] # => ["hi", "hey", "hello", "heyo"] unique [1,2,3,4,1,2,3,5,1,2,3,4,5] # => [1,2,3,4,5] diff --git a/Task/Remove-duplicate-elements/VBScript/remove-duplicate-elements.vb b/Task/Remove-duplicate-elements/VBScript/remove-duplicate-elements.vb new file mode 100644 index 0000000000..9af542c86b --- /dev/null +++ b/Task/Remove-duplicate-elements/VBScript/remove-duplicate-elements.vb @@ -0,0 +1,15 @@ +Function remove_duplicates(list) + arr = Split(list,",") + Set dict = CreateObject("Scripting.Dictionary") + For i = 0 To UBound(arr) + If dict.Exists(arr(i)) = False Then + dict.Add arr(i),"" + End If + Next + For Each key In dict.Keys + tmp = tmp & key & "," + Next + remove_duplicates = Left(tmp,Len(tmp)-1) +End Function + +WScript.Echo remove_duplicates("a,a,b,b,c,d,e,d,f,f,f,g,h") diff --git a/Task/Remove-lines-from-a-file/Fortran/remove-lines-from-a-file-1.f b/Task/Remove-lines-from-a-file/Fortran/remove-lines-from-a-file-1.f new file mode 100644 index 0000000000..51a146bfa0 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Fortran/remove-lines-from-a-file-1.f @@ -0,0 +1,51 @@ + SUBROUTINE CROAK(GASP) !Something bad has happened. + CHARACTER*(*) GASP !As noted. + WRITE (6,*) "Oh dear. ",GASP !So, gasp away. + STOP "++ungood." !Farewell, cruel world. + END !No return from this. + + SUBROUTINE FILEHACK(FNAME,IST,N) + CHARACTER*(*) FNAME !Name for the file. + INTEGER IST !First record to be omitted. + INTEGER N !Number of records to be omitted. + INTEGER ENUFF,L !Some lengths. + PARAMETER (ENUFF = 66666)!Surely? + CHARACTER*(ENUFF) ALINE !But not in general... + INTEGER NREC !A counter. + INTEGER F,T !Mnemonics for file unit numbers. + PARAMETER (F=66,T=67) !These should do. + LOGICAL EXIST + IF (FNAME.EQ."") CALL CROAK("Blank file name!") + IF (IST.LE.0) CALL CROAK("First record must be positive!") + IF (N.LE.0) CALL CROAK("Remove count must be positive!") + INQUIRE(FILE = FNAME, EXIST = EXIST) !This mishap is frequent, so attend to it. + IF (.NOT.EXIST) CALL CROAK("Can't find a file called "//FNAME) !Tough love. + OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READ",FORM="FORMATTED") !Grab the source file. + OPEN (T,STATUS="SCRATCH",FORM="FORMATTED") !Request a temporary file. + NREC = 0 !Number of records read so far. +Copy the desired records to a temporary file. + 10 READ (F,11,END = 20) L,ALINE(1:MIN(L,ENUFF)) !Minimal protection. + 11 FORMAT (Q,A) !Obviously, Q = # of characters to come, A = their format. + IF (L.GT.ENUFF) CALL CROAK("Ow! Lengthy record!!") + NREC = NREC + 1 !If we're here. we've read a record. + IF (NREC.LT.IST .OR. NREC.GE.IST + N) WRITE (T,12) ALINE(1:L) !A desired record? + 12 FORMAT (A) !No character count is explicitly specified. + GO TO 10 !Keep on thumping. +Convert from input to output... + 20 IF (NREC.LT.IST + N) CALL CROAK("Insufficient records!") !Finished ignoring records? + REWIND T !Not CLOSE! That would discard the file! + CLOSE(F) !The source file still exists. + OPEN (F,FILE=FNAME,FORM="FORMATTED", !But, + 1 ACTION="WRITE",STATUS="REPLACE") !This dooms it! +Copy from the temporary file. + 21 READ (T,11,END = 30) L,ALINE(1:L) !All records are not longer than ALINE. + WRITE (F,12) ALINE(1:L) !Out it goes. + GO TO 21 !Keep on thumping. +Completed. + 30 CLOSE(T) !Abandon the temporary file. + CLOSE(F) !Finished with the source file. + END !Done. + + PROGRAM CHOPPER + CALL FILEHACK("foobar.txt",1,2) + END diff --git a/Task/Remove-lines-from-a-file/Fortran/remove-lines-from-a-file-2.f b/Task/Remove-lines-from-a-file/Fortran/remove-lines-from-a-file-2.f new file mode 100644 index 0000000000..82effdf043 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Fortran/remove-lines-from-a-file-2.f @@ -0,0 +1,54 @@ + CHARACTER*42 FUNCTION ERRORWORDS(IT) !Look for an explanation. One day, the system may offer coherent messages. +Curious collection of encountered codes. Will they differ on other systems? +Compaq's compiler was taken over by unintel; http://software.intel.com/sites/products/documentation/hpc/compilerpro/en-us/fortran/lin/compiler_f/bldaps_for/common/bldaps_rterrs.htm +contains a schedule of error numbers that matched those I'd found for Compaq, and so some assumptions are added. +Copying all (hundreds!) is excessive; these seem possible for the usage so far made of error diversion. +Compaq's compiler interface ("visual" blah) has a help offering, which can provide error code information. +Compaq messages also appear in http://cens.ioc.ee/local/man/CompaqCompilers/cf/dfuum028.htm#tab_runtime_errors +Combines IOSTAT codes (file open, read etc) with STAT codes (allocate/deallocate) as their numbers are distinct. +Completeness and context remains a problem. Excess brevity means cause and effect can be confused. + INTEGER IT !The error code in question. + INTEGER LASTKNOWN !Some codes I know about. + PARAMETER (LASTKNOWN = 26) !But only a few, discovered by experiment and mishap. + TYPE HINT !For them, I can supply a table. + INTEGER CODE !The code number. (But, different systems..??) + CHARACTER*42 EXPLICATION !An explanation. Will it be te answer? + END TYPE HINT !Simple enough. + TYPE(HINT) ERROR(LASTKNOWN) !So, let's have a collection. + PARAMETER (ERROR = (/ !With these values. + 1 HINT(-1,"End-of-file at the start of reading!"), !From examples supplied with the Compaq compiler involving IOSTAT. + 2 HINT( 0,"No worries."), !Apparently the only standard value. + 3 HINT( 9,"Permissions - read only?"), + 4 HINT(10,"File already exists!"), + 5 HINT(17,"Syntax error in NameList input."), + 6 HINT(18,"Too many values for the recipient."), + 7 HINT(19,"Invalid naming of a variable."), + 8 HINT(24,"Surprise end-of-file during read!"), !From example source. + 9 HINT(25,"Invalid record number!"), + o HINT(29,"File name not found."), + 1 HINT(30,"Unavailable - exclusive use?"), + 2 HINT(32,"Invalid fileunit number!"), + 3 HINT(35,"'Binary' form usage is rejected."), !From example source. + 4 HINT(36,"Record number for a non-existing record!"), + 5 HINT(37,"No record length has been specified."), + 6 HINT(38,"I/O error during a write!"), + 7 HINT(39,"I/O error during a read!"), + 8 HINT(41,"Insufficient memory available!"), + 9 HINT(43,"Malformed file name."), + o HINT(47,"Attempting a write, but read-only is set."), + 1 HINT(66,"Output overflows single record size."), !This one from experience. + 2 HINT(67,"Input demand exceeds single record size."), !These two are for unformatted I/O. + 3 HINT(151,"Can't allocate: already allocated!"), !These different numbers are for memory allocation failures. + 4 HINT(153,"Can't deallocate: not allocated!"), + 5 HINT(173,"The fingered item was not allocated!"), !Such as an ordinary array that was not allocated. + 6 HINT(179,"Size exceeds addressable memory!")/)) + INTEGER I !A stepper. + DO I = LASTKNOWN,1,-1 !So, step through the known codes. + IF (IT .EQ. ERROR(I).CODE) GO TO 1 !This one? + END DO !On to the next. + 1 IF (I.LE.0) THEN !Fail with I = 0. + ERRORWORDS = I8FMT(IT)//" is a novel code!" !Reveal the mysterious number. + ELSE !But otherwise, it is found. + ERRORWORDS = ERROR(I).EXPLICATION !And these words might even apply. + END IF !But on all systems? + END FUNCTION ERRORWORDS !Hopefully, helpful. diff --git a/Task/Remove-lines-from-a-file/Julia/remove-lines-from-a-file.julia b/Task/Remove-lines-from-a-file/Julia/remove-lines-from-a-file.julia new file mode 100644 index 0000000000..1c83bc4e8a --- /dev/null +++ b/Task/Remove-lines-from-a-file/Julia/remove-lines-from-a-file.julia @@ -0,0 +1,33 @@ +#!/usr/bin/env julia + +const prgm = basename(Base.source_path()) + +if length(ARGS) < 2 + println("usage: ", prgm, " [line]...") + exit(1) +end + +file = ARGS[1] + +const numbers = map(x -> begin + try + parse(Uint, x) + catch + println(prgm, ": ", x, ": not a number") + exit(1) + end +end, ARGS[2:end]) + +f = open(file) +lines = readlines(f) +close(f) + +if maximum(numbers) > length(lines) + println(prgm, ": detected extraneous line number") + exit(1) +end + +deleteat!(lines, sort(unique(numbers))) +f = open(file, "w") +write(f, join(lines)) +close(f) diff --git a/Task/Remove-lines-from-a-file/PowerShell/remove-lines-from-a-file.psh b/Task/Remove-lines-from-a-file/PowerShell/remove-lines-from-a-file.psh new file mode 100644 index 0000000000..192abc7346 --- /dev/null +++ b/Task/Remove-lines-from-a-file/PowerShell/remove-lines-from-a-file.psh @@ -0,0 +1,11 @@ +function del-line($file, $start, $end) { + $i = 0 + $start-- + $end-- + (Get-Content $file) | where{ + ($i -lt $start -or $i -gt $end) + $i++ + } > $file + (Get-Content $file) +} +del-line "foobar.txt" 1 2 diff --git a/Task/Remove-lines-from-a-file/REXX/remove-lines-from-a-file.rexx b/Task/Remove-lines-from-a-file/REXX/remove-lines-from-a-file.rexx index 05e72e9514..e963ecb0f4 100644 --- a/Task/Remove-lines-from-a-file/REXX/remove-lines-from-a-file.rexx +++ b/Task/Remove-lines-from-a-file/REXX/remove-lines-from-a-file.rexx @@ -1,24 +1,23 @@ -/*REXX program to read a specified file and delete specified record(s). */ -parse arg iFID ',' at ',' many /*input FID, del start, how many.*/ -if iFID='' then call er "no input fileID specified." -if at='' then call er "no start number specified." -if many='' then many=1 /*Not specified? Assume 1 line.*/ -stop=at+many-1 /*calculate high end of deletes. */ -oFID=iFID'.out' /*the name of the output file. */ -w=0 - do j=1 while lines(iFID)\==0 /*J is the line number being read*/ - x=linein(iFID) /*read a line from the input file*/ - if j>=at & j<=stop then iterate /*if in the range, then ignore it*/ - call lineout oFID,x; w=w+1 /*write line, bump the write cnt.*/ - end -j=j-1 -if j=N & j<=stop then iterate /*if it's in the range, then ignore it.*/ + call lineout oFID,@; #=#+1 /*write record (line);, bump write cnt.*/ + end /*j*/ /* [↑] by ignoring it is to delete it.*/ +j=j-1 /*adjust J (because of DO loop advance)*/ +if j= (args.arg_start + args.arg_count) { + println!("{}", line.unwrap()); + } + } +} diff --git a/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb b/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb new file mode 100644 index 0000000000..634e1673c0 --- /dev/null +++ b/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb @@ -0,0 +1,31 @@ +Sub remove_lines(filepath,start,number) + Set objFSO = CreateObject("Scripting.FileSystemObject") + Set InFile = objFSO.OpenTextFile(filepath,1,False) + line_count = 1 + discard_count = 1 + out_txt = "" + Do Until InFile.AtEndOfStream + line = InFile.ReadLine + If line_count <> start Then + If InFile.AtEndOfStream = False Then + out_txt = out_txt & line & vbCrLf + Else + out_txt = out_txt & line + End If + line_count = line_count + 1 + Else + Do Until discard_count = number + InFile.SkipLine + discard_count = discard_count + 1 + line_count = line_count + 1 + Loop + End If + Loop + InFile.Close + Set OutFile = objFSO.OpenTextFile(filepath,2,False) + OutFile.Write(out_txt) + OutFile.Close + Set objFSO = Nothing +End Sub + +Call remove_lines("C:\Test.txt",3,4) diff --git a/Task/Rendezvous/Racket/rendezvous-1.rkt b/Task/Rendezvous/Racket/rendezvous-1.rkt new file mode 100644 index 0000000000..001b26aa2b --- /dev/null +++ b/Task/Rendezvous/Racket/rendezvous-1.rkt @@ -0,0 +1,61 @@ +#lang racket + +;;; Rendezvous primitives implemented in terms of synchronous channels. +(define (send ch msg) + (define handshake (make-channel)) + (channel-put ch (list msg handshake)) + (channel-get handshake) + (void)) + +(define (receive ch action) + (match-define (list msg handshake) (channel-get ch)) + (action msg) + (channel-put handshake 'done)) + +;;; A printer receives a line of text, then +;;; - prints it (still ink left) +;;; - sends it to the backup printer (if present) +;;; - raises exception (if no ink and no backup) +(define (printer id ink backup) + (define (on-line-received line) + (cond + [(and (= ink 0) (not backup)) (raise 'out-of-ink)] + [(= ink 0) (send backup line)] + [else (display (~a id ":")) + (for ([c line]) (display c)) + (newline)])) + (define ch (make-channel)) + (thread + (λ () + (let loop () + (receive ch on-line-received) + (set! ink (max 0 (- ink 1))) + (loop)))) + ch) + +;;; Setup two printers + +(define reserve (printer "reserve" 5 #f)) +(define main (printer "main" 5 reserve)) + +;;; Two stories + +(define humpty + '("Humpty Dumpty sat on a wall." + "Humpty Dumpty had a great fall." + "All the king's horses and all the king's men," + "Couldn't put Humpty together again.")) + +(define goose + '("Old Mother Goose," + "When she wanted to wander," + "Would ride through the air," + "On a very fine gander." + "Jack's mother came in," + "And caught the goose soon," + "And mounting its back," + "Flew up to the moon.")) + +;;; Print the stories +(for ([l humpty]) (send main l)) +(for ([l goose]) (send main l)) diff --git a/Task/Rendezvous/Racket/rendezvous-2.rkt b/Task/Rendezvous/Racket/rendezvous-2.rkt new file mode 100644 index 0000000000..659b75c374 --- /dev/null +++ b/Task/Rendezvous/Racket/rendezvous-2.rkt @@ -0,0 +1,11 @@ +main:Humpty Dumpty sat on a wall. +main:Humpty Dumpty had a great fall. +main:All the king's horses and all the king's men, +main:Couldn't put Humpty together again. +main:Old Mother Goose, +reserve:When she wanted to wander, +reserve:Would ride through the air, +reserve:On a very fine gander. +reserve:Jack's mother came in, +reserve:And caught the goose soon, +uncaught exception: 'out-of-ink diff --git a/Task/Rep-string/Forth/rep-string-1.fth b/Task/Rep-string/Forth/rep-string-1.fth new file mode 100644 index 0000000000..8f29dd0fe3 --- /dev/null +++ b/Task/Rep-string/Forth/rep-string-1.fth @@ -0,0 +1,21 @@ +: rep-string ( caddr1 u1 -- caddr2 u2 ) \ u2=0: not a rep-string + 2dup dup >r r@ 2/ /string + begin 2over 2over string-prefix? 0= over r@ < and while -1 /string repeat + r> swap - >r 2drop r> ; + +: test ( caddr u -- ) + 2dup type ." has " + rep-string ?dup 0= if drop ." no " else type ." as " then + ." repeating substring" cr ; +: tests + s" 1001110011" test + s" 1110111011" test + s" 0010010010" test + s" 1010101010" test + s" 1111111111" test + s" 0100101101" test + s" 0100100" test + s" 101" test + s" 11" test + s" 00" test + s" 1" test ; diff --git a/Task/Rep-string/Forth/rep-string-2.fth b/Task/Rep-string/Forth/rep-string-2.fth new file mode 100644 index 0000000000..2ca14f3d8a --- /dev/null +++ b/Task/Rep-string/Forth/rep-string-2.fth @@ -0,0 +1,13 @@ +cr tests +1001110011 has 10011 as repeating substring +1110111011 has 1110 as repeating substring +0010010010 has 001 as repeating substring +1010101010 has 1010 as repeating substring +1111111111 has 11111 as repeating substring +0100101101 has no repeating substring +0100100 has 010 as repeating substring +101 has no repeating substring +11 has 1 as repeating substring +00 has 0 as repeating substring +1 has no repeating substring + ok diff --git a/Task/Rep-string/Julia/rep-string.julia b/Task/Rep-string/Julia/rep-string.julia new file mode 100644 index 0000000000..c49688dde6 --- /dev/null +++ b/Task/Rep-string/Julia/rep-string.julia @@ -0,0 +1,34 @@ +function list_reps{T<:String}(r::T) + n = length(r) + replst = T[] + for m in 1:n>>1 + s = r[1:chr2ind(r,m)] + (s^(div(n,m)+1))[1:chr2ind(r,n)] == r || continue + push!(replst, s) + end + return replst +end + +tests = {"1001110011", + "1110111011", + "0010010010", + "1010101010", + "1111111111", + "0100101101", + "0100100", + "101", + "11", + "00", + "1", + "\u2200\u2203\u2200\u2203\u2200\u2203\u2200\u2203"} + +for r in tests + replst = list_reps(r) + rlen = length(replst) + print(@sprintf(" %s ", r)) + if rlen == 0 + println("is not a rep-string.") + else + println("is a rep-string of ", join(replst, ", "), ".") + end +end diff --git a/Task/Rep-string/Objeck/rep-string.objeck b/Task/Rep-string/Objeck/rep-string.objeck new file mode 100644 index 0000000000..4cf0e2dec9 --- /dev/null +++ b/Task/Rep-string/Objeck/rep-string.objeck @@ -0,0 +1,62 @@ +class RepString { + function : Main(args : String[]) ~ Nil { + strings := ["1001110011", "1110111011", "0010010010", "1111111111", + "0100101101", "0100100", "101", "11", "00", "1"]; + each(i : strings) { + string := strings[i]; + repstring := RepString(string); + if(repstring->Size() > 0) { + "\"{$string}\" = rep-string \"{$repstring}\""->PrintLine(); + } + else { + "\"{$string}\" = not a rep-string"->PrintLine(); + }; + }; + } + + function : RepString(string : String) ~ String { + offset := string->Size() / 2; + + while(offset > 0) { + left := string->SubString(offset); + right := string->SubString(left->Size(),left->Size()); + if(left->Equals(right)) { + if(ValidateMatch(left, string)) { + return left; + } + else { + return ""; + }; + }; + + offset--; + }; + + return ""; + } + + function : ValidateMatch(left : String, string : String) ~ Bool { + parts := string->Size() / left->Size(); + tail := string->Size() % left->Size() <> 0; + + for(i := 1; i < parts; i+=1;) { + offset := i * left->Size(); + right := string->SubString(offset, left->Size()); + if(<>left->Equals(right)) { + return false; + }; + }; + + if(tail) { + offset := parts * left->Size(); + right := string->SubString(offset, string->Size() - offset); + each(i : right) { + if(left->Get(i) <> right->Get(i)) { + return false; + }; + }; + }; + + return true; + } +} diff --git a/Task/Rep-string/PureBasic/rep-string.purebasic b/Task/Rep-string/PureBasic/rep-string.purebasic new file mode 100644 index 0000000000..3f87319a1c --- /dev/null +++ b/Task/Rep-string/PureBasic/rep-string.purebasic @@ -0,0 +1,22 @@ +a$="1001110011"+#CRLF$+"1110111011"+#CRLF$+"0010010010"+#CRLF$+"1010101010"+#CRLF$+"1111111111"+#CRLF$+ + "0100101101"+#CRLF$+"0100100" +#CRLF$+"101" +#CRLF$+"11" +#CRLF$+"00" +#CRLF$+ + "1" +#CRLF$ + +Define.i : OpenConsole() + +Procedure isRepStr(s1$,s2$) + If Int(Len(s1$)/Len(s2$))>=2 : ProcedureReturn isRepStr(s1$,s2$+s2$) : EndIf + If Len(s1$)>Len(s2$) : ProcedureReturn isRepStr(s1$,s2$+Left(s2$,Len(s1$)%Len(s2$))) : EndIf + If s1$=s2$ : ProcedureReturn #True : Else : ProcedureReturn #False : EndIf +EndProcedure + +For k=1 To CountString(a$,#CRLF$) + s1$=StringField(a$,k,#CRLF$) : s2$=Left(s1$,Len(s1$)/2) + While Len(s2$) + r=isRepStr(s1$,s2$) + If Not r : s2$=Left(s2$,Len(s2$)-1) : Else : Break : EndIf + Wend + If Len(s2$) And r : PrintN(LSet(s1$,15,Chr(32))+#TAB$+"longest sequence: "+s2$) : EndIf + If Not Len(s2$) : PrintN(LSet(s1$,15,Chr(32))+#TAB$+"found nothing.") : EndIf +Next +Input() diff --git a/Task/Rep-string/REXX/rep-string-2.rexx b/Task/Rep-string/REXX/rep-string-2.rexx index 391980301f..c6142a9905 100644 --- a/Task/Rep-string/REXX/rep-string-2.rexx +++ b/Task/Rep-string/REXX/rep-string-2.rexx @@ -1,13 +1,17 @@ -/*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*/ +/*REXX pgm determines if a string is a repString, returns min. length repStr. */ +parse arg s /*get optional strings from the C.L. */ +if s='' then s=1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1 45 + /* [↑] S not specified? Use defaults*/ + do k=1 for words(s); _=word(s,k); w=length(_) /*process binary strings.*/ + say right(_,max(25,w)) repString(_) /*show repString & result*/ + end /*k*/ /* [↑] the "result" may be negatory.*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +repString: procedure; parse arg x; L=length(x) +if \datatype(x,'B') then return " ***error!*** string isn't a binary string." + + do j=1 for L-1 while j<=L%2; $=left(x,j); $$=copies($,L) + if left($$,L)==x then return ' rep string=' left($,15) '[length' j"]" + end /*j*/ /* [↑] we have found a good repString.*/ + +return ' (no repetitions)' /*(sigh)··· a failure to find repString*/ diff --git a/Task/Rep-string/VBScript/rep-string.vb b/Task/Rep-string/VBScript/rep-string.vb new file mode 100644 index 0000000000..3ef913e037 --- /dev/null +++ b/Task/Rep-string/VBScript/rep-string.vb @@ -0,0 +1,37 @@ +Function rep_string(s) + max_len = Int(Len(s)/2) + tmp = "" + If max_len = 0 Then + rep_string = "No Repeating String" + Exit Function + End If + For i = 1 To max_len + If InStr(i+1,s,tmp & Mid(s,i,1))Then + tmp = tmp & Mid(s,i,1) + Else + Exit For + End If + Next + Do While Len(tmp) > 0 + If Mid(s,Len(tmp)+1,Len(tmp)) = tmp Then + rep_string = tmp + Exit Do + Else + tmp = Mid(tmp,1,Len(tmp)-1) + End If + Loop + If Len(tmp) > 0 Then + rep_string = tmp + Else + rep_string = "No Repeating String" + End If +End Function + +'testing the function +arr = Array("1001110011","1110111011","0010010010","1010101010",_ + "1111111111","0100101101","0100100","101","11","00","1") + +For n = 0 To UBound(arr) + WScript.StdOut.Write arr(n) & ": " & rep_string(arr(n)) + WScript.StdOut.WriteLine +Next diff --git a/Task/Repeat-a-string/AutoIt/repeat-a-string.autoit b/Task/Repeat-a-string/AutoIt/repeat-a-string.autoit new file mode 100644 index 0000000000..2053df0ab1 --- /dev/null +++ b/Task/Repeat-a-string/AutoIt/repeat-a-string.autoit @@ -0,0 +1,3 @@ +#include + +ConsoleWrite(_StringRepeat("ha", 5) & @CRLF) diff --git a/Task/Repeat-a-string/DCL/repeat-a-string.dcl b/Task/Repeat-a-string/DCL/repeat-a-string.dcl new file mode 100644 index 0000000000..e75f9d09d0 --- /dev/null +++ b/Task/Repeat-a-string/DCL/repeat-a-string.dcl @@ -0,0 +1,2 @@ +$ write sys$output f$fao( "!AS!-!AS!-!AS!-!AS!-!AS", "ha" ) +$ write sys$output f$fao( "!12*d" ) diff --git a/Task/Repeat-a-string/JavaScript/repeat-a-string-3.js b/Task/Repeat-a-string/JavaScript/repeat-a-string-3.js new file mode 100644 index 0000000000..e646361594 --- /dev/null +++ b/Task/Repeat-a-string/JavaScript/repeat-a-string-3.js @@ -0,0 +1,12 @@ +function nreps(s, n) { + var o = ''; + if (n < 1) return o; + while (n > 1) { + if (n & 1) o += s; + n >>= 1; + s += s; + } + return o + s; +} + +nreps('ha', 500); diff --git a/Task/Repeat-a-string/Kotlin/repeat-a-string.kotlin b/Task/Repeat-a-string/Kotlin/repeat-a-string.kotlin new file mode 100644 index 0000000000..fe8c1cbd59 --- /dev/null +++ b/Task/Repeat-a-string/Kotlin/repeat-a-string.kotlin @@ -0,0 +1,3 @@ +fun main(args: Array) { + println("ha".repeat(5)) +} diff --git a/Task/Repeat-a-string/Lua/repeat-a-string-1.lua b/Task/Repeat-a-string/Lua/repeat-a-string-1.lua index 0a8d3c53f8..71de955b02 100644 --- a/Task/Repeat-a-string/Lua/repeat-a-string-1.lua +++ b/Task/Repeat-a-string/Lua/repeat-a-string-1.lua @@ -1 +1 @@ -function repeats(s, n) return n > 0 and s .. repeat(s, n-1) or "" end +function repeats(s, n) return n > 0 and s .. repeats(s, n-1) or "" end diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-1.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-1.ocaml index 49216afd99..fe1dd25dc6 100644 --- a/Task/Repeat-a-string/OCaml/repeat-a-string-1.ocaml +++ b/Task/Repeat-a-string/OCaml/repeat-a-string-1.ocaml @@ -1,8 +1,8 @@ let string_repeat s n = - let len = String.length s in - let res = String.create(n * len) in + let len = Bytes.length s in + let res = Bytes.create(n * len) in for i = 0 to pred n do - String.blit s 0 res (i * len) len; + Bytes.blit s 0 res (i * len) len done; - (res) + Bytes.to_string res (* not stricly necessary, the bytes type is equivalent to string except mutability *) ;; diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-2.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-2.ocaml index 2e347b1cff..53a03c5028 100644 --- a/Task/Repeat-a-string/OCaml/repeat-a-string-2.ocaml +++ b/Task/Repeat-a-string/OCaml/repeat-a-string-2.ocaml @@ -1,2 +1 @@ -# string_repeat "Hiuoa" 3 ;; -- : string = "HiuoaHiuoaHiuoa" + val string_repeat : bytes -> int -> string = diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-3.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-3.ocaml index d388be7490..2e347b1cff 100644 --- a/Task/Repeat-a-string/OCaml/repeat-a-string-3.ocaml +++ b/Task/Repeat-a-string/OCaml/repeat-a-string-3.ocaml @@ -1,3 +1,2 @@ -let string_repeat s n = - String.concat "" (Array.to_list (Array.make n s)) -;; +# string_repeat "Hiuoa" 3 ;; +- : string = "HiuoaHiuoaHiuoa" diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-4.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-4.ocaml index 7914dfb1c7..d388be7490 100644 --- a/Task/Repeat-a-string/OCaml/repeat-a-string-4.ocaml +++ b/Task/Repeat-a-string/OCaml/repeat-a-string-4.ocaml @@ -1,3 +1,3 @@ let string_repeat s n = - Array.fold_left (^) "" (Array.make n s) + String.concat "" (Array.to_list (Array.make n s)) ;; diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-5.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-5.ocaml index a3b44b8b1f..7914dfb1c7 100644 --- a/Task/Repeat-a-string/OCaml/repeat-a-string-5.ocaml +++ b/Task/Repeat-a-string/OCaml/repeat-a-string-5.ocaml @@ -1 +1,3 @@ -String.make 5 '*' +let string_repeat s n = + Array.fold_left (^) "" (Array.make n s) +;; diff --git a/Task/Repeat-a-string/OCaml/repeat-a-string-6.ocaml b/Task/Repeat-a-string/OCaml/repeat-a-string-6.ocaml new file mode 100644 index 0000000000..a3b44b8b1f --- /dev/null +++ b/Task/Repeat-a-string/OCaml/repeat-a-string-6.ocaml @@ -0,0 +1 @@ +String.make 5 '*' diff --git a/Task/Repeat-a-string/Rust/repeat-a-string.rust b/Task/Repeat-a-string/Rust/repeat-a-string.rust new file mode 100644 index 0000000000..82c2ebcde0 --- /dev/null +++ b/Task/Repeat-a-string/Rust/repeat-a-string.rust @@ -0,0 +1 @@ +std::iter::repeat("ha").take(5).collect::(); // ==> "hahahahaha" diff --git a/Task/Repeat-a-string/UNIX-Shell/repeat-a-string-5.sh b/Task/Repeat-a-string/UNIX-Shell/repeat-a-string-5.sh index c6d9c6f081..6c681dc91e 100644 --- a/Task/Repeat-a-string/UNIX-Shell/repeat-a-string-5.sh +++ b/Task/Repeat-a-string/UNIX-Shell/repeat-a-string-5.sh @@ -1,2 +1,2 @@ -width=72; char='=' -head -c ${width} < /dev/zero | tr '\0' "$char" +len=12; str='=' +repeat $len printf "$str" diff --git a/Task/Repeat-a-string/UNIX-Shell/repeat-a-string-6.sh b/Task/Repeat-a-string/UNIX-Shell/repeat-a-string-6.sh new file mode 100644 index 0000000000..c6d9c6f081 --- /dev/null +++ b/Task/Repeat-a-string/UNIX-Shell/repeat-a-string-6.sh @@ -0,0 +1,2 @@ +width=72; char='=' +head -c ${width} < /dev/zero | tr '\0' "$char" diff --git a/Task/Respond-to-an-unknown-method-call/Forth/respond-to-an-unknown-method-call.fth b/Task/Respond-to-an-unknown-method-call/Forth/respond-to-an-unknown-method-call.fth new file mode 100644 index 0000000000..709103f794 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Forth/respond-to-an-unknown-method-call.fth @@ -0,0 +1,5 @@ +include FMS-SI.f +include FMS-SILib.f + +var x \ instantiate a class var object named x +x add: \ => "aborted: message not understood" diff --git a/Task/Respond-to-an-unknown-method-call/JavaScript/respond-to-an-unknown-method-call-1.js b/Task/Respond-to-an-unknown-method-call/JavaScript/respond-to-an-unknown-method-call-1.js new file mode 100644 index 0000000000..5e2c832974 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/JavaScript/respond-to-an-unknown-method-call-1.js @@ -0,0 +1,14 @@ +obj = new Proxy({}, + { get : function(target, prop) + { + if(target[prop] === undefined) + return function() { + console.log('an otherwise undefined function!!'); + }; + else + return target[prop]; + } + }); +obj.f() ///'an otherwise undefined function!!' +obj.l = function() {console.log(45);}; +obj.l(); ///45 diff --git a/Task/Respond-to-an-unknown-method-call/JavaScript/respond-to-an-unknown-method-call.js b/Task/Respond-to-an-unknown-method-call/JavaScript/respond-to-an-unknown-method-call-2.js similarity index 100% rename from Task/Respond-to-an-unknown-method-call/JavaScript/respond-to-an-unknown-method-call.js rename to Task/Respond-to-an-unknown-method-call/JavaScript/respond-to-an-unknown-method-call-2.js diff --git a/Task/Respond-to-an-unknown-method-call/Mathematica/respond-to-an-unknown-method-call.math b/Task/Respond-to-an-unknown-method-call/Mathematica/respond-to-an-unknown-method-call.math new file mode 100644 index 0000000000..f69bebe408 --- /dev/null +++ b/Task/Respond-to-an-unknown-method-call/Mathematica/respond-to-an-unknown-method-call.math @@ -0,0 +1,6 @@ +obj[foo] = "This is foo."; +obj[bar] = "This is bar."; +obj[f_Symbol] := "What is " <> SymbolName[f] <> "?"; +Print[obj@foo]; +Print[obj@bar]; +Print[obj@baz]; diff --git a/Task/Return-multiple-values/C++/return-multiple-values.cpp b/Task/Return-multiple-values/C++/return-multiple-values.cpp index 384eeffcfa..0dcab202a9 100644 --- a/Task/Return-multiple-values/C++/return-multiple-values.cpp +++ b/Task/Return-multiple-values/C++/return-multiple-values.cpp @@ -1,18 +1,19 @@ #include +#include +#include #include #include -std::tuple minmax ( const int * numbers , const int num ) { - const int *maximum = std::max_element ( numbers , numbers + num ) ; - const int *minimum = std::min_element ( numbers , numbers + num ) ; - return std::make_tuple( *maximum , *minimum ) ; +std::tuple minmax(const int * numbers, const std::size_t num) { + const auto maximum = std::max_element(numbers, numbers + num); + const auto minimum = std::min_element(numbers, numbers + num); + return std::make_tuple(*minimum, *maximum) ; } int main( ) { - const int numbers[ ] = { 17 , 88 , 9 , 33 , 4 , 987 , -10 , 2 } ; - int numbersize = sizeof( numbers ) / sizeof ( int ) ; - std::tuple result = minmax( numbers , numbersize ) ; - std::cout << "The greatest number is " << std::get<0>( result ) - << " , the smallest " << std::get<1>( result ) << " !\n" ; - return 0 ; + const auto numbers = std::array{{17, 88, 9, 33, 4, 987, -10, 2}}; + int min{}; + int max{}; + std::tie(min, max) = minmax(numbers.data(), numbers.size()); + std::cout << "The smallest number is " << min << ", the biggest " << max << "!\n" ; } diff --git a/Task/Return-multiple-values/Elixir/return-multiple-values.elixir b/Task/Return-multiple-values/Elixir/return-multiple-values.elixir new file mode 100644 index 0000000000..2299388bfa --- /dev/null +++ b/Task/Return-multiple-values/Elixir/return-multiple-values.elixir @@ -0,0 +1,8 @@ +defmodule RC do + def addsub(a, b) do + {a+b, a-b} + end +end + +{add, sub} = RC.addsub(7, 4) +IO.puts "Add: #{add},\tSub: #{sub}" diff --git a/Task/Return-multiple-values/JavaScript/return-multiple-values.js b/Task/Return-multiple-values/JavaScript/return-multiple-values.js new file mode 100644 index 0000000000..a528a2e7a6 --- /dev/null +++ b/Task/Return-multiple-values/JavaScript/return-multiple-values.js @@ -0,0 +1,24 @@ +//returns array with three values +var arrBind = function () { + return [1, 2, 3]; //return array of three items to assign +}; + +//returns object with three named values +var objBind = function () { + return {foo: "abc", bar: "123", baz: "zzz"}; +}; + +//keep all three values +var [a, b, c] = arrBind();//assigns a => 1, b => 2, c => 3 +//skip a value +var [a, , c] = arrBind();//assigns a => 1, c => 3 +//keep final values together as array +var [a, ...rest] = arrBind();//assigns a => 1, rest => [2, 3] + + +//same return name +var {foo, bar, baz} = objBind();//assigns foo => "abc", bar => "123", baz => "zzz" +//different return name (ignoring baz) +var {baz: foo, buz: bar} = objBind();//assigns baz => "abc", buz => "123" +//keep rest of values together as object +var {foo, ...rest} = objBind();//assigns foo => "abc, rest => {bar: "123", baz: "zzz"} diff --git a/Task/Return-multiple-values/PowerShell/return-multiple-values.psh b/Task/Return-multiple-values/PowerShell/return-multiple-values.psh new file mode 100644 index 0000000000..561e6813f0 --- /dev/null +++ b/Task/Return-multiple-values/PowerShell/return-multiple-values.psh @@ -0,0 +1,9 @@ +function multiple-value ($a, $b) { + [pscustomobject]@{ + a = $a + b = $b + } +} +$m = multiple-value "value" 1 +$m.a +$m.b diff --git a/Task/Return-multiple-values/Rust/return-multiple-values.rust b/Task/Return-multiple-values/Rust/return-multiple-values.rust new file mode 100644 index 0000000000..4b2158752b --- /dev/null +++ b/Task/Return-multiple-values/Rust/return-multiple-values.rust @@ -0,0 +1,8 @@ +fn multi_hello() -> (&'static str, i32) { + ("Hello",42) +} + +fn main() { + let (str,num)=multi_hello(); + println!("{},{}",str,num); +} diff --git a/Task/Reverse-a-string/Agda/reverse-a-string.agda b/Task/Reverse-a-string/Agda/reverse-a-string.agda new file mode 100644 index 0000000000..36d529693d --- /dev/null +++ b/Task/Reverse-a-string/Agda/reverse-a-string.agda @@ -0,0 +1,7 @@ +module reverse_string where + +open import Data.String +open import Data.List + +reverse_string : String → String +reverse_string s = fromList (reverse (toList s)) diff --git a/Task/Reverse-a-string/AppleScript/reverse-a-string.applescript b/Task/Reverse-a-string/AppleScript/reverse-a-string.applescript index 0eb1fc07d0..fda371212f 100644 --- a/Task/Reverse-a-string/AppleScript/reverse-a-string.applescript +++ b/Task/Reverse-a-string/AppleScript/reverse-a-string.applescript @@ -1,12 +1,5 @@ -get reverse_string("as⃝df̅") +reverseString("Hello World!") -on reverse_string(str) - set old_delim to (get AppleScript's text item delimiters) - set AppleScript's text item delimiters to "" - - set temp to (reverse of text items of str) - set temp to (text items of temp) as Unicode text - - set AppleScript's text item delimiters to old_delim - return temp -end reverse_string +on reverseString(str) + reverse of characters of str as string +end reverseString diff --git a/Task/Reverse-a-string/Befunge/reverse-a-string.bf b/Task/Reverse-a-string/Befunge/reverse-a-string.bf index 062a605564..57a753620c 100644 --- a/Task/Reverse-a-string/Befunge/reverse-a-string.bf +++ b/Task/Reverse-a-string/Befunge/reverse-a-string.bf @@ -1,14 +1 @@ -v The string to reverse. The row to copy to. - | | The actual copying happens here. - | | | Increment column to write to. - | | | | Store column #. - v v v v v -> "reverse me" 3 10p >10g 4 p 10g1+ 10pv - ^ ^ |: < -First column --| | @ ^ -to write to. | ^ Get the address - All calls to 10 | to copy the next - involve saving or | character to. - reading the End when stack is empty or - column to write explicit zero is reached. - to. +~>:#,_@ diff --git a/Task/Reverse-a-string/Forth/reverse-a-string.fth b/Task/Reverse-a-string/Forth/reverse-a-string-1.fth similarity index 100% rename from Task/Reverse-a-string/Forth/reverse-a-string.fth rename to Task/Reverse-a-string/Forth/reverse-a-string-1.fth diff --git a/Task/Reverse-a-string/Forth/reverse-a-string-2.fth b/Task/Reverse-a-string/Forth/reverse-a-string-2.fth new file mode 100644 index 0000000000..488136e33e --- /dev/null +++ b/Task/Reverse-a-string/Forth/reverse-a-string-2.fth @@ -0,0 +1,18 @@ +\ reverse a counted string using the stack +\ Method: Read the input string character by character onto the parameter stack +\ Then write the character back into the same string from the stack + +create mystring ," ABCDEFGHIJKLMNOPQRSTUVWXYZ987654321" \ this is a counted string + +: pushstr ( str -- char[1].. char[n]) \ read the contents of STR onto the stack + count bounds do I c@ loop ; + +: popstr ( char[1].. char[n] str -- ) \ read chars off stack into str + count bounds do I c! loop ; + +: reverse ( str -- ) \ create the reverse function with the factored words + dup >r \ put a copy of the string addr on return stack + pushstr \ push the characters onto the parameter stack + r> popstr ; \ get back our copy of the string addr and pop the characters into it + +\ test in the Forth console diff --git a/Task/Reverse-a-string/JavaScript/reverse-a-string.js b/Task/Reverse-a-string/JavaScript/reverse-a-string.js index 84f953d4e8..972208b96d 100644 --- a/Task/Reverse-a-string/JavaScript/reverse-a-string.js +++ b/Task/Reverse-a-string/JavaScript/reverse-a-string.js @@ -10,7 +10,6 @@ function reverseStr(s) { } //fast method using while loop (faster with long strings in some browsers when compared with for loop) - function reverseStr(s) { var i = s.length, o = ''; while (i--) o += s[i]; diff --git a/Task/Reverse-a-string/Julia/reverse-a-string-2.julia b/Task/Reverse-a-string/Julia/reverse-a-string-2.julia index 172cb13913..d6f93d10a4 100644 --- a/Task/Reverse-a-string/Julia/reverse-a-string-2.julia +++ b/Task/Reverse-a-string/Julia/reverse-a-string-2.julia @@ -1,2 +1,2 @@ -julia> join(reverse(collect(graphemes("nöel")))) -"leön" +julia> join(reverse(collect(graphemes("as⃝df̅")))) +"f̅ds⃝a" diff --git a/Task/Reverse-a-string/RapidQ/reverse-a-string.rapidq b/Task/Reverse-a-string/RapidQ/reverse-a-string.rapidq new file mode 100644 index 0000000000..b3b1e79eb7 --- /dev/null +++ b/Task/Reverse-a-string/RapidQ/reverse-a-string.rapidq @@ -0,0 +1 @@ +print reverse$("This is a test") diff --git a/Task/Reverse-a-string/Rust/reverse-a-string.rust b/Task/Reverse-a-string/Rust/reverse-a-string.rust new file mode 100644 index 0000000000..fe9ec09630 --- /dev/null +++ b/Task/Reverse-a-string/Rust/reverse-a-string.rust @@ -0,0 +1,12 @@ +extern crate unicode_segmentation; +use unicode_segmentation::UnicodeSegmentation; + +fn main() { + let s = "一二三四五六七八九十"; + let s2 = "as⃝df̅"; + let reversed: String = s.chars().rev().collect(); + let reversed2: String = UnicodeSegmentation::graphemes(s2, true) + .rev().collect(); + println!("{}", reversed); + println!("{}", reversed2); +} diff --git a/Task/Reverse-a-string/Self/reverse-a-string.self b/Task/Reverse-a-string/Self/reverse-a-string.self new file mode 100644 index 0000000000..ed2b0a4db8 --- /dev/null +++ b/Task/Reverse-a-string/Self/reverse-a-string.self @@ -0,0 +1 @@ +'asdf' copyMutable reverse diff --git a/Task/Reverse-a-string/TI-83-BASIC/reverse-a-string.ti-83 b/Task/Reverse-a-string/TI-83-BASIC/reverse-a-string.ti-83 index 0aff34ab2f..5b7994dc2a 100644 --- a/Task/Reverse-a-string/TI-83-BASIC/reverse-a-string.ti-83 +++ b/Task/Reverse-a-string/TI-83-BASIC/reverse-a-string.ti-83 @@ -1,8 +1,5 @@ -:"ASDF"→Str1 -: -:" "→Str0 -:length(Str1)→B -:For(A,B,1,-1) -:Str0+sub(Str1,A,1)→Str0 +:Str1 +:For(I,1,length(Ans)-1 +:sub(Ans,2I,1)+Ans :End -:sub(Str0,2,B)→Str0 +:sub(Ans,1,I→Str1 diff --git a/Task/Reverse-a-string/UNIX-Shell/reverse-a-string.sh b/Task/Reverse-a-string/UNIX-Shell/reverse-a-string-1.sh similarity index 100% rename from Task/Reverse-a-string/UNIX-Shell/reverse-a-string.sh rename to Task/Reverse-a-string/UNIX-Shell/reverse-a-string-1.sh diff --git a/Task/Reverse-a-string/UNIX-Shell/reverse-a-string-2.sh b/Task/Reverse-a-string/UNIX-Shell/reverse-a-string-2.sh new file mode 100644 index 0000000000..d602bc90fc --- /dev/null +++ b/Task/Reverse-a-string/UNIX-Shell/reverse-a-string-2.sh @@ -0,0 +1,3 @@ +str='i43go1342iu 23iu4o 23iu14i324y 2i13' +rev <<< "$str" +#rev is not built-in function, though is in /usr/bin/rev diff --git a/Task/Reverse-words-in-a-string/00DESCRIPTION b/Task/Reverse-words-in-a-string/00DESCRIPTION index 2cd6416a98..23329c62b8 100644 --- a/Task/Reverse-words-in-a-string/00DESCRIPTION +++ b/Task/Reverse-words-in-a-string/00DESCRIPTION @@ -1,7 +1,15 @@ -The task is to reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified. -: '''Example:''' “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.) +The task is to reverse the order of all tokens in each of a number of strings and display the result;   the order of characters within a token should not be modified. +: '''Example:'''   “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
@@ -20,3 +28,6 @@ Tokens are any non-space characters separated by spaces (formally, white-space);
   10 ║  Frost Robert -----------------------  ║
      ╚════════════════════════════════════════╝
 
+ +;Cf. +* [[Phrase reversals]] diff --git a/Task/Reverse-words-in-a-string/Batch-File/reverse-words-in-a-string.bat b/Task/Reverse-words-in-a-string/Batch-File/reverse-words-in-a-string.bat new file mode 100644 index 0000000000..ca3a8dd01f --- /dev/null +++ b/Task/Reverse-words-in-a-string/Batch-File/reverse-words-in-a-string.bat @@ -0,0 +1,35 @@ +@echo off + +::The Main Thing... +cls +echo. +call :reverse "---------- Ice and Fire ------------" +call :reverse +call :reverse "fire, in end will world the say Some" +call :reverse "ice. in say Some" +call :reverse "desire of tasted I've what From" +call :reverse "fire. favor who those with hold I" +call :reverse +call :reverse "... elided paragraph last ..." +call :reverse +call :reverse "Frost Robert -----------------------" +echo. +pause>nul +exit +::/The Main Thing... + +::The Function... +:reverse +set reversed=&set word=&set str=%1 +:process +for /f "tokens=1,*" %%A in (%str%) do ( + set str=%%B + set word=%%A +) +set reversed=%word% %reversed% +set str="%str%" +if not %str%=="" goto process + +echo.%reversed% +goto :EOF +::/The Function... diff --git a/Task/Reverse-words-in-a-string/Burlesque/reverse-words-in-a-string.blq b/Task/Reverse-words-in-a-string/Burlesque/reverse-words-in-a-string.blq new file mode 100644 index 0000000000..a793bca264 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Burlesque/reverse-words-in-a-string.blq @@ -0,0 +1,4 @@ +blsq ) "It is not raining"wd<-wd +"raining not is It" +blsq ) "ice. in say some"wd<-wd +"some say in ice." 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 index f1d7824738..e7494201e0 100644 --- 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 @@ -1,13 +1,14 @@ -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 -----------------------" +txt = """ +---------- 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 ----------------------- +""" IO.puts RC.reverse_words(txt) diff --git a/Task/Reverse-words-in-a-string/Emacs-Lisp/reverse-words-in-a-string.l b/Task/Reverse-words-in-a-string/Emacs-Lisp/reverse-words-in-a-string.l new file mode 100644 index 0000000000..1b76913b05 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Emacs-Lisp/reverse-words-in-a-string.l @@ -0,0 +1,19 @@ +(defun reverse-words (line) + (insert + (format "%s\n" + (mapconcat 'identity (reverse (split-string line)) " ")))) + +(defun reverse-lines (lines) + (mapcar 'reverse-words lines)) + +(reverse-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 ----------------------- ")) diff --git a/Task/Reverse-words-in-a-string/Fortran/reverse-words-in-a-string.f b/Task/Reverse-words-in-a-string/Fortran/reverse-words-in-a-string.f new file mode 100644 index 0000000000..ec20ab8045 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Fortran/reverse-words-in-a-string.f @@ -0,0 +1,27 @@ + character*40 words + character*40 reversed + logical inblank + ierr=0 + read (5,fmt="(a)",iostat=ierr)words + do while (ierr.eq.0) + inblank=.true. + ipos=1 + do i=40,1,-1 + if(words(i:i).ne.' '.and.inblank) then + last=i + inblank=.false. + end if + if(.not.inblank.and.words(i:i).eq.' ') then + reversed(ipos:ipos+last-i)=words(i+1:last) + ipos=ipos+last-i+1 + inblank=.true. + end if + if(.not.inblank.and.i.eq.1) then + reversed(ipos:ipos+last-1)=words(1:last) + ipos=ipos+last + end if + end do + print *,words,'=> ',reversed(1:ipos-1) + read (5,fmt="(a)",iostat=ierr)words + end do + end diff --git a/Task/Reverse-words-in-a-string/Frink/reverse-words-in-a-string.frink b/Task/Reverse-words-in-a-string/Frink/reverse-words-in-a-string.frink new file mode 100644 index 0000000000..a6924a3711 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Frink/reverse-words-in-a-string.frink @@ -0,0 +1,14 @@ +lines=split["\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 -----------------------"""] + +for line = lines + println[join[" ", reverse[split[%r/\s+/, line]]]] diff --git a/Task/Reverse-words-in-a-string/Gema/reverse-words-in-a-string.gema b/Task/Reverse-words-in-a-string/Gema/reverse-words-in-a-string.gema new file mode 100644 index 0000000000..1e1bfd813f --- /dev/null +++ b/Task/Reverse-words-in-a-string/Gema/reverse-words-in-a-string.gema @@ -0,0 +1 @@ +\L =@{$2} $1 diff --git a/Task/Reverse-words-in-a-string/JavaScript/reverse-words-in-a-string.js b/Task/Reverse-words-in-a-string/JavaScript/reverse-words-in-a-string.js new file mode 100644 index 0000000000..f06e0a6206 --- /dev/null +++ b/Task/Reverse-words-in-a-string/JavaScript/reverse-words-in-a-string.js @@ -0,0 +1,23 @@ +var strReversed = +"---------- 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 -----------------------"; + +function reverseString(s) { + return s.split('\n').map( + function (line) { + return line.split(/\s/).reverse().join(' '); + } + ).join('\n'); +} + +console.log( + reverseString(strReversed) +); diff --git a/Task/Reverse-words-in-a-string/Liberty-BASIC/reverse-words-in-a-string.liberty b/Task/Reverse-words-in-a-string/Liberty-BASIC/reverse-words-in-a-string.liberty new file mode 100644 index 0000000000..f275175d64 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Liberty-BASIC/reverse-words-in-a-string.liberty @@ -0,0 +1,26 @@ +for i = 1 to 10 + read string$ + print reverse$(string$) +next +end + +function reverse$(string$) + token$="*" + while token$<>"" + i=i+1 + token$ = word$(string$, i) + output$=token$+" "+output$ + wend + reverse$ = trim$(output$) +end function + +data "---------- Ice and Fire ------------" +data "" +data "fire, in end will world the say Some" +data "ice. in say Some" +data "desire of tasted I've what From" +data "fire. favor who those with hold I" +data "" +data "... elided paragraph last ..." +data "" +data "Frost Robert -----------------------" 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 index 1c077532a5..b3e71317fb 100644 --- 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 @@ -3,7 +3,16 @@ rev: procedure options (main); /* 5 May 2014 */ declare (i, j) fixed binary; declare in file; - open file (in) title ('/REV-WRD.DAT,type(text),recsize(50)'); + open file (in) title ('/REV-WRD.DAT,type(text),recsize(5> Nil) { + for(j := words->Size() - 1; j > -1; j-=1;) { + IO.Console->Print(words[j])->Print(" "); + }; + }; + IO.Console->PrintLine(); + lines->Next(); + }; + } +}0)'); do j = 1 to 10; get file (in) edit (s) (L); 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 index 6111d45ed4..85c0bc75d6 100644 --- 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 @@ -1 +1 @@ -say .words.reverse for lines +say ~.words.reverse for lines diff --git a/Task/Reverse-words-in-a-string/PicoLisp/reverse-words-in-a-string.l b/Task/Reverse-words-in-a-string/PicoLisp/reverse-words-in-a-string.l new file mode 100644 index 0000000000..4d1ecde77d --- /dev/null +++ b/Task/Reverse-words-in-a-string/PicoLisp/reverse-words-in-a-string.l @@ -0,0 +1,3 @@ +(in "FireIce.txt" + (until (eof) + (prinl (glue " " (flip (split (line) " ")))))) diff --git a/Task/Reverse-words-in-a-string/PowerShell/reverse-words-in-a-string.psh b/Task/Reverse-words-in-a-string/PowerShell/reverse-words-in-a-string.psh new file mode 100644 index 0000000000..0ee891ce48 --- /dev/null +++ b/Task/Reverse-words-in-a-string/PowerShell/reverse-words-in-a-string.psh @@ -0,0 +1,20 @@ +Function Reverse-Words($lines) { + $lines | foreach { + $array = $PSItem.Split(' ') + $array[($array.Count-1)..0] -join ' ' + } +} + +$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 -----------------------" + +Reverse-Words($lines) diff --git a/Task/Reverse-words-in-a-string/PureBasic/reverse-words-in-a-string.purebasic b/Task/Reverse-words-in-a-string/PureBasic/reverse-words-in-a-string.purebasic new file mode 100644 index 0000000000..2ff69ff3d5 --- /dev/null +++ b/Task/Reverse-words-in-a-string/PureBasic/reverse-words-in-a-string.purebasic @@ -0,0 +1,21 @@ +a$ = "---------- Ice and Fire ------------" +#CRLF$+ + " " +#CRLF$+ + "fire, in end will world the say Some" +#CRLF$+ + "ice. in say Some " +#CRLF$+ + "desire of tasted I've what From " +#CRLF$+ + "fire. favor who those with hold I " +#CRLF$+ + " " +#CRLF$+ + "... elided paragraph last ... " +#CRLF$+ + " " +#CRLF$+ + "Frost Robert -----------------------" +#CRLF$ +a$ = "Hey you, Bub! " +#CRLF$+#CRLF$+ a$ + +OpenConsole() +For p1=1 To CountString(a$,#CRLF$) + b$=StringField(a$,p1,#CRLF$) : c$="" + For p2=1 To CountString(b$,Chr(32))+1 + c$=StringField(b$,p2,Chr(32))+Space(1)+c$ + Next + PrintN(LSet(b$,36,Chr(32))+" ---> "+Trim(c$)) +Next +Input() diff --git a/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string-1.rexx b/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string-1.rexx new file mode 100644 index 0000000000..af7637665c --- /dev/null +++ b/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string-1.rexx @@ -0,0 +1,20 @@ +/*REXX program 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 of the 10 lines of poem.*/ + $= /*nullify the $ string (the new line)*/ + do k=1 for words(@.j) /*process each word in a @.j string.*/ + $=word(@.j,k) $ /*prepend a word to the new line ($). */ + end /*k*/ /* [↑] we could do this another way. */ + + say $ /*display the newly constructed line. */ + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string-2.rexx b/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string-2.rexx new file mode 100644 index 0000000000..4d3993fe21 --- /dev/null +++ b/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string-2.rexx @@ -0,0 +1,20 @@ +/*REXX program 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 of the 10 lines of poem.*/ + $= /*nullify the $ string (the new line)*/ + do k=words(@.j) to 1 by -1 /*process each word in a @.j string.*/ + $=$ word(@.j,k) /*append a word to the new line ($). */ + end /*k*/ /* [↑] process last word to first word*/ + + say $ /*display the newly constructed line. */ + end /*j*/ /*stick a fork in it, we're all done. */ 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 deleted file mode 100644 index cbc564aba3..0000000000 --- a/Task/Reverse-words-in-a-string/REXX/reverse-words-in-a-string.rexx +++ /dev/null @@ -1,19 +0,0 @@ -/*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/Ruby/reverse-words-in-a-string.rb b/Task/Reverse-words-in-a-string/Ruby/reverse-words-in-a-string.rb index 2d5d763712..cf4cc07642 100644 --- 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 @@ -1,8 +1,4 @@ -def reverse_words(string) - string.each_line.map {|line| line.split.reverse.join(" ")} -end - -str = <<'EOS' +puts < String { + line.split_whitespace().rev().collect::>().join(" ") +} + +fn rev_words_on_lines(text: &str) -> String { + text.lines().map(rev_words).collect::>().join("\n") +} + +fn main() { + let 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 -----------------------"; + + println!("{}", rev_words_on_lines(text)); +} diff --git a/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-1.txr b/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-1.txr new file mode 100644 index 0000000000..cdb3ac9a62 --- /dev/null +++ b/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-1.txr @@ -0,0 +1 @@ +txr reverse.txr verse.txt diff --git a/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-2.txr b/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-2.txr new file mode 100644 index 0000000000..595ffc0d69 --- /dev/null +++ b/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-2.txr @@ -0,0 +1,13 @@ +@(collect) +@ (some) +@(coll)@{words /[^ ]+/}@(end) +@ (or) +@(bind words nil) +@ (end) +@(end) +@(set words @(mapcar (fun nreverse) words)) +@(output) +@ (repeat) +@(rep)@words @(last)@words@(end) +@ (end) +@(end) diff --git a/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-3.txr b/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-3.txr new file mode 100644 index 0000000000..4b21acaaa4 --- /dev/null +++ b/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-3.txr @@ -0,0 +1,2 @@ +@(end) +[EOF] diff --git a/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-4.txr b/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-4.txr new file mode 100644 index 0000000000..d49f5d4aa3 --- /dev/null +++ b/Task/Reverse-words-in-a-string/TXR/reverse-words-in-a-string-4.txr @@ -0,0 +1 @@ +@(end)[EOF] diff --git a/Task/Rock-paper-scissors/J/rock-paper-scissors-1.j b/Task/Rock-paper-scissors/J/rock-paper-scissors-1.j index 04b4416aa4..f9848521e2 100644 --- a/Task/Rock-paper-scissors/J/rock-paper-scissors-1.j +++ b/Task/Rock-paper-scissors/J/rock-paper-scissors-1.j @@ -1,4 +1,4 @@ -require'misc strings' +require'general/misc/prompt strings' NB. was 'misc strings' in older versions of J game=:3 :0 outcomes=. rps=. 0 0 0 choice=. 1+?3 diff --git a/Task/Rock-paper-scissors/Python/rock-paper-scissors-1.py b/Task/Rock-paper-scissors/Python/rock-paper-scissors-1.py new file mode 100644 index 0000000000..edaf6eda6f --- /dev/null +++ b/Task/Rock-paper-scissors/Python/rock-paper-scissors-1.py @@ -0,0 +1,22 @@ +from random import choice + +rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'} +previous = ['rock', 'paper', 'scissors'] + +while True: + human = input('\nchoose your weapon: ') + computer = rules[choice(previous)] # choose the weapon which beats a randomly chosen weapon from "previous" + + if human in ('quit', 'exit'): break + + elif human in rules: + previous.append(human) + print('the computer played', computer, end='; ') + + if rules[computer] == human: # if what beats the computer's choice is the human's choice... + print('yay you win!') + elif rules[human] == computer: # if what beats the human's choice is the computer's choice... + print('the computer beat you... :(') + else: print("it's a tie!") + + else: print("that's not a valid choice") diff --git a/Task/Rock-paper-scissors/Python/rock-paper-scissors-2.py b/Task/Rock-paper-scissors/Python/rock-paper-scissors-2.py new file mode 100644 index 0000000000..6c14fbf95d --- /dev/null +++ b/Task/Rock-paper-scissors/Python/rock-paper-scissors-2.py @@ -0,0 +1,10 @@ +from random import randint + +hands = ['rock', 'scissors', 'paper']; judge = ['its a tie!', 'the computer beat you... :(', 'yay you win!'] +while True: + try: + YOU = hands.index(input('Choose your weapon: ')) # YOU = hands.index(raw_input('Choose your weapon: ')) If you use Python2.7 + except ValueError: + break + NPC = randint(0, 2) + print('The computer played ' + hands[NPC] + '; ' + judge[YOU-NPC]) diff --git a/Task/Rock-paper-scissors/Python/rock-paper-scissors.py b/Task/Rock-paper-scissors/Python/rock-paper-scissors.py deleted file mode 100644 index 61b61b0dbc..0000000000 --- a/Task/Rock-paper-scissors/Python/rock-paper-scissors.py +++ /dev/null @@ -1,23 +0,0 @@ -from random import choice - -rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'} -previous = ['rock', 'paper', 'scissors'] - -while True: - human = input('\nchoose your weapon: ') - computer = rules[choice(previous)] # choose the weapon which beats a randomly chosen weapon from "previous" - - if human in ('quit', 'exit'): break - - elif human in rules: - previous.append(human) - print('the computer played', computer, end='; ') - - if rules[computer] == human: # if what beats the computer's choice is the human's choice... - print('yay you win!') - elif rules[human] == computer: # if what beats the human's choice is the computer's choice... - print('the computer beat you... :(') - else: - print("it's a tie!") - - else: print("that's not a valid choice") diff --git a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx index 4a85a226a7..32e70f85f6 100644 --- a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx +++ b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx @@ -1,35 +1,35 @@ -/*REXX pgm plays rock─paper─scissors with a CBLF: carbon─based life form*/ -!= '────────'; err='***error!***'; @.=0 /*some pgm constants. */ +/*REXX program plays rock─paper─scissors with a CBLF: carbon─based life form.*/ +!= '────────'; err=! '***error!***'; @.=0 /*some program constants. */ prompt=! 'Please enter one of: Rock Paper Scissors (or Quit)' -$.p='paper' ; $.s='scissors'; $.r='rock' /*computer's choices. */ -t.p=$.r ; t.s=$.p ; t.r=$.s /*thingys beats stuff.*/ -w.p=$.s ; w.s=$.r ; w.r=$.p /*stuff beats thingys.*/ -b.p='covers'; b.s='cuts' ; b.r='breaks' /*how the choice wins.*/ +$.p='paper' ; $.s='scissors'; $.r='rock' /*list of computer's choices*/ +t.p=$.r ; t.s=$.p ; t.r=$.s /*thingys that beats stuff */ +w.p=$.s ; w.s=$.r ; w.r=$.p /*stuff " " thingys*/ +b.p='covers'; b.s='cuts' ; b.r='breaks' /*verbs: how the choice wins*/ - do forever; say; say prompt; say /*prompt the CBLF, get response.*/ - c=word($.p $.s $.r, random(1, 3)) /*choose the computer's 1st pick.*/ - m=max(@.r, @.p, @.s); c=w.r /*prepare to examine the history.*/ - if @.p==m then c=w.p /*emulate JC's The Amazing Karnac*/ - if @.s==m then c=w.s /* " " " " " */ - c1=left(c,1) /*C1 is used for fast comparing.*/ - parse pull u; a=strip(u) /*get the CBLF's choice (answer).*/ - upper a c1 ; a1=left(a,1) /*uppercase choices, get 1st char*/ - ok=0 /*indicate answer isn't OK so far*/ - select /*process the CBLF's choice. */ + do forever; say; say prompt; say /*prompt the CBLF; then get a response.*/ + c=word($.p $.s $.r, random(1, 3)) /*choose the computer's first pick. */ + m=max(@.r, @.p, @.s); c=w.r /*prepare to examine the choice history*/ + if @.p==m then c=w.p /*emulate JC's: The Amazing Karnac. */ + if @.s==m then c=w.s /* " " " " " */ + c1=left(c,1) /*C1 is used for faster comparing. */ + parse pull u; a=strip(u) /*get the CBLF's choice/pick (answer). */ + upper a c1 ; a1=left(a,1) /*uppercase choices, get 1st character.*/ + ok=0 /*indicate answer isn't OK (so far). */ + select /*process/verify the CBLF's choice. */ when words(u)==0 then say err 'nothing entered' when words(u)>1 then say err 'too many choices: ' u - when abbrev('QUIT', a) then do; say ! 'quitting.'; exit; end + when abbrev('QUIT', a) then do; say ! 'quitting.'; exit; end when abbrev('ROCK', a) |, abbrev('PAPER', a) |, - abbrev('SCISSORS',a) then ok=1 /*a valid answer by CBLF.*/ - otherwise say err 'you entered a bad choice: ' u + abbrev('SCISSORS',a) then ok=1 /*Yes? A valid answer by CBLF.*/ + otherwise say err 'you entered a bad choice: ' u end /*select*/ - if \ok then iterate /*answer ¬ OK? Then get another.*/ - @.a1=@.a1+1 /*keep track of CBLF's answers. */ - say ! 'computer chose: ' c - if a1==c1 then do; say ! 'draw.'; iterate; end + if \ok then iterate /*answer ¬OK? Then get another choice.*/ + @.a1=@.a1+1 /*keep a history of the CBLF's choices.*/ + say ! 'computer chose: ' c + if a1==c1 then do; say ! 'draw.'; iterate; end /*it's a draw. */ if $.a1==t.c1 then say ! 'the computer wins. ' ! $.c1 b.c1 $.a1 else say ! 'you win! ' ! $.a1 b.a1 $.c1 end /*forever*/ - /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx index ab8c55e6c4..71390367c9 100644 --- a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx +++ b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx @@ -1,47 +1,48 @@ +/*REXX program plays rock─paper─scissors with a CBLF: carbon─based life form.*/ +!= '────────'; err=! '***error!***'; @.=0 /*some program constants.*/ prompt=! 'Please enter one of: Rock Paper SCissors Lizard SPock (Vulcan) (or Quit)' -$.p='paper' ; $.s='scissors' ; $.r='rock' ; $.l='lizard' ; $.v='Spock' /*names of the thingys*/ -t.p= $.r $.v ; t.s= $.p $.l ; t.r= $.s $.l ; t.l= $.p $.v ; t.v= $.r $.s /*thingys beats stuff.*/ -w.p= $.l $.s ; w.s= $.v $.r ; w.r= $.v $.p ; w.l= $.r $.s ; w.v= $.l $.p /*stuff beats thingys.*/ -b.p='covers disproves'; b.s='cuts decapitates'; b.r='breaks crushes'; b.l='eats poisons'; b.v='vaporizes smashes' /*how the choice wins.*/ -whom.1=! 'the computer wins. ' !; whom.2=! 'you win! ' !; win=words(t.p) +$.p='paper' ; $.s='scissors' ; $.r='rock' ; $.L='lizard' ; $.v='Spock' /*names of the thingys*/ +t.p= $.r $.v ; t.s= $.p $.L ; t.r= $.s $.L ; t.L= $.p $.v ; t.v= $.r $.s /*thingys beats stuff.*/ +w.p= $.L $.s ; w.s= $.v $.r ; w.r= $.v $.p ; w.L= $.r $.s ; w.v= $.L $.p /*stuff beats thingys.*/ +b.p='covers disproves'; b.s='cuts decapitates'; b.r='breaks crushes'; b.L='eats poisons'; b.v='vaporizes smashes' /*how the choice wins.*/ +whom.1=! 'the computer wins. ' !; whom.2=! 'you win! ' !; win=words(t.p) - do forever; say; say prompt; say /*prompt CBLF & get response.*/ - c=word($.p $.s $.r $.l $.v',random(1,5)) /*the computer's first pick. */ - m=max(@.r,@.p,@.s,$.l,$.v) /*prepare to examine history.*/ - if @.p==m then c=word(w.p,random(1,2)) /*emulate The Amazing Karnac.*/ - if @.s==m then c=word(w.s,random(1,2)) /* " " " " */ - if @.r==m then c=word(w.r,random(1,2)) /* " " " " */ - if @.l==m then c=word(w.l,random(1,2)) /* " " " " */ - if @.v==m then c=word(w.v,random(1,2)) /* " " " " */ - c1=left(c,1) /*C1 is used for fast comparing.*/ - parse pull u; a=strip(u) /*get the CBLF's choice (answer).*/ - upper a c1 ; a1=left(a,1) /*uppercase choices, get 1st char*/ - ok=0 /*indicate answer isn't OK so far*/ - select /*process the CBLF's choice. */ - when words(u)==0 then say err 'nothing entered.' - when words(u)>1 then say err 'too many choices: ' u - when abbrev('QUIT', a) then do; say ! 'quitting.'; exit; end + do forever; say; say prompt; say /*prompt CBLF; then get a response.*/ + c=word($.p $.s $.r $.L $.v,random(1,5)) /*the computer's first choice/pick.*/ + m=max(@.r,@.p,@.s,@.L,@.v) /*used in examining CBLF's history.*/ + if @.p==m then c=word(w.p,random(1,2)) /*emulate JC's The Amazing Karnac.*/ + if @.s==m then c=word(w.s,random(1,2)) /* " " " " " */ + if @.r==m then c=word(w.r,random(1,2)) /* " " " " " */ + if @.L==m then c=word(w.L,random(1,2)) /* " " " " " */ + if @.v==m then c=word(w.v,random(1,2)) /* " " " " " */ + c1=left(c,1) /*C1 is used for faster comparing. */ + parse pull u; a=strip(u) /*obtain the CBLF's choice/pick. */ + upper a c1 ; a1=left(a,1) /*uppercase the choices, get 1st char. */ + ok=0 /*indicate answer isn't OK (so far). */ + select /* [↓] process the CBLF's choice/pick.*/ + when words(u)==0 then say err 'nothing entered.' + when words(u)>1 then say err 'too many choices: ' u + when abbrev('QUIT', a) then do; say ! 'quitting.'; exit; end when abbrev('LIZARD', a) |, abbrev('ROCK', a) |, abbrev('PAPER', a) |, abbrev('Vulcan', a) |, abbrev('SPOCK', a,2) | , - abbrev('SCISSORS',a,2) then ok=1 /*a valid CBLF answer.*/ - otherwise say err 'you entered a bad choice: ' u + abbrev('SCISSORS',a,2) then ok=1 /*it's a valid CBLF choice.*/ + otherwise say err 'you entered a bad choice: ' u end /*select*/ - if \ok then iterate /*answer ¬ OK? Then get another.*/ - @.a1=@.a1+1 /*keep track of CBLF's answers. */ + if \ok then iterate /*answer ¬OK? Then get another choice.*/ + @.a1=@.a1+1 /*keep a history of the CBLF's choices.*/ say ! 'computer chose: ' c - if a1==c1 then do; say ! 'draw.'; iterate; end - - do who=1 for 2 /*either computer | CBLF*/ - if who==2 then parse value a1 c1 with c1 a1 - do j=1 for win - if $.a1\==word(t.c1,j) then iterate - say whom.who $.c1 word(b.c1,j) $.a1 - leave - end /*j*/ - end /*who*/ + if a1==c1 then say ! 'draw.' /*Oh rats! The contest ended up a draw*/ + else do who=1 for 2 /*either the computer or the CBLF won. */ + if who==2 then parse value a1 c1 with c1 a1 + do j=1 for win /*see who won. */ + if $.a1\==word(t.c1,j) then iterate /*not this 'un. */ + say whom.who $.c1 word(b.c1,j) $.a1 /*notify winner.*/ + leave /*leave J loop.*/ + end /*j*/ + end /*who*/ end /*forever*/ - /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Roman-numerals-Decode/ALGOL-W/roman-numerals-decode.alg b/Task/Roman-numerals-Decode/ALGOL-W/roman-numerals-decode.alg new file mode 100644 index 0000000000..ace8268d94 --- /dev/null +++ b/Task/Roman-numerals-Decode/ALGOL-W/roman-numerals-decode.alg @@ -0,0 +1,95 @@ +begin + % decodes a roman numeral into an integer % + % there must be at least one blank after the numeral % + % This takes a lenient view on roman numbers so e.g. IIXX is 18 - see % + % the Discussion % + integer procedure romanToDecimal ( string(32) value roman ) ; + begin + integer decimal, rPos, currDigit, nextDigit, seqValue; + string(1) rDigit; + + % the roman number is a sequence of sequences of roman digits % + % if the previous sequence is of higher value digits than the next, % + % the higher value is added to the overall value % + % if the previous seequence is of lower value, it is subtracted % + % e.g. MCMLXII % + % the sequences are M, C, M, X, II % + % M is added, C subtracted, M added, X added and II added % + + % get the value of a sequence of roman digits % + integer procedure getSequence ; + if rDigit = " " then begin + % end of the number % + 0 + end + else begin + % have another sequence % + integer sValue; + sValue := 0; + while roman( rPos // 1 ) = rDigit do begin + sValue := sValue + currDigit; + rPos := rPos + 1; + end while_have_same_digit ; + % remember the next digit % + rDigit := roman( rPos // 1 ); + % result is the sequence value % + sValue + end getSequence ; + + % convert a roman digit into its decimal equivalent % + % an invalid digit will terminate the program, " " is 0 % + integer procedure getValue( string(1) value romanDigit ) ; + if romanDigit = "m" or romanDigit = "M" then 1000 + else if romanDigit = "d" or romanDigit = "D" then 500 + else if romanDigit = "c" or romanDigit = "C" then 100 + else if romanDigit = "l" or romanDigit = "L" then 50 + else if romanDigit = "x" or romanDigit = "X" then 10 + else if romanDigit = "v" or romanDigit = "V" then 5 + else if romanDigit = "i" or romanDigit = "I" then 1 + else if romanDigit = " " then 0 + else begin + write( s_w := 0, "Invalid roman digit: """, romanDigit, """" ); + assert false; + 0 + end getValue ; + + % get the first sequence % + decimal := 0; + rPos := 0; + rDigit := roman( rPos // 1 ); + currDigit := getValue( rDigit ); + seqValue := getSequence; + + % handle the sequences % + while rDigit not = " " do begin + % have another sequence % + nextDigit := getValue( rDigit ); + if currDigit < nextDigit + then % prev digit is lower % decimal := decimal - seqValue + else % prev digit is higher % decimal := decimal + seqValue + ; + currDigit := nextDigit; + seqValue := getSequence; + end while_have_a_roman_digit ; + + % add the final sequence % + decimal + seqValue + end roman ; + + % test the romanToDecimal routine % + + procedure testRoman ( string(32) value romanNumber ) ; + write( i_w := 5, romanNumber, romanToDecimal( romanNumber ) ); + + testRoman( "I" ); testRoman( "II" ); + testRoman( "III" ); testRoman( "IV" ); + testRoman( "V" ); testRoman( "VI" ); + testRoman( "VII" ); testRoman( "VIII" ); + testRoman( "IX" ); testRoman( "IIXX" ); + testRoman( "XIX" ); testRoman( "XX" ); + write( "..." ); + testRoman( "MCMXC" ); + testRoman( "MMVIII" ); + testRoman( "MDCLXVI" ); + +end. diff --git a/Task/Roman-numerals-Decode/Batch-File/roman-numerals-decode.bat b/Task/Roman-numerals-Decode/Batch-File/roman-numerals-decode.bat new file mode 100644 index 0000000000..f35c04023e --- /dev/null +++ b/Task/Roman-numerals-Decode/Batch-File/roman-numerals-decode.bat @@ -0,0 +1,45 @@ +@echo off +setlocal enabledelayedexpansion + +::Testing... +call :toArabic MCMXC +echo MCMXC = !arabic! +call :toArabic MMVIII +echo MMVIII = !arabic! +call :toArabic MDCLXVI +echo MDCLXVI = !arabic! +call :toArabic CDXLIV +echo CDXLIV = !arabic! +call :toArabic XCIX +echo XCIX = !arabic! +pause>nul +exit/b 0 + +::The "function"... +:toArabic +set roman=%1 +set arabic= +set lastval= + %== Alternative for counting the string length ==% +set leng=-1 +for /l %%. in (0,1,1000) do set/a leng+=1&if "!roman:~%%.,1!"=="" goto break +:break +set /a last=!leng!-1 +for /l %%i in (!last!,-1,0) do ( + set n=0 + if /i "!roman:~%%i,1!"=="M" set n=1000 + if /i "!roman:~%%i,1!"=="D" set n=500 + if /i "!roman:~%%i,1!"=="C" set n=100 + if /i "!roman:~%%i,1!"=="L" set n=50 + if /i "!roman:~%%i,1!"=="X" set n=10 + if /i "!roman:~%%i,1!"=="V" set n=5 + if /i "!roman:~%%i,1!"=="I" set n=1 + + if !n! lss !lastval! ( + set /a arabic-=n + ) else ( + set /a arabic+=n + ) + set lastval=!n! +) +goto :EOF diff --git a/Task/Roman-numerals-Decode/Elixir/roman-numerals-decode.elixir b/Task/Roman-numerals-Decode/Elixir/roman-numerals-decode.elixir new file mode 100644 index 0000000000..7a94956e49 --- /dev/null +++ b/Task/Roman-numerals-Decode/Elixir/roman-numerals-decode.elixir @@ -0,0 +1,23 @@ +defmodule Roman_numeral do + def decode([]), do: 0 + def decode([x]), do: to_value(x) + def decode([h1, h2 | rest]) do + case {to_value(h1), to_value(h2)} do + {v1, v2} when v1 < v2 -> v2 - v1 + decode(rest) + {v1, v1} -> v1 + v1 + decode(rest) + {v1, _} -> v1 + decode([h2 | rest]) + end + end + + defp to_value(?M), do: 1000 + defp to_value(?D), do: 500 + defp to_value(?C), do: 100 + defp to_value(?L), do: 50 + defp to_value(?X), do: 10 + defp to_value(?V), do: 5 + defp to_value(?I), do: 1 +end + +Enum.each(['MCMXC', 'MMVIII', 'MDCLXVI'], fn clist -> + IO.puts "#{clist}\t: #{Roman_numeral.decode(clist)}" +end) diff --git a/Task/Roman-numerals-Decode/Forth/roman-numerals-decode.fth b/Task/Roman-numerals-Decode/Forth/roman-numerals-decode-1.fth similarity index 100% rename from Task/Roman-numerals-Decode/Forth/roman-numerals-decode.fth rename to Task/Roman-numerals-Decode/Forth/roman-numerals-decode-1.fth diff --git a/Task/Roman-numerals-Decode/Forth/roman-numerals-decode-2.fth b/Task/Roman-numerals-Decode/Forth/roman-numerals-decode-2.fth new file mode 100644 index 0000000000..2276cf894f --- /dev/null +++ b/Task/Roman-numerals-Decode/Forth/roman-numerals-decode-2.fth @@ -0,0 +1,44 @@ + Alternative Forth methodology +\ create words to describe and solve the problem +HEX +: toUpper ( char -- char ) 05F and ; + +DECIMAL +\ status holders +variable oldndx +variable curndx +variable negcnt + +\ word to compile a quote delimtited string into memory +: ," ( -- ) [char] " word C@ 1+ allot ; + +\ look-up tables place into memory +create numerals ," IVXLCDM" +create values 0 , 1 , 5 , 10 , 50 , 100 , 500 , 1000 , + +\ define words to describe/solve the problem +: init ( -- ) curndx off oldndx off negcnt off ; +: toindex ( char -- indx) toUpper numerals count rot SCAN dup 0= abort" invalid numeral" ; +: tovalue ( ndx -- n ) cells values + @ ; +: remember ( ndx -- ndx ) curndx @ oldndx ! dup curndx ! ; +: memory@ ( -- n1 n2 ) curndx @ oldndx @ ; +: numval ( char -- n ) toindex remember tovalue ; +: ?illegal ( ndx -- ) memory@ = negcnt @ and abort" illegal format" ; + +\ logic +: negate? ( n -- +/- n ) + memory@ < + if negcnt on + negate + else + ?illegal + negcnt off + then ; + +\ solution +: decode ( c-addr -- n ) + init + 0 \ accumulator on the stack + swap + count 1- bounds swap + do i c@ numval negate? + -1 +loop ;. diff --git a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode.js b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-1.js similarity index 100% rename from Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode.js rename to Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-1.js diff --git a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-2.js b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-2.js new file mode 100644 index 0000000000..ab56d55035 --- /dev/null +++ b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-2.js @@ -0,0 +1,71 @@ +(function (lstTest) { + + var dctGlyphs = { + 'M': 1000, + 'CM': 900, + 'D': 500, + 'CD': 400, + 'C': 100, + 'XC': 90, + 'L': 50, + 'XL': 40, + 'X': 10, + 'IX': 9, + 'V': 5, + 'IV': 4, + 'I': 1 + }, + lstGlyphs = Object.keys(dctGlyphs); + + // s -> {name: [s], value: Int} + function romanValue(s) { + + function trans(lstChars, lngStart) { + var lngChars = lstChars.length, + dctParse = lngChars ? lstGlyphs.reduce( + function (dctA, strGlyph) { + return isPrefixOf(strGlyph.split(''), dctA.chars) ? { + value: dctA.value + dctGlyphs[strGlyph], + chars: drop(strGlyph.length, dctA.chars) + } : dctA; + }, { + value: lngStart, + chars: lstChars + } + ) : { + chars: [], + value: null + }, + lstRest = dctParse.chars || [], + lngRest = lstRest.length; + + return lngRest && (lngRest !== lngChars) ? ( + trans(lstRest, dctParse.value) + ) : dctParse; + } + + var dctTrans = trans(s.toUpperCase().split(''), 0); + + return dctTrans.chars.length ? null : dctTrans.value; + } + + // [a] -> [a] -> Bool + function isPrefixOf(lstFirst, lstSecond) { + return lstFirst.length ? ( + lstSecond.length ? + lstFirst[0] === lstSecond[0] && isPrefixOf( + lstFirst.slice(1), lstSecond.slice(1) + ) : false + ) : true; + } + + // Int -> [a] -> [a] + function drop(n, lst) { + return n <= 0 ? lst : ( + lst.length ? drop(n - 1, lst.slice(1)) : [] + ); + } + + return lstTest.map(romanValue); + +})(['MCMXC', 'MDCLXVI', 'MMVIII']); diff --git a/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-3.js b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-3.js new file mode 100644 index 0000000000..58f75b9898 --- /dev/null +++ b/Task/Roman-numerals-Decode/JavaScript/roman-numerals-decode-3.js @@ -0,0 +1 @@ +[1990, 1666, 2008] diff --git a/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-1.julia b/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-1.julia new file mode 100644 index 0000000000..80f987f460 --- /dev/null +++ b/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-1.julia @@ -0,0 +1,21 @@ +function parseroman(r::ASCIIString) + const RD = ["I" => 1, "V" => 5, "X" => 10, "L" => 50, + "C" => 100, "D" => 500, "M" => 1000] + maxval = 0 + accum = 0 + for d in reverse(split(uppercase(r), "")) + if !(d in keys(RD)) + throw(DomainError()) + end + val = RD[d] + if val > maxval + maxval = val + end + if val < maxval + accum -= val + else + accum += val + end + end + return accum +end diff --git a/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-2.julia b/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-2.julia new file mode 100644 index 0000000000..6576e9bc3d --- /dev/null +++ b/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-2.julia @@ -0,0 +1,14 @@ +testcases = ASCIIString["I", "III", "IX", "IVI", "IIM", + "CMMDXL", "icv", "cDxLiV", "MCMLD", "ccccccd", + "iiiiiv", "MMXV", "MCMLXXXIV", "ivxmm", "SPQR"] + +println("Test parseroman, roman => arabic:") +for r in testcases + print(r, " => ") + i = try + parseroman(r) + catch + "Invalid" + end + println(i) +end diff --git a/Task/Roman-numerals-Decode/PowerShell/roman-numerals-decode.psh b/Task/Roman-numerals-Decode/PowerShell/roman-numerals-decode.psh new file mode 100644 index 0000000000..6df0d6c8a4 --- /dev/null +++ b/Task/Roman-numerals-Decode/PowerShell/roman-numerals-decode.psh @@ -0,0 +1,93 @@ +function ConvertFrom-RomanNumeral +{ + <# + .SYNOPSIS + Converts a roman numeral to a number. + .DESCRIPTION + Converts a roman numeral - in the range of I..MMMCMXCIX - to a number. + .PARAMETER Numeral + A roman numeral in the range I..MMMCMXCIX (1..3,999). + .INPUTS + System.String + .OUTPUTS + System.Int32 + .NOTES + Requires PowerShell version 3.0 + .EXAMPLE + ConvertFrom-RomanNumeral -Numeral MMXIV + .EXAMPLE + "MMXIV" | ConvertFrom-RomanNumeral + #> + [CmdletBinding()] + [OutputType([int])] + Param + ( + [Parameter(Mandatory=$true, + HelpMessage="Enter a roman numeral in the range I..MMMCMXCIX", + ValueFromPipeline=$true, + Position=0)] + [ValidatePattern("(?x)^ + M{0,3} # Thousands + (CM|CD|D?C{0,3}) # Hundreds + (XC|XL|L?X{0,3}) # Tens + (IX|IV|V?I{0,3}) # Ones + $")] + [string] + $Numeral + ) + + Begin + { + # This must be an [ordered] hashtable + $RomanToDecimal = [ordered]@{ + M = 1000 + CM = 900 + D = 500 + CD = 400 + C = 100 + XC = 90 + L = 50 + X = 10 + IX = 9 + V = 5 + IV = 4 + I = 1 + } + } + Process + { + $roman = $Numeral + '$' + $value = 0 + + do + { + foreach ($key in $RomanToDecimal.Keys) + { + if ($key.Length -eq 1) + { + if ($key -match $roman.Substring(0,1)) + { + $value += $RomanToDecimal.$key + $roman = $roman.Substring(1) + break + } + } + else + { + if ($key -match $roman.Substring(0,2)) + { + $value += $RomanToDecimal.$key + $roman = $roman.Substring(2) + break + } + } + } + } + until ($roman -eq '$') + + $value + } + End + { + } +} diff --git a/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode.rb b/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode-1.rb similarity index 100% rename from Task/Roman-numerals-Decode/Ruby/roman-numerals-decode.rb rename to Task/Roman-numerals-Decode/Ruby/roman-numerals-decode-1.rb diff --git a/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode-2.rb b/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode-2.rb new file mode 100644 index 0000000000..9b09a68bba --- /dev/null +++ b/Task/Roman-numerals-Decode/Ruby/roman-numerals-decode-2.rb @@ -0,0 +1,11 @@ +SYMBOLS = [ ['M', 1000], ['CM', 900], ['D', 500], ['CD', 400], ['C', 100], ['XC', 90], + ['L', 50], ['XL', 40], ['X', 10], ['IX', 9], ['V', 5], ['IV', 4], ['I', 1] ] + +def parseRoman(roman) + r = roman.upcase + n = 0 + SYMBOLS.each { |sym, val| n += val while r.sub!(/^#{sym}/, "") } + n +end + +[ "MCMXC", "MMVIII", "MDCLXVI" ].each {|r| puts "%8s :%5d" % [r, parseRoman(r)]} diff --git a/Task/Roman-numerals-Decode/Rust/roman-numerals-decode.rust b/Task/Roman-numerals-Decode/Rust/roman-numerals-decode.rust index 2c89fe68a8..7074bcd58e 100644 --- a/Task/Roman-numerals-Decode/Rust/roman-numerals-decode.rust +++ b/Task/Roman-numerals-Decode/Rust/roman-numerals-decode.rust @@ -1,37 +1,35 @@ struct RomanNumeral { - symbol: &'static str, - value: uint + symbol: &'static str, + value: u32 } -static NUMERALS: [RomanNumeral, ..13] = [ - RomanNumeral {symbol: "M", value: 1000}, - RomanNumeral {symbol: "CM", value: 900}, - RomanNumeral {symbol: "D", value: 500}, - RomanNumeral {symbol: "CD", value: 400}, - RomanNumeral {symbol: "C", value: 100}, - RomanNumeral {symbol: "XC", value: 90}, - RomanNumeral {symbol: "L", value: 50}, - RomanNumeral {symbol: "XL", value: 40}, - RomanNumeral {symbol: "X", value: 10}, - RomanNumeral {symbol: "IX", value: 9}, - RomanNumeral {symbol: "V", value: 5}, - RomanNumeral {symbol: "IV", value: 4}, - RomanNumeral {symbol: "I", value: 1} +const NUMERALS: [RomanNumeral; 13] = [ + RomanNumeral {symbol: "M", value: 1000}, + RomanNumeral {symbol: "CM", value: 900}, + RomanNumeral {symbol: "D", value: 500}, + RomanNumeral {symbol: "CD", value: 400}, + RomanNumeral {symbol: "C", value: 100}, + RomanNumeral {symbol: "XC", value: 90}, + RomanNumeral {symbol: "L", value: 50}, + RomanNumeral {symbol: "XL", value: 40}, + RomanNumeral {symbol: "X", value: 10}, + RomanNumeral {symbol: "IX", value: 9}, + RomanNumeral {symbol: "V", value: 5}, + RomanNumeral {symbol: "IV", value: 4}, + RomanNumeral {symbol: "I", value: 1} ]; -fn to_hindu(roman: &str) -> uint { - for numeral in NUMERALS.iter() { - if roman.starts_with(numeral.symbol) { - return numeral.value + to_hindu(roman.slice_from(numeral.symbol.len())); +fn to_hindu(roman: &str) -> u32 { + match NUMERALS.iter().find(|num| roman.starts_with(num.symbol)) { + Some(num) => num.value + to_hindu(&roman[num.symbol.len()..]), + None => 0, // if string empty, add nothing } - } - - return 0; } fn main() { - let roms = ["MMXIV", "MCMXCIX", "XXV", "MDCLXVI", "MMMDCCCLXXXVIII"]; - for r in roms.iter() { - println!("{:s} = {:u}", *r, to_hindu(*r)); - } + let roms = ["MMXIV", "MCMXCIX", "XXV", "MDCLXVI", "MMMDCCCLXXXVIII"]; + for &r in &roms { + // 15 is minimum formatting width of the first argument, there for alignment + println!("{:2$} = {}", r, to_hindu(r), 15); + } } diff --git a/Task/Roman-numerals-Encode/Batch-File/roman-numerals-encode.bat b/Task/Roman-numerals-Encode/Batch-File/roman-numerals-encode.bat new file mode 100644 index 0000000000..468ab2db04 --- /dev/null +++ b/Task/Roman-numerals-Encode/Batch-File/roman-numerals-encode.bat @@ -0,0 +1,32 @@ +@echo off +setlocal enabledelayedexpansion + +set cnt=0&for %%A in (1000,900,500,400,100,90,50,40,10,9,5,4,1) do (set arab!cnt!=%%A&set /a cnt+=1) +set cnt=0&for %%R in (M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I) do (set rom!cnt!=%%R&set /a cnt+=1) + +::Testing +call :toRoman 2009 +echo 2009 = !result! +call :toRoman 1666 +echo 1666 = !result! +call :toRoman 3888 +echo 3888 = !result! +pause>nul +exit/b 0 + +::The "function"... +:toRoman +set value=%1 +set result= + +for /l %%i in (0,1,12) do ( + set a=%%i + call :add_val +) +goto :EOF + +:add_val +if !value! lss !arab%a%! goto :EOF +set result=!result!!rom%a%! +set /a value-=!arab%a%! +goto add_val diff --git a/Task/Roman-numerals-Encode/Befunge/roman-numerals-encode.bf b/Task/Roman-numerals-Encode/Befunge/roman-numerals-encode.bf new file mode 100644 index 0000000000..2ca53ebb02 --- /dev/null +++ b/Task/Roman-numerals-Encode/Befunge/roman-numerals-encode.bf @@ -0,0 +1,6 @@ +&>0\0>00p:#v_$ >:#,_ $ @ +4-v >5+#:/#<\55+%:5/\5%: +vv_$9+00g+5g\00g8+>5g\00 +g>\20p>:10p00g \#v _20gv +> 2+ v^-1g01\g5+8<^ +9 _ + IVXLCDM diff --git a/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-1.elixir b/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-1.elixir new file mode 100644 index 0000000000..38aa568803 --- /dev/null +++ b/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-1.elixir @@ -0,0 +1,17 @@ +defmodule Roman_numeral do + def encode(0), do: '' + def encode(x) when x >= 1000, do: [?M | encode(x - 1000)] + def encode(x) when x >= 100, do: digit(div(x,100), ?C, ?D, ?M) ++ encode(rem(x,100)) + def encode(x) when x >= 10, do: digit(div(x,10), ?X, ?L, ?C) ++ encode(rem(x,10)) + def encode(x) when x >= 1, do: digit(x, ?I, ?V, ?X) + + defp digit(1, x, _, _), do: [x] + defp digit(2, x, _, _), do: [x, x] + defp digit(3, x, _, _), do: [x, x, x] + defp digit(4, x, y, _), do: [x, y] + defp digit(5, _, y, _), do: [y] + defp digit(6, x, y, _), do: [y, x] + defp digit(7, x, y, _), do: [y, x, x] + defp digit(8, x, y, _), do: [y, x, x, x] + defp digit(9, x, _, z), do: [x, z] +end diff --git a/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-2.elixir b/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-2.elixir new file mode 100644 index 0000000000..5890ff4f02 --- /dev/null +++ b/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-2.elixir @@ -0,0 +1,10 @@ +defmodule Roman_numeral do + @symbols [ {1000, 'M'}, {900, 'CM'}, {500, 'D'}, {400, 'CD'}, {100, 'C'}, {90, 'XC'}, + {50, 'L'}, {40, 'XL'}, {10, 'X'}, {9, 'IX'}, {5, 'V'}, {4, 'IV'}, {1, 'I'} ] + def encode(num) do + {roman,_} = Enum.reduce(@symbols, {[], num}, fn {divisor, letter}, {memo, n} -> + {memo ++ List.duplicate(letter, div(n, divisor)), rem(n, divisor)} + end) + Enum.join(roman) + end +end diff --git a/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-3.elixir b/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-3.elixir new file mode 100644 index 0000000000..a22a336ccf --- /dev/null +++ b/Task/Roman-numerals-Encode/Elixir/roman-numerals-encode-3.elixir @@ -0,0 +1,3 @@ +Enum.each([1990, 2008, 1666], fn n -> + IO.puts "#{n}: #{Roman_numeral.encode(n)}" +end) diff --git a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode.js b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-1.js similarity index 100% rename from Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode.js rename to Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-1.js diff --git a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-2.js b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-2.js new file mode 100644 index 0000000000..b72885b53a --- /dev/null +++ b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-2.js @@ -0,0 +1,50 @@ +function roman(strIntegers) { + 'use strict'; + // DICTIONARY OF GLYPH:VALUE MAPPINGS + var dctGlyphs = { + M: 1000, + CM: 900, + D: 500, + CD: 400, + C: 100, + XC: 90, + L: 50, + XL: 40, + X: 10, + IX: 9, + V: 5, + IV: 4, + I: 1 + }; + + // LIST OF INTEGER STRINGS, WITH ANY SEPARATOR + var strNums = typeof strIntegers === 'string' ? strIntegers : strIntegers.toString(), + lstParts = strNums.split(/\d+/), + strSeparator = lstParts.length > 1 ? lstParts[1] : '', + lstDecimal = strSeparator ? strIntegers.split(strSeparator) : [strNums]; + + + // REWRITE OF DECIMAL INTEGER AS ROMAN + function rewrite(strN) { + var n = Number(strN); + + /* Starting with the highest-valued glyph: + take as many bites as we can with it + (decrementing residual value with each bite, + and appending a corresponding glyph copy to the string) + before moving down to the next most expensive glyph */ + + // return Object.keys(dctGlyphs).reduce( + // OR: + return 'M CM D CD C XC L XL X IX V IV I'.split(' ').reduce( + function (s, k) { + var v = dctGlyphs[k]; + return n >= v ? (n -= v, s + k) : s; + }, '' + ) + + } + + // ALL REWRITTEN, WITH SEPARATOR RESTORED + return lstDecimal.map(rewrite).join(strSeparator); +} diff --git a/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-3.js b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-3.js new file mode 100644 index 0000000000..4b13115362 --- /dev/null +++ b/Task/Roman-numerals-Encode/JavaScript/roman-numerals-encode-3.js @@ -0,0 +1,5 @@ +roman(1999); +// --> "MCMXCIX" + +[1990, 2008, "14.09.2015", 2000, 1666].map(roman); +// --> ["MCMXC", "MCMCVI", "XIV.IX.MCMCXV", "MCMC", "MDCLXVI"] diff --git a/Task/Roman-numerals-Encode/Julia/roman-numerals-encode.julia b/Task/Roman-numerals-Encode/Julia/roman-numerals-encode.julia new file mode 100644 index 0000000000..d60290ff8f --- /dev/null +++ b/Task/Roman-numerals-Encode/Julia/roman-numerals-encode.julia @@ -0,0 +1,35 @@ +function romanencode(n::Integer) + const DR = [["I", "X", "C", "M"] ["V", "L", "D", "MMM"]] + rnum = "" + if n > 4999 || n < 1 + throw(DomainError()) + end + for (omag, d) in enumerate(digits(n)) + if d == 0 + omr = "" + elseif d < 4 + omr = DR[omag, 1]^d + elseif d == 4 + omr = DR[omag, 1]*DR[omag, 2] + elseif d == 5 + omr = DR[omag, 2] + elseif d < 9 + omr = DR[omag, 2]*(DR[omag, 1]^(d - 5)) + else + omr = DR[omag, 1]*DR[(omag +1), 1] + end + rnum = omr*rnum + end + return rnum +end + +testcases = Int64[1990, 2008, 1668] +for i in 1:12 + push!(testcases, rand(1:4999)) +end +testcases = unique(testcases) + +println("Test romanencode, arabic => roman:") +for i in testcases + println(i, " => ", romanencode(i)) +end diff --git a/Task/Roman-numerals-Encode/PowerShell/roman-numerals-encode.psh b/Task/Roman-numerals-Encode/PowerShell/roman-numerals-encode.psh new file mode 100644 index 0000000000..16d4475449 --- /dev/null +++ b/Task/Roman-numerals-Encode/PowerShell/roman-numerals-encode.psh @@ -0,0 +1,64 @@ +function ConvertTo-RomanNumeral +{ + <# + .SYNOPSIS + Converts a number to a Roman numeral. + .DESCRIPTION + Converts a number - in the range of 1 to 3,999 - to a Roman numeral. + .PARAMETER Number + An integer in the range 1 to 3,999. + .INPUTS + System.Int32 + .OUTPUTS + System.String + .EXAMPLE + ConvertTo-RomanNumeral -Number (Get-Date).Year + .EXAMPLE + (Get-Date).Year | ConvertTo-RomanNumeral + #> + [CmdletBinding()] + [OutputType([string])] + Param + ( + [Parameter(Mandatory=$true, + HelpMessage="Enter an integer in the range 1 to 3,999", + ValueFromPipeline=$true, + Position=0)] + [ValidateRange(1,3999)] + [int] + $Number + ) + + Begin + { + $DecimalToRoman = @{ + Thousands = "","M","MM","MMM" + Hundreds = "","C","CC","CCC","CD","D","DC","DCC","DCCC","CM" + Tens = "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC" + Ones = "","I","II","III","IV","V","VI","VII","VIII","IX" + } + + $column = @{ + Thousands = 0 + Hundreds = 1 + Tens = 2 + Ones = 3 + } + } + Process + { + [int[]]$digits = $Number.ToString().PadLeft(4,"0").ToCharArray() | + ForEach-Object { [Char]::GetNumericValue($_) } + + $RomanNumeral = "" + $RomanNumeral += $DecimalToRoman.Thousands[$digits[$column.Thousands]] + $RomanNumeral += $DecimalToRoman.Hundreds[$digits[$column.Hundreds]] + $RomanNumeral += $DecimalToRoman.Tens[$digits[$column.Tens]] + $RomanNumeral += $DecimalToRoman.Ones[$digits[$column.Ones]] + + $RomanNumeral + } + End + { + } +} diff --git a/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust b/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust index 26b44eefad..29de2256a4 100644 --- a/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust +++ b/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust @@ -1,37 +1,39 @@ struct RomanNumeral { - symbol: &'static str, - value: uint + symbol: &'static str, + value: u32 } -static NUMERALS: [RomanNumeral, ..13] = [ - RomanNumeral {symbol: "M", value: 1000}, - RomanNumeral {symbol: "CM", value: 900}, - RomanNumeral {symbol: "D", value: 500}, - RomanNumeral {symbol: "CD", value: 400}, - RomanNumeral {symbol: "C", value: 100}, - RomanNumeral {symbol: "XC", value: 90}, - RomanNumeral {symbol: "L", value: 50}, - RomanNumeral {symbol: "XL", value: 40}, - RomanNumeral {symbol: "X", value: 10}, - RomanNumeral {symbol: "IX", value: 9}, - RomanNumeral {symbol: "V", value: 5}, - RomanNumeral {symbol: "IV", value: 4}, - RomanNumeral {symbol: "I", value: 1} +const NUMERALS: [RomanNumeral; 13] = [ + RomanNumeral {symbol: "M", value: 1000}, + RomanNumeral {symbol: "CM", value: 900}, + RomanNumeral {symbol: "D", value: 500}, + RomanNumeral {symbol: "CD", value: 400}, + RomanNumeral {symbol: "C", value: 100}, + RomanNumeral {symbol: "XC", value: 90}, + RomanNumeral {symbol: "L", value: 50}, + RomanNumeral {symbol: "XL", value: 40}, + RomanNumeral {symbol: "X", value: 10}, + RomanNumeral {symbol: "IX", value: 9}, + RomanNumeral {symbol: "V", value: 5}, + RomanNumeral {symbol: "IV", value: 4}, + RomanNumeral {symbol: "I", value: 1} ]; -fn to_roman(num: uint) -> String { - for numeral in NUMERALS.iter() { - if num >= numeral.value { - return numeral.symbol.to_string() + to_roman(num - numeral.value); +fn to_roman(mut number: u32) -> String { + let mut min_numeral = String::new(); + for numeral in NUMERALS.iter() { + while numeral.value <= number { + min_numeral = min_numeral + numeral.symbol; + number -= numeral.value; + } } - } - - return "".to_string(); + min_numeral } fn main() { - let nums = [2014, 1999, 25, 1666, 3888]; - for n in nums.iter() { - println!("{:u} = {:s}", *n, to_roman(*n)); - } + let nums = [2014, 1999, 25, 1666, 3888]; + for &n in nums.iter() { + // 4 is minimum printing width, for alignment + println!("{:2$} = {}", n, to_roman(n), 4); + } } diff --git a/Task/Roots-of-a-function/C++/roots-of-a-function.cpp b/Task/Roots-of-a-function/C++/roots-of-a-function-1.cpp similarity index 100% rename from Task/Roots-of-a-function/C++/roots-of-a-function.cpp rename to Task/Roots-of-a-function/C++/roots-of-a-function-1.cpp diff --git a/Task/Roots-of-a-function/C++/roots-of-a-function-2.cpp b/Task/Roots-of-a-function/C++/roots-of-a-function-2.cpp new file mode 100644 index 0000000000..846905f576 --- /dev/null +++ b/Task/Roots-of-a-function/C++/roots-of-a-function-2.cpp @@ -0,0 +1,97 @@ +#include +#include +#include +#include + +double brents_fun(std::function f, double lower, double upper, double tol, unsigned int max_iter) +{ + double a = lower; + double b = upper; + double fa = f(a); // calculated now to save function calls + double fb = f(b); // calculated now to save function calls + double fs = 0; // initialize + + if (!(fa * fb < 0)) + { + std::cout << "Signs of f(lower_bound) and f(upper_bound) must be opposites" << std::endl; // throws exception if root isn't bracketed + return -11; + } + + if (std::abs(fa) < std::abs(b)) // if magnitude of f(lower_bound) is less than magnitude of f(upper_bound) + { + std::swap(a,b); + std::swap(fa,fb); + } + + double c = a; // c now equals the largest magnitude of the lower and upper bounds + double fc = fa; // precompute function evalutation for point c by assigning it the same value as fa + bool mflag = true; // boolean flag used to evaluate if statement later on + double s = 0; // Our Root that will be returned + double d = 0; // Only used if mflag is unset (mflag == false) + + for (unsigned int iter = 1; iter < max_iter; ++iter) + { + // stop if converged on root or error is less than tolerance + if (std::abs(b-a) < tol) + { + std::cout << "After " << iter << " iterations the root is: " << s << std::endl; + return s; + } // end if + + if (fa != fc && fb != fc) + { + // use inverse quadratic interopolation + s = ( a * fb * fc / ((fa - fb) * (fa - fc)) ) + + ( b * fa * fc / ((fb - fa) * (fb - fc)) ) + + ( c * fa * fb / ((fc - fa) * (fc - fb)) ); + } + else + { + // secant method + s = b - fb * (b - a) / (fb - fa); + } + + // checks to see whether we can use the faster converging quadratic && secant methods or if we need to use bisection + if ( ( (s < (3 * a + b) * 0.25) || (s > b) ) || + ( mflag && (std::abs(s-b) >= (std::abs(b-c) * 0.5)) ) || + ( !mflag && (std::abs(s-b) >= (std::abs(c-d) * 0.5)) ) || + ( mflag && (std::abs(b-c) < tol) ) || + ( !mflag && (std::abs(c-d) < tol)) ) + { + // bisection method + s = (a+b)*0.5; + + mflag = true; + } + else + { + mflag = false; + } + + fs = f(s); // calculate fs + d = c; // first time d is being used (wasnt used on first iteration because mflag was set) + c = b; // set c equal to upper bound + fc = fb; // set f(c) = f(b) + + if ( fa * fs < 0) // fa and fs have opposite signs + { + b = s; + fb = fs; // set f(b) = f(s) + } + else + { + a = s; + fa = fs; // set f(a) = f(s) + } + + if (std::abs(fa) < std::abs(fb)) // if magnitude of fa is less than magnitude of fb + { + std::swap(a,b); // swap a and b + std::swap(fa,fb); // make sure f(a) and f(b) are correct after swap + } + + } // end for + + std::cout<< "The solution does not converge or iterations are not sufficient" << std::endl; + +} // end brents_fun diff --git a/Task/Roots-of-a-function/C/roots-of-a-function.c b/Task/Roots-of-a-function/C/roots-of-a-function-1.c similarity index 100% rename from Task/Roots-of-a-function/C/roots-of-a-function.c rename to Task/Roots-of-a-function/C/roots-of-a-function-1.c diff --git a/Task/Roots-of-a-function/C/roots-of-a-function-2.c b/Task/Roots-of-a-function/C/roots-of-a-function-2.c new file mode 100644 index 0000000000..3bc63c8f43 --- /dev/null +++ b/Task/Roots-of-a-function/C/roots-of-a-function-2.c @@ -0,0 +1,17 @@ +#include +#include + +int main(int argc, char *argv[]) +{ + /* 0 + 2x - 3x^2 + 1x^3 */ + double p[] = {0, 2, -3, 1}; + double z[6]; + gsl_poly_complex_workspace *w = gsl_poly_complex_workspace_alloc(4); + gsl_poly_complex_solve(p, 4, w, z); + gsl_poly_complex_workspace_free(w); + + for(int i = 0; i < 3; ++i) + printf("%.12f\n", z[2 * i]); + + return 0; +} diff --git a/Task/Roots-of-a-function/Elixir/roots-of-a-function.elixir b/Task/Roots-of-a-function/Elixir/roots-of-a-function.elixir new file mode 100644 index 0000000000..994776ce81 --- /dev/null +++ b/Task/Roots-of-a-function/Elixir/roots-of-a-function.elixir @@ -0,0 +1,27 @@ +defmodule RC do + def find_roots(f, range, step \\ 0.001) do + first .. last = range + max = last + step / 2 + Stream.iterate(first, &(&1 + step)) + |> Stream.take_while(&(&1 < max)) + |> Enum.reduce(sign(first), fn x,sn -> + value = f.(x) + cond do + abs(value) < step / 100 -> + IO.puts "Root found at #{x}" + 0 + sign(value) == -sn -> + IO.puts "Root found between #{x-step} and #{x}" + -sn + true -> sign(value) + end + end) + end + + defp sign(x) when x>0, do: 1 + defp sign(x) when x<0, do: -1 + defp sign(0) , do: 0 +end + +f = fn x -> x*x*x - 3*x*x + 2*x end +RC.find_roots(f, -1..3) diff --git a/Task/Roots-of-a-function/Julia/roots-of-a-function.julia b/Task/Roots-of-a-function/Julia/roots-of-a-function.julia new file mode 100644 index 0000000000..b8a407d5e3 --- /dev/null +++ b/Task/Roots-of-a-function/Julia/roots-of-a-function.julia @@ -0,0 +1,3 @@ +using Roots + +println(fzeros(x -> x^3 - 3x^2 + 2x)) diff --git a/Task/Roots-of-a-function/REXX/roots-of-a-function-1.rexx b/Task/Roots-of-a-function/REXX/roots-of-a-function-1.rexx index 1672c68dc6..db33bccef1 100644 --- a/Task/Roots-of-a-function/REXX/roots-of-a-function-1.rexx +++ b/Task/Roots-of-a-function/REXX/roots-of-a-function-1.rexx @@ -1,16 +1,18 @@ -/*REXX program to find the roots of a specific function. */ -parse arg bot top inc . /*allow user to specify options. */ -if bot=='' | bot==',' then bot=-3 /*Not specified? Then use default*/ -if top=='' | top==',' then top=+3 /* " " " " " */ -if inc=='' | inc==',' then inc=.0001 /* " " " " " */ -z=f(bot); !=sign(z) +/*REXX pgm finds roots of a specific function: x^3 -3*x^2 +2*x via bisection.*/ +parse arg bot top inc . /*obtain optional arguments from the CL*/ +if bot=='' | bot==',' then bot= -5 /*Not specified? Then use the default.*/ +if top=='' | top==',' then top= +5 /* " " " " " " */ +if inc=='' | inc==',' then inc= .0001 /* " " " " " " */ +z=f(bot); !=sign(z) /*use these values for initial compare.*/ - do j=bot to top by inc /*traipse through all the values.*/ - z=f(j); $=sign(z) /*compute new value and the sign.*/ - if z=0 then say 'found a root at' j/1 - else if !\==$ then if !\==0 then say 'passed a root at' j/1 - !=$ /*use the new sign. */ + do j=bot to top by inc /*traipse through the specified range. */ + z=f(j); $=sign(z) /*compute the new value and the sign.*/ + if z=0 then say 'found an exact root at' j/1 + else if !\==$ then if !\==0 then say 'passed a root at' j/1 + !=$ /*use the new sign for the next compare*/ end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────F function──────────────────────────*/ -f: procedure; parse arg x; return x**3 - 3 * x**2 + 2 * x +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +f: parse arg x; return x*(x*(x-3)+2) /* x^3 - 3x^2 + 2x */ + /*with factoring ──► x{ x^2 -3x + 2 } */ + /*more " ──► x{ x( x-3 ) + 2 } */ diff --git a/Task/Roots-of-a-function/REXX/roots-of-a-function-2.rexx b/Task/Roots-of-a-function/REXX/roots-of-a-function-2.rexx index bfca864f74..ddee5551c5 100644 --- a/Task/Roots-of-a-function/REXX/roots-of-a-function-2.rexx +++ b/Task/Roots-of-a-function/REXX/roots-of-a-function-2.rexx @@ -1,2 +1,11 @@ -/*──────────────────────────────────F function──────────────────────────*/ -f: procedure; parse arg x; x2=x*x; return x*x2 - 3*x2 + x+x +/* REXX */ +Parse Version v; Say v +n=1000000 +Say 'N='n +Call time 'R'; Do i=1 To n; xx=f1(5); End; Say 'f1' xx time('E') +Call time 'R'; Do i=1 To n; xx=f2(5); End; Say 'f2' xx time('E') +Call time 'R'; Do i=1 To n; xx=f3(5); End; Say 'f3' xx time('E') +Exit +f1: procedure; parse arg x; return x**3 - 3 * x**2 + 2 * x +f2: procedure; parse arg x; x2=x*x; return x*x2 - 3*x2 + x+x +f3: Return((arg(1)-3)*arg(1)+2)*arg(1) diff --git a/Task/Roots-of-a-quadratic-function/00DESCRIPTION b/Task/Roots-of-a-quadratic-function/00DESCRIPTION index 189cd63840..5d4ed114fd 100644 --- a/Task/Roots-of-a-quadratic-function/00DESCRIPTION +++ b/Task/Roots-of-a-quadratic-function/00DESCRIPTION @@ -1,6 +1,11 @@ -{{Clarified-review}}Write a program to find the roots of a quadratic equation, i.e., solve the equation ax^2 + bx + c = 0. Your program must correctly handle non-real roots, but it need not check that a \neq 0. +{{Clarified-review}}Write a program to find the roots of a quadratic equation, i.e., solve the equation ax^2 + bx + c = 0. +Your program must correctly handle non-real roots, but it need not check that a \neq 0. -The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic. The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other. In their classic textbook on numeric methods ''[http://www.pdas.com/fmm.htm Computer Methods for Mathematical Computations]'', George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with a = 1, b = -10^5, and c = 1. (For double-precision floats, set b = -10^9.) Consider the following implementation in [[Ada]]: +The problem of solving a quadratic equation is a good example of how dangerous it can be to ignore the peculiarities of floating-point arithmetic. +The obvious way to implement the quadratic formula suffers catastrophic loss of accuracy when one of the roots to be found is much closer to 0 than the other. +In their classic textbook on numeric methods ''[http://www.pdas.com/fmm.htm Computer Methods for Mathematical Computations]'', George Forsythe, Michael Malcolm, and Cleve Moler suggest trying the naive algorithm with a = 1, b = -10^5, and c = 1. +(For double-precision floats, set b = -10^9.) +Consider the following implementation in [[Ada]]: with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; @@ -17,7 +22,7 @@ procedure Quadratic_Equation is begin Put_Line ("X1 =" & Float'Image (R (1)) & " X2 =" & Float'Image (R (2))); end Quadratic_Equation; -Sample output: +{{out}}
X1 = 1.00000E+06 X2 = 0.00000E+00
As we can see, the second root has lost all significant figures. The right answer is that X2 is about 10^{-6}. The naive method is numerically unstable. diff --git a/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-2.c b/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-2.c index 17ec4f1ef7..42f26ba658 100644 --- a/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-2.c +++ b/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-2.c @@ -1,2 +1,12 @@ -(-1e+12 + 0 i), (-1 + 0 i) -(1.00208e+07 + 0 i), (9.9792e-08 + 0 i) +#include +#include +#include + +void roots_quadratic_eq(double a, double b, double c, complex double *x) +{ + double delta; + + delta = b*b - 4.0*a*c; + x[0] = (-b + csqrt(delta)) / (2.0*a); + x[1] = (-b - csqrt(delta)) / (2.0*a); +} diff --git a/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-3.c b/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-3.c index 42f26ba658..3a55550957 100644 --- a/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-3.c +++ b/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-3.c @@ -1,12 +1,15 @@ -#include -#include -#include - -void roots_quadratic_eq(double a, double b, double c, complex double *x) +void roots_quadratic_eq2(double a, double b, double c, complex double *x) { - double delta; - - delta = b*b - 4.0*a*c; - x[0] = (-b + csqrt(delta)) / (2.0*a); - x[1] = (-b - csqrt(delta)) / (2.0*a); + b /= a; + c /= a; + double delta = b*b - 4*c; + if ( delta < 0 ) { + x[0] = -b/2 + I*sqrt(-delta)/2.0; + x[1] = -b/2 - I*sqrt(-delta)/2.0; + } else { + double root = sqrt(delta); + double sol = (b>0) ? (-b - root)/2.0 : (-b + root)/2.0; + x[0] = sol; + x[1] = c/sol; + } } diff --git a/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-4.c b/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-4.c index 3a55550957..904393f0cc 100644 --- a/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-4.c +++ b/Task/Roots-of-a-quadratic-function/C/roots-of-a-quadratic-function-4.c @@ -1,15 +1,15 @@ -void roots_quadratic_eq2(double a, double b, double c, complex double *x) +int main() { - b /= a; - c /= a; - double delta = b*b - 4*c; - if ( delta < 0 ) { - x[0] = -b/2 + I*sqrt(-delta)/2.0; - x[1] = -b/2 - I*sqrt(-delta)/2.0; - } else { - double root = sqrt(delta); - double sol = (b>0) ? (-b - root)/2.0 : (-b + root)/2.0; - x[0] = sol; - x[1] = c/sol; - } + complex double x[2]; + + roots_quadratic_eq(1, -1e20, 1, x); + printf("x1 = (%.20le, %.20le)\nx2 = (%.20le, %.20le)\n\n", + creal(x[0]), cimag(x[0]), + creal(x[1]), cimag(x[1])); + roots_quadratic_eq2(1, -1e20, 1, x); + printf("x1 = (%.20le, %.20le)\nx2 = (%.20le, %.20le)\n\n", + creal(x[0]), cimag(x[0]), + creal(x[1]), cimag(x[1])); + + return 0; } diff --git a/Task/Roots-of-a-quadratic-function/Elixir/roots-of-a-quadratic-function.elixir b/Task/Roots-of-a-quadratic-function/Elixir/roots-of-a-quadratic-function.elixir new file mode 100644 index 0000000000..3306c77e52 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Elixir/roots-of-a-quadratic-function.elixir @@ -0,0 +1,24 @@ +defmodule Quadratic do + def roots(a, b, c) do + IO.puts "Roots of a quadratic function (#{a}, #{b}, #{c})" + d = b * b - 4 * a * c + a2 = a * 2 + cond do + d > 0 -> + sd = :math.sqrt(d) + IO.puts " the real roots are #{(- b + sd) / a2} and #{(- b - sd) / a2}" + d == 0 -> + IO.puts " the single root is #{- b / a2}" + true -> + sd = :math.sqrt(-d) + IO.puts " the complex roots are #{- b / a2} +/- #{sd / a2}*i" + end + end +end + +Quadratic.roots(1, -2, 1) +Quadratic.roots(1, -3, 2) +Quadratic.roots(1, 0, 1) +Quadratic.roots(1, -1.0e10, 1) +Quadratic.roots(1, 2, 3) +Quadratic.roots(2, -1, -6) diff --git a/Task/Roots-of-a-quadratic-function/Fortran/roots-of-a-quadratic-function.f b/Task/Roots-of-a-quadratic-function/Fortran/roots-of-a-quadratic-function-1.f similarity index 100% rename from Task/Roots-of-a-quadratic-function/Fortran/roots-of-a-quadratic-function.f rename to Task/Roots-of-a-quadratic-function/Fortran/roots-of-a-quadratic-function-1.f diff --git a/Task/Roots-of-a-quadratic-function/Fortran/roots-of-a-quadratic-function-2.f b/Task/Roots-of-a-quadratic-function/Fortran/roots-of-a-quadratic-function-2.f new file mode 100644 index 0000000000..bd3a25fa2d --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Fortran/roots-of-a-quadratic-function-2.f @@ -0,0 +1,27 @@ +COMPUTE ROOTS OF A QUADRATIC FUNCTION - 1956 + READ 100,A,B,C + 100 FORMAT(3F8.3) + PRINT 100,A,B,C + DISC=B**2-4.*A*C + IF(DISC),1,2,3 + 1 XR=-B/(2.*A) + XI=SQRT(-DISC)/(2.*A) + XJ=-XI + PRINT 311 + PRINT 312,XR,XI,XR,XJ + 311 FORMAT(13HCOMPLEX ROOTS) + 312 FORMAT(4HX1=(,2E12.4,6H),X2=(,2E12.4,1H)) + GO TO 999 + 2 X1=-B/(2.*A) + X2=X1 + PRINT 321 + PRINT 332,X1,X2 + 321 FORMAT(16HEQUAL REAL ROOTS) + GO TO 999 + 3 X1= (-B+SQRT(DISC)) / (2.*A) + X2= (-B-SQRT(DISC)) / (2.*A) + PRINT 331 + PRINT 332,X1,X2 + 331 FORMAT(10HREAL ROOTS) + 332 FORMAT(3HX1=,E12.5,4H,X2=,E12.5) + 999 STOP diff --git a/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-1.j b/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-1.j index e670b4e0a0..4e3179ccf5 100644 --- a/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-1.j +++ b/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-1.j @@ -1,6 +1,7 @@ - coeff =. _3 |.\ 3 4 4r3 3 2 _1 3 2 1 1 _1e6 1 + coeff =. _3 |.\ 3 4 4r3 3 2 _1 3 2 1 1 _1e6 1 1 _1e9 1 > {:"1 p. coeff _0.666667 _0.666667 _1 0.333333 _0.333333j0.471405 _0.333333j_0.471405 1e6 1e_6 + 1e9 1e_9 diff --git a/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-3.j b/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-3.j index bcdb2f8ed5..c67959250a 100644 --- a/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-3.j +++ b/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-3.j @@ -1,10 +1,10 @@ - 1{::p. 1 _1e5 1 NB. display roots + 1{::p. 1 _1e5 1 NB. display roots 100000 1e_5 - 1 _1e5 1 p. 1{::p. 1 _1e5 1 NB. test roots + 1 _1e5 1 p. 1{::p. 1 _1e5 1 NB. test roots _3.38436e_7 0 - 1 _1e5 1 p. 1e5 1e_5 NB. test displayed roots + 1 _1e5 1 p. 1e5 1e_5 NB. test displayed roots 1 9.99999e_11 - 1e5 1e_5 - 1{::p. 1 _1e5 1 NB. find difference + 1e5 1e_5 - 1{::p. 1 _1e5 1 NB. find difference 1e_5 _1e_15 1 _1e5 1 p. 1e5 1e_5-1e_5 _1e_15 NB. test displayed roots with adjustment _3.38436e_7 0 diff --git a/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-4.j b/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-4.j index 4b9a60008b..fdb1537b76 100644 --- a/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-4.j +++ b/Task/Roots-of-a-quadratic-function/J/roots-of-a-quadratic-function-4.j @@ -1,2 +1,9 @@ - 1 {:: p.1 _1e9 1 -1e9 1e_9 +q_r=: verb define + 'a b c' =. y + q=. b %~ %: a * c + f=. 0.5 + 0.5 * %:(1-4*q*q) + (-b*f%a),(-c%b*f) +) + + q_r 1 _1e6 1 +1e6 1e_6 diff --git a/Task/Roots-of-a-quadratic-function/Julia/roots-of-a-quadratic-function.julia b/Task/Roots-of-a-quadratic-function/Julia/roots-of-a-quadratic-function.julia new file mode 100644 index 0000000000..be411a0539 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/Julia/roots-of-a-quadratic-function.julia @@ -0,0 +1,27 @@ +function quad_roots{S<:Real,T<:Real,U<:Real}(x::S, y::T, z::U) + (a, b, c) = promote(float(x), y, z) + 2eps(a) < abs(a) || return [-c/b] + disc = b^2 - 4a*c + 2eps(b^2) < abs(disc) || return [-sqrt(c/a)] + if disc < 0 + disc += 0.0im + end + d = sqrt(disc) + if b < 0 + d += -b + return [d/2a, 2c/d] + else + d = -b - d + return [2c/d, d/2a] + end +end + +a = {1, 1, 1.0, 10} +b = {10, 2, -10.0^9, 1} +c = {1, 1, 1, 1} + +for i in 1:length(a) + pstr = @sprintf "%fx^2 + %fx + %f" a[i] b[i] c[i] + println("The roots of ", pstr, " are: ") + println(" ", join(quad_roots(a[i], b[i], c[i]), " and "), "\n") +end diff --git a/Task/Roots-of-a-quadratic-function/Python/roots-of-a-quadratic-function.py b/Task/Roots-of-a-quadratic-function/Python/roots-of-a-quadratic-function.py index bdb3319605..dd9136aadd 100644 --- a/Task/Roots-of-a-quadratic-function/Python/roots-of-a-quadratic-function.py +++ b/Task/Roots-of-a-quadratic-function/Python/roots-of-a-quadratic-function.py @@ -1,25 +1,73 @@ ->>> def quad_discriminating_roots(a,b,c, entier = 1e-5): - discriminant = b*b - 4*a*c - a,b,c,d =complex(a), complex(b), complex(c), complex(discriminant) - root1 = (-b + d**0.5)/2./a - root2 = (-b - d**0.5)/2./a - if abs(discriminant) < entier: - return "real and equal", abs(root1), abs(root1) - if discriminant > 0: - return "real", root1.real, root2.real - return "complex", root1, root2 - ->>> for coeffs in ((3, 4, 4/3.), (3, 2, -1), (3, 2, 1), (1.0, -10.0E5, 1.0)): - print "Roots of: %gX^2 %+gX %+g are" % coeffs - print " %s: %s, %s" % quad_discriminating_roots(*coeffs) - - -Roots of: 3X^2 +4X +1.33333 are - real and equal: 0.666666666667, 0.666666666667 -Roots of: 3X^2 +2X -1 are - real: 0.333333333333, -1.0 -Roots of: 3X^2 +2X +1 are - complex: (-0.333333333333+0.471404520791j), (-0.333333333333-0.471404520791j) -Roots of: 1X^2 -1e+06X +1 are - real: 999999.999999, 1.00000761449e-06 ->>> +#!/usr/bin/env python3 + +import math +import cmath +import numpy + +def quad_discriminating_roots(a,b,c, entier = 1e-5): + """For reference, the naive algorithm which shows complete loss of + precision on the quadratic in question. (This function also returns a + characterization of the roots.)""" + discriminant = b*b - 4*a*c + a,b,c,d =complex(a), complex(b), complex(c), complex(discriminant) + root1 = (-b + cmath.sqrt(d))/2./a + root2 = (-b - cmath.sqrt(d))/2./a + if abs(discriminant) < entier: + return "real and equal", abs(root1), abs(root1) + if discriminant > 0: + return "real", root1.real, root2.real + return "complex", root1, root2 + +def middlebrook(a, b, c): + try: + q = math.sqrt(a*c)/b + f = .5+ math.sqrt(1-4*q*q)/2 + except ValueError: + q = cmath.sqrt(a*c)/b + f = .5+ cmath.sqrt(1-4*q*q)/2 + return (-b/a)*f, -c/(b*f) + +def whatevery(a, b, c): + try: + d = math.sqrt(b*b-4*a*c) + except ValueError: + d = cmath.sqrt(b*b-4*a*c) + if b > 0: + return div(2*c, (-b-d)), div((-b-d), 2*a) + else: + return div((-b+d), 2*a), div(2*c, (-b+d)) + +def div(n, d): + """Divide, with a useful interpretation of division by zero.""" + try: + return n/d + except ZeroDivisionError: + if n: + return n*float('inf') + return float('nan') + +testcases = [ + (3, 4, 4/3), # real, equal + (3, 2, -1), # real, unequal + (3, 2, 1), # complex + (1, -1e9, 1), # ill-conditioned "quadratic in question" required by task. + (1, -1e100, 1), + (1, -1e200, 1), + (1, -1e300, 1), +] + +print('Naive:') +for c in testcases: + print("{} {:.5} {:.5}".format(*quad_discriminating_roots(*c))) + +print('\nMiddlebrook:') +for c in testcases: + print(("{:.5} "*2).format(*middlebrook(*c))) + +print('\nWhat Every...') +for c in testcases: + print(("{:.5} "*2).format(*whatevery(*c))) + +print('\nNumpy:') +for c in testcases: + print(("{:.5} "*2).format(*numpy.roots(c))) diff --git a/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx index 24b626b8f8..466feb3c66 100644 --- a/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx +++ b/Task/Roots-of-a-quadratic-function/REXX/roots-of-a-quadratic-function-1.rexx @@ -1,36 +1,28 @@ -/*REXX program finds the roots (may be complex) of a quadratic function.*/ -numeric digits 120 /*use enough digits for extremes.*/ -parse arg a b c . /*get specified arguments: A B C*/ -a=a/1; b=b/1; c=c/1 /*normalize the three numbers. */ -call quadratic a b c /*solve the quadratic function. */ -numeric digits sqrt(digits())%1 /*reduce digits for human beans. */ -r1=r1/1 /*normalize to the new digits. */ -r2=r2/1 /* " " " " " */ -if r1j\=0 then r1=r1 || left('+',r1j>0)(r1j/1)"i" /*handle complex num.*/ -if r2j\=0 then r2=r2 || left('+',r2j>0)(r2j/1)"i" /* " " " */ -say ' a =' a /*show value of A. */ -say ' b =' b /* " " " B. */ -say ' c =' c /* " " " C. */ -say -say 'root1 =' r1 /*show 1st root (may be complex).*/ -say 'root2 =' r2 /* " 2nd " " " " */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────QUADRATIC subroutine────────────────*/ -quadratic: parse arg aa bb cc . /*obtain the specified arguments.*/ -?=sqrt(bb**2-4*aa*cc) /*compute sqrt (might be complex)*/ -aa2=1 / (aa+aa) /*compute reciprocal of 2*aa */ -if right(?,1)=='i' then do /*are the roots complex? */ - ?i=left(?,length(?)-1) - r1=-bb*aa2; r2=r1; r1j=?i*aa2; r2j=-?i*aa2 - end - else do - r1=(-bb+?)*aa2; r2=(-bb-?)*aa2; r1j=0; r2j=0 - end -return -/*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure; parse arg x,f; if x=0 then return 0; d=digits() -numeric digits 11; g=.sqrtG(); do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k; g=.5*(g+x/g); end - numeric digits d;return (g/1)i -.sqrtG: i=left('i',x<0); numeric form; m.=11; p=d+d%4+2; x=abs(x) - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 +/*REXX program finds the roots (which may be complex) of a quadratic function.*/ +numeric digits 200 /*use enough digits to handle extremes.*/ +parse arg a b c . /*obtain the specified arguments: A B C*/ +call quadratic a,b,c /*solve quadratic function via the sub.*/ +numeric digits 10 /*reduce (output) digits for human eyes*/ +r1=r1/1; r2=r2/1; a=a/1; b=b/1; c=c/1 /*normalize numbers to the new digits. */ +if r1j\=0 then r1=r1 || left('+',r1j>0)(r1j/1)"i" /*handle complex number.*/ +if r2j\=0 then r2=r2 || left('+',r2j>0)(r2j/1)"i" /* " " " */ + say ' a =' a /*display the normalized value of A. */ + say ' b =' b /* " " " " " B. */ + say ' c =' c /* " " " " " C. */ + say; say 'root1 =' r1 /* " " " " 1st root*/ + say 'root2 =' r2 /* " " " " 2nd root*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +quadratic: parse arg aa,bb,cc /*obtain the specified three arguments.*/ + $=sqrt(bb**2-4*aa*cc); L=length($) /*compute SQRT (which may be complex).*/ + rp=1/(aa+aa); c?=right($,1)=='i' /*compute reciprocal of 2*aa; Complex?*/ + if c? then do; n=left($,L-1); r1=-bb*rp; r2=r1; r1j=n*rp; r2j=-r1j; end + else do; r1=(-bb+$)*rp; r2=(-bb-$)*rp; r1j=0; r2j=0; end + return +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Roots-of-a-quadratic-function/Ruby/roots-of-a-quadratic-function.rb b/Task/Roots-of-a-quadratic-function/Ruby/roots-of-a-quadratic-function.rb index f07b74af21..de56de2886 100644 --- a/Task/Roots-of-a-quadratic-function/Ruby/roots-of-a-quadratic-function.rb +++ b/Task/Roots-of-a-quadratic-function/Ruby/roots-of-a-quadratic-function.rb @@ -1,7 +1,7 @@ -require 'complex' +require 'cmath' def quadratic(a, b, c) - sqrt_discriminant = Math.sqrt(b**2 - 4*a*c) + sqrt_discriminant = CMath.sqrt(b**2 - 4*a*c) [(-b + sqrt_discriminant) / (2.0*a), (-b - sqrt_discriminant) / (2.0*a)] end diff --git a/Task/Roots-of-a-quadratic-function/TI-89-BASIC/roots-of-a-quadratic-function.ti-89 b/Task/Roots-of-a-quadratic-function/TI-89-BASIC/roots-of-a-quadratic-function.ti-89 new file mode 100644 index 0000000000..1e2d1fbde2 --- /dev/null +++ b/Task/Roots-of-a-quadratic-function/TI-89-BASIC/roots-of-a-quadratic-function.ti-89 @@ -0,0 +1 @@ +solve(x^2-1E9x+1.0) diff --git a/Task/Roots-of-unity/JavaScript/roots-of-unity.js b/Task/Roots-of-unity/JavaScript/roots-of-unity.js new file mode 100644 index 0000000000..97571285a0 --- /dev/null +++ b/Task/Roots-of-unity/JavaScript/roots-of-unity.js @@ -0,0 +1,19 @@ +function Root(angle) { + with (Math) { this.r = cos(angle); this.i = sin(angle) } +} + +Root.prototype.toFixed = function(p) { + return this.r.toFixed(p) + (this.i >= 0 ? '+' : '') + this.i.toFixed(p) + 'i' +} + +function roots(n) { + var rs = [], teta = 2*Math.PI/n + for (var angle=0, i=0; i') +} diff --git a/Task/Roots-of-unity/Maple/roots-of-unity-1.maple b/Task/Roots-of-unity/Maple/roots-of-unity-1.maple new file mode 100644 index 0000000000..1954209513 --- /dev/null +++ b/Task/Roots-of-unity/Maple/roots-of-unity-1.maple @@ -0,0 +1,3 @@ +RootsOfUnity := proc( n ) + solve(z^n = 1, z); +end proc: diff --git a/Task/Roots-of-unity/Maple/roots-of-unity-2.maple b/Task/Roots-of-unity/Maple/roots-of-unity-2.maple new file mode 100644 index 0000000000..9f3acb21fb --- /dev/null +++ b/Task/Roots-of-unity/Maple/roots-of-unity-2.maple @@ -0,0 +1,3 @@ +for i from 2 to 6 do + printf( "%d: %a\n", i, [ RootsOfUnity(i) ] ); +end do; diff --git a/Task/Roots-of-unity/Maple/roots-of-unity-3.maple b/Task/Roots-of-unity/Maple/roots-of-unity-3.maple new file mode 100644 index 0000000000..590e2bc054 --- /dev/null +++ b/Task/Roots-of-unity/Maple/roots-of-unity-3.maple @@ -0,0 +1,5 @@ +2: [1, -1] +3: [1, -1/2-1/2*I*3^(1/2), -1/2+1/2*I*3^(1/2)] +4: [1, -1, I, -I] +5: [1, 1/4*5^(1/2)-1/4+1/4*I*2^(1/2)*(5+5^(1/2))^(1/2), -1/4*5^(1/2)-1/4+1/4*I*2^(1/2)*(5-5^(1/2))^(1/2), -1/4*5^(1/2)-1/4-1/4*I*2^(1/2)*(5-5^(1/2))^(1/2), 1/4*5^(1/2)-1/4-1/4*I*2^(1/2)*(5+5^(1/2))^(1/2)] +6: [1, -1, 1/2*(-2-2*I*3^(1/2))^(1/2), -1/2*(-2-2*I*3^(1/2))^(1/2), 1/2*(-2+2*I*3^(1/2))^(1/2), -1/2*(-2+2*I*3^(1/2))^(1/2)] diff --git a/Task/Roots-of-unity/Ruby/roots-of-unity.rb b/Task/Roots-of-unity/Ruby/roots-of-unity.rb index 7b89d60a0b..2a3eb2a89b 100644 --- a/Task/Roots-of-unity/Ruby/roots-of-unity.rb +++ b/Task/Roots-of-unity/Ruby/roots-of-unity.rb @@ -1,6 +1,4 @@ -require 'complex' - for n in 2..10 - printf "%2d ", n - puts (0..n-1).map { |k| Complex.polar(1, 2 * Math::PI * k / n) }.join(" ") + printf "%2d: ", n + puts (0...n).map { |k| "%8.5f %+8.5fi" % Complex.polar(1, 2 * Math::PI * k / n).rect }.join(", ") end diff --git a/Task/Rot-13/C++/rot-13-3.cpp b/Task/Rot-13/C++/rot-13-3.cpp new file mode 100644 index 0000000000..a7a0fa2865 --- /dev/null +++ b/Task/Rot-13/C++/rot-13-3.cpp @@ -0,0 +1,34 @@ +#include +#include +#include + +char rot13(char c){ + if (c >= 'a' && c <= 'z') + return (c - 'a' + 13) % 26 + 'a'; + else if (c >= 'A' && c <= 'Z') + return (c - 'A' + 13) % 26 + 'A'; + return c; +} + +std::string &rot13(std::string &s){ + for (auto &c : s) //range based for is the only used C++11 feature + c = rot13(c); + return s; +} + +void rot13(std::istream &in, std::ostream &out){ + std::string s; + while (std::getline(in, s)) + out << rot13(s) << '\n'; +} + +int main(int argc, char *argv[]){ + if (argc == 1) + rot13(std::cin, std::cout); + for (int arg = 1; arg < argc; ++arg){ + std::ifstream f(argv[arg]); + if (!f) + return EXIT_FAILURE; + rot13(f, std::cout); + } +} diff --git a/Task/Rot-13/Elixir/rot-13.elixir b/Task/Rot-13/Elixir/rot-13.elixir new file mode 100644 index 0000000000..aabd4e22b0 --- /dev/null +++ b/Task/Rot-13/Elixir/rot-13.elixir @@ -0,0 +1,12 @@ +defmodule RC do + def rot13(clist) do + f = fn(c) when (?A <= c and c <= ?M) or (?a <= c and c <= ?m) -> c + 13 + (c) when (?N <= c and c <= ?Z) or (?n <= c and c <= ?z) -> c - 13 + (c) -> c + end + Enum.map(clist, f) + end +end + +IO.inspect encode = RC.rot13('Rosetta Code') +IO.inspect RC.rot13(encode) diff --git a/Task/Rot-13/Julia/rot-13.julia b/Task/Rot-13/Julia/rot-13.julia index fd018c1b0e..f4b73421ec 100644 --- a/Task/Rot-13/Julia/rot-13.julia +++ b/Task/Rot-13/Julia/rot-13.julia @@ -4,4 +4,4 @@ function rot13(c::Char) c end -rot13(s::String) = map(rot13,CharString(s...)) +rot13(s::String) = map(rot13,s) diff --git a/Task/Rot-13/PL-SQL/rot-13.sql b/Task/Rot-13/PL-SQL/rot-13.sql new file mode 100644 index 0000000000..d55c584241 --- /dev/null +++ b/Task/Rot-13/PL-SQL/rot-13.sql @@ -0,0 +1,44 @@ +-- Works for VARCHAR2 (up to 32k chars) +CREATE OR REPLACE FUNCTION fn_rot13_native(p_text VARCHAR2) RETURN VARCHAR2 IS + c_source CONSTANT VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + c_target CONSTANT VARCHAR2(52) := 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'; +BEGIN + RETURN TRANSLATE(p_text, c_source, c_target); +END; +/ + +-- For CLOBs (translate only works with VARCHAR2, so do it in chunks) +CREATE OR REPLACE FUNCTION fn_rot13_clob(p_text CLOB) RETURN CLOB IS + c_source CONSTANT VARCHAR2(52) := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + c_target CONSTANT VARCHAR2(52) := 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'; + c_chunk_size CONSTANT PLS_INTEGER := 4000; + v_result CLOB := NULL; +BEGIN + FOR i IN 0..TRUNC(LENGTH(p_text) / c_chunk_size) LOOP + v_result := v_result || + TRANSLATE(dbms_lob.substr(p_text, c_chunk_size, i * c_chunk_size + 1), c_source, c_target); + END LOOP; + RETURN v_result; +END; +/ + +-- The full algorithm (Slower. And MUCH slower if using CLOB!) +CREATE OR REPLACE FUNCTION fn_rot13_algorithm(p_text VARCHAR2) RETURN CLOB IS + c_upper_a CONSTANT PLS_INTEGER := ASCII('A'); + c_lower_a CONSTANT PLS_INTEGER := ASCII('a'); + v_rot VARCHAR2(32000); + v_char VARCHAR2(1); +BEGIN + FOR i IN 1..LENGTH(p_text) LOOP + v_char := SUBSTR(p_text, i, 1); + IF v_char BETWEEN 'A' AND 'Z' THEN + v_rot := v_rot || CHR(MOD(ASCII(v_char) - c_upper_a + 13, 26) + c_upper_a); + ELSIF v_char BETWEEN 'a' AND 'z' THEN + v_rot := v_rot || CHR(MOD(ASCII(v_char) - c_lower_a + 13, 26) + c_lower_a); + ELSE + v_rot := v_rot || v_char; + END IF; + END LOOP; + RETURN v_rot; +END; +/ diff --git a/Task/Rot-13/REXX/rot-13.rexx b/Task/Rot-13/REXX/rot-13.rexx index 94031a425e..5c8355b8d4 100644 --- a/Task/Rot-13/REXX/rot-13.rexx +++ b/Task/Rot-13/REXX/rot-13.rexx @@ -1,25 +1,15 @@ -/*REXX program encodes several text strings with the ROT-13 algorithm.*/ -aa = 'foo' - say 'simple text = 'aa - say 'rot-13 text = 'rot13(aa) - say -bb = 'bar' - say 'simple text = 'bb - say 'rot-13 text = 'rot13(bb) - say -cc = "Noyr jnf V, 'rer V fnj Ryon." - say 'simple text = 'cc - say 'rot-13 text = 'rot13(cc) - say -dd = 'abc? ABC!' - say 'simple text = 'dd - say 'rot-13 text = 'rot13(dd) - say -ee = 'abjurer NOWHERE' - say 'simple text = 'ee - say 'rot-13 text = 'rot13(ee) -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ROT13 subroutine────────────────────*/ +/*REXX program encodes several example text strings with the ROT-13 algorithm.*/ +@simple = 'simple text =' +@rot_13 = 'rot-13 text =' + +$= 'foo' ; say @simple $; say @rot_13 rot13($); say +$= 'bar' ; say @simple $; say @rot_13 rot13($); say +$= "Noyr jnf V, 'rer V fnj Ryon." ; say @simple $; say @rot_13 rot13($); say +$= 'abc? ABC!' ; say @simple $; say @rot_13 rot13($); say +$= 'abjurer NOWHERE' ; say @simple $; say @rot_13 rot13($); say + +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ rot13: return translate(arg(1), , - 'abcdefghijklmABCDEFGHIJKLMnopqrstuvwxyzNOPQRSTUVWXYZ', , - 'nopqrstuvwxyzNOPQRSTUVWXYZabcdefghijklmABCDEFGHIJKLM') + 'abcdefghijklmABCDEFGHIJKLMnopqrstuvwxyzNOPQRSTUVWXYZ', , + 'nopqrstuvwxyzNOPQRSTUVWXYZabcdefghijklmABCDEFGHIJKLM') diff --git a/Task/Rot-13/RapidQ/rot-13.rapidq b/Task/Rot-13/RapidQ/rot-13.rapidq new file mode 100644 index 0000000000..6e6707b645 --- /dev/null +++ b/Task/Rot-13/RapidQ/rot-13.rapidq @@ -0,0 +1,21 @@ +function ROT13 (InputTxt as string) as string + dim i as integer, ascVal as byte + Result = "" + + for i = 1 to len(InputTxt) + ascVal = asc(InputTxt[i]) + + select case ascVal + case 65 to 77, 97 to 109 + Result = Result + chr$(ascVal + 13) + case 78 to 90, 110 to 122 + Result = Result + chr$(ascVal - 13) + case else + Result = Result + chr$(ascVal) + end select + next +end function + +Input "Text to encode: "; a$ +Print ROT13(a$) +Input "Press a key to end..."; a$ diff --git a/Task/Rot-13/Rust/rot-13.rust b/Task/Rot-13/Rust/rot-13.rust index 44d4dfea16..90a0d081e3 100644 --- a/Task/Rot-13/Rust/rot-13.rust +++ b/Task/Rot-13/Rust/rot-13.rust @@ -1,17 +1,16 @@ -fn rot13 (string: ~str) -> ~str { - fn rot13u8 (c: u8) -> u8 { - match c { - 97..109 => c+13, - 65..77 => c+13, - 110..122 => c-13, - 78..90 => c-13, - _ => c - } - } - std::str::from_utf8_owned(string.as_bytes().map(|c| rot13u8(*c))).unwrap() +fn rot13 (string: String) -> String { + let mut bytes: Vec = string.into(); + for byte in &mut bytes { + match *byte { + b'a'...b'm' | b'A'...b'M' => *byte += 13, + b'n'...b'z' | b'N'...b'Z' => *byte -= 13, + _ => (), // do nothing + } + } + String::from_utf8(bytes).unwrap() } fn main () { - let a = rot13(~"abc"); - assert_eq!(a, ~"nop"); + let a = rot13("abc".to_owned()); + assert_eq!(a, "nop"); } diff --git a/Task/Rot-13/UNIX-Shell/rot-13-1.sh b/Task/Rot-13/UNIX-Shell/rot-13-1.sh new file mode 100644 index 0000000000..f7b8199d92 --- /dev/null +++ b/Task/Rot-13/UNIX-Shell/rot-13-1.sh @@ -0,0 +1,6 @@ +#!/bin/sh +rot13() { + tr a-zA-Z n-za-mN-ZA-M +} + +cat "$@" | rot13 diff --git a/Task/Rot-13/UNIX-Shell/rot-13-2.sh b/Task/Rot-13/UNIX-Shell/rot-13-2.sh new file mode 100644 index 0000000000..4088947596 --- /dev/null +++ b/Task/Rot-13/UNIX-Shell/rot-13-2.sh @@ -0,0 +1,6 @@ +#!/bin/sh +rot13() { + tr '[a-m][n-z][A-M][N-Z]' '[n-z][a-m][N-Z][A-M]' +} + +cat ${1+"$@"} | rot13 diff --git a/Task/Rot-13/UNIX-Shell/rot-13.sh b/Task/Rot-13/UNIX-Shell/rot-13.sh deleted file mode 100644 index 8cead31535..0000000000 --- a/Task/Rot-13/UNIX-Shell/rot-13.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh -function rot13 () { - tr '[a-m][n-z][A-M][N-Z]' '[n-z][a-m][N-Z][A-M]' - } - -cat ${1+"$@"} | rot13 diff --git a/Task/Run-length-encoding/Elixir/run-length-encoding.elixir b/Task/Run-length-encoding/Elixir/run-length-encoding.elixir new file mode 100644 index 0000000000..83a5049e8f --- /dev/null +++ b/Task/Run-length-encoding/Elixir/run-length-encoding.elixir @@ -0,0 +1,27 @@ +defmodule Run_length do + def encode(str) when is_bitstring(str) do + to_char_list(str) |> encode |> to_string + end + def encode(list) when is_list(list) do + Enum.chunk_by(list, &(&1)) + |> Enum.flat_map(fn chars -> to_char_list(length(chars)) ++ [hd(chars)] end) + end + + def decode(str) when is_bitstring(str) do + Regex.scan(~r/(\d+)(.)/, str) + |> Enum.map_join(fn [_,n,c] -> String.duplicate(c, String.to_integer(n)) end) + end + def decode(list) when is_list(list) do + to_string(list) |> decode |> to_char_list + end +end + +text = [ string: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", + char_list: 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' ] + +Enum.each(text, fn {type, txt} -> + IO.puts type + txt |> IO.inspect + |> Run_length.encode |> IO.inspect + |> Run_length.decode |> IO.inspect +end) diff --git a/Task/Run-length-encoding/J/run-length-encoding-4.j b/Task/Run-length-encoding/J/run-length-encoding-4.j new file mode 100644 index 0000000000..c3f61fda64 --- /dev/null +++ b/Task/Run-length-encoding/J/run-length-encoding-4.j @@ -0,0 +1,2 @@ + torle=: (#, {.);.1~ 1,2 ~:/\ ] + frle=: #/@|: diff --git a/Task/Run-length-encoding/J/run-length-encoding-5.j b/Task/Run-length-encoding/J/run-length-encoding-5.j new file mode 100644 index 0000000000..736d5630b8 --- /dev/null +++ b/Task/Run-length-encoding/J/run-length-encoding-5.j @@ -0,0 +1,10 @@ + torle a.i.'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' +12 87 + 1 66 +12 87 + 3 66 +24 87 + 1 66 +14 87 + u: frle torle a.i.'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' +WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW diff --git a/Task/Run-length-encoding/Perl/run-length-encoding-1.pl b/Task/Run-length-encoding/Perl/run-length-encoding-1.pl index d2023794ae..27a6ad5119 100644 --- a/Task/Run-length-encoding/Perl/run-length-encoding-1.pl +++ b/Task/Run-length-encoding/Perl/run-length-encoding-1.pl @@ -1,13 +1,7 @@ -# functional approach (return the encoded or decoded string) sub encode { - (my $str = shift) =~ s {(.)(\1*)} {length($&).$1}gse; - return $str; } -sub decode { - (my $str = shift) =~ s {(\d+)(.)} {$2 x $1}gse; - return $str;} + shift =~ s/(.)\1*/length($&).$1/grse; +} -# procedural approach (modify the argument in place) -sub encode { - $_[0] =~ s {(.)(\1*)} {length($&).$1}gse; } sub decode { - $_[0] =~ s {(\d+)(.)} {$2 x $1}gse; } + shift =~ s/(\d+)(.)/$2 x $1/grse; +} diff --git a/Task/Run-length-encoding/Perl/run-length-encoding-2.pl b/Task/Run-length-encoding/Perl/run-length-encoding-2.pl index 09a65df427..e28bd4e523 100644 --- a/Task/Run-length-encoding/Perl/run-length-encoding-2.pl +++ b/Task/Run-length-encoding/Perl/run-length-encoding-2.pl @@ -1,14 +1,7 @@ -sub encode - {my $str = shift; - $str =~ s {(.)(\1{0,254})} {pack("C",(length($2) + 1)) . $1 }gse; - return $str;} +sub encode { + shift =~ s/(.)\1{0,254}/pack("C", length($&)).$1/grse; +} -sub decode -{ - my @str = split //, shift; - my $r = ""; - foreach my $i (0 .. scalar(@str)/2-1) { - $r .= $str[2*$i + 1] x unpack("C", $str[2*$i]); - } - return $r; +sub decode { + shift =~ s/(.)(.)/$2 x unpack("C", $1)/grse; } diff --git a/Task/Run-length-encoding/Perl/run-length-encoding-3.pl b/Task/Run-length-encoding/Perl/run-length-encoding-3.pl new file mode 100644 index 0000000000..950545a238 --- /dev/null +++ b/Task/Run-length-encoding/Perl/run-length-encoding-3.pl @@ -0,0 +1,32 @@ +sub encode { + my $str = shift; + my $ret = ""; + my $nonrep = ""; + while ($str =~ m/(.)\1{0,127}|\z/gs) { + my $len = length($&); + if (length($nonrep) && (length($nonrep) == 127 || $len != 1)) { + $ret .= pack("C", 128 + length($nonrep)) . $nonrep; + $nonrep = ""; + } + if ($len == 1) { $nonrep .= $1 } + elsif ($len > 1) { $ret .= pack("C", $len) . $1 } + } + return $ret; +} + +sub decode { + my $str = shift; + my $ret = ""; + for (my $i = 0; $i < length($str);) { + my $len = unpack("C", substr($str, $i, 1)); + if ($len <= 128) { + $ret .= substr($str, $i + 1, 1) x $len; + $i += 2; + } + else { + $ret .= substr($str, $i + 1, $len - 128); + $i += 1 + $len - 128; + } + } + return $ret; +} diff --git a/Task/Run-length-encoding/Perl/run-length-encoding-4.pl b/Task/Run-length-encoding/Perl/run-length-encoding-4.pl new file mode 100644 index 0000000000..fcb2b491e6 --- /dev/null +++ b/Task/Run-length-encoding/Perl/run-length-encoding-4.pl @@ -0,0 +1,4 @@ +use Data::Dump qw(dd); +dd my $str = "XXXXXABCDEFGHIoooooooooooooooooooooooooAAAAAA"; +dd my $enc = encode($str); +dd decode($enc); diff --git a/Task/Run-length-encoding/REXX/run-length-encoding-1.rexx b/Task/Run-length-encoding/REXX/run-length-encoding-1.rexx index 3435e38c35..d923800f7e 100644 --- a/Task/Run-length-encoding/REXX/run-length-encoding-1.rexx +++ b/Task/Run-length-encoding/REXX/run-length-encoding-1.rexx @@ -1,22 +1,19 @@ -/*REXX program encodes a string by using a run-length scheme. */ -parse arg x . /*normally, input would be a file*/ -/*═══ arg x . ═══*/ /*◄── use if X must be uppercase.*/ +/*REXX program encodes a string by using a run─length encoding scheme. */ +parse arg x . /*normally, input would be in a file. */ def= 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' -if x='' then x=def /*No input? Then use the default.*/ -Lx=length(x) /*get the length of the X string.*/ -y= /*Y is the output string (so far)*/ - do j=1 by 0 to Lx /*J is incremented (below). */ - c=substr(x,j,1) /*pick a character, check for err*/ - if \datatype(c,'M') then do; say "error!: data isn't alphabetic:" c; exit 13; end - r=0 /*R is NOT the number of chars. */ - do k=j+1 to Lx while substr(x,k,1)==c - r=r+1 /*R is a replication count. */ - end /*k*/ - j=j+1+r /*modify (add to) the do index. */ - if r==0 then r= /*don't use R if R is zero.*/ - Y = Y || r || c /*add it to the encoded string.*/ - end /*j*/ +if x='' then x=def /*Input not specified? Then use default*/ +Lx=length(x) /*get the length of the X string. */ +y= /*Y: is the output string (so far). */ + do j=1 by 0 to Lx /*J: is incremented within the loop. */ + c=substr(x,j,1) /*pick a character, check for an error.*/ + if \datatype(c,'M') then do; say "error!: data isn't alphabetic:" c; exit 13; end + r=0 /*R: is NOT the number of characters. */ + do k=j+1 to Lx while substr(x,k,1)==c; r=r+1 + end /*k*/ /*R: is a replication count for a char*/ + j=j+1+r /*increment (add to) the DO loop index.*/ + if r==0 then r= /*don't use R if it is equal to zero.*/ + Y = Y || r || c /*add character to the encoded string. */ + end /*j*/ -say ' input=' x -say 'encoded=' y - /*stick a fork in it, we're done.*/ +say ' input=' x +say 'encoded=' y /*stick a fork in it, we're all done. */ diff --git a/Task/Run-length-encoding/REXX/run-length-encoding-2.rexx b/Task/Run-length-encoding/REXX/run-length-encoding-2.rexx index 1ff19df869..27d4a1f089 100644 --- a/Task/Run-length-encoding/REXX/run-length-encoding-2.rexx +++ b/Task/Run-length-encoding/REXX/run-length-encoding-2.rexx @@ -1,23 +1,21 @@ -/*REXX program decodes a string by using a run-length scheme. */ -parse arg x . /*normally, input would be a file*/ -if x=='' then x='11WB11W2B23WB13W' /*No input? Then use the default*/ -Lx=length(x) /*get the length of the X string.*/ -y= /*Y is the output string (so far)*/ - do j=1 by 0 to Lx /*warning! J is modified below.*/ +/*REXX program decodes a string by using a run─length decoding scheme. */ +parse arg x . /*normally, input would be in a file. */ +if x=='' then x=11WB11W2B23WB13W /*X not specified? Then use default.*/ +Lx=length(x) /*get the length of the input string. */ +y= /*Y: is the output string (so far). */ + do j=1 by 0 to Lx /*warning! J is modified within loop.*/ c=substr(x,j,1) - if \datatype(c,'W') then do /*a loner char, simply add to OUT*/ + if \datatype(c,'W') then do /*a loner char, simply add to output. */ y=y || c; j=j+1; iterate /*j*/ end - d=1 - do k=j+1 to Lx while datatype(substr(x,k,1),'w') /*look for #end*/ - d=d+1 /*D is the number of digs so far.*/ - end /*k*/ + d=1 /* [↓] W: a Whole number.*/ + do k=j+1 to Lx while datatype(substr(x,k,1),'w'); d=d+1 /*end of #?*/ + end /*k*/ /*D: is the number of characters so far*/ - n=substr(x,j,d)+1 /*D is length of encoded number.*/ - y=y || copies(substr(x,k,1),n) /*N is now the number of chars. */ - j=j+1+d /*increment the DO loop index. */ + n=substr(x,j,d)+1 /*D: is length of the encoded number. */ + y=y || copies(substr(x,k,1), n) /*N: is now the number of characters. */ + j=j+1+d /*increment the DO loop index by D+1. */ end /*j*/ say ' input=' x -say 'decoded=' y - /*stick a fork in it, we're done.*/ +say 'decoded=' y /*stick a fork in it, we're all done. */ diff --git a/Task/Run-length-encoding/REXX/run-length-encoding-3.rexx b/Task/Run-length-encoding/REXX/run-length-encoding-3.rexx new file mode 100644 index 0000000000..c5247f8084 --- /dev/null +++ b/Task/Run-length-encoding/REXX/run-length-encoding-3.rexx @@ -0,0 +1,39 @@ +s='WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' +Say ' s='s +enc=encode(s) +Say 'enc='enc +dec=decode(enc) +Say 'dec='dec +if dec==s Then Say 'OK' +Exit + +encode: Procedure +Parse Arg s +c=left(s,1) +cnt=1 +ol='' +Do i=2 To length(s) + If substr(s,i,1)=c Then + cnt=cnt+1 + Else Do + Call o cnt||c + c=substr(s,i,1) + cnt=1 + End + End +Call o cnt||c +Return ol + +decode: Procedure +Parse Arg s +abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +ol='' +Do While s<>'' + p=verify(s,abc,'M') + Parse Var s cnt =(p) c +1 s + Call o copies(c,cnt) + End +Return ol + +o: ol=ol||arg(1) + Return diff --git a/Task/Run-length-encoding/REXX/run-length-encoding-4.rexx b/Task/Run-length-encoding/REXX/run-length-encoding-4.rexx new file mode 100644 index 0000000000..224581cf18 --- /dev/null +++ b/Task/Run-length-encoding/REXX/run-length-encoding-4.rexx @@ -0,0 +1,48 @@ +s='WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' +Say ' s='s +enc=encode(s) +Say 'enc='enc +dec=decode(enc) +Say 'dec='dec +if dec==s Then Say 'OK' +Exit + +encode: Procedure +Parse Arg s +c=left(s,1) +cnt=1 +ol='' +Do i=2 To length(s) + If substr(s,i,1)=c Then + cnt=cnt+1 + Else Do + If cnt=1 Then + Call o c + Else + Call o cnt||c + c=substr(s,i,1) + cnt=1 + End + End +Call o cnt||c +Return ol + +decode: Procedure +Parse Arg s +abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +ol='' +Do While s<>'' + p=verify(s,abc,'M') + If pos(left(s,1),abc)>0 Then Do + Parse Var s c +1 s + Call o c + End + Else Do + Parse Var s cnt =(p) c +1 s + Call o copies(c,cnt) + End + End +Return ol + +o: ol=ol||arg(1) + Return diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-1.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-1.rb index c7d7ed4b8b..bea2223f08 100644 --- a/Task/Run-length-encoding/Ruby/run-length-encoding-1.rb +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-1.rb @@ -1,9 +1,14 @@ -def encode(string) - string.scan(/(.)(\1*)/).collect do |char, repeat| - [1 + repeat.length, char] - end.join +# run_encode("aaabbbbc") #=> [["a", 3], ["b", 4], ["c", 1]] +def run_encode(string) + string + .chars + .chunk{|i| i} + .map {|kind, array| [kind, array.length]} end -def decode(string) - string.scan(/(\d+)(\D)/).collect {|length, char| char * length.to_i}.join +# run_decode([["a", 3], ["b", 4], ["c", 1]]) #=> "aaabbbbc" +def run_decode(char_counts) + char_counts + .map{|char, count| char * count} + .join end diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-2.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-2.rb index 818809907b..c7d7ed4b8b 100644 --- a/Task/Run-length-encoding/Ruby/run-length-encoding-2.rb +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-2.rb @@ -1,11 +1,9 @@ def encode(string) - string.scan(/(.)(\1*)/).inject("") do |encoding, (char, repeat)| - encoding << (1 + repeat.length).to_s << char - end + string.scan(/(.)(\1*)/).collect do |char, repeat| + [1 + repeat.length, char] + end.join end def decode(string) - string.scan(/(\d+)(\D)/).inject("") do |decoding, (length, char)| - decoding << char * length.to_i - end + string.scan(/(\d+)(\D)/).collect {|length, char| char * length.to_i}.join end diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb index 82a7825ac7..818809907b 100644 --- a/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-3.rb @@ -1,7 +1,11 @@ -def encode(str) - str.gsub(/(.)\1*/) {$&.length.to_s + $1} +def encode(string) + string.scan(/(.)(\1*)/).inject("") do |encoding, (char, repeat)| + encoding << (1 + repeat.length).to_s << char + end end -def decode(str) - str.gsub(/(\d+)(\D)/) {$2 * $1.to_i} +def decode(string) + string.scan(/(\d+)(\D)/).inject("") do |decoding, (length, char)| + decoding << char * length.to_i + end end diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-4.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-4.rb index 564770ee53..82a7825ac7 100644 --- a/Task/Run-length-encoding/Ruby/run-length-encoding-4.rb +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-4.rb @@ -1,4 +1,7 @@ -orig = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" -p enc = encode(orig) -p dec = decode(enc) -puts "success!" if dec == orig +def encode(str) + str.gsub(/(.)\1*/) {$&.length.to_s + $1} +end + +def decode(str) + str.gsub(/(\d+)(\D)/) {$2 * $1.to_i} +end diff --git a/Task/Run-length-encoding/Ruby/run-length-encoding-5.rb b/Task/Run-length-encoding/Ruby/run-length-encoding-5.rb new file mode 100644 index 0000000000..564770ee53 --- /dev/null +++ b/Task/Run-length-encoding/Ruby/run-length-encoding-5.rb @@ -0,0 +1,4 @@ +orig = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" +p enc = encode(orig) +p dec = decode(enc) +puts "success!" if dec == orig diff --git a/Task/Runge-Kutta-method/ALGOL-68/runge-kutta-method.alg b/Task/Runge-Kutta-method/ALGOL-68/runge-kutta-method.alg new file mode 100644 index 0000000000..03866195a5 --- /dev/null +++ b/Task/Runge-Kutta-method/ALGOL-68/runge-kutta-method.alg @@ -0,0 +1,26 @@ +BEGIN + PROC rk4 = (PROC (REAL, REAL) REAL f, REAL y, x, dx) REAL : + BEGIN CO Fourth-order Runge-Kutta method CO + REAL dy1 = dx * f(x, y); + REAL dy2 = dx * f(x + dx / 2.0, y + dy1 / 2.0); + REAL dy3 = dx * f(x + dx / 2.0, y + dy2 / 2.0); + REAL dy4 = dx * f(x + dx, y + dy3); + y + (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0 + END; + REAL x0 = 0, x1 = 10, y0 = 1.0; CO Boundary conditions. CO + REAL dx = 0.1; CO Step size. CO + INT num points = ENTIER ((x1 - x0) / dx + 0.5); CO Add 0.5 for rounding errors. CO + [0:num points]REAL y; y[0] := y0; CO Grid and starting point.CO + PROC dy by dx = (REAL x, y) REAL : x * sqrt(y); CO Differential equation. CO + FOR i TO num points + DO + y[i] := rk4 (dy by dx, y[i-1], x0 + dx * (i - 1), dx) + OD; + print ((" x true y calc y relative error", newline)); + FOR i FROM 0 BY 10 TO num points + DO + REAL x = x0 + dx * i; + REAL true y = (x * x + 4.0) ^ 2 / 16.0; + printf (($3(-zzd.7dxxx), -d.4de-ddl$, x, true y, y[i], y[i] / true y - 1.0)) + OD +END diff --git a/Task/Runge-Kutta-method/Common-Lisp/runge-kutta-method.lisp b/Task/Runge-Kutta-method/Common-Lisp/runge-kutta-method.lisp new file mode 100644 index 0000000000..a606c605bf --- /dev/null +++ b/Task/Runge-Kutta-method/Common-Lisp/runge-kutta-method.lisp @@ -0,0 +1,32 @@ +(defun runge-kutta (f x y x-end n) + (let ((h (float (/ (- x-end x) n) 1d0)) + k1 k2 k3 k4) + (setf x (float x 1d0) + y (float y 1d0)) + (cons (cons x y) + (loop for i below n do + (setf k1 (* h (funcall f x y)) + k2 (* h (funcall f (+ x (* 0.5d0 h)) (+ y (* 0.5d0 k1)))) + k3 (* h (funcall f (+ x (* 0.5d0 h)) (+ y (* 0.5d0 k2)))) + k4 (* h (funcall f (+ x h) (+ y k3))) + x (+ x h) + y (+ y (/ (+ k1 k2 k2 k3 k3 k4) 6))) + collect (cons x y))))) + +(let ((sol (runge-kutta (lambda (x y) (* x (sqrt y))) 0 1 10 100))) + (loop for n from 0 + for (x . y) in sol + when (zerop (mod n 10)) + collect (list x y (- y (/ (expt (+ 4 (* x x)) 2) 16))))) + +((0.0d0 1.0d0 0.0d0) + (0.9999999999999999d0 1.562499854278108d0 -1.4572189210859676d-7) + (2.0000000000000004d0 3.9999990805207988d0 -9.194792029987298d-7) + (3.0000000000000013d0 10.562497090437557d0 -2.9095624576314094d-6) + (4.000000000000002d0 24.999993765090643d0 -6.234909392333066d-6) + (4.999999999999998d0 52.56248918030259d0 -1.081969734428867d-5) + (5.999999999999995d0 99.9999834054036d0 -1.659459609015812d-5) + (6.999999999999991d0 175.56247648227117d0 -2.3517728038768837d-5) + (7.999999999999988d0 288.9999684347983d0 -3.156520000402452d-5) + (8.999999999999984d0 451.56245927683887d0 -4.072315812209126d-5) + (9.99999999999998d0 675.9999490167083d0 -5.0983286655537086d-5)) diff --git a/Task/Runge-Kutta-method/Liberty-BASIC/runge-kutta-method.liberty b/Task/Runge-Kutta-method/Liberty-BASIC/runge-kutta-method.liberty new file mode 100644 index 0000000000..bfa4232d59 --- /dev/null +++ b/Task/Runge-Kutta-method/Liberty-BASIC/runge-kutta-method.liberty @@ -0,0 +1,31 @@ +'[RC] Runge-Kutta method +'initial conditions +x0 = 0 +y0 = 1 +'step +h = 0.1 +'number of points +N=101 + +y=y0 +FOR i = 0 TO N-1 + x = x0+ i*h + IF x = INT(x) THEN + actual = exactY(x) + PRINT "y("; x ;") = "; y; TAB(20); "Error = "; actual - y + END IF + + k1 = h*dydx(x,y) + k2 = h*dydx(x+h/2,y+k1/2) + k3 = h*dydx(x+h/2,y+k2/2) + k4 = h*dydx(x+h,y+k3) + y = y + 1/6 * (k1 + 2*k2 + 2*k3 + k4) +NEXT i + +function dydx(x,y) + dydx=x*sqr(y) +end function + +function exactY(x) + exactY=(x^2 + 4)^2 / 16 +end function diff --git a/Task/Runge-Kutta-method/Objeck/runge-kutta-method.objeck b/Task/Runge-Kutta-method/Objeck/runge-kutta-method.objeck new file mode 100644 index 0000000000..7f43d55e6e --- /dev/null +++ b/Task/Runge-Kutta-method/Objeck/runge-kutta-method.objeck @@ -0,0 +1,36 @@ +class RungeKuttaMethod { + function : Main(args : String[]) ~ Nil { + x0 := 0.0; x1 := 10.0; dx := .1; + + n := 1 + (x1 - x0)/dx; + y := Float->New[n->As(Int)]; + + y[0] := 1; + for(i := 1; i < n; i++;) { + y[i] := Rk4(Rate(Float, Float) ~ Float, dx, x0 + dx * (i - 1), y[i-1]); + }; + + for(i := 0; i < n; i += 10;) { + x := x0 + dx * i; + y2 := (x * x / 4 + 1)->Power(2.0); + + x_value := x->As(Int); + y_value := y[i]; + rel_value := y_value/y2 - 1.0; + "y({$x_value})={$y_value}; error: {$rel_value}"->PrintLine(); + }; + } + + function : native : Rk4(f : (Float, Float) ~ Float, dx : Float, x : Float, y : Float) ~ Float { + 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; + } + + function : native : Rate(x : Float, y : Float) ~ Float { + return x * y->SquareRoot(); + } +} diff --git a/Task/Runge-Kutta-method/PowerShell/runge-kutta-method.psh b/Task/Runge-Kutta-method/PowerShell/runge-kutta-method.psh new file mode 100644 index 0000000000..78d4a58b97 --- /dev/null +++ b/Task/Runge-Kutta-method/PowerShell/runge-kutta-method.psh @@ -0,0 +1,36 @@ +function Runge-Kutta (${function:F}, ${function:y}, $y0, $t0, $dt, $tEnd) { + function RK ($tn,$yn) { + $y1 = $dt*(F -t $tn -y $yn) + $y2 = $dt*(F -t ($tn + (1/2)*$dt) -y ($yn + (1/2)*$y1)) + $y3 = $dt*(F -t ($tn + (1/2)*$dt) -y ($yn + (1/2)*$y2)) + $y4 = $dt*(F -t ($tn + $dt) -y ($yn + $y3)) + $yn + (1/6)*($y1 + 2*$y2 + 2*$y3 + $y4) + } + function time ($t0, $dt, $tEnd) { + $end = [MATH]::Floor(($tEnd - $t0)/$dt) + foreach ($_ in 0..$end) { $_*$dt + $t0 } + } + $time, $yn, $t = (time $t0 $dt $tEnd), $y0, 0 + foreach ($tn in $time) { + if($t -eq $tn) { + [pscustomobject]@{ + t = "$tn" + y = "$yn" + error = "$([MATH]::abs($yn - (y $tn)))" + } + $t += 1 + } + $yn = RK $tn $yn + } +} +function F ($t,$y) { + $t * [MATH]::Sqrt($y) +} +function y ($t) { + (1/16) * [MATH]::Pow($t*$t + 4,2) +} +$y0 = 1 +$t0 = 0 +$dt = 0.1 +$tEnd = 10 +Runge-Kutta F y $y0 $t0 $dt $tEnd diff --git a/Task/Runge-Kutta-method/Python/runge-kutta-method.py b/Task/Runge-Kutta-method/Python/runge-kutta-method-1.py similarity index 100% rename from Task/Runge-Kutta-method/Python/runge-kutta-method.py rename to Task/Runge-Kutta-method/Python/runge-kutta-method-1.py diff --git a/Task/Runge-Kutta-method/Python/runge-kutta-method-2.py b/Task/Runge-Kutta-method/Python/runge-kutta-method-2.py new file mode 100644 index 0000000000..9727676e3d --- /dev/null +++ b/Task/Runge-Kutta-method/Python/runge-kutta-method-2.py @@ -0,0 +1,35 @@ +from math import sqrt + +def rk4(f, x0, y0, x1, n): + vx = [0]*(n + 1) + vy = [0]*(n + 1) + h = (x1 - x0)/n + vx[0] = x = x0 + vy[0] = y = y0 + for i in range(1, n + 1): + k1 = h*f(x, y) + k2 = h*f(x + 0.5*h, y + 0.5*k1) + k3 = h*f(x + 0.5*h, y + 0.5*k2) + k4 = h*f(x + h, y + k3) + vx[i] = x = x0 + i*h + vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4)/6 + return vx, vy + +def f(x, y): + return x*sqrt(y) + +vx, vy = rk4(f, 0, 1, 10, 100) +for x, y in list(zip(vx, vy))[::10]: + print(x, y, y - (4 + x*x)**2/16) + +0 1 0.0 +1.0 1.562499854278108 -1.4572189210859676e-07 +2.0 3.9999990805207997 -9.194792003341945e-07 +3.0 10.562497090437551 -2.9095624487496252e-06 +4.0 24.999993765090636 -6.234909363911356e-06 +5.0 52.562489180302585 -1.0819697415342944e-05 +6.0 99.99998340540358 -1.659459641700778e-05 +7.0 175.56247648227125 -2.3517728749311573e-05 +8.0 288.9999684347986 -3.156520142510999e-05 +9.0 451.56245927683966 -4.07231603389846e-05 +10.0 675.9999490167097 -5.098329029351589e-05 diff --git a/Task/Runge-Kutta-method/R/runge-kutta-method.r b/Task/Runge-Kutta-method/R/runge-kutta-method.r new file mode 100644 index 0000000000..e8c6ed50fa --- /dev/null +++ b/Task/Runge-Kutta-method/R/runge-kutta-method.r @@ -0,0 +1,32 @@ +rk4 <- function(f, x0, y0, x1, n) { + vx <- double(n + 1) + vy <- double(n + 1) + vx[1] <- x <- x0 + vy[1] <- y <- y0 + h <- (x1 - x0)/n + for(i in 1:n) { + k1 <- h*f(x, y) + k2 <- h*f(x + 0.5*h, y + 0.5*k1) + k3 <- h*f(x + 0.5*h, y + 0.5*k2) + k4 <- h*f(x + h, y + k3) + vx[i + 1] <- x <- x0 + i*h + vy[i + 1] <- y <- y + (k1 + k2 + k2 + k3 + k3 + k4)/6 + } + cbind(vx, vy) +} + +sol <- rk4(function(x, y) x*sqrt(y), 0, 1, 10, 100) +cbind(sol, sol[, 2] - (4 + sol[, 1]^2)^2/16)[seq(1, 101, 10), ] + + vx vy + [1,] 0 1.000000 0.000000e+00 + [2,] 1 1.562500 -1.457219e-07 + [3,] 2 3.999999 -9.194792e-07 + [4,] 3 10.562497 -2.909562e-06 + [5,] 4 24.999994 -6.234909e-06 + [6,] 5 52.562489 -1.081970e-05 + [7,] 6 99.999983 -1.659460e-05 + [8,] 7 175.562476 -2.351773e-05 + [9,] 8 288.999968 -3.156520e-05 +[10,] 9 451.562459 -4.072316e-05 +[11,] 10 675.999949 -5.098329e-05 diff --git a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx index aa63e8aa3a..3a4dc91690 100644 --- a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx +++ b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx @@ -1,35 +1,34 @@ -/*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 +/*REXX program uses the Runge─Kutta method to solve the differential equation:*/ +/* _____ ══ the exact solution: y(t)=(t²+4)²/16 ══*/ +/* y'(t)═t² √ y(t) ══════════════════════════════════════════*/ +numeric digits 40; d=digits()%2 /*use 40 digits, but only 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,'─') +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) + 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' /*adjust for 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 ) +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +rate: return arg(1) * sqrt(arg(2)) +/*────────────────────────────────────────────────────────────────────────────*/ +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 +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Runtime-evaluation-In-an-environment/Clojure/runtime-evaluation-in-an-environment-1.clj b/Task/Runtime-evaluation-In-an-environment/Clojure/runtime-evaluation-in-an-environment-1.clj new file mode 100644 index 0000000000..09bf98e0ad --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Clojure/runtime-evaluation-in-an-environment-1.clj @@ -0,0 +1,5 @@ +(def ^:dynamic x nil) + +(defn eval-with-x [program a b] + (- (binding [x b] (eval program)) + (binding [x a] (eval program)))) diff --git a/Task/Runtime-evaluation-In-an-environment/Clojure/runtime-evaluation-in-an-environment-2.clj b/Task/Runtime-evaluation-In-an-environment/Clojure/runtime-evaluation-in-an-environment-2.clj new file mode 100644 index 0000000000..151f66c803 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Clojure/runtime-evaluation-in-an-environment-2.clj @@ -0,0 +1,2 @@ +(eval-with-x '(* x x) 4 9) +=> 65 diff --git a/Task/Runtime-evaluation-In-an-environment/Tcl/runtime-evaluation-in-an-environment-3.tcl b/Task/Runtime-evaluation-In-an-environment/Tcl/runtime-evaluation-in-an-environment-3.tcl new file mode 100644 index 0000000000..117773c7b0 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Tcl/runtime-evaluation-in-an-environment-3.tcl @@ -0,0 +1,7 @@ +package require Tcl 8.5 +proc eval_with {body a b} { + set lambda [list x $body] + expr {[apply $lambda $b] - [apply $lambda $a]} +} + +eval_with {expr {2**$x}} 3 5 ;# ==> 24 diff --git a/Task/Runtime-evaluation/Mathematica/runtime-evaluation.math b/Task/Runtime-evaluation/Mathematica/runtime-evaluation.math new file mode 100644 index 0000000000..954d232b48 --- /dev/null +++ b/Task/Runtime-evaluation/Mathematica/runtime-evaluation.math @@ -0,0 +1,9 @@ +Print[ToExpression["1 + 1"]]; +Print[ToExpression["Print[\"Hello, world!\"]; 10!"]]; +x = 5; +Print[ToExpression["x!"]]; +Print[ToExpression["Module[{x = 8}, x!]"]]; +Print[MemoryConstrained[ToExpression["Range[5]"], 10000, {}]]; +Print[MemoryConstrained[ToExpression["Range[10^5]"], 10000, {}]]; +Print[TimeConstrained[ToExpression["Pause[1]; True"], 2, False]]; +Print[TimeConstrained[ToExpression["Pause[60]; True"], 2, False]]; diff --git a/Task/S-Expressions/J/s-expressions-1.j b/Task/S-Expressions/J/s-expressions-1.j index a502424dac..5e72daac88 100644 --- a/Task/S-Expressions/J/s-expressions-1.j +++ b/Task/S-Expressions/J/s-expressions-1.j @@ -3,7 +3,7 @@ chrMap=: '()';'"';' ',LF,TAB,CR NB. state columns correspond to the above character classes NB. first digit chooses next state. -NB. second digit is action 0: do nothing, 1: start word, 2: end word +NB. second digit is action 0: do nothing, 1: start token, 2: end token states=: 10 10#: ".;._2]0 :0 11 21 00 31 NB. state 0: initial state 12 22 02 32 NB. state 1: after () or after closing " diff --git a/Task/S-Expressions/JavaScript/s-expressions.js b/Task/S-Expressions/JavaScript/s-expressions.js new file mode 100644 index 0000000000..98abef0592 --- /dev/null +++ b/Task/S-Expressions/JavaScript/s-expressions.js @@ -0,0 +1,38 @@ +String.prototype.parseSexpr = function() { + var t = this.match(/\s*("[^"]*"|\(|\)|"|[^\s()"]+)/g) + for (var o, c=0, i=t.length-1; i>=0; i--) { + var n, ti = t[i].trim() + if (ti == '"') return + else if (ti == '(') t[i]='[', c+=1 + else if (ti == ')') t[i]=']', c-=1 + else if ((n=+ti) == ti) t[i]=n + else t[i] = '\'' + ti.replace('\'', '\\\'') + '\'' + if (i>0 && ti!=']' && t[i-1].trim()!='(' ) t.splice(i,0, ',') + if (!c) if (!o) o=true; else return + } + return c ? undefined : eval(t.join('')) +} + +Array.prototype.toString = function() { + var s=''; for (var i=0, e=this.length; i' + var s2 = s + Array(6).join(' ') + for (var i=0, e=this.length; i' : ai.toPretty(s2) + } + return r + s + ')
' +} + +var str = '((data "quoted data" 123 4.5)\n (data (!@# (4.5) "(more" "data)")))' +document.write('text:
', str.replace(/\n/g,'
').replace(/ /g,' '), '

') +var sexpr = str.parseSexpr() +if (sexpr === undefined) + document.write('Invalid s-expr!', '
') +else + document.write('s-expr:
', sexpr, '

', sexpr.constructor != Array ? '' : 'pretty print:
' + sexpr.toPretty()) diff --git a/Task/S-Expressions/REXX/s-expressions.rexx b/Task/S-Expressions/REXX/s-expressions.rexx index 2d79e2f785..01bc5275fb 100644 --- a/Task/S-Expressions/REXX/s-expressions.rexx +++ b/Task/S-Expressions/REXX/s-expressions.rexx @@ -1,75 +1,65 @@ -/*REXX program parses an S-expression and displays the results. */ +/*REXX program parses an S-expression and displays the results. */ input= '((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))' -say 'input:' /*indicate what is being shown. */ -say input /*echo the input to the screen. */ -say copies('═',length(input)) /*display a header fence. */ -$.= /*stem array to hold the tokens. */ -groupO.1 = '{' ; groupC.1 = '}' /*grouping symbols (Open & Close)*/ -groupO.2 = '[' ; groupC.2 = ']' /* " " " " " */ -groupO.3 = '(' ; groupC.3 = ')' /* " " " " " */ -groupSym = 3 /*the number of grouping symbols.*/ -# = 0 /*the number of tokens. */ -tabs = 10 /*used for indenting the levels. */ -q.1 = "'" /*literal string delimiter, 1st. */ -q.2 = '"' /* " " " 2nd. */ -numLits = 2 /*number of kinds of literals. */ -seps = ',;' /*characters used for separation.*/ -atoms = ' 'seps /*characters used to sep atoms. */ -level = 0 /*current level being processed. */ -quoted = 0 /*quotation level (when nested). */ -groupu = /*used to go ↑ an expresion level*/ -groupd = /* " " " ↓ " " " */ - do n=1 for groupSym /*handle for # grouping symbols. */ - atoms = atoms || groupO.n || groupC.n - groupu = groupu || groupO.n - groupd = groupd || groupC.n - end /*n*/ +say 'input:'; say input /*display the input data string to term*/ +say copies('═',length(input)) /*also, display a header fence. */ +groupO.= /*default value for grouping symbols. */ +groupO.1 = '{' ; groupC.1 = '}' /*grouping symbols (Open & Close). */ +groupO.2 = '[' ; groupC.2 = ']' /* " " " " " */ +groupO.3 = '(' ; groupC.3 = ')' /* " " " " " */ +# = 0 /*the number of tokens found (so far). */ +tabs = 10 /*used for the indenting of the levels.*/ +q.1 = "'" /*literal string delimiter, first. */ +q.2 = '"' /* " " " second. */ +numLits = 2 /*the number of kinds of literals. */ +seps = ',;' /*characters used for separation. */ +atoms = ' 'seps /*characters used to separate atoms. */ +level = 0 /*the current level being processed. */ +quoted = 0 /*quotation level (when nested). */ +groupu = /*used to go ↑ an expression level. */ +groupd = /* " " " ↓ " " " */ +$.= /*the stem array to hold the tokens. */ + do n=1 while groupO.n\=='' /*handle the number of grouping symbols*/ + atoms =atoms || groupO.n || groupC.n + groupu=groupu || groupO.n + groupd=groupd || groupC.n + end /*n*/ literals= - do k=1 for numLits - literals = literals || q.k - end /*k*/ + do k=1 for numLits + literals=literals || q.k + end /*k*/ != -/*═════════════════════════════════════start of the text parsing.═══════*/ - do j=1 to length(input); _ = substr(input,j,1) - if quoted then do - !=! || _ - if _==literalStart then quoted=0 - iterate - end + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ text parsing ▒▒▒▒▒▒▒▒*/ + do j=1 to length(input); _=substr(input,j,1) /*▒*/ + /*▒*/ + if quoted then do; !=! || _ /*▒*/ + if _==literalStart then quoted=0 /*▒*/ + iterate /*▒*/ + end /*▒*/ + /*▒*/ + if pos(_,literals)\==0 then do; literalStart=_ /*▒*/ + !=! || _ /*▒*/ + quoted=1 /*▒*/ + iterate /*▒*/ + end /*▒*/ + /*▒*/ + if pos(_,atoms)==0 then do; !=! || _ ; iterate; end /*▒*/ + else do; call add!; !=_; end /*▒*/ + /*▒*/ + if pos(_,literals)==0 then do /*▒*/ + if pos(_,groupu)\==0 then level=level+1 /*▒*/ + call add! /*▒*/ + if pos(_,groupd)\==0 then level=level-1 /*▒*/ + if level<0 then say 'oops, mismatched' _ /*▒*/ + end /*▒*/ + end /*j*/ /*▒*/ + /*▒*/ +call add! /*handle any residual tokens.*/ /*▒*/ +if level\==0 then say 'oops, mismatched grouping symbol' /*▒*/ +if quoted then say 'oops, no end of quoted literal' literalStart /*▒*/ + /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ - if pos(_,literals)\==0 then do - literalStart = _ - ! = ! || _ - quoted = 1 - iterate - end - - if pos(_,atoms)==0 then do; !=! || _ ; iterate; end - else do; call add!; ! = _ ; end - - if pos(_,literals)==0 then do - if pos(_,groupu)\==0 then level=level+1 - call add! - if pos(_,groupd)\==0 then level=level-1 - if level<0 then say 'oops, mismatched' _ - iterate - end - end /*j*/ - -call add! /*handle any residual tokens. */ -if level\==0 then say 'oops, mismatched grouping symbol' -if quoted then say 'oops, no end of quoted literal' literalStart -/*═════════════════════════════════════end of text parsing.═════════════*/ - - do j=1 for # - say $.j - end /*j*/ -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────ADD! subroutine─────────────────────*/ -add!: if !\='' then do - #=#+1 - $.#=left('',max(0,tabs*(level-1)))! - end - != - return + do j=1 for #; say $.j; end /*display the tokens to the terminal. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +add!: if !\='' then do; #=#+1; $.#=left('', max(0, tabs*(level-1)))!; end; != +return diff --git a/Task/SEDOLs/00DESCRIPTION b/Task/SEDOLs/00DESCRIPTION index 3e03433d90..5c45ca3a88 100644 --- a/Task/SEDOLs/00DESCRIPTION +++ b/Task/SEDOLs/00DESCRIPTION @@ -25,4 +25,4 @@ B000300
For extra credit, check each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. -C.f. [[Luhn test]] +C.f. [[Luhn test]], [[Calculate International Securities Identification Number|ISIN]] diff --git a/Task/SEDOLs/VBScript/sedols.vb b/Task/SEDOLs/VBScript/sedols.vb new file mode 100644 index 0000000000..959f6b0d97 --- /dev/null +++ b/Task/SEDOLs/VBScript/sedols.vb @@ -0,0 +1,44 @@ +arr = Array("710889",_ + "B0YBKJ",_ + "406566",_ + "B0YBLH",_ + "228276",_ + "B0YBKL",_ + "557910",_ + "B0YBKR",_ + "585284",_ + "B0YBKT",_ + "12345",_ + "A12345",_ + "B00030") + +For j = 0 To UBound(arr) + WScript.StdOut.Write arr(j) & getSEDOLCheckDigit(arr(j)) + WScript.StdOut.WriteLine +Next + +Function getSEDOLCheckDigit(str) + If Len(str) <> 6 Then + getSEDOLCheckDigit = " is invalid. Only 6 character strings are allowed." + Exit Function + End If + Set mult = CreateObject("Scripting.Dictionary") + With mult + .Add "1","1" : .Add "2", "3" : .Add "3", "1" + .Add "4","7" : .Add "5", "3" : .Add "6", "9" + End With + total = 0 + For i = 1 To 6 + s = Mid(str,i,1) + If s = "A" Or s = "E" Or s = "I" Or s = "O" Or s = "U" Then + getSEDOLCheckDigit = " is invalid. Vowels are not allowed." + Exit Function + End If + If Asc(s) >= 48 And Asc(s) <=57 Then + total = total + CInt(s) * CInt(mult.Item(CStr(i))) + Else + total = total + (Asc(s) - 55) * CInt(mult.Item(CStr(i))) + End If + Next + getSEDOLCheckDigit = (10 - total Mod 10) Mod 10 +End Function diff --git a/Task/SHA-1/00DESCRIPTION b/Task/SHA-1/00DESCRIPTION index 371d162e9d..3a9342910f 100644 --- a/Task/SHA-1/00DESCRIPTION +++ b/Task/SHA-1/00DESCRIPTION @@ -1,7 +1,14 @@ -'''SHA-1''' or '''SHA1''' is a one-way hash function; it computes a 160-bit message digest. SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections. BitTorrent uses SHA-1 to verify downloads. Git and Mercurial use SHA-1 digests to identify commits. +'''SHA-1''' or '''SHA1''' is a one-way hash function; +it computes a 160-bit message digest. +SHA-1 often appears in security protocols; for example, +many HTTPS websites use RSA with SHA-1 to secure their connections. +BitTorrent uses SHA-1 to verify downloads. +Git and Mercurial use SHA-1 digests to identify commits. A US government standard, [[SHA-1/FIPS-180-1|FIPS 180-1]], defines SHA-1. Find the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code. -{{alertbox|lightgray|'''Warning:''' SHA-1 has [https://en.wikinews.org/wiki/Chinese_researchers_crack_major_U.S._government_algorithm_used_in_digital_signatures known weaknesses]. Theoretical attacks may find a collision after [http://lwn.net/Articles/337745/ 252 operations], or perhaps fewer. This is much faster than a brute force attack of 280 operations. US government [http://csrc.nist.gov/groups/ST/hash/statement.html deprecated SHA-1]. For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}} +{{alertbox|lightgray|'''Warning:''' SHA-1 has [https://en.wikinews.org/wiki/Chinese_researchers_crack_major_U.S._government_algorithm_used_in_digital_signatures known weaknesses]. Theoretical attacks may find a collision after [http://lwn.net/Articles/337745/ 252 operations], or perhaps fewer. +This is much faster than a brute force attack of 280 operations. USgovernment [http://csrc.nist.gov/groups/ST/hash/statement.html deprecated SHA-1]. +For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}} diff --git a/Task/SHA-1/Julia/sha-1.julia b/Task/SHA-1/Julia/sha-1.julia new file mode 100644 index 0000000000..355c720d93 --- /dev/null +++ b/Task/SHA-1/Julia/sha-1.julia @@ -0,0 +1,39 @@ +using Nettle + +function sha1sum(s::String) + bytes2hex(sha1_hash(s)) +end + +println("Testing SHA-1 function against FIPS 180-1") + +s = sha1sum("abc") +t = lowercase("A9993E364706816ABA3E25717850C26C9CD0D89D") +print(" \"abc\" should yield ", t) +if s == t + println(", and it does.") +else + println(", but it yields ", s) +end + +s = sha1sum("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") +t = lowercase("84983E441C3BD26EBAAE4AA1F95129E5E54670F1") +print(" \"abcdbc...\" should yield ", t) +if s == t + println(", and it does.") +else + println(", but it yields ", s) +end + +s = sha1sum("a"^10^6) +t = lowercase("34AA973CD4C4DAA4F61EEB2BDBAD27316534016F") +print(" a million \"a\"s should yield ", t) +if s == t + println(", and it does.") +else + println(", but it yields ", s) +end + +println("\nAlso") +s = "Rosetta Code" +h = sha1sum(s) +println(" ", s, " => ", h) diff --git a/Task/SHA-1/Liberty-BASIC/sha-1.liberty b/Task/SHA-1/Liberty-BASIC/sha-1.liberty new file mode 100644 index 0000000000..92781e416b --- /dev/null +++ b/Task/SHA-1/Liberty-BASIC/sha-1.liberty @@ -0,0 +1,70 @@ +'-------------------------------------------------------------------------------- +' FAST SHA1 CALCULATION BASED ON MS ADVAPI32.DLL BY CRYPTOMAN ' +' BASED ON SHA256 EXAMPLE BY RICHARD T. RUSSEL AUTHOR OF LBB ' +' http://lbb.conforums.com/ ' +' VERIFY CORRECTNESS BY http://www.fileformat.info/tool/hash.htm ' +'-------------------------------------------------------------------------------- + +print sha1$("Rosetta Code") +end + + X$="1234567890ABCDEF" + + dat$ = pack$(X$) + + print "SPEED TEST" + for i=1 to 20 + t1=time$("ms") + print sha1$(dat$) + t2=time$("ms") + print "calculated in ";t2-t1;" ms" + next + end + +function sha1$(message$) + + HP.HASHVAL = 2 + CRYPT.NEWKEYSET = 48 + PROV.RSA.AES = 24 + buffer$ = space$(128) + + PROVRSAFULL = 1 + ALGCLASSHASH = 32768 + ALGTYPEANY = 0 + ALGSIDMD2 = 1 + ALGSIDMD4 = 2 + ALGSIDMD5 = 3 + ALGSIDSHA1 = 4 + + ALGOSHA1 = ALGCLASSHASH OR ALGTYPEANY OR ALGSIDSHA1 + + struct temp, v as long + open "ADVAPI32.DLL" for dll as #advapi32 + calldll #advapi32, "CryptAcquireContextA", temp as struct, _ + 0 as long, 0 as long, PROV.RSA.AES as long, _ + 0 as long, re as long + hprov = temp.v.struct + calldll #advapi32, "CryptCreateHash", hprov as long, _ + ALGOSHA1 as long, 0 as long, 0 as long, _ + temp as struct, re as long + hhash = temp.v.struct + l = len(message$) + calldll #advapi32, "CryptHashData", hhash as long, message$ as ptr, _ + l as long, 0 as long, re as long + temp.v.struct = len(buffer$) + calldll #advapi32, "CryptGetHashParam", hhash as long, _ + HP.HASHVAL as long, buffer$ as ptr, _ + temp as struct, 0 as long, re as long + calldll #advapi32, "CryptDestroyHash", hhash as long, re as long + calldll #advapi32, "CryptReleaseContext", hprov as long, re as long + close #advapi32 + for i = 1 TO temp.v.struct + sha1$ = sha1$ + right$("0" + dechex$(asc(mid$(buffer$,i))), 2) + next +end function + +function pack$(x$) + for i = 1 TO len(x$) step 2 + pack$ = pack$ + chr$(hexdec(mid$(x$,i,2))) + next +end function diff --git a/Task/SHA-1/Perl-6/sha-1.pl6 b/Task/SHA-1/Perl-6/sha-1.pl6 index 647b54d317..af6c6a910f 100644 --- a/Task/SHA-1/Perl-6/sha-1.pl6 +++ b/Task/SHA-1/Perl-6/sha-1.pl6 @@ -12,19 +12,18 @@ my \K = 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6; sub sha1-pad(Blob $msg) { my \bits = 8 * $msg.elems; - my @padded = $msg.list, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64); - @padded.map({ :256[$^a,$^b,$^c,$^d] }), (bits +> 32)mod2³², (bits)mod2³²; + my @padded = flat $msg.list, 0x80, 0x00 xx (-($msg.elems + 1 + 8) % 64); + flat @padded.map({ :256[$^a,$^b,$^c,$^d] }), (bits +> 32)mod2³², (bits)mod2³²; } -sub sha1-block(@H is rw, @M) +sub sha1-block(@H is rw, @M is copy) { - my @W = @M; - @W.push: S(1, [+^] @W[$_ «-« <3 8 14 16>] ) for 16 .. 79; + @M.push: S(1, [+^] @M[$_ «-« <3 8 14 16>] ) for 16 .. 79; my ($A,$B,$C,$D,$E) = @H; for 0..79 -> \t { ($A, $B, $C, $D, $E) = - S(5,$A) ⊕ f[t div 20]($B,$C,$D) ⊕ $E ⊕ @W[t] ⊕ K[t div 20], + S(5,$A) ⊕ f[t div 20]($B,$C,$D) ⊕ $E ⊕ @M[t] ⊕ K[t div 20], $A, S(30,$B), $C, $D; } @H »⊕=« ($A,$B,$C,$D,$E); @@ -35,7 +34,7 @@ sub sha1(Blob $msg) returns Blob my @M = sha1-pad($msg); my @H = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0; sha1-block(@H,@M[$_..$_+15]) for 0, 16...^ +@M; - Blob.new: map { reverse .polymod(256 xx 3) }, @H; + Blob.new: flat map { reverse .polymod(256 xx 3) }, @H; } say sha1(.encode('ascii')), " $_" diff --git a/Task/SHA-1/Scala/sha-1.scala b/Task/SHA-1/Scala/sha-1.scala new file mode 100644 index 0000000000..429a8bb082 --- /dev/null +++ b/Task/SHA-1/Scala/sha-1.scala @@ -0,0 +1,89 @@ +import java.nio._ + +case class Hash(message: List[Byte]) { + val defaultHashes = List(0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0) + + val hash = { + val padded = generatePadding(message) + val chunks: List[List[Byte]] = messageToChunks(padded) + toHashForm(hashesFromChunks(chunks)) + } + + def generatePadding(message: List[Byte]): List[Byte] = { + val finalPadding = BigInt(message.length * 8).toByteArray match { + case x => List.fill(8 - x.length)(0.toByte) ++ x + } + val padding = (message.length + 1) % 64 match { + case l if l < 56 => + message ::: 0x80.toByte :: List.fill(56 - l)(0.toByte) + case l => + message ::: 0x80.toByte :: List.fill((64 - l) + 56 + 1)(0.toByte) + } + padding ::: finalPadding + } + + def toBigEndian(bytes: List[Byte]) = + ByteBuffer.wrap(bytes.toArray).getInt + + def messageToChunks(message: List[Byte]) = + message.grouped(64).toList + + def chunkToWords(chunk: List[Byte]) = + chunk.grouped(4).map(toBigEndian).toList + + def extendWords(words: List[Int]): List[Int] = words.length match { + case i if i < 80 => extendWords(words :+ Integer.rotateLeft( + (words(i - 3) ^ words(i - 8) ^ words(i - 14) ^ words(i - 16)), 1)) + case _ => words + } + + def generateFK(i: Int, b: Int, c: Int, d: Int) = i match { + case i if i < 20 => (b & c | ~b & d, 0x5A827999) + case i if i < 40 => (b ^ c ^ d, 0x6ED9EBA1) + case i if i < 60 => (b & c | b & d | c & d, 0x8F1BBCDC) + case i if i < 80 => (b ^ c ^ d, 0xCA62C1D6) + } + + def generateHash(words: List[Int], prevHash: List[Int]): List[Int] = { + def generateHash(i: Int, currentHashes: List[Int]): List[Int] = i match { + case i if i < 80 => currentHashes match { + case a :: b :: c :: d :: e :: Nil => { + val (f, k) = generateFK(i, b, c, d) + val x = Integer.rotateLeft(a, 5) + f + e + k + words(i) + val t = Integer.rotateLeft(b, 30) + generateHash(i + 1, x :: a :: t :: c :: d :: Nil) + } + } + case _ => currentHashes + } + addHashes(prevHash, generateHash(0, prevHash)) + } + + def addHashes(xs: List[Int], ys: List[Int]) = (xs, ys).zipped.map(_ + _) + + def hashesFromChunks(chunks: List[List[Byte]], + remainingHash: List[Int] = defaultHashes): List[Int] = + chunks match { + case Nil => remainingHash + case x :: xs => { + val words = extendWords(chunkToWords(x)) + val newHash = generateHash(words, remainingHash) + hashesFromChunks(xs, newHash) + } + } + + def toHashForm(hashes: List[Int]) = + hashes.map(b => ByteBuffer.allocate(4) + .order(ByteOrder.BIG_ENDIAN).putInt(b).array.toList) + .map(bytesToHex).mkString + + def bytesToHex(bytes: List[Byte]) = + (for (byte <- bytes) yield (Character.forDigit((byte >> 4) & 0xF, 16) :: + Character.forDigit((byte & 0xF), 16) :: Nil).mkString).mkString +} + +object Hash extends App { + def hash(message: String) = new Hash(message.getBytes.toList).hash + + println(hash("Rosetta Code")) +} diff --git a/Task/SHA-1/Scheme/sha-1-1.ss b/Task/SHA-1/Scheme/sha-1-1.ss new file mode 100644 index 0000000000..9b21ce4141 --- /dev/null +++ b/Task/SHA-1/Scheme/sha-1-1.ss @@ -0,0 +1,169 @@ +(define-library (lib sha1) + (export + sha1:digest) + + (import (r5rs base) + (owl math) (owl list) (owl string) (owl list-extra)) +(begin + +; band - binary AND operation +; bor - binary OR operation +; bxor - binary XOR operation +; >>, << - binary shift operations +; runes->string - convert byte list to string /(runes->string '(65 66 67 65)) => "ABCA"/ + + +(define (sha1-padding-size n) + (let ((x (mod (- 56 (rem n 64)) 64))) + (if (= x 0) 64 x))) + +(define (sha1-pad-message message) + (let*((message-len (string-length message)) + (message-len-in-bits (* message-len 8)) + (buffer-len (+ message-len 8 (sha1-padding-size message-len))) + (message (string-append message (runes->string '(#b10000000)))) + (zeroes-len (- buffer-len message-len 1 4)) ; for ending length encoded value + (message (string-append message (make-string zeroes-len 0))) + (message (string-append message (runes->string (list + (band (>> message-len-in-bits 24) #xFF) + (band (>> message-len-in-bits 16) #xFF) + (band (>> message-len-in-bits 8) #xFF) + (band (>> message-len-in-bits 0) #xFF)))))) +; (print "message-len: " message-len) +; (print "message-len-in-bits: " message-len-in-bits) +; (print "buffer-len: " buffer-len) +; (print "zeroes-len: " zeroes-len) +; (print "message: " message) +; (print "length(message): " (string-length message)) + message)) + +(define XOR (lambda args (fold bxor 0 args))) ; bxor more than 2 arguments +(define OR (lambda args (fold bor 0 args))) ; bor more than 2 arguments +(define NOT (lambda (arg) (bxor arg #xFFFFFFFF))) ; binary not operation + +; to 32-bit number +(define (->32 i) + (band i #xFFFFFFFF)) + +; binary cycle rotate left +(define (rol bits x) + (->32 + (bor + (<< x bits) + (>> x (- 32 bits))))) + +(define (word->list x) + (list + (band (>> x 24) #xFF) + (band (>> x 16) #xFF) + (band (>> x 8) #xFF) + (band (>> x 0) #xFF))) + +(define (message->words message) + (let cycle ((W + (let loop ((t (iota 0 1 16))) + (if (null? t) + null + (let*((p (* (car t) 4))) + (cons (OR + (<< (string-ref message (+ p 0)) 24) + (<< (string-ref message (+ p 1)) 16) + (<< (string-ref message (+ p 2)) 8) + (<< (string-ref message (+ p 3)) 0)) + (loop (cdr t))))))) + (t 16)) + (if (eq? t 80) + W + (cycle (append W (list + (XOR + (rol 1 (list-ref W (- t 3))) + (rol 1 (list-ref W (- t 8))) + (rol 1 (list-ref W (- t 14))) + (rol 1 (list-ref W (- t 16)))))) + (+ t 1))))) + +(define (sha1:digest message) + (let*((h0 #x67452301) + (h1 #xEFCDAB89) + (h2 #x98BADCFE) + (h3 #x10325476) + (h4 #xC3D2E1F0) + (K '(#x5A827999 #x6ED9EBA1 #x8F1BBCDC #xCA62C1D6)) + (padded-message (sha1-pad-message message)) + (n (/ (string-length padded-message) 64))) + + (let main ((i 0) + (A h0) (B h1) (C h2) (D h3) (E h4)) + (if (= i n) + (fold append null + (list (word->list A) (word->list B) (word->list C) (word->list D) (word->list E))) + (let*((message (substring padded-message (* i 64) (+ (* i 64) 64))) + (W (message->words message))) + (let*((a b c d e ; round 1 + (let loop ((a A) (b B) (c C) (d D) (e E) (t 0)) + (if (< t 20) + (loop (->32 + (+ (rol 5 a) + (OR (band b c) (band (NOT b) d)) + e + (list-ref W t) + (list-ref K 0))) + a + (rol 30 b) + c + d + (+ t 1)) + (values a b c d e)))) + (a b c d e ; round 2 + (let loop ((a a) (b b) (c c) (d d) (e e) (t 20)) + (if (< t 40) + (loop (->32 + (+ (rol 5 a) + (XOR b c d) + e + (list-ref W t) + (list-ref K 1))) + a + (rol 30 b) + c + d + (+ t 1)) + (values a b c d e)))) + (a b c d e ; round 3 + (let loop ((a a) (b b) (c c) (d d) (e e) (t 40)) + (if (< t 60) + (loop (->32 + (+ (rol 5 a) + (OR (band b c) (band b d) (band c d)) + e + (list-ref W t) + (list-ref K 2))) + a + (rol 30 b) + c + d + (+ t 1)) + (values a b c d e)))) + (a b c d e ; round 4 + (let loop ((a a) (b b) (c c) (d d) (e e) (t 60)) + (if (< t 80) + (loop (->32 + (+ (rol 5 a) + (XOR b c d) + e + (list-ref W t) + (list-ref K 3))) + a + (rol 30 b) + c + d + (+ t 1)) + (values a b c d e))))) + + (main (+ i 1) + (->32 (+ A a)) + (->32 (+ B b)) + (->32 (+ C c)) + (->32 (+ D d)) + (->32 (+ E e))))))))) +)) diff --git a/Task/SHA-1/Scheme/sha-1-2.ss b/Task/SHA-1/Scheme/sha-1-2.ss new file mode 100644 index 0000000000..bae5015050 --- /dev/null +++ b/Task/SHA-1/Scheme/sha-1-2.ss @@ -0,0 +1,16 @@ +(import (lib sha1)) +(define (->string value) + (runes->string + (let ((L "0123456789abcdef")) + (let loop ((v value)) + (if (null? v) null + (cons + (string-ref L (>> (car v) 4)) + (cons + (string-ref L (band (car v) #xF)) + (loop (cdr v))))))))) + +(print (->string (sha1:digest "Rosetta Code"))) +> 48c98f7e5a6e736d790ab740dfc3f51a61abe2b5 +(print (->string (sha1:digest ""))) +> da39a3ee5e6b4b0d3255bfef95601890afd80709 diff --git a/Task/SHA-256/Haskell/sha-256.hs b/Task/SHA-256/Haskell/sha-256.hs new file mode 100644 index 0000000000..d9ee0dfe97 --- /dev/null +++ b/Task/SHA-256/Haskell/sha-256.hs @@ -0,0 +1,12 @@ +import Data.Char (ord) +import Crypto.Hash.SHA256 (hash) +import Data.ByteString (unpack, pack) +import Text.Printf (printf) + +main = putStrLn $ -- output to terminal + concatMap (printf "%02x") $ -- to hex string + unpack $ -- to array of Word8 + hash $ -- SHA-256 hash to ByteString + pack $ -- to ByteString + map (fromIntegral.ord) -- to array of Word8 + "Rosetta code" diff --git a/Task/SHA-256/Julia/sha-256.julia b/Task/SHA-256/Julia/sha-256.julia new file mode 100644 index 0000000000..b0ca1f726d --- /dev/null +++ b/Task/SHA-256/Julia/sha-256.julia @@ -0,0 +1,13 @@ +clear = "Rosetta code" +standard = "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf" + +using SHA + +crypt = sha256(clear) + +println("Testing Julia's SHA-256:") +if crypt == standard + println(" OK, \"", clear, "\" => ", crypt) +else + println("The hash does not match the standard value.") +end diff --git a/Task/SHA-256/Perl-6/sha-256.pl6 b/Task/SHA-256/Perl-6/sha-256.pl6 index 9ccbff63c4..997da999f3 100644 --- a/Task/SHA-256/Perl-6/sha-256.pl6 +++ b/Task/SHA-256/Perl-6/sha-256.pl6 @@ -1,8 +1,8 @@ say sha256 "Rosetta code"; -constant primes = grep &is-prime, 2 .. *; sub init(&f) { - map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int }, primes + map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int }, + state @ = grep *.is-prime, 2 .. *; } sub infix: { ($^a + $^b) % 2**32 } @@ -14,7 +14,7 @@ multi sha256(Str $str where all($str.ords) < 128) { } multi sha256(Blob $data) { constant K = init(* **(1/3))[^64]; - my @b = $data.list, 0x80; + my @b = flat $data.list, 0x80; push @b, 0 until (8 * @b - 448) %% 512; push @b, reverse (8 * $data).polymod(256 xx 7); my @word = :256[@b.shift xx 4] xx @b/4; @@ -36,9 +36,9 @@ multi sha256(Blob $data) { my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25; my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j]; my $t2 = $σ0 m+ $maj; - @h = $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6]; + @h = flat $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6]; } - @H = @H Z[m+] @h; + @H [Z[m+]]= @h; } return Blob.new: map { reverse .polymod(256 xx 3) }, @H; } diff --git a/Task/SHA-256/Perl/sha-256.pl b/Task/SHA-256/Perl/sha-256-1.pl similarity index 100% rename from Task/SHA-256/Perl/sha-256.pl rename to Task/SHA-256/Perl/sha-256-1.pl diff --git a/Task/SHA-256/Perl/sha-256-2.pl b/Task/SHA-256/Perl/sha-256-2.pl new file mode 100644 index 0000000000..09efd3c1c5 --- /dev/null +++ b/Task/SHA-256/Perl/sha-256-2.pl @@ -0,0 +1,139 @@ +package Digest::SHA256::PP; + +use strict; +use warnings; + +use constant WORD => 2**32; +use constant MASK => WORD - 1; + +my @h; +my @k; + +for my $p ( 2 .. 311 ) { + # Horrible primality test, but sufficient for this task. + next if ("1" x $p) =~ /^(11+?)\1+$/; + # The choice to generate h and k instead of hard coding + # them is inspired by the Perl 6 implementation. + my $c = $p ** ( 1/3 ); + push @k, int( ($c - int $c) * WORD ); + next if @h == 8; + my $s = $p ** ( 1/2 ); + push @h, int( ($s - int $s) * WORD ); +} + +sub new { + my %self = ( state => [@h], str => "", len => 0 ); + bless \%self, shift; +} + +my $rightrotate = sub { + my $lo = $_[0] >> $_[1]; + my $hi = $_[0] << (32 - $_[1]); + ($hi | $lo); +}; + +# This is adapted from the wikipedia entry on SHA2. +my $compress = sub { + my ($state, $bytes) = @_; + my @w = unpack 'N*', $bytes; + @w == 16 or die 'internal error'; + my ($a, $b, $c, $d, $e, $f, $g, $h) = @$state; + until( @w == 64 ) { + my $s0 = $w[-15] >> 3; + my $s1 = $w[-2] >> 10; + $s0 ^= $rightrotate->($w[-15], $_) for 7, 18; + $s1 ^= $rightrotate->($w[-2], $_) for 17, 19; + push @w, ($w[-16] + $s0 + $w[-7] + $s1) & MASK; + } + my $i = 0; + for my $w (@w) { + my $ch = ($e & $f) ^ ((~$e) & $g); + my $maj = ($a & $b) ^ ($a & $c) ^ ($b & $c); + my ($S0, $S1) = (0, 0); + $S1 ^= $rightrotate->( $e, $_ ) for 6, 11, 25; + $S0 ^= $rightrotate->( $a, $_ ) for 2, 13, 22; + my $temp1 = $h + $S1 + $ch + $k[$i++] + $w; + my $temp2 = $S0 + $maj; + ($h, $g, $f, $e, $d, $c, $b, $a) = + ($g, $f, $e, ($d+$temp1)&MASK, $c, $b, $a, ($temp1+$temp2)&MASK); + } + my $j = 0; + $state->[$j++] += $_ for $a, $b, $c, $d, $e, $f, $g, $h; +}; + +use constant can_Q => eval { length pack 'Q>', 0 }; + +sub add { + my ($self, $bytes) = @_; + $self->{len} += 8 * length $bytes; + if( !can_Q and $self->{len} >= WORD ) { + my $hi = int( $self->{len} / WORD ); + $self->{big} += $hi; + $self->{len} -= $hi * WORD; + } + my $len = length $self->{str}; + if( ($len + length $bytes) < 64 ) { + $self->{str} .= $bytes; + return $self; + } + my $off = 64 - $len; + $compress->( $self->{state}, $self->{str} . substr( $bytes, 0, $off ) ); + $len = length $_[0]; + while( $off+64 <= $len ) { + $compress->( $self->{state}, substr( $bytes, $off, 64 ) ); + $off += 64; + } + $self->{str} = substr( $bytes, $off ); + $self; +} + +sub addfile { + my ($self, $fh) = @_; + my $s = ""; + while( read( $fh, $s, 2**13 ) ) { + $self->add( $s ); + } + $self; +} + + +sub digest { + my $self = shift; + my $final = $self->{str}; + $final .= chr 0x80; + while( ( 8+length $final ) % 64 ) { + $final .= chr 0; + } + if( can_Q ) { + $final .= pack 'Q>', $self->{len}; + } else { + $self->{big} ||= 0; + $final .= pack 'NN', $self->{big}, $self->{len}; + } + $compress->( $self->{state}, substr $final, 0, 64, "" ) while length $final; + if( wantarray ) { + map pack('N', $_), @{ $self->{state} }; + } else { + pack 'N*', @{ $self->{state} }; + } +} + +sub hexdigest { + if( wantarray ) { + map unpack( 'H*', $_), &digest; + } else { + unpack 'H*', &digest; + } +} + +unless( caller ) { + my @testwith = (@ARGV ? @ARGV : 'Rosetta code'); + for my $str (@testwith) { + my $digester = __PACKAGE__->new; + $digester->add($str); + print "'$str':\n"; + print join(" ", $digester->hexdigest), "\n"; + } +} + +1; diff --git a/Task/SHA-256/Rust/sha-256.rust b/Task/SHA-256/Rust/sha-256.rust index 455c61f2e7..b19da64b3a 100644 --- a/Task/SHA-256/Rust/sha-256.rust +++ b/Task/SHA-256/Rust/sha-256.rust @@ -1,9 +1,10 @@ -extern crate rustc; +extern crate crypto; -use rustc::util::sha2::{Sha256, Digest}; +use crypto::sha2::Sha256; +use crypto::digest::Digest; fn main() { let mut digest = Sha256::new(); digest.input_str("Rosetta code"); - assert!(digest.result_str() == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf".to_string()); + assert!(digest.result_str() == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf".into()); } diff --git a/Task/SQL-based-authentication/Mathematica/sql-based-authentication.math b/Task/SQL-based-authentication/Mathematica/sql-based-authentication.math new file mode 100644 index 0000000000..99e5e084f8 --- /dev/null +++ b/Task/SQL-based-authentication/Mathematica/sql-based-authentication.math @@ -0,0 +1,24 @@ +Needs["DatabaseLink`"]; +connectDb[dbUser_, dbPass_, dbUrl_] := + OpenSQLConnection[JDBC["mysql", dbUrl], "Username" -> dbUser, + "Password" -> dbPass]; +createUser::nameTaken = "The username '`1`' is already taken."; +createUser[dbUser_, dbPass_, dbUrl_, user_, pass_] := + Module[{db = connectDb[dbUser, dbPass, dbUrl], + salt = RandomChoice[Range[32, 127], 16]}, + If[MemberQ[SQLSelect[db, "users", {"username"}], {user}], + Message[createUser::nameTaken, user]; Return[]]; + SQLInsert[db, + "users", {"username", "pass_salt", "pass_md5"}, {user, + SQLBinary[salt], + SQLBinary[ + IntegerDigits[Hash[FromCharacterCode[salt] <> pass, "MD5"], 256, + 16]]}]; CloseSQLConnection[db];]; +authenticateUser[dbUser_, dbPass_, dbUrl_, user_, pass_] := + Module[{db = connectDb[dbUser, dbPass, dbUrl], rtn}, + rtn = MemberQ[SQLSelect[db, "users", {"username"}], {user}] && + Module[{data = + SQLSelect[db, "users", {"username", "pass_salt", "pass_md5"}, + SQLColumn["username"] == user][[1]]}, + Hash[FromCharacterCode[data[[2, 1]]] <> pass, "MD5"] == + FromDigits[data[[3, 1]], 256]]; CloseSQLConnection[db]; rtn]; diff --git a/Task/Safe-addition/Forth/safe-addition.fth b/Task/Safe-addition/Forth/safe-addition.fth new file mode 100644 index 0000000000..33bace2d07 --- /dev/null +++ b/Task/Safe-addition/Forth/safe-addition.fth @@ -0,0 +1,15 @@ +c-library m +s" m" add-lib +\c #include +c-function fnextafter nextafter r r -- r +end-c-library + +s" MAX-FLOAT" environment? drop fconstant MAX-FLOAT + +: fstepdown ( F: r1 -- r2 ) + MAX-FLOAT fnegate fnextafter ; +: fstepup ( F: r1 -- r2 ) + MAX-FLOAT fnextafter ; + +: savef+ ( F: r1 r2 -- r3 r4 ) \ r4 <= r1+r2 <= r3 + f+ fdup fstepup fswap fstepdown ; diff --git a/Task/Safe-addition/REXX/safe-addition.rexx b/Task/Safe-addition/REXX/safe-addition.rexx index 869b593684..e24c342ef1 100644 --- a/Task/Safe-addition/REXX/safe-addition.rexx +++ b/Task/Safe-addition/REXX/safe-addition.rexx @@ -1,5 +1,5 @@ -numeric digits 1000 /*defines precision to be 1000 digits. */ +numeric digits 1000 /*defines precision to be 1,000 decimal digits. */ -y=digits() /*sets Y to existing number of digits.*/ +y=digits() /*sets Y to existing number of decimal digits.*/ -numeric digits digits()+digits()%10 /*increase digits by 10%.*/ +numeric digits y + y%10 /*increase the (numeric) decimal digits by 10%.*/ diff --git a/Task/Same-Fringe/Racket/same-fringe-1.rkt b/Task/Same-Fringe/Racket/same-fringe-1.rkt new file mode 100644 index 0000000000..665a4b1b3a --- /dev/null +++ b/Task/Same-Fringe/Racket/same-fringe-1.rkt @@ -0,0 +1,19 @@ +#lang racket + +(module same-fringe lazy + (provide same-fringe?) + (define (same-fringe? t1 t2) + (! (equal? (flatten t1) (flatten t2)))) + (define (flatten tree) + (if (list? tree) + (apply append (map flatten tree)) + (list tree)))) + +(require 'same-fringe) + +(module+ test + (require rackunit) + (check-true (same-fringe? '((1 2 3) ((4 5 6) (7 8))) + '(((1 2 3) (4 5 6)) (7 8)))) + (check-false (same-fringe? '((1 2 3) ((4 5 6) (7 8))) + '(((1 2 3) (4 6)) (8))))) diff --git a/Task/Same-Fringe/Racket/same-fringe-2.rkt b/Task/Same-Fringe/Racket/same-fringe-2.rkt new file mode 100644 index 0000000000..8a767bbc14 --- /dev/null +++ b/Task/Same-Fringe/Racket/same-fringe-2.rkt @@ -0,0 +1,15 @@ +#lang racket + +(define (fringe->channel tree) + (define ch (make-channel)) + (thread (λ() (let loop ([tree tree]) + (if (list? tree) (for-each loop tree) (channel-put ch tree))) + (channel-put ch (void)))) ; mark the end + ch) + +(define (same-fringe? tree1 tree2) + (define ch1 (fringe->channel tree1)) + (define ch2 (fringe->channel tree2)) + (let loop () + (let ([x1 (channel-get ch1)] [x2 (channel-get ch2)]) + (and (equal? x1 x2) (or (void? x1) (loop)))))) diff --git a/Task/Same-Fringe/Racket/same-fringe-3.rkt b/Task/Same-Fringe/Racket/same-fringe-3.rkt new file mode 100644 index 0000000000..407eedbaec --- /dev/null +++ b/Task/Same-Fringe/Racket/same-fringe-3.rkt @@ -0,0 +1,15 @@ +#lang racket + +(define (pipe-fringe tree) + (define-values [I O] (make-pipe 100)) + (thread (λ() (let loop ([tree tree]) + (if (list? tree) (for-each loop tree) (fprintf O "~s\n" tree))) + (close-output-port O))) + I) + +(define (same-fringe? tree1 tree2) + (define i1 (pipe-fringe tree1)) + (define i2 (pipe-fringe tree2)) + (let loop () + (let ([x1 (read i1)] [x2 (read i2)]) + (and (equal? x1 x2) (or (eof-object? x1) (loop)))))) diff --git a/Task/Same-Fringe/Racket/same-fringe-4.rkt b/Task/Same-Fringe/Racket/same-fringe-4.rkt new file mode 100644 index 0000000000..97cb06c74f --- /dev/null +++ b/Task/Same-Fringe/Racket/same-fringe-4.rkt @@ -0,0 +1,14 @@ +#lang racket +(require racket/generator) + +(define (fringe-generator tree) + (generator () + (let loop ([tree tree]) + (if (list? tree) (for-each loop tree) (yield tree))))) + +(define (same-fringe? tree1 tree2) + (define g1 (fringe-generator tree1)) + (define g2 (fringe-generator tree2)) + (let loop () + (let ([x1 (g1)] [x2 (g2)]) + (and (equal? x1 x2) (or (void? x1) (loop)))))) diff --git a/Task/Same-Fringe/Racket/same-fringe-5.rkt b/Task/Same-Fringe/Racket/same-fringe-5.rkt new file mode 100644 index 0000000000..d703a832c2 --- /dev/null +++ b/Task/Same-Fringe/Racket/same-fringe-5.rkt @@ -0,0 +1,18 @@ +#lang racket + +(require racket/control) + +(define (fringe-iterator tree) + (λ() (let loop ([tree tree]) + (if (list? tree) (for-each loop tree) (fcontrol tree))) + (fcontrol (void)))) + +(define (same-fringe? tree1 tree2) + (let loop ([iter1 (fringe-iterator tree1)] + [iter2 (fringe-iterator tree2)]) + (% (iter1) + (λ (x1 iter1) + (% (iter2) + (λ (x2 iter2) + (and (equal? x1 x2) + (or (void? x1) (loop iter1 iter2))))))))) diff --git a/Task/Same-Fringe/Racket/same-fringe.rkt b/Task/Same-Fringe/Racket/same-fringe.rkt deleted file mode 100644 index 4a6dd9c785..0000000000 --- a/Task/Same-Fringe/Racket/same-fringe.rkt +++ /dev/null @@ -1,30 +0,0 @@ -#lang racket -(require racket/control) - -(define (make-fringe-getter tree) - (λ () - (let loop ([tree tree]) - (match tree - [(cons a d) (loop a) - (loop d)] - ['() (void)] - [else (fcontrol tree)])) - (fcontrol 'done))) - -(define (same-fringe? tree1 tree2) - (let loop ([get-fringe1 (make-fringe-getter tree1)] - [get-fringe2 (make-fringe-getter tree2)]) - (% (get-fringe1) - (λ (fringe1 get-fringe1) - (% (get-fringe2) - (λ (fringe2 get-fringe2) - (and (equal? fringe1 fringe2) - (or (eq? fringe1 'done) - (loop get-fringe1 get-fringe2))))))))) - -;; unit tests -(require rackunit) -(check-true (same-fringe? '((1 2 3) ((4 5 6) (7 8))) - '(((1 2 3) (4 5 6)) (7 8)))) -(check-false (same-fringe? '((1 2 3) ((4 5 6) (7 8))) - '(((1 2 3) (4 6)) (8)))) diff --git a/Task/Scope-modifiers/REXX/scope-modifiers.rexx b/Task/Scope-modifiers/REXX/scope-modifiers-1.rexx similarity index 100% rename from Task/Scope-modifiers/REXX/scope-modifiers.rexx rename to Task/Scope-modifiers/REXX/scope-modifiers-1.rexx diff --git a/Task/Scope-modifiers/REXX/scope-modifiers-2.rexx b/Task/Scope-modifiers/REXX/scope-modifiers-2.rexx new file mode 100644 index 0000000000..62f5fcf373 --- /dev/null +++ b/Task/Scope-modifiers/REXX/scope-modifiers-2.rexx @@ -0,0 +1,17 @@ +a=1 +b=2 +c=3 +Call p /* a Procedure */ +Say 'in m a b c x' a b c x +Call s /* a subroutine */ +Say 'in m a b c x' a b c x + +Exit +p: Procedure Expose sigl b +Say 'in p sigl a b c' sigl a b c +Call s +Return +s: +Say 'in s sigl a b c' sigl a b c +x=4 +Return diff --git a/Task/Search-a-list/Batch-File/search-a-list.bat b/Task/Search-a-list/Batch-File/search-a-list.bat new file mode 100644 index 0000000000..91f61d9bb9 --- /dev/null +++ b/Task/Search-a-list/Batch-File/search-a-list.bat @@ -0,0 +1,40 @@ +@echo off +setlocal enabledelayedexpansion + + %==Sample list==% +set "data=foo, bar, baz, quux, quuux, quuuux, bazola, ztesch, foo, bar, thud, grunt" +set "data=%data% foo, bar, bletch, foo, bar, fum, fred, jim, sheila, barney, flarp, zxc" +set "data=%data% spqr, wombat, shme, foo, bar, baz, bongo, spam, eggs, snork, foo, bar" +set "data=%data% zot, blarg, wibble, toto, titi, tata, tutu, pippo, pluto, paperino, aap" +set "data=%data% noot, mies, oogle, foogle, boogle, zork, gork, bork" + + %==Sample "needles" [whitespace is the delimiter]==% +set "needles=foo bar baz jim bong" + + %==Counting and Seperating each Data==% +set datalen=0 +for %%. in (!data!) do ( + set /a datalen+=1 + set data!datalen!=%%. +) + %==Do the search==% +for %%A in (!needles!) do ( + set "first=" + set "last=" + set "found=0" + for /l %%B in (1,1,%datalen%) do ( + if "!data%%B!" == "%%A" ( + set /a found+=1 + if !found! equ 1 set first=%%B + set last=%%B + ) + ) + + if !found! equ 0 echo."%%A": Not found. + if !found! equ 1 echo."%%A": Found once in index [!first!]. + if !found! gtr 1 echo."%%A": Found !found! times. First instance:[!first!] Last instance:[!last!]. + +) + %==We are done==% +echo. +pause diff --git a/Task/Search-a-list/Elixir/search-a-list.elixir b/Task/Search-a-list/Elixir/search-a-list.elixir new file mode 100644 index 0000000000..655a8d3e8d --- /dev/null +++ b/Task/Search-a-list/Elixir/search-a-list.elixir @@ -0,0 +1,7 @@ +haystack = ~w(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo) + +Enum.each(~w(Bush Washington), fn needle -> + index = Enum.find_index(haystack, fn x -> x==needle end) + if index, do: (IO.puts "#{index} #{needle}"), + else: raise "#{needle} is not in haystack\n" +end) diff --git a/Task/Search-a-list/Forth/search-a-list.fth b/Task/Search-a-list/Forth/search-a-list-1.fth similarity index 100% rename from Task/Search-a-list/Forth/search-a-list.fth rename to Task/Search-a-list/Forth/search-a-list-1.fth diff --git a/Task/Search-a-list/Forth/search-a-list-2.fth b/Task/Search-a-list/Forth/search-a-list-2.fth new file mode 100644 index 0000000000..eee53f57ad --- /dev/null +++ b/Task/Search-a-list/Forth/search-a-list-2.fth @@ -0,0 +1,29 @@ +include FMS-SI.f +include FMS-SILib.f + +${ Dishonest Fake Left Karl Hillary Monica Bubba Hillary Multi-Millionaire } constant haystack + +: needleIndex { addr len $list | cnt -- idx } + 0 to cnt $list uneach: + begin + $list each: + while + @: addr len compare 0= if cnt exit then + cnt 1+ to cnt + repeat true abort" Not found" ; + +: LastIndexOf { addr len $list | cnt last-found -- idx } + 0 to cnt 0 to last-found $list uneach: + begin + $list each: + while + @: addr len compare 0= if cnt to last-found then + cnt 1+ to cnt + repeat + last-found if last-found + else true abort" Not found" + then ; + +s" Hillary" haystack needleIndex . \ => 4 +s" Hillary" haystack LastIndexOf . \ => 7 +s" Washington" haystack needleIndex . \ => aborted: Not found diff --git a/Task/Search-a-list/Go/search-a-list-1.go b/Task/Search-a-list/Go/search-a-list-1.go new file mode 100644 index 0000000000..a0edba582d --- /dev/null +++ b/Task/Search-a-list/Go/search-a-list-1.go @@ -0,0 +1,14 @@ +package main + +var haystack = []string{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", + "Charlie", "Bush", "Bozo", "Zag", "mouse", "hat", "cup", "deodorant", + "television", "soap", "methamphetamine", "severed cat heads", "foo", + "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", + "bar", "thud", "grunt", "foo", "bar", "bletch", "foo", "bar", "fum", + "fred", "jim", "sheila", "barney", "flarp", "zxc", "spqr", ";wombat", + "shme", "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", + "bar", "zot", "blarg", "wibble", "toto", "titi", "tata", "tutu", "pippo", + "pluto", "paperino", "aap", "noot", "mies", "oogle", "foogle", "boogle", + "zork", "gork", "bork", "sodium", "phosphorous", "californium", + "copernicium", "gold", "thallium", "carbon", "silver", "gold", "copper", + "helium", "sulfur"} diff --git a/Task/Search-a-list/Go/search-a-list-2.go b/Task/Search-a-list/Go/search-a-list-2.go new file mode 100644 index 0000000000..1b97f3eea3 --- /dev/null +++ b/Task/Search-a-list/Go/search-a-list-2.go @@ -0,0 +1,66 @@ +package main + +import "fmt" + +func main() { + // first task + printSearchForward("soap") + printSearchForward("gold") + printSearchForward("fire") + // extra task + printSearchReverseMult("soap") + printSearchReverseMult("gold") + printSearchReverseMult("fire") +} + +// First task solution uses panic as an exception-like mechanism, as requested +// by the task. Note however, this is not idiomatic in Go and in fact +// is considered bad practice. +func printSearchForward(s string) { + fmt.Printf("Forward search: %s: ", s) + defer func() { + if x := recover(); x != nil { + if err, ok := x.(string); ok && err == "no match" { + fmt.Println(err) + return + } + panic(x) + } + }() + fmt.Println("smallest index =", searchForwardPanic(s)) +} + +func searchForwardPanic(s string) int { + for i, h := range haystack { + if h == s { + return i + } + } + panic("no match") + return -1 +} + +// Extra task, a quirky search for multiple occurrences. This is written +// without panic, and shows more acceptable Go programming practice. +func printSearchReverseMult(s string) { + fmt.Printf("Reverse search for multiples: %s: ", s) + if i := searchReverseMult(s); i > -1 { + fmt.Println("largest index =", i) + } else { + fmt.Println("no multiple occurrence") + } +} + +func searchReverseMult(s string) int { + largest := -1 + for i := len(haystack) - 1; i >= 0; i-- { + switch { + case haystack[i] != s: + case largest == -1: + largest = i + default: + return largest + } + } + return -1 +} diff --git a/Task/Search-a-list/Go/search-a-list-3.go b/Task/Search-a-list/Go/search-a-list-3.go new file mode 100644 index 0000000000..8321b2b484 --- /dev/null +++ b/Task/Search-a-list/Go/search-a-list-3.go @@ -0,0 +1,13 @@ +package main + +import "fmt" + +func main() { + m := map[string][]int{} + for i, needle := range haystack { + m[needle] = append(m[needle], i) + } + for _, n := range []string{"soap", "gold", "fire"} { + fmt.Println(n, m[n]) + } +} diff --git a/Task/Search-a-list/Go/search-a-list.go b/Task/Search-a-list/Go/search-a-list.go deleted file mode 100644 index da03484dd3..0000000000 --- a/Task/Search-a-list/Go/search-a-list.go +++ /dev/null @@ -1,79 +0,0 @@ -package main - -import "fmt" - -var haystack = []string{"Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", - "Charlie", "Bush", "Bozo", "Zag", "mouse", "hat", "cup", "deodorant", - "television", "soap", "methamphetamine", "severed cat heads", "foo", - "bar", "baz", "quux", "quuux", "quuuux", "bazola", "ztesch", "foo", - "bar", "thud", "grunt", "foo", "bar", "bletch", "foo", "bar", "fum", - "fred", "jim", "sheila", "barney", "flarp", "zxc", "spqr", ";wombat", - "shme", "foo", "bar", "baz", "bongo", "spam", "eggs", "snork", "foo", - "bar", "zot", "blarg", "wibble", "toto", "titi", "tata", "tutu", "pippo", - "pluto", "paperino", "aap", "noot", "mies", "oogle", "foogle", "boogle", - "zork", "gork", "bork", "sodium", "phosphorous", "californium", - "copernicium", "gold", "thallium", "carbon", "silver", "gold", "copper", - "helium", "sulfur"} - -func main() { - // first task - printSearchForward("soap") - printSearchForward("gold") - printSearchForward("fire") - // extra task - printSearchReverseMult("soap") - printSearchReverseMult("gold") - printSearchReverseMult("fire") -} - -// First task solution uses panic as an exception-like mechanism, as requested -// by the task. Note however, this is not idiomatic in Go and in fact -// is considered bad practice. -func printSearchForward(s string) { - fmt.Printf("Forward search: %s: ", s) - defer func() { - if x := recover(); x != nil { - if err, ok := x.(string); ok && err == "no match" { - fmt.Println(err) - return - } - panic(x) - } - }() - fmt.Println("smallest index =", searchForwardPanic(s)) -} - -func searchForwardPanic(s string) int { - for i, h := range haystack { - if h == s { - return i - } - } - panic("no match") - return -1 -} - -// Extra task, a quirky search for multiple occurrences. This is written -// without panic, and shows more acceptable Go programming practice. -func printSearchReverseMult(s string) { - fmt.Printf("Reverse search for multiples: %s: ", s) - if i := searchReverseMult(s); i > -1 { - fmt.Println("largest index =", i) - } else { - fmt.Println("no multiple occurrence") - } -} - -func searchReverseMult(s string) int { - largest := -1 - for i := len(haystack) - 1; i >= 0; i-- { - switch { - case haystack[i] != s: - case largest == -1: - largest = i - default: - return largest - } - } - return -1 -} diff --git a/Task/Search-a-list/PowerShell/search-a-list.psh b/Task/Search-a-list/PowerShell/search-a-list.psh new file mode 100644 index 0000000000..99740bc29d --- /dev/null +++ b/Task/Search-a-list/PowerShell/search-a-list.psh @@ -0,0 +1,12 @@ +function index($haystack,$needle) { + $index = $haystack.IndexOf($needle) + if($index -eq -1) { + Write-Warning "$needle is absent" + } else { + $index + } + +} +$haystack = @("word", "phrase", "preface", "title", "house", "line", "chapter", "page", "book", "house") +index $haystack "house" +index $haystack "paragraph" diff --git a/Task/Search-a-list/Ruby/search-a-list-1.rb b/Task/Search-a-list/Ruby/search-a-list-1.rb index 24bfd0d5b7..cc77c373c9 100644 --- a/Task/Search-a-list/Ruby/search-a-list-1.rb +++ b/Task/Search-a-list/Ruby/search-a-list-1.rb @@ -2,7 +2,7 @@ %w(Bush Washington).each do |needle| if (i = haystack.index(needle)) - print i, " ", needle, "\n" + puts "#{i} #{needle}" else raise "#{needle} is not in haystack\n" end diff --git a/Task/Search-a-list/Ruby/search-a-list-2.rb b/Task/Search-a-list/Ruby/search-a-list-2.rb index 99ecb018af..504561b3be 100644 --- a/Task/Search-a-list/Ruby/search-a-list-2.rb +++ b/Task/Search-a-list/Ruby/search-a-list-2.rb @@ -5,3 +5,4 @@ break end end +#=> Bush last appears at index 7 diff --git a/Task/Search-a-list/Ruby/search-a-list-3.rb b/Task/Search-a-list/Ruby/search-a-list-3.rb index 67ff7a12e0..54aa2ef18a 100644 --- a/Task/Search-a-list/Ruby/search-a-list-3.rb +++ b/Task/Search-a-list/Ruby/search-a-list-3.rb @@ -1,3 +1,6 @@ -multi_item = haystack .each_with_index .group_by {|elem, idx| elem} .find {|key, val| val.length > 1} -# multi_item is => ["Bush", [["Bush", 4], ["Bush", 7]]] -puts "#{multi_item[0]} last appears at index #{multi_item[1][-1][1]}" unless multi_item.nil? +multi_item = haystack.each_index.group_by{|idx| haystack[idx]}.select{|key, val| val.length > 1} +# multi_item is => {"Bush"=>[4, 7]} +multi_item.each do |key, val| + puts "#{key} appears at index #{val}" +end +#=> Bush appears at index [4, 7] diff --git a/Task/Search-a-list/Rust/search-a-list-1.rust b/Task/Search-a-list/Rust/search-a-list-1.rust new file mode 100644 index 0000000000..27c18ece6e --- /dev/null +++ b/Task/Search-a-list/Rust/search-a-list-1.rust @@ -0,0 +1,8 @@ +fn main() { + let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", + "Bush", "Boz", "Zag"]; + + println!("First occurence of 'Bush' at {:?}",haystack.iter().position(|s| *s=="Bush")); + println!("Last occurence of 'Bush' at {:?}",haystack.iter().rposition(|s| *s=="Bush")); + println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob")); +} diff --git a/Task/Search-a-list/Rust/search-a-list-2.rust b/Task/Search-a-list/Rust/search-a-list-2.rust new file mode 100644 index 0000000000..e52c35a0e8 --- /dev/null +++ b/Task/Search-a-list/Rust/search-a-list-2.rust @@ -0,0 +1,8 @@ +fn main() { + let haystack=vec!["Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", + "Bush", "Boz", "Zag"]; + + println!("First occurence of 'Bush' at {:?}",haystack.iter().position(|s| *s=="Bush").unwrap()); + println!("Last occurence of 'Bush' at {:?}",haystack.iter().rposition(|s| *s=="Bush").unwrap()); + println!("First occurence of 'Rob' at {:?}",haystack.iter().position(|s| *s=="Rob").unwrap()); +} diff --git a/Task/Search-a-list/VBScript/search-a-list.vb b/Task/Search-a-list/VBScript/search-a-list.vb new file mode 100644 index 0000000000..5c7adae073 --- /dev/null +++ b/Task/Search-a-list/VBScript/search-a-list.vb @@ -0,0 +1,28 @@ +data = "foo,bar,baz,quux,quuux,quuuux,bazola,ztesch,foo,bar,thud,grunt," &_ + "foo,bar,bletch,foo,bar,fum,fred,jim,sheila,barney,flarp,zxc," &_ + "spqr,wombat,shme,foo,bar,baz,bongo,spam,eggs,snork,foo,bar," &_ + "zot,blarg,wibble,toto,titi,tata,tutu,pippo,pluto,paperino,aap," &_ + "noot,mies,oogle,foogle,boogle,zork,gork,bork" + +haystack = Split(data,",") + +Do + WScript.StdOut.Write "Word to search for? (Leave blank to exit) " + needle = WScript.StdIn.ReadLine + If needle <> "" Then + found = 0 + For i = 0 To UBound(haystack) + If UCase(haystack(i)) = UCase(needle) Then + found = 1 + WScript.StdOut.Write "Found " & Chr(34) & needle & Chr(34) & " at index " & i + WScript.StdOut.WriteLine + End If + Next + If found < 1 Then + WScript.StdOut.Write Chr(34) & needle & Chr(34) & " not found." + WScript.StdOut.WriteLine + End If + Else + Exit do + End If +Loop diff --git a/Task/Secure-temporary-file/Go/secure-temporary-file.go b/Task/Secure-temporary-file/Go/secure-temporary-file-1.go similarity index 100% rename from Task/Secure-temporary-file/Go/secure-temporary-file.go rename to Task/Secure-temporary-file/Go/secure-temporary-file-1.go diff --git a/Task/Secure-temporary-file/Go/secure-temporary-file-2.go b/Task/Secure-temporary-file/Go/secure-temporary-file-2.go new file mode 100644 index 0000000000..fc4f315d4d --- /dev/null +++ b/Task/Secure-temporary-file/Go/secure-temporary-file-2.go @@ -0,0 +1,6 @@ +def file = File.createTempFile( "xxx", ".txt" ) + +// There is no requirement in the instructions to delete the file. +//file.deleteOnExit() + +println file diff --git a/Task/Secure-temporary-file/Java/secure-temporary-file.java b/Task/Secure-temporary-file/Java/secure-temporary-file.java index accbc7b3ea..2340197bbe 100644 --- a/Task/Secure-temporary-file/Java/secure-temporary-file.java +++ b/Task/Secure-temporary-file/Java/secure-temporary-file.java @@ -1,13 +1,15 @@ import java.io.File; - -try { - // Create temp file - File filename = File.createTempFile("prefix", ".suffix"); - - // Delete temp file when program exits - filename.deleteOnExit(); - - System.out.println(filename); - -} catch (IOException e) { +import java.io.IOException; + +public class CreateTempFile { + public static void main(String[] args) { + try { + //create a temp file + File temp = File.createTempFile("temp-file-name", ".tmp"); + System.out.println("Temp file : " + temp.getAbsolutePath()); + } + catch(IOException e) { + e.printStackTrace(); + } + } } diff --git a/Task/Secure-temporary-file/Julia/secure-temporary-file-1.julia b/Task/Secure-temporary-file/Julia/secure-temporary-file-1.julia new file mode 100644 index 0000000000..c318d78c0d --- /dev/null +++ b/Task/Secure-temporary-file/Julia/secure-temporary-file-1.julia @@ -0,0 +1,7 @@ +msg = "Rosetta Code, Secure temporary file, implemented with Julia." + +(fname, tio) = mktemp() +println(fname, " created as a temporary file.") +println(tio, msg) +close(tio) +println("\"", msg, "\" written to ", fname) diff --git a/Task/Secure-temporary-file/Julia/secure-temporary-file-2.julia b/Task/Secure-temporary-file/Julia/secure-temporary-file-2.julia new file mode 100644 index 0000000000..8963509ccd --- /dev/null +++ b/Task/Secure-temporary-file/Julia/secure-temporary-file-2.julia @@ -0,0 +1,6 @@ +ENV["TMPDIR"] = pwd() +(fname, tio) = mktemp() +println(fname, " created as a \"temporary\" file.") +println(tio, msg) +close(tio) +println("\"", msg, "\" written to ", fname) diff --git a/Task/Secure-temporary-file/Ruby/secure-temporary-file.rb b/Task/Secure-temporary-file/Ruby/secure-temporary-file.rb index e7130b3dc4..4e23bb0cc0 100644 --- a/Task/Secure-temporary-file/Ruby/secure-temporary-file.rb +++ b/Task/Secure-temporary-file/Ruby/secure-temporary-file.rb @@ -6,3 +6,5 @@ => "/tmp/foo20081226-307-10p746n-0" irb(main):004:0> f.close => nil +irb(main):005:0> f.unlink +=> # diff --git a/Task/Self-describing-numbers/00DESCRIPTION b/Task/Self-describing-numbers/00DESCRIPTION index 87d87ac572..be7f194965 100644 --- a/Task/Self-describing-numbers/00DESCRIPTION +++ b/Task/Self-describing-numbers/00DESCRIPTION @@ -1,13 +1,15 @@ -There are several integers numbers called "self-describing" or "[[wp:Self-descriptive number|self-descriptive]]" +There are several so-called "self-describing" or "[[wp:Self-descriptive number|self-descriptive]]" integers. -Integers with the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. +An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number. -For example 2020 is a four digit self describing number. +For example, 2020 is a four-digit self describing number: -Position "0" has value 2 and there is two 0 in the number. Position "1" has value 0 because there are not 1's in the number. -Position "2" has value 2 and there is two 2. And the position "3" has value 0 and there are zero 3's. +* position 0 has value 2 and there are two 0s in the number; +* position 1 has value 0 and there are no 1s in the number; +* position 2 has value 2 and there are two 2s; +* position 3 has value 0 and there are zero 3s. -Self-describing numbers < 100.000.000: 1210 - 2020 - 21200 - 3211000 - 42101000 +Self-describing numbers < 100.000.000: 1210, 2020, 21200, 3211000, 42101000. ;Task Description # Write a function/routine/method/... that will check whether a given positive integer is self-describing. diff --git a/Task/Self-describing-numbers/D/self-describing-numbers-1.d b/Task/Self-describing-numbers/D/self-describing-numbers-1.d index 1501ddc2d1..8e95e79542 100644 --- a/Task/Self-describing-numbers/D/self-describing-numbers-1.d +++ b/Task/Self-describing-numbers/D/self-describing-numbers-1.d @@ -6,5 +6,5 @@ bool isSelfDescribing(in long n) pure nothrow @safe { } void main() { - 4_000_.iota.filter!isSelfDescribing.writeln; + 4_000_000.iota.filter!isSelfDescribing.writeln; } diff --git a/Task/Self-describing-numbers/VBScript/self-describing-numbers.vb b/Task/Self-describing-numbers/VBScript/self-describing-numbers.vb new file mode 100644 index 0000000000..9e51be5543 --- /dev/null +++ b/Task/Self-describing-numbers/VBScript/self-describing-numbers.vb @@ -0,0 +1,39 @@ +Function IsSelfDescribing(n) + IsSelfDescribing = False + Set digit = CreateObject("Scripting.Dictionary") + For i = 1 To Len(n) + k = Mid(n,i,1) + If digit.Exists(k) Then + digit.Item(k) = digit.Item(k) + 1 + Else + digit.Add k,1 + End If + Next + c = 0 + For j = 0 To Len(n)-1 + l = Mid(n,j+1,1) + If digit.Exists(CStr(j)) Then + If digit.Item(CStr(j)) = CInt(l) Then + c = c + 1 + End If + ElseIf l = 0 Then + c = c + 1 + Else + Exit For + End If + Next + If c = Len(n) Then + IsSelfDescribing = True + End If +End Function + +'testing +start_time = Now +s = "" +For m = 1 To 100000000 + If IsSelfDescribing(m) Then + WScript.StdOut.WriteLine m + End If +Next +end_time = Now +WScript.StdOut.WriteLine "Elapse Time: " & DateDiff("s",start_time,end_time) & " seconds" diff --git a/Task/Self-referential-sequence/C++/self-referential-sequence.cpp b/Task/Self-referential-sequence/C++/self-referential-sequence.cpp new file mode 100644 index 0000000000..1c55c35530 --- /dev/null +++ b/Task/Self-referential-sequence/C++/self-referential-sequence.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include +#include + +std::map _map; +std::vector _result; +size_t longest = 0; + +void make_sequence( std::string n ) { + _map.clear(); + for( std::string::iterator i = n.begin(); i != n.end(); i++ ) + _map.insert( std::make_pair( *i, _map[*i]++ ) ); + + std::string z; + for( std::map::reverse_iterator i = _map.rbegin(); i != _map.rend(); i++ ) { + char c = ( *i ).second + 48; + z.append( 1, c ); + z.append( 1, i->first ); + } + + if( longest <= z.length() ) { + longest = z.length(); + if( std::find( _result.begin(), _result.end(), z ) == _result.end() ) { + _result.push_back( z ); + make_sequence( z ); + } + } +} +int main( int argc, char* argv[] ) { + std::vector tests; + tests.push_back( "9900" ); tests.push_back( "9090" ); tests.push_back( "9009" ); + for( std::vector::iterator i = tests.begin(); i != tests.end(); i++ ) { + make_sequence( *i ); + std::cout << "[" << *i << "] Iterations: " << _result.size() + 1 << "\n"; + for( std::vector::iterator j = _result.begin(); j != _result.end(); j++ ) { + std::cout << *j << "\n"; + } + std::cout << "\n\n"; + } + return 0; +} diff --git a/Task/Self-referential-sequence/Eiffel/self-referential-sequence.e b/Task/Self-referential-sequence/Eiffel/self-referential-sequence.e new file mode 100644 index 0000000000..591725a6dd --- /dev/null +++ b/Task/Self-referential-sequence/Eiffel/self-referential-sequence.e @@ -0,0 +1,198 @@ +class + SELF_REFERENTIAL_SEQUENCE + +create + make + +feature + + make + local + i: INTEGER + length, max: INTEGER_64 + do + create seed_value.make + create sequence.make (25) + create permuted_values.make + from + i := 1 + until + i > 1000000 + loop + length := check_length (i.out) + if length > max then + max := length + seed_value.wipe_out + seed_value.extend (i) + elseif length = max then + seed_value.extend (i) + end + sequence.wipe_out + i := next_ascending (i).to_integer + end + io.put_string ("Maximal length: " + max.out) + io.put_string ("%NSeed Value: %N") + across + seed_value as s + loop + permute (s.item.out, 1) + end + across + permuted_values as p + loop + io.put_string (p.item + "%N") + end + io.put_string ("Sequence:%N") + max := check_length (seed_value [1].out) + across + sequence as s + loop + io.put_string (s.item) + io.new_line + end + end + + next_ascending (n: INTEGER_64): STRING + -- Next number with ascending digits after 'n'. + -- Numbers with trailing zeros are treated as ascending numbers. + local + st: STRING + first, should_be, zero: STRING + i: INTEGER + do + create Result.make_empty + create zero.make_empty + st := (n + 1).out + from + until + st.count < 2 + loop + first := st.at (1).out + if st [2] ~ '0' then + from + i := 3 + until + i > st.count + loop + zero.append ("0") + i := i + 1 + end + Result.append (first + first + zero) + st := "" + else + should_be := st.at (2).out + if first > should_be then + should_be := first + end + st.remove_head (2) + st.prepend (should_be) + Result.append (first) + end + end + if st.count > 0 then + Result.append (st [st.count].out) + end + end + +feature {NONE} + + seed_value: SORTED_TWO_WAY_LIST [INTEGER] + + permuted_values: SORTED_TWO_WAY_LIST [STRING] + + sequence: ARRAYED_LIST [STRING] + + permute (a: STRING; k: INTEGER) + -- All permutations of 'a'. + require + count_positive: a.count > 0 + k_valid_index: k > 0 + local + t: CHARACTER + b: STRING + found: BOOLEAN + do + across + permuted_values as p + loop + if p.item ~ a then + found := True + end + end + if k = a.count and a [1] /= '0' and not found then + create b.make_empty + b.deep_copy (a) + permuted_values.extend (b) + else + across + k |..| a.count as c + loop + t := a [k] + a [k] := a [c.item] + a [c.item] := t + permute (a, k + 1) + t := a [k] + a [k] := a [c.item] + a [c.item] := t + end + end + end + + check_length (i: STRING): INTEGER_64 + -- Length of the self referential sequence starting with 'i'. + local + found: BOOLEAN + j: INTEGER + s: STRING + do + create s.make_from_string (i) + from + until + found + loop + sequence.extend (s) + s := next (s) + from + j := sequence.count - 1 + until + j < 1 + loop + if sequence [j] ~ s then + found := True + end + j := j - 1 + end + end + Result := sequence.count + end + + next (n: STRING): STRING + -- Next item after 'n' in a self referential sequence. + local + i, count: INTEGER + counter: ARRAY [INTEGER] + do + create counter.make_filled (0, 0, 9) + create Result.make_empty + from + i := 1 + until + i > n.count + loop + count := n [i].out.to_integer + counter [count] := counter [count] + 1 + i := i + 1 + end + from + i := 9 + until + i < 0 + loop + if counter [i] > 0 then + Result.append (counter [i].out + i.out) + end + i := i - 1 + end + end + +end diff --git a/Task/Semiprime/DCL/semiprime.dcl b/Task/Semiprime/DCL/semiprime.dcl new file mode 100644 index 0000000000..117b1f8f65 --- /dev/null +++ b/Task/Semiprime/DCL/semiprime.dcl @@ -0,0 +1,48 @@ +$ p1 = f$integer( p1 ) +$ if p1 .lt. 2 +$ then +$ write sys$output "out of range 2 thru 2^31-1" +$ exit +$ endif +$ +$ close /nolog primes +$ on control_y then $ goto clean +$ open primes primes.txt +$ +$ loop1: +$ read /end_of_file = prime primes prime +$ prime = f$integer( prime ) +$ loop2: +$ t = p1 / prime +$ if t * prime .eq. p1 +$ then +$ if f$type( factorization ) .eqs. "" +$ then +$ factorization = f$string( prime ) +$ else +$ factorization = factorization + "*" + f$string( prime ) +$ endif +$ if t .eq. 1 then $ goto done +$ p1 = t +$ goto loop2 +$ else +$ goto loop1 +$ endif +$ prime: +$ if f$type( factorization ) .eqs. "" +$ then +$ factorization = f$string( p1 ) +$ else +$ factorization = factorization + "*" + f$string( p1 ) +$ endif +$ done: +$ show symbol factorization +$ if f$locate( "*", factorization ) .eq. f$length( factorization ) +$ then +$ write sys$output "so, it is prime" +$ else +$ if f$element( 2, "*", factorization ) .eqs. "*" then $ write sys$output "so, it is semiprime" +$ endif +$ +$ clean: +$ close primes diff --git a/Task/Semiprime/Erlang/semiprime.erl b/Task/Semiprime/Erlang/semiprime.erl new file mode 100644 index 0000000000..e131628c30 --- /dev/null +++ b/Task/Semiprime/Erlang/semiprime.erl @@ -0,0 +1,20 @@ +-module(factors). +-export([factors/1,kthfactor/2]). + +factors(N) -> + factors(N,2,[]). + +factors(1,_,Acc) -> Acc; +factors(N,K,Acc) when N rem K == 0 -> +% io:format("Ks: ~w~n", [[K|Acc]]), + factors(N div K,K, [K|Acc]); +factors(N,K,Acc) -> + factors(N,K+1,Acc). + + +% is integer N factorable into M primes? +kthfactor(N,M) -> + case length(factors(N)) of M -> + factors(N); + _ -> + false end. diff --git a/Task/Semiprime/Maple/semiprime-1.maple b/Task/Semiprime/Maple/semiprime-1.maple new file mode 100644 index 0000000000..480a0f3ff3 --- /dev/null +++ b/Task/Semiprime/Maple/semiprime-1.maple @@ -0,0 +1,10 @@ +SemiPrimes := proc( n ) + local fact; + fact := numtheory:-divisors( n ) minus {1, n}; + if numelems( fact ) in {1,2} and not( member( 'false', isprime ~ ( fact ) ) ) then + return n; + else + return NULL; + end if; +end proc: +{ seq( SemiPrime( i ), i = 1..100 ) }; diff --git a/Task/Semiprime/Maple/semiprime-2.maple b/Task/Semiprime/Maple/semiprime-2.maple new file mode 100644 index 0000000000..f3d220e2ee --- /dev/null +++ b/Task/Semiprime/Maple/semiprime-2.maple @@ -0,0 +1 @@ +{ 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/Semordnilap/Common-Lisp/semordnilap.lisp b/Task/Semordnilap/Common-Lisp/semordnilap.lisp new file mode 100644 index 0000000000..61c2710b2f --- /dev/null +++ b/Task/Semordnilap/Common-Lisp/semordnilap.lisp @@ -0,0 +1,21 @@ +(defun semordnilaps (word-list) + (let ((word-map (make-hash-table :test 'equal))) + (loop for word in word-list do + (setf (gethash word word-map) t)) + (loop for word in word-list + for rword = (reverse word) + when (and (string< word rword) (gethash rword word-map)) + collect (cons word rword)))) + +(defun main () + (let ((words + (semordnilaps + (with-open-file (s "unixdict.txt") + (loop for line = (read-line s nil nil) + until (null line) + collect (string-right-trim #(#\space #\return #\newline) line)))))) + (format t "Found pairs: ~D" (length words)) + (loop for x from 1 to 5 + for word in words + do (print word))) + (values)) diff --git a/Task/Semordnilap/Eiffel/semordnilap-1.e b/Task/Semordnilap/Eiffel/semordnilap-1.e index ea5a951358..f53e49ea51 100644 --- a/Task/Semordnilap/Eiffel/semordnilap-1.e +++ b/Task/Semordnilap/Eiffel/semordnilap-1.e @@ -1,80 +1,79 @@ -note - description: "Summary description for {SEMORDNILAP}." - author: "" - date: "$Date$" - revision: "$Revision$" - class SEMORDNILAP + create make - feature +feature + make - --read wordlist "unixdict.txt", search across wordlist with binary_search + --Semordnilaps in 'solution'. local - count,i,j, middle, upper, lower: INTEGER + count, i, middle, upper, lower: INTEGER reverse: STRING do read_wordlist create solution.make_empty from - i:= 1 + i := 1 until - i> word_array.count + i > word_array.count loop - word_array[i].mirror - reverse:=word_array[i] + word_array [i].mirror + reverse := word_array [i] from - lower:= i+1 - upper:= word_array.count + lower := i + 1 + upper := word_array.count until - lower>=upper + lower >= upper loop - - middle:= (upper-lower)//2+lower - if reverse.is_case_insensitive_equal (word_array[middle]) then - count:= count+1 - upper:= 0 - lower:= 1 - solution.force (word_array[middle],count) - elseif reverse.is_less (word_array[middle]) then - upper:= middle-1 + middle := (upper - lower) // 2 + lower + if reverse.same_string (word_array [middle]) then + count := count + 1 + upper := 0 + lower := 1 + solution.force (word_array [i], count) + elseif reverse.is_less (word_array [middle]) then + upper := middle - 1 else - lower:= middle+1 + lower := middle + 1 end end - if lower < word_array.count and then reverse.is_case_insensitive_equal (word_array[lower]) then - count:= count+1 - upper:= 0 - lower:= 1 - solution.force (word_array[middle],count) + if lower < word_array.count and then reverse.same_string (word_array [lower]) then + count := count + 1 + upper := 0 + lower := 1 + solution.force (word_array [i], count) end - i:= i+1 + i := i + 1 end end - solution: ARRAY[STRING] + solution: ARRAY [STRING] + + original_list: STRING = "unixdict.txt" + feature {NONE} + read_wordlist + -- Preprocessed word_array for finding Semordnilaps. local l_file: PLAIN_TEXT_FILE - wordlist: LIST[STRING] - i: INTEGER + wordlist: LIST [STRING] do - create l_file.make_open_read_write ("unixdict.txt") + create l_file.make_open_read_write (original_list) l_file.read_stream (l_file.count) - wordlist:=l_file.last_string.split ('%N') + wordlist := l_file.last_string.split ('%N') + l_file.close create word_array.make_empty - from - i:= 1 - until - i> wordlist.count + across + 1 |..| wordlist.count as i loop - word_array.force( wordlist.at (i),i) - i:= i+1 + word_array.force (wordlist.at (i.item), i.item) end end - word_array: ARRAY[STRING] + + word_array: ARRAY [STRING] + end diff --git a/Task/Semordnilap/Eiffel/semordnilap-2.e b/Task/Semordnilap/Eiffel/semordnilap-2.e index 9b26bdb297..00b10484c5 100644 --- a/Task/Semordnilap/Eiffel/semordnilap-2.e +++ b/Task/Semordnilap/Eiffel/semordnilap-2.e @@ -1,16 +1,34 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - do - create se.make - across se.solution.subarray (27, 32)as s loop io.put_string (s.item.out+"%T"); s.item.mirror; io.put_string(s.item.out+"%N") end - io.put_string ("There are "+se.solution.count.out+" pairs.") - end + local + test: ARRAY [STRING] + s: STRING + do + create se.make + test := se.solution + create sort.sort (test) + across + test.subarray (1, 5) as t + loop + s := t.item + io.put_string (t.item + "%T") + s.mirror + io.put_string (s) + io.new_line + end + io.put_string ("Total number of semordnilaps: ") + io.put_integer (test.count) + end se: SEMORDNILAP + + sort: MERGE_SORT [STRING] + end diff --git a/Task/Semordnilap/Kotlin/semordnilap.kotlin b/Task/Semordnilap/Kotlin/semordnilap.kotlin new file mode 100644 index 0000000000..ce88182048 --- /dev/null +++ b/Task/Semordnilap/Kotlin/semordnilap.kotlin @@ -0,0 +1,10 @@ +import java.nio.file.Files +import java.nio.file.Paths + +fun semordnilap() { + val words = Files.readAllLines(Paths.get("unixdict.txt"), Charsets.UTF_8).toSet() + val pairs = words.asSequence().map { it to it.reverse() } // Pair(word, reversed word) + .filter { it.first < it.second && it.second in words }.toList() // avoid dupes+palindromes, find matches + println("Found ${pairs.size()} semordnilap pairs") + println(pairs.take(5)) +} diff --git a/Task/Semordnilap/VBScript/semordnilap.vb b/Task/Semordnilap/VBScript/semordnilap.vb new file mode 100644 index 0000000000..f56f78ccdf --- /dev/null +++ b/Task/Semordnilap/VBScript/semordnilap.vb @@ -0,0 +1,36 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") +Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\unixdict.txt",1) + +Set objUnixDict = CreateObject("Scripting.Dictionary") +Set objSemordnilap = CreateObject("Scripting.Dictionary") + +Do Until objInFile.AtEndOfStream + line = objInFile.ReadLine + If Len(line) > 1 Then + objUnixDict.Add line,"" + End If + reverse_line = StrReverse(line) + If reverse_line <> line And objUnixDict.Exists(reverse_line) Then + objSemordnilap.Add line, reverse_line + End If +Loop + +'Display the first 5 keys. +k = 0 +For Each Key In objSemordnilap.Keys + WScript.StdOut.Write Key & " - " & objSemordnilap.Item(Key) + WScript.StdOut.WriteLine + k = k + 1 + If k = 5 Then + Exit For + End If +Next + +WScript.StdOut.Write "Total Count: " & objSemordnilap.Count +WScript.StdOut.WriteLine + +objInFile.Close +Set objFSO = Nothing +Set objUnixDict = Nothing +Set objSemordnilap = Nothing diff --git a/Task/Send-an-unknown-method-call/Forth/send-an-unknown-method-call.fth b/Task/Send-an-unknown-method-call/Forth/send-an-unknown-method-call.fth new file mode 100644 index 0000000000..b4956051a7 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Forth/send-an-unknown-method-call.fth @@ -0,0 +1,12 @@ +include FMS-SI.f +include FMS-SILib.f + +var x \ instantiate a class var object named x + +: test + heap> string locals| s | + '!' s +: ':' s +: \ build the message "!:" into string s + 42 x s @: evaluate \ retrieve the text from s and execute it + x p: ; \ lastly, send the p: message to x to print it + +test \ => 42 ok diff --git a/Task/Send-email/Emacs-Lisp/send-email.l b/Task/Send-email/Emacs-Lisp/send-email.l new file mode 100644 index 0000000000..d3d58c2b9e --- /dev/null +++ b/Task/Send-email/Emacs-Lisp/send-email.l @@ -0,0 +1,13 @@ +(defun my-send-email (from to cc subject text) + (with-temp-buffer + (insert "From: " from "\n" + "To: " to "\n" + "Cc: " cc "\n" + "Subject: " subject "\n" + mail-header-separator "\n" + text) + (funcall send-mail-function))) + +(my-send-email "from@example.com" "to@example.com" "" + "very important" + "body\ntext\n") diff --git a/Task/Send-email/Go/send-email.go b/Task/Send-email/Go/send-email.go new file mode 100644 index 0000000000..217233450d --- /dev/null +++ b/Task/Send-email/Go/send-email.go @@ -0,0 +1,161 @@ +package main + +import ( + "bufio" + "bytes" + "errors" + "flag" + "fmt" + "io/ioutil" + "net/smtp" + "os" + "strings" +) + +type Message struct { + From string + To []string + Cc []string + Subject string + Content string +} + +func (m Message) Bytes() (r []byte) { + to := strings.Join(m.To, ",") + cc := strings.Join(m.Cc, ",") + + r = append(r, []byte("From: "+m.From+"\n")...) + r = append(r, []byte("To: "+to+"\n")...) + r = append(r, []byte("Cc: "+cc+"\n")...) + r = append(r, []byte("Subject: "+m.Subject+"\n\n")...) + r = append(r, []byte(m.Content)...) + + return +} + +func (m Message) Send(host string, port int, user, pass string) (err error) { + err = check(host, user, pass) + if err != nil { + return + } + + err = smtp.SendMail(fmt.Sprintf("%v:%v", host, port), + smtp.PlainAuth("", user, pass, host), + m.From, + m.To, + m.Bytes(), + ) + + return +} + +func check(host, user, pass string) error { + if host == "" { + return errors.New("Bad host") + } + if user == "" { + return errors.New("Bad username") + } + if pass == "" { + return errors.New("Bad password") + } + + return nil +} + +func main() { + var flags struct { + host string + port int + user string + pass string + } + flag.StringVar(&flags.host, "host", "", "SMTP server to connect to") + flag.IntVar(&flags.port, "port", 587, "Port to connect to SMTP server on") + flag.StringVar(&flags.user, "user", "", "Username to authenticate with") + flag.StringVar(&flags.pass, "pass", "", "Password to authenticate with") + flag.Parse() + + err := check(flags.host, flags.user, flags.pass) + if err != nil { + flag.Usage() + os.Exit(1) + } + + bufin := bufio.NewReader(os.Stdin) + + fmt.Printf("From: ") + from, err := bufin.ReadString('\n') + if err != nil { + fmt.Printf("Error: %v\n", err) + os.Exit(1) + } + from = strings.Trim(from, " \t\n\r") + + var to []string + for { + fmt.Printf("To (Blank to finish): ") + tmp, err := bufin.ReadString('\n') + if err != nil { + fmt.Printf("Error: %v\n", err) + os.Exit(1) + } + tmp = strings.Trim(tmp, " \t\n\r") + + if tmp == "" { + break + } + + to = append(to, tmp) + } + + var cc []string + for { + fmt.Printf("Cc (Blank to finish): ") + tmp, err := bufin.ReadString('\n') + if err != nil { + fmt.Printf("Error: %v\n", err) + os.Exit(1) + } + tmp = strings.Trim(tmp, " \t\n\r") + + if tmp == "" { + break + } + + cc = append(cc, tmp) + } + + fmt.Printf("Subject: ") + subject, err := bufin.ReadString('\n') + if err != nil { + fmt.Printf("Error: %v\n", err) + os.Exit(1) + } + subject = strings.Trim(subject, " \t\n\r") + + fmt.Printf("Content (Until EOF):\n") + content, err := ioutil.ReadAll(os.Stdin) + if err != nil { + fmt.Printf("Error: %v\n", err) + os.Exit(1) + } + content = bytes.Trim(content, " \t\n\r") + + m := Message{ + From: from, + To: to, + Cc: cc, + Subject: subject, + Content: string(content), + } + + fmt.Printf("\nSending message...\n") + err = m.Send(flags.host, flags.port, flags.user, flags.pass) + if err != nil { + fmt.Printf("Error: %v\n", err) + os.Exit(1) + } + + fmt.Printf("Message sent.\n") +} diff --git a/Task/Send-email/Groovy/send-email-1.groovy b/Task/Send-email/Groovy/send-email-1.groovy new file mode 100644 index 0000000000..cca0f16d34 --- /dev/null +++ b/Task/Send-email/Groovy/send-email-1.groovy @@ -0,0 +1,47 @@ +import javax.mail.* +import javax.mail.internet.* + +public static void simpleMail(String from, String password, String to, + String subject, String body) throws Exception { + + String host = "smtp.gmail.com"; + Properties props = System.getProperties(); + props.put("mail.smtp.starttls.enable",true); + /* mail.smtp.ssl.trust is needed in script to avoid error "Could not convert socket to TLS" */ + props.setProperty("mail.smtp.ssl.trust", host); + props.put("mail.smtp.auth", true); + props.put("mail.smtp.host", host); + props.put("mail.smtp.user", from); + props.put("mail.smtp.password", password); + props.put("mail.smtp.port", "587"); + + Session session = Session.getDefaultInstance(props, null); + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress(from)); + + InternetAddress toAddress = new InternetAddress(to); + + message.addRecipient(Message.RecipientType.TO, toAddress); + + message.setSubject(subject); + message.setText(body); + + Transport transport = session.getTransport("smtp"); + + transport.connect(host, from, password); + + transport.sendMessage(message, message.getAllRecipients()); + transport.close(); +} + +/* Set email address sender */ +String s1 = "example@gmail.com"; + +/* Set password sender */ +String s2 = ""; + +/* Set email address sender */ +String s3 = "example@gmail.com" + +/*Call function */ +simpleMail(s1, s2 , s3, "TITLE", "TEXT"); diff --git a/Task/Send-email/Groovy/send-email-2.groovy b/Task/Send-email/Groovy/send-email-2.groovy new file mode 100644 index 0000000000..fb1360862f --- /dev/null +++ b/Task/Send-email/Groovy/send-email-2.groovy @@ -0,0 +1,7 @@ +procedure main(args) + mail := open("mailto:"||args[1], "m", "Subject : "||args[2], + "X-Note: automatically send by Unicon") | + stop("Cannot send mail to ",args[1]) + every write(mail , !&input) + close (mail) +end diff --git a/Task/Send-email/Perl/send-email-4.pl b/Task/Send-email/Perl/send-email-4.pl new file mode 100644 index 0000000000..7a662cf1dd --- /dev/null +++ b/Task/Send-email/Perl/send-email-4.pl @@ -0,0 +1,22 @@ +use strict; +use LWP::UserAgent; +use HTTP::Request; + +sub send_email { + my ($from, $to, $cc, $subject, $text) = @_; + + my $ua = LWP::UserAgent->new; + my $req = HTTP::Request->new (POST => "mailto:$to", + [ From => $from, + Cc => $cc, + Subject => $subject ], + $text); + my $resp = $ua->request($req); + if (! $resp->is_success) { + print $resp->status_line,"\n"; + } +} + +send_email('from-me@example.com', 'to-foo@example.com', '', + "very important subject", + "Body text\n"); diff --git a/Task/Send-email/VBScript/send-email.vb b/Task/Send-email/VBScript/send-email.vb new file mode 100644 index 0000000000..5b3ebffd31 --- /dev/null +++ b/Task/Send-email/VBScript/send-email.vb @@ -0,0 +1,20 @@ +Function send_mail(from,recipient,cc,subject,message) + With CreateObject("CDO.Message") + .From = from + .To = recipient + .CC = cc + .Subject = subject + .Textbody = message + .Configuration.Fields.Item _ + ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 + .Configuration.Fields.Item _ + ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _ + "mystmpserver" + .Configuration.Fields.Item _ + ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 + .Configuration.Fields.Update + .Send + End With +End Function + +Call send_mail("Alerts@alerts.org","jkspeed@jkspeed.org","","Test Email","this is a test message") diff --git a/Task/Sequence-of-non-squares/Eiffel/sequence-of-non-squares.e b/Task/Sequence-of-non-squares/Eiffel/sequence-of-non-squares.e index 618c6d472f..ff348b0667 100644 --- a/Task/Sequence-of-non-squares/Eiffel/sequence-of-non-squares.e +++ b/Task/Sequence-of-non-squares/Eiffel/sequence-of-non-squares.e @@ -1,42 +1,43 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - do - non_square(22) - end + do + sequence_of_non_squares (22) + io.new_line + sequence_of_non_squares (1000000) + end - non_square(n:INTEGER) - require - n_positive: n>=1 - local - i: INTEGER - non_sq, part: REAL_64 - math: DOUBLE_MATH - square: BOOLEAN - do - create math - from - i:= 1 - until - i> n - loop - part:=(0.5+math.sqrt (i.to_double)) - non_sq:= i+part.floor - io.put_string (non_sq.out + " ") - if math.sqrt (non_sq)-math.sqrt (non_sq).floor=0 then - square:= True + sequence_of_non_squares (n: INTEGER) + -- Sequence of non-squares up to the n'th member. + require + n_positive: n >= 1 + local + non_sq, part: REAL_64 + math: DOUBLE_MATH + square: BOOLEAN + do + create math + across + 1 |..| (n) as c + loop + part := (0.5 + math.sqrt (c.item.to_double)) + non_sq := c.item + part.floor + io.put_string (non_sq.out + "%N") + if math.sqrt (non_sq) - math.sqrt (non_sq).floor = 0 then + square := True + end + end + if square = True then + io.put_string ("There are squares for n equal to " + n.out + ".") + else + io.put_string ("There are no squares for n equal to " + n.out + ".") end - i:= i+1 - end - if square= TRUE then - io.put_string ("%NThere are squares for n equal to "+ n.out + "." ) - else - io.put_string ("%NThere are no squares for n equal to "+ n.out + ".") end - end + end diff --git a/Task/Sequence-of-non-squares/J/sequence-of-non-squares.j b/Task/Sequence-of-non-squares/J/sequence-of-non-squares.j index 6aca38b57e..50946f312a 100644 --- a/Task/Sequence-of-non-squares/J/sequence-of-non-squares.j +++ b/Task/Sequence-of-non-squares/J/sequence-of-non-squares.j @@ -1,4 +1,4 @@ - rf=:+ 0.5 <.@+ %: NB. Remarkable formula + rf=: + 0.5 <.@+ %: NB. Remarkable formula rf 1+i.22 NB. Results from 1 to 22 2 3 5 6 7 8 10 11 12 13 14 15 17 18 19 20 21 22 23 24 26 27 diff --git a/Task/Sequence-of-non-squares/JavaScript/sequence-of-non-squares.js b/Task/Sequence-of-non-squares/JavaScript/sequence-of-non-squares.js new file mode 100644 index 0000000000..d765308b57 --- /dev/null +++ b/Task/Sequence-of-non-squares/JavaScript/sequence-of-non-squares.js @@ -0,0 +1,7 @@ +var a = []; +for (var i = 1; i < 23; i++) a[i] = i + Math.floor(1/2 + Math.sqrt(i)); +console.log(a); + +for (i = 1; i < 1000000; i++) if (Number.isInteger(i + Math.floor(1/2 + Math.sqrt(i))) === false) { + console.log("The ",i,"th element of the sequence is a square"); +} diff --git a/Task/Sequence-of-non-squares/PHP/sequence-of-non-squares.php b/Task/Sequence-of-non-squares/PHP/sequence-of-non-squares.php new file mode 100644 index 0000000000..bd6cc5a559 --- /dev/null +++ b/Task/Sequence-of-non-squares/PHP/sequence-of-non-squares.php @@ -0,0 +1,21 @@ + diff --git a/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx b/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx index 3014021735..a88ff3acbc 100644 --- a/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx +++ b/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx @@ -1,6 +1,6 @@ -/*REXX program displays some non─square numbers (with validation check).*/ +/*REXX program displays some non─square numbers (with a validation check). */ do j=1 for 22 - say right(j,6) right(j+floor(1/2 + sqrt(j)),7) + say right(j, 6) right(j + floor(1/2 + sqrt(j)), 7) end /*j*/ oops=0 do k=1 for 1000000-1 @@ -9,19 +9,19 @@ oops=0 if iroot*iroot==n then oops=oops+1 end /*k*/ say -say oops 'squares found up to' k-1 -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FLOOR subroutine────────────────────*/ +say oops 'squares found up to' k-1 +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ floor: procedure; parse arg x; return trunc(x- (x<0) ) -/*──────────────────────────────────ISQRT subroutine────────────────────*/ +/*────────────────────────────────────────────────────────────────────────────*/ isqrt: procedure; parse arg x; x=trunc(x); r=0; q=1 - do while q<=x; q=q*4; end - do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do; x=_;r=r+q;end;end -return r /*return the integer square root of X. */ -/*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure; parse arg x,f; if x=0 then return 0; d=digits() -numeric digits 11; g=x/4; m.=11; p=d+d%4+2 - do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k;g=.5*(g+x/g); end -numeric digits d -return g/1 /*return the normalized square root of X.*/ + do while q<=x; q=q*4; end + do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do; x=_;r=r+q;end;end + return r /*return the integer square root of X.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Sequence-of-non-squares/Rust/sequence-of-non-squares.rust b/Task/Sequence-of-non-squares/Rust/sequence-of-non-squares.rust new file mode 100644 index 0000000000..0c78a8df7e --- /dev/null +++ b/Task/Sequence-of-non-squares/Rust/sequence-of-non-squares.rust @@ -0,0 +1,14 @@ +fn f(n: i64) -> i64 { + n + (0.5 + (n as f64).sqrt()) as i64 +} + +fn is_sqr(n: i64) -> bool { + let a = (n as f64).sqrt() as i64; + n == a * a || n == (a+1) * (a+1) || n == (a-1) * (a-1) +} + +fn main() { + println!( "{:?}", (1..23).map(|n| f(n)).collect::>() ); + let count = (1..1_000_000).map(|n| f(n)).filter(|&n| is_sqr(n)).count(); + println!("{} unexpected squares found", count); +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/C++/sequence-of-primes-by-trial-division.cpp b/Task/Sequence-of-primes-by-Trial-Division/C++/sequence-of-primes-by-trial-division.cpp new file mode 100644 index 0000000000..370923bdfb --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/C++/sequence-of-primes-by-trial-division.cpp @@ -0,0 +1,30 @@ +#include +#include +#include + +bool isPrime( unsigned u ) { + if( u < 4 ) return u > 1; + if( /*!( u % 2 ) ||*/ !( u % 3 ) ) return false; + + unsigned q = static_cast( sqrt( static_cast( u ) ) ), + c = 5; + while( c <= q ) { + if( !( u % c ) || !( u % ( c + 2 ) ) ) return false; + c += 6; + } + return true; +} +int main( int argc, char* argv[] ) +{ + unsigned mx = 100000000, + wid = static_cast( log10( static_cast( mx ) ) ) + 1; + + std::cout << "[" << std::setw( wid ) << 2 << " "; + unsigned u = 3, p = 1; // <- start computing from 3 + while( u < mx ) { + if( isPrime( u ) ) { std::cout << std::setw( wid ) << u << " "; p++; } + u += 2; + } + std::cout << "]\n\n Found " << p << " primes.\n\n"; + return 0; +} diff --git a/Task/Sequence-of-primes-by-Trial-Division/Eiffel/sequence-of-primes-by-trial-division.e b/Task/Sequence-of-primes-by-Trial-Division/Eiffel/sequence-of-primes-by-trial-division.e new file mode 100644 index 0000000000..f2a0d112b8 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Eiffel/sequence-of-primes-by-trial-division.e @@ -0,0 +1,72 @@ +class + APPLICATION + +create + make + +feature + + make + do + sequence (1, 27) + end + + sequence (lower, upper: INTEGER) + -- Sequence of primes from 'lower' to 'upper'. + require + lower_positive: lower > 0 + upper_positive: upper > 0 + lower_smaller: lower < upper + local + i: INTEGER + do + io.put_string ("Sequence of primes from " + lower.out + " up to " + upper.out + ".%N") + i := lower + if i \\ 2 = 0 then + i := i + 1 + end + from + until + i > upper + loop + if is_prime (i) then + io.put_integer (i) + io.put_new_line + end + i := i + 2 + end + end + +feature {NONE} + + is_prime (n: INTEGER): BOOLEAN + -- Is 'n' a prime number? + require + positiv_input: n > 0 + local + i: INTEGER + max: REAL_64 + math: DOUBLE_MATH + do + create math + if n = 2 then + Result := True + elseif n <= 1 or n \\ 2 = 0 then + Result := False + else + Result := True + max := math.sqrt (n) + from + i := 3 + until + i > max + loop + if n \\ i = 0 then + Result := False + end + i := i + 2 + end + end + end + +end diff --git a/Task/Sequence-of-primes-by-Trial-Division/Fortran/sequence-of-primes-by-trial-division.f b/Task/Sequence-of-primes-by-Trial-Division/Fortran/sequence-of-primes-by-trial-division.f new file mode 100644 index 0000000000..0a61897415 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Fortran/sequence-of-primes-by-trial-division.f @@ -0,0 +1,45 @@ +CONCOCTED BY R.N.MCLEAN, APPLIED MATHS COURSE, AUCKLAND UNIVERSITY, MCMLXXI. + INTEGER ENUFF,PRIME(44) +CALCULATION SHOWS PRIME(43) = 181, AND PRIME(44) = 191. + INTEGER N,F,Q,XP2 + INTEGER INC,IP,LP,PP + INTEGER ALINE(20),LL,I + DATA ENUFF/44/ + DATA PP/4/ + DATA PRIME(1),PRIME(2),PRIME(3),PRIME(4)/1,2,3,5/ +COPY THE KNOWN PRIMES TO THE OUTPUT LINE. + DO 1 I = 1,PP + 1 ALINE(I) = PRIME(I) + LL = PP + LP = 3 + XP2 = PRIME(LP + 1)**2 + N = 5 + INC = 4 +CONSIDER ANOTHER CANDIDATE. VIA INC, DODGE MULTIPLES OF 2 AND 3. + 10 INC = 6 - INC + N = N + INC + IF (N - XP2) 20,11,20 + 11 LP = LP + 1 + XP2 = PRIME(LP + 1)**2 + GO TO 40 +CHECK SUCCESSIVE PRIMES AS FACTORS, STARTING WITH PRIME(4) = 5. + 20 IP = 4 + 21 F = PRIME(IP) + Q = N/F + IF (Q*F - N) 22,40,22 + 22 IP = IP + 1 + IF (IP - LP) 21,21,30 +CAUGHT ANOTHER PRIME. + 30 IF (PP - ENUFF) 31,32,32 + 31 PP = PP + 1 + PRIME(PP) = N + 32 IF (LL - 20) 35,33,33 + 33 WRITE (6,34) (ALINE(I), I = 1,LL) + 34 FORMAT (20I6) + LL = 0 + 35 LL = LL + 1 + ALINE(LL) = N +COMPLETED? + 40 IF (N - 32767) 10,41,41 + 41 WRITE (6,34) (ALINE(I), I = 1,LL) + END 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 index ebbc9d635d..7230ff909a 100644 --- 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 @@ -18,13 +18,11 @@ func Filter(in <-chan int, out chan<- int, prime int) { } 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++ { @@ -32,18 +30,23 @@ func Sieve(out chan<- int) { if n < q { out <- n // n is prime } else { - ch1 := make(chan int) - go Filter(nums, ch1, p) // postponed creation of a filter + ch1 := make(chan int) // n == q == p*p + go Filter(nums, ch1, p) // creation of a filter by p, at p*p nums = ch1 - p = <-ps - q = p*p + p = <-ps // next prime + q = p*p // and its square } } } +func primes (c chan<- int) { + c <- 2 + go Sieve(c) +} + func main() { ch := make(chan int) - go Sieve(ch) + go primes(ch) fmt.Print("First twenty:") for i := 0; i < 20; i++ { fmt.Print(" ", <-ch) 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 index ce1d956e4a..62a5e6ede6 100644 --- 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 @@ -3,6 +3,6 @@ primesPT = 2 : 3 : sieve [5,7..] 9 (tail primesPT) 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)) +-- fix $ (2:) . concatMap (fst.snd) +-- . iterate (\(p:t,(h,xs)) -> (t,span (< head t^2) [y | y <- xs, rem y p /= 0])) +-- . (, ([3],[4..])) diff --git a/Task/Sequence-of-primes-by-Trial-Division/Julia/sequence-of-primes-by-trial-division.julia b/Task/Sequence-of-primes-by-Trial-Division/Julia/sequence-of-primes-by-trial-division.julia new file mode 100644 index 0000000000..f85b21bd6e --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Julia/sequence-of-primes-by-trial-division.julia @@ -0,0 +1,38 @@ +type TDPrimes{T<:Integer} + plim::T +end + +function Base.start{T<:Integer}(pl::TDPrimes{T}) + 2ones(T, 1) +end + +function Base.done{T<:Integer}(pl::TDPrimes{T}, p::Array{T,1}) + p[end] > pl.plim +end + +function Base.next{T<:Integer}(pl::TDPrimes{T}, p::Array{T,1}) + pr = p[end] + for i in (pr+1):(pl.plim) + ispr = true + for j in p + if i%j == 0 + ispr = false + break + end + end + if ispr + push!(p, i) + return (pr, p) + end + end + push!(p, typemax(T)) + return (pr, p) +end + +n = 100 +print("The primes <= ", n, " are:\n ") + +for i in TDPrimes(n) + print(i, " ") +end +println() diff --git a/Task/Sequence-of-primes-by-Trial-Division/MATLAB/sequence-of-primes-by-trial-division.m b/Task/Sequence-of-primes-by-Trial-Division/MATLAB/sequence-of-primes-by-trial-division.m new file mode 100644 index 0000000000..e2e8acb011 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/MATLAB/sequence-of-primes-by-trial-division.m @@ -0,0 +1,15 @@ +function primeList = sieveOfEratosthenes(lastNumber) + + list = (2:lastNumber); %Construct list of numbers + primeList = []; %Preallocate prime list + + while( list(1)^2 1)); /* Handle negatives */ + forprime(p=2,sqrt(n), + if(n%p == 0, return(0)) + ); + 1 +}; + +select(trial, [1..100]) diff --git a/Task/Sequence-of-primes-by-Trial-Division/Pascal/sequence-of-primes-by-trial-division.pascal b/Task/Sequence-of-primes-by-Trial-Division/Pascal/sequence-of-primes-by-trial-division.pascal new file mode 100644 index 0000000000..fa76756f89 --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Pascal/sequence-of-primes-by-trial-division.pascal @@ -0,0 +1,12 @@ +program PrimeRng; +uses + primTrial; +var + Range : ptPrimeList; + i : integer; +Begin + Range := PrimeRange(1000*1000*1000,1000*1000*1000+100); + For i := Low(Range) to High(Range) do + write(Range[i]:12); + writeln; +end. diff --git a/Task/Sequence-of-primes-by-Trial-Division/Perl/sequence-of-primes-by-trial-division.pl b/Task/Sequence-of-primes-by-Trial-Division/Perl/sequence-of-primes-by-trial-division.pl new file mode 100644 index 0000000000..73d14a513c --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Perl/sequence-of-primes-by-trial-division.pl @@ -0,0 +1,13 @@ +sub isprime { + my $n = shift; + return ($n >= 2) if $n < 4; + return unless $n % 2 && $n % 3; + my $sqrtn = int(sqrt($n)); + for (my $i = 5; $i <= $sqrtn; $i += 6) { + return unless $n % $i && $n % ($i+2); + } + 1; +} + +print join(" ", grep { isprime($_) } 0 .. 100 ), "\n"; +print join(" ", grep { isprime($_) } 12345678 .. 12345678+100 ), "\n"; diff --git a/Task/Sequence-of-primes-by-Trial-Division/PowerShell/sequence-of-primes-by-trial-division.psh b/Task/Sequence-of-primes-by-Trial-Division/PowerShell/sequence-of-primes-by-trial-division.psh new file mode 100644 index 0000000000..09a989e5dc --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/PowerShell/sequence-of-primes-by-trial-division.psh @@ -0,0 +1,22 @@ +function eratosthenes ($n) { + if($n -ge 1){ + $prime = @(1..($n+1) | foreach{$true}) + $prime[1] = $false + $m = [Math]::Floor([Math]::Sqrt($n)) + for($i = 2; $i -le $m; $i++) { + if($prime[$i]) { + for($j = $i*$i; $j -le $n; $j += $i) { + $prime[$j] = $false + } + } + } + 1..$n | where{$prime[$_]} + } else { + "$n must be equal or greater than 1" + } +} +function sieve-start-end ($start,$end) { + (eratosthenes $end) | where{$_ -ge $start} + +} +"$(sieve-start-end 100 200)" diff --git a/Task/Sequence-of-primes-by-Trial-Division/Python/sequence-of-primes-by-trial-division.py b/Task/Sequence-of-primes-by-Trial-Division/Python/sequence-of-primes-by-trial-division.py new file mode 100644 index 0000000000..e90f2d900a --- /dev/null +++ b/Task/Sequence-of-primes-by-Trial-Division/Python/sequence-of-primes-by-trial-division.py @@ -0,0 +1,5 @@ +def prime(a): + return not (a < 2 or any(a % x == 0 for x in xrange(2, int(a**0.5) + 1))) + +def primes_below(n): + return [i for i in range(n) if prime(i)] diff --git a/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx b/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx index 870b630d4e..ef95231930 100644 --- a/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx +++ b/Task/Sequence-of-primes-by-Trial-Division/REXX/sequence-of-primes-by-trial-division-2.rexx @@ -1,26 +1,27 @@ -/*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.*/ +/*REXX pgm lists a sequence of primes by testing primality by trial division.*/ +parse arg n . /*get optional number of primes to find*/ +if n=='' then n=26 /*Not specified? Then assume default.*/ +tell=n>0; n=abs(n) /*N is negative? Then 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 # %s" % [str, e] (0..2).each{|i| puts " #{i} : #{e.include?(i)}"} end @@ -41,5 +41,5 @@ puts inf = 1.0 / 0.0 # infinity puts "a = #{a = Rset(-inf,inf)}" -puts "b = #{b = Rset.from_s('[1/3,11/7)')}" +puts "b = #{b = Rset.parse('[1/3,11/7)')}" puts "a - b -> #{a - b}" diff --git a/Task/Set-puzzle/C++/set-puzzle.cpp b/Task/Set-puzzle/C++/set-puzzle.cpp new file mode 100644 index 0000000000..b1dbd6310d --- /dev/null +++ b/Task/Set-puzzle/C++/set-puzzle.cpp @@ -0,0 +1,131 @@ +#include +#include +#include +#include +#include +#include + +enum color { + red, green, purple +}; +enum symbol { + oval, squiggle, diamond +}; +enum number { + one, two, three +}; +enum shading { + solid, open, striped +}; +class card { +public: + card( color c, symbol s, number n, shading h ) { + clr = c; smb = s; nbr = n; shd = h; + } + color getColor() { + return clr; + } + symbol getSymbol() { + return smb; + } + number getNumber() { + return nbr; + } + shading getShading() { + return shd; + } + std::string toString() { + std::string str = "["; + str += clr == red ? "red " : clr == green ? "green " : "purple "; + str += nbr == one ? "one " : nbr == two ? "two " : "three "; + str += smb == oval ? "oval " : smb == squiggle ? "squiggle " : "diamond "; + str += shd == solid ? "solid" : shd == open ? "open" : "striped"; + return str + "]"; + } +private: + color clr; + symbol smb; + number nbr; + shading shd; +}; +typedef struct { + std::vector index; +} set; +class setPuzzle { +public: + setPuzzle() { + for( size_t c = red; c <= purple; c++ ) { + for( size_t s = oval; s <= diamond; s++ ) { + for( size_t n = one; n <= three; n++ ) { + for( size_t h = solid; h <= striped; h++ ) { + card crd( static_cast ( c ), + static_cast ( s ), + static_cast ( n ), + static_cast( h ) ); + _cards.push_back( crd ); + } + } + } + } + } + void create( size_t countCards, size_t countSets, std::vector& cards, std::vector& sets ) { + while( true ) { + sets.clear(); + cards.clear(); + std::random_shuffle( _cards.begin(), _cards.end() ); + for( size_t f = 0; f < countCards; f++ ) { + cards.push_back( _cards.at( f ) ); + } + for( size_t c1 = 0; c1 < cards.size() - 2; c1++ ) { + for( size_t c2 = c1 + 1; c2 < cards.size() - 1; c2++ ) { + for( size_t c3 = c2 + 1; c3 < cards.size(); c3++ ) { + if( testSet( &cards.at( c1 ), &cards.at( c2 ), &cards.at( c3 ) ) ) { + set s; + s.index.push_back( c1 ); s.index.push_back( c2 ); s.index.push_back( c3 ); + sets.push_back( s ); + } + } + } + } + if( sets.size() == countSets ) return; + } + } +private: + bool testSet( card* c1, card* c2, card* c3 ) { + int + c = ( c1->getColor() + c2->getColor() + c3->getColor() ) % 3, + s = ( c1->getSymbol() + c2->getSymbol() + c3->getSymbol() ) % 3, + n = ( c1->getNumber() + c2->getNumber() + c3->getNumber() ) % 3, + h = ( c1->getShading() + c2->getShading() + c3->getShading() ) % 3; + return !( c + s + n + h ); + } + std::vector _cards; +}; +void displayCardsSets( std::vector& cards, std::vector& sets ) { + size_t cnt = 1; + std::cout << " ** DEALT " << cards.size() << " CARDS: **\n"; + for( std::vector::iterator i = cards.begin(); i != cards.end(); i++ ) { + std::cout << std::setw( 2 ) << cnt++ << ": " << ( *i ).toString() << "\n"; + } + std::cout << "\n ** CONTAINING " << sets.size() << " SETS: **\n"; + for( std::vector::iterator i = sets.begin(); i != sets.end(); i++ ) { + for( size_t j = 0; j < ( *i ).index.size(); j++ ) { + std::cout << " " << std::setiosflags( std::ios::left ) << std::setw( 34 ) + << cards.at( ( *i ).index.at( j ) ).toString() << " : " + << std::resetiosflags( std::ios::left ) << std::setw( 2 ) << ( *i ).index.at( j ) + 1 << "\n"; + } + std::cout << "\n"; + } + std::cout << "\n\n"; +} +int main( int argc, char* argv[] ) { + srand( static_cast( time( NULL ) ) ); + setPuzzle p; + std::vector v9, v12; + std::vector s4, s6; + p.create( 9, 4, v9, s4 ); + p.create( 12, 6, v12, s6 ); + displayCardsSets( v9, s4 ); + displayCardsSets( v12, s6 ); + return 0; +} diff --git a/Task/Set-puzzle/Haskell/set-puzzle.hs b/Task/Set-puzzle/Haskell/set-puzzle.hs new file mode 100644 index 0000000000..4894002ad3 --- /dev/null +++ b/Task/Set-puzzle/Haskell/set-puzzle.hs @@ -0,0 +1,75 @@ +import Data.List +import System.Random +import Control.Monad.State + +combinations :: Int -> [a] -> [[a]] +combinations 0 _ = [[]] +combinations _ [] = [] +combinations k (y:ys) = map (y:) (combinations (k - 1) ys) ++ combinations k ys + +data Color = Red | Green | Purple deriving (Show, Enum, Bounded, Ord, Eq) +data Symbol = Oval | Squiggle | Diamond deriving (Show, Enum, Bounded, Ord, Eq) +data Count = One | Two | Three deriving (Show, Enum, Bounded, Ord, Eq) +data Shading = Solid | Open | Striped deriving (Show, Enum, Bounded, Ord, Eq) + +data Card = Card { + color :: Color, + symbol :: Symbol, + count :: Count, + shading :: Shading + } deriving (Show) + +-- Identify a set of three cards by counting all attribute types. +-- if each count is 3 or 1 ( not 2 ) the the cards compose a set. +isSet :: [Card] -> Bool +isSet cs = + let colorCount = length $ nub $ sort $ map color cs + symbolCount = length $ nub $ sort $ map symbol cs + countCount = length $ nub $ sort $ map count cs + shadingCount = length $ nub $ sort $ map shading cs + in colorCount /= 2 && symbolCount /= 2 && countCount /= 2 && shadingCount /= 2 + +-- Get a random card from a deck. Returns the card and removes it from the deck. +getCard :: State (StdGen, [Card]) Card +getCard = state $ \(gen, cs) -> let (i, newGen) = randomR (0, length cs - 1) gen + (a,b) = splitAt i cs + in (head b, (newGen, a ++ tail b)) + +-- Get a hand of cards. Starts with new deck and then removes the +-- appropriate number of cards from that deck. +getHand :: Int -> State StdGen [Card] +getHand n = state $ \gen -> + let deck = [Card co sy ct sh | + co <- [minBound..maxBound], + sy <- [minBound..maxBound], + ct <- [minBound..maxBound], + sh <- [minBound..maxBound]] + (a,(newGen, _)) = runState (replicateM n getCard) (gen,deck) + in (a, newGen) + +-- Get an unbounded number of hands of the appropriate number of cards. +getManyHands :: Int -> State StdGen [[Card]] +getManyHands n = (sequence.repeat) (getHand n) + +-- Deal out hands of the appropriate size until one with the desired number +-- of sets is found. then print the hand and the sets. +showSolutions :: Int -> Int -> IO () +showSolutions cardCount solutionCount = do + putStrLn $ "Showing hand of " ++ show cardCount ++ " cards with " ++ show solutionCount ++ " solutions." + gen <- newStdGen + let Just z = find (\ls -> length (filter isSet $ combinations 3 ls) == solutionCount) $ + evalState (getManyHands cardCount) gen + mapM_ print z + putStrLn "" + putStrLn "Solutions:" + mapM_ putSet $ filter isSet $ combinations 3 z where + putSet st = do + mapM_ print st + putStrLn "" + +-- Show a hand of 9 cards with 4 solutions +-- and a hand of 12 cards with 6 solutions. +main :: IO () +main = do + showSolutions 9 4 + showSolutions 12 6 diff --git a/Task/Set-puzzle/J/set-puzzle-1.j b/Task/Set-puzzle/J/set-puzzle-1.j index 04362826d1..a017676773 100644 --- a/Task/Set-puzzle/J/set-puzzle-1.j +++ b/Task/Set-puzzle/J/set-puzzle-1.j @@ -9,7 +9,7 @@ Deck=: > ; <"1 { i.@#&.> Features sayCards=: (', ' joinstring Features {&>~ ])"1 drawRandom=: ] {~ (? #) isSet=: *./@:(1 3 e.~ [: #@~."1 |:)"2 -getSets=: ([: (] #~ isSet) ] {~ 3 comb #) +getSets=: [: (] #~ isSet) ] {~ 3 comb # countSets=: #@:getSets set_puzzle=: verb define diff --git a/Task/Set-puzzle/REXX/set-puzzle.rexx b/Task/Set-puzzle/REXX/set-puzzle.rexx index d87536e22c..ab42e18e7e 100644 --- a/Task/Set-puzzle/REXX/set-puzzle.rexx +++ b/Task/Set-puzzle/REXX/set-puzzle.rexx @@ -1,99 +1,99 @@ -/*REXX program finds "sets" (solutions) for the SET puzzle (game). */ -parse arg game seed . /*get optional # cards to deal. */ -if game ==',' | game=='' then game=9 /*Not specified? Then use default*/ -if seed==',' | seed=='' then seed=77 /* " " " " " */ -call aGame 0 /*with tell=0, suppress output. */ -call aGame 1 /*with tell=1, allow output. */ -exit sets /*stick a fork in it, we're done.*/ -/*──────────────────────────────────AGAME subroutine────────────────────*/ -aGame: tell=arg(1); good=game%2 /*enable or disable the output. */ - /* [↑] GOOD is the right # sets.*/ - do seed=seed until good==sets /*generate deals until good# sets*/ - call random ,,seed /*repeatability for last invoke. */ - call genFeatures /*generate various card features.*/ - call genDeck /*generate a deck (with 81 cards)*/ - call dealer game /*deal a number of cards (game). */ - call findSets game%2 /*find sets from the dealt cards.*/ - end /*until*/ /*when leaving, SETS is right num*/ -return /*return to invoker of this sub. */ -/*──────────────────────────────────DEALER subroutine───────────────────*/ -dealer: call sey 'dealing' game "cards:",,. /*shuffle and deal cards*/ - do cards=1 until cards==game /*keep dealing 'til done*/ - _=random(1,words(##)); ##=delword(##,_,1) /*pick card; delete it. */ - @.cards=deck._ /*add it to the tableau.*/ - call sey right('card' cards,30) " " @.cards /*display card to screen*/ - do j=1 for words(@.cards) /*define cells for card.*/ - @.cards.j=word(@.cards,j) /*define a cell for card*/ +/*REXX program finds "sets" (solutions) for the SET puzzle (game). */ +parse arg game seed . /*get optional # cards to deal and seed*/ +if game ==',' | game=='' then game=9 /*Not specified? Then use the default.*/ +if seed==',' | seed=='' then seed=77 /* " " " " " " */ +call aGame 0 /*with tell=0: suppress the output. */ +call aGame 1 /*with tell=1: display " " */ +exit sets /*stick a fork in it, we're all done. */ +/*──────────────────────────────────AGAME subroutine──────────────────────────*/ +aGame: tell=arg(1); good=game%2 /*enable/disable the showing of output.*/ + /* [↑] the GOOD var is the right #sets*/ + do seed=seed until good==sets /*generate deals until good # of sets.*/ + call random ,,seed /*repeatability for the RANDOM invokes.*/ + call genFeatures /*generate various card game features. */ + call genDeck /*generate a deck (with 81 "cards").*/ + call dealer game /*deal a number of cards for the game. */ + call findSets game%2 /*find # of sets from the dealt cards. */ + end /*until*/ /* [↓] when leaving, SETS is right #.*/ +return /*return to invoker of this subroutine.*/ +/*──────────────────────────────────DEALER subroutine─────────────────────────*/ +dealer: call sey 'dealing' game "cards:",,. /*shuffle and deal the cards. */ + do cards=1 until cards==game /*keep dealing until finished.*/ + _=random(1,words(##)); ##=delword(##,_,1) /*pick card; delete a card. */ + @.cards=deck._ /*add the card to the tableau.*/ + call sey right('card' cards,30) " " @.cards /*display the card to screen. */ + do j=1 for words(@.cards) /* [↓] define cells for cards*/ + @.cards.j=word(@.cards,j) /*define a cell for a card.*/ end /*j*/ end /*cards*/ return -/*──────────────────────────────────DEFFEATURES subroutine──────────────*/ -defFeatures: parse arg what,v; _=words(v) /*obtain what to define.*/ +/*──────────────────────────────────DEFFEATURES subroutine────────────────────*/ +defFeatures: parse arg what,v; _=words(v) /*obtain what is to be defined*/ if _\==values then do; call sey 'error,' what "features ¬=" values,.,. - exit -1 - end /* [↑] check for typos.*/ - do k=1 for words(values) /*define all possibles. */ - call value what'.'k, word(values,k) /*define a card feature.*/ + exit -1 + end /* [↑] check for typos/errors*/ + do k=1 for words(values) /*define all the possible vals*/ + call value what'.'k, word(values,k) /*define a card feature. */ end /*k*/ return -/*──────────────────────────────────GENDECK subroutine──────────────────*/ -genDeck: #=0; ##= /*#cards in deck; ##=shuffle aid.*/ - do num=1 for values; xnum=word(numbers, num) - do col=1 for values; xcol=word(colors, col) - do sym=1 for values; xsym=word(symbols, sym) - do sha=1 for values; xsha=word(shadings, sha) - #=#+1; ##=## #; deck.#=xnum xcol xsym xsha /*create a card.*/ +/*──────────────────────────────────GENDECK subroutine────────────────────────*/ +genDeck: #=0; ##= /*#: cards in deck; ##: shuffle aid.*/ + do num=1 for values; xnum = word(numbers, num) + do col=1 for values; xcol = word(colors, col) + do sym=1 for values; xsym = word(symbols, sym) + do sha=1 for values; xsha = word(shadings, sha) + #=#+1; ##=## #; deck.#=xnum xcol xsym xsha /*create a card.*/ end /*sha*/ end /*num*/ end /*sym*/ end /*col*/ -return /*#: the number of cards in deck.*/ -/*──────────────────────────────────GENFEATURES subroutine──────────────*/ -genFeatures: features=3; groups=4; values=3 /*define # feats,grps,vals*/ -numbers = 'one two three' ; call defFeatures 'number', numbers -colors = 'red green purple' ; call defFeatures 'color', colors -symbols = 'oval squiggle diamond' ; call defFeatures 'symbol', symbols -shadings= 'solid open striped' ; call defFeatures 'shading', shadings +return /*#: the number of cards in the deck. */ +/*──────────────────────────────────GENFEATURES subroutine────────────────────*/ +genFeatures: features=3; groups=4; values=3 /*define # features, groups, vals.*/ +numbers = 'one two three' ; call defFeatures 'number', numbers +colors = 'red green purple' ; call defFeatures 'color', colors +symbols = 'oval squiggle diamond' ; call defFeatures 'symbol', symbols +shadings= 'solid open striped' ; call defFeatures 'shading', shadings return -/*──────────────────────────────────GENPOSS subroutine──────────────────*/ -genPoss: p=0; sets=0; sep=' ───── '; !.= /*define some REXX variables.*/ - do i=1 for game /* [↓] the IFs eliminate dups.*/ - do j=i+1 to game; if j==i then iterate - do k=j+1 to game; if k==j | k==i then iterate - p=p+1; !.p.1=@.i; !.p.2=@.j; !.p.3=@.k +/*──────────────────────────────────GENPOSS subroutine────────────────────────*/ +genPoss: p=0; sets=0; sep=' ───── '; !.= /*define some REXX variables. */ + do i=1 for game /* [↓] the IFs eliminate duplicates.*/ + do j=i+1 to game + do k=j+1 to game + p=p+1; !.p.1=@.i; !.p.2=@.j; !.p.3=@.k end /*k*/ end /*j*/ - end /*i*/ /* [↑] build permutation list. */ + end /*i*/ /* [↑] generate the permutation list. */ return -/*──────────────────────────────────FINDSETS subroutine─────────────────*/ -findSets: parse arg n; call genPoss /*N: the number of sets to find.*/ -call sey /*find any sets generated above. */ - do j=1 for p /*P is the # of possible sets. */ +/*──────────────────────────────────FINDSETS subroutine───────────────────────*/ +findSets: parse arg n; call genPoss /*N: the number of sets to be found. */ +call sey /*find any sets that were generated [↑]*/ + do j=1 for p /*P: is the number of possible sets. */ do f=1 for features - do g=1 for groups; !!.j.f.g=word(!.j.f, g) + do g=1 for groups; !!.j.f.g=word(!.j.f, g) end /*g*/ end /*f*/ - ok=1 /*everything is OK so far. */ - do g=1 for groups; _=!!.j.1.g /*generate strings to hole poss. */ - equ=1 /* [↓] handles all equal feats. */ - do f=2 to features while equ; equ=equ & _==!!.j.f.g + ok=1 /*everything is peachy─kean (OK) so far*/ + do g=1 for groups; _=!!.j.1.g /*build strings to hold possibilities. */ + equ=1 /* [↓] handles all the equal features.*/ + do f=2 to features while equ; equ=equ & _==!!.j.f.g end /*f*/ dif=1 - __=!!.j.1.g /* [↓] handles all unequal feats*/ + __=!!.j.1.g /* [↓] handles all unequal features.*/ do f=2 to features while \equ - dif=dif & wordpos(!!.j.f.g,__)==0 - __=__ !!.j.f.g /*append to string for next test.*/ + dif=dif & (wordpos(!!.j.f.g,__)==0) + __=__ !!.j.f.g /*append to the string for next test. */ end /*f*/ - ok=ok&(equ|dif) /*now, see if all equal | unequal*/ + ok=ok & (equ | dif) /*now, see if all are equal or unequal.*/ end /*g*/ - if \ok then iterate /*Is this set OK? Nope, skip it.*/ - sets=sets+1 /*bump the number of sets found. */ - call sey right('set' sets": ",15) !.j.1 sep !.j.2 sep !.j.3 + if \ok then iterate /*Is this set OK? Nope, then skip it.*/ + sets=sets+1 /*bump the number of the sets found. */ + call sey right('set' sets": ",15) !.j.1 sep !.j.2 sep !.j.3 end /*j*/ -call sey sets 'sets found.',. +call sey sets 'sets found.',. return -/*──────────────────────────────────SEY subroutine──────────────────────*/ -sey: if \tell then return /*should output be suppressed? */ -if arg(2)==. then say; say arg(1); if arg(3)==. then say; return +/*──────────────────────────────────SEY subroutine────────────────────────────*/ +sey: if \tell then return /*¬ tell? Then suppress the output. */ +if arg(2)==. then say; say arg(1); if arg(3)==. then say; return diff --git a/Task/Set/Elixir/set.elixir b/Task/Set/Elixir/set.elixir new file mode 100644 index 0000000000..a5c6c1174a --- /dev/null +++ b/Task/Set/Elixir/set.elixir @@ -0,0 +1,26 @@ +iex(101)> s = HashSet.new +#HashSet<[]> +iex(102)> sa = Set.put(s, :a) +#HashSet<[:a]> +iex(103)> sab = Set.put(sa, :b) +#HashSet<[:b, :a]> +iex(104)> sbc = Enum.into([:b,:c], HashSet.new) +#HashSet<[:c, :b]> +iex(105)> Set.member?(sa, :a) +true +iex(106)> Set.member?(sa, :b) +false +iex(107)> Set.union(sab, sbc) +#HashSet<[:c, :b, :a]> +iex(108)> Set.intersection(sab, sbc) +#HashSet<[:b]> +iex(109)> Set.difference(sab, sbc) +#HashSet<[:a]> +iex(110)> Set.disjoint?(sab, sbc) +false +iex(111)> Set.subset?(sa, sab) +true +iex(112)> Set.subset?(sab, sa) +false +iex(113)> sa == sab +false diff --git a/Task/Set/Frink/set.frink b/Task/Set/Frink/set.frink new file mode 100644 index 0000000000..72b8d1c3dc --- /dev/null +++ b/Task/Set/Frink/set.frink @@ -0,0 +1,9 @@ +a = new set[1, 2] +b = toSet[[2,3]] // Construct a set from an array + +a.contains[2] // Element test (returns true) +union[a,b] +intersection[a,b] +setDifference[a,b] +isSubset[a,b] // Returns true if a is a subset of b +a==b // set equality test diff --git a/Task/Set/J/set-4.j b/Task/Set/J/set-4.j index 003746e134..8d4186357a 100644 --- a/Task/Set/J/set-4.j +++ b/Task/Set/J/set-4.j @@ -1 +1 @@ -properSubset=: subset *. 1 - equality +properSubset=: subset * 1 - equality diff --git a/Task/Set/JavaScript/set.js b/Task/Set/JavaScript/set.js new file mode 100644 index 0000000000..773cc7babc --- /dev/null +++ b/Task/Set/JavaScript/set.js @@ -0,0 +1,24 @@ +var set = new Set(); + +set.add(0); +set.add(1); +set.add('two'); +set.add('three'); + +set.has(0); //=> true +set.has(3); //=> false +set.has('two'); // true +set.has(Math.sqrt(4)); //=> true +set.has('TWO'.toLowerCase()); //=> true + +set.size; //=> 4 + +set.delete('two'); +set.has('two'); //==> false +set.size; //=> 3 + +//iterating set using ES6 for..of +//Set order is preserved in order items are added. +for (var item of set) { + console.log('item is ' + item); +} diff --git a/Task/Set/OCaml/set.ocaml b/Task/Set/OCaml/set.ocaml index 73811eb1c5..fa3360b6d6 100644 --- a/Task/Set/OCaml/set.ocaml +++ b/Task/Set/OCaml/set.ocaml @@ -27,18 +27,18 @@ module IntSet : val max_elt : t -> elt val choose : t -> elt val split : elt -> t -> t * bool * t + val find : elt -> t -> elt + val of_list : elt list -> t end # IntSet.empty;; (* Empty set. A set is an abstract type that will not display in the interpreter *) - : IntSet.t = # IntSet.elements (IntSet.empty);; (* Get the previous set into a list *) - : IntSet.elt list = [] -# let from_list lst = List.fold_right IntSet.add lst IntSet.empty;; (* Convenience function for constructing a set from a list *) -val from_list : IntSet.elt list -> IntSet.t = -# let s1 = from_list [1;2;3;4;3];; +# let s1 = IntSet.of_list [1;2;3;4;3];; val s1 : IntSet.t = # IntSet.elements s1;; - : IntSet.elt list = [1; 2; 3; 4] -# let s2 = from_list [3;4;5;6];; +# let s2 = IntSet.of_list [3;4;5;6];; val s2 : IntSet.t = # IntSet.elements s2;; - : IntSet.elt list = [3; 4; 5; 6] @@ -50,9 +50,9 @@ val s2 : IntSet.t = - : IntSet.elt list = [1; 2] # IntSet.subset s1 s1;; (* Subset *) - : bool = true -# IntSet.subset (from_list [3;1]) s1;; +# IntSet.subset (IntSet.of_list [3;1]) s1;; - : bool = true -# IntSet.equal (from_list [3;2;4;1]) s1;; (* Equality *) +# IntSet.equal (IntSet.of_list [3;2;4;1]) s1;; (* Equality *) - : bool = true # IntSet.equal s1 s2;; - : bool = false diff --git a/Task/Set/Rust/set.rust b/Task/Set/Rust/set.rust new file mode 100644 index 0000000000..277b4443de --- /dev/null +++ b/Task/Set/Rust/set.rust @@ -0,0 +1,15 @@ +use std::collections::HashSet; + +fn main() { + let a = vec![1, 3, 4].into_iter().collect::>(); + let b = vec![3, 5, 6].into_iter().collect::>(); + + println!("Set A: {:?}", a.iter().collect::>()); + println!("Set B: {:?}", b.iter().collect::>()); + println!("Does A contain 4? {}", a.contains(&4)); + println!("Union: {:?}", a.union(&b).collect::>()); + println!("Intersection: {:?}", a.intersection(&b).collect::>()); + println!("Difference: {:?}", a.difference(&b).collect::>()); + println!("Is A a subset of B? {}", a.is_subset(&b)); + println!("Is A equal to B? {}", a == b); +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/00DESCRIPTION b/Task/Seven-sided-dice-from-five-sided-dice/00DESCRIPTION index 7a4b8bb037..8b54219441 100644 --- a/Task/Seven-sided-dice-from-five-sided-dice/00DESCRIPTION +++ b/Task/Seven-sided-dice-from-five-sided-dice/00DESCRIPTION @@ -1,7 +1,7 @@ Given an equal-probability generator of one of the integers 1 to 5 as dice5; create dice7 that generates a pseudo-random integer from 1 to 7 in equal probability using only dice5 as a source of random -numbers, and check the distribution for at least 1000000 calls using the function created in [[Simple Random Distribution Checker]]. +numbers, and check the distribution for at least 1000000 calls using the function created in [[Verify distribution uniformity/Naive|Simple Random Distribution Checker]]. '''Implementation suggestion:''' dice7 might call dice5 twice, re-call if four of the 25 diff --git a/Task/Seven-sided-dice-from-five-sided-dice/C-sharp/seven-sided-dice-from-five-sided-dice.cs b/Task/Seven-sided-dice-from-five-sided-dice/C-sharp/seven-sided-dice-from-five-sided-dice.cs new file mode 100644 index 0000000000..a3f2d1aaa3 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/C-sharp/seven-sided-dice-from-five-sided-dice.cs @@ -0,0 +1,26 @@ +using System; + +public class SevenSidedDice +{ + Random random = new Random(); + + static void Main(string[] args) + { + SevenSidedDice sevenDice = new SevenSidedDice(); + Console.WriteLine("Random number from 1 to 7: "+ sevenDice.seven()); + Console.Read(); + } + + int seven() + { + int v=21; + while(v>20) + v=five()+five()*5-6; + return 1+v%7; + } + + int five() + { + return 1 + random.Next(5); + } +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Elixir/seven-sided-dice-from-five-sided-dice.elixir b/Task/Seven-sided-dice-from-five-sided-dice/Elixir/seven-sided-dice-from-five-sided-dice.elixir new file mode 100644 index 0000000000..70f2892627 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Elixir/seven-sided-dice-from-five-sided-dice.elixir @@ -0,0 +1,19 @@ +defmodule Dice do + def dice5, do: :random.uniform( 5 ) + + def dice7 do + dice7_from_dice5 + end + + def dice7_from_dice5 do + d55 = 5*dice5 + dice5 - 6 # 0..24 + if d55 < 21, do: rem( d55, 7 ) + 1, + else: dice7_from_dice5 + end +end + +:random.seed(:erlang.now) +fun5 = fn -> Dice.dice5 end +IO.inspect VerifyDistribution.naive( fun5, 1000000 ) +fun7 = fn -> Dice.dice7 end +IO.inspect VerifyDistribution.naive( fun7, 1000000 ) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Factor/seven-sided-dice-from-five-sided-dice.factor b/Task/Seven-sided-dice-from-five-sided-dice/Factor/seven-sided-dice-from-five-sided-dice.factor new file mode 100644 index 0000000000..d869712219 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Factor/seven-sided-dice-from-five-sided-dice.factor @@ -0,0 +1,57 @@ +USING: kernel random sequences assocs locals sorting prettyprint + math math.functions math.statistics math.vectors math.ranges ; +IN: rosetta-code.dice7 + +! Output a random integer 1..5. +: dice5 ( -- x ) + 5 [1,b] random +; + +! Output a random integer 1..7 using dice5 as randomness source. +: dice7 ( -- x ) + 0 [ dup 21 < ] [ drop dice5 5 * dice5 + 6 - ] do until + 7 rem 1 + +; + +! Roll the die by calling the quotation the given number of times and return +! an array with roll results. +! Sample call: 1000 [ dice7 ] roll +: roll ( times quot: ( -- x ) -- array ) + [ call( -- x ) ] curry replicate +; + +! Input array contains outcomes of a number of die throws. Each die result is +! an integer in the range 1..X. Calculate and return the number of each +! of the results in the array so that in the first position of the result +! there is the number of ones in the input array, in the second position +! of the result there is the number of twos in the input array, etc. +: count-dice-outcomes ( X array -- array ) + histogram + swap [1,b] [ over [ 0 or ] change-at ] each + sort-keys values +; + +! Verify distribution uniformity/Naive. Delta is the acceptable deviation +! from the ideal number of items in each bucket, expressed as a fraction of +! the total count. Sides is the number of die sides. Die-func is a word that +! produces a random number on stack in the range [1..sides], times is the +! number of times to call it. +! Sample call: 0.02 7 [ dice7 ] 100000 verify +:: verify ( delta sides die-func: ( -- random ) times -- ) + sides + times die-func roll + count-dice-outcomes + dup . + times sides / :> ideal-count + ideal-count v-n vabs + times v/n + delta [ < ] curry all? + [ "Random enough" . ] [ "Not random enough" . ] if +; + + +! Call verify with 1, 10, 100, ... 1000000 rolls of 7-sided die. +: verify-all ( -- ) + { 1 10 100 1000 10000 100000 1000000 } + [| times | 0.02 7 [ dice7 ] times verify ] each +; diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Forth/seven-sided-dice-from-five-sided-dice.fth b/Task/Seven-sided-dice-from-five-sided-dice/Forth/seven-sided-dice-from-five-sided-dice.fth new file mode 100644 index 0000000000..47dba4d0ac --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Forth/seven-sided-dice-from-five-sided-dice.fth @@ -0,0 +1,7 @@ +require random.fs + +: d5 5 random 1+ ; +: discard? 5 = swap 1 > and ; +: d7 + begin d5 d5 2dup discard? while 2drop repeat + 1- 5 * + 1- 7 mod 1+ ; diff --git a/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-3.j b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-3.j index 39141ac0ab..0bf1859c33 100644 --- a/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-3.j +++ b/Task/Seven-sided-dice-from-five-sided-dice/J/seven-sided-dice-from-five-sided-dice-3.j @@ -1,7 +1,7 @@ rollD7x=: monad define n=. */y NB. product of vector y is total number of D7 rolls required rolls=. '' NB. initialize empty noun rolls - while. n > #res do. NB. checks if if enough D7 rolls accumulated + while. n > #rolls do. NB. checks if if enough D7 rolls accumulated rolls=. rolls, getD7 >. 0.75 * n NB. calcs 3/4 of required rolls and accumulates getD7 rolls end. y $ rolls NB. shape the result according to the vector y diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Liberty-BASIC/seven-sided-dice-from-five-sided-dice.liberty b/Task/Seven-sided-dice-from-five-sided-dice/Liberty-BASIC/seven-sided-dice-from-five-sided-dice.liberty new file mode 100644 index 0000000000..dcf5050528 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Liberty-BASIC/seven-sided-dice-from-five-sided-dice.liberty @@ -0,0 +1,23 @@ +n=1000000 '1000000 would take several minutes +print "Testing ";n;" times" +if not(check(n, 0.05)) then print "Test failed" else print "Test passed" +end + +'function check(n, delta) is defined at +'http://rosettacode.org/wiki/Verify_distribution_uniformity/Naive#Liberty_BASIC + +function GENERATOR() + 'GENERATOR = int(rnd(0)*10) '0..9 + 'GENERATOR = 1+int(rnd(0)*5) '1..5: dice5 + + 'dice7() + do + temp =dice5() *5 +dice5() -6 + loop until temp <21 + GENERATOR =( temp mod 7) +1 + +end function + +function dice5() + dice5=1+int(rnd(0)*5) '1..5: dice5 +end function diff --git a/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx b/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx index 26498a468a..f67322017d 100644 --- a/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx +++ b/Task/Seven-sided-dice-from-five-sided-dice/REXX/seven-sided-dice-from-five-sided-dice.rexx @@ -1,22 +1,21 @@ -/*REXX program to simulate 7-sided die based on a 5-sided throw. */ -parse arg trials sample . /*get arguments from command line*/ -if trials=='' then trials=1 /*Not specified? Then use default*/ -if sample=='' then sample=1000000 /* " " " " " */ +/*REXX program simulate a 7─sided die based on a 5─sided throw. */ +parse arg trials sample . /*obtain optional arguments from the CL*/ +if trials=='' then trials=1 /*Not specified? Then use the default.*/ +if sample=='' then sample=1000000 /* " " " " " " */ - do t=1 for trials /*performe the number of trials. */ - die.=0; k=0 - do until k==sample; r=5*random(1,5)+random(1,5)-6 + do t=1 for trials /*performs the number of desired trials*/ + die.=0; k=0 + do until k==sample; r=5*random(1,5) + random(1,5) - 6 if r>20 then iterate - k=k+1; r=r//7+1; die.r=die.r+1 + k=k+1; r=r//7 + 1; die.r=die.r + 1 end /*until*/ - expect=sample%7 - say - say center('trial:'right(t,4) ' ' sample 'samples, expect='expect,79,'─') - say - - do j=1 for 7 - say ' side' j "had " die.j ' occurences', - ' difference from expected:'right(die.j-expect,length(sample)) - end /*j*/ - end /*t*/ - /*stick a fork in it, we're done.*/ + expect=sample%7 + say + say center('trial:'right(t,4) ' ' sample 'samples, expect='expect,79,'─') + say + do j=1 for 7 + say ' side' j "had " die.j ' occurrences', + ' difference from expected:'right(die.j-expect, length(sample)) + end /*j*/ + end /*t*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Shell-one-liner/AppleScript/shell-one-liner.applescript b/Task/Shell-one-liner/AppleScript/shell-one-liner.applescript new file mode 100644 index 0000000000..3fd2e834e5 --- /dev/null +++ b/Task/Shell-one-liner/AppleScript/shell-one-liner.applescript @@ -0,0 +1 @@ +osascript -e 'say "Hello, World!"' diff --git a/Task/Shell-one-liner/Elixir/shell-one-liner.elixir b/Task/Shell-one-liner/Elixir/shell-one-liner.elixir new file mode 100644 index 0000000000..ccfbe64876 --- /dev/null +++ b/Task/Shell-one-liner/Elixir/shell-one-liner.elixir @@ -0,0 +1 @@ +elixir -e "IO.inspect 'Hello, World\!'" diff --git a/Task/Shell-one-liner/OCaml/shell-one-liner.ocaml b/Task/Shell-one-liner/OCaml/shell-one-liner-1.ocaml similarity index 100% rename from Task/Shell-one-liner/OCaml/shell-one-liner.ocaml rename to Task/Shell-one-liner/OCaml/shell-one-liner-1.ocaml diff --git a/Task/Shell-one-liner/OCaml/shell-one-liner-2.ocaml b/Task/Shell-one-liner/OCaml/shell-one-liner-2.ocaml new file mode 100644 index 0000000000..b22d1d1572 --- /dev/null +++ b/Task/Shell-one-liner/OCaml/shell-one-liner-2.ocaml @@ -0,0 +1,2 @@ +$ echo 'print_endline "Hello"' | ocaml -stdin +Hello diff --git a/Task/Short-circuit-evaluation/ALGOL-W/short-circuit-evaluation.alg b/Task/Short-circuit-evaluation/ALGOL-W/short-circuit-evaluation.alg new file mode 100644 index 0000000000..3bc3ad3d29 --- /dev/null +++ b/Task/Short-circuit-evaluation/ALGOL-W/short-circuit-evaluation.alg @@ -0,0 +1,15 @@ +begin + + logical procedure a( logical value v ) ; begin write( "a: ", v ); v end ; + logical procedure b( logical value v ) ; begin write( "b: ", v ); v end ; + + write( "and: ", a( true ) and b( true ) ); + write( "---" ); + write( "or: ", a( true ) or b( true ) ); + write( "---" ); + write( "and: ", a( false ) and b( true ) ); + write( "---" ); + write( "or: ", a( false ) or b( true ) ); + write( "---" ); + +end. diff --git a/Task/Short-circuit-evaluation/Batch-File/short-circuit-evaluation.bat b/Task/Short-circuit-evaluation/Batch-File/short-circuit-evaluation.bat new file mode 100644 index 0000000000..ee9deb7364 --- /dev/null +++ b/Task/Short-circuit-evaluation/Batch-File/short-circuit-evaluation.bat @@ -0,0 +1,47 @@ +%=== Batch Files have no booleans. ===% +%=== I will instead use 1 as true and 0 as false. ===% + +@echo off +setlocal enabledelayedexpansion +echo AND +for /l %%i in (0,1,1) do ( +for /l %%j in (0,1,1) do ( + echo.a^(%%i^) AND b^(%%j^) + call :a %%i + set res=!bool_a! + if not !res!==0 ( + call :b %%j + set res=!bool_b! + ) + echo.=^> !res! +) +) + +echo --------------------------------- +echo OR +for /l %%i in (0,1,1) do ( + for /l %%j in (0,1,1) do ( + echo a^(%%i^) OR b^(%%j^) + call :a %%i + set res=!bool_a! + if !res!==0 ( + call :b %%j + set res=!bool_b! + ) + echo.=^> !res! + ) +) +pause>nul +exit /b 0 + + +::---------------------------------------- +:a +echo. calls func a +set bool_a=%1 +goto :EOF + +:b +echo. calls func b +set bool_b=%1 +goto :EOF diff --git a/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-1.js b/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-1.js new file mode 100644 index 0000000000..3bf5960b01 --- /dev/null +++ b/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-1.js @@ -0,0 +1,14 @@ +function a(bool) { + console.log('a -->', bool); + + return bool; +} + +function b(bool) { + console.log('b -->', bool); + + return bool; +} + +var x = a(false) && b(true), + y = a(true) || b(false); diff --git a/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-2.js b/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-2.js new file mode 100644 index 0000000000..effde750b2 --- /dev/null +++ b/Task/Short-circuit-evaluation/JavaScript/short-circuit-evaluation-2.js @@ -0,0 +1,2 @@ +a --> false +a --> true diff --git a/Task/Short-circuit-evaluation/Liberty-BASIC/short-circuit-evaluation.liberty b/Task/Short-circuit-evaluation/Liberty-BASIC/short-circuit-evaluation.liberty index 67046c98aa..1ae49f8f23 100644 --- a/Task/Short-circuit-evaluation/Liberty-BASIC/short-circuit-evaluation.liberty +++ b/Task/Short-circuit-evaluation/Liberty-BASIC/short-circuit-evaluation.liberty @@ -14,7 +14,7 @@ print "---------------------------------" print "OR" for i = 0 to 1 for j = 0 to 1 - print "a("; i; ") AND b("; j; ")" + print "a("; i; ") OR b("; j; ")" res =a( i) 'call always if res = 0 then 'short circuit if <>0 res = b( j) diff --git a/Task/Short-circuit-evaluation/NetRexx/short-circuit-evaluation.netrexx b/Task/Short-circuit-evaluation/NetRexx/short-circuit-evaluation.netrexx new file mode 100644 index 0000000000..58fb06befd --- /dev/null +++ b/Task/Short-circuit-evaluation/NetRexx/short-circuit-evaluation.netrexx @@ -0,0 +1,29 @@ +/* NetRexx */ +options replace format comments java crossref symbols nobinary + +Parse Version v +Say 'Version='v + +If a() | b() Then Say 'a and b are true' +If \a() | b() Then Say 'Surprise' +Else Say 'ok' + +If a(), b() Then Say 'a is true' +If \a(), b() Then Say 'Surprise' +Else Say 'ok: \\a() is false' + +Select + When \a(), b() Then Say 'Surprise' + Otherwise Say 'ok: \\a() is false (Select)' + End +Return + +method a private static binary returns boolean + state = Boolean.TRUE.booleanValue() + Say '--a returns' state + Return state + +method b private static binary returns boolean + state = Boolean.TRUE.booleanValue() + Say '--b returns' state + Return state diff --git a/Task/Show-the-epoch/ABAP/show-the-epoch.abap b/Task/Show-the-epoch/ABAP/show-the-epoch.abap new file mode 100644 index 0000000000..fee00f403f --- /dev/null +++ b/Task/Show-the-epoch/ABAP/show-the-epoch.abap @@ -0,0 +1,5 @@ +DATA: lv_date TYPE datum. + +lv_date = 0. + +WRITE: / lv_date. diff --git a/Task/Show-the-epoch/CoffeeScript/show-the-epoch.coffee b/Task/Show-the-epoch/CoffeeScript/show-the-epoch.coffee new file mode 100644 index 0000000000..cc4123ca93 --- /dev/null +++ b/Task/Show-the-epoch/CoffeeScript/show-the-epoch.coffee @@ -0,0 +1 @@ +console.log new Date(0).toISOString() diff --git a/Task/Show-the-epoch/Julia/show-the-epoch.julia b/Task/Show-the-epoch/Julia/show-the-epoch.julia new file mode 100644 index 0000000000..719a4f9413 --- /dev/null +++ b/Task/Show-the-epoch/Julia/show-the-epoch.julia @@ -0,0 +1 @@ +println("Time zero (the epoch) is ", strftime("%c", 0), ".") diff --git a/Task/Show-the-epoch/Rust/show-the-epoch.rust b/Task/Show-the-epoch/Rust/show-the-epoch.rust new file mode 100644 index 0000000000..e97e8d3b64 --- /dev/null +++ b/Task/Show-the-epoch/Rust/show-the-epoch.rust @@ -0,0 +1,8 @@ +extern crate time; + +use time::{at_utc, Timespec}; + +fn main() { + let epoch = at_utc(Timespec::new(0, 0)); + println!("{}", epoch.asctime()); +} diff --git a/Task/Sierpinski-carpet/Befunge/sierpinski-carpet.bf b/Task/Sierpinski-carpet/Befunge/sierpinski-carpet.bf new file mode 100644 index 0000000000..901083465c --- /dev/null +++ b/Task/Sierpinski-carpet/Befunge/sierpinski-carpet.bf @@ -0,0 +1,4 @@ +311>*#3\>#-:#1_$:00p00g-#@_010p0>:20p10g30v +>p>40p"#"30g40g*!#v_$48*30g3%1-v^ >$55+,1v> +0 ^p03/3g03/3g04$_v#!*!-1%3g04!<^_^#- g00 < +^3g01p02:0p01_@#-g>#0,#02#:0#+g#11#g+#0:#<^ diff --git a/Task/Sierpinski-carpet/Elixir/sierpinski-carpet.elixir b/Task/Sierpinski-carpet/Elixir/sierpinski-carpet.elixir new file mode 100644 index 0000000000..16f2e82146 --- /dev/null +++ b/Task/Sierpinski-carpet/Elixir/sierpinski-carpet.elixir @@ -0,0 +1,16 @@ +defmodule RC do + def sierpinski_carpet(n), do: sierpinski_carpet(n, ["#"]) + + def sierpinski_carpet(0, carpet), do: carpet + def sierpinski_carpet(n, carpet) do + new_carpet = Enum.map(carpet, fn x -> x <> x <> x end) ++ + Enum.map(carpet, fn x -> x <> String.replace(x, "#", " ") <> x end) ++ + Enum.map(carpet, fn x -> x <> x <> x end) + sierpinski_carpet(n-1, new_carpet) + end +end + +Enum.each(0..3, fn n -> + IO.puts "\nN=#{n}" + Enum.each(RC.sierpinski_carpet(n), fn line -> IO.puts line end) +end) diff --git a/Task/Sierpinski-carpet/Java/sierpinski-carpet.java b/Task/Sierpinski-carpet/Java/sierpinski-carpet-1.java similarity index 100% rename from Task/Sierpinski-carpet/Java/sierpinski-carpet.java rename to Task/Sierpinski-carpet/Java/sierpinski-carpet-1.java diff --git a/Task/Sierpinski-carpet/Java/sierpinski-carpet-2.java b/Task/Sierpinski-carpet/Java/sierpinski-carpet-2.java new file mode 100644 index 0000000000..feeb7c81c1 --- /dev/null +++ b/Task/Sierpinski-carpet/Java/sierpinski-carpet-2.java @@ -0,0 +1,59 @@ +import java.awt.*; +import java.awt.event.ActionEvent; +import javax.swing.*; + +public class SierpinskiCarpet extends JPanel { + private final int dim = 513; + private final int margin = 20; + + private int limit = dim; + + public SierpinskiCarpet() { + setPreferredSize(new Dimension(dim + 2 * margin, dim + 2 * margin)); + setBackground(Color.white); + setForeground(Color.orange); + + new Timer(2000, (ActionEvent e) -> { + limit /= 3; + if (limit <= 3) + limit = dim; + repaint(); + }).start(); + } + + void drawCarpet(Graphics2D g, int x, int y, int size) { + if (size < limit) + return; + size /= 3; + for (int i = 0; i < 9; i++) { + if (i == 4) { + g.fillRect(x + size, y + size, size, size); + } else { + drawCarpet(g, x + (i % 3) * size, y + (i / 3) * size, size); + } + } + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g.translate(margin, margin); + drawCarpet(g, 0, 0, dim); + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(() -> { + JFrame f = new JFrame(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setTitle("Sierpinski Carpet"); + f.setResizable(false); + f.add(new SierpinskiCarpet(), BorderLayout.CENTER); + f.pack(); + f.setLocationRelativeTo(null); + f.setVisible(true); + }); + } +} diff --git a/Task/Sierpinski-carpet/JavaScript/sierpinski-carpet.js b/Task/Sierpinski-carpet/JavaScript/sierpinski-carpet-1.js similarity index 100% rename from Task/Sierpinski-carpet/JavaScript/sierpinski-carpet.js rename to Task/Sierpinski-carpet/JavaScript/sierpinski-carpet-1.js diff --git a/Task/Sierpinski-carpet/JavaScript/sierpinski-carpet-2.js b/Task/Sierpinski-carpet/JavaScript/sierpinski-carpet-2.js new file mode 100644 index 0000000000..128bb5e3dd --- /dev/null +++ b/Task/Sierpinski-carpet/JavaScript/sierpinski-carpet-2.js @@ -0,0 +1,56 @@ +// Orders 1, 2 and 3 of the Sierpinski Carpet +// as lines of text. + +// Generic text output for use in any JavaScript environment +// Browser JavaScripts may use console.log() to return textual output +// others use print() or analogous functions. + +[1, 2, 3].map(function sierpinskiCarpetOrder(n) { + + // An (n * n) grid of (filled or empty) sub-rectangles + // n --> [[s]] + var carpet = function (n) { + var lstN = range(0, Math.pow(3, n) - 1); + + // State of each cell in an N * N grid + return lstN.map(function (x) { + return lstN.map(function (y) { + return inCarpet(x, y); + }); + }); + }, + + // State of a given coordinate in the grid: + // Filled or not ? + // (See https://en.wikipedia.org/wiki/Sierpinski_carpet#Construction) + // n --> n --> bool + inCarpet = function (x, y) { + return (!x || !y) ? true : + !( + (x % 3 === 1) && + (y % 3 === 1) + ) && inCarpet( + x / 3 | 0, + y / 3 | 0 + ); + }, + + // Sequence of integers from m to n + // n --> n --> [n] + range = function (m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { + return m + i; + } + ); + }; + + // Grid of booleans mapped to lines of characters + // [[bool]] --> s + return carpet(n).map(function (line) { + return line.map(function (bool) { + return bool ? '\u2588' : ' '; + }).join(''); + }).join('\n'); + +}).join('\n\n'); diff --git a/Task/Sierpinski-carpet/PowerShell/sierpinski-carpet.psh b/Task/Sierpinski-carpet/PowerShell/sierpinski-carpet.psh index 89f83e6560..d01cb8e5b1 100644 --- a/Task/Sierpinski-carpet/PowerShell/sierpinski-carpet.psh +++ b/Task/Sierpinski-carpet/PowerShell/sierpinski-carpet.psh @@ -6,7 +6,7 @@ function inCarpet($x, $y) { $x = [Math]::Truncate($x / 3) $y = [Math]::Truncate($y / 3) } - return "█" + return "#" } function carpet($n) { @@ -17,3 +17,5 @@ function carpet($n) { Write-Host } } + #Display the carpet for N=3... + carpet 3 diff --git a/Task/Sierpinski-carpet/Ruby/sierpinski-carpet.rb b/Task/Sierpinski-carpet/Ruby/sierpinski-carpet.rb index 0af1939b26..9708ea82ed 100644 --- a/Task/Sierpinski-carpet/Ruby/sierpinski-carpet.rb +++ b/Task/Sierpinski-carpet/Ruby/sierpinski-carpet.rb @@ -1,11 +1,11 @@ def sierpinski_carpet(n) carpet = ["#"] n.times do - carpet = carpet.collect {|x| x + x + x} + \ - carpet.collect {|x| x + x.tr("#"," ") + x} + \ + carpet = carpet.collect {|x| x + x + x} + + carpet.collect {|x| x + x.tr("#"," ") + x} + carpet.collect {|x| x + x + x} end - carpet.join("\n") + carpet end -puts sierpinski_carpet(3) +4.times{|i| puts "\nN=#{i}", sierpinski_carpet(i)} diff --git a/Task/Sierpinski-carpet/X86-Assembly/sierpinski-carpet.x86 b/Task/Sierpinski-carpet/X86-Assembly/sierpinski-carpet.x86 new file mode 100644 index 0000000000..334c828f9c --- /dev/null +++ b/Task/Sierpinski-carpet/X86-Assembly/sierpinski-carpet.x86 @@ -0,0 +1,160 @@ +;x86-64 assembly code for Microsoft Windows +;Tested in windows 7 Enterprise Service Pack 1 64 bit +;With the AMD FX(tm)-6300 processor +;Assembled with NASM version 2.11.06 +;Linked to C library with gcc version 4.9.2 (x86_64-win32-seh-rev1, Built by MinGW-W64 project) + +;Assembled and linked with the following commands: +;nasm -f win64 .asm -o .obj +;gcc .obj -o + +;Takes magnitude of Sierpinski Carpet as command line argument. + +extern atoi,puts,putchar,exit + +section .data +errmsg_noarg: db "Magnitude of Sierpinski Carpet was not specified.",0 +errmsg_argnumber: db "There should be no more than one argument.",0 + +section .bss + +section .text +global main + +main: + +;check for argument +cmp rcx,1 +jle err_noarg + +;ensure that only one argument was entered +cmp rcx,2 +jg err_argnumber + +;column in rsi +;row in rdi +;x in r8 +;y in r9 +;width in r13 +;magic number in r14 + +mov r14,2863311531 + +;get magnitude in rbx from first arg +mov rcx,[rdx + 8] +call atoi +mov rbx,rax + +cmp rbx,0 +jz magnitude_zero + + +;determine dimensions of square +mov rax,1 + +find_width: + +lea rax,[rax * 3] + +dec rbx +jg find_width + +sub rax,1 + +mov r13,rax +mov rdi,rax + + +next_row: + +mov rsi,r13 + +fill_row: + +;x in r8, y in r9 +mov r8,rsi +mov r9,rdi + +is_filled: + +;if(x%3==1 && y%3==1) +;x%3 in rbx +mov rax,r8 +mov rbx,r8 +mul r14 +shr rax,33 +mov r8,rax +lea rax,[rax * 3] +sub rbx,rax + +;y%3 in rcx +mov rax,r9 +mov rcx,r9 +mul r14 +shr rax,33 +mov r9,rax +lea rax,[rax * 3] +sub rcx,rax + +;x%3==1 && y%3==1 +xor rbx,1 +xor rcx,1 +or rbx,rcx +mov rcx,' ' +cmp rbx,0 +jz dont_fill + +;x>0 || y>0 +mov rax,r8 +or rax,r9 +cmp rax,0 +jg is_filled + +mov rcx,'#' +dont_fill: + +call putchar + +dec rsi +jge fill_row + +;put newline at the end of each row +mov rcx,0xa +call putchar + +dec rdi +jge next_row + +xor rcx,rcx +call exit + +magnitude_zero: + +mov rcx,'#' +call putchar + +mov rcx,0xa +call putchar + +xor rcx,rcx +call exit + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;error message + +err_noarg: + +mov rcx,errmsg_noarg +call puts + +mov rcx,1 +call exit + + +err_argnumber: + +mov rcx,errmsg_argnumber +call puts + +mov rcx,1 +call exit diff --git a/Task/Sierpinski-triangle-Graphical/Kotlin/sierpinski-triangle-graphical.kotlin b/Task/Sierpinski-triangle-Graphical/Kotlin/sierpinski-triangle-graphical.kotlin new file mode 100644 index 0000000000..9c74c85c78 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Kotlin/sierpinski-triangle-graphical.kotlin @@ -0,0 +1,54 @@ +import javax.swing.* +import java.awt.* + +fun main(args: Array) +{ + var i = 8 // Default + if (args.size() >= 1) + try + { + i = args[0].toInt() + } + catch (e: NumberFormatException) + { + println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to $i") + } + + val size = 800 + val panel = object : JPanel() + { + init { preferredSize = Dimension(size, size) } + + public override fun paintComponent(g: Graphics) + { + g.color = Color.BLACK + val level = i + SierpinskyTriangle.drawSierpinskyTriangle(level, 20, 20, size - 40, g as Graphics2D) + } + } + + val frame = JFrame("Sierpinsky Triangle - Java") + frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE + frame.add(panel) + frame.pack() + frame.isResizable = false + frame.setLocationRelativeTo(null) + frame.isVisible = true +} + +internal object SierpinskyTriangle +{ + fun drawSierpinskyTriangle(level: Int, x: Int, y: Int, size: Int, g: Graphics2D) + { + if (level > 0) + { + g.drawLine(x, y, x + size, y) + g.drawLine(x, y, x, y + size) + g.drawLine(x + size, y, x, y + size) + + drawSierpinskyTriangle(level - 1, x, y, size / 2, g) + drawSierpinskyTriangle(level - 1, x + size / 2, y, size / 2, g) + drawSierpinskyTriangle(level - 1, x, y + size / 2, size / 2, g) + } + } +} diff --git a/Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical.tcl b/Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical-1.tcl similarity index 100% rename from Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical.tcl rename to Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical-1.tcl diff --git a/Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical-2.tcl b/Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical-2.tcl new file mode 100644 index 0000000000..baa5ba7f6d --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Tcl/sierpinski-triangle-graphical-2.tcl @@ -0,0 +1,14 @@ +:1→X:1→Y +:Zdecimal +:Horizontal 3.1 +:Vertical -4.5 +:While 1 +:X+1→X +:DS<(Y,1 +:While 0 +:X→Y +:1→X +:End +:If pxl-Test(Y-1,X) xor (pxl-Test(Y,X-1 +:PxlOn(Y,X +:End diff --git a/Task/Sierpinski-triangle/Befunge/sierpinski-triangle.bf b/Task/Sierpinski-triangle/Befunge/sierpinski-triangle.bf new file mode 100644 index 0000000000..d9cfe1a3ed --- /dev/null +++ b/Task/Sierpinski-triangle/Befunge/sierpinski-triangle.bf @@ -0,0 +1,7 @@ +41+2>\#*1#2-#<:#\_$:1+v +v:$_:#`0#\\#00#:p#->#1< +>2/1\0p:2/\::>1-:>#v_1v +>8#4*#*+#+,#5^#5g0:< 1 +vg11<\*g11!:g 0-1:::!*+!!\0g11p\ 0p1-:#^_v +@$$_\#!:#::#-^#1\$,+55< diff --git a/Task/Sierpinski-triangle/Elixir/sierpinski-triangle.elixir b/Task/Sierpinski-triangle/Elixir/sierpinski-triangle.elixir new file mode 100644 index 0000000000..d35dce8528 --- /dev/null +++ b/Task/Sierpinski-triangle/Elixir/sierpinski-triangle.elixir @@ -0,0 +1,14 @@ +defmodule RC do + def sierpinski_triangle(n) do + f = fn(x) -> IO.puts "#{x}" end + Enum.each(triangle(n, ["*"], " "), f) + end + + defp triangle(0, down, _), do: down + defp triangle(n, down, sp) do + newDown = (for x <- down, do: sp<>x<>sp) ++ (for x <- down, do: x<>" "<>x) + triangle(n-1, newDown, sp<>sp) + end +end + +RC.sierpinski_triangle(4) diff --git a/Task/Sierpinski-triangle/Java/sierpinski-triangle-3.java b/Task/Sierpinski-triangle/Java/sierpinski-triangle-3.java new file mode 100644 index 0000000000..9ffec66057 --- /dev/null +++ b/Task/Sierpinski-triangle/Java/sierpinski-triangle-3.java @@ -0,0 +1,62 @@ +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.geom.Path2D; +import javax.swing.*; + +public class SierpinskiTriangle extends JPanel { + private final int dim = 512; + private final int margin = 20; + + private int limit = dim; + + public SierpinskiTriangle() { + setPreferredSize(new Dimension(dim + 2 * margin, dim + 2 * margin)); + setBackground(Color.white); + setForeground(Color.green.darker()); + + new Timer(2000, (ActionEvent e) -> { + limit /= 2; + if (limit <= 2) + limit = dim; + repaint(); + }).start(); + } + + void drawTriangle(Graphics2D g, int x, int y, int size) { + if (size <= limit) { + Path2D p = new Path2D.Float(); + p.moveTo(x, y); + p.lineTo(x + size / 2, y + size); + p.lineTo(x - size / 2, y + size); + g.fill(p); + } else { + size /= 2; + drawTriangle(g, x, y, size); + drawTriangle(g, x + size / 2, y + size, size); + drawTriangle(g, x - size / 2, y + size, size); + } + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + g.translate(margin, margin); + drawTriangle(g, dim / 2, 0, dim); + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(() -> { + JFrame f = new JFrame(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setTitle("Sierpinski Triangle"); + f.setResizable(false); + f.add(new SierpinskiTriangle(), BorderLayout.CENTER); + f.pack(); + f.setLocationRelativeTo(null); + f.setVisible(true); + }); + } +} diff --git a/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-1.js b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-1.js new file mode 100644 index 0000000000..dcce5dd458 --- /dev/null +++ b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-1.js @@ -0,0 +1,81 @@ +// A Sierpinski triangle of order N, +// constructed as Pascal's triangle mod 2 +// and mapped to 2^N lines of centred {1:asterisk, 0:space} strings + +(function (n) { + var nRows = Math.pow(2, n), + lstSierpinski = sierpinski(nRows).map(asciiBinary), + + nBaseWidth = lstSierpinski[nRows - 1].length; + + return lstSierpinski.map( + function (s) { + return centreAligned(s, nBaseWidth); + } + ).join('\n'); +})(4); + +// A Sierpinski sieve of n rows +// (Pascal triangle mod 2) +// n --> [bool] +function sierpinski(n) { + return pascalTriangle(n).map( + function (line) { + return line.map(function (x) { + return x % 2; + }); + } + ) +} + +// A Pascal triangle of n rows +// n --> [[n]] +function pascalTriangle(n) { + + // Sums of each consecutive pair of numbers + // [n] --> [n] + function pairSums(lst) { + return lst.reduce(function (acc, n, i, l) { + var iPrev = i ? i - 1 : 0; + return i ? acc.concat(l[iPrev] + l[i]) : acc + }, []); + } + + // Next line in a Pascal triangle series + // [n] --> [n] + function nextPascal(lst) { + return lst.length ? [1].concat( + pairSums(lst) + ).concat(1) : [1]; + } + + // Each row is a function of the preceding row + return n ? Array.apply(null, Array(n - 1)).reduce( + function (a, _, i) { + return a.concat( + [nextPascal(a[i])] + ); + }, [ + [1] + ] + ) : []; +} + +// [bool] --> s +function asciiBinary(lst) { + return lst.map( + function (x) { + return x ? '*' : ' '; + } + ).join(' '); +} + +// Space-padded to left and right +// s --> n --> s +function centreAligned(s, n) { + var lngWhite = n - s.length, + lngMargin = lngWhite > 0 ? Math.ceil(lngWhite / 2) : 0, + strMargin = lngMargin ? Array(lngMargin + 1).join(' ') : ''; + + return strMargin ? strMargin + s + strMargin : s; +} diff --git a/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle.js b/Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-2.js similarity index 100% rename from Task/Sierpinski-triangle/JavaScript/sierpinski-triangle.js rename to Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-2.js diff --git a/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia b/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia index aebb070b7b..52efdfb146 100644 --- a/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia +++ b/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia @@ -1,5 +1,4 @@ -pprint(matrix) = print(mapslices(x-> [join(x)], matrix, [2])) - +pprint(matrix) = for i = 1:size(matrix,1) println(join(matrix[i,:])) end spaces(m,n) = [" " for i=1:m, j=1:n] function sierpinski(n) diff --git a/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 b/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 index 69ad29facf..3901b94a7a 100644 --- a/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 +++ b/Task/Sierpinski-triangle/Perl-6/sierpinski-triangle.pl6 @@ -2,7 +2,7 @@ sub sierpinski ($n) { my @down = '*'; my $space = ' '; for ^$n { - @down = @down.map({"$space$_$space"}), @down.map({"$_ $_"}); + @down = flat @down.map({"$space$_$space"}), @down.map({"$_ $_"}); $space x= 2; } return @down; diff --git a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-1.rb b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-1.rb index a4cd0712ef..888249a753 100644 --- a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-1.rb +++ b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-1.rb @@ -1 +1 @@ -ruby -le'16.times{|y|print" "*(15-y),(0..y).map{|x|~y&x>0?" ":" *"}}' +ruby -le'16.times{|y|print" "*(15-y),*(0..y).map{|x|~y&x>0?" ":" *"}}' diff --git a/Task/Sierpinski-triangle/VBScript/sierpinski-triangle.vb b/Task/Sierpinski-triangle/VBScript/sierpinski-triangle.vb new file mode 100644 index 0000000000..6f3ac9a9fb --- /dev/null +++ b/Task/Sierpinski-triangle/VBScript/sierpinski-triangle.vb @@ -0,0 +1,27 @@ +Sub triangle(o) + n = 2 ^ o + Dim line() + ReDim line(2*n) + line(n) = "*" + i = 0 + Do While i < n + WScript.StdOut.WriteLine Join(line,"") + u = "*" + j = n - i + Do While j < (n+i+1) + If line(j-1) = line(j+1) Then + t = " " + Else + t = "*" + End If + line(j-1) = u + u = t + j = j + 1 + Loop + line(n+i) = t + line(n+i+1) = "*" + i = i + 1 + Loop +End Sub + +triangle(4) diff --git a/Task/Sieve-of-Eratosthenes/00DESCRIPTION b/Task/Sieve-of-Eratosthenes/00DESCRIPTION index 0af7155246..e180178c0d 100644 --- a/Task/Sieve-of-Eratosthenes/00DESCRIPTION +++ b/Task/Sieve-of-Eratosthenes/00DESCRIPTION @@ -11,3 +11,5 @@ If there's an easy way to add such a wheel based optimization, implement this as * [[Primality by trial division]]. * [[Sequence of primes by Trial Division]]. * [[Prime decomposition]]. +* [[Extensible prime generator]]. +* [[Emirp primes]]. diff --git a/Task/Sieve-of-Eratosthenes/ABAP/sieve-of-eratosthenes.abap b/Task/Sieve-of-Eratosthenes/ABAP/sieve-of-eratosthenes.abap new file mode 100644 index 0000000000..b22dd0489c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/ABAP/sieve-of-eratosthenes.abap @@ -0,0 +1,41 @@ +PARAMETERS: p_limit TYPE i OBLIGATORY DEFAULT 100. + +AT SELECTION-SCREEN ON p_limit. + IF p_limit LE 1. + MESSAGE 'Limit must be higher then 1.' TYPE 'E'. + ENDIF. + +START-OF-SELECTION. + FIELD-SYMBOLS: TYPE flag. + DATA: gt_prime TYPE TABLE OF flag, + gv_prime TYPE flag, + gv_i TYPE i, + gv_j TYPE i. + + DO p_limit TIMES. + IF sy-index > 1. + gv_prime = abap_true. + ELSE. + gv_prime = abap_false. + ENDIF. + + APPEND gv_prime TO gt_prime. + ENDDO. + + gv_i = 2. + WHILE ( gv_i <= trunc( sqrt( p_limit ) ) ). + IF ( gt_prime[ gv_i ] EQ abap_true ). + gv_j = gv_i ** 2. + WHILE ( gv_j <= p_limit ). + gt_prime[ gv_j ] = abap_false. + gv_j = ( gv_i ** 2 ) + ( sy-index * gv_i ). + ENDWHILE. + ENDIF. + gv_i = gv_i + 1. + ENDWHILE. + + LOOP AT gt_prime INTO gv_prime. + IF gv_prime = abap_true. + WRITE: / sy-tabix. + ENDIF. + ENDLOOP. diff --git a/Task/Sieve-of-Eratosthenes/ALGOL-W/sieve-of-eratosthenes.alg b/Task/Sieve-of-Eratosthenes/ALGOL-W/sieve-of-eratosthenes.alg new file mode 100644 index 0000000000..dae683e713 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/ALGOL-W/sieve-of-eratosthenes.alg @@ -0,0 +1,43 @@ +begin + + % implements the sieve of Eratosthenes % + % s(i) is set to true if i is prime, false otherwise % + % algol W doesn't have a upb operator, so we pass the size of the % + % array in n % + procedure sieve( logical array s ( * ); integer value n ) ; + begin + + % start with everything flagged as prime % + for i := 1 until n do s( i ) := true; + + % sieve out the non-primes % + s( 1 ) := false; + for i := 2 until truncate( sqrt( n ) ) + do begin + if s( i ) + then begin + for p := i * i step i until n do s( p ) := false + end if_s_i + end for_i ; + + end sieve ; + + % test the sieve procedure % + + integer sieveMax; + + sieveMax := 100; + begin + + logical array s ( 1 :: sieveMax ); + + i_w := 2; % set output field width % + s_w := 1; % and output separator width % + + % find and display the primes % + sieve( s, sieveMax ); + for i := 1 until sieveMax do if s( i ) then writeon( i ); + + end + +end. diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj index 33f66ac07b..0712ea1149 100644 --- a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj @@ -1,19 +1,13 @@ (defn primes-to - "Returns a list of all primes from 2 to n" + "Computes lazy sequence of prime numbers up to a given number using sieve of Eratosthenes" [n] - (let [n (int n)] - (let [root (-> n Math/sqrt int)] - (loop [i (int 2), a (boolean-array (inc n)), result (transient [])] - (if (> i n) - (persistent! result) - (recur (inc i) - (if (and (<= i root) (not (aget a i))) - (loop [arr a, j (* i i)] - (if (> j n) - arr - (recur (do (aset arr j true) arr) - (+ j i)))) - a) - (if (not (aget a i)) - (conj! result i) - result))))))) + (let [root (-> n Math/sqrt long), + cmpsts (boolean-array (inc n)), + cullp (fn [p] + (loop [i (* p p)] + (if (<= i n) + (do (aset cmpsts i true) + (recur (+ i p))))))] + (do (dorun (map #(cullp %) (filter #(not (aget cmpsts %)) + (range 2 (inc root))))) + (filter #(not (aget cmpsts %)) (range 2 (inc n)))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-10.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-10.clj new file mode 100644 index 0000000000..18fd065157 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-10.clj @@ -0,0 +1,17 @@ +(defn primes-hashmap + "Infinite sequence of primes using an incremental Sieve or Eratosthenes with a Hashmap" + [] + (letfn [(nxtoddprm [c q bsprms cmpsts] + (if (>= c q) ;; only ever equal + (let [p2 (* (first bsprms) 2), nbps (next bsprms), nbp (first nbps)] + (recur (+ c 2) (* nbp nbp) nbps (assoc cmpsts (+ q p2) p2))) + (if (contains? cmpsts c) + (recur (+ c 2) q bsprms + (let [adv (cmpsts c), ncmps (dissoc cmpsts c)] + (assoc ncmps + (loop [try (+ c adv)] ;; ensure map entry is unique + (if (contains? ncmps try) + (recur (+ try adv)) try)) adv))) + (cons c (lazy-seq (nxtoddprm (+ c 2) q bsprms cmpsts))))))] + (do (def baseoddprms (cons 3 (lazy-seq (nxtoddprm 5 9 baseoddprms {})))) + (cons 2 (lazy-seq (nxtoddprm 3 9 baseoddprms {})))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-11.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-11.clj new file mode 100644 index 0000000000..42c40e12a3 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-11.clj @@ -0,0 +1,67 @@ +(deftype PQEntry [k, v] + Object + (toString [_] (str "<" k "," v ">"))) +(deftype PQNode [^PQEntry ntry, lft, rght, lvl] + Object + (toString [_] (str "<" lvl ntry " left: " (str lft) " right: " (str rght) ">"))) + +(defn empty-pq [] nil) + +(defn getMin-pq ^PQEntry [pq] (condp instance? pq + PQEntry pq, + PQNode (.ntry ^PQNode pq) + nil)) + +(defn insert-pq [opq k v] + (loop [kv (->PQEntry k v), msk 0, pq opq, cont identity] + (condp instance? pq + PQEntry (if (< k (.k ^PQEntry pq)) (cont (->PQNode kv pq nil 2)) + (cont (->PQNode pq kv nil 2))), + PQNode (let [^PQNode pqn pq, kvn (.ntry pqn), l (.lft pqn), r (.rght pqn), + nlvl (+ (.lvl pqn) 1), + nmsk (if (zero? msk) ;; never ever 0 again with the bit or'ed 1 + (bit-or (bit-shift-left nlvl (- 64 (long (quot (Math/log (double nlvl)) + (Math/log (double 2)))))) 1) + (bit-shift-left msk 1))] + (if (<= k (.k ^PQEntry kvn)) + (if (neg? nmsk) + (recur kvn nmsk r (fn [npq] (cont (->PQNode kv l npq nlvl)))) + (recur kvn nmsk l (fn [npq] (cont (->PQNode kv npq r nlvl))))) + (if (neg? nmsk) + (recur kv nmsk r (fn [npq] (cont (->PQNode kvn l npq nlvl)))) + (recur kv nmsk l (fn [npq] (cont (->PQNode kvn npq r nlvl))))))), + (cont kv)))) + +(defn replaceMinAs-pq [opq k v] + (let [kv (->PQEntry k v)] + (loop [pq opq, cont identity] + (if (instance? PQNode pq) + (let [^PQNode pqn pq, l (.lft pqn), r (.rght pqn), lvl (.lvl pqn)] + (cond + (and (instance? PQEntry r) (> k (.k ^PQEntry r))) + (cond ;; right not empty so left is never empty + (and (instance? PQEntry l) (> k (.k ^PQEntry l))) ;; both qualify; choose least + (if (> (.k ^PQEntry l) (.k ^PQEntry r)) + (cont (->PQNode r l kv lvl)) + (cont (->PQNode l kv r lvl))), + (and (instance? PQNode l) (> k (.k ^PQEntry (.ntry ^PQNode l)))) + (let [^PQEntry kvl (.ntry ^PQNode l)] + (if (> (.k kvl) (.k ^PQEntry r)) ;; both qualify; choose least + (cont (->PQNode r l kv lvl)) + (recur l (fn [npq] (cont (->PQNode kvl npq r lvl)))))), + :else (cont (->PQNode r l kv lvl))), ;; only right qualifies; no recursion + (and (instance? PQNode r) (> k (.k ^PQEntry (.ntry ^PQNode r)))) + (let [^PQEntry kvr (.ntry ^PQNode r)] + (if (and (instance? PQNode l) (> k (.k ^PQEntry (.ntry ^PQNode l)))) + (let [^PQEntry kvl (.ntry ^PQNode l)] + (if (> (.k kvl) (.k kvr)) ;; both qualify; choose least + (recur r (fn [npq] (cont (->PQNode kvr l npq lvl)))) + (recur l (fn [npq] (cont (->PQNode kvl npq r lvl)))))) + (recur r (fn [npq] (cont (->PQNode kvr l npq lvl)))))), ;; only right qualifies + :else (cond ;; right is empty, but as this is a node, left is never empty + (and (instance? PQEntry l) (> k (.k ^PQEntry l))) + (cont (->PQNode l kv r lvl)), + (and (instance? PQNode l) (> k (.k ^PQEntry (.ntry ^PQNode l)))) + (recur l (fn [npq] (cont (->PQNode (.ntry ^PQNode l) npq r lvl)))), + :else (cont (->PQNode kv l r lvl))))) ;; just replace contents, leave same + (cont kv))))) ;; if was empty or just an entry, just use current entry diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-12.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-12.clj new file mode 100644 index 0000000000..7c36b3af08 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-12.clj @@ -0,0 +1,19 @@ +(defn primes-pq + "Infinite sequence of primes using an incremental Sieve or Eratosthenes with a Priority Queue" + [] + (letfn [(nxtoddprm [c q bsprms cmpsts] + (if (>= c q) ;; only ever equal + (let [p2 (* (first bsprms) 2), nbps (next bsprms), nbp (first nbps)] + (recur (+ c 2) (* nbp nbp) nbps (insert-pq cmpsts (+ q p2) p2))) + (let [mn (getMin-pq cmpsts)] + (if (and mn (>= c (.k mn))) ;; never greater than + (recur (+ c 2) q bsprms + (loop [adv (.v mn), cmps cmpsts] ;; advance repeat composites for value + (let [ncmps (replaceMinAs-pq cmps (+ c adv) adv), + nmn (getMin-pq ncmps)] + (if (and nmn (>= c (.k nmn))) + (recur (.v nmn) ncmps) + ncmps)))) + (cons c (lazy-seq (nxtoddprm (+ c 2) q bsprms cmpsts)))))))] + (do (def baseoddprms (cons 3 (lazy-seq (nxtoddprm 5 9 baseoddprms (empty-pq))))) + (cons 2 (lazy-seq (nxtoddprm 3 9 baseoddprms (empty-pq))))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj index 90d5448ce6..39af1285f7 100644 --- a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj @@ -1,10 +1,11 @@ -(defn primes - "Computes all prime numbers up to a given number using sieve of Eratosthenes" - [n] - (loop [cs (range 2 n) ; candidates - ps [2]] ; results - (let [lp (last ps) - ncs (-> (range lp n lp) set (remove cs))] - (if (> lp (Math/sqrt n)) - (concat ps ncs) - (recur ncs (concat ps [(first ncs)])))))) +(defn primes-to + "Returns a lazy sequence of prime numbers less than lim" + [lim] + (let [refs (boolean-array (+ lim 1) true) + root (int (Math/sqrt lim))] + (do (doseq [i (range 2 lim) + :while (<= i root) + :when (aget refs i)] + (doseq [j (range (* i i) lim i)] + (aset refs j false))) + (filter #(aget refs %) (range 2 lim))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj index 54d0323d00..70f5d2da32 100644 --- a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj @@ -1,14 +1,9 @@ -(defn primes [max-prime] - (let [sieve (fn [s n] - (if (<= (* n n) max-prime) - (recur (if (s n) - (reduce #(assoc %1 %2 false) s (range (* n n) (inc max-prime) n)) - s) - (inc n)) - s))] - (-> (vector-of :boolean) ; form the return vector - (reduce conj (range (inc max-prime))) - (assoc 0 false) - (assoc 1 false) - (sieve 2) - #(->> % count range (map vector %) (filter first) (map second))))) +(defn primes-to + "Computes lazy sequence of prime numbers up to a given number using sieve of Eratosthenes" + [n] + (letfn [(nxtprm [cs] ; current candidates + (let [p (first cs)] + (if (> p (Math/sqrt n)) cs + (cons p (lazy-seq (nxtprm (-> (range (* p p) (inc n) p) + set (remove cs) rest)))))))] + (nxtprm (range 2 (inc n))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-4.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-4.clj new file mode 100644 index 0000000000..d9e6b989f2 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-4.clj @@ -0,0 +1,15 @@ +(defn primes-to + "Computes lazy sequence of prime numbers up to a given number using sieve of Eratosthenes" + [max-prime] + (let [sieve (fn [s n] + (if (<= (* n n) max-prime) + (recur (if (s n) + (reduce #(assoc %1 %2 false) s (range (* n n) (inc max-prime) n)) + s) + (inc n)) + s))] + (->> (-> (reduce conj (vector-of :boolean) (map #(= % %) (range (inc max-prime)))) + (assoc 0 false) + (assoc 1 false) + (sieve 2)) + (map-indexed #(vector %2 %1)) (filter first) (map second)))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-5.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-5.clj new file mode 100644 index 0000000000..167340129b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-5.clj @@ -0,0 +1,27 @@ +(set! *unchecked-math* true) + +(defn primes-to + "Computes lazy sequence of prime numbers up to a given number using sieve of Eratosthenes" + [n] + (let [root (-> n Math/sqrt long), + rootndx (long (/ (- root 3) 2)), + ndx (long (/ (- n 3) 2)), + cmpsts (long-array (inc (/ ndx 64))), + isprm #(zero? (bit-and (aget cmpsts (bit-shift-right % 6)) + (bit-shift-left 1 (bit-and % 63)))), + cullp (fn [i] + (let [p (long (+ i i 3))] + (loop [i (bit-shift-right (- (* p p) 3) 1)] + (if (<= i ndx) + (do (let [w (bit-shift-right i 6)] + (aset cmpsts w (bit-or (aget cmpsts w) + (bit-shift-left 1 (bit-and i 63))))) + (recur (+ i p))))))), + cull (fn [] (loop [i 0] (if (<= i rootndx) + (do (if (isprm i) (cullp i)) (recur (inc i))))))] + (letfn [(nxtprm [i] (if (<= i ndx) + (cons (+ i i 3) (lazy-seq (nxtprm (loop [i (inc i)] + (if (or (> i ndx) (isprm i)) i + (recur (inc i)))))))))] + (if (< n 2) nil + (cons 3 (if (< n 3) nil (do (cull) (lazy-seq (nxtprm 0))))))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-6.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-6.clj new file mode 100644 index 0000000000..a00c63174f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-6.clj @@ -0,0 +1,73 @@ +(defn primes-tox + "Computes lazy sequence of prime numbers up to a given number using sieve of Eratosthenes" + [n] + (let [root (-> n Math/sqrt long), + rootndx (long (/ (- root 3) 2)), + ndx (max (long (/ (- n 3) 2)) 0), + lmt (quot ndx 64), + cmpsts (long-array (inc lmt)), + cullp (fn [i] + (let [p (long (+ i i 3))] + (loop [i (bit-shift-right (- (* p p) 3) 1)] + (if (<= i ndx) + (do (let [w (bit-shift-right i 6)] + (aset cmpsts w (bit-or (aget cmpsts w) + (bit-shift-left 1 (bit-and i 63))))) + (recur (+ i p))))))), + cull (fn [] (do (aset cmpsts lmt (bit-or (aget cmpsts lmt) + (bit-shift-left -2 (bit-and ndx 63)))) + (loop [i 0] + (when (<= i rootndx) + (when (zero? (bit-and (aget cmpsts (bit-shift-right i 6)) + (bit-shift-left 1 (bit-and i 63)))) + (cullp i)) + (recur (inc i)))))) + numprms (fn [] + (let [w (dec (alength cmpsts))] ;; fast results count bit counter + (loop [i 0, cnt (bit-shift-left (alength cmpsts) 6)] + (if (> i w) cnt + (recur (inc i) + (- cnt (java.lang.Long/bitCount (aget cmpsts i))))))))] + (if (< n 2) nil + (cons 2 (if (< n 3) nil + (do (cull) + (deftype OPSeq [^long i ^longs cmpsa ^long cnt ^long tcnt] ;; for arrays maybe need to embed the array so that it doesn't get garbage collected??? + clojure.lang.ISeq + (first [_] (if (nil? cmpsa) nil (+ i i 3))) + (next [_] (let [ncnt (inc cnt)] (if (>= ncnt tcnt) nil + (OPSeq. + (loop [j (inc i)] + (let [p? (zero? (bit-and (aget cmpsa (bit-shift-right j 6)) + (bit-shift-left 1 (bit-and j 63))))] + (if p? j (recur (inc j))))) + cmpsa ncnt tcnt)))) + (more [this] (let [ncnt (inc cnt)] (if (>= ncnt tcnt) (OPSeq. 0 nil tcnt tcnt) + (.next this)))) + (cons [this o] (clojure.core/cons o this)) + (empty [_] (if (= cnt tcnt) nil (OPSeq. 0 nil tcnt tcnt))) + (equiv [this o] (if (or (not= (type this) (type o)) + (not= cnt (.cnt ^OPSeq o)) (not= tcnt (.tcnt ^OPSeq o)) + (not= i (.i ^OPSeq o))) false true)) + clojure.lang.Counted + (count [_] (- tcnt cnt)) + clojure.lang.Seqable + (clojure.lang.Seqable/seq [this] (if (= cnt tcnt) nil this)) + clojure.lang.IReduce + (reduce [_ f v] (let [c (- tcnt cnt)] + (if (<= c 0) nil + (loop [ci i, n c, rslt v] + (if (zero? (bit-and (aget cmpsa (bit-shift-right ci 6)) + (bit-shift-left 1 (bit-and ci 63)))) + (let [rrslt (f rslt (+ ci ci 3)), + rdcd (reduced? rrslt), + nrslt (if rdcd @rrslt rrslt)] + (if (or (<= n 1) rdcd) nrslt + (recur (inc ci) (dec n) nrslt))) + (recur (inc ci) n rslt)))))) + (reduce [this f] (if (nil? i) (f) (if (= (.count this) 1) (+ i i 3) + (.reduce ^clojure.lang.IReduce (.next this) f (+ i i 3))))) + clojure.lang.Sequential + Object + (toString [this] (if (= cnt tcnt) "()" + (.toString (seq (map identity this)))))) + (->OPSeq 0 cmpsts 0 (numprms)))))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-7.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-7.clj new file mode 100644 index 0000000000..50cc25e527 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-7.clj @@ -0,0 +1,22 @@ +(defn primes-Bird + "Computes the unbounded sequence of primes using a Sieve of Eratosthenes algorithm by Richard Bird." + [] + (letfn [(mltpls [p] (let [p2 (* 2 p)] + (letfn [(nxtmltpl [c] + (cons c (lazy-seq (nxtmltpl (+ c p2)))))] + (nxtmltpl (* p p))))), + (allmtpls [ps] (cons (mltpls (first ps)) (lazy-seq (allmtpls (next ps))))), + (union [xs ys] (let [xv (first xs), yv (first ys)] + (if (< xv yv) (cons xv (lazy-seq (union (next xs) ys))) + (if (< yv xv) (cons yv (lazy-seq (union xs (next ys)))) + (cons xv (lazy-seq (union (next xs) (next ys)))))))), + (mrgmltpls [mltplss] (cons (first (first mltplss)) + (lazy-seq (union (next (first mltplss)) + (mrgmltpls (next mltplss)))))), + (minusStrtAt [n cmpsts] (loop [n n, cmpsts cmpsts] + (if (< n (first cmpsts)) + (cons n (lazy-seq (minusStrtAt (+ n 2) cmpsts))) + (recur (+ n 2) (next cmpsts)))))] + (do (def oddprms (cons 3 (lazy-seq (let [cmpsts (-> oddprms (allmtpls) (mrgmltpls))] + (minusStrtAt 5 cmpsts))))) + (cons 2 (lazy-seq oddprms))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-8.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-8.clj new file mode 100644 index 0000000000..88ef52e5a3 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-8.clj @@ -0,0 +1,25 @@ +(defn primes-treeFolding + "Computes the unbounded sequence of primes using a Sieve of Eratosthenes algorithm modified from Bird." + [] + (letfn [(mltpls [p] (let [p2 (* 2 p)] + (letfn [(nxtmltpl [c] + (cons c (lazy-seq (nxtmltpl (+ c p2)))))] + (nxtmltpl (* p p))))), + (allmtpls [ps] (cons (mltpls (first ps)) (lazy-seq (allmtpls (next ps))))), + (union [xs ys] (let [xv (first xs), yv (first ys)] + (if (< xv yv) (cons xv (lazy-seq (union (next xs) ys))) + (if (< yv xv) (cons yv (lazy-seq (union xs (next ys)))) + (cons xv (lazy-seq (union (next xs) (next ys)))))))), + (pairs [mltplss] (let [tl (next mltplss)] + (cons (union (first mltplss) (first tl)) + (lazy-seq (pairs (next tl)))))), + (mrgmltpls [mltplss] (cons (first (first mltplss)) + (lazy-seq (union (next (first mltplss)) + (mrgmltpls (pairs (next mltplss))))))), + (minusStrtAt [n cmpsts] (loop [n n, cmpsts cmpsts] + (if (< n (first cmpsts)) + (cons n (lazy-seq (minusStrtAt (+ n 2) cmpsts))) + (recur (+ n 2) (next cmpsts)))))] + (do (def oddprms (cons 3 (lazy-seq (let [cmpsts (-> oddprms (allmtpls) (mrgmltpls))] + (minusStrtAt 5 cmpsts))))) + (cons 2 (lazy-seq oddprms))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-9.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-9.clj new file mode 100644 index 0000000000..56556a39d9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-9.clj @@ -0,0 +1,48 @@ +(defn primes-treeFoldingx + "Computes the unbounded sequence of primes using a Sieve of Eratosthenes algorithm modified from Bird." + [] + (do (deftype CIS [v cont] + clojure.lang.ISeq + (first [_] v) + (next [_] (if (nil? cont) nil (cont))) + (more [this] (let [nv (.next this)] (if (nil? nv) (CIS. nil nil) nv))) + (cons [this o] (clojure.core/cons o this)) + (empty [_] (if (and (nil? v) (nil? cont)) nil (CIS. nil nil))) + (equiv [this o] (loop [cis1 this, cis2 o] (if (nil? cis1) (if (nil? cis2) true false) + (if (or (not= (type cis1) (type cis2)) + (not= (.v cis1) (.v ^CIS cis2)) + (and (nil? (.cont cis1)) + (not (nil? (.cont ^CIS cis2)))) + (and (nil? (.cont ^CIS cis2)) + (not (nil? (.cont cis1))))) false + (if (nil? (.cont cis1)) true + (recur ((.cont cis1)) ((.cont ^CIS cis2)))))))) + (count [this] (loop [cis this, cnt 0] (if (or (nil? cis) (nil? (.cont cis))) cnt + (recur ((.cont cis)) (inc cnt))))) + clojure.lang.Seqable + (seq [this] (if (and (nil? v) (nil? cont)) nil this)) + clojure.lang.Sequential + Object + (toString [this] (if (and (nil? v) (nil? cont)) "()" (.toString (seq (map identity this)))))) + (letfn [(mltpls [p] (let [p2 (* 2 p)] + (letfn [(nxtmltpl [c] + (->CIS c (fn [] (nxtmltpl (+ c p2)))))] + (nxtmltpl (* p p))))), + (allmtpls [^CIS ps] (->CIS (mltpls (.v ps)) (fn [] (allmtpls ((.cont ps)))))), + (union [^CIS xs ^CIS ys] (let [xv (.v xs), yv (.v ys)] + (if (< xv yv) (->CIS xv (fn [] (union ((.cont xs)) ys))) + (if (< yv xv) (->CIS yv (fn [] (union xs ((.cont ys))))) + (->CIS xv (fn [] (union (next xs) ((.cont ys))))))))), + (pairs [^CIS mltplss] (let [^CIS tl ((.cont mltplss))] + (->CIS (union (.v mltplss) (.v tl)) + (fn [] (pairs ((.cont tl))))))), + (mrgmltpls [^CIS mltplss] (->CIS (.v ^CIS (.v mltplss)) + (fn [] (union ((.cont ^CIS (.v mltplss))) + (mrgmltpls (pairs ((.cont mltplss)))))))), + (minusStrtAt [n ^CIS cmpsts] (loop [n n, cmpsts cmpsts] + (if (< n (.v cmpsts)) + (->CIS n (fn [] (minusStrtAt (+ n 2) cmpsts))) + (recur (+ n 2) ((.cont cmpsts))))))] + (do (def oddprms (->CIS 3 (fn [] (let [cmpsts (-> oddprms (allmtpls) (mrgmltpls))] + (minusStrtAt 5 cmpsts))))) + (->CIS 2 (fn [] oddprms)))))) diff --git a/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-1.lisp b/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-1.lisp index 4c52808bbf..70d66b2fe4 100644 --- a/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-1.lisp +++ b/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-1.lisp @@ -1,9 +1,11 @@ (defun sieve-of-eratosthenes (maximum) - (let ((sieve (make-array (1+ maximum) :element-type 'bit - :initial-element 0))) - (loop for candidate from 2 to maximum - when (zerop (bit sieve candidate)) - collect candidate - and do (loop for composite from (expt candidate 2) - to maximum by candidate - do (setf (bit sieve composite) 1))))) + (loop + with sieve = (make-array (1+ maximum) + :element-type 'bit + :initial-element 0) + for candidate from 2 to maximum + when (zerop (bit sieve candidate)) + collect candidate + and do (loop for composite from (expt candidate 2) + to maximum by candidate + do (setf (bit sieve composite) 1)))) diff --git a/Task/Sieve-of-Eratosthenes/Elixir/sieve-of-eratosthenes.elixir b/Task/Sieve-of-Eratosthenes/Elixir/sieve-of-eratosthenes.elixir new file mode 100644 index 0000000000..c580449941 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Elixir/sieve-of-eratosthenes.elixir @@ -0,0 +1,25 @@ +defmodule Prime do + def eratosthenes(limit \\ 1000) do + sieve = [false, false | Enum.to_list(2..limit)] |> List.to_tuple + check_list = [2 | Stream.iterate(3, &(&1+2)) |> Enum.take(round(:math.sqrt(limit)/2))] + Enum.reduce(check_list, sieve, fn i,tuple -> + if elem(tuple,i) do + clear_num = Stream.iterate(i*i, &(&1+i)) |> Enum.take_while(fn x -> x <= limit end) + clear(tuple, clear_num) + else + tuple + end + end) + end + + defp clear(sieve, list) do + Enum.reduce(list, sieve, fn i, acc -> put_elem(acc, i, false) end) + end +end + +limit = 199 +sieve = Prime.eratosthenes(limit) +Enum.each(0..limit, fn n -> + if x=elem(sieve, n), do: :io.format("~3w", [x]), else: :io.format(" .") + if rem(n+1, 20)==0, do: IO.puts "" +end) diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-1.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-1.erl index 9bf1560c45..0c4cfa644e 100644 --- a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-1.erl +++ b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-1.erl @@ -1,38 +1,17 @@ -%% Task: Implementation of Sieve of Eratosthenes -%% Author: Abhay Jain +-module( sieve_of_eratosthenes ). --module(sieve_module). --export([find_primes_below/1]). +-export( [primes_upto/1] ). +primes_upto( N ) -> + Ns = lists:seq( 2, N ), + Dict = dict:from_list( [{X, potential_prime} || X <- Ns] ), + {Upto_sqrt_ns, _T} = lists:split( erlang:round(math:sqrt(N)), Ns ), + {N, Prime_dict} = lists:foldl( fun find_prime/2, {N, Dict}, Upto_sqrt_ns ), + lists:sort( dict:fetch_keys(Prime_dict) ). -find_primes_below(N) -> - NumList = lists:seq(1, N), - determine_primes(NumList, 1, []). -%% Sieve of Eratosthenes algorithm -determine_primes(NumList, Index, Primes) -> - case next_prime(NumList, Index+1, length(NumList)) of - {Prime, PrimeIndex, NewNumList} -> - NewPrimes = lists:append(Primes, [Prime]), - determine_primes(NewNumList, PrimeIndex, NewPrimes); - _ -> - %% All prime numbers have been calculated - Primes - end. -next_prime(NumList, Index, Length) -> - if Index > Length -> - false; - true -> - case lists:nth(Index, NumList) of - 0 -> - next_prime(NumList, Index+1, Length); - Prime -> - NewNumList = lists:map(fun(A) -> - if A > Index andalso A rem Index == 0 -> 0; - true -> A - end - end, NumList), - {Prime, Index, NewNumList} - end - end. +find_prime( N, {Max, Dict} ) -> find_prime( dict:find(N, Dict), N, {Max, Dict} ). + +find_prime( error, _N, Acc ) -> Acc; +find_prime( {ok, _Value}, N, {Max, Dict} ) -> {Max, lists:foldl( fun dict:erase/2, Dict, lists:seq(N*N, Max, N) )}. diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-2.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-2.erl index 36abe84913..a861895b3c 100644 --- a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-2.erl +++ b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-2.erl @@ -1 +1,33 @@ -[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] +-module( sieve ). +-export( [main/1,primes/2] ). + +main(N) -> io:format("Primes: ~w~n", [ primes(2,N) ]). + +primes(M,N) -> primes(M, N,lists:seq( M, N ),[]). + +primes(M,N,_Acc,Tuples) when M > N/2-> out(Tuples); + +primes(M,N,Acc,Tuples) when length(Tuples) < 1 -> + primes(M,N,Acc,[{X, X} || X <- Acc]); + +primes(M,N,Acc,Tuples) -> + {SqrtN, _T} = lists:split( erlang:round(math:sqrt(N)), Acc ), + F = Tuples, + Ms = lists:filtermap(fun(X) -> if X > 0 -> {true, X * M}; true -> false end end, SqrtN), + P = lists:filtermap(fun(T) -> + case lists:keymember(T,1,F) of true -> + {true, lists:keyreplace(T,1,F,{T,0})}; + _-> false end end, Ms), + AA = mergeT(P,lists:last(P),1 ), + primes(M+1,N,Acc,AA). + +mergeT(L,M,Acc) when Acc == length(L) -> M; +mergeT(L,M,Acc) -> + A = lists:nth(Acc,L), + B = M, + Mer = lists:zipwith(fun(X, Y) -> if X < Y -> X; true -> Y end end, A, B), + mergeT(L,Mer,Acc+1). + +out(Tuples) -> + Primes = lists:filter( fun({_,Y}) -> Y > 0 end, Tuples), + [ X || {X,_} <- Primes ]. diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-3.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-3.erl new file mode 100644 index 0000000000..7eef5e7120 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-3.erl @@ -0,0 +1,24 @@ +-module(ossieve). +-export([main/1]). + +sieve(Candidates,SearchList,Primes,_Maximum) when length(SearchList) == 0 -> + ordsets:union(Primes,Candidates); +sieve(Candidates,SearchList,Primes,Maximum) -> + H = lists:nth(1,string:substr(Candidates,1,1)), + Reduced1 = ordsets:del_element(H, Candidates), + {Reduced2, ReducedSearch} = remove_multiples_of(H, Reduced1, SearchList), + NewPrimes = ordsets:add_element(H,Primes), + sieve(Reduced2, ReducedSearch, NewPrimes, Maximum). + +remove_multiples_of(Number,Candidates,SearchList) -> + NewSearchList = ordsets:filter( fun(X) -> X >= Number * Number end, SearchList), + RemoveList = ordsets:filter( fun(X) -> X rem Number == 0 end, NewSearchList), + {ordsets:subtract(Candidates, RemoveList), ordsets:subtract(NewSearchList, RemoveList)}. + +main(N) -> + io:fwrite("Creating Candidates...~n"), + CandidateList = lists:seq(3,N,2), + Candidates = ordsets:from_list(CandidateList), + io:fwrite("Sieving...~n"), + ResultSet = ordsets:add_element(2,sieve(Candidates,Candidates,ordsets:new(),N)), + io:fwrite("Sieved... ~w~n",[ResultSet]). diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-4.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-4.erl new file mode 100644 index 0000000000..913f7960d3 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes-4.erl @@ -0,0 +1,17 @@ +-module(sieveof). +-export([main/1,primes/1, primes/2]). + +main(X) -> io:format("Primes: ~w~n", [ primes(X) ]). + +primes(X) -> sieve(range(2, X)). +primes(X, Y) -> remove(primes(X), primes(Y)). + +range(X, X) -> [X]; +range(X, Y) -> [X | range(X + 1, Y)]. + +sieve([X]) -> [X]; +sieve([H | T]) -> [H | sieve(remove([H * X || X <-[H | T]], T))]. + +remove(_, []) -> []; +remove([H | X], [H | Y]) -> remove(X, Y); +remove(X, [H | Y]) -> [H | remove(X, Y)]. diff --git a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes.erl b/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes.erl deleted file mode 100644 index 0c4cfa644e..0000000000 --- a/Task/Sieve-of-Eratosthenes/Erlang/sieve-of-eratosthenes.erl +++ /dev/null @@ -1,17 +0,0 @@ --module( sieve_of_eratosthenes ). - --export( [primes_upto/1] ). - -primes_upto( N ) -> - Ns = lists:seq( 2, N ), - Dict = dict:from_list( [{X, potential_prime} || X <- Ns] ), - {Upto_sqrt_ns, _T} = lists:split( erlang:round(math:sqrt(N)), Ns ), - {N, Prime_dict} = lists:foldl( fun find_prime/2, {N, Dict}, Upto_sqrt_ns ), - lists:sort( dict:fetch_keys(Prime_dict) ). - - - -find_prime( N, {Max, Dict} ) -> find_prime( dict:find(N, Dict), N, {Max, Dict} ). - -find_prime( error, _N, Acc ) -> Acc; -find_prime( {ok, _Value}, N, {Max, Dict} ) -> {Max, lists:foldl( fun dict:erase/2, Dict, lists:seq(N*N, Max, N) )}. diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs index b5304c006e..6783f1256b 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs @@ -1,21 +1,20 @@ -type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //Co Inductive Stream for laziness +type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //'Co Inductive Stream for laziness new (v,cont) = { v = v; cont = cont } end -let primes = - let rec pculls p cull = CIS(cull, fun() -> pculls p (cull + p)) - let rec allculls (ps:CIS<_>) = //stream of streams of composite culls - CIS(pculls ps.v (ps.v * ps.v),fun() -> allculls (ps.cont())) - let rec (^^) (xs:CIS) (ys:CIS) = //union op for CIS's - match compare xs.v ys.v with - | -1 -> CIS(xs.v, fun() -> xs.cont() ^^ ys) // < - | 0 -> CIS(xs.v, fun() -> xs.cont() ^^ ys.cont()) // == - | _ -> CIS(ys.v, fun() -> xs ^^ ys.cont()) //must be > (= 1) - let rec join (cmpsts:CIS>) = - CIS(cmpsts.v.v, fun() -> cmpsts.v.cont() ^^ join (cmpsts.cont())) - let rec mkPrms cnd (cmpsts:CIS<_>) = - let ncnd = cnd + 1u - if cnd >= cmpsts.v then mkPrms ncnd (cmpsts.cont()) //implements 'minus' - else CIS(cnd,fun()->mkPrms ncnd cmpsts) //found a prime - let rec basePrimes = CIS(2u, fun() -> mkPrms 3u initCmpsts) - and initCmpsts = join (allculls (basePrimes)) - let genseq cis = Seq.unfold (fun (cs:CIS<_>) -> Some(cs.v, cs.cont())) cis - genseq (mkPrms 2u initCmpsts) +type Primes = uint32 + +let primesBird() = + let rec (^^) (xs: CIS) (ys: CIS) = // stream merge function + let x = xs.v in let y = ys.v + if x < y then CIS(x, fun() -> xs.cont() ^^ ys) + elif y < x then CIS(y, fun() -> xs ^^ ys.cont()) + else CIS(x, fun() -> xs.cont() ^^ ys.cont()) // no duplications + let pmltpls p = let rec nxt c = CIS(c, fun() -> nxt (c + p)) in nxt (p * p) + let rec allmltps (ps: CIS) = CIS(pmltpls ps.v, fun() -> allmltps (ps.cont())) + let rec cmpsts (css: CIS>) = + CIS(css.v.v, fun() -> (css.v.cont()) ^^ (cmpsts (css.cont()))) + let rec minusat n (cs: CIS) = + if n < cs.v then CIS(n, fun() -> minusat (n + 1u) cs) + else minusat (n + 1u) (cs.cont()) + let rec baseprms() = CIS(2u, fun() -> minusat 3u (cmpsts (allmltps (baseprms())))) + Seq.unfold (fun (ps: CIS) -> Some(ps.v, ps.cont())) + (minusat 2u (cmpsts (allmltps (baseprms())))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-10.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-10.fs new file mode 100644 index 0000000000..7093f14210 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-10.fs @@ -0,0 +1,8 @@ +let primes limit = + let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u + let buf = System.Collections.BitArray(int lmtb + 1, true) + let rec culltest i = if i <= lmtbsqrt then + let p = i + i + 3u in let s = p * (i + 1u) + i in + let rec cullp c = if c <= lmtb then buf.[int c] <- false; cullp (c + p) + (if buf.[int i] then cullp s); culltest (i + 1u) in culltest 0u + seq {yield 2u; for i = 0u to lmtb do if buf.[int i] then yield i + i + 3u } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-11.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-11.fs new file mode 100644 index 0000000000..c1e54606e3 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-11.fs @@ -0,0 +1,3 @@ + let rec count i acc = + if i > int lmtb then acc else if buf.[i] then count (i + 1) (acc + 1) else count (i + 1) acc + count 0 1 diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-12.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-12.fs new file mode 100644 index 0000000000..b63afd6809 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-12.fs @@ -0,0 +1,17 @@ + let nmrtr() = + let i = ref -2 + let rec nxti() = i:=!i + 1;if !i <= int lmtb && not buf.[!i] then nxti() else !i <= int lmtb + let inline curr() = if !i < 0 then (if !i= -1 then 2u else failwith "Enumeration not started!!!") + else let v = uint32 !i in v + v + 3u + { new System.Collections.Generic.IEnumerator<_> with + member this.Current = curr() + interface System.Collections.IEnumerator with + member this.Current = box (curr()) + member this.MoveNext() = if !i< -1 then i:=!i+1;true else nxti() + member this.Reset() = failwith "IEnumerator.Reset() not implemented!!!"a + interface System.IDisposable with + member this.Dispose() = () } + { new System.Collections.Generic.IEnumerable<_> with + member this.GetEnumerator() = nmrtr() + interface System.Collections.IEnumerable with + member this.GetEnumerator() = nmrtr() :> System.Collections.IEnumerator } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-13.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-13.fs new file mode 100644 index 0000000000..c73f43fa2b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-13.fs @@ -0,0 +1,26 @@ +type Prime = uint32 +let frstprm = 2u +let frstoddprm = 3u +let inc = 2u +let primesDict() = + let dct = System.Collections.Generic.Dictionary() + let rec nxtprm n q (bps: CIS) = + if n >= q then let bp = bps.v in let adv = bp + bp + let nbps = bps.cont() in let nbp = nbps.v + dct.Add(n + adv, adv) + nxtprm (n + inc) (nbp * nbp) nbps + else if dct.ContainsKey(n) then + let adv = dct.[n] + dct.Remove(n) |> ignore +// let mutable nn = n + adv // ugly imperative code +// while dct.ContainsKey(nn) do nn <- nn + adv +// dct.Add(nn, adv) + let rec nxtmt k = // advance to next empty spot + if dct.ContainsKey(k) then nxtmt (k + adv) + else dct.Add(k, adv) in nxtmt (n + adv) + nxtprm (n + inc) q bps + else CIS(n, fun() -> nxtprm (n + inc) q bps) + let rec oddprms() = CIS(frstoddprm, fun() -> + nxtprm (frstoddprm + inc) (frstoddprm * frstoddprm) (oddprms())) + Seq.unfold (fun (cis: CIS) -> Some(cis.v, cis.cont())) + (CIS(frstprm, fun() -> (oddprms()))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-14.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-14.fs new file mode 100644 index 0000000000..bf9bac2624 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-14.fs @@ -0,0 +1,66 @@ +let private PGSZBTS = (1 <<< 14) * 8 // sieve buffer size in bits +type private PS = class + val i:int val p:uint64 val cmpsts:uint32[] + new(i,p,c) = { i=i; p=p; cmpsts=c } end +let rec primesPaged(): System.Collections.Generic.IEnumerable<_> = + let lbpse = lazy (primesPaged().GetEnumerator()) // lazy to prevent race + let bpa = ResizeArray() // fills from above sequence as needed + let makePg low = + let nxt = low + (uint64 PGSZBTS <<< 1) + let cmpsts = Array.zeroCreate (PGSZBTS >>> 5) + let inline notprm c = cmpsts.[c >>> 5] &&& (1u <<< c) <> 0u + let rec nxti c = if c < PGSZBTS && notprm c + then nxti (c + 1) else c + let inline mrkc c = let w = c >>> 5 + cmpsts.[w] <- cmpsts.[w] ||| (1u <<< c) + let rec cullf i = + if notprm i then cullf (i + 1) else + let p = 3 + i + i in let sqr = p * p + if uint64 sqr < nxt then + let rec cullp c = if c < PGSZBTS then mrkc c; cullp (c + p) + else cullf (i + 1) in cullp ((sqr - 3) >>> 1) + if low <= 3UL then cullf 0 // special culling for the first page + else // cull rest based on a secondary base prime stream + let bpse = lbpse.Force() + if bpa.Count <= 0 then // move past 2 to 3 + bpse.MoveNext() |> ignore; bpse.MoveNext() |> ignore + let rec fill np = + if np * np >= nxt then + let bpasz = bpa.Count + let rec cull i = + if i < bpasz then + let p = bpa.[i] in let sqr = p * p in let pi = int p + let strt = if sqr >= low then int (sqr - low) >>> 1 + else let r = int (((low - sqr) >>> 1) % p) + if r = 0 then 0 else int p - r + let rec cullp c = if c < PGSZBTS then mrkc c; cullp (c + pi) + cullp strt; cull (i + 1) in cull 0 + else bpa.Add(np); bpse.MoveNext() |> ignore + fill bpse.Current + fill bpse.Current // fill pba as necessary and do cull + let ni = nxti 0 in let np = low + uint64 (ni <<< 1) + PS(ni, np, cmpsts) + let nmrtr() = + let ps = ref (PS(0, 0UL, Array.zeroCreate 0)) + { new System.Collections.Generic.IEnumerator<_> with + member this.Current = (!ps).p + interface System.Collections.IEnumerator with + member this.Current = box ((!ps).p) + member this.MoveNext() = + let drps = !ps in let i = drps.i in let p = drps.p + let cmpsts = drps.cmpsts in let lmt = cmpsts.Length <<< 5 + if p < 3UL then (if p < 2UL then ps := PS(0, 2UL, cmpsts); true + else ps := makePg 3UL; true) else + let inline notprm c = cmpsts.[c >>> 5] &&& (1u <<< c) <> 0u + let rec nxti c = if c < lmt && notprm c + then nxti (c + 1) else c + let ni = nxti (i + 1) in let np = p + uint64 ((ni - i) <<< 1) + if ni < lmt then ps := PS(ni, np, cmpsts); true + else ps := makePg np; true + member this.Reset() = failwith "IEnumerator.Reset() not implemented!!!" + interface System.IDisposable with + member this.Dispose() = () } + { new System.Collections.Generic.IEnumerable<_> with + member this.GetEnumerator() = nmrtr() + interface System.Collections.IEnumerable with + member this.GetEnumerator() = nmrtr() :> System.Collections.IEnumerator } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs index d048100abe..1bc45177cb 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs @@ -1,21 +1,21 @@ -type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //Co Inductive Stream for laziness +type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //'Co Inductive Stream for laziness new (v,cont) = { v = v; cont = cont } end -let primes = - let rec pculls p cull = CIS(cull, fun() -> pculls p (cull + 2u * p)) - let rec allculls (ps:CIS<_>) = //stream of streams of composite culls - CIS(pculls ps.v (ps.v * ps.v),fun() -> allculls (ps.cont())) - let rec (^^) (xs:CIS) (ys:CIS) = //union op for CIS's - match compare xs.v ys.v with - | -1 -> CIS(xs.v, fun() -> xs.cont() ^^ ys) // < - | 0 -> CIS(xs.v, fun() -> xs.cont() ^^ ys.cont()) // == - | _ -> CIS(ys.v, fun() -> xs ^^ ys.cont()) //must be > (= 1) - let rec join (cmpsts:CIS>) = - CIS(cmpsts.v.v, fun() -> cmpsts.v.cont() ^^ join (cmpsts.cont())) - let rec mkPrms cnd (cmpsts:CIS<_>) = - let ncnd = cnd + 2u - if cnd >= cmpsts.v then mkPrms ncnd (cmpsts.cont()) //implements 'minus' - else CIS(cnd,fun()->mkPrms ncnd cmpsts) //found a prime - let rec oddBasePrimes = CIS(3u, fun() -> mkPrms 5u initCmpsts) - and initCmpsts = join (allculls (oddBasePrimes)) - let genseq cis = Seq.unfold (fun (cs:CIS<_>) -> Some(cs.v, cs.cont())) cis - seq { yield 2u; yield! genseq (mkPrms 3u initCmpsts) } +type Prime = uint32 + +let primesBirdOdds() = + let rec (^^) (xs: CIS) (ys: CIS) = // stream merge function + let x = xs.v in let y = ys.v + if x < y then CIS(x, fun() -> xs.cont() ^^ ys) + elif y < x then CIS(y, fun() -> xs ^^ ys.cont()) + else CIS(x, fun() -> xs.cont() ^^ ys.cont()) // no duplications + let pmltpls p = let adv = p + p + let rec nxt c = CIS(c, fun() -> nxt (c + adv)) in nxt (p * p) + let rec allmltps (ps: CIS) = CIS(pmltpls ps.v, fun() -> allmltps (ps.cont())) + let rec cmpsts (css: CIS>) = + CIS(css.v.v, fun() -> (css.v.cont()) ^^ (cmpsts (css.cont()))) + let rec minusat n (cs: CIS) = + if n < cs.v then CIS(n, fun() -> minusat (n + 2u) cs) + else minusat (n + 2u) (cs.cont()) + let rec oddprms() = CIS(3u, fun() -> minusat 5u (cmpsts (allmltps (oddprms())))) + Seq.unfold (fun (ps: CIS) -> Some(ps.v, ps.cont())) + (CIS(2u, fun() -> minusat 3u (cmpsts (allmltps (oddprms()))))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs index eda1d46ed1..fc4da68ce7 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs @@ -1,11 +1,24 @@ -let primes limit = - let buf = System.Collections.BitArray(int limit + 1, true) - let cull p = { p * p .. p .. limit } |> Seq.iter (fun c -> buf.[int c] <- false) - { 2u .. uint32 (sqrt (double limit)) } |> Seq.iter (fun c -> if buf.[int c] then cull c) - { 2u .. limit } |> Seq.map (fun i -> if buf.[int i] then i else 0u) |> Seq.filter ((<>) 0u) +type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //'Co Inductive Stream for laziness + new (v,cont) = { v = v; cont = cont } end +type Prime = uint32 -[] -let main argv = - if argv = null || argv.Length = 0 then failwith "no command line argument for limit!!!" - printfn "%A" (primes (System.UInt32.Parse argv.[0]) |> Seq.length) - 0 // return an integer exit code +let primesTreeFold() = + let rec (^^) (xs: CIS) (ys: CIS) = // merge streams; no duplicates + let x = xs.v in let y = ys.v + if x < y then CIS(x, fun() -> xs.cont() ^^ ys) + elif y < x then CIS(y, fun() -> xs ^^ ys.cont()) + else CIS(x, fun() -> xs.cont() ^^ ys.cont()) + let pmltpls p = let adv = p + p + let rec nxt c = CIS(c, fun() -> nxt (c + adv)) in nxt (p * p) + let rec allmltps (ps: CIS) = CIS(pmltpls ps.v, fun() -> allmltps (ps.cont())) + let rec pairs (css: CIS>) = + let ncss = css.cont() + CIS(css.v ^^ ncss.v, fun() -> pairs (ncss.cont())) + let rec cmpsts (css: CIS>) = + CIS(css.v.v, fun() -> (css.v.cont()) ^^ (cmpsts << pairs << css.cont)()) + let rec minusat n (cs: CIS) = + if n < cs.v then CIS(n, fun() -> minusat (n + 2u) cs) + else minusat (n + 2u) (cs.cont()) + let rec oddprms() = CIS(3u, fun() -> (minusat 5u << cmpsts << allmltps) (oddprms())) + Seq.unfold (fun (ps: CIS) -> Some(ps.v, ps.cont())) + (CIS(2u, fun() -> (minusat 3u << cmpsts << allmltps) (oddprms()))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs index 4c9836434c..9634d42d70 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs @@ -1,9 +1,38 @@ -let primes limit = - let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u - let buf = System.Collections.BitArray(int lmtb + 1, true) - let cull i = let p = i + i + 3u in let s = p * (i + 1u) + i in - { s .. p .. lmtb } |> Seq.iter (fun c -> buf.[int c] <- false) - { 0u .. lmtbsqrt } |> Seq.iter (fun i -> if buf.[int i] then cull i ) - let oddprms = { 0u .. lmtb } |> Seq.map (fun i -> if buf.[int i] then i + i + 3u else 0u) - |> Seq.filter ((<>) 0u) - seq { yield 2u; yield! oddprms } +[] +module MinHeap = + + type HeapEntry<'V> = struct val k:uint32 val v:'V new(k,v) = {k=k;v=v} end + [] + [] + type PQ<'V> = + | Mt + | Br of HeapEntry<'V> * PQ<'V> * PQ<'V> + + let empty = Mt + + let peekMin = function | Br(kv, _, _) -> Some(kv.k, kv.v) + | _ -> None + + let rec push wk wv = + function | Mt -> Br(HeapEntry(wk, wv), Mt, Mt) + | Br(vkv, ll, rr) -> + if wk <= vkv.k then + Br(HeapEntry(wk, wv), push vkv.k vkv.v rr, ll) + else Br(vkv, push wk wv rr, ll) + + let private siftdown wk wv pql pqr = + let rec sift pl pr = + match pl with + | Mt -> Br(HeapEntry(wk, wv), Mt, Mt) + | Br(vkvl, pll, plr) -> + match pr with + | Mt -> if wk <= vkvl.k then Br(HeapEntry(wk, wv), pl, Mt) + else Br(vkvl, Br(HeapEntry(wk, wv), Mt, Mt), Mt) + | Br(vkvr, prl, prr) -> + if wk <= vkvl.k && wk <= vkvr.k then Br(HeapEntry(wk, wv), pl, pr) + elif vkvl.k <= vkvr.k then Br(vkvl, sift pll plr, pr) + else Br(vkvr, pl, sift prl prr) + sift pql pqr + + let replaceMin wk wv = function | Mt -> Mt + | Br(_, ll, rr) -> siftdown wk wv ll rr diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs index 7093f14210..c21cfa0a7d 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs @@ -1,8 +1,6 @@ -let primes limit = - let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u - let buf = System.Collections.BitArray(int lmtb + 1, true) - let rec culltest i = if i <= lmtbsqrt then - let p = i + i + 3u in let s = p * (i + 1u) + i in - let rec cullp c = if c <= lmtb then buf.[int c] <- false; cullp (c + p) - (if buf.[int i] then cullp s); culltest (i + 1u) in culltest 0u - seq {yield 2u; for i = 0u to lmtb do if buf.[int i] then yield i + i + 3u } +type CIS<'T> = struct val v: 'T val cont: unit -> CIS<'T> new(v,cont) = {v=v;cont=cont} end +type Prime = uint32 +let frstprm = 2u +let frstoddprm = 3u +let inc1 = 1u +let inc = 2u diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs index c1e54606e3..dcca30c0f5 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs @@ -1,3 +1,31 @@ - let rec count i acc = - if i > int lmtb then acc else if buf.[i] then count (i + 1) (acc + 1) else count (i + 1) acc - count 0 1 +type CIS<'T> = struct val v: 'T val cont: unit -> CIS<'T> new(v,cont) = {v=v;cont=cont} end +type Prime = uint64 +let frstprm = 2UL +let frstoddprm = 3UL +let inc = 2UL + +let primesPQ() = + let pmult p (xs: CIS) = // does map (* p) xs + let rec nxtm (cs: CIS) = + CIS(p * cs.v, fun() -> nxtm (cs.cont())) in nxtm xs + let insertprime p xs table = + MinHeap.push (p * p) (pmult p xs) table + let rec sieve' (ns: CIS) table = + let nextcomposite = match MinHeap.peekMin table with + | None -> ns.v // never happens + | Some (k, _) -> k + let rec adjust table = + let (n, advs) = match MinHeap.peekMin table with + | None -> (ns.v, ns.cont()) // never happens + | Some kv -> kv + if n <= ns.v then adjust (MinHeap.replaceMin advs.v (advs.cont()) table) + else table + if nextcomposite <= ns.v then sieve' (ns.cont()) (adjust table) + else let n = ns.v in CIS(n, fun() -> + let nxtns = ns.cont() in sieve' nxtns (insertprime n nxtns table)) + let rec sieve (ns: CIS) = let n = ns.v in CIS(n, fun() -> + let nxtns = ns.cont() in sieve' nxtns (insertprime n nxtns MinHeap.empty)) + let odds = // is the odds CIS from 3 up + let rec nxto i = CIS(i, fun() -> nxto (i + inc)) in nxto frstoddprm + Seq.unfold (fun (cis: CIS) -> Some(cis.v, cis.cont())) + (CIS(frstprm, fun() -> (sieve odds))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs index b63afd6809..252b9d203e 100644 --- a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs @@ -1,17 +1,20 @@ - let nmrtr() = - let i = ref -2 - let rec nxti() = i:=!i + 1;if !i <= int lmtb && not buf.[!i] then nxti() else !i <= int lmtb - let inline curr() = if !i < 0 then (if !i= -1 then 2u else failwith "Enumeration not started!!!") - else let v = uint32 !i in v + v + 3u - { new System.Collections.Generic.IEnumerator<_> with - member this.Current = curr() - interface System.Collections.IEnumerator with - member this.Current = box (curr()) - member this.MoveNext() = if !i< -1 then i:=!i+1;true else nxti() - member this.Reset() = failwith "IEnumerator.Reset() not implemented!!!"a - interface System.IDisposable with - member this.Dispose() = () } - { new System.Collections.Generic.IEnumerable<_> with - member this.GetEnumerator() = nmrtr() - interface System.Collections.IEnumerable with - member this.GetEnumerator() = nmrtr() :> System.Collections.IEnumerator } +let primesPQx() = + let rec nxtprm n pq q (bps: CIS) = + if n >= q then let bp = bps.v in let adv = bp + bp + let nbps = bps.cont() in let nbp = nbps.v + nxtprm (n + inc) (MinHeap.push (n + adv) adv pq) (nbp * nbp) nbps + else let ck, cv = match MinHeap.peekMin pq with + | None -> (q, inc) // only happens until first insertion + | Some kv -> kv + if n >= ck then let rec adjpq ck cv pq = + let npq = MinHeap.replaceMin (ck + cv) cv pq + match MinHeap.peekMin npq with + | None -> npq // never happens + | Some(nk, nv) -> if n >= nk then adjpq nk nv npq + else npq + nxtprm (n + inc) (adjpq ck cv pq) q bps + else CIS(n, fun() -> nxtprm (n + inc) pq q bps) + let rec oddprms() = CIS(frstoddprm, fun() -> + nxtprm (frstoddprm + inc) MinHeap.empty (frstoddprm * frstoddprm) (oddprms())) + Seq.unfold (fun (cis: CIS) -> Some(cis.v, cis.cont())) + (CIS(frstprm, fun() -> (oddprms()))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-8.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-8.fs new file mode 100644 index 0000000000..eda1d46ed1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-8.fs @@ -0,0 +1,11 @@ +let primes limit = + let buf = System.Collections.BitArray(int limit + 1, true) + let cull p = { p * p .. p .. limit } |> Seq.iter (fun c -> buf.[int c] <- false) + { 2u .. uint32 (sqrt (double limit)) } |> Seq.iter (fun c -> if buf.[int c] then cull c) + { 2u .. limit } |> Seq.map (fun i -> if buf.[int i] then i else 0u) |> Seq.filter ((<>) 0u) + +[] +let main argv = + if argv = null || argv.Length = 0 then failwith "no command line argument for limit!!!" + printfn "%A" (primes (System.UInt32.Parse argv.[0]) |> Seq.length) + 0 // return an integer exit code diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-9.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-9.fs new file mode 100644 index 0000000000..4c9836434c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-9.fs @@ -0,0 +1,9 @@ +let primes limit = + let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u + let buf = System.Collections.BitArray(int lmtb + 1, true) + let cull i = let p = i + i + 3u in let s = p * (i + 1u) + i in + { s .. p .. lmtb } |> Seq.iter (fun c -> buf.[int c] <- false) + { 0u .. lmtbsqrt } |> Seq.iter (fun i -> if buf.[int i] then cull i ) + let oddprms = { 0u .. lmtb } |> Seq.map (fun i -> if buf.[int i] then i + i + 3u else 0u) + |> Seq.filter ((<>) 0u) + seq { yield 2u; yield! oddprms } diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-10.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-10.hs index 0fcbf4cb42..f79534a9b9 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-10.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-10.hs @@ -1,3 +1,12 @@ -tail . concat - . unfoldr (\(a:b:r)-> case span (< head b) a of (h,t)-> Just (h, minus t b:r)) - . scanl1 (zipWith(+) . tail) $ tails [1..] +primesW :: [Int] +primesW = [2,3,5,7] ++ _Y ( (11:) . gapsW 13 (tail wheel) . _U . + map (\p-> + map (p*) . dropWhile (< p) $ + scanl (+) (p - rem (p-11) 210) wheel) ) + +gapsW k (d:w) s@(c:cs) | k < c = k : gapsW (k+d) w s -- set difference + | otherwise = gapsW (k+d) w cs -- k==c + +wheel = 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:wheel + -- cycle $ zipWith (-) =<< tail $ [i | i <- [11..221], gcd i 210 == 1] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-11.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-11.hs index 6800fccdcf..f19990e5f7 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-11.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-11.hs @@ -1,23 +1,30 @@ -> mapM_ (print . take 15) $ take 10 $ scanl1 (zipWith(+)) $ repeat [2..] -[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] -[ 4, 6, 8,10,12,14,16,18, 20, 22, 24, 26, 28, 30] -[ 6, 9,12,15,18,21,24,27, 30, 33, 36, 39, 42, 45] -[ 8,12,16,20,24,28,32,36, 40, 44, 48, 52, 56, 60] -[10,15,20,25,30,35,40,45, 50, 55, 60, 65, 70, 75] -[12,18,24,30,36,42,48,54, 60, 66, 72, 78, 84, 90] -[14,21,28,35,42,49,56,63, 70, 77, 84, 91, 98,105] -[16,24,32,40,48,56,64,72, 80, 88, 96,104,112,120] -[18,27,36,45,54,63,72,81, 90, 99,108,117,126,135] -[20,30,40,50,60,70,80,90,100,110,120,130,140,150] +data PriorityQ k v = Mt + | Br !k v !(PriorityQ k v) !(PriorityQ k v) + deriving (Eq, Ord, Read, Show) -> mapM_ (print . take 15) $ take 10 $ scanl1 (zipWith(+) . tail) $ tails [1..] -[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] -[ 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32] -[ 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51] -[ 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72] -[ 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] -[ 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96,102,108,114,120] -[ 49, 56, 63, 70, 77, 84, 91, 98,105,112,119,126,133,140,147] -[ 64, 72, 80, 88, 96,104,112,120,128,136,144,152,160,168,176] -[ 81, 90, 99,108,117,126,135,144,153,162,171,180,189,198,207] -[100,110,120,130,140,150,160,170,180,190,200,210,220,230,240] +emptyPQ :: PriorityQ k v +emptyPQ = Mt + +peekMinPQ :: PriorityQ k v -> Maybe (k, v) +peekMinPQ Mt = Nothing +peekMinPQ (Br k v _ _) = Just (k, v) + +pushPQ :: Ord k => k -> v -> PriorityQ k v -> PriorityQ k v +pushPQ wk wv Mt = Br wk wv Mt Mt +pushPQ wk wv (Br vk vv pl pr) + | wk <= vk = Br wk wv (pushPQ vk vv pr) pl + | otherwise = Br vk vv (pushPQ wk wv pr) pl + +siftdown :: Ord k => k -> v -> PriorityQ k v -> PriorityQ k v -> PriorityQ k v +siftdown wk wv Mt _ = Br wk wv Mt Mt +siftdown wk wv (pl @ (Br vk vv _ _)) Mt + | wk <= vk = Br wk wv pl Mt + | otherwise = Br vk vv (Br wk wv Mt Mt) Mt +siftdown wk wv (pl @ (Br vkl vvl pll plr)) (pr @ (Br vkr vvr prl prr)) + | wk <= vkl && wk <= vkr = Br wk wv pl pr + | vkl <= vkr = Br vkl vvl (siftdown wk wv pll plr) pr + | otherwise = Br vkr vvr pl (siftdown wk wv prl prr) + +replaceMinPQ :: Ord k => k -> v -> PriorityQ k v -> PriorityQ k v +replaceMinPQ wk wv Mt = Mt +replaceMinPQ wk wv (Br _ _ pl pr) = siftdown wk wv pl pr diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-12.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-12.hs new file mode 100644 index 0000000000..adadd068ea --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-12.hs @@ -0,0 +1,24 @@ +-- (c) 2006-2007 Melissa O'Neill. Code may be used freely so long as +-- this copyright message is retained and changed versions of the file +-- are clearly marked. +-- the only changes are the names of the called PQ functions and the +-- included processing for the result of the peek function being a maybe tuple. + +primesPQ() = 2 : sieve [3,5..] + where + sieve [] = [] + sieve (x:xs) = x : sieve' xs (insertprime x xs emptyPQ) + where + insertprime p xs table = pushPQ (p*p) (map (* p) xs) table + sieve' [] table = [] + sieve' (x:xs) table + | nextComposite <= x = sieve' xs (adjust table) + | otherwise = x : sieve' xs (insertprime x xs table) + where + nextComposite = case peekMinPQ table of + Just (c, _) -> c + adjust table + | n <= x = adjust (replaceMinPQ n' ns table) + | otherwise = table + where (n, n':ns) = case peekMinPQ table of + Just tpl -> tpl diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-13.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-13.hs new file mode 100644 index 0000000000..069c89051f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-13.hs @@ -0,0 +1,22 @@ +primesPQx :: () -> [Int] +primesPQx() = 2 : _Y ((3 :) . sieve 5 emptyPQ 9) -- initBasePrms + where + _Y g = g (_Y g) -- non-sharing multi-stage fixpoint combinator OR +-- initBasePrms = 3 : sieve 5 emptyPQ 9 initBasePrms -- single stage + insertprime p table = let adv = 2 * p in let nv = p * p + adv in + nv `seq` pushPQ nv adv table + sieve n table q bps@(bp:bps') + | n >= q = let nbp = head bps' in + sieve (n + 2) (insertprime bp table) (nbp * nbp) bps' + | n >= nextComposite = sieve (n + 2) (adjust table) q bps + | otherwise = n : sieve (n + 2) table q bps + where + nextComposite = case peekMinPQ table of + Nothing -> q -- at beginning when queue empty + Just (c, _) -> c + adjust table + | c <= n = let nc = c + adv in + nc `seq` adjust (replaceMinPQ nc adv table) + | otherwise = table + where (c, adv) = case peekMinPQ table of + Just ct -> ct diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-14.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-14.hs new file mode 100644 index 0000000000..971c310d6e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-14.hs @@ -0,0 +1,42 @@ +import Data.Bits +import Data.Array.Base +import Control.Monad.ST +import Data.Array.ST (runSTUArray, STUArray(..)) + +type PrimeType = Int +szPGBTS = (2^14) * 8 :: PrimeType -- CPU L1 cache in bits + +primesPaged :: () -> [PrimeType] +primesPaged() = 2 : _Y (listPagePrms . pagesFrom 0) where + _Y g = g (_Y g) -- non-sharing multi-stage fixpoint combinator + listPagePrms (hdpg @ (UArray lowi _ rng _) : tlpgs) = + let loop i = if i >= rng then listPagePrms tlpgs + else if unsafeAt hdpg i then loop (i + 1) + else let ii = lowi + fromIntegral i in + case 3 + ii + ii of + p -> p `seq` p : loop (i + 1) in loop 0 + makePg lowi bps = runSTUArray $ do + let limi = lowi + szPGBTS - 1 + let nxt = 3 + limi + limi -- last candidate in range + cmpsts <- newArray (lowi, limi) False + let pbts = fromIntegral szPGBTS + let cull (p:ps) = + let sqr = p * p in + if sqr > nxt then return cmpsts + else let pi = fromIntegral p in + let cullp c = if c > pbts then return () + else do + unsafeWrite cmpsts c True + cullp (c + pi) in + let a = (sqr - 3) `shiftR` 1 in + let s = if a >= lowi then fromIntegral (a - lowi) + else let r = fromIntegral ((lowi - a) `rem` p) in + if r == 0 then 0 else pi - r in + do { cullp s; cull ps} + if lowi == 0 then do + pg0 <- unsafeFreezeSTUArray cmpsts + cull $ listPagePrms [pg0] + else cull bps + pagesFrom lowi bps = + let cf lwi = case makePg lwi bps of + pg -> pg `seq` pg : cf (lwi + szPGBTS) in cf lowi diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-15.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-15.hs new file mode 100644 index 0000000000..66a2593fcb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-15.hs @@ -0,0 +1,3 @@ +zipWith (flip (!!)) [0..] -- or: take n . last . take n ... + . scanl1 minus + . scanl1 (zipWith (+)) $ repeat [2..] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-16.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-16.hs new file mode 100644 index 0000000000..f86cda8ec8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-16.hs @@ -0,0 +1,3 @@ +unfoldr (\(a:b:t) -> Just . (head &&& (:t) . (`minus` b) + . tail) $ a) + . scanl1 (zipWith (+)) $ repeat [2..] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-17.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-17.hs new file mode 100644 index 0000000000..64a5c5ef57 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-17.hs @@ -0,0 +1,5 @@ +tail . concat + . unfoldr (\(a:b:t) -> Just . second ((:t) . (`minus` b)) + . span (< head b) $ a) + . scanl1 (zipWith (+) . tail) $ tails [1..] + -- $ [ [n*n, n*n+n..] | n <- [1..] ] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-18.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-18.hs new file mode 100644 index 0000000000..4f17ef912a --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-18.hs @@ -0,0 +1,4 @@ +fix ( (2:) . concat + . unfoldr (\(a:b:t) -> Just . second ((:t) . (`minus` b)) + . span (< head b) $ a) + . ([3..] :) . map (\p-> [p*p, p*p+p..]) ) diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-19.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-19.hs new file mode 100644 index 0000000000..3d39f11468 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-19.hs @@ -0,0 +1,23 @@ +> mapM_ (print . take 15) $ take 10 $ scanl1 (zipWith(+)) $ repeat [2..] +[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] +[ 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32] +[ 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48] +[ 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64] +[ 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80] +[ 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96] +[ 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91, 98,105,112] +[ 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96,104,112,120,128] +[ 18, 27, 36, 45, 54, 63, 72, 81, 90, 99,108,117,126,135,144] +[ 20, 30, 40, 50, 60, 70, 80, 90,100,110,120,130,140,150,160] + +> mapM_ (print . take 15) $ take 10 $ scanl1 (zipWith(+) . tail) $ tails [1..] +[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] +[ 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32] +[ 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51] +[ 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72] +[ 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] +[ 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96,102,108,114,120] +[ 49, 56, 63, 70, 77, 84, 91, 98,105,112,119,126,133,140,147] +[ 64, 72, 80, 88, 96,104,112,120,128,136,144,152,160,168,176] +[ 81, 90, 99,108,117,126,135,144,153,162,171,180,189,198,207] +[100,110,120,130,140,150,160,170,180,190,200,210,220,230,240] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs index 2b6656ce04..17693021db 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs @@ -1,6 +1,9 @@ primesTo m = 2 : eratos [3,5..m] where - eratos (p : xs) | p*p>m = p : xs - | otherwise = p : eratos (xs `minus` [p*p, p*p+2*p..m]) + eratos (p : xs) + | p*p > m = p : xs + | otherwise = p : eratos (xs `minus` [p*p, p*p+2*p..m]) + -- map (p*) [p,p+2..] + -- map (p*) (p:xs) -- (Euler's sieve) minus a@(x:xs) b@(y:ys) = case compare x y of LT -> x : minus xs b diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs index 2d43670c1c..f88220823d 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs @@ -1,3 +1,3 @@ -primesE = sieve [2..] -- slow, ~ n^2 +primesE = sieve [2..] where - sieve (p:xs) = p : sieve (minus xs [p,p+p..]) + sieve (p:xs) = p : sieve (minus xs [p, p+p..]) diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs index 08a67954c3..ffd6526088 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs @@ -1,6 +1,5 @@ -primesEQ = after 4 [2..] (sieve primesEQ) -- faster, ~ n^1.5 - where -- q==p*p - sieve (p:t) q xs = after (head t^2) (minus xs [q,q+p..]) (sieve t) - -after q (x:xs) k | x < q = x : after q xs k - | otherwise = k x xs +primesPE = 2 : sieve [3..] 4 primesPE + where + sieve (x:xs) q (p:t) + | x < q = x : sieve xs q (p:t) + | otherwise = sieve (minus xs [q, q+p..]) (head t^2) t diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-7.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-7.hs index 48431cbef8..d41feef2d1 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-7.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-7.hs @@ -1,10 +1,10 @@ -primes = _Y $ ((2:) . minus [3..] - . foldr (\x-> (x*x :) . union [x*x+x, x*x+2*x..]) []) +import Data.List (inits) -_Y g = g (_Y g) -- non-sharing multistage fixpoint combinator --- = let x = g x in g x -- sharing two-stage fixpoint combinator - -union a@(x:xs) b@(y:ys) = case compare x y of - LT -> x : union xs b - EQ -> x : union xs ys - GT -> y : union a ys +primesSE = 2 : sieve 3 4 (tail primesSE) (inits primesSE) + where + sieve x q ps (fs:ft) = + foldl minus [x..q-1] [[n, n+f..q-1] | f <- fs, let n=div x f * f] + -- [i|(i,True) <- assocs ( accumArray (\ b c -> False) + -- True (x,q-1) [(i,()) | f <- fs, let n=div(x+f-1)f*f, + -- i <- [n, n+f..q-1]] :: UArray Int Bool )] + ++ sieve q (head ps^2) (tail ps) ft diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-8.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-8.hs index 5dbe9fadb9..5ffd86b063 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-8.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-8.hs @@ -1,9 +1,11 @@ -primes :: [Int] -primes = 2 : _Y ((3 :) . gaps 5 . _U . map(\p-> [p*p, p*p+2*p..])) +primesB = _Y $ ((2:) . minus [3..] + . foldr (\x-> (x*x :) . union [x*x+x, x*x+2*x..]) []) -gaps k s@(x:xs) | k < x = k : gaps (k+2) s -- ~= ([k,k+2..] \\ s) - | otherwise = gaps (k+2) xs -- when null(s\\[k,k+2..]) +_Y g = g (_Y g) -- = g . g . g . ... non-sharing multistage fixpoint combinator +-- = let x = g x in g x -- = g (fix g) two-stage fixpoint combinator +-- = let x = g x in x -- = fix g sharing fixpoint combinator -_U ((x:xs):t) = x : (union xs . _U . pairs) t -- ~= nub . sort . concat - where - pairs (xs:ys:t) = union xs ys : pairs t +union a@(x:xs) b@(y:ys) = case compare x y of + LT -> x : union xs b + EQ -> x : union xs ys + GT -> y : union a ys diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-9.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-9.hs index c6b54a210f..53eb96f9a7 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-9.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-9.hs @@ -1,2 +1,9 @@ -zipWith (flip (!!)) [0..] - . scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] +primes :: [Int] +primes = 2 : _Y ( (3:) . gaps 5 . _U . map(\p-> [p*p, p*p+2*p..]) ) + +gaps k s@(c:cs) | k < c = k : gaps (k+2) s -- ~= ([k,k+2..] \\ s) + | otherwise = gaps (k+2) cs -- when null(s\\[k,k+2..]) + +_U ((x:xs):t) = x : (union xs . _U . pairs) t -- ~= nub . sort . concat + where + pairs (xs:ys:t) = union xs ys : pairs t diff --git a/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes.julia b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes.julia new file mode 100644 index 0000000000..9a1eed7a81 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Julia/sieve-of-eratosthenes.julia @@ -0,0 +1,17 @@ +# Returns an array of positive prime numbers less than or equal to lim +function sieve(lim :: Int) + is_prime :: Array = trues(lim) + llim :: Int = isqrt(lim) + result :: Array = [2] #Initial array + for i = 3:2:lim + if is_prime[i] + if i <= llim + for j = i*i:2*i:lim + is_prime[j] = false + end + end + push!(result,i) + end + end + return result +end diff --git a/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-1.logtalk b/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-1.logtalk new file mode 100644 index 0000000000..e169cc7b83 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-1.logtalk @@ -0,0 +1,38 @@ +:- object(sieve). + + :- public(primes/2). + + :- coinductive([ + sieve/2, filter/3 + ]). + + % computes a coinductive list with all the primes in the 2..N interval + primes(N, Primes) :- + generate_infinite_list(N, List), + sieve(List, Primes). + + % generate a coinductive list with a 2..N repeating patern + generate_infinite_list(N, List) :- + sequence(2, N, List, List). + + sequence(Sup, Sup, [Sup| List], List) :- + !. + sequence(Inf, Sup, [Inf| List], Tail) :- + Next is Inf + 1, + sequence(Next, Sup, List, Tail). + + sieve([H| T], [H| R]) :- + filter(H, T, F), + sieve(F, R). + + filter(H, [K| T], L) :- + ( K > H, K mod H =:= 0 -> + % throw away the multiple we found + L = T1 + ; % we must not throw away the integer used for filtering + % as we must return a filtered coinductive list + L = [K| T1] + ), + filter(H, T, T1). + +:- end_object. diff --git a/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-2.logtalk b/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-2.logtalk new file mode 100644 index 0000000000..06afd043b6 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Logtalk/sieve-of-eratosthenes-2.logtalk @@ -0,0 +1,3 @@ +?- sieve::primes(20, P). +P = [2, 3|_S1], % where + _S1 = [5, 7, 11, 13, 17, 19, 2, 3|_S1] . diff --git a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-1.m b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-1.m index e2e8acb011..b6bed71b17 100644 --- a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-1.m +++ b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-1.m @@ -1,15 +1,14 @@ -function primeList = sieveOfEratosthenes(lastNumber) +function P = erato(x) % Sieve of Eratosthenes: returns all primes between 2 and x - list = (2:lastNumber); %Construct list of numbers - primeList = []; %Preallocate prime list + P = [0 2:x] ; % Create vector with all ints between 2 and x where + % position 1 is hard-coded as 0 since 1 is not a prime. - while( list(1)^2 () + done done; - (is_prime) + is_prime.(0) <- false; + is_prime.(1) <- false; + is_prime diff --git a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml index bf5d16820e..ea7a9f9958 100644 --- a/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml +++ b/Task/Sieve-of-Eratosthenes/OCaml/sieve-of-eratosthenes-2.ocaml @@ -1,9 +1,9 @@ let primes n = - let _, primes = - Array.fold_left (fun (i,acc) -> function - | true -> (i+1, i::acc) - | false -> (i+1, acc)) - (0, []) - (sieve n) + let primes, _ = + let sieve = sieve n in + Array.fold_right + (fun is_prime (xs, i) -> if is_prime then (i::xs, i-1) else (xs, i-1)) + sieve + ([], Array.length sieve - 1) in - List.tl(List.tl(List.rev primes)) + primes diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl index 34e6783944..73dff3b16f 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl @@ -3,52 +3,104 @@ package Tie::SieveOfEratosthenes; sub TIEARRAY { - my $class = shift; - my @primes = (2,3,5,7); - return bless \@primes, $class; + my $class = shift; + bless \$class, $class; } -sub prextend { # Extend the given list of primes using a segment sieve - my($primes, $to) = @_; - $to-- unless $to & 1; # Ensure end is odd - return if $to < $primes->[-1]; - my $sqrtn = int(sqrt($to)+0.001); - prextend($primes, $sqrtn) if $primes->[-1] < $sqrtn; - my($segment, $startp) = ('', $primes->[-1]+1); - my($s_beg, $s_len) = ($startp >> 1, ($to>>1) - ($startp>>1)); - for my $p (@$primes) { - last if $p > $sqrtn; - if ($p >= 3) { - my $p2 = $p*$p; - if ($p2 < $startp) { # Bump up to next odd multiple of p >= startp - my $f = 1+int(($startp-1)/$p); - $p2 = $p * ($f | 1); - } - for (my $s = ($p2>>1)-$s_beg; $s <= $s_len; $s += $p) { - vec($segment, $s, 1) = 1; # Mark composites in segment - } - } - } - # Now add all the primes found in the segment to the list - do { push @$primes, 1+2*($_+$s_beg) if !vec($segment,$_,1) } for 0 .. $s_len; -} +# If set to true, produces copious output. Observing this output +# is an excellent way to gain insight into how the algorithm works. +use constant DEBUG => 0; + +# If set to true, causes the code to skip over even numbers, +# improving runtime. It does not alter the output content, only the speed. +use constant WHEEL2 => 0; + +BEGIN { + + # This is loosely based on the Python implementation of this task, + # specifically the "Infinite generator with a faster algorithm" + + my @primes = (2, 3); + my $ps = WHEEL2 ? 1 : 0; + my $p = $primes[$ps]; + my $q = $p*$p; + my $incr = WHEEL2 ? 2 : 1; + my $candidate = $primes[-1] + $incr; + my %sieve; + + print "Initial: p = $p, q = $q, candidate = $candidate\n" if DEBUG; + + sub FETCH { + my $n = pop; + return if $n < 0; + return $primes[$n] if $n <= $#primes; + OUTER: while( 1 ) { + + # each key in %sieve is a composite number between + # p and p-squared. Each value in %sieve is $incr x the prime + # which acted as a 'seed' for that key. We use the value + # to step through multiples of the seed-prime, until we find + # an empty slot in %sieve. + while( my $s = delete $sieve{$candidate} ) { + print "$candidate a multiple of ".($s/$incr).";\t\t" if DEBUG; + my $composite = $candidate + $s; + $composite += $s while exists $sieve{$composite}; + print "The next stored multiple of ".($s/$incr)." is $composite\n" if DEBUG; + $sieve{$composite} = $s; + $candidate += $incr; + } + + print "Candidate $candidate is not in sieve\n" if DEBUG; + + while( $candidate < $q ) { + print "$candidate is prime\n" if DEBUG; + push @primes, $candidate; + $candidate += $incr; + next OUTER if exists $sieve{$candidate}; + } + + die "Candidate = $candidate, p = $p, q = $q" if $candidate > $q; + print "Candidate $candidate is equal to $p squared;\t" if DEBUG; + + # Thus, it is now time to add p to the sieve, + my $step = $incr * $p; + my $composite = $q + $step; + $composite += $step while exists $sieve{$composite}; + print "The next multiple of $p is $composite\n" if DEBUG; + $sieve{$composite} = $step; + + # and fetch out a new value for p from our primes array. + $p = $primes[++$ps]; + $q = $p * $p; + + # And since $candidate was equal to some prime squared, + # it's obviously composite, and we need to increment it. + $candidate += $incr; + print "p is $p, q is $q, candidate is $candidate\n" if DEBUG; + } continue { + return $primes[$n] if $n <= $#primes; + } + } -sub FETCHSIZE { 0x7FFF_FFFF } # Allows foreach to work -sub FETCH { - my($primes, $n) = @_; - return if $n < 0; - # Keep expanding the list as necessary, 5% larger each time. - prextend($primes, 1000+int(1.05*$primes->[-1])) while $n > $#$primes; - return $primes->[$n]; } if( !caller ) { - tie my @prime_list, 'Tie::SieveOfEratosthenes'; - my $limit = $ARGV[0] || 100; - print $prime_list[0]; - my $i = 1; - while ($prime_list[$i] < $limit) { print " ", $prime_list[$i++]; } - print "\n"; + tie my (@prime_list), 'Tie::SieveOfEratosthenes'; + my $limit = $ARGV[0] || 100; + my $line = ""; + for( my $count = 0; $prime_list[$count] < $limit; ++$count ) { + $line .= $prime_list[$count]. ", "; + next if length($line) <= 70; + if( $line =~ tr/,// > 1 ) { + $line =~ s/^(.*,) (.*, )/$2/; + print $1, "\n"; + } else { + print $line, "\n"; + $line = ""; + } + } + $line =~ s/, \z//; + print $line, "\n" if $line; } 1; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-11.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-11.pl new file mode 100644 index 0000000000..34e6783944 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-11.pl @@ -0,0 +1,54 @@ +use strict; +use warnings; +package Tie::SieveOfEratosthenes; + +sub TIEARRAY { + my $class = shift; + my @primes = (2,3,5,7); + return bless \@primes, $class; +} + +sub prextend { # Extend the given list of primes using a segment sieve + my($primes, $to) = @_; + $to-- unless $to & 1; # Ensure end is odd + return if $to < $primes->[-1]; + my $sqrtn = int(sqrt($to)+0.001); + prextend($primes, $sqrtn) if $primes->[-1] < $sqrtn; + my($segment, $startp) = ('', $primes->[-1]+1); + my($s_beg, $s_len) = ($startp >> 1, ($to>>1) - ($startp>>1)); + for my $p (@$primes) { + last if $p > $sqrtn; + if ($p >= 3) { + my $p2 = $p*$p; + if ($p2 < $startp) { # Bump up to next odd multiple of p >= startp + my $f = 1+int(($startp-1)/$p); + $p2 = $p * ($f | 1); + } + for (my $s = ($p2>>1)-$s_beg; $s <= $s_len; $s += $p) { + vec($segment, $s, 1) = 1; # Mark composites in segment + } + } + } + # Now add all the primes found in the segment to the list + do { push @$primes, 1+2*($_+$s_beg) if !vec($segment,$_,1) } for 0 .. $s_len; +} + +sub FETCHSIZE { 0x7FFF_FFFF } # Allows foreach to work +sub FETCH { + my($primes, $n) = @_; + return if $n < 0; + # Keep expanding the list as necessary, 5% larger each time. + prextend($primes, 1000+int(1.05*$primes->[-1])) while $n > $#$primes; + return $primes->[$n]; +} + +if( !caller ) { + tie my @prime_list, 'Tie::SieveOfEratosthenes'; + my $limit = $ARGV[0] || 100; + print $prime_list[0]; + my $i = 1; + while ($prime_list[$i] < $limit) { print " ", $prime_list[$i++]; } + print "\n"; +} + +1; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl index e50c825074..a74a427d91 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl @@ -1,27 +1,16 @@ -sub dj_string { - my($end) = @_; - return @{([],[],[2],[2,3],[2,3])[$end]} if $end <= 4; - $end-- if ($end & 1) == 0; - my $s_end = $end >> 1; +sub string_sieve { + my ($n, $i, $s, $d, @primes) = (shift, 7); - my $whole = int( ($end>>1) / 15); # prefill with 3 and 5 marked - my $sieve = '100010010010110' . '011010010010110' x $whole; - substr($sieve, ($end>>1)+1) = ''; - my ($n, $limit, $s) = ( 7, int(sqrt($end)), 0 ); - while ( $n <= $limit ) { - for ($s = ($n*$n) >> 1; $s <= $s_end; $s += $n) { - substr($sieve, $s, 1) = '1'; - } - do { $n += 2 } while substr($sieve, $n>>1, 1); - } - # If you just want the count, it's very fast: - # my $count = 1 + $sieve =~ tr/0//; - my @primes = (2, 3, 5); - ($s, $n) = (3, 7-2); - while ( (my $nexts = 1 + index($sieve, "0", $s)) > 0 ) { - $n += 2 * ($nexts - $s); - $s = $nexts; - push @primes, $n; + local $_ = '110010101110101110101110111110' . + '101111101110101110101110111110' x ($n/30); + + until (($s = $i*$i) > $n) { + $d = $i<<1; + do { substr($_, $s, 1, '1') } until ($s += $d) > $n; + 1 while substr($_, $i += 2, 1); } + $_ = substr($_, 1, $n); + # For just the count: return ($_ =~ tr/0//); + push @primes, pos while m/0/g; @primes; } diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-5.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-5.pl index b9b9db360d..b6acec9b81 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-5.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-5.pl @@ -1,7 +1,22 @@ -sub sieve{ my (@s, $i); - grep { not $s[ $i = $_ ] and do - { $s[ $i += $_ ]++ while $i <= $_[0]; 1 } - } 2..$_[0] -} +sub dj_string { + my($end) = @_; + return @{([],[],[2],[2,3],[2,3])[$end]} if $end <= 4; + $end-- if ($end & 1) == 0; + my $s_end = $end >> 1; -print join ", " => sieve 100; + my $whole = int( ($end>>1) / 15); # prefill with 3 and 5 marked + my $sieve = '100010010010110' . '011010010010110' x $whole; + substr($sieve, ($end>>1)+1) = ''; + my ($n, $limit, $s) = ( 7, int(sqrt($end)), 0 ); + while ( $n <= $limit ) { + for ($s = ($n*$n) >> 1; $s <= $s_end; $s += $n) { + substr($sieve, $s, 1) = '1'; + } + do { $n += 2 } while substr($sieve, $n>>1, 1); + } + # If you just want the count, it's very fast: + # my $count = 1 + $sieve =~ tr/0//; + my @primes = (2); + push @primes, 2*pos($sieve)-1 while $sieve =~ m/0/g; + @primes; +} diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl index d1c4825ca1..b9b9db360d 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-6.pl @@ -1,6 +1,6 @@ -sub sieve{ my ($s, $i); - grep { not vec $s, $i = $_, 1 and do - { (vec $s, $i += $_, 1) = 1 while $i <= $_[0]; 1 } +sub sieve{ my (@s, $i); + grep { not $s[ $i = $_ ] and do + { $s[ $i += $_ ]++ while $i <= $_[0]; 1 } } 2..$_[0] } diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl index f8936deb18..d1c4825ca1 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-7.pl @@ -1,6 +1,7 @@ -sub erat { - my $p = shift; - return $p, $p**2 > $_[$#_] ? @_ : erat(grep $_%$p, @_) +sub sieve{ my ($s, $i); + grep { not vec $s, $i = $_, 1 and do + { (vec $s, $i += $_, 1) = 1 while $i <= $_[0]; 1 } + } 2..$_[0] } -print join ', ' => erat 2..100000; +print join ", " => sieve 100; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-8.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-8.pl index 8d9cc27e14..f8936deb18 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-8.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-8.pl @@ -1,12 +1,6 @@ -sub sieve { - my ($s, $p) = "." . ("x" x shift); - - 1 while ++$p - and $s =~ /^(.{$p,}?)x/g - and $p = length($1) - and $s =~ s/(.{$p})./${1}./g - and substr($s, $p, 1) = "x"; - $s +sub erat { + my $p = shift; + return $p, $p**2 > $_[$#_] ? @_ : erat(grep $_%$p, @_) } -print sieve(1000); +print join ', ' => erat 2..100000; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl index 73dff3b16f..8d9cc27e14 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-9.pl @@ -1,106 +1,12 @@ -use strict; -use warnings; -package Tie::SieveOfEratosthenes; - -sub TIEARRAY { - my $class = shift; - bless \$class, $class; -} - -# If set to true, produces copious output. Observing this output -# is an excellent way to gain insight into how the algorithm works. -use constant DEBUG => 0; - -# If set to true, causes the code to skip over even numbers, -# improving runtime. It does not alter the output content, only the speed. -use constant WHEEL2 => 0; - -BEGIN { - - # This is loosely based on the Python implementation of this task, - # specifically the "Infinite generator with a faster algorithm" - - my @primes = (2, 3); - my $ps = WHEEL2 ? 1 : 0; - my $p = $primes[$ps]; - my $q = $p*$p; - my $incr = WHEEL2 ? 2 : 1; - my $candidate = $primes[-1] + $incr; - my %sieve; - - print "Initial: p = $p, q = $q, candidate = $candidate\n" if DEBUG; - - sub FETCH { - my $n = pop; - return if $n < 0; - return $primes[$n] if $n <= $#primes; - OUTER: while( 1 ) { - - # each key in %sieve is a composite number between - # p and p-squared. Each value in %sieve is $incr x the prime - # which acted as a 'seed' for that key. We use the value - # to step through multiples of the seed-prime, until we find - # an empty slot in %sieve. - while( my $s = delete $sieve{$candidate} ) { - print "$candidate a multiple of ".($s/$incr).";\t\t" if DEBUG; - my $composite = $candidate + $s; - $composite += $s while exists $sieve{$composite}; - print "The next stored multiple of ".($s/$incr)." is $composite\n" if DEBUG; - $sieve{$composite} = $s; - $candidate += $incr; - } - - print "Candidate $candidate is not in sieve\n" if DEBUG; - - while( $candidate < $q ) { - print "$candidate is prime\n" if DEBUG; - push @primes, $candidate; - $candidate += $incr; - next OUTER if exists $sieve{$candidate}; - } - - die "Candidate = $candidate, p = $p, q = $q" if $candidate > $q; - print "Candidate $candidate is equal to $p squared;\t" if DEBUG; - - # Thus, it is now time to add p to the sieve, - my $step = $incr * $p; - my $composite = $q + $step; - $composite += $step while exists $sieve{$composite}; - print "The next multiple of $p is $composite\n" if DEBUG; - $sieve{$composite} = $step; - - # and fetch out a new value for p from our primes array. - $p = $primes[++$ps]; - $q = $p * $p; - - # And since $candidate was equal to some prime squared, - # it's obviously composite, and we need to increment it. - $candidate += $incr; - print "p is $p, q is $q, candidate is $candidate\n" if DEBUG; - } continue { - return $primes[$n] if $n <= $#primes; - } - } - -} - -if( !caller ) { - tie my (@prime_list), 'Tie::SieveOfEratosthenes'; - my $limit = $ARGV[0] || 100; - my $line = ""; - for( my $count = 0; $prime_list[$count] < $limit; ++$count ) { - $line .= $prime_list[$count]. ", "; - next if length($line) <= 70; - if( $line =~ tr/,// > 1 ) { - $line =~ s/^(.*,) (.*, )/$2/; - print $1, "\n"; - } else { - print $line, "\n"; - $line = ""; - } - } - $line =~ s/, \z//; - print $line, "\n" if $line; +sub sieve { + my ($s, $p) = "." . ("x" x shift); + + 1 while ++$p + and $s =~ /^(.{$p,}?)x/g + and $p = length($1) + and $s =~ s/(.{$p})./${1}./g + and substr($s, $p, 1) = "x"; + $s } -1; +print sieve(1000); diff --git a/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes.psh b/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-1.psh similarity index 100% rename from Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes.psh rename to Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-1.psh diff --git a/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-2.psh b/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-2.psh new file mode 100644 index 0000000000..3465b394d1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/PowerShell/sieve-of-eratosthenes-2.psh @@ -0,0 +1,18 @@ +function eratosthenes ($n) { + if($n -ge 1){ + $prime = @(1..($n+1) | foreach{$true}) + $prime[1] = $false + $m = [Math]::Floor([Math]::Sqrt($n)) + for($i = 2; $i -le $m; $i++) { + if($prime[$i]) { + for($j = $i*$i; $j -le $n; $j += $i) { + $prime[$j] = $false + } + } + } + 1..$n | where{$prime[$_]} + } else { + "$n must be equal or greater than 1" + } +} +"$(eratosthenes 100)" diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-3.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-3.pro index be0cc99ee3..59fbc049d2 100644 --- a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-3.pro +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-3.pro @@ -20,3 +20,11 @@ add_mults(DI,I,N) :- I1 is I+DI, add_mults(DI,I1,N). add_mults(_,I,N) :- I > N. + +main(N) :- current_prolog_flag(verbose,F), + set_prolog_flag(verbose,normal), + time( sieve( N,P)), length(P,Len), last(P, LP), writeln([Len,LP]), + set_prolog_flag(verbose,F). + +:- dynamic( mult/1 ). +:- main(100000), main(1000000). diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-4.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-4.pro index 3405beff59..dac25fcae5 100644 --- a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-4.pro +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-4.pro @@ -1,26 +1,7 @@ -?- use_module(library(heaps)). +%% stdout copy +[9592, 99991] +[78498, 999983] -prime(2). -prime(N) :- prime_heap(N, _). - -prime_heap(3, H) :- list_to_heap([9-6], H). -prime_heap(N, H) :- - prime_heap(M, H0), N0 is M + 2, - next_prime(N0, H0, N, H). - -next_prime(N0, H0, N, H) :- - \+ min_of_heap(H0, N0, _), - N = N0, Composite is N*N, Skip is N+N, - add_to_heap(H0, Composite, Skip, H). -next_prime(N0, H0, N, H) :- - min_of_heap(H0, N0, _), - adjust_heap(H0, N0, H1), N1 is N0 + 2, - next_prime(N1, H1, N, H). - -adjust_heap(H0, N, H) :- - min_of_heap(H0, N, _), - get_from_heap(H0, N, Skip, H1), - Composite is N + Skip, add_to_heap(H1, Composite, Skip, H2), - adjust_heap(H2, N, H). -adjust_heap(H, N, H) :- - \+ min_of_heap(H, N, _). +%% stderr copy +% 293,176 inferences, 0.14 CPU in 0.14 seconds (101% CPU, 2094114 Lips) +% 3,122,303 inferences, 1.63 CPU in 1.67 seconds (97% CPU, 1915523 Lips) diff --git a/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-5.pro b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-5.pro new file mode 100644 index 0000000000..3405beff59 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Prolog/sieve-of-eratosthenes-5.pro @@ -0,0 +1,26 @@ +?- use_module(library(heaps)). + +prime(2). +prime(N) :- prime_heap(N, _). + +prime_heap(3, H) :- list_to_heap([9-6], H). +prime_heap(N, H) :- + prime_heap(M, H0), N0 is M + 2, + next_prime(N0, H0, N, H). + +next_prime(N0, H0, N, H) :- + \+ min_of_heap(H0, N0, _), + N = N0, Composite is N*N, Skip is N+N, + add_to_heap(H0, Composite, Skip, H). +next_prime(N0, H0, N, H) :- + min_of_heap(H0, N0, _), + adjust_heap(H0, N0, H1), N1 is N0 + 2, + next_prime(N1, H1, N, H). + +adjust_heap(H0, N, H) :- + min_of_heap(H0, N, _), + get_from_heap(H0, N, Skip, H1), + Composite is N + Skip, add_to_heap(H1, Composite, Skip, H2), + adjust_heap(H2, N, H). +adjust_heap(H, N, H) :- + \+ min_of_heap(H, N, _). diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py index c2b2145b53..dfe9de9b7b 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py @@ -2,7 +2,7 @@ def eratosthenes2(n): multiples = set() for i in range(2, n+1): if i not in multiples: - print(i) + yield i multiples.update(range(i*i, n+1, i)) -eratosthenes2(100) +print(list(eratosthenes2(100))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-10.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-10.rkt index 2c488f3c3d..b2b4ba5221 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-10.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-10.rkt @@ -1,5 +1,26 @@ -(define primes - (cons 2 (diff (ints-from 3 1) - (foldr (λ(p r) (define q (* p p)) - (cons q (union (ints-from (+ q p) p) r))) - '() primes)))) +#lang racket +(define-syntax (define-thread-loop stx) + (syntax-case stx () + [(_ (name . args) expr ...) + (with-syntax ([out! (datum->syntax stx 'out!)]) + #'(define (name . args) + (define out (make-channel)) + (define (out! x) (channel-put out x)) + (thread (λ() (let loop () expr ... (loop)))) + out))])) +(define-thread-loop (ints-from i d) (out! i) (set! i (+ i d))) +(define-thread-loop (merge c1 c2) + (let loop ([x1 (channel-get c1)] [x2 (channel-get c2)]) + (cond [(< x1 x2) (out! x1) (loop (channel-get c1) x2)] + [(> x1 x2) (out! x2) (loop x1 (channel-get c2))] + [else (out! x1) (loop (channel-get c1) (channel-get c2))]))) +(define-thread-loop (sieve l non-primes) + (let loop ([x (channel-get l)] [np (channel-get non-primes)]) + (cond [(< np x) (loop x (channel-get non-primes))] + [(= np x) (loop (channel-get l) (channel-get non-primes))] + [else (out! x) + (set! non-primes (merge (ints-from (* x x) x) non-primes))]))) +(define-thread-loop (cons x l) + (out! x) (let loop () (out! (channel-get l)) (loop))) +(define primes (cons 2 (sieve (ints-from 3 2) (ints-from 2 2)))) +(for/list ([i 25] [x (in-producer channel-get eof primes)]) x) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-11.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-11.rkt index b2b4ba5221..4de4f01b06 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-11.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-11.rkt @@ -1,26 +1,21 @@ #lang racket -(define-syntax (define-thread-loop stx) - (syntax-case stx () - [(_ (name . args) expr ...) - (with-syntax ([out! (datum->syntax stx 'out!)]) - #'(define (name . args) - (define out (make-channel)) - (define (out! x) (channel-put out x)) - (thread (λ() (let loop () expr ... (loop)))) - out))])) -(define-thread-loop (ints-from i d) (out! i) (set! i (+ i d))) -(define-thread-loop (merge c1 c2) - (let loop ([x1 (channel-get c1)] [x2 (channel-get c2)]) - (cond [(< x1 x2) (out! x1) (loop (channel-get c1) x2)] - [(> x1 x2) (out! x2) (loop x1 (channel-get c2))] - [else (out! x1) (loop (channel-get c1) (channel-get c2))]))) -(define-thread-loop (sieve l non-primes) - (let loop ([x (channel-get l)] [np (channel-get non-primes)]) - (cond [(< np x) (loop x (channel-get non-primes))] - [(= np x) (loop (channel-get l) (channel-get non-primes))] - [else (out! x) - (set! non-primes (merge (ints-from (* x x) x) non-primes))]))) -(define-thread-loop (cons x l) - (out! x) (let loop () (out! (channel-get l)) (loop))) +(require racket/generator) +(define (ints-from i d) + (generator () (let loop ([i i]) (yield i) (loop (+ i d))))) +(define (merge g1 g2) + (generator () + (let loop ([x1 (g1)] [x2 (g2)]) + (cond [(< x1 x2) (yield x1) (loop (g1) x2)] + [(> x1 x2) (yield x2) (loop x1 (g2))] + [else (yield x1) (loop (g1) (g2))])))) +(define (sieve l non-primes) + (generator () + (let loop ([x (l)] [np (non-primes)]) + (cond [(< np x) (loop x (non-primes))] + [(= np x) (loop (l) (non-primes))] + [else (yield x) + (set! non-primes (merge (ints-from (* x x) x) non-primes)) + (loop (l) (non-primes))])))) +(define (cons x l) (generator () (yield x) (let loop () (yield (l)) (loop)))) (define primes (cons 2 (sieve (ints-from 3 2) (ints-from 2 2)))) -(for/list ([i 25] [x (in-producer channel-get eof primes)]) x) +(for/list ([i 25] [x (in-producer primes)]) x) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt index aa7dd15905..fc3199350b 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt @@ -1,5 +1,4 @@ #lang racket - (define (sieve n) (define primes (make-vector (add1 n) #t)) (for* ([i (in-range 2 (add1 n))] @@ -9,5 +8,4 @@ (for/list ([n (in-range 2 (add1 n))] #:when (vector-ref primes n)) n)) - (sieve 100) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt index da4d0e9628..2505ab5ef4 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt @@ -1,17 +1,13 @@ #lang racket (require data/bit-vector) +;; Returns a list of prime numbers up to natural number limit (define (eratosthenes limit) - " Returns a list of prime numbers up to natural number limit " - (let ((bv (make-bit-vector (+ limit 1) #f))) - (bit-vector-set! bv 0 #t) - (bit-vector-set! bv 1 #t) - (for ((i (in-range (sqrt limit)))) - (when (false? (bit-vector-ref bv i)) - (for ((j (in-range (+ i i) (bit-vector-length bv) i))) - (bit-vector-set! bv j #t)))) - ;; Translate bit-vector into list of primes - ;; the following is extremely ugly/imperative and needs the result list reversed - (let ((to-return null)) - (for ((i (bit-vector-length bv))) - (when (not (bit-vector-ref bv i)) (set! to-return (cons i to-return)))) - (reverse to-return)))) ; NOTE: needs to be reversed + (define bv (make-bit-vector (+ limit 1) #f)) + (bit-vector-set! bv 0 #t) + (bit-vector-set! bv 1 #t) + (for* ([i (in-range (add1 (sqrt limit)))] #:unless (bit-vector-ref bv i) + [j (in-range (* 2 i) (bit-vector-length bv) i)]) + (bit-vector-set! bv j #t)) + ;; translate to a list of primes + (for/list ([i (bit-vector-length bv)] #:unless (bit-vector-ref bv i)) i)) +(eratosthenes 100) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt index 0a982bc615..41bed2d8ca 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt @@ -1,17 +1,14 @@ -#lang racket -(require data/bit-vector) -(define (eratosthenes limit) - " Returns a list of prime numbers up to natural number limit " - (let ((bv (make-bit-vector (+ limit 1) #f))) - (bit-vector-set! bv 0 #t) - (bit-vector-set! bv 1 #t) - (for ((i (in-range (sqrt limit)))) - (when (false? (bit-vector-ref bv i)) - (for ((j (in-range (+ i i) (bit-vector-length bv) i))) - (bit-vector-set! bv j #t)))) - ;; Translate bit-vector into list of primes using recursion - ;; may as well use the list comprehension from the second version, which does the same thing - (let recur ((i 2)) (cond ((> i limit) '()) - ((false? (bit-vector-ref bv i)) (cons i (recur (+ i 1)))) - (else (recur (+ i 1))))))) -(eratosthenes 100) +#lang lazy +(define (ints-from i d) (cons i (ints-from (+ i d) d))) +(define (after n l f) + (if (< (car l) n) (cons (car l) (after n (cdr l) f)) (f l))) +(define (diff l1 l2) + (let ([x1 (car l1)] [x2 (car l2)]) + (cond [(< x1 x2) (cons x1 (diff (cdr l1) l2 ))] + [(> x1 x2) (diff l1 (cdr l2)) ] + [else (diff (cdr l1) (cdr l2)) ]))) +(define (union l1 l2) ; union of two lists + (let ([x1 (car l1)] [x2 (car l2)]) + (cond [(< x1 x2) (cons x1 (union (cdr l1) l2 ))] + [(> x1 x2) (cons x2 (union l1 (cdr l2)))] + [else (cons x1 (union (cdr l1) (cdr l2)))]))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt index 41bed2d8ca..0ddb68abf0 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt @@ -1,14 +1,5 @@ -#lang lazy -(define (ints-from i d) (cons i (ints-from (+ i d) d))) -(define (after n l f) - (if (< (car l) n) (cons (car l) (after n (cdr l) f)) (f l))) -(define (diff l1 l2) - (let ([x1 (car l1)] [x2 (car l2)]) - (cond [(< x1 x2) (cons x1 (diff (cdr l1) l2 ))] - [(> x1 x2) (diff l1 (cdr l2)) ] - [else (diff (cdr l1) (cdr l2)) ]))) -(define (union l1 l2) ; union of two lists - (let ([x1 (car l1)] [x2 (car l2)]) - (cond [(< x1 x2) (cons x1 (union (cdr l1) l2 ))] - [(> x1 x2) (cons x2 (union l1 (cdr l2)))] - [else (cons x1 (union (cdr l1) (cdr l2)))]))) +(define (sieve l) + (define x (car l)) + (cons x (sieve (diff (cdr l) (ints-from (+ x x) x))))) +(define primes (sieve (ints-from 2 1))) +(!! (take 25 primes)) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-6.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-6.rkt index 0ddb68abf0..ed1edfb20f 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-6.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-6.rkt @@ -1,5 +1,6 @@ -(define (sieve l) - (define x (car l)) - (cons x (sieve (diff (cdr l) (ints-from (+ x x) x))))) -(define primes (sieve (ints-from 2 1))) -(!! (take 25 primes)) +(define (sieve l non-primes) + (let ([x (car l)] [np (car non-primes)]) + (cond [(= x np) (sieve (cdr l) (cdr non-primes))] ; else x < np + [else (cons x (sieve (cdr l) (union (ints-from (* x x) (* 2 x)) + non-primes)))]))) +(define primes (cons 2 (cons 3 (sieve (ints-from 5 2) (ints-from 9 6))))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-7.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-7.rkt index ed1edfb20f..1652054e12 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-7.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-7.rkt @@ -1,6 +1,5 @@ -(define (sieve l non-primes) - (let ([x (car l)] [np (car non-primes)]) - (cond [(= x np) (sieve (cdr l) (cdr non-primes))] ; else x < np - [else (cons x (sieve (cdr l) (union (ints-from (* x x) (* 2 x)) - non-primes)))]))) -(define primes (cons 2 (cons 3 (sieve (ints-from 5 2) (ints-from 9 6))))) +(define (sieve l prs) + (define p (car prs)) + (define q (* p p)) + (after q l (λ(t) (sieve (diff t (ints-from q p)) (cdr prs))))) +(define primes (cons 2 (sieve (ints-from 3 1) primes))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-8.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-8.rkt index 1652054e12..62409279cf 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-8.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-8.rkt @@ -1,5 +1,6 @@ -(define (sieve l prs) - (define p (car prs)) - (define q (* p p)) - (after q l (λ(t) (sieve (diff t (ints-from q p)) (cdr prs))))) -(define primes (cons 2 (sieve (ints-from 3 1) primes))) +(define (composites l q primes) + (after q l (λ(t) (let ([p (car primes)] [r (cadr primes)]) + (composites (union t (ints-from q (* 2 p))) ; q = p*p + (* r r) (cdr primes)))))) +(define primes (cons 2 (cons 3 (diff (ints-from 5 2) + (composites (ints-from 9 6) 25 (cddr primes)))))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-9.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-9.rkt index 62409279cf..2c488f3c3d 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-9.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-9.rkt @@ -1,6 +1,5 @@ -(define (composites l q primes) - (after q l (λ(t) (let ([p (car primes)] [r (cadr primes)]) - (composites (union t (ints-from q (* 2 p))) ; q = p*p - (* r r) (cdr primes)))))) -(define primes (cons 2 (cons 3 (diff (ints-from 5 2) - (composites (ints-from 9 6) 25 (cddr primes)))))) +(define primes + (cons 2 (diff (ints-from 3 1) + (foldr (λ(p r) (define q (* p p)) + (cons q (union (ints-from (+ q p) p) r))) + '() primes)))) diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust index e6e27524fa..fb9fe3e5df 100644 --- a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust +++ b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust @@ -1,28 +1,24 @@ -use std::iter; +fn simple_sieve(limit: usize) -> Vec { -fn int_sqrt(n: uint) -> uint { - (n as f64).sqrt() as uint -} - -fn simple_sieve(limit: uint) -> Vec { - - if limit < 2 { - return Vec::new(); - } - - let mut primes: Vec = Vec::from_elem(limit + 1, true); + let mut is_prime = vec![true; limit+1]; + is_prime[0] = false; + if limit >= 1 { is_prime[1] = false } - for prime in iter::range_inclusive(2, int_sqrt(limit) + 1) { - if primes[prime] { - for multiple in iter::range_step(prime * prime, limit + 1, prime) { - *primes.get_mut(multiple) = false; + for num in 2..limit+1 { + if is_prime[num] { + let mut multiple = num*num; + while multiple <= limit { + is_prime[multiple] = false; + multiple += num; } } } - iter::range_inclusive(2, limit).filter(|&n| primes[n]).collect() + is_prime.iter().enumerate() + .filter_map(|(pr, &is_pr)| if is_pr {Some(pr)} else {None} ) + .collect() } fn main() { - println!("{}", simple_sieve(100)) + println!("{:?}", simple_sieve(100)); } diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss index 3d7ee0eb86..b5da14b8b4 100644 --- a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss @@ -1,9 +1,11 @@ - (define odd-primes - (s-cons 3 (s-diff (from-By 5 2) - (s-foldr (lambda (p r) (let ((q (* p p))) - (s-cons q (s-union (from-By (+ q (* 2 p)) (* 2 p)) r)))) - '() odd-primes)))) + (define (primes-stream-ala-Bird) + (define (mults p) (from-By (* p p) (* 2 p))) + (define odd-primes ;; primes are + (s-cons 3 (s-diff (from-By 5 2) ;; odds, without + (s-linear-join (s-map mults odd-primes))))) ;; multiples of primes + (s-cons 2 odd-primes)) - (define primes (s-cons 2 odd-primes)) - - ;;;; TODO: implement s-foldr function + ;;;; join streams using linear structure + (define (s-linear-join sts) + (s-cons (head (head sts)) (s-union (tail (head sts)) + (s-linear-join (tail sts))))) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss index bcc5b06655..26d81cb2e8 100644 --- a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss @@ -11,7 +11,7 @@ (cond ((> n 1) (cons (head s) (take (- n 1) (tail s)))) ((= n 1) (list (head s))) ;; don't force it too soon!! - (else ()))) ;; so (take 4 (s-map / (from-By 4 -1))) works + (else '()))) ;; so (take 4 (s-map / (from-By 4 -1))) works (define (drop n s) (cond ((> n 0) (drop (- n 1) (tail s))) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss index 6f02ed0785..c9e4708c98 100644 --- a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss @@ -11,10 +11,13 @@ ;;;; join an ordered stream of streams (here, of primes' multiples) ;;;; into one ordered stream, via an infinite right-deepening tree - (define (s-tree-join sts) ;; sts -> s - (define (join-With of-Tail sts) ;; sts -> s - (s-cons (head (head sts)) - (s-union (tail (head sts)) (of-Tail (tail sts))))) - (define (pairs sts) ;; sts -> sts - (s-cons (join-With head sts) (pairs (tail (tail sts))))) - (join-With (lambda (t) (s-tree-join (pairs t))) sts)) + (define (s-tree-join sts) + (s-cons (head (head sts)) + (s-union (tail (head sts)) + (s-tree-join (pairs (tail sts)))))) + + (define (pairs sts) ;; {a.(b.t)} -> (a+b).{t} + (s-cons (s-cons (head (head sts)) + (s-union (tail (head sts)) + (head (tail sts)))) + (pairs (tail (tail sts))))) diff --git a/Task/Simple-windowed-application/Elena/simple-windowed-application.elena b/Task/Simple-windowed-application/Elena/simple-windowed-application.elena new file mode 100644 index 0000000000..50cd41e848 --- /dev/null +++ b/Task/Simple-windowed-application/Elena/simple-windowed-application.elena @@ -0,0 +1,46 @@ +#import system. +#import forms. +#import extensions. + +#class Window +{ + #field form. + #field lblClicks. + #field btmClickMe. + #field clicksCount. + + #constructor new + [ + form := SDIDialog new. + lblClicks := Label new. + btmClickMe := Button new. + + clicksCount := 0. + + form controls append:lblClicks. + form controls append:btmClickMe. + + form set &caption:"Rosseta Code". + form set &x:100 &y:100. + form set &width:160 &height:80. + + lblClicks set &x:10 &y:2. + lblClicks set &width:160 &height:20. + lblClicks set &caption:"Clicks: 0". + + btmClickMe set &x:7 &y:20. + btmClickMe set &width:140 &height:30. + btmClickMe set &caption:"Click me". + btmClickMe set &onClick:args + + [ $self $onButtonClick. ]. + ] + + #method $onButtonClick + [ + clicksCount := clicksCount + 1. + lblClicks set &caption:("Clicks: " + clicksCount literal). + ] + + #method => form. +} diff --git a/Task/Simulate-input-Keyboard/00DESCRIPTION b/Task/Simulate-input-Keyboard/00DESCRIPTION index 6cb948c0a2..259e36f560 100644 --- a/Task/Simulate-input-Keyboard/00DESCRIPTION +++ b/Task/Simulate-input-Keyboard/00DESCRIPTION @@ -9,7 +9,7 @@ {{omit from|R}} {{omit from|Retro}} {{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} -{{omit from|zkl} +{{omit from|zkl}} Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created diff --git a/Task/Simulate-input-Mouse/Common-Lisp/simulate-input-mouse.lisp b/Task/Simulate-input-Mouse/Common-Lisp/simulate-input-mouse.lisp new file mode 100644 index 0000000000..efa54c6891 --- /dev/null +++ b/Task/Simulate-input-Mouse/Common-Lisp/simulate-input-mouse.lisp @@ -0,0 +1,8 @@ +(defun sh (cmd) +#+clisp (shell cmd) +#+ecl (si:system cmd) +#+sbcl (sb-ext:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*) +#+clozure (ccl:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*)) +(sh "xdotool mousemove 0 0 click 1") +(sleep 2) +(sh "xdotool mousemove 300 300 click 1") diff --git a/Task/Simulate-input-Mouse/Racket/simulate-input-mouse.rkt b/Task/Simulate-input-Mouse/Racket/simulate-input-mouse.rkt new file mode 100644 index 0000000000..fa7b0f0561 --- /dev/null +++ b/Task/Simulate-input-Mouse/Racket/simulate-input-mouse.rkt @@ -0,0 +1,10 @@ +#lang at-exp racket + +(require ffi/unsafe) + +(define mouse-event + (get-ffi-obj "mouse_event" (ffi-lib "user32") + (_fun _int32 _int32 _int32 _int32 _pointer -> _void))) + +(mouse-event #x2 0 0 0 #f) +(mouse-event #x4 0 0 0 #f) diff --git a/Task/Singleton/C++/singleton-3.cpp b/Task/Singleton/C++/singleton-3.cpp new file mode 100644 index 0000000000..a1bc2611cc --- /dev/null +++ b/Task/Singleton/C++/singleton-3.cpp @@ -0,0 +1,36 @@ +class Singleton +{ +public: + static Singleton & Instance() + { + // Since it's a static variable, if the class has already been created, + // It won't be created again. + // And it **is** thread-safe in C++11. + + static Singleton myInstance; + + // Return a reference to our instance. + return myInstance; + } + + // delete copy and move constructors and assign operators + Singleton(Singleton const&) = delete; // Copy construct + Singleton(Singleton&&) = delete; // Move construct + Singleton& operator=(Singleton const&) = delete; // Copy assign + Singleton& operator=(Singleton &&) = delete; // Move assign + + // Any other public methods + +protected: + Singleton() + { + // Constructor code goes here. + } + + ~Singleton() + { + // Destructor code goes here. + } + + // And any other protected methods. +} diff --git a/Task/Singleton/Eiffel/singleton-1.e b/Task/Singleton/Eiffel/singleton-1.e new file mode 100644 index 0000000000..ee8788e089 --- /dev/null +++ b/Task/Singleton/Eiffel/singleton-1.e @@ -0,0 +1,7 @@ +class + SINGLETON +create {SINGLETON_ACCESS} + default_create +feature + -- singleton features go here +end diff --git a/Task/Singleton/Eiffel/singleton-2.e b/Task/Singleton/Eiffel/singleton-2.e new file mode 100644 index 0000000000..1ae1ab9433 --- /dev/null +++ b/Task/Singleton/Eiffel/singleton-2.e @@ -0,0 +1,10 @@ +frozen class + SINGLETON_ACCESS +feature + singleton: SINGLETON + once ("PROCESS") + create Result + ensure + Result /= Void + end +end diff --git a/Task/Singleton/Eiffel/singleton-3.e b/Task/Singleton/Eiffel/singleton-3.e new file mode 100644 index 0000000000..b329f59a4e --- /dev/null +++ b/Task/Singleton/Eiffel/singleton-3.e @@ -0,0 +1,3 @@ +s: SINGLETON -- declaration somewhere + +s := (create{SINGLETON_ACCESS}).singleton -- in some routine diff --git a/Task/Singleton/Forth/singleton.fth b/Task/Singleton/Forth/singleton.fth new file mode 100644 index 0000000000..0a374b5f47 --- /dev/null +++ b/Task/Singleton/Forth/singleton.fth @@ -0,0 +1,27 @@ +include FMS-SI.f + +\ A singleton is created by using normal Forth data +\ allocation words such as value or variable as instance variables. +\ Any number of instances of a singleton class may be +\ instantiated but they will all operate on the same shared data. +\ The data name space will remain private to objects of the class. + +:class singleton + 0 value a + 0 value b + :m printa a . ;m + :m printb b . ;m + :m add-a ( n -- ) a + to a ;m + :m add-b ( n -- ) b + to b ;m +;class + +singleton s1 +singleton s2 +singleton s3 + +4 s1 add-a +9 s2 add-b +s3 printa \ => 4 +s3 printb \ => 9 +s1 printb \ => 9 +s2 printa \ => 4 diff --git a/Task/Singly-linked-list-Element-definition/ALGOL-W/singly-linked-list-element-definition.alg b/Task/Singly-linked-list-Element-definition/ALGOL-W/singly-linked-list-element-definition.alg new file mode 100644 index 0000000000..c368b810de --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/ALGOL-W/singly-linked-list-element-definition.alg @@ -0,0 +1,8 @@ + % record type to hold a singly linked list of integers % + record ListI ( integer iValue; reference(ListI) next ); + + % declare a variable to hold a list % + reference(ListI) head; + + % create a list of integers % + head := ListI( 1701, ListI( 9000, ListI( 42, ListI( 90210, null ) ) ) ); diff --git a/Task/Singly-linked-list-Element-definition/Modula-3/singly-linked-list-element-definition.mod3 b/Task/Singly-linked-list-Element-definition/Modula-3/singly-linked-list-element-definition.mod3 new file mode 100644 index 0000000000..88568370ce --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Modula-3/singly-linked-list-element-definition.mod3 @@ -0,0 +1,6 @@ +TYPE + Link = REF LinkRcd; + LinkRcd = RECORD + Next: Link; + Data: INTEGER + END; diff --git a/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m b/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m index 818e885922..bc0c923a9b 100644 --- a/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m +++ b/Task/Singly-linked-list-Element-definition/Objective-C/singly-linked-list-element-definition.m @@ -1,14 +1,14 @@ #import -@interface RCListElement : NSObject +@interface RCListElement : NSObject { - RCListElement *next; - id datum; + RCListElement *next; + T datum; } -- (RCListElement *)next; -- (id)datum; -- (RCListElement *)setNext: (RCListElement *)nx; -- (void)setDatum: (id)d; +- (RCListElement *)next; +- (T)datum; +- (RCListElement *)setNext: (RCListElement *)nx; +- (void)setDatum: (T)d; @end @implementation RCListElement @@ -22,8 +22,7 @@ - (id)datum } - (RCListElement *)setNext: (RCListElement *)nx { - RCListElement *p; - p = next; + RCListElement *p = next; next = nx; return p; } diff --git a/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition.rust b/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition.rust index 1b166c7b74..befb53b201 100644 --- a/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition.rust +++ b/Task/Singly-linked-list-Element-definition/Rust/singly-linked-list-element-definition.rust @@ -1,4 +1,4 @@ enum SingleLinkedList { - Node(T, @mut SingleLinkedList), - None + Node(T, Box>), + None } diff --git a/Task/Singly-linked-list-Element-insertion/ALGOL-W/singly-linked-list-element-insertion.alg b/Task/Singly-linked-list-Element-insertion/ALGOL-W/singly-linked-list-element-insertion.alg new file mode 100644 index 0000000000..e0945b1242 --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/ALGOL-W/singly-linked-list-element-insertion.alg @@ -0,0 +1,14 @@ + % inserts a new value after the specified element of a list % + procedure insert( reference(ListI) value list + ; integer value newValue + ) ; + next(list) := ListI( newValue, next(list) ); + + % declare a variable to hold a list % + reference(ListI) head; + + % create a list of integers % + head := ListI( 1701, ListI( 9000, ListI( 42, ListI( 90210, null ) ) ) ); + + % insert a new value into the list % + insert( next(head), 4077 ); diff --git a/Task/Singly-linked-list-Element-insertion/Modula-3/singly-linked-list-element-insertion.mod3 b/Task/Singly-linked-list-Element-insertion/Modula-3/singly-linked-list-element-insertion.mod3 new file mode 100644 index 0000000000..78a515e41b --- /dev/null +++ b/Task/Singly-linked-list-Element-insertion/Modula-3/singly-linked-list-element-insertion.mod3 @@ -0,0 +1,26 @@ +MODULE SinglyLinkedList EXPORTS Main; + +TYPE + Link = REF LinkRcd; + LinkRcd = RECORD + Next: Link; + Data: INTEGER + END; + + PROCEDURE InsertAppend(anchor, next: Link) = + BEGIN + IF anchor # NIL AND next # NIL THEN + next.Next := anchor.Next; + anchor.Next := next + END + END InsertAppend; + +VAR + a: Link := NEW(Link, Next := NIL, Data := 1); + b: Link := NEW(Link, Next := NIL, Data := 2); + c: Link := NEW(Link, Next := NIL, Data := 3); + +BEGIN + InsertAppend(a, b); + InsertAppend(a, c) +END SinglyLinkedList. diff --git a/Task/Singly-linked-list-Traversal/ALGOL-W/singly-linked-list-traversal.alg b/Task/Singly-linked-list-Traversal/ALGOL-W/singly-linked-list-traversal.alg new file mode 100644 index 0000000000..fb8c59ac84 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/ALGOL-W/singly-linked-list-traversal.alg @@ -0,0 +1,28 @@ +begin + % record type to hold a singly linked list of integers % + record ListI ( integer iValue; reference(ListI) next ); + + % inserts a new value after the specified element of a list % + procedure insert( reference(ListI) value list + ; integer value newValue + ) ; + next(list) := ListI( newValue, next(list) ); + + % declare variables to hold the list % + reference(ListI) head, pos; + + % create a list of integers % + head := ListI( 1701, ListI( 9000, ListI( 42, ListI( 90210, null ) ) ) ); + + % insert a new value into the list % + insert( next(head), 4077 ); + + % traverse the list % + pos := head; + + while pos not = null do begin + write( iValue(pos) ); + pos := next(pos); + end; + +end. diff --git a/Task/Singly-linked-list-Traversal/C++/singly-linked-list-traversal.cpp b/Task/Singly-linked-list-Traversal/C++/singly-linked-list-traversal.cpp new file mode 100644 index 0000000000..9d305ddefb --- /dev/null +++ b/Task/Singly-linked-list-Traversal/C++/singly-linked-list-traversal.cpp @@ -0,0 +1,9 @@ +#include +#include + +int main() +{ + std::forward_list list{1, 2, 3, 4, 5}; + for (int e : list) + std::cout << e << std::endl; +} diff --git a/Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal.js b/Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal-1.js similarity index 100% rename from Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal.js rename to Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal-1.js diff --git a/Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal-2.js b/Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal-2.js new file mode 100644 index 0000000000..69abab42f1 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/JavaScript/singly-linked-list-traversal-2.js @@ -0,0 +1,46 @@ +var map = function (fn, list) { + return list.map(fn); + }, + + foldr = function (fn, acc, list) { + var listr = list.slice(); + listr.reverse(); + + return listr.reduce(fn, acc); + }, + + traverse = function (list, fn) { + return list.forEach(fn); + }; + +var range = function (m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { + return m + i; + } + ); +}; + +// --> [false, false, false, false, false, true, true, true, true, true] +map(function (x) { + return x > 5; +}, range(1, 10)); + +// --> ["Apples", "Oranges", "Mangos", "Pears"] +map(function (x) { + return x + 's'; +}, ["Apple", "Orange", "Mango", "Pear"]) + +// --> 55 +foldr(function (acc, x) { + return acc + x; +}, 0, range(1, 10)) + + +traverse(["Apple", "Orange", "Mango", "Pear"], function (x) { + console.log(x); +}) +/* Apple */ +/* Orange */ +/* Mango */ +/* Pear */ diff --git a/Task/Sleep/DCL/sleep.dcl b/Task/Sleep/DCL/sleep.dcl new file mode 100644 index 0000000000..1763e17b37 --- /dev/null +++ b/Task/Sleep/DCL/sleep.dcl @@ -0,0 +1,4 @@ +$ amount_of_time = p1 ! hour[:[minute][:[second][.[hundredth]]]] +$ write sys$output "Sleeping..." +$ wait 'amount_of_time +$ write sys$output "Awake!" diff --git a/Task/Sockets/AutoIt/sockets.autoit b/Task/Sockets/AutoIt/sockets.autoit new file mode 100644 index 0000000000..4125b1cbec --- /dev/null +++ b/Task/Sockets/AutoIt/sockets.autoit @@ -0,0 +1,7 @@ +Func _HelloWorldSocket() + TCPStartup() + $Socket = TCPConnect("127.0.0.1", 256) + TCPSend($Socket, "Hello World") + TCPCloseSocket($Socket) + TCPShutdown() +EndFunc diff --git a/Task/Sockets/BBC-BASIC/sockets.bbc b/Task/Sockets/BBC-BASIC/sockets.bbc index 48652367d4..448872a470 100644 --- a/Task/Sockets/BBC-BASIC/sockets.bbc +++ b/Task/Sockets/BBC-BASIC/sockets.bbc @@ -2,7 +2,7 @@ PROC_initsockets socket% = FN_tcpconnect("localhost", "256") - IF socket% = 0 ERROR 100, "Failed to open socket" + IF socket% <=0 ERROR 100, "Failed to open socket" REM Don't use FN_writesocket since an error is expected msg$ = "hello socket world" diff --git a/Task/Sockets/C++/sockets.cpp b/Task/Sockets/C++/sockets.cpp new file mode 100644 index 0000000000..7ca31e0349 --- /dev/null +++ b/Task/Sockets/C++/sockets.cpp @@ -0,0 +1,16 @@ +//compile with g++ main.cpp -lboost_system -pthread + +#include + +int main() +{ + boost::asio::io_service io_service; + boost::asio::ip::tcp::socket sock(io_service); + boost::asio::ip::tcp::resolver resolver(io_service); + boost::asio::ip::tcp::resolver::query query("localhost", "4321"); + + boost::asio::connect(sock, resolver.resolve(query)); + boost::asio::write(sock, boost::asio::buffer("Hello world socket\r\n")); + + return 0; +} diff --git a/Task/Sockets/Emacs-Lisp/sockets.l b/Task/Sockets/Emacs-Lisp/sockets.l new file mode 100644 index 0000000000..d48d8d2d9d --- /dev/null +++ b/Task/Sockets/Emacs-Lisp/sockets.l @@ -0,0 +1,5 @@ +(let ((proc (make-network-process :name "my sock" + :host 'local ;; or hostname string + :service 256))) + (process-send-string proc "hello socket world") + (delete-process proc)) diff --git a/Task/Sockets/Go/sockets.go b/Task/Sockets/Go/sockets.go index 166fbcc285..503bd28e44 100644 --- a/Task/Sockets/Go/sockets.go +++ b/Task/Sockets/Go/sockets.go @@ -11,10 +11,9 @@ func main() { fmt.Println(err) return } + defer conn.Close() _, err = conn.Write([]byte("hello socket world")) if err != nil { fmt.Println(err) - return } - conn.Close() } diff --git a/Task/Sockets/Prolog/sockets.pro b/Task/Sockets/Prolog/sockets.pro new file mode 100644 index 0000000000..d0bbc30494 --- /dev/null +++ b/Task/Sockets/Prolog/sockets.pro @@ -0,0 +1,6 @@ +start(Port) :- socket('AF_INET',Socket), + socket_connect(Socket, 'AF_INET'(localhost,Port), Input, Output), + write(Output, 'hello socket world'), + flush_output(Output), + close(Output), + close(Input). diff --git a/Task/Sockets/Rust/sockets.rust b/Task/Sockets/Rust/sockets.rust new file mode 100644 index 0000000000..914197fe06 --- /dev/null +++ b/Task/Sockets/Rust/sockets.rust @@ -0,0 +1,11 @@ +use std::io::prelude::*; +use std::net::TcpStream; + +fn main() { + // Open a tcp socket connecting to 127.0.0.1:256, no error handling (unwrap) + let mut my_stream = TcpStream::connect("127.0.0.1:256").unwrap(); + + // Write 'hello socket world' to the stream, ignoring the result of write + let _ = my_stream.write(b"hello socket world"); + +} // <- my_stream's drop function gets called, which closes the socket 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 index a9615e4ba7..341eda5714 100644 --- 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 @@ -2,11 +2,11 @@ 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*/ +if N=='' | N==',' then N=8 /*Boardsize specified? Default. */ +if sRank=='' | sRank==',' then sRank=N /*starting rank given? Default. */ +if sFile=='' | sFile==',' then sFile=1 /* " file " " */ +NN=N**2; NxN='a ' N"x"N ' chessboard' /*[↓ ↓] r f = Rank and 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*/ @@ -14,7 +14,7 @@ cents=0 /*number of pennies on chessboard*/ 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*/ + 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.*/ @@ -23,40 +23,40 @@ cents=0 /*number of pennies on chessboard*/ /* [↑] 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 + /*[↑] create the NxN chessboard.*/ + Kr = '2 1 -1 -2 -2 -1 1 2' /*legal "rank" move for a knight.*/ + Kf = '1 2 2 1 -1 -2 -2 -1' /* " "file" " " " " */ +parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 /*parse by hand.*/ +parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 /* " " " */ +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 iterate + @.sRank.sFile=1 + leave sRank /*got a spot, so leave. */ 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':' +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':' + /*show chessboard with moves & ¢.*/ +!=left('', 9*(n<18)) /*used for indentation of board. */ _=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.*/ + say ! translate(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=' ' +move: procedure expose @. Kr. Kf. target; parse arg #,rank,file do t=1 for 8; nr=rank+Kr.t; nf=file+Kf.t - if @.nr.nf==b then do; @.nr.nf=# /*Kn move.*/ + if @.nr.nf==. 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. */ + @.nr.nf=. /*undo the above move. */ end /*try different move. */ end /*t*/ return 0 /*the tour not possible.*/ 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 index 17ed017ee4..eb827de4b9 100644 --- a/Task/Solve-a-Numbrix-puzzle/C++/solve-a-numbrix-puzzle.cpp +++ b/Task/Solve-a-Numbrix-puzzle/C++/solve-a-numbrix-puzzle.cpp @@ -2,154 +2,154 @@ #include #include #include -#include -#include - +#include +#include +#include using namespace std; +typedef bitset<4> hood_t; struct node { - int val; - unsigned char neighbors; + int val; + hood_t 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++ ) + void solve(vector& puzz, int max_wid) { - if( ( *i ) == "." ) - { - ostringstream o; o << arr[c].val; - ( *i ) = o.str(); - } - c++; + if (puzz.size() < 1) return; + wid = max_wid; + hei = static_cast(puzz.size()) / wid; + max = wid * hei; + int len = max, c = 0; + arr = vector(len, node({ 0, 0 })); + weHave = vector(len + 1, false); + + for (const auto& s : puzz) + { + if (s == "*") { max--; arr[c++].val = -1; continue; } + arr[c].val = atoi(s.c_str()); + if (arr[c].val > 0) weHave[arr[c].val] = true; + c++; + } + + solveIt(); c = 0; + for (auto&& s : puzz) + { + if (s == ".") + s = std::to_string(arr[c].val); + 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] ) + bool search(int x, int y, int w, int dr) { - for( int d = 0; d < 4; d++ ) - { - if( n->neighbors & ( 1 << d ) ) + 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]) { - 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; + for (int d = 0; d < 4; d++) + { + if (n.neighbors[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; } - } - return false; + + for (int d = 0; d < 4; d++) + { + if (n.neighbors[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; } - for( int d = 0; d < 4; d++ ) + hood_t getNeighbors(int x, int y) { - if( n->neighbors & ( 1 << d ) ) - { - int a = x + dx[d], b = y + dy[d]; - if( arr[a + b * wid].val == 0 ) + hood_t retval; + for (int xx = 0; xx < 4; xx++) { - arr[a + b * wid].val = w; - if( search( a, b, w + dr, dr ) ) return true; - arr[a + b * wid].val = 0; + int 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) + retval.set(xx); } - } + return retval; } - return false; - } - unsigned char getNeighbors( int x, int y ) - { - unsigned char c = 0; int a, b; - for( int xx = 0; xx < 4; xx++ ) + void solveIt() { - 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 ); + 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); } - 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 ) + + 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; + x = a; y = b; + z = arr[a + wid * b].val; } - } + } - int wid, hei, max, dx[4], dy[4]; - node* arr; - bool* weHave; + vector dx = vector({ -1, 1, 0, 0 }); + vector dy = vector({ 0, 0, -1, 1 }); + int wid, hei, max; + vector arr; + vector weHave; }; + //------------------------------------------------------------------------------ -int main( int argc, char* argv[] ) +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 ) != "." ) + 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 (const auto& s : puzz) { - if( atoi( ( *i ).c_str() ) < 10 ) cout << "0"; - cout << ( *i ) << " "; + if (s != "*" && s != ".") + { + if (atoi(s.c_str()) < 10) cout << "0"; + cout << s << " "; + } + else cout << " "; + if (++c >= wid) { cout << endl; c = 0; } } - else cout << " "; - if( ++c >= wid ) { cout << endl; c = 0; } - } - cout << endl << endl; - return system( "pause" ); + cout << endl << endl; + return system("pause"); } diff --git a/Task/Solve-a-Numbrix-puzzle/Tcl/solve-a-numbrix-puzzle.tcl b/Task/Solve-a-Numbrix-puzzle/Tcl/solve-a-numbrix-puzzle.tcl new file mode 100644 index 0000000000..e8ee12b383 --- /dev/null +++ b/Task/Solve-a-Numbrix-puzzle/Tcl/solve-a-numbrix-puzzle.tcl @@ -0,0 +1,197 @@ +# Loop over adjacent pairs in a list. +# Example: +# % eachpair {a b} {1 2 3} {puts $a $b} +# 1 2 +# 2 3 +proc eachpair {varNames ls script} { + if {[lassign $varNames _i _j] ne ""} { + return -code error "Must supply exactly two arguments" + } + tailcall foreach $_i [lrange $ls 0 end-1] $_j [lrange $ls 1 end] $script +} + +namespace eval numbrix { + + namespace path {::tcl::mathop ::tcl::mathfunc} + + proc parse {txt} { + set map [split [string trim $txt] \n] + } + + proc print {map} { + join [lmap row $map { + join [lmap val $row { + format %2d $val + }] " " + }] \n + } + + proc mark {map x y i} { + lset map $x $y $i + } + + proc moves {x y} { + foreach {dx dy} { + 0 1 + -1 0 1 0 + 0 -1 + } { + lappend r [+ $dx $x] [+ $dy $y] + } + return $r + } + + proc rmap {map} { ;# generate a reverse map in a dict {val {x y} ..} + set rmap {} + set h [llength $map] + set w [llength [lindex $map 0]] + set x $w + while {[incr x -1]>=0} { + set y $h + while {[incr y -1]>=0} { + set i [lindex $map $x $y] + if {$i} { + dict set rmap [lindex $map $x $y] [list $x $y] + } + } + } + return $rmap + } + + proc gaps {rmap} { ;# list all the gaps to be filled + set known [lsort -integer [dict keys $rmap]] + set gaps {} + eachpair {i j} $known { + if {$j > $i+1} { + lappend gaps $i $j + } + } + return $gaps + } + + proc fixgaps {map rmap gaps} { ;# add a "tail" gap if needed + set w [llength $map] + set h [llength [lindex $map 0]] + set size [* $h $w] + set max [max {*}[dict keys $rmap]] + if {$max ne $size} { + lappend gaps $max Inf + } + return $gaps + } + + + proc paths {map x0 y0 n} { ;# generate all the maps with a single path filled legally + if {$n == 0} {return [list $map]} + set i [lindex $map $x0 $y0] + set paths {} + foreach {x y} [moves $x0 $y0] { + set j [lindex $map $x $y] + if {$j eq ""} { + continue + } elseif {$j == 0 && $n == $n+1} { + return [list [mark $map $x $y [+ $i 1]]] + } elseif {$j == $i+1} { + lappend paths $map + continue + } elseif {$j || ($n == 1)} { + continue + } else { + lappend paths {*}[ + paths [ + mark $map $x $y [+ $i 1] + ] $x $y [- $n 1] + ] + } + } + return $paths + } + + proc solve {map} { + # fixpoint map + while 1 { ;# first we iteratively fill in paths with distinct solutions + set rmap [rmap $map] + set gaps [gaps $rmap] + set gaps [fixgaps $map $rmap $gaps] + if {$gaps eq ""} { + return $map + } + set oldmap $map + foreach {i j} $gaps { + lassign [dict get $rmap $i] x0 y0 + set n [- $j $i] + set paths [paths $map $x0 $y0 $n] + if {$paths eq ""} { + return "" + } elseif {[llength $paths] == 1} { + #puts "solved $i..$j" + #puts [print $map] + set map [lindex $paths 0] + } + ;# we could intersect the paths to maybe get some tiles + } + if {$map eq $oldmap} { + break + } + } + #puts "unique paths exhausted - going DFS" + try { ;# for any left over paths, go DFS + ;# we might want to sort the gaps first + foreach {i j} $gaps { + lassign [dict get $rmap $i] x0 y0 + set n [- $j $i] + set paths [paths $map $x0 $y0 $n] + foreach path $paths { + #puts "recursing on $i..$j" + set sol [solve $path] + if {$sol ne ""} { + return $sol + } + } + } + } + } + + namespace export {[a-z]*} + namespace ensemble create +} + +set puzzles { + { + 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 + } + + { + 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 + } +} + + +foreach puzzle $puzzles { + set map [numbrix parse $puzzle] + puts "\n== Puzzle [incr i] ==" + puts [numbrix print $map] + set sol [numbrix solve $map] + if {$sol ne ""} { + puts "\n== Solution $i ==" + puts [numbrix print $sol] + } else { + puts "\n== No Solution for Puzzle $i ==" + } +} diff --git a/Task/Solve-the-no-connection-puzzle/00META.yaml b/Task/Solve-the-no-connection-puzzle/00META.yaml index a0bf2f827b..31274225a6 100644 --- a/Task/Solve-the-no-connection-puzzle/00META.yaml +++ b/Task/Solve-the-no-connection-puzzle/00META.yaml @@ -1,4 +1,2 @@ --- -category: -- Puzzles -note: Solve the no connection puzzle +note: Puzzles diff --git a/Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chapel b/Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chapel new file mode 100644 index 0000000000..2bf1bc26c7 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Chapel/solve-the-no-connection-puzzle.chapel @@ -0,0 +1,78 @@ +type hole = int; +param A : hole = 1; +param B : hole = A+1; +param C : hole = B+1; +param D : hole = C+1; +param E : hole = D+1; +param F : hole = E+1; +param G : hole = F+1; +param H : hole = G+1; +param starting : int = 0; +const holes : domain(hole) = { A,B,C,D,E,F,G,H }; +const graph : [holes] domain(hole) = [ A => { C,D,E }, + B => { D,E,F }, + C => { A,D,G }, + D => { A,B,C,E,G,H }, + E => { A,B,D,F,G,H }, + F => { B,E,H }, + G => { C,D,E }, + H => { D,E,F } + ]; + +proc check( configuration : [] int, idx : hole ) : bool { + var good = true; + for adj in graph[idx] { + if adj >= idx then continue; + if abs( configuration[idx] - configuration[adj] ) <= 1 { + good = false; + break; + } + } + + return good; +} + +proc solve( configuration : [] int, pegs : domain(int), idx : hole = A ) : bool { + for value in pegs { + configuration[idx] = value; + if check( configuration, idx ) { + if idx < holes.size { + var prePegs = pegs; + if solve( configuration, prePegs - value, idx + 1 ){ + return true; + } + } else { + return true; + } + } + } + configuration[idx] = starting; + return false; +} + +proc printBoard( configuration : [] int ){ +return +"\n " + configuration[A] + " " + configuration[B]+ "\n" + +" /|\\ /|\\ \n"+ +" / | X | \\ \n"+ +" / |/ \\| \\ \n"+ +" " + configuration[C] +" - " + configuration[D] + " - " + configuration[E] + " - " + configuration[F] + " \n"+ +" \\ |\\ /| / \n"+ +" \\ | X | / \n"+ +" \\|/ \\|/ \n"+ +" " + configuration[G] + " " + configuration[H]+ "\n"; + +} + + + +proc main(){ + var configuration : [holes] int; + for idx in holes do configuration[idx] = starting; + + var pegs : domain(int) = {1,2,3,4,5,6,7,8}; + solve( configuration, pegs ); + + writeln( printBoard( configuration ) ); + +} diff --git a/Task/Solve-the-no-connection-puzzle/Haskell/solve-the-no-connection-puzzle.hs b/Task/Solve-the-no-connection-puzzle/Haskell/solve-the-no-connection-puzzle.hs new file mode 100644 index 0000000000..bf10541830 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Haskell/solve-the-no-connection-puzzle.hs @@ -0,0 +1,34 @@ +import Data.List + +isSolution :: [Int] -> Bool +isSolution (a:b:c:d:e:f:g:h:_) = + all (\v -> abs v > 1) + [a-d, + c-d, + g-d, + e-d, + + a-c, + c-g, + g-e, + e-a, + + b-e, + -- d-e, + h-e, + f-e, + + b-d, + d-h, + h-f, + f-b] + + +main :: IO () +main = do + let solution@(a:b:c:d:e:f:g:h:_) = head $ filter isSolution (permutations [1..8]) + mapM_ putStrLn $ zipWith (\label val -> [label] ++ " = " ++ show val) ['A'..'H'] solution + putStrLn "" + putStrLn $ " " ++ (show a) ++ " " ++ (show b) + putStrLn $ (show c) ++ " " ++ (show d) ++ " " ++ (show e) ++ " " ++ (show f) + putStrLn $ " " ++ (show g) ++ " " ++ (show h) diff --git a/Task/Solve-the-no-connection-puzzle/Mathematica/solve-the-no-connection-puzzle.math b/Task/Solve-the-no-connection-puzzle/Mathematica/solve-the-no-connection-puzzle.math new file mode 100644 index 0000000000..3f4c15ced2 --- /dev/null +++ b/Task/Solve-the-no-connection-puzzle/Mathematica/solve-the-no-connection-puzzle.math @@ -0,0 +1,11 @@ +sol = Fold[ + Select[#, + Function[perm, Abs[perm[[#2[[1]]]] - perm[[#2[[2]]]]] > 1]] &, + Permutations[ + Range[8]], {{1, 3}, {1, 4}, {1, 5}, {2, 4}, {2, 5}, {2, 6}, {3, + 4}, {3, 7}, {4, 5}, {4, 7}, {4, 8}, {5, 6}, {5, 7}, {5, 8}, {6, + 8}}][[1]]; +Print[StringForm[ + " `` ``\n /|\\ /|\\\n / | X | \\\n / |/ \\| \\\n`` - `` \ +- `` - ``\n \\ |\\ /| /\n \\ | X | /\n \\|/ \\|/\n `` ``", + Sequence @@ sol]]; diff --git a/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-1.bracmat b/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-1.bracmat new file mode 100644 index 0000000000..258210614d --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-1.bracmat @@ -0,0 +1,7 @@ +( (tab=("C++",1979)+(Ada,1983)+(Ruby,1995)+(Eiffel,1985)) +& out$"unsorted array:" +& lst$tab +& out$("sorted array:" !tab \n) +& out$"But tab is still unsorted:" +& lst$tab +); diff --git a/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-2.bracmat b/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-2.bracmat new file mode 100644 index 0000000000..cb306ed949 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-2.bracmat @@ -0,0 +1,4 @@ +( !tab:?tab +& out$"Now tab is sorted:" +& lst$tab +); diff --git a/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-3.bracmat b/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-3.bracmat new file mode 100644 index 0000000000..8adc1e2b99 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-3.bracmat @@ -0,0 +1,21 @@ +( ((name.map),(weight.9),(value.150)) + ((name.compass),(weight.13),(value.35)) + ((name.water),(weight.153),(value.200)) + ((name.sandwich),(weight.50),(value.60)) + ((name.glucose),(weight.15),(value.60)) + : ?array +& ( reverse + = e A + . :?A + & whl'(!arg:%?e ?arg&!e !A:?A) + & !A + ) +& out$("Array before sorting:" !array \n) +& 0:?sum +& whl + ' (!array:%?element ?array&!element+!sum:?sum) +& whl + ' (!sum:%?element+?sum&!element !array:?array) +& out$("Array after sorting (descending order):" !array \n) +& out$("Array after sorting (ascending order):" reverse$!array \n) +); diff --git a/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-4.bracmat b/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-4.bracmat new file mode 100644 index 0000000000..dc50e577fb --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Bracmat/sort-an-array-of-composite-structures-4.bracmat @@ -0,0 +1,22 @@ +( (Joe,5531) + (Adam,2341) + (Bernie,122) + (Walter,1234) + (David,19) + : ?array +& 0:?sum +& whl + ' ( !array:(?car,?cdr) ?array + & (!cdr.!car)+!sum:?sum + ) +& whl + ' ( !sum:(?car.?cdr)+?sum + & (!cdr,!car) !array:?array + ) +& out$("Array after sorting on second field (descending order):" !array \n) +& out + $ ( "Array after sorting on second field (ascending order):" + reverse$!array + \n + ) +); diff --git a/Task/Sort-an-array-of-composite-structures/Elixir/sort-an-array-of-composite-structures.elixir b/Task/Sort-an-array-of-composite-structures/Elixir/sort-an-array-of-composite-structures.elixir new file mode 100644 index 0000000000..7c39639349 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Elixir/sort-an-array-of-composite-structures.elixir @@ -0,0 +1,12 @@ +defmodule Person do + defstruct name: "", value: 0 +end + +list = [struct(Person, [name: "Joe", value: 3]), + struct(Person, [name: "Bill", value: 4]), + struct(Person, [name: "Alice", value: 20]), + struct(Person, [name: "Harry", value: 3])] + +Enum.sort(list) |> Enum.each(fn x -> IO.inspect x end) +IO.puts "" +Enum.sort_by(list, &(&1.value)) |> Enum.each(&IO.inspect &1) diff --git a/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures.java b/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures-1.java similarity index 100% rename from Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures.java rename to Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures-1.java diff --git a/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures-2.java b/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures-2.java new file mode 100644 index 0000000000..d05ded595f --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures-2.java @@ -0,0 +1,3 @@ + public static void sortByName(Pair[] pairs) { + Arrays.sort(pairs, (p1, p2) -> p1.name.compareTo(p2.name)); + } diff --git a/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures-3.java b/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures-3.java new file mode 100644 index 0000000000..40e2f1cfb5 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Java/sort-an-array-of-composite-structures-3.java @@ -0,0 +1,3 @@ + public static void sortByName(Pair[] pairs) { + Arrays.sort(pairs, Comparator.comparing(p -> p.name)); + } diff --git a/Task/Sort-an-array-of-composite-structures/Julia/sort-an-array-of-composite-structures.julia b/Task/Sort-an-array-of-composite-structures/Julia/sort-an-array-of-composite-structures.julia new file mode 100644 index 0000000000..7b71facbc0 --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/Julia/sort-an-array-of-composite-structures.julia @@ -0,0 +1,38 @@ +type Pair{T<:String} + name::T + value::T +end + +Base.show(a::Pair) = @sprintf "%s => %s" a.name a.value + +x = Pair[Pair("gold", "shiny"), + Pair("neon", "inert"), + Pair("sulphur", "yellow"), + Pair("iron", "magnetic"), + Pair("zebra", "striped"), + Pair("star", "brilliant"), + Pair("apple", "tasty"), + Pair("ruby", "red"), + Pair("dice", "random"), + Pair("coffee", "stimulating"), + Pair("book", "interesting")] + + +println("x, the original list of pairs: ") +for p in x + println(" ", show(p)) +end + +println() +println("x sorted by name:") +x = sort(x, by=a->a.name) +for p in x + println(" ", show(p)) +end + +println() +println("x sorted by value:") +x = sort(x, by=a->a.value) +for p in x + println(" ", show(p)) +end diff --git a/Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.psh b/Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.psh new file mode 100644 index 0000000000..267f005feb --- /dev/null +++ b/Task/Sort-an-array-of-composite-structures/PowerShell/sort-an-array-of-composite-structures.psh @@ -0,0 +1,9 @@ +$list = @{ +"def" = "one" +"abc" = "two" +"jkl" = "three" +"abcdef" = "four" +"ghi" = "five" +"ghijkl" = "six" + } + $list.GetEnumerator() | sort {-($PSItem.Name).length}, Name diff --git a/Task/Sort-an-integer-array/Elixir/sort-an-integer-array.elixir b/Task/Sort-an-integer-array/Elixir/sort-an-integer-array.elixir new file mode 100644 index 0000000000..65629b31c8 --- /dev/null +++ b/Task/Sort-an-integer-array/Elixir/sort-an-integer-array.elixir @@ -0,0 +1,3 @@ +list = [2, 4, 3, 1, 2] +IO.inspect Enum.sort(list) +IO.inspect Enum.sort(list, &(&1>&2)) diff --git a/Task/Sort-an-integer-array/Ruby/sort-an-integer-array.rb b/Task/Sort-an-integer-array/Ruby/sort-an-integer-array.rb index 8e3a799c73..1a37b21a73 100644 --- a/Task/Sort-an-integer-array/Ruby/sort-an-integer-array.rb +++ b/Task/Sort-an-integer-array/Ruby/sort-an-integer-array.rb @@ -1,3 +1,7 @@ nums = [2,4,3,1,2] -sorted = nums.sort # returns a new sorted array. 'nums' is unchanged -nums.sort! # sort 'nums' "in-place" +sorted = nums.sort # returns a new sorted array. 'nums' is unchanged +p sorted #=> [1, 2, 2, 3, 4] +p nums #=> [2, 4, 3, 1, 2] + +nums.sort! # sort 'nums' "in-place" +p nums #=> [1, 2, 2, 3, 4] diff --git a/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust b/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust index 7116d4e875..6a49d6f657 100644 --- a/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust +++ b/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust @@ -2,5 +2,5 @@ fn main() { let mut a = vec!(9, 8, 7, 6, 5, 4, 3, 2, 1, 0); a.sort(); - println!("{}", a); + println!("{:?}", a); } diff --git a/Task/Sort-disjoint-sublist/Elixir/sort-disjoint-sublist.elixir b/Task/Sort-disjoint-sublist/Elixir/sort-disjoint-sublist.elixir new file mode 100644 index 0000000000..6cb80d02b9 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Elixir/sort-disjoint-sublist.elixir @@ -0,0 +1,20 @@ +defmodule Sort_disjoint do + def sublist(values, indices) when is_list(values) and is_list(indices) do + indices2 = Enum.sort(indices) + selected = select(Enum.with_index(values), indices2, []) + replace(Enum.with_index(values), Enum.zip(indices2, selected), []) + end + + defp select(_, [], selected), do: Enum.sort(selected) + defp select([{val,i}|t], [idx|rest], selected) when i==idx, do: select(t, rest, [val|selected]) + defp select([_|t], indices, selected), do: select(t, indices, selected) + + defp replace([], [], list), do: Enum.reverse(list) + defp replace([{val,_}|t], [], list), do: replace(t, [], [val|list]) + defp replace([{_,idx}|t], [{i,v}|rest], list) when idx==i, do: replace(t, rest, [v|list]) + defp replace([{val,_}|t], indices, list), do: replace(t, indices, [val|list]) +end + +values = [7, 6, 5, 4, 3, 2, 1, 0] +indices = [6, 1, 7] +IO.inspect Sort_disjoint.sublist(values, indices) diff --git a/Task/Sort-disjoint-sublist/Julia/sort-disjoint-sublist.julia b/Task/Sort-disjoint-sublist/Julia/sort-disjoint-sublist.julia new file mode 100644 index 0000000000..6756a4ef29 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Julia/sort-disjoint-sublist.julia @@ -0,0 +1,18 @@ +function sortselected{S<:Real,T<:Integer}(a::AbstractArray{S,1}, + s::AbstractArray{T,1}) + sel = unique(sort(s)) + if sel[1] < 1 || length(a) < sel[end] + throw(ArgumentError("Tried to select outside of input array.")) + end + b = collect(copy(a)) + b[sel] = sort(b[sel]) + return b +end + +a = [7, 6, 5, 4, 3, 2, 1, 0] +sel = [7, 2, 8] +b = sortselected(a, sel) + +print("Original Array: ", a) +println(" sorted on ", sel) +println("Sorted Array: ", b) diff --git a/Task/Sort-disjoint-sublist/PowerShell/sort-disjoint-sublist.psh b/Task/Sort-disjoint-sublist/PowerShell/sort-disjoint-sublist.psh new file mode 100644 index 0000000000..373109e071 --- /dev/null +++ b/Task/Sort-disjoint-sublist/PowerShell/sort-disjoint-sublist.psh @@ -0,0 +1,9 @@ +function sublistsort($values, $indices) { + $indices = $indices | sort + $sub, $i = ($values[$indices] | sort), 0 + $indices | foreach { $values[$_] = $sub[$i++] } + $values +} +$values = 7, 6, 5, 4, 3, 2, 1, 0 +$indices = 6, 1, 7 +"$(sublistsort $values $indices)" diff --git a/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx b/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx index ae91e06894..3522fb60cd 100644 --- a/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx +++ b/Task/Sort-disjoint-sublist/REXX/sort-disjoint-sublist.rexx @@ -1,29 +1,26 @@ -/*REXX program uses a strand sort to sort a random list of words | nums.*/ -parse arg old ',' idx /*get options from command line. */ -if old='' then old=7 6 5 4 3 2 1 0 /*no list? Then use the default.*/ -if idx='' then idx=7 2 8 /*no idxs? " " " " */ -old=space(old) /*remove any extraneous blanks. */ -say 'list of indices:' idx -idx=sortL(idx) /*ensure the index list is sorted*/ -say -say ' unsorted list:' old - new=disjoint_sort(old,idx) /*sort it.*/ -say ' sorted list:' new +/*REXX program uses a disjointed sublist to sort a random list of values*/ +parse arg old ',' idx /*get lists from the command line*/ +if old='' then old=7 6 5 4 3 2 1 0 /*No old? Then use the default.*/ +if idx='' then idx=7 2 8 /* " idx? " " " " */ +say ' list of indices:' idx; say /* [↑] is for one─based lists*/ +say ' unsorted list:' old /*display old list.*/ +say ' sorted list:' disjoint_sort(old, idx) /*sort, display it.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────DISJOINT_SORT subroutine────────────*/ -disjoint_sort: procedure; parse arg x,indL; y=; z=; p=0 - do i=1 for words(indL) /*extract indexed values from X.*/ - z=z word(x,word(indL,i)) - end /*j*/ +disjoint_sort: procedure; parse arg x,ix; y=; z=; p=0 +ix=sortL(ix) /*ensure the index list is sorted*/ + do i=1 for words(ix) /*extract indexed values from X.*/ + z=z word(x, word(ix, i)) /*pick the correct value from X.*/ + end /*j*/ z=sortL(z) /*sort extracted (indexed) values*/ - do m=1 for words(x) /*re-build (re-populate) X list.*/ - if wordpos(m,indL)==0 then y=y word(x,m) /*same | new?*/ - else do; p=p+1; y=y word(z,p); end - end /*m*/ + do m=1 for words(x) /*re-build (re-populate) X list.*/ + if wordpos(m,ix)==0 then y=y word(x,m) /*same | new?*/ + else do; p=p+1; y=y word(z,p); end + end /*m*/ return strip(y) /*──────────────────────────────────SORTL subroutine────────────────────*/ -sortL: procedure; parse arg L; n=words(L); do j=1 for n; @.j=word(L,j); end - do k=1 to n-1 /*sort index list the slow way. */ - do m=k+1 to n; if @.m<@.k then parse value @.k @.m with @.m @.k; end - end /*k*/ -s=@.1; do j=2 to n; s=s @.j; end; return s +sortL: procedure; parse arg L; n=words(L); do j=1 for n; @.j=word(L,j);end + do k=1 for n-1 /*sort a list using a slow method*/ + do m=k+1 to n; if @.m<@.k then parse value @.k @.m with @.m @.k; end + end /*k*/ /* [↑] use PARSE for swapping.*/ +$=@.1; do j=2 to n; $=$ @.j; end; return $ diff --git a/Task/Sort-stability/Elixir/sort-stability-1.elixir b/Task/Sort-stability/Elixir/sort-stability-1.elixir new file mode 100644 index 0000000000..2823aac41d --- /dev/null +++ b/Task/Sort-stability/Elixir/sort-stability-1.elixir @@ -0,0 +1,9 @@ +cities = [ {"UK", "London"}, + {"US", "New York"}, + {"US", "Birmingham"}, + {"UK", "Birmingham"} ] + +IO.inspect Enum.sort(cities) +IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) >= elem(b,0) end) +IO.inspect Enum.sort_by(cities, fn {country, _city} -> country end) +IO.inspect Enum.sort_by(cities, fn {_country, city} -> city end) diff --git a/Task/Sort-stability/Elixir/sort-stability-2.elixir b/Task/Sort-stability/Elixir/sort-stability-2.elixir new file mode 100644 index 0000000000..22dcfd602a --- /dev/null +++ b/Task/Sort-stability/Elixir/sort-stability-2.elixir @@ -0,0 +1 @@ +IO.inspect Enum.sort(cities, fn a,b -> elem(a,0) > elem(b,0) end) diff --git a/Task/Sort-stability/Liberty-BASIC/sort-stability.liberty b/Task/Sort-stability/Liberty-BASIC/sort-stability.liberty new file mode 100644 index 0000000000..d8fc5fbccd --- /dev/null +++ b/Task/Sort-stability/Liberty-BASIC/sort-stability.liberty @@ -0,0 +1,28 @@ +randomize 0.5 +N=15 +dim a(N,2) + +for i = 0 to N-1 + a(i,1)= int(i/5) + a(i,2)= int(rnd(1)*5) +next + +print "Unsorted by column #2" +print "by construction sorted by column #1" +for i = 0 to N-1 + print a(i,1), a(i,2) +next + +sort a(), 0, N-1, 2 +print + +print "After sorting by column #2" +print "Notice wrong order by column #1" +for i = 0 to N-1 + print a(i,1), a(i,2), + if i=0 then + print + else + if a(i,2) = a(i-1,2) AND a(i,1) < a(i-1,1) then print "bad order" else print + end if +next diff --git a/Task/Sort-using-a-custom-comparator/Julia/sort-using-a-custom-comparator.julia b/Task/Sort-using-a-custom-comparator/Julia/sort-using-a-custom-comparator.julia new file mode 100644 index 0000000000..c12cff5561 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Julia/sort-using-a-custom-comparator.julia @@ -0,0 +1,17 @@ +st = """You will rejoice to hear that no disaster has accompanied the +commencement of an enterprise which you have regarded with such evil +forebodings.""" + +wl = filter(x->length(x)>0, split(st, r"\W+")) + +println("Original List:") +for w in wl + println(" ", w) +end + +wl = sort(wl, by=x->(-length(x), lowercase(x))) + +println("\nSorted List:") +for w in wl + println(" ", w) +end diff --git a/Task/Sorting-algorithms-Bead-sort/00DESCRIPTION b/Task/Sorting-algorithms-Bead-sort/00DESCRIPTION index df3edab475..8d8f32597a 100644 --- a/Task/Sorting-algorithms-Bead-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Bead-sort/00DESCRIPTION @@ -1,4 +1,5 @@ {{Sorting Algorithm}} In this task, the goal is to sort an array of positive integers using the [[wp:Bead_sort|Bead Sort Algorithm]]. -Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations. +Algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually. +This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations. diff --git a/Task/Sorting-algorithms-Bead-sort/Common-Lisp/sorting-algorithms-bead-sort.lisp b/Task/Sorting-algorithms-Bead-sort/Common-Lisp/sorting-algorithms-bead-sort.lisp new file mode 100644 index 0000000000..3c6a38d5c5 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Common-Lisp/sorting-algorithms-bead-sort.lisp @@ -0,0 +1,10 @@ +(defun transpose (remain &optional (ret '())) + (if (null remain) + ret + (transpose (remove-if #'null (mapcar #'cdr remain)) + (append ret (list (mapcar #'car remain)))))) + +(defun bead-sort (xs) + (mapcar #'length (transpose (transpose (mapcar (lambda (x) (make-list x :initial-element 1)) xs))))) + +(bead-sort '(5 2 4 1 3 3 9)) diff --git a/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-1.e b/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-1.e index 1fdb130674..e24d4639ed 100644 --- a/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-1.e +++ b/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-1.e @@ -1,61 +1,83 @@ class BEAD_SORT + feature - bead_sort(ar: ARRAY[INTEGER]): ARRAY[INTEGER] + + bead_sort (ar: ARRAY [INTEGER]): ARRAY [INTEGER] + -- Sorted array in descending order. + require + only_positive_integers: across ar as a all a.item > 0 end local max, count, i, j, k: INTEGER - sorted: ARRAY[INTEGER] do - max:= max_item(ar) - create sorted.make_filled(0,1, ar.count) + max := max_item (ar) + create Result.make_filled (0, 1, ar.count) from - i:= 1 + i := 1 until - i> max + i > max loop - count:= 0 + count := 0 from - k:= 1 + k := 1 until - k> ar.count + k > ar.count loop if ar.item (k) >= i then - count:= count+1 + count := count + 1 end - k:= k+1 + k := k + 1 end from - j:= 1 + j := 1 until - j>count + j > count loop - sorted[j]:= i - j:= j+1 + Result [j] := i + j := j + 1 end - i:= i+1 + i := i + 1 end - RESULT:= sorted - end + ensure + array_is_sorted: is_sorted (Result) + end -feature{NONE} - max_item(ar: ARRAY [INTEGER]):INTEGER - require - ar_not_void: ar/= Void - local - i, max: INTEGER - do - from - i:=1 - until - i > ar.count - loop - if ar.item(i) > max then - max := ar.item(i) - end - i := i + 1 - end - Result := max +feature {NONE} + + max_item (ar: ARRAY [INTEGER]): INTEGER + -- Max item of 'ar'. + require + ar_not_void: ar /= Void + do + across + ar as a + loop + if a.item > Result then + Result := a.item + end + end ensure - result_is_set: Result /= Void - end + Result_is_max: across ar as a all a.item <= Result end + end + + is_sorted (ar: ARRAY [INTEGER]): BOOLEAN + --- Is 'ar' sorted in descending order? + require + ar_not_empty: ar.is_empty = False + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i = ar.upper + loop + if ar [i] < ar [i + 1] then + Result := False + end + i := i + 1 + end + end + end diff --git a/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-2.e b/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-2.e index 72204af86e..186de855e0 100644 --- a/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-2.e +++ b/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-2.e @@ -1,20 +1,32 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature - make - do - test:= <<1, 5, 99, 2, 95, 7, 7>> - create beadsort - io.put_string ("unsorted:"+"%N") - across test as ar loop io.put_string(ar.item.out + "%T") end - io.put_string ("%N"+"sorted:"+"%N") - test:= beadsort.bead_sort (test) - across test as ar loop io.put_string(ar.item.out + "%T") end - end - beadsort: BEAD_SORT - test: ARRAY[INTEGER] + + make + do + test := <<1, 5, 99, 2, 95, 7, 7>> + create beadsort + io.put_string ("unsorted:" + "%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + io.put_string ("%N" + "sorted:" + "%N") + test := beadsort.bead_sort (test) + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + end + + beadsort: BEAD_SORT + + test: ARRAY [INTEGER] + end diff --git a/Task/Sorting-algorithms-Bead-sort/Elixir/sorting-algorithms-bead-sort.elixir b/Task/Sorting-algorithms-Bead-sort/Elixir/sorting-algorithms-bead-sort.elixir new file mode 100644 index 0000000000..8c2170fdef --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Elixir/sorting-algorithms-bead-sort.elixir @@ -0,0 +1,10 @@ +defmodule Sort do + def bead_sort(list) when is_list(list), do: dist(dist(list)) + + defp dist(list), do: List.foldl(list, [], fn(n, acc) when n>0 -> dist(acc, n, []) end) + + defp dist([], 0, acc), do: Enum.reverse(acc) + defp dist([h|t], 0, acc), do: dist(t, 0, [h |acc]) + defp dist([], n, acc), do: dist([], n-1, [1 |acc]) + defp dist([h|t], n, acc), do: dist(t, n-1, [h+1|acc]) +end diff --git a/Task/Sorting-algorithms-Bead-sort/Julia/sorting-algorithms-bead-sort.julia b/Task/Sorting-algorithms-Bead-sort/Julia/sorting-algorithms-bead-sort.julia new file mode 100644 index 0000000000..d58b468b2d --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Julia/sorting-algorithms-bead-sort.julia @@ -0,0 +1,36 @@ +function beadsort{T<:Integer}(a::Array{T,1}) + (lo, hi) = extrema(a) + if lo < 1 + throw(DomainError()) + end + hi = convert(Int, hi) + len = length(a) + abacus = falses(len, hi) + for (i, v) in enumerate(a) + abacus[i,1:v] = true + end + for i in 1:hi + v = sum(abacus[:,i]) + if v < len + abacus[1:end-v,i] = false + abacus[end-v+1:end,i] = true + end + end + return T[sum(abacus[i,:]) for i in 1:len] +end + +a = Uint8[rand(1:typemax(Uint8)) for i in 1:20] +println("Sort of Unsigned Bytes:") +println(" Before Sort:") +println(" ", a) +a = beadsort(a) +println("\n After Sort:") +println(" ", a, "\n") + +a = [rand(1:2^10) for i in 1:20] +println("Sort of Integers:") +println(" Before Sort:") +println(" ", a) +a = beadsort(a) +println("\n After Sort:") +println(" ", a) diff --git a/Task/Sorting-algorithms-Bead-sort/PHP/sorting-algorithms-bead-sort.php b/Task/Sorting-algorithms-Bead-sort/PHP/sorting-algorithms-bead-sort.php index 18732beea8..dda678e997 100644 --- a/Task/Sorting-algorithms-Bead-sort/PHP/sorting-algorithms-bead-sort.php +++ b/Task/Sorting-algorithms-Bead-sort/PHP/sorting-algorithms-bead-sort.php @@ -1,9 +1,9 @@ = 1 + 1 and i <= ar.count + 1 until @@ -32,27 +38,29 @@ feature{NONE} end end - shuffel(ar:ARRAY[INTEGER]): ARRAY[INTEGER] - require - not_void: ar/= Void - local - i,j:INTEGER - ith: INTEGER - random: V_RANDOM - do - create random - from - i:=ar.count - until - i<2 - loop - j:=random.bounded_item (1, i) - ith:= ar[i] - ar[i]:= ar[j] - ar[j]:= ith - random.forth - i:=i-1 - end - Result:= ar - end + shuffle (ar: ARRAY [INTEGER]): ARRAY [INTEGER] + -- Array containing the same elements as 'ar' in a shuffled order. + require + more_than_one_element: ar.count > 1 + local + count, j, ith: INTEGER + random: V_RANDOM + do + create random + create Result.make_empty + Result.deep_copy (ar) + count := ar.count + across + 1 |..| count as c + loop + j := random.bounded_item (c.item, count) + ith := Result [c.item] + Result [c.item] := Result [j] + Result [j] := ith + random.forth + end + ensure + same_elements: across ar as a all Result.has (a.item) end + end + end diff --git a/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-2.e b/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-2.e index d4dd10b837..7ab2eb7456 100644 --- a/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-2.e +++ b/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-2.e @@ -1,24 +1,32 @@ class APPLICATION -inherit - ARGUMENTS - create make -feature {NONE} -- Initialization +feature {NONE} make do - test:= <<3,2,5,7,1>> + test := <<3, 2, 5, 7, 1>> io.put_string ("Unsorted: ") - across test as t loop io.put_string (t.item.out + " ") end + across + test as t + loop + io.put_string (t.item.out + " ") + end create sorter - test:= sorter.bogo_sort (test) + test := sorter.bogo_sort (test) io.put_string ("%NSorted: ") - across test as t loop io.put_string (t.item.out + " ") end + across + test as t + loop + io.put_string (t.item.out + " ") + end end - test: ARRAY[INTEGER] - sorter: BOGO_SORT + + test: ARRAY [INTEGER] + + sorter: BOGO_SORT + end diff --git a/Task/Sorting-algorithms-Bogosort/Elixir/sorting-algorithms-bogosort.elixir b/Task/Sorting-algorithms-Bogosort/Elixir/sorting-algorithms-bogosort.elixir new file mode 100644 index 0000000000..683ed033f5 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Elixir/sorting-algorithms-bogosort.elixir @@ -0,0 +1,13 @@ +defmodule Sort do + def bogo_sort(list) do + if sorted?(list) do + list + else + bogo_sort(Enum.shuffle(list)) + end + end + + defp sorted?(list) when length(list)<=1, do: true + defp sorted?([x, y | _]) when x>y, do: false + defp sorted?([_, y | rest]), do: sorted?([y | rest]) +end diff --git a/Task/Sorting-algorithms-Bogosort/Julia/sorting-algorithms-bogosort.julia b/Task/Sorting-algorithms-Bogosort/Julia/sorting-algorithms-bogosort.julia new file mode 100644 index 0000000000..b2bc6f0f2f --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Julia/sorting-algorithms-bogosort.julia @@ -0,0 +1,25 @@ +function isordered{T}(a::AbstractArray{T,1}) + if length(a) < 2 + return true + end + for i in 2:length(a) + if a[i] < a[i-1] + return false + end + end + return true +end + +function bogosort!{T}(a::AbstractArray{T,1}) + while !isordered(a) + shuffle!(a) + end + return a +end + +a = [rand(-10:10) for i in 1:10] +println("Before bogosort:") +println(a) +bogosort!(a) +println("\nAfter bogosort:") +println(a) diff --git a/Task/Sorting-algorithms-Bogosort/Scala/sorting-algorithms-bogosort.scala b/Task/Sorting-algorithms-Bogosort/Scala/sorting-algorithms-bogosort.scala index aa54bb6ff3..8c26287c69 100644 --- a/Task/Sorting-algorithms-Bogosort/Scala/sorting-algorithms-bogosort.scala +++ b/Task/Sorting-algorithms-Bogosort/Scala/sorting-algorithms-bogosort.scala @@ -1,2 +1,2 @@ -def isSorted(l: List[Int]) = l.iterator sliding 2 forall (s => s.head < s.last) +def isSorted(l: List[Int]) = l.iterator sliding 2 forall (s => s.head <= s.last) def bogosort(l: List[Int]): List[Int] = if (isSorted(l)) l else bogosort(scala.util.Random.shuffle(l)) diff --git a/Task/Sorting-algorithms-Bubble-sort/ALGOL-W/sorting-algorithms-bubble-sort.alg b/Task/Sorting-algorithms-Bubble-sort/ALGOL-W/sorting-algorithms-bubble-sort.alg new file mode 100644 index 0000000000..507f435334 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/ALGOL-W/sorting-algorithms-bubble-sort.alg @@ -0,0 +1,60 @@ +begin + % As algol W does not allow overloading, we have to have type-specific % + % sorting procedures - this bubble sorts an integer array % + % as there is no way for the procedure to determine the array bounds, we % + % pass the lower and upper bounds in lb and ub % + procedure bubbleSortIntegers( integer array item( * ) + ; integer value lb + ; integer value ub + ) ; + begin + integer lower, upper; + + lower := lb; + upper := ub; + + while + begin + logical swapped; + upper := upper - 1; + swapped := false; + for i := lower until upper + do begin + if item( i ) > item( i + 1 ) + then begin + integer val; + val := item( i ); + item( i ) := item( i + 1 ); + item( i + 1 ) := val; + swapped := true; + end if_must_swap ; + end for_i ; + swapped + end + do begin end; + end bubbleSortIntegers ; + + begin % test the bubble sort % + integer array data( 1 :: 10 ); + + procedure writeData ; + begin + write( data( 1 ) ); + for i := 2 until 10 do writeon( data( i ) ); + end writeData ; + + % initialise data to unsorted values % + integer dPos; + dPos := 1; + for i := 16, 2, -6, 9, 90, 14, 0, 23, 8, 9 + do begin + data( dPos ) := i; + dPos := dPos + 1; + end for_i ; + + i_w := 3; s_w := 1; % set output format % + writeData; + bubbleSortIntegers( data, 1, 10 ); + writeData; + end test +end. diff --git a/Task/Sorting-algorithms-Bubble-sort/Elixir/sorting-algorithms-bubble-sort.elixir b/Task/Sorting-algorithms-Bubble-sort/Elixir/sorting-algorithms-bubble-sort.elixir new file mode 100644 index 0000000000..84240a2e70 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Elixir/sorting-algorithms-bubble-sort.elixir @@ -0,0 +1,17 @@ +defmodule Sort do + def bubble_sort(list) when length(list)<=1, do: list + def bubble_sort(list) when is_list(list), do: bubble_sort(list, []) + + def bubble_sort([x], sorted), do: [x | sorted] + def bubble_sort(list, sorted) do + {rest, [max]} = Enum.split(bubble_move(list), -1) + bubble_sort(rest, [max | sorted]) + end + + def bubble_move([x]), do: [x] + def bubble_move([x, y | t]) when x > y, do: [y | bubble_move([x | t])] + def bubble_move([x, y | t]) , do: [x | bubble_move([y | t])] + +end + +IO.inspect Sort.bubble_sort([3,2,1,4,5,2]) diff --git a/Task/Sorting-algorithms-Bubble-sort/Julia/sorting-algorithms-bubble-sort.julia b/Task/Sorting-algorithms-Bubble-sort/Julia/sorting-algorithms-bubble-sort.julia new file mode 100644 index 0000000000..3f6ec381fa --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Julia/sorting-algorithms-bubble-sort.julia @@ -0,0 +1,25 @@ +function bubblesort{T}(a::AbstractArray{T,1}) + b = copy(a) + isordered = false + span = length(b) + while !isordered && span > 1 + isordered = true + for i in 2:span + if b[i] < b[i-1] + t = b[i] + b[i] = b[i-1] + b[i-1] = t + isordered = false + end + end + span -= 1 + end + return b +end + +a = [rand(-100:100) for i in 1:20] +println("Before bubblesort:") +println(a) +a = bubblesort(a) +println("\nAfter bubblesort:") +println(a) diff --git a/Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort.scala b/Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort-1.scala similarity index 100% rename from Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort.scala rename to Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort-1.scala diff --git a/Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort-2.scala b/Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort-2.scala new file mode 100644 index 0000000000..6e28737dc3 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Scala/sorting-algorithms-bubble-sort-2.scala @@ -0,0 +1,14 @@ +import scala.annotation.tailrec + +def bubbleSort(xt: List[Int]) = { + @tailrec + def bubble(xs: List[Int], rest: List[Int], sorted: List[Int]): List[Int] = xs match { + case x :: Nil => + if (rest.isEmpty) x :: sorted + else bubble(rest, Nil, x :: sorted) + case a :: b :: xs => + if (a > b) bubble(a :: xs, b :: rest, sorted) + else bubble(b :: xs, a :: rest, sorted) + } + bubble(xt, Nil, Nil) +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/ALGOL-W/sorting-algorithms-cocktail-sort.alg b/Task/Sorting-algorithms-Cocktail-sort/ALGOL-W/sorting-algorithms-cocktail-sort.alg new file mode 100644 index 0000000000..38a2ded870 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/ALGOL-W/sorting-algorithms-cocktail-sort.alg @@ -0,0 +1,65 @@ +begin + % As algol W does not allow overloading, we have to have type-specific % + % sorting procedures - this coctail sorts an integer array % + % as there is no way for the procedure to determine the array bounds, we % + % pass the lower and upper bounds in lb and ub % + procedure coctailSortIntegers( integer array item( * ) + ; integer value lb + ; integer value ub + ) ; + begin + integer lower, upper; + + lower := lb; + upper := ub - 1; + + while + begin + logical swapped; + + procedure swap( integer value i ) ; + begin + integer val; + val := item( i ); + item( i ) := item( i + 1 ); + item( i + 1 ) := val; + swapped := true; + end swap ; + + swapped := false; + for i := lower until upper do if item( i ) > item( i + 1 ) then swap( i ); + if swapped + then begin + % there was at least one unordered element so try a 2nd sort pass % + for i := upper step -1 until lower do if item( i ) > item( i + 1 ) then swap( i ); + upper := upper - 1; lower := lower + 1; + end if_swapped ; + swapped + end + do begin end; + end coctailSortIntegers ; + + begin % test the sort % + integer array data( 1 :: 10 ); + + procedure writeData ; + begin + write( data( 1 ) ); + for i := 2 until 10 do writeon( data( i ) ); + end writeData ; + + % initialise data to unsorted values % + integer dPos; + dPos := 1; + for i := 16, 2, -6, 9, 90, 14, 0, 23, 8, 9 + do begin + data( dPos ) := i; + dPos := dPos + 1; + end for_i ; + + i_w := 3; s_w := 1; % set output format % + writeData; + coctailSortIntegers( data, 1, 10 ); + writeData; + end test ; +end. diff --git a/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-1.e b/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-1.e index 5c0b0435e5..d21d10ba28 100644 --- a/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-1.e +++ b/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-1.e @@ -1,50 +1,90 @@ class - COCKTAIL_SORT[G -> COMPARABLE] + COCKTAIL_SORT [G -> COMPARABLE] + feature -cocktail_sort(ar: ARRAY[G]): ARRAY[G] - require - ar_not_empty: ar.count>=1 - local - swapped, finished: BOOLEAN - sol: ARRAY[G] - i,j : INTEGER - t: G - do - create sol.make_from_array (ar) - from - until finished= TRUE - loop - swapped := FALSE - from - i:= 1 - until - i= ar.count-1 - loop - if ar[i]> ar[i+1] then - t:= ar[i] - ar[i]:= ar[i+1] - ar[i+1]:= t - swapped:= true + + cocktail_sort (ar: ARRAY [G]): ARRAY [G] + -- Array sorted in ascending order. + require + ar_not_empty: ar.count >= 1 + local + not_swapped: BOOLEAN + sol: ARRAY [G] + i, j: INTEGER + t: G + do + create Result.make_empty + Result.deep_copy (ar) + from + until + not_swapped = True + loop + not_swapped := True + from + i := Result.lower + until + i = Result.upper - 1 + loop + if Result [i] > Result [i + 1] then + Result := swap (Result, i) + not_swapped := False + end + i := i + 1 + end + from + j := Result.upper - 1 + until + j = Result.lower + loop + if Result [j] > Result [j + 1] then + Result := swap (Result, j) + not_swapped := False + end + j := j - 1 + end end - i:= i+1 + ensure + ar_is_sorted: is_sorted (Result) end - from j:= ar.count-1 - until j= 1 - loop - if ar[j]> ar[j+1] then - t:= ar[j] - ar[j]:= ar[j+1] - ar[j+1]:= t - swapped:= TRUE - end - j:= j-1 - end - if swapped= FALSE then - finished:= TRUE - sol:= ar +feature{NONE} + + swap (ar: ARRAY [G]; i: INTEGER): ARRAY [G] + -- Array with elements i and i+1 swapped. + require + ar_not_void: ar /= Void + i_is_in_bounds: ar.valid_index (i) + local + t: G + do + create Result.make_empty + Result.deep_copy (ar) + t := Result [i] + Result [i] := Result [i + 1] + Result [i + 1] := t + ensure + swapped_right: Result [i + 1] = ar [i] + swapped_left: Result [i] = ar [i + 1] end + + is_sorted (ar: ARRAY [G]): BOOLEAN + --- Is 'ar' sorted in ascending order? + require + ar_not_empty: ar.is_empty = False + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i = ar.upper + loop + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 + end end - Result:= sol - end + end diff --git a/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-2.e b/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-2.e index ec76e37587..fcf96839ad 100644 --- a/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-2.e +++ b/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-2.e @@ -1,18 +1,33 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - do - test:= <<5,1,99,3,2>> - across test as t loop io.put_string (t.item.out + "%T") end - create cs - test:= cs.cocktail_sort(test) - across test as ar loop io.put_string (ar.item.out+"%T") end - end - cs: COCKTAIL_SORT[INTEGER] - test: ARRAY[INTEGER] + do + test := <<5, 1, 99, 3, 2>> + io.put_string ("unsorted%N") + across + test as t + loop + io.put_string (t.item.out + "%T") + end + io.new_line + io.put_string ("sorted%N") + create cs + test := cs.cocktail_sort (test) + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + end + + cs: COCKTAIL_SORT [INTEGER] + + test: ARRAY [INTEGER] + end diff --git a/Task/Sorting-algorithms-Cocktail-sort/Elixir/sorting-algorithms-cocktail-sort.elixir b/Task/Sorting-algorithms-Cocktail-sort/Elixir/sorting-algorithms-cocktail-sort.elixir new file mode 100644 index 0000000000..e970fdfefb --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Elixir/sorting-algorithms-cocktail-sort.elixir @@ -0,0 +1,21 @@ +defmodule Sort do + def cocktail_sort(list) when is_list(list), do: cocktail_sort(list, [], []) + + defp cocktail_sort([], minlist, maxlist), do: Enum.reverse(minlist, maxlist) + defp cocktail_sort([x], minlist, maxlist), do: Enum.reverse(minlist, [x | maxlist]) + defp cocktail_sort(list, minlist, maxlist) do + {max, rev} = cocktail_max(list, []) + {min, rest} = cocktail_min(rev, []) + cocktail_sort(rest, [min | minlist], [max | maxlist]) + end + + defp cocktail_max([max], list), do: {max, list} + defp cocktail_max([x,y | t], list) when xy, do: cocktail_min([y | t], [x | list]) + defp cocktail_min([x,y | t], list) , do: cocktail_min([x | t], [y | list]) +end + +IO.inspect Sort.cocktail_sort([5,3,9,4,1,6,8,2,7]) diff --git a/Task/Sorting-algorithms-Cocktail-sort/Julia/sorting-algorithms-cocktail-sort.julia b/Task/Sorting-algorithms-Cocktail-sort/Julia/sorting-algorithms-cocktail-sort.julia new file mode 100644 index 0000000000..18158daaa1 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Julia/sorting-algorithms-cocktail-sort.julia @@ -0,0 +1,38 @@ +function coctailsort{T<:Real}(a::Array{T,1}) + b = copy(a) + isordered = false + lo = one(Int) + hi = length(b) + while !isordered && hi > lo + isordered = true + for i in lo+1:hi + if b[i] < b[i-1] + t = b[i] + b[i] = b[i-1] + b[i-1] = t + isordered = false + end + end + hi -= 1 + if isordered || hi <= lo + break + end + for i in hi:-1:lo+1 + if b[i-1] > b[i] + t = b[i] + b[i] = b[i-1] + b[i-1] = t + isordered = false + end + end + lo += 1 + end + return b +end + +a = [rand(-2^10:2^10) for i in 1:20] +println("Before Sort:") +println(a) +a = coctailsort(a) +println("\nAfter Sort:") +println(a) diff --git a/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-1.e b/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-1.e index aeeeb39124..b789b7b427 100644 --- a/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-1.e +++ b/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-1.e @@ -1,44 +1,70 @@ class - COMB_SORT[G -> COMPARABLE] + COMB_SORT [G -> COMPARABLE] + feature - combsort (ar: ARRAY[G]): ARRAY[G] + + combsort (ar: ARRAY [G]): ARRAY [G] + -- Sorted array in ascending order. require - array_not_empty: ar.count >0 + array_not_void: ar /= Void local gap, i: INTEGER swap: G swapped: BOOLEAN shrink: REAL_64 do - gap:= ar.count + create Result.make_empty + Result.deep_copy (ar) + gap := Result.count from - until - gap= 1 and swapped = false + gap = 1 and swapped = False loop from - i:= 1 - swapped:= false + i := Result.lower + swapped := False until - i+gap > ar.count + i + gap > Result.count loop - if ar[i]> ar[i+gap] then - swap:= ar[i] - ar[i]:= ar[i+gap] - ar[i+gap]:= swap - swapped:= TRUE + if Result [i] > Result [i + gap] then + swap := Result [i] + Result [i] := Result [i + gap] + Result [i + gap] := swap + swapped := True end - i:= i+1 + i := i + 1 end - shrink:= gap/1.3 - gap:= shrink.floor - if gap <1 then - gap:= 1 + shrink := gap / 1.3 + gap := shrink.floor + if gap < 1 then + gap := 1 end end - RESULT:= ar - ensure - RESULT_is_set: Result /= VOID + ensure + Result_is_set: Result /= Void + Result_is_sorted: is_sorted (Result) + end +feature {NONE} + + is_sorted (ar: ARRAY [G]): BOOLEAN + --- Is 'ar' sorted in ascending order? + require + ar_not_empty: ar.is_empty = False + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i = ar.upper + loop + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 + end end + end diff --git a/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-2.e b/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-2.e index f26caf6d1c..f4214d25b0 100644 --- a/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-2.e +++ b/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-2.e @@ -1,24 +1,32 @@ class APPLICATION -inherit - ARGUMENTS - create - make + make feature - make - do - test:= <<1,5,99,2,95, 7,-7>> - io.put_string ("unsorted"+"%N") - across test as ar loop io.put_string(ar.item.out + "%T") end - io.put_string ("%N"+"sorted:"+"%N") - create combsort - test:=combsort.combsort(test) - across test as ar loop io.put_string (ar.item.out + "%T") end - end - combsort: COMB_SORT[INTEGER] - test: ARRAY[INTEGER] + make + do + test := <<1, 5, 99, 2, 95, 7, -7>> + io.put_string ("unsorted" + "%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + io.put_string ("%N" + "sorted:" + "%N") + create combsort + test := combsort.combsort (test) + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + end + + combsort: COMB_SORT [INTEGER] + + test: ARRAY [INTEGER] + end diff --git a/Task/Sorting-algorithms-Comb-sort/Liberty-BASIC/sorting-algorithms-comb-sort.liberty b/Task/Sorting-algorithms-Comb-sort/Liberty-BASIC/sorting-algorithms-comb-sort.liberty new file mode 100644 index 0000000000..74f5d24e00 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Liberty-BASIC/sorting-algorithms-comb-sort.liberty @@ -0,0 +1,38 @@ +'randomize 0.5 +itemCount = 20 + dim item(itemCount) + for i = 1 to itemCount + item(i) = int(rnd(1) * 100) + next i + print "Before Sort" + for i = 1 to itemCount + print item(i) + next i + print: print +'t0=time$("ms") + + gap=itemCount + while gap>1 or swaps <> 0 + gap=int(gap/1.25) + 'if gap = 10 or gap = 9 then gap = 11 'uncomment to get Combsort11 + if gap <1 then gap = 1 + i = 1 + swaps = 0 + for i = 1 to itemCount-gap + if item(i) > item(i + gap) then + temp = item(i) + item(i) = item(i + gap) + item(i + gap) = temp + swaps = 1 + end if + next + wend + + print "After Sort" +'t1=time$("ms") +'print t1-t0 + + for i = 1 to itemCount + print item(i) + next i +end diff --git a/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx b/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx index dcde047a63..3703ad567c 100644 --- a/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx +++ b/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx @@ -1,36 +1,34 @@ -/*REXX program sorts a stemmed array using the comb-sort algorithm. */ -call gen@; w=length(#) /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call combSort # /*invoke the comb sort. */ -call show@ ' after sort' /*show the after array elements.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────COMBSORT subroutine─────────────────*/ -combSort: procedure expose @.; parse arg N /*N: is number of elements.*/ -s=N-1 /*S: is the spread between COMBs.*/ - do until s<=1 & done; done=1 /*assume sort is done (so far). */ - s=trunc(s*.8) /* ÷ is slow, * is better.*/ +/*REXX program sorts a stemmed array using the comb sort algorithm. */ +call gen; w=length(#) /*generate the @ array elements. */ +call show 'before sort' /*display the before array elements. */ +say copies('▒',60) /*display a separator line (a fence). */ +call combSort # /*invoke the comb sort. */ +call show ' after sort' /*display the after array elements. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────COMBSORT subroutine───────────────────────*/ +combSort: procedure expose @.; parse arg N /*N: is number of @ elements. */ +s=N-1 /*S: is the spread between COMBs.*/ + do until s<=1 & done; done=1 /*assume sort is done (so far). */ + s=trunc(s*.8) /* ÷ is slow, * is better.*/ do j=1 until js>=N; js=j+s if @.j>@.js then do; _=@.j; @.j=@.js; @.js=_; done=0; end end /*j*/ end /*until*/ return -/*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @. = ; @.12 = 'dodecagon 12' - @.1 = '----polygon--- sides' ; @.13 = 'tridecagon 13' - @.2 = '============== =======' ; @.14 = 'tetradecagon 14' - @.3 = 'triangle 3' ; @.15 = 'pentadecagon 15' - @.4 = 'quadrilateral 4' ; @.16 = 'hexadecagon 16' - @.5 = 'pentagon 5' ; @.17 = 'heptadecagon 17' - @.6 = 'hexagon 6' ; @.18 = 'octadecagon 18' - @.7 = 'heptagon 7' ; @.19 = 'enneadecagon 19' - @.8 = 'octagon 8' ; @.20 = 'icosagon 20' - @.9 = 'nonagon 9' ; @.21 = 'hectogon 100' - @.10 = 'decagon 10' ; @.22 = 'chiliagon 1000' - @.11 = 'hendecagon 11' ; @.23 = 'myriagon 10000' - do #=1 while @.#\==''; end; #=#-1 /*find how many entries in array.*/ -return -/*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: say copies('▒',60); do j=1 for # /*display array elements.*/ - say ' element' right(j,w) arg(1)":" @.j - end /*j*/ +/*──────────────────────────────────GEN subroutine────────────────────────────*/ +gen: @. = ; @.12 = 'dodecagon 12' + @.1 = '----polygon--- sides' ; @.13 = 'tridecagon 13' + @.2 = '============== =======' ; @.14 = 'tetradecagon 14' + @.3 = 'triangle 3' ; @.15 = 'pentadecagon 15' + @.4 = 'quadrilateral 4' ; @.16 = 'hexadecagon 16' + @.5 = 'pentagon 5' ; @.17 = 'heptadecagon 17' + @.6 = 'hexagon 6' ; @.18 = 'octadecagon 18' + @.7 = 'heptagon 7' ; @.19 = 'enneadecagon 19' + @.8 = 'octagon 8' ; @.20 = 'icosagon 20' + @.9 = 'nonagon 9' ; @.21 = 'hectogon 100' + @.10 = 'decagon 10' ; @.22 = 'chiliagon 1000' + @.11 = 'hendecagon 11' ; @.23 = 'myriagon 10000' + do #=1 while @.#\==''; end; #=#-1 /*determine how many entries in @ array*/ return +/*──────────────────────────────────SHOW subroutine───────────────────────────*/ +show: do j=1 for #; say ' element' right(j,w) arg(1)":" @.j; end; return diff --git a/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-1.e b/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-1.e index 1295132c97..46114a80f3 100644 --- a/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-1.e +++ b/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-1.e @@ -1,34 +1,69 @@ class COUNTING_SORT + feature -sort(ar: ARRAY[INTEGER]; min, max: INTEGER): ARRAY[INTEGER] - local - count: ARRAY[INTEGER] - i, j, z: INTEGER - do - create count.make_filled (0, 0, max-min) - from - i:= 0 - until - i= ar.count - loop - count[ar[i]-min]:= count[ar[i]-min]+1 - i:= i+1 + + sort (ar: ARRAY [INTEGER]; min, max: INTEGER): ARRAY [INTEGER] + -- Sorted Array in ascending order. + require + ar_not_void: ar /= Void + lowest_index_zero: ar.lower = 0 + local + count: ARRAY [INTEGER] + i, j, z: INTEGER + do + create Result.make_empty + Result.deep_copy (ar) + create count.make_filled (0, 0, max - min) + from + i := 0 + until + i = Result.count + loop + count [Result [i] - min] := count [Result [i] - min] + 1 + i := i + 1 + end + z := 0 + from + i := min + until + i > max + loop + from + j := 0 + until + j = count [i - min] + loop + Result [z] := i + z := z + 1 + j := j + 1 + end + i := i + 1 + end + ensure + Result_is_sorted: is_sorted (Result) end - across count as c loop io.put_string (c.item.out + "%T") end - z:= 0 - from i:= min - until i>max - loop - from j:= 0 - until j= count[i-min] + +feature {NONE} + + is_sorted (ar: ARRAY [INTEGER]): BOOLEAN + --- Is 'ar' sorted in ascending order? + require + ar_not_empty: ar.is_empty = False + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i = ar.upper loop - ar[z]:=i - z:= z+1 - j:= j+1 + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 end - i:= i+1 end - Result:= ar - end + end diff --git a/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-2.e b/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-2.e index 68ca47029c..e65b39c1d7 100644 --- a/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-2.e +++ b/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-2.e @@ -1,24 +1,39 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - do - create test.make_filled(0,0,5) - test[0]:=-7 - test[1]:=4 - test[2]:=2 - test[3]:=6 - test[4]:=1 - test[5]:=3 - across test as t loop io.put_string (t.item.out + "%T") end - create count - test:=count.sort (test, -7, 6) - across test as ar loop io.put_string (ar.item.out+"%T") end - end + do + create test.make_filled (0, 0, 5) + test [0] := -7 + test [1] := 4 + test [2] := 2 + test [3] := 6 + test [4] := 1 + test [5] := 3 + io.put_string ("unsorted:%N") + across + test as t + loop + io.put_string (t.item.out + "%T") + end + io.new_line + io.put_string ("sorted:%N") + create count + test := count.sort (test, -7, 6) + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + end + count: COUNTING_SORT - test: ARRAY[INTEGER] + + test: ARRAY [INTEGER] + end diff --git a/Task/Sorting-algorithms-Counting-sort/Elixir/sorting-algorithms-counting-sort.elixir b/Task/Sorting-algorithms-Counting-sort/Elixir/sorting-algorithms-counting-sort.elixir new file mode 100644 index 0000000000..8d98e5f580 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Elixir/sorting-algorithms-counting-sort.elixir @@ -0,0 +1,24 @@ +defmodule Sort do + def counting_sort([]), do: [] + def counting_sort(list) do + {min, max} = minmax(list) + count = List.to_tuple(for _ <- min..max, do: 0) + counted = Enum.reduce(list, count, fn x,acc -> + i = x - min + put_elem(acc, i, elem(acc, i) + 1) + end) + Enum.reduce(max..min, [], fn n,acc -> + m = elem(counted, n - min) + List.duplicate(n, m) ++ acc + end) + end + + defp minmax([h|t]), do: minmax(t, h, h) + + defp minmax([], min, max), do: {min, max} + defp minmax([h|t], min, max) when h COMPARABLE] feature - sort(ar: ARRAY[INTEGER]): ARRAY[INTEGER] - -- sort array ar with gnome sort - require - array_not_void: ar/= VOID - local - i,j, ith: INTEGER - do - from - i:= 2 - j:= 3 - until - i>ar.count - loop - if ar[i-1] <= ar[i] then - i:= j - j:= j+1 - else - ith := ar[i-1] - ar[i-1] := ar[i] - ar[i] := ith - i:= i-1 - if i=1 then - i:=j - j:= j+1 + + sort (ar: ARRAY [G]): ARRAY [G] + -- Sorted array in ascending order. + require + array_not_void: ar /= Void + local + i, j: INTEGER + ith: G + do + create Result.make_empty + Result.deep_copy (ar) + from + i := 2 + j := 3 + until + i > Result.count + loop + if Result [i - 1] <= Result [i] then + i := j + j := j + 1 + else + ith := Result [i - 1] + Result [i - 1] := Result [i] + Result [i] := ith + i := i - 1 + if i = 1 then + i := j + j := j + 1 + end end end - end - Result := ar ensure - same_length: ar.count = Result.count - same_items: Result.same_items (ar) - end + Same_length: ar.count = Result.count + Result_is_sorted: is_sorted (Result) + end + +feature {NONE} + + is_sorted (ar: ARRAY [G]): BOOLEAN + --- Is 'ar' sorted in ascending order? + require + ar_not_empty: ar.is_empty = False + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i = ar.upper + loop + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 + end + end end diff --git a/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e index ccae0061d0..bdb8fd203f 100644 --- a/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e +++ b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e @@ -1,21 +1,33 @@ class APPLICATION -inherit - ARGUMENTS - create - make + make feature - make - do - test:= <<7, 99, -7, 1, 0, 25, -10>> - create gnome - test:= gnome.sort (test) - across test as ar loop io.put_string( ar.item.out + "%T") end - end - test: ARRAY[INTEGER] - gnome: GNOME_SORT[INTEGER] + make + do + test := <<7, 99, -7, 1, 0, 25, -10>> + io.put_string ("unsorted:%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + io.new_line + io.put_string ("sorted:%N") + create gnome + test := gnome.sort (test) + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + end + + test: ARRAY [INTEGER] + + gnome: GNOME_SORT [INTEGER] + end diff --git a/Task/Sorting-algorithms-Gnome-sort/Elixir/sorting-algorithms-gnome-sort.elixir b/Task/Sorting-algorithms-Gnome-sort/Elixir/sorting-algorithms-gnome-sort.elixir new file mode 100644 index 0000000000..f1ae80df7c --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Elixir/sorting-algorithms-gnome-sort.elixir @@ -0,0 +1,10 @@ +defmodule Sort do + def gnome_sort(list) when length(list) <= 1, do: list + def gnome_sort([h|t]), do: gnome_sort([h], t) + + defp gnome_sort(list, []), do: list + defp gnome_sort([prev|p], [next|n]) when next > prev, do: gnome_sort(p, [next|[prev|n]]) + defp gnome_sort(p, [next|n]), do: gnome_sort([next|p], n) +end + +IO.inspect Sort.gnome_sort([8,3,9,1,3,2,6]) diff --git a/Task/Sorting-algorithms-Gnome-sort/Julia/sorting-algorithms-gnome-sort.julia b/Task/Sorting-algorithms-Gnome-sort/Julia/sorting-algorithms-gnome-sort.julia new file mode 100644 index 0000000000..6452a6b0cf --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Julia/sorting-algorithms-gnome-sort.julia @@ -0,0 +1,22 @@ +function gnomesort(A::AbstractVector) + i = 1 + j = 2 + while i < length(A) + if A[i] <= A[i + 1] + i = j + j += 1 + else + A[i], A[i + 1] = A[i + 1], A[i] + i -= 1 + if i == 0 + i = j + j += 1 + end + end + end + A +end + +A = randcycle(20) +println("unsorted: ", A) +println("sorted: ", gnomesort(A)) diff --git a/Task/Sorting-algorithms-Gnome-sort/PL-I/sorting-algorithms-gnome-sort.pli b/Task/Sorting-algorithms-Gnome-sort/PL-I/sorting-algorithms-gnome-sort.pli new file mode 100644 index 0000000000..66aab709be --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/PL-I/sorting-algorithms-gnome-sort.pli @@ -0,0 +1,28 @@ +SORT: PROCEDURE OPTIONS (MAIN); + DECLARE A(0:9) FIXED STATIC INITIAL (5, 2, 7, 1, 9, 8, 6, 3, 4, 0); + + CALL GNOME_SORT (A); + put skip edit (A) (f(7)); + +GNOME_SORT: PROCEDURE (A) OPTIONS (REORDER); /* 9 September 2015 */ + declare A(*) fixed; + declare t fixed; + declare (i, j) fixed; + + i = 1; j = 2; + do while (i <= hbound(A)); + if a(i-1) <= a(i) then + do; + i = j; j = j + 1; + end; + else + do; + t = a(i-1); a(i-1) = a(i); a(i) = t; + i = i - 1; + if i = 0 then do; i = j; j = j + 1; end; + end; + end; + +END GNOME_SORT; + +END SORT; diff --git a/Task/Sorting-algorithms-Gnome-sort/PowerShell/sorting-algorithms-gnome-sort.psh b/Task/Sorting-algorithms-Gnome-sort/PowerShell/sorting-algorithms-gnome-sort.psh new file mode 100644 index 0000000000..590eb7ff12 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/PowerShell/sorting-algorithms-gnome-sort.psh @@ -0,0 +1,20 @@ +function gnomesort($a) { + $size, $i, $j = $a.Count, 1, 2 + while($i -lt $size) { + if ($a[$i-1] -le $a[$i]) { + $i = $j + $j++ + } + else { + $a[$i-1], $a[$i] = $a[$i], $a[$i-1] + $i-- + if($i -eq 0) { + $i = $j + $j++ + } + } + } + $a +} +$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11) +"$(gnomesort $array)" diff --git a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx index f14311d2f5..fb5e89fe88 100644 --- a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx +++ b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx @@ -1,31 +1,25 @@ -/*REXX program sorts a stemmed array using the gnome-sort algorithm.*/ -call gen@ /*generate the @. array elements.*/ -call show@ 'before sort' /*show "before" array elements.*/ -call gnomeSort # /*invoke the infamous gnome sort.*/ -call show@ ' after sort' /*show "after" array elements.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────GNOMESORT subroutine────────────────*/ -gnomeSort: procedure expose @.; parse arg n; k=2 /*n=num items.*/ - do j=3 while k<=n; km=k-1 /*KM=prev item*/ - if @.km<<=@.k then do; k=j; iterate; end /*OK so far···*/ - _=@.km; @.km=@.k; @.k=_ /*swap 2 entries in the @. array.*/ - k=k-1; if k==1 then k=j; else j=j-1 /*test index 1*/ - end /*j*/ /* [↑] perform gnome sort on @.*/ +/*REXX program sorts a stemmed array using the gnome sort algorithm. */ +call gen; w=length(#) /*generate @ array; W is width of #.*/ +call show 'before sort' /*display the "before" array elements.*/ +say copies('▒',60) /*show a separator line between sorts. */ +call gnomeSort # /*invoke the well─known gnome sort. */ +call show ' after sort' /*display the "after" array elements.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────GNOMESORT subroutine──────────────────────*/ +gnomeSort: procedure expose @.; parse arg n; k=2 /*N: is number items.*/ + do j=3 while k<=n; p=k-1 /*P: is previous item*/ + if @.p<<=@.k then do; k=j; iterate; end /*array is OK so far.*/ + _=@.p; @.p=@.k; @.k=_ /*swap two @ entries.*/ + k=k-1; if k==1 then k=j; else j=j-1 /*test for 1st index.*/ + end /*j*/ return -/*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: !=... 'deadbeef'x ...; @.=! /*default none-value; allows null*/ -@.1 = '---the seven virtues---' /* [↓] indent the seven virtues.*/ -@.2 = '=======================' ; @.6 = 'Fortitude' -@.3 = 'Faith' ; @.7 = 'Justice' -@.4 = 'Hope' ; @.8 = 'Prudence' -@.5 = 'Charity [Love]' ; @.9 = 'Temperance' - - do #=1 while @.#\==!; end /*find the # of items in @ array.*/ -#=#-1 /*adjust the numer of items by 1.*/ -return -/*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: do j=1 for # /* [↓] display all items for @. */ - say ' element' right(j,length(#)) arg(1)":" @.j - end /*j*/ /* [↑] right justify the J num.*/ -say copies('■',60) /*show a separator line that fits*/ +/*──────────────────────────────────GEN subroutine────────────────────────────*/ +gen: @.=; @.1 = '---the seven virtues---' ; @.5 = 'Charity [Love]' + @.2 = '=======================' ; @.6 = 'Fortitude' + @.3 = 'Faith' ; @.7 = 'Justice' + @.4 = 'Hope' ; @.8 = 'Prudence' + @.9 = 'Temperance' + do #=1 while @.#\==''; end; #=#-1 /*determine number of items in @ array.*/ return +/*──────────────────────────────────SHOW subroutine───────────────────────────*/ +show: do j=1 for #; say ' element' right(j,w) arg(1)":" @.j; end; return diff --git a/Task/Sorting-algorithms-Heapsort/ALGOL-68/sorting-algorithms-heapsort.alg b/Task/Sorting-algorithms-Heapsort/ALGOL-68/sorting-algorithms-heapsort.alg new file mode 100644 index 0000000000..f610e50358 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/ALGOL-68/sorting-algorithms-heapsort.alg @@ -0,0 +1,52 @@ +#--- Swap function ---# +PROC swap = (REF []INT array, INT first, INT second) VOID: +( + INT temp := array[first]; + array[first] := array[second]; + array[second]:= temp +); + +#--- Heap sort Move Down ---# +PROC heapmove = (REF []INT array, INT i, INT last) VOID: +( + INT index := i; + INT larger := (index*2); + + WHILE larger <= last DO + IF larger < last THEN IF array[larger] < array[larger+1] THEN + larger +:= 1 + FI FI; + IF array[index] < array[larger] THEN + swap(array, index, larger) + FI; + index := larger; + larger := (index*2) + OD +); + +#--- Heap sort ---# +PROC heapsort = (REF []INT array) VOID: +( + FOR i FROM ENTIER((UPB array) / 2) BY -1 WHILE + heapmove(array, i, UPB array); + i > 1 DO SKIP OD; + + FOR i FROM UPB array BY -1 WHILE + swap(array, 1, i); + heapmove(array, 1, i-1); + i > 1 DO SKIP OD +); +#***************************************************************# +main: +( + [10]INT a; + FOR i FROM 1 TO UPB a DO + a[i] := ROUND(random*100) + OD; + + print(("Before:", a)); + print((newline, newline)); + heapsort(a); + print(("After: ", a)) + +) diff --git a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-1.cpp b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-1.cpp index d9cde9cd98..5fb4a92699 100644 --- a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-1.cpp +++ b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-1.cpp @@ -1,21 +1,16 @@ +#include +#include #include -#include // for std::make_heap, std::sort_heap -template -void heapsort(Iterator begin, Iterator end) -{ - std::make_heap(begin, end); - std::sort_heap(begin, end); +template +void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) { + std::make_heap(begin, end); + std::sort_heap(begin, end); } -int main() -{ - double valsToSort[] = { - 1.4, 50.2, 5.11, -1.55, 301.521, 0.3301, 40.17, - -18.0, 88.1, 30.44, -37.2, 3012.0, 49.2}; - const int VSIZE = sizeof(valsToSort)/sizeof(*valsToSort); - - heapsort(valsToSort, valsToSort+VSIZE); - for (int ix=0; ix(std::cout, " ")); + std::cout << "\n"; } diff --git a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-2.cpp b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-2.cpp index 052df60528..eb68d3f4db 100644 --- a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-2.cpp +++ b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort-2.cpp @@ -1,10 +1,47 @@ #include -#include // for std::make_heap, std::pop_heap - -template -void heapsort(Iterator begin, Iterator end) -{ - std::make_heap(begin, end); - while (begin != end) - std::pop_heap(begin, end--); +#include + +using namespace std; + +void shift_down(vector& heap,int i, int max) { + int i_big, c1, c2; + while(i < max) { + i_big = i; + c1 = (2*i) + 1; + c2 = c1 + 1; + if( c1heap[i_big] ) + i_big = c1; + if( c2heap[i_big] ) + i_big = c2; + if(i_big == i) return; + swap(heap[i],heap[i_big]); + i = i_big; + } +} + +void to_heap(vector& arr) { + int i = (arr.size()/2) - 1; + while(i >= 0) { + shift_down(arr, i, arr.size()); + --i; + } +} + +void heap_sort(vector& arr) { + to_heap(arr); + int end = arr.size() - 1; + while (end > 0) { + swap(arr[0], arr[end]); + shift_down(arr, 0, end); + --end; + } +} + +int main() { + vector data = { + 12, 11, 15, 10, 9, 1, 2, + 3, 13, 14, 4, 5, 6, 7, 8 + }; + heap_sort(data); + for(int i : data) cout << i << " "; } diff --git a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort.cpp b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort.cpp deleted file mode 100644 index 5fb4a92699..0000000000 --- a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include -#include -#include - -template -void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) { - std::make_heap(begin, end); - std::sort_heap(begin, end); -} - -int main() { - int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; - heap_sort(std::begin(a), std::end(a)); - copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); - std::cout << "\n"; -} diff --git a/Task/Sorting-algorithms-Heapsort/Eiffel/sorting-algorithms-heapsort-1.e b/Task/Sorting-algorithms-Heapsort/Eiffel/sorting-algorithms-heapsort-1.e new file mode 100644 index 0000000000..b5cff34166 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Eiffel/sorting-algorithms-heapsort-1.e @@ -0,0 +1,81 @@ +class + HEAPSORT + +feature + + sort_array (ar: ARRAY [INTEGER]) + -- Sorts array 'ar' in ascending order. + require + not_empty: ar.count > 0 + local + i, j, r, l, m, n: INTEGER + sorted: BOOLEAN + do + n := ar.count + j := 0 + i := 0 + m := 0 + r := n + l := (n // 2)+1 + from + until + sorted + loop + if l > 1 then + l := l - 1 + m := ar[l] + else + m := ar[r] + ar[r] := ar[1] + r := r - 1 + if r = 1 then + ar[1]:=m + sorted := True + end + end + if not sorted then + i := l + j := l * 2 + from + until + j > r + loop + if (j < r) and (ar[j] < ar[j + 1]) then + j := j + 1 + end + if m < ar[j] then + ar[i]:= ar[j] + i := j + j := j + i + else + j := r + 1 + end + end + ar[i]:= m + end + end + ensure + sorted: is_sorted(ar) + end + +feature{NONE} + + is_sorted (ar: ARRAY [INTEGER]): BOOLEAN + --- Is 'ar' sorted in ascending order? + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i >= ar.upper + loop + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 + end + end + +end diff --git a/Task/Sorting-algorithms-Heapsort/Eiffel/sorting-algorithms-heapsort-2.e b/Task/Sorting-algorithms-Heapsort/Eiffel/sorting-algorithms-heapsort-2.e new file mode 100644 index 0000000000..d848c4de72 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Eiffel/sorting-algorithms-heapsort-2.e @@ -0,0 +1,34 @@ +class + APPLICATION + +create + make + +feature + + make + local + test: ARRAY [INTEGER] + do + create test.make_empty + test := <<5, 91, 13, 99,7, 35>> + io.put_string ("Unsorted: ") + across + test as t + loop + io.put_string (t.item.out + " ") + end + io.new_line + create heap_sort + heap_sort.sort_array (test) + io.put_string ("Sorted: ") + across + test as t + loop + io.put_string (t.item.out + " ") + end + end + + heap_sort: HEAPSORT + +end diff --git a/Task/Sorting-algorithms-Heapsort/PowerShell/sorting-algorithms-heapsort.psh b/Task/Sorting-algorithms-Heapsort/PowerShell/sorting-algorithms-heapsort.psh new file mode 100644 index 0000000000..2128561424 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/PowerShell/sorting-algorithms-heapsort.psh @@ -0,0 +1,35 @@ +function heapsort($a, $count) { + $a = heapify $a $count + $end = $count - 1 + while( $end -gt 0) { + $a[$end], $a[0] = $a[0], $a[$end] + $end-- + $a = siftDown $a 0 $end + } + $a +} +function heapify($a, $count) { + $start = [Math]::Floor(($count - 2) / 2) + while($start -ge 0) { + $a = siftDown $a $start ($count-1) + $start-- + } + $a +} +function siftdown($a, $start, $end) { + $b, $root = $true, $start + while(( ($root * 2 + 1) -le $end) -and $b) { + $child = $root * 2 + 1 + if( ($child + 1 -le $end) -and ($a[$child] -lt $a[$child + 1]) ) { + $child++ + } + if($a[$root] -lt $a[$child]) { + $a[$root], $a[$child] = $a[$child], $a[$root] + $root = $child + } + else { $b = $false} + } + $a +} +$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11) +"$(heapsort $array $array.Count)" diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx index 61b7048ae9..1a2c1b509a 100644 --- a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx +++ b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx @@ -1,42 +1,29 @@ -/*REXX program sorts an array using the heapsort algorithm. */ -call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements*/ -call heapSort # /*invoke the heap sort. */ -call show@ ' after sort' /*show the after array elements*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────HEAPSORT subroutine─────────────────*/ +/*REXX pgm sorts an array (modern Greek alphabet) using a heapsort algorithm. */ +@.=; @.1='alpha' ; @.6 ='zeta' ; @.11='lambda' ; @.16='pi' ; @.21='phi' + @.2='beta' ; @.7 ='eta' ; @.12='mu' ; @.17='rho' ; @.22='chi' + @.3='gamma' ; @.8 ='theta'; @.13='nu' ; @.18='sigma' ; @.23='psi' + @.4='delta' ; @.9 ='iota' ; @.14='xi' ; @.19='tau' ; @.24='omega' + @.5='epsilon'; @.10='kappa'; @.15='omicron'; @.20='upsilon' + do #=1 while @.#\==''; end; #=#-1 /*find # entries*/ +call show "before sort:" +call heapSort #; say copies('▒',40) /*sort; show sep*/ +call show " after sort:" +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ heapSort: procedure expose @.; parse arg n; do j=n%2 by -1 to 1 call shuffle j,n end /*j*/ - do n=n by -1 to 2 - _=@.1; @.1=@.n; @.n=_; call shuffle 1,n-1 /*swap and shuffle.*/ - end /*n*/ -return -/*──────────────────────────────────SHUFFLE subroutine──────────────────*/ -shuffle: procedure expose @.; parse arg i,n; _=@.i - do while i+i<=n; j=i+i; k=j+1 - if k<=n then if @.k>@.j then j=k - if _>=@.j then leave - @.i=@.j; i=j - end /*while*/ -@.i=_ -return -/*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.=; @.1='---modern Greek alphabet letters---' /*default; title.*/ - @.2= copies('=', length(@.1)) /*match sep with ↑*/ -@.3='alpha' ; @.9 ='eta' ; @.15='nu' ; @.21='tau' -@.4='beta' ; @.10='theta' ; @.16='xi' ; @.22='upsilon' -@.5='gamma' ; @.11='iota' ; @.17='omicron' ; @.23='phi' -@.6='delta' ; @.12='kappa' ; @.18='pi' ; @.24='chi' -@.7='epsilon' ; @.13='lambd' ; @.19='rho' ; @.25='psi' -@.8='zeta' ; @.14='mu' ; @.20='sigma' ; @.26='omega' - - do #=1 while @.#\==''; end /*find how many entries in list. */ -#=#-1 /*adjust highItem slightly. */ -return -/*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: do j=1 for # /* [↓] display elements in array.*/ - say ' element' right(j,length(#)) arg(1)':' @.j - end /*j*/ -say copies('■', 70) /*show a separator line. */ + do n=n by -1 to 2 + _=@.1; @.1=@.n; @.n=_; call shuffle 1,n-1 /*swap and shuffle.*/ + end /*n*/ return +/*────────────────────────────────────────────────────────────────────────────*/ +shuffle: procedure expose @.; parse arg i,n; $=@.i /*obtain the parent*/ + do while i+i<=n; j=i+i; k=j+1 + if k<=n then if @.k>@.j then j=k + if $>=@.j then leave + @.i=@.j; i=j + end /*while*/ +@.i=$; return +/*────────────────────────────────────────────────────────────────────────────*/ +show: do e=1 for #; say ' element' right(e,length(#)) arg(1) @.e; end; return diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx index 0c318e4d70..ef69424436 100644 --- a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx +++ b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-2.rexx @@ -1,72 +1,26 @@ -/* REXX *************************************************************** -* Translated from PL/I -* 27.07.2013 Walter Pachl -**********************************************************************/ - list='---letters of the modern Greek Alphabet---|'||, - '==========================================|'||, - 'alpha|beta|gamma|delta|epsilon|zeta|eta|theta|'||, - 'iota|kappa|lambda|mu|nu|xi|omicron|pi|'||, - 'rho|sigma|tau|upsilon|phi|chi|psi|omega' - Do i=0 By 1 While list<>'' - Parse Var list a.i '|' list - End - n=i-1 - - Call showa 'before sort' - Call heapsort n - Call showa ' after sort' - Exit - - heapSort: Procedure Expose a. - Parse Arg count - Call heapify count - end=count-1 - do while end>0 - Call swap end,0 - end=end-1 - Call siftDown 0,end - End - Return - - heapify: Procedure Expose a. - Parse Arg count - start=(count-2)%2 - Do while start>=0 - Call siftDown start,count-1 - start=start-1 - End - Return - - siftDown: Procedure Expose a. - Parse Arg start,end - root=start - Do while root*2+1<= end - child=root*2+1 - sw=root - if a.swroot Then Do - Call swap root,sw - root=sw - End - else - return - End - Return - - swap: Procedure Expose a. - Parse arg x,y - temp=a.x - a.x=a.y - a.y=temp - Return - - showa: Procedure Expose a. n - Parse Arg txt - Do j=0 To n-1 - Say 'element' format(j,2) txt a.j - End - Return +/*REXX pgm sorts an array (modern Greek alphabet) using a heapsort algorithm. */ +g = 'alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi', + "omicron pi rho sigma tau upsilon phi chi psi omega" /*adjust # [↓] */ + do #=1 for words(g); @.#=word(g,#); end; #=#-1 +call show "before sort:" +call heapSort #; say copies('▒',40) /*sort; show sep*/ +call show " after sort:" +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +heapSort: procedure expose @.; parse arg n; do j=n%2 by -1 to 1 + call shuffle j,n + end /*j*/ + do n=n by -1 to 2 + _=@.1; @.1=@.n; @.n=_; call shuffle 1,n-1 /*swap and shuffle.*/ + end /*n*/ +return +/*────────────────────────────────────────────────────────────────────────────*/ +shuffle: procedure expose @.; parse arg i,n; $=@.i /*obtain the parent*/ + do while i+i<=n; j=i+i; k=j+1 + if k<=n then if @.k>@.j then j=k + if $>=@.j then leave + @.i=@.j; i=j + end /*while*/ +@.i=$; return +/*────────────────────────────────────────────────────────────────────────────*/ +show: do e=1 for #; say ' element' right(e,length(#)) arg(1) @.e; end; return diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-3.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-3.rexx new file mode 100644 index 0000000000..0c318e4d70 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-3.rexx @@ -0,0 +1,72 @@ +/* REXX *************************************************************** +* Translated from PL/I +* 27.07.2013 Walter Pachl +**********************************************************************/ + list='---letters of the modern Greek Alphabet---|'||, + '==========================================|'||, + 'alpha|beta|gamma|delta|epsilon|zeta|eta|theta|'||, + 'iota|kappa|lambda|mu|nu|xi|omicron|pi|'||, + 'rho|sigma|tau|upsilon|phi|chi|psi|omega' + Do i=0 By 1 While list<>'' + Parse Var list a.i '|' list + End + n=i-1 + + Call showa 'before sort' + Call heapsort n + Call showa ' after sort' + Exit + + heapSort: Procedure Expose a. + Parse Arg count + Call heapify count + end=count-1 + do while end>0 + Call swap end,0 + end=end-1 + Call siftDown 0,end + End + Return + + heapify: Procedure Expose a. + Parse Arg count + start=(count-2)%2 + Do while start>=0 + Call siftDown start,count-1 + start=start-1 + End + Return + + siftDown: Procedure Expose a. + Parse Arg start,end + root=start + Do while root*2+1<= end + child=root*2+1 + sw=root + if a.swroot Then Do + Call swap root,sw + root=sw + End + else + return + End + Return + + swap: Procedure Expose a. + Parse arg x,y + temp=a.x + a.x=a.y + a.y=temp + Return + + showa: Procedure Expose a. n + Parse Arg txt + Do j=0 To n-1 + Say 'element' format(j,2) txt a.j + End + Return diff --git a/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-1.cmake b/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-1.cmake index 93f515492b..5b754ead7a 100644 --- a/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-1.cmake +++ b/Task/Sorting-algorithms-Insertion-sort/CMake/sorting-algorithms-insertion-sort-1.cmake @@ -1,7 +1,7 @@ # insertion_sort(var [value1 value2...]) sorts a list of integers. function(insertion_sort var) math(EXPR last "${ARGC} - 1") # Sort ARGV[1..last]. - foreach(i RANGE 2 ${last}) + foreach(i RANGE 1 ${last}) # Extend the sorted area to ARGV[1..i]. set(b ${i}) set(v ${ARGV${b}}) diff --git a/Task/Sorting-algorithms-Insertion-sort/Elixir/sorting-algorithms-insertion-sort.elixir b/Task/Sorting-algorithms-Insertion-sort/Elixir/sorting-algorithms-insertion-sort.elixir new file mode 100644 index 0000000000..7382de37b7 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Elixir/sorting-algorithms-insertion-sort.elixir @@ -0,0 +1,10 @@ +defmodule Sort do + def insert_sort(list) when is_list(list), do: insert_sort(list, []) + + def insert_sort([], sorted), do: sorted + def insert_sort([h | t], sorted), do: insert_sort(t, insert(h, sorted)) + + defp insert(x, []), do: [x] + defp insert(x, sorted) when x < hd(sorted), do: [x | sorted] + defp insert(x, [h | t]), do: [h | insert(x, t)] +end diff --git a/Task/Sorting-algorithms-Insertion-sort/OCaml/sorting-algorithms-insertion-sort.ocaml b/Task/Sorting-algorithms-Insertion-sort/OCaml/sorting-algorithms-insertion-sort.ocaml index 1a17698bc3..57f5ce972a 100644 --- a/Task/Sorting-algorithms-Insertion-sort/OCaml/sorting-algorithms-insertion-sort.ocaml +++ b/Task/Sorting-algorithms-Insertion-sort/OCaml/sorting-algorithms-insertion-sort.ocaml @@ -1,9 +1,10 @@ -let rec insert x = function - [] -> [x] -| y :: ys -> - if x <= y then x :: y :: ys - else y :: insert x ys +let rec insert lst x = + match lst with + [] -> [x] + | y :: ys when x <= y -> x :: y :: ys + | y :: ys -> y :: insert ys x + ;; -let insertion_sort lst = List.fold_right insert lst [];; +let insertion_sort = List.fold_left insert [];; insertion_sort [6;8;5;9;3;2;1;4;7];; diff --git a/Task/Sorting-algorithms-Insertion-sort/PowerShell/sorting-algorithms-insertion-sort.psh b/Task/Sorting-algorithms-Insertion-sort/PowerShell/sorting-algorithms-insertion-sort.psh new file mode 100644 index 0000000000..a67a0cb3e1 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/PowerShell/sorting-algorithms-insertion-sort.psh @@ -0,0 +1,15 @@ +function insertionSort($arr){ + for($i=0;$i -lt $arr.length;$i++){ + $val = $arr[$i] + $j = $i-1 + while($j -ge 0 -and $arr[$j] -gt $val){ + $arr[$j+1] = $arr[$j] + $j-- + } + $arr[$j+1] = $val + } +} + +$arr = @(4,2,1,6,9,3,8,7) +insertionSort($arr) +$arr -join "," diff --git a/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx b/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx index 75bfc38f19..7b0a13986d 100644 --- a/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx +++ b/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx @@ -1,38 +1,30 @@ -/*REXX program sorts a stemmed array using the insertion-sort algoritm.*/ -call gen@ /*generate the array's elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call insertionSort # /*invoke the insertion sort. */ -call show@ ' after sort' /*show the after array elements.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @. = /*assign default value to array. */ - @.1 = "---Monday's Child Is Fair of Face (by Mother Goose)---" - @.2 = "Monday's child is fair of face;" - @.3 = "Tuesday's child is full of grace;" - @.4 = "Wednesday's child is full of woe;" - @.5 = "Thursday's child has far to go;" - @.6 = "Friday's child is loving and giving;" - @.7 = "Saturday's child works hard for a living;" - @.8 = "But the child that is born on the Sabbath day" - @.9 = "Is blithe and bonny, good and gay." - - do #=1 while @.#\=='' /*find how many entries in array.*/ - end /*#*/ /*short and sweet DO loop, eh? */ -#=#-1 /*because of DO, adjust # entries*/ +/*REXX program sorts a stemmed array using the insertion sort algorithm. */ +call gen /*generate the array's elements. */ +call show 'before sort' /*display the before array elements. */ +say copies('▒',79) /*display a separator line (a fence). */ +call insertionSort # /*invoke the insertion sort. */ +call show ' after sort' /*display the after array elements. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────GEN subroutine────────────────────────────*/ +gen: @.=; @.1 = "---Monday's Child Is Fair of Face (by Mother Goose)---" + @.2 = "Monday's child is fair of face;" + @.3 = "Tuesday's child is full of grace;" + @.4 = "Wednesday's child is full of woe;" + @.5 = "Thursday's child has far to go;" + @.6 = "Friday's child is loving and giving;" + @.7 = "Saturday's child works hard for a living;" + @.8 = "But the child that is born on the Sabbath day" + @.9 = "Is blithe and bonny, good and gay." + do #=1 while @.#\==''; end; #=#-1 /*determine how many entries in @ array*/ return -/*──────────────────────────────────INSERTIONSORT subroutine────────────*/ -insertionSort: procedure expose @. # - do i=2 to # - value=@.i; do j=i-1 by -1 while j\==0 & @.j>value - jp=j+1; @.jp=@.j - end /*j*/ - jp=j+1 - @.jp=value - end /*i*/ -return -/*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: do j=1 for # - say 'element' right(j,length(#)) arg(1)': ' @.j - end /*j*/ -say copies('─',79) /*show a separator line that fits*/ +/*──────────────────────────────────INSERTIONSORT subroutine──────────────────*/ +insertionSort: procedure expose @.; parse arg # + do i=2 to #; $=@.i + do j=i-1 by -1 while j\==0 & @.j>$ + _=j+1; @._=@.j + end /*j*/ + _=j+1; @._=$ + end /*i*/ return +/*──────────────────────────────────SHOW subroutine───────────────────────────*/ +show: do j=1 for #; say 'element' right(j,length(#)) arg(1)': ' @.j; end; return diff --git a/Task/Sorting-algorithms-Insertion-sort/Rust/sorting-algorithms-insertion-sort.rust b/Task/Sorting-algorithms-Insertion-sort/Rust/sorting-algorithms-insertion-sort.rust index 66a7aa1b12..b56ad9c996 100644 --- a/Task/Sorting-algorithms-Insertion-sort/Rust/sorting-algorithms-insertion-sort.rust +++ b/Task/Sorting-algorithms-Insertion-sort/Rust/sorting-algorithms-insertion-sort.rust @@ -1,9 +1,9 @@ fn insertion_sort(arr: &mut [T]) { - for i in range(1, arr.len()) { - let mut j = i; - while (j > 0 && arr[j] < arr[j-1]) { - arr.swap(j, j-1); - j = j-1; + for i in 1..arr.len() { + let mut j = i; + while j > 0 && arr[j] < arr[j-1] { + arr.swap(j, j-1); + j = j-1; + } } - } } diff --git a/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-1.e b/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-1.e index b292c9d68f..7ed0badb98 100644 --- a/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-1.e +++ b/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-1.e @@ -1,60 +1,68 @@ class MERGE_SORT [G -> COMPARABLE] + create sort + feature - sort(ar: ARRAY[G]) - -- sort array ar with mergesort and save it in sorted_array - require - ar_not_empty: ar.is_empty= FALSE - do + + sort (ar: ARRAY [G]) + -- Sorted array in ascending order. + require + ar_not_empty: not ar.is_empty + do create sorted_array.make_empty - mergesort(ar, 1, ar.count) - sorted_array:= ar - ensure - sorted_array_not_empty: sorted_array.is_empty = FALSE - sorted: is_sorted(sorted_array, 1, sorted_array.count)= TRUE - end - sorted_array: ARRAY[G] + mergesort (ar, 1, ar.count) + sorted_array := ar + ensure + sorted_array_not_empty: not sorted_array.is_empty + sorted: is_sorted (sorted_array, 1, sorted_array.count) + end + + sorted_array: ARRAY [G] + feature {NONE} - mergesort(ar:ARRAY[G]; l,r:INTEGER) + + mergesort (ar: ARRAY [G]; l, r: INTEGER) + -- Sorting part of mergesort. local m: INTEGER do - if l=1 - positive_index_m: m>=1 - positive_index_r: r>=1 - ar_not_empty: ar.is_empty= FALSE + positive_index_l: l >= 1 + positive_index_m: m >= 1 + positive_index_r: r >= 1 + ar_not_empty: not ar.is_empty local - merged: ARRAY[G] - h,i,j,k: INTEGER + merged: ARRAY [G] + h, i, j, k: INTEGER do i := l - j := m+1 + j := m + 1 k := l - create merged.make_empty + create merged.make_filled (ar [1], 1, ar.count) from until i > m or j > r loop if ar.item (i) <= ar.item (j) then - merged.force(ar.item(i),k) - i := i +1 + merged.force (ar.item (i), k) + i := i + 1 elseif ar.item (i) > ar.item (j) then - merged.force(ar.item(j),k) - j := j+1 + merged.force (ar.item (j), k) + j := j + 1 end - k := k+1 + k := k + 1 end if i > m then from @@ -62,8 +70,8 @@ feature {NONE} until h > r loop - merged.force(ar.item(h),k+h-j) - h := h+1 + merged.force (ar.item (h), k + h - j) + h := h + 1 end elseif j > m then from @@ -71,8 +79,8 @@ feature {NONE} until h > m loop - merged.force(ar.item(h),k+h-i) - h := h+1 + merged.force (ar.item (h), k + h - i) + h := h + 1 end end from @@ -81,37 +89,32 @@ feature {NONE} h > r loop ar.item (h) := merged.item (h) - h := h+1 + h := h + 1 end - ensure - is_partially_sorted: is_sorted(ar, l,r)= TRUE + ensure + is_partially_sorted: is_sorted (ar, l, r) end - is_sorted(ar: ARRAY[G];l, r: INTEGER): BOOLEAN - --- feature is not required for mergesort but is used for contracts + is_sorted (ar: ARRAY [G]; l, r: INTEGER): BOOLEAN + -- Is 'ar' sorted in ascending order? require - ar_not_empty: ar.is_empty= FALSE + ar_not_empty: not ar.is_empty l_in_range: l >= 1 r_in_range: r <= ar.count local - smaller : BOOLEAN i: INTEGER do - smaller:= TRUE + Result := True from - i:= l + i := l until - i=r + i = r loop - if ar[i]> ar[i+1] then - smaller:= FALSE + if ar [i] > ar [i + 1] then + Result := False end - i:= i+1 - end - if smaller = TRUE then - RESULT := TRUE - else - RESULT:= FALSE + i := i + 1 end end + end diff --git a/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-2.e b/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-2.e index 8e7c456ca6..2c9cb8781f 100644 --- a/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-2.e +++ b/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-2.e @@ -1,19 +1,31 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - do - test:= <<2,5,66,-2, 0, 7>> - io.put_string ("unsorted"+ "%N") - across test as ar loop io.put_string (ar.item.out + "%T") end - io.put_string ("%N"+"sorted"+ "%N") - create merge.sort (test) - across merge.sorted_array as ar loop io.put_string (ar.item.out + "%T") end - end - test: ARRAY[INTEGER] - merge: MERGE_SORT[INTEGER] + do + test := <<2, 5, 66, -2, 0, 7>> + io.put_string ("unsorted" + "%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + io.put_string ("%N" + "sorted" + "%N") + create merge.sort (test) + across + merge.sorted_array as ar + loop + io.put_string (ar.item.out + "%T") + end + end + + test: ARRAY [INTEGER] + + merge: MERGE_SORT [INTEGER] + end diff --git a/Task/Sorting-algorithms-Merge-sort/Elixir/sorting-algorithms-merge-sort.elixir b/Task/Sorting-algorithms-Merge-sort/Elixir/sorting-algorithms-merge-sort.elixir new file mode 100644 index 0000000000..317aac02fa --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Elixir/sorting-algorithms-merge-sort.elixir @@ -0,0 +1,7 @@ +defmodule Sort do + def merge_sort(list) when length(list) <= 1, do: list + def merge_sort(list) do + {left, right} = Enum.split(list, div(length(list), 2)) + :lists.merge( merge_sort(left), merge_sort(right)) + end +end diff --git a/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js b/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js index bb828800d2..08bc244205 100644 --- a/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js +++ b/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js @@ -1,21 +1,31 @@ function merge(left, right, arr) { - var a = 0; - while (left.length && right.length) - arr[a++] = right[0] < left[0] ? right.shift() : left.shift(); - while (left.length) arr[a++] = left.shift(); - while (right.length) arr[a++] = right.shift(); + var a = 0; + + while (left.length && right.length) { + arr[a++] = (right[0] < left[0]) ? right.shift() : left.shift(); + } + while (left.length) { + arr[a++] = left.shift(); + } + while (right.length) { + arr[a++] = right.shift(); + } } + function mSort(arr, tmp, len) { - if (len == 1) return; - var m = Math.floor(len / 2), - tmp_l = tmp.slice(0, m), - tmp_r = tmp.slice(m); - mSort(tmp_l, arr.slice(0, m), m); - mSort(tmp_r, arr.slice(m), len - m); - merge(tmp_l, tmp_r, arr); + if (len === 1) { return; } + + var m = Math.floor(len / 2), + tmp_l = tmp.slice(0, m), + tmp_r = tmp.slice(m); + + mSort(tmp_l, arr.slice(0, m), m); + mSort(tmp_r, arr.slice(m), len - m); + merge(tmp_l, tmp_r, arr); } + function merge_sort(arr) { - mSort(arr, arr.slice(), arr.length); + mSort(arr, arr.slice(), arr.length); } var arr = [1, 5, 2, 7, 3, 9, 4, 6, 8]; diff --git a/Task/Sorting-algorithms-Merge-sort/Julia/sorting-algorithms-merge-sort.julia b/Task/Sorting-algorithms-Merge-sort/Julia/sorting-algorithms-merge-sort.julia new file mode 100644 index 0000000000..1fd913eae9 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Julia/sorting-algorithms-merge-sort.julia @@ -0,0 +1,42 @@ +function mergesort!(A::AbstractVector) + if length(A) <= 1 + return A + end + middle = div(length(A), 2) + left = mergesort(A[1:middle]) + right = mergesort(A[middle + 1:end]) + result = Array(eltype(left), length(left) + length(right)) + idx = 1 + @inbounds while !isempty(left) && !isempty(right) + if left[1] <= right[1] + result[idx] = left[1] + left = left[2:end] + else + result[idx] = right[1] + right = right[2:end] + end + idx += 1 + end + @inbounds while !isempty(left) + result[idx] = left[1] + left = left[2:end] + idx += 1 + end + @inbounds while !isempty(right) + result[idx] = right[1] + right = right[2:end] + idx += 1 + end + for i=1:length(A) + A[i] = result[i] + end + return A +end + +function mergesort(A::AbstractVector) + return mergesort!(copy(A)) +end + +A = randcycle(10) +println("unsorted: ", A) +println("sorted: ", mergesort(A)) diff --git a/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-2.pascal b/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-2.pascal index 221a92e049..bef43ba2c7 100644 --- a/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-2.pascal +++ b/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-2.pascal @@ -8,11 +8,13 @@ uses sysutils; //for timing type tDataElem = record + myText : AnsiString; myX, myY : double; myTag, myOrgIdx : LongInt; end; + tpDataElem = ^tDataElem; tData = array of tDataElem; @@ -36,6 +38,7 @@ begin Sortdata[i] := @D[i]; with D[i] do Begin + myText := Format('_%.9d',[random(cnt)+1]); myX := Random*k; myY := Random*k; myTag := Random(k); @@ -51,9 +54,32 @@ begin Setlength(D,0); end; +function CompLowercase(A,B:tpDataElem):integer; +var + lcA,lcB: String; +Begin + lcA := lowercase(A^.myText); + lcB := lowercase(B^.myText); + result := ORD(lcA > lcB)-ORD(lcA < lcB); +end; + +function myCompText(A,B:tpDataElem):integer; +{sort an array (or list) of strings in order of descending length, + and in ascending lexicographic order for strings of equal length.} +var + lA,lB:integer; + +Begin + lA := Length(A^.myText); + lB := Length(B^.myText); + result := ORD(lAlB); + IF result = 0 then + result := CompLowercase(A,B); +end; + function myCompX(A,B:tpDataElem):integer; //same as sign without jumps in assembler code -Begin +begin result := ORD(A^.myX > B^.myX)-ORD(A^.myX < B^.myX); end; @@ -145,10 +171,15 @@ Begin randomize; InitData(Data,1*1000*1000); + T0 := Time; + mergesort(Low(SortData),High(SortData),SortData,@myCompText); + T1 := Time; + Writeln('myText ',FormatDateTime('NN:SS.ZZZ',T1-T0)); +// For i := 0 to High(Data) do Write(SortData[i].myText); writeln; T0 := Time; mergesort(Low(SortData),High(SortData),SortData,@myCompX); T1 := Time; - Writeln('myX ',FormatDateTime('NN:SS.ZZZ',T1-T0)); + Writeln('myX ',FormatDateTime('NN:SS.ZZZ',T1-T0)); //check For i := 1 to High(Data) do IF myCompX(SortData[i-1],SortData[i]) = 1 then @@ -157,7 +188,7 @@ Begin T0 := Time; mergesort(Low(SortData),High(SortData),SortData,@myCompY); T1 := Time; - Writeln('myY ',FormatDateTime('NN:SS.ZZZ',T1-T0)); + Writeln('myY ',FormatDateTime('NN:SS.ZZZ',T1-T0)); T0 := Time; mergesort(Low(SortData),High(SortData),SortData,@myCompTag); diff --git a/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.psh b/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.psh index efdb55c28b..4a34367b5b 100644 --- a/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.psh +++ b/Task/Sorting-algorithms-Merge-sort/PowerShell/sorting-algorithms-merge-sort.psh @@ -1,105 +1,36 @@ -Function Merge-Array( [Object[]] $lhs, [Object[]] $rhs ) +function MergeSort([object[]] $SortInput) { - $result = @() - $lhsl = $lhs.length - $rhsl = $rhs.length - if( $lhsl -gt 0 ) - { - if( $rhsl -gt 0 ) - { - $i = 0 - for( $j = 0; ( $i -lt $lhsl ) -and ( $j -lt $rhsl ); ) - { - if( $lhs[ $i ] -le $rhs[ $j ] ) - { - $result += $lhs[ $i ] - [void] ( $i++ ) - } else { - $result += $rhs[ $j ] - [void] ( $j++ ) - } - } - if( $i -lt $lhsl ) - { - $result += $lhs[ $i..( $lhsl - 1 ) ] - } - if( $j -lt $rhsl ) - { - $result += $rhs[ $j..( $rhsl - 1 ) ] - } - } else { - for( $i = 0; $i -lt $lhsl; $i++ ) - { - if( $rhs -le $lhs[ $i ] ) - { - $result += $rhs - break - } - $result += $lhs[ $i ] - } - if( $i -lt $lhsl ) - { - $result += $lhs[ $i..( $lhsl - 1 ) ] - } - } - } else { - if( $rhsl -gt 0 ) - { - for( $i = 0; $i -lt $rhsl; $i++ ) - { - if( $lhs -le $rhs[ $i ] ) - { - $result += $lhs - break - } - $result += $rhs[ $i ] - } - if( $i -lt $rhsl ) - { - $result += $rhs[ $i..( $rhsl - 1 ) ] - } - } else { - if( $lhs -lt $rhs ) - { - $result += $lhs - $result += $rhs - } else { - $result += $rhs - $result += $lhs - } - } - } - $result -} + # The base case exits for minimal lists that are sorted by definition + if ($SortInput.Length -le 1) {return $SortInput} + + # Divide and conquer + [int] $midPoint = $SortInput.Length/2 + # The @() operators ensure a single result remains typed as an array + [object[]] $left = @(MergeSort @($SortInput[0..($midPoint-1)])) + [object[]] $right = @(MergeSort @($SortInput[$midPoint..($SortInput.Length-1)])) -Function MergeSort( [Object[]] $data ) -{ - $datal = $data.length - 1 - if( $datal -gt 0 ) + # Merge + [object[]] $result = @() + while (($left.Length -gt 0) -and ($right.Length -gt 0)) { - $middle = [Math]::Floor( $datal / 2 ) - $left = @() - $left += MergeSort $data[ 0..$middle ] - $right = @() - $right += MergeSort $data[ ( $middle + 1 )..$datal ] - if( $left[ -1 ] -le $right[ 0 ] ) + if ($left[0] -lt $right[0]) { - $result = @() - $result += $left - $result += $right - $result - } elseif( $right[ -1 ] -le $left[ 0 ] ) + $result += $left[0] + # Use an if/else rather than accessing the array range as $array[1..0] + if ($left.Length -gt 1){$left = $left[1..$($left.Length-1)]} + else {$left = @()} + } + else { - $result = @() - $result += $right - $result += $left - $result - } else { - Merge-Array $left $right + $result += $right[0] + # Without the if/else, $array[1..0] would return the whole array when $array.Length == 1 + if ($right.Length -gt 1){$right = $right[1..$($right.Length-1)]} + else {$right = @()} } - } else { - $data } + + # If we get here, either $left or $right is an empty array (or both are empty!). Since the + # rest of the unmerged array is already sorted, we can simply string together what we have. + # This line outputs the concatenated result. An explicit 'return' statement is not needed. + $result + $left + $right } - -$l = 100; MergeSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) diff --git a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb index 2c026cc79b..5556e87f35 100644 --- a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb +++ b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-1.rb @@ -2,22 +2,15 @@ def merge_sort(m) return m if m.length <= 1 middle = m.length / 2 - left = m[0..middle - 1] - right = m[middle..-1] - - left = merge_sort(left) - right = merge_sort(right) + left = merge_sort(m[0...middle]) + right = merge_sort(m[middle..-1]) merge(left, right) end def merge(left, right) result = [] until left.empty? || right.empty? - if left.first <= right.first - result << left.shift - else - result << right.shift - end + result << (left.first<=right.first ? left.shift : right.shift) end result + left + right end diff --git a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb index 4d64d1851b..25a91f5e9b 100644 --- a/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb +++ b/Task/Sorting-algorithms-Merge-sort/Ruby/sorting-algorithms-merge-sort-2.rb @@ -1,9 +1,9 @@ class Array def mergesort(&comparitor) return self if length <= 1 - comparitor ||= lambda {|a, b| a <=> b} + comparitor ||= proc{|a, b| a <=> b} middle = length / 2 - left = self[0..middle - 1].mergesort(&comparitor) + left = self[0...middle].mergesort(&comparitor) right = self[middle..-1].mergesort(&comparitor) merge(left, right, comparitor) end @@ -28,5 +28,7 @@ def merge(left, right, comparitor) p ary.mergesort {|a, b| b <=> a} # => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] +p ary.mergesort +# => [["UK", "Birmingham"], ["UK", "London"], ["US", "Birmingham"], ["US", "New York"]] p ary.mergesort {|a, b| a[1] <=> b[1]} # => [["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]] diff --git a/Task/Sorting-algorithms-Pancake-sort/ALGOL-68/sorting-algorithms-pancake-sort.alg b/Task/Sorting-algorithms-Pancake-sort/ALGOL-68/sorting-algorithms-pancake-sort.alg new file mode 100644 index 0000000000..5756ce1558 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/ALGOL-68/sorting-algorithms-pancake-sort.alg @@ -0,0 +1,41 @@ +PROC flip = ([]INT s, INT n) []INT: + BEGIN + [UPB s]INT ss := s; + INT temp; + FOR i TO n OVER 2 DO + temp := ss[i]; + ss[i] := ss[n-i+1]; + ss[n-i+1] := temp + OD; + ss + END; + +PROC pancake sort = ([]INT s) []INT: + BEGIN + INT m; + [UPB s]INT ss := s; + FOR i FROM UPB s DOWNTO 2 DO + m := 1; + FOR j FROM 2 TO i DO + IF ss[j] > ss[m] THEN + m := j + FI + OD; + + IF m < i THEN + IF m > 1 THEN + ss := flip (ss,m) + FI; + ss := flip (ss,i) + FI + OD; + ss + END; + +[10]INT s; +FOR i TO UPB s DO + s[i] := ENTIER (next random * 100-50) +OD; +printf (($"Pancake sort demonstration"l$)); +printf (($"unsorted: "10(g(4) )l$, s)); +printf (($"sorted: "10(g(4) )l$, pancake sort(s))) diff --git a/Task/Sorting-algorithms-Pancake-sort/Batch-File/sorting-algorithms-pancake-sort.bat b/Task/Sorting-algorithms-Pancake-sort/Batch-File/sorting-algorithms-pancake-sort.bat new file mode 100644 index 0000000000..7609b2ae39 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Batch-File/sorting-algorithms-pancake-sort.bat @@ -0,0 +1,82 @@ +::Pancake Sort +::Batch File Implementation +:: +::Using the "Classic XOR trick" to swap integer values of two variables... +::...IF the variable names are different... + +@echo off +setlocal enabledelayedexpansion + +::Initial Values and Variables +set "range=0" +set "output=" +set "list=-2 0 -1 5 2 7 4 3 6 -1 7 2 1 8" + ::Put the sequence of integers (ONLY) on the list variable. + ::Please do not "play" with the list variable. + ::or else the code will not work or crash. + +for %%l in (!list!) do ( + set num!range!=%%l + set /a range+=1 +) +set /a range-=1 + +::Scramble +for /l %%l in (%range%,-1,1) do ( + set /a n=^(%random% %% %%l^) + set /a num%%l^^^^=num!n! + set /a num!n!^^^^=num%%l + set /a num%%l^^^^=num!n! +) +::/Scramble (Remove this if you do not want to scramble the integers) + +::Display initial condition +for /l %%l in (0,1,%range%) do set "output=!output! !num%%l!" +echo.Initial Sequence: +echo. +echo. ^>^> !output! +echo. +echo Sorting: +echo. + + ::Sort begins! +for /l %%m in (%range%,-1,1) do ( + set n=0 + for /l %%l in (1,1,%%m) do ( + set /a tmp_var1=num!n! + if !tmp_var1! lss !num%%l! set n=%%l + ) + if !n! lss %%m ( + if !n! gtr 0 ( + set /a tmp_var1=!n!/2 + for /l %%l in (0,1,!tmp_var1!) do ( + set /a tmp_var2=!n!-%%l + if !tmp_var2! neq %%l ( + set /a num!tmp_var2!^^^^=num%%l + set /a num%%l^^^^=num!tmp_var2! + set /a num!tmp_var2!^^^^=num%%l + ) + ) + set output= + for /l %%x in (0,1,%range%) do set "output=!output! !num%%x!" + echo. ^>^> !output! + ) + set /a tmp_var3=%%m/2 + for /l %%l in (0,1,!tmp_var3!) do ( + set /a tmp_var4=%%m-%%l + if !tmp_var4! neq %%l ( + set /a num!tmp_var4!^^^^=num%%l + set /a num%%l^^^^=num!tmp_var4! + set /a num!tmp_var4!^^^^=num%%l + ) + ) + set output= + for /l %%x in (0,1,%range%) do set "output=!output! !num%%x!" + echo. ^>^> !output! + ) + ) + +) + ::We are done. + echo DONE^^! + exit /b 0 diff --git a/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-1.e b/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-1.e index 76ee5e9ec2..33c96c3e0d 100644 --- a/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-1.e +++ b/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-1.e @@ -1,87 +1,105 @@ class - PANCAKE_SORT -create - make -feature{NONE} - arraymax(array: ARRAY [INTEGER]; upper: INTEGER):INTEGER - require - upper_index_positive: upper >=0 - array_exists: array/= void - local - i, cur_max, index: INTEGER - do - from - i:=1 - cur_max := array.item (i) - index := i - until - i+1 > upper - loop - if array.item(i+1) > cur_max then - cur_max := array.item(i+1) - index := i+1 - end - i := i + 1 - end - Result:=index - ensure - Index_positive: Result > 0 - end + PANCAKE_SORT [G -> COMPARABLE] - reverse_array(ar:ARRAY[INTEGER]; upper:INTEGER):ARRAY[INTEGER] - require - upper_positive: upper >0 - ar_not_void: ar /= void - local - i,j:INTEGER - new_array: ARRAY[INTEGER] - do - create new_array.make_empty - new_array.copy (ar) +feature {NONE} + + arraymax (array: ARRAY [G]; upper: INTEGER): INTEGER + --- Max item of 'array' between index 1 and 'upper'. + require + upper_index_positive: upper >= 0 + array_not_void: array /= Void + local + i: INTEGER + cur_max: G + do + from + i := 1 + cur_max := array.item (i) + Result := i + until + i + 1 > upper + loop + if array.item (i + 1) > cur_max then + cur_max := array.item (i + 1) + Result := i + 1 + end + i := i + 1 + end + ensure + Index_positive: Result > 0 + end + + reverse_array (ar: ARRAY [G]; upper: INTEGER): ARRAY [G] + -- Array reversed from index one to upper. + require + upper_positive: upper > 0 + ar_not_void: ar /= Void + local + i, j: INTEGER + new_array: ARRAY [G] + do + create Result.make_empty + Result.deep_copy (ar) from - i:= 1 - j:=upper + i := 1 + j := upper until - i>j + i > j loop - new_array[i]:=ar[j] - new_array[j]:=ar[i] - i:=i+1 - j:=j-1 + Result [i] := ar [j] + Result [j] := ar [i] + i := i + 1 + j := j - 1 end - Result:= new_array - ensure + ensure same_length: ar.count = Result.count - end + end - sort(ar:ARRAY[INTEGER]):ARRAY[INTEGER] - local - i:INTEGER - do - my_array:=ar - from - i:=ar.count - until - i=1 - loop - my_array:=reverse_array(reverse_array(my_array, arraymax(my_array,i)),i) - i:=i-1 + sort (ar: ARRAY [G]): ARRAY [G] + -- Sorted array in ascending order. + local + i: INTEGER + do + create Result.make_empty + Result.deep_copy (ar) + from + i := ar.count + until + i = 1 + loop + Result := reverse_array (reverse_array (Result, arraymax (Result, i)), i) + i := i - 1 + end + ensure + same_length: ar.count = Result.count + Result_sorted: is_sorted (Result) end - Result := my_array - ensure - same_length: ar.count= Result.count - end - my_array:ARRAY[INTEGER] + is_sorted (ar: ARRAY [G]): BOOLEAN + --- Is 'ar' sorted in ascending order? + require + ar_not_empty: ar.is_empty = False + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i = ar.upper + loop + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 + end + end feature - make(ar:ARRAY[INTEGER]) - do - create my_array.make_from_array(ar) - end - pancake_sort:ARRAY[INTEGER] - do - Result:= sort(my_array) - end + pancake_sort (ar: ARRAY [G]): ARRAY [G] + do + Result := sort (ar) + end + end diff --git a/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-2.e b/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-2.e index 7ec3a5616c..5db7c5456b 100644 --- a/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-2.e +++ b/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-2.e @@ -1,21 +1,32 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature - make - do - test := <<1, 27, 32, 99, 1, -7, 3, 5>> - create sorter.make(test) - io.put_string ("Unsorted: ") - across test as ar loop io.put_string (ar.item.out + " ") end - io.put_string ("%NSorted: ") - test:= sorter.pancake_sort - across test as ar loop io.put_string (ar.item.out + " ") end - end - test: ARRAY[INTEGER] - sorter: PANCAKE_SORT + make + do + test := <<1, 27, 32, 99, 1, -7, 3, 5>> + create sorter + io.put_string ("Unsorted: ") + across + test as ar + loop + io.put_string (ar.item.out + " ") + end + io.put_string ("%NSorted: ") + test := sorter.pancake_sort(test) + across + test as ar + loop + io.put_string (ar.item.out + " ") + end + end + + test: ARRAY [INTEGER] + + sorter: PANCAKE_SORT[INTEGER] + end diff --git a/Task/Sorting-algorithms-Pancake-sort/Elixir/sorting-algorithms-pancake-sort.elixir b/Task/Sorting-algorithms-Pancake-sort/Elixir/sorting-algorithms-pancake-sort.elixir new file mode 100644 index 0000000000..e91a554122 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Elixir/sorting-algorithms-pancake-sort.elixir @@ -0,0 +1,27 @@ +defmodule Sort do + def pancake_sort(list) when is_list(list), do: pancake_sort(list, length(list)) + + defp pancake_sort(list, 0), do: list + defp pancake_sort(list, limit) do + index = search_max(list, limit) + flip(list, index) |> flip(limit) |> pancake_sort(limit-1) + end + + defp search_max([h | t], limit), do: search_max(t, limit, 2, h, 1) + + defp search_max(_, limit, index, _, max_index) when limit max, do: search_max(t, limit, index+1, h, index), + else: search_max(t, limit, index+1, max, max_index) + end + + defp flip(list, n), do: flip(list, n, []) + + defp flip(list, 0, reverse), do: reverse ++ list + defp flip([h | t], n, reverse) do + flip(t, n-1, [h | reverse]) + end +end + +IO.inspect list = Enum.shuffle(1..9) +IO.inspect Sort.pancake_sort(list) diff --git a/Task/Sorting-algorithms-Pancake-sort/Julia/sorting-algorithms-pancake-sort.julia b/Task/Sorting-algorithms-Pancake-sort/Julia/sorting-algorithms-pancake-sort.julia new file mode 100644 index 0000000000..3ea738583d --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Julia/sorting-algorithms-pancake-sort.julia @@ -0,0 +1,21 @@ +function pancakesort!{T<:Real}(a::Array{T,1}) + len = length(a) + if len < 2 + return a + end + for i in len:-1:2 + j = indmax(a[1:i]) + i != j || continue + a[1:j] = reverse(a[1:j]) + a[1:i] = reverse(a[1:i]) + end + return a +end + +pancakesort{T<:Real}(a::Array{T,1}) = pancakesort!(copy(a)) + +println("Testing a pancake sort.") +a = [rand(-100:100) for i in 1:20] +println("Pre: ", a) +b = pancakesort(a) +println("Post: ", b) diff --git a/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx b/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx index 381b4cac95..4ffabd0047 100644 --- a/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx +++ b/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx @@ -1,38 +1,35 @@ -/*REXX program sorts & shows an array using the pancake sort algorithm.*/ -call gen@ /*generate elements in the array.*/ -call show@ 'before sort' /*show the BEFORE array elements.*/ -call pancakeSort # /*invoke the pancake sort. Yummy.*/ -call show@ ' after sort' /*show the AFTER array elements.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────FLIP subroutine─────────────────────*/ -flip: procedure expose @.; parse arg y - do i=1 for (y+1)%2 - ymp=y-i+1; _=@.i; @.i=@.ymp; @.ymp=_ - end /*i*/ +/*REXX program sorts and displays an array using the pancake sort algorithm.*/ +call gen /*generate elements in the @. array.*/ +call show 'before sort' /*display the BEFORE array elements.*/ +say copies('▒',40) /*display a separator line for eyeballs*/ +call pancakeSort # /*invoke the pancake sort. Yummy. */ +call show ' after sort' /*display the AFTER array elements. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +flip: procedure expose @.; parse arg y + do i=1 for (y+1)%2; ymp=y-i+1; _=@.i; @.i=@.ymp; @.ymp=_ + end /*i*/ return -/*──────────────────────────────────GEN@ subroutine──────────────────────────────────────────────────────────────────*/ -gen@: /*a few sorted bread primes which are primes of the form: (p-3)÷2 and 2∙p+3 */ - /*where p is a prime. Bread primes are related to sandwich and meat primes. */ +/*────────────────────────────────────────────────────────────────────────────*/ +gen: fibs= '-55 -21 -1 -8 -8 -21 -55 0 0' /*some non─positive Fibonacci numbers, most of which are repeated. */ + /* ┌───◄ a few sorted bread primes which are primes of the form: (p-3)÷2 and 2∙p+3 */ + /* ↓ where p is a prime. Bread primes are related to sandwich and meat primes.*/ bp=2 17 5 29 7 37 13 61 43 181 47 197 67 277 97 397 113 461 137 557 167 677 173 701 797 1117 307 1237 1597 463 1861 467 -fb='-55 -21 -1 -8 -8 -21 -55 0 0' /*some non-positive Fibonacci #s,*/ -$=bp fb /* most of which are repeated.*/ -#=words($) /*get number of items in $ list. */ - /* [↓] populate @ array with #s.*/ - do j=1 for #; @.j=word($,j); end /*obtain a number of the $ list.*/ +$=bp fibs; #=words($) /*combine the two lists; get # of items*/ + /* [↓] populate the @. array with #s*/ + do j=1 for #; @.j=word($,j); end /*◄─── obtain a number from the $ list.*/ return -/*──────────────────────────────────PANCAKESORT subroutine──────────────*/ +/*────────────────────────────────────────────────────────────────────────────*/ pancakeSort: procedure expose @.; parse arg N do N=N by -1 for N-1 - !=@.1; ?=1; do j=2 to N; if @.j<=! then iterate - !=@.j; ?=j + !=@.1; ?=1; do j=2 to N; if @.j<=! then iterate + !=@.j; ?=j end /*j*/ - call flip ?; call flip N + call flip ?; call flip N end /*N*/ return -/*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: w=length(#); do k=1 for # - say ' element' right(k,w) arg(1)':' right(@.k,9) - end /*k*/ -say copies('█',40) /*show an eyeball separator line.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +show: w=length(#) /* [↓] display elements of @. array.*/ + do k=1 for #; say ' element' right(k,w) arg(1)':' right(@.k,9); end return diff --git a/Task/Sorting-algorithms-Quicksort/360-Assembly/sorting-algorithms-quicksort.360 b/Task/Sorting-algorithms-Quicksort/360-Assembly/sorting-algorithms-quicksort.360 new file mode 100644 index 0000000000..02478bd0e8 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/360-Assembly/sorting-algorithms-quicksort.360 @@ -0,0 +1,164 @@ +* quicksort 14/09/2015 +QUICKSOR CSECT + USING QUICKSOR,R15 set base register +BEGIN MVC A,=F'1' a(1)=1 + MVC B,=A((A-T)/4) b(1)=hbound(t) + L R6,=F'1' k=1 +WHILEK LTR R6,R6 do while k^=0 + BZ EWHILEK + LR R1,R6 k + SLA R1,2 ~ + L R10,A-4(R1) l=a(k) + LR R1,R6 k + SLA R1,2 ~ + L R11,B-4(R1) m=b(k) + BCTR R6,0 k=k-1 + LR R4,R11 m + C R4,=F'2' if m<2 + BL WHILEK then iterate + LR R2,R10 l + AR R2,R11 +m + BCTR R2,0 -1 + ST R2,X x=l+m-1 + LR R2,R11 m + SRA R2,1 m/2 + AR R2,R10 +l + ST R2,Y y=l+m/2 + L R1,X x + SLA R1,2 ~ + L R4,T-4(R1) r4=t(x) + L R1,Y y + SLA R1,2 ~ + L R5,T-4(R1) r5=t(y) + LR R1,R10 l + SLA R1,2 ~ + L R3,T-4(R1) r3=t(l) +IF CR R4,R3 if t(x)t(l) + BNH IFXELIF + LR R7,R3 p=t(l) + B EIFX +IFXELIF LR R7,R5 p=t(y) + L R1,Y y + SLA R1,2 ~ + ST R3,T-4(R1) t(y)=t(l) +EIFX B ENDIF +ELSE CR R5,R3 if t(y)t(x) + BNH IFYELIF + LR R7,R4 p=t(x) + L R1,X x + SLA R1,2 ~ + ST R3,T-4(R1) t(x)=t(l) + B ENDIF +IFYELIF LR R7,R5 p=t(y) + L R1,Y y + SLA R1,2 ~ + ST R3,T-4(R1) t(y)=t(l) +ENDIF LA R8,1(R10) i=l+1 + L R9,X j=x +FOREVER EQU * +LOOPWI CR R8,R9 i<=j + BH ELOOPWI + LR R1,R8 i + SLA R1,2 ~ + L R2,T-4(R1) t(i) + CR R2,R7 t(i)<=p + BH ELOOPWI + LA R8,1(R8) i=i+1 + B LOOPWI +ELOOPWI EQU * +LOOPWJ CR R8,R9 i=p + BL ELOOPWJ + BCTR R9,0 j=j-1 + B LOOPWJ +ELOOPWJ CR R8,R9 if i>=j + BNL EFOREVER then leave segment finished + LR R1,R8 i + SLA R1,2 ~ + LA R2,T-4(R1) @t(i) + LR R1,R9 j + SLA R1,2 ~ + LA R3,T-4(R1) @t(j) + L R0,0(R2) w=t(i) + MVC 0(4,R2),0(R3) t(i)=t(j) swap t(i),t(j) + ST R0,0(R3) t(j)=w + B FOREVER +EFOREVER LR R9,R8 j=i + BCTR R9,0 j=i-1 + LR R1,R9 j + SLA R1,2 ~ + LA R3,T-4(R1) @t(j) + L R2,0(R3) t(j) + LR R1,R10 l + SLA R1,2 ~ + ST R2,T-4(R1) t(l)=t(j) + ST R7,0(R3) t(j)=p + LA R6,1(R6) k=k+1 + LR R1,R6 k + SLA R1,2 ~ + LA R4,A-4(R1) r4=@a(k) + LA R5,B-4(R1) r5=@b(k) + C R8,Y if i<=y + BH IFIHY + ST R8,0(R4) a(k)=i + L R2,X x + SR R2,R8 -i + LA R2,1(R2) +1 + ST R2,0(R5) b(k)=x-i+1 + LA R6,1(R6) k=k+1 + ST R10,4(R4) a(k)=l + LR R2,R9 j + SR R2,R10 -l + ST R2,4(R5) b(k)=j-l + B EIFIHY +IFIHY ST R10,4(R4) a(k)=l + LR R2,R9 j + SR R2,R10 -l + ST R2,0(R5) b(k)=j-l + LA R6,1(R6) k=k+1 + ST R8,4(R4) a(k)=i + L R2,X x + SR R2,R8 -i + LA R2,1(R2) +1 + ST R2,4(R5) b(k)=x-i+1 +EIFIHY B WHILEK +EWHILEK LA R3,PG ibuffer + LA R4,T @t(i) +LOOPI C R4,=A(A) do i=1 to hbound(t) + BH ELOOPI + L R2,0(R4) t(i) + XDECO R2,XD edit t(i) + MVC 0(4,R3),XD+8 put in buffer + LA R3,4(R3) ibuffer=ibuffer+1 + LA R4,4(R4) i=i+1 + B LOOPI +ELOOPI XPRNT PG,80 print bufffer +RETURN XR R15,R15 set return code + BR R14 return to caller +T DC F'10',F'9',F'9',F'6',F'7',F'16',F'1',F'16',F'17',F'15' + DC F'1',F'9',F'18',F'16',F'8',F'20',F'18',F'2',F'19',F'8' +A DS ((A-T)/4)F same size as T +B DS ((A-T)/4)F same size as T +X DS F +Y DS F +PG DS CL80 +XD DS CL12 + YREGS + END QUICKSOR diff --git a/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg b/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg index 1fe7cc4b16..05997bb3f5 100644 --- a/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg +++ b/Task/Sorting-algorithms-Quicksort/ALGOL-68/sorting-algorithms-quicksort-1.alg @@ -1,47 +1,62 @@ -PROC partition =(REF [] DATA array, PROC (REF DATA, REF DATA) BOOL cmp)INT: ( - INT begin:=LWB array; - INT end:=UPB array; - WHILE begin < end DO - WHILE begin < end DO - IF cmp(array[begin], array[end]) THEN - DATA tmp=array[begin]; - array[begin]:=array[end]; - array[end]:=tmp; - GO TO break while decr end - FI; - end -:= 1 +#--- Swap function ---# +PROC swap = (REF []INT array, INT first, INT second) VOID: +( + INT temp := array[first]; + array[first] := array[second]; + array[second]:= temp +); + +#--- Quick sort 3 arg function ---# +PROC quick = (REF [] INT array, INT first, INT last) VOID: +( + INT smaller := first + 1, + larger := last, + pivot := array[first]; + + WHILE smaller <= larger DO + WHILE array[smaller] < pivot AND smaller < last DO + smaller +:= 1 + OD; + WHILE array[larger] > pivot AND larger > first DO + larger -:= 1 + OD; + IF smaller < larger THEN + swap(array, smaller, larger); + smaller +:= 1; + larger -:= 1 + ELSE + smaller +:= 1 + FI OD; - break while decr end: SKIP; - WHILE begin < end DO - IF cmp(array[begin], array[end]) THEN - DATA tmp=array[begin]; - array[begin]:=array[end]; - array[end]:=tmp; - GO TO break while incr begin - FI; - begin +:= 1 - OD; - break while incr begin: SKIP - OD; - begin + + swap(array, first, larger); + + IF first < larger-1 THEN + quick(array, first, larger-1) + FI; + IF last > larger +1 THEN + quick(array, larger+1, last) + FI ); -PROC qsort=(REF [] DATA array, PROC (REF DATA, REF DATA) BOOL cmp)VOID: ( - IF LWB array < UPB array THEN - INT i := partition(array, cmp); - PAR ( # remove PAR for single threaded sort # - qsort(array[:i-1], cmp), - qsort(array[i+1:], cmp) - ) +#--- Quick sort 1 arg function ---# +PROC quicksort = (REF []INT array) VOID: +( + IF UPB array > 1 THEN + quick(array, 1, UPB array) FI ); -MODE DATA = INT; -PROC cmp=(REF DATA a,b)BOOL: a>b; +#***************************************************************# +main: +( + [10]INT a; + FOR i FROM 1 TO UPB a DO + a[i] := ROUND(random*1000) + OD; -main:( - []DATA const l=(5,4,3,2,1); - [UPB const l]DATA l:=const l; - qsort(l,cmp); - printf(($g(3)$,l)) + print(("Before:", a)); + quicksort(a); + print((newline, newline)); + print(("After: ", a)) ) diff --git a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada index 783d8b56ce..f83dd46d5c 100644 --- a/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada +++ b/Task/Sorting-algorithms-Quicksort/Ada/sorting-algorithms-quicksort-2.ada @@ -33,10 +33,11 @@ begin end loop; exit when Left >= Right; Swap(Item(Left), Item(Right)); - if Pivot_Index = Left then - Pivot_Index := Right; - elsif Pivot_Index = Right then - Pivot_Index := Left; + if Left < Item'Last then + Left := Index_Type'Succ(Left); + end if; + if Right > Item'First then + Right := Index_Type'Pred(Right); end if; end loop; if Right > Item'First then diff --git a/Task/Sorting-algorithms-Quicksort/Elixir/sorting-algorithms-quicksort.elixir b/Task/Sorting-algorithms-Quicksort/Elixir/sorting-algorithms-quicksort.elixir new file mode 100644 index 0000000000..17760b5e44 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Elixir/sorting-algorithms-quicksort.elixir @@ -0,0 +1,9 @@ +defmodule QuickSort do + def qsort([]) do + [] + end + def qsort([pivot | rest]) do + { left, right } = Enum.partition(rest, fn(x) -> x < pivot end) + qsort(left) ++ [pivot] ++ qsort(right) + end +end diff --git a/Task/Sorting-algorithms-Quicksort/Fexl/sorting-algorithms-quicksort.fexl b/Task/Sorting-algorithms-Quicksort/Fexl/sorting-algorithms-quicksort.fexl index 150baa4178..0a480ac601 100644 --- a/Task/Sorting-algorithms-Quicksort/Fexl/sorting-algorithms-quicksort.fexl +++ b/Task/Sorting-algorithms-Quicksort/Fexl/sorting-algorithms-quicksort.fexl @@ -1,15 +1,18 @@ -# (sort keep compare xs) sorts the list xs using the three-way comparison -# function. It keeps duplicates if the keep flag is true, otherwise it -# discards them and returns only the unique entries. - -\sort == - (\keep\compare\xs - xs end \x\xs - - \lo = (filter (\y compare y x T F F) xs) - \hi = (filter (\y compare y x F keep T) xs) +# (sort xs) is the ordered list of all elements in list xs. +# This version preserves duplicates. +\sort== + (\xs + xs [] \x\xs + append (sort; filter (gt x) xs); # all the items less than x + cons x; append (filter (eq x) xs); # all the items equal to x + sort; filter (lt x) xs # all the items greater than x + ) - append (sort keep compare lo); - item x; - sort keep compare hi +# (unique xs) is the ordered list of unique elements in list xs. +\unique== + (\xs + xs [] \x\xs + append (unique; filter (gt x) xs); # all the items less than x + cons x; # x itself + unique; filter (lt x) xs # all the items greater than x ) diff --git a/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-1.js b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-1.js index a660d645b8..713ba6f034 100644 --- a/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-1.js +++ b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-1.js @@ -1,22 +1,31 @@ function sort(array, less) { - function swap(i, j) { var t=array[i]; array[i]=array[j]; array[j]=t } + function swap(i, j) { + var t = array[i]; + array[i] = array[j]; + array[j] = t; + } function quicksort(left, right) { if (left < right) { - - var pivot = array[(left + right) >> 1]; - var left_new = left, right_new = right; + var pivot = array[(left + right) / 1], + left_new = left, + right_new = right; do { - while (less(array[left_new], pivot) - left_new++; - while (less(pivot, array[right_new]) - right_new--; - if (left_new <= right_new) - swap(left_new++, right_new--); - } while (left_new <= right_new); + while (less(array[left_new], pivot) { + left_new += 1; + } + while (less(pivot, array[right_new]) { + right_new -= 1; + } + if (left_new <= right_new) { + swap(left_new, right_new); + left_new += 1; + right_new -= 1; + } + } while (left_new <= right_new); quicksort(left, right_new); quicksort(left_new, right); @@ -24,7 +33,7 @@ function sort(array, less) { } } - quicksort(0, array.length-1); + quicksort(0, array.length - 1); return array; } diff --git a/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-2.js b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-2.js index 6d5a253808..a5c8c97c33 100644 --- a/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-2.js +++ b/Task/Sorting-algorithms-Quicksort/JavaScript/sorting-algorithms-quicksort-2.js @@ -1,11 +1,10 @@ -Array.prototype.quick_sort = function () -{ - if (this.length <= 1) - return this; +Array.prototype.quick_sort = function () { + if (this.length < 2) { return this; } var pivot = this[Math.round(this.length / 2)]; - return this.filter(function (x) { return x < pivot }).quick_sort().concat( - this.filter(function (x) { return x == pivot })).concat( - this.filter(function (x) { return x > pivot }).quick_sort()); -} + return this.filter(x => x < pivot) + .quick_sort() + .concat(this.filter(x => x == pivot)) + .concat(this.filter(x => x > pivot).quick_sort()); +}; diff --git a/Task/Sorting-algorithms-Quicksort/Perl-6/sorting-algorithms-quicksort.pl6 b/Task/Sorting-algorithms-Quicksort/Perl-6/sorting-algorithms-quicksort.pl6 index 11d9270739..073df3e21b 100644 --- a/Task/Sorting-algorithms-Quicksort/Perl-6/sorting-algorithms-quicksort.pl6 +++ b/Task/Sorting-algorithms-Quicksort/Perl-6/sorting-algorithms-quicksort.pl6 @@ -8,5 +8,5 @@ my @after := @rest.grep(* !before $pivot); # Sort the partitions. - (quicksort(@before), $pivot, quicksort(@after)) + flat quicksort(@before), $pivot, quicksort(@after) } diff --git a/Task/Sorting-algorithms-Quicksort/Perl/sorting-algorithms-quicksort.pl b/Task/Sorting-algorithms-Quicksort/Perl/sorting-algorithms-quicksort.pl index 242042c0ec..226d8ba855 100644 --- a/Task/Sorting-algorithms-Quicksort/Perl/sorting-algorithms-quicksort.pl +++ b/Task/Sorting-algorithms-Quicksort/Perl/sorting-algorithms-quicksort.pl @@ -1,8 +1,7 @@ sub quick_sort { - my @a = @_; - return @a if @a < 2; - my $p = splice @a, int rand @a, 1; - quick_sort(grep $_ < $p, @a), $p, quick_sort(grep $_ >= $p, @a); + return @_ if @_ < 2; + my $p = splice @_, int rand @_, 1; + quick_sort(grep $_ < $p, @_), $p, quick_sort(grep $_ >= $p, @_); } my @a = (4, 65, 2, -31, 0, 99, 83, 782, 1); diff --git a/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort.psh b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-1.psh similarity index 100% rename from Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort.psh rename to Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-1.psh diff --git a/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-2.psh b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-2.psh new file mode 100644 index 0000000000..e6d08dae43 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-2.psh @@ -0,0 +1,15 @@ +function quicksort($array) { + $less, $equal, $greater = @(), @(), @() + if( $array.Count -gt 1 ) { + $pivot = $array[0] + foreach( $x in $array) { + if($x -lt $pivot) { $less += @($x) } + elseif ($x -eq $pivot) { $equal += @($x)} + else { $greater += @($x) } + } + $array = (@(quicksort $less) + @($equal) + @(quicksort $greater)) + } + $array +} +$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11) +"$(quicksort $array)" diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb index 11aef435dd..2361ae2527 100644 --- a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb +++ b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-1.rb @@ -1,9 +1,8 @@ class Array def quick_sort return self if length <= 1 - pivot = sample - find_all { |i| i < pivot }.quick_sort + - find_all { |i| i == pivot } + - find_all { |i| i > pivot }.quick_sort + pivot = self[0] + less, greatereq = self[1..-1].partition { |x| x < pivot } + less.quick_sort + [pivot] + greatereq.quick_sort end end diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb index 2361ae2527..be8e6e9bf2 100644 --- a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb +++ b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-2.rb @@ -1,8 +1,9 @@ class Array def quick_sort return self if length <= 1 - pivot = self[0] - less, greatereq = self[1..-1].partition { |x| x < pivot } - less.quick_sort + [pivot] + greatereq.quick_sort + pivot = sample + group = group_by{ |x| x <=> pivot } + group.default = [] + group[-1].quick_sort + group[0] + group[1].quick_sort end end diff --git a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-3.rb b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-3.rb index be8e6e9bf2..9872f7b147 100644 --- a/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-3.rb +++ b/Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-3.rb @@ -1,9 +1,6 @@ class Array def quick_sort - return self if length <= 1 - pivot = sample - group = group_by{ |x| x <=> pivot } - group.default = [] - group[-1].quick_sort + group[0] + group[1].quick_sort + h, *t = self + h ? t.partition { |e| e < h }.inject { |l, r| l.quick_sort + [h] + r.quick_sort } : [] end end diff --git a/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust b/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust index 71cda9a762..fdb0bcefad 100644 --- a/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust +++ b/Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust @@ -9,23 +9,23 @@ fn quick_sort(v: &mut[T]) { let pivot_index = partition(v); // Sort the left side - quick_sort(v.mut_slice(0, pivot_index)); + quick_sort(&mut v[0..pivot_index]); // Sort the right side - quick_sort(v.mut_slice(pivot_index + 1, len)); + quick_sort(&mut v[pivot_index + 1..len]); } // Reorders the slice with values lower than the pivot at the left side, // and values bigger than it at the right side. // Also returns the store index. -fn partition(v: &mut [T]) -> uint { +fn partition(v: &mut [T]) -> usize { let len = v.len(); let pivot_index = len / 2; v.swap(pivot_index, len - 1); let mut store_index = 0; - for i in range(0, len - 1) { + for i in 0..len - 1 { if v[i] <= v[len - 1] { v.swap(i, store_index); store_index += 1; @@ -39,15 +39,15 @@ fn partition(v: &mut [T]) -> uint { fn main() { // Sort numbers let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; - println!("Before: {}", numbers.as_slice()); + println!("Before: {:?}", numbers); - quick_sort(numbers); - println!("After: {}", numbers.as_slice()); + quick_sort(&mut numbers); + println!("After: {:?}", numbers); // Sort strings let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"]; - println!("Before: {}", strings.as_slice()); + println!("Before: {:?}", strings); - quick_sort(strings); - println!("After: {}", strings.as_slice()); + quick_sort(&mut strings); + println!("After: {:?}", strings); } diff --git a/Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vb b/Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vb new file mode 100644 index 0000000000..b3c3d53d89 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/VBScript/sorting-algorithms-quicksort.vb @@ -0,0 +1,31 @@ +Function quicksort(arr,s,n) + l = s + r = s + n - 1 + p = arr(Int((l + r)/2)) + Do Until l > r + Do While arr(l) < p + l = l + 1 + Loop + Do While arr(r) > p + r = r -1 + Loop + If l <= r Then + tmp = arr(l) + arr(l) = arr(r) + arr(r) = tmp + l = l + 1 + r = r - 1 + End If + Loop + If s < r Then + Call quicksort(arr,s,r-s+1) + End If + If l < t Then + Call quicksort(arr,l,t-l+1) + End If + quicksort = arr +End Function + +myarray=Array(9,8,7,6,5,5,4,3,2,1,0,-1) +m = quicksort(myarray,0,12) +WScript.Echo Join(m,",") diff --git a/Task/Sorting-algorithms-Radix-sort/ALGOL-68/sorting-algorithms-radix-sort.alg b/Task/Sorting-algorithms-Radix-sort/ALGOL-68/sorting-algorithms-radix-sort.alg new file mode 100644 index 0000000000..270f9dccd7 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/ALGOL-68/sorting-algorithms-radix-sort.alg @@ -0,0 +1,50 @@ +PROC radixsort = (REF []INT array) VOID: +( + [UPB array]INT zero; + [UPB array]INT one; + BITS mask := 16r01; + INT zero_index := 0, + one_index := 0, + array_index := 1; + + WHILE ABS(mask) > 0 DO + WHILE array_index <= UPB array DO + IF (BIN(array[array_index]) AND mask) = 16r0 THEN + zero_index +:= 1; + zero[zero_index] := array[array_index] + ELSE + one_index +:= 1; + one[one_index] := array[array_index] + FI; + array_index +:= 1 + OD; + + array_index := 1; + FOR i FROM 1 TO zero_index DO + array[array_index] := zero[i]; + array_index +:= 1 + OD; + + FOR i FROM 1 TO one_index DO + array[array_index] := one[i]; + array_index +:=1 + OD; + + array_index := 1; + zero_index := one_index := 0; + mask := mask SHL 1 + OD +); + +main: +( + [10]INT a; + FOR i FROM 1 TO UPB a DO + a[i] := ROUND(random*1000) + OD; + + print(("Before:", a)); + print((newline, newline)); + radixsort(a); + print(("After: ", a)) +) diff --git a/Task/Sorting-algorithms-Radix-sort/Eiffel/sorting-algorithms-radix-sort-1.e b/Task/Sorting-algorithms-Radix-sort/Eiffel/sorting-algorithms-radix-sort-1.e new file mode 100644 index 0000000000..3c0876919c --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Eiffel/sorting-algorithms-radix-sort-1.e @@ -0,0 +1,92 @@ +class + RADIX_SORT + +feature + + radix_sort (ar: ARRAY [INTEGER]) + -- Array 'ar' sorted in ascending order. + require + ar_not_void: ar /= Void + not_negative: across ar as a all a.item >= 0 end + local + bucket_1, bucket_0: LINKED_LIST [INTEGER] + j, k, dig: INTEGER + do + create bucket_0.make + create bucket_1.make + dig := digits (ar) + across + 0 |..| dig as c + loop + across + ar as r + loop + if r.item.bit_test (c.item) then + bucket_1.extend (r.item) + else + bucket_0.extend (r.item) + end + end + from + j := 1 + until + j > bucket_0.count + loop + ar [j] := bucket_0 [j] + j := j + 1 + end + from + k := j + j := 1 + until + j > bucket_1.count + loop + ar [k] := bucket_1 [j] + k := k + 1 + j := j + 1 + end + bucket_0.wipe_out + bucket_1.wipe_out + end + ensure + is_sorted: is_sorted (ar) + end + +feature {NONE} + + digits (ar: ARRAY [INTEGER]): INTEGER + -- Number of digits of the largest item in 'ar'. + local + max: INTEGER + math: DOUBLE_MATH + do + create math + across + ar as a + loop + if a.item > max then + max := a.item + end + end + Result := math.log_2 (max).ceiling + 1 + end + + is_sorted (ar: ARRAY [INTEGER]): BOOLEAN + --- Is 'ar' sorted in ascending order? + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i >= ar.upper + loop + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 + end + end + +end diff --git a/Task/Sorting-algorithms-Radix-sort/Eiffel/sorting-algorithms-radix-sort-2.e b/Task/Sorting-algorithms-Radix-sort/Eiffel/sorting-algorithms-radix-sort-2.e new file mode 100644 index 0000000000..5c72cdd4ff --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Eiffel/sorting-algorithms-radix-sort-2.e @@ -0,0 +1,33 @@ +class + APPLICATION + +create + make + +feature + + make + local + test: ARRAY [INTEGER] + do + create rs + create test.make_empty + test := <<5, 4, 999, 5, 70, 0, 1000, 55, 1, 2, 3>> + io.put_string ("Unsorted:%N") + across + test as t + loop + io.put_string (t.item.out + " ") + end + rs.radix_sort (test) + io.put_string ("%NSorted:%N") + across + test as t + loop + io.put_string (t.item.out + " ") + end + end + + rs: RADIX_SORT + +end diff --git a/Task/Sorting-algorithms-Radix-sort/Elixir/sorting-algorithms-radix-sort.elixir b/Task/Sorting-algorithms-Radix-sort/Elixir/sorting-algorithms-radix-sort.elixir new file mode 100644 index 0000000000..692f5f0a78 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Elixir/sorting-algorithms-radix-sort.elixir @@ -0,0 +1,24 @@ +defmodule Sort do + def radix_sort(list), do: radix_sort(list, 10) + + def radix_sort([], _), do: [] + def radix_sort(list, base) do + max = abs(Enum.max_by(list, &abs(&1))) + sorted = radix_sort(list, base, max, 1) + {minus, plus} = Enum.partition(sorted, &(&1<0)) + Enum.reverse(minus, plus) + end + + defp radix_sort(list, _, max, m) when max + i = abs(x) |> div(m) |> rem(base) + put_elem(acc, i, [x | elem(acc, i)]) + end) + list2 = Enum.reduce(base-1..0, [], fn i,acc -> Enum.reverse(elem(bucket2, i), acc) end) + radix_sort(list2, base, max, m*base) + end +end + +IO.inspect Sort.radix_sort([-4, 5, -26, 58, -990, 331, 331, 990, -1837, 2028]) diff --git a/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx b/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx index 7ce49cb805..e2b42ad9de 100644 --- a/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx +++ b/Task/Sorting-algorithms-Radix-sort/REXX/sorting-algorithms-radix-sort.rexx @@ -1,71 +1,63 @@ -/*REXX program performs a radix sort on a stemmed integer array. */ -aList='0 2 3 4 5 5 7 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15 9 11', - '29 10 31 10 14 19 12 10 37 21 16 11 41 12 43 15 11 25 47 11 14 12', - '20 17 53 11 16 13 22 31 59 12 61 33 13 12 18 16 67 21 26 14 71 12', - '73 39 13 23 18 18 79 13 12 43 83 14 22 45 32 17 89 13 20 27 34 49', - '24 13 97 16 17 14 101 22 103 19 15 55 107 13 109 18 40 15 113 -42' -/*excluding -42, the abbreviated list is called the integer log function*/ -mina=word(aList,1); maxa=mina - do n=1 for words(aList); x=word(aList,n); @.n=x /*list ──► array.*/ - mina =min(x,mina); maxa=max(x,maxa) - width=max(length(abs(mina)),length(maxa)) - end /*n*/ -n=words(aList); w=length(n); call radSort n - do j=1 for n - say 'item' right(j,w) "after the radix sort:" right(@.j,width+1) - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────RADSORT subroutine─────────────────*/ -radSort: procedure expose @. width; parse arg size; mote=c2d(' '); #=1 -!.#._b=1; !.#._i=1 -!.#._n=size; do i=1 for size; y=@.i; @.i=right(abs(y),width,0) - if y<0 then @.i='-'@.i - end /*i*/ -/*══════════════════════════════════════where the rubber meets the road.*/ - do while #\==0; ctr.=0; L='ffff'x; low=!.#._b; n=!.#._n; radi=!.#._i; H= - #=#-1 - do j=low for n; parse var @.j =(radi) _ +1; ctr._=ctr._+1 - if ctr._==1 then if _\=='' then do - if _<>H then H=_ - end - end /*j*/ - if L>>H then iterate - _= - if L==H then if ctr._==0 then do; #=#+1; !.#._b=low - !.#._n=n - !.#._i=radi+1; iterate - end - L=c2d(L); H=c2d(H); ?=ctr._+low; top._=?; ts=mote; max=L - do k=L to H; _=d2c(k,1); cen=ctr._ - if cen>ts then parse value cen k with ts max - ?=?+cen; top._=? - end /*k*/ - pivot=low - do while pivot=cen then leave - top._=cen; ?=@.cen; @.cen=it; it=? - end /*forever*/ - top._=pivot; @.pivot=it; pivot=pivot+ctr._ - end /*while pivotH then i=L; d=ctr._ - if d<=mote then do; if d>1 then call .radSortP top._,d; iterate; end - #=#+1; !.#._b=top._ - !.#._n=d - !.#._i=radi+1 - end /*until i==max*/ - end /*while #\==0 */ -/*═════════════════════════════════════we're done with the heavy lifting*/ -#=0; do i=size by -1 to 1; if @.i>=0 then iterate; #=#+1; @@.#=@.i; end - do j=1 for size; if @.j <0 then iterate; #=#+1; @@.#=@.j; end - do k=1 for size; @.k=@@.k+0; end /*combine neg&pos radix lists*/ -return -/*───────────────────────────────────.radSortP subroutine───────────────*/ -.radSortP: parse arg bbb,nnn - do k=bbb+1 for nnn-1; q=@.k - do j=k-1 by -1 to bbb while q<<@.j; jp=j+1; @.jp=@.j; end - jp=j+1; @.jp=q +/*REXX program performs a radix sort on an integer (can be neg/zero/pos) array*/ +ILF='0 2 3 4 5 5 7 6 6 7 11 7 13 9 8 8 17 8 19 9 10 13 23 9 10 15 9 11 29 10 31 10 14 19', + '12 10 37 21 16 11 41 12 43 15 11 25 47 11 14 12 20 17 53 11 16 13 22 31 59 12 61 33', + '13 12 18 16 67 21 26 14 71 12 73 39 13 23 18 18 79 13 12 43 83 14 22 45 32 17 89 13', + '20 27 34 49 24 13 97 16 17 14 101 22 103 19 15 55 107 13 109 18 40 15 113 -42' + /*excluding -42, the abbreviated list (above) is called the integer log function.*/ +n=words(ILF) /* I────── L── F─────── */ +w=0 /*width so far.*/ + do m=1 for n; _=word(ILF,m); @.m=_; w=max(w,length(_)) /*store #s──►@.*/ + end /*m*/ /* ↑ */ + /* └─── is the maximum width of numbers*/ +call radSort n /*invoke the radix sort subroutine. */ + + do j=1 for n; say 'item' right(j,w) "after the radix sort:" right(@.j,w); end +exit /*stick a fork in it, we're all done. */ +/*───────────────────────────────────RADSORT subroutine───────────────────────*/ +radSort: procedure expose @. w; parse arg size; mote=c2d(' '); #=1; !.#._n=size +!.#._b=1; +!.#._i=1; do i=1 for size; y=@.i; @.i=right(abs(y),w,0); if y<0 then @.i='-'@.i + end /*i*/ /* [↓] where the rubber meats the road*/ +/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ + do while #\==0; ctr.=0; L='ffff'x; low=!.#._b; n=!.#._n; $=!.#._i; H= /*▒*/ + #=#-1 /* [↑] is radix.*/ /*▒*/ + do j=low for n; parse var @.j =($) _ +1; ctr._=ctr._+1 /*▒*/ + if ctr._==1 & _\=='' then do; if _<>H then H=_ /*▒*/ + end /* ↑ */ /*▒*/ + end /*j*/ /* └── << is a strict comparison.*/ /*▒*/ + _= /* ┌── >> " " " " */ /*▒*/ + if L>>H then iterate /*◄─┘ */ /*▒*/ + if L==H & ctr._==0 then do; #=#+1; !.#._b=low; !.#._n=n; !.#._i=$+1; iterate /*▒*/ + end /*▒*/ + L=c2d(L); H=c2d(H); ?=ctr._+low; top._=?; ts=mote /*▒*/ + max=L /*▒*/ + do k=L to H; _=d2c(k,1); cen=ctr._ /*▒*/ + if cen>ts then parse value cen k with ts max /*swap.*/ /*▒*/ + ?=?+cen; top._=? /*▒*/ + end /*k*/ /*▒*/ + piv=low /*set pivot to the low part.*/ /*▒*/ + do while piv=cen then leave; top._=cen; ?=@.cen; @.cen=it; it=? /*▒*/ + end /*forever*/ /*▒*/ + top._=piv /*▒*/ + @.piv=it; piv=piv+ctr._ /*▒*/ + end /*while pivH then i=L; d=ctr._ /*▒*/ + if d<=mote then do; if d>1 then call .radSortP top._,d; iterate; end /*▒*/ + #=#+1; !.#._b=top._; !.#._n=d; !.#._i=$+1 /*▒*/ + end /*until i==max */ /*▒*/ + end /*while #\==0 */ /*▒*/ +/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +#=0; do i=size by -1 to 1; if @.i>=0 then iterate; #=#+1; @@.#=@.i; end + do j=1 for size; if @.j>=0 then do; #=#+1; @@.#=@.j; end; @.j=@@.j+0; end +return /* [↑↑↑] combine 2 lists into 1 list. */ +/*───────────────────────────────────.radSortP subroutine─────────────────────*/ +.radSortP: parse arg bb,nn + do k=bb+1 for nn-1; q=@.k + do j=k-1 by -1 to bb while q<<@.j; jp=j+1; @.jp=@.j; end /*j*/ + jp=j+1; @.jp=q end /*k*/ return diff --git a/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort-1.rb b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort-1.rb new file mode 100644 index 0000000000..f2562e6d56 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort-1.rb @@ -0,0 +1,26 @@ +class Array + def radix_sort(base=10) + ary = dup + rounds = (Math.log(ary.minmax.map(&:abs).max)/Math.log(base)).floor + 1 + rounds.times do |i| + buckets = Array.new(2*base){[]} + base_i = base**i + ary.each do |n| + digit = (n/base_i) % base + digit += base if 0<=n + buckets[digit] << n + end + ary = buckets.flatten + p [i, ary] if $DEBUG + end + ary + end + def radix_sort!(base=10) + replace radix_sort(base) + end +end + +p [1, 3, 8, 9, 0, 0, 8, 7, 1, 6].radix_sort +p [170, 45, 75, 90, 2, 24, 802, 66].radix_sort +p [170, 45, 75, 90, 2, 24, -802, -66].radix_sort +p [100000, -10000, 400, 23, 10000].radix_sort diff --git a/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort-2.rb b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort-2.rb new file mode 100644 index 0000000000..5157e2b656 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort-2.rb @@ -0,0 +1,13 @@ +class Array + def radix_sort(base=10) + ary = dup + m, max = 1, ary.minmax.map(&:abs).max + while m <= max + buckets = Array.new(base){[]} + ary.each {|n| buckets[(n.abs / m) % base] << n} + ary = buckets.flatten + m *= base + end + ary.partition{|n| n<0}.inject{|minus,plus| minus.reverse + plus} + end +end diff --git a/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb b/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb deleted file mode 100644 index d1c46fdb1b..0000000000 --- a/Task/Sorting-algorithms-Radix-sort/Ruby/sorting-algorithms-radix-sort.rb +++ /dev/null @@ -1,25 +0,0 @@ -class Array - def radix_sort(base=10) - ary = dup - rounds = (Math.log(ary.minmax.map(&:abs).max)/Math.log(base)).ceil - rounds.times do |i| - buckets = Array.new(2*base){[]} - base_i = base**i - ary.each do |n| - digit = (n/base_i) % base - digit += base if 0<=n - buckets[digit] << n - end - ary = buckets.flatten - p [i, ary] if $DEBUG - end - ary - end - def radix_sort!(base=10) - replace radix_sort(base) - end -end - -p [1, 3, 8, 9, 0, 0, 8, 7, 1, 6].radix_sort -p [170, 45, 75, 90, 2, 24, 802, 66].radix_sort -p [170, 45, 75, 90, 2, 24, -802, -66].radix_sort diff --git a/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-1.e b/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-1.e index df8538f3c6..c7d9f21464 100644 --- a/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-1.e +++ b/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-1.e @@ -1,62 +1,83 @@ class - SELECTION_SORT[G -> COMPARABLE] - - + SELECTION_SORT [G -> COMPARABLE] feature {NONE} -index_of_min(ar: ARRAY [G]; lower: INTEGER):INTEGER - --find index of smallest element in array ar in the range of lower and the max index. - require - lower_positiv : lower >=1 - lower_in_range: lower <= ar.count - ar_not_void: ar/= Void - local - i, index: INTEGER - min: G - do - from - i:=lower - min := ar.item (i) - index := i - until - i+1 > ar.count - loop - if ar.item(i+1) < min then - min := ar.item(i+1) - index := i+1 - end - i := i + 1 - end - Result := index + + index_of_min (ar: ARRAY [G]; lower: INTEGER): INTEGER + --Index of smallest element in 'ar' in the range of lower and the max index. + require + lower_positiv: lower >= 1 + lower_in_range: lower <= ar.count + ar_not_void: ar /= Void + local + i: INTEGER + min: G + do + from + i := lower + min := ar.item (i) + Result := i + until + i + 1 > ar.count + loop + if ar.item (i + 1) < min then + min := ar.item (i + 1) + Result := i + 1 + end + i := i + 1 + end ensure result_is_set: Result /= Void - end - - + end -sort (ar: ARRAY [G]):ARRAY[G] - -- sort array ar with selectionsort + sort (ar: ARRAY [G]): ARRAY [G] + -- sort array ar with selectionsort require - ar_not_void: ar/=VOID + ar_not_void: ar /= Void local min_index: INTEGER ith: G - do - across ar as ic loop - min_index := index_of_min(ar,ic.cursor_index) - ith:=ar[ic.cursor_index] - ar[ic.cursor_index]:= ar[min_index] - ar[min_index]:=ith - end - Result:= ar + do + create Result.make_empty + Result.deep_copy (ar) + across + Result as ic + loop + min_index := index_of_min (Result, ic.cursor_index) + ith := Result [ic.cursor_index] + Result [ic.cursor_index] := Result [min_index] + Result [min_index] := ith + end ensure Result_is_set: Result /= Void - end + Result_sorted: is_sorted (Result) = True + end + is_sorted (ar: ARRAY [G]): BOOLEAN + --- Is 'ar' sorted in ascending order? + require + ar_not_empty: ar.is_empty = False + local + i: INTEGER + do + Result := True + from + i := ar.lower + until + i = ar.upper + loop + if ar [i] > ar [i + 1] then + Result := False + end + i := i + 1 + end + end feature -selectionsort(ar: ARRAY[G]):ARRAY[G] + + selectionsort (ar: ARRAY [G]): ARRAY [G] do - Result:= sort(ar) + Result := sort (ar) end + end diff --git a/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-2.e b/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-2.e index ac85664410..5ac6809f00 100644 --- a/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-2.e +++ b/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-2.e @@ -1,23 +1,32 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make feature - make - do - test := <<1, 27, 32, 99, 1, -7, 3, 5, 7>> - io.put_string ("Unsorted: ") - across test as ic loop io.put_string (ic.item.out + " ") end - create selection - io.put_string ("%NSorted: ") - test:= selectionsort.selectionsort(test) - across test as ar loop io.put_string (ar.item.out + " ") end - end + make + do + test := <<1, 27, 32, 99, 1, -7, 3, 5, 7>> + io.put_string ("Unsorted: ") + across + test as ic + loop + io.put_string (ic.item.out + " ") + end + create selectionsort + io.put_string ("%NSorted: ") + test := selectionsort.selectionsort (test) + across + test as ar + loop + io.put_string (ar.item.out + " ") + end + end + + test: ARRAY [INTEGER] + + selectionsort: SELECTION_SORT [INTEGER] - test: ARRAY[INTEGER] - selection: SELECTION_SORT[INTEGER] end diff --git a/Task/Sorting-algorithms-Selection-sort/Elixir/sorting-algorithms-selection-sort.elixir b/Task/Sorting-algorithms-Selection-sort/Elixir/sorting-algorithms-selection-sort.elixir new file mode 100644 index 0000000000..c54a428f08 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Elixir/sorting-algorithms-selection-sort.elixir @@ -0,0 +1,9 @@ +defmodule Sort do + def selection_sort(list) when is_list(list), do: selection_sort(list, []) + + defp selection_sort([], sorted), do: sorted + defp selection_sort(list, sorted) do + max = Enum.max(list) + selection_sort(List.delete(list, max), [max | sorted]) + end +end diff --git a/Task/Sorting-algorithms-Selection-sort/Julia/sorting-algorithms-selection-sort.julia b/Task/Sorting-algorithms-Selection-sort/Julia/sorting-algorithms-selection-sort.julia new file mode 100644 index 0000000000..1d1d52d95a --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Julia/sorting-algorithms-selection-sort.julia @@ -0,0 +1,21 @@ +function selectionsort!{T<:Real}(a::Array{T,1}) + len = length(a) + if len < 2 + return nothing + end + for i in 1:len-1 + (lmin, j) = findmin(a[i+1:end]) + if lmin < a[i] + a[i+j] = a[i] + a[i] = lmin + end + end + return nothing +end + +a = [rand(-100:100) for i in 1:20] +println("Before Sort:") +println(a) +selectionsort!(a) +println("\nAfter Sort:") +println(a) diff --git a/Task/Sorting-algorithms-Selection-sort/PL-I/sorting-algorithms-selection-sort.pli b/Task/Sorting-algorithms-Selection-sort/PL-I/sorting-algorithms-selection-sort.pli index e19b7a937a..d345dde665 100644 --- a/Task/Sorting-algorithms-Selection-sort/PL-I/sorting-algorithms-selection-sort.pli +++ b/Task/Sorting-algorithms-Selection-sort/PL-I/sorting-algorithms-selection-sort.pli @@ -1,6 +1,6 @@ Selection: procedure options (main); /* 2 November 2013 */ - declare a(10) fixed b inary initial ( + declare a(10) fixed binary initial ( 5, 7, 3, 98, 4, -3, 25, 20, 60, 17); put edit (trim(a)) (a, x(1)); diff --git a/Task/Sorting-algorithms-Selection-sort/Python/sorting-algorithms-selection-sort.py b/Task/Sorting-algorithms-Selection-sort/Python/sorting-algorithms-selection-sort.py index efa4588b0c..09db8ba521 100644 --- a/Task/Sorting-algorithms-Selection-sort/Python/sorting-algorithms-selection-sort.py +++ b/Task/Sorting-algorithms-Selection-sort/Python/sorting-algorithms-selection-sort.py @@ -1,5 +1,5 @@ -def selectionSort(lst): - for i in range(0,len(lst)-1): +def selection_sort(lst): + for i, e in enumerate(lst): mn = min(range(i,len(lst)), key=lst.__getitem__) - lst[i],lst[mn] = lst[mn],lst[i] + lst[i], lst[mn] = lst[mn], e return lst diff --git a/Task/Sorting-algorithms-Selection-sort/VBScript/sorting-algorithms-selection-sort.vb b/Task/Sorting-algorithms-Selection-sort/VBScript/sorting-algorithms-selection-sort.vb new file mode 100644 index 0000000000..d7460f747e --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/VBScript/sorting-algorithms-selection-sort.vb @@ -0,0 +1,19 @@ +Function Selection_Sort(s) + arr = Split(s,",") + For i = 0 To UBound(arr) + For j = i To UBound(arr) + temp = arr(i) + If arr(j) < arr(i) Then + arr(i) = arr(j) + arr(j) = temp + End If + Next + Next + Selection_Sort = (Join(arr,",")) +End Function + +WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted" +WScript.StdOut.WriteLine +WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1") +WScript.StdOut.WriteLine +WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d") diff --git a/Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort.j b/Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort-1.j similarity index 100% rename from Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort.j rename to Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort-1.j diff --git a/Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort-2.j b/Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort-2.j new file mode 100644 index 0000000000..9f84bdcce4 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/J/sorting-algorithms-shell-sort-2.j @@ -0,0 +1,2 @@ + shellSort 8 6 4 2 1 3 5 7 9 +1 2 3 4 5 6 7 8 9 diff --git a/Task/Sorting-algorithms-Shell-sort/Liberty-BASIC/sorting-algorithms-shell-sort.liberty b/Task/Sorting-algorithms-Shell-sort/Liberty-BASIC/sorting-algorithms-shell-sort.liberty new file mode 100644 index 0000000000..8f0d992d81 --- /dev/null +++ b/Task/Sorting-algorithms-Shell-sort/Liberty-BASIC/sorting-algorithms-shell-sort.liberty @@ -0,0 +1,30 @@ +siz = 100 +dim a(siz) +for i = 1 to siz + a(i) = int(rnd(1) * 1000) +next + +' ------------------------------- +' Shell Sort +' ------------------------------- + incr = int(siz / 2) + WHILE incr > 0 + for i = 1 to siz + j = i + temp = a(i) + WHILE (j >= incr+1 and a(abs(j-incr)) > temp) + a(j) = a(j-incr) + j = j - incr + wend + a(j) = temp + next + IF incr = 2 THEN + incr = 1 + ELSE + incr = int(incr * (5 / 11)) + end if + WEND + +for i = 1 to siz +print a(i) +next diff --git a/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx b/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx index eb0de4af9b..f8749fe19c 100644 --- a/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx +++ b/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx @@ -1,54 +1,48 @@ -/*REXX program sorts an (stemmed) array using the shellsort method. */ -call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call shellSort # /*invoke the shell sort. */ -call show@ ' after sort' /*show the after array elements.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.= /*assign default value to stem. */ - @.1='3 character abbreviations for states of the USA' /*predates ZIP.*/ +/*REXX program sorts a stemmed array using the shell sort algorithm. */ +call gen /*generate the array elements. */ +call show 'before sort' /*display the before array elements. */ +say copies('▒',75) /*displat a separator line (a fence). */ +call shellSort # /*invoke the shell sort. */ +call show ' after sort' /*display the after array elements. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────GEN subroutine────────────────────────────*/ +gen: @.= /*assign a default value to stem array.*/ + @.1='3 character abbreviations for states of the USA' /*predates ZIP code.*/ @.2='===============================================' - @.3='RHO Rhode Island and Providence Plantations' ; @.36='NMX New Mexico' - @.4='CAL California' ; @.20='NEV Nevada' ; @.37='IND Indiana' - @.5='KAN Kansas' ; @.21='TEX Texas' ; @.38='MOE Missouri' - @.6='MAS Massachusetts' ; @.22='VGI Virginia' ; @.39='COL Colorado' - @.7='WAS Washington' ; @.23='OHI Ohio' ; @.40='CON Connecticut' - @.8='HAW Hawaii' ; @.24='NHM New Hampshire'; @.41='MON Montana' - @.9='NCR North Carolina'; @.25='MAE Maine' ; @.42='LOU Louisiana' -@.10='SCR South Carolina'; @.26='MIC Michigan' ; @.43='IOW Iowa' -@.11='IDA Idaho' ; @.27='MIN Minnesota' ; @.44='ORE Oregon' -@.12='NDK North Dakota' ; @.28='MIS Mississippi' ; @.45='ARK Arkansas' -@.13='SDK South Dakota' ; @.29='WIS Wisconsin' ; @.46='ARZ Arizona' -@.14='NEB Nebraska' ; @.30='OKA Oklahoma' ; @.47='UTH Utah' -@.15='DEL Delaware' ; @.31='ALA Alabama' ; @.48='KTY Kentucky' -@.16='PEN Pennsylvania' ; @.32='FLA Florida' ; @.49='WVG West Virginia' -@.17='TEN Tennessee' ; @.33='MLD Maryland' ; @.50='NWJ New Jersey' -@.18='GEO Georgia' ; @.34='ALK Alaska' ; @.51='NYK New York' -@.19='VER Vermont' ; @.35='ILL Illinois' ; @.52='WYO Wyoming' - - do #=1 while @.#\=='' /*find how many entries in array.*/ - end /*#*/ -#=#-1 /*adjust # of entries slightly.*/ + @.3='RHO Rhode Island and Providence Plantations' ; @.36='NMX New Mexico' + @.4='CAL California' ; @.20='NEV Nevada' ; @.37='IND Indiana' + @.5='KAN Kansas' ; @.21='TEX Texas' ; @.38='MOE Missouri' + @.6='MAS Massachusetts' ; @.22='VGI Virginia' ; @.39='COL Colorado' + @.7='WAS Washington' ; @.23='OHI Ohio' ; @.40='CON Connecticut' + @.8='HAW Hawaii' ; @.24='NHM New Hampshire'; @.41='MON Montana' + @.9='NCR North Carolina'; @.25='MAE Maine' ; @.42='LOU Louisiana' +@.10='SCR South Carolina'; @.26='MIC Michigan' ; @.43='IOW Iowa' +@.11='IDA Idaho' ; @.27='MIN Minnesota' ; @.44='ORE Oregon' +@.12='NDK North Dakota' ; @.28='MIS Mississippi' ; @.45='ARK Arkansas' +@.13='SDK South Dakota' ; @.29='WIS Wisconsin' ; @.46='ARZ Arizona' +@.14='NEB Nebraska' ; @.30='OKA Oklahoma' ; @.47='UTH Utah' +@.15='DEL Delaware' ; @.31='ALA Alabama' ; @.48='KTY Kentucky' +@.16='PEN Pennsylvania' ; @.32='FLA Florida' ; @.49='WVG West Virginia' +@.17='TEN Tennessee' ; @.33='MLD Maryland' ; @.50='NWJ New Jersey' +@.18='GEO Georgia' ; @.34='ALK Alaska' ; @.51='NYK New York' +@.19='VER Vermont' ; @.35='ILL Illinois' ; @.52='WYO Wyoming' + do #=1 while @.#\==''; end; #=#-1 /*determine number of entries in array.*/ return -/*──────────────────────────────────SHELLSORT subroutine────────────────*/ +/*──────────────────────────────────SHELLSORT subroutine──────────────────────*/ shellSort: procedure expose @.; parse arg N -i=N%2 /*integer divide N by two. */ - do while i\==0 - do j=i+1 to N; k=j; kmi=k-i - _=@.j - do while k>=i+1 & @.kmi>_; @.k=@.kmi - k=k-i; kmi=k-i - end /*while k>=i+1 & ···*/ - @.k=_ - end /*j*/ +i=N%2 /*% is integer division in REXX. */ + do while i\==0 + do j=i+1 to N; k=j; p=k-i /*P: previous item*/ + _=@.j + do while k>=i+1 & @.p>_; @.k=@.p + k=k-i; p=k-i + end /*while k≥i+1*/ + @.k=_ + end /*j*/ - if i==2 then i=1 - else i=i*5%11 - end /*while i\==0*/ -return -/*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: do j=1 for # - say 'element' right(j,length(#)) arg(1)': ' @.j - end /*j*/ -say copies('─',79) /*show a separator line (a fence)*/ + if i==2 then i=1 + else i=i*5%11 + end /*while i¬==0*/ return +/*──────────────────────────────────SHOW subroutine───────-───────────────────*/ +show: do j=1 for #; say 'element' right(j,length(#)) arg(1)': ' @.j; end; return diff --git a/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort.hs b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-1.hs similarity index 100% rename from Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort.hs rename to Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-1.hs diff --git a/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-2.hs b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-2.hs new file mode 100644 index 0000000000..362463413c --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Haskell/sorting-algorithms-sleep-sort-2.hs @@ -0,0 +1,9 @@ +import System.Environment +import Control.Concurrent +import Control.Concurrent.Async + +sleepSort :: [Int] -> IO [()] +sleepSort = mapConcurrently (\x -> threadDelay (x*10^4) >> print x) + +main :: IO [()] +main = getArgs >>= sleepSort . map read diff --git a/Task/Sorting-algorithms-Sleep-sort/Julia/sorting-algorithms-sleep-sort.julia b/Task/Sorting-algorithms-Sleep-sort/Julia/sorting-algorithms-sleep-sort.julia new file mode 100644 index 0000000000..cd5dc69979 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Julia/sorting-algorithms-sleep-sort.julia @@ -0,0 +1,12 @@ +input = [3,2,4,7,3,6,9,1] +output = Int[] + +@sync for i in input + @async begin + sleep(i) + push!(output, i) + end +end + +@assert output == sort(input) +println(output) diff --git a/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust b/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust index a8242b39fb..fd4544bb91 100644 --- a/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust +++ b/Task/Sorting-algorithms-Sleep-sort/Rust/sorting-algorithms-sleep-sort.rust @@ -1,15 +1,13 @@ -// rust 0.9 +use std::thread; -fn main() -{ - let args = std::os::args(); - for arg in args.tail().iter() - { - let n = from_str::(*arg).unwrap(); - do std::task::spawn - { - std::io::timer::sleep(n); - println!("{}", n); - } - } +fn sleepsort>(nums: I) { + let threads: Vec<_> = nums.map(|n| + thread::spawn(move || { + thread::sleep_ms(n); + println!("{}", n); })).collect(); + for t in threads { t.join(); } +} + +fn main() { + sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap())); } diff --git a/Task/Sorting-algorithms-Sleep-sort/SNUSP/sorting-algorithms-sleep-sort.snusp b/Task/Sorting-algorithms-Sleep-sort/SNUSP/sorting-algorithms-sleep-sort.snusp new file mode 100644 index 0000000000..5ee13b4632 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/SNUSP/sorting-algorithms-sleep-sort.snusp @@ -0,0 +1,5 @@ + /$>\ input until eof + #/?<\?,/ foreach: fork + \ &/:+ copy and\ + /:\?-; delay / + \.# print and exit thread diff --git a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e index 73e1861b98..6c4d571b4d 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e +++ b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e @@ -2,6 +2,7 @@ class STOOGE_SORT feature stoogesort (ar: ARRAY[INTEGER]; i,j: INTEGER) + -- Sorted array in ascending order. require ar_not_empty: ar.count >= 0 i_in_range: i>=1 diff --git a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e index bd968fbbe8..2277afa5b9 100644 --- a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e +++ b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e @@ -1,20 +1,32 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - do - test:= <<2,5,66,-2, 0, 7>> - io.put_string ("%Nunsorted:%N") - across test as ar loop io.put_string (ar.item.out + "%T") end - create stoogesort - stoogesort.stoogesort (test, 1, test.count) - io.put_string ("%Nsorted:%N") - across test as ar loop io.put_string (ar.item.out + "%T") end - end - test: ARRAY[INTEGER] + do + test := <<2, 5, 66, -2, 0, 7>> + io.put_string ("%Nunsorted:%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + create stoogesort + stoogesort.stoogesort (test, 1, test.count) + io.put_string ("%Nsorted:%N") + across + test as ar + loop + io.put_string (ar.item.out + "%T") + end + end + + test: ARRAY [INTEGER] + stoogesort: STOOGE_SORT + end diff --git a/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb b/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb index 497c5be305..9d7e1cd29d 100644 --- a/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb +++ b/Task/Sorting-algorithms-Strand-sort/Ruby/sorting-algorithms-strand-sort.rb @@ -1,18 +1,14 @@ class Array def strandsort - a = self.dup + a = dup result = [] until a.empty? - sublist = [a.shift] - a.each_with_index.each_with_object([]) { |(val, idx), remove| - next if val <= sublist.last - sublist << val - remove << idx - }.reverse_each {|idx| a.delete_at(idx)} + v = a.first + sublist, a = a.partition{|val| v=val if v<=val} # In case of v>val, it becomes nil. result.each_index do |idx| break if sublist.empty? - result.insert(idx, sublist.shift) if sublist[0] < result[idx] + result.insert(idx, sublist.shift) if sublist.first < result[idx] end result += sublist end diff --git a/Task/Soundex/Clojure/soundex.clj b/Task/Soundex/Clojure/soundex-1.clj similarity index 100% rename from Task/Soundex/Clojure/soundex.clj rename to Task/Soundex/Clojure/soundex-1.clj diff --git a/Task/Soundex/Clojure/soundex-2.clj b/Task/Soundex/Clojure/soundex-2.clj new file mode 100644 index 0000000000..f2c1e651a0 --- /dev/null +++ b/Task/Soundex/Clojure/soundex-2.clj @@ -0,0 +1,27 @@ +;;; With proper consecutive duplicates elimination + +(defn get-code [c] + (case c + (\B \F \P \V) 1 + (\C \G \J \K + \Q \S \X \Z) 2 + (\D \T) 3 + \L 4 + (\M \N) 5 + \R 6 + nil)) ;(\A \E \I \O \U \H \W \Y) + +(defn reduce-fn [acc nxt] + (let [next-code (get-code nxt)] + (if (and (not= next-code (last acc)) + (not (nil? next-code))) + (conj acc next-code) + acc))) + +(defn soundex [the-word] + (let [[first-char & the-rest] (.toUpperCase the-word) + next-code (get-code (first the-rest))] + (if (nil? next-code) + (recur (apply str first-char (rest the-rest))) + (let [soundex-nums (reduce reduce-fn [] the-rest)] + (apply str first-char (take 3 (conj soundex-nums 0 0 0))))))) diff --git a/Task/Sparkline-in-unicode/APL/sparkline-in-unicode-1.apl b/Task/Sparkline-in-unicode/APL/sparkline-in-unicode-1.apl new file mode 100644 index 0000000000..4fde26cf07 --- /dev/null +++ b/Task/Sparkline-in-unicode/APL/sparkline-in-unicode-1.apl @@ -0,0 +1 @@ + sparkln←{'▁▂▃▄▅▆▇█'[⌊0.5+7×⍵÷⌈/⍵]} diff --git a/Task/Sparkline-in-unicode/APL/sparkline-in-unicode-2.apl b/Task/Sparkline-in-unicode/APL/sparkline-in-unicode-2.apl new file mode 100644 index 0000000000..f38f566899 --- /dev/null +++ b/Task/Sparkline-in-unicode/APL/sparkline-in-unicode-2.apl @@ -0,0 +1,4 @@ + sparkln 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 +▂▃▄▅▅▆▇█▇▆▅▅▄▃▂ + sparkln 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 +▂▁▄▃▆▅█▇ diff --git a/Task/Sparkline-in-unicode/Clojure/sparkline-in-unicode.clj b/Task/Sparkline-in-unicode/Clojure/sparkline-in-unicode.clj new file mode 100644 index 0000000000..04c1c068fb --- /dev/null +++ b/Task/Sparkline-in-unicode/Clojure/sparkline-in-unicode.clj @@ -0,0 +1,15 @@ +(defn sparkline [nums] + (let [sparks "▁▂▃▄▅▆▇█" + high (apply max nums) + low (apply min nums) + spread (- high low) + quantize #(Math/round (* 7.0 (/ (- % low) spread)))] + (apply str (map #(nth sparks (quantize %)) nums)))) + +(defn spark [line] + (if line + (let [nums (read-string (str "[" line "]"))] + (println (sparkline nums)) + (recur (read-line))))) + +(spark (read-line)) diff --git a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-2.j b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-2.j index c80f79d100..152ab1fead 100644 --- a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-2.j +++ b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-2.j @@ -1 +1 @@ - spkln =: (4 u:16b2581+i.8)&$: : ([ {~ <:@#@[ * ] (- % >./@[ - ]) <./@]) + 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 index b1ed8c1dd6..d58dbc4f8d 100644 --- a/Task/Sparkline-in-unicode/J/sparkline-in-unicode-3.j +++ b/Task/Sparkline-in-unicode/J/sparkline-in-unicode-3.j @@ -1 +1 @@ - spkln =: (4 u:16b2581+i.8)&$: : ([ {~ ((* <:@#)~ ((- % (- >./))~ <./))) + spkln =: (u:9601+i.8)&$: : ([ {~ ((<.@* <:@#)~ ((- % (- >./))~ <./))) diff --git a/Task/Sparkline-in-unicode/Julia/sparkline-in-unicode.julia b/Task/Sparkline-in-unicode/Julia/sparkline-in-unicode.julia new file mode 100644 index 0000000000..e160edb25f --- /dev/null +++ b/Task/Sparkline-in-unicode/Julia/sparkline-in-unicode.julia @@ -0,0 +1,22 @@ +function sparklineit(a) + const sparkchars = '\u2581':'\u2588' + const dyn = length(sparkchars) + (lo, hi) = extrema(a) + b = max(iceil(dyn*(a-lo)/(hi-lo)), 1) + return join(sparkchars[b], "") +end + +function getnumbers(s) + a = split(s, r"[,,\s]+") + a = try + map(parseint, a) + catch + map(parsefloat, a) + end +end + +test = getnumbers("1 2 3 4 5 6 7 8 7 6 5 4 3 2 1") +println(test, " => ", sparklineit(test)) + +test = getnumbers("1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5") +println(test, " => ", sparklineit(test)) diff --git a/Task/Special-variables/00META.yaml b/Task/Special-variables/00META.yaml index d12c4ff10b..af053c5d56 100644 --- a/Task/Special-variables/00META.yaml +++ b/Task/Special-variables/00META.yaml @@ -1,3 +1,4 @@ --- category: - Special variables +note: Basic language learning diff --git a/Task/Speech-synthesis/BASIC256/speech-synthesis.basic256 b/Task/Speech-synthesis/BASIC256/speech-synthesis.basic256 index 18dc7fbcfd..d61168dff9 100644 --- a/Task/Speech-synthesis/BASIC256/speech-synthesis.basic256 +++ b/Task/Speech-synthesis/BASIC256/speech-synthesis.basic256 @@ -1 +1,2 @@ say "Goodbye, World for the " + 123456 + "th time." +say "This is an example of speech synthesis." diff --git a/Task/Speech-synthesis/Batch-File/speech-synthesis.bat b/Task/Speech-synthesis/Batch-File/speech-synthesis.bat new file mode 100644 index 0000000000..745211e724 --- /dev/null +++ b/Task/Speech-synthesis/Batch-File/speech-synthesis.bat @@ -0,0 +1,9 @@ +@set @dummy=0 /* + ::Batch File section + @echo off + cscript //e:jscript //nologo "%~f0" "%~1" + exit /b +::*/ +//The JScript section +var objVoice = new ActiveXObject("SAPI.SpVoice"); +objVoice.speak(WScript.Arguments(0)); diff --git a/Task/Speech-synthesis/JavaScript/speech-synthesis.js b/Task/Speech-synthesis/JavaScript/speech-synthesis.js new file mode 100644 index 0000000000..748b9010c3 --- /dev/null +++ b/Task/Speech-synthesis/JavaScript/speech-synthesis.js @@ -0,0 +1,2 @@ +var voice = new ActiveXObject("SAPI.SpVoice"); +voice.speak("This is an example of speech synthesis."); diff --git a/Task/Speech-synthesis/REXX/speech-synthesis.rexx b/Task/Speech-synthesis/REXX/speech-synthesis.rexx index 33d7915796..43fd132b4b 100644 --- a/Task/Speech-synthesis/REXX/speech-synthesis.rexx +++ b/Task/Speech-synthesis/REXX/speech-synthesis.rexx @@ -1,16 +1,18 @@ -/*REXX pgm uses a CLI cmd to invoke Windows/XP SAM for speech synthesis.*/ -parse arg t; t=space(t) /*get the (optional) text from CL*/ -if t=='' then exit /*Nothing to say? Then exit pgm.*/ -homedrive=value('HOMEDRIVE',,'SYSTEM') /*get HOMEDRIVE location of \TEMP*/ -tmp =value('TEMP',,'SYSTEM') /* " TEMP directory name. */ -if homedrive=='' then homedrive='C:' /*use default if none found. */ -if tmp=='' then tmp=homedrive'\TEMP' /* " " " " " */ - /*code could be added here to get*/ - /*a unique name for the TEMP file*/ -tFN='SPEAK_IT'; tFT='$$$' /*use this for the TEMP's fileID.*/ -tFID=homedrive||'\TEMP\' || tFN"."tFT /*create temp name for the output*/ -call lineout tFID,t /*write text──►a temp output file*/ -call lineout tFID /*close the file just to be neat.*/ -'NIRCMD' "speak file" tFID /*NIRCMD invokes the MS Sam voice*/ -'ERASE' tfid /*clean up (delete) the TEMP file*/ - /*stick a fork in it, we're done.*/ +/*REXX program uses a C.L. command to invoke Windows SAM for speech synthesis.*/ +parse arg t; t=space(t) /*get the (optional) text from the C.L.*/ +if t=='' then signal done /*Nothing to say? Then exit program.*/ + +homedrive=value('HOMEDRIVE',,'SYSTEM') /*get HOMEDRIVE location of \TEMP */ +tmp =value('TEMP',,'SYSTEM') /* " TEMP directory name. */ +if homedrive=='' then homedrive='C:' /*use the default if none was found. */ +if tmp=='' then tmp=homedrive'\TEMP' /* " " " " " " " */ + /*code could be added here to get a ···*/ + /* ··· unique name for the TEMP file.*/ +tFN='SPEAK_IT'; tFT='$$$' /*use this name for the TEMP's fileID.*/ +tFID=homedrive||'\TEMP\' || tFN"."tFT /*create temporary name for the output.*/ +call lineout tFID,t /*write text ──► temporary output file.*/ +call lineout tFID /*close the output file just to be neat*/ +'NIRCMD' "speak file" tFID /*NIRCMD invokes Microsoft's Sam voice*/ +'ERASE' tFID /*clean up (delete) the TEMP file.*/ + +done: /*stick a fork in it, we're all done. */ diff --git a/Task/Spiral-matrix/DCL/spiral-matrix.dcl b/Task/Spiral-matrix/DCL/spiral-matrix.dcl new file mode 100644 index 0000000000..722aee2aac --- /dev/null +++ b/Task/Spiral-matrix/DCL/spiral-matrix.dcl @@ -0,0 +1,56 @@ +$ p1 = f$integer( p1 ) +$ max = p1 * p1 +$ +$ i = 0 +$ r = 1 +$ rd = 0 +$ c = 1 +$ cd = 1 +$ loop: +$ a'r'_'c' = i +$ nr = r + rd +$ nc = c + cd +$ if nr .eq. 0 .or. nc .eq. 0 .or. nr .gt. p1 .or. nc .gt. p1 .or. f$type( a'nr'_'nc' ) .nes. "" +$ then +$ gosub change_directions +$ endif +$ r = r + rd +$ c = c + cd +$ i = i + 1 +$ if i .lt. max then $ goto loop +$ length = f$length( f$string( max - 1 )) +$ r = 1 +$ loop2: +$ c = 1 +$ output = "" +$ loop3: +$ output = output + f$fao( "!#UL ", length, a'r'_'c' ) +$ c = c + 1 +$ if c .le. p1 then $ goto loop3 +$ write sys$output output +$ r = r + 1 +$ if r .le. p1 then $ goto loop2 +$ exit +$ +$ change_directions: +$ if rd .eq. 0 .and cd .eq. 1 +$ then +$ rd = 1 +$ cd = 0 +$ else +$ if rd .eq. 1 .and. cd .eq. 0 +$ then +$ rd = 0 +$ cd = -1 +$ else +$ if rd .eq. 0 .and. cd .eq. -1 +$ then +$ rd = -1 +$ cd = 0 +$ else +$ rd = 0 +$ cd = 1 +$ endif +$ endif +$ endif +$ return diff --git a/Task/Spiral-matrix/Elixir/spiral-matrix.elixir b/Task/Spiral-matrix/Elixir/spiral-matrix.elixir new file mode 100644 index 0000000000..5feb85aa20 --- /dev/null +++ b/Task/Spiral-matrix/Elixir/spiral-matrix.elixir @@ -0,0 +1,33 @@ +defmodule RC do + def spiral_matrix(n) do + right(n,n-1,0,[]) |> Enum.with_index |> Enum.sort |> Enum.with_index |> + Enum.each(fn {{_,x},i} -> + :io.format("~2w ", [x]) + if( rem(i+1,n)==0, do: IO.puts "") + end) + end + + def right(n,side,i,coordinates) do + coord = for j <- 0..side, do: {i, i+j} + down(n,side,i,coordinates++coord) + end + + def down(_,0,_,coordinates), do: coordinates + def down(n,side,i,coordinates) do + coord = for j <- 1..side, do: {i+j, n-1-i} + left(n,side-1,i,coordinates++coord) + end + + def left(n,side,i,coordinates) do + coord = for j <- 0..side, do: {n-1-i, i+side-j} + up(n,side,i,coordinates++coord) + end + + def up(_,0,_,coordinates), do: coordinates + def up(n,side,i,coordinates) do + coord = for j <- 1..side, do: {i+side-j+1, i} + right(n,side-1,i+1,coordinates++coord) + end +end + +RC.spiral_matrix(5) diff --git a/Task/Spiral-matrix/JavaScript/spiral-matrix.js b/Task/Spiral-matrix/JavaScript/spiral-matrix-1.js similarity index 100% rename from Task/Spiral-matrix/JavaScript/spiral-matrix.js rename to Task/Spiral-matrix/JavaScript/spiral-matrix-1.js diff --git a/Task/Spiral-matrix/JavaScript/spiral-matrix-2.js b/Task/Spiral-matrix/JavaScript/spiral-matrix-2.js new file mode 100644 index 0000000000..66de8c8ec8 --- /dev/null +++ b/Task/Spiral-matrix/JavaScript/spiral-matrix-2.js @@ -0,0 +1,55 @@ +(function (n) { + + // Spiral: the first row plus a smaller spiral rotated 90 degrees clockwise + function spiral(lngRows, lngCols, nStart) { + return lngRows ? [range(nStart, (nStart + lngCols) - 1)].concat( + transpose( + spiral(lngCols, lngRows - 1, nStart + lngCols) + ).map(reverse) + ) : [[]]; + } + + // rows and columns transposed (for 90 degree rotation) + function transpose(lst) { + return lst.length > 1 ? lst[0].map( + function (_, col) { + return lst.map(function (row) { + return row[col]; + }); + } + ) : lst; + } + + // elements in reverse order (for 90 degree rotation) + function reverse(lst) { + return lst.length > 1 ? lst.reduceRight( + function (acc, x) { + return acc.concat(x); + }, [] + ) : lst; + } + + // [m..n] + function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { + return m + i; + } + ); + } + + // Width of column for spaced display ? + var lngColWidth = ((n * n) - 1).toString().length + 2; + + // Numeric columns right-aligned + return spiral(n, n, 0).map(function (l) { + return l.reduce(function (a, x) { + var s = x.toString(); + + return a + Array( + lngColWidth - s.length + ).join(' ') + s; + }, ''); + }).join('\n') + +})(5); diff --git a/Task/Spiral-matrix/JavaScript/spiral-matrix-3.js b/Task/Spiral-matrix/JavaScript/spiral-matrix-3.js new file mode 100644 index 0000000000..02c1d15a4b --- /dev/null +++ b/Task/Spiral-matrix/JavaScript/spiral-matrix-3.js @@ -0,0 +1,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 diff --git a/Task/Spiral-matrix/Julia/spiral-matrix-1.julia b/Task/Spiral-matrix/Julia/spiral-matrix-1.julia new file mode 100644 index 0000000000..c1522b761e --- /dev/null +++ b/Task/Spiral-matrix/Julia/spiral-matrix-1.julia @@ -0,0 +1,43 @@ +immutable Spiral + m::Int + n::Int + cmax::Int + dir::Array{Array{Int,1},1} + bdelta::Array{Array{Int,1},1} +end + +function Spiral(m::Int, n::Int) + cmax = m*n + dir = Array{Int,1}[[0,1], [1,0], [0,-1], [-1,0]] + bdelta = Array{Int,1}[[0,0,0,1], [-1,0,0,0], + [0,-1,0,0], [0,0,1,0]] + Spiral(m, n, cmax, dir, bdelta) +end + +function spiral(m::Int, n::Int) + 0 sp.cmax + +function Base.next(sp::Spiral, sps::SpState) + s = sub2ind((sp.m, sp.n), sps.cell[1], sps.cell[2]) + if sps.cell[rem1(sps.dirdex+1, 2)] == sps.bounds[sps.dirdex] + sps.bounds += sp.bdelta[sps.dirdex] + sps.dirdex = rem1(sps.dirdex+1, 4) + end + sps.cell += sp.dir[sps.dirdex] + sps.cnt += 1 + return (s, sps) +end diff --git a/Task/Spiral-matrix/Julia/spiral-matrix-2.julia b/Task/Spiral-matrix/Julia/spiral-matrix-2.julia new file mode 100644 index 0000000000..de8b6dbdab --- /dev/null +++ b/Task/Spiral-matrix/Julia/spiral-matrix-2.julia @@ -0,0 +1,24 @@ +using Formatting + +function width{T<:Integer}(n::T) + w = ndigits(n) + n < 0 || return w + return w + 1 +end + +function pretty{T<:Integer}(a::Array{T,2}, indent::Int=4) + lo, hi = extrema(a) + w = max(width(lo), width(hi)) + id = " "^indent + fe = FormatExpr(@sprintf(" {:%dd}", w)) + s = id + nrow = size(a)[1] + for i in 1:nrow + for j in a[i,:] + s *= format(fe, j) + end + i != nrow || continue + s *= "\n"*id + end + return s +end diff --git a/Task/Spiral-matrix/Julia/spiral-matrix-3.julia b/Task/Spiral-matrix/Julia/spiral-matrix-3.julia new file mode 100644 index 0000000000..bc303febbe --- /dev/null +++ b/Task/Spiral-matrix/Julia/spiral-matrix-3.julia @@ -0,0 +1,26 @@ +n = 5 +println("The n = ", n, " spiral matrix:") +a = zeros(Int, (n, n)) +for (i, s) in enumerate(spiral(n)) + a[s] = i-1 +end +println(pretty(a)) + +m = 3 +println() +println("Generalize to a non-square matrix (", m, "x", n, "):") +a = zeros(Int, (m, n)) +for (i, s) in enumerate(spiral(m, n)) + a[s] = i-1 +end +println(pretty(a)) + +p = primes(10^3) +n = 7 +println() +println("An n = ", n, " prime spiral matrix:") +a = zeros(Int, (n, n)) +for (i, s) in enumerate(spiral(n)) + a[s] = p[i] +end +println(pretty(a)) diff --git a/Task/Spiral-matrix/Ruby/spiral-matrix-3.rb b/Task/Spiral-matrix/Ruby/spiral-matrix-3.rb new file mode 100644 index 0000000000..f5066cc67d --- /dev/null +++ b/Task/Spiral-matrix/Ruby/spiral-matrix-3.rb @@ -0,0 +1,10 @@ +def spiral_matrix(n) + x, y, dx, dy = -1, 0, 0, -1 + fmt = "%#{(n*n-1).to_s.size}d " * n + n.downto(1).flat_map{|x| [x, x-1]}.flat_map{|run| + dx, dy = -dy, dx # turn 90 + run.times.map { [y+=dy, x+=dx] } + }.each_with_index.sort.map(&:last).each_slice(n){|row| puts fmt % row} +end + +spiral_matrix(5) diff --git a/Task/Spiral-matrix/VBScript/spiral-matrix.vb b/Task/Spiral-matrix/VBScript/spiral-matrix.vb new file mode 100644 index 0000000000..742971e351 --- /dev/null +++ b/Task/Spiral-matrix/VBScript/spiral-matrix.vb @@ -0,0 +1,47 @@ +Function build_spiral(n) + botcol = 0 : topcol = n - 1 + botrow = 0 : toprow = n - 1 + 'declare a two dimensional array + Dim matrix() + ReDim matrix(topcol,toprow) + dir = 0 : col = 0 : row = 0 + 'populate the array + For i = 0 To n*n-1 + matrix(col,row) = i + Select Case dir + Case 0 + If col < topcol Then + col = col + 1 + Else + dir = 1 : row = row + 1 : botrow = botrow + 1 + End If + Case 1 + If row < toprow Then + row = row + 1 + Else + dir = 2 : col = col - 1 : topcol = topcol - 1 + End If + Case 2 + If col > botcol Then + col = col - 1 + Else + dir = 3 : row = row - 1 : toprow = toprow - 1 + End If + Case 3 + If row > botrow Then + row = row - 1 + Else + dir = 0 : col = col + 1 : botcol = botcol + 1 + End If + End Select + Next + 'print the array + For y = 0 To n-1 + For x = 0 To n-1 + WScript.StdOut.Write matrix(x,y) & vbTab + Next + WScript.StdOut.WriteLine + Next +End Function + +build_spiral(CInt(WScript.Arguments(0))) diff --git a/Task/Stable-marriage-problem/00DESCRIPTION b/Task/Stable-marriage-problem/00DESCRIPTION index 4326c48945..28d111a6ba 100644 --- a/Task/Stable-marriage-problem/00DESCRIPTION +++ b/Task/Stable-marriage-problem/00DESCRIPTION @@ -45,3 +45,4 @@ And a complete list of ranked preferences, where the most liked is to the left: # [http://mathsite.math.berkeley.edu/smp/smp.html Another Gale-Shapley Algorithm Demonstration]. # [https://www.youtube.com/watch?v=Qcv1IqHWAzg Stable Marriage Problem - Numberphile] (Video). # [https://www.youtube.com/watch?v=LtTV6rIxhdo Stable Marriage Problem (the math bit)] (Video). +# [http://www.ams.org/samplings/feature-column/fc-2015-03 The Stable Marriage Problem and School Choice]. (Excellent exposition) diff --git a/Task/Stable-marriage-problem/Batch-File/stable-marriage-problem.bat b/Task/Stable-marriage-problem/Batch-File/stable-marriage-problem.bat new file mode 100644 index 0000000000..ade89857dc --- /dev/null +++ b/Task/Stable-marriage-problem/Batch-File/stable-marriage-problem.bat @@ -0,0 +1,139 @@ +@echo off +setlocal enabledelayedexpansion + + %== Initialization ==% +set "male= abe bob col dan ed fred gav hal ian jon" ::First whitespace is necessary +set "female= abi bea cath dee eve fay gay hope ivy jan" ::same here... + + ::Initialization of pseudo-arrays [Male] +set "cnt=0" & for %%. in (abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay) do (set abe[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay) do (set bob[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan) do (set col[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi) do (set dan[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay) do (set ed[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay) do (set fred[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay) do (set gav[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee) do (set hal[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve) do (set ian[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope) do (set jon[!cnt!]=%%.&set /a cnt+=1) + + ::Initialization of pseudo-arrays [Female] +set "cnt=0" & for %%. in (bob, fred, jon, gav, ian, abe, dan, ed, col, hal) do (set abi[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (bob, abe, col, fred, gav, dan, ian, ed, jon, hal) do (set bea[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (fred, bob, ed, gav, hal, col, ian, abe, dan, jon) do (set cath[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (fred, jon, col, abe, ian, hal, gav, dan, bob, ed) do (set dee[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (jon, hal, fred, dan, abe, gav, col, ed, ian, bob) do (set eve[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (bob, abe, ed, ian, jon, dan, fred, gav, col, hal) do (set fay[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (jon, gav, hal, fred, bob, abe, col, ed, dan, ian) do (set gay[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (gav, jon, bob, abe, ian, dan, hal, ed, col, fred) do (set hope[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (ian, col, hal, gav, fred, bob, abe, ed, jon, dan) do (set ivy[!cnt!]=%%.&set /a cnt+=1) +set "cnt=0" & for %%. in (ed, hal, gav, abe, bob, jon, col, ian, fred, dan) do (set jan[!cnt!]=%%.&set /a cnt+=1) + %==/Initialization ==% + +( %== The main thing ==% +echo.HISTORY: +call :stableMatching +echo. +echo.NEWLYWEDS: +call :display +echo. +call :isStable +echo. +echo.What if ed and hal swapped? +call :swapper ed hal +echo. +echo.NEW-NEWLYWEDS: +call :display +echo. +call :isStable +pause>nul +exit /b 0 +) %==/The main thing ==% + + %== The algorithm ==% +:stableMatching + set "free_men=%male%" ::The free-men variable + set "free_women=%female%" ::The free-women variable + set nextgirl=0 +:thematchloop + set m=&for %%F in (!free_men!) do (if not defined m set "m=%%F") + if "!m!"=="" goto :EOF + + for /f "tokens=1-2 delims==" %%A in ('set !m![!nextgirl!]') do set "w=%%B" + set "propo=" + for %%W in (!free_women!) do ( + if "%%W"=="!w!" ( + set propo=TRUE + set "!w!_=!m!" & set "!m!_=!w!" + set free_women=!free_women: %w%=! + set free_men=!free_men: %m%=! + echo. !w! ACCEPTED !m!. + ) + ) + if defined propo (set "nextgirl=0" & goto thematchloop) + + for /f "tokens=1-2 delims==" %%A in ('set !w!_') do set "mbef=%%B" + set "replace=" & for /f "tokens=1-2 delims==" %%R in ('set !w![') do ( + if not defined replace ( + if "%%S"=="!m!" ( + set replace=TRUE + set "!w!_=!m!" & set "!m!_=!w!" + set "free_men=!free_men! !mbef!" + set "free_men=!free_men: %m%=!" + set nextgirl=0 + echo. !w! LEFT !mbef!. + echo. !w! ACCEPTED !m!. + ) + if "%%S"=="!mbef!" ( + set /a nextgirl+=1 + set replace=FALSE + ) + ) + ) +goto thematchloop + %==/The Algorithm ==% + + %== Output the Couples ==% +:display +for %%S in (!male!) do echo. %%S and !%%S_!. +goto :EOF + %==/Output the Couples ==% + + %== Stability Checking ==% +:isStable +for %%M in (!female!) do ( + set "better=" + set "dislike=" & for /f "tokens=1-2 delims==" %%R in ('set %%M[') do ( + if not defined dislike ( + if "%%S"=="!%%M_!" (set dislike=T) else (set "better=!better! %%S") + ) + ) + for %%X in (!better!) do ( + for /f "tokens=1-2 delims==" %%F in ('set %%X_') do set curr_partner_of_boy=%%G + set "main_check=" + for /f "tokens=1-2 delims==" %%B in ('set %%X[') do ( + if not defined main_check ( + if "%%C"=="%%M" ( + echo.STABILITY = FALSE. + echo %%M and %%X would rather be together than their current partners. + goto :EOF + ) + if "%%C"=="!curr_partner_of_boy!" set "main_check=CONTINUE" + ) + ) + ) +) +echo.STABILITY = TRUE. +goto :EOF + %==/Stability Chacking ==% + + %== Swapper ==% +:swapper + set %~1.tmp=!%~1_! + set %~2.tmp=!%~2_! + set "%~1_=!%~2.tmp!" + set "%~2_=!%~1.tmp!" + set "!%~1.tmp!_=%~2" + set "!%~2.tmp!_=%~1" + goto :EOF + %==/Swapper==% diff --git a/Task/Stable-marriage-problem/Lua/stable-marriage-problem.lua b/Task/Stable-marriage-problem/Lua/stable-marriage-problem.lua index a4fbe45a2a..89974d3c2a 100644 --- a/Task/Stable-marriage-problem/Lua/stable-marriage-problem.lua +++ b/Task/Stable-marriage-problem/Lua/stable-marriage-problem.lua @@ -1,106 +1,128 @@ -local men = -{ -abe={'abi','eve','cath','ivy','jan','dee','fay','bea','hope','gay'}, -bob={'cath','hope','abi','dee','eve','fay','bea','jan','ivy','gay'}, -col={'hope','eve','abi','dee','bea','fay','ivy','gay','cath','jan'}, -dan={'ivy','fay','dee','gay','hope','eve','jan','bea','cath','abi'}, -ed={'jan','dee','bea','cath','fay','eve','abi','ivy','hope','gay'}, -fred={'bea','abi','dee','gay','eve','ivy','cath','jan','hope','fay'}, -gav={'gay','eve','ivy','bea','cath','abi','dee','hope','jan','fay'}, -hal={'abi','eve','hope','fay','ivy','cath','jan','bea','gay','dee'}, -ian={'hope','cath','dee','gay','bea','abi','fay','ivy','jan','eve'}, -jon={'abi','fay','jan','gay','eve','bea','dee','cath','ivy','hope'} -} - -local women = -{ -abi={'bob','fred','jon','gav','ian','abe','dan','ed','col','hal'}, -bea={'bob','abe','col','fred','gav','dan','ian','ed','jon','hal'}, -cath={'fred','bob','ed','gav','hal','col','ian','abe','dan','jon'}, -dee={'fred','jon','col','abe','ian','hal','gav','dan','bob','ed'}, -eve={'jon','hal','fred','dan','abe','gav','col','ed','ian','bob'}, -fay={'bob','abe','ed','ian','jon','dan','fred','gav','col','hal'}, -gay={'jon','gav','hal','fred','bob','abe','col','ed','dan','ian'}, -hope={'gav','jon','bob','abe','ian','dan','hal','ed','col','fred'}, -ivy={'ian','col','hal','gav','fred','bob','abe','ed','jon','dan'} -} - -local engagements = {} - -local singlemen = 0 - -local function single(name) - - local partner = engagements[name] - - if partner then - engagements[name] = nil - engagements[partner] = nil - end - - - if men[name] then - singlemen = singlemen + 1 - end +local Person = {} +Person.__index = Person + +function Person.new(inName) + local o = { + name = inName, + prefs = nil, + fiance = nil, + _candidateIndex = 1, + } + return setmetatable(o, Person) end -for guys,_ in pairs(men) do single(guys) end -for ladies,_ in pairs(women) do single(ladies) end --that is, ahem, ALL the single ladies. - - -local function engage(man,woman) - engagements[man] = woman - engagements[woman] = man - singlemen = singlemen - 1 +function Person:indexOf(other) + for i, p in pairs(self.prefs) do + if p == other then return i end + end + return 999 end - -local attemptedEngagementsByMan = {} -for name,list in pairs(men) do - attemptedEngagementsByMan[name] = {} +function Person:prefers(other) + return self:indexOf(other) < self:indexOf(self.fiance) end +function Person:nextCandidateNotYetProposedTo() + if self._candidateIndex >= #self.prefs then return nil end + local c = self.prefs[self._candidateIndex]; + self._candidateIndex = self._candidateIndex + 1 + return c; +end -while singlemen > 0 do - local man - local woman - - --get a single man - for singleman,prefs in pairs(men) do - if not engagements[singleman] then - man = singleman; break +function Person:engageTo(other) + if other.fiance then + other.fiance.fiance = nil end - end - - - --get his most preferred untried lady - local myAttempts = attemptedEngagementsByMan[man] - for i,lady in ipairs(men[man]) do - if not myAttempts[lady] then - woman = lady; break + other.fiance = self + if self.fiance then + self.fiance.fiance = nil end - end + self.fiance = other; +end +local function isStable(men) + local women = men[1].prefs + local stable = true + for _, guy in pairs(men) do + for _, gal in pairs(women) do + if guy:prefers(gal) and gal:prefers(guy) then + stable = false + print(guy.name .. ' and ' .. gal.name .. + ' prefer each other over their partners ' .. + guy.fiance.name .. ' and ' .. gal.fiance.name) + end + end + end + return stable +end - --propose - myAttempts[woman] = true - local totalJerk = engagements[woman] - if not totalJerk then - engage(man,woman) - else - for i,herPreference in ipairs(women[woman]) do - if herPreference == man then - single(totalJerk) - single(woman) - engage(man,woman) - break --leaves the jerk at the altar! - elseif herPreference == totalJerk then - break --shot down - end +local abe = Person.new("Abe") +local bob = Person.new("Bob") +local col = Person.new("Col") +local dan = Person.new("Dan") +local ed = Person.new("Ed") +local fred = Person.new("Fred") +local gav = Person.new("Gav") +local hal = Person.new("Hal") +local ian = Person.new("Ian") +local jon = Person.new("Jon") + +local abi = Person.new("Abi") +local bea = Person.new("Bea") +local cath = Person.new("Cath") +local dee = Person.new("Dee") +local eve = Person.new("Eve") +local fay = Person.new("Fay") +local gay = Person.new("Gay") +local hope = Person.new("Hope") +local ivy = Person.new("Ivy") +local jan = Person.new("Jan") + +abe.prefs = { abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay } +bob.prefs = { cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay } +col.prefs = { hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan } +dan.prefs = { ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi } +ed.prefs = { jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay } +fred.prefs = { bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay } +gav.prefs = { gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay } +hal.prefs = { abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee } +ian.prefs = { hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve } +jon.prefs = { abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope } + +abi.prefs = { bob, fred, jon, gav, ian, abe, dan, ed, col, hal } +bea.prefs = { bob, abe, col, fred, gav, dan, ian, ed, jon, hal } +cath.prefs = { fred, bob, ed, gav, hal, col, ian, abe, dan, jon } +dee.prefs = { fred, jon, col, abe, ian, hal, gav, dan, bob, ed } +eve.prefs = { jon, hal, fred, dan, abe, gav, col, ed, ian, bob } +fay.prefs = { bob, abe, ed, ian, jon, dan, fred, gav, col, hal } +gay.prefs = { jon, gav, hal, fred, bob, abe, col, ed, dan, ian } +hope.prefs = { gav, jon, bob, abe, ian, dan, hal, ed, col, fred } +ivy.prefs = { ian, col, hal, gav, fred, bob, abe, ed, jon, dan } +jan.prefs = { ed, hal, gav, abe, bob, jon, col, ian, fred, dan } + +local men = abi.prefs +local freeMenCount = #men +while freeMenCount > 0 do + for _, guy in pairs(men) do + if not guy.fiance then + local gal = guy:nextCandidateNotYetProposedTo() + if not gal.fiance then + guy:engageTo(gal) + freeMenCount = freeMenCount - 1 + elseif gal:prefers(guy) then + guy:engageTo(gal) + end + end end - end end -for name,_ in pairs(men) do - print(name, " liked it so he put a ring on ", engagements[name]) +print(' ') +for _, guy in pairs(men) do + print(guy.name .. ' is engaged to ' .. guy.fiance.name) end +print('Stable: ', isStable(men)) + +print(' ') +print('Switching ' .. fred.name .. "'s & " .. jon.name .. "'s partners") +jon.fiance, fred.fiance = fred.fiance, jon.fiance +print('Stable: ', isStable(men)) diff --git a/Task/Stack-traces/Ada/stack-traces.ada b/Task/Stack-traces/Ada/stack-traces.ada index 11d46e94b1..a80d4a1852 100644 --- a/Task/Stack-traces/Ada/stack-traces.ada +++ b/Task/Stack-traces/Ada/stack-traces.ada @@ -1,14 +1,14 @@ -with Ada.Text_IO; use Ada.Text_IO; -with GNAT.Traceback; use GNAT.Traceback; -with GNAT.Traceback.Symbolic; use GNAT.Traceback.Symbolic; +with Ada.Text_IO; use Ada.Text_IO; +with GNAT.Traceback; +with GNAT.Traceback.Symbolic; procedure Test_Stack_Trace is procedure Call_Stack is - Trace : Tracebacks_Array (1..1_000); + Trace : GNAT.Traceback.Tracebacks_Array (1..1_000); Length : Natural; begin - Call_Chain (Trace, Length); - Put_Line (Symbolic_Traceback (Trace (1..Length))); + GNAT.Traceback.Call_Chain (Trace, Length); + Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (Trace (1..Length))); end Call_Stack; procedure Inner (K : Integer) is diff --git a/Task/Stack/ALGOL-68/stack-5.alg b/Task/Stack/ALGOL-68/stack-5.alg new file mode 100644 index 0000000000..a43706f9d3 --- /dev/null +++ b/Task/Stack/ALGOL-68/stack-5.alg @@ -0,0 +1,45 @@ +MODE DIETITEM = STRUCT ( + STRING food, annual quantity, units, REAL cost +); + +MODE OBJVALUE = DIETITEM; + +# PUSH element to stack # +OP +:= = (REF FLEX[]OBJVALUE stack, OBJVALUE item) VOID: + BEGIN + FLEX[UPB stack + 1]OBJVALUE newstack; + newstack[2:UPB newstack] := stack; + newstack[1] := item; + stack := newstack + END; + +OP POP = (REF FLEX[]OBJVALUE stack) OBJVALUE: + IF UPB stack > 0 THEN + OBJVALUE result = stack[1]; + stack := stack[2:UPB stack]; + result + ELSE + # raise index error; # SKIP + FI; + +# Stigler's 1939 Diet ... # +FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$; +[]DIETITEM stigler diet = ( + ("Cabbage", "111","lb.", 4.11), + ("Dried Navy Beans", "285","lb.", 16.80), + ("Evaporated Milk", "57","cans", 3.84), + ("Spinach", "23","lb.", 1.85), + ("Wheat Flour", "370","lb.", 13.33), + ("Total Annual Cost", "","", 39.93) +); + +FLEX[0]DIETITEM example stack; + +FOR i TO UPB stigler diet DO + example stack +:= stigler diet[i] +OD; + +printf($"Items popped in reverse:"l$); +WHILE UPB example stack > 0 DO + printf((diet item fmt, POP example stack, $l$)) +OD diff --git a/Task/Stack/Elixir/stack.elixir b/Task/Stack/Elixir/stack.elixir new file mode 100644 index 0000000000..13f3344f47 --- /dev/null +++ b/Task/Stack/Elixir/stack.elixir @@ -0,0 +1,12 @@ +defmodule Stack do + def new, do: [] + + def empty?([]), do: true + def empty?(_), do: false + + def pop([h|t]), do: {h,t} + + def push(h,t), do: [h|t] + + def top([h|_]), do: h +end diff --git a/Task/Stack/Ruby/stack-2.rb b/Task/Stack/Ruby/stack-2.rb index e97db478a9..d1156d8f8a 100644 --- a/Task/Stack/Ruby/stack-2.rb +++ b/Task/Stack/Ruby/stack-2.rb @@ -41,25 +41,15 @@ def push(*objects) # If passing a number _n_, removes the top _n_ elements, and returns # an Array of them. If this Stack contains fewer than _n_ elements, # returns them all. If this Stack is empty, returns an empty Array. - nil + def_delegator :@ary, :pop - if ([].pop(0) rescue false) - # Ruby >= 1.8.7 - def_delegator :@ary, :pop - else - # Ruby < 1.8.7 - def pop(*args) # :nodoc: - case len = args.length - when 0 - @ary.pop - when 1 - n = [@ary.length, args.first].min - @ary.slice!(-n, n) - else - raise ArgumentError, "wrong number of arguments (#{len} for 0..1)" - end - end - end + ## + # :method: top + # :call-seq: + # top -> obj or nil + # top(n) -> ary + # Returns the topmost element without modifying the stack. + def_delegator :@ary, :last, :top ## # :method: empty? diff --git a/Task/Stack/Ruby/stack-3.rb b/Task/Stack/Ruby/stack-3.rb index 06634e1a75..502bda0d05 100644 --- a/Task/Stack/Ruby/stack-3.rb +++ b/Task/Stack/Ruby/stack-3.rb @@ -1,12 +1,19 @@ -s = Stack.new -s.empty? # => true -s.pop # => nil -s.pop(1) # => [] -s.push(1) # => Stack[1] -s.push(2, 3) # => Stack[1, 2, 3] -s.pop # => 3 -s.pop(1) # => [2] -s.empty? # => false +p s = Stack.new # => Stack[] +p s.empty? # => true +p s.size # => 0 +p s.top # => nil +p s.pop # => nil +p s.pop(1) # => [] +p s.push(1) # => Stack[1] +p s.push(2, 3) # => Stack[1, 2, 3] +p s.top # => 3 +p s.top(2) # => [2, 3] +p s # => Stack[1, 2, 3] +p s.size # => 3 +p s.pop # => 3 +p s.pop(1) # => [2] +p s.empty? # => false -s = Stack[:a, :b, :c] -s.pop # => :c +p s = Stack[:a, :b, :c] # => Stack[:a, :b, :c] +p s << :d # => Stack[:a, :b, :c, :d] +p s.pop # => :d diff --git a/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle.lua b/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle.lua new file mode 100644 index 0000000000..e32ddcc7d4 --- /dev/null +++ b/Task/Stair-climbing-puzzle/Lua/stair-climbing-puzzle.lua @@ -0,0 +1,3 @@ +function step_up() + while not step() do step_up() end +end diff --git a/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx b/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx index 5f61341680..f7fa7345d7 100644 --- a/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx +++ b/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx @@ -1,6 +1,2 @@ -step_up: do while \step() - call step_up - end +step_up: do while \step(); call step_up; end return - -step: return random(0,1) /*randomly step up or fail to step up.*/ diff --git a/Task/Stair-climbing-puzzle/Run-BASIC/stair-climbing-puzzle.run b/Task/Stair-climbing-puzzle/Run-BASIC/stair-climbing-puzzle.run new file mode 100644 index 0000000000..977ba13f1e --- /dev/null +++ b/Task/Stair-climbing-puzzle/Run-BASIC/stair-climbing-puzzle.run @@ -0,0 +1,12 @@ +result = stepUp() + +Function stepUp() + While Not(stepp()) + result = stepUp() + Wend +End Function + +Function stepp() + stepp = int((Rnd(1) * 2)) + print "Robot stepped "+word$("up down",stepp+1) +End Function diff --git a/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg b/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg index 1aaff5438d..630300ee2c 100644 --- a/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg +++ b/Task/Standard-deviation/ALGOL-68/standard-deviation-1.alg @@ -45,8 +45,8 @@ main: LONG REAL sd; FOR i FROM LWB v TO UPB v DO - sd := stat object(v[i], LOC VALUE) - OD; + sd := stat object(v[i], LOC VALUE); + printf(($"value: "g(0,6)," standard dev := "g(0,6)l$, v[i], sd)) + OD - printf(($"standard dev := "g(0,6)l$, sd)) ) diff --git a/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg b/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg index 55561bfc45..d38ca7fad1 100644 --- a/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg +++ b/Task/Standard-deviation/ALGOL-68/standard-deviation-2.alg @@ -55,16 +55,21 @@ init OF class stat := (REF STAT self)REF STAT:( main: ( - printf(($"standard deviation operator = "g(0,6)l$, STDDEV value)); +# printf(($"standard deviation operator = "g(0,6)l$, STDDEV value)); +# REF STAT stat = INIT LOC STAT; FOR i FROM LWB value TO UPB value DO - stat +:= value[i] - OD; - + stat +:= value[i]; + printf(($"value: "g(0,6)," standard dev := "g(0,6)l$, value[i], (stddev OF class stat)(stat))) + OD +# +; printf(($"standard deviation = "g(0,6)l$, (stddev OF class stat)(stat))); printf(($"mean = "g(0,6)l$, (mean OF class stat)(stat))); printf(($"variance = "g(0,6)l$, (variance OF class stat)(stat))); printf(($"count = "g(0,6)l$, (count OF class stat)(stat))) +# + ) diff --git a/Task/Standard-deviation/ALGOL-W/standard-deviation.alg b/Task/Standard-deviation/ALGOL-W/standard-deviation.alg new file mode 100644 index 0000000000..09be0596dc --- /dev/null +++ b/Task/Standard-deviation/ALGOL-W/standard-deviation.alg @@ -0,0 +1,25 @@ +begin + + long real sum, sum2; + integer n; + + long real procedure sd (long real value x) ; + begin + sum := sum + x; + sum2 := sum2 + (x*x); + n := n + 1; + if n = 0 then 0 else longsqrt(sum2/n - sum*sum/n/n) + end sd; + + sum := sum2 := n := 0; + + r_format := "A"; r_w := 14; r_d := 6; % set output to fixed point format % + + for i := 2,4,4,4,5,5,7,9 + do begin + long real val; + val := i; + write(val, sd(val)) + end for_i + +end. diff --git a/Task/Standard-deviation/Ada/standard-deviation.ada b/Task/Standard-deviation/Ada/standard-deviation.ada index 25a924438a..b6b91eb78e 100644 --- a/Task/Standard-deviation/Ada/standard-deviation.ada +++ b/Task/Standard-deviation/Ada/standard-deviation.ada @@ -1,28 +1,35 @@ with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; +with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions; with Ada.Text_IO; use Ada.Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; procedure Test_Deviation is type Sample is record - N : Natural := 0; - Mean : Float := 0.0; - Squares : Float := 0.0; + N : Natural := 0; + Sum : Float := 0.0; + SumOfSquares : Float := 0.0; end record; procedure Add (Data : in out Sample; Point : Float) is begin Data.N := Data.N + 1; - Data.Mean := Data.Mean + Point; - Data.Squares := Data.Squares + Point ** 2; + Data.Sum := Data.Sum + Point; + Data.SumOfSquares := Data.SumOfSquares + Point ** 2; end Add; function Deviation (Data : Sample) return Float is begin - return Sqrt (Data.Squares / Float (Data.N) - (Data.Mean / Float (Data.N)) ** 2); + return Sqrt (Data.SumOfSquares / Float (Data.N) - (Data.Sum / Float (Data.N)) ** 2); end Deviation; Data : Sample; - Test : array (1..8) of Float := (2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0); + Test : array (1..8) of Integer := (2, 4, 4, 4, 5, 5, 7, 9); begin - for Item in Test'Range loop - Add (Data, Test (Item)); + for Index in Test'Range loop + Add (Data, Float(Test(Index))); + Put("N="); Put(Item => Index, Width => 1); + Put(" ITEM="); Put(Item => Test(Index), Width => 1); + Put(" AVG="); Put(Item => Float(Data.Sum)/Float(Index), Fore => 1, Aft => 3, Exp => 0); + Put(" STDDEV="); Put(Item => Deviation (Data), Fore => 1, Aft => 3, Exp => 0); + New_line; end loop; - Put_Line ("Deviation" & Float'Image (Deviation (Data))); end Test_Deviation; diff --git a/Task/Standard-deviation/C++/standard-deviation.cpp b/Task/Standard-deviation/C++/standard-deviation.cpp index 03bd5512cb..d66a4e51cd 100644 --- a/Task/Standard-deviation/C++/standard-deviation.cpp +++ b/Task/Standard-deviation/C++/standard-deviation.cpp @@ -1,25 +1,39 @@ -#include -#include -#include +#include #include #include -#include -#include +#include + +template struct MomentsAccumulator_ +{ + std::vector m_; + MomentsAccumulator_() : m_(N + 1, 0.0) {} + void operator()(double v) + { + double inc = 1.0; + for (auto& mi : m_) + { + mi += inc; + inc *= v; + } + } +}; -template -double standard_dev( Iterator begin , Iterator end ) { - double mean = std::accumulate( begin , end , 0 ) / std::distance( begin , end ) ; - std::vector squares ; - for( Iterator vdi = begin ; vdi != end ; vdi++ ) - squares.push_back( std::pow( *vdi - mean , 2 ) ) ; - return std::sqrt( std::accumulate( squares.begin( ) , squares.end( ) , 0 ) / squares.size( ) ) ; +double Stdev(const std::vector& moments) +{ + assert(moments.size() > 2); + assert(moments[0] > 0.0); + const double mean = moments[1] / moments[0]; + const double meanSquare = moments[2] / moments[0]; + return sqrt(meanSquare - mean * mean); } -int main( ) { - double demoset[] = { 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 } ; - int demosize = sizeof demoset / sizeof *demoset ; - std::cout << "The standard deviation of\n" ; - std::copy( demoset , demoset + demosize , std::ostream_iterator( std::cout, " " ) ) ; - std::cout << "\nis " << standard_dev( demoset , demoset + demosize ) << " !\n" ; - return 0 ; +int main(void) +{ + std::vector data({ 2, 4, 4, 4, 5, 5, 7, 9 }); + MomentsAccumulator_<2> accum; + for (auto d : data) + { + accum(d); + std::cout << "Running stdev: " << Stdev(accum.m_) << "\n"; + } } diff --git a/Task/Standard-deviation/COBOL/standard-deviation-1.cobol b/Task/Standard-deviation/COBOL/standard-deviation-1.cobol index 7298ace86a..88dbe30c94 100644 --- a/Task/Standard-deviation/COBOL/standard-deviation-1.cobol +++ b/Task/Standard-deviation/COBOL/standard-deviation-1.cobol @@ -1 +1,71 @@ -FUNCTION STANDARD-DEVIATION(2, 4, 4, 4, 5, 5, 7, 9) +IDENTIFICATION DIVISION. +PROGRAM-ID. run-stddev. +environment division. +input-output section. +file-control. + select input-file assign to "input.txt" + organization is line sequential. +data division. +file section. +fd input-file. + 01 inp-record. + 03 inp-fld pic 9(03). +working-storage section. +01 filler pic 9(01) value 0. + 88 no-more-input value 1. +01 ws-tb-data. + 03 ws-tb-size pic 9(03). + 03 ws-tb-table. + 05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times + depending on ws-tb-size. +01 ws-stddev pic s9(05)v9999 comp-3. +PROCEDURE DIVISION. + move 0 to ws-tb-size + open input input-file + read input-file + at end + set no-more-input to true + end-read + perform + test after + until no-more-input + add 1 to ws-tb-size + move inp-fld to ws-tb-fld (ws-tb-size) + call 'stddev' using by reference ws-tb-data + ws-stddev + display 'inp=' inp-fld ' stddev=' ws-stddev + read input-file at end set no-more-input to true end-read + end-perform + close input-file + stop run. +end program run-stddev. +IDENTIFICATION DIVISION. +PROGRAM-ID. stddev. +data division. +working-storage section. +01 ws-tbx pic s9(03) comp. +01 ws-tb-work. + 03 ws-sum pic s9(05)v9999 comp-3 value +0. + 03 ws-sumsq pic s9(05)v9999 comp-3 value +0. + 03 ws-avg pic s9(05)v9999 comp-3 value +0. +linkage section. +01 ws-tb-data. + 03 ws-tb-size pic 9(03). + 03 ws-tb-table. + 05 ws-tb-fld pic s9(05)v9999 comp-3 occurs 0 to 100 times + depending on ws-tb-size. +01 ws-stddev pic s9(05)v9999 comp-3. +PROCEDURE DIVISION using ws-tb-data ws-stddev. + compute ws-sum = 0 + perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size + compute ws-sum = ws-sum + ws-tb-fld (ws-tbx) + end-perform + compute ws-avg rounded = ws-sum / ws-tb-size + compute ws-sumsq = 0 + perform test before varying ws-tbx from 1 by +1 until ws-tbx > ws-tb-size + compute ws-sumsq = ws-sumsq + + (ws-tb-fld (ws-tbx) - ws-avg) ** 2.0 + end-perform + compute ws-stddev = ( ws-sumsq / ws-tb-size) ** 0.5 + goback. +end program stddev. diff --git a/Task/Standard-deviation/COBOL/standard-deviation-2.cobol b/Task/Standard-deviation/COBOL/standard-deviation-2.cobol index 53e193c268..b52f8d5aaf 100644 --- a/Task/Standard-deviation/COBOL/standard-deviation-2.cobol +++ b/Task/Standard-deviation/COBOL/standard-deviation-2.cobol @@ -1 +1,9 @@ -FUNCTION SQRT(FUNCTION VARIANCE(2, 4, 4, 4, 5, 5, 7, 9)) +sample output: +inp=002 stddev=+00000.0000 +inp=004 stddev=+00001.0000 +inp=004 stddev=+00000.9427 +inp=004 stddev=+00000.8660 +inp=005 stddev=+00000.9797 +inp=005 stddev=+00001.0000 +inp=007 stddev=+00001.3996 +inp=009 stddev=+00002.0000 diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp index 21246166ae..a94734f8b8 100644 --- a/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp +++ b/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp @@ -1,7 +1,17 @@ -(defun std-dev (samples) - (let* ((n (length samples)) - (mean (/ (reduce #'+ samples) n)) - (tmp (mapcar (lambda (x) (expt (- x mean) 2)) samples))) - (sqrt (/ (reduce #'+ tmp) n)))) +(defun running-stddev () + (let ((sum 0) (sq 0) (n 0)) + (lambda (x) + (incf sum x) (incf sq (* x x)) (incf n) + (/ (sqrt (- (* n sq) (* sum sum))) n)))) -(format t "~a" (std-dev '(2 4 4 4 5 5 7 9))) +CL-USER> (loop with f = (running-stddev) for i in '(2 4 4 4 5 5 7 9) do + (format t "~a ~a~%" i (funcall f i))) +NIL +2 0.0 +4 1.0 +4 0.94280905 +4 0.8660254 +5 0.97979593 +5 1.0 +7 1.3997085 +9 2.0 diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp index 5e7339b6af..918d5931c6 100644 --- a/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp +++ b/Task/Standard-deviation/Common-Lisp/standard-deviation-2.lisp @@ -1,16 +1,18 @@ -(defun arithmetic-average (samples) - (/ (reduce #'+ samples) - (length samples))) - -(defun standard-deviation (samples) - (let ((mean (arithmetic-average samples))) - (sqrt (* (/ 1.0d0 (length samples)) - (reduce #'+ samples - :key (lambda (x) - (expt (- x mean) 2))))))) - -(defun make-deviator () - (let ((numbers '())) - (lambda (x) - (push x numbers) - (standard-deviation numbers)))) +CL-USER> (setf fn (running-stddev)) +# +CL-USER> (funcall fn 2) +0.0 +CL-USER> (funcall fn 4) +1.0 +CL-USER> (funcall fn 4) +0.94280905 +CL-USER> (funcall fn 4) +0.8660254 +CL-USER> (funcall fn 5) +0.97979593 +CL-USER> (funcall fn 5) +1.0 +CL-USER> (funcall fn 7) +1.3997085 +CL-USER> (funcall fn 9) +2.0 diff --git a/Task/Standard-deviation/Emacs-Lisp/standard-deviation-3.l b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-3.l new file mode 100644 index 0000000000..2e9bff1108 --- /dev/null +++ b/Task/Standard-deviation/Emacs-Lisp/standard-deviation-3.l @@ -0,0 +1,2 @@ +(setq x '[2 4 4 4 5 5 7 9]) +(string-to-number (calc-eval (format "sqrt(vpvar(%s))" x))) diff --git a/Task/Standard-deviation/Forth/standard-deviation-1.fth b/Task/Standard-deviation/Forth/standard-deviation-1.fth index 27be9b2ff5..9cf9aa2954 100644 --- a/Task/Standard-deviation/Forth/standard-deviation-1.fth +++ b/Task/Standard-deviation/Forth/standard-deviation-1.fth @@ -4,11 +4,6 @@ : st-sum ( stats -- sum ) float+ f@ ; : st-sumsq ( stats -- sum*sum ) 2 floats + f@ ; -: st-add ( fnum stats -- ) - 1e dup f+! float+ - fdup dup f+! float+ - fdup f* f+! ; - : st-mean ( stats -- mean ) dup st-sum st-count f/ ; @@ -19,3 +14,10 @@ : st-stddev ( stats -- stddev ) st-variance fsqrt ; + +: st-add ( fnum stats -- ) + dup + 1e dup f+! float+ + fdup dup f+! float+ + fdup f* f+! + std-stddev ; diff --git a/Task/Standard-deviation/Forth/standard-deviation-2.fth b/Task/Standard-deviation/Forth/standard-deviation-2.fth index 644715a9bd..de7357fe44 100644 --- a/Task/Standard-deviation/Forth/standard-deviation-2.fth +++ b/Task/Standard-deviation/Forth/standard-deviation-2.fth @@ -6,6 +6,7 @@ : st-stddev ( stats -- stddev ) st-variance fsqrt ; : st-add ( x stats -- ) + dup 1e dup f+! \ update count fdup dup st-mean f- fswap ( delta x ) @@ -13,4 +14,5 @@ ( delta x delta/n ) float+ dup f+! \ update mean ( delta x ) - dup f@ f- f* float+ f+! ; \ update nvar + dup f@ f- f* float+ f+! \ update nvar + st-stddev ; diff --git a/Task/Standard-deviation/Forth/standard-deviation-3.fth b/Task/Standard-deviation/Forth/standard-deviation-3.fth index 2da097c3bf..14462821e2 100644 --- a/Task/Standard-deviation/Forth/standard-deviation-3.fth +++ b/Task/Standard-deviation/Forth/standard-deviation-3.fth @@ -1,12 +1,10 @@ create stats 0e f, 0e f, 0e f, -2e stats st-add -4e stats st-add -4e stats st-add -4e stats st-add -5e stats st-add -5e stats st-add -7e stats st-add -9e stats st-add - -stats st-stddev f. \ 2. +2e stats st-add f. \ 0. +4e stats st-add f. \ 1. +4e stats st-add f. \ 0.942809041582063 +4e stats st-add f. \ 0.866025403784439 +5e stats st-add f. \ 0.979795897113271 +5e stats st-add f. \ 1. +7e stats st-add f. \ 1.39970842444753 +9e stats st-add f. \ 2. diff --git a/Task/Standard-deviation/Fortran/standard-deviation-1.f b/Task/Standard-deviation/Fortran/standard-deviation-1.f index bd4fe63369..fbe6b25fc7 100644 --- a/Task/Standard-deviation/Fortran/standard-deviation-1.f +++ b/Task/Standard-deviation/Fortran/standard-deviation-1.f @@ -1,61 +1,49 @@ -program Test_Stddev +program standard_deviation implicit none + integer(kind=4), parameter :: dp = kind(0.0d0) - real, dimension(8) :: v = (/ 2,4,4,4,5,5,7,9 /) - integer :: i - real :: sd + real(kind=dp), dimension(:), allocatable :: vals + integer(kind=4) :: i - do i = 1, size(v) - sd = stat_object(v(i)) - end do + real(kind=dp), dimension(8) :: sample_data = (/ 2, 4, 4, 4, 5, 5, 7, 9 /) - print *, "std dev = ", sd + do i = lbound(sample_data, 1), ubound(sample_data, 1) + call sample_add(vals, sample_data(i)) + write(*, fmt='(''#'',I1,1X,''value = '',F3.1,1X,''stddev ='',1X,F10.8)') & + i, sample_data(i), stddev(vals) + end do + if (allocated(vals)) deallocate(vals) contains + ! Adds value :val: to array :population: dynamically resizing array + subroutine sample_add(population, val) + real(kind=dp), dimension(:), allocatable, intent (inout) :: population + real(kind=dp), intent (in) :: val - recursive function stat_object(a, cmd) result(stddev) - real :: stddev - real, intent(in) :: a - character(len=*), intent(in), optional :: cmd - - real, save :: summa = 0.0, summa2 = 0.0 - integer, save :: num = 0 - - real :: m + real(kind=dp), dimension(:), allocatable :: tmp + integer(kind=4) :: n - if ( .not. present(cmd) ) then - num = num + 1 - summa = summa + a - summa2 = summa2 + a*a - stddev = stat_object(0.0, "stddev") + if (.not. allocated(population)) then + allocate(population(1)) + population(1) = val else - select case(cmd) - case("stddev") - stddev = sqrt(stat_object(0.0, "variance")) - case("variance") - m = stat_object(0.0, "mean") - if ( num > 0 ) then - stddev = summa2/real(num) - m*m - else - stddev = 0.0 - end if - case("count") - stddev = real(num) - case("mean") - if ( num > 0 ) then - stddev = summa/real(num) - else - stddev = 0.0 - end if - case("reset") - summa = 0.0 - summa2 = 0.0 - num = 0 - case default - stddev = 0.0 - end select - end if - - end function stat_object - -end program Test_Stddev + n = size(population) + call move_alloc(population, tmp) + + allocate(population(n + 1)) + population(1:n) = tmp + population(n + 1) = val + endif + end subroutine sample_add + + ! Calculates standard deviation for given set of values + real(kind=dp) function stddev(vals) + real(kind=dp), dimension(:), intent(in) :: vals + real(kind=dp) :: mean + integer(kind=4) :: n + + n = size(vals) + mean = sum(vals)/n + stddev = sqrt(sum((vals - mean)**2)/n) + end function stddev +end program standard_deviation diff --git a/Task/Standard-deviation/Fortran/standard-deviation-2.f b/Task/Standard-deviation/Fortran/standard-deviation-2.f index cf558c73c8..73f2657bbe 100644 --- a/Task/Standard-deviation/Fortran/standard-deviation-2.f +++ b/Task/Standard-deviation/Fortran/standard-deviation-2.f @@ -1,28 +1,74 @@ -program stats - implicit none + REAL FUNCTION STDDEV(X) !Standard deviation for successive values. + REAL X !The latest value. + REAL V !Scratchpad. + INTEGER N !Ongoing: count of the values. + REAL EX,EX2 !Ongoing: sum of X and X**2. + SAVE N,EX,EX2 !Retain values from one invocation to the next. + DATA N,EX,EX2/0,0.0,0.0/ !Initial values. + N = N + 1 !Another value arrives. + EX = X + EX !Augment the total. + EX2 = X**2 + EX2 !Augment the sum of squares. + V = EX2/N - (EX/N)**2 !The variance, but, it might come out negative! + STDDEV = SIGN(SQRT(ABS(V)),V) !Protect the SQRT, but produce a negative result if so. + END FUNCTION STDDEV !For the sequence of received X values. - integer, parameter :: N = 8 - integer :: data(N) - real(8) :: mean - real(8) :: std_dev1, std_dev2 + REAL FUNCTION STDDEVP(X) !Standard deviation for successive values. + REAL X !The latest value. + INTEGER N !Ongoing: count of the values. + REAL A,V !Ongoing: average, and sum of squared deviations. + SAVE N,A,V !Retain values from one invocation to the next. + DATA N,A,V/0,0.0,0.0/ !Initial values. + N = N + 1 !Another value arrives. + V = (N - 1)*(X - A)**2 /N + V !First, as it requires the existing average. + A = (X - A)/N + A != [x + (n - 1).A)]/n: recover the total from the average. + STDDEVP = SQRT(V/N) !V can never be negative, even with limited precision. + END FUNCTION STDDEVP !For the sequence of received X values. - ! Set the data - data = [2,4,4,4,5,5,7,9] ! Strictly this is a Fortran 2003 construct + REAL FUNCTION STDDEVW(X) !Standard deviation for successive values. + REAL X !The latest value. + REAL V,D !Scratchpads. + INTEGER N !Ongoing: count of the values. + REAL EX,EX2 !Ongoing: sum of X and X**2. + REAL W !Ongoing: working mean. + SAVE N,EX,EX2,W !Retain values from one invocation to the next. + DATA N,EX,EX2/0,0.0,0.0/ !Initial values. + IF (N.LE.0) W = X !Take the first value as the working mean. + N = N + 1 !Another value arrives. + D = X - W !Its deviation from the working mean. + EX = D + EX !Augment the total. + EX2 = D**2 + EX2 !Augment the sum of squares. + V = EX2/N - (EX/N)**2 !The variance, but, it might come out negative! + STDDEVW = SIGN(SQRT(ABS(V)),V) !Protect the SQRT, but produce a negative result if so. + END FUNCTION STDDEVW !For the sequence of received X values. - ! Use intrinsic function 'sum' to calculate the mean - mean = sum(data)/N + REAL FUNCTION STDDEVPW(X) !Standard deviation for successive values. + REAL X !The latest value. + INTEGER N !Ongoing: count of the values. + REAL A,V !Ongoing: average, and sum of squared deviations. + REAL W !Ongoing: working mean. + SAVE N,A,V,W !Retain values from one invocation to the next. + DATA N,A,V/0,0.0,0.0/ !Initial values. + IF (N.LE.0) W = X !Oh for self-modifying code! + N = N + 1 !Another value arrives. + D = X - W !Its deviation from the working mean. + V = (N - 1)*(D - A)**2 /N + V !First, as it requires the existing average. + A = (D - A)/N + A != [x + (n - 1).A)]/n: recover the total from the average. + STDDEVPW = SQRT(V/N) !V can never be negative, even with limited precision. + END FUNCTION STDDEVPW !For the sequence of received X values. - ! Method1: - ! Calculate the standard deviation directly from the definition - std_dev1 = sqrt(sum((data - mean)**2)/N) - - ! Method 2: - ! Use the alternative version that is less susceptible to rounding error - std_dev2 = sqrt(sum(data**2)/N - mean**2) - - write(*,'(a,8i2)') 'Data = ',data - write(*,'(a,f3.1)') 'Mean = ',mean - write(*,'(a,f3.1)') 'Standard deviation (method 1) = ',std_dev1 - write(*,'(a,f3.1)') 'Standard deviation (method 2) = ',std_dev2 - -end program stats + PROGRAM TEST + INTEGER I !A stepper. + REAL A(8) !The example data. + DATA A/2.0,3*4.0,2*5.0,7.0,9.0/ !Alas, another opportunity to use @ passed over. + REAL B !An offsetting base. + WRITE (6,1) + 1 FORMAT ("Progressive calculation of the standard deviation."/ + 1 " I",7X,"A(I) EX EX2 Av V*N Ed Ed2 wAv V*N") + B = 1000000 !Provoke truncation error. + DO I = 1,8 !Step along the data series, + WRITE (6,2) I,INT(A(I) + B), !No fractional part, so I don't want F11.0. + 1 STDDEV(A(I) + B),STDDEVP(A(I) + B), !Showing progressive values. + 2 STDDEVW(A(I) + B),STDDEVPW(A(I) + B) !These with a working mean. + 2 FORMAT (I2,I11,1X,4F12.6) !Should do for the example. + END DO !On to the next value. + END diff --git a/Task/Standard-deviation/Julia/standard-deviation.julia b/Task/Standard-deviation/Julia/standard-deviation.julia new file mode 100644 index 0000000000..c026609938 --- /dev/null +++ b/Task/Standard-deviation/Julia/standard-deviation.julia @@ -0,0 +1,22 @@ +function makerunningstd() + a = zero(Float64) + b = zero(Float64) + n = zero(Int64) + function runningstd(x) + a += x + b += x^2 + n += 1 + std = sqrt(n*b - a^2)/n + return std + end + return runningstd +end + +test = [2, 4, 4, 4, 5, 5, 7, 9] + +rstd = makerunningstd() + +println("Perform a running standard deviation of ", test) +for i in test + println(i, " => ", rstd(i)) +end diff --git a/Task/Standard-deviation/MATLAB/standard-deviation-3.m b/Task/Standard-deviation/MATLAB/standard-deviation-3.m new file mode 100644 index 0000000000..52ba6537f5 --- /dev/null +++ b/Task/Standard-deviation/MATLAB/standard-deviation-3.m @@ -0,0 +1,3 @@ +function stdDevEval(n) +disp(sqrt(sum((n-sum(n)/length(n)).^2)/length(n))); +end diff --git a/Task/Standard-deviation/PHP/standard-deviation.php b/Task/Standard-deviation/PHP/standard-deviation.php new file mode 100644 index 0000000000..e56cdaeb7f --- /dev/null +++ b/Task/Standard-deviation/PHP/standard-deviation.php @@ -0,0 +1,31 @@ +reset(); + } + # callable on an instance + function reset() { + $this->cnt=0; $this->sumup=0; $this->square=0; + } + function add($f) { + $this->cnt++; + $this->sumup += $f; + $this->square += pow($f, 2); + return $this->calc(); + } + function calc() { + if ($this->cnt==0 || $this->sumup==0) { + return 0; + } else { + return sqrt($this->square / $this->cnt - pow(($this->sumup / $this->cnt),2)); + } + } + } + +# start test, adding test data one by one +$c = new sdcalc(); +foreach ([2,4,4,4,5,5,7,9] as $v) { + printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL); +} diff --git a/Task/Standard-deviation/Pascal/standard-deviation.pascal b/Task/Standard-deviation/Pascal/standard-deviation-1.pascal similarity index 100% rename from Task/Standard-deviation/Pascal/standard-deviation.pascal rename to Task/Standard-deviation/Pascal/standard-deviation-1.pascal diff --git a/Task/Standard-deviation/Pascal/standard-deviation-2.pascal b/Task/Standard-deviation/Pascal/standard-deviation-2.pascal new file mode 100644 index 0000000000..3dbfb225a3 --- /dev/null +++ b/Task/Standard-deviation/Pascal/standard-deviation-2.pascal @@ -0,0 +1,31 @@ +program prj_CalcStdDerv; + +{$APPTYPE CONSOLE} + +uses + Math; + +var Series:Array of Extended; + UserString:String; + + +function AppendAndCalc(NewVal:Extended):Extended; + +begin + setlength(Series,high(Series)+2); + Series[high(Series)] := NewVal; + result := PopnStdDev(Series); +end; + +const data:array[0..7] of Extended = + (2,4,4,4,5,5,7,9); + +var rr: Extended; +begin + setlength(Series,0); + for rr in data do + begin + writeln(rr,' -> ',AppendAndCalc(rr)); + end; + Readln; +end. diff --git a/Task/Standard-deviation/Python/standard-deviation-5.py b/Task/Standard-deviation/Python/standard-deviation-5.py new file mode 100644 index 0000000000..9ad200307c --- /dev/null +++ b/Task/Standard-deviation/Python/standard-deviation-5.py @@ -0,0 +1,5 @@ +>>> myMean = lambda MyList : reduce(lambda x, y: x + y, MyList) / float(len(MyList)) +>>> myStd = lambda MyList : (reduce(lambda x,y : x + y , map(lambda x: (x-myMean(MyList))**2 , MyList)) / float(len(MyList)))**.5 + +>>> print myStd([2,4,4,4,5,5,7,9]) +2.0 diff --git a/Task/Standard-deviation/REXX/standard-deviation.rexx b/Task/Standard-deviation/REXX/standard-deviation.rexx index 991bca3c46..d8f4955e87 100644 --- a/Task/Standard-deviation/REXX/standard-deviation.rexx +++ b/Task/Standard-deviation/REXX/standard-deviation.rexx @@ -1,17 +1,17 @@ -/*REXX pgm finds & displays the standard deviation of a given set of #s.*/ -parse arg # /*any optional args on the C.L. ?*/ -if #='' then #=2 4 4 4 5 5 7 9 /*None given? Then use default.*/ -w=words(#); s=0; ss=0 /*define: #items; a couple sums.*/ - - do j=1 for w; _=word(#,j); s=s+_; ss=ss+_*_ - say ' item' right(j,length(w))":" right(_,4), - ' average=' left(s/j,12), - ' standard deviation=' left(sqrt( ss/j - (s/j)**2 ),15) - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits 11 -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 +/*REXX pgm finds & displays the standard deviation of a given set of numbers.*/ +parse arg # /*any optional arguments on the C.L. ? */ +if #='' then # = 2 4 4 4 5 5 7 9 /*None specified? Then use the default*/ +w=words(#); L=length(w); $=0; $$=0 /*# items; item width; couple of sums*/ + /* [↓] process each number in the list*/ + do j=1 for w; _=word(#,j); $=$+_; $$=$$+_**2 + say ' item' right(j,L)":" right(_,4) ' average=' left($/j,12), + ' standard deviation=' left(sqrt( $$/j - ($/j)**2 ), 15) + end /*j*/ /* [↑] prettify output with whitespace*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Standard-deviation/SQL/standard-deviation.sql b/Task/Standard-deviation/SQL/standard-deviation.sql new file mode 100644 index 0000000000..74b10a02a8 --- /dev/null +++ b/Task/Standard-deviation/SQL/standard-deviation.sql @@ -0,0 +1,34 @@ +-- the minimal table +create table if not exists teststd (n double precision not null); + +-- code modularity with view, we could have used a common table expression instead +create view vteststd as + select count(n) as cnt, + sum(n) as tsum, + sum(power(n,2)) as tsqr +from teststd; + +-- you can of course put this code into every query +create or replace function std_dev() returns double precision as $$ + select sqrt(tsqr/cnt - (tsum/cnt)^2) from vteststd; +$$ language sql; + +-- test data is: 2,4,4,4,5,5,7,9 +insert into teststd values (2); +select std_dev() as std_deviation; +insert into teststd values (4); +select std_dev() as std_deviation; +insert into teststd values (4); +select std_dev() as std_deviation; +insert into teststd values (4); +select std_dev() as std_deviation; +insert into teststd values (5); +select std_dev() as std_deviation; +insert into teststd values (5); +select std_dev() as std_deviation; +insert into teststd values (7); +select std_dev() as std_deviation; +insert into teststd values (9); +select std_dev() as std_deviation; +-- cleanup test data +delete from teststd; diff --git a/Task/Standard-deviation/Scala/standard-deviation.scala b/Task/Standard-deviation/Scala/standard-deviation.scala index 3d9095e0f1..dab352a6e8 100644 --- a/Task/Standard-deviation/Scala/standard-deviation.scala +++ b/Task/Standard-deviation/Scala/standard-deviation.scala @@ -1,16 +1,18 @@ -import scala.math._ -import Numeric.Implicits._ +import scala.math.sqrt object StddevCalc extends App { - def avg[T](ts: Iterable[T])(implicit num: Fractional[T]): T = { - num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T - } - def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = { + def avg(ts: Iterable[T])(implicit num: Fractional[T]): T = { + num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T + } + val mean = avg(ts) // Leave val type of T val stdDev = // Root of mean diffs - sqrt(num.toDouble(ts.foldLeft(num.zero)((b, a) => num.plus(b, num.times(num.minus(a, mean), num.minus(a, mean))))) / ts.size) + sqrt(num.toDouble( + ts.foldLeft(num.zero)((b, a) => + num.plus(b, num.times(num.minus(a, mean), num.minus(a, mean))))) / + ts.size) (mean, stdDev) } diff --git a/Task/Standard-deviation/Scheme/standard-deviation.ss b/Task/Standard-deviation/Scheme/standard-deviation.ss index 66aef5aafb..db5d10a333 100644 --- a/Task/Standard-deviation/Scheme/standard-deviation.ss +++ b/Task/Standard-deviation/Scheme/standard-deviation.ss @@ -1,3 +1,16 @@ -(define ((running-stddev . nums) num) - (set! nums (cons num nums)) - (sqrt (- (/ (apply + (map (lambda (i) (* i i)) nums)) (length nums)) (expt (/ (apply + nums) (length nums)) 2)))) +(define (standart-deviation-generator) + (let ((nums '())) + (lambda (x) + (set! nums (cons x nums)) + (let* ((mean (/ (apply + nums) (length nums))) + (mean-sqr (lambda (y) (expt (- y mean) 2))) + (variance (/ (apply + (map mean-sqr nums)) (length nums)))) + (sqrt variance))))) + +(let loop ((f (standart-deviation-generator)) + (input '(2 4 4 4 5 5 7 9))) + (if (not (null? input)) + (begin + (display (f (car input))) + (newline) + (loop f (cdr input))))) diff --git a/Task/Standard-deviation/VBScript/standard-deviation.vb b/Task/Standard-deviation/VBScript/standard-deviation.vb new file mode 100644 index 0000000000..237a6d559a --- /dev/null +++ b/Task/Standard-deviation/VBScript/standard-deviation.vb @@ -0,0 +1,21 @@ +data = Array(2,4,4,4,5,5,7,9) + +For i = 0 To UBound(data) + WScript.StdOut.Write "value = " & data(i) &_ + " running sd = " & sd(data,i) + WScript.StdOut.WriteLine +Next + +Function sd(arr,n) + mean = 0 + variance = 0 + For j = 0 To n + mean = mean + arr(j) + Next + mean = mean/(n+1) + For k = 0 To n + variance = variance + ((arr(k)-mean)^2) + Next + variance = variance/(n+1) + sd = FormatNumber(Sqr(variance),6) +End Function diff --git a/Task/State-name-puzzle/00DESCRIPTION b/Task/State-name-puzzle/00DESCRIPTION index ef72fa6abf..75ad5caabe 100644 --- a/Task/State-name-puzzle/00DESCRIPTION +++ b/Task/State-name-puzzle/00DESCRIPTION @@ -12,7 +12,7 @@ A second challenge in the form of a set of fictitious new states was also presen 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) +* case and spacing aren'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) diff --git a/Task/State-name-puzzle/C++/state-name-puzzle.cpp b/Task/State-name-puzzle/C++/state-name-puzzle.cpp new file mode 100644 index 0000000000..d56266119c --- /dev/null +++ b/Task/State-name-puzzle/C++/state-name-puzzle.cpp @@ -0,0 +1,105 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +// some common code +template C_ Unique(const C_& src, const LT_& less) +{ + C_ retval(src); + std::sort(retval.begin(), retval.end(), less); + retval.erase(unique(retval.begin(), retval.end()), retval.end()); + return retval; +} +template C_ Unique(const C_& src) +{ + return Unique(src, std::less()); +} + +#define USE_FAKES 1 + +vector states = Unique(vector({ +#if USE_FAKES + "Slender Dragon", "Abalamara", +#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" +})); + +struct CountedPair_ +{ + string name_; + vector count_; + + void Add(const string& s) + { + for (auto c : s) + { + if (c >= 'a' && c <= 'z') ++count_[c - 'a']; + if (c >= 'A' && c <= 'Z') ++count_[c - 'A']; + } + } + + CountedPair_(const string& s1, const string& s2) : name_(s1 + " + " + s2), count_(26, 0u) + { + Add(s1); Add(s2); + } +}; + +bool operator<(const CountedPair_& lhs, const CountedPair_& rhs) +{ + const int s1 = lhs.name_.size(), s2 = rhs.name_.size(); + return s1 == s2 + ? lexicographical_compare(lhs.count_.begin(), lhs.count_.end(), rhs.count_.begin(), rhs.count_.end()) + : s1 < s2; +} + +bool operator==(const CountedPair_& lhs, const CountedPair_& rhs) +{ + return lhs.name_.size() == rhs.name_.size() + && lhs.count_ == rhs.count_; +} + +void FindPairs() +{ + const int n_states = states.size(); + + vector pairs; + for (int i = 0; i < n_states; i++) + for (int j = 0; j < i; j++) + pairs.emplace_back(states[i], states[j]); + sort(pairs.begin(), pairs.end()); + + auto start = pairs.begin(); + for (;;) + { + auto match = adjacent_find(start, pairs.end()); + if (match == pairs.end()) + break; + auto next = match + 1; + cout << match->name_ << " => " << next->name_ << "\n"; + start = next; + } +} + +int main(void) +{ + FindPairs(); + return 0; +} diff --git a/Task/State-name-puzzle/Haskell/state-name-puzzle.hs b/Task/State-name-puzzle/Haskell/state-name-puzzle.hs new file mode 100644 index 0000000000..0566e7b42a --- /dev/null +++ b/Task/State-name-puzzle/Haskell/state-name-puzzle.hs @@ -0,0 +1,87 @@ +{-# LANGUAGE TupleSections #-} + +import Data.Char (toLower, isLetter) +import Data.List (sort, sortBy, nub, groupBy) +import Data.Function (on) + +stateNames :: [String] +stateNames= + ["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"] + +fakeStateNames :: [String] +fakeStateNames = + ["New Kory", + "Wen Kory", + "York New", + "Kory New", + "New Kory"] + +pairs :: [a] -> [(a,a)] +pairs [] = [] +pairs (y:ys) = map (y,) ys ++ pairs ys + +puzzle :: [String] -> [((String,String), (String, String))] +puzzle states = + concatMap (filter isValid.pairs) $ + map (map snd) $ + filter ((>1) . length ) $ + groupBy ((==) `on` fst) $ + sortBy (compare `on` fst) [(pkey (a++b), (a,b)) | (a,b) <- pairs (nub $ sort states)] where + pkey = sort . filter isLetter . map toLower + isValid ((a0, a1),(b0, b1)) = (a0 /= b0) && (a0 /= b1) && (a1 /= b0) && (a1 /= b1) + +main :: IO () +main = do + putStrLn $ "Matching pairs generated from " + ++ show (length stateNames) ++ " state names and " + ++ show (length fakeStateNames) ++ " fake state names:" + mapM_ print $ puzzle $ stateNames ++ fakeStateNames diff --git a/Task/State-name-puzzle/REXX/state-name-puzzle.rexx b/Task/State-name-puzzle/REXX/state-name-puzzle.rexx index c80dc257eb..e05cedc049 100644 --- a/Task/State-name-puzzle/REXX/state-name-puzzle.rexx +++ b/Task/State-name-puzzle/REXX/state-name-puzzle.rexx @@ -1,88 +1,88 @@ -/*REXX pgm: state name puzzle, rearrange 2 state's names──►2 new states.*/ +/*REXX pgm (state name puzzle) rearranges two state's names ──► two 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*/ +parse arg xtra; !=! ',' xtra /*add optional (fictitious) names.*/ +@abcU='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; !=space(!) /*ABCs; the state list.*/ +deads=0; dups=0; L.=0; !orig=!; z=0; @@.= /*initialize some vars. */ - do de=0 to 1; !=!orig; @.= /*use the original state list.*/ + do de=0 for 2; !=!orig; @.= /*use original state list for each. */ - 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 + do states=0 until !=='' /*parse until the cows come home. */ + parse var ! x ',' !; x=space(x) /*remove all blanks from state name.*/ + if @.x\=='' then do /*was state was already specified? */ + if de then iterate /*don't tell error if doing 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) + @.x=x /*indicate this state name exists. */ + y=space(x,0); upper y; yLen=length(y) /*get upper name with no spaces; Len*/ - 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 + if de then do /*Is the 1st pass? Then process. */ + do j=1 for yLen /*see if it's a dead─end state name.*/ + _=substr(y,j,1) /* _: is some state name character.*/ + if L._\==1 then iterate /*Count ¬1? Then state name is O.K.*/ + say 'removing dead─end state [which has the letter ' _"]: " x + deads=deads+1 /*bump number of dead─ends states. */ + iterate states /*go and process another state name.*/ end /*j*/ - z=z+1 /*bump counter of the states. */ - #.z=y; ##.z=x /*assign state name; &original*/ + z=z+1 /*bump counter of the state names. */ + #.z=y; ##.z=x /*assign state name; and original. */ end - else do k=1 for yLen /*inventorize state's letters.*/ - _=substr(y,k,1); L._=L._+1 /*count each letter in state. */ + else do k=1 for yLen /*inventorize state name's letters. */ + _=substr(y,k,1); L._=L._+1 /*count each letter in state name. */ end /*k*/ end /*states*/ end /*de*/ -say; do i=1 for z /*list states in order given. */ - say right(i,9) ##.i +say; do i=1 for z /*list state names in order given. */ + say right(i,9) ##.i /*show the index number, state name.*/ 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; 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. */ +sols=0 /*number of solutions found (so far)*/ - 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 j=1 for z /*◄─────────────────────────────────────────────────────┐ */ + /*look for mix and match states. │ */ + do k=j+1 to z /* ◄─── state K, state J ►───────┘ */ + if #.j<<#.k then JK=#.j || #.k /*is in proper order?*/ + else JK=#.k || #.j /*use new state name.*/ - 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 m=1 for z; if m==j | m==k then iterate /*no overlaps allowed*/ + if verify(#.m,jk)\==0 then iterate /*is this possible? */ + nJK=elider(JK,#.m) /*new JK, after eliding #.m characters.*/ - 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. */ + do n=m+1 to z; if n==j | n==k then iterate /*no overlaps allowed*/ + if verify(#.n,nJK)\==0 then iterate /*is it possible? */ + if elider(nJK,#.n)\=='' then iterate /*leftovers letters? */ + if #.m<<#.n then MN=#.m || #.n /*is in proper order?*/ + else MN=#.n || #.m /*a new state name. */ + if @@.JK.MN\=='' | @@.MN.JK\=='' then iterate /*was it done before?*/ + say 'found: ' ##.j',' ##.k " ───► " ##.m',' ##.n + @@.JK.MN=1 /*indicate this solution as being found*/ + sols=sols+1 /*bump the number of solutions found. */ 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.*/ +say /*show a blank line for easier reading.*/ +if sols==0 then sols='No' /*use mucher gooder (sic) Englishings. */ +say sols 'solution's(sols) "found." /*display the number of solutions found*/ +exit /*stick a fork in it, we're all done. */ +/*───────────────────────────────────ELIDER───────────────────────────────────*/ +elider: parse arg hay,pins /*remove letters (pins) from haystack. */ + + do e=1 for length(pins); p=pos(substr(pins,e,1), hay) + if p==0 then iterate ; hay=overlay(' ',hay,p) + end /*e*/ /* [↑] remove a letter.*/ +return space(hay,0) /*remove blanks from hay*/ +/*──────────────────────────────────S subroutine──────────────────────────────*/ +s: if arg(1)==1 then return arg(3);return word(arg(2) 's',1) /*pluralizer.*/ diff --git a/Task/Statistics-Basic/REXX/statistics-basic.rexx b/Task/Statistics-Basic/REXX/statistics-basic.rexx index ecaa3cd304..efd799b40e 100644 --- a/Task/Statistics-Basic/REXX/statistics-basic.rexx +++ b/Task/Statistics-Basic/REXX/statistics-basic.rexx @@ -1,38 +1,35 @@ -/*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. */ +/*REXX pgm gens some random numbers, shows bin histogram, finds mean & stdDev.*/ +numeric digits 20 /*use twenty decimal digits precision, */ +showDigs=digits()%2 /* ··· but only show ten decimal digits*/ +parse arg size seed . /*allow specification: size, and seed.*/ +if size=='' | size==',' then size=100 /*Not specified? Then use the default.*/ +if datatype(seed,'W') then call random ,,seed /*allow a seed for RAND BIF.*/ +#.=0 /*count of the numbers in each bin. */ + do j=1 for size /*generate some random numbers. */ + @.j=random(0,99999)/100000 /*express it as a fraction. */ + _=substr(@.j'00',3,1) /*determine which bin the number is 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.*/ + do k=0 for 10 /*show a histogram of the bins. */ + lr='0.'k ; if k==0 then lr='0 ' /*adjust for the 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 +avg=mean(size) ; say ' mean = ' format(avg,,showDigs) +std=stdDev(size); say ' stdDev = ' format(std,,showDigs) +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +mean: parse arg N; $=0; do m=1 for N; $=$+@.m; end; return $/n +stdDev: parse arg N; $=0; do s=1 for N; $=$+(@.s-avg)**2; end; return sqrt($/n) +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Stem-and-leaf-plot/Julia/stem-and-leaf-plot-1.julia b/Task/Stem-and-leaf-plot/Julia/stem-and-leaf-plot-1.julia new file mode 100644 index 0000000000..b4b5f5d1b2 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Julia/stem-and-leaf-plot-1.julia @@ -0,0 +1,25 @@ +function stemleaf{T<:Real}(a::Array{T,1}, leafsize=1) + ls = 10^int(log10(leafsize)) + (stem, leaf) = divrem(sort(int(a/ls)), 10) + leaf[sign(stem) .== -1] *= -1 + negzero = leaf .< 0 + if any(negzero) + leaf[negzero] *= -1 + nz = @sprintf "%10s | " "-0" + nz *= join(map(string, leaf[negzero]), " ") + nz *= "\n" + stem = stem[!negzero] + leaf = leaf[!negzero] + else + nz = "" + end + slp = "" + for i in stem[1]:stem[end] + i != 0 || (slp *= nz) + slp *= @sprintf "%10d | " i + slp *= join(map(string, leaf[stem .== i]), " ") + slp *= "\n" + end + slp *= " Leaf Unit = " * string(convert(T, ls)) * "\n" + return slp +end diff --git a/Task/Stem-and-leaf-plot/Julia/stem-and-leaf-plot-2.julia b/Task/Stem-and-leaf-plot/Julia/stem-and-leaf-plot-2.julia new file mode 100644 index 0000000000..c75aea97dd --- /dev/null +++ b/Task/Stem-and-leaf-plot/Julia/stem-and-leaf-plot-2.julia @@ -0,0 +1,19 @@ +println("Using the Task's Test Data") +test = """12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 + 31 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 + 63 27 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 + 53 114 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 + 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 + 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 + 116 146""" +test = map(parseint, split(test, r"\s")) +println(stemleaf(test)) + +println("Test with Reals and Negative Zero Stem") +test = [-23.678758, -12.45, -3.4, 4.43, 5.5, 5.678, 16.87, 24.7, 56.8] +println(stemleaf(test)) + +println("Test with Leaf Size Scaling") +test = int(500*randn(20)) +println("Using: ", test) +println(stemleaf(test, 10)) diff --git a/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot.rexx b/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot.rexx index 6742c2c399..e25a1d52aa 100644 --- a/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot.rexx +++ b/Task/Stem-and-leaf-plot/REXX/stem-and-leaf-plot.rexx @@ -1,26 +1,23 @@ -/*REXX program displays a stem-and-leaf plot of real numbers [-, 0, +].*/ -min= /*This program handles negatives */ -max= /* ··· and decimal fractions. */ -parse arg data; if data='' then data=, /*Not specified? Then use default*/ - 12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31 125, - 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27, - 44 105 99 41 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114, - 96 25 109 7 31 141 46 13 27 43 117 116 27 7 68 40 31 115 124 42 128 52, - 71 118 117 38 27 106 33 117 116 111 40 119 47 105 57 122 109 124 115, - 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 -#.= - do j=1 for words(data); _=format(word(data,j),,0)/1 /*normalize*/ - stem=left(_, max(1, length(_)-1)) /*extract the stem from the num. */ - if length(_)==1 then stem=0 /*handle single-digit leaves. */ - if min=='' then min=stem; if max=='' then max=stem - min=min(min, stem*sign(_)); max=max(max, stem*sign(_)) - leaf=right(_,1) /*pick off the leaf from the num.*/ - #.stem.leaf=#.stem.leaf leaf /*construct a sorted stem-&-leaf.*/ +/*REXX program displays a stem─and─leaf plot of any real numbers [-, 0, +]. */ +parse arg data /* [↓] Not specified? Then use default*/ +if data='' then data=12 127 28 42 39 113 42 18 44 118 44 37 113 124 37 48 127 36 29 31, + 125 139 131 115 105 132 104 123 35 113 122 42 117 119 58 109 23 105 63 27 44 105 99 41, + 128 121 116 125 32 61 37 127 29 113 121 58 114 126 53 114 96 25 109 7 31 141 46 13 27 43, + 117 116 27 7 68 40 31 115 124 42 128 52 71 118 117 38 27 106 33 117 116 111 40 119 47 105, + 57 122 109 124 115 43 120 43 27 27 18 28 48 125 107 114 34 133 45 120 30 127 31 116 146 +parse var data bot . 1 top . '' #. /*define MIN & MAX as the first number.*/ + /* [↑] define all #. elements as null.*/ + do j=1 for words(data); _=format(word(data,j),,0)/1 /*normalize the #*/ + stem=left(_, max(1, length(_)-1)) /*extract the stem (1st dig) from the #*/ + if length(_)==1 then stem=0 /*special case: single─digit leaves. */ + bot=min(bot, stem*sign(_)); top=max(top, stem*sign(_)) /*find MIN,MAX*/ + parse var _ '' -1 leaf /*obtain the leaf (last dig) from the #*/ + #.stem.leaf=#.stem.leaf leaf /*construct sorted stem-and-leaf entry.*/ end /*j*/ -w=max(length(min),length(max)) /*width: used to align the stems.*/ +w=max(length(min), length(max)) +1 /*W: used to right─justify the output.*/ - do k=min to max; _=; do m=0 for 10; _=_ #.k.m; end /*m*/ - say right(k,w) '│' space(_) + do k=bot to top; $=; do m=0 for 10; $=$ #.k.m; end /*m*/ + say right(k,w) '║' space($) end /*k*/ - /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.ada b/Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.ada new file mode 100644 index 0000000000..71b516b13d --- /dev/null +++ b/Task/Stern-Brocot-sequence/Ada/stern-brocot-sequence.ada @@ -0,0 +1,94 @@ +with Ada.Text_IO, Ada.Containers.Vectors; + +procedure Sequence is + + package Vectors is new + Ada.Containers.Vectors(Index_Type => Positive, Element_Type => Positive); + use type Vectors.Vector; + + type Sequence is record + List: Vectors.Vector; + Index: Positive; + -- This implements some form of "lazy evaluation": + -- + List holds the elements computed, so far, it is extended + -- if the user tries to "Get" an element not yet computed; + -- + Index is the location of the next element under consideration + end record; + + function Initialize return Sequence is + (List => (Vectors.Empty_Vector & 1 & 1), Index => 2); + + function Get(Seq: in out Sequence; Location: Positive) return Positive is + -- returns the Location'th element of the sequence + -- extends Seq.List (and then increases Seq.Index) if neccessary + That: Positive := Seq.List.Element(Seq.Index); + This: Positive := That + Seq.List.Element(Seq.Index-1); + begin + while Seq.List.Last_Index < Location loop + Seq.List := Seq.List & This & That; + Seq.Index := Seq.Index + 1; + end loop; + return Seq.List.Element(Location); + end Get; + + S: Sequence := Initialize; + J: Positive; + + use Ada.Text_IO; + +begin + -- show first fifteen members + Put("First 15:"); + for I in 1 .. 15 loop + Put(Integer'Image(Get(S, I))); + end loop; + New_Line; + + -- show the index where 1, 2, 3, ... first appear in the sequence + for I in 1 .. 10 loop + J := 1; + while Get(S, J) /= I loop + J := J + 1; + end loop; + Put("First" & Integer'Image(I) & " at" & Integer'Image(J) & "; "); + if I mod 4 = 0 then + New_Line; -- otherwise, the output gets a bit too ugly + end if; + end loop; + + -- show the index where 100 first appears in the sequence + J := 1; + while Get(S, J) /= 100 loop + J := J + 1; + end loop; + Put_Line("First 100 at" & Integer'Image(J) & "."); + + -- check GCDs + declare + function GCD (A, B : Integer) return Integer is + M : Integer := A; + N : Integer := B; + T : Integer; + begin + while N /= 0 loop + T := M; + M := N; + N := T mod N; + end loop; + return M; + end GCD; + + A, B: Positive; + begin + for I in 1 .. 999 loop + A := Get(S, I); + B := Get(S, I+1); + if GCD(A, B) /= 1 then + raise Constraint_Error; + end if; + end loop; + Put_Line("Correct: The first 999 consecutive pairs are relative prime!"); + exception + when Constraint_Error => Put_Line("Some GCD > 1; this is wrong!!!") ; + end; +end Sequence; diff --git a/Task/Stern-Brocot-sequence/C++/stern-brocot-sequence.cpp b/Task/Stern-Brocot-sequence/C++/stern-brocot-sequence.cpp new file mode 100644 index 0000000000..aaafb2b300 --- /dev/null +++ b/Task/Stern-Brocot-sequence/C++/stern-brocot-sequence.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include + +unsigned gcd( unsigned i, unsigned j ) { + return i ? i < j ? gcd( j % i, i ) : gcd( i % j, j ) : j; +} +void createSequence( std::vector& seq, int c ) { + if( 1500 == seq.size() ) return; + unsigned t = seq.at( c ) + seq.at( c + 1 ); + seq.push_back( t ); + seq.push_back( seq.at( c + 1 ) ); + createSequence( seq, c + 1 ); +} +int main( int argc, char* argv[] ) { + std::vector seq( 2, 1 ); + createSequence( seq, 0 ); + + std::cout << "First fifteen members of the sequence:\n "; + for( unsigned x = 0; x < 15; x++ ) { + std::cout << seq[x] << " "; + } + + std::cout << "\n\n"; + for( unsigned x = 1; x < 11; x++ ) { + std::vector::iterator i = std::find( seq.begin(), seq.end(), x ); + if( i != seq.end() ) { + std::cout << std::setw( 3 ) << x << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; + } + } + + std::cout << "\n"; + std::vector::iterator i = std::find( seq.begin(), seq.end(), 100 ); + if( i != seq.end() ) { + std::cout << 100 << " is at pos. #" << 1 + distance( seq.begin(), i ) << "\n"; + } + + std::cout << "\n"; + unsigned g; + bool f = false; + for( int x = 0, y = 1; x < 1000; x++, y++ ) { + g = gcd( seq[x], seq[y] ); + if( g != 1 ) f = true; + std::cout << std::setw( 4 ) << x + 1 << ": GCD (" << seq[x] << ", " + << seq[y] << ") = " << g << ( g != 1 ? " <-- ERROR\n" : "\n" ); + } + std::cout << "\n" << ( f ? "THERE WERE ERRORS --- NOT ALL GCDs ARE '1'!" : "CORRECT: ALL GCDs ARE '1'!" ) << "\n\n"; + return 0; +} diff --git a/Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence.pl b/Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence-1.pl similarity index 100% rename from Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence.pl rename to Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence-1.pl diff --git a/Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence-2.pl b/Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence-2.pl new file mode 100644 index 0000000000..6c86b1c3e2 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Perl/stern-brocot-sequence-2.pl @@ -0,0 +1,20 @@ +use List::Util qw/first/; +use ntheory qw/gcd vecsum/; + +sub stern_diatomic { + my ($p,$q,$i) = (0,1,shift); + while ($i) { + if ($i & 1) { $p += $q; } else { $q += $p; } + $i >>= 1; + } + $p; +} + +my @s = map { stern_diatomic($_) } 1..15; +print "First fifteen: [@s]\n"; +@s = map { my $n=$_; first { stern_diatomic($_) == $n } 1..10000 } 1..10; +print "Index of 1-10 first occurrence: [@s]\n"; +print "Index of 100 first occurrence: ", (first { stern_diatomic($_) == 100 } 1..10000), "\n"; +print "The first 999 consecutive pairs are ", + (vecsum( map { gcd(stern_diatomic($_),stern_diatomic($_+1)) } 1..999 ) == 999) + ? "all coprime.\n" : "NOT all coprime!\n"; diff --git a/Task/Stern-Brocot-sequence/REXX/stern-brocot-sequence.rexx b/Task/Stern-Brocot-sequence/REXX/stern-brocot-sequence.rexx index 660efe475a..5600fed28f 100644 --- a/Task/Stern-Brocot-sequence/REXX/stern-brocot-sequence.rexx +++ b/Task/Stern-Brocot-sequence/REXX/stern-brocot-sequence.rexx @@ -1,43 +1,43 @@ -/*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*/ +/*REXX program gens/shows Stern─Brocot sequence, finds 1─based indices, GCDs. */ +parse arg N idx fix chk . /*get optional arguments from the C.L. */ +if N=='' | N==',' then N= 15 /* N defined? Then use the default. */ +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 sequence.*/ +say a /*display the sequence to the terminal.*/ + +say; say center('the 1-based index for the first' idx "integers",70,'═') +a=Stern_Brocot(-idx) /*invoke function to generate sequence.*/ do i=1 for idx - say 'for ' right(i,length(idx))", the index is: " wordpos(i,a) + 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*/ + +say; say center('the 1-based index for' fix,70,'═') +a=Stern_Brocot(-fix) /*invoke function to generate sequence.*/ +say 'for ' fix", the index is: " wordpos(fix, a) + +say; say center('checking if all two consecutive members have a GCD=1',70,'═') +a=Stern_Brocot(chk) /*invoke function to generate sequence.*/ do c=1 for chk-1; if gcd(subword(a,c,2))==1 then iterate - say 'GCD check failed at member' c"."; exit 13 + 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*/ +say '───── All ' chk " two consecutive members have a GCD of unity." +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +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*/ + do j=2 to words($); y=abs(word($,j)); if y=0 then iterate + do until y==0; parse value x//y y with y x; 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)) _ +/*────────────────────────────────────────────────────────────────────────────*/ +Stern_Brocot: parse arg h 1 f; $=1 1; if h<0 then h=1e9 + else f=0; f=abs(f) + do k=2 until words($)>=h; _=word($,k); $=$ (_+word($,k-1)) _ if f==0 then iterate; if wordpos(f,$)\==0 then leave end /*until*/ diff --git a/Task/Stern-Brocot-sequence/Tcl/stern-brocot-sequence.tcl b/Task/Stern-Brocot-sequence/Tcl/stern-brocot-sequence.tcl new file mode 100644 index 0000000000..a23ca30944 --- /dev/null +++ b/Task/Stern-Brocot-sequence/Tcl/stern-brocot-sequence.tcl @@ -0,0 +1,104 @@ +#!/usr/bin/env tclsh +# + +package require generator ;# from tcllib + +namespace eval stern-brocot { + proc generate {{count 100}} { + set seq {1 1} + set n 0 + while {[llength $seq] < $count} { + lassign [lrange $seq $n $n+1] a b + lappend seq [expr {$a + $b}] $b + incr n + } + return $seq + } + + proc genr {} { + yield [info coroutine] + set seq {1 1} + while {1} { + set seq [lassign $seq a] + set b [lindex $seq 0] + set c [expr {$a + $b}] + lappend seq $c $b + yield $a + } + } + + proc Step {a b args} { + set c [expr {$a + $b}] + list $a [list $b {*}$args $c $b] + } + + generator define gen {} { + set cmd [list 1 1] + while {1} { + lassign [Step {*}$cmd] a cmd + generator yield $a + } + } + + namespace export {[a-z]*} + namespace ensemble create +} + +interp alias {} sb {} stern-brocot + +# a simple adaptation of gcd from http://wiki.tcl.tk/2891 +proc coprime {a args} { + set gcd $a + foreach arg $args { + while {$arg != 0} { + set t $arg + set arg [expr {$gcd % $arg}] + set gcd $t + if {$gcd == 1} {return true} + } + } + return false +} + +proc main {} { + + puts "#1. First 15 members of the Stern-Brocot sequence:" + puts \t[generator to list [generator take 16 [sb gen]]] + + puts "#2. First occurrences of 1 through 10:" + set first {} + set got 0 + set i 0 + generator foreach x [sb gen] { + incr i + if {$x>10} continue + if {[dict exists $first $x]} continue + dict set first $x $i + if {[incr got] >= 10} break + } + foreach {a b} [lsort -integer -stride 2 $first] { + puts "\tFirst $a at $b" + } + + puts "#3. First occurrence of 100:" + set i 0 + generator foreach x [sb gen] { + incr i + if {$x eq 100} break + } + puts "\tFirst $x at $i" + + puts "#4. Check first 1k elements for common divisors:" + set prev [expr {2*3*5*7*11*13*17*19+1}] ;# a handy prime + set i 0 + generator foreach x [sb gen] { + if {[incr i] >= 1000} break + if {![coprime $x $prev]} { + error "Element $i, $x is not coprime with $prev!" + } + set prev $x + } + puts "\tFirst $i elements are all pairwise coprime" +} + +main diff --git a/Task/String-append/Elena/string-append.elena b/Task/String-append/Elena/string-append.elena new file mode 100644 index 0000000000..ceb3efa7bd --- /dev/null +++ b/Task/String-append/Elena/string-append.elena @@ -0,0 +1,9 @@ +#import system. + +#symbol program = +[ + #var s := String new:"Hello". + s += " World". + + console writeLine:s. +]. diff --git a/Task/String-append/Elixir/string-append.elixir b/Task/String-append/Elixir/string-append.elixir new file mode 100644 index 0000000000..fc30cf5faf --- /dev/null +++ b/Task/String-append/Elixir/string-append.elixir @@ -0,0 +1,4 @@ +iex(60)> s = "Hello" +"Hello" +iex(61)> s <> " World!" +"Hello World!" diff --git a/Task/String-append/Emacs-Lisp/string-append-1.l b/Task/String-append/Emacs-Lisp/string-append-1.l new file mode 100644 index 0000000000..ce0fea35ac --- /dev/null +++ b/Task/String-append/Emacs-Lisp/string-append-1.l @@ -0,0 +1,2 @@ +(defun glue (str1 str2) + (concat str1 str2) ) diff --git a/Task/String-append/Emacs-Lisp/string-append-2.l b/Task/String-append/Emacs-Lisp/string-append-2.l new file mode 100644 index 0000000000..47be3a5570 --- /dev/null +++ b/Task/String-append/Emacs-Lisp/string-append-2.l @@ -0,0 +1,2 @@ +(defun glue (str1 str2) + (format "%s%s" str1 str2) ) diff --git a/Task/String-append/Emacs-Lisp/string-append-3.l b/Task/String-append/Emacs-Lisp/string-append-3.l new file mode 100644 index 0000000000..f197d43171 --- /dev/null +++ b/Task/String-append/Emacs-Lisp/string-append-3.l @@ -0,0 +1,3 @@ +(setq str "Hello, ") +(setq str (glue str "World!") ) +(insert str) diff --git a/Task/String-append/Forth/string-append-1.fth b/Task/String-append/Forth/string-append-1.fth new file mode 100644 index 0000000000..5a1519bdce --- /dev/null +++ b/Task/String-append/Forth/string-append-1.fth @@ -0,0 +1,7 @@ +Strings in Forth are simply named memory locations + +create astring 256 allot \ create a "string" + +s" Hello " astring PLACE \ initialize the string + +s" World!" astring +PLACE \ append with "+place" diff --git a/Task/String-append/Forth/string-append-2.fth b/Task/String-append/Forth/string-append-2.fth new file mode 100644 index 0000000000..80a9d9fb12 --- /dev/null +++ b/Task/String-append/Forth/string-append-2.fth @@ -0,0 +1,4 @@ + ok +s" Hello " astring place ok +s" World!" astring +place ok +astring count type Hello World! ok diff --git a/Task/String-append/Fortran/string-append.f b/Task/String-append/Fortran/string-append.f new file mode 100644 index 0000000000..f8704cfae9 --- /dev/null +++ b/Task/String-append/Fortran/string-append.f @@ -0,0 +1,10 @@ +program main + + character(len=:),allocatable :: str + + str = 'hello' + str = str//' world' + + write(*,*) str + +end program main diff --git a/Task/String-append/NewLISP/string-append.newlisp b/Task/String-append/NewLISP/string-append.newlisp index 482c19f2eb..8f880fd7ad 100644 --- a/Task/String-append/NewLISP/string-append.newlisp +++ b/Task/String-append/NewLISP/string-append.newlisp @@ -1,3 +1,7 @@ (setq str "foo") + (push "bar" str -1) +; or as an alternative introduced in v.10.1 +(extend str "bar") + (println str) diff --git a/Task/String-append/PowerShell/string-append.psh b/Task/String-append/PowerShell/string-append.psh new file mode 100644 index 0000000000..ee546a310d --- /dev/null +++ b/Task/String-append/PowerShell/string-append.psh @@ -0,0 +1,3 @@ +$str = "Hello, " +$str += "World!" +$str diff --git a/Task/String-append/VBScript/string-append.vb b/Task/String-append/VBScript/string-append.vb new file mode 100644 index 0000000000..2e742f3955 --- /dev/null +++ b/Task/String-append/VBScript/string-append.vb @@ -0,0 +1,3 @@ +s = "Rosetta" +s = s & " Code" +WScript.StdOut.Write s diff --git a/Task/String-case/360-Assembly/string-case-1.360 b/Task/String-case/360-Assembly/string-case-1.360 new file mode 100644 index 0000000000..9935084017 --- /dev/null +++ b/Task/String-case/360-Assembly/string-case-1.360 @@ -0,0 +1,15 @@ +UCASE CSECT + USING UCASE,R15 + MVC UC,PG + MVC LC,PG + OC UC,=16C' ' or X'40' uppercase + NC LC,=16X'BF' and X'BF' lowercase + XPRNT PG,L'PG print original + XPRNT UC,L'UC print uc + XPRNT LC,L'LC print lc + BR R14 +PG DC CL9'alphaBETA' +UC DS CL(L'PG) +LC DS CL(L'PG) + YREGS + END UCASE diff --git a/Task/String-case/360-Assembly/string-case-2.360 b/Task/String-case/360-Assembly/string-case-2.360 new file mode 100644 index 0000000000..378d459023 --- /dev/null +++ b/Task/String-case/360-Assembly/string-case-2.360 @@ -0,0 +1,31 @@ +UCASE CSECT + USING UCASE,R15 + MVC UC,PG + MVC LC,PG + TR UC,TABLEU TR uppercase + TR LC,TABLEL TR lowercase + XPRNT PG,L'PG print original + XPRNT UC,L'UC print uc + XPRNT LC,L'LC print lc + BR R14 +PG DC CL9'alphaBETA' +UC DS CL(L'PG) +LC DS CL(L'PG) +TABLEU DC 256AL1(*-TABLEU) + ORG TABLEU+C'a' + DC C'ABCDEFGHI' + ORG TABLEU+C'j' + DC C'JKLMNOPQR' + ORG TABLEU+C's' + DC C'STUVWXYZ' + ORG +TABLEL DC 256AL1(*-TABLEL) + ORG TABLEL+C'A' + DC C'abcdefghi' + ORG TABLEL+C'J' + DC C'jklmnopqr' + ORG TABLEL+C'S' + DC C'stuvwxyz' + ORG + YREGS + END UCASE diff --git a/Task/String-case/ALGOL-W/string-case.alg b/Task/String-case/ALGOL-W/string-case.alg new file mode 100644 index 0000000000..08907ec0fd --- /dev/null +++ b/Task/String-case/ALGOL-W/string-case.alg @@ -0,0 +1,42 @@ +begin + % algol W doesn't have standard case conversion routines, this is one way % + % such facilities could be provided % + + % converts text to upper case % + % assumes the letters are contiguous in the character set (as in ASCII) % + % would not work in EBCDIC (as the original algol W implementations used) % + procedure upCase( string(256) value result text ) ; + for i := 0 until 255 do begin + string(1) c; + c := text( i // 1 ); + if c >= "a" and c <= "z" + then begin + text( i // 1 ) := code( decode( "A" ) + + ( decode( c ) - decode( "a" ) ) + ) + end + end upCase ; + + % converts text to lower case % + % assumes the letters are contiguous in the character set (as in ASCII) % + % would not work in EBCDIC (as the original algol W implementations used) % + procedure dnCase( string(256) value result text ) ; + for i := 0 until 255 do begin + string(1) c; + c := text( i // 1 ); + if c >= "A" and c <= "Z" + then begin + text( i // 1 ) := code( decode( "a" ) + + ( decode( c ) - decode( "A" ) ) + ) + end + end dnCase ; + + string(256) text; + text := "alphaBETA"; + upCase( text ); + write( text( 0 // 40 ) ); + dnCase( text ); + write( text( 0 // 40 ) ); + +end. diff --git a/Task/String-case/Elena/string-case.elena b/Task/String-case/Elena/string-case.elena new file mode 100644 index 0000000000..a6e82ccf1f --- /dev/null +++ b/Task/String-case/Elena/string-case.elena @@ -0,0 +1,15 @@ +#import system. +#import system'culture. + +#symbol program = +[ + #var s1 := "alphaBETA". + + // Alternative 1 + console writeLine:(s1::caseLiteralOp lowerCase). + console writeLine:(s1::caseLiteralOp upperCase). + + // Alternative 2 + console writeLine:(s1 toLower &locale:currentLocale). + console writeLine:(s1 toUpper &locale:currentLocale). +]. diff --git a/Task/String-case/Objective-C/string-case.m b/Task/String-case/Objective-C/string-case.m index f07dfa3bd2..8d1475ed91 100644 --- a/Task/String-case/Objective-C/string-case.m +++ b/Task/String-case/Objective-C/string-case.m @@ -1,4 +1,4 @@ -NSLog(@"%@", [@"alphaBETA" uppercaseString]); -NSLog(@"%@", [@"alphaBETA" lowercaseString]); +NSLog(@"%@", @"alphaBETA".uppercaseString); +NSLog(@"%@", @"alphaBETA".lowercaseString); -NSLog(@"%@", [@"foO BAr" capitalizedString]); // "Foo Bar" +NSLog(@"%@", @"foO BAr".capitalizedString); // "Foo Bar" diff --git a/Task/String-case/Rust/string-case.rust b/Task/String-case/Rust/string-case.rust new file mode 100644 index 0000000000..6f99c4e23e --- /dev/null +++ b/Task/String-case/Rust/string-case.rust @@ -0,0 +1,4 @@ +fn main() { + println!("{}", "jalapeño".to_uppercase()); // JALAPEÑO + println!("{}", "JALAPEÑO".to_lowercase()); // jalapeño +} diff --git a/Task/String-comparison/AppleScript/string-comparison.applescript b/Task/String-comparison/AppleScript/string-comparison.applescript new file mode 100644 index 0000000000..9c95b2ad80 --- /dev/null +++ b/Task/String-comparison/AppleScript/string-comparison.applescript @@ -0,0 +1,52 @@ +--Comparing two strings for exact equality +set s1 to "this" +set s2 to "that" +if s1 is s2 then + -- strings are equal +end if + +--Comparing two strings for inequality (i.e., the inverse of exact equality) +if s1 is not s2 then + -- string are not equal +end if + +-- Comparing two strings to see if one is lexically ordered before than the other +if s1 < s2 then + -- s1 is lexically ordered before s2 +end if + +-- Comparing two strings to see if one is lexically ordered after than the other +if s1 > s2 then + -- s1 is lexically ordered after s2 +end if + +-- How to achieve both case sensitive comparisons and case insensitive comparisons within the language +set s1 to "this" +set s2 to "This" + +considering case + if s1 is s2 then + -- strings are equal with case considering + end if +end considering + +ignoring case -- default + if s2 is s2 then + -- string are equal without case considering + end if +end ignoring + +-- Demonstrate any other kinds of string comparisons that the language provides, particularly as it relates to your type system. For example, you might demonstrate the difference between generic/polymorphic comparison and coercive/allomorphic comparison if your language supports such a distinction. + +-- When comparing the right object is coerced into the same type as the object left from the operator. This implicit coercion enables to compare integers with strings (containining integer values). + +set s1 to "3" +set int1 to 2 + +if s1 < int1 then + -- comparison is lexically +end if + +if int1 < s1 then + -- comparison is numeric +end if diff --git a/Task/String-comparison/C++/string-comparison.cpp b/Task/String-comparison/C++/string-comparison.cpp new file mode 100644 index 0000000000..4392a24a0a --- /dev/null +++ b/Task/String-comparison/C++/string-comparison.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include + +template +void demo_compare(const T &a, const T &b, const std::string &semantically) { + std::cout << a << " and " << b << " are " << ((a == b) ? "" : "not ") + << "exactly " << semantically << " equal." << std::endl; + + std::cout << a << " and " << b << " are " << ((a != b) ? "" : "not ") + << semantically << "inequal." << std::endl; + + std::cout << a << " is " << ((a < b) ? "" : "not ") << semantically + << " ordered before " << b << '.' << std::endl; + + std::cout << a << " is " << ((a > b) ? "" : "not ") << semantically + << " ordered after " << b << '.' << std::endl; +} + +int main(int argc, char *argv[]) { + // Case-sensitive comparisons. + std::string a((argc > 1) ? argv[1] : "1.2.Foo"); + std::string b((argc > 2) ? argv[2] : "1.3.Bar"); + demo_compare(a, b, "lexically"); + + // Case-insensitive comparisons by folding both strings to a common case. + std::transform(a.begin(), a.end(), a.begin(), ::tolower); + std::transform(b.begin(), b.end(), b.begin(), ::tolower); + demo_compare(a, b, "lexically"); + + // Numeric comparisons; here 'double' could be any type for which the + // relevant >> operator is defined, eg int, long, etc. + double numA, numB; + std::istringstream(a) >> numA; + std::istringstream(b) >> numB; + demo_compare(numA, numB, "numerically"); + return (a == b); +} diff --git a/Task/String-comparison/ColdFusion/string-comparison-1.cfm b/Task/String-comparison/ColdFusion/string-comparison-1.cfm new file mode 100644 index 0000000000..64f76e82b7 --- /dev/null +++ b/Task/String-comparison/ColdFusion/string-comparison-1.cfm @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Task/String-comparison/ColdFusion/string-comparison-2.cfm b/Task/String-comparison/ColdFusion/string-comparison-2.cfm new file mode 100644 index 0000000000..a92fb1f709 --- /dev/null +++ b/Task/String-comparison/ColdFusion/string-comparison-2.cfm @@ -0,0 +1,24 @@ + + function CompareString( String1, String2 ) { + VARIABLES.Result = ""; + if ( ARGUMENTS.String1 LT ARGUMENTS.String2 ) { + VARIABLES.Result = VARIABLES.Result & "('" & ARGUMENTS.String1 & "' is less than '" & ARGUMENTS.String2 & "')"; + } + if ( ARGUMENTS.String1 LTE ARGUMENTS.String2 ) { + VARIABLES.Result = VARIABLES.Result & "('" & ARGUMENTS.String1 & "' is less than or equal to '" & ARGUMENTS.String2 & "')"; + } + if ( ARGUMENTS.String1 GT ARGUMENTS.String2 ) { + VARIABLES.Result = VARIABLES.Result & "('" & ARGUMENTS.String1 & "' is greater than '" & ARGUMENTS.String2 & "')"; + } + if ( ARGUMENTS.String1 GTE ARGUMENTS.String2 ) { + VARIABLES.Result = VARIABLES.Result & "('" & ARGUMENTS.String1 & "' is greater than or equal to '" & ARGUMENTS.String2 & "')"; + } + if ( ARGUMENTS.String1 EQ ARGUMENTS.String2 ) { + VARIABLES.Result = VARIABLES.Result & "('" & ARGUMENTS.String1 & "' is equal to '" & ARGUMENTS.String2 & "')"; + } + if ( ARGUMENTS.String1 NEQ ARGUMENTS.String2 ) { + VARIABLES.Result = VARIABLES.Result & "('" & ARGUMENTS.String1 & "' is not equal to '" & ARGUMENTS.String2 & "')"; + } + return VARIABLES.Result; + } + diff --git a/Task/String-comparison/Elena/string-comparison.elena b/Task/String-comparison/Elena/string-comparison.elena new file mode 100644 index 0000000000..670060fd47 --- /dev/null +++ b/Task/String-comparison/Elena/string-comparison.elena @@ -0,0 +1,19 @@ +#import system. +#import extensions. + +#symbol compareStrings = (:val1 :val2) +[ + (val1 == val2)? [ console writeLine:"The strings ":val1:" and ":val2:" are equal". ]. + (val1 != val2)? [ console writeLine:"The strings ":val1:" and ":val2:" are not equal". ]. + (val1 > val2)? [ console writeLine:"The string ":val1:" is lexically after than ":val2. ]. + (val1 < val2)? [ console writeLine:"The string ":val1:" is lexically before than ":val2. ]. + (val1 >= val2)? [ console writeLine:"The string ":val1:" is not lexically before than ":val2. ]. + (val1 <= val2)? [ console writeLine:"The string ":val1:" is not lexically after than ":val2. ]. +]. + +#symbol program = +[ + #var s1 := "this". + #var s2 := "that". + compareStrings :s1 :s2. +]. diff --git a/Task/String-comparison/Elixir/string-comparison.elixir b/Task/String-comparison/Elixir/string-comparison.elixir new file mode 100644 index 0000000000..941679dbdb --- /dev/null +++ b/Task/String-comparison/Elixir/string-comparison.elixir @@ -0,0 +1,9 @@ +s = "abcd" +s == "abcd" #=> true +s == "abce" #=> false +s != "abcd" #=> false +s != "abce" #=> true +s > "abcd" #=> false +s < "abce" #=> true +s >= "abce" #=> false +s <= "abce" #=> true diff --git a/Task/String-comparison/PowerShell/string-comparison-1.psh b/Task/String-comparison/PowerShell/string-comparison-1.psh new file mode 100644 index 0000000000..e91e05eca5 --- /dev/null +++ b/Task/String-comparison/PowerShell/string-comparison-1.psh @@ -0,0 +1,6 @@ +"a" -lt "b" # lower than +"a" -eq "b" # equal +"a" -gt "b" # greater than +"a" -le "b" # lower than or equal +"a" -ne "b" # not equal +"a" -ge "b" # greater than or equal diff --git a/Task/String-comparison/PowerShell/string-comparison-2.psh b/Task/String-comparison/PowerShell/string-comparison-2.psh new file mode 100644 index 0000000000..029fb8a0ef --- /dev/null +++ b/Task/String-comparison/PowerShell/string-comparison-2.psh @@ -0,0 +1,2 @@ +"a" -eq "A" +"a" -ceq "A" diff --git a/Task/String-comparison/Rust/string-comparison.rust b/Task/String-comparison/Rust/string-comparison.rust new file mode 100644 index 0000000000..7df33ee309 --- /dev/null +++ b/Task/String-comparison/Rust/string-comparison.rust @@ -0,0 +1,29 @@ +use std::ascii::AsciiExt; // for case insensitives only + +fn main() { + // only same types can be compared + // String and String or &str and &str + // exception: strict equality and inequality also work on &str and String + let a: &str = "abc"; + let b: String = "Bac".to_owned(); + + // Strings are coerced to &str when borrowed and needed + if a == b { println!("The strings are equal") } + if a != b { println!("The strings are not equal") } + if a > &b { println!("The first string is lexically after the second") } + if a < &b { println!("The first string is lexically before the second") } + if a >= &b { println!("The first string is not lexically before the second") } + if a <= &b { println!("The first string is not lexically after the second") } + + // case-insensitives: + + // equality + // this avoids new allocations + if a.eq_ignore_ascii_case(&b) { println!("Both strings are equal when ignoring case") } + + // everything else, create owned Strings, then compare as above + let a2 = a.to_ascii_uppercase(); + let b2 = b.to_ascii_uppercase(); + + // repeat checks +} diff --git a/Task/String-concatenation/ABAP/string-concatenation.abap b/Task/String-concatenation/ABAP/string-concatenation.abap new file mode 100644 index 0000000000..c15ccc9650 --- /dev/null +++ b/Task/String-concatenation/ABAP/string-concatenation.abap @@ -0,0 +1,7 @@ +DATA: s1 TYPE string, + s2 TYPE string. + +s1 = 'Hello'. +CONCATENATE s1 ' literal' INTO s2 RESPECTING BLANKS. +WRITE: / s1. +WRITE: / s2. diff --git a/Task/String-concatenation/DCL/string-concatenation.dcl b/Task/String-concatenation/DCL/string-concatenation.dcl new file mode 100644 index 0000000000..19c88e3f9d --- /dev/null +++ b/Task/String-concatenation/DCL/string-concatenation.dcl @@ -0,0 +1,3 @@ +$ string1 = "hello" +$ string2 = string1 + " world" +$ show symbol string* diff --git a/Task/String-concatenation/Elena/string-concatenation.elena b/Task/String-concatenation/Elena/string-concatenation.elena new file mode 100644 index 0000000000..b0e2dbf3f5 --- /dev/null +++ b/Task/String-concatenation/Elena/string-concatenation.elena @@ -0,0 +1,11 @@ +#import system. +#import extensions. + +#symbol program = +[ + #var s := "Hello". + #var s2 := s + " literal". + + console writeLine:s. + console writeLine:s2. +]. diff --git a/Task/String-concatenation/Emacs-Lisp/string-concatenation-1.l b/Task/String-concatenation/Emacs-Lisp/string-concatenation-1.l new file mode 100644 index 0000000000..ce0fea35ac --- /dev/null +++ b/Task/String-concatenation/Emacs-Lisp/string-concatenation-1.l @@ -0,0 +1,2 @@ +(defun glue (str1 str2) + (concat str1 str2) ) diff --git a/Task/String-concatenation/Emacs-Lisp/string-concatenation-2.l b/Task/String-concatenation/Emacs-Lisp/string-concatenation-2.l new file mode 100644 index 0000000000..47be3a5570 --- /dev/null +++ b/Task/String-concatenation/Emacs-Lisp/string-concatenation-2.l @@ -0,0 +1,2 @@ +(defun glue (str1 str2) + (format "%s%s" str1 str2) ) diff --git a/Task/String-concatenation/Emacs-Lisp/string-concatenation-3.l b/Task/String-concatenation/Emacs-Lisp/string-concatenation-3.l new file mode 100644 index 0000000000..39e5dec8b5 --- /dev/null +++ b/Task/String-concatenation/Emacs-Lisp/string-concatenation-3.l @@ -0,0 +1,3 @@ +(setq str1 "Hello, ") +(setq str2 "World!") +(insert (glue str1 str2) ) diff --git a/Task/String-concatenation/Rust/string-concatenation.rust b/Task/String-concatenation/Rust/string-concatenation.rust index ec6f85fb50..83bc385b43 100644 --- a/Task/String-concatenation/Rust/string-concatenation.rust +++ b/Task/String-concatenation/Rust/string-concatenation.rust @@ -1,7 +1,5 @@ -// rust 0.13 - fn main() { - let s = "hello".to_string(); + let s = "hello".to_owned(); println!("{}", s); let s1 = s + " world"; diff --git a/Task/String-concatenation/TI-83-BASIC/string-concatenation.ti-83 b/Task/String-concatenation/TI-83-BASIC/string-concatenation.ti-83 new file mode 100644 index 0000000000..ea0ad85434 --- /dev/null +++ b/Task/String-concatenation/TI-83-BASIC/string-concatenation.ti-83 @@ -0,0 +1,2 @@ +"HELLO"→Str0 +Str0+" WORLD!"→Str0 diff --git a/Task/String-interpolation--included-/Elena/string-interpolation--included-.elena b/Task/String-interpolation--included-/Elena/string-interpolation--included-.elena new file mode 100644 index 0000000000..a3f061c54e --- /dev/null +++ b/Task/String-interpolation--included-/Elena/string-interpolation--included-.elena @@ -0,0 +1,7 @@ +#import system. + +#symbol program = +[ + #var s := "Mary had a @@x lamb." replace &literal:"@@x" &literal:"little". + console writeLine:s. +]. diff --git a/Task/String-length/PHP/string-length.php b/Task/String-length/PHP/string-length.php new file mode 100644 index 0000000000..d40d923166 --- /dev/null +++ b/Task/String-length/PHP/string-length.php @@ -0,0 +1,5 @@ +) { + match possible_match { + Some(match_pos) => println!("Found match at pos {}", match_pos), + None => println!("Did not find any matches") + } +} + +fn main() { + let s1 = "abcd"; + let s2 = "abab"; + let s3 = "ab"; + + // Determining if the first string starts with second string + assert!(s1.starts_with(s3)); + // Determining if the first string contains the second string at any location + assert!(s1.contains(s3)); + // Print the location of the match + print_match(s1.find(s3)); // Found match at pos 0 + print_match(s1.find(s2)); // Did not find any matches + // Determining if the first string ends with the second string + assert!(s2.ends_with(s3)); +} diff --git a/Task/String-matching/VBScript/string-matching.vb b/Task/String-matching/VBScript/string-matching.vb new file mode 100644 index 0000000000..9ce40a09c6 --- /dev/null +++ b/Task/String-matching/VBScript/string-matching.vb @@ -0,0 +1,43 @@ +Function StartsWith(s1,s2) + StartsWith = False + If Left(s1,Len(s2)) = s2 Then + StartsWith = True + End If +End Function + +Function Contains(s1,s2) + Contains = False + If InStr(1,s1,s2) Then + Contains = True & " at positions " + j = 1 + Do Until InStr(j,s1,s2) = False + Contains = Contains & InStr(j,s1,s2) & ", " + If j = 1 Then + If Len(s2) = 1 Then + j = j + InStr(j,s1,s2) + Else + j = j + (InStr(j,s1,s2) + (Len(s2) - 1)) + End If + Else + If Len(s2) = 1 Then + j = j + ((InStr(j,s1,s2) - j) + 1) + Else + j = j + ((InStr(j,s1,s2) - j) + (Len(s2) - 1)) + End If + End If + Loop + End If +End Function + +Function EndsWith(s1,s2) + EndsWith = False + If Right(s1,Len(s2)) = s2 Then + EndsWith = True + End If +End Function + +WScript.StdOut.Write "Starts with test, 'foo' in 'foobar': " & StartsWith("foobar","foo") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Contains test, 'o' in 'fooooobar': " & Contains("fooooobar","o") +WScript.StdOut.WriteLine +WScript.StdOut.Write "Ends with test, 'bar' in 'foobar': " & EndsWith("foobar","bar") diff --git a/Task/String-prepend/Elena/string-prepend.elena b/Task/String-prepend/Elena/string-prepend.elena new file mode 100644 index 0000000000..c33704378b --- /dev/null +++ b/Task/String-prepend/Elena/string-prepend.elena @@ -0,0 +1,13 @@ +#import system. + +#symbol program = +[ + #var s := "World". + s := "Hello " + s. + console writeLine:s. + + // Alternative way + #var s2 := String new:"World". + s2 insert:"Hello " &at:0. + console writeLine:s2. +]. diff --git a/Task/String-prepend/Elixir/string-prepend.elixir b/Task/String-prepend/Elixir/string-prepend.elixir new file mode 100644 index 0000000000..16bdf65b3d --- /dev/null +++ b/Task/String-prepend/Elixir/string-prepend.elixir @@ -0,0 +1,2 @@ +str1 = "World!" +str = "Hello, " <> str1 diff --git a/Task/String-prepend/Emacs-Lisp/string-prepend-1.l b/Task/String-prepend/Emacs-Lisp/string-prepend-1.l new file mode 100644 index 0000000000..ce0fea35ac --- /dev/null +++ b/Task/String-prepend/Emacs-Lisp/string-prepend-1.l @@ -0,0 +1,2 @@ +(defun glue (str1 str2) + (concat str1 str2) ) diff --git a/Task/String-prepend/Emacs-Lisp/string-prepend-2.l b/Task/String-prepend/Emacs-Lisp/string-prepend-2.l new file mode 100644 index 0000000000..47be3a5570 --- /dev/null +++ b/Task/String-prepend/Emacs-Lisp/string-prepend-2.l @@ -0,0 +1,2 @@ +(defun glue (str1 str2) + (format "%s%s" str1 str2) ) diff --git a/Task/String-prepend/Emacs-Lisp/string-prepend-3.l b/Task/String-prepend/Emacs-Lisp/string-prepend-3.l new file mode 100644 index 0000000000..c0b64005af --- /dev/null +++ b/Task/String-prepend/Emacs-Lisp/string-prepend-3.l @@ -0,0 +1,3 @@ +(setq str "World!") +(setq str (glue "Hello, " str) ) +(insert str) diff --git a/Task/String-prepend/PowerShell/string-prepend.psh b/Task/String-prepend/PowerShell/string-prepend.psh new file mode 100644 index 0000000000..88f8bb054d --- /dev/null +++ b/Task/String-prepend/PowerShell/string-prepend.psh @@ -0,0 +1,3 @@ +$str = "World!" +$str = "Hello, " + $str +$str diff --git a/Task/String-prepend/REXX/string-prepend.rexx b/Task/String-prepend/REXX/string-prepend.rexx index 37f7389f81..78d3b40686 100644 --- a/Task/String-prepend/REXX/string-prepend.rexx +++ b/Task/String-prepend/REXX/string-prepend.rexx @@ -1,17 +1,14 @@ - /*──────────────── using literal abuttal. */ - /*──────────────── this won't work as the first */ - /*──────────────── variable name is X or B */ -zz='llo world!' -zz='he'zz +zz= 'llo world!' /*─────────────── using literal abuttal.────────────*/ +zz= 'he'zz /*This won't work if the variable name is X or B */ say zz - /*──────────────── using literal concatenation. */ -gg = "llo world!" + +gg = "llo world!" /*─────────────── using literal concatenation.──────*/ gg = 'he' || gg say gg - /*──────────────── using variable concatenation.*/ -aString = 'llo world!' -bString = "he" -aString = bString || aString + +aString= 'llo world!' /*─────────────── using variable concatenation.─────*/ +bString= "he" +aString= bString || aString say aString diff --git a/Task/String-prepend/VBScript/string-prepend.vb b/Task/String-prepend/VBScript/string-prepend.vb new file mode 100644 index 0000000000..df8157a3dd --- /dev/null +++ b/Task/String-prepend/VBScript/string-prepend.vb @@ -0,0 +1,3 @@ +s = "bar" +s = "foo" & s +WScript.Echo s diff --git a/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string.applescript b/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string.applescript new file mode 100644 index 0000000000..de818d4072 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/AppleScript/strip-a-set-of-characters-from-a-string.applescript @@ -0,0 +1,13 @@ +stripChar("She was a soul stripper. She took my heart!", "aei") + +on stripChar(str, chrs) + tell AppleScript + set oldTIDs to text item delimiters + set text item delimiters to characters of chrs + set TIs to text items of str + set text item delimiters to "" + set str to TIs as string + set text item delimiters to oldTIDs + end tell + return str +end stripChar diff --git a/Task/Strip-a-set-of-characters-from-a-string/Forth/strip-a-set-of-characters-from-a-string-1.fth b/Task/Strip-a-set-of-characters-from-a-string/Forth/strip-a-set-of-characters-from-a-string-1.fth new file mode 100644 index 0000000000..2c1f72237c --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Forth/strip-a-set-of-characters-from-a-string-1.fth @@ -0,0 +1,39 @@ +\ rosetta Code strip chars from a string +\ Forth is a low level language that is extended to solve your problem +\ Using the Forth parser, primitive memory operations and the stack +\ for data transfer between functions, we create high level functionality +\ STRIPCHARS here has 1st Argument as the chars. If you don't like it +\ reverse the arguments with SWAP. :) + +create buffer1 256 allot \ temp buffer, returns its address to the stack + +\ extend the language a little +: STRING, ( addr len -- ) \ compile a string at the next available memory (called 'HERE') + here over 1+ allot place ; + +: APPEND-CHAR ( char string -- ) \ append char to a counted string + dup >r count dup 1+ r> c! + c! ; + +: ," [CHAR] " PARSE STRING, ; \ Parse input stream until '"' and compile into memory + +: ="" ( cstring -- ) 0 swap c! ; \ empty a counted string by setting count to zero + +: writestr ( cstring -- ) \ print a counted string from the stack with new line + count type cr ; + + +\ use our language extensions +create "aei" ," aei" +create input ," She was a soul stripper. She took my heart!" + +: stripchars ( str1 str2 -- str3 ) \ chars are 1st argument, str2 is the input string + buffer1 ="" \ clear the buffer + count bounds \ calc loop limits for str2 + DO + dup count I C@ scan 0= \ scan for char in str1, test for zero + IF \ if NOT found + I c@ buffer1 append-char \ append the str2 char to buffer1 + THEN \ ... and then ... continue the loop + LOOP + drop \ we don't need str1 now + buffer1 ; \ addr of buffer1 put on stack as the output diff --git a/Task/Strip-a-set-of-characters-from-a-string/Forth/strip-a-set-of-characters-from-a-string-2.fth b/Task/Strip-a-set-of-characters-from-a-string/Forth/strip-a-set-of-characters-from-a-string-2.fth new file mode 100644 index 0000000000..79b3cb406c --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Forth/strip-a-set-of-characters-from-a-string-2.fth @@ -0,0 +1,6 @@ +: ?exit ( c1 c2 -- ) ]] = if drop unloop exit then [[ ; immediate +: .stripped ( a u c -- ) -rot bounds ?do dup i c@ ?exit loop emit ; +: stripchars ( a1 u1 a2 u2 -- ) bounds ?do 2dup i c@ .stripped loop 2drop ; + +: "aei" s" aei" ; +"aei" s" She was a soul stripper. She took my heart!" stripchars diff --git a/Task/Strip-a-set-of-characters-from-a-string/Julia/strip-a-set-of-characters-from-a-string.julia b/Task/Strip-a-set-of-characters-from-a-string/Julia/strip-a-set-of-characters-from-a-string.julia new file mode 100644 index 0000000000..f9b9556025 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Julia/strip-a-set-of-characters-from-a-string.julia @@ -0,0 +1,8 @@ +function fullstrip(s::String, r::String) + replace(s, Set(r), "") +end + +tests = "She was a soul stripper. She took my heart!" +testr = "aei" + +println(tests, " => ", fullstrip(tests, testr)) diff --git a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx index 24bc0c1c2e..6c5ab3dd72 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx +++ b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-2.rexx @@ -1,14 +1,10 @@ -/* REXX *************************************************************** -* If source and stripchars don't contain a hex 00 character, this works -* 06.07.2012 Walter Pachl -* 19.06.2013 -"- space(result,0) -> space(result,0,' ') -* space(result,0) removes WHITESPACE not only blanks -**********************************************************************/ -Say 'Sh ws soul strppr. Sh took my hrt! -- expected' -Say stripchars("She was a soul stripper. She took my heart!","aei") -Exit -stripchars: Parse Arg string,stripchars -result=translate(string,'00'x,' ') /* turn blanks into '00'x */ -result=translate(result,' ',stripchars) /* turn stripchars into ' ' */ -result=space(result,0,' ') /* remove all blanks */ -Return translate(result,' ','00'x) /* '00'x back to blanks */ +/* REXX */ +say StripChars('She was a soul stripper. She took my heart!','iea') +exit 0 + +StripChars: procedure +parse arg strng,remove +removepos=Verify(strng,remove,'MATCH') +if removepos=0 then return strng +parse value strng with strng =(removepos) +1 rest +return strng || StripChars(rest,remove) diff --git a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-3.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-3.rexx index b6b9647afd..24bc0c1c2e 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-3.rexx +++ b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-3.rexx @@ -1,9 +1,14 @@ -stripchars: Procedure - Parse Arg i,s /* get input and chars to be removed */ - o='' /* initialize result */ - Do While i\=='' /* loop through input */ - Parse Var i c +1 i /* get one character */ - If pos(c,s)=0 Then /* it's not to be removed */ - o=o||c /* append it to the result */ - End - Return o /* return the result */ +/* REXX *************************************************************** +* If source and stripchars don't contain a hex 00 character, this works +* 06.07.2012 Walter Pachl +* 19.06.2013 -"- space(result,0) -> space(result,0,' ') +* space(result,0) removes WHITESPACE not only blanks +**********************************************************************/ +Say 'Sh ws soul strppr. Sh took my hrt! -- expected' +Say stripchars("She was a soul stripper. She took my heart!","aei") +Exit +stripchars: Parse Arg string,stripchars +result=translate(string,'00'x,' ') /* turn blanks into '00'x */ +result=translate(result,' ',stripchars) /* turn stripchars into ' ' */ +result=space(result,0,' ') /* remove all blanks */ +Return translate(result,' ','00'x) /* '00'x back to blanks */ diff --git a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-4.rexx b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-4.rexx index 4b1d54aa04..b6b9647afd 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-4.rexx +++ b/Task/Strip-a-set-of-characters-from-a-string/REXX/strip-a-set-of-characters-from-a-string-4.rexx @@ -1,12 +1,9 @@ -/* REXX *************************************************************** -* If source and stripchars don't contain a hex 00 character, this works -* 06.07.2012 Walter Pachl -**********************************************************************/ -Say 'Sh ws soul strppr. Sh took my hrt! -- expected' -Say stripchars("She was a soul stripper. She took my heart!","aei") -Exit -stripchars: Parse Arg string,stripchars -result=translate(string,'00'x,' ') /* turn blanks into '00'x */ -result=translate(result,' ',stripchars) /* turn stripchars into ' ' */ -result=space(result,0) /* remove all blanks */ -Return translate(result,' ','00'x) /* '00'x back to blanks */ +stripchars: Procedure + Parse Arg i,s /* get input and chars to be removed */ + o='' /* initialize result */ + Do While i\=='' /* loop through input */ + Parse Var i c +1 i /* get one character */ + If pos(c,s)=0 Then /* it's not to be removed */ + o=o||c /* append it to the result */ + End + Return o /* return the result */ diff --git a/Task/Strip-a-set-of-characters-from-a-string/VBScript/strip-a-set-of-characters-from-a-string.vb b/Task/Strip-a-set-of-characters-from-a-string/VBScript/strip-a-set-of-characters-from-a-string.vb new file mode 100644 index 0000000000..f712b473c2 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/VBScript/strip-a-set-of-characters-from-a-string.vb @@ -0,0 +1,10 @@ +Function stripchars(s1,s2) + For i = 1 To Len(s1) + If InStr(s2,Mid(s1,i,1)) Then + s1 = Replace(s1,Mid(s1,i,1),"") + End If + Next + stripchars = s1 +End Function + +WScript.StdOut.Write stripchars("She was a soul stripper. She took my heart!","aei") diff --git a/Task/Strip-block-comments/Haskell/strip-block-comments-1.hs b/Task/Strip-block-comments/Haskell/strip-block-comments-1.hs new file mode 100644 index 0000000000..d05834e884 --- /dev/null +++ b/Task/Strip-block-comments/Haskell/strip-block-comments-1.hs @@ -0,0 +1 @@ +test = "This {- is not the beginning of a block comment" -- Do your homework properly -} diff --git a/Task/Strip-block-comments/Haskell/strip-block-comments.hs b/Task/Strip-block-comments/Haskell/strip-block-comments-2.hs similarity index 100% rename from Task/Strip-block-comments/Haskell/strip-block-comments.hs rename to Task/Strip-block-comments/Haskell/strip-block-comments-2.hs diff --git a/Task/Strip-comments-from-a-string/Julia/strip-comments-from-a-string.julia b/Task/Strip-comments-from-a-string/Julia/strip-comments-from-a-string.julia new file mode 100644 index 0000000000..431172b955 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Julia/strip-comments-from-a-string.julia @@ -0,0 +1,20 @@ +function striplinecomment{T<:String,U<:String}(a::T, cchars::U="#;") + b = strip(a) + 0 < length(cchars) || return b + for c in cchars + r = Regex(@sprintf "\\%c.*" c) + b = replace(b, r, "") + end + strip(b) +end + +tests = {"apples, pears # and bananas", + "apples, pears ; and bananas", + " apples, pears & bananas ", + " # "} + +for t in tests + s = striplinecomment(t) + println("Testing \"", t, "\":") + println(" \"", s, "\"") +end diff --git a/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-3.py b/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-3.py new file mode 100644 index 0000000000..44001e73f8 --- /dev/null +++ b/Task/Strip-comments-from-a-string/Python/strip-comments-from-a-string-3.py @@ -0,0 +1,5 @@ +import re + +m = re.match(r'^([^#]*)#(.*)$', line) +if m: # The line contains a hash / comment + line = m.group(1) diff --git a/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string-1.rexx b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string-1.rexx new file mode 100644 index 0000000000..75c90b3ef5 --- /dev/null +++ b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string-1.rexx @@ -0,0 +1,41 @@ +/*REXX program strips a string delineated by a hash (#) or a semicolon (;). */ +old1=' apples, pears # and bananas' ; say ' old ───►'old1"◄───" +new1=stripCom1(old1) ; say '1st version new ───►'new1"◄───" +new2=stripCom2(old1) ; say '2nd version new ───►'new2"◄───" +new3=stripCom3(old1) ; say '3rd version new ───►'new3"◄───" +new4=stripCom4(old1) ; say '4th version new ───►'new4"◄───" + say copies('═',55) +old2=' apples, pears ; and bananas' ; say ' old ───►'old2"◄───" +new1=stripCom1(old2) ; say '1st version new ───►'new1"◄───" +new2=stripCom2(old2) ; say '2nd version new ───►'new2"◄───" +new3=stripCom3(old2) ; say '3rd version new ───►'new3"◄───" +new4=stripCom4(old2) ; say '4th version new ───►'new4"◄───" +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +stripCom1: procedure; parse arg x /*obtain the argument (the X string).*/ +x=translate(x, '#', ";") /*translate semicolons to a hash (#). */ +parse var x x '#' /*parse the X string, ending in hash. */ +return strip(x) /*return the striped shortened string. */ +/*────────────────────────────────────────────────────────────────────────────*/ +stripCom2: procedure; parse arg x /*obtain the argument (the X string).*/ +d = ';#' /*this is the delimiter list to be used*/ +d1=left(d,1) /*get the first character in delimiter.*/ +x=translate(x,copies(d1,length(d)),d) /*translates delimiters ──► 1st delim.*/ +parse var x x (d1) /*parse the string, ending in a hash. */ +return strip(x) /*return the striped shortened string. */ +/*────────────────────────────────────────────────────────────────────────────*/ +stripCom3: procedure; parse arg x /*obtain the argument (the X string).*/ +d = ';#' /*this is the delimiter list to be used*/ + do j=1 for length(d) /*process each of the delimiters singly*/ + _=substr(d,j,1) /*use only one delimiter at a time. */ + parse var x x (_) /*parse the X string for each delim. */ + end /*j*/ /* [↑] (_) means stop parsing at _ */ +return strip(x) /*return the striped shortened string. */ +/*────────────────────────────────────────────────────────────────────────────*/ +stripCom4: procedure; parse arg x /*obtain the argument (the X string).*/ +d = ';#' /*this is the delimiter list to be used*/ + do k=1 for length(d) /*process each of the delimiters singly*/ + p=pos(substr(d,k,1), x) /*see if a delimiter is in the X string*/ + if p\==0 then x=left(x,p-1) /*shorten the X string by one character*/ + end /*k*/ /* [↑] If p==0, then char wasn't found*/ +return strip(x) /*return the striped shortened string. */ diff --git a/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string-2.rexx b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string-2.rexx new file mode 100644 index 0000000000..8ec44b7ec9 --- /dev/null +++ b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string-2.rexx @@ -0,0 +1,14 @@ +Call stripd ' apples, pears # and bananas' +Call stripd ' apples, pears and bananas' +Exit +stripd: + Parse Arg old + dlist='#;' /* delimiter list */ + p=verify(old,dlist,'M') /* find position of delimiter */ + If p>0 Then /* delimiter found */ + new=strip(left(old,p-1)) + Else + new=strip(old) + Say '>'old'<' + Say '>'new'<' + Return diff --git a/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx deleted file mode 100644 index 39c1839872..0000000000 --- a/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx +++ /dev/null @@ -1,41 +0,0 @@ -/*REXX program strips a string delinated by a hash (#) or semicolon (;).*/ -old1=' apples, pears # and bananas' ; say ' old ───►'old1"◄───" -new1=stripCom1(old1) ; say '1st version new ───►'new1"◄───" -new2=stripCom2(old1) ; say '2nd version new ───►'new2"◄───" -new3=stripCom3(old1) ; say '3rd version new ───►'new3"◄───" -new4=stripCom3(old1) ; say '4th version new ───►'new4"◄───" - say copies('═',55) -old2=' apples, pears ; and bananas' ; say ' old ───►'old2"◄───" -new1=stripCom1(old2) ; say '1st version new ───►'new1"◄───" -new2=stripCom2(old2) ; say '2nd version new ───►'new2"◄───" -new3=stripCom3(old2) ; say '3rd version new ───►'new3"◄───" -new4=stripCom3(old2) ; say '4th version new ───►'new4"◄───" -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────STRIPCOM1 subroutine────────────────*/ -stripCom1: procedure; parse arg x /*get the argument (string). */ -x=translate(x, '#', ";") /*translate semicolons to hash. */ -parse var x x '#' /*parse string, ending in hash. */ -return strip(x) /*return striped shortened string*/ -/*──────────────────────────────────STRIPCOM2 subroutine────────────────*/ -stripCom2: procedure; parse arg x /*get the argument (string). */ -d = ';#' /*the delimiter list to be used. */ -d1=left(d,1) /*get the 1st character in delim.*/ -x=translate(x,copies(d1,length(d)),d) /*trans all delims ──► 1st delim.*/ -parse var x x (d1) /*parse string, ending in hash. */ -return strip(x) /*return striped shortened string*/ -/*──────────────────────────────────STRIPCOM3 subroutine────────────────*/ -stripCom3: procedure; parse arg x /*get the argument (string). */ -d = ';#' /*the delimiter list to be used. */ - do j=1 for length(d) /*process each delimiter singly. */ - _=substr(d,j,1) /*use one delimiter at a time. */ - parse var x x (_) /*parse X string for each delim. */ - end /*j*/ -return strip(x) /*return striped shortened string*/ -/*──────────────────────────────────STRIPCOM4 subroutine────────────────*/ -stripCom4: procedure; parse arg x /*get the argument (string). */ -d = ';#' /*the delimiter list to be used. */ - do k=1 for length(d) /*process each delimiter singly. */ - p=pos(substr(d,k,1),x) /*see if a delimiter is in X. */ - if p\==0 then x=left(x,p-1) /*shorten the X string.*/ - end /*k*/ -return strip(x) /*return striped shortened string*/ diff --git a/Task/Strip-comments-from-a-string/VBScript/strip-comments-from-a-string.vb b/Task/Strip-comments-from-a-string/VBScript/strip-comments-from-a-string.vb new file mode 100644 index 0000000000..72d1512059 --- /dev/null +++ b/Task/Strip-comments-from-a-string/VBScript/strip-comments-from-a-string.vb @@ -0,0 +1,11 @@ +Function strip_comments(s,char) + If InStr(1,s,char) > 0 Then + arr = Split(s,char) + strip_comments = RTrim(arr(0)) + Else + strip_comments = s + End If +End Function + +WScript.StdOut.WriteLine strip_comments("apples, pears # and bananas","#") +WScript.StdOut.WriteLine strip_comments("apples, pears ; and bananas",";") diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Julia/strip-control-codes-and-extended-characters-from-a-string.julia b/Task/Strip-control-codes-and-extended-characters-from-a-string/Julia/strip-control-codes-and-extended-characters-from-a-string.julia new file mode 100644 index 0000000000..63dde3c3cb --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Julia/strip-control-codes-and-extended-characters-from-a-string.julia @@ -0,0 +1,8 @@ +stripc0{T<:String}(a::T) = replace(a, r"[\x00-\x1f\x7f]", "") +stripc0x{T<:String}(a::T) = replace(a, r"[^\x20-\x7e]", "") + +a = "a\n\tb\u2102d\u2147f" + +println("Original String:\n ", a) +println("\nWith C0 control characters removed:\n ", stripc0(a)) +println("\nWith C0 and extended characters removed:\n ", stripc0x(a)) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py b/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py index 8ae4b5da0c..a2f055eb98 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Python/strip-control-codes-and-extended-characters-from-a-string-1.py @@ -1,4 +1,3 @@ -def stripped(x): - return "".join([i for i in x if 31 < ord(i) < 127]) +stripped = lambda s: "".join(i for i in s if 31 < ord(i) < 127) -print stripped("\ba\x00b\n\rc\fd\xc3") +print(stripped("\ba\x00b\n\rc\fd\xc3")) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Ruby/strip-control-codes-and-extended-characters-from-a-string.rb b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ruby/strip-control-codes-and-extended-characters-from-a-string.rb index 1b5d10b6e8..6c785227fc 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Ruby/strip-control-codes-and-extended-characters-from-a-string.rb +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Ruby/strip-control-codes-and-extended-characters-from-a-string.rb @@ -1,20 +1,13 @@ class String - def strip_control_characters() - self.chars.inject("") do |str, char| - unless char.ascii_only? and (char.ord < 32 or char.ord == 127) - str << char - end - str + chars.each_with_object("") do |char, str| + str << char unless char.ascii_only? and (char.ord < 32 or char.ord == 127) end end def strip_control_and_extended_characters() - self.chars.inject("") do |str, char| - if char.ascii_only? and char.ord.between?(32,126) - str << char - end - str + chars.each_with_object("") do |char, str| + str << char if char.ascii_only? and char.ord.between?(32,126) end end end diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/VBScript/strip-control-codes-and-extended-characters-from-a-string.vb b/Task/Strip-control-codes-and-extended-characters-from-a-string/VBScript/strip-control-codes-and-extended-characters-from-a-string.vb new file mode 100644 index 0000000000..376d0552a0 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/VBScript/strip-control-codes-and-extended-characters-from-a-string.vb @@ -0,0 +1,26 @@ +Function StripCtrlCodes(s) + tmp = "" + For i = 1 To Len(s) + n = Asc(Mid(s,i,1)) + If (n >= 32 And n <= 126) Or n >=128 Then + tmp = tmp & Mid(s,i,1) + End If + Next + StripCtrlCodes = tmp +End Function + +Function StripCtrlCodesExtChrs(s) + tmp = "" + For i = 1 To Len(s) + n = Asc(Mid(s,i,1)) + If n >= 32 And n <= 126 Then + tmp = tmp & Mid(s,i,1) + End If + Next + StripCtrlCodesExtChrs = tmp +End Function + +WScript.StdOut.Write "ab�cd�ef�gh€" & " = " & StripCtrlCodes("ab�cd�ef�gh€") +WScript.StdOut.WriteLine +WScript.StdOut.Write "ab�cd�ef�ghij†klð€" & " = " & StripCtrlCodesExtChrs("ab�cd�ef�ghij†klð€") +WScript.StdOut.WriteLine diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail-1.awk b/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail-1.awk new file mode 100644 index 0000000000..2e2f1f5d6e --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail-1.awk @@ -0,0 +1,29 @@ +function trimleft(str ,c, out, arr) { + c = split(str, arr, "") + for ( i = match(str, /[[:graph:]]/); i <= c; i++) + out = out arr[i] + return out +} + +function reverse(str ,n, tmp, j, out) { + n = split(str, tmp, "") + for (j = n; j > 0; j--) + out = out tmp[j] + return out +} + +function trimright(str) { + return reverse(trimleft(reverse(str))) +} + +function trim(str) { + return trimright(trimleft(str)) +} + +BEGIN { + str = " \x0B\t\r\n \xA0 Hellö \xA0\x0B\t\r\n " + print "string = |" str "|" + print "left = |" trimleft(str) "|" + print "right = |" trimright(str) "|" + print "both = |" trim(str) "|" +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail-2.awk b/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail-2.awk new file mode 100644 index 0000000000..5267c643fc --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail-2.awk @@ -0,0 +1,6 @@ +function trim(str) { + gsub(/^[[:blank:]]+/,"", str) # Remove leading + gsub(/[[:blank:]]+$/,"", str) # Remove trailing + gsub(/^[[:blank:]]+|[[:blank:]]+$/, "", str) # Remove both + return str; +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail.awk b/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail.awk deleted file mode 100644 index 22fdeeca3b..0000000000 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/AWK/strip-whitespace-from-a-string-top-and-tail.awk +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/awk -f -function trim(str) { - sub(/^[ \t]+/,"",str); # remove leading whitespaces - sub(/[ \t]+$/,"",str); # remove trailing whitespaces - return str; -} -{ - print trim($0); -} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir b/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir index c0f188035d..015de1bf66 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir @@ -1,3 +1,4 @@ -IO.puts "'" <> String.strip(" x ") <> "'" -IO.puts "'" <> String.rstrip(" x ") <> "'" -IO.puts "'" <> String.lstrip(" x ") <> "'" +str = "\n \t foo bar \t \n" +IO.inspect String.strip(str) +IO.inspect String.rstrip(str) +IO.inspect String.lstrip(str) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-1.l b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-1.l new file mode 100644 index 0000000000..f8e1b9a0e0 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-1.l @@ -0,0 +1,5 @@ +(defun trim-l (str) + (replace-regexp-in-string "^ +" "" str) ) + +(setq str " left between right ") +(insert (trim-l str) ) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-2.l b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-2.l new file mode 100644 index 0000000000..84eb04860a --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-2.l @@ -0,0 +1,5 @@ +(defun trim-r (str) + (replace-regexp-in-string " +$" "" str) ) + +(setq str " left between right ") +(insert (trim-r str) ) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-3.l b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-3.l new file mode 100644 index 0000000000..284c2c26a4 --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-3.l @@ -0,0 +1,5 @@ +(defun trim (str) + (trim-l (trim-r str) )) + +(setq str " left between right ") +(insert (trim str) ) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-4.l b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-4.l new file mode 100644 index 0000000000..45539fe71b --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Emacs-Lisp/strip-whitespace-from-a-string-top-and-tail-4.l @@ -0,0 +1,5 @@ +(defun trim (str) + (mapconcat 'identity (split-string str) " ") ) + +(setq str " left between right ") +(insert (trim str) ) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/PowerShell/strip-whitespace-from-a-string-top-and-tail.psh b/Task/Strip-whitespace-from-a-string-Top-and-tail/PowerShell/strip-whitespace-from-a-string-top-and-tail.psh new file mode 100644 index 0000000000..2aed20bdfb --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/PowerShell/strip-whitespace-from-a-string-top-and-tail.psh @@ -0,0 +1,4 @@ +$var = " Hello World " +$var.TrimStart() # String with leading whitespace removed +$var.TrimEnd() # String with trailing whitespace removed +$var.Trim() # String with both leading and trailing whitespace removed diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust index 94e692e4b9..90336f9902 100644 --- a/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Rust/strip-whitespace-from-a-string-top-and-tail.rust @@ -1,12 +1,9 @@ -// rust 0.9-pre - -fn main() -{ +fn main() { let string = "String without spaces"; - let spaces = " \x0B\t\r\n \xA0 \u2000 \u3000 "; - let string_with_spaces = spaces + string + spaces; + let spaces = " \x0B\t\r\n \u{A0} \u{2000} \u{3000} "; + let string_with_spaces = spaces.to_string() + string + spaces; assert_eq!(string_with_spaces.trim(), string); - assert_eq!(string_with_spaces.trim_left().to_owned(), string + spaces); - assert_eq!(string_with_spaces.trim_right().to_owned(), spaces + string); + assert_eq!(string_with_spaces.trim_left().to_string(), string.to_string() + spaces); + assert_eq!(string_with_spaces.trim_right().to_string(), spaces.to_string() + string); } diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/VBScript/strip-whitespace-from-a-string-top-and-tail.vb b/Task/Strip-whitespace-from-a-string-Top-and-tail/VBScript/strip-whitespace-from-a-string-top-and-tail.vb new file mode 100644 index 0000000000..81b032a62f --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/VBScript/strip-whitespace-from-a-string-top-and-tail.vb @@ -0,0 +1,28 @@ +Function LeftTrim(s) + Set regex = New RegExp + With regex + .Pattern = "^\s*" + If .Test(s) Then + LeftTrim = .Replace(s,"") + Else + LeftTrim = s + End If + End With +End Function + +Function RightTrim(s) + Set regex = New RegExp + With regex + .Pattern = "\s*$" + If .Test(s) Then + RightTrim = .Replace(s,"") + Else + RightTrim = s + End If + End With +End Function + +'testing the functions +WScript.StdOut.WriteLine LeftTrim(" RosettaCode") +WScript.StdOut.WriteLine RightTrim("RosettaCode ") +WScript.StdOut.WriteLine LeftTrim(RightTrim(" RosettaCode ")) diff --git a/Task/Substring-Top-and-tail/Burlesque/substring-top-and-tail.blq b/Task/Substring-Top-and-tail/Burlesque/substring-top-and-tail.blq new file mode 100644 index 0000000000..093b8fff7a --- /dev/null +++ b/Task/Substring-Top-and-tail/Burlesque/substring-top-and-tail.blq @@ -0,0 +1,10 @@ +blsq ) "RosettaCode"[- +"osettaCode" +blsq ) "RosettaCode"-] +'R +blsq ) "RosettaCode"~] +"RosettaCod" +blsq ) "RosettaCode"[~ +'e +blsq ) "RosettaCode"~- +"osettaCod" diff --git a/Task/Substring-Top-and-tail/Elixir/substring-top-and-tail.elixir b/Task/Substring-Top-and-tail/Elixir/substring-top-and-tail.elixir new file mode 100644 index 0000000000..e715b8e459 --- /dev/null +++ b/Task/Substring-Top-and-tail/Elixir/substring-top-and-tail.elixir @@ -0,0 +1,8 @@ +iex(1)> str = "abcdefg" +"abcdefg" +iex(2)> String.slice(str, 1..-1) +"bcdefg" +iex(3)> String.slice(str, 0..-2) +"abcdef" +iex(4)> String.slice(str, 1..-2) +"bcdef" diff --git a/Task/Substring-Top-and-tail/Emacs-Lisp/substring-top-and-tail.l b/Task/Substring-Top-and-tail/Emacs-Lisp/substring-top-and-tail.l new file mode 100644 index 0000000000..bbf37763e2 --- /dev/null +++ b/Task/Substring-Top-and-tail/Emacs-Lisp/substring-top-and-tail.l @@ -0,0 +1,7 @@ +(progn + (setq string "top and tail") + (insert (format "%s\n" string) ) + (setq len (length string) ) + (insert (format "%s\n" (substring string 1) )) + (insert (format "%s\n" (substring string 0 (1- len) ))) + (insert (format "%s\n" (substring string 1 (1- len) )))) diff --git a/Task/Substring-Top-and-tail/Erlang/substring-top-and-tail.erl b/Task/Substring-Top-and-tail/Erlang/substring-top-and-tail.erl index c2e4ce551b..8ad14d8991 100644 --- a/Task/Substring-Top-and-tail/Erlang/substring-top-and-tail.erl +++ b/Task/Substring-Top-and-tail/Erlang/substring-top-and-tail.erl @@ -1,6 +1,8 @@ -% Implemented by Arjun Sunel -string:left("Hello", length("Hello")-1,$.). % To strip the word from the right by 1 - -string:right("Hello", length("Hello")-1,$.). % To strip the word from the left by 1 - -string:left(string:right("Hello", length("Hello")-1,$.), length("Hello")-2,$.). %To strip the word from both sides by 1. +1> Str = "Hello". +"Hello" +2> string:sub_string(Str, 2). % To strip the string from the right by 1 +"ello" +3> string:sub_string(Str, 1, length(Str)-1). % To strip the string from the left by 1 +"Hell" +4> string:sub_string(Str, 2, length(Str)-1). % To strip the string from both sides by 1 +"ell" diff --git a/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail.hs b/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail-1.hs similarity index 100% rename from Task/Substring-Top-and-tail/Haskell/substring-top-and-tail.hs rename to Task/Substring-Top-and-tail/Haskell/substring-top-and-tail-1.hs diff --git a/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail-2.hs b/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail-2.hs new file mode 100644 index 0000000000..e1e10d8dec --- /dev/null +++ b/Task/Substring-Top-and-tail/Haskell/substring-top-and-tail-2.hs @@ -0,0 +1,18 @@ +word = "knights" + +main = do + -- You can drop the first item + -- using `tail` + putStrLn (tail word) + + -- The `init` function will drop + -- the last item + putStrLn (init word) + + -- We can combine these two to drop + -- the last and the first characters + putStrLn (middle word) + +-- You can combine functions using `.`, +-- which is pronounced "compose" or "of" +middle = init . tail diff --git a/Task/Substring-Top-and-tail/PowerShell/substring-top-and-tail-1.psh b/Task/Substring-Top-and-tail/PowerShell/substring-top-and-tail-1.psh new file mode 100644 index 0000000000..b6a8f5e946 --- /dev/null +++ b/Task/Substring-Top-and-tail/PowerShell/substring-top-and-tail-1.psh @@ -0,0 +1,5 @@ +$string = "top and tail" +$string +$string.Substring(1) +$string.Substring(0, $string.Length - 1) +$string.Substring(1, $string.Length - 2) diff --git a/Task/Substring-Top-and-tail/PowerShell/substring-top-and-tail-2.psh b/Task/Substring-Top-and-tail/PowerShell/substring-top-and-tail-2.psh new file mode 100644 index 0000000000..0298cc5b5f --- /dev/null +++ b/Task/Substring-Top-and-tail/PowerShell/substring-top-and-tail-2.psh @@ -0,0 +1,5 @@ +$string = "top and tail" +$string +$string[1..($string.Length - 1)] -join "" +$string[0..($string.Length - 2)] -join "" +$string[1..($string.Length - 2)] -join "" diff --git a/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-1.rexx b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-1.rexx new file mode 100644 index 0000000000..a1d3705b0c --- /dev/null +++ b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-1.rexx @@ -0,0 +1,13 @@ +/*REXX program demonstrates removal of 1st/last/1st&last chars from a string. */ +@ = 'abcdefghijk' +say ' the original string =' @ +say 'string first character removed =' substr(@,2) +say 'string last character removed =' left(@,length(@)-1) +say 'string first & last character removed =' substr(@,2,length(@)-2) + /*stick a fork in it, we're all done. */ + + /* ╔═══════════════════════════════════════════════════════╗ + ║ However, the original string may be null or exactly ║ + ║ one byte in length which will cause the BIFs to ║ + ║ fail because of either zero or a negative length. ║ + ╚═══════════════════════════════════════════════════════╝ */ diff --git a/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-2.rexx b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-2.rexx new file mode 100644 index 0000000000..c536dcb34a --- /dev/null +++ b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-2.rexx @@ -0,0 +1,15 @@ +/*REXX program demonstrates removal of 1st/last/1st&last chars from a string. */ +@ = 'abcdefghijk' +say ' the original string =' @ +say 'string first character removed =' substr(@,2) +say 'string last character removed =' left(@,max(0,length(@)-1)) +say 'string first & last character removed =' substr(@,2,max(0,length(@)-2)) +exit /*stick a fork in it, we're all done. */ + + /* [↓] an easier to read version using a length variable.*/ +@ = 'abcdefghijk' +L=length(@) +say ' the original string =' @ +say 'string first character removed =' substr(@,2) +say 'string last character removed =' left(@,max(0,L-1)) +say 'string first & last character removed =' substr(@,2,max(0,L-2)) diff --git a/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-3.rexx b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-3.rexx new file mode 100644 index 0000000000..766b217fc0 --- /dev/null +++ b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail-3.rexx @@ -0,0 +1,16 @@ +/*REXX program demonstrates removal of 1st/last/1st&last chars from a string. */ +@ = 'abcdefghijk' +say ' the original string =' @ + +parse var @ 2 z +say 'string first character removed =' z + +m=length(@)-1 +parse var @ z +(m) +say 'string last character removed =' z + +n=length(@)-2 +parse var @ 2 z +(n) +if n==0 then z= /*handle special case of a length of 2.*/ +say 'string first & last character removed =' z + /*stick a fork in it, we're all done. */ diff --git a/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx deleted file mode 100644 index e078d9fbb0..0000000000 --- a/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx +++ /dev/null @@ -1,19 +0,0 @@ -/*REXX program to show removal of 1st/last/1st&last chars from a string.*/ -z = 'abcdefghijk' - -say ' the original string =' z -say 'string first character removed =' substr(z,2) -say 'string last character removed =' left(z,length(z)-1) -say 'string first & last character removed =' substr(z,2,length(z)-2) -exit - /* ┌───────────────────────────────────────────────┐ - │ however, the original string may be null, │ - │ or of insufficient length which may cause the │ - │ BIFs to fail (because of negative length). │ - └───────────────────────────────────────────────┘ */ - -say ' the original string =' z -say 'string first character removed =' substr(z,2) -say 'string last character removed =' left(z,max(0,length(z)-1)) -say 'string first & last character removed =' substr(z,2,max(0,length(z)-2)) - /*stick a fork in it,we're done.*/ diff --git a/Task/Substring-Top-and-tail/VBScript/substring-top-and-tail.vb b/Task/Substring-Top-and-tail/VBScript/substring-top-and-tail.vb new file mode 100644 index 0000000000..8d0324ffe9 --- /dev/null +++ b/Task/Substring-Top-and-tail/VBScript/substring-top-and-tail.vb @@ -0,0 +1,14 @@ +Function TopNTail(s,mode) + Select Case mode + Case "top" + TopNTail = Mid(s,2,Len(s)-1) + Case "tail" + TopNTail = Mid(s,1,Len(s)-1) + Case "both" + TopNTail = Mid(s,2,Len(s)-2) + End Select +End Function + +WScript.Echo "Top: UPRAISERS = " & TopNTail("UPRAISERS","top") +WScript.Echo "Tail: UPRAISERS = " & TopNTail("UPRAISERS","tail") +WScript.Echo "Both: UPRAISERS = " & TopNTail("UPRAISERS","both") diff --git a/Task/Substring/Burlesque/substring-1.blq b/Task/Substring/Burlesque/substring-1.blq new file mode 100644 index 0000000000..ddaccb8a1e --- /dev/null +++ b/Task/Substring/Burlesque/substring-1.blq @@ -0,0 +1,12 @@ +blsq ) "RosettaCode"5.+ +"Roset" +blsq ) "RosettaCode"5.+2.- +"set" +blsq ) "RosettaCode""set"ss +2 +blsq ) "RosettaCode"J"set"ss.- +"settaCode" +blsq ) "RosettaCode"~] +"RosettaCod" +blsq ) "RosettaCode"[- +"osettaCode" diff --git a/Task/Substring/Burlesque/substring-2.blq b/Task/Substring/Burlesque/substring-2.blq new file mode 100644 index 0000000000..c543d73e28 --- /dev/null +++ b/Task/Substring/Burlesque/substring-2.blq @@ -0,0 +1,4 @@ +blsq ) "RosettaCode"{0 1 3 5}si +"Roet" +blsq ) "RosettaCode"{0 1 3 5}di +"oetaCde" diff --git a/Task/Substring/Elixir/substring.elixir b/Task/Substring/Elixir/substring.elixir new file mode 100644 index 0000000000..0072f1fa81 --- /dev/null +++ b/Task/Substring/Elixir/substring.elixir @@ -0,0 +1,5 @@ +s = "abcdefgh" +String.slice(s, 2, 3) #=> "cde" +String.slice(s, 1..3) #=> "bcd" +String.slice(s, -3, 2) #=> "fg" +String.slice(s, 3..-1) #=> "defgh" diff --git a/Task/Substring/REBOL/substring.rebol b/Task/Substring/REBOL/substring.rebol index 0b1c629277..0c89332620 100644 --- a/Task/Substring/REBOL/substring.rebol +++ b/Task/Substring/REBOL/substring.rebol @@ -2,7 +2,7 @@ REBOL [ Title: "Retrieve Substring" Author: oofoe Date: 2009-12-06 - URL: http://rosettacode.org/wiki/Retrieve_a_substring + URL: http://rosettacode.org/wiki/Substring#REBOL ] s: "abcdefgh" n: 2 m: 3 char: #"d" chars: "cd" diff --git a/Task/Subtractive-generator/REXX/subtractive-generator.rexx b/Task/Subtractive-generator/REXX/subtractive-generator.rexx index 44852b3dff..4189269151 100644 --- a/Task/Subtractive-generator/REXX/subtractive-generator.rexx +++ b/Task/Subtractive-generator/REXX/subtractive-generator.rexx @@ -1,23 +1,23 @@ -/*REXX pgm uses a subtractive generator, creates a sequence of random #s*/ -numeric digits 20; s.0=292929; s.1=1; billion=10**9 -cI=55; cJ=24; cP=34; billion=1e9 /*same*/ +/*REXX pgm uses a subtractive generator, creates a sequence of random numbers.*/ +numeric digits 20; s.0=292929; s.1=1; billion=10**9 +cI=55; cJ=24; cP=34; billion=1e9 /* [↑] same*/ do i=2 to cI-1 s.i=mod(s(i-2) - s(i-1), billion) end /*i*/ - do j=0 to cI-1 - r.j=s(mod(cP*(j+1), cI)) - end /*j*/ + do j=0 to cI-1 + r.j=s(mod(cP*(j+1), cI)) + end /*j*/ m=219 - do k=cI to m; x=k//cI - r.x=mod(r(mod(k-cI, cI)) - r(mod(k-cJ, cI)), billion) - end /*m*/ + do k=cI to m; x=k//cI + r.x=mod(r(mod(k-cI, cI)) - r(mod(k-cJ, cI)), billion) + end /*m*/ t=235 - do n=m+1 to t; y=n//cI - r.y=mod(r(mod(n-cI, cI)) - r(mod(n-cJ, cI)), billion) - say right(r.y, 40) - end /*n*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────one─liner subroutines───────────────*/ -mod: procedure; parse arg a,b; return ((a // b) + b) // b -r: parse arg _; return r._ -s: parse arg _; return s._ + do n=m+1 to t; y=n//cI + r.y=mod(r(mod(n-cI, cI)) - r(mod(n-cJ, cI)), billion) + say right(r.y, 40) + end /*n*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +mod: procedure; parse arg a,b; return ((a // b) + b) // b +r: parse arg _; return r._ +s: parse arg _; return s._ diff --git a/Task/Sudoku/Delphi/sudoku-1.delphi b/Task/Sudoku/Delphi/sudoku-1.delphi index ff359fff55..d2e850c045 100644 --- a/Task/Sudoku/Delphi/sudoku-1.delphi +++ b/Task/Sudoku/Delphi/sudoku-1.delphi @@ -118,7 +118,7 @@ end; procedure TSudokuSolver.Solve; begin if not PlaceNumber(0) then - ShowMessage('Unsolvable'); + ShowMessage('Unsolvable') else ShowMessage('Solved!'); end; diff --git a/Task/Sudoku/Elixir/sudoku.elixir b/Task/Sudoku/Elixir/sudoku.elixir new file mode 100644 index 0000000000..6107053262 --- /dev/null +++ b/Task/Sudoku/Elixir/sudoku.elixir @@ -0,0 +1,163 @@ +defmodule Sudoku do + def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) ) + + def start( knowns ), do: :dict.from_list( knowns ) + + def solve( grid ) do + sure = solve_all_sure( grid ) + solve_unsure( potentials(sure), sure ) + end + + def task do + simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7}, + {{4, 2}, 3}, {{7, 2}, 4}, + {{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2}, + {{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9}, + {{1, 5}, 6}, {{9, 5}, 7}, + {{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8}, + {{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8}, + {{3, 8}, 9}, {{6, 8}, 8}, + {{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}] + task( simple ) + difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5}, + {{3, 3}, 1}, {{5, 3}, 2}, + {{4, 4}, 5}, {{6, 4}, 7}, + {{3, 5}, 4}, {{7, 5}, 1}, + {{2, 6}, 9}, + {{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3}, + {{3, 8}, 2}, {{5, 8}, 1}, + {{5, 9}, 4}, {{9, 9}, 9}] + task( difficult ) + end + + defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid ) + + defp bt_accept( true, board ), do: throw( {:ok, board} ) + defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid ) + + defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( :dict.store(position, x, grid) ) ) + + defp bt_reject( true, _grid ), do: :backtrack + defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid ) + + defp display_row( row, grid ) do + for x <- [1, 4, 7], do: display_row_group( x, row, grid ) + display_row_nl( row ) + end + + defp display_row_group( start, row, grid ) do + for x <- [start, start+1, start+2], do: :io.fwrite(" ~c", [display_value(x, row, grid)]) + IO.write( " " ) + end + + defp display_row_nl( n ) when n == 3 or n == 6 or n == 9, do: IO.puts "\n" + defp display_row_nl( _N ), do: IO.puts "" + + defp display_value( x, y, grid ), do: display_value( :dict.find({x, y}, grid) ) + + defp display_value( :error ), do: ?. + defp display_value( {:ok, value} ), do: value + ?0 + + defp is_all_correct( grid ), do: :dict.size( grid ) == 81 + + defp is_not_allowed( grid ) do + is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid ) + end + + defp is_not_allowed_columns( grid ), do: Enum.any?( values_all_columns(grid), fn x-> is_not_allowed_values(x) end) + + defp is_not_allowed_groups( grid ), do: Enum.any?( values_all_groups(grid), fn x-> is_not_allowed_values(x) end) + + defp is_not_allowed_rows( grid ), do: Enum.any?( values_all_rows(grid), fn x-> is_not_allowed_values(x) end) + + defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) ) + + defp group_positions( {x, y} ), do: ( for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row} ) + + defp group_positions_close( n ) when n < 4, do: [1,2,3] + defp group_positions_close( n ) when n < 7, do: [4,5,6] + defp group_positions_close( _n ) , do: [7,8,9] + + defp positions_not_in_grid( grid ) do + keys = :dict.fetch_keys( grid ) + for x <- 1..9, y <- 1..9, not Enum.member?(keys, {x, y}), do: {x, y} + end + + defp potentials_one_position( grid ) do + [{_shortest, position, values} | _t] = Enum.sort( for {position, values} <- potentials( grid ), do: {length(values), position, values} ) + {position, values} + end + + defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) ) + + defp potentials( position, grid ) do + useds = potentials_used_values( position, grid ) + {position, (for value <- :lists.seq(1, 9) -- useds, do: value) } + end + + defp potentials_used_values( {x, y}, grid ) do + row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid ) + column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid ) + group_values = List.delete( group_positions({x, y}), {x, y} ) |> potentials_values( grid ) + row_values ++ column_values ++ group_values + end + + defp potentials_values( keys, grid ) do + row_values_unfiltered = for x <- keys, do: :dict.find(x, grid) + for {:ok, value} <- row_values_unfiltered, do: value + end + + defp values_all_columns( grid ), do: ( for x <- 1..9, do: values_all_columns(x, grid) ) + + defp values_all_columns( x, grid ) do + ( for y <- 1..9, do: {x, y} ) |> potentials_values( grid ) + end + + defp values_all_groups( grid ) do + [[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1, 4, 7], do: values_all_groups(x, grid) + [g1,g2,g3,g4,g5,g6,g7,g8,g9] + end + + defp values_all_groups( x, grid ), do: ( for x_offset <- [x, x+1, x+2], do: values_all_groups(x, x_offset, grid) ) + + defp values_all_groups( _x, x_offset, grid ) do + ( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} ) + |> potentials_values( grid ) + end + + defp values_all_rows( grid ), do: ( for y <- 1..9, do: values_all_rows(y, grid) ) + + defp values_all_rows( y, grid ) do + ( for x <- 1..9, do: {x, y} ) |> potentials_values( grid ) + end + + defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid ) + + defp solve_all_sure( [], grid ), do: grid + defp solve_all_sure( sures, grid ), do: solve_all_sure( List.foldl(sures, grid, fn(x,acc)-> solve_all_sure_store(x,acc) end) ) + + defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} ) + + defp solve_all_sure_store( {position, value}, acc ), do: :dict.store( position, value, acc ) + + defp solve_unsure( [], grid ), do: grid + defp solve_unsure( _potentials, grid ) do + try do + bt( grid ) + catch + {:ok, board} -> board + end + end + + defp task( knowns ) do + IO.puts "start" + start = start( knowns ) + display( start ) + IO.puts "solved" + solved = solve( start ) + display( solved ) + IO.puts "" + end +end + +Sudoku.task diff --git a/Task/Sudoku/Mathematica/sudoku-1.math b/Task/Sudoku/Mathematica/sudoku-1.math index 9ea1a4d429..2740a8d09b 100644 --- a/Task/Sudoku/Mathematica/sudoku-1.math +++ b/Task/Sudoku/Mathematica/sudoku-1.math @@ -1,13 +1,10 @@ -solve[array_] := +solve[sudoku_] := NestWhile[ - Join @@ Function[newarray, - Function[{i, j}, - Table[ReplacePart[newarray, - Position[newarray, 0, {2}, 1][[1]] -> n], {n, - Select[Range@9, - FreeQ[newarray[[i]], #] && FreeQ[newarray[[All, j]], #] && - FreeQ[Partition[ - newarray, {3, 3}][[Sequence @@ - Quotient[{i, j}, 3, -2]]], #] &]}]] @@ - Position[newarray, 0, {2}, 1][[1]]] /@ # &, {array}, ! - FreeQ[#, 0] &] + Join @@ Table[ + Table[ReplacePart[s, #1 -> n], {n, #2}] & @@ + First@SortBy[{#, + Complement[Range@9, s[[First@#]], s[[;; , Last@#]], + Catenate@ + Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@ + Position[s, 0, {2}], + Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &] diff --git a/Task/Sum-and-product-of-an-array/4D/sum-and-product-of-an-array.4d b/Task/Sum-and-product-of-an-array/4D/sum-and-product-of-an-array.4d index 03b36813b0..75a82e9d77 100644 --- a/Task/Sum-and-product-of-an-array/4D/sum-and-product-of-an-array.4d +++ b/Task/Sum-and-product-of-an-array/4D/sum-and-product-of-an-array.4d @@ -9,3 +9,7 @@ For ($i;1;Size of array($list)) $sum:=$var+$list{$i} $product:=$product*$list{$i} End for + +// since 4D v13 + +$sum:=sum($list) diff --git a/Task/Sum-and-product-of-an-array/ALGOL-W/sum-and-product-of-an-array.alg b/Task/Sum-and-product-of-an-array/ALGOL-W/sum-and-product-of-an-array.alg new file mode 100644 index 0000000000..ae029f51ce --- /dev/null +++ b/Task/Sum-and-product-of-an-array/ALGOL-W/sum-and-product-of-an-array.alg @@ -0,0 +1,34 @@ +begin + + % computes the sum and product of intArray % + % the results are returned in sum and product % + % the bounds of the array must be specified in lb and ub % + procedure sumAndProduct( integer array intArray ( * ) + ; integer value lb, ub + ; integer result sum, product + ) ; + begin + + sum := 0; + product := 1; + + for i := lb until ub + do begin + sum := sum + intArray( i ); + product := product * intArray( i ); + end for_i ; + + end sumAndProduct ; + + % test the sumAndProduct procedure % + begin + + integer array v ( 1 :: 10 ); + integer sum, product; + + for i := 1 until 10 do v( i ) := i; + + sumAndProduct( v, 1, 10, sum, product ); + write( sum, product ); + end +end. diff --git a/Task/Sum-and-product-of-an-array/Eiffel/sum-and-product-of-an-array.e b/Task/Sum-and-product-of-an-array/Eiffel/sum-and-product-of-an-array.e index 48f2835064..b69e7ffc03 100644 --- a/Task/Sum-and-product-of-an-array/Eiffel/sum-and-product-of-an-array.e +++ b/Task/Sum-and-product-of-an-array/Eiffel/sum-and-product-of-an-array.e @@ -1,64 +1,41 @@ -note - description : "project application root class" - date : "$Date$" - revision : "$Revision$" - class APPLICATION -inherit - ARGUMENTS - create make feature {NONE} - array : ARRAY[INTEGER] - make + local + test: ARRAY [INTEGER] do - create array.make_filled (0, 0, 4) - array.put (2, 0) - array.put (4, 1) - array.put (6, 2) - array.put (8, 3) - array.put (10, 4) - - print("%NSum of the elements of the array: ") - print(sum(array)) - print("%NProduct of the elements of the array: ") - print(product(array)) + create test.make_empty + test := <<5, 1, 9, 7>> + io.put_string ("Sum: " + sum (test).out) + io.new_line + io.put_string ("Product: " + product (test).out) end - sum(ar : ARRAY[INTEGER]):INTEGER - local - s, i: INTEGER + sum (ar: ARRAY [INTEGER]): INTEGER + -- Sum of the items of the array 'ar'. do - from - i := 0 - until - i > 4 + across + ar.lower |..| ar.upper as c loop - s := s + ar[i] - i := i + 1 + Result := Result + ar [c.item] end - Result := s end - product(ar : ARRAY [INTEGER]):INTEGER - local - prod, i: INTEGER + product (ar: ARRAY [INTEGER]): INTEGER + -- Product of the items of the array 'ar'. do - prod := 1 - from - i := 0 - until - i > 4 + Result := 1 + across + ar.lower |..| ar.upper as c loop - prod := prod * ar[i] - i := i + 1 + Result := Result * ar [c.item] end - Result := prod end + end diff --git a/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-1.elixir b/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-1.elixir new file mode 100644 index 0000000000..2ccb871378 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-1.elixir @@ -0,0 +1,18 @@ +iex(26)> Enum.reduce([1,2,3,4,5], 0, fn x,acc -> x+acc end) +15 +iex(27)> Enum.reduce([1,2,3,4,5], 1, fn x,acc -> x*acc end) +120 +iex(28)> Enum.reduce([1,2,3,4,5], fn x,acc -> x+acc end) +15 +iex(29)> Enum.reduce([1,2,3,4,5], fn x,acc -> x*acc end) +120 +iex(30)> Enum.reduce([], 0, fn x,acc -> x+acc end) +0 +iex(31)> Enum.reduce([], 1, fn x,acc -> x*acc end) +1 +iex(32)> Enum.reduce([], fn x,acc -> x+acc end) +** (Enum.EmptyError) empty error + (elixir) lib/enum.ex:1287: Enum.reduce/2 +iex(32)> Enum.reduce([], fn x,acc -> x*acc end) +** (Enum.EmptyError) empty error + (elixir) lib/enum.ex:1287: Enum.reduce/2 diff --git a/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-2.elixir b/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-2.elixir new file mode 100644 index 0000000000..2397fbe8fe --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Elixir/sum-and-product-of-an-array-2.elixir @@ -0,0 +1 @@ +Enum.sum([1,2,3,4,5]) #=> 15 diff --git a/Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array.go b/Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array-1.go similarity index 100% rename from Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array.go rename to Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array-1.go diff --git a/Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array-2.go b/Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array-2.go new file mode 100644 index 0000000000..90aa790c37 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Go/sum-and-product-of-an-array-2.go @@ -0,0 +1,14 @@ +package main + +import ( + "fmt" + + "github.com/gonum/floats" +) + +var a = []float64{1, 2, 5} + +func main() { + fmt.Println("Sum: ", floats.Sum(a)) + fmt.Println("Product:", floats.Prod(a)) +} diff --git a/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia b/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia index 0481d49ae1..e184caa5ab 100644 --- a/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia +++ b/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia @@ -1,5 +1,11 @@ julia> sum([4,6,8]) 18 +julia> +((1:10)...) +55 + +julia +([1,2,3]...) +6 + julia> prod([4,6,8]) 192 diff --git a/Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array.lua b/Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array-1.lua similarity index 100% rename from Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array.lua rename to Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array-1.lua diff --git a/Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array-2.lua b/Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array-2.lua new file mode 100644 index 0000000000..8177e7c741 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Lua/sum-and-product-of-an-array-2.lua @@ -0,0 +1,12 @@ +function table.sum(arr, length) + --same as if <> then <> else <> + return length == 1 and arr[1] or arr[length] + table.sum(arr, length -1) +end + +function table.product(arr, length) + return length == 1 and arr[1] or arr[length] * table.sum(arr, length -1) +end + +t = {1,2,3} +print(table.sum(t,#t)) +print(table.product(t,3)) diff --git a/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx b/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx index 3d6c598499..f9b04f5931 100644 --- a/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx +++ b/Task/Sum-and-product-of-an-array/REXX/sum-and-product-of-an-array.rexx @@ -1,16 +1,17 @@ -/*REXX program to add and separately multiply elements of an array. */ -numeric digits 30 /*allow 30-digit numbers (default is 9)*/ -m=20 /*one method of indicating array size. */ - do j=1 for m /*build an array of twenty elements. */ - y.j=j /*set 1st to 1, 3rd to 3, 9th to 9 ... */ +/*REXX program adds and multiplies N elements of a (populated) array @. */ +numeric digits 200 /*200 decimal digit #s (default is 9).*/ +parse arg N .; if N=='' then N=20 /*Not specified? Then use the default.*/ + + do j=1 for N /*build array of N elements (or 20?).*/ + @.j=j /*set 1st to 1, 3rd to 3, 8th to 8 ··· */ end /*j*/ -sum=0 /*initialize SUM to zero. */ -prod=1 /*initialize PROD to unity. */ - do k=1 for m - sum =sum +y.k /*add the element to the running total.*/ - prod=prod*y.k /*multiple the element to running prod.*/ - end /*k*/ +sum=0 /*initialize SUM (variable) to zero. */ +prod=1 /*initialize PROD (variable) to unity.*/ + do k=1 for N + sum = sum + @.k /*add the element to the running total.*/ + prod = prod * @.k /*multiply element to running product. */ + end /*k*/ /* [↑] this pgm: same as N factorial.*/ -say ' sum of' m "elements for the Y array is: " sum -say 'product of' m "elements for the Y array is: " prod - /*stick a fork in it, we're done. */ +say ' sum of ' m " elements for the @ array is: " sum +say ' product of ' m " elements for the @ array is: " prod + /*stick a fork in it, we're all done. */ diff --git a/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust index 559ce77b3e..01be26c8b0 100644 --- a/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust +++ b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust @@ -1,16 +1,16 @@ -use std::iter::{AdditiveIterator, MultiplicativeIterator}; +#![feature(iter_arith)] fn main() { - let arr = [1i, 2, 3, 4, 5, 6, 7, 8, 9]; + let arr: [i32; 9] = [1i32, 2, 3, 4, 5, 6, 7, 8, 9]; - // using fold - let sum = arr.iter().fold(0, |a, &b| a + b); - let product = arr.iter().fold(1, |a, &b| a * b); - println!("the sum is {:d} and the product is {:d}", sum, product); + // using fold + let sum = arr.iter().fold(0i32, |a, &b| a + b); + let product = arr.iter().fold(1i32, |a, &b| a * b); + println!("the sum is {} and the product is {}", sum, product); - // or using sum and product from AdditiveIterator - // and MultiplicativeIterator - let sum2 = arr.iter().map(|&a| a).sum(); - let product2 = arr.iter().map(|&a| a).product(); - println!("the sum is {:d} and the product is {:d}", sum2, product2); + // or using sum and product + // these are NOT YET STABLE (hence the #![feature(..)] line + let sum = arr.iter().sum::(); + let product = arr.iter().product::(); + println!("the sum is {} and the product is {}", sum, product); } diff --git a/Task/Sum-and-product-of-an-array/VBScript/sum-and-product-of-an-array.vb b/Task/Sum-and-product-of-an-array/VBScript/sum-and-product-of-an-array.vb new file mode 100644 index 0000000000..e29464f287 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/VBScript/sum-and-product-of-an-array.vb @@ -0,0 +1,15 @@ +Function sum_and_product(arr) + sum = 0 + product = 1 + For i = 0 To UBound(arr) + sum = sum + arr(i) + product = product * arr(i) + Next + WScript.StdOut.Write "Sum: " & sum + WScript.StdOut.WriteLine + WScript.StdOut.Write "Product: " & product + WScript.StdOut.WriteLine +End Function + +myarray = Array(1,2,3,4,5,6) +sum_and_product(myarray) diff --git a/Task/Sum-digits-of-an-integer/Elixir/sum-digits-of-an-integer.elixir b/Task/Sum-digits-of-an-integer/Elixir/sum-digits-of-an-integer.elixir new file mode 100644 index 0000000000..5537a94604 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Elixir/sum-digits-of-an-integer.elixir @@ -0,0 +1,16 @@ +defmodule RC do + def sumDigits(n), do: sumDigits(n, 10) + + def sumDigits(n, base) when is_integer(n) do + sumDigits(Integer.to_string(n, base), base) + end + + def sumDigits(n, base) when is_bitstring(n) do + String.split(n, "", trim: true) |> Enum.map(&(String.to_integer(&1, base))) + |> Enum.sum + end +end + +Enum.each([1, 1234], fn n -> IO.puts "#{n}: #{ RC.sumDigits(n) }" end) +base = 16 +Enum.each(["fe", "f0e"], fn n -> IO.puts "#{n}(#{base}): #{ RC.sumDigits(n,base) }" end) diff --git a/Task/Sum-digits-of-an-integer/Emacs-Lisp/sum-digits-of-an-integer.l b/Task/Sum-digits-of-an-integer/Emacs-Lisp/sum-digits-of-an-integer.l new file mode 100644 index 0000000000..6eda44edaf --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Emacs-Lisp/sum-digits-of-an-integer.l @@ -0,0 +1,6 @@ +(defun digit-sum (n) + (apply '+ + (mapcar 'string-to-number + (cdr (butlast (split-string (number-to-string n) "") ))))) + +(insert (format "%d\n" (digit-sum 1234) )) diff --git a/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-3.rexx b/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-3.rexx new file mode 100644 index 0000000000..6e9ca936d4 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/REXX/sum-digits-of-an-integer-3.rexx @@ -0,0 +1,13 @@ +/*REXX program sums the decimal digits of integers expressed in base ten*/ +parse arg z /*get optional #s or use default.*/ +if z='' then z=copies(7, 108) /*let's generate a pretty huge #.*/ +numeric digits 1+max(length(z)) /*enable use of gigantic numbers.*/ + + do j=1 for words(z); _=abs(word(z,j)) /*ignore sign, if any.*/ + say sumDigs(_) ' is the sum of the digits for the number ' _ + end /*j*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SUMDIGS subroutine──────────────────*/ +sumDigs: procedure; parse arg N 1 s 2 ? /*use first dig for S (sum),*/ + do while ?\==''; parse var ? _ 2 ?; s=s+_; end /*k*/ +return s diff --git a/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5.e b/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5.e new file mode 100644 index 0000000000..f60ded0190 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Eiffel/sum-multiples-of-3-and-5.e @@ -0,0 +1,26 @@ +class + APPLICATION + +create + make + +feature {NONE} + + make + do + io.put_integer (sum_multiples (1000)) + end + + sum_multiples (n: INTEGER): INTEGER + -- Sum of all positive multiples of 3 or 5 below 'n'. + do + across + 1 |..| (n - 1) as c + loop + if c.item \\ 3 = 0 or c.item \\ 5 = 0 then + Result := Result + c.item + end + end + end + +end diff --git a/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-1.elixir b/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-1.elixir new file mode 100644 index 0000000000..acfdf4b232 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-1.elixir @@ -0,0 +1,2 @@ +iex(1)> Enum.filter(0..1000-1, fn x -> rem(x,3)==0 or rem(x,5)==0 end) |> Enum.sum +233168 diff --git a/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-2.elixir b/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-2.elixir new file mode 100644 index 0000000000..9fa4cfecd9 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Elixir/sum-multiples-of-3-and-5-2.elixir @@ -0,0 +1,15 @@ +defmodule RC do + def sumMul(n, f) do + n1 = div(n - 1, f) + div(f * n1 * (n1 + 1), 2) + end + + def sum35(n) do + sumMul(n, 3) + sumMul(n, 5) - sumMul(n, 15) + end +end + +Enum.each(1..20, fn i -> + n = round(:math.pow(10, i)) + IO.puts RC.sum35(n) +end) diff --git a/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-1.l b/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-1.l new file mode 100644 index 0000000000..489bc73b57 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-1.l @@ -0,0 +1,5 @@ +(defun sum-3-5 (ls) + (apply '+ (mapcar + '(lambda (x) (if (or (= 0 (% x 3) ) (= 0 (% x 5) )) + x 0) ) + ls) )) diff --git a/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-2.l b/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-2.l new file mode 100644 index 0000000000..b6397edb57 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-2.l @@ -0,0 +1,4 @@ +(defun sum-3-5 (ls) + (apply '+ (seq-filter + '(lambda (x) (or (= 0 (% x 3) ) (= 0 (% x 5) ))) + ls) )) diff --git a/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-3.l b/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-3.l new file mode 100644 index 0000000000..f4849edd44 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/Emacs-Lisp/sum-multiples-of-3-and-5-3.l @@ -0,0 +1 @@ +(insert (format "%d" (sum-3-5 (number-sequence 1 100) ))) 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 index 901bde1844..4224d4e1e8 100644 --- 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 @@ -1,15 +1,15 @@ -/*REXX pgm sums all integers from 1──>N─1 that're multiples of 3 or 5.*/ +/*REXX pgm sums all integers from 1 ──► N─1 that are 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.*/ +say /* [↓] change the format/look of nE+nn*/ + do t; parse value format(N,2,1,,0) 'E0' with m 'E' _ .; _=_+0 + y=right((m/1)'e'_,5)'-1' /*this fixes a bug in a certain REXX. */ + if t==1 then y=N-1 /*handle a special case of a one-timer.*/ + 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 the 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 +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +sumDivisors: procedure; parse arg x,d; _=x%d; return d*_*(_+1)%2 diff --git a/Task/Sum-multiples-of-3-and-5/VBScript/sum-multiples-of-3-and-5.vb b/Task/Sum-multiples-of-3-and-5/VBScript/sum-multiples-of-3-and-5.vb new file mode 100644 index 0000000000..a504b0a407 --- /dev/null +++ b/Task/Sum-multiples-of-3-and-5/VBScript/sum-multiples-of-3-and-5.vb @@ -0,0 +1,10 @@ +Function multsum35(n) + For i = 1 To n - 1 + If i Mod 3 = 0 Or i Mod 5 = 0 Then + multsum35 = multsum35 + i + End If + Next +End Function + +WScript.StdOut.Write multsum35(CLng(WScript.Arguments(0))) +WScript.StdOut.WriteLine diff --git a/Task/Sum-of-a-series/Befunge/sum-of-a-series.bf b/Task/Sum-of-a-series/Befunge/sum-of-a-series.bf new file mode 100644 index 0000000000..43b716a9e7 --- /dev/null +++ b/Task/Sum-of-a-series/Befunge/sum-of-a-series.bf @@ -0,0 +1,4 @@ +05558***>::"~"%00p"~"/10p"( }}2"*v +v*8555$_^#!:-1+*"~"g01g00+/*:\***< +<@$_,#!>#:<+*\55+/00g1-:#^_$ diff --git a/Task/Sum-of-a-series/Elixir/sum-of-a-series.elixir b/Task/Sum-of-a-series/Elixir/sum-of-a-series.elixir new file mode 100644 index 0000000000..b22c27828a --- /dev/null +++ b/Task/Sum-of-a-series/Elixir/sum-of-a-series.elixir @@ -0,0 +1,2 @@ +iex(1)> Enum.reduce(1..1000, 0, fn x,sum -> sum + 1/(x*x) end) +1.6439345666815615 diff --git a/Task/Sum-of-a-series/Emacs-Lisp/sum-of-a-series.l b/Task/Sum-of-a-series/Emacs-Lisp/sum-of-a-series.l new file mode 100644 index 0000000000..3affcbfc24 --- /dev/null +++ b/Task/Sum-of-a-series/Emacs-Lisp/sum-of-a-series.l @@ -0,0 +1,6 @@ +(defun serie (n) + (if (< 0 n) + (apply '+ (mapcar (lambda (k) (/ 1.0 (* k k) )) (number-sequence 1 n) )) + (error "input error") )) + +(insert (format "%.10f" (serie 1000) )) diff --git a/Task/Sum-of-a-series/JavaScript/sum-of-a-series.js b/Task/Sum-of-a-series/JavaScript/sum-of-a-series-1.js similarity index 100% rename from Task/Sum-of-a-series/JavaScript/sum-of-a-series.js rename to Task/Sum-of-a-series/JavaScript/sum-of-a-series-1.js diff --git a/Task/Sum-of-a-series/JavaScript/sum-of-a-series-2.js b/Task/Sum-of-a-series/JavaScript/sum-of-a-series-2.js new file mode 100644 index 0000000000..329aa022e8 --- /dev/null +++ b/Task/Sum-of-a-series/JavaScript/sum-of-a-series-2.js @@ -0,0 +1,17 @@ +sum(function (x) { return 1 / (x * x) }, range(1, 1000)); + +function sum(fn, lstRange) { + return lstRange.reduce( + function (lngSum, x) { + return lngSum + fn(x); + }, 0 + ); +} + +function range(m, n) { + return Array.apply(null, Array(n - m + 1)).map( + function (x, i) { + return m + i; + } + ); +} diff --git a/Task/Sum-of-a-series/REXX/sum-of-a-series-1.rexx b/Task/Sum-of-a-series/REXX/sum-of-a-series-1.rexx index 1229345d01..553c8a8f78 100644 --- a/Task/Sum-of-a-series/REXX/sum-of-a-series-1.rexx +++ b/Task/Sum-of-a-series/REXX/sum-of-a-series-1.rexx @@ -1,14 +1,11 @@ -/*REXX program sums the first N terms of 1/(i**2), i=1 ──► N.*/ -parse arg N D . /*maybe get num of terms, digits.*/ -if N=='' | N==',' then N=1000 /*Not specified? Use the default*/ -if D=='' then D=60 /* " " " " " */ -numeric digits D /*use D digits: 9 is default for */ - /*REXX, 60 is this pgm's default.*/ -w = length(N) /*use max width for nice output.*/ -sum = 0 /*initialize the sum to zero. */ - do j=1 for N /*compute for N terms. */ - sum = sum + 1 / j**2 /*add another term to the sum. */ - end /*j*/ +/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */ +parse arg N D . /*obtain optional arguments from C.L. */ +if N=='' | N==',' then N=1000 /*Not specified? Then use the default.*/ +if D=='' | D==',' then D= 60 /* " " " " " " */ +numeric digits D /*use D digits (nine is the default)*/ +$=0 /*initialize the sum to zero. */ + do k=1 for N /* [↓] compute for N terms. */ + $=$ + 1/k**2 /*add a squared reciprocal to the sum. */ + end /*k*/ -say 'The sum of' right(N,w) "terms is:" sum - /*stick a fork in it, we're done.*/ +say 'The sum of' N "terms is:" $ /*stick a fork in it, we're all done. */ diff --git a/Task/Sum-of-a-series/REXX/sum-of-a-series-2.rexx b/Task/Sum-of-a-series/REXX/sum-of-a-series-2.rexx index f79e1f5629..a017a9fe76 100644 --- a/Task/Sum-of-a-series/REXX/sum-of-a-series-2.rexx +++ b/Task/Sum-of-a-series/REXX/sum-of-a-series-2.rexx @@ -1,16 +1,16 @@ -/*REXX program sums the first N terms of 1/(i**2), i=1 ──► N.*/ -parse arg N D . /*maybe get num of terms, digits.*/ -if N=='' | N==',' then N=1000 /*Not specified? Use the default*/ -if D=='' then D=60 /* " " " " " */ -numeric digits D /*use D digits: 9 is default for */ - /*REXX, 60 is this pgm's default.*/ -w = length(N) /*use max width for nice output.*/ -sum=0 /*initialize the sum to zero. */ - do j=1 for N /*compute for N terms. */ - sum = sum + 1 / j**2 /*add another term to the sum. */ - if left(j,1)\==1 then iterate /*does J start with a one ? */ - if right(j,1)\==0 then iterate /* " " end " " zero ? */ - if substr(j,2)\= 0 then iterate /* " " " " all zeroes ? */ - say 'The sum of' right(j,w) "terms is:" sum /*display it.*/ - end /*j*/ - /*stick a fork in it, we're done.*/ +/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */ +parse arg N D . /*obtain optional arguments from C.L. */ +if N=='' | N==',' then N=1000 /*Not specified? Then use the default.*/ +if D=='' | D==',' then D= 60 /* " " " " " " */ +numeric digits D /*use D digits (nine is the default)*/ +w=length(N) /*max width for the formatted output. */ +$=0 /*initialize the sum to zero. */ + do k=1 for N /* [↓] compute for N terms. */ + $=$ + 1/k**2 /*add a squared reciprocal to the sum. */ + parse var k s 2 m '' -1 e /*obtain the start and end decimal digs*/ + if e\==0 then iterate /*does K end with the dec digit 0 ? */ + if s\==1 then iterate /* " " start " " " " 1 ? */ + if m\=0 then iterate /* " " middle contain any non-zero ?*/ + say 'The sum of' right(k,w) "terms is:" $ /*display running sum.*/ + end /*k*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Sum-of-a-series/REXX/sum-of-a-series-3.rexx b/Task/Sum-of-a-series/REXX/sum-of-a-series-3.rexx index e6ba7728e4..ae02d361a1 100644 --- a/Task/Sum-of-a-series/REXX/sum-of-a-series-3.rexx +++ b/Task/Sum-of-a-series/REXX/sum-of-a-series-3.rexx @@ -1,24 +1,22 @@ -/*REXX program sums the first N terms of 1/(i**2), i=1 ──► N.*/ -parse arg N D . /*optional num of terms, digits.*/ -if N=='' | N==',' then N=1000 /*Not specified? Use the default*/ -if D=='' then D=60 /* " " " " " */ -@sig = 'The significant sum of' /*literal used in SAY statement.*/ -numeric digits D /*use D digits: 9 is default for */ - /*REXX, 60 is this pgm's default.*/ -w = length(N) /*use max width for nice output.*/ -sum = 0 /*initialize the SUM to zero. */ -old = 1 /*the SUM to compared to the NEW.*/ -p = 0 /*significant precision so far. */ - do j=1 for N /*compute for n terms. */ - sum = sum + 1 / j**2 /*add another term to the sum. */ - c = compare(sum,old) /*see how we're doing with prec. */ - if c>p then do /*Got another significant digit? */ - say @sig right(j,w) "terms is:" left(sum,c) - p = c /*the new significant precision. */ - end - old = sum /*use "old" sum for next compare.*/ - end /*j*/ -say -say 'The sum of' right(N,w) "terms is:" /*display sum's preamble.*/ -say sum /*display the sum on its own line*/ - /*stick a fork in it, we're done.*/ +/*REXX program sums the first N terms of 1/(k**2), k=1 ──► N. */ +parse arg N D . /*obtain optional arguments from C.L. */ +if N=='' | N==',' then N=1000 /*Not specified? Then use the default.*/ +if D=='' | D==',' then D= 60 /* " " " " " " */ +numeric digits D /*use D digits (nine is the default)*/ +w=length(N) /*max width for the formatted output. */ +$=0 /*initialize the sum to zero. */ +old=1 /*the new sum to compared to the old. */ +p=0 /*significant decimal precision so far.*/ + do k=1 for N /* [↓] compute for N terms. */ + $=$ + 1/k**2 /*add a squared reciprocal to the sum. */ + c=compare($,old) /*see how we're doing with precision. */ + if c>p then do /*Got another significant decimal dig? */ + say 'The significant sum of' right(k,w) "terms is:" left($,c) + p=c /*use the new significant precision. */ + end /* [↑] display significant part of sum*/ + old=$ /*use "old" sum for the next compare. */ + end /*k*/ +say /*display blank line for sep.*/ +say 'The sum of' right(N,w) "terms is:" /*display the sum's preamble.*/ +say $ /*display the sum on its own line. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Sum-of-a-series/Rust/sum-of-a-series.rust b/Task/Sum-of-a-series/Rust/sum-of-a-series.rust index c221b0dc7f..36286bd506 100644 --- a/Task/Sum-of-a-series/Rust/sum-of-a-series.rust +++ b/Task/Sum-of-a-series/Rust/sum-of-a-series.rust @@ -1,8 +1,4 @@ -use std::iter::range_inclusive; -use std::iter::AdditiveIterator; - fn main() { - let series = range_inclusive(1f64, 1000f64); - let sum = series.map(|a| 1f64 / (a * a)).sum(); - println!("{}", sum); + let sum: f64 = (1u64..1000+1).fold(0.,|sum, num| sum + 1./(num*num) as f64); + println!("{}", sum); } diff --git a/Task/Sum-of-a-series/SQL/sum-of-a-series.sql b/Task/Sum-of-a-series/SQL/sum-of-a-series.sql index d3d14d0087..0b1d65c7f4 100644 --- a/Task/Sum-of-a-series/SQL/sum-of-a-series.sql +++ b/Task/Sum-of-a-series/SQL/sum-of-a-series.sql @@ -1,17 +1,6 @@ -create table sequence ( - n real -) - -insert into sequence values (0) -insert into sequence values (1) -insert into sequence select 2+n from sequence -insert into sequence select 4+n from sequence -insert into sequence select 8+n from sequence -insert into sequence select 16+n from sequence -insert into sequence select 32+n from sequence -insert into sequence select 64+n from sequence -insert into sequence select 128+n from sequence -insert into sequence select 256+n from sequence -insert into sequence select 512+n from sequence - -select sum(1/n) from sequence where n>=1 and n<=1000 +create table t1 (n real); +-- this is postgresql specific, fill the table +insert into t1 (select generate_series(1,1000)::real); +with tt as ( + select 1/(n*n) as recip from t1 +) select sum(recip) from tt; diff --git a/Task/Sum-of-squares/0815/sum-of-squares.0815 b/Task/Sum-of-squares/0815/sum-of-squares.0815 new file mode 100644 index 0000000000..6321c7847c --- /dev/null +++ b/Task/Sum-of-squares/0815/sum-of-squares.0815 @@ -0,0 +1,3 @@ +{x{*%<:d:~$<:1:~>><:2:~>><:3:~>><:4:~>><:5:~>><:6:~>><:7: +~>><:8:~>><:9:~>><:a:~>><:b:~>><:c:~>><:ffffffffffffffff: +~>{x{*>}:8f:{x{*&{=+>{~>&=x<:ffffffffffffffff:/#:8f:{{~% diff --git a/Task/Sum-of-squares/360-Assembly/sum-of-squares.360 b/Task/Sum-of-squares/360-Assembly/sum-of-squares.360 new file mode 100644 index 0000000000..99385825fb --- /dev/null +++ b/Task/Sum-of-squares/360-Assembly/sum-of-squares.360 @@ -0,0 +1,24 @@ +* Sum of squares 27/08/2015 +SUMOFSQR CSECT + USING SUMOFSQR,R12 + LR R12,R15 + LA R7,A a(1) + SR R6,R6 sum=0 + LA R3,1 i=1 +LOOPI CH R3,N do i=1 to hbound(a) + BH ELOOPI + L R5,0(R7) a(i) + M R4,0(R7) a(i)*a(i) + AR R6,R5 sum=sum+a(i)**2 + LA R7,4(R7) next a + LA R3,1(R3) i=i+1 + B LOOPI end i +ELOOPI XDECO R6,PG+23 edit sum + XPRNT PG,80 + XR R15,R15 + BR R14 +A DC F'1',F'2',F'3',F'4',F'5',F'6',F'7',F'8',F'9',F'10' +PG DC CL80'The sum of squares is: ' +N DC AL2((PG-A)/4) + YREGS + END SUMOFSQR diff --git a/Task/Sum-of-squares/ALGOL-W/sum-of-squares.alg b/Task/Sum-of-squares/ALGOL-W/sum-of-squares.alg new file mode 100644 index 0000000000..0a4dd274f9 --- /dev/null +++ b/Task/Sum-of-squares/ALGOL-W/sum-of-squares.alg @@ -0,0 +1,20 @@ +begin + % procedure to sum the elements of a vector. As the procedure can't find % + % the bounds of the array for itself, we pass them in lb and ub % + real procedure sumSquares ( real array vector ( * ) + ; integer value lb + ; integer value ub + ) ; + begin + real sum; + sum := 0; + for i := lb until ub do sum := sum + ( vector( i ) * vector( i ) ); + sum + end sumOfSquares ; + + % test the sumSquares procedure % + real array numbers ( 1 :: 5 ); + for i := 1 until 5 do numbers( i ) := i; + r_format := "A"; r_w := 10; r_d := 1; % set fixed point output % + write( sumSquares( numbers, 1, 5 ) ); +end. diff --git a/Task/Sum-of-squares/APL/sum-of-squares.apl b/Task/Sum-of-squares/APL/sum-of-squares.apl index 17ea52a29d..6df3b96b25 100644 --- a/Task/Sum-of-squares/APL/sum-of-squares.apl +++ b/Task/Sum-of-squares/APL/sum-of-squares.apl @@ -1,4 +1,4 @@ - square_sum←{+/2*⍨⍵} + square_sum←{+/⍵*2} square_sum 1 2 3 4 5 55 square_sum ⍬ ⍝The empty vector diff --git a/Task/Sum-of-squares/Elixir/sum-of-squares.elixir b/Task/Sum-of-squares/Elixir/sum-of-squares.elixir new file mode 100644 index 0000000000..e7320dec5e --- /dev/null +++ b/Task/Sum-of-squares/Elixir/sum-of-squares.elixir @@ -0,0 +1,2 @@ +iex(1)> Enum.reduce([3,1,4,1,5,9], 0, fn x,sum -> sum + x*x end) +133 diff --git a/Task/Sum-of-squares/Emacs-Lisp/sum-of-squares.l b/Task/Sum-of-squares/Emacs-Lisp/sum-of-squares.l new file mode 100644 index 0000000000..a81b1d40d2 --- /dev/null +++ b/Task/Sum-of-squares/Emacs-Lisp/sum-of-squares.l @@ -0,0 +1,4 @@ +(defun sum-square (ls) + (apply '+ (mapcar (lambda (k) (* k k) ) ls) )) + +(insert (format "%d"(sum-square (number-sequence 0 3) ))) diff --git a/Task/Sum-of-squares/Go/sum-of-squares-1.go b/Task/Sum-of-squares/Go/sum-of-squares-1.go new file mode 100644 index 0000000000..d86f44cca3 --- /dev/null +++ b/Task/Sum-of-squares/Go/sum-of-squares-1.go @@ -0,0 +1,13 @@ +package main + +import "fmt" + +var v = []float32{1, 2, .5} + +func main() { + var sum float32 + for _, x := range v { + sum += x * x + } + fmt.Println(sum) +} diff --git a/Task/Sum-of-squares/Go/sum-of-squares-2.go b/Task/Sum-of-squares/Go/sum-of-squares-2.go new file mode 100644 index 0000000000..602187bc1a --- /dev/null +++ b/Task/Sum-of-squares/Go/sum-of-squares-2.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" + + "github.com/gonum/floats" +) + +var v = []float64{1, 2, .5} + +func main() { + fmt.Println(floats.Dot(v, v)) +} diff --git a/Task/Sum-of-squares/Go/sum-of-squares.go b/Task/Sum-of-squares/Go/sum-of-squares.go deleted file mode 100644 index 2d79bcff0c..0000000000 --- a/Task/Sum-of-squares/Go/sum-of-squares.go +++ /dev/null @@ -1,11 +0,0 @@ -package main - -import "fmt" - -func main() { - var sum float32 - for _, x := range []float32{1,2,.5} { - sum += x*x - } - fmt.Println(sum) -} diff --git a/Task/Sum-of-squares/Python/sum-of-squares-3.py b/Task/Sum-of-squares/Python/sum-of-squares-3.py new file mode 100644 index 0000000000..fc591b3a50 --- /dev/null +++ b/Task/Sum-of-squares/Python/sum-of-squares-3.py @@ -0,0 +1,2 @@ +def mySumSquare(n): + return reduce(lambda x,y : x + y, map(lambda x : x*x, range(n+1))) diff --git a/Task/Sum-of-squares/REXX/sum-of-squares.rexx b/Task/Sum-of-squares/REXX/sum-of-squares.rexx index 461693c923..039fca4e31 100644 --- a/Task/Sum-of-squares/REXX/sum-of-squares.rexx +++ b/Task/Sum-of-squares/REXX/sum-of-squares.rexx @@ -1,12 +1,10 @@ -/*REXX program sums the squares of a vector which contains 15 numbers.*/ -numeric digits 50 /*allow 50-digit # (default is 9)*/ -v=-100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12 /*define a vector with some #s. */ -sum=0 /*initialize SUM to zero. */ - /*if vector is empty, sum = zero.*/ - do k=1 for words(v) /*process each number in the list*/ - sum=sum + word(v,k)**2 /*add squared element to the sum.*/ - end /*k*/ +/*REXX program sums the squares of the numbers in a (numeric) vector of 15 #s.*/ +numeric digits 100 /*allow 100─digit numbers; default is 9*/ +v=-100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12 /*define a vector with fifteen numbers.*/ +$=0 /*initialize the sum ($) to zero. */ + do k=1 for words(v) /*process each number in the V vector.*/ + $=$ + word(v,k)**2 /*add squared element (#) to the sum. */ + end /*k*/ /* [↑] if vector is empty, then sum=0.*/ -say 'The sum of ' words(v) " squared elements for the V vector is: " sum - /*stick a fork in it, we're done.*/ - /*stick a fork in it, we're done.*/ +say 'The sum of ' words(v) " squared elements for the V vector is: " $ + /*stick a fork in it, we're all done. */ diff --git a/Task/Sum-of-squares/Rust/sum-of-squares.rust b/Task/Sum-of-squares/Rust/sum-of-squares.rust index 58e648ae53..2615e2f0ff 100644 --- a/Task/Sum-of-squares/Rust/sum-of-squares.rust +++ b/Task/Sum-of-squares/Rust/sum-of-squares.rust @@ -1,17 +1,11 @@ -fn sqsum(v: Vec) -> f64 { - let mut s = 0.0; - - for i in v.iter() { - s += *i * *i; - } - - return s; +fn sq_sum(v: &[f64]) -> f64 { + v.iter().fold(0., |sum, &num| sum + num*num) } fn main() { - let v = vec!(3.0, 1.0, 4.0, 1.0, 5.0, 9.0); - println!("{}", sqsum(v)); + let v = vec![3.0, 1.0, 4.0, 1.0, 5.5, 9.7]; + println!("{}", sq_sum(&v)); - let u : Vec = vec!(); - println!("{}", sqsum(u)); + let u : Vec = vec![]; + println!("{}", sq_sum(&u)); } diff --git a/Task/Sum-of-squares/VBScript/sum-of-squares.vb b/Task/Sum-of-squares/VBScript/sum-of-squares.vb new file mode 100644 index 0000000000..6e81f40739 --- /dev/null +++ b/Task/Sum-of-squares/VBScript/sum-of-squares.vb @@ -0,0 +1,11 @@ +Function sum_of_squares(arr) + If UBound(arr) = -1 Then + sum_of_squares = 0 + End If + For i = 0 To UBound(arr) + sum_of_squares = sum_of_squares + (arr(i)^2) + Next +End Function + +WScript.StdOut.WriteLine sum_of_squares(Array(1,2,3,4,5)) +WScript.StdOut.WriteLine sum_of_squares(Array()) diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Fortran/sutherland-hodgman-polygon-clipping.f b/Task/Sutherland-Hodgman-polygon-clipping/Fortran/sutherland-hodgman-polygon-clipping.f new file mode 100644 index 0000000000..e597bf3297 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Fortran/sutherland-hodgman-polygon-clipping.f @@ -0,0 +1,257 @@ +module SutherlandHodgmanUtil + ! functions and type needed for Sutherland-Hodgman algorithm + + ! -------------------------------------------------------- ! + type polygon + !type for polygons + ! when you define a polygon, the first and the last vertices have to be the same + integer :: n + double precision, dimension(:,:), allocatable :: vertex + end type polygon + + contains + + ! -------------------------------------------------------- ! + subroutine sutherlandHodgman( ref, clip, outputPolygon ) + ! Sutherland Hodgman algorithm for 2d polygons + + ! -- parameters of the subroutine -- + type(polygon) :: ref, clip, outputPolygon + + ! -- variables used is the subroutine + type(polygon) :: workPolygon ! polygon clipped step by step + double precision, dimension(2) :: y1,y2 ! vertices of edge to clip workPolygon + integer :: i + + ! allocate workPolygon with the maximal possible size + ! the sum of the size of polygon ref and clip + allocate(workPolygon%vertex( ref%n+clip%n , 2 )) + + ! initialise the work polygon with clip + workPolygon%n = clip%n + workPolygon%vertex(1:workPolygon%n,:) = clip%vertex(1:workPolygon%n,:) + + do i=1,ref%n-1 ! for each edge i of the polygon ref + y1(:) = ref%vertex(i,:) ! vertex 1 of edge i + y2(:) = ref%vertex(i+1,:) ! vertex 2 of edge i + + ! clip the work polygon by edge i + call edgeClipping( workPolygon, y1, y2, outputPolygon) + ! workPolygon <= outputPolygon + workPolygon%n = outputPolygon%n + workPolygon%vertex(1:workPolygon%n,:) = outputPolygon%vertex(1:workPolygon%n,:) + + end do + deallocate(workPolygon%vertex) + end subroutine sutherlandHodgman + + ! -------------------------------------------------------- ! + subroutine edgeClipping( poly, y1, y2, outputPoly ) + ! make the clipping of the polygon by the line (x1x2) + + type(polygon) :: poly, outputPoly + double precision, dimension(2) :: y1, y2, x1, x2, intersecPoint + integer :: i, c + + c = 0 ! counter for the output polygon + + do i=1,poly%n-1 ! for each edge i of poly + x1(:) = poly%vertex(i,:) ! vertex 1 of edge i + x2(:) = poly%vertex(i+1,:) ! vertex 2 of edge i + + if ( inside(x1, y1, y2) ) then ! if vertex 1 in inside clipping region + if ( inside(x2, y1, y2) ) then ! if vertex 2 in inside clipping region + ! add the vertex 2 to the output polygon + c = c+1 + outputPoly%vertex(c,:) = x2(:) + + else ! vertex i+1 is outside + intersecPoint = intersection(x1, x2, y1,y2) + c = c+1 + outputPoly%vertex(c,:) = intersecPoint(:) + end if + else ! vertex i is outside + if ( inside(x2, y1, y2) ) then + intersecPoint = intersection(x1, x2, y1,y2) + c = c+1 + outputPoly%vertex(c,:) = intersecPoint(:) + + c = c+1 + outputPoly%vertex(c,:) = x2(:) + end if + end if + end do + + if (c .gt. 0) then + ! if the last vertice is not equal to the first one + if ( (outputPoly%vertex(1,1) .ne. outputPoly%vertex(c,1)) .or. & + (outputPoly%vertex(1,2) .ne. outputPoly%vertex(c,2))) then + c=c+1 + outputPoly%vertex(c,:) = outputPoly%vertex(1,:) + end if + end if + ! set the size of the outputPolygon + outputPoly%n = c + end subroutine edgeClipping + + ! -------------------------------------------------------- ! + function intersection( x1, x2, y1, y2) + ! computes the intersection between segment [x1x2] + ! and line the line (y1y2) + + ! -- parameters of the function -- + double precision, dimension(2) :: x1, x2, & ! points of the segment + y1, y2 ! points of the line + + double precision, dimension(2) :: intersection, vx, vy, x1y1 + double precision :: a + + vx(:) = x2(:) - x1(:) + vy(:) = y2(:) - y1(:) + + ! if the vectors are colinear + if ( crossProduct(vx,vy) .eq. 0.d0) then + x1y1(:) = y1(:) - x1(:) + ! if the the segment [x1x2] is included in the line (y1y2) + if ( crossProduct(x1y1,vx) .eq. 0.d0) then + ! the intersection is the last point of the segment + intersection(:) = x2(:) + end if + else ! the vectors are not colinear + ! we want to find the inersection between [x1x2] + ! and (y1,y2). + ! mathematically, we want to find a in [0;1] such + ! that : + ! x1 + a vx = y1 + b vy + ! <=> a vx = x1y1 + b vy + ! <=> a vx^vy = x1y1^vy , ^ is cross product + ! <=> a = x1y1^vy / vx^vy + + x1y1(:) = y1(:) - x1(:) + ! we compute a + a = crossProduct(x1y1,vy)/crossProduct(vx,vy) + ! if a is not in [0;1] + if ( (a .gt. 1.d0) .or. (a .lt. 0)) then + ! no intersection + else + intersection(:) = x1(:) + a*vx(:) + end if + end if + + end function intersection + + + ! -------------------------------------------------------- ! + function inside( p, y1, y2) + ! function that tells is the point p is at left of the line (y1y2) + + double precision, dimension(2) :: p, y1, y2, v1, v2 + logical :: inside + v1(:) = y2(:) - y1(:) + v2(:) = p(:) - y1(:) + if ( crossProduct(v1,v2) .ge. 0.d0) then + inside = .true. + else + inside = .false. + end if + + contains + end function inside + + ! -------------------------------------------------------- ! + function dotProduct( v1, v2) + ! compute the dot product of vectors v1 and v2 + double precision, dimension(2) :: v1 + double precision, dimension(2) :: v2 + double precision :: dotProduct + dotProduct = v1(1)*v2(1) + v1(2)*v2(2) + end function dotProduct + + ! -------------------------------------------------------- ! + function crossProduct( v1, v2) + ! compute the crossproduct of vectors v1 and v2 + double precision, dimension(2) :: v1 + double precision, dimension(2) :: v2 + double precision :: crossProduct + crossProduct = v1(1)*v2(2) - v1(2)*v2(1) + end function crossProduct + +end module SutherlandHodgmanUtil + +program main + + ! load the module for S-H algorithm + use SutherlandHodgmanUtil, only : polygon, & + sutherlandHodgman, & + edgeClipping + + type(polygon) :: p1, p2, res + integer :: c, n + double precision, dimension(2) :: y1, y2 + + ! when you define a polygon, the first and the last vertices have to be the same + + ! first polygon + p1%n = 10 + allocate(p1%vertex(p1%n,2)) + p1%vertex(1,1)=50.d0 + p1%vertex(1,2)=150.d0 + + p1%vertex(2,1)=200.d0 + p1%vertex(2,2)=50.d0 + + p1%vertex(3,1)= 350.d0 + p1%vertex(3,2)= 150.d0 + + p1%vertex(4,1)= 350.d0 + p1%vertex(4,2)= 300.d0 + + p1%vertex(5,1)= 250.d0 + p1%vertex(5,2)= 300.d0 + + p1%vertex(6,1)= 200.d0 + p1%vertex(6,2)= 250.d0 + + p1%vertex(7,1)= 150.d0 + p1%vertex(7,2)= 350.d0 + + p1%vertex(8,1)= 100.d0 + p1%vertex(8,2)= 250.d0 + + p1%vertex(9,1)= 100.d0 + p1%vertex(9,2)= 200.d0 + + p1%vertex(10,1)= 50.d0 + p1%vertex(10,2)= 150.d0 + + y1 = (/ 100.d0, 300.d0 /) + y2 = (/ 300.d0, 300.d0 /) + + ! second polygon + p2%n = 5 + allocate(p2%vertex(p2%n,2)) + + p2%vertex(1,1)= 100.d0 + p2%vertex(1,2)= 100.d0 + + p2%vertex(2,1)= 300.d0 + p2%vertex(2,2)= 100.d0 + + p2%vertex(3,1)= 300.d0 + p2%vertex(3,2)= 300.d0 + + p2%vertex(4,1)= 100.d0 + p2%vertex(4,2)= 300.d0 + + p2%vertex(5,1)= 100.d0 + p2%vertex(5,2)= 100.d0 + + allocate(res%vertex(p1%n+p2%n,2)) + call sutherlandHodgman( p2, p1, res) + write(*,*) "Suterland-Hodgman" + do c=1, res%n + write(*,*) res%vertex(c,1), res%vertex(c,2) + end do + deallocate(res%vertex) + +end program main diff --git a/Task/Symmetric-difference/Elixir/symmetric-difference.elixir b/Task/Symmetric-difference/Elixir/symmetric-difference.elixir new file mode 100644 index 0000000000..756bcdfcf1 --- /dev/null +++ b/Task/Symmetric-difference/Elixir/symmetric-difference.elixir @@ -0,0 +1,8 @@ +iex(1)> a = Enum.into(~w(John Bob Mary Serena), HashSet.new) +#HashSet<["Mary", "Serena", "John", "Bob"]> +iex(2)> b = Enum.into(~w(Jim Mary John Bob), HashSet.new) +#HashSet<["Mary", "Jim", "John", "Bob"]> +iex(3)> sym_dif = fn(a,b) -> Set.difference(Set.union(a,b), Set.intersection(a,b)) end +#Function<12.90072148/2 in :erl_eval.expr/5> +iex(4)> sym_dif.(a,b) +#HashSet<["Serena", "Jim"]> diff --git a/Task/Symmetric-difference/Julia/symmetric-difference.julia b/Task/Symmetric-difference/Julia/symmetric-difference.julia new file mode 100644 index 0000000000..42314067c6 --- /dev/null +++ b/Task/Symmetric-difference/Julia/symmetric-difference.julia @@ -0,0 +1,7 @@ +a = Set(["John", "Bob", "Mary", "Serena"]) +b = Set(["Jim", "Mary", "John", "Bob"]) +c = symdiff(a, b) + +println("Set a is: ", a) +println("Set b is: ", b) +println("Their symmetric difference is: ", c) diff --git a/Task/Synchronous-concurrency/C++/synchronous-concurrency.cpp b/Task/Synchronous-concurrency/C++/synchronous-concurrency.cpp new file mode 100644 index 0000000000..c8fbcc8f3f --- /dev/null +++ b/Task/Synchronous-concurrency/C++/synchronous-concurrency.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include +#include +#include + +struct lock_queue +{ + std::queue q; + std::mutex mutex; +}; + +void reader(std::string filename, std::future lines, lock_queue& out) +{ + std::string line; + std::ifstream in(filename); + while(std::getline(in, line)) { + line += '\n'; + std::lock_guard lock(out.mutex); + out.q.push(line); + } { + std::lock_guard lock(out.mutex); + out.q.push(""); + } + lines.wait(); + std::cout << "\nPrinted " << lines.get() << " lines\n"; +} + +void printer(std::promise lines, lock_queue& in) +{ + std::string s; + size_t line_n = 0; + bool print = false; + while(true) { + { + std::lock_guard lock(in.mutex); + if(( print = not in.q.empty() )) { //Assignment intended + s = in.q.front(); + in.q.pop(); + } + } + if(print) { + if(s == "") break; + std::cout << s; + ++line_n; + print = false; + } + } + lines.set_value(line_n); +} + +int main() +{ + lock_queue queue; + std::promise promise; + std::thread t1(reader, "input.txt", promise.get_future(), std::ref(queue)); + std::thread t2(printer, std::move(promise), std::ref(queue)); + t1.join(); t2.join(); +} diff --git a/Task/Synchronous-concurrency/Rust/synchronous-concurrency.rust b/Task/Synchronous-concurrency/Rust/synchronous-concurrency.rust new file mode 100644 index 0000000000..210910e255 --- /dev/null +++ b/Task/Synchronous-concurrency/Rust/synchronous-concurrency.rust @@ -0,0 +1,44 @@ +use std::fs::File; +use std::io::BufReader; +use std::io::BufRead; + +use std::thread::spawn; +use std::sync::mpsc::{SyncSender, Receiver, sync_channel}; + +fn main() { + let (tx, rx): (SyncSender, Receiver) = sync_channel::(0); + + // Reader thread. + spawn(move || { + let file = File::open("input.txt").unwrap(); + let reader = BufReader::new(file); + + for line in reader.lines() { + match line { + Ok(msg) => tx.send(msg).unwrap(), + Err(e) => println!("{}", e) + } + } + + drop(tx); + }); + + // Writer thread. + spawn(move || { + let mut loop_count: u16 = 0; + + loop { + let recvd = rx.recv(); + + match recvd { + Ok(msg) => { + println!("{}", msg); + loop_count += 1; + }, + Err(_) => break // rx.recv() will only err when tx is closed. + } + } + + println!("Line count: {}", loop_count); + }).join().unwrap(); +} diff --git a/Task/System-time/DCL/system-time.dcl b/Task/System-time/DCL/system-time.dcl new file mode 100644 index 0000000000..da3544d14a --- /dev/null +++ b/Task/System-time/DCL/system-time.dcl @@ -0,0 +1,6 @@ +$ start_time = f$time() +$ wait 0::10 +$ end_time = f$time() +$ write sys$output "start time was ", start_time +$ write sys$output "end time was ", end_time +$ write sys$output "delta time is ", f$delta_time( start_time, end_time ) diff --git a/Task/System-time/Elixir/system-time-1.elixir b/Task/System-time/Elixir/system-time-1.elixir new file mode 100644 index 0000000000..20b316d83d --- /dev/null +++ b/Task/System-time/Elixir/system-time-1.elixir @@ -0,0 +1,8 @@ +:os.timestamp # => {MegaSecs, Secs, MicroSecs} +:erlang.time # => {Hour, Minute, Second} +:erlang.date # => {Year, Month, Day} +:erlang.localtime # => {{Year, Month, Day}, {Hour, Minute, Second}} +:erlang.universaltime # => {{Year, Month, Day}, {Hour, Minute, Second}} + +:calendar.local_time # => {{Year, Month, Day}, {Hour, Minute, Second}} +:calendar.universal_time # => {{Year, Month, Day}, {Hour, Minute, Second}} diff --git a/Task/System-time/Elixir/system-time-2.elixir b/Task/System-time/Elixir/system-time-2.elixir new file mode 100644 index 0000000000..f6fb6dcd66 --- /dev/null +++ b/Task/System-time/Elixir/system-time-2.elixir @@ -0,0 +1 @@ +:random.seed(:erlang.now) diff --git a/Task/System-time/Emacs-Lisp/system-time.l b/Task/System-time/Emacs-Lisp/system-time.l new file mode 100644 index 0000000000..6d1063df26 --- /dev/null +++ b/Task/System-time/Emacs-Lisp/system-time.l @@ -0,0 +1,3 @@ +(message "%s" (current-time-string)) +=> +"Wed Oct 14 22:21:05 1987" diff --git a/Task/System-time/Julia/system-time.julia b/Task/System-time/Julia/system-time.julia new file mode 100644 index 0000000000..062183c510 --- /dev/null +++ b/Task/System-time/Julia/system-time.julia @@ -0,0 +1,4 @@ +ts = time() + +println("The system time is (in ISO 8601 format):") +println(strftime(" %F %T %Z", ts)) diff --git a/Task/System-time/PARI-GP/system-time.pari b/Task/System-time/PARI-GP/system-time-1.pari similarity index 100% rename from Task/System-time/PARI-GP/system-time.pari rename to Task/System-time/PARI-GP/system-time-1.pari diff --git a/Task/System-time/PARI-GP/system-time-2.pari b/Task/System-time/PARI-GP/system-time-2.pari new file mode 100644 index 0000000000..b5b44d2fac --- /dev/null +++ b/Task/System-time/PARI-GP/system-time-2.pari @@ -0,0 +1,3 @@ +install(time, "lf"); +t = time(); +print(t); \\ integer seconds since the epoch (usually 1 Jan 1970) diff --git a/Task/System-time/Ruby/system-time.rb b/Task/System-time/Ruby/system-time.rb index f92f64778c..2e59a882a5 100644 --- a/Task/System-time/Ruby/system-time.rb +++ b/Task/System-time/Ruby/system-time.rb @@ -8,3 +8,6 @@ # epoch time with fractional seconds puts t.to_f # => 1388134823.9801579 + +# epoch time as a rational (more precision): +puts Time.now.to_r # 1424900671883862959/1000000000 diff --git a/Task/Table-creation-Postal-addresses/Clojure/table-creation-postal-addresses.clj b/Task/Table-creation-Postal-addresses/Clojure/table-creation-postal-addresses.clj new file mode 100644 index 0000000000..1d604f7e33 --- /dev/null +++ b/Task/Table-creation-Postal-addresses/Clojure/table-creation-postal-addresses.clj @@ -0,0 +1,13 @@ +(require '[clojure.java.jdbc :as sql]) +; Using h2database for this simple example. +(def db {:classname "org.h2.Driver" + :subprotocol "h2:file" + :subname "db/my-dbname"}) + +(sql/db-do-commands db + (sql/create-table-ddl :address + [:id "bigint primary key auto_increment"] + [:street "varchar"] + [:city "varchar"] + [:state "varchar"] + [:zip "varchar"])) diff --git a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx index 01bbbca72f..a5809da825 100644 --- a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx +++ b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-1.rexx @@ -1,84 +1,37 @@ -/*REXX program to create/build/list a table of US postal addresses. */ -/*┌────────────────────────────────────────────────────────────────────┐ - │ Format of an entry in the USA address/city/state/zipcode structure.│ - │ │ - │ The "structure" name can be any legal variable name, but here the │ - │ name will be shortened to make these comments (and program) easier │ - │ to read; its name will be @USA (in any case). In addition, │ - │ the following variables names (stemmed array tails) will need to │ - │ be kept uninitialized (that is, not used for any variable name). │ - │ To that end, each of these "hands-off" variable names will have an │ - │ underscore in the beginning of each name. Other possibilities are │ - │ to have a trailing underscore (or both leading and trailing), some │ - │ other special eye-catching character such as: ! @ # $ ? │ - │ │ - │ Any field not specified will have a value of "null" (length 0). │ - │ │ - │ Any field can contain any number of characters, this can be limited│ - │ by the restrictions imposed by standards or USA legal definitions. │ - │ Any number of fields could be added (with invalid field testing). │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.0 the number of entries in the @USA "array". │ - │ │ - │ nnn is some positive integer (no leading zeros, it │ - │ can be any length). │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._name = name of person, business, or lot description.│ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._addr = 1st street address │ - │ @USA.nnn._addr2 = 2nd street address │ - │ @USA.nnn._addr3 = 3rd street address │ - │ @USA.nnn._addrNN = ... (any number, but in sequential order). │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._state = US postal code for the state/territory/etc. │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._city = official city name, may include any char. │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._zip = US postal zipcode, 5 digit format or │ - │ 10 char format. │ - ├────────────────────────────────────────────────────────────────────┤ - │ @USA.nnn._upHist = update History (who, date and timestamp). │ - └────────────────────────────────────────────────────────────────────┘*/ -@USA.=; @USA.0=0 - -@usa.0=@usa.0+1 /*bump the unique number for use.*/ -call @USA '_city','Boston' -call @USA '_state','MA' -call @USA '_addr',"51 Franklin Street" -call @USA '_name',"FSF Inc." -call @USA '_zip','02110-1301' - -@usa.0=@usa.0+1 /*bump the unique number for use.*/ -call @USA '_city','Washington' -call @USA '_state','DC' -call @USA '_addr',"The Oval Office" -call @USA '_addr2',"1600 Pennsylvania Avenue NW" -call @USA '_name',"The White House" -call @USA '_zip',20500 -call @USA 'list' -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────@USA subroutine────────────────────────*/ -@USA: procedure expose @USA.; parse arg what,txt; arg ?; nn=@usa.0 -if ?\=='LIST' then do - call value '@USA.'nn"."what,txt - call value '@USA.'nn".upHist",userid() date() time() - end - else do nn=1 for @usa.0 - call @USA_list - end /*nn*/ -return -/*───────────────────────────────@USA_tell subroutine───────────────────*/ -@USA_tell: _=value('@USA.'nn"."arg(1)); - if _\=='' then say right(translate(arg(1),,'_'),6) "──►" _ - return -/*───────────────────────────────@USA_list subroutine───────────────────*/ -@USA_list: call @USA_tell '_name' - call @USA_tell '_addr' - do j=2 until _=='' - call @USA_tell '_addr'j - end /*j*/ - call @USA_tell '_city' - call @USA_tell '_state' - call @USA_tell '_zip' - say copies('─',40) - return +╔════════════════════════════════════════════════════════════════════════════════╗ +╟───── Format of an entry in the USA address/city/state/zip code structure:──────╣ +║ ║ +║ The "structure" name can be any legal variable name, but here the name will be ║ +║ shortened to make these comments (and program) easier to read; its name will ║ +║ be @USA (in any letter case). In addition, the following variable names║ +║ (stemmed array tails) will need to be kept uninitialized (that is, not used ║ +║ for any variable name). To that end, each of these variable names will have an║ +║ underscore in the beginning of each name. Other possibilities are to have a ║ +║ trailing underscore (or both leading and trailing), or some other special eye─ ║ +║ catching character such as: ! @ # $ ? ║ +║ ║ +║ Any field not specified will have a value of "null" (which has a length of 0).║ +║ ║ +║ Any field can contain any number of characters, this can be limited by the ║ +║ restrictions imposed by the standards or the USA legal definitions. ║ +║ Any number of fields could be added (with invalid field testing). ║ +╟────────────────────────────────────────────────────────────────────────────────╣ +║ @USA.0 the number of entries in the @USA stemmed array. ║ +║ ║ +║ nnn is some positive integer of any length (no leading zeroes).║ +╟────────────────────────────────────────────────────────────────────────────────╣ +║ @USA.nnn._name is the name of person, business, or a lot description. ║ +╟────────────────────────────────────────────────────────────────────────────────╣ +║ @USA.nnn._addr is the 1st street address ║ +║ @USA.nnn._addr2 is the 2nd street address ║ +║ @USA.nnn._addr3 is the 3rd street address ║ +║ @USA.nnn._addrNN ··· (any number, but in sequential order). ║ +╟────────────────────────────────────────────────────────────────────────────────╣ +║ @USA.nnn._state is the USA postal code for the state, terrority, etc. ║ +╟────────────────────────────────────────────────────────────────────────────────╣ +║ @USA.nnn._city is the official city name, it may include any character. ║ +╟────────────────────────────────────────────────────────────────────────────────╣ +║ @USA.nnn._zip is the USA postal zip code, five or ten digit format. ║ +╟────────────────────────────────────────────────────────────────────────────────╣ +║ @USA.nnn._upHist is the update history (who, date and timestamp). ║ +╚════════════════════════════════════════════════════════════════════════════════╝ diff --git a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-2.rexx b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-2.rexx index e33e9020ab..186c4a578d 100644 --- a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-2.rexx +++ b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-2.rexx @@ -1,35 +1,38 @@ -/* REXX *************************************************************** -* 17.05.2013 Walter Pachl -* should work with every REXX. -* I use 0xxx for the tail because this can't be modified -**********************************************************************/ -USA.=''; USA.0=0 -Call add_usa 'Boston','MA','51 Franklin Street',,'FSF Inc.',, - '02110-1301' -Call add_usa 'Washington','DC','The Oval Office',, - '1600 Pennsylvania Avenue NW','The White House',20500 -call list_usa -Exit - -add_usa: -z=usa.0+1 -Parse Arg usa.z.0city,, - usa.z.0state,, - usa.z.0addr,, - usa.z.0addr2,, - usa.z.0name,, - usa.z.0zip -usa.0=z -Return - -list_usa: -Do z=1 To usa.0 - Say ' name -->' usa.z.0name - Say ' addr -->' usa.z.0addr - If usa.z.0addr2<>'' Then Say ' addr2 -->' usa.z.0addr2 - Say ' city -->' usa.z.0city - Say ' state -->' usa.z.0state - Say ' zip -->' usa.z.0zip - Say copies('-',40) - End -Return +/*REXX program creates, builds, and lists a table of U.S.A. postal addresses.*/ +@usa.=; @usa.0=0 /*initialize stemmed array & 1st value.*/ +@usa.0=@usa.0+1 /*bump the unique number for usage. */ + call USA '_city' , 'Boston' + call USA '_state' , 'MA' + call USA '_addr' , "51 Franklin Street" + call USA '_name' , "FSF Inc." + call USA '_zip' , '02110-1301' +@usa.0=@usa.0+1 /*bump the unique number for usage. */ + call USA '_city' , 'Washington' + call USA '_state' , 'DC' + call USA '_addr' , "The Oval Office" + call USA '_addr2' , "1600 Pennsylvania Avenue NW" + call USA '_name' , "The White House" + call USA '_zip' , 20500 + call USA 'list' +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +USA: procedure expose @USA.; parse arg what,txt; arg ?; nn=@usa.0 +if ?=='LIST' then do nn=1 for @usa.0; call lister; end /*nn*/ + else do + call value '@USA.'nn"."what , txt + call value '@USA.'nn".upHist", userid() date() time() + end +return +/*────────────────────────────────────────────────────────────────────────────*/ +tell: _=value('@USA.'nn"."arg(1)) + if _\=='' then say right(translate(arg(1), , '_'), 6) "──►" _ + return +/*────────────────────────────────────────────────────────────────────────────*/ +lister: call tell '_name' + call tell '_addr' + do j=2 until _==''; call tell '_addr'j; end /*j*/ + call tell '_city' + call tell '_state' + call tell '_zip' + say copies('─', 40) + return diff --git a/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-3.rexx b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-3.rexx new file mode 100644 index 0000000000..e33e9020ab --- /dev/null +++ b/Task/Table-creation-Postal-addresses/REXX/table-creation-postal-addresses-3.rexx @@ -0,0 +1,35 @@ +/* REXX *************************************************************** +* 17.05.2013 Walter Pachl +* should work with every REXX. +* I use 0xxx for the tail because this can't be modified +**********************************************************************/ +USA.=''; USA.0=0 +Call add_usa 'Boston','MA','51 Franklin Street',,'FSF Inc.',, + '02110-1301' +Call add_usa 'Washington','DC','The Oval Office',, + '1600 Pennsylvania Avenue NW','The White House',20500 +call list_usa +Exit + +add_usa: +z=usa.0+1 +Parse Arg usa.z.0city,, + usa.z.0state,, + usa.z.0addr,, + usa.z.0addr2,, + usa.z.0name,, + usa.z.0zip +usa.0=z +Return + +list_usa: +Do z=1 To usa.0 + Say ' name -->' usa.z.0name + Say ' addr -->' usa.z.0addr + If usa.z.0addr2<>'' Then Say ' addr2 -->' usa.z.0addr2 + Say ' city -->' usa.z.0city + Say ' state -->' usa.z.0state + Say ' zip -->' usa.z.0zip + Say copies('-',40) + End +Return diff --git a/Task/Take-notes-on-the-command-line/Mathematica/take-notes-on-the-command-line.math b/Task/Take-notes-on-the-command-line/Mathematica/take-notes-on-the-command-line.math new file mode 100644 index 0000000000..238662cbc4 --- /dev/null +++ b/Task/Take-notes-on-the-command-line/Mathematica/take-notes-on-the-command-line.math @@ -0,0 +1,5 @@ +If[Length[$CommandLine < 11], str = OpenRead["NOTES.TXT"]; + Print[ReadString[str, EndOfFile]]; Close[str], + str = OpenAppend["NOTES.TXT"]; WriteLine[str, DateString[]]; + WriteLine[str, "\t" <> StringRiffle[$CommandLine[[11 ;;]]]]; + Close[str]] diff --git a/Task/Temperature-conversion/360-Assembly/temperature-conversion.360 b/Task/Temperature-conversion/360-Assembly/temperature-conversion.360 new file mode 100644 index 0000000000..8a370c6eeb --- /dev/null +++ b/Task/Temperature-conversion/360-Assembly/temperature-conversion.360 @@ -0,0 +1,73 @@ +* Temperature conversion 10/09/2015 +TEMPERAT CSECT + USING TEMPERAT,R15 + LA R4,1 i=1 + LA R5,TT @tt(1) + LA R6,IDE @ide(1) +LOOPI CH R4,=AL2((T-TT)/8) do i=1 to hbound(tt) + BH ELOOPI + ZAP T,0(8,R5) t=tt(i) + CVD R4,DW store to packed decimal + UNPK PG(1),DW+7(1) unpack + OI PG,X'F0' zap sign + MVI PG+1,C' ' + MVC PG+2(12),0(R6) ide(i) + XPRNT PG,14 output i + MVC PG(12),=C'Kelvin: ' + MVC ZN,EDMASKN load mask + EDMK ZN,T+5 t (PL3) + BCTR R1,0 sign location + MVC 0(1,R1),ZN+L'ZN-1 put sign + MVC PG+12(L'ZN-1),ZN value + MVC PG+19(2),=C' K' unit + XPRNT PG,21 output Kelvin + MVC PG(12),=C'Celsius: ' + ZAP DW,T t + SP DW,=P'273.15' t-273.15 + MVC ZN,EDMASKN load mask + EDMK ZN,DW+5 (PL3) + BCTR R1,0 sign location + MVC 0(1,R1),ZN+L'ZN-1 put sign + MVC PG+12(L'ZN-1),ZN value + MVC PG+19(2),=C' C' unit + XPRNT PG,21 output Celsius + MVC PG(12),=C'Fahrenheit: ' + ZAP DW,T t + MP DW,=P'18' *18 + DP DW,=PL3'10' /10 + ZAP DW,DW(5) + SP DW,=P'459.67' t*1.8-459.67 + MVC ZN,EDMASKN load mask + EDMK ZN,DW+5 (PL3) + BCTR R1,0 sign location + MVC 0(1,R1),ZN+L'ZN-1 put sign + MVC PG+12(L'ZN-1),ZN value + MVC PG+19(2),=C' F' unit + XPRNT PG,21 output Fahrenheit + MVC PG(12),=C'Rankine: ' + ZAP DW,T t + MP DW,=P'18' *18 + DP DW,=PL3'10' /10 + ZAP DW,DW(5) t*1.8 + MVC ZN,EDMASKN load mask + EDMK ZN,DW+5 (PL3) + BCTR R1,0 sign location + MVC 0(1,R1),ZN+L'ZN-1 put sign + MVC PG+12(L'ZN-1),ZN value + MVC PG+19(2),=C' R' unit + XPRNT PG,21 output Rankine + LA R4,1(R4) i=i+1 + LA R5,8(R5) @tt(i) + LA R6,12(R6) @ide(i) + B LOOPI +ELOOPI XR R15,R15 + BR R14 +IDE DC CL12'absolute',CL12'ice melts',CL12'water boils' +TT DC PL8'0.00',PL8'273.15',PL8'373.15' +T DS PL8 +PG DS CL24 +ZN DS ZL8 5num +DW DS D PL8 15num +EDMASKN DC X'402021204B202060' CL8 5num + YREGS + END TEMPERAT diff --git a/Task/Temperature-conversion/ALGOL-68/temperature-conversion.alg b/Task/Temperature-conversion/ALGOL-68/temperature-conversion.alg new file mode 100644 index 0000000000..074517a29a --- /dev/null +++ b/Task/Temperature-conversion/ALGOL-68/temperature-conversion.alg @@ -0,0 +1,8 @@ +BEGIN + REAL kelvin; + read (kelvin); + FORMAT f = $g(8,2), " K = ", g(8,2)xgl$; + printf ((f, kelvin, kelvin - 273.15, "C")); + printf ((f, kelvin, 9.0 * kelvin / 5.0, "R")); + printf ((f, kelvin, 9.0 * kelvin / 5.0 - 459.67, "F")) +END diff --git a/Task/Temperature-conversion/Befunge/temperature-conversion.bf b/Task/Temperature-conversion/Befunge/temperature-conversion.bf new file mode 100644 index 0000000000..ece5de6c07 --- /dev/null +++ b/Task/Temperature-conversion/Befunge/temperature-conversion.bf @@ -0,0 +1,6 @@ +0000>0p~>"."-:!#v_2-::0\`\9`+!#v_$1>/\:3`#v_\>\:3 \`#v_v +1#<<^0 /2++g001!<1 \+g00\+*+55\< ^+55\-1< ^*+55\+1"."\>:55+% 68*v >:#,_$55+,\:!#@_^ + $_^#!:/+55\+< ^\" :"_°C ( F: kelvin -- celsius ) 273.15e0 f- ; +: k>°R ( F: kelvin -- rankine ) 1.8e0 f* ; +: °R>°F ( F: rankine -- fahrenheit ) 459.67e0 f- ; +: k>°F ( F: kelvin -- fahrenheit ) k>°R °R>°F ; +: main + argc 1 > if 1 arg >float + fdup f. ." K" cr + fdup k>°C f. ." °C" cr + fdup k>°F f. ." °F" cr + fdup k>°R f. ." °R" cr + then ; + +main bye diff --git a/Task/Temperature-conversion/JavaScript/temperature-conversion.js b/Task/Temperature-conversion/JavaScript/temperature-conversion.js new file mode 100644 index 0000000000..faca3a822b --- /dev/null +++ b/Task/Temperature-conversion/JavaScript/temperature-conversion.js @@ -0,0 +1,14 @@ +var k2c = k => k - 273.15 +var k2r = k => k * 1.8 +var k2f = k => k2r(k) - 459.67 + +Number.prototype.toMaxDecimal = function (d) { + return +this.toFixed(d) + '' +} + +function kCnv(k) { + document.write( k,'K° = ', k2c(k).toMaxDecimal(2),'C° = ', k2r(k).toMaxDecimal(2),'R° = ', k2f(k).toMaxDecimal(2),'F°
' ) +} + +kCnv(21) +kCnv(295) diff --git a/Task/Temperature-conversion/NewLISP/temperature-conversion.newlisp b/Task/Temperature-conversion/NewLISP/temperature-conversion.newlisp new file mode 100644 index 0000000000..24f1a714a2 --- /dev/null +++ b/Task/Temperature-conversion/NewLISP/temperature-conversion.newlisp @@ -0,0 +1,21 @@ +(define (to-celsius k) + (- k 273.15) +) + +(define (to-fahrenheit k) + (- (* k 1.8) 459.67) +) + +(define (to-rankine k) + (* k 1.8) +) + +(define (kelvinConversion k) + (if (number? k) + (println k " kelvin is equivalent to:\n" + (to-celsius k) " celsius\n" + (to-fahrenheit k) " fahrenheit\n" + (to-rankine k) " rankine") + (println "Please enter a number only, with no º or letter. ") + ) +) diff --git a/Task/Temperature-conversion/Pascal/temperature-conversion.pascal b/Task/Temperature-conversion/Pascal/temperature-conversion.pascal new file mode 100644 index 0000000000..1767de1aa3 --- /dev/null +++ b/Task/Temperature-conversion/Pascal/temperature-conversion.pascal @@ -0,0 +1,54 @@ +program TemperatureConvert; + +type + TemperatureType = (C, F, K, R); + +var + kelvin: real; + + function ConvertTemperature(temperature: real; fromType, toType: TemperatureType): real; + + var + initial, result: real; + + begin + (* We are going to first convert whatever we're given into Celsius. + Then we'll convert that into whatever we're asked to convert into. + Maybe not the most efficient way to do this, but easy to understand + and should make it easier to add any additional temperature units. *) + if fromType <> toType then + begin + case fromType of (* first convert the temperature into Celsius *) + C: + initial := temperature; + F: + initial := (temperature - 32) / 1.8; + K: + initial := temperature - 273.15; + R: + initial := (temperature - 491.67) / 1.8; + end; + case toType of (* now convert from Celsius into whatever degree type was asked for *) + C: + result := initial; + F: + result := (initial * 1.8) + 32; + K: + result := initial + 273.15; + R: + result := (initial * 1.8) + 491.67; + end; + end + else (* no point doing all that math if we're asked to convert from and to the same type *) + result := temperature; + ConvertTemperature := result; + end; + +begin + write('Temperature to convert (in kelvins): '); + readln(kelvin); + writeln(kelvin : 3 : 2, ' in kelvins is '); + writeln(' ', ConvertTemperature(kelvin, K, C) : 3 : 2, ' in degrees Celsius.'); + writeln(' ', ConvertTemperature(kelvin, K, F) : 3 : 2, ' in degrees Fahrenheit.'); + writeln(' ', ConvertTemperature(kelvin, K, R) : 3 : 2, ' in degrees Rankine.'); +end. diff --git a/Task/Temperature-conversion/Perl-6/temperature-conversion.pl6 b/Task/Temperature-conversion/Perl-6/temperature-conversion.pl6 index 2903905fbc..399ccd179d 100644 --- a/Task/Temperature-conversion/Perl-6/temperature-conversion.pl6 +++ b/Task/Temperature-conversion/Perl-6/temperature-conversion.pl6 @@ -1,4 +1,4 @@ -while '' ne my $answer = prompt 'Temperature: ' { +while my $answer = prompt 'Temperature: ' { my $k = do given $answer { when s/:i C $// { $_ + 273.15 } when s/:i F $// { ($_ + 459.67) / 1.8 } diff --git a/Task/Temperature-conversion/PowerShell/temperature-conversion.psh b/Task/Temperature-conversion/PowerShell/temperature-conversion.psh new file mode 100644 index 0000000000..c367d25e96 --- /dev/null +++ b/Task/Temperature-conversion/PowerShell/temperature-conversion.psh @@ -0,0 +1,21 @@ +function temp($k){ + try{ + $c = $k - 273.15 + $r = $k / 5 * 9 + $f = $r - 459.67 + } catch { + Write-host "Input error." + return + } + + Write-host "" + Write-host " TEMP (Kelvin) : " $k + Write-host " TEMP (Celsius) : " $c + Write-host " TEMP (Fahrenheit): " $f + Write-host " TEMP (Rankine) : " $r + Write-host "" + +} + +$input=Read-host "Enter a temperature in Kelvin" +temp $input diff --git a/Task/Temperature-conversion/PureBasic/temperature-conversion.purebasic b/Task/Temperature-conversion/PureBasic/temperature-conversion.purebasic new file mode 100644 index 0000000000..63ecebd472 --- /dev/null +++ b/Task/Temperature-conversion/PureBasic/temperature-conversion.purebasic @@ -0,0 +1,16 @@ +Procedure.d Kelvin2Celsius(tK.d) : ProcedureReturn tK-273.15 : EndProcedure +Procedure.d Kelvin2Fahrenheit(tK.d) : ProcedureReturn tK*1.8-459.67 : EndProcedure +Procedure.d Kelvin2Rankine(tK.d) : ProcedureReturn tK*1.8 : EndProcedure + +OpenConsole() +Repeat + Print("Temperatur Kelvin? ") : Kelvin.d = ValD(Input()) + PrintN("Conversion:") + PrintN(#TAB$+"Celsius "+#TAB$+RSet(StrD(Kelvin2Celsius(Kelvin),2),8,Chr(32))) + PrintN(#TAB$+"Fahrenheit"+#TAB$+RSet(StrD(Kelvin2Fahrenheit(Kelvin),2),8,Chr(32))) + PrintN(#TAB$+"Rankine "+#TAB$+RSet(StrD(Kelvin2Rankine(Kelvin),2),8,Chr(32))) + PrintN("ESC = End.") + Repeat + k$=Inkey() : Delay(50) : If RawKey()=#ESC : End : EndIf + Until RawKey() +ForEver diff --git a/Task/Temperature-conversion/VBScript/temperature-conversion.vb b/Task/Temperature-conversion/VBScript/temperature-conversion.vb new file mode 100644 index 0000000000..027c64cdd2 --- /dev/null +++ b/Task/Temperature-conversion/VBScript/temperature-conversion.vb @@ -0,0 +1,19 @@ +WScript.StdOut.Write "Enter the temperature in Kelvin:" +tmp = WScript.StdIn.ReadLine + +WScript.StdOut.WriteLine "Kelvin: " & tmp +WScript.StdOut.WriteLine "Fahrenheit: " & fahrenheit(CInt(tmp)) +WScript.StdOut.WriteLine "Celsius: " & celsius(CInt(tmp)) +WScript.StdOut.WriteLine "Rankine: " & rankine(CInt(tmp)) + +Function fahrenheit(k) + fahrenheit = (k*1.8)-459.67 +End Function + +Function celsius(k) + celsius = k-273.15 +End Function + +Function rankine(k) + rankine = (k-273.15)*1.8+491.67 +End Function diff --git a/Task/Terminal-control-Clear-the-screen/Befunge/terminal-control-clear-the-screen.bf b/Task/Terminal-control-Clear-the-screen/Befunge/terminal-control-clear-the-screen.bf new file mode 100644 index 0000000000..7115fcbc42 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Befunge/terminal-control-clear-the-screen.bf @@ -0,0 +1 @@ +"J2["39*,,,,@ diff --git a/Task/Terminal-control-Clear-the-screen/Common-Lisp/terminal-control-clear-the-screen-1.lisp b/Task/Terminal-control-Clear-the-screen/Common-Lisp/terminal-control-clear-the-screen-1.lisp new file mode 100644 index 0000000000..8f1d0e2538 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Common-Lisp/terminal-control-clear-the-screen-1.lisp @@ -0,0 +1 @@ +(format t "~C[2J" #\Esc) diff --git a/Task/Terminal-control-Clear-the-screen/Common-Lisp/terminal-control-clear-the-screen-2.lisp b/Task/Terminal-control-Clear-the-screen/Common-Lisp/terminal-control-clear-the-screen-2.lisp new file mode 100644 index 0000000000..615a78c017 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Common-Lisp/terminal-control-clear-the-screen-2.lisp @@ -0,0 +1,7 @@ +(defun sh (cmd) + "A multi-implementation function equivalent for the C function system" + #+clisp (shell cmd) + #+ecl (si:system cmd) + #+sbcl (sb-ext:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*) + #+clozure (ccl:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*)) +(sh "clear") diff --git a/Task/Terminal-control-Clear-the-screen/Erlang/terminal-control-clear-the-screen.erl b/Task/Terminal-control-Clear-the-screen/Erlang/terminal-control-clear-the-screen.erl new file mode 100644 index 0000000000..d1663b8cca --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/Erlang/terminal-control-clear-the-screen.erl @@ -0,0 +1 @@ +clear()->io:format(os:cmd("clear")). diff --git a/Task/Terminal-control-Clear-the-screen/NewLISP/terminal-control-clear-the-screen-1.newlisp b/Task/Terminal-control-Clear-the-screen/NewLISP/terminal-control-clear-the-screen-1.newlisp new file mode 100644 index 0000000000..0ddcb3caa3 --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/NewLISP/terminal-control-clear-the-screen-1.newlisp @@ -0,0 +1 @@ +(! "clear") diff --git a/Task/Terminal-control-Clear-the-screen/NewLISP/terminal-control-clear-the-screen-2.newlisp b/Task/Terminal-control-Clear-the-screen/NewLISP/terminal-control-clear-the-screen-2.newlisp new file mode 100644 index 0000000000..cf6ba7a83c --- /dev/null +++ b/Task/Terminal-control-Clear-the-screen/NewLISP/terminal-control-clear-the-screen-2.newlisp @@ -0,0 +1 @@ +!clear diff --git a/Task/Terminal-control-Coloured-text/Befunge/terminal-control-coloured-text.bf b/Task/Terminal-control-Coloured-text/Befunge/terminal-control-coloured-text.bf new file mode 100644 index 0000000000..fbd501c3e7 --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Befunge/terminal-control-coloured-text.bf @@ -0,0 +1,2 @@ +:#,_55+"m["39*,,, diff --git a/Task/Terminal-control-Coloured-text/Julia/terminal-control-coloured-text.julia b/Task/Terminal-control-Coloured-text/Julia/terminal-control-coloured-text.julia new file mode 100644 index 0000000000..a65f80988a --- /dev/null +++ b/Task/Terminal-control-Coloured-text/Julia/terminal-control-coloured-text.julia @@ -0,0 +1,34 @@ +using AnsiColor + +function showbasecolors() + for color in keys(Base.text_colors) + print_with_color(color, " ", string(color), " ") + end + println() +end + +function showansicolors() + for fore in keys(AnsiColor.COLORS) + print(@sprintf("%15s ", fore)) + for back in keys(AnsiColor.COLORS) + print(" ", colorize(fore, "RC", background=back), " ") + end + println() + end + println() + for eff in keys(AnsiColor.MODES) + print(@sprintf(" %s ", eff), colorize("default", "RC", mode=eff)) + end + println() +end + +if Base.have_color + println() + println("Base Colors") + showbasecolors() + println("\nusing AnsiColor") + showansicolors() + println() +else + println("This terminal appears not to support color.") +end diff --git a/Task/Terminal-control-Coloured-text/REXX/terminal-control-coloured-text.rexx b/Task/Terminal-control-Coloured-text/REXX/terminal-control-coloured-text.rexx index 630baf2dba..9082d4e656 100644 --- a/Task/Terminal-control-Coloured-text/REXX/terminal-control-coloured-text.rexx +++ b/Task/Terminal-control-Coloured-text/REXX/terminal-control-coloured-text.rexx @@ -8,7 +8,7 @@ color.1 = 'dark blue' /*│ Normally, all programs issue│*/ color.2 = 'dark green' /*│ the (above) error messages │*/ color.3 = 'dark cyan/turquois' /*│ through another REXX program│*/ color.4 = 'dark red' /*│ ($ERR) which has more │*/ -color.5 = 'dark pink/magenta' /*│ verbage and explanations, │*/ +color.5 = 'dark pink/magenta' /*│ verbiage and explanations, │*/ color.6 = 'dark yellow (orange)' /*│ and issues the error text in│*/ color.7 = 'dark white' /*│ red (if color is available).│*/ color.8 = 'brite black (grey/gray)' /*└─────────────────────────────┘*/ diff --git a/Task/Terminal-control-Cursor-positioning/Befunge/terminal-control-cursor-positioning.bf b/Task/Terminal-control-Cursor-positioning/Befunge/terminal-control-cursor-positioning.bf new file mode 100644 index 0000000000..b5ad17e203 --- /dev/null +++ b/Task/Terminal-control-Cursor-positioning/Befunge/terminal-control-cursor-positioning.bf @@ -0,0 +1 @@ +0"olleHH3;6["39*>:#,_$@ diff --git a/Task/Terminal-control-Dimensions/Batch-File/terminal-control-dimensions.bat b/Task/Terminal-control-Dimensions/Batch-File/terminal-control-dimensions.bat new file mode 100644 index 0000000000..2a3393b146 --- /dev/null +++ b/Task/Terminal-control-Dimensions/Batch-File/terminal-control-dimensions.bat @@ -0,0 +1,10 @@ +@echo off + +for /f "tokens=1,2 delims= " %%A in ('mode con') do ( + if "%%A"=="Lines:" set line=%%B + if "%%A"=="Columns:" set cols=%%B +) + +echo Lines: %line% +echo Columns: %cols% +exit /b 0 diff --git a/Task/Terminal-control-Dimensions/Visual-Basic/terminal-control-dimensions.vb b/Task/Terminal-control-Dimensions/Visual-Basic/terminal-control-dimensions.vb new file mode 100644 index 0000000000..25f6f5205e --- /dev/null +++ b/Task/Terminal-control-Dimensions/Visual-Basic/terminal-control-dimensions.vb @@ -0,0 +1,19 @@ +Module Module1 + + Sub Main() + Dim bufferHeight = Console.BufferHeight + Dim bufferWidth = Console.BufferWidth + Dim windowHeight = Console.WindowHeight + Dim windowWidth = Console.WindowWidth + + Console.Write("Buffer Height: ") + Console.WriteLine(bufferHeight) + Console.Write("Buffer Width: ") + Console.WriteLine(bufferWidth) + Console.Write("Window Height: ") + Console.WriteLine(windowHeight) + Console.Write("Window Width: ") + Console.WriteLine(windowWidth) + End Sub + +End Module diff --git a/Task/Terminal-control-Display-an-extended-character/Befunge/terminal-control-display-an-extended-character-1.bf b/Task/Terminal-control-Display-an-extended-character/Befunge/terminal-control-display-an-extended-character-1.bf new file mode 100644 index 0000000000..f1a155e1ef --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Befunge/terminal-control-display-an-extended-character-1.bf @@ -0,0 +1 @@ +"| "+,@ diff --git a/Task/Terminal-control-Display-an-extended-character/Befunge/terminal-control-display-an-extended-character-2.bf b/Task/Terminal-control-Display-an-extended-character/Befunge/terminal-control-display-an-extended-character-2.bf new file mode 100644 index 0000000000..286a506f3d --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Befunge/terminal-control-display-an-extended-character-2.bf @@ -0,0 +1 @@ +"%~"+,@ diff --git a/Task/Terminal-control-Display-an-extended-character/Common-Lisp/terminal-control-display-an-extended-character.lisp b/Task/Terminal-control-Display-an-extended-character/Common-Lisp/terminal-control-display-an-extended-character.lisp new file mode 100644 index 0000000000..cf76df8cc9 --- /dev/null +++ b/Task/Terminal-control-Display-an-extended-character/Common-Lisp/terminal-control-display-an-extended-character.lisp @@ -0,0 +1,2 @@ +(format t "札幌~%") +(format t "~C~%" (code-char #x00A3)) diff --git a/Task/Terminal-control-Hiding-the-cursor/Befunge/terminal-control-hiding-the-cursor.bf b/Task/Terminal-control-Hiding-the-cursor/Befunge/terminal-control-hiding-the-cursor.bf new file mode 100644 index 0000000000..aeebab488a --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Befunge/terminal-control-hiding-the-cursor.bf @@ -0,0 +1,3 @@ +"l52?["39*,,,,,, >v +"retnE sserP">:#,_v> +"h52?["39*,,,,,,@ >~ diff --git a/Task/Terminal-control-Hiding-the-cursor/Common-Lisp/terminal-control-hiding-the-cursor.lisp b/Task/Terminal-control-Hiding-the-cursor/Common-Lisp/terminal-control-hiding-the-cursor.lisp new file mode 100644 index 0000000000..ebc72077d9 --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/Common-Lisp/terminal-control-hiding-the-cursor.lisp @@ -0,0 +1,13 @@ +(defun sh (cmd) + #+clisp (shell cmd) + #+ecl (si:system cmd) + #+sbcl (sb-ext:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*) + #+clozure (ccl:run-program "/bin/sh" (list "-c" cmd) :input nil :output *standard-output*)) + +(defun show-cursor (x) + (if x (sh "tput cvvis") (sh "tput civis"))) + +(show-cursor nil) +(sleep 3) +(show-cursor t) +(sleep 3) diff --git a/Task/Terminal-control-Hiding-the-cursor/REXX/terminal-control-hiding-the-cursor.rexx b/Task/Terminal-control-Hiding-the-cursor/REXX/terminal-control-hiding-the-cursor.rexx new file mode 100644 index 0000000000..18518b72bb --- /dev/null +++ b/Task/Terminal-control-Hiding-the-cursor/REXX/terminal-control-hiding-the-cursor.rexx @@ -0,0 +1,20 @@ +/*REXX pgm calls a function in a shared library (regutil) to hide/show cursor.*/ +z=rxfuncadd('sysloadfuncs', "regutil", 'sysloadfuncs') /*add a function lib.*/ +if z\==0 then do /*test the return cod*/ + say 'return code' z "from rxfuncadd" /*tell about bad RC. */ + exit z /*exit this program. */ + end + +call sysloadfuncs /*load the functions.*/ + + /* [↓] call a particular function. */ +call syscurstate 'off' /*hide the displaying of the cursor. */ +say 'showing of the cursor is now off' /*inform that the cursor is now hidden.*/ + + /* ··· and perform some stuff here ··· */ +say 'sleeping for three seconds ...' /*inform the user of what we're doing. */ +call sleep 3 /*might as well sleep for three seconds*/ + +call syscurstate 'on' /*(unhide) the displaying of the cursor*/ +say 'showing of the cursor is now on' /*inform that the cursor is now showing*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Terminal-control-Inverse-video/Befunge/terminal-control-inverse-video.bf b/Task/Terminal-control-Inverse-video/Befunge/terminal-control-inverse-video.bf new file mode 100644 index 0000000000..baae3fe0dc --- /dev/null +++ b/Task/Terminal-control-Inverse-video/Befunge/terminal-control-inverse-video.bf @@ -0,0 +1 @@ +0"lamroNm["39*"esrevnIm7["39*>:#,_$@ diff --git a/Task/Terminal-control-Preserve-screen/Common-Lisp/terminal-control-preserve-screen.lisp b/Task/Terminal-control-Preserve-screen/Common-Lisp/terminal-control-preserve-screen.lisp new file mode 100644 index 0000000000..668453b0e6 --- /dev/null +++ b/Task/Terminal-control-Preserve-screen/Common-Lisp/terminal-control-preserve-screen.lisp @@ -0,0 +1,7 @@ +(format t "~C[?1049h~C[H" (code-char #O33) (code-char #O33)) +(format t "Alternate screen buffer~%") +(loop for i from 5 downto 1 do (progn + (format t "~%going back in ~a" i) + (sleep 1) + )) +(format t "~C[?1049l" (code-char #O33)) diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Batch-File/terminal-control-ringing-the-terminal-bell.bat b/Task/Terminal-control-Ringing-the-terminal-bell/Batch-File/terminal-control-ringing-the-terminal-bell.bat new file mode 100644 index 0000000000..2f413a3aa2 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Batch-File/terminal-control-ringing-the-terminal-bell.bat @@ -0,0 +1,3 @@ +@echo off +for /f %%. in ('forfiles /m "%~nx0" /c "cmd /c echo 0x07"') do set bell=%%. +echo %bell% diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Common-Lisp/terminal-control-ringing-the-terminal-bell.lisp b/Task/Terminal-control-Ringing-the-terminal-bell/Common-Lisp/terminal-control-ringing-the-terminal-bell.lisp new file mode 100644 index 0000000000..f831709a50 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Common-Lisp/terminal-control-ringing-the-terminal-bell.lisp @@ -0,0 +1 @@ +(format t "~C" (code-char 7)) diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/Julia/terminal-control-ringing-the-terminal-bell.julia b/Task/Terminal-control-Ringing-the-terminal-bell/Julia/terminal-control-ringing-the-terminal-bell.julia new file mode 100644 index 0000000000..fda92ff600 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/Julia/terminal-control-ringing-the-terminal-bell.julia @@ -0,0 +1 @@ +println("This should ring a bell.\a") diff --git a/Task/Terminal-control-Unicode-output/Common-Lisp/terminal-control-unicode-output.lisp b/Task/Terminal-control-Unicode-output/Common-Lisp/terminal-control-unicode-output.lisp new file mode 100644 index 0000000000..3aedd8497e --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Common-Lisp/terminal-control-unicode-output.lisp @@ -0,0 +1,19 @@ +(defun my-getenv (name &optional default) + #+CMU + (let ((x (assoc name ext:*environment-list* + :test #'string=))) + (if x (cdr x) default)) + #-CMU + (or + #+Allegro (sys:getenv name) + #+CLISP (ext:getenv name) + #+ECL (si:getenv name) + #+SBCL (sb-unix::posix-getenv name) + #+ABCL (getenv name) + #+LISPWORKS (lispworks:environment-variable name) + default)) + +(if (not ( null (remove-if #'null (mapcar #'my-getenv '("LANG" "LC_ALL" "LC_CTYPE"))))) + (format t "Unicode is supported on this terminal and U+25B3 is : ~a~&" (code-char #x25b3)) + (format t "Unicode is not supported on this terminal.~&") + ) diff --git a/Task/Terminal-control-Unicode-output/Julia/terminal-control-unicode-output.julia b/Task/Terminal-control-Unicode-output/Julia/terminal-control-unicode-output.julia new file mode 100644 index 0000000000..62eeeb51ca --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Julia/terminal-control-unicode-output.julia @@ -0,0 +1,7 @@ +c = '\u25b3' + +if ismatch(r"UTF", get(ENV, "LANG", "")) + println("This output device supports Unicode: ", c) +else + println("This output device does not support Unicode.") +end diff --git a/Task/Terminal-control-Unicode-output/Mercury/terminal-control-unicode-output.mercury b/Task/Terminal-control-Unicode-output/Mercury/terminal-control-unicode-output.mercury new file mode 100644 index 0000000000..6499ed0ff0 --- /dev/null +++ b/Task/Terminal-control-Unicode-output/Mercury/terminal-control-unicode-output.mercury @@ -0,0 +1,24 @@ +:- module unicode_output. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module list. +:- import_module maybe. +:- import_module string. + +main(!IO) :- + list.map_foldl(io.get_environment_var, ["LANG", "LC_ALL", "LC_CTYPE"], EnvValues, !IO), + ( if + list.member(EnvValue, EnvValues), + EnvValue = yes(Lang), + string.sub_string_search(Lang, "UTF-8", _) + then + io.write_string("Unicode is supported on this terminal and U+25B3 is : \u25b3\n", !IO) + else + io.write_string("Unicode is not supported on this terminal.\n", !IO) + ). diff --git a/Task/Ternary-logic/C++/ternary-logic.cpp b/Task/Ternary-logic/C++/ternary-logic.cpp new file mode 100644 index 0000000000..10fb8b9f1b --- /dev/null +++ b/Task/Ternary-logic/C++/ternary-logic.cpp @@ -0,0 +1,74 @@ +#include +#include + +class trit { +public: + static const trit False, Maybe, True; + + trit operator !() const { + return static_cast(-value); + } + + trit operator &&(const trit &b) const { + return (value < b.value) ? value : b.value; + } + + trit operator ||(const trit &b) const { + return (value > b.value) ? value : b.value; + } + + trit operator >>(const trit &b) const { + return -value > b.value ? static_cast(-value) : b.value; + } + + trit operator ==(const trit &b) const { + return static_cast(value * b.value); + } + + char chr() const { + return "F?T"[value + 1]; + } + +protected: + typedef enum { FALSE=-1, MAYBE, TRUE } Value; + + Value value; + + trit(const Value value) : value(value) { } +}; + +std::ostream& operator<<(std::ostream &os, const trit &t) +{ + os << t.chr(); + return os; +} + +const trit trit::False = trit(trit::FALSE); +const trit trit::Maybe = trit(trit::MAYBE); +const trit trit::True = trit(trit::TRUE); + +int main(int, char**) { + const trit trits[3] = { trit::True, trit::Maybe, trit::False }; + +#define for_each(name) \ + for (size_t name=0; name<3; ++name) + +#define show_op(op) \ + std::cout << std::endl << #op << " "; \ + for_each(a) std::cout << ' ' << trits[a]; \ + std::cout << std::endl << " -------"; \ + for_each(a) { \ + std::cout << std::endl << trits[a] << " |"; \ + for_each(b) std::cout << ' ' << (trits[a] op trits[b]); \ + } \ + std::cout << std::endl; + + std::cout << "! ----" << std::endl; + for_each(a) std::cout << trits[a] << " | " << !trits[a] << std::endl; + + show_op(&&); + show_op(||); + show_op(>>); + show_op(==); + return EXIT_SUCCESS; +} diff --git a/Task/Ternary-logic/PHP/ternary-logic.php b/Task/Ternary-logic/PHP/ternary-logic.php new file mode 100644 index 0000000000..8c418d775e --- /dev/null +++ b/Task/Ternary-logic/PHP/ternary-logic.php @@ -0,0 +1,61 @@ +#!/usr/bin/php +triTrue, triMaybe=>triMaybe, triTrue=>triFalse); + +# output helper +function triString ($tri) { + if ($tri===triFalse) return 'false '; + if ($tri===triMaybe) return 'unknown'; + if ($tri===triTrue) return 'true '; + trigger_error('triString: parameter not a tri value', E_USER_ERROR); +} + +function triAnd() { + if (func_num_args() < 2) + trigger_error('triAnd needs 2 or more parameters', E_USER_ERROR); + return min(func_get_args()); +} + +function triOr() { + if (func_num_args() < 2) + trigger_error('triOr needs 2 or more parameters', E_USER_ERROR); + return max(func_get_args()); +} + +function triNot($t) { + global $triNotarray; # using result table + if (in_array($t, $triNotarray)) return $triNotarray[$t]; + trigger_error('triNot: Parameter is not a tri value', E_USER_ERROR); +} + +function triImplies($a, $b) { + if ($a===triFalse || $b===triTrue) return triTrue; + if ($a===triMaybe || $b===triMaybe) return triMaybe; + # without parameter type check I just would return triFalse here + if ($a===triTrue && $b===triFalse) return triFalse; + trigger_error('triImplies: parameter type error', E_USER_ERROR); +} + +function triEquiv($a, $b) { + if ($a===triTrue) return $b; + if ($a===triMaybe) return $a; + if ($a===triFalse) return triNot($b); + trigger_error('triEquiv: parameter type error', E_USER_ERROR); +} + +# data sampling + +printf("--- Sample output for a equivalent b ---\n\n"); + +foreach ([triTrue,triMaybe,triFalse] as $a) { + foreach ([triTrue,triMaybe,triFalse] as $b) { + printf("for a=%s and b=%s a equivalent b is %s\n", + triString($a), triString($b), triString(triEquiv($a, $b))); + } +} diff --git a/Task/Ternary-logic/Perl-6/ternary-logic-1.pl6 b/Task/Ternary-logic/Perl-6/ternary-logic-1.pl6 index 7926aebd61..46d8839701 100644 --- a/Task/Ternary-logic/Perl-6/ternary-logic-1.pl6 +++ b/Task/Ternary-logic/Perl-6/ternary-logic-1.pl6 @@ -5,5 +5,5 @@ sub prefix:<¬> (Trit $a) { Trit(1-($a-1)) } sub infix:<∧> is equiv(&infix:<*>) (Trit $a, Trit $b) { $a min $b } sub infix:<∨> is equiv(&infix:<+>) (Trit $a, Trit $b) { $a max $b } -sub infix:<→> is equiv(&infix:<..>) (Trit $a, Trit $b) { ¬$a max $b } +sub infix:<⇒> is equiv(&infix:<..>) (Trit $a, Trit $b) { ¬$a max $b } sub infix:<≡> is equiv(&infix:) (Trit $a, Trit $b) { Trit(1 + ($a-1) * ($b-1)) } diff --git a/Task/Ternary-logic/Perl-6/ternary-logic-2.pl6 b/Task/Ternary-logic/Perl-6/ternary-logic-2.pl6 index 197cf8046f..298f94b080 100644 --- a/Task/Ternary-logic/Perl-6/ternary-logic-2.pl6 +++ b/Task/Ternary-logic/Perl-6/ternary-logic-2.pl6 @@ -14,7 +14,7 @@ sub tbl (&op,$name) { tbl(&infix:<∧>, '∧'); tbl(&infix:<∨>, '∨'); -tbl(&infix:<→>, '→'); +tbl(&infix:<⇒>, '⇒'); tbl(&infix:<≡>, '≡'); say ''; @@ -30,6 +30,6 @@ say ~( Too ∨ Too ∧ ¬Too ≡ Too, (Too ∨ Too) ∧ ¬Too ≡ ¬Too, - Foo ∧ Too ∨ Foo → Foo ≡ Too, - Foo ∧ Too ∨ Too → Foo ≡ Foo, + Foo ∧ Too ∨ Foo ⇒ Foo ≡ Too, + Foo ∧ Too ∨ Too ⇒ Foo ≡ Foo, ); diff --git a/Task/Test-a-function/00DESCRIPTION b/Task/Test-a-function/00DESCRIPTION index dcc74924ed..0be0e08803 100644 --- a/Task/Test-a-function/00DESCRIPTION +++ b/Task/Test-a-function/00DESCRIPTION @@ -1,2 +1,2 @@ {{omit from|BBC BASIC}} -Using a well known testing specific library/module/suite for your language, write some tests for your language's entry in [[Palindrome]]. If your language does not have a testing specific library well known to the language's community then state this or omit the language. +Using a well-known testing-specific library/module/suite for your language, write some tests for your language's entry in [[Palindrome]]. If your language does not have a testing specific library well known to the language's community then state this or omit the language. diff --git a/Task/Test-a-function/JavaScript/test-a-function.js b/Task/Test-a-function/JavaScript/test-a-function.js new file mode 100644 index 0000000000..26fab025ec --- /dev/null +++ b/Task/Test-a-function/JavaScript/test-a-function.js @@ -0,0 +1,24 @@ +const assert = require('assert'); + +describe('palindrome', () => { + const pali = require('../lib/palindrome'); + + describe('.check()', () => { + it('should return true on encountering a palindrome', () => { + assert.ok(pali.check('racecar')); + assert.ok(pali.check('abcba')); + assert.ok(pali.check('aa')); + assert.ok(pali.check('a')); + }); + + it('should return true on encountering an empty string', () => { + assert.ok(pali.check('')); + }); + + it('should return false on encountering a non-palindrome', () => { + assert.ok(!pali.check('alice')); + assert.ok(!pali.check('ab')); + assert.ok(!pali.check('abcdba')); + }); + }) +}); diff --git a/Task/Text-processing-1/00DESCRIPTION b/Task/Text-processing-1/00DESCRIPTION index c554e7775a..91240ea009 100644 --- a/Task/Text-processing-1/00DESCRIPTION +++ b/Task/Text-processing-1/00DESCRIPTION @@ -1,7 +1,7 @@ {{Template:clarify task}} Often data is produced by one program, in the wrong format for later use by another program or person. In these situations another program can be written to parse and transform the original data into a format useful to the other. The term "Data Munging" is [http://www.google.co.uk/search?q=%22data+munging%22 often] used in programming circles for this task. -A [http://groups.google.co.uk/group/comp.lang.awk/msg/0ecba3a3fbf247d8?hl=en request] on the comp.lang.awk newsgroup lead to a typical data munging task: +A [http://groups.google.co.uk/group/comp.lang.awk/msg/0ecba3a3fbf247d8?hl=en request] on the comp.lang.awk newsgroup led to a typical data munging task:
I have to analyse data files that have the following format:
 Each row corresponds to 1 day and the field logic is: $1 is the date,
 followed by 24 value/flag pairs, representing measurements at 01:00,
diff --git a/Task/Text-processing-1/Eiffel/text-processing-1.e b/Task/Text-processing-1/Eiffel/text-processing-1.e
new file mode 100644
index 0000000000..4effcc6679
--- /dev/null
+++ b/Task/Text-processing-1/Eiffel/text-processing-1.e
@@ -0,0 +1,119 @@
+class
+	APPLICATION
+
+create
+	make
+
+feature
+
+	make
+			-- Summary statistics for 'hash'.
+		local
+			reject, accept, reading_total: INTEGER
+			total, average, file_total: REAL
+		do
+			read_wordlist
+			across
+				hash as h
+			loop
+				io.put_string (h.key + "%T")
+				reject := 0
+				accept := 0
+				total := 0
+				across
+					h.item as data
+				loop
+					if data.item.flag > 0 then
+						accept := accept + 1
+						total := total + data.item.val
+					else
+						reject := reject + 1
+					end
+				end
+				file_total := file_total + total
+				reading_total := reading_total + accept
+				io.put_string ("accept: " + accept.out + "%Treject: " + reject.out + "%Ttotal: " + total.out + "%T")
+				average := total / accept.to_real
+				io.put_string ("average: " + average.out + "%N")
+			end
+			io.put_string ("File total: " + file_total.out + "%N")
+			io.put_string ("Readings total: " + reading_total.out + "%N")
+			find_longest_gap
+		end
+
+	find_longest_gap
+			-- Longest gap (flag values <= 0).
+		local
+			count: INTEGER
+			longest_gap: INTEGER
+			end_date: STRING
+		do
+			create end_date.make_empty
+			across
+				hash as h
+			loop
+				across
+					h.item as data
+				loop
+					if data.item.flag <= 0 then
+						count := count + 1
+					else
+						if count > longest_gap then
+							longest_gap := count
+							end_date := h.key
+						end
+						count := 0
+					end
+				end
+			end
+			io.put_string ("%NThe longest gap is " + longest_gap.out + ". It ends at the date stamp " + end_date + ". %N")
+		end
+
+	original_list: STRING = "readings.txt"
+
+	read_wordlist
+			-- Preprocessed wordlist in 'hash'.
+		local
+			l_file: PLAIN_TEXT_FILE
+			data: LIST [STRING]
+			by_dates: LIST [STRING]
+			date: STRING
+			data_tup: TUPLE [val: REAL; flag: INTEGER]
+			data_arr: ARRAY [TUPLE [val: REAL; flag: INTEGER]]
+			i: INTEGER
+		do
+			create l_file.make_open_read_write (original_list)
+			l_file.read_stream (l_file.count)
+			data := l_file.last_string.split ('%N')
+			l_file.close
+			create hash.make (data.count)
+			across
+				data as d
+			loop
+				if not d.item.is_empty then
+					by_dates := d.item.split ('%T')
+					date := by_dates [1]
+					by_dates.prune (date)
+					create data_tup
+					create data_arr.make_empty
+					from
+						i := 1
+					until
+						i > by_dates.count - 1
+					loop
+						data_tup := [by_dates [i].to_real, by_dates [i + 1].to_integer]
+						data_arr.force (data_tup, data_arr.count + 1)
+						i := i + 2
+					end
+					hash.put (data_arr, date)
+					if not hash.inserted then
+						date.append ("_double_date_stamp")
+						hash.put (data_arr, date)
+					end
+				end
+			end
+		end
+
+	hash: HASH_TABLE [ARRAY [TUPLE [val: REAL; flag: INTEGER]], STRING]
+
+end
diff --git a/Task/Text-processing-1/Fortran/text-processing-1.f b/Task/Text-processing-1/Fortran/text-processing-1.f
new file mode 100644
index 0000000000..f2605f7825
--- /dev/null
+++ b/Task/Text-processing-1/Fortran/text-processing-1.f
@@ -0,0 +1,92 @@
+Crunches a set of hourly data. Starts with a date, then 24 pairs of value,indicator for that day, on one line.
+      INTEGER Y,M,D		!Year, month, and day.
+      INTEGER GOOD(24)		!The indicators.
+      REAL*8 V(24),VTOT,T	!The grist.
+      INTEGER NV,N,NB		!Number of good values overall, and in a day.
+      INTEGER I,NREC,HIC	!Some counters.
+      INTEGER BI,BN,BBI,BBN	!Stuff to locate the longest run of bad data,
+      CHARACTER*10 BDATE,BBDATE	!Along with the starting date.
+      LOGICAL INGOOD		!State flipper for the runs of data.
+      INTEGER IN,MSG		!I/O mnemonics.
+      CHARACTER*666 ACARD	!Scratchpad, of sufficient length for all expectation.
+      IN = 10		!Unit number for the input file.
+      MSG = 6		!Output.
+      OPEN (IN,FILE="Readings1.txt", FORM="FORMATTED",	!This should be a function.
+     1 STATUS ="OLD",ACTION="READ")			!Returning success, or failure.
+      NB = 0		!No bad values read.
+      NV = 0		!Nor good values read.
+      VTOT = 0		!Their average is to come.
+      NREC = 0		!No records read.
+      HIC = 0		!Provoking no complaints.
+      INGOOD = .TRUE.	!I start in hope.
+      BBN = 0		!And the longest previous bad run is short.
+Chew into the file.
+   10 READ (IN,11,END=100,ERR=666) L,ACARD(1:MIN(L,LEN(ACARD)))	!With some protection.
+      NREC = NREC + 1		!So, a record has been read.
+   11 FORMAT (Q,A)		!Obviously, Q ascertains the length of the record being read.
+      READ (ACARD,12,END=600,ERR=601) Y,M,D	!The date part is trouble, as always.
+   12 FORMAT (I4,2(1X,I2))				!Because there are no delimiters between the parts.
+      READ (ACARD(11:L),*,END=600,ERR=601) (V(I),GOOD(I),I = 1,24)	!But after the date, delimiters abound.
+Calculations. Could use COUNT(array) and SUM(array), but each requires its own pass through the array.
+   20 T = 0		!Start on the day's statistics.
+      N = 0		!No values yet.
+      DO I = 1,24	!So, scan the cargo and do all the twiddling in one pass..
+        IF (GOOD(I).GT.0) THEN	!A good value?
+          N = N + 1		!Yes. Count it in.
+          T = T + V(I)		!And augment for the average.
+          IF (.NOT.INGOOD) THEN	!Had we been ungood?
+            INGOOD = .TRUE.	!Yes. But now it changes.
+            IF (BN.GT.BBN) THEN	!The run just ending: is it longer?
+              BBN = BN		!Yes. Make it the new baddest.
+              BBI = BI		!Recalling its start index,
+              BBDATE = BDATE	!And its start date.
+            END IF		!So much for bigger badness.
+          END IF		!Now we're in good data.
+         ELSE		!Otherwise, a bad value is upon us.
+          IF (INGOOD) THEN	!Were we good?
+            INGOOD = .FALSE.	!No longer. A new bad run is starting.
+            BDATE = ACARD(1:10)	!Recall the date for this starter.
+            BI = I		!And its index.
+            BN = 0		!Start the run-length counter.
+          END IF		!So much for a fall.
+          BN = BN + 1	!Count another bad value.
+        END IF		!Good or bad, so much for that value.
+      END DO		!On to the next.
+Commentary for the day's data..
+      IF (N.LE.0) THEN	!I prefer to avoid dividing by zero.
+        WRITE (MSG,21) NREC,ACARD(1:10)	!So, no average to report.
+   21   FORMAT ("Record",I8," (",A,") has no good data!")	!Just a remark.
+       ELSE			!But otherwise,
+        WRITE(MSG,22) NREC,ACARD(1:10),N,T/N	!An average is possible.
+   22   FORMAT("Record",I8," (",A,")",I3," good, average",F9.3)	!So here it is.
+        NB = NB + 24 - N	!Count the bad by implication.
+        NV = NV + N		!Count the good directly.
+        VTOT = VTOT + T		!Should really sum deviations from a working average.
+      END IF			!So much for that line.
+      GO TO 10		!More! More! I want more!!
+
+Complaints. Should really distinguish between trouble in the date part and in the data part.
+  600 WRITE (MSG,*) '"END" declared - insufficient data?'	!Not enough numbers, presumably.
+      GO TO 602				!Reveal the record.
+  601 WRITE (MSG,*) '"ERR" declared - improper number format?'	!Ah, but which number?
+  602 WRITE (MSG,603) NREC,L,ACARD(1:L)	!Anyway, reveal the uninterpreted record.
+  603 FORMAT(" Record ",I0,", length ",I0," reads ",A)	!Just so.
+      HIC = HIC + 1			!This may grow into a habit.
+      IF (HIC.LE.12) GO TO 10		!But if not yet, try the next record.
+      STOP "Enough distaste."		!Or, give up.
+  666 WRITE (MSG,101) NREC,"format error!"	!For A-style data? Should never happen!
+      GO TO 900				!But if it does, give up!
+
+Closedown.
+  100 WRITE (MSG,101) NREC,"then end-of-file"	!Discovered on the next attempt.
+  101 FORMAT (" Record ",I0,": ",A)		!A record number plus a remark.
+      WRITE (MSG,102) NV,NB,VTOT/NV		!The overall results.
+  102 FORMAT (I8," values, ",I0," bad. Average",F9.4)	!This should do.
+      IF (BBN.LE.0) THEN		!Now for a special report.
+        WRITE (MSG,*) "No bad value presented, so no longest run."	!Unneeded!
+       ELSE				!But actually, the example data has some bad values.
+        WRITE (MSG,103) BBN,BBI,BBDATE	!And this is for the longest encountered.
+  103   FORMAT ("Longest bad run: ",I0,", starting hour ",I0," on ",A)	!Just so.
+      END IF			!Enough remarks.
+  900 CLOSE(IN)		!Done.
+      END	!Spaghetti rules.
diff --git a/Task/Text-processing-1/REXX/text-processing-1.rexx b/Task/Text-processing-1/REXX/text-processing-1.rexx
index d96b5c6c49..2bdae8f3e1 100644
--- a/Task/Text-processing-1/REXX/text-processing-1.rexx
+++ b/Task/Text-processing-1/REXX/text-processing-1.rexx
@@ -1,72 +1,65 @@
-/*REXX program to process  instrument data  from a  data file.          */
-numeric digits 20                      /*allow for bigger numbers.      */
-ifid='READINGS.TXT'                    /*the  input  file.              */
-ofid='READINGS.OUT'                    /*the  outut  file.              */
-grandSum=0                             /*grand sum of whole file.       */
-grandflg=0                             /*grand num of flagged data.     */
+/*REXX program to process  instrument data  from a  data file.                */
+numeric digits 20                      /*allow for bigger (precision) numbers.*/
+ifid='READINGS.TXT'                    /*the name of the    input    file.    */
+ofid='READINGS.OUT'                    /* "    "   "  "     output     "      */
+grandSum=0                             /*the grand sum of whole file.         */
+grandFlg=0                             /*the grand number of flagged data.    */
 grandOKs=0
-longFlag=0                             /*longest period of flagged data.*/
-contFlag=0                             /*longest continous flagged data.*/
-w=16                                   /*width of fields when displayed.*/
+Lflag=0                                /*the longest period of flagged data.  */
+Cflag=0                                /*the longest continous flagged data.  */
+w=16                                   /*the width of fields when displayed.  */
 
-  do recs=1  while lines(ifid)\==0     /*read until finished.           */
-  rec=linein(ifid)                     /*read the next record (line).   */
-  parse var rec datestamp Idata        /*pick off the dateStamp & data. */
+  do recs=1  while lines(ifid)\==0     /*keep reading records until finished. */
+  rec=linein(ifid)                     /*read the next record (line) of file. */
+  parse var rec datestamp Idata        /*pick off the dateStamp and the data. */
   sum=0
   flg=0
   OKs=0
 
-    do j=1  until Idata=''             /*process the instrument data.  */
+    do j=1  until Idata=''             /*process the  instrument  data.       */
     parse var Idata data.j flag.j Idata
 
-    if flag.j>0 then do                /*if good data, ...              */
+    if flag.j>0 then do                /*process good data ···                */
                      OKs=OKs+1
                      sum=sum+data.j
-                     if contFlag>longFlag then do
-                                               longdate=datestamp
-                                               longFlag=contFlag
-                                               end
-                     contFlag=0
+                     if Cflag>Lflag  then do
+                                          Ldate=datestamp
+                                          Lflag=Cflag
+                                          end
+                     Cflag=0
                      end
-                else do                /*flagged data ...               */
+                else do                /*process flagged data ···             */
                      flg=flg+1
-                     contFlag=contFlag+1
+                     Cflag=Cflag+1
                      end
     end   /*j*/
 
-  if OKs\==0 then avg=format(sum/OKs,,3)
-             else avg='[n/a]'
+  if OKs\==0  then avg=format(sum/OKs,,3)
+              else avg='[n/a]'
   grandOKs=grandOKs+OKs
-  _=right(comma(avg),w)
+  _=right(commas(avg),w)
   grandSum=grandSum+sum
   grandFlg=grandFlg+flg
-  if flg==0 then call sy datestamp ' average='_
-            else call sy datestamp ' average='_ '  flagged='right(flg,2)
+  if flg==0  then call sy datestamp ' average='_
+             else call sy datestamp ' average='_ '  flagged='right(flg,2)
   end   /*recs*/
 
-recs=recs-1                            /*adjust for reading end-of-file.*/
-if grandOKs\==0 then Gavg=format(grandsum/grandOKs,,3)
+recs=recs-1                            /*adjust for reading the end─of─file.  */
+if grandOKs\==0 then Gavg=format(grandSum/grandOKs,,3)
                 else Gavg='[n/a]'
 call sy
 call sy copies('═',60)
-call sy '      records read:' right(comma(recs),w)
-call sy '     grand     sum:' right(comma(grandSum),w+4)
-call sy '     grand average:' right(comma(Gavg),w+4)
-call sy '     grand OK data:' right(comma(grandOKs),w)
-call sy '     grand flagged:' right(comma(grandFlg),w)
-if longFlag\==0 then
-call sy '   longest flagged:' right(comma(longFlag),w) " ending at " longdate
+call sy '      records read:'   right(commas(recs),     w)
+call sy '     grand     sum:'   right(commas(grandSum), w+4)
+call sy '     grand average:'   right(commas(Gavg),     w+4)
+call sy '     grand OK data:'   right(commas(grandOKs), w)
+call sy '     grand flagged:'   right(commas(grandFlg), w)
+if Lflag\==0 then call sy '   longest flagged:' right(commas(Lflag),w) " ending at " Ldate
 call sy copies('═',60)
-exit                                   /*stick a fork in it, we're done.*/
-/*──────────────────────────────────SY subroutine───────────────────────*/
-sy: procedure; parse arg stuff;   say stuff
-    if  1==0  then  call lineout ofid,stuff
-    return
-/*──────────────────────────────────COMMA subroutine────────────────────*/
-comma: procedure; parse arg _,c,p,t;arg ,cu;c=word(c ",",1)
-       if cu=='BLANK' then c=' ';o=word(p 3,1);p=abs(o);t=word(t 999999999,1)
-       if \datatype(p,'W')|\datatype(t,'W')|p==0|arg()>4 then return _;n=_'.9'
-       #=123456789;k=0;if o<0 then do;b=verify(_,' ');if b==0 then return _
-       e=length(_)-verify(reverse(_),' ')+1;end;else do;b=verify(n,#,"M")
-       e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1;end
-       do j=e to b by -p while k 0 ? (sum / good.size) : 0 end
+  def print_status
+    puts "%11s:  good: %2d  bad: %2d  total: %8.3f  avg: %6.3f" % [date, good.count, bad.count, sum, avg]
+    self
+  end
+end
+
+daily_readings = IO.foreach(ARGV.first).map do |line|
+  (date, *parts) = line.chomp.split(/\s/)
+  readings = parts.each_slice(2).map {|pair| Reading.new(date, pair.first.to_f, pair.last.to_i > 0)}
+  DailyReading.new(date, readings).print_status
+end
+
+all_readings = daily_readings.flat_map(&:readings)
+good_readings = all_readings.select(&:flag)
+all_streaks = all_readings.slice_when {|bef, aft| bef.flag != aft.flag }
+worst_streak = all_streaks.reject {|grp| grp.any?(&:flag)}.sort_by(&:size).last
+
+total = good_readings.map(&:value).reduce(:+)
+num_readings = good_readings.count
+puts
+puts "Total: %.3f" % total
+puts "Readings: #{num_readings}"
+puts "Average  %.3f" % total./(num_readings)
+puts
+puts "Max run of #{worst_streak.count} consecutive false readings from #{worst_streak.first.date} until #{worst_streak.last.date}"
diff --git a/Task/Text-processing-1/VBScript/text-processing-1.vb b/Task/Text-processing-1/VBScript/text-processing-1.vb
new file mode 100644
index 0000000000..1a004b7926
--- /dev/null
+++ b/Task/Text-processing-1/VBScript/text-processing-1.vb
@@ -0,0 +1,63 @@
+Set objFSO = CreateObject("Scripting.FileSystemObject")
+Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
+			"\data.txt",1)
+
+bad_readings_total = 0
+good_readings_total = 0
+data_gap = 0
+start_date = ""
+end_date = ""
+tmp_datax_gap = 0
+tmp_start_date = ""
+
+Do Until objFile.AtEndOfStream
+	bad_readings = 0
+	good_readings = 0
+	line_total = 0
+	line = objFile.ReadLine
+	token = Split(line,vbTab)
+	n = 1
+	Do While n <= UBound(token)
+		If n + 1 <= UBound(token) Then
+			If CInt(token(n+1)) < 1 Then
+				bad_readings = bad_readings + 1
+				bad_readings_total = bad_readings_total + 1
+				'Account for bad readings.
+				If tmp_start_date = "" Then
+					tmp_start_date = token(0)
+				End If
+				tmp_data_gap = tmp_data_gap + 1
+			Else
+				good_readings = good_readings + 1
+				line_total = line_total + CInt(token(n))
+				good_readings_total = good_readings_total + 1
+				'Sum up the bad readings.
+				If (tmp_start_date <> "") And (tmp_data_gap > data_gap) Then
+					start_date = tmp_start_date
+					end_date = token(0)
+					data_gap = tmp_data_gap
+					tmp_start_date = ""
+					tmp_data_gap = 0
+				Else
+					tmp_start_date = ""
+					tmp_data_gap = 0
+				End If
+			End If	
+		End If
+		n = n + 2
+	Loop
+	line_avg = line_total/good_readings
+	WScript.StdOut.Write "Date: " & token(0) & vbTab &_
+		"Bad Reads: " & bad_readings & vbTab &_
+		"Good Reads: " & good_readings & vbTab &_
+		"Line Total: " & FormatNumber(line_total,3) & vbTab &_
+		"Line Avg: " & FormatNumber(line_avg,3)
+	WScript.StdOut.WriteLine
+Loop
+WScript.StdOut.WriteLine
+WScript.StdOut.Write "Maximum run of " & data_gap &_
+	" consecutive bad readings from " & start_date & " to " &_
+	end_date & "."
+WScript.StdOut.WriteLine
+objFile.Close
+Set objFSO = Nothing
diff --git a/Task/Text-processing-2/00DESCRIPTION b/Task/Text-processing-2/00DESCRIPTION
index 40125f7251..9212d70bb7 100644
--- a/Task/Text-processing-2/00DESCRIPTION
+++ b/Task/Text-processing-2/00DESCRIPTION
@@ -1,12 +1,10 @@
-The following data shows a few lines from the file readings.txt (as used in the [[Data Munging]] task).
-
-The data comes from a pollution monitoring station with twenty four instruments monitoring twenty four aspects of pollution in the air. Periodically a record is added to the file constituting a line of 49 white-space separated fields, where white-space can be one or more space or tab characters.
+The following task concerns data that came from a pollution monitoring station with twenty-four instruments monitoring twenty-four aspects of pollution in the air. Periodically a record is added to the file, each record being a line of 49 fields separated by white-space, which can be one or more space or tab characters.
 
 The fields (from the left) are:
   DATESTAMP [ VALUEn FLAGn ] * 24
-i.e. a datestamp followed by twenty four repetitions of a floating point instrument value and that instruments associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with that instrument, in which case that instrument's value should be ignored.
+i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
 
-A sample from the full data file [http://rosettacode.org/resources/readings.zip readings.txt] is:
+A sample from the full data file [http://rosettacode.org/resources/readings.zip readings.txt], which is also used in the [[Data Munging]] task, follows:
 
 1991-03-30	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1
 1991-03-31	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	20.000	1	20.000	1	20.000	1	35.000	1	50.000	1	60.000	1	40.000	1	30.000	1	30.000	1	30.000	1	25.000	1	20.000	1	20.000	1	20.000	1	20.000	1	20.000	1	35.000	1
@@ -17,6 +15,6 @@ A sample from the full data file [http://rosettacode.org/resources/readings.zip
 
The task: -# Confirm the general field format of the file +# Confirm the general field format of the file. # Identify any DATESTAMPs that are duplicated. -# What number of records have good readings for all instruments. +# Report the number of records that have good readings for all instruments. diff --git a/Task/Text-processing-2/Eiffel/text-processing-2.e b/Task/Text-processing-2/Eiffel/text-processing-2.e new file mode 100644 index 0000000000..c7ae1df0ef --- /dev/null +++ b/Task/Text-processing-2/Eiffel/text-processing-2.e @@ -0,0 +1,115 @@ +class + APPLICATION + +create + make + +feature + + make + -- Finds double date stamps and wrong formats. + local + found: INTEGER + double: STRING + do + read_wordlist + fill_hash_table + across + hash as h + loop + if h.key.has_substring ("_double") then + io.put_string ("Double date stamp: %N") + double := h.key + double.remove_tail (7) + io.put_string (double) + io.new_line + end + if h.item.count /= 24 then + io.put_string (h.key.out + " has the wrong format. %N") + found := found + 1 + end + end + io.put_string (found.out + " records have not 24 readings.%N") + good_records + end + + good_records + -- Number of records that have flag values > 0 for all readings. + local + count, total: INTEGER + end_date: STRING + do + create end_date.make_empty + across + hash as h + loop + count := 0 + across + h.item as d + loop + if d.item.flag > 0 then + count := count + 1 + end + end + if count = 24 then + total := total + 1 + end + end + io.put_string ("%NGood records: " + total.out + ". %N") + end + + original_list: STRING = "readings.txt" + + read_wordlist + --Preprocesses data in 'data'. + local + l_file: PLAIN_TEXT_FILE + do + create l_file.make_open_read_write (original_list) + l_file.read_stream (l_file.count) + data := l_file.last_string.split ('%N') + l_file.close + end + + data: LIST [STRING] + + fill_hash_table + --Fills 'hash' using the date as key. + local + by_dates: LIST [STRING] + date: STRING + data_tup: TUPLE [val: REAL; flag: INTEGER] + data_arr: ARRAY [TUPLE [val: REAL; flag: INTEGER]] + i: INTEGER + do + create hash.make (data.count) + across + data as d + loop + if not d.item.is_empty then + by_dates := d.item.split ('%T') + date := by_dates [1] + by_dates.prune (date) + create data_tup + create data_arr.make_empty + from + i := 1 + until + i > by_dates.count - 1 + loop + data_tup := [by_dates [i].to_real, by_dates [i + 1].to_integer] + data_arr.force (data_tup, data_arr.count + 1) + i := i + 2 + end + hash.put (data_arr, date) + if not hash.inserted then + date.append ("_double") + hash.put (data_arr, date) + end + end + end + end + + hash: HASH_TABLE [ARRAY [TUPLE [val: REAL; flag: INTEGER]], STRING] + +end diff --git a/Task/Text-processing-2/Fortran/text-processing-2.f b/Task/Text-processing-2/Fortran/text-processing-2.f new file mode 100644 index 0000000000..12e8b9067b --- /dev/null +++ b/Task/Text-processing-2/Fortran/text-processing-2.f @@ -0,0 +1,62 @@ +Crunches a set of hourly data. Starts with a date, then 24 pairs of value,indicator for that day, on one line. + INTEGER Y,M,D !Year, month, and day. + INTEGER GOOD(24,2) !The indicators. + REAL*8 V(24,2) !The grist. + CHARACTER*10 DATE(2) !Along with the starting date. + INTEGER IT,TI !A flipper and its antiflipper. + INTEGER NV !Number of entirely good records. + INTEGER I,NREC,HIC !Some counters. + LOGICAL INGOOD !State flipper for the runs of data. + INTEGER IN,MSG !I/O mnemonics. + CHARACTER*666 ACARD !Scratchpad, of sufficient length for all expectation. + IN = 10 !Unit number for the input file. + MSG = 6 !Output. + OPEN (IN,FILE="Readings1.txt", FORM="FORMATTED", !This should be a function. + 1 STATUS ="OLD",ACTION="READ") !Returning success, or failure. + NV = 0 !No pure records seen. + NREC = 0 !No records read. + HIC = 0 !Provoking no complaints. + DATE = "snargle" !No date should look like this! + IT = 2 !Syncopation for the 1-2 flip flop. +Chew into the file. + 10 READ (IN,11,END=100,ERR=666) L,ACARD(1:MIN(L,LEN(ACARD))) !With some protection. + NREC = NREC + 1 !So, a record has been read. + 11 FORMAT (Q,A) !Obviously, Q ascertains the length of the record being read. + READ (ACARD,12,END=600,ERR=601) Y,M,D !The date part is trouble, as always. + 12 FORMAT (I4,2(1X,I2)) !Because there are no delimiters between the parts. + TI = IT !Thus finger the previous value. + IT = 3 - IT !Flip between 1 and 2. + DATE(IT) = ACARD(1:10) !Save the date field. + READ (ACARD(11:L),*,END=600,ERR=601) (V(I,IT),GOOD(I,IT),I = 1,24) !But after the date, delimiters abound. +Comparisons. Should really convert the date to a daynumber, check it by reversion, and then check for + 1 day only. + 20 IF (DATE(IT).EQ.DATE(TI)) THEN !Same date? + IF (ALL(V(:,IT) .EQ.V(:,TI)) .AND. !Yes. What about the data? + 1 ALL(GOOD(:,IT).EQ.GOOD(:,TI))) THEN !This disregards details of the spacing of the data. + WRITE (MSG,21) NREC,DATE(IT),"same." !Also trailing zeroes, spurious + signs, blah blah. + 21 FORMAT ("Record",I8," Duplicate date field (",A,"), data ",A) !Say it. + ELSE !But if they're not all equal, + WRITE (MSG,21) NREC,DATE(IT),"different!" !They're different! + END IF !So much for comparing the data. + END IF !So much for just comparing the date's text. + IF (ALL(GOOD(:,IT).GT.0)) NV = NV + 1 !A fully healthy record, either way? + GO TO 10 !More! More! I want more!! + +Complaints. Should really distinguish between trouble in the date part and in the data part. + 600 WRITE (MSG,*) '"END" declared - insufficient data?' !Not enough numbers, presumably. + GO TO 602 !Reveal the record. + 601 WRITE (MSG,*) '"ERR" declared - improper number format?' !Ah, but which number? + 602 WRITE (MSG,603) NREC,L,ACARD(1:L) !Anyway, reveal the uninterpreted record. + 603 FORMAT("Record",I8,", length ",I0," reads ",A) !Just so. + HIC = HIC + 1 !This may grow into a habit. + IF (HIC.LE.12) GO TO 10 !But if not yet, try the next record. + STOP "Enough distaste." !Or, give up. + 666 WRITE (MSG,101) NREC,"format error!" !For A-style data? Should never happen! + GO TO 900 !But if it does, give up! + +Closedown. + 100 WRITE (MSG,101) NREC,"then end-of-file" !Discovered on the next attempt. + 101 FORMAT ("Record",I8,": ",A) !A record number plus a remark. + WRITE (MSG,102) NV !The overall results. + 102 FORMAT (" with",I8," having all values good.") !This should do. + 900 CLOSE(IN) !Done. + END !Spaghetti rules. diff --git a/Task/Text-processing-2/REXX/text-processing-2.rexx b/Task/Text-processing-2/REXX/text-processing-2.rexx index b3bb62b853..b273cb2c14 100644 --- a/Task/Text-processing-2/REXX/text-processing-2.rexx +++ b/Task/Text-processing-2/REXX/text-processing-2.rexx @@ -1,43 +1,43 @@ -/*REXX program to process instrument data from a data file. */ -numeric digits 20 /*allow for bigger numbers. */ -ifid='READINGS.TXT' /*the input file. */ -ofid='READINGS.OUT' /*the outut file. */ -grandSum=0 /*grand sum of whole file. */ -grandflg=0 /*grand num of flagged data. */ +/*REXX program to process instrument data from a data file. */ +numeric digits 20 /*allow for bigger numbers. */ +ifid='READINGS.TXT' /*name of the input file. */ +ofid='READINGS.OUT' /* " " " output " */ +grandSum=0 /*grand sum of the whole file. */ +grandFlg=0 /*grand number of flagged data. */ grandOKs=0 -longFlag=0 /*longest period of flagged data.*/ -contFlag=0 /*longest continous flagged data.*/ -oldDate =0 /*placeholder of penutilmate date*/ -w =16 /*width of fields when displayed.*/ -dupDates=0 /*count of duplicated timestamps.*/ -badflags=0 /*count of bad flags (¬ integer).*/ -badDates=0 /*count of bad dates (bad format)*/ -badData =0 /*count of bad datas (¬ numeric).*/ -ignoredR=0 /*count of ignored records (bad).*/ -maxInstruments=24 /*maximum number of instruments. */ -yyyyCurr=right(date(),4) /*get the current year (today). */ -monDD. =31 /*number of days in every month. */ - /*February is figured on the fly.*/ +Lflag=0 /*longest period of flagged data. */ +Cflag=0 /*longest continuous flagged data. */ +oldDate =0 /*placeholder of penultimate date. */ +w =16 /*width of fields when displayed. */ +dupDates=0 /*count of duplicated timestamps. */ +badFlags=0 /*count of bad flags (not integer). */ +badDates=0 /*count of bad dates (bad format). */ +badData =0 /*count of bad data (not numeric). */ +ignoredR=0 /*count of ignored records, bad records*/ +maxInstruments=24 /*maximum number of instruments. */ +yyyyCurr=right(date(),4) /*get the current year (today). */ +monDD. =31 /*number of days in every month. */ + /*# days in Feb. is figured on the fly.*/ monDD.4 =30 monDD.6 =30 monDD.9 =30 monDD.11=30 - do records=1 while lines(ifid)\==0 /*read until finished. */ - rec=linein(ifid) /*read the next record (line). */ - parse var rec datestamp Idata /*pick off the dateStamp & data. */ - if datestamp==oldDate then do /*found a duplicate timestamp. */ - dupDates=dupDates+1 /*bump the counter.*/ - call sy datestamp copies('~',30), - 'is a duplicate of the', - "previous datestamp." - ignoredR=ignoredR+1 /*bump ignoredRecs.*/ - iterate /*ignore this duplicate record. */ - end + do records=1 while lines(ifid)\==0 /*read until finished. */ + rec=linein(ifid) /*read the next record (line). */ + parse var rec datestamp Idata /*pick off the the dateStamp and data. */ + if datestamp==oldDate then do /*found a duplicate timestamp. */ + dupDates=dupDates+1 /*bump the dupDate counter*/ + call sy datestamp copies('~',30), + 'is a duplicate of the', + "previous datestamp." + ignoredR=ignoredR+1 /*bump # of ignoredRecs.*/ + iterate /*ignore this duplicate record. */ + end - parse var datestamp yyyy '-' mm '-' dd /*obtain YYYY, MM, and DD. */ - monDD.2=28+leapyear(yyyy) /*how long is February in YYYY ? */ - /*check for various bad formats. */ + parse var datestamp yyyy '-' mm '-' dd /*obtain YYYY, MM, and the DD. */ + monDD.2=28+leapyear(yyyy) /*how long is February in year YYYY ? */ + /*check for various bad formats. */ if verify(yyyy||mm||dd,1234567890)\==0 |, length(datestamp)\==10 |, length(yyyy)\==4 |, @@ -45,104 +45,96 @@ monDD.11=30 length(dd )\==2 |, yyyy<1970 |, yyyy>yyyyCurr |, - mm=0 | dd=0 |, - mm>12 | dd>monDD.mm then do + mm=0 | dd=0 |, + mm>12 | dd>monDD.mm then do badDates=badDates+1 call sy datestamp copies('~'), 'has an illegal format.' - ignoredR=ignoredR+1 /*bump ignoredRecs.*/ - iterate /*ignore this bad date record. */ + ignoredR=ignoredR+1 /*bump number ignoredRecs.*/ + iterate /*ignore this bad record. */ end - oldDate=datestamp /*save datestamp for next read. */ + oldDate=datestamp /*save datestamp for the next read. */ sum=0 flg=0 OKs=0 - do j=1 until Idata='' /*process the instrument data. */ + do j=1 until Idata='' /*process the instrument data. */ parse var Idata data.j flag.j Idata - if pos('.',flag.j)\==0 |, /*flag have a decimal point -or-*/ - \datatype(flag.j,'W') then do /*is the flag not a whole number?*/ - badflags=badflags+1 /*bump counter.*/ - call sy datestamp copies('~'), - 'instrument' j "has a bad flag:", - flag.j - iterate /*ignore it & it's data.*/ - end + if pos('.',flag.j)\==0 |, /*does flag have a decimal point -or- */ + \datatype(flag.j,'W') then do /* ··· is the flag not a whole number? */ + badFlags=badFlags+1 /*bump badFlags counter*/ + call sy datestamp copies('~'), + 'instrument' j "has a bad flag:", + flag.j + iterate /*ignore it and it's data. */ + end - if \datatype(data.j,'N') then do /*is the flag not a whole number?*/ - badData=badData+1 /*bump counter.*/ - call sy datestamp copies('~'), - 'instrument' j "has bad data:", - data.j - iterate /*ignore it & it's flag.*/ - end + if \datatype(data.j,'N') then do /*is the flag not a whole number?*/ + badData=badData+1 /*bump counter.*/ + call sy datestamp copies('~'), + 'instrument' j "has bad data:", + data.j + iterate /*ignore it & it's flag.*/ + end - if flag.j>0 then do /*if good data, ... */ - OKs=OKs+1 - sum=sum+data.j - if contFlag>longFlag then do - longdate=datestamp - longFlag=contFlag - end - contFlag=0 - end - else do /*flagged data ... */ - flg=flg+1 - contFlag=contFlag+1 - end + if flag.j>0 then do /*if good data, ~~~ */ + OKs=OKs+1 + sum=sum+data.j + if Cflag>Lflag then do + Ldate=datestamp + Lflag=Cflag + end + Cflag=0 + end + else do /*flagged data ~~~ */ + flg=flg+1 + Cflag=Cflag+1 + end end /*j*/ if j>maxInstruments then do - badData=badData+1 /*bump counter.*/ + badData=badData+1 /*bump the badData counter.*/ call sy datestamp copies('~'), 'too many instrument datum' end - if OKs\==0 then avg=format(sum/OKs,,3) - else avg='[n/a]' + if OKs\==0 then avg=format(sum/OKs,,3) + else avg='[n/a]' grandOKs=grandOKs+OKs - _=right(comma(avg),w) + _=right(commas(avg),w) grandSum=grandSum+sum grandFlg=grandFlg+flg if flg==0 then call sy datestamp ' average='_ else call sy datestamp ' average='_ ' flagged='right(flg,2) end /*records*/ -records=records-1 /*adjust for reading end-of-file.*/ -if grandOKs\==0 then grandAvg=format(grandsum/grandOKs,,3) - else grandAvg='[n/a]' +records=records-1 /*adjust for reading the end─of─file. */ +if grandOKs\==0 then grandAvg=format(grandsum/grandOKs,,3) + else grandAvg='[n/a]' call sy call sy copies('=',60) -call sy ' records read:' right(comma(records ),w) -call sy ' records ignored:' right(comma(ignoredR),w) -call sy ' grand sum:' right(comma(grandSum),w+4) -call sy ' grand average:' right(comma(grandAvg),w+4) -call sy ' grand OK data:' right(comma(grandOKs),w) -call sy ' grand flagged:' right(comma(grandFlg),w) -call sy ' duplicate dates:' right(comma(dupDates),w) -call sy ' bad dates:' right(comma(badDates),w) -call sy ' bad data:' right(comma(badData ),w) -call sy ' bad flags:' right(comma(badflags),w) -if longFlag\==0 then -call sy ' longest flagged:' right(comma(longFlag),w) " ending at " longdate +call sy ' records read:' right(commas(records ),w) +call sy ' records ignored:' right(commas(ignoredR),w) +call sy ' grand sum:' right(commas(grandSum),w+4) +call sy ' grand average:' right(commas(grandAvg),w+4) +call sy ' grand OK data:' right(commas(grandOKs),w) +call sy ' grand flagged:' right(commas(grandFlg),w) +call sy ' duplicate dates:' right(commas(dupDates),w) +call sy ' bad dates:' right(commas(badDates),w) +call sy ' bad data:' right(commas(badData ),w) +call sy ' bad flags:' right(commas(badFlags),w) +if Lflag\==0 then call sy ' longest flagged:' right(commas(LFlag),w) " ending at " Ldate call sy copies('=',60) -call sy -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────LEAPYEAR subroutine─────────────────*/ -leapyear: procedure; arg y /*year could be: Y, YY, YYY, YYYY*/ -if length(y)==2 then y=left(right(date(),4),2)y /*adjust for YY year.*/ -if y//4\==0 then return 0 /* not ≈ by 4? Not a leapyear.*/ -return y//100\==0 | y//400==0 /*apply 100 and 400 year rule. */ -/*──────────────────────────────────SY subroutine───────────────────────*/ -sy: procedure; parse arg stuff; say stuff - if 1==0 then call lineout ofid,stuff - return -/*──────────────────────────────────COMMA subroutine────────────────────*/ -comma: procedure; parse arg _,c,p,t;arg ,cu;c=word(c ",",1) - if cu=='BLANK' then c=' ';o=word(p 3,1);p=abs(o);t=word(t 999999999,1) - if \datatype(p,'W')|\datatype(t,'W')|p==0|arg()>4 then return _;n=_'.9' - #=123456789;k=0;if o<0 then do;b=verify(_,' ');if b==0 then return _ - e=length(_)-verify(reverse(_),' ')+1;end;else do;b=verify(n,#,"M") - e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1;end - do j=e to b by -p while k "" Then + token = Split(line,vbTab) + If objDateStamp.Exists(token(0)) = False Then + objDateStamp.Add token(0),"" + Total_Records = Total_Records + 1 + If IsValid(token) Then + Valid_Records = Valid_Records + 1 + End If + Else + Duplicate_TimeStamps = Duplicate_TimeStamps & token(0) & vbCrLf + Total_Records = Total_Records + 1 + End If + End If +Loop + +Function IsValid(arr) + IsValid = True + Bad_Readings = 0 + n = 1 + Do While n <= UBound(arr) + If n + 1 <= UBound(arr) Then + If CInt(arr(n+1)) < 1 Then + Bad_Readings = Bad_Readings + 1 + End If + End If + n = n + 2 + Loop + If Bad_Readings > 0 Then + IsValid = False + End If +End Function + +WScript.StdOut.Write "Total Number of Records = " & Total_Records +WScript.StdOut.WriteLine +WScript.StdOut.Write "Total Valid Records = " & Valid_Records +WScript.StdOut.WriteLine +WScript.StdOut.Write "Duplicate Timestamps:" +WScript.StdOut.WriteLine +WScript.StdOut.Write Duplicate_TimeStamps +WScript.StdOut.WriteLine + +objFile.Close +Set objFSO = Nothing diff --git a/Task/Text-processing-Max-licenses-in-use/Eiffel/text-processing-max-licenses-in-use.e b/Task/Text-processing-Max-licenses-in-use/Eiffel/text-processing-max-licenses-in-use.e new file mode 100644 index 0000000000..ed88278559 --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Eiffel/text-processing-max-licenses-in-use.e @@ -0,0 +1,53 @@ +class + APPLICATION + +create + make + +feature + + make + -- Max Licences used. + local + count: INTEGER + max_count: INTEGER + date: STRING + do + read_list + create date.make_empty + across + data as d + loop + if d.item.has_substring ("OUT") then + count := count + 1 + if count > max_count then + max_count := count + date := d.item + end + elseif d.item.has_substring ("IN") then + count := count - 1 + end + end + io.put_string ("Max Licences OUT: " + max_count.out) + io.new_line + io.put_string ("Date: " + date.substring (15, 33)) + end + + original_list: STRING = "mlijobs.txt" + +feature {NONE} + + read_list + -- Data read into 'data. + local + l_file: PLAIN_TEXT_FILE + do + create l_file.make_open_read_write (original_list) + l_file.read_stream (l_file.count) + data := l_file.last_string.split ('%N') + l_file.close + end + + data: LIST [STRING] + +end diff --git a/Task/Textonyms/C++/textonyms.cpp b/Task/Textonyms/C++/textonyms.cpp new file mode 100644 index 0000000000..9ba7811459 --- /dev/null +++ b/Task/Textonyms/C++/textonyms.cpp @@ -0,0 +1,120 @@ +#include +#include +#include +#include + +struct Textonym_Checker { +private: + int total; + int elements; + int textonyms; + int max_found; + std::vector max_strings; + std::unordered_map> values; + + int get_mapping(std::string &result, const std::string &input) + { + static std::unordered_map mapping = { + {'A', '2'}, {'B', '2'}, {'C', '2'}, + {'D', '3'}, {'E', '3'}, {'F', '3'}, + {'G', '4'}, {'H', '4'}, {'I', '4'}, + {'J', '5'}, {'K', '5'}, {'L', '5'}, + {'M', '6'}, {'N', '6'}, {'O', '6'}, + {'P', '7'}, {'Q', '7'}, {'R', '7'}, {'S', '7'}, + {'T', '8'}, {'U', '8'}, {'V', '8'}, + {'W', '9'}, {'X', '9'}, {'Y', '9'}, {'Z', '9'} + }; + + result = input; + for (char &c : result) { + if (!isalnum(c)) return 0; + if (isalpha(c)) c = mapping[toupper(c)]; + } + + return 1; + } + +public: + Textonym_Checker(void) : total(0), elements(0), textonyms(0), max_found(0) { } + + ~Textonym_Checker(void) { } + + void add(const std::string &str) { + std::string mapping; + total += 1; + + if (!get_mapping(mapping, str)) return; + + const int num_strings = values[mapping].size(); + + textonyms += num_strings == 1 ? 1 : 0; + elements += 1; + + if (num_strings > max_found) { + max_strings.clear(); + max_strings.push_back(mapping); + max_found = num_strings; + } + else if (num_strings == max_found) { + max_strings.push_back(mapping); + } + + values[mapping].push_back(str); + } + + void results(const std::string &filename) { + std::cout << "Read " << total << " words from " << filename << "\n\n"; + + std::cout << "There are " << elements << " words in " << filename; + std::cout << " which can be represented by the digit key mapping.\n"; + std::cout << "They require " << values.size() << + " digit combinations to represent them.\n"; + std::cout << textonyms << " digit combinations represent Textonyms.\n\n"; + std::cout << "The numbers mapping to the most words map to "; + std::cout << max_found + 1 << " words each:\n"; + + for (auto it1 = max_strings.begin(); it1 != max_strings.end(); ++it1) { + std::cout << '\t' << *it1 << " maps to: "; + for (auto it2 = values[*it1].begin(); it2 != values[*it1].end(); ++it2) { + std::cout << *it2 << " "; + } + std::cout << "\n"; + } + std::cout << '\n'; + } + + void match(const std::string &str) { + auto match = values.find(str); + + if (match == values.end()) { + std::cout << "Key '" << str << "' not found\n"; + } + else { + std::cout << "Key '" << str << "' matches: "; + for (auto it = values[str].begin(); it != values[str].end(); ++it) + std::cout << *it << " "; + std::cout << '\n'; + } + } +}; + +int main(void) +{ + std::string filename = "unixdict.txt"; + std::ifstream input(filename); + Textonym_Checker tc; + + if (input.is_open()) { + std::string line; + while (getline(input, line)) + tc.add(line); + } + + input.close(); + + tc.results(filename); + tc.match("001"); + tc.match("228"); + tc.match("27484247"); + tc.match("7244967473642"); +} diff --git a/Task/Textonyms/D/textonyms.d b/Task/Textonyms/D/textonyms.d new file mode 100644 index 0000000000..a17654c968 --- /dev/null +++ b/Task/Textonyms/D/textonyms.d @@ -0,0 +1,27 @@ +void main() { + import std.stdio, std.string, std.range, std.algorithm, std.ascii; + + immutable src = "unixdict.txt"; + const words = src.File.byLineCopy.map!strip.filter!(w => w.all!isAlpha).array; + + immutable table = makeTrans("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", + "2223334445556667777888999922233344455566677778889999"); + + string[][string] dials; + foreach (const word; words) + dials[word.translate(table)] ~= word; + + auto textonyms = dials.byPair.filter!(p => p[1].length > 1).array; + + writefln("There are %d words in %s which can be represented by the digit key mapping.", words.length, src); + writefln("They require %d digit combinations to represent them.", dials.length); + writefln("%d digit combinations represent Textonyms.", textonyms.length); + + "\nTop 5 in ambiguity:".writeln; + foreach (p; textonyms.schwartzSort!(p => -p[1].length).take(5)) + writefln(" %s => %-(%s %)", p[]); + + "\nTop 5 in length:".writeln; + foreach (p; textonyms.schwartzSort!(p => -p[0].length).take(5)) + writefln(" %s => %-(%s %)", p[]); +} diff --git a/Task/Textonyms/Haskell/textonyms.hs b/Task/Textonyms/Haskell/textonyms.hs new file mode 100644 index 0000000000..330b851d6e --- /dev/null +++ b/Task/Textonyms/Haskell/textonyms.hs @@ -0,0 +1,48 @@ +import Data.Maybe (isJust, isNothing, fromMaybe) +import Data.Char (toUpper) +import Data.List (sortBy, groupBy) +import Data.Function (on) + +toKey :: Char -> Maybe Char +toKey ch + | ch < 'A' = Nothing + | ch < 'D' = Just '2' + | ch < 'G' = Just '3' + | ch < 'J' = Just '4' + | ch < 'M' = Just '5' + | ch < 'P' = Just '6' + | ch < 'T' = Just '7' + | ch < 'W' = Just '8' + | ch <= 'Z' = Just '9' + | otherwise = Nothing + +toKeyString :: String -> Maybe String +toKeyString st = + let mch = map (toKey.toUpper) st + in if any isNothing mch then Nothing + else Just $ map (fromMaybe '!') mch + +showTextonym :: [(String,String)] -> IO () +showTextonym ts = do + let keyCode = fst $ head ts + putStrLn $ keyCode ++ " => " ++ concat [w ++ " " | (_,w) <- ts ] + +main :: IO() +main = do + let src = "unixdict.txt" + contents <- readFile src + + let wordList = lines contents + keyedList = [(key, word) | (Just key, word) <- filter (isJust.fst) $ zip (map toKeyString wordList) wordList] + groupedList = groupBy ((==) `on` fst) $ sortBy (compare `on` fst) keyedList + textonymList = filter ((>1) . length) groupedList + + putStrLn $ "There are " ++ show (length keyedList) ++ " words in " ++ src ++ " which can be represented by the digit key mapping." + putStrLn $ "They require " ++ show (length groupedList) ++ " digit combinations to represent them." + putStrLn $ show (length textonymList) ++ " digit combinations represent Textonyms." + putStrLn "" + putStrLn "Top 5 in ambiguity:" + mapM_ showTextonym $ take 5 $ sortBy (flip compare `on` length) textonymList + putStrLn "" + putStrLn "Top 5 in length:" + mapM_ showTextonym $ take 5 $ sortBy (flip compare `on` (length.fst.head)) textonymList diff --git a/Task/Textonyms/Java/textonyms.java b/Task/Textonyms/Java/textonyms.java new file mode 100644 index 0000000000..f16070f9c5 --- /dev/null +++ b/Task/Textonyms/Java/textonyms.java @@ -0,0 +1,162 @@ +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Scanner; +import java.util.Vector; + +public class RTextonyms { + + private static final Map mapping; + private int total, elements, textonyms, max_found; + private String filename, mappingResult; + private Vector max_strings; + private Map> values; + + static { + mapping = new HashMap(); + mapping.put('A', '2'); mapping.put('B', '2'); mapping.put('C', '2'); + mapping.put('D', '3'); mapping.put('E', '3'); mapping.put('F', '3'); + mapping.put('G', '4'); mapping.put('H', '4'); mapping.put('I', '4'); + mapping.put('J', '5'); mapping.put('K', '5'); mapping.put('L', '5'); + mapping.put('M', '6'); mapping.put('N', '6'); mapping.put('O', '6'); + mapping.put('P', '7'); mapping.put('Q', '7'); mapping.put('R', '7'); mapping.put('S', '7'); + mapping.put('T', '8'); mapping.put('U', '8'); mapping.put('V', '8'); + mapping.put('W', '9'); mapping.put('X', '9'); mapping.put('Y', '9'); mapping.put('Z', '9'); + } + + public RTextonyms(String filename) { + + this.filename = filename; + this.total = this.elements = this.textonyms = this.max_found = 0; + this.values = new HashMap>(); + this.max_strings = new Vector(); + + return; + } + + public void add(String line) { + + String mapping = ""; + total++; + if (!get_mapping(line)) { + return; + } + mapping = mappingResult; + + if (values.get(mapping) == null) { + values.put(mapping, new Vector()); + } + + int num_strings; + num_strings = values.get(mapping).size(); + textonyms += num_strings == 1 ? 1 : 0; + elements++; + + if (num_strings > max_found) { + max_strings.clear(); + max_strings.add(mapping); + max_found = num_strings; + } + else if (num_strings == max_found) { + max_strings.add(mapping); + } + + values.get(mapping).add(line); + + return; + } + + public void results() { + + System.out.printf("Read %,d words from %s%n%n", total, filename); + System.out.printf("There are %,d words in %s which can be represented by the digit key mapping.%n", elements, + filename); + System.out.printf("They require %,d digit combinations to represent them.%n", values.size()); + System.out.printf("%,d digit combinations represent Textonyms.%n", textonyms); + System.out.printf("The numbers mapping to the most words map to %,d words each:%n", max_found + 1); + for (String key : max_strings) { + System.out.printf("%16s maps to: %s%n", key, values.get(key).toString()); + } + System.out.println(); + + return; + } + + public void match(String key) { + + Vector match; + match = values.get(key); + if (match == null) { + System.out.printf("Key %s not found%n", key); + } + else { + System.out.printf("Key %s matches: %s%n", key, match.toString()); + } + + return; + } + + private boolean get_mapping(String line) { + + mappingResult = line; + StringBuilder mappingBuilder = new StringBuilder(); + for (char cc : line.toCharArray()) { + if (Character.isAlphabetic(cc)) { + mappingBuilder.append(mapping.get(Character.toUpperCase(cc))); + } + else if (Character.isDigit(cc)) { + mappingBuilder.append(cc); + } + else { + return false; + } + } + mappingResult = mappingBuilder.toString(); + + return true; + } + + public static void main(String[] args) { + + String filename; + if (args.length > 0) { + filename = args[0]; + } + else { + filename = "./unixdict.txt"; + } + RTextonyms tc; + tc = new RTextonyms(filename); + Path fp = Paths.get(filename); + try (Scanner fs = new Scanner(fp, StandardCharsets.UTF_8.name())) { + while (fs.hasNextLine()) { + tc.add(fs.nextLine()); + } + } + catch (IOException ex) { + ex.printStackTrace(); + } + + List numbers = Arrays.asList( + "001", "228", "27484247", "7244967473642", + "." + ); + + tc.results(); + for (String number : numbers) { + if (number.equals(".")) { + System.out.println(); + } + else { + tc.match(number); + } + } + + return; + } +} diff --git a/Task/Textonyms/Julia/textonyms-1.julia b/Task/Textonyms/Julia/textonyms-1.julia new file mode 100644 index 0000000000..3a665aeb25 --- /dev/null +++ b/Task/Textonyms/Julia/textonyms-1.julia @@ -0,0 +1,22 @@ +const tcode = (Regex=>Char)[r"A|B|C|Ä|Å|Á|Â|Ç" => '2', + r"D|E|F|È|Ê|É" => '3', + r"G|H|I|Í" => '4', + r"J|K|L" => '5', + r"M|N|O|Ó|Ö|Ô|Ñ" => '6', + r"P|Q|R|S" => '7', + r"T|U|V|Û|Ü" => '8', + r"W|X|Y|Z" => '9'] + +function tpad(str::IOStream) + tnym = (String=>Array{String,1})[] + for w in eachline(str) + w = chomp(w) + t = uppercase(w) + for (k,v) in tcode + t = replace(t, k, v) + end + t = replace(t, r"\D", '1') + tnym[t] = [get(tnym, t, String[]), w] + end + return tnym +end diff --git a/Task/Textonyms/Julia/textonyms-2.julia b/Task/Textonyms/Julia/textonyms-2.julia new file mode 100644 index 0000000000..c4d77ab07f --- /dev/null +++ b/Task/Textonyms/Julia/textonyms-2.julia @@ -0,0 +1,39 @@ +dname = "/usr/share/dict/american-english" +DF = open(dname, "r") +tnym = tpad(DF) +close(DF) + +println("The character to digit mapping is done according to") +println("these regular expressions (following uppercase conversion):") +for k in sort(collect(keys(tcode)), by=x->tcode[x]) + println(" ", tcode[k], " -> ", k) +end +println("Unmatched non-digit characters are mapped to 1") + +println() +print("There are ", sum(map(x->length(x), values(tnym)))) +println(" words in ", dname) +println(" which can be represented by the digit key mapping.") +print("They require ", length(keys(tnym))) +println(" digit combinations to represent them.") +print(sum(map(x->length(x)>1, values(tnym)))) +println(" digit combinations represent Textonyms.") + +println() +println("The degeneracies of telephone key encodings are:") +println(" Words Encoded Number of codes") +dgen = zeros(maximum(map(x->length(x), values(tnym)))) +for v in values(tnym) + dgen[length(v)] += 1 +end +for (i, d) in enumerate(dgen) + println(@sprintf "%10d %15d" i d) +end + +println() +dgen = length(dgen) - 2 +println("Codes mapping to ", dgen, " or more words:") +for (k, v) in tnym + dgen <= length(v) || continue + println(@sprintf "%7s (%2d) %s" k length(v) join(v, ", ")) +end diff --git a/Task/Textonyms/Racket/textonyms.rkt b/Task/Textonyms/Racket/textonyms.rkt new file mode 100644 index 0000000000..a83154190c --- /dev/null +++ b/Task/Textonyms/Racket/textonyms.rkt @@ -0,0 +1,81 @@ +#lang racket +(module+ test (require tests/eli-tester)) +(module+ test + (test + (map char->sms-digit (string->list "ABCDEFGHIJKLMNOPQRSTUVWXYZ.")) + => (list 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 7 8 8 8 9 9 9 9 #f))) + +(define char->sms-digit + (match-lambda + [(? char-lower-case? (app char-upcase C)) (char->sms-digit C)] + ;; Digits, too, can be entered on a text pad! + [(? char-numeric? (app char->integer c)) (- c (char->integer #\0))] + [(or #\A #\B #\C) 2] + [(or #\D #\E #\F) 3] + [(or #\G #\H #\I) 4] + [(or #\J #\K #\L) 5] + [(or #\M #\N #\O) 6] + [(or #\P #\Q #\R #\S) 7] + [(or #\T #\U #\V) 8] + [(or #\W #\X #\Y #\Z) 9] + [_ #f])) + +(module+ test + (test + (word->textonym "criticisms") => 2748424767 + (word->textonym "Briticisms") => 2748424767 + (= (word->textonym "Briticisms") (word->textonym "criticisms")))) + +(define (word->textonym w) + (for/fold ((n 0)) ((s (sequence-map char->sms-digit (in-string w))) #:final (not s)) + (and s (+ (* n 10) s)))) + +(module+ test + (test + ((cons-uniquely 'a) null) => '(a) + ((cons-uniquely 'a) '(b)) => '(a b) + ((cons-uniquely 'a) '(a b c)) => '(a b c))) + +(define ((cons-uniquely a) d) + (if (member a d) d (cons a d))) + +(module+ test + (test + (with-input-from-string "criticisms" port->textonym#) => + (values 1 (hash 2748424767 '("criticisms"))) + (with-input-from-string "criticisms\nBriticisms" port->textonym#) => + (values 2 (hash 2748424767 '("Briticisms" "criticisms"))) + (with-input-from-string "oh-no!-dashes" port->textonym#) => + (values 0 (hash)))) + +(define (port->textonym#) + (for/fold + ((n 0) (t# (hash))) + ((w (in-port read-line))) + (define s (word->textonym w)) + (if s + (values (+ n 1) (hash-update t# s (cons-uniquely w) null)) + (values n t#)))) + +(define (report-on-file f-name) + (define-values (n-words textonym#) (with-input-from-file f-name port->textonym#)) + + (define n-textonyms (for/sum ((v (in-hash-values textonym#)) #:when (> (length v) 1)) 1)) + + (printf "--- report on ~s ends ---~%" f-name) + (printf + #<= (length v) 6)) (printf "~a -> ~s~%" k v)) + (printf "--- report on ~s ends ---~%" f-name)) + +(module+ main + (report-on-file "data/unixdict.txt")) diff --git a/Task/Textonyms/Tcl/textonyms.tcl b/Task/Textonyms/Tcl/textonyms.tcl new file mode 100644 index 0000000000..4bd5961e52 --- /dev/null +++ b/Task/Textonyms/Tcl/textonyms.tcl @@ -0,0 +1,68 @@ +set keymap { + 2 -> ABC + 3 -> DEF + 4 -> GHI + 5 -> JKL + 6 -> MNO + 7 -> PQRS + 8 -> TUV + 9 -> WXYZ +} + +set url http://www.puzzlers.org/pub/wordlists/unixdict.txt + +set report { +There are %1$s words in %2$s which can be represented by the digit key mapping. +They require %3$s digit combinations to represent them. +%4$s digit combinations represent Textonyms. + +A %5$s-letter textonym which has %6$s combinations is %7$s: + + %8$s +} + +package require http +proc geturl {url} { + try { + set tok [http::geturl $url] + return [http::data $tok] + } finally { + http::cleanup $tok + } +} + +proc main {keymap url} { + foreach {digit -> letters} $keymap { + foreach l [split $letters ""] { + dict set strmap $l $digit + } + } + set doc [geturl $url] + foreach word [split $doc \n] { + if {![string is alpha -strict $word]} continue + dict lappend words [string map $strmap [string toupper $word]] $word + } + + set ncombos [dict size $words] + set nwords 0 + set ntextos 0 + set nmax 0 + set dmax "" + dict for {d ws} $words { + puts [list $d $ws] + set n [llength $ws] + incr nwords $n + if {$n > 1} { + incr ntextos $n + } + if {$n >= $nmax && [string length $d] > [string length $dmax]} { + set nmax $n + set dmax $d + } + } + set maxwords [dict get $words $dmax] + set lenmax [llength $maxwords] + format $::report $nwords $url $ncombos $ntextos $lenmax $nmax $dmax $maxwords +} + +puts [main $keymap $url] diff --git a/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION b/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION index 3c17c7859a..514011826b 100644 --- a/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION +++ b/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION @@ -1,4 +1,6 @@ -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.) +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/Befunge/the-twelve-days-of-christmas.bf b/Task/The-Twelve-Days-of-Christmas/Befunge/the-twelve-days-of-christmas.bf new file mode 100644 index 0000000000..e50c77242a --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Befunge/the-twelve-days-of-christmas.bf @@ -0,0 +1,9 @@ +0246*+00p20#v_:#`2#g+#0:#0<>\#%"O"/#:3#:+#< g48*- >1-:!#v_\1+::"O"%\"O"/v +>-#11#\0#50#< g2-:00p4v >\#%"O"/#::$#<3#$+g48*-v^\,+*+ 55!:*!!-"|":g+3< + ^02_>#`>#< 2 5 3 1 0 \1-:#^\_^#:-1\+<00_@#:>#<$< +(On the ?|A partridge in a pear tree.||&first% andL day of Christmas,|My true l +ove gave to me:2|Two turtle doves'second3|Three french hens&third4|Four calling + birds'fourth3|Five golden rings&fifth4|Six geese a-laying&sixth8|Seven swans a +-swimming(seventh7|Eight maids a-milking'eighth5|Nine ladies dancing&ninth5|Ten + lords a-leaping&tenth6|Eleven pipers piping)eleventh:|Twelve drummers drumming +(twelfth diff --git a/Task/The-Twelve-Days-of-Christmas/Eiffel/the-twelve-days-of-christmas.e b/Task/The-Twelve-Days-of-Christmas/Eiffel/the-twelve-days-of-christmas.e new file mode 100644 index 0000000000..3372fc35bf --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Eiffel/the-twelve-days-of-christmas.e @@ -0,0 +1,55 @@ +class + APPLICATION + +create + make + +feature + + make + do + twelve_days_of_christmas + end + +feature {NONE} + + twelve_days_of_christmas + -- Christmas carol: Twelve days of christmas. + local + i, j: INTEGER + do + create gifts.make_empty + create days.make_empty + 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">> + days := <<"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "Twelfth">> + from + i := 1 + until + i > days.count + loop + io.put_string ("On the " + days [i] + " day of Christmas.%N") + io.put_string ("My true love gave to me:%N") + from + j := i + until + j <= 0 + loop + if i = 12 and j = 2 then + io.put_string (gifts [14] + "%N") + io.put_string (gifts [13] + "%N") + j := j - 1 + else + io.put_string (gifts [j] + "%N") + end + j := j - 1 + end + io.new_line + i := i + 1 + end + end + + gifts: ARRAY [STRING] + + days: ARRAY [STRING] + +end diff --git a/Task/The-Twelve-Days-of-Christmas/Elixir/the-twelve-days-of-christmas.elixir b/Task/The-Twelve-Days-of-Christmas/Elixir/the-twelve-days-of-christmas.elixir new file mode 100644 index 0000000000..c9658e912c --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Elixir/the-twelve-days-of-christmas.elixir @@ -0,0 +1,23 @@ +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 +""" |> String.split("\n", trim: true) + +days = ~w(first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth) + +Enum.with_index(days) |> Enum.each(fn {day, i} -> + IO.puts "On the #{day} day of Christmas" + IO.puts "My true love gave to me:" + Enum.take(gifts, i+1) |> Enum.reverse |> Enum.each(&IO.puts &1) + IO.puts "" +end) diff --git a/Task/The-Twelve-Days-of-Christmas/Haskell/the-twelve-days-of-christmas.hs b/Task/The-Twelve-Days-of-Christmas/Haskell/the-twelve-days-of-christmas.hs new file mode 100644 index 0000000000..010189c3ac --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Haskell/the-twelve-days-of-christmas.hs @@ -0,0 +1,30 @@ +gifts :: [String] +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," ] + +days :: [String] +days = [ + "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", + "ninth", "tenth", "eleventh", "twelfth" ] + +verseOfTheDay :: Int -> IO () +verseOfTheDay day = do + putStrLn $ "On the " ++ days !! day ++ " day of Christmas my true love gave to me... " + mapM_ putStrLn [dayGift day d | d <- [day, day-1..0]] + putStrLn "" + where dayGift 0 _ = "A partridge in a pear tree!" + dayGift _ gift = gifts !! gift + +main :: IO () +main = mapM_ verseOfTheDay [0..11] 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-1.js similarity index 100% rename from Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas.js rename to Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-1.js diff --git a/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-2.js b/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-2.js new file mode 100644 index 0000000000..79ca33c070 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-2.js @@ -0,0 +1,75 @@ +JSON.stringify( + (function ( + strPrepn, + strHoliday, + strUnit, + strRole, + strProcess, + strRecipient + ) { + var lstOrdinal = + 'first second third fourth fifth sixth\ + seventh eighth ninth tenth eleventh twelfth' + .split(/\s+/), + lngUnits = lstOrdinal.length, + + lstGoods = + '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(/\s{2,}/), + + lstReversed = (function () { + var lst = lstGoods.slice(0); + return (lst.reverse(), lst); + })(), + + strProvenance = [strRole, strProcess, strRecipient + ':'].join(' '), + + strPenultimate = lstReversed[lngUnits - 2] + ' and', + strFinal = lstGoods[0]; + + return lstOrdinal.reduce( + function (sofar, day, i) { + return sofar.concat( + [ + [ + [ // abstraction of line 1 + strPrepn, + 'the', + lstOrdinal[i], + strUnit, + 'of', + strHoliday + ].join(' '), + strProvenance + ].concat( // reversed descent through memory + (i > 1 ? [lstGoods[i]] : []).concat( + lstReversed.slice( + lngUnits - i, + lngUnits - 2 + ) + ).concat( // penultimate line ends with 'and' + [ + strPenultimate, + strFinal + ].slice(i ? 0 : 1) + ) + ) + ] + ); + }, [] + ); + })( + 'On', 'Christmas', 'day', 'my true love', 'gave to', 'me' + ), null, 2 +); diff --git a/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-3.js b/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-3.js new file mode 100644 index 0000000000..731a5ff4a1 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-3.js @@ -0,0 +1,22 @@ +JSON.stringify(function (h, k, l, f, m, n) { + var c = + "first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth" + .split(" "), + d = c.length, + e = + "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(";"), + g = function () { + var b = e.slice(0); + return b.reverse(), b; + }(), + p = [f, m, n + ":"].join(" "), + q = g[d - 2] + " and", + r = e[0]; + + return c.reduce(function (b, f, a) { + return b.concat([[[h, "the", c[a], l, "of", k].join(" "), p].concat((1 < + a ? [e[a]] : []).concat(g.slice(d - a, d - 2)).concat([q, r].slice(a ? + 0 : 1)))]); + }, []); +}("On", "Christmas", "day", "my true love", "gave to", "me"), null, 2); diff --git a/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-4.js b/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-4.js new file mode 100644 index 0000000000..c188578c35 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/JavaScript/the-twelve-days-of-christmas-4.js @@ -0,0 +1,40 @@ +[ + [ + "On the first day of Christmas", + "my true love gave to me:", + "A partridge in a pear tree." + ], + [ + "On the second day of Christmas", + "my true love gave to me:", + "Two turtle doves and", + "A partridge in a pear tree." + ], + [ + "On the third day of Christmas", + "my true love gave to me:", + "Three french hens", + "Two turtle doves and", + "A partridge in a pear tree." + ], + [ + "On the fourth day of Christmas", + "my true love gave to me:", + "Four calling birds", + "Three french hens", + "Two turtle doves and", + "A partridge in a pear tree." + ], + [ + "On the fifth day of Christmas", + "my true love gave to me:", + "Five golden rings", + "Four calling birds", + "Three french hens", + "Two turtle doves and", + "A partridge in a pear tree." + ] + +//... etc. + +] diff --git a/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx b/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx index 75326c4761..e3877c948f 100644 --- a/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx +++ b/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx @@ -1,17 +1,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) +/*REXX program displays the verses of the song: "The 12 days of Christmas". */ +@='first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth' +pad=left('',20) /*used for indenting the shown verses.*/ - 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,' + 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.*/ + say pad 'On the' word(@,day) 'day of Christmas' /*display line 1 prologue*/ + say pad 'My True Love gave to me:' /* " " 2 " */ + do j=day to 1 by -1; say pad g.j; end /* " the daily gifts*/ + say /*add a blank line between the verses. */ + end /*day*/ /*stick a fork in it, we're all done. */ 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 index ffb94c9e67..6006b1973b 100644 --- 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 @@ -1,5 +1,5 @@ gifts = "A partridge in a pear tree -Two turtle doves +Two turtle doves and Three french hens Four calling birds Five golden rings @@ -19,5 +19,4 @@ 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 index 2f7d3ce205..eb2924da70 100644 --- 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 @@ -1,43 +1,38 @@ -// -*- rust v0.9 -*- +fn showpresents(count : usize) { + let days = ["second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", + "tenth", "eleventh", "twelfth"]; -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"]; + 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"); + println!("On the {} day of Christmas my true love gave to me {}", days[count-1], presents[count-1]); + if count > 0 { + let mut j = count-1; + while j > 0 { + println!("{}", 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; - } - - + 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/SQL/the-twelve-days-of-christmas.sql b/Task/The-Twelve-Days-of-Christmas/SQL/the-twelve-days-of-christmas.sql new file mode 100644 index 0000000000..30320a2c1a --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/SQL/the-twelve-days-of-christmas.sql @@ -0,0 +1,48 @@ +with +function nl ( s in varchar2 ) +return varchar2 +is +begin + return chr(10) || s; +end nl; +function v ( d number, x number, g in varchar2 ) +return varchar2 +is +begin + return + case when d >= x then nl (g) end; +end v; +select 'On the ' + || case level + when 1 then 'first' + when 2 then 'second' + when 3 then 'third' + when 4 then 'fourth' + when 5 then 'fifth' + when 6 then 'sixth' + when 7 then 'seventh' + when 8 then 'eighth' + when 9 then 'ninth' + when 10 then 'tenth' + when 11 then 'eleventh' + when 12 then 'twelfth' + end + || ' of Christmas,' + || nl( 'My true love gave to me:') + || v ( level, 12, 'Twelve drummers drumming' ) + || v ( level, 11, 'Eleven pipers piping' ) + || v ( level, 10, 'Ten lords a-leaping' ) + || v ( level, 9, 'Nine ladies dancing' ) + || v ( level, 8, 'Eight maids a-milking' ) + || v ( level, 7, 'Seven swans a-swimming' ) + || v ( level, 6, 'Six geese a-laying' ) + || v ( level, 5, 'Five golden rings!' ) + || v ( level, 4, 'Four calling birds' ) + || v ( level, 3, 'Three French hens' ) + || v ( level, 2, 'Two turtle doves' ) + || v ( level, 1, case level when 1 then 'A' else 'And a' end || ' partridge in a pear tree.' ) + || nl(null) + "The Twelve Days of Christmas" +from dual +connect by level <= 12 +/ diff --git a/Task/The-Twelve-Days-of-Christmas/Self/the-twelve-days-of-christmas.self b/Task/The-Twelve-Days-of-Christmas/Self/the-twelve-days-of-christmas.self new file mode 100644 index 0000000000..2cf58d4acf --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Self/the-twelve-days-of-christmas.self @@ -0,0 +1,31 @@ +(| +parent* = traits oddball. + +gifts = ( + 'And a partridge in a pear tree' & + 'Two turtle doves' & + 'Three french hens' & + 'Four calling birds' & + 'FIVE GO-OLD 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' +) asSequence. + +days = ( + 'first' & 'second' & 'third' & 'fourth' & + 'fifth' & 'sixth' & 'seventh' & 'eighth' & + 'ninth' & 'tenth' & 'eleventh' & 'twelfth' +) asSequence. + +intro: i = ( 'On the ', (days at: i), ' day of Christmas, my true love gave to me:'). +gifts: i = ( i = 0 ifTrue: [sequence copyAddFirst: 'A partridge in a pear tree' ] + False: [(gifts slice: 0@(i + 1)) reverse ]). +verse: i = ( ((sequence copyAddFirst: intro: i) addAll: gifts: i) addLast: '' ). +value = ( (days gather: [|:d. :i| verse: i ]) asSequence joinUsing: '\n' ) + +|) value printLine diff --git a/Task/The-Twelve-Days-of-Christmas/VBScript/the-twelve-days-of-christmas.vb b/Task/The-Twelve-Days-of-Christmas/VBScript/the-twelve-days-of-christmas.vb new file mode 100644 index 0000000000..522068f63b --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/VBScript/the-twelve-days-of-christmas.vb @@ -0,0 +1,27 @@ +days = Array("first","second","third","fourth","fifth","sixth",_ + "seventh","eight","ninth","tenth","eleventh","twelfth") + +gifts = Array("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 To 11 + WScript.StdOut.Write "On the " & days(i) & " day of Christmas" + WScript.StdOut.WriteLine + WScript.StdOut.Write "My true love sent to me:" + WScript.StdOut.WriteLine + If i = 0 Then + WScript.StdOut.Write gifts(i) + Else + For j = i To 0 Step - 1 + If j = 0 Then + WScript.StdOut.Write "and " & gifts(0) + Else + WScript.StdOut.Write gifts(j) + WScript.StdOut.WriteLine + End If + Next + End If + WScript.StdOut.WriteBlankLines(2) +Next diff --git a/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 b/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 index 3c9c46f709..d8ed6f4512 100644 --- a/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 +++ b/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 @@ -1,26 +1,23 @@ use v6; # reciprocal difference: -multi sub rho($f, @x where { +@x < 1 }) { 0 } # Identity -multi sub rho($f, @x where { +@x == 1 }) { $f(@x[0]) } -multi sub rho($f, @x where { +@x > 1 }) { - my $ord = +@x; - - return - ( @x[0] - @x[* -1] ) # ( x - x[n] ) - / ( rho($f, @x[^($ord -1)]) # / ( rho[n-1](x[0], ..., x[n-1]) - - rho($f, @x[1..^($ord)]) ) # - rho[n-1](x[1], ..., x[n]) ) - + rho($f, @x[1..^($ord -1)]); # + rho[n-2](x[1], ..., x[n-1]) +multi sub ρ(&f, @x where * < 1) { 0 } # Identity +multi sub ρ(&f, @x where * == 1) { &f(@x[0]) } +multi sub ρ(&f, @x where * > 1) { + ( @x[0] - @x[* - 1] ) # ( x - x[n] ) + / (ρ(&f, @x[^(@x - 1)]) # / ( ρ[n-1](x[0], ..., x[n-1]) + - ρ(&f, @x[1..^@x]) ) # - ρ[n-1](x[1], ..., x[n]) ) + + ρ(&f, @x[1..^(@x - 1)]); # + ρ[n-2](x[1], ..., x[n-1]) } # Thiele: multi sub thiele($x, %f, $ord where { $ord == +%f }) { 1 } # Identity multi sub thiele($x, %f, $ord) { - my $f = {%f{$^a}}; # f(x) as a table lookup + my &f = {%f{$^a}}; # f(x) as a table lookup # Caveat: depends on the fact that Rakudo maintains key order within hashes - my $a = rho($f, %f.keys[^($ord +1)]); - my $b = rho($f, %f.keys[^($ord -1)]); + my $a = ρ(&f, %f.keys[^($ord +1)]); + my $b = ρ(&f, %f.keys[^($ord -1)]); my $num = $x - %f.keys[$ord]; my $cont = thiele($x, %f, $ord +1); @@ -30,9 +27,9 @@ multi sub thiele($x, %f, $ord) { } ## Demo -sub mk-inv($fn, $d, $lim) { +sub mk-inv(&fn, $d, $lim) { my %h; - for 0..$lim { %h{ $fn($_ * $d) } = $_ * $d } + for 0..$lim { %h{ &fn($_ * $d) } = $_ * $d } return %h; } diff --git a/Task/Thieles-interpolation-formula/Python/thieles-interpolation-formula.py b/Task/Thieles-interpolation-formula/Python/thieles-interpolation-formula.py new file mode 100644 index 0000000000..c5387679c0 --- /dev/null +++ b/Task/Thieles-interpolation-formula/Python/thieles-interpolation-formula.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 + +import math + +def thieleInterpolator(x, y): + ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)] + for i in range(len(ρ)-1): + ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0]) + for i in range(2, len(ρ)): + for j in range(len(ρ)-i): + ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2] + ρ0 = ρ[0] + def t(xin): + a = 0 + for i in range(len(ρ0)-1, 1, -1): + a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a) + return y[0] + (xin-x[0]) / (ρ0[1]+a) + return t + +# task 1: build 32 row trig table +xVal = [i*.05 for i in range(32)] +tSin = [math.sin(x) for x in xVal] +tCos = [math.cos(x) for x in xVal] +tTan = [math.tan(x) for x in xVal] +# task 2: define inverses +iSin = thieleInterpolator(tSin, xVal) +iCos = thieleInterpolator(tCos, xVal) +iTan = thieleInterpolator(tTan, xVal) +# task 3: demonstrate identities +print('{:16.14f}'.format(6*iSin(.5))) +print('{:16.14f}'.format(3*iCos(.5))) +print('{:16.14f}'.format(4*iTan(1))) diff --git a/Task/Tic-tac-toe/ALGOL-W/tic-tac-toe.alg b/Task/Tic-tac-toe/ALGOL-W/tic-tac-toe.alg new file mode 100644 index 0000000000..d1237a08cf --- /dev/null +++ b/Task/Tic-tac-toe/ALGOL-W/tic-tac-toe.alg @@ -0,0 +1,180 @@ +begin + + string(10) board; + + % initialise the board % + procedure initBoard ; board := " 123456789"; + + % display the board % + procedure showBoard ; + begin + s_w := 0; + write( board(1//1), "|", board(2//1), "|", board(3//1) ); + write( "-+-+-" ); + write( board(4//1), "|", board(5//1), "|", board(6//1) ); + write( "-+-+-" ); + write( board(7//1), "|", board(8//1), "|", board(9//1) ) + end showBoard ; + + % returns true if board pos is free, false otherwise % + logical procedure freeSpace( integer value pos ) ; + ( board(pos//1) >= "1" and board(pos//1) <= "9" ); + + % check for game over % + logical procedure gameOver ; + begin + logical noMoves; + noMoves := true; + for i := 1 until 9 do if noMoves then noMoves := not freeSpace( i ); + noMoves + end gameOver ; + + % makes the specified winning move or blocks it, if it will win % + logical procedure winOrBlock( integer value pos1, pos2, pos3 + ; string(1) value searchCharacter + ; string(1) value playerCharacter + ) ; + if board(pos1//1) = searchCharacter + and board(pos2//1) = searchCharacter + and freeSpace( pos3 ) + then begin + board(pos3//1) := playerCharacter; + true + end + else if board(pos1//1) = searchCharacter + and freeSpace( pos2 ) + and board(pos3//1) = searchCharacter + then begin + board(pos2//1) := playerCharacter; + true + end + else if freeSpace( pos1 ) + and board(pos2//1) = searchCharacter + and board(pos3//1) = searchCharacter + then begin + board(pos1//1) := playerCharacter; + true + end + else begin + false + end winOrBlock ; + + % makes a winning move or blocks a winning move, if there is one % + logical procedure makeOrBlockWinningMove( string(1) value searchCharacter + ; string(1) value playerCharacter + ) ; + ( winOrBlock( 1, 2, 3, searchCharacter, playerCharacter ) + or winOrBlock( 4, 5, 6, searchCharacter, playerCharacter ) + or winOrBlock( 7, 8, 9, searchCharacter, playerCharacter ) + or winOrBlock( 1, 4, 7, searchCharacter, playerCharacter ) + or winOrBlock( 2, 5, 8, searchCharacter, playerCharacter ) + or winOrBlock( 3, 6, 9, searchCharacter, playerCharacter ) + or winOrBlock( 1, 5, 9, searchCharacter, playerCharacter ) + or winOrBlock( 3, 5, 7, searchCharacter, playerCharacter ) + ) ; + + % makes a move when there isn't an obvious winning/blocking move % + procedure move ( string(1) value playerCharacter ) ; + begin + logical moved; + moved := false; + % try for the centre, a corner or the midle of a line % + for pos := 5, 1, 3, 7, 9, 2, 4, 6, 8 do begin + if not moved and freeSpace( pos ) then begin + moved := true; + board(pos//1) := playerCharacter + end + end + end move ; + + % gets a move from the user % + procedure userMove( string(1) value playerCharacter ) ; + begin + integer move; + while + begin + write( "Please enter the move for ", playerCharacter, " " ); + read( move ); + ( move < 1 or move > 9 or not freeSpace( move ) ) + end + do begin + write( "Invalid move" ) + end; + board(move//1) := playerCharacter + end userMove ; + + % returns true if the three board positions have the player character, % + % false otherwise % + logical procedure same( integer value pos1, pos2, pos3 + ; string(1) value playerCharacter + ) ; + ( board(pos1//1) = playerCharacter + and board(pos2//1) = playerCharacter + and board(pos3//1) = playerCharacter + ); + + % returns true if the player has made a winning move, false otherwise % + logical procedure playerHasWon( string(1) value playerCharacter ) ; + ( same( 1, 2, 3, playerCharacter ) + or same( 4, 5, 6, playerCharacter ) + or same( 7, 8, 9, playerCharacter ) + or same( 1, 4, 7, playerCharacter ) + or same( 2, 5, 8, playerCharacter ) + or same( 3, 6, 9, playerCharacter ) + or same( 1, 5, 9, playerCharacter ) + or same( 3, 5, 7, playerCharacter ) + ) ; + + % takes a players turn - either automated or user input % + procedure turn ( string(1) value playerCharacter, otherCharacter + ; logical value playerIsUser + ) ; + begin + if playerIsUser then userMove( playerCharacter ) + else begin + write( playerCharacter, " moves..." ); + if not makeOrBlockWinningMove( playerCharacter, playerCharacter ) + and not makeOrBlockWinningMove( otherCharacter, playerCharacter ) + then move( playerCharacter ) + end; + showBoard + end turn ; + + % asks a question and returns true if the user inputs y/Y, % + % false otherwise % + logical procedure yes( string(32) value question ) ; + begin + string(1) answer; + write( question ); + read( answer ); + answer = "y" or answer = "Y" + end yes ; + + % play the game % + while + begin + string(1) again; + string(32) gameResult; + logical oIsUser, xIsUser; + + oIsUser := yes( "Do you want to play O? " ); + xIsUser := yes( "Do you want to play X? " ); + + gameResult := "it's a draw"; + initBoard; + showBoard; + while not gameOver and not playerHasWon( "O" ) and not playerHasWon( "X" ) do begin + turn( "O", "X", oIsUser ); + if playerHasWon( "O" ) then gameResult := "O wins" + else if not gameOver then begin + turn( "X", "O", xIsUser ); + if playerHasWon( "X" ) then gameResult := "X wins" + end + end ; + write( gameResult ); + + yes( "Play again? " ) + end + do begin end + +end. diff --git a/Task/Tic-tac-toe/AppleScript/tic-tac-toe.applescript b/Task/Tic-tac-toe/AppleScript/tic-tac-toe.applescript new file mode 100644 index 0000000000..d871d8fc29 --- /dev/null +++ b/Task/Tic-tac-toe/AppleScript/tic-tac-toe.applescript @@ -0,0 +1,113 @@ +property OMask : missing value +property XMask : missing value +property winningNumbers : {7, 56, 73, 84, 146, 273, 292, 448} +property difficulty : missing value + +repeat + set OMask to 0 + set XMask to 0 + + if button returned of (display dialog "Who should start?" buttons {"I shoud", "CPU"}) = "CPU" then set OMask to npcGet() + set difficulty to button returned of (display dialog "Please choose your difficulty" buttons {"Hard", "Normal"}) + + repeat + set XMask to XMask + 2 ^ (nGet() - 1) + if winnerForMask(XMask) or OMask + XMask = 511 then exit repeat + set OMask to npcGet() + if winnerForMask(OMask) or OMask + XMask = 511 then exit repeat + end repeat + + if winnerForMask(OMask) then + set msg to "CPU Wins!" + else if winnerForMask(XMask) then + set msg to "You WON!!!" + else + set msg to "It's a draw" + end if + + display dialog msg & return & return & drawGrid() & return & return & "Do you want to play again?" +end repeat + +on nGet() + set theMessage to "It's your turn Player 1, please fill in the number for X" & return & return & drawGrid() + repeat + set value to text returned of (display dialog theMessage default answer "") + if (offset of value in "123456789") is not 0 then + if not positionIsUsed(value as integer) then exit repeat + end if + end repeat + return value as integer +end nGet + +on npcGet() + --first get the free positions + set freeSpots to {} + repeat with s from 1 to 9 + if not positionIsUsed(s) then set end of freeSpots to 2 ^ (s - 1) + end repeat + --second check if 1 move can make the CPU win + repeat with spot in freeSpots + if winnerForMask(OMask + spot) then return OMask + spot + end repeat + + if difficulty is "Hard" and OMask is 0 then + if XMask = 1 or XMask = 4 then return 2 + if XMask = 64 or XMask = 256 then return 128 + end if + --third check if a user can make make it win (defensive) place it on position + repeat with spot in freeSpots + if winnerForMask(XMask + spot) then return OMask + spot + end repeat + + --fourth check if CPU can win in two moves + repeat with spot1 in freeSpots + repeat with spot2 in freeSpots + if winnerForMask(OMask + spot1 + spot2) then return OMask + spot2 + end repeat + end repeat + --fifth check if player can win in two moves + repeat with spot1 in freeSpots + repeat with spot2 in reverse of freeSpots + if winnerForMask(XMask + spot1 + spot2) then return OMask + spot1 + end repeat + end repeat + --at last pick a random spot + if XMask + OMask = 0 and difficulty = "Hard" then return 1 + + return OMask + (some item of freeSpots) +end npcGet + +on winnerForMask(mask) + repeat with winLine in winningNumbers + if BWAND(winLine, mask) = contents of winLine then return true + end repeat + return false +end winnerForMask + +on drawGrid() + set grid to "" + repeat with o from 0 to 8 + if BWAND(OMask, 2 ^ o) = 2 ^ o then + set grid to grid & "O" + else if BWAND(XMask, 2 ^ o) = 2 ^ o then + set grid to grid & "X" + else + set grid to grid & o + 1 + end if + if o is in {2, 5} then set grid to grid & return + end repeat + return grid +end drawGrid + +on positionIsUsed(pos) + return BWAND(OMask + XMask, 2 ^ (pos - 1)) = 2 ^ (pos - 1) +end positionIsUsed + +on BWAND(n1, n2) + set theResult to 0 + repeat with o from 0 to 8 + if (n1 mod 2) = 1 and (n2 mod 2) = 1 then set theResult to theResult + 2 ^ o + set {n1, n2} to {n1 div 2, n2 div 2} + end repeat + return theResult as integer +end BWAND diff --git a/Task/Tic-tac-toe/Batch-File/tic-tac-toe.bat b/Task/Tic-tac-toe/Batch-File/tic-tac-toe.bat new file mode 100644 index 0000000000..0734d289da --- /dev/null +++ b/Task/Tic-tac-toe/Batch-File/tic-tac-toe.bat @@ -0,0 +1,136 @@ +:: +::Tic-Tac-Toe Task from Rosetta Code Wiki +::Batch File Implementation +:: +::Directly OPEN the Batch File to play. +:: + +@echo off +title Sample TicTacToe Game +mode con cols=50 lines=21 +setlocal enabledelayedexpansion + +set win=a1a2a3 a4a5a6 a7a8a9 a1a4a7 a2a5a8 a3a6a9 a1a5a9 a3a5a7 + +:begin +set blanks=123456789&set numblanks=9 +for /l %%. in (1,1,9) do set "a%%.= " + +set /a rnd=%random%%%2 +if %rnd%==1 set msg=YOU will move first.&goto :youmove +set msg=CPU will move first.&goto :rndmove + +:youmove +cls +call :display +echo Your Turn: +set "move=" +for /F "usebackq delims=" %%L in (`xcopy /L /w "%~f0" "%~f0" 2^>NUL`) do ( + if not defined move set "move=%%L" +) +set move=!move:~-1! +for /l %%. in (1,1,9) do if "!move!"=="%%." goto :preproc +if /i "!move!"=="n" goto :begin +if /i "!move!"=="o" exit +set msg=Invalid Input. +goto youmove + +:preproc +if "!a%move%!"=="X" (set msg=An X is already There.&goto youmove) +if "!a%move%!"=="O" (set msg=An O is already There.&goto youmove) + +set a%move%=O +set /a numblanks-=1&set blanks=!blanks:%move%=! +call :ifdraw + +for %%. in (%win%) do ( + set comb=%%. + call :mainproc1 +) +set block=0 +for %%. in (%win%) do ( + if !block!==0 ( + set comb=%%. + call :mainproc2 + ) +) +if %block%==1 ( + set /a numblanks-=1&set blanks=!blanks:%remove%=! + set msg=CPU Puts an X on Grid %remove%. + call :ifdraw + goto youmove +) +goto rndmove + + +:mainproc1 +if "!%comb:~0,2%!!%comb:~2,2%!!%comb:~4,2%!"=="OOO" (set msg=You Win^^!&goto res) + +if "!%comb:~0,2%!!%comb:~2,2%!!%comb:~4,2%!"=="XX " ( + set %comb:~4,2%=X&set msg=CPU Wins^^! + goto res +) +if "!%comb:~0,2%!!%comb:~2,2%!!%comb:~4,2%!"=="X X" ( + set %comb:~2,2%=X&set msg=CPU Wins^^! + goto res +) +if "!%comb:~0,2%!!%comb:~2,2%!!%comb:~4,2%!"==" XX" ( + set %comb:~0,2%=X&set msg=CPU Wins^^! + goto res +) +goto :EOF + +:mainproc2 +if "!%comb:~0,2%!!%comb:~2,2%!!%comb:~4,2%!"=="OO " ( + set %comb:~4,2%=X&set remove=%comb:~5,1% + set block=1 +) +if "!%comb:~0,2%!!%comb:~2,2%!!%comb:~4,2%!"=="O O" ( + set %comb:~2,2%=X&set remove=%comb:~3,1% + set block=1 +) +if "!%comb:~0,2%!!%comb:~2,2%!!%comb:~4,2%!"==" OO" ( + set %comb:~0,2%=X&set remove=%comb:~1,1% + set block=1 +) +goto :EOF + +:ifdraw +if %numblanks%==0 (set msg=Game Draw.&goto res) +goto :EOF + +:rndmove +set /a rnd=(%random%%%%numblanks%) +set bla=!blanks:~%rnd%,1! +set a%bla%=X +set /a numblanks-=1&set blanks=!blanks:%bla%=! +if not %numblanks%==8 (set msg=CPU Puts an X on Grid %bla%.) +call :ifdraw +goto youmove + +:res +cls +call :display +echo Press any char key to play again. +pause>nul +goto begin + +:display +echo. +echo Tic-Tac-Toe (Man VS CPU) +echo Batch File Implementation +echo. +echo. +echo Gameboard Press: +echo. +echo +---+---+---+ N - New Game +echo 1-3 ^| %a1% ^| %a2% ^| %a3% ^| O - Exit +echo +---+---+---+ +echo 4-6 ^| %a4% ^| %a5% ^| %a6% ^| +echo +---+---+---+ You - O +echo 7-9 ^| %a7% ^| %a8% ^| %a9% ^| CPU - X +echo +---+---+---+ +echo. +echo Message: !msg! +echo. +goto :EOF diff --git a/Task/Tic-tac-toe/Befunge/tic-tac-toe.bf b/Task/Tic-tac-toe/Befunge/tic-tac-toe.bf new file mode 100644 index 0000000000..fdfc841b71 --- /dev/null +++ b/Task/Tic-tac-toe/Befunge/tic-tac-toe.bf @@ -0,0 +1,14 @@ +v123456789 --- >9 >48*,:55+\-0g,1v +>9>066+0p076+0p^ ^,," |"_v#%3:- < +:,,0537051v>:#,_$#^5#,5#+<>:#v_55+ +74 1098709<^+55"---+---+---"0:!#v_0\1v>$2-:6%v>803 +6 +0g\66++0p^ $_>#% v#9:-1_ 6/5 +5 vv5!/*88\%*28 ::g0_^>9/#v_ "I", +,,5v>5++0p82*/3-:*+\:^v,_@ >"uoY", +0+5:^:" win!"\ +1-^ g >$>0" :evom ruoY">:#,_$v>p +\*8+ 65_^#!/*88g0** `0\!`9:::<&<^0 +v >:!67+0g:!56+0g *+*+0" :evom " +>"yM">:#,_$ :. 1234+++, 789*+ \0^< +"a s't"98:*+>:#,_$@>365*+"ward"48* diff --git a/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx b/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx index b79606c37e..f2d0f5a992 100644 --- a/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx +++ b/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx @@ -1,6 +1,6 @@ /*REXX program plays (with a human) the tic-tac-toe game on an NxN grid.*/ -oops =$ '***error!*** '; cell# ='cell number' /*a couple of literals*/ $=copies('─',9) /*eyecatcher literal for messages*/ +oops =$ '***error!*** '; cell# ='cell number' /*a couple of literals*/ sing='│─┼'; jam='║'; bar='═'; junc='╬'; dbl=jam || bar || junc sw=linesize()-1 /*get the width of the terminal. */ parse arg N hm cm .,@.; if N=='' then N=3; oN=N /*specifying some args?*/ diff --git a/Task/Time-a-function/C/time-a-function.c b/Task/Time-a-function/C/time-a-function.c index 4ade5d8478..481f03787f 100644 --- a/Task/Time-a-function/C/time-a-function.c +++ b/Task/Time-a-function/C/time-a-function.c @@ -10,8 +10,13 @@ int sum(int s) return s; } -#define CLOCKTYPE CLOCK_MONOTONIC +#ifdef CLOCK_PROCESS_CPUTIME_ID +/* cpu time in the current process */ +#define CLOCKTYPE CLOCK_PROCESS_CPUTIME_ID +#else /* this one should be appropriate to avoid errors on multiprocessors systems */ +#define CLOCKTYPE CLOCK_MONOTONIC +#endif double time_it(int (*action)(int), int arg) { diff --git a/Task/Time-a-function/Elixir/time-a-function-1.elixir b/Task/Time-a-function/Elixir/time-a-function-1.elixir new file mode 100644 index 0000000000..97c320da68 --- /dev/null +++ b/Task/Time-a-function/Elixir/time-a-function-1.elixir @@ -0,0 +1,2 @@ +iex(10)> :timer.tc(fn -> Enum.each(1..100000, fn x -> x*x end) end) +{236000, :ok} diff --git a/Task/Time-a-function/Elixir/time-a-function-2.elixir b/Task/Time-a-function/Elixir/time-a-function-2.elixir new file mode 100644 index 0000000000..bf7363cbfd --- /dev/null +++ b/Task/Time-a-function/Elixir/time-a-function-2.elixir @@ -0,0 +1,2 @@ +iex(11)> :timer.tc(fn x -> Enum.each(1..x, fn y -> y*y end) end, [1000000]) +{2300000, :ok} diff --git a/Task/Time-a-function/Elixir/time-a-function-3.elixir b/Task/Time-a-function/Elixir/time-a-function-3.elixir new file mode 100644 index 0000000000..9717c57baa --- /dev/null +++ b/Task/Time-a-function/Elixir/time-a-function-3.elixir @@ -0,0 +1,5 @@ +iex(12)> :timer.tc(Enum, :to_list, [1..1000000]) +{224000, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, + 42, 43, 44, 45, 46, 47, 48, 49, ...]} diff --git a/Task/Time-a-function/PowerShell/time-a-function.psh b/Task/Time-a-function/PowerShell/time-a-function.psh new file mode 100644 index 0000000000..670ec0b62f --- /dev/null +++ b/Task/Time-a-function/PowerShell/time-a-function.psh @@ -0,0 +1,12 @@ +function fun($n){ + $res = 0 + if($n -gt 0) { + 1..$n | foreach{ + $a, $b = $_, ($n+$_) + $res += $a + $b + } + + } + $res +} +"$((Measure-Command {fun 10000}).TotalSeconds) Seconds" diff --git a/Task/Tokenize-a-string/C/tokenize-a-string-2.c b/Task/Tokenize-a-string/C/tokenize-a-string-2.c index 310d2ed7ea..22de5ee947 100644 --- a/Task/Tokenize-a-string/C/tokenize-a-string-2.c +++ b/Task/Tokenize-a-string/C/tokenize-a-string-2.c @@ -1,12 +1,12 @@ #include -typedef (void *callbackfunc)(const char *); +typedef void (*callbackfunc)(const char *); void doprint(const char *s) { printf("%s.", s); } -void tokenize(char *s, char delim, callbackfunc *cb) { +void tokenize(char *s, char delim, callbackfunc cb) { char *olds = s; char olddelim = delim; while(olddelim && *s) { diff --git a/Task/Tokenize-a-string/Julia/tokenize-a-string.julia b/Task/Tokenize-a-string/Julia/tokenize-a-string.julia new file mode 100644 index 0000000000..7925599513 --- /dev/null +++ b/Task/Tokenize-a-string/Julia/tokenize-a-string.julia @@ -0,0 +1,7 @@ +s = "Hello,How,Are,You,Today" +a = split(s, ",") +t = join(a, ".") + +println("The string \"", s, "\"") +println("Splits into ", a) +println("Reconstitutes to \"", t, "\"") diff --git a/Task/Tokenize-a-string/K/tokenize-a-string.k b/Task/Tokenize-a-string/K/tokenize-a-string.k new file mode 100644 index 0000000000..7854f2c8a7 --- /dev/null +++ b/Task/Tokenize-a-string/K/tokenize-a-string.k @@ -0,0 +1,2 @@ +words: "," \: "Hello,How,Are,You,Today" +"." /: words diff --git a/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin b/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin new file mode 100644 index 0000000000..8fd8f1e797 --- /dev/null +++ b/Task/Tokenize-a-string/Kotlin/tokenize-a-string.kotlin @@ -0,0 +1,2 @@ +val input = "Hello,How,Are,You,Today" +println(input.splitBy(",").join(".")) diff --git a/Task/Tokenize-a-string/Q/tokenize-a-string.q b/Task/Tokenize-a-string/Q/tokenize-a-string.q new file mode 100644 index 0000000000..6fafdd7995 --- /dev/null +++ b/Task/Tokenize-a-string/Q/tokenize-a-string.q @@ -0,0 +1,2 @@ +words: "," vs "Hello,How,Are,You,Today" +"." sv words diff --git a/Task/Tokenize-a-string/Self/tokenize-a-string.self b/Task/Tokenize-a-string/Self/tokenize-a-string.self new file mode 100644 index 0000000000..08429ea4b4 --- /dev/null +++ b/Task/Tokenize-a-string/Self/tokenize-a-string.self @@ -0,0 +1,2 @@ +| s = 'Hello,How,Are,You,Today' | +((s splitOn: ',') joinUsing: '.') printLine. diff --git a/Task/Tokenize-a-string/VBScript/tokenize-a-string.vb b/Task/Tokenize-a-string/VBScript/tokenize-a-string.vb index 2e5b6a5fa3..918d9bdfeb 100644 --- a/Task/Tokenize-a-string/VBScript/tokenize-a-string.vb +++ b/Task/Tokenize-a-string/VBScript/tokenize-a-string.vb @@ -1 +1,2 @@ -WScript.Echo Join(Split("Hello,How,Are,You,Today", ","), ".") +s = "Hello,How,Are,You,Today" +WScript.StdOut.Write Join(Split(s,","),".") diff --git a/Task/Top-rank-per-group/Elixir/top-rank-per-group.elixir b/Task/Top-rank-per-group/Elixir/top-rank-per-group.elixir new file mode 100644 index 0000000000..154795ac22 --- /dev/null +++ b/Task/Top-rank-per-group/Elixir/top-rank-per-group.elixir @@ -0,0 +1,30 @@ +data = "Employee Name,Employee ID,Salary,Department +Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190" + +salary = fn [_,_,x,_] -> String.to_integer(x) end +department = fn [_,_,_,x] -> x end +str_format = fn [a,b,c,d] -> "Department #{d}: #{a} - #{b} - #{c} annual salary" end + +data + |> String.split(~r/(\n|\r\n|\r)/,trim: true) + |> Enum.map(fn n -> String.split(n,",") end) + |> Enum.drop(1) + |> Enum.group_by(fn m -> department.(m) end) + |> Dict.values + |> Enum.map(fn n -> + Enum.sort_by(n, fn m -> -salary.(m) end) + |> Enum.take(3) + |> Enum.map(fn q -> IO.puts str_format.(q) end) + end) diff --git a/Task/Top-rank-per-group/REXX/top-rank-per-group-1.rexx b/Task/Top-rank-per-group/REXX/top-rank-per-group-1.rexx index ba33c850ed..8b23b12369 100644 --- a/Task/Top-rank-per-group/REXX/top-rank-per-group-1.rexx +++ b/Task/Top-rank-per-group/REXX/top-rank-per-group-1.rexx @@ -1,42 +1,42 @@ -/*REXX program shows top N salaries in each department (internal table).*/ -parse arg topN . /*get number for top N salaries. */ -if topN=='' then topN=1 /*if none, then assume only 1. */ -say 'Finding top' topN 'salaries in each department.'; say -@.= /*employee name, ID, salary, dept.*/ - @.1 = "Tyler Bennett,E10297,32000,D101" - @.2 = "John Rappl,E21437,47000,D050" - @.3 = "George Woltman,E00127,53500,D101" - @.4 = "Adam Smith,E63535,18000,D202" - @.5 = "Claire Buckman,E39876,27800,D202" - @.6 = "David McClellan,E04242,41500,D101" - @.7 = "Rich Holcomb,E01234,49500,D202" - @.8 = "Nathan Adams,E41298,21900,D050" - @.9 = "Richard Potter,E43128,15900,D101" - @.10 = "David Motsinger,E27002,19250,D202" - @.11 = "Tim Sampair,E03033,27000,D101" - @.12 = "Kim Arlich,E10001,57000,D190" - @.13 = "Timothy Grove,E16398,29900,D190" +/*REXX program displays the top N salaries in each department (internal table)*/ +parse arg topN . /*get optional # for the top N salaries*/ +if topN=='' then topN=1 /*Not specified? Then use the default.*/ +say 'Finding the top ' topN ' salaries in each department.'; say +@.= /*════════ employee name ID salary dept. ═══════ */ + @.1 = "Tyler Bennett ,E10297, 32000, D101" + @.2 = "John Rappl ,E21437, 47000, D050" + @.3 = "George Woltman ,E00127, 53500, D101" + @.4 = "Adam Smith ,E63535, 18000, D202" + @.5 = "Claire Buckman ,E39876, 27800, D202" + @.6 = "David McClellan ,E04242, 41500, D101" + @.7 = "Rich Holcomb ,E01234, 49500, D202" + @.8 = "Nathan Adams ,E41298, 21900, D050" + @.9 = "Richard Potter ,E43128, 15900, D101" + @.10 = "David Motsinger ,E27002, 19250, D202" + @.11 = "Tim Sampair ,E03033, 27000, D101" + @.12 = "Kim Arlich ,E10001, 57000, D190" + @.13 = "Timothy Grove ,E16398, 29900, D190" depts= - do j=1 until @.j=='' /*build the database elements. */ - parse var @.j name.j ',' id.j "," sal.j ',' dept.j - if wordpos(dept.j,depts)==0 then depts=depts dept.j - end /*j*/ + do j=1 until @.j=='' /*build database elements from @ array.*/ + parse var @.j name.j ',' id.j "," sal.j ',' dept.j . + if wordpos(dept.j,depts)==0 then depts=depts dept.j + end /*j*/ employees=j-1 #d=words(depts) -say employees 'employees,' #d "departments:" depts; say +say 'There are ' employees 'employees, ' #d "departments: " depts +say + do dep=1 for #d; say /*process each of the departments. */ + Xdept=word(depts,dep) /*current department being processed. */ + do topN; highSal=0 /*process the top N salaries. */ + h=0 /*point to the highest paid employee. */ + do e=1 for employees /*process each employee in department. */ + if dept.e\==Xdept | sal.e Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01. C.f: [[Topological sort/Extracted top item]]. + +There are two popular algorithms for topological sorting: +Kahn's 1962 topological sort, and depth-first search. + +[[wp: topological sorting]] + +Jason Sachs +[http://www.embeddedrelated.com/showarticle/799.php "Ten little algorithms, part 4: topological sort"]. + diff --git a/Task/Topological-sort/Fortran/topological-sort-3.f b/Task/Topological-sort/Fortran/topological-sort-3.f new file mode 100644 index 0000000000..3bb7de9bfe --- /dev/null +++ b/Task/Topological-sort/Fortran/topological-sort-3.f @@ -0,0 +1,37 @@ +subroutine tsort(nl,nd,idep,iord,no) + + implicit none + + integer,intent(in) :: nl + integer,intent(in) :: nd + integer,dimension(nd,2),intent(in) :: idep + integer,dimension(nl),intent(out) :: iord + integer,intent(out) :: no + + integer :: i,j,k,il,ir,ipl,ipr,ipos(nl) + + do i=1,nl + iord(i)=i + ipos(i)=i + end do + k=1 + do + j=k + k=nl+1 + do i=1,nd + il=idep(i,1) + ir=idep(i,2) + ipl=ipos(il) + ipr=ipos(ir) + if (il==ir .or. ipl>=k .or. iplparsed - depends=. (-.L:0"_1 #,.i.@#) names i.L:1 parsed - depends=. (~.@,&.> ;@:{L:0 1~)^:_ depends - assert.-.1 e. (i.@# e.S:0"0 ])depends - (-.&names ~.;parsed),names /: #@> depends -) + >dependencySort dependencies + std + ieee + dware + gtech + ramlib + std_cell_lib + synopsys + dw02 + dw05 + dw06 + dw07 + dw01 + dw04 + dw03 + des_system_lib diff --git a/Task/Topological-sort/J/topological-sort-3.j b/Task/Topological-sort/J/topological-sort-3.j new file mode 100644 index 0000000000..b37393374c --- /dev/null +++ b/Task/Topological-sort/J/topological-sort-3.j @@ -0,0 +1,3 @@ + dependencySort dependencies,'dw01 dw04',LF +|assertion failure: dependencySort +| -.1 e.(<0 1)|:depends diff --git a/Task/Topological-sort/J/topological-sort-4.j b/Task/Topological-sort/J/topological-sort-4.j new file mode 100644 index 0000000000..5071753fab --- /dev/null +++ b/Task/Topological-sort/J/topological-sort-4.j @@ -0,0 +1,8 @@ +depSort=: monad define + parsed=. <@;:;._2 y + names=. {.&>parsed + depends=. (-.L:0"_1 #,.i.@#) names i.L:1 parsed + depends=. (~.@,&.> ;@:{L:0 1~)^:_ depends + assert.-.1 e. (i.@# e.S:0"0 ])depends + (-.&names ~.;parsed),names /: #@> depends +) diff --git a/Task/Topological-sort/Ruby/topological-sort.rb b/Task/Topological-sort/Ruby/topological-sort.rb index 542eb9b5d9..5f420edbf4 100644 --- a/Task/Topological-sort/Ruby/topological-sort.rb +++ b/Task/Topological-sort/Ruby/topological-sort.rb @@ -9,8 +9,7 @@ def tsort_each_child(node, &block) depends = {} DATA.each do |line| - libs = line.split(' ') - key = libs.shift + key, *libs = line.split depends[key] = libs libs.each {|lib| depends[lib] ||= []} end @@ -20,7 +19,7 @@ def tsort_each_child(node, &block) depends["dw01"] << "dw04" p depends.tsort rescue TSort::Cyclic => e - puts "cycle detected: #{e}" + puts "\ncycle detected: #{e}" end __END__ diff --git a/Task/Topswops/Eiffel/topswops-1.e b/Task/Topswops/Eiffel/topswops-1.e index d87cedd44d..0dad84ce26 100644 --- a/Task/Topswops/Eiffel/topswops-1.e +++ b/Task/Topswops/Eiffel/topswops-1.e @@ -1,109 +1,111 @@ class TOPSWOPS + create make + feature - make(n: INTEGER) - local - perm,ar: ARRAY[INTEGER] - i,j,k, tcount, count: INTEGER - do - create perm_sol.make_empty - create solution.make_empty - from j:= 1 - until j> n - loop - create ar.make_filled (0, 1, j) - from - k:=1 - until - k>j - loop - ar[k]:=k - k:= k+1 - end - permute(ar, 1) - from - i:= 1 - until - i> perm_sol.count - loop - tcount:= 0 - from - until - perm_sol.at (i).at (1)=1 + make (n: INTEGER) + -- Topswop game. + local + perm, ar: ARRAY [INTEGER] + tcount, count: INTEGER + do + create perm_sol.make_empty + create solution.make_empty + across + 1 |..| n as c loop - perm_sol.at(i):=reverse_array(perm_sol.at(i)) - tcount:= tcount+1 - end - if tcount>count then - count:= tcount + create ar.make_filled (0, 1, c.item) + across + 1 |..| c.item as d + loop + ar [d.item] := d.item + end + permute (ar, 1) + across + 1 |..| perm_sol.count as e + loop + tcount := 0 + from + until + perm_sol.at (e.item).at (1) = 1 + loop + perm_sol.at (e.item) := reverse_array (perm_sol.at (e.item)) + tcount := tcount + 1 + end + if tcount > count then + count := tcount + end + end + solution.force (count, c.item) end - i:= i+1 - end - solution.force(count, j) - j:=j+1 end - end - solution: ARRAY[INTEGER] + + solution: ARRAY [INTEGER] feature {NONE} - perm_sol: ARRAY[ARRAY[INTEGER]] - reverse_array(ar:ARRAY[INTEGER]):ARRAY[INTEGER] - require - ar_not_void: ar /= void - local - i,j:INTEGER - new_array: ARRAY[INTEGER] - do - create new_array.make_empty - new_array.copy(ar) + perm_sol: ARRAY [ARRAY [INTEGER]] + + reverse_array (ar: ARRAY [INTEGER]): ARRAY [INTEGER] + -- Array with 'ar[1]' elements reversed. + require + ar_not_void: ar /= Void + local + i, j: INTEGER + do + create Result.make_empty + Result.deep_copy (ar) from - i:= 1 - j:=ar[1] + i := 1 + j := ar [1] until - i>j + i > j loop - new_array[i]:=ar[j] - new_array[j]:=ar[i] - i:=i+1 - j:=j-1 + Result [i] := ar [j] + Result [j] := ar [i] + i := i + 1 + j := j - 1 end - Result:= new_array ensure - same_length: ar.count = Result.count - end - + same_elements: across ar as a all Result.has (a.item) end + end -permute(a: ARRAY[INTEGER]; k: INTEGER) - require - ar_not_void: a.count>=1 - k_valid_index: k>0 - local - i,t: INTEGER - temp: ARRAY[INTEGER] - do - create temp.make_empty - if k=a.count then - across a as ar loop temp.force (ar.item, temp.count+1) end - perm_sol.force(temp, perm_sol.count+1) - else - from - i:= k - until - i> a.count - loop - t:= a[k] - a[k]:= a[i] - a[i]:= t - permute(a,k+1) - t:= a[k] - a[k]:= a[i] - a[i]:= t - i:= i+1 + permute (a: ARRAY [INTEGER]; k: INTEGER) + -- All permutations of array 'a' stored in perm_sol. + require + ar_not_void: a.count >= 1 + k_valid_index: k > 0 + local + i, t: INTEGER + temp: ARRAY [INTEGER] + do + create temp.make_empty + if k = a.count then + across + a as ar + loop + temp.force (ar.item, temp.count + 1) + end + perm_sol.force (temp, perm_sol.count + 1) + else + from + i := k + until + i > a.count + loop + t := a [k] + a [k] := a [i] + a [i] := t + permute (a, k + 1) + t := a [k] + a [k] := a [i] + a [i] := t + i := i + 1 + end + end end - end -end + end diff --git a/Task/Topswops/Eiffel/topswops-2.e b/Task/Topswops/Eiffel/topswops-2.e index 61664d3932..15443c0e5b 100644 --- a/Task/Topswops/Eiffel/topswops-2.e +++ b/Task/Topswops/Eiffel/topswops-2.e @@ -1,14 +1,21 @@ class APPLICATION -inherit - ARGUMENTS + create - make + make + feature + make - do - create ts.make (10) - across ts.solution as t loop io.put_string (t.item.out+"%N") end - end - ts: TOPSWOPS + do + create topswop.make (10) + across + topswop.solution as t + loop + io.put_string (t.item.out + "%N") + end + end + + topswop: TOPSWOPS + end diff --git a/Task/Towers-of-Hanoi/360-Assembly/towers-of-hanoi.360 b/Task/Towers-of-Hanoi/360-Assembly/towers-of-hanoi.360 new file mode 100644 index 0000000000..07d27adba3 --- /dev/null +++ b/Task/Towers-of-Hanoi/360-Assembly/towers-of-hanoi.360 @@ -0,0 +1,72 @@ +* Towers of Hanoi 08/09/2015 +HANOITOW CSECT + USING HANOITOW,R12 r12 : base register + LR R12,R15 establish base register + ST R14,SAVE14 save r14 +BEGIN LH R2,=H'4' n <=== + L R3,=C'123 ' stating position + BAL R14,MOVE r1=move(m,n) +RETURN L R14,SAVE14 restore r14 + BR R14 return to caller +SAVE14 DS F static save r14 +PG DC CL44'xxxxxxxxxxxx Move disc from pole X to pole Y' +NN DC F'0' +POLEX DS F current poles +POLEN DS F new poles +* .... recursive subroutine move(n, poles) [r2,r3] +MOVE LR R10,R11 save stackptr (r11) in r10 temp + LA R1,STACKLEN amount of storage required + GETMAIN RU,LV=(R1) allocate storage for stack + USING STACKDS,R11 make storage addressable + LR R11,R1 establish stack addressability + ST R14,SAVE14M save previous r14 + ST R10,SAVE11M save previous r11 + LR R1,R5 restore saved argument r5 +BEGINM STM R2,R3,STACK push arguments to stack + ST R3,POLEX + CH R2,=H'1' if n<>1 + BNE RECURSE then goto recurse + L R1,NN + LA R1,1(R1) nn=nn+1 + ST R1,NN + XDECO R1,PG nn + MVC PG+33(1),POLEX+0 from + MVC PG+43(1),POLEX+1 to + XPRNT PG,44 print "move disk from to" + B RETURNM +RECURSE L R2,N n + BCTR R2,0 n=n-1 + MVC POLEN+0(1),POLES+0 from + MVC POLEN+1(1),POLES+2 via + MVC POLEN+2(1),POLES+1 to + L R3,POLEN new poles + BAL R14,MOVE call move(n-1,from,via,to) + LA R2,1 n=1 + MVC POLEN,POLES + L R3,POLEN new poles + BAL R14,MOVE call move(1,from,to,via) + L R2,N n + BCTR R2,0 n=n-1 + MVC POLEN+0(1),POLES+2 via + MVC POLEN+1(1),POLES+1 to + MVC POLEN+2(1),POLES+0 from + L R3,POLEN new poles + BAL R14,MOVE call move(n-1,via,to,from) +RETURNM LM R2,R3,STACK pull arguments from stack + LR R1,R11 current stack + L R14,SAVE14M restore r14 + L R11,SAVE11M restore r11 + LA R0,STACKLEN amount of storage to free + FREEMAIN A=(R1),LV=(R0) free allocated storage + BR R14 return to caller + LTORG + DROP R12 base no longer needed +STACKDS DSECT dynamic area +SAVE14M DS F saved r14 +SAVE11M DS F saved r11 +STACK DS 0F stack +N DS F r2 n +POLES DS F r3 poles +STACKLEN EQU *-STACKDS + YREGS + END HANOITOW diff --git a/Task/Towers-of-Hanoi/ALGOL-W/towers-of-hanoi.alg b/Task/Towers-of-Hanoi/ALGOL-W/towers-of-hanoi.alg new file mode 100644 index 0000000000..089d609a59 --- /dev/null +++ b/Task/Towers-of-Hanoi/ALGOL-W/towers-of-hanoi.alg @@ -0,0 +1,10 @@ +begin + procedure move ( integer value n, from, to, via ) ; + if n > 0 then begin + move( n - 1, from, via, to ); + write( i_w := 1, s_w := 0, "Move disk from peg: ", from, " to peg: ", to ); + move( n - 1, via, to, from ) + end move ; + + move( 4, 1, 2, 3 ) +end. diff --git a/Task/Towers-of-Hanoi/Batch-File/towers-of-hanoi.bat b/Task/Towers-of-Hanoi/Batch-File/towers-of-hanoi.bat new file mode 100644 index 0000000000..ba71b24870 --- /dev/null +++ b/Task/Towers-of-Hanoi/Batch-File/towers-of-hanoi.bat @@ -0,0 +1,28 @@ +@echo off +setlocal enabledelayedexpansion + + %==The main thing==% + %==First param - Number of disks==% + %==Second param - Start pole==% + %==Third param - End pole==% + %==Fourth param - Helper pole==% +call :move 4 START END HELPER +echo. +pause +exit /b 0 + + %==The "function"==% +:move + setlocal + set n=%1 + set from=%2 + set to=%3 + set via=%4 + + if %n% gtr 0 ( + set /a x=!n!-1 + call :move !x! %from% %via% %to% + echo Move top disk from pole %from% to pole %to%. + call :move !x! %via% %to% %from% + ) + exit /b 0 diff --git a/Task/Towers-of-Hanoi/Brainf---/towers-of-hanoi.bf b/Task/Towers-of-Hanoi/Brainf---/towers-of-hanoi.bf new file mode 100644 index 0000000000..0f1748498f --- /dev/null +++ b/Task/Towers-of-Hanoi/Brainf---/towers-of-hanoi.bf @@ -0,0 +1,153 @@ +[ +This implementation is recursive and uses +a stack, consisting of frames that are 8 +bytes long. The layout is as follows: + +Byte Description + 0 recursion flag + (the program stops if the flag is + zero) + 1 the step which is currently + executed + 4 means a call to + move(a, c, b, n - 1) + 3 means a call to + move(a, b, c, 1) + 2 means a call to + move(b, a, c, n - 1) + 1 prints the source and dest pile + 2 flag to check whether the current + step has already been done or if + it still must be executed + 3 the step which will be executed + in the next loop + 4 the source pile + 5 the helper pile + 6 the destination pile + 7 the number of disks to move + +The first stack frame (0 0 0 0 0 0 0 0) +is used to abort the recursion. +] + +>>>>>>>> + +These are the parameters for the program +(1 4 1 0 'a 'b 'c 5) ++>++++>+>> +>>>>++++++++[<++++++++++++>-]< +[<<<+>+>+>-]<<<+>++>+++>+++++> +<<<<<<<< + +[> while (recurse) + [- if (step gt 0) + >[-]+< todo = 1 + [- if (step gt 1) + [- if (step gt 2) + [- if (step gt 3) + >>+++<< next = 3 + >-< todo = 0 + >>>>>>[>+>+<<-]>[<+>-]> n dup + - + [[-] if (sub(n 1) gt 0) + <+>>>++++> push (1 0 0 4) + + copy and push a + <<<<<<<<[>>>>>>>>+>+ + <<<<<<<<<-]>>>>>>>> + >[<<<<<<<<<+>>>>>>>>>-]< > + + copy and push c + <<<<<<<[>>>>>>>+>+ + <<<<<<<<-]>>>>>>> + >[<<<<<<<<+>>>>>>>>-]< > + + copy and push b + <<<<<<<<<[>>>>>>>>>+>+ + <<<<<<<<<<-]>>>>>>>>> + >[<<<<<<<<<<+>>>>>>>>>>-]< > + + copy n and push sub(n 1) + <<<<<<<<[>>>>>>>>+>+ + <<<<<<<<<-]>>>>>>>> + >[<<<<<<<<<+>>>>>>>>>-]< - + >> + ] + <<<<<<<< + ] + >[-< if ((step gt 2) and todo) + >>++<< next = 2 + >>>>>>> + +>>>+> push 1 0 0 1 a b c 1 + <<<<<<<<[>>>>>>>>+>+ + <<<<<<<<<-]>>>>>>>> + >[<<<<<<<<<+>>>>>>>>>-]< > a + <<<<<<<<[>>>>>>>>+>+ + <<<<<<<<<-]>>>>>>>> + >[<<<<<<<<<+>>>>>>>>>-]< > b + <<<<<<<<[>>>>>>>>+>+ + <<<<<<<<<-]>>>>>>>> + >[<<<<<<<<<+>>>>>>>>>-]< > c + + >> + >]< + ] + >[-< if ((step gt 1) and todo) + >>>>>>[>+>+<<-]>[<+>-]> n dup + - + [[-] if (n sub 1 gt 0) + <+>>>++++> push (1 0 0 4) + + copy and push b + <<<<<<<[>>>>>>>+ + <<<<<<<-]>>>>>>> + >[<<<<<<<<+>>>>>>>>-]< > + + copy and push a + <<<<<<<<<[>>>>>>>>>+ + <<<<<<<<<-]>>>>>>>>> + >[<<<<<<<<<<+>>>>>>>>>>-]< > + + copy and push c + <<<<<<<<[>>>>>>>>+ + <<<<<<<<-]>>>>>>>> + >[<<<<<<<<<+>>>>>>>>>-]< > + + copy n and push sub(n 1) + <<<<<<<<[>>>>>>>>+>+ + <<<<<<<<<-]>>>>>>>> + >[<<<<<<<<<+>>>>>>>>>-]< - + >> + ] + <<<<<<<< + >]< + ] + >[-< if ((step gt 0) and todo) + >>>>>>> + >++++[<++++++++>-]< + >>++++++++[<+++++++++>-]<++++ + >>++++++++[<++++++++++++>-]<+++++ + >>+++++++++[<++++++++++++>-]<+++ + <<< + >.+++++++>.++.--.<<. + >>-.+++++.----.<<. + >>>.<---.+++.>+++.+.+.<.<<. + >.>--.+++++.---.++++. + -------.+++.<<. + >>>++.-------.-.<<<. + >+.>>+++++++.---.-----.<<<. + <<<<.>>>>. + >>----.>++++++++.<+++++.<<. + >.>>.---.-----.<<<. + <<.>>++++++++++++++. + >>>[-]<[-]<[-]<[-] + +++++++++++++.---.[-] + <<<<<<< + >]< + >>[<<+>>-]<< step = next + ] + return with clear stack frame + <[-]>[-]>[-]>[-]>[-]>[-]>[-]>[-]<<<<<< + <<<<<<<< + >>[<<+>>-]<< step = next + < +] diff --git a/Task/Towers-of-Hanoi/Elixir/towers-of-hanoi.elixir b/Task/Towers-of-Hanoi/Elixir/towers-of-hanoi.elixir new file mode 100644 index 0000000000..c2cde68925 --- /dev/null +++ b/Task/Towers-of-Hanoi/Elixir/towers-of-hanoi.elixir @@ -0,0 +1,14 @@ +defmodule RC do + def hanoi(n) when 0 0) { - move(n-1, a, c, b); - console.log("Move disk from " + a + " to " + c); - move(n-1, b, a, c); - } + if (n > 0) { + move(n-1, a, c, b); + console.log("Move disk from " + a + " to " + c); + move(n-1, b, a, c); + } } move(4, "A", "B", "C"); diff --git a/Task/Towers-of-Hanoi/LOLCODE/towers-of-hanoi.lol b/Task/Towers-of-Hanoi/LOLCODE/towers-of-hanoi.lol new file mode 100644 index 0000000000..4c1e736d0e --- /dev/null +++ b/Task/Towers-of-Hanoi/LOLCODE/towers-of-hanoi.lol @@ -0,0 +1,20 @@ +HAI + +HOW DUZ I HANOI YR N AN YR SRC AN YR DST AN YR VIA + BTW VISIBLE SMOOSH "HANOI N=" N " SRC=" SRC " DST=" DST " VIA=" VIA MKAY + BOTH SAEM N AN 0, O RLY? + YA RLY + BTW VISIBLE "Done." + GTFO + NO WAI + I HAS A LOWER ITZ DIFF OF N AN 1 + HANOI DST VIA SRC LOWER + VISIBLE SMOOSH "Move disc " N " from " SRC ... + " to " DST MKAY + HANOI SRC DST VIA LOWER + OIC +IF U SAY SO + +HANOI 2 3 1 4 BTW requires reversed arguments? + +KTHXBYE diff --git a/Task/Towers-of-Hanoi/PowerShell/towers-of-hanoi.psh b/Task/Towers-of-Hanoi/PowerShell/towers-of-hanoi.psh new file mode 100644 index 0000000000..51cb6fea55 --- /dev/null +++ b/Task/Towers-of-Hanoi/PowerShell/towers-of-hanoi.psh @@ -0,0 +1,10 @@ +function hanoi($n, $a, $b, $c) { + if($n -eq 1) { + "$a -> $c" + } else{ + hanoi ($n - 1) $a $c $b + hanoi 1 $a $b $c + hanoi ($n - 1) $b $a $c + } +} +hanoi 3 "A" "B" "C" diff --git a/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-1.rexx b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-1.rexx index 7d7cee010a..51a2cf2f24 100644 --- a/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-1.rexx +++ b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-1.rexx @@ -1,21 +1,21 @@ -/*REXX pgm shows the moves to solve the Tower of Hanoi (with 3 disks). */ -parse arg N . /*get optional # towers from C.L.*/ -if N=='' then N=3 /*Not given? Use default 3 towers*/ -#=0; z=2**N - 1 /*number of ring moves so far. */ -call mov 1, 3, N /*move top ring, then recurse··· */ +/*REXX program shows the moves to solve the Tower of Hanoi (with N disks).*/ +parse arg N . /*get optional number of disks from CL.*/ +if N=='' then N=3 /*Not given? Then use default 3 towers*/ +#=0; z=2**N - 1 /*# disk moves so far; # of min moves.*/ +call mov 1, 3, N /*move the top disk, then recurse ··· */ say -say 'The minimum number of moves to solve a ' N " Tower of Hanoi is " z -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────DSK subroutine───────────────────────────*/ -dsk: #=#+1 /*bump the move counter by one. */ -say 'step' right(#,length(z))": move disk on tower" arg(1) '───►' arg(2) -return -/*─────────────────────────────MOV subroutine───────────────────────────*/ +say 'The minimum number of moves to solve a ' N"-disk Tower of Hanoi is " z +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +dsk: #=#+1 /*bump the (disk) move counter by one. */ + say 'step' right(#,length(z))": move disk on tower" arg(1) '───►' arg(2) + return /* [↑] display the move message (text)*/ +/*────────────────────────────────────────────────────────────────────────────*/ mov: procedure expose # z; parse arg @1, @2, @3 -if @3==1 then call dsk @1, @2 - else do - call mov @1, 6-@1-@2, @3-1 - call mov @1, @2, 1 - call mov 6-@1-@2, @2, @3-1 - end -return + if @3==1 then call dsk @1, @2 + else do + call mov @1, 6-@1-@2, @3-1 + call mov @1, @2, 1 + call mov 6-@1-@2, @2, @3-1 + end + return diff --git a/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx index e22ea1f9e2..c6c818562d 100644 --- a/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx +++ b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx @@ -1,82 +1,69 @@ -/*REXX pgm shows pictorial moves to solve Tower of Hanoi (with N disks).*/ -parse arg N .; if N=='' then N=3 /*Not given? Use default 3 disks.*/ -sw=80; wp=sw%3-1; blanks=center('',wp) /*define some default variables. */ -c.1=sw%3%2 +/*REXX program shows pictorial moves to solve Tower of Hanoi (with N disks).*/ +parse arg N .; if N=='' then N=3 /*Not given? Then use default 3 disks.*/ +sw=80; wp=sw%3-1; blanks=left('',wp) /*define some default REXX variables. */ +c.1=sw%3%2 /* [↑] SW: assume default Screen Width*/ c.2=sw%2-1 c.3=sw-1-c.1-1 -#=0; z=2**N-1; movek=z -@abc='abcdefghijklmnopqrstuvwxyN' /*dithering chars when many disks*/ -ebcdic= 'f0'x==0 /*determine if EBCDIC or ASCII*/ -if ebcdic then do - bar='bf'x;ar='df'x;boxen='db9f9caf'x;tl='ac'x;tr='bf'x;bl='ab'x;br='bb'x;vert='fa'x;down='9a'x +#=0; z=2**N-1; moveK=z /*#moves; min# of moves; where to move.*/ +@abc='abcdefghijklmnopqrstuvwxyN' /*dithering chars when many disks used.*/ +ebcdic= ('f0'x==0) /*determine if EBCDIC or ASCII machine.*/ + +if ebcdic then do; bar='bf'x; ar="df"x; boxen='db9f9caf'x; down="9a"x + tr='bc'x; bl="ab"x; br='bb'x; vert="fa"x; tl='ac'x end - else do - bar='c4'x;ar='10'x;boxen='b0b1b2db'x;tl='da'x;tr='bf'x;bl='c0'x;br='d9'x;vert='b3'x;down='19'x + else do; bar='c4'x; ar="10"x; boxen='b0b1b2db'x; down="18"x + tr='bf'x; bl="c0"x; br='d9'x; vert="b3"x; tl='da'x end -verts=vert || vert -downs=down || down -Tcorners=tl || tr -Bcorners=bl || br -box=left(boxen,1); boxchars=boxen || @abc -bararrow=bar || bar || ar -$.=0; $.1=N; k=N; kk=k+k - do j=1 for N - @.3.j=blanks; @.2.j=blanks - @.1.j=center(copies(box,kk),wp) - if N<=length(boxchars) then @.1.j=translate(@.1.j, , - substr(boxchars,kk%2,1),box) +verts= vert || vert; Tcorners= tl || tr +downs= down || down; Bcorners= bl || br +box = left(boxen,1); boxChars= boxen || @abc +$.=0; $.1=N; k=N; kk=k+k + + do j=1 for N; @.3.j=blanks; @.2.j=blanks; @.1.j=center(copies(box,kk),wp) + if N<=length(boxChars) then @.1.j=translate(@.1.j,,substr(boxChars,kk%2,1),box) kk=kk-2 - end /*j*/ + end /*j*/ /*populate the tower of Hanoi spindles.*/ -call showtowers; call mov 1,3,N -say -say "The minimum number of moves to solve a " N ' Tower of Hanoi is ' z +call showtowers; call mov 1,3,N; say +say 'The minimum number of moves to solve a ' N"-disk Tower of Hanoi is " z exit -/*─────────────────────────────MOV subroutine───────────────────────────*/ -mov: if arg(3)==1 then call rng arg(1) arg(2) - else do - call mov arg(1), 6-arg(1)-arg(2), arg(3)-1 - call mov arg(1), arg(2), 1 - call mov 6-arg(1)-arg(2),arg(2), arg(3)-1 +/*─────────────────────────────MOV subroutine─────────────────────────────────*/ +mov: if arg(3)==1 then call dsk arg(1) arg(2) + else do; call mov arg(1), 6-arg(1)-arg(2), arg(3)-1 + call mov arg(1), arg(2), 1 + call mov 6-arg(1)-arg(2), arg(2), arg(3)-1 end return -/*─────────────────────────────RNG subroutine───────────────────────────*/ -rng: parse arg from dest; #=#+1; pp= +/*─────────────────────────────DSK subroutine─────────────────────────────────*/ +dsk: parse arg from dest; #=#+1; pp= if from==1 then do - pp=overlay(bl,pp,c.1) - pp=overlay(bar,pp,c.1+1,c.dest-c.1-1,bar) - pp=pp || tr - end -if from==3 then do - pp=overlay(br,pp,c.3) - pp=overlay(bar,pp,c.dest+1,c.3-c.dest-1,bar) - pp=overlay(tl,pp,c.dest) + pp=overlay(bl, pp, c.1) + pp=overlay(bar, pp, c.1+1, c.dest-c.1-1, bar) || tr end if from==2 then do - lpost=min(2,dest) - hpost=max(2,dest) - if dest==1 then do - pp=overlay(tl,pp,c.1) - pp=overlay(bar,pp,c.1+1,c.2-c.1-1,bar) - pp=pp || br - end - if dest==3 then do - pp=overlay(bl,pp,c.2) - pp=overlay(bar,pp,c.2+1,c.3-c.2-1,bar) - pp=pp || tr - end + lpost=min(2, dest) + hpost=max(2, dest) + if dest==1 then do + pp=overlay(tl, pp, c.1) + pp=overlay(bar, pp, c.1+1, c.2-c.1-1, bar)||br + end + if dest==3 then do + pp=overlay(bl, pp,c.2) + pp=overlay(bar, pp,c.2+1, c.3-c.2-1, bar) ||tr + end end -say translate(pp,downs,Bcorners||Tcorners||bar); say overlay(movek,pp,1) -say translate(pp,verts,Tcorners||Bcorners||bar) -say translate(pp,downs,Tcorners||Bcorners||bar) -movek=movek-1 -$.from=$.from-1; $.dest=$.dest+1; _f=$.from+1; _t=$.dest -@.dest._t=@.from._f; @.from._f=blanks -call showtowers -return -/*─────────────────────────────SHOWTOWERS subroutine────────────────────*/ -showtowers: do j=N by -1 for N - _=@.1.j @.2.j @.3.j; if _\='' then say _ - end /*j*/ +if from==3 then do + pp=overlay(br, pp, c.3) + pp=overlay(bar, pp, c.dest+1, c.3-c.dest-1, bar) + pp=overlay(tl, pp, c.dest) + end +say translate(pp, downs, Bcorners || Tcorners || bar); say overlay(moveK,pp,1) +say translate(pp, verts, Tcorners || Bcorners || bar) +say translate(pp, downs, Tcorners || Bcorners || bar); moveK=moveK-1 +$.from=$.from-1; $.dest=$.dest+1; _f=$.from+1; _t=$.dest +@.dest._t=@.from._f; @.from._f=blanks; call showtowers return +/*─────────────────────────────SHOWTOWERS subroutine──────────────────────────*/ +showtowers: do j=N by -1 for N; _=@.1.j @.2.j @.3.j; if _\='' then say _; end + return diff --git a/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust b/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust index 55b7ed1002..6bc4a42742 100644 --- a/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust +++ b/Task/Towers-of-Hanoi/Rust/towers-of-hanoi.rust @@ -1,11 +1,11 @@ -fn move(n: int, from: int, to: int, via: int) { - if n > 0 { - move(n - 1, from, via, to); - println!("Move disk from pole {:d} to pole {:d}", from, to); - move(n - 1, via, to, from); - } +fn move_(n: i32, from: i32, to: i32, via: i32) { + if n > 0 { + move_(n - 1, from, via, to); + println!("Move disk from pole {} to pole {}", from, to); + move_(n - 1, via, to, from); + } } fn main() { - move(4, 1,2,3); + move_(4, 1,2,3); } diff --git a/Task/Towers-of-Hanoi/VBScript/towers-of-hanoi.vb b/Task/Towers-of-Hanoi/VBScript/towers-of-hanoi.vb new file mode 100644 index 0000000000..c70b994863 --- /dev/null +++ b/Task/Towers-of-Hanoi/VBScript/towers-of-hanoi.vb @@ -0,0 +1,11 @@ +Sub Move(n,fromPeg,toPeg,viaPeg) + If n > 0 Then + Move n-1, fromPeg, viaPeg, toPeg + WScript.StdOut.Write "Move disk from " & fromPeg & " to " & toPeg + WScript.StdOut.WriteBlankLines(1) + Move n-1, viaPeg, toPeg, fromPeg + End If +End Sub + +Move 4,1,2,3 +WScript.StdOut.Write("Towers of Hanoi puzzle completed!") diff --git a/Task/Trabb-Pardo-Knuth-algorithm/00DESCRIPTION b/Task/Trabb-Pardo-Knuth-algorithm/00DESCRIPTION index c5ba65c870..2c882a9a18 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/00DESCRIPTION +++ b/Task/Trabb-Pardo-Knuth-algorithm/00DESCRIPTION @@ -1,4 +1,6 @@ -The TPK algorithm is an early example of programming chrestomathy. It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report [http://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-76-562_EarlyDevelPgmgLang_Aug76.pdf The Early Development of Programming Languages]. The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. +The TPK algorithm is an early example of a programming chrestomathy. +It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report [http://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-76-562_EarlyDevelPgmgLang_Aug76.pdf The Early Development of Programming Languages]. +The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm. From the [[wp:Trabb Pardo–Knuth algorithm|wikipedia entry]]: diff --git a/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-W/trabb-pardo-knuth-algorithm.alg b/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-W/trabb-pardo-knuth-algorithm.alg new file mode 100644 index 0000000000..5de656ea83 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/ALGOL-W/trabb-pardo-knuth-algorithm.alg @@ -0,0 +1,13 @@ +begin + real y; real array a( 0 :: 10 ); + real procedure f( real value t ); + sqrt(abs(t))+5*t*t*t; + for i:=0 until 10 do read( a(i) ); + r_format := "A"; r_w := 9; r_d := 4; + for i:=10 step -1 until 0 do + begin + y:=f(a(i)); + if y > 400 then write( "TOO LARGE" ) + else write( y ); + end +end. diff --git a/Task/Trabb-Pardo-Knuth-algorithm/C++/trabb-pardo-knuth-algorithm.cpp b/Task/Trabb-Pardo-Knuth-algorithm/C++/trabb-pardo-knuth-algorithm.cpp index b5c7ae65cb..38a4e13622 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/C++/trabb-pardo-knuth-algorithm.cpp +++ b/Task/Trabb-Pardo-Knuth-algorithm/C++/trabb-pardo-knuth-algorithm.cpp @@ -6,12 +6,10 @@ int main( ) { std::vector input( 11 ) , results( 11 ) ; - double number = 0.0 ; std::cout << "Please enter 11 numbers!\n" ; - for ( int i = 0 ; i < input.size( ) ; i++ ) { - std::cin >> number ; - input[ i ] = number ; - } + for ( int i = 0 ; i < input.size( ) ; i++ ) + std::cin >> input[i]; + std::transform( input.begin( ) , input.end( ) , results.begin( ) , [ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ; for ( int i = 10 ; i > -1 ; i-- ) { diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Fortran/trabb-pardo-knuth-algorithm.f b/Task/Trabb-Pardo-Knuth-algorithm/Fortran/trabb-pardo-knuth-algorithm-1.f similarity index 100% rename from Task/Trabb-Pardo-Knuth-algorithm/Fortran/trabb-pardo-knuth-algorithm.f rename to Task/Trabb-Pardo-Knuth-algorithm/Fortran/trabb-pardo-knuth-algorithm-1.f diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Fortran/trabb-pardo-knuth-algorithm-2.f b/Task/Trabb-Pardo-Knuth-algorithm/Fortran/trabb-pardo-knuth-algorithm-2.f new file mode 100644 index 0000000000..c1bb832e9c --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Fortran/trabb-pardo-knuth-algorithm-2.f @@ -0,0 +1,16 @@ +C THE TPK ALGORITH - FORTRAN I - 1957 TPK00010 + FTPKF(X)=SQRTF(ABSF(X))+5.0*X**3 TPK00020 + DIMENSION A(11) TPK00030 + READ 100,A TPK00040 + 100 FORMAT(6F12.4/) TPK00050 + DO 3 I=1,11 TPK00060 + J=12-I TPK00070 + Y=FTPKF(A(J)) TPK00080 + IF (Y-400.0)2,2,1 TPK00090 + 1 PRINT 301,I,A(J) TPK00100 + 301 FORMAT(I10,F12.7,18H *** TOO LARGE ***) TPK00110 + GO TO 10 TPK00120 + 2 PRINT 302,I,A(J),Y TPK00130 + 302 FORMAT(I10,2F12.7) TPK00140 + 3 CONTINUE TPK00150 + STOP 0 TPK00160 diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PureBasic/trabb-pardo-knuth-algorithm.purebasic b/Task/Trabb-Pardo-Knuth-algorithm/PureBasic/trabb-pardo-knuth-algorithm.purebasic index d1eac8940d..6816a526bd 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/PureBasic/trabb-pardo-knuth-algorithm.purebasic +++ b/Task/Trabb-Pardo-Knuth-algorithm/PureBasic/trabb-pardo-knuth-algorithm.purebasic @@ -37,7 +37,7 @@ If OpenConsole() Until entriesAreValid = 1 ForEach numbers() - output$ = "f(" + RTrim(RTrim(StrD(numbers(), 3), "0"), ".") + ") = " + output$ = "f(" + RTrim(RTrim(StrD(numbers(), 3), "0"), ".") + ") = " result.d = f(numbers()) If result > 400 output$ + "Too Large" diff --git a/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx b/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx index 336270640c..09fb34a819 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx +++ b/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx @@ -1,49 +1,45 @@ -/*REXX program to implement the Trabb-Pardo-Knuth algorithm for N nums.*/ -N=11 /*N is the number of numbers. */ -maxValue=400 /*the maximum value f(x) can have*/ -precDigs=200 /*compute with this many digits. */ -showDigs=20 /*...but only show this many digs*/ -numeric digits precDigs /*the number of digits precision.*/ -prompt='enter' N "numbers for the Trabb-Pardo-Knuth algorithm: (or Quit)" -say ' _____ ' /*vinculum.*/ +/*REXX program to implement the Trabb─Pardo-Knuth algorithm for N numbers.*/ +N=11 /*N is the number of numbers to be used*/ +maxValue=400 /*the maximum value f(x) can have. */ +compDigs=200 /*compute with this many decimal digits*/ +showDigs=20 /* ··· but only show this many digits.*/ +numeric digits compDigs /*the number of digits precision to use*/ +say ' _____ ' /*vinculum.*/ say 'function: ƒ(x) ≡ √ │x│ + (5 * x^3)' -/*██████████████████████████████████████████████████████████████████████*/ - do ask=0; say; say prompt; say; parse pull yyyU . 1 yyy; say - upper yyyU; if abbrev('QUIT',yyyU,1) then exit - - do validate=0 - select - when yyy='' then say 'no numbers entered' - when words(yyy)N then say 'too many numbers entered' - otherwise leave validate - end /*select*/ - iterate ask - end /*validate*/ - do j=1 for N; _=word(yyy,j) - if \datatype(_,'N') then do - say _ "isn't numeric" - iterate ask - end - end /*j*/ - leave ask - end /*ask*/ -say 'numbers entered:' yyy; say -/*██████████████████████████████████████████████████████████████████████*/ - do i=N by -1 to 1; p=word(yyy,i)/1 /*process #s in reverse.*/ - g=f(p) - numeric digits showdigs; g=g/1 /*scale down the result.*/ - if g>maxValue then say 'f('p") is > " maxValue ' ['g"]" - else say 'f('p") = " g /*show the (good) result*/ - numeric digits precDigs /*re-instate big digits.*/ +prompt= 'enter ' N " numbers for the Trabb─Pardo─Knuth algorithm: (or Quit)" +/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ */ + do ask=0; say; say prompt; say; pull $; say /* ▒ */ + if abbrev('QUIT',$,1) then exit /*does the user want to QUIT this pgm? */ /* ▒ */ + ok=0 /* ▒ */ + select /*validate that there are N numbers. */ /* ▒ */ + when $='' then say 'no numbers entered' /* ▒ */ + when words($)N then say 'too many numbers entered' /* ▒ */ + otherwise ok=1 /* ▒ */ + end /*select*/ /* ▒ */ + if \ok then iterate /* [↓] is max width*/ /* ▒ */ + w=0; do v=1 for N; _=word($,v); w=max(w,length(_)) /* ▒ */ + if datatype(_,'N') then iterate /*numeric ? */ /* ▒ */ + say _ "isn't numeric"; iterate ask /* ▒ */ + end /*v*/ /* ▒ */ + leave /* ▒ */ + end /*ask*/ /* ▒ */ +say 'numbers entered: ' $; say /* ▒ */ +/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ */ + do i=N by -1 to 1; #=word($,i)/1 /*process nums in reverse. */ + numeric digits compDigs; g=f(#) /*for func. ƒ, use big digs*/ + numeric digits showdigs; g=g/1 /*scale down output digits.*/ + gw=right('ƒ('#") ",w+7) /*nice formatted ƒ(number)*/ + if g>maxValue then say gw "is > " maxValue ' ['g"]" + else say gw " = " g /*display the (good) result*/ end /*i*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────F function──────────────────────────*/ -f: procedure; arg x; return sqrt(abs(x)) + 5 * x**3 -/*──────────────────────────────────SQRT function───────────────────────*/ -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 +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +f: procedure; parse arg x; return sqrt(abs(x)) + 5 * x**3 +/*────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Scala/trabb-pardo-knuth-algorithm.scala b/Task/Trabb-Pardo-Knuth-algorithm/Scala/trabb-pardo-knuth-algorithm.scala new file mode 100644 index 0000000000..ab953fe86f --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Scala/trabb-pardo-knuth-algorithm.scala @@ -0,0 +1,26 @@ +object TPKa extends App { + final val numbers = scala.collection.mutable.MutableList[Double]() + final val in = new java.util.Scanner(System.in) + while (numbers.length < CAPACITY) { + print("enter a number: ") + try { + numbers += in.nextDouble() + } + catch { + case _: Exception => + in.next() + println("invalid input, try again") + } + } + + numbers reverseMap { x => + val fx = Math.pow(Math.abs(x), .5D) + 5D * (Math.pow(x, 3)) + if (fx < THRESHOLD) + print("%8.3f -> %8.3f\n".format(x, fx)) + else + print("%8.3f -> %s\n".format(x, Double.PositiveInfinity.toString)) + } + + private final val THRESHOLD = 400D + private final val CAPACITY = 11 +} diff --git a/Task/Trabb-Pardo-Knuth-algorithm/VBScript/trabb-pardo-knuth-algorithm.vb b/Task/Trabb-Pardo-Knuth-algorithm/VBScript/trabb-pardo-knuth-algorithm.vb new file mode 100644 index 0000000000..8bb0e47935 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/VBScript/trabb-pardo-knuth-algorithm.vb @@ -0,0 +1,20 @@ +Function tpk(s) + arr = Split(s," ") + For i = UBound(arr) To 0 Step -1 + n = fx(CDbl(arr(i))) + If n > 400 Then + WScript.StdOut.WriteLine arr(i) & " = OVERFLOW" + Else + WScript.StdOut.WriteLine arr(i) & " = " & n + End If + Next +End Function + +Function fx(x) + fx = Sqr(Abs(x))+5*x^3 +End Function + +'testing the function +WScript.StdOut.Write "Please enter a series of numbers:" +list = WScript.StdIn.ReadLine +tpk(list) diff --git a/Task/Tree-traversal/AWK/tree-traversal.awk b/Task/Tree-traversal/AWK/tree-traversal.awk new file mode 100644 index 0000000000..2291c476e0 --- /dev/null +++ b/Task/Tree-traversal/AWK/tree-traversal.awk @@ -0,0 +1,89 @@ +function preorder(tree, node, res, child) { + if (node == "") + return + res[res["count"]++] = node + split(tree[node], child, ",") + preorder(tree,child[1],res) + preorder(tree,child[2],res) +} + +function inorder(tree, node, res, child) { + if (node == "") + return + split(tree[node], child, ",") + inorder(tree,child[1],res) + res[res["count"]++] = node + inorder(tree,child[2],res) +} + +function postorder(tree, node, res, child) { + if (node == "") + return + split(tree[node], child, ",") + postorder(tree,child[1], res) + postorder(tree,child[2], res) + res[res["count"]++] = node +} + +function levelorder(tree, node, res, nextnode, queue, child) { + if (node == "") + return + + queue["tail"] = 0 + queue[queue["head"]++] = node + + while (queue["head"] - queue["tail"] >= 1) { + + nextnode = queue[queue["tail"]] + delete queue[queue["tail"]++] + + res[res["count"]++] = nextnode + + split(tree[nextnode], child, ",") + if (child[1] != "") + queue[queue["head"]++] = child[1] + if (child[2] != "") + queue[queue["head"]++] = child[2] + } + delete queue +} + +BEGIN { + tree["1"] = "2,3" + tree["2"] = "4,5" + tree["3"] = "6," + tree["4"] = "7," + tree["5"] = "," + tree["6"] = "8,9" + tree["7"] = "," + tree["8"] = "," + tree["9"] = "," + + preorder(tree,"1",result) + printf "preorder:\t" + for (n = 0; n < result["count"]; n += 1) + printf result[n]" " + printf "\n" + delete result + + inorder(tree,"1",result) + printf "inorder:\t" + for (n = 0; n < result["count"]; n += 1) + printf result[n]" " + printf "\n" + delete result + + postorder(tree,"1",result) + printf "postorder:\t" + for (n = 0; n < result["count"]; n += 1) + printf result[n]" " + printf "\n" + delete result + + levelorder(tree,"1",result) + printf "level-order:\t" + for (n = 0; n < result["count"]; n += 1) + printf result[n]" " + printf "\n" + delete result +} diff --git a/Task/Tree-traversal/J/tree-traversal-10.j b/Task/Tree-traversal/J/tree-traversal-10.j new file mode 100644 index 0000000000..433bf5355c --- /dev/null +++ b/Task/Tree-traversal/J/tree-traversal-10.j @@ -0,0 +1,53 @@ +dataorder=: /:@data reorder ] +levelorder=: /:@depth@parent reorder ] + +inorder=: inperm@parent reorder ] +inperm=:3 :0 + chil=. childinds y + node=. {.I.(= i.@#) y + todo=. i.0 2 + r=. i.0 + whilst. (#todo)+.0<:node do. + if. 0 <: node do. + if. 0 <: {.ch=. node{chil do. + todo=. todo, node,{:ch + node=. {.ch + else. + r=. r, node + node=. _1 end. + else. + r=. r, {.ch=. {: todo + todo=. }: todo + node=. {:ch end. end. + r +) + +postorder=: postperm@parent reorder ] +postperm=:3 :0 + chil=. 0,1+childinds y + todo=. 1+I.(= i.@#) y + r=. i.0 + whilst. (#todo) do. + node=. {: todo + todo=. }: todo + if. 0 < node do. + if. #ch=. (node{chil)-.0 do. + todo=. todo,(-node),|.ch + else. + r=. r, <:node end. + else. + r=. r, <:|node end. end. +) + +preorder=: preperm@parent reorder ] +preperm=:3 :0 + chil=. childinds y + todo=. I.(= i.@#) y + r=. i.0 + whilst. (#todo) do. + r=. r,node=. {: todo + todo=. }: todo + if. #ch=. (node{chil)-._1 do. + todo=. todo,|.ch end. end. + r +) diff --git a/Task/Tree-traversal/J/tree-traversal-11.j b/Task/Tree-traversal/J/tree-traversal-11.j new file mode 100644 index 0000000000..8029d114ed --- /dev/null +++ b/Task/Tree-traversal/J/tree-traversal-11.j @@ -0,0 +1,12 @@ + levelorder dataorder example +1 2 3 4 5 6 7 8 9 +0 0 0 1 1 2 3 5 5 + inorder dataorder example +7 4 2 5 1 8 6 9 3 +1 2 4 2 4 6 8 6 4 + preorder dataorder example +1 2 4 7 5 3 6 8 9 +0 0 1 2 1 0 5 6 6 + postorder dataorder example +7 4 5 2 8 9 6 3 1 +1 3 3 8 6 6 7 8 8 diff --git a/Task/Tree-traversal/J/tree-traversal-8.j b/Task/Tree-traversal/J/tree-traversal-8.j new file mode 100644 index 0000000000..a5aa254bda --- /dev/null +++ b/Task/Tree-traversal/J/tree-traversal-8.j @@ -0,0 +1 @@ +example=:1 8 3 4 7 5 9 6 2,: 0 7 0 8 3 8 7 2 0 diff --git a/Task/Tree-traversal/J/tree-traversal-9.j b/Task/Tree-traversal/J/tree-traversal-9.j new file mode 100644 index 0000000000..7b41d3f139 --- /dev/null +++ b/Task/Tree-traversal/J/tree-traversal-9.j @@ -0,0 +1,13 @@ +depth=: +/@((~: , (~: i.@#@{.)~) {:@,)@({~^:a:) + +reorder=:4 :0 + 'data parent'=. y + data1=. x{data + parent1=. x{data1 i. parent{data + if. 0=L.y do. data1,:parent1 else. data1;parent1 end. +) + +data=:3 :'data[''data parent''=. y' +parent=:3 :'parent[''data parent''=. y' + +childinds=: [: <:@(2&{.@-.&> #\) ( isa(x, Number) ? (f(x); {}) : x, vcat, t) + t = mapreduce(x -> isa(x, Number) ? (f(x); []) : x, vcat, t) end diff --git a/Task/Tree-traversal/Mercury/tree-traversal.mercury b/Task/Tree-traversal/Mercury/tree-traversal.mercury new file mode 100644 index 0000000000..bfdfd5c7dd --- /dev/null +++ b/Task/Tree-traversal/Mercury/tree-traversal.mercury @@ -0,0 +1,93 @@ +:- module tree_traversal. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module list. + +:- type tree(V) + ---> empty + ; node(V, tree(V), tree(V)). + +:- pred preorder(pred(V, A, A), tree(V), A, A). +:- mode preorder(pred(in, di, uo) is det, in, di, uo) is det. + +preorder(_, empty, !Acc). +preorder(P, node(Value, Left, Right), !Acc) :- + P(Value, !Acc), + preorder(P, Left, !Acc), + preorder(P, Right, !Acc). + +:- pred inorder(pred(V, A, A), tree(V), A, A). +:- mode inorder(pred(in, di, uo) is det, in, di, uo) is det. + +inorder(_, empty, !Acc). +inorder(P, node(Value, Left, Right), !Acc) :- + inorder(P, Left, !Acc), + P(Value, !Acc), + inorder(P, Right, !Acc). + +:- pred postorder(pred(V, A, A), tree(V), A, A). +:- mode postorder(pred(in, di, uo) is det, in, di, uo) is det. + +postorder(_, empty, !Acc). +postorder(P, node(Value, Left, Right), !Acc) :- + postorder(P, Left, !Acc), + postorder(P, Right, !Acc), + P(Value, !Acc). + +:- pred levelorder(pred(V, A, A), tree(V), A, A). +:- mode levelorder(pred(in, di, uo) is det, in, di, uo) is det. + +levelorder(P, Tree, !Acc) :- + do_levelorder(P, [Tree], !Acc). + +:- pred do_levelorder(pred(V, A, A), list(tree(V)), A, A). +:- mode do_levelorder(pred(in, di, uo) is det, in, di, uo) is det. + +do_levelorder(_, [], !Acc). +do_levelorder(P, [empty | Xs], !Acc) :- + do_levelorder(P, Xs, !Acc). +do_levelorder(P, [node(Value, Left, Right) | Xs], !Acc) :- + P(Value, !Acc), + do_levelorder(P, Xs ++ [Left, Right], !Acc). + +:- func tree = tree(int). + +tree = + node(1, + node(2, + node(4, + node(7, empty, empty), + empty + ), + node(5, empty, empty) + ), + node(3, + node(6, + node(8, empty, empty), + node(9, empty, empty) + ), + empty + ) + ). + +main(!IO) :- + io.write_string("preorder: " ,!IO), + preorder(print_value, tree, !IO), io.nl(!IO), + io.write_string("inorder: " ,!IO), + inorder(print_value, tree, !IO), io.nl(!IO), + io.write_string("postorder: " ,!IO), + postorder(print_value, tree, !IO), io.nl(!IO), + io.write_string("levelorder: " ,!IO), + levelorder(print_value, tree, !IO), io.nl(!IO). + +:- pred print_value(V::in, io::di, io::uo) is det. + +print_value(V, !IO) :- + io.print(V, !IO), + io.write_string(" ", !IO). diff --git a/Task/Tree-traversal/Python/tree-traversal.py b/Task/Tree-traversal/Python/tree-traversal-1.py similarity index 100% rename from Task/Tree-traversal/Python/tree-traversal.py rename to Task/Tree-traversal/Python/tree-traversal-1.py diff --git a/Task/Tree-traversal/Python/tree-traversal-2.py b/Task/Tree-traversal/Python/tree-traversal-2.py new file mode 100644 index 0000000000..81d292803b --- /dev/null +++ b/Task/Tree-traversal/Python/tree-traversal-2.py @@ -0,0 +1,61 @@ +from collections import namedtuple +from sys import stdout + +class Node(namedtuple('Node', 'data, left, right')): + __slots__ = () + + def preorder(self, visitor): + if self is not None: + visitor(self.data) + Node.preorder(self.left, visitor) + Node.preorder(self.right, visitor) + + def inorder(self, visitor): + if self is not None: + Node.inorder(self.left, visitor) + visitor(self.data) + Node.inorder(self.right, visitor) + + def postorder(self, visitor): + if self is not None: + Node.postorder(self.left, visitor) + Node.postorder(self.right, visitor) + visitor(self.data) + + def levelorder(self, visitor, more=None): + if self is not None: + if more is None: + more = [] + more += [self.left, self.right] + visitor(self.data) + if more: + Node.levelorder(more[0], visitor, more[1:]) + + +def printwithspace(i): + stdout.write("%i " % i) + + +tree = Node(1, + Node(2, + Node(4, + Node(7, None, None), + None), + Node(5, None, None)), + Node(3, + Node(6, + Node(8, None, None), + Node(9, None, None)), + None)) + + +if __name__ == '__main__': + stdout.write(' preorder: ') + tree.preorder(printwithspace) + stdout.write('\n inorder: ') + tree.inorder(printwithspace) + stdout.write('\n postorder: ') + tree.postorder(printwithspace) + stdout.write('\nlevelorder: ') + tree.levelorder(printwithspace) + stdout.write('\n') diff --git a/Task/Trigonometric-functions/ALGOL-W/trigonometric-functions.alg b/Task/Trigonometric-functions/ALGOL-W/trigonometric-functions.alg new file mode 100644 index 0000000000..49229dd1b1 --- /dev/null +++ b/Task/Trigonometric-functions/ALGOL-W/trigonometric-functions.alg @@ -0,0 +1,62 @@ +begin + % Algol W only supplies sin, cos and arctan as standard. We can define % + % arcsin, arccos and tan functions using these. The standard functions % + % use radians so we also provide versions that use degrees % + + % convert degrees to radians % + real procedure toRadians( real value x ) ; pi * ( x / 180 ); + % convert radians to degrees % + real procedure toDegrees( real value x ) ; 180 * ( x / pi ); + % tan of an angle in radians % + real procedure tan( real value x ) ; sin( x ) / cos( x ); + % arcsin in radians % + real procedure arcsin( real value x ) ; arctan( x / sqrt( 1 - ( x * x ) ) ); + % arccos in radians % + real procedure arccos( real value x ) ; arctan( sqrt( 1 - ( x * x ) ) / x ); + % sin of an angle in degrees % + real procedure sinD( real value x ) ; sin( toRadians( x ) ); + % cos of an angle in degrees % + real procedure cosD( real value x ) ; cos( toRadians( x ) ); + % tan of an angle in degrees % + real procedure tanD( real value x ) ; tan( toRadians( x ) ); + % arctan in degrees % + real procedure arctanD( real value x ) ; toDegrees( arctan( x ) ); + % arcsin in degrees % + real procedure arcsinD( real value x ) ; toDegrees( arcsin( x ) ); + % arccos in degrees % + real procedure arccosD( real value x ) ; toDegrees( arccos( x ) ); + + + % test the procedures % + begin + + real piOver4, piOver3, oneOverRoot2, root3Over2; + piOver3 := pi / 3; piOver4 := pi / 4; + oneOverRoot2 := 1.0 / sqrt( 2 ); root3Over2 := sqrt( 3 ) / 2; + + + r_w := 12; r_d := 5; r_format := "A"; s_w := 0; % set output format % + + write( "PI/4: ", piOver4, " 1/root(2): ", oneOverRoot2 ); + write(); + write( "sin 45 degrees: ", sinD( 45 ), " sin pi/4 radians: ", sin( piOver4 ) ); + write( "cos 45 degrees: ", cosD( 45 ), " cos pi/4 radians: ", cos( piOver4 ) ); + write( "tan 45 degrees: ", tanD( 45 ), " tan pi/4 radians: ", tan( piOver4 ) ); + write(); + write( "arcsin( sin( pi/4 radians ) ): ", arcsin( sin( piOver4 ) ) ); + write( "arccos( cos( pi/4 radians ) ): ", arccos( cos( piOver4 ) ) ); + write( "arctan( tan( pi/4 radians ) ): ", arctan( tan( piOver4 ) ) ); + write(); + write( "PI/3: ", piOver4, " root(3)/2: ", root3Over2 ); + write(); + write( "sin 60 degrees: ", sinD( 60 ), " sin pi/3 radians: ", sin( piOver3 ) ); + write( "cos 60 degrees: ", cosD( 60 ), " cos pi/3 radians: ", cos( piOver3 ) ); + write( "tan 60 degrees: ", tanD( 60 ), " tan pi/3 radians: ", tan( piOver3 ) ); + write(); + write( "arcsin( sin( 60 degrees ) ): ", arcsinD( sinD( 60 ) ) ); + write( "arccos( cos( 60 degrees ) ): ", arccosD( cosD( 60 ) ) ); + write( "arctan( tan( 60 degrees ) ): ", arctanD( tanD( 60 ) ) ); + + end + +end. diff --git a/Task/Trigonometric-functions/Elixir/trigonometric-functions.elixir b/Task/Trigonometric-functions/Elixir/trigonometric-functions.elixir new file mode 100644 index 0000000000..98e7bac34f --- /dev/null +++ b/Task/Trigonometric-functions/Elixir/trigonometric-functions.elixir @@ -0,0 +1,18 @@ +iex(61)> deg = 45 +45 +iex(62)> rad = :math.pi / 4 +0.7853981633974483 +iex(63)> :math.sin(deg * :math.pi / 180) == :math.sin(rad) +true +iex(64)> :math.cos(deg * :math.pi / 180) == :math.cos(rad) +true +iex(65)> :math.tan(deg * :math.pi / 180) == :math.tan(rad) +true +iex(66)> temp = :math.acos(:math.cos(rad)) +0.7853981633974483 +iex(67)> temp * 180 / :math.pi == deg +true +iex(68)> temp = :math.atan(:math.tan(rad)) +0.7853981633974483 +iex(69)> temp * 180 / :math.pi == deg +true diff --git a/Task/Trigonometric-functions/Fortran/trigonometric-functions-3.f b/Task/Trigonometric-functions/Fortran/trigonometric-functions-3.f new file mode 100644 index 0000000000..0bd890883a --- /dev/null +++ b/Task/Trigonometric-functions/Fortran/trigonometric-functions-3.f @@ -0,0 +1,63 @@ +Calculate various trigonometric functions from the Fortran library. + INTEGER BIT(32),B,IP !Stuff for bit fiddling. + INTEGER ENUFF,I !Step through the test angles. + PARAMETER (ENUFF = 17) !A selection of special values. + INTEGER ANGLE(ENUFF) !All in whole degrees. + DATA ANGLE/0,30,45,60,90,120,135,150,180, !Here they are. + 1 210,225,240,270,300,315,330,360/ !Thus check angle folding. + REAL PI,DEG2RAD !Special numbers. + REAL D,R,FD,FR,AD,AR !Degree, Radian, F(D), F(R), inverses. + PI = 4*ATAN(1.0) !SINGLE PRECISION 1·0. + DEG2RAD = PI/180 !Limited precision here too for a transcendental number. +Case the first: sines. + WRITE (6,10) ("Sin", I = 1,4) !Supply some names. + 10 FORMAT (" Deg.",A7,"(Deg)",A7,"(Rad) Rad - Deg", !Ah, layout. + 1 6X,"Arc",A3,"D",6X,"Arc",A3,"R",9X,"Diff") + DO I = 1,ENUFF !Step through the test values. + D = ANGLE(I) !The angle in degrees, in floating point. + R = D*DEG2RAD !Approximation, in radians. + FD = SIND(D); AD = ASIND(FD) !Functions working in degrees. + FR = SIN(R); AR = ASIN(FR)/DEG2RAD !Functions working in radians. + WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD !Results. + 11 FORMAT (I4,":",3F12.8,3F13.7) !Ah, alignment with FORMAT 10... + END DO !On to the next test value. +Case the second: cosines. + WRITE (6,10) ("Cos", I = 1,4) + DO I = 1,ENUFF + D = ANGLE(I) + R = D*DEG2RAD + FD = COSD(D); AD = ACOSD(FD) + FR = COS(R); AR = ACOS(FR)/DEG2RAD + WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD + END DO +Case the third: tangents. + WRITE (6,10) ("Tan", I = 1,4) + DO I = 1,ENUFF + D = ANGLE(I) + R = D*DEG2RAD + FD = TAND(D); AD = ATAND(FD) + FR = TAN(R); AR = ATAN(FR)/DEG2RAD + WRITE (6,11) INT(D),FD,FR,FR - FD,AD,AR,AR - AD + END DO + WRITE (6,*) "...Special deal for 90 degrees..." + D = 90 + R = D*DEG2RAD + FD = TAND(D); AD = ATAND(FD) + FR = TAN(R); AR = ATAN(FR)/DEG2RAD + WRITE (6,*) "TanD =",FD,"Atan =",AD + WRITE (6,*) "TanR =",FR,"Atan =",AR +Convert PI to binary... + PI = PI - 3 !I know it starts with three, and I need the fractional part. + BIT(1:2) = 1 !So, the binary is 11. something. + B = 2 !Two bits known. + DO I = 1,26 !For single precision, more than enough additional bits. + PI = PI*2 !Hoist a bit to the hot spot. + IP = PI !The integral part. + PI = PI - IP !Remove it from the work in progress. + B = B + 1 !Another bit bitten. + BIT(B) = IP !Place it. + END DO !On to the next. + WRITE (6,20) BIT(1:B) !Reveal the bits. + 20 FORMAT (" Pi ~ ",2I1,".",66I1) !A known format. + WRITE (6,*) " = 11.00100100001111110110101010001000100001..." !But actually... + END !So much for that. diff --git a/Task/Trigonometric-functions/J/trigonometric-functions-1.j b/Task/Trigonometric-functions/J/trigonometric-functions-1.j index 1f128a4518..26093da1bc 100644 --- a/Task/Trigonometric-functions/J/trigonometric-functions-1.j +++ b/Task/Trigonometric-functions/J/trigonometric-functions-1.j @@ -1 +1,4 @@ - >,:(1&o. ; 2&o. ; 3&o.) (4%~o. 1), 180%~o. 45 + (1&o. , 2&o. ,: 3&o.) (4 %~ o. 1) , 180 %~ o. 45 +0.707107 0.707107 +0.707107 0.707107 + 1 1 diff --git a/Task/Trigonometric-functions/J/trigonometric-functions-2.j b/Task/Trigonometric-functions/J/trigonometric-functions-2.j index 2d42bfe3be..09f2abc8d2 100644 --- a/Task/Trigonometric-functions/J/trigonometric-functions-2.j +++ b/Task/Trigonometric-functions/J/trigonometric-functions-2.j @@ -1 +1,4 @@ - >,:([ , 180p_1&*)&.> (_1&o. ; _2&o. ; _3&o.) 0.5 + ([ ,. 180p_1&*) (_1&o. , _2&o. ,: _3&o.) 0.5 +0.523599 30 + 1.0472 60 +0.463648 26.5651 diff --git a/Task/Trigonometric-functions/J/trigonometric-functions-3.j b/Task/Trigonometric-functions/J/trigonometric-functions-3.j new file mode 100644 index 0000000000..bcf66f2cb9 --- /dev/null +++ b/Task/Trigonometric-functions/J/trigonometric-functions-3.j @@ -0,0 +1,10 @@ + require 'trig' + (sin , cos ,: tan) (1p1 % 4), rfd 45 +0.707107 0.707107 +0.707107 0.707107 + 1 1 + + ([ ,. dfr) (arcsin , arccos ,: arctan) 0.5 +0.523599 30 + 1.0472 60 +0.463648 26.5651 diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx index fd11c97b29..c1c1f4e7b3 100644 --- a/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions-1.rexx @@ -2,7 +2,7 @@ │ One common method that ensures enough accuracy in REXX is specifying │ │ more precision (via NUMERIC DIGITS nnn) than is needed, and then │ │ displaying the number of digits that are desired, or the number(s) │ - │ could be re-normalized using the FORMAT bif. │ + │ could be re-normalized using the FORMAT BIF. │ │ │ │ The technique used (below) is to set the numeric digits ten higher │ │ than the desired digits, as specified by the SHOWDIGS variable. │ diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx index 4be6f47e6b..d754b5b200 100644 --- a/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions-2.rexx @@ -2,6 +2,7 @@ showdigs=30 /*show only 30 digits of number. */ numeric digits showdigs+10 /*DIGITS default is 9, but use */ /*extra digs to prevent rounding.*/ + say 'Using' showdigs 'decimal digits precision.'; say do j=-180 to +180 by 15 /*let's just do a half-Monty. */ @@ -22,7 +23,7 @@ say; do k=-1 to +1 by 1/2 /*keep the Arc-functions happy. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────subroutines─────────────────────────*/ Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a - if a>1 then call $81r -1,1,x,"ASIN" /*X arg is out of range.*/ + if a>1 then call AsinErr x /*X arg is out of range.*/ if a>=sqrt(2)*.5 then return sign(x)*acos(sqrt(1-aa), '-ASIN') do j=2 by 2 until p=z; p=z; o=o*aa*(j-1)/j; z=z+o/(j+1); end return z /* [↑] compute until no noise.*/ @@ -30,56 +31,54 @@ Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a Atan: procedure; parse arg x; if abs(x)=1 then return pi() * .25 * sign(x) return Asin(x/sqrt(1+x*x) ) -cos: procedure; parse arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9) - if a=pi then return -1; if a=pi*.5 | a=pi*2 then return 0 - pi3=pi/3; if a=pi3 then return .5; if a=2*pi3 then return -.5 - return .sinCos(1,1,-1) +cos: procedure; parse arg x; x=r2r(x); a=abs(x); hpi=pi*.5 + numeric fuzz min(6,digits()-3); if a=pi() then return -1 + if a=hpi | a=hpi*3 then return 0; if a=pi()/3 then return .5 + if a=pi()*2/3 then return -.5; return .sinCos(1,-1) -sin: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3) - if x=pi*.5 then return 1; if x==pi*1.5 then return -1 - if abs(x)=pi | x=0 then return 0; return .sinCos(x, x, +1) +sin: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3) + if x=pi*.5 then return 1; if x==pi*1.5 then return -1 + if abs(x)=pi | x=0 then return 0; return .sinCos(x,1) -.sinCos: parse arg z,_,i; x=x*x - do k=2 by 2 until p=z; p=z; _=-_*x/(k*(k+i)); z=z+_; end /*k*/ +.sinCos: parse arg z 1 _,i; q=x*x + do k=2 by 2 until p=z; p=z; _=-_*q/(k*(k+i)); z=z+_; end /*k*/ return z -sqrt: procedure; parse arg x,i; if x=0 then return 0; d=digits(); m.=11 - if x<0 then i='i'; numeric digits 11; numeric form; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2 - do j=0 while p>9; m.j=p; p=p%2+1; end /*j*/ - do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k - g=.5*(g+x/g); end /*k*/; numeric digits d; return g/1 +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 + numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + numeric digits d; return (g/1)i /*make complex if X < 0.*/ + e: e=2.7182818284590452353602874713526624977572470936999595749669676277240766303535 -return e /*Note: the actual E subroutine returns E's accuracy that */ - /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ - /*If more than 1 million digits are required, be patient. */ +return e /*Note: the actual E subroutine returns E's accuracy that */ + /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ exp: procedure; parse arg x; ix=x%1; if abs(x-ix)>.5 then ix=ix+sign(x); x=x-ix z=1; _=1; w=z; do j=1; _=_*x/j; z=(z+_)/1; if z==w then leave; w=z; end if z\==0 then z=e()**ix*z; return z pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862 -return pi /*Note: the actual PI subroutine returns PI's accuracy that */ - /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ - /*John Machin's formula is used for calculating more digits. */ - /*If more than 1 million digits are required, be patient. */ +return pi /*Note: the actual PI subroutine returns PI's accuracy that */ + /*matches the current NUMERIC DIGITS, up to 1 million digits.*/ + /*John Machin's formula is used for calculating more digits. */ $fuzz: return min(arg(1), max(1, digits() - arg(2) ) ) -Acos: procedure; parse arg x; if x<-1|x>1 then call AcosErr; return .5*pi()-Asin(x) +Acos: procedure; parse arg x; if x<-1|x>1 then call AcosErr; return pi()*.5-Asin(x) AcosD: return r2d(Acos(arg(1))) AsinD: return r2d(Asin(arg(1))) cosD: return cos(d2r(arg(1))) sinD: return sin(d2r(d2d(arg(1)))) -tan: procedure; parse arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ +tan: procedure; parse arg x; _=cos(x); if _=0 then call tanErr; return sin(x)/_ tanD: return tan(d2r(arg(1))) -d2d: return arg(1) // 360 /*normalize degrees►1 unit circle. */ -d2r: return r2r(d2d(arg(1))*pi() /180) /*convert degrees ──► radians. */ -r2d: return d2d((arg(1)*180 /pi())) /*convert radians ──► degrees. */ -r2r: return arg(1) // (pi()*2) /*normalize radians ──►a unit circle*/ +d2d: return arg(1) // 360 /*normalize degrees ──► a unit circle*/ +d2r: return r2r(d2d(arg(1))*pi() / 180) /*convert degrees ──► radians. */ +r2d: return d2d((arg(1)*180 / pi())) /*convert radians ──► degrees. */ +r2r: return arg(1) // (pi()*2) /*normalize radians ──► a unit circle*/ show: return left(left('',arg(1)>=0)format(arg(1),,showdigs)/1,showdigs) -tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 -tanErr: call tellErr 'tan('||x") causes division by zero, X=" || x +tellErr: say; say '*** error! ***'; say; say arg(1); say; exit 13 +tanErr: call tellErr 'tan(' || x") causes division by zero, X=" || x AsinErr: call tellErr 'Asin(x), X must be in the range of -1 ──► +1, X=' || x AcosErr: call tellErr 'Acos(x), X must be in the range of -1 ──► +1, X=' || x -sqrtErr: call tellErr "sqrt(x), X can't be negative, X=" || x diff --git a/Task/Trigonometric-functions/REXX/trigonometric-functions-3.rexx b/Task/Trigonometric-functions/REXX/trigonometric-functions-3.rexx new file mode 100644 index 0000000000..9873608ccc --- /dev/null +++ b/Task/Trigonometric-functions/REXX/trigonometric-functions-3.rexx @@ -0,0 +1,30 @@ + ╔═════════════════════════════════════════════════════════════════════════════╗ + ║ Functions that are not included here are (among others): ║ + ║ ║ + ║ some of the usual higher-math functions normally associated with trig ║ + ║ functions: POW, GAMMA, LGGAMMA, ERF, ERFC, ROOT, ATAN2, ║ + ║ LOG (LN), LOG2, LOG10, and all of the ║ + ║ hyperbolic trigonometric functions and their inverses (too many to list ║ + ║ here), ║ + ║ angle conversions/normalizations: degrees/radians/grads/mils: ║ + ║ a circle ≡ 2 pi radians ≡ 360 degrees ≡ 400 grads ≡ 6400 mils. ║ + ║ ║ + ║ Some of the other trigonometric functions are (hyphens added intentionally):║ + ║ ║ + ║ CHORD ║ + ║ COT (co-tangent) ║ + ║ CSC (co-secant) ║ + ║ CVC (co-versed cosine) ║ + ║ CVS (co-versed sine) ║ + ║ CXS (co-exsecant) ║ + ║ HAC (haver-cosine) ║ + ║ HAV (haver-sine ║ + ║ SEC (secant) ║ + ║ VCS (versed cosine or ver-cosine) ║ + ║ VSN (versed sine or ver-sine) ║ + ║ XCS (ex-secant) ║ + ║ COS/SIN/TAN cardinal (damped COS/SIN/TAN functions) ║ + ║ COS/SIN integral ║ + ║ ║ + ║ and all pertinent inverses of the above functions (AVSN, ACVS, ···). ║ + ╚═════════════════════════════════════════════════════════════════════════════╝ diff --git a/Task/Trigonometric-functions/Run-BASIC/trigonometric-functions.run b/Task/Trigonometric-functions/Run-BASIC/trigonometric-functions.run index f573d3991b..0b10476886 100644 --- a/Task/Trigonometric-functions/Run-BASIC/trigonometric-functions.run +++ b/Task/Trigonometric-functions/Run-BASIC/trigonometric-functions.run @@ -1,13 +1,19 @@ +' Find these three ratios: Sine, Cosine, Tangent. (These ratios have NO units.) + deg = 45.0 -' Run BASIC works in radians. Convert deg and rad as shown. -d2r = ACS(-1)/180 -rad = deg*d2r -r2d = 180/ACS(-1) +' Run BASIC works in radians; so, first convert deg to rad as shown in next line. +rad = deg * (atn(1)/45) +print "Ratios for a "; deg; " degree angle, (or "; rad; " radian angle.)" +print "Sine: "; SIN(rad) +print "Cosine: "; COS(rad) +print "Tangent: "; TAN(rad) + +print "Inverse Functions - - (Using above ratios)" +' Now, use those ratios to work backwards to show their original angle in radians. +' Also, use this: rad / (atn(1)/45) = deg (To change radians to degrees.) +print "Arcsine: "; ASN(SIN(rad)); " radians, (or "; ASN(SIN(rad))/(atn(1)/45); " degrees)" +print "Arccosine: "; ACS(COS(rad)); " radians, (or "; ACS(COS(rad))/(atn(1)/45); " degrees)" +print "Arctangent: "; ATN(TAN(rad)); " radians, (or "; ATN(TAN(rad))/(atn(1)/45); " degrees)" -print "Sine: ";SIN(rad);" ";SIN(deg*d2r) -print "Cosine: ";COS(rad);" ";COS(deg*d2r) -print "Tangent: ";TAN(rad);" ";TAN(deg*d2r) -print -print "Arcsine: ";ASN(SIN(rad));" radians, (or ";ASN(SIN(deg*d2r))*r2d;" degrees)" -print "Arccosine: ";ACS(COS(rad));" radians, (or ";ACS(COS(deg*d2r))*r2d;" degrees)" -print "Arctangent: ";ATN(TAN(rad));" radians, (or ";ATN(TAN(deg*d2r))*r2d;" degrees)" +' This code also works in Liberty BASIC. +' The above (atn(1)/45) = approx .01745329252 diff --git a/Task/Truncatable-primes/Eiffel/truncatable-primes.e b/Task/Truncatable-primes/Eiffel/truncatable-primes.e new file mode 100644 index 0000000000..5152b259b3 --- /dev/null +++ b/Task/Truncatable-primes/Eiffel/truncatable-primes.e @@ -0,0 +1,150 @@ +class + APPLICATION + +create + make + +feature + + make + do + io.put_string ("Largest right truncatable prime: " + find_right_truncatable_primes.out) + io.new_line + io.put_string ("Largest left truncatable prime: " + find_left_truncatable_primes.out) + end + + find_right_truncatable_primes: INTEGER + -- Largest right truncatable prime below 1000000. + local + i, maybe_prime: INTEGER + found, is_one: BOOLEAN + do + from + i := 999999 + until + found + loop + is_one := True + from + maybe_prime := i + until + not is_one or maybe_prime.out.count = 1 + loop + if maybe_prime.out.has ('0') or maybe_prime.out.has ('2') or maybe_prime.out.has ('4') or maybe_prime.out.has ('6') or maybe_prime.out.has ('8') then + is_one := False + else + if not is_prime (maybe_prime) then + is_one := False + elseif is_prime (maybe_prime) and maybe_prime.out.count > 1 then + maybe_prime := truncate_right (maybe_prime) + end + end + end + if is_one then + found := True + Result := i + end + i := i - 2 + end + ensure + Result_is_smaller: Result < 1000000 + end + + find_left_truncatable_primes: INTEGER + -- Largest left truncatable prime below 1000000. + local + i, maybe_prime: INTEGER + found, is_one: BOOLEAN + do + from + i := 999999 + until + found + loop + is_one := True + from + maybe_prime := i + until + not is_one or maybe_prime.out.count = 1 + loop + if not is_prime (maybe_prime) then + is_one := False + elseif is_prime (maybe_prime) and maybe_prime.out.count > 1 then + if maybe_prime.out.at (2) = '0' then + is_one := False + else + maybe_prime := truncate_left (maybe_prime) + end + end + end + if is_one then + found := True + Result := i + end + i := i - 2 + end + ensure + Result_is_smaller: Result < 1000000 + end + +feature {NONE} + + is_prime (n: INTEGER): BOOLEAN + --Is 'n' a prime number? + require + positiv_input: n > 0 + local + i: INTEGER + max: REAL_64 + math: DOUBLE_MATH + do + create math + if n = 2 then + Result := True + elseif n <= 1 or n \\ 2 = 0 then + Result := False + else + Result := True + max := math.sqrt (n) + from + i := 3 + until + i > max + loop + if n \\ i = 0 then + Result := False + end + i := i + 2 + end + end + end + + truncate_left (n: INTEGER): INTEGER + -- 'n' truncated by one digit from the left side. + require + truncatable: n.out.count > 1 + local + st: STRING + do + st := n.out + st.remove_head (1) + Result := st.to_integer + ensure + Result_truncated: Result.out.count = n.out.count - 1 + end + + truncate_right (n: INTEGER): INTEGER + -- 'n' truncated by one digit from the right side. + require + truncatable: n.out.count > 1 + local + st: STRING + do + st := n.out + st.remove_tail (1) + Result := st.to_integer + ensure + Result_truncated: Result.out.count = n.out.count - 1 + end + +end diff --git a/Task/Truncatable-primes/Julia/truncatable-primes.julia b/Task/Truncatable-primes/Julia/truncatable-primes.julia new file mode 100644 index 0000000000..48170e13d6 --- /dev/null +++ b/Task/Truncatable-primes/Julia/truncatable-primes.julia @@ -0,0 +1,36 @@ +function isltruncprime{T<:Integer}(n::T, base::T=10) + isprime(n) || return false + p = n + f = prevpow(base, p) + while 1 < f + (d, p) = divrem(p, f) + isprime(p) || return false + d != 0 || return false + f = div(f, base) + end + return true +end + +function isrtruncprime{T<:Integer}(n::T, base::T=10) + isprime(n) || return false + p = n + while base < p + p = div(p, base) + isprime(p) || return false + end + return true +end + +hi = 10^6 + +for i in reverse(primes(hi)) + isltruncprime(i) || continue + println("The largest left truncatable prime ≤ ", hi, " is ", i, ".") + break +end + +for i in reverse(primes(hi)) + isrtruncprime(i) || continue + println("The largest right truncatable prime ≤ ", hi, " is ", i, ".") + break +end diff --git a/Task/Truncatable-primes/Perl-6/truncatable-primes.pl6 b/Task/Truncatable-primes/Perl-6/truncatable-primes.pl6 index a5c912e44b..888a7cd3bf 100644 --- a/Task/Truncatable-primes/Perl-6/truncatable-primes.pl6 +++ b/Task/Truncatable-primes/Perl-6/truncatable-primes.pl6 @@ -1,9 +1,9 @@ -constant ltp = [2, 3, 5, 7], -> @ltp { - [ grep &is-prime, ((1..9) X~ @ltp) ] +constant ltp = $[2, 3, 5, 7], -> @ltp { + $[ grep { .&is-prime }, ((1..9) X~ @ltp) ] } ... *; -constant rtp = [2, 3, 5, 7], -> @rtp { - [ grep &is-prime, (@rtp X~ (1..9)) ] +constant rtp = $[2, 3, 5, 7], -> @rtp { + $[ grep { .&is-prime }, (@rtp X~ (1..9)) ] } ... *; say "Highest ltp = ", ltp[5][*-1]; diff --git a/Task/Truncatable-primes/Perl/truncatable-primes-1.pl b/Task/Truncatable-primes/Perl/truncatable-primes-1.pl new file mode 100644 index 0000000000..f543f78c18 --- /dev/null +++ b/Task/Truncatable-primes/Perl/truncatable-primes-1.pl @@ -0,0 +1,15 @@ +use ntheory ":all"; +sub isltrunc { + my $n = shift; + return (is_prime($n) && $n !~ /0/ && ($n < 10 || isltrunc(substr($n,1)))); +} +sub isrtrunc { + my $n = shift; + return (is_prime($n) && $n !~ /0/ && ($n < 10 || isrtrunc(substr($n,0,-1)))); +} +for (reverse @{primes(1e6)}) { + if (isltrunc($_)) { print "ltrunc: $_\n"; last; } +} +for (reverse @{primes(1e6)}) { + if (isrtrunc($_)) { print "rtrunc: $_\n"; last; } +} diff --git a/Task/Truncatable-primes/Perl/truncatable-primes-2.pl b/Task/Truncatable-primes/Perl/truncatable-primes-2.pl new file mode 100644 index 0000000000..9efc0f2427 --- /dev/null +++ b/Task/Truncatable-primes/Perl/truncatable-primes-2.pl @@ -0,0 +1,13 @@ +use ntheory ":all"; + +my @lprimes = my @rprimes = (2,3,5,7); + +@lprimes = sort { $a <=> $b } + map { my $p=$_; map { is_prime($_.$p) ? $_.$p : () } 1..9 } @lprimes + for 2..6; + +@rprimes = sort { $a <=> $b } + map { my $p=$_; map { is_prime($p.$_) ? $p.$_ : () } 1..9 } @rprimes + for 2..6; + +print "ltrunc: $lprimes[-1]\nrtrunc: $rprimes[-1]\n"; diff --git a/Task/Truncatable-primes/Perl/truncatable-primes.pl b/Task/Truncatable-primes/Perl/truncatable-primes-3.pl similarity index 100% rename from Task/Truncatable-primes/Perl/truncatable-primes.pl rename to Task/Truncatable-primes/Perl/truncatable-primes-3.pl diff --git a/Task/Truncatable-primes/VBScript/truncatable-primes.vb b/Task/Truncatable-primes/VBScript/truncatable-primes.vb new file mode 100644 index 0000000000..68f7096177 --- /dev/null +++ b/Task/Truncatable-primes/VBScript/truncatable-primes.vb @@ -0,0 +1,68 @@ +start_time = Now + +lt = 0 +rt = 0 + +For h = 1 To 1000000 + If IsLeftTruncatable(h) And h > lt Then + lt = h + End If + If IsRightTruncatable(h) And h > rt Then + rt = h + End If +Next + +end_time = now + +WScript.StdOut.WriteLine "Largest LTP from 1..1000000: " & lt +WScript.StdOut.WriteLine "Largest RTP from 1..1000000: " & rt +WScript.StdOut.WriteLine "Elapse Time(seconds) : " & DateDiff("s",start_time,end_time) + +'------------ +Function IsLeftTruncatable(n) + IsLeftTruncatable = False + c = 0 + For i = Len(n) To 1 Step -1 + If InStr(1,n,"0") > 0 Then + Exit For + End If + If IsPrime(Right(n,i)) Then + c = c + 1 + End If + Next + If c = Len(n) Then + IsLeftTruncatable = True + End If +End Function + +Function IsRightTruncatable(n) + IsRightTruncatable = False + c = 0 + For i = Len(n) To 1 Step -1 + If InStr(1,n,"0") > 0 Then + Exit For + End If + If IsPrime(Left(n,i)) Then + c = c + 1 + End If + Next + If c = Len(n) Then + IsRightTruncatable = True + End If +End Function + +Function IsPrime(n) + If n = 2 Then + IsPrime = True + ElseIf n <= 1 Or n Mod 2 = 0 Then + IsPrime = False + Else + IsPrime = True + For i = 3 To Int(Sqr(n)) Step 2 + If n Mod i = 0 Then + IsPrime = False + Exit For + End If + Next + End If +End Function diff --git a/Task/Truncate-a-file/Python/truncate-a-file.py b/Task/Truncate-a-file/Python/truncate-a-file.py index ae0f3d50b8..b21f5ef2be 100644 --- a/Task/Truncate-a-file/Python/truncate-a-file.py +++ b/Task/Truncate-a-file/Python/truncate-a-file.py @@ -1,4 +1,9 @@ -def truncate_file(fname, size): - "Open a file for writing, and truncate it to size bytes." - with open(fname, "ab") as f: - f.truncate(size) +def truncate_file(name, length): + if not os.path.isfile(name): + return False + if length >= os.path.getsize(name): + return False + with open(name, 'ab') as f: + f.truncate(length) + f.close() + return True diff --git a/Task/Truncate-a-file/REXX/truncate-a-file-1.rexx b/Task/Truncate-a-file/REXX/truncate-a-file-1.rexx new file mode 100644 index 0000000000..73e7f100ed --- /dev/null +++ b/Task/Truncate-a-file/REXX/truncate-a-file-1.rexx @@ -0,0 +1,20 @@ +/*REXX program truncates a file to a specified (smaller) number of bytes.*/ +parse arg siz FID /*get required arguments from the C.L. */ +FID=strip(FID) /*elide leading/trailing blanks from FID*/ +if siz=='' then call ser "No truncation size was specified (1st argument)." +if FID=='' then call ser "No fileID was specified (2nd argument)." +if \datatype(siz,'W') then call ser "trunc size isn't an integer: " siz +if siz<1 then call ser "trunc size isn't a positive integer: " siz +_=charin(FID,1,siz+1) /*position file and read a wee bit more*/ +#=length(_) /*get the length of the part just read.*/ +if #==0 then call ser "the specified file doesn't exist: " FID +if # 12 + loop + if s [i] then + count := count + 1 + end + i := i + 2 + end + Result := s [3] = (count = 2) + end + + check4: BOOLEAN + -- Is statement 4 fulfilled? + do + Result := s [4] = ((not s [5]) or (s [6] and s [7])) + end + + check5: BOOLEAN + -- Is statement 5 fulfilled? + do + Result := s [5] = ((not s [2]) and (not s [3]) and (not s [4])) + end + + check6: BOOLEAN + -- Is statement 6 fulfilled? + local + count, i: INTEGER + do + from + i := 1 + until + i > 11 + loop + if s [i] then + count := count + 1 + end + i := i + 2 + end + Result := s [6] = (count = 4) + end + + check7: BOOLEAN + -- Is statement 7 fulfilled? + do + Result := s [7] = ((s [2] or s [3]) and not (s [2] and s [3])) + end + + check8: BOOLEAN + -- Is statement 8 fulfilled? + do + Result := s [8] = (not s [7] or (s [5] and s [6])) + end + + check9: BOOLEAN + -- Is statement 9 fulfilled? + local + count: INTEGER + do + across + 1 |..| 6 as c + loop + if s [c.item] then + count := count + 1 + end + end + Result := s [9] = (count = 3) + end + + check10: BOOLEAN + -- Is statement 10 fulfilled? + do + Result := s [10] = (s [11] and s [12]) + end + + check11: BOOLEAN + -- Is statement 11 fulfilled? + local + count: INTEGER + do + across + 7 |..| 9 as c + loop + if s [c.item] then + count := count + 1 + end + end + Result := s [11] = (count = 1) + end + + check12: BOOLEAN + -- Is statement 12 fulfilled? + local + count: INTEGER + do + across + 1 |..| 11 as c + loop + if s [c.item] then + count := count + 1 + end + end + Result := (s [12] = (count = 4)) + end + + counter: INTEGER + + checkit + -- Check if all statements are correctly solved. + do + if check2 and check3 and check4 and check5 and check6 and check7 and check8 and check9 and check10 and check11 and check12 then + across + 1 |..| 12 as c + loop + if s [c.item] then + io.put_string (c.item.out + "%T") + end + end + io.new_line + counter := counter + 1 + end + end + + recurseAll (k: INTEGER) + -- All possible True and False combinations to check for a solution. + do + if k = 13 then + checkit + else + s [k] := False + recurseAll (k + 1) + s [k] := True + recurseAll (k + 1) + end + end + +end diff --git a/Task/Twelve-statements/J/twelve-statements-10.j b/Task/Twelve-statements/J/twelve-statements-10.j new file mode 100644 index 0000000000..a090540682 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-10.j @@ -0,0 +1,18 @@ + offby1=: 1=+/errors + 'Statement ',"1 (":1+I.|: offby1 #"1 errors),"1 ' is inconsistent with exactly ',"1 ((1":@:+I.)"1 #:I.offby1),"1 ' being true' +Statement 1 is inconsistent with exactly 5 8 11 being true +Statement 1 is inconsistent with exactly 5 8 10 11 12 being true +Statement 1 is inconsistent with exactly 4 8 10 11 12 being true +Statement 8 is inconsistent with exactly 1 5 being true +Statement 11 is inconsistent with exactly 1 5 8 being true +Statement 12 is inconsistent with exactly 1 5 8 11 being true +Statement 12 is inconsistent with exactly 1 5 8 10 11 12 being true +Statement 8 is inconsistent with exactly 1 5 6 9 11 being true +Statement 8 is inconsistent with exactly 1 4 being true +Statement 12 is inconsistent with exactly 1 4 8 10 11 12 being true +Statement 6 is inconsistent with exactly 1 4 6 8 9 being true +Statement 7 is inconsistent with exactly 1 3 4 8 9 being true +Statement 9 is inconsistent with exactly 1 3 4 6 7 9 being true +Statement 12 is inconsistent with exactly 1 2 4 7 9 12 being true +Statement 10 is inconsistent with exactly 1 2 4 7 9 10 being true +Statement 8 is inconsistent with exactly 1 2 4 7 8 9 being true diff --git a/Task/Twelve-statements/J/twelve-statements-2.j b/Task/Twelve-statements/J/twelve-statements-2.j index 155cc47c28..24465b2b3a 100644 --- a/Task/Twelve-statements/J/twelve-statements-2.j +++ b/Task/Twelve-statements/J/twelve-statements-2.j @@ -1,16 +1,16 @@ S=: <;._2 (0 :0) -12&=@# -3=+/@:{.~&_6 -2= +/@:{~&1 3 5 7 9 11 -4&{=*./@:{~&4 5 6 -0=+/@:{~&1 2 3 -4=+/@:{~&0 2 4 6 8 10 -1=+/@:{~&1 2 -6&{=*./@:{~&4 5 6 -3=+/@:{.~&6 -2=+/@:{~&10 11 -1=+/@:{~&6 7 8 -4=+/@:{.~&11 + 12&=@# NB. 1. This is a numbered list of twelve statements. + 3=+/@:{.~&_6 NB. 2. Exactly 3 of the last 6 statements are true. + 2= +/@:{~&1 3 5 7 9 11 NB. 3. Exactly 2 of the even-numbered statements are true. + 4&{=*./@:{~&4 5 6 NB. 4. If statement 5 is true, then statements 6 and 7 are both true. + 0=+/@:{~&1 2 3 NB. 5. The 3 preceding statements are all false. + 4=+/@:{~&0 2 4 6 8 10 NB. 6. Exactly 4 of the odd-numbered statements are true. + 1=+/@:{~&1 2 NB. 7. Either statement 2 or 3 is true, but not both. + 6&{=*./@:{~&4 5 6 NB. 8. If statement 7 is true, then 5 and 6 are both true. + 3=+/@:{.~&6 NB. 9. Exactly 3 of the first 6 statements are true. + 2=+/@:{~&10 11 NB. 10. The next two statements are both true. + 1=+/@:{~&6 7 8 NB. 11. Exactly 1 of statements 7, 8 and 9 are true. + 4=+/@:{.~&11 NB. 12. Exactly 4 of the preceding statements are true. ) testall=: (];"1 0<@I.@:(]~:(apply&><))"1) #:@i.@(2&^)@# diff --git a/Task/Twelve-statements/J/twelve-statements-4.j b/Task/Twelve-statements/J/twelve-statements-4.j index d27ef187bc..4f13768542 100644 --- a/Task/Twelve-statements/J/twelve-statements-4.j +++ b/Task/Twelve-statements/J/twelve-statements-4.j @@ -1,34 +1,2 @@ - (#~1=#@{::~&_1"1) testall S -┌───────────────────────┬──┐ -│0 0 0 0 1 0 0 1 0 0 1 0│0 │ -├───────────────────────┼──┤ -│0 0 0 0 1 0 0 1 0 1 1 1│0 │ -├───────────────────────┼──┤ -│0 0 0 1 0 0 0 1 0 1 1 1│0 │ -├───────────────────────┼──┤ -│1 0 0 0 1 0 0 0 0 0 0 0│7 │ -├───────────────────────┼──┤ -│1 0 0 0 1 0 0 1 0 0 0 0│10│ -├───────────────────────┼──┤ -│1 0 0 0 1 0 0 1 0 0 1 0│11│ -├───────────────────────┼──┤ -│1 0 0 0 1 0 0 1 0 1 1 1│11│ -├───────────────────────┼──┤ -│1 0 0 0 1 1 0 0 1 0 1 0│7 │ -├───────────────────────┼──┤ -│1 0 0 1 0 0 0 0 0 0 0 0│7 │ -├───────────────────────┼──┤ -│1 0 0 1 0 0 0 1 0 1 1 1│11│ -├───────────────────────┼──┤ -│1 0 0 1 0 1 0 1 1 0 0 0│5 │ -├───────────────────────┼──┤ -│1 0 1 1 0 0 0 1 1 0 0 0│6 │ -├───────────────────────┼──┤ -│1 0 1 1 0 1 1 0 1 0 0 0│8 │ -├───────────────────────┼──┤ -│1 1 0 1 0 0 1 0 1 0 0 1│11│ -├───────────────────────┼──┤ -│1 1 0 1 0 0 1 0 1 1 0 0│9 │ -├───────────────────────┼──┤ -│1 1 0 1 0 0 1 1 1 0 0 0│7 │ -└───────────────────────┴──┘ + 1+I.;(#~0=#@{::~&_1"1) testall S +1 3 4 6 7 11 diff --git a/Task/Twelve-statements/J/twelve-statements-5.j b/Task/Twelve-statements/J/twelve-statements-5.j index 3272f7a419..d27ef187bc 100644 --- a/Task/Twelve-statements/J/twelve-statements-5.j +++ b/Task/Twelve-statements/J/twelve-statements-5.j @@ -1,2 +1,34 @@ - (-N)&{. #: S <:@]^:((]-.@-:(apply&><)"1) (-N)&{.@#:@])^:(_) 2^N=.#S -1 0 1 1 0 1 1 0 0 0 1 0 + (#~1=#@{::~&_1"1) testall S +┌───────────────────────┬──┐ +│0 0 0 0 1 0 0 1 0 0 1 0│0 │ +├───────────────────────┼──┤ +│0 0 0 0 1 0 0 1 0 1 1 1│0 │ +├───────────────────────┼──┤ +│0 0 0 1 0 0 0 1 0 1 1 1│0 │ +├───────────────────────┼──┤ +│1 0 0 0 1 0 0 0 0 0 0 0│7 │ +├───────────────────────┼──┤ +│1 0 0 0 1 0 0 1 0 0 0 0│10│ +├───────────────────────┼──┤ +│1 0 0 0 1 0 0 1 0 0 1 0│11│ +├───────────────────────┼──┤ +│1 0 0 0 1 0 0 1 0 1 1 1│11│ +├───────────────────────┼──┤ +│1 0 0 0 1 1 0 0 1 0 1 0│7 │ +├───────────────────────┼──┤ +│1 0 0 1 0 0 0 0 0 0 0 0│7 │ +├───────────────────────┼──┤ +│1 0 0 1 0 0 0 1 0 1 1 1│11│ +├───────────────────────┼──┤ +│1 0 0 1 0 1 0 1 1 0 0 0│5 │ +├───────────────────────┼──┤ +│1 0 1 1 0 0 0 1 1 0 0 0│6 │ +├───────────────────────┼──┤ +│1 0 1 1 0 1 1 0 1 0 0 0│8 │ +├───────────────────────┼──┤ +│1 1 0 1 0 0 1 0 1 0 0 1│11│ +├───────────────────────┼──┤ +│1 1 0 1 0 0 1 0 1 1 0 0│9 │ +├───────────────────────┼──┤ +│1 1 0 1 0 0 1 1 1 0 0 0│7 │ +└───────────────────────┴──┘ diff --git a/Task/Twelve-statements/J/twelve-statements-6.j b/Task/Twelve-statements/J/twelve-statements-6.j new file mode 100644 index 0000000000..3272f7a419 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-6.j @@ -0,0 +1,2 @@ + (-N)&{. #: S <:@]^:((]-.@-:(apply&><)"1) (-N)&{.@#:@])^:(_) 2^N=.#S +1 0 1 1 0 1 1 0 0 0 1 0 diff --git a/Task/Twelve-statements/J/twelve-statements-7.j b/Task/Twelve-statements/J/twelve-statements-7.j new file mode 100644 index 0000000000..f03c660709 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-7.j @@ -0,0 +1,16 @@ +true=:1 :'(m-1)&{' + +S=: <;._2 (0 :0) + 12 = # NB. 1. This is a numbered list of twelve statements. + 3 (= +/) _6&{. NB. 2. Exactly 3 of the last 6 statements are true. + 2 (= +/) (12$0 1)&# NB. 3. Exactly 2 of the even-numbered statements are true. + 5 true (<: */) 6 7 true NB. 4. If statement 5 is true, then statements 6 and 7 are both true. + 0 (= +/) 2 3 4 true NB. 5. The 3 preceding statements are all false. + 4 (= +/) (12$1 0)&# NB. 6. Exactly 4 of the odd-numbered statements are true. + 1 (= +/) 2 3 true NB. 7. Either statement 2 or 3 is true, but not both. + 7 true (<: */) 5 6 true NB. 8. If statement 7 is true, then 5 and 6 are both true. + 3 (= +/) 6&{. NB. 9. Exactly 3 of the first 6 statements are true. + */@(11 12 true) NB. 10. The next two statements are both true. + 1 (= +/) 7 8 9 true NB. 11. Exactly 1 of statements 7, 8 and 9 are true. + 4 (= +/) }: NB. 12. Exactly 4 of the preceding statements are true. +) diff --git a/Task/Twelve-statements/J/twelve-statements-8.j b/Task/Twelve-statements/J/twelve-statements-8.j new file mode 100644 index 0000000000..bc8129efc8 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-8.j @@ -0,0 +1,17 @@ +'sum not mask'=: |:".;._2(0 :0) + 0; 0; 0 0 0 0 0 0 0 0 0 0 0 0 NB. 1. This is a numbered list of twelve statements. + 3; 0; 0 0 0 0 0 0 1 1 1 1 1 1 NB. 2. Exactly 3 of the last 6 statements are true. + 2; 0; 0 1 0 1 0 1 0 1 0 1 0 1 NB. 3. Exactly 2 of the even-numbered statements are true. + 2; 5; 0 0 0 0 0 1 1 0 0 0 0 0 NB. 4. If statement 5 is true, then statements 6 and 7 are both true. + 0; 0; 0 1 1 1 0 0 0 0 0 0 0 0 NB. 5. The 3 preceding statements are all false. + 4; 0; 1 0 1 0 1 0 1 0 1 0 1 0 NB. 6. Exactly 4 of the odd-numbered statements are true. + 1; 0; 0 1 1 0 0 0 0 0 0 0 0 0 NB. 7. Either statement 2 or 3 is true, but not both. + 2; 7; 0 0 0 0 1 1 0 0 0 0 0 0 NB. 8. If statement 7 is true, then 5 and 6 are both true. + 3; 0; 1 1 1 1 1 1 0 0 0 0 0 0 NB. 9. Exactly 3 of the first 6 statements are true. + 2; 0; 0 0 0 0 0 0 0 0 0 0 1 1 NB. 10. The next two statements are both true. + 1; 0; 0 0 0 0 0 0 1 1 1 0 0 0 NB. 11. Exactly 1 of statements 7, 8 and 9 are true. + 4; 0; 1 1 1 1 1 1 1 1 1 1 1 0 NB. 12. Exactly 4 of the preceding statements are true. +) +propositions=: |:#:i.2^#sum + +errors=: propositions~:(1 - not { 1,propositions) >. sum = mask +/ .*propositions diff --git a/Task/Twelve-statements/J/twelve-statements-9.j b/Task/Twelve-statements/J/twelve-statements-9.j new file mode 100644 index 0000000000..6c0bac80a8 --- /dev/null +++ b/Task/Twelve-statements/J/twelve-statements-9.j @@ -0,0 +1,4 @@ + #:I.0=+/errors +1 0 1 1 0 1 1 0 0 0 1 0 + 1+I.#:I.0=+/errors NB. true propositions for the consistent case +1 3 4 6 7 11 diff --git a/Task/Twelve-statements/Julia/twelve-statements.julia b/Task/Twelve-statements/Julia/twelve-statements.julia new file mode 100644 index 0000000000..533a1f0e95 --- /dev/null +++ b/Task/Twelve-statements/Julia/twelve-statements.julia @@ -0,0 +1,54 @@ +function showflaggedbits{T<:BitArray{1}}(a::T, f::T) + tf = map(x->x ? "T" : "F", a) + flg = map(x->x ? "*" : " ", f) + join(tf .* flg, " ") +end + +const props = [s -> length(s) == 12, + s -> sum(s[7:12]) == 3, + s -> sum(s[2:2:end]) == 2, + s -> !s[5] || (s[6] & s[7]), + s -> !any(s[2:4]), + s -> sum(s[1:2:end]) == 4, + s -> s[2] $ s[3], + s -> !s[7] || (s[5] & s[6]), + s -> sum(s[1:6]) == 3, + s -> s[11] & s[12], + s -> sum(s[7:9]) == 1, + s -> sum(s[1:end-1]) == 4] + +const NDIG = length(props) +NDIG < WORD_SIZE || println("WARNING, too many propositions!") + +mhist = zeros(Int, NDIG+1) + +println("Checking the ", NDIG, " statements against all possibilities.\n") +print(" "^15) +for i in 1:NDIG + print(@sprintf "%3d" i) +end +println() + +for i in 0:(2^NDIG-1) + s = bitpack(digits(i, 2, NDIG)) + t = bitpack([p(s) for p in props]) + misses = s$t + mcnt = sum(misses) + mhist[NDIG-mcnt+1] += 1 + mcnt < 2 || mcnt == NDIG || continue + if mcnt == 0 + print(" Exact Match: ") + elseif mcnt == NDIG + print(" Total Miss: ") + else + print(" Near Miss: ") + end + println(showflaggedbits(t, misses)) +end + +println() +println("Distribution of matches") +println(" Matches Cases") +for i in (NDIG+1):-1:1 + println(@sprintf " %2d => %4d" i-1 mhist[i]) +end diff --git a/Task/URL-decoding/00DESCRIPTION b/Task/URL-decoding/00DESCRIPTION index 35d8334261..f797aa4a5e 100644 --- a/Task/URL-decoding/00DESCRIPTION +++ b/Task/URL-decoding/00DESCRIPTION @@ -1,6 +1,8 @@ -This task (the reverse of [[URL encoding]]) is to provide a function +This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function or mechanism to convert an URL-encoded string into its original unencoded form. -'''Example''' +'''Test cases''' -The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/". +*The encoded string "http%3A%2F%2Ffoo%20bar%2F" should be reverted to the unencoded form "http://foo bar/". + +*The encoded string "google.com/search?q=%60Abdu%27l-Bah%C3%A1" should revert to the unencoded form "google.com/search?q=`Abdu'l-Bahá". diff --git a/Task/URL-decoding/ABAP/url-decoding.abap b/Task/URL-decoding/ABAP/url-decoding.abap new file mode 100644 index 0000000000..e52137abd0 --- /dev/null +++ b/Task/URL-decoding/ABAP/url-decoding.abap @@ -0,0 +1,12 @@ +REPORT Z_DECODE_URL. + +DATA: lv_encoded_url TYPE string VALUE 'http%3A%2F%2Ffoo%20bar%2F', + lv_decoded_url TYPE string. + +CALL METHOD CL_HTTP_UTILITY=>UNESCAPE_URL + EXPORTING + ESCAPED = lv_encoded_url + RECEIVING + UNESCAPED = lv_decoded_url. + +WRITE: 'Encoded URL: ', lv_encoded_url, /, 'Decoded URL: ', lv_decoded_url. diff --git a/Task/URL-decoding/AppleScript/url-decoding.applescript b/Task/URL-decoding/AppleScript/url-decoding.applescript new file mode 100644 index 0000000000..1d0b32c34b --- /dev/null +++ b/Task/URL-decoding/AppleScript/url-decoding.applescript @@ -0,0 +1 @@ +AST URL decode "google.com/search?q=%60Abdu%27l-Bah%C3%A1" diff --git a/Task/URL-decoding/C/url-decoding.c b/Task/URL-decoding/C/url-decoding.c index 4f79285e26..61c9677743 100644 --- a/Task/URL-decoding/C/url-decoding.c +++ b/Task/URL-decoding/C/url-decoding.c @@ -31,7 +31,7 @@ int decode(const char *s, char *dec) int main() { const char *url = "http%3A%2F%2ffoo+bar%2fabcd"; - char out[sizeof(url)]; + char out[strlen(url) + 1]; printf("length: %d\n", decode(url, 0)); puts(decode(url, out) < 0 ? "bad string" : out); diff --git a/Task/URL-decoding/Elixir/url-decoding.elixir b/Task/URL-decoding/Elixir/url-decoding.elixir new file mode 100644 index 0000000000..0dcb42f517 --- /dev/null +++ b/Task/URL-decoding/Elixir/url-decoding.elixir @@ -0,0 +1,2 @@ +IO.inspect URI.decode("http%3A%2F%2Ffoo%20bar%2F") +IO.inspect URI.decode("google.com/search?q=%60Abdu%27l-Bah%C3%A1") diff --git a/Task/URL-decoding/Go/url-decoding.go b/Task/URL-decoding/Go/url-decoding.go index 6a1bb18aa1..9824c7ded2 100644 --- a/Task/URL-decoding/Go/url-decoding.go +++ b/Task/URL-decoding/Go/url-decoding.go @@ -1,16 +1,21 @@ package main import ( - "fmt" - "net/url" + "fmt" + "log" + "net/url" ) -const escaped = "http%3A%2F%2Ffoo%20bar%2F" - func main() { - if u, err := url.QueryUnescape(escaped); err == nil { - fmt.Println(u) - } else { - fmt.Println(err) - } + for _, escaped := range []string{ + "http%3A%2F%2Ffoo%20bar%2F", + "google.com/search?q=%60Abdu%27l-Bah%C3%A1", + } { + u, err := url.QueryUnescape(escaped) + if err != nil { + log.Println(err) + continue + } + fmt.Println(u) + } } diff --git a/Task/URL-decoding/J/url-decoding-1.j b/Task/URL-decoding/J/url-decoding-1.j index 598749f6c0..103e44622e 100644 --- a/Task/URL-decoding/J/url-decoding-1.j +++ b/Task/URL-decoding/J/url-decoding-1.j @@ -1,2 +1,2 @@ require'strings convert' -urldecode=: rplc&(;"_1&a."2(,:tolower)'%',.hfd i.#a.) +urldecode=: rplc&(~.,/;"_1&a."2(,:tolower)'%',.toupper hfd i.#a.) diff --git a/Task/URL-decoding/J/url-decoding-3.j b/Task/URL-decoding/J/url-decoding-3.j index e82a0b3acc..ff9469d194 100644 --- a/Task/URL-decoding/J/url-decoding-3.j +++ b/Task/URL-decoding/J/url-decoding-3.j @@ -1 +1,2 @@ -urldecode=: rplc&(~.,/;"_1&a."2(,:tolower)'%',.hfd i.#a.) + urldecode 'google.com/search?q=%60Abdu%27l-Bah%C3%A1' +google.com/search?q=`Abdu'l-Bahá diff --git a/Task/URL-decoding/Julia/url-decoding.julia b/Task/URL-decoding/Julia/url-decoding.julia new file mode 100644 index 0000000000..f1c415d0e4 --- /dev/null +++ b/Task/URL-decoding/Julia/url-decoding.julia @@ -0,0 +1,7 @@ +using URIParser + +enc = "http%3A%2F%2Ffoo%20bar%2F" + +dcd = unescape(enc) + +println(enc, " => ", dcd) diff --git a/Task/URL-decoding/Objective-C/url-decoding.m b/Task/URL-decoding/Objective-C/url-decoding-1.m similarity index 100% rename from Task/URL-decoding/Objective-C/url-decoding.m rename to Task/URL-decoding/Objective-C/url-decoding-1.m diff --git a/Task/URL-decoding/Objective-C/url-decoding-2.m b/Task/URL-decoding/Objective-C/url-decoding-2.m new file mode 100644 index 0000000000..1f49833ade --- /dev/null +++ b/Task/URL-decoding/Objective-C/url-decoding-2.m @@ -0,0 +1,3 @@ +NSString *encoded = @"http%3A%2F%2Ffoo%20bar%2F"; +NSString *normal = [encoded stringByRemovingPercentEncoding]; +NSLog(@"%@", normal); diff --git a/Task/URL-decoding/REXX/url-decoding-2.rexx b/Task/URL-decoding/REXX/url-decoding-2.rexx index 9cf3204b6e..942bd73fa0 100644 --- a/Task/URL-decoding/REXX/url-decoding-2.rexx +++ b/Task/URL-decoding/REXX/url-decoding-2.rexx @@ -1,7 +1,7 @@ -/*REXX pgm convert an URL─encoded string ──► its original unencoded form*/ -url.1 = 'http%3A%2F%2Ffoo%20bar%2F' -url.2 = 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' -url.3 = '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' +/*REXX program converts an URL─encoded string ──► its original unencoded form.*/ +url.1='http%3A%2F%2Ffoo%20bar%2F' +url.2='mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' +url.3='%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' URLs=3 do j=1 for URLs say url.j @@ -9,7 +9,7 @@ URLs=3 say end /*j*/ exit -/*──────────────────────────────────DECODEURL subroutine────────────────*/ +/*────────────────────────────────────────────────────────────────────────────*/ decodeURL: procedure; parse arg encoded; decoded='' encoded=translate(encoded,,'+') /*special case for encoded blank.*/ diff --git a/Task/URL-decoding/REXX/url-decoding-3.rexx b/Task/URL-decoding/REXX/url-decoding-3.rexx index be9b40dcc7..d48e970597 100644 --- a/Task/URL-decoding/REXX/url-decoding-3.rexx +++ b/Task/URL-decoding/REXX/url-decoding-3.rexx @@ -1,17 +1,17 @@ -/*REXX pgm convert an URL─encoded string ──► its original unencoded form*/ -url.1 = 'http%3A%2F%2Ffoo%20bar%2F' -url.2 = 'mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' -url.3 = '%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' +/*REXX program converts an URL─encoded string ──► its original unencoded form.*/ +url.1='http%3A%2F%2Ffoo%20bar%2F' +url.2='mailto%3A%22Ivan%20Aim%22%20%3Civan%2Eaim%40email%2Ecom%3E' +url.3='%6D%61%69%6C%74%6F%3A%22%49%72%6D%61%20%55%73%65%72%22%20%3C%69%72%6D%61%2E%75%73%65%72%40%6D%61%69%6C%2E%63%6F%6D%3E' URLs=3 - do j=1 for URLs; say - say url.j - say URLdecode(url.j) + do j=1 for URLs; say /*process each URL; display blank line.*/ + say url.j /*display the original URL. */ + say URLdecode(url.j) /* " " decoded " */ end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────URLDECODE subroutine────────────────*/ -URLdecode: procedure; parse arg yyy /*get encoded URL from arg list. */ -yyy=translate(yyy,,'+') /*special case for encoded blank.*/ -URL='' +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +URLdecode: procedure; parse arg yyy /*get encoded URL from argument list. */ +yyy=translate(yyy,,'+') /*a special case for an encoded blank. */ +URL= do until yyy='' parse var yyy plain '%' +1 code +2 yyy URL=URL || plain diff --git a/Task/URL-encoding/00DESCRIPTION b/Task/URL-encoding/00DESCRIPTION index 53c8d236b2..c7f4d67351 100644 --- a/Task/URL-encoding/00DESCRIPTION +++ b/Task/URL-encoding/00DESCRIPTION @@ -31,3 +31,4 @@ However, this is an optional feature and is not a requirement of this task. ;See also [[URL decoding]] +[[URL parser]] diff --git a/Task/URL-encoding/AppleScript/url-encoding.applescript b/Task/URL-encoding/AppleScript/url-encoding.applescript new file mode 100644 index 0000000000..1416987375 --- /dev/null +++ b/Task/URL-encoding/AppleScript/url-encoding.applescript @@ -0,0 +1 @@ +AST URL encode "http://foo bar/" diff --git a/Task/URL-encoding/C/url-encoding.c b/Task/URL-encoding/C/url-encoding.c index ef9cc19e1b..6af08b12da 100644 --- a/Task/URL-encoding/C/url-encoding.c +++ b/Task/URL-encoding/C/url-encoding.c @@ -5,7 +5,7 @@ char rfc3986[256] = {0}; char html5[256] = {0}; /* caller responsible for memory */ -void encode(unsigned char *s, char *enc, char *tb) +void encode(const char *s, char *enc, char *tb) { for (; *s; s++) { if (tb[*s]) sprintf(enc, "%c", tb[*s]); @@ -16,8 +16,8 @@ void encode(unsigned char *s, char *enc, char *tb) int main() { - unsigned char url[] = "http://foo bar/"; - char enc[sizeof(url) * 3]; + const char url[] = "http://foo bar/"; + char enc[(strlen(url) * 3) + 1]; int i; for (i = 0; i < 256; i++) { diff --git a/Task/URL-encoding/Elixir/url-encoding.elixir b/Task/URL-encoding/Elixir/url-encoding.elixir new file mode 100644 index 0000000000..984c4ad90c --- /dev/null +++ b/Task/URL-encoding/Elixir/url-encoding.elixir @@ -0,0 +1,2 @@ +iex(1)> URI.encode("http://foo bar/", &(URI.char_unreserved?/1)) +"http%3A%2F%2Ffoo%20bar%2F" diff --git a/Task/URL-encoding/Groovy/url-encoding.groovy b/Task/URL-encoding/Groovy/url-encoding.groovy new file mode 100644 index 0000000000..89e94e46c5 --- /dev/null +++ b/Task/URL-encoding/Groovy/url-encoding.groovy @@ -0,0 +1,3 @@ +def normal = "http://foo bar/" +def encoded = URLEncoder.encode(normal, "utf-8") +println encoded diff --git a/Task/URL-encoding/Julia/url-encoding.julia b/Task/URL-encoding/Julia/url-encoding.julia new file mode 100644 index 0000000000..bc167203bb --- /dev/null +++ b/Task/URL-encoding/Julia/url-encoding.julia @@ -0,0 +1,6 @@ +using URIParser + +dcd = "http://foo bar/" +enc = escape(dcd) + +println(dcd, " => ", enc) diff --git a/Task/URL-encoding/Objective-C/url-encoding.m b/Task/URL-encoding/Objective-C/url-encoding-1.m similarity index 100% rename from Task/URL-encoding/Objective-C/url-encoding.m rename to Task/URL-encoding/Objective-C/url-encoding-1.m diff --git a/Task/URL-encoding/Objective-C/url-encoding-2.m b/Task/URL-encoding/Objective-C/url-encoding-2.m new file mode 100644 index 0000000000..d0c4676a62 --- /dev/null +++ b/Task/URL-encoding/Objective-C/url-encoding-2.m @@ -0,0 +1,3 @@ +NSString *normal = @"http://foo bar/"; +NSString *encoded = [normal stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]]; +NSLog(@"%@", encoded); diff --git a/Task/URL-encoding/Perl-6/url-encoding.pl6 b/Task/URL-encoding/Perl-6/url-encoding.pl6 index ecd9faec47..401ddcc8c7 100644 --- a/Task/URL-encoding/Perl-6/url-encoding.pl6 +++ b/Task/URL-encoding/Perl-6/url-encoding.pl6 @@ -1,3 +1,3 @@ my $url = 'http://foo bar/'; -say $url.subst(/<-[ A..Z a..z 0..9 ]>/, *.ord.fmt("%%%02X"), :g); +say $url.subst(/<-alnum>/, *.ord.fmt("%%%02X"), :g); diff --git a/Task/Ulam-spiral--for-primes-/C++/ulam-spiral--for-primes-.cpp b/Task/Ulam-spiral--for-primes-/C++/ulam-spiral--for-primes-.cpp new file mode 100644 index 0000000000..1fe709a234 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/C++/ulam-spiral--for-primes-.cpp @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include + +class ulamSpiral { +public: + void create( unsigned n, unsigned startWith = 1 ) { + _lst.clear(); + if( !( n & 1 ) ) n++; + _mx = n; + unsigned v = n * n; + _wd = static_cast( log10( static_cast( v ) ) ) + 1; + for( unsigned u = 0; u < v; u++ ) + _lst.push_back( -1 ); + + arrange( startWith ); + + } + void display( char c ) { + if( !c ) displayNumbers(); + else displaySymbol( c ); + } + +private: + bool isPrime( unsigned u ) { + if( u < 4 ) return u > 1; + if( !( u % 2 ) || !( u % 3 ) ) return false; + + unsigned q = static_cast( sqrt( static_cast( u ) ) ), + c = 5; + while( c <= q ) { + if( !( u % c ) || !( u % ( c + 2 ) ) ) return false; + c += 6; + } + return true; + } + void arrange( unsigned s ) { + unsigned stp = 1, n = 1, posX = _mx >> 1, + posY = posX, stC = 0; + int dx = 1, dy = 0; + + while( posX < _mx && posY < _mx ) { + _lst.at( posX + posY * _mx ) = isPrime( s ) ? s : 0; + s++; + + if( dx ) { + posX += dx; + if( ++stC == stp ) { + dy = -dx; + dx = stC = 0; + } + } else { + posY += dy; + if( ++stC == stp ) { + dx = dy; + dy = stC = 0; + stp++; + } + } + } + } + void displayNumbers() { + unsigned ct = 0; + for( std::vector::iterator i = _lst.begin(); i != _lst.end(); i++ ) { + if( *i ) std::cout << std::setw( _wd ) << *i << " "; + else std::cout << std::string( _wd, '*' ) << " "; + if( ++ct >= _mx ) { + std::cout << "\n"; + ct = 0; + } + } + std::cout << "\n\n"; + } + void displaySymbol( char c ) { + unsigned ct = 0; + for( std::vector::iterator i = _lst.begin(); i != _lst.end(); i++ ) { + if( *i ) std::cout << c; + else std::cout << " "; + if( ++ct >= _mx ) { + std::cout << "\n"; + ct = 0; + } + } + std::cout << "\n\n"; + } + + std::vector _lst; + unsigned _mx, _wd; +}; + +int main( int argc, char* argv[] ) +{ + ulamSpiral ulam; + ulam.create( 9 ); + ulam.display( 0 ); + ulam.create( 35 ); + ulam.display( '#' ); + return 0; +} diff --git a/Task/Ulam-spiral--for-primes-/Fortran/ulam-spiral--for-primes--1.f b/Task/Ulam-spiral--for-primes-/Fortran/ulam-spiral--for-primes--1.f new file mode 100644 index 0000000000..412f636228 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Fortran/ulam-spiral--for-primes--1.f @@ -0,0 +1,76 @@ +program ulam + implicit none + + integer, parameter :: nsize = 49 + integer :: i, j, n, x, y + integer :: a(nsize*nsize) = (/ (i, i = 1, nsize*nsize) /) + character(1) :: spiral(nsize, nsize) = " " + character(2) :: sstr + character(10) :: fmt + + n = 1 + x = nsize / 2 + 1 + y = x + if(isprime(a(n))) spiral(x, y) = "O" + n = n + 1 + + do i = 1, nsize-1, 2 + do j = 1, i + x = x + 1 + if(isprime(a(n))) spiral(x, y) = "O" + n = n + 1 + end do + + do j = 1, i + y = y - 1 + if(isprime(a(n))) spiral(x, y) = "O" + n = n + 1 + end do + + do j = 1, i+1 + x = x - 1 + if(isprime(a(n))) spiral(x, y) = "O" + n = n + 1 + end do + + do j = 1, i+1 + y = y + 1 + if(isprime(a(n))) spiral(x, y) = "O" + n = n + 1 + end do + end do + + do j = 1, nsize-1 + x = x + 1 + if(isprime(a(n))) spiral(x, y) = "O" + n = n + 1 + end do + + write(sstr, "(i0)") nsize + fmt = "(" // sstr // "(a,1x))" + do i = 1, nsize + write(*, fmt) spiral(:, i) + end do + +contains + +function isprime(number) + logical :: isprime + integer, intent(in) :: number + integer :: i + + if(number == 2) then + isprime = .true. + else if(number < 2 .or. mod(number,2) == 0) then + isprime = .false. + else + isprime = .true. + do i = 3, int(sqrt(real(number))), 2 + if(mod(number,i) == 0) then + isprime = .false. + exit + end if + end do + end if +end function +end program diff --git a/Task/Ulam-spiral--for-primes-/Fortran/ulam-spiral--for-primes--2.f b/Task/Ulam-spiral--for-primes-/Fortran/ulam-spiral--for-primes--2.f new file mode 100644 index 0000000000..59642022ec --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Fortran/ulam-spiral--for-primes--2.f @@ -0,0 +1,57 @@ + SUBROUTINE ULAMSPIRAL(START,ORDER) !Idle scribbles can lead to new ideas. +Careful with phasing: each lunge's first number is the second placed along its direction. + INTEGER START !Usually 1. + INTEGER ORDER !MUST be an odd number, so there is a middle. + INTEGER L,M,N !Counters. + COMPLEX WAY,PLACE !Just so. + CHARACTER*1 SPLOT(0:1) !Tricks for output. + PARAMETER (SPLOT = (/" ","*"/)) !Selected according to ISPRIME(n) + INTEGER TILE(ORDER,ORDER) !Work area. + WRITE (6,1) START,ORDER !Here we go. + 1 FORMAT ("Ulam spiral starting with ",I0,", of order ",I0,/) + IF (MOD(ORDER,2) .NE. 1) STOP "The order must be odd!" !Otherwise, out of bounds. + M = ORDER/2 + 1 !Find the number of the middle. + PLACE = CMPLX(M,M) !Start there. + WAY = (1,0) !Thence in the +x direction. + N = START !Different start, different layout. + DO L = 1,ORDER !Advance one step, then two, then three, etc. + DO LUNGE = 1,2 !But two lunges for each length. + DO STEP = 1,L !Take the steps. + TILE(INT(REAL(PLACE)),INT(AIMAG(PLACE))) = N !This number for this square. + PLACE = PLACE + WAY !Make another step. + N = N + 1 !Count another step. + END DO !And consider making another. + IF (N .GE. ORDER**2) EXIT !Otherwise, one lunge too many! + WAY = WAY*(0,1) !Rotate a quarter-turn counter-clockwise. + END DO !And make another lunge. + END DO !Until finished. +Cast forth the numbers. +c DO L = ORDER,1,-1 !From the top of the grid to the bottom. +c WRITE (6,66) TILE(1:ORDER,L) !One row at at time. +c 66 FORMAT (666I6) !This will do for reassurance. +c END DO !Line by line. +Cast forth the splots. + DO L = ORDER,1,-1 !Just put out a marker. + WRITE (6,67) (SPLOT(ISPRIME(TILE(M,L))),M = 1,ORDER) !One line at a time. + 67 FORMAT (666A1) !A single character at each position. + END DO !On to the next row. + END SUBROUTINE ULAMSPIRAL !So much for a boring lecture. + + INTEGER FUNCTION ISPRIME(N) !Returns 0 or 1. + INTEGER N !The number. + INTEGER F,Q !Factor and quotient. + ISPRIME = 0 !The more likely outcome. + IF (N.LE.1) RETURN !Just in case the start is peculiar. + IF (N.LE.3) GO TO 2 !Oops! I forgot this! + IF (MOD(N,2).EQ.0) RETURN !Special case. + F = 1 !Now get stuck in to testing odd numbers. + 1 F = F + 2 !A trial factor. + Q = N/F !The quotient. + IF (N .EQ. Q*F) RETURN !No remainder? Not a prime. + IF (Q.GT.F) GO TO 1 !Thus chug up to the square root. + 2 ISPRIME = 1 !Well! + END FUNCTION ISPRIME !Simple enough. + + PROGRAM TWIRL + CALL ULAMSPIRAL(1,49) + END diff --git a/Task/Ulam-spiral--for-primes-/Haskell/ulam-spiral--for-primes-.hs b/Task/Ulam-spiral--for-primes-/Haskell/ulam-spiral--for-primes-.hs new file mode 100644 index 0000000000..192ee48822 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Haskell/ulam-spiral--for-primes-.hs @@ -0,0 +1,45 @@ +import Data.List +import Data.Numbers.Primes + +-- Add a row to existing spiral by rotating right and adding new row to top +-- Results in spirals that turn in the wrong direction and must later be fixed. +addRow :: [[Int]] -> [[Int]] +addRow spiral = let height = length spiral + width = length $ head spiral + row = [height*width+1.. height*width+height] + in row : reverse (transpose spiral) + +-- Generate spiral by adding two rows (vertical & horizontal) to smaller spiral +preSpiral :: Int => [[Int]] +preSpiral 1 = [[1]] +preSpiral n = addRow $ addRow $ preSpiral (n-1) + +-- Make ulamSpiral; fix spiral direction by flipping preSpiral. +ulamSpiral :: Int => [[Int]] +ulamSpiral n | odd n = reverse $ preSpiral n + | otherwise = map reverse $ preSpiral n + +-- Make and print ulamSpiral: + -- Use converter to change numbers to strings. + -- Change empty strings to dashes. + -- Pad strings out to correct length before printing. +prettyPrintSpiral :: Int -> (Int -> String) -> IO () +prettyPrintSpiral n converter = + let stringSpiral = map (map converter) (ulamSpiral n) + maxLen = maximum (map (maximum.map length) stringSpiral) + dashFunc s = if s == "" then replicate maxLen '-' else s + padFunc s = replicate (maxLen - length s) ' ' ++ s + padded = map (padFunc.dashFunc) + showRow = unwords.padded + in mapM_ (putStrLn.showRow) stringSpiral + + +main :: IO () +main = do + -- Display with converter that shows primes as Strings. + prettyPrintSpiral 10 (\n -> if isPrime n then show n else "") + + putStrLn "" + + -- Display with converter that shows primes as single dots. + prettyPrintSpiral 60 (\n -> if isPrime n then "*" else " ") diff --git a/Task/Ulam-spiral--for-primes-/Pascal/ulam-spiral--for-primes-.pascal b/Task/Ulam-spiral--for-primes-/Pascal/ulam-spiral--for-primes-.pascal new file mode 100644 index 0000000000..69c6c07c36 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Pascal/ulam-spiral--for-primes-.pascal @@ -0,0 +1,186 @@ +Program Ulam; Uses crt; +{Concocted by R.N.McLean (whom God preserve), ex Victoria university, NZ.} +{$B- evaluate boolean expressions only so far as necessary.} +{$R+ range checking...} + + FUNCTION Trim(S : string) : string; + var L1,L2 : integer; + BEGIN + L1 := 1; + WHILE (L1 <= LENGTH(S)) AND (S[L1] = ' ') DO INC(L1); + L2 := LENGTH(S); + WHILE (S[L2] = ' ') AND (L2 > L1) DO DEC(L2); + IF L2 >= L1 THEN Trim := COPY(S,L1,L2 - L1 + 1) ELSE Trim := ''; + END; {Of Trim.} + +FUNCTION Ifmt(Digits : integer) : string; + var S : string[255]; + BEGIN + STR(Digits,S); + Ifmt := Trim(S); + END; { Ifmt } + Function min(i,j: integer): integer; + begin + if i <= j then min:=i else min:=j; + end; + Procedure Croak(Gasp: string); {A lethal word.} + Begin + WriteLn; + WriteLn(Gasp); + HALT; {This way to the egress...} + End; + var ScreenLine,ScreenColumn: byte; {Line and column position.} +{=========================enough support===================} + const Mstyle = 6; {Display different results.} + const StyleName: array[1..Mstyle] of string = ('IsPrime','First Prime Factor Index', + 'First Prime Factor','Number of Prime Factors', + 'Sum of Prime Factors','Sum of Proper Factors'); + const OrderLimit = 49; Limit2 = OrderLimit*OrderLimit; {A 50-line screen has room for a heading.} + var Tile: array[1..OrderLimit,1..OrderLimit] of integer; {Alas, can't put [Order,Order], only constants.} + var FirstPrimeFactorIndex,FirstPrimeFactor,NumPFactor,SumPFactor,SumFactor: array[1..Limit2] of integer; + const enuffP = 17; {Given the value of Limit2.} + const Prime: array[1..enuffP] of integer = (1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53); + Procedure Prepare; {Various arrays are to be filled for the different styles.} + var i,j,p: integer; + Begin + for i:=1 to limit2 do {Alas, can't just put A:=0;} + begin {Nor clear A;} + FirstPrimeFactorIndex[i]:=1; {Prime[1] = 1, so this means no other divisor.} + FirstPrimeFactor[i]:=0; + NumPFactor[i]:=0; + SumPFactor[i]:=0; + SumFactor[i]:=1; {1 is counted as a proper factor.} + end; + FirstPrimeFactorIndex[1]:=0; {Fiddle, as 1 is not a prime number.} + SumFactor[1]:=0; {N is not a proper factor of N, so 1 has no proper factors...} + for i:=2 to enuffP do {Prime[1] = 1, Prime[2] = 2, so start with i = 2.} + begin + p:=Prime[i]; + j:=p + p; + while j <= Limit2 do + begin + if FirstPrimeFactorIndex[j] = 1 then FirstPrimeFactorIndex[j]:=i; + if FirstPrimeFactor[j] = 0 then FirstPrimeFactor[j]:=p; + SumPFactor[j]:=SumPFactor[j] + p; + inc(NumPFactor[j]); + j:=j + p; + end; + end; + for i:=2 to Limit2 div 2 do {Step through all possible proper factors.} + begin {N is not a proper factor of N, so start at 2N,} + j:=2*i; {for which N is a proper factor of 2N.} + while j <= Limit2 do {Sigh. for j:=2*i:Limit2:i do ... Next i;} + begin + SumFactor[j]:=SumFactor[j] + i; + j:=j + i; + end; + end; + End; {Enough preparation.} + + const enuffC = 11; {Perhaps the colours will highlight interesting patterns.} + const colour:array[0..enuffC] of byte = (black,white,LightRed, + LightMagenta,Yellow,LightGreen,LightCyan,LightBlue,LightGray, + Red,Green,DarkGray); {Colours on the screen don't always match their name!} + + Procedure UlamSpiral(Order,Start,Style: integer); {Generate the numbers, then display.} + Function Encode(N: integer): integer; {Acording to Style, choose a result to show.} + Begin + if N <= 1 then Encode:=0 + else + case style of + 1:if FirstPrimeFactorIndex[N] = 1 then Encode:=1 else Encode:=0; {1 = Prime.} + 2:Encode:=FirstPrimeFactorIndex[N]; + 3:Encode:=FirstPrimeFactor[N]; + 4:Encode:=NumPFactor[N]; + 5:Encode:=SumPFactor[N]; + 6:Encode:=SumFactor[N]; + end; + End; {So much for encoding.} + var Place,Way: array[1..2] of integer; {Complex numbers.} + var m, {Middle.} + N, {Counter.} + length, {length of a side.} + lunge, {two lunges for each length.} + step {steps to make up a lunge of some length.} + : integer; + var i,j: integer; {Steppers.} + var code,it: integer; {Mess with the results.} + label XX; {Escape the second lunge.} + var OutF: text; {Utter drivel. It is a disc file.} + Begin + Write('Ulam Spiral, order ',Order,', start ',Start,', style ',style); {Start the heading.} + if style <= 0 then Croak('Must be a positive style'); + if style > Mstyle then croak('Last known style is '+ifmt(Mstyle)); + if Order > OrderLimit then Croak('Array OrderLimit is order '+IFmt(OrderLimit)); + if Order mod 2 <>1 then Croak('The order must be an odd number!'); + writeln(': ',StyleName[Style]); {Finish the heading. The pattern starts with line two.} + Assign(OutF,'Ulam.txt'); Rewrite(OutF); Writeln(OutF,'Ulam spiral: the codes for ',StyleName[style]); + m:=order div 2 + 1; {This is why Order must be odd.} + Place[1]:=m; Place[2]:=m; {Start at the middle.} + way[1]:=1; way[2]:=0; {Initial direction is along the x-axis.} + n:=Start; + for length:=1 to Order do {Advance through the lengths.} + for lunge:=1 to 2 do {Two lunges for each length.} + begin + for step:=1 to length do {Make the steps.} + begin + Tile[Place[1],Place[2]]:=N; + for i:=1 to 2 do Place[i]:=Place[i] + Way[i]; {Place:=Place + Way;} + N:=N + 1; + end; + if N >= Order*Order then goto XX; {Each corner piece is part of two lunges.} + i:=Way[1]; Way[1]:=-Way[2]; Way[2]:=i; {Way:=Way*(0,1) in complex numbers: (x,y)*(0,1) = (-y,x).} + end; +XX:for i:=order downto 1 do {Output: Lines count downwards, y runs upwards.} + begin {The first line is the topmost y.} + for j:=1 to order do {(line,column) = (y,x).} + begin {Work along the line.} + it:=Tile[j,i]; {Grab the number.} + code:=Encode(it); {Presentation scheme.} + Write(OutF,'(',it:4,':',code:2,')'); {Debugging...} + if FirstPrimeFactorIndex[it] > 1 then TextBackGround(Black) {Not a prime.} + else if it = 1 then TextBackGround(Black) {Darkness for one, also.} + else TextBackGround(White); {A prime number!} + TextColor(Colour[min(code,enuffC)]); {A lot of fuss for this!} + {Write(code:2);} + {Write(it:3);} + if it <= 9 then write(it) else Write('*'); {Thus mark the centre.} + end; {Next position along the line.} + if i > 1 then WriteLn; {Ending the last line would scroll the heading up.} + WriteLn(OutF); {But this is good for the text file.} + end; {On to the next line.} + Close(OutF); {Finished with the trace.} +{Some revelations to help in choosing a colour sequence.} + ScreenLine:=WhereY; ScreenColumn:=WhereX; {Gibberish to find the location.} + if Style > 1 then {Only the fancier styles go beyond 0 and 1.} + begin {So explain only for them.} + GoToXY(ScreenColumn + 1,ScreenLine - 4); {Unused space is to the right.} + TextColor(White); write('Colour sequence'); {Given 80-column displays.} + GoToXY(ScreenColumn + 1,ScreenLine - 3); {And no more than 50 lines.} + for i:=1 to enuffC do begin TextColor(Colour[i]); write(i); end; {My sequence.} + GoToXY(ScreenColumn + 1,ScreenLine - 2); + TextColor(White); write('From options'); + GoToXY(ScreenColumn + 1,ScreenLine - 1); + for i:=1 to 15 do begin TextColor(i);write(i); end; {The options.} + end; + End; {of UlamSpiral.} + + var start,wot,order: integer; {A selector.} + BEGIN {After all that.} + TextMode(Lo(LastMode) + Font8x8); {Gibberish sets 43 lines on EGA and 50 on VGA.} + ClrScr; TextColor(White); {This also gives character blocks that are almost square...} + WriteLn('Presents consecutive integers in a spiral, as per Stanislaw Ulam.'); + WriteLn('Starting with 1, runs up to Order*Order.'); + Write('What value for Order? (Limit ' + Ifmt(OrderLimit),'): '); + ReadLn(Order); {ReadKey needs no "enter", but requires decoding.} + if (order < 1) or (order > OrderLimit) then Croak('Out of range!'); {Oh dear.} + Prepare; + wot:=1; {The original task.} + Repeat {Until bored?} + ClrScr; {Scrub any previous stuff.} + UlamSpiral(Order,1,wot); {The deed!} + GoToXY(ScreenColumn + 1,ScreenLine); {Note that the last WriteLn was skipped.} + TextColor(White); Write('Enter 0, or 1 to '+Ifmt(Mstyle),': '); {Wot now?} + ReadLn(wot); {Receive.} + Until (wot <= 0) or (wot > Mstyle); {Alas, "Enter" must be pressed.} + END. diff --git a/Task/Ulam-spiral--for-primes-/Ruby/ulam-spiral--for-primes--1.rb b/Task/Ulam-spiral--for-primes-/Ruby/ulam-spiral--for-primes--1.rb new file mode 100644 index 0000000000..f682348df1 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Ruby/ulam-spiral--for-primes--1.rb @@ -0,0 +1,28 @@ +require 'prime' + +def cell(n, x, y, start=1) + y, x = y - n/2, x - (n - 1)/2 + l = 2 * [x.abs, y.abs].max + d = y >= x ? l*3 + x + y : l - x - y + (l - 1)**2 + d + start - 1 +end + +def show_spiral(n, symbol=nil, start=1) + puts "\nN : #{n}" + format = "%#{(start + n*n - 1).to_s.size}s " + n.times do |y| + n.times do |x| + i = cell(n,x,y,start) + if symbol + print i.prime? ? symbol[0] : symbol[1] + else + print format % (i.prime? ? i : '') + end + end + puts + end +end + +show_spiral(9) +show_spiral(25) +show_spiral(25, "# ") diff --git a/Task/Ulam-spiral--for-primes-/Ruby/ulam-spiral--for-primes--2.rb b/Task/Ulam-spiral--for-primes-/Ruby/ulam-spiral--for-primes--2.rb new file mode 100644 index 0000000000..996e41c708 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Ruby/ulam-spiral--for-primes--2.rb @@ -0,0 +1,36 @@ +require 'prime' + +def spiral_generator(x=0, y=0) + Enumerator.new do |yielder| + yielder << [x, y] # start position + dx, dy = 0, 1 # first direction + yielder << [x+=dx, y+=dy] # second position + 0.step do |i| + 2.times do + i.times{ yielder << [x+=dx, y+=dy] } # going straight + dx, dy = -dy, dx # 90 degree turn + yielder << [x+=dx, y+=dy] + end + end + end +end + +def ulam_spiral(n, start=1) + h = Hash.new(0) + position = spiral_generator + (start ... start+n*n).each do |i| + pos = position.next + h[pos] = 1 if i.prime? + end + + chr = [[' ', '▄'], ['▀', '█']] + (xmin, xmax), (ymin, ymax) = h.keys.transpose.map(&:minmax) + (xmin..xmax).step(2).each do |x| + puts (ymin..ymax).map{|y| chr[h[[x,y]]][h[[x+1,y]]]}.join + end +end + +[11, 122].each do |n| + puts "\nN : #{n}" + ulam_spiral(n) +end diff --git a/Task/Ulam-spiral--for-primes-/Tcl/ulam-spiral--for-primes-.tcl b/Task/Ulam-spiral--for-primes-/Tcl/ulam-spiral--for-primes-.tcl new file mode 100644 index 0000000000..d1b32aecf0 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Tcl/ulam-spiral--for-primes-.tcl @@ -0,0 +1,51 @@ +proc is_prime {n} { + if {$n == 1} {return 0} + if {$n in {2 3 5}} {return 1} + for {set i 2} {$i*$i <= $n} {incr i} { + if {$n % $i == 0} {return 0} + } + return 1 +} + +proc spiral {w h} { + yield [info coroutine] + set x [expr {$w / 2}] + set y [expr {$h / 2}] + set n 1 + set dir 0 + set steps 1 + set step 1 + while {1} { + yield [list $x $y] + switch $dir { + 0 {incr x} + 1 {incr y -1} + 2 {incr x -1} + 3 {incr y} + } + if {![incr step -1]} { + set dir [expr {($dir+1)%4}] + if {$dir % 2 == 0} { + incr steps + } + set step $steps + } + } +} + +set radius 16 +set side [expr {1 + 2 * $radius}] +set n [expr {$side * $side}] +set cells [lrepeat $side [lrepeat $side ""]] +set i 1 + +coroutine spin spiral $side $side + +while {$i < $n} { + lassign [spin] y x + set c [expr {[is_prime $i] ? "\u169b" : " "}] + lset cells $x $y $c + incr i +} + +puts [join [lmap row $cells {join $row " "}] \n] diff --git a/Task/Ulam-spiral--for-primes-/VBScript/ulam-spiral--for-primes-.vb b/Task/Ulam-spiral--for-primes-/VBScript/ulam-spiral--for-primes-.vb new file mode 100644 index 0000000000..7ea52764c1 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/VBScript/ulam-spiral--for-primes-.vb @@ -0,0 +1,80 @@ +Function build_spiral(n) + 'declare a two dimentional array + Dim matrix() + ReDim matrix(n-1,n-1) + 'determine starting point + x = (n-1)/2 : y = (n-1)/2 + 'set the initial iterations + x_max = 1 : y_max = 1 : count = 1 + 'set initial direction + dir = "R" + 'populate the array + For i = 1 To n*n + l = Len(n*n) + If IsPrime(i) Then + matrix(x,y) = Right("000" & i,l) + Else + matrix(x,y) = String(l,"-") + End If + Select Case dir + Case "R" + If x_max > 0 Then + x = x + 1 : x_max = x_max - 1 + Else + dir = "U" : y_max = count + y = y - 1 : y_max = y_max - 1 + End If + Case "U" + If y_max > 0 Then + y = y - 1 : y_max = y_max - 1 + Else + dir = "L" : count = count + 1 : x_max = count + x = x - 1 : x_max = x_max - 1 + End If + Case "L" + If x_max > 0 Then + x = x - 1 : x_max = x_max - 1 + Else + dir = "D" : y_max = count + y = y + 1 : y_max = y_max - 1 + End If + Case "D" + If y_max > 0 Then + y = y + 1 : y_max = y_max - 1 + Else + dir = "R" : count = count + 1 : x_max = count + x = x + 1 : x_max = x_max - 1 + End If + End Select + Next + 'print the matrix + For y = 0 To n - 1 + For x = 0 To n - 1 + If x = n - 1 Then + WScript.StdOut.Write matrix(x,y) + Else + WScript.StdOut.Write matrix(x,y) & vbTab + End If + Next + WScript.StdOut.WriteLine + Next +End Function + +Function IsPrime(n) + If n = 2 Then + IsPrime = True + ElseIf n <= 1 Or n Mod 2 = 0 Then + IsPrime = False + Else + IsPrime = True + For i = 3 To Int(Sqr(n)) Step 2 + If n Mod i = 0 Then + IsPrime = False + Exit For + End If + Next + End If +End Function + +'test with 9 +build_spiral(9) diff --git a/Task/Unbias-a-random-generator/Elixir/unbias-a-random-generator.elixir b/Task/Unbias-a-random-generator/Elixir/unbias-a-random-generator.elixir index fdbae27a39..4d6e5cb2f5 100644 --- a/Task/Unbias-a-random-generator/Elixir/unbias-a-random-generator.elixir +++ b/Task/Unbias-a-random-generator/Elixir/unbias-a-random-generator.elixir @@ -1,11 +1,9 @@ defmodule Random do def init() do - :random.seed(:erlang.now()) + :random.seed(:erlang.now) end def randN(n) do - if Enum.member?(3..6, n) do - if :random.uniform(n) == 1, do: 1, else: 0 - end + if :random.uniform(n) == 1, do: 1, else: 0 end def unbiased(n) do {x, y} = {randN(n), randN(n)} @@ -14,7 +12,7 @@ defmodule Random do end IO.puts "N biased unbiased" -Random.init() +Random.init for n <- 3..6 do xs = for _ <- 1..10000, do: Random.randN(n) ys = for _ <- 1..10000, do: Random.unbiased(n) diff --git a/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx b/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx index 4d362f08e9..168c5857f8 100644 --- a/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx +++ b/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx @@ -1,21 +1,21 @@ -/*REXX program generates unbiased random numbers and displays results.*/ -parse arg samples seed . /*allow specification of options.*/ -if samples=='' | samples==',' then samples=1000 /*SAMPLES specified?*/ -if seed\=='' then call random ,,seed /*if specified, use it for RANDOM*/ -w=14 /*width of most columnar output */ -dash='─' /*filler character for column hdr*/ -say ct('N',3) ct('biased') ct('biased'), /*show the */ - ct('unbiased') ct('unbiased') ct('samples') /*6col hdr.*/ +/*REXX program generates unbiased random numbers and displays the results. */ +parse arg # R seed . /*get optional parameters from the CL. */ +if #=='' | #==',' then #=1000 /*# the number of SAMPLES to be used.*/ +if R=='' | R==',' then R=6 /*R the high number for the range. */ +if seed\=='' then call random ,,seed /*Not specified? Use for RANDOM seed. */ +w=12; pad=left('',5) /*width of columnar output; indentation*/ +dash='─'; @b='biased'; @ub='un'@b /*literals for the SAY column headers. */ +say pad c('N',5) c(@b) c(@b'%') c(@ub) c(@ub"%") c('samples') /*6 col header.*/ dash= - do N=3 to 6; b=0; u=0; do j=1 for samples - b=b + randN(N) - u=u + unbiased() - end /*j*/ - say ct(N,3) ct(b) pc(b) ct(u) pc(u) ct(samples) - end /*N*/ -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────one─line subroutines───────────────*/ -ct: return center(arg(1), word(arg(2) w,1), right(dash,1)) -pc: return ct(format(arg(1)/samples*100, , 2)'%') -randN: parse arg z; return random(1, z)==z -unbiased: do until x\==randN(N); x=randN(N); end; return x + do N=3 to R; b=0; u=0; do j=1 for # + b=b+randN(N) + u=u+unbiased() + end /*j*/ + say pad c(N,5) c(b) pct(b) c(u) pct(u) c(#) + end /*N*/ +exit /*stick a fork in it, we're all done. */ +/*───────────────────────────────────one─liner subroutines────────────────────*/ +c: return center(arg(1), word(arg(2) w,1), left(dash,1)) +pct: return c(format(arg(1)/#*100,,2)'%') /*2 decimal digs.*/ +randN: parse arg z; return random(1,z)==z +unbiased: do until x\==randN(N); x=randN(N); end; return x diff --git a/Task/Undefined-values/Fortran/undefined-values.f b/Task/Undefined-values/Fortran/undefined-values.f new file mode 100644 index 0000000000..bcde6203db --- /dev/null +++ b/Task/Undefined-values/Fortran/undefined-values.f @@ -0,0 +1 @@ +IsNaN(x) diff --git a/Task/Undefined-values/REXX/undefined-values.rexx b/Task/Undefined-values/REXX/undefined-values.rexx index 86254fc5e8..7f4124ad89 100644 --- a/Task/Undefined-values/REXX/undefined-values.rexx +++ b/Task/Undefined-values/REXX/undefined-values.rexx @@ -1,23 +1,20 @@ -/*REXX program to test if a variable is defined. */ - -tlaloc = "rain god of the Aztecs." - - - /*check if the rain god is defined.*/ -y='tlaloc' -if symbol(y)=="VAR" then say y 'is defined.' - else say y "ain't defined." - - - /*check if the fire god is defined.*/ - -y='xiuhtecuhtli' -if symbol(y)=="VAR" then say y 'is defined.' - else say y "ain't defined." - - -drop tlaloc /*un-define the TLALOC variable. */ - /*check if the rain god is defined.*/ -y='tlaloc' -if symbol(y)=="VAR" then say y 'is defined.' - else say y "ain't defined." +/*REXX program test if a (REXX) variable is defined or not defined. */ +tlaloc = "rain god of the Aztecs." /*assign a value to the Aztec rain god.*/ + /*check if the rain god is defined. */ +y= 'tlaloc' +if symbol(y)=="VAR" then say y ' is defined.' + else say y "isn't defined." + + /*check if the fire god is defined. */ + +y= 'xiuhtecuhtli' /*assign a value to the Aztec file god.*/ +if symbol(y)=="VAR" then say y ' is defined.' + else say y "isn't defined." + + +drop tlaloc /*un─define the TLALOC REXX variable.*/ + /*check if the rain god is defined. */ +y= 'tlaloc' +if symbol(y)=="VAR" then say y ' is defined.' + else say y "isn't defined." + /*stick a fork in it, we're all done. */ diff --git a/Task/Unicode-strings/Common-Lisp/unicode-strings.lisp b/Task/Unicode-strings/Common-Lisp/unicode-strings.lisp new file mode 100644 index 0000000000..46e6230037 --- /dev/null +++ b/Task/Unicode-strings/Common-Lisp/unicode-strings.lisp @@ -0,0 +1,2 @@ +(defvar ♥♦♣♠ "♥♦♣♠") +(defun ✈ () "a plane unicode function") diff --git a/Task/Unicode-variable-names/Rust/unicode-variable-names.rust b/Task/Unicode-variable-names/Rust/unicode-variable-names.rust index 5ac0415af8..0f96c3d8a4 100644 --- a/Task/Unicode-variable-names/Rust/unicode-variable-names.rust +++ b/Task/Unicode-variable-names/Rust/unicode-variable-names.rust @@ -1,9 +1,7 @@ -// rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800) - -#[feature(non_ascii_idents)]; +#![feature(non_ascii_idents)] fn main() { - let mut Δ:int = 1; + let mut Δ: i32 = 1; Δ += 1; println!("{}", Δ); } diff --git a/Task/Unix-ls/Ada/unix-ls.ada b/Task/Unix-ls/Ada/unix-ls.ada index 4edec9cd49..f9f341e76d 100644 --- a/Task/Unix-ls/Ada/unix-ls.ada +++ b/Task/Unix-ls/Ada/unix-ls.ada @@ -10,6 +10,7 @@ procedure Directory_List is function SName return String is (Simple_Name(Found)); begin + -- search directory and store it in Result, a vector of strings Start_Search(Search, Directory => ".", Pattern =>""); while More_Entries(Search) loop Get_Next_Entry(Search, Found); @@ -20,9 +21,11 @@ begin Result.Append(Name); end if; -- ingnore filenames beginning with "." end; - end loop; -- now Result holds the entire directory in arbitrary order + end loop; -- Result holds the entire directory in arbitrary order - Sort(Result); -- nor Result holds the directory in proper order + Sort(Result); -- Result holds the directory in proper order + + -- print Result for I in Result.First_Index .. Result.Last_Index loop Put_Line(Result.Element(I)); end loop; diff --git a/Task/Unix-ls/C++/unix-ls.cpp b/Task/Unix-ls/C++/unix-ls.cpp new file mode 100644 index 0000000000..c7540264e5 --- /dev/null +++ b/Task/Unix-ls/C++/unix-ls.cpp @@ -0,0 +1,17 @@ +#include +#include +#include + +namespace fs = boost::filesystem; + +int main(void) +{ + fs::path p(fs::current_path()); + std::set tree; + + for (auto it = fs::directory_iterator(p); it != fs::directory_iterator(); ++it) + tree.insert(it->path().filename().native()); + + for (auto entry : tree) + std::cout << entry << '\n'; +} diff --git a/Task/Unix-ls/Pascal/unix-ls.pascal b/Task/Unix-ls/Pascal/unix-ls.pascal new file mode 100644 index 0000000000..116985d3be --- /dev/null +++ b/Task/Unix-ls/Pascal/unix-ls.pascal @@ -0,0 +1,11 @@ +Program ls; {To list the names of all files/directories in the current directory.} + Uses DOS; + var DirInfo: SearchRec; {Predefined. See page 403 of the Turbo Pascal 4 manual.} + BEGIN + FindFirst('*.*',AnyFile,DirInfo); {AnyFile means any file name OR directory name.} + While DOSerror = 0 do {Result of FindFirst/Next not being a function, damnit.} + begin + WriteLn(DirInfo.Name); + FindNext(DirInfo); + end; + END. diff --git a/Task/Unix-ls/Rust/unix-ls.rust b/Task/Unix-ls/Rust/unix-ls.rust index 3ea0f7c86c..045cb32914 100644 --- a/Task/Unix-ls/Rust/unix-ls.rust +++ b/Task/Unix-ls/Rust/unix-ls.rust @@ -1,17 +1,22 @@ -use std::os; -use std::io::fs; +use std::env; +use std::fs; +use std::path::Path; 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()); - } + // ignoring all arguments except the 1st + match env::args().nth(1) { // check if the program received an argument + Some(path) => { print_files(Path::new(&path)); } + _ => { print_files( &env::current_dir().unwrap() ); } + // note that current_dir value might be invalid, so it's a Result + } +} - filenames.sort(); - for filename in filenames.iter() { - println!("{}", filename); - } +fn print_files(path:&Path) { + let mut entries: Vec<_> = fs::read_dir(path).unwrap() + .map(|x| x.unwrap().file_name()) + .collect(); + entries.sort(); + for x in entries { + println!("{}", x.to_string_lossy()); + } } diff --git a/Task/Update-a-configuration-file/Perl-6/update-a-configuration-file.pl6 b/Task/Update-a-configuration-file/Perl-6/update-a-configuration-file.pl6 new file mode 100644 index 0000000000..0d91f72fa8 --- /dev/null +++ b/Task/Update-a-configuration-file/Perl-6/update-a-configuration-file.pl6 @@ -0,0 +1,42 @@ +#!/usr/bin/env perl6 + +my $tmpfile = tmpfile; + +sub MAIN ($file, *%changes) { + %changes.=map({; .key.uc => .value }); + my %seen; + + my $out = open $tmpfile, :w; + + for $file.IO.lines { + when /:s ^ ('#' .* | '') $/ { + say $out: ~$0; + } + when /:s ^ (';'+)? [(\w+) (\w+)?]? $/ { + next if !$1 or %seen{$1.uc}++; + my $new = %changes{$1.uc}:delete; + say $out: format-line $1, |( !defined($new) ?? ($2, !$0) !! + $new ~~ Bool ?? ($2, $new) !! ($new, True) ); + } + default { + note "Malformed line: $_\nAborting."; + exit 1; + } + } + + say $out: format-line .key, |(.value ~~ Bool ?? (Nil, .value) !! (.value, True)) + for %changes; + + run 'mv', $tmpfile, $file; # work-around for NYI `move $tmpfile, $file;` +} + +END { unlink $tmpfile if $tmpfile.IO.e } + + +sub format-line ($key, $value, $enabled) { + ("; " if !$enabled) ~ $key.uc ~ (" $value" if defined $value); +} + +sub tmpfile { + $*SPEC.catfile: $*SPEC.tmpdir, ("a".."z").roll(20).join +} diff --git a/Task/Update-a-configuration-file/REXX/update-a-configuration-file-1.rexx b/Task/Update-a-configuration-file/REXX/update-a-configuration-file-1.rexx new file mode 100644 index 0000000000..3807496df4 --- /dev/null +++ b/Task/Update-a-configuration-file/REXX/update-a-configuration-file-1.rexx @@ -0,0 +1,45 @@ +/*REXX pgm shows how to update a configuration file (4 specific tasks).*/ +parse arg iFID oFID . /*obtain optional input file─id. */ +if iFID=='' | iFID==',' then iFID= 'UPDATECF.TXT' /*use default? */ +if oFID=='' | oFID==',' then oFID='\TEMP\UPDATECF.$$$' /*use default? */ +call lineout iFID; call lineout oFID /*close the input & output files.*/ +$.=0 /*placeholder of options found. */ +call dos 'ERASE' oFID /*erase a file (with no err MSGs)*/ +changed=0 /*nothing changed in file so far.*/ + /* [↓] read the entire cfg file.*/ + do rec=0 while lines(iFID)\==0 /*read a record; bump record cnt.*/ + z=linein(iFID); zz=space(z) /*get rec; del extraneous blanks.*/ + say '───────── record:' z /*echo the record just read──►con*/ + a=left(zz,1); _=space(translate(zz,,';')) /*_ is used to elide multi;*/ + if zz=='' | a=='#' then do; call cpy z; iterate; end /*blank|comment*/ + if _=='' then do; changed=1; iterate; end /*elide any ; empty records*/ + parse upper var z op . /*obtain the option from the rec.*/ + /* [↓] OP may have leading or */ + if a==';' then do; parse upper var z 2 op . /*trailing blanks.*/ + if op='SEEDSREMOVED' then call new space(substr(z,2)) + call cpy z; $.op=1 /*write the Z record to output.*/ + iterate /*rec*/ /*··· and go read the next record*/ + end + if $.op then do; changed=1; iterate; end /*option already defined?*/ + $.op=1 /* [↑] Yes? Delete it.*/ + if op=='NEEDSPEELING' then call new ';' z + if op=='NUMBEROFBANANAS' then call new op 1024 + if op=='NUMBEROFSTRAWBERRIES' then call new op 62000 + call cpy z /*write the Z record to output.*/ + end /*rec*/ + + nos='NUMBEROFSTRAWBERRIES' /* [↓] NOS option need updating?*/ +if \$.nos then do; call new nos 62000; call cpy z; end /*update opt.*/ +call lineout iFID; call lineout oFID /*close the input & output files.*/ +if rec==0 then do; say "ERROR: input file wasn't found:" iFID; exit; end +if changed then do /*possibly overwrite input file. */ + call dos 'XCOPY' oFID iFID '/y /q',">nul" /*quietly*/ + say; say center('output file', 79, "▒") /*title. */ + call dos 'TYPE' oFID /*display output file's content. */ + end +call dos 'ERASE' oFID /*erase a file (with no err msg)*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one─line subroutines────────────────*/ +cpy: call lineout oFID,arg(1); return /*write one line of text───►oFID.*/ +dos: ''arg(1) word(arg(2) "2>nul",1); return /*execute a DOS command.*/ +new: z=arg(1); changed=1; return /*use new Z, indicate changed rec*/ diff --git a/Task/Update-a-configuration-file/REXX/update-a-configuration-file-2.rexx b/Task/Update-a-configuration-file/REXX/update-a-configuration-file-2.rexx new file mode 100644 index 0000000000..625e47af02 --- /dev/null +++ b/Task/Update-a-configuration-file/REXX/update-a-configuration-file-2.rexx @@ -0,0 +1,43 @@ +fid='updatecf.txt' +oid='updatecf.xxx'; 'erase' oid +options=translate('FAVOURITEFRUIT NEEDSPEELING SEEDSREMOVED NUMBEROFBANANAS numberofstrawberries') +done.=0 +Do While lines(fid)>0 + l=linein(fid) + c=left(l,1) + option='' + If c='#' | l='' Then + call o l + Else Do + If c=';' Then l=substr(l,3) + Parse Upper Var l option value + Select + When option='NEEDSPEELING' Then + Call o ';' option + When option='SEEDSREMOVED' Then + Call o option + When option='NUMBEROFBANANAS' Then + Call o option 1024 + When option='FAVOURITEFRUIT' Then + Call o l + When option='NUMBEROFSTRAWBERRIES' Then + Call o option 62000 + Otherwise + Call o '>>>' l + End + End + End +Do while options<>'' + Parse Var options option options + If done.option=0 Then + Call o option 62000 + End +Exit +o: +If option<>'' & done.option Then + Say 'Duplicate' option 'ignored' +Else Do + Call lineout oid,arg(1) + done.option=1 + End +Return diff --git a/Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vb b/Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vb new file mode 100644 index 0000000000..653bd3fd27 --- /dev/null +++ b/Task/Update-a-configuration-file/VBScript/update-a-configuration-file.vb @@ -0,0 +1,57 @@ +Set objFSO = CreateObject("Scripting.FileSystemObject") + +'Paramater lookups +Set objParamLookup = CreateObject("Scripting.Dictionary") +With objParamLookup + .Add "FAVOURITEFRUIT", "banana" + .Add "NEEDSPEELING", "" + .Add "SEEDSREMOVED", "" + .Add "NUMBEROFBANANAS", "1024" + .Add "NUMBEROFSTRAWBERRIES", "62000" +End With + +'Open the config file for reading. +Set objInFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\IN_config.txt",1) +'Initialize output. +Output = "" +Isnumberofstrawberries = False +With objInFile + Do Until .AtEndOfStream + line = .ReadLine + If Left(line,1) = "#" Or line = "" Then + Output = Output & line & vbCrLf + ElseIf Left(line,1) = " " And InStr(line,"#") Then + Output = Output & Mid(line,InStr(1,line,"#"),1000) & vbCrLf + ElseIf Replace(Replace(line,";","")," ","") <> "" Then + If InStr(1,line,"FAVOURITEFRUIT",1) Then + Output = Output & "FAVOURITEFRUIT" & " " & objParamLookup.Item("FAVOURITEFRUIT") & vbCrLf + ElseIf InStr(1,line,"NEEDSPEELING",1) Then + Output = Output & "; " & "NEEDSPEELING" & vbCrLf + ElseIf InStr(1,line,"SEEDSREMOVED",1) Then + Output = Output & "SEEDSREMOVED" & vbCrLf + ElseIf InStr(1,line,"NUMBEROFBANANAS",1) Then + Output = Output & "NUMBEROFBANANAS" & " " & objParamLookup.Item("NUMBEROFBANANAS") & vbCrLf + ElseIf InStr(1,line,"NUMBEROFSTRAWBERRIES",1) Then + Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf + Isnumberofstrawberries = True + End If + End If + Loop + If Isnumberofstrawberries = False Then + Output = Output & "NUMBEROFSTRAWBERRIES" & " " & objParamLookup.Item("NUMBEROFSTRAWBERRIES") & vbCrLf + Isnumberofstrawberries = True + End If + .Close +End With + +'Create a new config file. +Set objOutFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_ + "\OUT_config.txt",2,True) +With objOutFile + .Write Output + .Close +End With + +Set objFSO = Nothing +Set objParamLookup = Nothing diff --git a/Task/Use-another-language-to-call-a-function/00DESCRIPTION b/Task/Use-another-language-to-call-a-function/00DESCRIPTION index c0913a5f87..0c8a6e4c5d 100644 --- a/Task/Use-another-language-to-call-a-function/00DESCRIPTION +++ b/Task/Use-another-language-to-call-a-function/00DESCRIPTION @@ -20,4 +20,5 @@ int main (int argc, char * argv []) putchar ('\n'); } } -Write an implementation of Query in your language and make ''main'' calling it. The function Query takes the buffer a places the string ''Here am I'' into it. The buffer size in bytes is specified by the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1. + +Implement the missing Query function in your language, and let this C program call it. The function should place the string ''Here am I'' into the buffer which is passed to it as the parameter Data. The buffer size in bytes is passed as the parameter Length. When there is no room in the buffer, Query shall return 0. Otherwise it overwrites the beginning of Buffer, sets the number of overwritten bytes into Length and returns 1. diff --git a/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-3.go b/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-3.go new file mode 100644 index 0000000000..21147e368c --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Go/use-another-language-to-call-a-function-3.go @@ -0,0 +1,45 @@ +// This buildmode requires the package to be main +package main + +// Import C so we can export the function to C and use C types + +//#include // for size_t +import "C" + +// Import reflect and unsafe so we can wrap the C array in a Go slice +import "reflect" +import "unsafe" + +// This buildmode also requires a main function, but it is never actually called +func main() {} + +// The message to copy into the buffer +const msg = "Here am I" + +// Here we declare the Query function using C types and export it to C + +//export Query +func Query(buffer *C.char, length *C.size_t) C.int { + // Check there is enough space in the buffer + if int(*length) < len(msg) { + return 0 + } + + // Wrap the buffer in a slice to make it easier to copy into + sliceHeader := reflect.SliceHeader { + Data: uintptr(unsafe.Pointer(buffer)), + Len: len(msg), + Cap: len(msg), + } + bufferSlice := *(*[]byte)(unsafe.Pointer(&sliceHeader)) + + // Iterate through the message and copy it to the buffer, byte by byte + for i:=0;i _bool) + (λ(bs len) + (define out #"Here I am") + (let ([bs (make-sized-byte-string bs (ptr-ref len _int))]) + (and ((bytes-length out) . <= . (bytes-length bs)) + (begin (bytes-copy! bs 0 out) + (ptr-set! len _int (bytes-length out)) + #t))))) + +((get-ffi-obj "main" xlib (_fun _int (_list i _bytes) -> _void)) + 0 '()) diff --git a/Task/User-input-Text/APL/user-input-text.apl b/Task/User-input-Text/APL/user-input-text.apl new file mode 100644 index 0000000000..c3b0dc3ee5 --- /dev/null +++ b/Task/User-input-Text/APL/user-input-text.apl @@ -0,0 +1,2 @@ +str←⍞ +int←⎕ diff --git a/Task/User-input-Text/Bracmat/user-input-text.bracmat b/Task/User-input-Text/Bracmat/user-input-text.bracmat new file mode 100644 index 0000000000..90b665ddab --- /dev/null +++ b/Task/User-input-Text/Bracmat/user-input-text.bracmat @@ -0,0 +1,11 @@ +( doit += out'"Enter a string" + & get':?mystring + & whl + ' ( out'"Enter a number" + & get':?mynumber + & !mynumber:~# + & out'"I said:\"a number\"!" + ) + & out$(mystring is !mystring \nmynumber is !mynumber \n) +); diff --git a/Task/User-input-Text/Elixir/user-input-text.elixir b/Task/User-input-Text/Elixir/user-input-text.elixir new file mode 100644 index 0000000000..b36d48427e --- /dev/null +++ b/Task/User-input-Text/Elixir/user-input-text.elixir @@ -0,0 +1,4 @@ +a = IO.gets("Enter a string: ") |> String.strip +b = IO.gets("Enter an integer: ") |> String.strip |> String.to_integer() +IO.puts "String = #{a}" +IO.puts "Integer = #{b}" diff --git a/Task/User-input-Text/Julia/user-input-text.julia b/Task/User-input-Text/Julia/user-input-text.julia new file mode 100644 index 0000000000..d4c396c238 --- /dev/null +++ b/Task/User-input-Text/Julia/user-input-text.julia @@ -0,0 +1,11 @@ +print("String? ") +y = chomp(readline()) +println("Your input was \"", y, "\".\n") +print("Integer? ") +y = chomp(readline()) +try + y = parseint(y) + println("Your input was \"", y, "\".\n") +catch + println("Sorry, but \"", y, "\" does not compute as an integer.") +end diff --git a/Task/User-input-Text/REXX/user-input-text.rexx b/Task/User-input-Text/REXX/user-input-text.rexx index 0e60a97b4d..d2e9a8bd9b 100644 --- a/Task/User-input-Text/REXX/user-input-text.rexx +++ b/Task/User-input-Text/REXX/user-input-text.rexx @@ -1,12 +1,10 @@ -/*REXX program gets a string and the number 75000 from the console. */ - -say 'Please enter a text string:' /*show prompt for a text string. */ -parse pull userString /*get the user text and store it.*/ - - do until userNumber=75000 /*repeat until correct.*/ - say /*display a blank line.*/ - say 'Please enter the number 75000' /*show the nice prompt.*/ - parse pull userNumber /*get the user text. */ - end /*until*/ /*now, check if it's OK*/ - +/*REXX pgm prompts and gets a string and also the # 75000 from terminal.*/ +say 'Please enter a string:'; parse pull userString +say 'You entered this string:' userString /* show it on the console */ + /* [↑] string can be any length.*/ + do until userNumber=75000 /*repeat this loop until correct.*/ + say /*display blank line to terminal.*/ + say 'Please enter the number 75000' /*display a nice prompt message. */ + parse pull userNumber /*obtain the user text from term.*/ + end /*until ··· */ /*check if the response is legit.*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Vampire-number/Common-Lisp/vampire-number.lisp b/Task/Vampire-number/Common-Lisp/vampire-number.lisp new file mode 100644 index 0000000000..c88e05c87d --- /dev/null +++ b/Task/Vampire-number/Common-Lisp/vampire-number.lisp @@ -0,0 +1,60 @@ +(defun trailing-zerop (number) + "Is the lowest digit of `number' a 0" + (zerop (rem number 10))) + +(defun integer-digits (integer) + "Return the number of digits of the `integer'" + (assert (integerp integer)) + (length (write-to-string integer))) + +(defun paired-factors (number) + "Return a list of pairs that are factors of `number'" + (loop + :for candidate :from 2 :upto (sqrt number) + :when (zerop (mod number candidate)) + :collect (list candidate (/ number candidate)))) + +(defun vampirep (candidate &aux + (digits-of-candidate (integer-digits candidate)) + (half-the-digits-of-candidate (/ digits-of-candidate + 2))) + "Is the `candidate' a vampire number?" + (remove-if #'(lambda (pair) + (> (length (remove-if #'null (mapcar #'trailing-zerop pair))) + 1)) + (remove-if-not #'(lambda (pair) + (string= (sort (copy-seq (write-to-string candidate)) + #'char<) + (sort (copy-seq (format nil "~A~A" (first pair) (second pair))) + #'char<))) + (remove-if-not #'(lambda (pair) + (and (eql (integer-digits (first pair)) + half-the-digits-of-candidate) + (eql (integer-digits (second pair)) + half-the-digits-of-candidate))) + (paired-factors candidate))))) + +(defun print-vampire (candidate fangs &optional (stream t)) + (format stream + "The number ~A is a vampire number with fangs: ~{ ~{~A~^, ~}~^; ~}~%" + candidate + fangs)) + +;; Print the first 25 vampire numbers + +(loop + :with count := 0 + :for candidate :from 0 + :until (eql count 25) + :for fangs := (vampirep candidate) + :do + (when fangs + (print-vampire candidate fangs) + (incf count))) + +;; Check if 16758243290880, 24959017348650, 14593825548650 are vampire numbers + +(dolist (candidate '(16758243290880 24959017348650 14593825548650)) + (let ((fangs (vampirep candidate))) + (when fangs + (print-vampire candidate fangs)))) diff --git a/Task/Vampire-number/Eiffel/vampire-number.e b/Task/Vampire-number/Eiffel/vampire-number.e new file mode 100644 index 0000000000..06af2687d1 --- /dev/null +++ b/Task/Vampire-number/Eiffel/vampire-number.e @@ -0,0 +1,111 @@ +class + APPLICATION + +create + make + +feature + + fang_check (original, fang1, fang2: INTEGER_64): BOOLEAN + -- Are 'fang1' and 'fang2' correct fangs of the 'original' number? + require + original_positive: original > 0 + fangs_positive: fang1 > 0 and fang2 > 0 + local + original_length: INTEGER + fang, ori: STRING + sort_ori, sort_fang: SORTED_TWO_WAY_LIST [CHARACTER] + do + create sort_ori.make + create sort_fang.make + create ori.make_empty + create fang.make_empty + original_length := original.out.count // 2 + if fang1.out.count /= original_length or fang2.out.count /= (original_length) then + Result := False + elseif fang1.out.ends_with ("0") and fang2.out.ends_with ("0") then + Result := False + else + across + 1 |..| original.out.count as c + loop + sort_ori.extend (original.out [c.item]) + end + across + sort_ori as o + loop + ori.extend (o.item) + end + across + 1 |..| fang1.out.count as c + loop + sort_fang.extend (fang1.out [c.item]) + sort_fang.extend (fang2.out [c.item]) + end + across + sort_fang as f + loop + fang.extend (f.item) + end + Result := fang.same_string (ori) + end + ensure + fangs_right_length: Result implies original.out.count = fang1.out.count + fang2.out.count + end + + make + -- Uses fang_check to find vampire nubmers. + local + i, numbers: INTEGER + fang1, fang2: INTEGER_64 + num: ARRAY [INTEGER_64] + math: DOUBLE_MATH + do + create math + from + i := 1000 + until + numbers > 25 + loop + if i.out.count \\ 2 = 0 then + from + fang1 := 10 + until + fang1 >= math.sqrt (i) + loop + if (i \\ fang1 = 0) then + fang2 := i // fang1 + if i \\ 9 = (fang1 + fang2) \\ 9 then + if fang1 * fang2 = i and fang1 <= fang2 and then fang_check (i, fang1, fang2) then + numbers := numbers + 1 + io.put_string (i.out + ": " + fang1.out + " " + fang2.out) + io.new_line + end + end + end + fang1 := fang1 + 1 + end + end + i := i + 1 + end + num := <<16758243290880, 24959017348650, 14593825548650>> + across + num as n + loop + from + fang1 := 1000000 + until + fang1 >= math.sqrt (n.item) + 1 + loop + if (n.item \\ fang1 = 0) then + fang2 := (n.item // fang1) + if fang1 * fang2 = n.item and fang1 <= fang2 and then fang_check (n.item, fang1, fang2) then + io.put_string (n.item.out + ": " + fang1.out + " " + fang2.out + "%N") + end + end + fang1 := fang1 + 1 + end + end + end + +end diff --git a/Task/Vampire-number/Julia/vampire-number-1.julia b/Task/Vampire-number/Julia/vampire-number-1.julia new file mode 100644 index 0000000000..70031e33cc --- /dev/null +++ b/Task/Vampire-number/Julia/vampire-number-1.julia @@ -0,0 +1,34 @@ +function divisors{T<:Integer}(n::T) + !isprime(n) || return [one(T), n] + d = [one(T)] + for (k, v) in factor(n) + e = T[k^i for i in 1:v] + append!(d, vec([i*j for i in d, j in e])) + end + sort(d) +end + +function vampirefangs{T<:Integer}(n::T) + fangs = T[] + isvampire = false + vdcnt = ndigits(n) + fdcnt = vdcnt>>1 + iseven(vdcnt) || return (isvampire, fangs) + !isprime(n) || return (isvampire, fangs) + vdigs = sort(digits(n)) + d = divisors(n) + len = length(d) + len = iseven(len) ? len>>1 : len>>1 + 1 + for f in d[1:len] + ndigits(f) == fdcnt || continue + g = div(n, f) + f%10!=0 || g%10!=0 || continue + sort([digits(f), digits(g)]) == vdigs || continue + isvampire = true + append!(fangs, [f, g]) + end + if isvampire + fangs = reshape(fangs, (2,length(fangs)>>1))' + end + return (isvampire, fangs) +end diff --git a/Task/Vampire-number/Julia/vampire-number-2.julia b/Task/Vampire-number/Julia/vampire-number-2.julia new file mode 100644 index 0000000000..688d1e3814 --- /dev/null +++ b/Task/Vampire-number/Julia/vampire-number-2.julia @@ -0,0 +1,36 @@ +function showvampire{T<:Integer}(i::T, n::T, fangs::Array{T,2}) + s = @sprintf "%6d %14d %s\n" i n join(fangs[1,:], "\u00d7") + for i in 2:size(fangs)[1] + s *= " "^23*join(fangs[i,:], "\u00d7")*"\n" + end + return s +end + +vgoal = 25 +vcnt = 0 +dcnt = 0 +println("Finding the first ", vgoal, " vampire numbers.") +println(" N Vampire Fangs") +while vcnt < vgoal + dcnt += 2 + for i in (10^(dcnt-1)):(10^dcnt-1) + (isvampire, fangs) = vampirefangs(i) + isvampire || continue + vcnt += 1 + print(showvampire(vcnt, i, fangs)) + vcnt < vgoal || break + end +end + +test = [16758243290880, 24959017348650, 14593825548650] +println() +println("Checking a few numbers.") +println(" N Vampire Fangs") +for (i, v) in enumerate(test) + (isvampire, fangs) = vampirefangs(v) + if isvampire + print(showvampire(i, v, fangs)) + else + println(@sprintf "%6d %14d is not a vampire" i v) + end +end diff --git a/Task/Van-der-Corput-sequence/00DESCRIPTION b/Task/Van-der-Corput-sequence/00DESCRIPTION index a14aaa1c6f..a26c68ecc5 100644 --- a/Task/Van-der-Corput-sequence/00DESCRIPTION +++ b/Task/Van-der-Corput-sequence/00DESCRIPTION @@ -1,4 +1,4 @@ -When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the next column to the lefts digit has a multiplier of 2^1 and so on. +When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on. So in the following table:
  0.
@@ -6,9 +6,9 @@ So in the following table:
  10.
  11.
  ...
-The binary number "10" is 1 \times 2^1 + 0 \times 2^0. +the binary number "10" is 1 \times 2^1 + 0 \times 2^0. -You can have binary digits to the right of the “point” just as in the decimal number system too. in this case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. +You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. The weight for the second column to the right of the point is 2^{-2} or 1/4. And so on. If you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''. @@ -19,7 +19,7 @@ If you take the integer binary count of the first table, and ''reflect'' the dig .11 ...
-The third member of the sequence: binary 0.01 is therefore 0 \times 2^{-1} + 1 \times 2^{-2} or 1/4. +The third member of the sequence, binary 0.01, is therefore 0 \times 2^{-1} + 1 \times 2^{-2} or 1/4.
[[File:Van der corput distribution.png|400|thumb|right|Distribution of 2500 points each: Van der Corput (top) vs pseudorandom]] Members of the sequence lie within the interval 0 \leq x < 1. Points within the sequence tend to be evenly distributed which is a useful trait to have for [[wp:Monte Carlo method|Monte Carlo simulations]]. This sequence is also a superset of the numbers representable by the "fraction" field of [[wp:IEEE 754-1985|an old IEEE floating point standard]]. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101. diff --git a/Task/Van-der-Corput-sequence/AWK/van-der-corput-sequence.awk b/Task/Van-der-Corput-sequence/AWK/van-der-corput-sequence.awk new file mode 100644 index 0000000000..64936eba9e --- /dev/null +++ b/Task/Van-der-Corput-sequence/AWK/van-der-corput-sequence.awk @@ -0,0 +1,27 @@ +# syntax: GAWK -f VAN_DER_CORPUT_SEQUENCE.AWK +# converted from BBC BASIC +BEGIN { + printf("base") + for (i=0; i<=9; i++) { + printf(" %7d",i) + } + printf("\n") + for (base=2; base<=5; base++) { + printf("%-4s",base) + for (i=0; i<=9; i++) { + printf(" %7.5f",vdc(i,base)) + } + printf("\n") + } + exit(0) +} +function vdc(n,b, s,v) { + s = 1 + while (n) { + s *= b + v += (n % b) / s + n /= b + n = int(n) + } + return(v) +} diff --git a/Task/Van-der-Corput-sequence/Elixir/van-der-corput-sequence.elixir b/Task/Van-der-Corput-sequence/Elixir/van-der-corput-sequence.elixir new file mode 100644 index 0000000000..6c0585e88c --- /dev/null +++ b/Task/Van-der-Corput-sequence/Elixir/van-der-corput-sequence.elixir @@ -0,0 +1,19 @@ +defmodule Van_der_corput do + def sequence( n ), do: sequence( n, 2 ) + + def sequence( 0, _base ), do: 0.0 + def sequence( n, base ) do + List.to_float( '0.' ++ ( for x <- sequence_loop(n, base), do: Integer.to_char_list(x) ) |> List.flatten ) + end + + def sequence_loop( 0, _base ), do: [] + def sequence_loop( n, base ) do + new_n = div(n, base) + digit = rem(n, base) + [digit | sequence_loop( new_n, base )] + end +end + +Enum.each(2..5, fn base -> + IO.puts "Base #{base}: #{inspect Enum.map(0..9, fn x -> Van_der_corput.sequence(x, base) end)}" +end) diff --git a/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia b/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia new file mode 100644 index 0000000000..6e98e2939e --- /dev/null +++ b/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia @@ -0,0 +1,11 @@ +function vdc{T<:Integer}(n::T, b::T) + sum([d*float(b)^-i for (i, d) in enumerate(digits(n, b))]) +end + +for i in 2:9 + print(" Base ", i) + for j in 0:9 + print(@sprintf(" %8.6f", vdc(j, i))) + end + println() +end diff --git a/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-1.pl6 b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-1.pl6 index 71a36847c8..93a6f35a06 100644 --- a/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-1.pl6 +++ b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-1.pl6 @@ -1,16 +1,2 @@ -sub vdc($num, $base = 2) { - my $n = $num; - my $vdc = 0; - my $denom = 1; - while $n { - $vdc += $n mod $base / ($denom *= $base); - $n div= $base; - } - $vdc; -} - -for 2..5 -> $b { - say "Base $b"; - say (vdc($_,$b) for ^10).perl; - say ''; -} +constant VdC = map { :2("0." ~ .base(2).flip) }, ^Inf; +.say for VdC[^16]; diff --git a/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-2.pl6 b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-2.pl6 index 169d45a9ed..359eb63b43 100644 --- a/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-2.pl6 +++ b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-2.pl6 @@ -1,7 +1,7 @@ -sub vdc($value, $base = 2) { - my @values := $value, { $_ div $base } ... 0; - my @denoms := $base, { $_ * $base } ... *; - [+] do for @values Z @denoms -> $v, $d { - $v mod $base / $d; - } +sub VdC($base = 2) { + map { + [+] $_ && .polymod($base xx *) Z/ [\*] $base xx * + }, ^Inf } + +.say for VdC[^10]; diff --git a/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-3.pl6 b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-3.pl6 new file mode 100644 index 0000000000..71a36847c8 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-3.pl6 @@ -0,0 +1,16 @@ +sub vdc($num, $base = 2) { + my $n = $num; + my $vdc = 0; + my $denom = 1; + while $n { + $vdc += $n mod $base / ($denom *= $base); + $n div= $base; + } + $vdc; +} + +for 2..5 -> $b { + say "Base $b"; + say (vdc($_,$b) for ^10).perl; + say ''; +} diff --git a/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-4.pl6 b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-4.pl6 new file mode 100644 index 0000000000..169d45a9ed --- /dev/null +++ b/Task/Van-der-Corput-sequence/Perl-6/van-der-corput-sequence-4.pl6 @@ -0,0 +1,7 @@ +sub vdc($value, $base = 2) { + my @values := $value, { $_ div $base } ... 0; + my @denoms := $base, { $_ * $base } ... *; + [+] do for @values Z @denoms -> $v, $d { + $v mod $base / $d; + } +} diff --git a/Task/Variable-length-quantity/Julia/variable-length-quantity.julia b/Task/Variable-length-quantity/Julia/variable-length-quantity.julia new file mode 100644 index 0000000000..f719f0dd48 --- /dev/null +++ b/Task/Variable-length-quantity/Julia/variable-length-quantity.julia @@ -0,0 +1,34 @@ +type VLQ + q::Array{Uint8,1} +end + +function VLQ{T<:Integer}(n::T) + q = uint8(digits(n, 128)) + for i in 2:length(q) + q[i] |= 0x80 + end + VLQ(reverse(q)) +end + +function Base.uint(vlq::VLQ) + q = reverse(vlq.q) + n = shift!(q) + p = one(Uint64) + for i in q + p *= 0x80 + n += p*(i&0x7f) + end + return n +end + +test = [0x00200000, 0x001fffff, 0x00000000, 0x0000007f, + 0x00000080, 0x00002000, 0x00003fff, 0x00004000, + 0x08000000, 0x0fffffff] + +for i in test + q = VLQ(i) + j = uint(q) + print(@sprintf " 0x%x => " i) + print(@sprintf "[%s]" join(["0x"*hex(r, 2) for r in q.q], ", ")) + println(@sprintf " => 0x%x" j) +end diff --git a/Task/Variable-size-Set/360-Assembly/variable-size-set.360 b/Task/Variable-size-Set/360-Assembly/variable-size-set.360 index 0f7faf5110..8398393225 100644 --- a/Task/Variable-size-Set/360-Assembly/variable-size-set.360 +++ b/Task/Variable-size-Set/360-Assembly/variable-size-set.360 @@ -21,4 +21,5 @@ B1 DC B'10101010' 1 byte * Hexadecimal value (X) X1 DC X'AA' 1 byte * Address value (A) -A4 DC A(176) 4 bytes +A4 DC A(176) 4 bytes but only 3 bytes used +* (24 bits => 16 MB of storage) diff --git a/Task/Variable-size-Set/REXX/variable-size-set.rexx b/Task/Variable-size-Set/REXX/variable-size-set.rexx index d48b741ec7..6a46fd87cb 100644 --- a/Task/Variable-size-Set/REXX/variable-size-set.rexx +++ b/Task/Variable-size-Set/REXX/variable-size-set.rexx @@ -1,2 +1,11 @@ -numeric digits 100 -abc=12345678901111111112222222222333333333344444444445555555555.66 +/*REXX program demonstrates on setting a variable (using a "minimum var size".*/ +numeric digits 100 /*default: 9 (decimal digs) for numbers*/ + +/*── 1 2 3 4 5 6 7──*/ +/*──1234567890123456789012345678901234567890123456789012345678901234567890──*/ + +z = 12345678901111111112222222222333333333344444444445555555555.66 +n =-12345678901111111112222222222333333333344444444445555555555.66 + + /* [↑] these #'s are stored as coded. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Variables/ALGOL-W/variables-1.alg b/Task/Variables/ALGOL-W/variables-1.alg new file mode 100644 index 0000000000..e77f22d3bb --- /dev/null +++ b/Task/Variables/ALGOL-W/variables-1.alg @@ -0,0 +1,7 @@ +% declare some variables % +integer a1, a2; real b; long real c; complex d; long complex f; +logical g; bits h; string(32) j; + +% assign "initial values" % +f := d := c := b := a2 := a1 := 0; % multiple assignment % +g := false; h := #a0; j := "Hello, World!"; diff --git a/Task/Variables/ALGOL-W/variables-2.alg b/Task/Variables/ALGOL-W/variables-2.alg new file mode 100644 index 0000000000..03aebad6d1 --- /dev/null +++ b/Task/Variables/ALGOL-W/variables-2.alg @@ -0,0 +1,2 @@ +record R1 ( integer length; string(256) text ); +reference(R1) ref1, ref2; diff --git a/Task/Variables/ALGOL-W/variables-3.alg b/Task/Variables/ALGOL-W/variables-3.alg new file mode 100644 index 0000000000..6cde97ebb0 --- /dev/null +++ b/Task/Variables/ALGOL-W/variables-3.alg @@ -0,0 +1,3 @@ +record person( string(32) name; integer age ); +record date( integer day, month, year ); +reference(person, date) ref3; diff --git a/Task/Variables/ALGOL-W/variables-4.alg b/Task/Variables/ALGOL-W/variables-4.alg new file mode 100644 index 0000000000..b1cfe59f89 --- /dev/null +++ b/Task/Variables/ALGOL-W/variables-4.alg @@ -0,0 +1 @@ +reference(integer) refInt; % an illegal declaration % diff --git a/Task/Variables/ALGOL-W/variables-5.alg b/Task/Variables/ALGOL-W/variables-5.alg new file mode 100644 index 0000000000..c214cfdd93 --- /dev/null +++ b/Task/Variables/ALGOL-W/variables-5.alg @@ -0,0 +1,2 @@ +record INT_VALUE ( integer val ); +reference(INT_VALUE) refInt; diff --git a/Task/Variables/ALGOL-W/variables-6.alg b/Task/Variables/ALGOL-W/variables-6.alg new file mode 100644 index 0000000000..081f33e598 --- /dev/null +++ b/Task/Variables/ALGOL-W/variables-6.alg @@ -0,0 +1,7 @@ +% using the person record defined above...% + reference (person) someone; + someone := person % create a new person structure with uninitialised fields % + name(someone) := "Fred"; % initialise the fields % + age(someone) := 27; + % could also initialise the fields when the record is created: % + someone := person( "Harry", 32 ); diff --git a/Task/Variables/Cache-ObjectScript/variables-1.cos b/Task/Variables/Cache-ObjectScript/variables-1.cos new file mode 100644 index 0000000000..58c8c7a8fd --- /dev/null +++ b/Task/Variables/Cache-ObjectScript/variables-1.cos @@ -0,0 +1,3 @@ +set MyStr = "A string" +set MyInt = 4 +set MyFloat = 1.3 diff --git a/Task/Variables/Cache-ObjectScript/variables-2.cos b/Task/Variables/Cache-ObjectScript/variables-2.cos new file mode 100644 index 0000000000..52e4db3364 --- /dev/null +++ b/Task/Variables/Cache-ObjectScript/variables-2.cos @@ -0,0 +1,5 @@ +set MyArray(1) = "element 1" +set MyArray(2) = "element 2" +set MyArray(2,1) = "sub element 1 of element 2" +set MyArray("Element 3") "element indexed by a string" +set MyArray = "Root element" diff --git a/Task/Variables/Cache-ObjectScript/variables-3.cos b/Task/Variables/Cache-ObjectScript/variables-3.cos new file mode 100644 index 0000000000..b00b2b53be --- /dev/null +++ b/Task/Variables/Cache-ObjectScript/variables-3.cos @@ -0,0 +1 @@ +set ^MyGlobal("a subscript") = "My Value" diff --git a/Task/Variables/Cache-ObjectScript/variables-4.cos b/Task/Variables/Cache-ObjectScript/variables-4.cos new file mode 100644 index 0000000000..be677d98a9 --- /dev/null +++ b/Task/Variables/Cache-ObjectScript/variables-4.cos @@ -0,0 +1 @@ +set ^||MyProcessPrivateGlobal("subscript 1") = "value" diff --git a/Task/Variables/REXX/variables-1.rexx b/Task/Variables/REXX/variables-1.rexx index 1ab86d289f..b307fbdcf2 100644 --- a/Task/Variables/REXX/variables-1.rexx +++ b/Task/Variables/REXX/variables-1.rexx @@ -1,10 +1,10 @@ aa = 10 /*assigns chars 10 ───► AA */ bb = '' /*assigns a null value ───► BB */ -cc = 2*10 /*assigns charser 20 ───► CC */ +cc = 2*10 /*assigns chars 20 ───► CC */ dd = 'Adam' /*assigns chars Adam ───► DD */ ee = "Adam" /*same as above ───► EE */ ff = 10. /*assigns chars 10. ───► FF */ gg='10.' /*same as above ───► GG */ hh = "+10" /*assigns chars +10 ───► hh */ ii = 1e1 /*assigns chars 1e1 ───► ii */ -jj = +.1e+2 /*assigns chars +.1e+2 ───► jj */ +jj = +.1e+2 /*assigns chars .1e+2 ───► jj */ diff --git a/Task/Variadic-function/BASIC/variadic-function.basic b/Task/Variadic-function/BASIC/variadic-function-1.basic similarity index 100% rename from Task/Variadic-function/BASIC/variadic-function.basic rename to Task/Variadic-function/BASIC/variadic-function-1.basic diff --git a/Task/Variadic-function/BASIC/variadic-function-2.basic b/Task/Variadic-function/BASIC/variadic-function-2.basic new file mode 100644 index 0000000000..394499d08a --- /dev/null +++ b/Task/Variadic-function/BASIC/variadic-function-2.basic @@ -0,0 +1,39 @@ +' version 15-09-2015 +' compile with: fbc -s console + +Sub printAll_string Cdecl (count As Integer, ... ) + Dim arg As Any Ptr + Dim i As Integer + + arg = va_first() + For i = 1 To count + Print *Va_Arg(arg, ZString Ptr) + arg = va_next(arg, ZString Ptr) + Next i +End Sub + +' ------=< MAIN >=------ +' direct +printAll_string (5, "Foxtrot", "Romeo", "Echo", "Echo", "BASIC") + +' strings +Print : Print +Dim As String a = "one", b = "two", c = "three" +printAll_string (3, a, b, c) + +' count is smaller then the number of arguments, no problem +Print : Print +printAll_string (1, a, b, c) + +' count is greater then the number of arguments +' after the last valid argument garbage is displayed +' should be avoided, could lead to disaster +Print : Print +printAll_string (4, a, b, c) +Print + +' empty keyboard buffer +While InKey <> "" : Var _key_ = InKey : Wend +Print : Print "hit any key to end program" +Sleep +End diff --git a/Task/Variadic-function/Coq/variadic-function-1.coq b/Task/Variadic-function/Coq/variadic-function-1.coq new file mode 100644 index 0000000000..f67be4bf3d --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-1.coq @@ -0,0 +1,4 @@ +Fixpoint Arity (A B: Set) (n: nat): Set := match n with +|O => B +|S n' => A -> (Arity A B n') +end. diff --git a/Task/Variadic-function/Coq/variadic-function-2.coq b/Task/Variadic-function/Coq/variadic-function-2.coq new file mode 100644 index 0000000000..f40f8fdac1 --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-2.coq @@ -0,0 +1 @@ +Definition nat_twobools (n: nat) := Arity nat (Arity bool nat (2*n)) n. diff --git a/Task/Variadic-function/Coq/variadic-function-3.coq b/Task/Variadic-function/Coq/variadic-function-3.coq new file mode 100644 index 0000000000..6e0f54413f --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-3.coq @@ -0,0 +1,5 @@ +Require Import List. +Fixpoint build_list_aux {A: Set} (acc: list A) (n : nat): Arity A (list A) n := match n with +|O => acc +|S n' => fun (val: A) => build_list_aux (acc ++ (val :: nil)) n' +end. diff --git a/Task/Variadic-function/Coq/variadic-function-4.coq b/Task/Variadic-function/Coq/variadic-function-4.coq new file mode 100644 index 0000000000..06ea4cc55a --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-4.coq @@ -0,0 +1 @@ +Definition build_list {A: Set} := build_list_aux (@nil A). diff --git a/Task/Variadic-function/Coq/variadic-function-5.coq b/Task/Variadic-function/Coq/variadic-function-5.coq new file mode 100644 index 0000000000..60a22cadbd --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-5.coq @@ -0,0 +1 @@ +Check build_list 5 1 2 5 90 42. diff --git a/Task/Variadic-function/Coq/variadic-function-6.coq b/Task/Variadic-function/Coq/variadic-function-6.coq new file mode 100644 index 0000000000..9cf7d9cf84 --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-6.coq @@ -0,0 +1,11 @@ +Lemma transparent_plus_zero: forall n, n + O = n. +intros n; induction n. +- reflexivity. +- simpl; rewrite IHn; trivial. +Defined. + +Lemma transparent_plus_S: forall n m, n + S m = S n + m . +intros n; induction n; intros m. +- reflexivity. +- simpl; f_equal; rewrite IHn; reflexivity. +Defined. diff --git a/Task/Variadic-function/Coq/variadic-function-7.coq b/Task/Variadic-function/Coq/variadic-function-7.coq new file mode 100644 index 0000000000..a39598e836 --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-7.coq @@ -0,0 +1,7 @@ +Require Import Vector. + +Definition build_vector_aux {A: Set} (n: nat): forall (size_acc : nat) (acc: t A size_acc), Arity A (t A (size_acc + n)) n. +induction n; intros size_acc acc. +- rewrite transparent_plus_zero; apply acc. (*Just one argument, return the accumulator*) +- intros val. rewrite transparent_plus_S. apply IHn. (*Here we use the induction hypothesis. We just have to build the new accumulator*) + apply shiftin; [apply val | apply acc]. (*Shiftin adds a term at the end of a vector*) diff --git a/Task/Variadic-function/Coq/variadic-function-8.coq b/Task/Variadic-function/Coq/variadic-function-8.coq new file mode 100644 index 0000000000..141917dc3b --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-8.coq @@ -0,0 +1 @@ +Definition build_vector {A: Set} (n: nat) := build_vector_aux n O (@nil A). diff --git a/Task/Variadic-function/Coq/variadic-function-9.coq b/Task/Variadic-function/Coq/variadic-function-9.coq new file mode 100644 index 0000000000..2e06df752e --- /dev/null +++ b/Task/Variadic-function/Coq/variadic-function-9.coq @@ -0,0 +1,2 @@ +Require Import String. +Eval compute in build_vector 4 "Hello" "how" "are" "you". diff --git a/Task/Variadic-function/Elixir/variadic-function.elixir b/Task/Variadic-function/Elixir/variadic-function.elixir new file mode 100644 index 0000000000..fe0a99b653 --- /dev/null +++ b/Task/Variadic-function/Elixir/variadic-function.elixir @@ -0,0 +1,8 @@ +defmodule RC do + def print_each( arguments ) do + Enum.each(arguments, fn x -> IO.inspect x end) + end +end + +RC.print_each([1,2,3]) +RC.print_each(["Mary", "had", "a", "little", "lamb"]) diff --git a/Task/Variadic-function/JavaScript/variadic-function-3.js b/Task/Variadic-function/JavaScript/variadic-function-3.js new file mode 100644 index 0000000000..8ab9764907 --- /dev/null +++ b/Task/Variadic-function/JavaScript/variadic-function-3.js @@ -0,0 +1,29 @@ +let + fix = // Variant of the applicative order Y combinator + f => (f => f(f))(g => f((...a) => g(g)(...a))), + forAll = + f => + fix( + z => (a,...b) => ( + (a === void 0) + ||(f(a), z(...b)))), + printAll = forAll(print); + +printAll(0,1,2,3,4,5); +printAll(6,7,8); +(f => a => f(...a))(printAll)([9,10,11,12,13,14]); +// 0 +// 1 +// 2 +// 3 +// 4 +// 5 +// 6 +// 7 +// 8 +// 9 +// 10 +// 11 +// 12 +// 13 +// 14 diff --git a/Task/Variadic-function/Lua/variadic-function.lua b/Task/Variadic-function/Lua/variadic-function-1.lua similarity index 100% rename from Task/Variadic-function/Lua/variadic-function.lua rename to Task/Variadic-function/Lua/variadic-function-1.lua diff --git a/Task/Variadic-function/Lua/variadic-function-2.lua b/Task/Variadic-function/Lua/variadic-function-2.lua new file mode 100644 index 0000000000..3ed58be7b2 --- /dev/null +++ b/Task/Variadic-function/Lua/variadic-function-2.lua @@ -0,0 +1 @@ +varar(1, "bla", 5, "end"); diff --git a/Task/Variadic-function/Lua/variadic-function-3.lua b/Task/Variadic-function/Lua/variadic-function-3.lua new file mode 100644 index 0000000000..e8f469795d --- /dev/null +++ b/Task/Variadic-function/Lua/variadic-function-3.lua @@ -0,0 +1,3 @@ +local runtime_array = {1, "bla", 5, "end"}; + +varar(unpack(runtime_array)); diff --git a/Task/Variadic-function/REXX/variadic-function-3.rexx b/Task/Variadic-function/REXX/variadic-function-3.rexx index 037c4017cc..17407b8828 100644 --- a/Task/Variadic-function/REXX/variadic-function-3.rexx +++ b/Task/Variadic-function/REXX/variadic-function-3.rexx @@ -1,4 +1,4 @@ -call print_all .1,5,2,4,-3, 4.7e1, 013.000 ,, 8**2 -3, sign(-66), abs(-71.00), 8 || 6, 'seven numbers are prime, 8th is null' +call print_all .1,5,2,4,-3, 4.7e1, 013.000 ,, 8**2 -3, sign(-66), abs(-71.00), 8 || 9, 'seven numbers are prime, 8th is null' call print_all "One ringy-dingy,", "two ringy-dingy,", diff --git a/Task/Vector-products/ALGOL-W/vector-products.alg b/Task/Vector-products/ALGOL-W/vector-products.alg new file mode 100644 index 0000000000..ac10a97710 --- /dev/null +++ b/Task/Vector-products/ALGOL-W/vector-products.alg @@ -0,0 +1,45 @@ +begin + % define the Vector record type % + record Vector( integer X, Y, Z ); + + % calculates the dot product of two Vectors % + integer procedure dotProduct( reference(Vector) value A, B ) ; + ( X(A) * X(B) ) + ( Y(A) * Y(B) ) + ( Z(A) * Z(B) ); + + % calculates the cross product or two Vectors % + reference(Vector) procedure crossProduct( reference(Vector) value A, B ) ; + Vector( ( Y(A) * Z(B) ) - ( Z(A) * Y(B) ) + , ( Z(A) * X(B) ) - ( X(A) * Z(B) ) + , ( X(A) * Y(B) ) - ( Y(A) * X(B) ) + ); + + % calculates the scaler triple product of two vectors % + integer procedure scalerTripleProduct( reference(Vector) value A, B, C ) ; + dotProduct( A, crossProduct( B, C ) ); + + % calculates the vector triple product of two vectors % + reference(Vector) procedure vectorTripleProduct( reference(Vector) value A, B, C ) ; + crossProduct( A, crossProduct( B, C ) ); + + % test the Vector routines % + begin + procedure writeonVector( reference(Vector) value v ) ; + writeon( "(", X(v), ", ", Y(v), ", ", Z(v), ")" ); + + Reference(Vector) a, b, c; + + a := Vector( 3, 4, 5 ); + b := Vector( 4, 3, 5 ); + c := Vector( -5, -12, -13 ); + + i_w := 1; s_w := 0; % set output formatting % + + write( " a: " ); writeonVector( a ); + write( " b: " ); writeonVector( b ); + write( " c: " ); writeonVector( c ); + write( " a . b: ", dotProduct( a, b ) ); + write( " a x b: " ); writeonVector( crossProduct( a, b ) ); + write( "a . ( b x c ): ", scalerTripleProduct( a, b, c ) ); + write( "a x ( b x c ): " ); writeonVector( vectorTripleProduct( a, b, c ) ) + end +end. diff --git a/Task/Vector-products/Common-Lisp/vector-products.lisp b/Task/Vector-products/Common-Lisp/vector-products-1.lisp similarity index 100% rename from Task/Vector-products/Common-Lisp/vector-products.lisp rename to Task/Vector-products/Common-Lisp/vector-products-1.lisp diff --git a/Task/Vector-products/Common-Lisp/vector-products-2.lisp b/Task/Vector-products/Common-Lisp/vector-products-2.lisp new file mode 100644 index 0000000000..5cd194e422 --- /dev/null +++ b/Task/Vector-products/Common-Lisp/vector-products-2.lisp @@ -0,0 +1,22 @@ +(defun cross (a b) + (when (and (equal (length a) 3) (equal (length b) 3)) + (vector + (- (* (elt a 1) (elt b 2)) (* (elt a 2) (elt b 1))) + (- (* (elt a 2) (elt b 0)) (* (elt a 0) (elt b 2))) + (- (* (elt a 0) (elt b 1)) (* (elt a 1) (elt b 0)))))) + +(defun dot (a b) + (when (equal (length a) (length b)) + (loop for ai across a for bi across b sum (* ai bi)))) + +(defun scalar-triple (a b c) + (dot a (cross b c))) + +(defun vector-triple (a b c) + (cross a (cross b c))) + +(defun task (a b c) + (values (dot a b) + (cross a b) + (scalar-triple a b c) + (vector-triple a b c))) diff --git a/Task/Vector-products/J/vector-products-1.j b/Task/Vector-products/J/vector-products-1.j index 10e812887a..2f23451d7b 100644 --- a/Task/Vector-products/J/vector-products-1.j +++ b/Task/Vector-products/J/vector-products-1.j @@ -1,3 +1 @@ -CT=: C.!.2 @ (#:i.) @ $~ -ip=: +/ .* NB. inner product -cross=: ] ip CT@#@[ ip [ +cross=: (1&|.@[ * 2&|.@]) - 2&|.@[ * 1&|.@] diff --git a/Task/Vector-products/J/vector-products-2.j b/Task/Vector-products/J/vector-products-2.j index 81ad3d17fc..10e812887a 100644 --- a/Task/Vector-products/J/vector-products-2.j +++ b/Task/Vector-products/J/vector-products-2.j @@ -1 +1,3 @@ -cross=: [: > [: -&.>/ .(*&.>) (<"1=i.3) , ,:&:(<"0) +CT=: C.!.2 @ (#:i.) @ $~ +ip=: +/ .* NB. inner product +cross=: ] ip CT@#@[ ip [ diff --git a/Task/Vector-products/J/vector-products-3.j b/Task/Vector-products/J/vector-products-3.j index 15ef0dd933..81ad3d17fc 100644 --- a/Task/Vector-products/J/vector-products-3.j +++ b/Task/Vector-products/J/vector-products-3.j @@ -1,12 +1 @@ -a=: 3 4 5 -b=: 4 3 5 -c=: -5 12 13 - -A=: 0 {:: ] NB. contents of the first box on the right -B=: 1 {:: ] NB. contents of the second box on the right -C=: 2 {:: ] NB. contents of the third box on the right - -dotP=: A ip B -crossP=: A cross B -scTriP=: A ip B cross C -veTriP=: A cross B cross C +cross=: [: > [: -&.>/ .(*&.>) (<"1=i.3) , ,:&:(<"0) diff --git a/Task/Vector-products/J/vector-products-4.j b/Task/Vector-products/J/vector-products-4.j index 398e30e19d..15ef0dd933 100644 --- a/Task/Vector-products/J/vector-products-4.j +++ b/Task/Vector-products/J/vector-products-4.j @@ -1,8 +1,12 @@ - dotP a;b -49 - crossP a;b -5 5 _7 - scTriP a;b;c -6 - veTriP a;b;c -_267 204 _3 +a=: 3 4 5 +b=: 4 3 5 +c=: -5 12 13 + +A=: 0 {:: ] NB. contents of the first box on the right +B=: 1 {:: ] NB. contents of the second box on the right +C=: 2 {:: ] NB. contents of the third box on the right + +dotP=: A ip B +crossP=: A cross B +scTriP=: A ip B cross C +veTriP=: A cross B cross C diff --git a/Task/Vector-products/J/vector-products-5.j b/Task/Vector-products/J/vector-products-5.j new file mode 100644 index 0000000000..398e30e19d --- /dev/null +++ b/Task/Vector-products/J/vector-products-5.j @@ -0,0 +1,8 @@ + dotP a;b +49 + crossP a;b +5 5 _7 + scTriP a;b;c +6 + veTriP a;b;c +_267 204 _3 diff --git a/Task/Vector-products/Julia/vector-products.julia b/Task/Vector-products/Julia/vector-products.julia new file mode 100644 index 0000000000..670b3bdea2 --- /dev/null +++ b/Task/Vector-products/Julia/vector-products.julia @@ -0,0 +1,26 @@ +function scltrip{T<:Number}(a::AbstractArray{T,1}, + b::AbstractArray{T,1}, + c::AbstractArray{T,1}) + dot(a, cross(b, c)) +end + +function vectrip{T<:Number}(a::AbstractArray{T,1}, + b::AbstractArray{T,1}, + c::AbstractArray{T,1}) + cross(a, cross(b, c)) +end + +a = [3, 4, 5] +b = [4, 3, 5] +c = [-5, -12, -13] + +println("Test Vectors:") +println(" a = ", a) +println(" b = ", a) +println(" c = ", a) + +println("\nVector Products:") +println(" a dot b = ", dot(a, b)) +println(" a cross b = ", cross(a, b)) +println(" a dot b cross c = ", scltrip(a, b, c)) +println(" a cross b cross c = ", vectrip(a, b, c)) diff --git a/Task/Vector-products/PowerShell/vector-products.psh b/Task/Vector-products/PowerShell/vector-products.psh new file mode 100644 index 0000000000..93c7b58bac --- /dev/null +++ b/Task/Vector-products/PowerShell/vector-products.psh @@ -0,0 +1,27 @@ +function dot-product($a,$b) { + $a[0]*$b[0] + $a[1]*$b[1] + $a[2]*$b[2] +} + +function cross-product($a,$b) { + $v1 = $a[1]*$b[2] - $a[2]*$b[1] + $v2 = $a[2]*$b[0] - $a[0]*$b[2] + $v3 = $a[0]*$b[1] - $a[1]*$b[0] + @($v1,$v2,$v3) +} + +function scalar-triple-product($a,$b,$c) { + dot-product $a (cross-product $b $c) +} + +function vector-triple-product($a,$b) { + cross-product $a (cross-product $b $c) +} + +$a = @(3, 4, 5) +$b = @(4, 3, 5) +$c = @(-5, -12, -13) + +"a.b = $(dot-product $a $b)" +"axb = $(cross-product $a $b)" +"a.(bxc) = $(scalar-triple-product $a $b $c)" +"ax(bxc) = $(vector-triple-product $a $b $c)" diff --git a/Task/Verify-distribution-uniformity-Naive/00DESCRIPTION b/Task/Verify-distribution-uniformity-Naive/00DESCRIPTION index 52df8b5ccf..7acaef09fb 100644 --- a/Task/Verify-distribution-uniformity-Naive/00DESCRIPTION +++ b/Task/Verify-distribution-uniformity-Naive/00DESCRIPTION @@ -1,4 +1,4 @@ -This task is an adjunct to [[Seven-dice from Five-dice]]. +This task is an adjunct to [[Seven-sided dice from five-sided dice]]. Create a function to check that the random integers returned from a small-integer generator function have uniform distribution. @@ -11,7 +11,7 @@ The function should produce: * Some indication of the distribution achieved. * An 'error' if the distribution is not flat enough. -Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from [[Seven-dice from Five-dice]]). +Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from [[Seven-sided dice from five-sided dice]]). See also: *[[Verify distribution uniformity/Chi-squared test]] diff --git a/Task/Verify-distribution-uniformity-Naive/Elixir/verify-distribution-uniformity-naive.elixir b/Task/Verify-distribution-uniformity-Naive/Elixir/verify-distribution-uniformity-naive.elixir new file mode 100644 index 0000000000..08c101775a --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Elixir/verify-distribution-uniformity-naive.elixir @@ -0,0 +1,23 @@ +defmodule VerifyDistribution do + def naive( generator, times, delta_percent \\ 3 ) do + dict = Enum.reduce( List.duplicate(generator, times), Map.new, fn f,d -> update_counter(f,d) end ) + values = for x <- Dict.keys(dict), do: Dict.get(dict, x) + average = Enum.sum( values ) / Dict.size( dict ) + delta = average * (delta_percent / 100) + fun = fn {_key, value} -> abs(value - average) > delta end + too_large_dict = Enum.filter( dict, fun ) + return( Dict.size(too_large_dict), too_large_dict, average, delta_percent ) + end + + def return( 0, _too_large_dict, _average, _delta ), do: :ok + def return( _n, too_large_dict, average, delta ) do + {:error, {Dict.to_list(too_large_dict), :failed_expected_average, average, 'with_delta_%', delta}} + end + + def update_counter( fun, dict ), do: Dict.update( dict, fun.(), 1, fn(val) -> val+1 end ) +end + +:random.seed(:erlang.now) +fun = fn -> Dice.dice7 end +IO.inspect VerifyDistribution.naive( fun, 100000, 3 ) +IO.inspect VerifyDistribution.naive( fun, 100, 3 ) diff --git a/Task/Verify-distribution-uniformity-Naive/Factor/verify-distribution-uniformity-naive.factor b/Task/Verify-distribution-uniformity-Naive/Factor/verify-distribution-uniformity-naive.factor new file mode 100644 index 0000000000..d869712219 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Factor/verify-distribution-uniformity-naive.factor @@ -0,0 +1,57 @@ +USING: kernel random sequences assocs locals sorting prettyprint + math math.functions math.statistics math.vectors math.ranges ; +IN: rosetta-code.dice7 + +! Output a random integer 1..5. +: dice5 ( -- x ) + 5 [1,b] random +; + +! Output a random integer 1..7 using dice5 as randomness source. +: dice7 ( -- x ) + 0 [ dup 21 < ] [ drop dice5 5 * dice5 + 6 - ] do until + 7 rem 1 + +; + +! Roll the die by calling the quotation the given number of times and return +! an array with roll results. +! Sample call: 1000 [ dice7 ] roll +: roll ( times quot: ( -- x ) -- array ) + [ call( -- x ) ] curry replicate +; + +! Input array contains outcomes of a number of die throws. Each die result is +! an integer in the range 1..X. Calculate and return the number of each +! of the results in the array so that in the first position of the result +! there is the number of ones in the input array, in the second position +! of the result there is the number of twos in the input array, etc. +: count-dice-outcomes ( X array -- array ) + histogram + swap [1,b] [ over [ 0 or ] change-at ] each + sort-keys values +; + +! Verify distribution uniformity/Naive. Delta is the acceptable deviation +! from the ideal number of items in each bucket, expressed as a fraction of +! the total count. Sides is the number of die sides. Die-func is a word that +! produces a random number on stack in the range [1..sides], times is the +! number of times to call it. +! Sample call: 0.02 7 [ dice7 ] 100000 verify +:: verify ( delta sides die-func: ( -- random ) times -- ) + sides + times die-func roll + count-dice-outcomes + dup . + times sides / :> ideal-count + ideal-count v-n vabs + times v/n + delta [ < ] curry all? + [ "Random enough" . ] [ "Not random enough" . ] if +; + + +! Call verify with 1, 10, 100, ... 1000000 rolls of 7-sided die. +: verify-all ( -- ) + { 1 10 100 1000 10000 100000 1000000 } + [| times | 0.02 7 [ dice7 ] times verify ] each +; diff --git a/Task/Verify-distribution-uniformity-Naive/Forth/verify-distribution-uniformity-naive.fth b/Task/Verify-distribution-uniformity-Naive/Forth/verify-distribution-uniformity-naive.fth new file mode 100644 index 0000000000..74c9235589 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Forth/verify-distribution-uniformity-naive.fth @@ -0,0 +1,24 @@ +: .bounds ( u1 u2 -- ) ." lower bound = " . ." upper bound = " 1- . cr ; +: init-bins ( n -- addr ) + cells dup allocate throw tuck swap erase ; +: expected ( u1 cnt -- u2 ) over 2/ + swap / ; +: calc-limits ( n cnt pct -- low high ) + >r expected r> over 100 */ 2dup + 1+ >r - r> ; +: make-histogram ( bins xt cnt -- ) + 0 ?do 2dup execute 1- cells + 1 swap +! loop 2drop ; +: valid-bin? ( addr n low high -- f ) + 2>r cells + @ dup . 2r> within ; + +: check-distribution {: xt cnt n pct -- f :} +\ assumes xt generates numbers from 1 to n + n init-bins {: bins :} + n cnt pct calc-limits {: low high :} + high low .bounds + bins xt cnt make-histogram + true \ result flag + n 0 ?do + i 1+ . ." : " bins i low high valid-bin? + dup 0= if ." not " then ." ok" cr + and + loop + bins free throw ; diff --git a/Task/Verify-distribution-uniformity-Naive/Liberty-BASIC/verify-distribution-uniformity-naive.liberty b/Task/Verify-distribution-uniformity-Naive/Liberty-BASIC/verify-distribution-uniformity-naive.liberty new file mode 100644 index 0000000000..b5227ce739 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Liberty-BASIC/verify-distribution-uniformity-naive.liberty @@ -0,0 +1,58 @@ +n=1000 +print "Testing ";n;" times" +if not(check(n, 0.05)) then print "Test failed" else print "Test passed" +print + +n=10000 +print "Testing ";n;" times" +if not(check(n, 0.05)) then print "Test failed" else print "Test passed" +print + +n=50000 +print "Testing ";n;" times" +if not(check(n, 0.05)) then print "Test failed" else print "Test passed" +print + +end + +function check(n, delta) + 'fill randoms + dim a(n) + maxBucket=0 + minBucket=1e10 + for i = 1 to n + a(i) = GENERATOR() + if a(i)>maxBucket then maxBucket=a(i) + if a(i) buckets(i)) OR (buckets(i) > maxVal) ,"fail","") + if (minVal > buckets(i)) OR (buckets(i) > maxVal) then check = 0 + next +end function + +function iif$(test, valYes$, valNo$) + iif$ = valNo$ + if test then iif$ = valYes$ +end function + +function GENERATOR() + 'GENERATOR = int(rnd(0)*10) '0..9 + GENERATOR = 1+int(rnd(0)*5) '1..5: dice5 +end function diff --git a/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx b/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx index 8e215f5a13..fbc8d5f1d7 100644 --- a/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx +++ b/Task/Verify-distribution-uniformity-Naive/REXX/verify-distribution-uniformity-naive.rexx @@ -1,33 +1,33 @@ -/*REXX pgm simulates a # of trials of a random digit, show it's skew %. */ -parse arg f t d s . /*obtain arguments (options). */ -if f=='' | f==',' then f='RANDOM' /* func ¬specified? Use default.*/ -if t=='' | t==',' then t=1000000 /*times " " " */ -if d=='' | d==',' then d=1/2 /*delta% " " " */ -if s\=='' then call random ,,s /*use some seed for repeatibility*/ -highDig=9 /*use this for the highest digit.*/ -!.=0 /*zero all possible random trials*/ - do j=1 for t /* [↓] perform a lot of trials. */ - if f=='RANDOM' then ?=random(0,highDig) /*random func.*/ - else interpret '?='f"(0,"highDig')' /* user func.*/ - !.?=!.?+1 /*bump counter*/ - end /*j*/ /* [↑] trials ───► pigeonholes. */ - /* [↓] compute the dig skewness.*/ -g=t/(1+highDig) /*calculate # of each digit throw*/ -OK?='OK skewed' /*words to show skewed or if OK. */ -w=max(8,length(t)) /*maximum length of # of trials. */ -pad=left('',9) /*this is used for indentation. */ -say pad 'digit' center("hits",w) ' skew ' "skew%" 'result' /*hdr. */ -say pad '─────' center('',w,'─') '──────' "─────" '──────' /*sep. */ - /** [↑] show header & separator.*/ - do k=0 to highDig /*process each of the possible #.*/ - skew=g-!.k /*calculate the skew for the dig.*/ - skewPC=(1-(g-abs(skew))/g)*100 /* " " " percentage. */ - ok=right(word(ok?,1+(skewPC>d)),6) /*it's gotta be one or the other.*/ +/*REXX pgm simulates a number of trials of a random digit and show it's skew %*/ +parse arg f t d s . /*obtain arguments (options) from C.L. */ +if f=='' | f==',' then f='RANDOM' /*function not specified? Use default.*/ +if t=='' | t==',' then t=1000000 /*times " " " " */ +if d=='' | d==',' then d=1/2 /*delta% " " " " */ +if s\=='' then call random ,,s /*use some RAND seed for repeatability.*/ +highDig=9 /*use this var for the highest digit. */ +!.=0 /*initialize all possible random trials*/ + do t /* [↓] perform a bunch of trials. */ + if f=='RANDOM' then ?=random(0,highDig) /*random function.*/ + else interpret '?='f"(0,"highDig')' /* user function.*/ + !.?=!.?+1 /*bump the counter*/ + end /*t*/ /* [↑] store trials ───► pigeonholes. */ + /* [↓] compute the digit's skewness. */ +g=t/(1+highDig) /*calculate number of each digit throw.*/ +OK?='OK skewed' /*words to show "skewed" or if "OK".*/ +w=max(8,length(t)) /*maximum length of number of trials.*/ +pad=left('',9) /*this is used for output indentation. */ +say pad 'digit' center("hits",w) ' skew ' "skew%" 'result' /*header. */ +say pad '─────' center('',w,'─') '──────' "─────" '──────' /*separator.*/ + /** [↑] show header and the separator.*/ + do k=0 to highDig /*process each of the possible digits. */ + skew=g-!.k /*calculate the skew for the digit. */ + skewPC=(1-(g-abs(skew))/g)*100 /* " " " percentage for dig*/ + ok=center(word(ok?,1+(skewPC>d)),6) /*it's gotta be one of skewed or xx%*/ say pad center(k,5) right(!.k,w) right(skew,6) format(skewPC,,3) ok end /*k*/ -say pad '─────' center('',w,'─') '──────' "─────" '──────' /*sep. */ -y=5+1+w+1+6+1+6+1+6 /*width*/ -say pad center(" (with " t ' trials)',y) /*info.*/ -say pad center(" (skewed when exceeds " d'%)',y) /*info.*/ - /*stick a fork in it, we're done.*/ +say pad '─────' center('',w,'─') '──────' "─────" '──────' /*separator. */ +y=5+1+w+1+6+1+6+1+6 /*the width. */ +say pad center(" (with " t ' trials)',y) /*# trials. */ +say pad center(" (skewed when exceeds " d'%)',y) /*skewed note*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Julia/vigen-re-cipher-cryptanalysis.julia b/Task/Vigen-re-cipher-Cryptanalysis/Julia/vigen-re-cipher-cryptanalysis.julia new file mode 100644 index 0000000000..1e2073fa84 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Julia/vigen-re-cipher-cryptanalysis.julia @@ -0,0 +1,207 @@ +# ciphertext block {{{1 +const ciphertext = filter(isalpha, """ +MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH +VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD +ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS +FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG +ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ +ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS +JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT +LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST +MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH +QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV +RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW +TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO +SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR +ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX +BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB +BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA +FWAML ZZRXJ EKAHV FASMU LVVUT TGK +""") +# }}} + +# character frequencies {{{1 +const letters = Dict{Char, Float32}( + 'E' => 12.702, + 'T' => 9.056, + 'A' => 8.167, + 'O' => 7.507, + 'I' => 6.966, + 'N' => 6.749, + 'S' => 6.327, + 'H' => 6.094, + 'R' => 5.987, + 'D' => 4.253, + 'L' => 4.025, + 'C' => 2.782, + 'U' => 2.758, + 'M' => 2.406, + 'W' => 2.361, + 'F' => 2.228, + 'G' => 2.015, + 'Y' => 1.974, + 'P' => 1.929, + 'B' => 1.492, + 'V' => 0.978, + 'K' => 0.772, + 'J' => 0.153, + 'X' => 0.150, + 'Q' => 0.095, + 'Z' => 0.074) +const digraphs = Dict{String, Float32}( + "TH" => 15.2, + "HE" => 12.8, + "IN" => 9.4, + "ER" => 9.4, + "AN" => 8.2, + "RE" => 6.8, + "ND" => 6.3, + "AT" => 5.9, + "ON" => 5.7, + "NT" => 5.6, + "HA" => 5.6, + "ES" => 5.6, + "ST" => 5.5, + "EN" => 5.5, + "ED" => 5.3, + "TO" => 5.2, + "IT" => 5.0, + "OU" => 5.0, + "EA" => 4.7, + "HI" => 4.6, + "IS" => 4.6, + "OR" => 4.3, + "TI" => 3.4, + "AS" => 3.3, + "TE" => 2.7, + "ET" => 1.9, + "NG" => 1.8, + "OF" => 1.6, + "AL" => 0.9, + "DE" => 0.9, + "SE" => 0.8, + "LE" => 0.8, + "SA" => 0.6, + "SI" => 0.5, + "AR" => 0.4, + "VE" => 0.4, + "RA" => 0.4, + "LD" => 0.2, + "UR" => 0.2) +const trigraphs = Dict{String, Float32}( + "THE" => 18.1, + "AND" => 7.3, + "ING" => 7.2, + "ION" => 4.2, + "ENT" => 4.2, + "HER" => 3.6, + "FOR" => 3.4, + "THA" => 3.3, + "NTH" => 3.3, + "INT" => 3.2, + "TIO" => 3.1, + "ERE" => 3.1, + "TER" => 3.0, + "EST" => 2.8, + "ERS" => 2.8, + "HAT" => 2.6, + "ATI" => 2.6, + "ATE" => 2.5, + "ALL" => 2.5, + "VER" => 2.4, + "HIS" => 2.4, + "HES" => 2.4, + "ETH" => 2.4, + "OFT" => 2.2, + "STH" => 2.1, + "RES" => 2.1, + "OTH" => 2.1, + "ITH" => 2.1, + "FTH" => 2.1, + "ONT" => 2.0) +# 1}}} + +function decrypt(enc::ASCIIString, key::ASCIIString) + const enclen = length(enc) + const keylen = length(key) + + if keylen < enclen + key = (key^(div(enclen - keylen, keylen) + 2))[1:enclen] + end + + msg = Array(Char, enclen) + + for i=1:enclen + msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65) + end + + msg::Array{Char, 1} +end + +function cryptanalyze(enc::ASCIIString; maxkeylen::Integer = 20) + const enclen = length(enc) + maxkey = "" + maxdec = "" + maxscore = 0.0 + + for keylen=1:maxkeylen + key = Array(Char, keylen) + idx = filter(x -> x % keylen == 0, 1:enclen) - keylen + 1 + + for i=1:keylen + maxsubscore = 0.0 + + for j='A':'Z' + subscore = 0.0 + + for k in decrypt(enc[idx], ascii(string(j))) + subscore += get(letters, k, 0.0) + end + + if subscore > maxsubscore + maxsubscore = subscore + key[i] = j + end + end + + idx += 1 + end + + key = join(key) + const dec = decrypt(enc, key) + score = 0.0 + + for i in dec + score += get(letters, i, 0.0) + end + + for i=1:enclen - 2 + const digraph = string(dec[i], dec[i + 1]) + const trigraph = string(dec[i], dec[i + 1], dec[i + 2]) + + if haskey(digraphs, digraph) + score += 2 * get(digraphs, digraph, 0.0) + end + + if haskey(trigraphs, trigraph) + score += 3 * get(trigraphs, trigraph, 0.0) + end + end + + if score > maxscore + maxscore = score + maxkey = key + maxdec = dec + end + end + + (maxkey, join(maxdec))::Tuple{ASCIIString, ASCIIString} +end + +key, dec = cryptanalyze(ciphertext) +println("key: ", key, "\n\n", dec) + +# post-compilation profiling run +gc() +t = @elapsed cryptanalyze(ciphertext) +println("\nelapsed time: ", t, " seconds") diff --git a/Task/Vigen-re-cipher/Fortran/vigen-re-cipher.f b/Task/Vigen-re-cipher/Fortran/vigen-re-cipher.f new file mode 100644 index 0000000000..0301582903 --- /dev/null +++ b/Task/Vigen-re-cipher/Fortran/vigen-re-cipher.f @@ -0,0 +1,62 @@ +program vigenere_cipher + implicit none + + character(80) :: plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", & + ciphertext = "" + character(14) :: key = "VIGENERECIPHER" + + + call encrypt(plaintext, ciphertext, key) + write(*,*) plaintext + write(*,*) ciphertext + call decrypt(ciphertext, plaintext, key) + write(*,*) plaintext + +contains + +subroutine encrypt(intxt, outtxt, k) + character(*), intent(in) :: intxt, k + character(*), intent(out) :: outtxt + integer :: chrn + integer :: cp = 1, kp = 1 + integer :: i + + outtxt = "" + do i = 1, len(trim(intxt)) + select case(intxt(i:i)) + case ("A":"Z", "a":"z") + select case(intxt(i:i)) + case("a":"z") + chrn = iachar(intxt(i:i)) - 32 + + case default + chrn = iachar(intxt(i:i)) + + end select + + outtxt(cp:cp) = achar(modulo(chrn + iachar(k(kp:kp)), 26) + 65) + cp = cp + 1 + kp = kp + 1 + if(kp > len(k)) kp = kp - len(k) + + end select + end do +end subroutine + +subroutine decrypt(intxt, outtxt, k) + character(*), intent(in) :: intxt, k + character(*), intent(out) :: outtxt + integer :: chrn + integer :: cp = 1, kp = 1 + integer :: i + + outtxt = "" + do i = 1, len(trim(intxt)) + chrn = iachar(intxt(i:i)) + outtxt(cp:cp) = achar(modulo(chrn - iachar(k(kp:kp)), 26) + 65) + cp = cp + 1 + kp = kp + 1 + if(kp > len(k)) kp = kp - len(k) + end do +end subroutine +end program diff --git a/Task/Vigen-re-cipher/Julia/vigen-re-cipher.julia b/Task/Vigen-re-cipher/Julia/vigen-re-cipher.julia new file mode 100644 index 0000000000..304fb28082 --- /dev/null +++ b/Task/Vigen-re-cipher/Julia/vigen-re-cipher.julia @@ -0,0 +1,41 @@ +function encrypt(msg::ASCIIString, key::ASCIIString) + msg = uppercase(join(filter(isalpha, collect(msg)))) + len = length(msg) + key = uppercase(join(filter(isalpha, collect(key)))) + + if length(key) < len + key = (key^(div(len - length(key), length(key)) + 2))[1:len] + end + + enc = Array(Char, len) + + for i=1:length(msg) + enc[i] = Char((Int(msg[i]) + Int(key[i]) - 130) % 26 + 65) + end + + join(enc) +end + +function decrypt(enc::ASCIIString, key::ASCIIString) + enc = uppercase(join(filter(isalpha, collect(enc)))) + len = length(enc) + key = uppercase(join(filter(isalpha, collect(key)))) + + if length(key) < len + key = (key^(div(len - length(key), length(key)) + 2))[1:len] + end + + msg = Array(Char, len) + + for i=1:length(enc) + msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65) + end + + join(msg) +end + +const msg = "Attack at dawn." +const key = "LEMON" + +println(encrypt(msg, key)) +println(decrypt(encrypt(msg, key), key)) diff --git a/Task/Vigen-re-cipher/PHP/vigen-re-cipher.php b/Task/Vigen-re-cipher/PHP/vigen-re-cipher.php new file mode 100644 index 0000000000..14fe8e864d --- /dev/null +++ b/Task/Vigen-re-cipher/PHP/vigen-re-cipher.php @@ -0,0 +1,45 @@ + diff --git a/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust b/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust index 32d6736710..2115f3d994 100644 --- a/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust +++ b/Task/Vigen-re-cipher/Rust/vigen-re-cipher.rust @@ -1,55 +1,49 @@ -use std::ascii::AsciiCast; -use std::str::from_utf8; +use std::ascii::AsciiExt; static A: u8 = 'A' as u8; -static a: u8 = 'a' as u8; - -fn uppercase_and_filter(input: &str) -> ~[u8] { - let mut result = ~[]; - - for b in input.bytes() { - if b.is_ascii() { - let ascii = b.to_ascii(); - if ascii.is_lower() { - // We know it's ascii, so just do the math directly - result.push((b + (A - a))) - } else if ascii.is_upper() { - result.push(b); - } + +fn uppercase_and_filter(input: &str) -> Vec { + let alphabet = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + let mut result = Vec::new(); + + for c in input.chars() { + // Ignore anything that is not in our short list of chars. We can then safely cast to u8. + if alphabet.iter().any(|&x| x as char == c) { + result.push(c.to_ascii_uppercase() as u8); + } } - } - return result; + return result; } -fn vigenere(key: &str, text: &str, is_encoding: bool) -> ~str { +fn vigenere(key: &str, text: &str, is_encoding: bool) -> String { - let key_bytes = uppercase_and_filter(key); - let text_bytes = uppercase_and_filter(text); + let key_bytes = uppercase_and_filter(key); + let text_bytes = uppercase_and_filter(text); - let mut result_bytes = ~[]; + let mut result_bytes = Vec::new(); - for (i, c) in text_bytes.iter().enumerate() { - let c2 = if is_encoding { - (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A - } else { - (c - key_bytes[i % key_bytes.len()] + 26) % 26 + A - }; - result_bytes.push(c2); - } + for (i, c) in text_bytes.iter().enumerate() { + let c2 = if is_encoding { + (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A + } else { + (c + 26 - key_bytes[i % key_bytes.len()]) % 26 + A + }; + result_bytes.push(c2); + } - return from_utf8(result_bytes).to_owned(); + String::from_utf8(result_bytes).unwrap() } fn main() { - let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; - let key = "VIGENERECIPHER"; + let text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; + let key = "VIGENERECIPHER"; - println!("Text: {:s}", text); - println!("Key: {:s}", key); + println!("Text: {}", text); + println!("Key: {}", key); - let encoded = vigenere(key, text, true); - println!("Code: {:s}", encoded); - let decoded = vigenere(key, encoded, false); - println!("Back: {:s}", decoded); + let encoded = vigenere(key, text, true); + println!("Code: {}", encoded); + let decoded = vigenere(key, &encoded, false); + println!("Back: {}", decoded); } diff --git a/Task/Vigen-re-cipher/VBScript/vigen-re-cipher.vb b/Task/Vigen-re-cipher/VBScript/vigen-re-cipher.vb new file mode 100644 index 0000000000..194dfab3eb --- /dev/null +++ b/Task/Vigen-re-cipher/VBScript/vigen-re-cipher.vb @@ -0,0 +1,47 @@ +Function Encrypt(text,key) + text = OnlyCaps(text) + key = OnlyCaps(key) + j = 1 + For i = 1 To Len(text) + ms = Mid(text,i,1) + m = Asc(ms) - Asc("A") + ks = Mid(key,j,1) + k = Asc(ks) - Asc("A") + j = (j Mod Len(key)) + 1 + c = (m + k) Mod 26 + c = Chr(Asc("A")+c) + Encrypt = Encrypt & c + Next +End Function + +Function Decrypt(text,key) + key = OnlyCaps(key) + j = 1 + For i = 1 To Len(text) + ms = Mid(text,i,1) + m = Asc(ms) - Asc("A") + ks = Mid(key,j,1) + k = Asc(ks) - Asc("A") + j = (j Mod Len(key)) + 1 + c = (m - k + 26) Mod 26 + c = Chr(Asc("A")+c) + Decrypt = Decrypt & c + Next +End Function + +Function OnlyCaps(s) + For i = 1 To Len(s) + char = UCase(Mid(s,i,1)) + If Asc(char) >= 65 And Asc(char) <= 90 Then + OnlyCaps = OnlyCaps & char + End If + Next +End Function + +'testing the functions +orig_text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" +orig_key = "vigenerecipher" +WScript.StdOut.WriteLine "Original: " & orig_text +WScript.StdOut.WriteLine "Key: " & orig_key +WScript.StdOut.WriteLine "Encrypted: " & Encrypt(orig_text,orig_key) +WScript.StdOut.WriteLine "Decrypted: " & Decrypt(Encrypt(orig_text,orig_key),orig_key) diff --git a/Task/Visualize-a-tree/Clojure/visualize-a-tree.clj b/Task/Visualize-a-tree/Clojure/visualize-a-tree.clj new file mode 100644 index 0000000000..af6a0e62a3 --- /dev/null +++ b/Task/Visualize-a-tree/Clojure/visualize-a-tree.clj @@ -0,0 +1,3 @@ +(use 'vijual) + +(draw-tree [[:A] [:B] [:C [:D [:E] [:F]] [:G]]]) diff --git a/Task/Visualize-a-tree/Common-Lisp/visualize-a-tree-1.lisp b/Task/Visualize-a-tree/Common-Lisp/visualize-a-tree-1.lisp new file mode 100644 index 0000000000..dc18cefa7a --- /dev/null +++ b/Task/Visualize-a-tree/Common-Lisp/visualize-a-tree-1.lisp @@ -0,0 +1,32 @@ +(defun visualize (tree) + (labels + ((rprint (list) + (mapc #'princ (reverse list))) + (vis-h (tree branches) + (let ((len (length tree))) + (loop + for item in tree + for idx from 1 to len do + (cond + ((listp item) + (rprint (cdr branches)) + (princ "+---+") + (let ((next (cons "| " + (if (= idx len) + (cons " " (cdr branches)) + branches)))) + (terpri) + (rprint (if (null item) + (cdr next) + next)) + (terpri) + (vis-h item next))) + (t + (rprint (cdr branches)) + (princ item) + (terpri) + (rprint (if (= idx len) + (cdr branches) + branches)) + (terpri))))))) + (vis-h tree '("| ")))) diff --git a/Task/Visualize-a-tree/Common-Lisp/visualize-a-tree-2.lisp b/Task/Visualize-a-tree/Common-Lisp/visualize-a-tree-2.lisp new file mode 100644 index 0000000000..7712ec5d38 --- /dev/null +++ b/Task/Visualize-a-tree/Common-Lisp/visualize-a-tree-2.lisp @@ -0,0 +1,32 @@ +CL-USER> (visualize '(a b c ((d (e ((() ()))) f)) (g))) +A +| +B +| +C +| ++---+ +| | +| +---+ +| | +| D +| | +| +---+ +| | | +| | E +| | | +| | +---+ +| | | +| | +---+ +| | | +| | +---+ +| | | +| | +---+ +| | +| F +| ++---+ + | + G + +NIL diff --git a/Task/Visualize-a-tree/Go/visualize-a-tree-3.go b/Task/Visualize-a-tree/Go/visualize-a-tree-3.go new file mode 100644 index 0000000000..a26f52b06e --- /dev/null +++ b/Task/Visualize-a-tree/Go/visualize-a-tree-3.go @@ -0,0 +1,46 @@ +package main + +import "fmt" + +type tree []node + +type node struct { + label string + children []int // indexes into tree +} + +func main() { + vis(tree{ + 0: node{"root", []int{1, 2, 3}}, + 1: node{"ei", []int{4, 5}}, + 2: node{"bee", nil}, + 3: node{"si", nil}, + 4: node{"dee", nil}, + 5: node{"y", []int{6}}, + 6: node{"eff", nil}, + }) +} + +func vis(t tree) { + if len(t) == 0 { + fmt.Println("") + return + } + var f func(int, string) + f = func(n int, pre string) { + ch := t[n].children + if len(ch) == 0 { + fmt.Println("╴", t[n].label) + return + } + fmt.Println("┐", t[n].label) + last := len(ch) - 1 + for _, ch := range ch[:last] { + fmt.Print(pre, "├─") + f(ch, pre+"│ ") + } + fmt.Print(pre, "└─") + f(ch[last], pre+" ") + } + f(0, "") +} diff --git a/Task/Visualize-a-tree/J/visualize-a-tree-1.j b/Task/Visualize-a-tree/J/visualize-a-tree-1.j new file mode 100644 index 0000000000..8e0d3c6d64 --- /dev/null +++ b/Task/Visualize-a-tree/J/visualize-a-tree-1.j @@ -0,0 +1,43 @@ +BOXC=: 9!:6 '' NB. box drawing characters +EW =: {: BOXC NB. east-west + +showtree=: 4 : 0 + NB. y is parent index for each node (non-indices for root nodes) + NB. x is label for each node + t=. ( x NB. tree fragments + c=. |:(#~ e./@|:);(~.,"0&.>( j{&.>/ extend&.>)&> t -. a: +) + +subtree=: 4 : 0 + p=. EW={."1 s=. >{.t=. graft y + (<(>{.x) root p),(<(connect p),.s),}.t +) + +graft=: 3 : 0 + n=. (-~ >./) #&> y + f=. i.@(,&0)@#&.>@{.&.> y + ,&.>/ y ,&> n$&.>f +) + +connect=: 3 : 0 + b=. (+./\ *. +./\.) y + c=. (b+2*y){' ',9 3 3{BOXC NB. │ NS ├ E + c=. (0{BOXC) (b i. 1)}c NB. ┌ NW + c=. (6{BOXC) (b i: 1)}c NB. └ SW + j=. (b i. 1)+<.-:+/b + EW&(j})^:(1=+/b) c j}~ ((0 3 6 9{BOXC)i.j{c){1 4 7 5{BOXC +) + +root=: 4 : 0 + j=. k+<.-:1+(y i: 1)-k=. y i. 1 + (-j)|.(#y){.x,.,:' ',EW +) + +extend=: 3 : '(+./\"1 (y=EW) *. *./\."1 y e.'' '',EW)}y,:EW' diff --git a/Task/Visualize-a-tree/J/visualize-a-tree-2.j b/Task/Visualize-a-tree/J/visualize-a-tree-2.j new file mode 100644 index 0000000000..dd240a708d --- /dev/null +++ b/Task/Visualize-a-tree/J/visualize-a-tree-2.j @@ -0,0 +1,6 @@ + (i.10) showtree _,}.p:inv i.10 + ┌─ 6 + ┌─ 1 ─── 3 ─┴─ 7 + │ ┌─ 8 +─ 0 ─┤ ┌─ 4 ─┴─ 9 + └─ 2 ─┴─ 5 diff --git a/Task/Visualize-a-tree/REXX/visualize-a-tree.rexx b/Task/Visualize-a-tree/REXX/visualize-a-tree.rexx index 2585248fdc..d76231da5c 100644 --- a/Task/Visualize-a-tree/REXX/visualize-a-tree.rexx +++ b/Task/Visualize-a-tree/REXX/visualize-a-tree.rexx @@ -19,7 +19,7 @@ tt: Procedure Expose node. c=node.k.i If st<>'' Then st=left(st,length(st)-2)' ' - st=repl(st,' ','` ') + st=changestr('` ',st,' ') Say st||s||node.c.0name Call tt c,st||s End diff --git a/Task/Visualize-a-tree/Ruby/visualize-a-tree-3.rb b/Task/Visualize-a-tree/Ruby/visualize-a-tree-3.rb new file mode 100644 index 0000000000..be0fd7ee1b --- /dev/null +++ b/Task/Visualize-a-tree/Ruby/visualize-a-tree-3.rb @@ -0,0 +1,12 @@ +def ptree(tree,indent=" ") + case tree + when Array + head,*tail=tree + ptree(head,indent) + s=tail.size-1 + tail.each_with_index { |tree1,i| ptree(tree1,"#{indent}#{((i==s) ? ' ':'|')} ") } + else + puts(indent.gsub(/\s\s$/,"--").gsub(/ --$/,"\\--")+tree.to_s) + end +end +ptree [1,2,3,[4,5,6,[7,8,9]],3,[22,33]] diff --git a/Task/Vogels-approximation-method/00DESCRIPTION b/Task/Vogels-approximation-method/00DESCRIPTION index 46a48ff7af..5d526d19dc 100644 --- a/Task/Vogels-approximation-method/00DESCRIPTION +++ b/Task/Vogels-approximation-method/00DESCRIPTION @@ -44,11 +44,11 @@ Adjust the supply and demand accordingly. If demand or supply becomes 0 for a gi 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)
+2       2       2       0       3       2       3       1       0       -   C-W(50)
+3       5       5       7       4      35       -       1       0       -   E-X(10)
 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)
+6       -      19       -      23       -       -       -       4       -   D-Y(30)
         -       -       -       -       -       -       -       -       -   B-Y(20)
 
Finally calculate the cost of your solution. In the example given it is £3100: diff --git a/Task/Vogels-approximation-method/J/vogels-approximation-method-1.j b/Task/Vogels-approximation-method/J/vogels-approximation-method-1.j new file mode 100644 index 0000000000..123ac1bbb2 --- /dev/null +++ b/Task/Vogels-approximation-method/J/vogels-approximation-method-1.j @@ -0,0 +1,28 @@ +vam=:1 :0 +: + exceeding=. 0 <. -&(+/) + D=. x,y exceeding x NB. x: demands + S=. y,x exceeding y NB. y: sources + C=. (m,.0),0 NB. m: costs + B=. 1+>./,C NB. bigger than biggest cost + mincost=. <./@-.&0 NB. smallest non-zero cost + penalty=. |@(B * 2 -/@{. /:~ -. 0:)"1 - mincost"1 + R=. C*0 + while. 0 < +/D,S do. + pS=. penalty C + pD=. penalty |:C + if. pS >&(>./) pD do. + row=. (i. >./) pS + col=. (i. mincost) row { C + else. + col=. (i. >./) pD + row=. (i. mincost) col {"1 C + end. + n=. (row{S) <. col{D + S=. (n-~row{S) row} S + D=. (n-~col{D) col} D + C=. C * S *&*/ D + R=. n (avail[dim][x], vec(slicedim(tp.tsort[dim],dim,r.i))) + rcost = vec(slicedim(tp.toc, dim, r.i))[rsort] + if length(rsort) == 1 + r.l = r.m = rsort[1] + r.p = r.q = rcost[1] + else + r.l, r.m = rsort[1:2] + r.p = rcost[2] - rcost[1] + r.q = rcost[1] + end + end + nothing +end + +function vogel{T<:Integer,U<:String}(tp::TProblem{T,U}) + sdcnt = collect(size(tp.toc)) + sol = spzeros(T, sdcnt[1], sdcnt[2]) + sd = Array{Resource{T},1}[] + for dim in 1:2 + push!(sd, [Resource(dim, i, tp.sd[dim][i]) for i in 1:sdcnt[dim]]) + end + while any(map(isavailable, sd[1])) && any(map(isavailable, sd[2])) + penalize!(sd, tp) + a = maximum([sd[1], sd[2]]) + b = sd[rem1(a.dim+1,2)][a.l] + if a.dim == 2 # swap to make a supply and b demand + a, b = b, a + end + expend = min(a.quant, b.quant) + sol[a.i, b.i] = expend + a.quant -= expend + b.quant -= expend + end + return sol +end diff --git a/Task/Vogels-approximation-method/Julia/vogels-approximation-method-3.julia b/Task/Vogels-approximation-method/Julia/vogels-approximation-method-3.julia new file mode 100644 index 0000000000..91c068c516 --- /dev/null +++ b/Task/Vogels-approximation-method/Julia/vogels-approximation-method-3.julia @@ -0,0 +1,27 @@ +sup = [50, 60, 50, 50] +slab = ["W", "X", "Y", "Z"] +dem = [30, 20, 70, 30, 60] +dlab = ["A", "B", "C", "D", "E"] +c = [16 16 13 22 17; + 14 14 13 19 15; + 19 19 20 23 50; + 50 12 50 15 11] + +tp = TProblem(sup, dem, c, slab, dlab) +sol = vogel(tp) +cost = sum(tp.toc .* sol) + +println("The solution is:") +print(" ") +for s in tp.labels[2] + print(@sprintf "%4s" s) +end +println() +for i in 1:size(tp.toc)[1] + print(@sprintf " %4s" tp.labels[1][i]) + for j in 1:size(tp.toc)[2] + print(@sprintf "%4d" sol[i,j]) + end +println() +end +println("The total cost is: ", cost) diff --git a/Task/Voronoi-diagram/00DESCRIPTION b/Task/Voronoi-diagram/00DESCRIPTION index 2fc31b4e67..38885803eb 100644 --- a/Task/Voronoi-diagram/00DESCRIPTION +++ b/Task/Voronoi-diagram/00DESCRIPTION @@ -1,3 +1,4 @@ A [[wp:Voronoi diagram|Voronoi diagram]] is a diagram consisting of a number of sites. Each Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''. -The task is to demonstrate how to generate and display a Voroni diagram. See algo [[K-means++ clustering]]. +The task is to demonstrate how to generate and display a Voroni diagram. +See algo [[K-means++ clustering]]. diff --git a/Task/Voronoi-diagram/C++/voronoi-diagram.cpp b/Task/Voronoi-diagram/C++/voronoi-diagram.cpp index 011c152fcd..44320b8908 100644 --- a/Task/Voronoi-diagram/C++/voronoi-diagram.cpp +++ b/Task/Voronoi-diagram/C++/voronoi-diagram.cpp @@ -2,212 +2,190 @@ #include #include -//-------------------------------------------------------------------------------------------------- using namespace std; -//-------------------------------------------------------------------------------------------------- -class point -{ -public: - int x, y; - - point() { x = y = 0; } - point( int a, int b ) { x = a; y = b; } - int distanceSqrd( const point& p ) - { - int xd = p.x - x, - yd = p.y - y; - - return xd * xd + yd * yd; - } +////////////////////////////////////////////////////// +struct Point { + int x, y; }; -//-------------------------------------------------------------------------------------------------- -class myBitmap -{ -public: - myBitmap() : pen( NULL ) {} - ~myBitmap() - { - DeleteObject( pen ); - DeleteDC( hdc ); - DeleteObject( bmp ); - } - - bool create( int w, int h ) - { - BITMAPINFO bi; - void *pBits; - ZeroMemory( &bi, sizeof( bi ) ); - - bi.bmiHeader.biSize = sizeof( bi.bmiHeader ); - bi.bmiHeader.biBitCount = sizeof( DWORD ) * 8; - bi.bmiHeader.biCompression = BI_RGB; - bi.bmiHeader.biPlanes = 1; - bi.bmiHeader.biWidth = w; - bi.bmiHeader.biHeight = -h; - - HDC dc = GetDC( GetConsoleWindow() ); - bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 ); - if( !bmp ) return false; - - hdc = CreateCompatibleDC( dc ); - SelectObject( hdc, bmp ); - ReleaseDC( GetConsoleWindow(), dc ); - - width = w; height = h; - - return true; - } - void setPenColor( DWORD clr ) - { - if( pen ) DeleteObject( pen ); - pen = CreatePen( PS_SOLID, 1, clr ); - SelectObject( hdc, pen ); +////////////////////////////////////////////////////// +class MyBitmap { + public: + MyBitmap() : pen_(nullptr) {} + ~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; + + void *bits_ptr = nullptr; + HDC dc = GetDC(GetConsoleWindow()); + bmp_ = CreateDIBSection(dc, &bi, DIB_RGB_COLORS, &bits_ptr, nullptr, 0); + if (!bmp_) return false; + + hdc_ = CreateCompatibleDC(dc); + SelectObject(hdc_, bmp_); + ReleaseDC(GetConsoleWindow(), dc); + + width_ = w; + height_ = h; + + return true; + } + + void SetPenColor(DWORD clr) { + if (pen_) DeleteObject(pen_); + pen_ = CreatePen(PS_SOLID, 1, clr); + SelectObject(hdc_, pen_); + } + + bool SaveBitmap(const char* path) { + HANDLE file = CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) { + return false; } - 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; - } + BITMAPFILEHEADER fileheader; + BITMAPINFO infoheader; + BITMAP bitmap; + GetObject(bmp_, sizeof(bitmap), &bitmap); + + DWORD* dwp_bits = new DWORD[bitmap.bmWidth * bitmap.bmHeight]; + ZeroMemory(dwp_bits, 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)dwp_bits, &infoheader, DIB_RGB_COLORS); + + DWORD wb; + WriteFile(file, &fileheader, sizeof(BITMAPFILEHEADER), &wb, nullptr); + WriteFile(file, &infoheader.bmiHeader, sizeof(infoheader.bmiHeader), &wb, nullptr); + WriteFile(file, dwp_bits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, nullptr); + CloseHandle(file); + + delete[] dwp_bits; + return true; + } + + HDC hdc() { return hdc_; } + int width() { return width_; } + int height() { return height_; } + + private: + HBITMAP bmp_; + HDC hdc_; + HPEN pen_; + int width_, height_; +}; - HDC getDC() { return hdc; } - int getWidth() { return width; } - int getHeight() { return height; } +static int DistanceSqrd(const Point& point, int x, int y) { + int xd = x - point.x; + int yd = y - point.y; + return (xd * xd) + (yd * yd); +} -private: - HBITMAP bmp; - HDC hdc; - HPEN pen; - int width, height; -}; -//-------------------------------------------------------------------------------------------------- -class Voronoi -{ -public: - void make( myBitmap* bmp, int count ) - { - _bmp = bmp; - createPoints( count ); - createColors(); - createSites(); - setSitesPoints(); - } +////////////////////////////////////////////////////// +class Voronoi { + public: + void Make(MyBitmap* bmp, int count) { + bmp_ = bmp; + CreatePoints(count); + CreateColors(); + CreateSites(); + SetSitesPoints(); + } + + private: + void CreateSites() { + int w = bmp_->width(), h = bmp_->height(), d; + for (int hh = 0; hh < h; hh++) { + for (int ww = 0; ww < w; ww++) { + int ind = -1, dist = INT_MAX; + for (size_t it = 0; it < points_.size(); it++) { + const Point& p = points_[it]; + d = DistanceSqrd(p, ww, hh); + if (d < dist) { + dist = d; + ind = it; + } + } -private: - void createSites() - { - int w = _bmp->getWidth(), h = _bmp->getHeight(), d; - for( int hh = 0; hh < h; hh++ ) - { - for( int ww = 0; ww < w; ww++ ) - { - point bpt( ww, hh ); - int ind = -1, dist = INT_MAX; - for( int it = 0; it < points.size(); it++ ) - { - d = ( points[it] ).distanceSqrd( bpt ); - if( d < dist ) - { - dist = d; - ind = it; - } - } - - if( ind > -1 ) - SetPixel( _bmp->getDC(), ww, hh, colors[ind] ); - else - __asm nop // should never happen! - } + if (ind > -1) + SetPixel(bmp_->hdc(), ww, hh, colors_[ind]); + else + __asm nop // should never happen! } } - - void setSitesPoints() - { - for( vector::iterator it = points.begin(); it < points.end(); it++ ) - { - int x = ( *it ).x, y = ( *it ).y; - for( int i = -1; i < 2; i++ ) - for( int j = -1; j < 2; j++ ) - SetPixel( _bmp->getDC(), x + i, y + j, 0 ); - } + } + + void SetSitesPoints() { + for (const auto& point : points_) { + int x = point.x, y = point.y; + for (int i = -1; i < 2; i++) + for (int j = -1; j < 2; j++) + SetPixel(bmp_->hdc(), x + i, y + j, 0); } + } - void createPoints( int count ) - { - int w = _bmp->getWidth() - 20, h = _bmp->getHeight() - 20; - for( int i = 0; i < count; i++ ) - { - point p( rand() % w + 10, rand() % h + 10 ); - points.push_back( p ); - } + void CreatePoints(int count) { + const int w = bmp_->width() - 20, h = bmp_->height() - 20; + for (int i = 0; i < count; i++) { + points_.push_back({ rand() % w + 10, rand() % h + 10 }); } + } - void createColors() - { - for( int i = 0; i < points.size(); i++ ) - { - DWORD c = RGB( rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50 ); - colors.push_back( c ); - } + void CreateColors() { + for (size_t i = 0; i < points_.size(); i++) { + DWORD c = RGB(rand() % 200 + 50, rand() % 200 + 55, rand() % 200 + 50); + colors_.push_back(c); } + } - vector points; - vector colors; - myBitmap* _bmp; + vector points_; + vector colors_; + MyBitmap* bmp_; }; -//-------------------------------------------------------------------------------------------------- -int main(int argc, char* argv[]) -{ - ShowWindow( GetConsoleWindow(), SW_MAXIMIZE ); - srand( GetTickCount() ); - myBitmap bmp; - bmp.create( 512, 512 ); - bmp.setPenColor( 0 ); - - Voronoi v; - v.make( &bmp, 50 ); +////////////////////////////////////////////////////// +int main(int argc, char* argv[]) { + ShowWindow(GetConsoleWindow(), SW_MAXIMIZE); + srand(GetTickCount()); + + MyBitmap bmp; + bmp.Create(512, 512); + bmp.SetPenColor(0); + + Voronoi v; + v.Make(&bmp, 50); - BitBlt( GetDC( GetConsoleWindow() ), 20, 20, 512, 512, bmp.getDC(), 0, 0, SRCCOPY ); - bmp.saveBitmap( "f://rc//v.bmp" ); + BitBlt(GetDC(GetConsoleWindow()), 20, 20, 512, 512, bmp.hdc(), 0, 0, SRCCOPY); + bmp.SaveBitmap("v.bmp"); - system( "pause" ); + system("pause"); - return 0; + return 0; } -//-------------------------------------------------------------------------------------------------- diff --git a/Task/Voronoi-diagram/J/voronoi-diagram-2.j b/Task/Voronoi-diagram/J/voronoi-diagram-2.j index 7dd9229f83..7ff1965611 100644 --- a/Task/Voronoi-diagram/J/voronoi-diagram-2.j +++ b/Task/Voronoi-diagram/J/voronoi-diagram-2.j @@ -1,2 +1,2 @@ Voronoi=. ,"0/&i./@:] (i. <./)@:(+/@:*:@:-"1)"1 _ ] ?@$~ 2 ,~ [ -25 viewmat@:([ load bind'viewmat')@:Voronoi 500 500 +viewmat 25 Voronoi 500 500 [ load'viewmat' diff --git a/Task/Voronoi-diagram/Java/voronoi-diagram.java b/Task/Voronoi-diagram/Java/voronoi-diagram.java new file mode 100644 index 0000000000..c7bda4b227 --- /dev/null +++ b/Task/Voronoi-diagram/Java/voronoi-diagram.java @@ -0,0 +1,77 @@ +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.geom.Ellipse2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.Random; + +import javax.imageio.ImageIO; +import javax.swing.JFrame; + +public class Voronoi extends JFrame { + static double p = 3; + static BufferedImage I; + static int px[], py[], color[], cells = 100, size = 1000; + + public Voronoi() { + super("Voronoi Diagram"); + setBounds(0, 0, size, size); + setDefaultCloseOperation(EXIT_ON_CLOSE); + int n = 0; + Random rand = new Random(); + I = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB); + px = new int[cells]; + py = new int[cells]; + color = new int[cells]; + for (int i = 0; i < cells; i++) { + px[i] = rand.nextInt(size); + py[i] = rand.nextInt(size); + color[i] = rand.nextInt(16777215); + + } + for (int x = 0; x < size; x++) { + for (int y = 0; y < size; y++) { + n = 0; + for (byte i = 0; i < cells; i++) { + if (distance(px[i], x, py[i], y) < distance(px[n], x, py[n], y)) { + n = i; + + } + } + I.setRGB(x, y, color[n]); + + } + } + + Graphics2D g = I.createGraphics(); + g.setColor(Color.BLACK); + for (int i = 0; i < cells; i++) { + g.fill(new Ellipse2D .Double(px[i] - 2.5, py[i] - 2.5, 5, 5)); + } + + try { + ImageIO.write(I, "png", new File("voronoi.png")); + } catch (IOException e) { + + } + + } + + public void paint(Graphics g) { + g.drawImage(I, 0, 0, this); + } + + static double distance(int x1, int x2, int y1, int y2) { + double d; + d = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); // Euclidian + // d = Math.abs(x1 - x2) + Math.abs(y1 - y2); // Manhattan + // d = Math.pow(Math.pow(Math.abs(x1 - x2), p) + Math.pow(Math.abs(y1 - y2), p), (1 / p)); // Minkovski + return d; + } + + public static void main(String[] args) { + new Voronoi().setVisible(true); + } +} diff --git a/Task/Voronoi-diagram/Lua/voronoi-diagram.lua b/Task/Voronoi-diagram/Lua/voronoi-diagram.lua new file mode 100644 index 0000000000..0c3feef394 --- /dev/null +++ b/Task/Voronoi-diagram/Lua/voronoi-diagram.lua @@ -0,0 +1,77 @@ +function love.load() + love.math.setRandomSeed(os.time()) --set the random seed + keys = {} --an empty table where we will store key presses + number_cells = 50 --the number of cells we want in our diagram + --draw the voronoi diagram to a canvas + voronoiDiagram = generateVoronoi(love.window.getWidth(), love.window.getHeight(), number_cells) +end + +function hypot(x,y) + return math.sqrt(x*x + y*y) +end + +function generateVoronoi(width, height, num_cells) + canvas = love.graphics.newCanvas(width, height) + local imgx = canvas:getWidth() + local imgy = canvas:getHeight() + local nx = {} + local ny = {} + local nr = {} + local ng = {} + local nb = {} + for a = 1, num_cells do + table.insert(nx, love.math.random(0,imgx)) + table.insert(ny, love.math.random(0,imgy)) + table.insert(nr, love.math.random(0,255)) + table.insert(ng, love.math.random(0,255)) + table.insert(nb, love.math.random(0,255)) + end + love.graphics.setColor({255,255,255}) + love.graphics.setCanvas(canvas) + for y = 1, imgy do + for x = 1, imgx do + dmin = hypot(imgx-1, imgy-1) + j = -1 + for i = 1, num_cells do + d = hypot(nx[i]-x, ny[i]-y) + if d < dmin then + dmin = d + j = i + end + end + love.graphics.setColor({nr[j], ng[j], nb[j]}) + love.graphics.point(x, y) + end + end + --reset color + love.graphics.setColor({255,255,255}) + --draw points + for b = 1, num_cells do + love.graphics.point(nx[b], ny[b]) + end + love.graphics.setCanvas() + return canvas +end + +--RENDER +function love.draw() + --reset color + love.graphics.setColor({255,255,255}) + --draw diagram + love.graphics.draw(voronoiDiagram) + --draw drop shadow text + love.graphics.setColor({0,0,0}) + love.graphics.print("space: regenerate\nesc: quit",1,1) + --draw text + love.graphics.setColor({200,200,0}) + love.graphics.print("space: regenerate\nesc: quit") +end + +--CONTROL +function love.keyreleased(key) + if key == ' ' then + voronoiDiagram = generateVoronoi(love.window.getWidth(), love.window.getHeight(), number_cells) + elseif key == 'escape' then + love.event.quit() + end +end diff --git a/Task/Voronoi-diagram/Run-BASIC/voronoi-diagram.run b/Task/Voronoi-diagram/Run-BASIC/voronoi-diagram.run new file mode 100644 index 0000000000..0c1cdd107f --- /dev/null +++ b/Task/Voronoi-diagram/Run-BASIC/voronoi-diagram.run @@ -0,0 +1,75 @@ +graphic #g, 400,400 +#g flush() +spots = 100 +leftSide = 400 +rightSide = 400 + +dim locX(spots) +dim locY(spots) +dim rgb(spots,3) +dim seal(leftSide, rightSide) +dim reach(leftSide, rightSide) + +for i =1 to spots + locX(i) = int(leftSide * rnd(1)) + locY(i) = int(rightSide * rnd(1)) + rgb(i,1) = int(256 * rnd(1)) + rgb(i,2) = int(256 * rnd(1)) + rgb(i,3) = int(256 * rnd(1)) + #g color(rgb(i,1),rgb(i,2),rgb(i,3)) + #g set(locX(i),locY(i)) +next i +#g size(1) +' find reach to the first site +for x = 0 to leftSide - 1 + for y = 0 to rightSide - 1 + reach(x, y) = (locX(1) - x) ^ 2 + (locY(1) - y) ^ 2 + seal(x, y) = 1 + next y +next x +#g color("darkblue") + +' spots other than 1st spot +for i = 2 to spots + for x = locX(i) to 0 step -1 ' looking left + if not(chkPos(i,x,0, rightSide - 1)) then exit for + next x + for x = locX(i) + 1 to leftSide - 1 ' looking right + if not(chkPos(i, x, 0, rightSide - 1)) then exit for + next x +next i + +for x = 0 to leftSide - 1 + for y = 0 to rightSide - 1 + c1 = rgb(seal(x, y),1) + c2 = rgb(seal(x, y),2) + c3 = rgb(seal(x, y),3) + #g color(c1,c2,c3) + startY = y + nearest = seal(x, y) + for y = y + 1 to rightSide + if seal(x, y) <> nearest then y = y - 1 : exit for + next y + #g line(x,startY,x,y + 1) + next y +next x + +#g color("black") +#g size(4) +for i =1 to spots + #g set(locX(i),locY(i)) +next i +render #g +end + +function chkPos(site, x, startY, endY) + dxSqr = (locX(site) - x) ^ 2 + for y = startY to endY + dSqr = (locY(site) - y) ^ 2 + dxSqr + if dSqr <= reach(x, y) then + reach(x,y) = dSqr + seal(x,y) = site + chkPos = 1 + end if + next y +end function diff --git a/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-1.bat b/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-1.bat new file mode 100644 index 0000000000..fff44946df --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-1.bat @@ -0,0 +1 @@ +dir /b "%windir%\system32\*.exe" diff --git a/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-2.bat b/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-2.bat new file mode 100644 index 0000000000..14e7663827 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-2.bat @@ -0,0 +1 @@ +@for /F "tokens=*" %%F in ('dir /b "%windir%\system32\*.exe"') do echo %%F diff --git a/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-3.bat b/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-3.bat new file mode 100644 index 0000000000..4f3805b338 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Batch-File/walk-a-directory-non-recursively-3.bat @@ -0,0 +1 @@ +for /F "tokens=*" %F in ('dir /b "%windir%\system32\*.exe"') do echo %F diff --git a/Task/Walk-a-directory-Non-recursively/DCL/walk-a-directory-non-recursively.dcl b/Task/Walk-a-directory-Non-recursively/DCL/walk-a-directory-non-recursively.dcl new file mode 100644 index 0000000000..8d2f11587c --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/DCL/walk-a-directory-non-recursively.dcl @@ -0,0 +1,5 @@ +$ loop: +$ f = f$search( p1 ) +$ if f .eqs. "" then $ exit +$ write sys$output f +$ goto loop diff --git a/Task/Walk-a-directory-Non-recursively/Rust/walk-a-directory-non-recursively.rust b/Task/Walk-a-directory-Non-recursively/Rust/walk-a-directory-non-recursively.rust new file mode 100644 index 0000000000..356e599a43 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Rust/walk-a-directory-non-recursively.rust @@ -0,0 +1,36 @@ +extern crate docopt; +extern crate regex; +extern crate rustc_serialize; + +use docopt::Docopt; +use regex::Regex; + +const USAGE: &'static str = " +Usage: rosetta + +Walks the directory tree starting with the current working directory and +print filenames matching . +"; + +#[derive(Debug, RustcDecodable)] +struct Args { + arg_pattern: String, +} + +fn main() { + let args: Args = Docopt::new(USAGE) + .and_then(|d| d.decode()) + .unwrap_or_else(|e| e.exit()); + + let re = Regex::new(&args.arg_pattern).unwrap(); + let paths = std::fs::read_dir(".").unwrap(); + + for path in paths { + let path = path.unwrap().path(); + let path = path.to_str().unwrap(); + + if re.is_match(path) { + println!("{}", path); + } + } +} diff --git a/Task/Walk-a-directory-Non-recursively/VBScript/walk-a-directory-non-recursively.vb b/Task/Walk-a-directory-Non-recursively/VBScript/walk-a-directory-non-recursively.vb new file mode 100644 index 0000000000..f2548273b1 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/VBScript/walk-a-directory-non-recursively.vb @@ -0,0 +1,10 @@ +Sub show_files(folder_path,pattern) + Set objfso = CreateObject("Scripting.FileSystemObject") + For Each file In objfso.GetFolder(folder_path).Files + If InStr(file.Name,pattern) Then + WScript.StdOut.WriteLine file.Name + End If + Next +End Sub + +Call show_files("C:\Windows",".exe") diff --git a/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-1.bat b/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-1.bat index 2bc84f47fc..d1dc21781f 100644 --- a/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-1.bat +++ b/Task/Walk-a-directory-Recursively/Batch-File/walk-a-directory-recursively-1.bat @@ -1 +1 @@ -dir /a-d %1 +dir /s /b "%windir%\System32\*.exe" diff --git a/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal b/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal index 125f319de9..5c63b00191 100644 --- a/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal +++ b/Task/Walk-a-directory-Recursively/Rascal/walk-a-directory-recursively.rascal @@ -1,8 +1,11 @@ +//usage example: To list just Rascal source files, Walk(|home:///workspace/|, ".rsc"); +module Walk +import String; import IO; public void Walk(loc a, str pattern){ for (entry <- listEntries(a)) if (endsWith(entry, pattern)) println(entry); elseif (isDirectory(a+entry)) - Walk2(a+entry, pattern); + Walk(a+entry, pattern); } diff --git a/Task/Walk-a-directory-Recursively/Rust/walk-a-directory-recursively.rust b/Task/Walk-a-directory-Recursively/Rust/walk-a-directory-recursively.rust new file mode 100644 index 0000000000..2869652aa8 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Rust/walk-a-directory-recursively.rust @@ -0,0 +1,13 @@ +#![feature(fs_walk)] + +use std::fs; +use std::path::Path; + +fn main() { + for f in fs::walk_dir(&Path::new("/home/pavel/Music")).unwrap() { + let p = f.unwrap().path(); + if p.extension().unwrap_or("".as_ref()) == "mp3" { + println!("{:?}", p); + } + } +} diff --git a/Task/Web-scraping/00META.yaml b/Task/Web-scraping/00META.yaml index c73ffedaa5..55421ceeb8 100644 --- a/Task/Web-scraping/00META.yaml +++ b/Task/Web-scraping/00META.yaml @@ -1,4 +1,4 @@ --- category: - Input_Output -note: Networking +note: Networking and Web Interaction diff --git a/Task/Web-scraping/Julia/web-scraping-1.julia b/Task/Web-scraping/Julia/web-scraping-1.julia new file mode 100644 index 0000000000..2e73921cff --- /dev/null +++ b/Task/Web-scraping/Julia/web-scraping-1.julia @@ -0,0 +1,22 @@ +using Requests + +function getusnotime() + const url = "http://tycho.usno.navy.mil/timer.pl" + s = try + get(url) + catch err + @sprintf "get(%s)\n => %s" url err + end + isa(s, Requests.Response) || return (s, false) + t = match(r"
(.*UTC)", s.data) + isa(t, RegexMatch) || return (@sprintf("raw html:\n %s", s.data), false) + return (t.captures[1], true) +end + +(t, issuccess) = getusnotime() + +if issuccess + println("The USNO time is ", t) +else + println("Failed to fetch UNSO time:\n", t) +end diff --git a/Task/Web-scraping/Julia/web-scraping-2.julia b/Task/Web-scraping/Julia/web-scraping-2.julia new file mode 100644 index 0000000000..1fda6ba0d9 --- /dev/null +++ b/Task/Web-scraping/Julia/web-scraping-2.julia @@ -0,0 +1,17 @@ +Failed to fetch UNSO time: +raw html: + + + +What time is it? +

US Naval Observatory Master Clock Time

+
Apr. 20, 17:55:31 UTC Universal Time +
Apr. 20, 01:55:31 PM EDT Eastern Time +
Apr. 20, 12:55:31 PM CDT Central Time +
Apr. 20, 11:55:31 AM MDT Mountain Time +
Apr. 20, 10:55:31 AM PDT Pacific Time +
Apr. 20, 09:55:31 AM AKDT Alaska Time +
Apr. 20, 07:55:31 AM HAST Hawaii-Aleutian Time +

+ + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + +
+
+ + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + +
+ +', 'text/xml' diff --git a/Task/XML-XPath/CoffeeScript/xml-xpath-2.coffee b/Task/XML-XPath/CoffeeScript/xml-xpath-2.coffee new file mode 100644 index 0000000000..a6d6ee395a --- /dev/null +++ b/Task/XML-XPath/CoffeeScript/xml-xpath-2.coffee @@ -0,0 +1,12 @@ +# Retrieve the first "item" element +doc.evaluate('//item', doc, {}, 7, {}).snapshotItem 0 + +# Perform an action on each "price" element (print it out) +prices = doc.evaluate "//price", doc, {}, 7, {} +for i in [0...prices.snapshotLength] by 1 + console.log prices.snapshotItem(i).textContent + +# Get an array of all the "name" elements +names = doc.evaluate "//name", doc, {}, 7, {} +names = for i in [0...names.snapshotLength] by 1 + names.snapshotItem i diff --git a/Task/XML-XPath/REXX/xml-xpath-1.rexx b/Task/XML-XPath/REXX/xml-xpath-1.rexx index f4051b98c5..56ed3e634b 100644 --- a/Task/XML-XPath/REXX/xml-xpath-1.rexx +++ b/Task/XML-XPath/REXX/xml-xpath-1.rexx @@ -1,36 +1,35 @@ -/*REXX program to parse various queries on an XML document (from a file)*/ -iFID='XPATH.XML' /*name of the input XML file(doc)*/ -$= /*string will contain file's text*/ - do j=1 while lines(iFID)\==0 /*read the entire file into a str*/ - $=$ linein(iFID) /*append the line to the $ string*/ +/*REXX program to parse various queries on an XML document (from a file). */ +iFID='XPATH.XML' /*name of the input XML file (doc). */ +$= /*string will contain the file's text. */ + do j=1 while lines(iFID)\==0 /*read the entire file into a string. */ + $=$ linein(iFID) /*append the line to the $ string. */ end /*j*/ - /* [↓] show 1st ITEM in the doc*/ -parse var $ '" -say center('first item:',length(space(item)),'─') /*show a nice header*/ + /* [↓] show 1st ITEM in the document*/ +parse var $ '" +say center('first item:',length(space(item)),'─') /*display a nice header.*/ say space(item) - /* [↓] show all PRICES in the doc*/ -prices= /*nullify the list and add to it.*/ -$$=$ /*start with a fresh copy of doc.*/ - do until $$='' /* [↓] keep parsing until done. */ - parse var $$ '' price '' $$ - prices=prices price /*added the price to the list. */ + /* [↓] show all PRICES in the document*/ +prices= /*nullify the list and add/append to it*/ +$$=$ /*start with a fresh copy of document. */ + do until $$='' /* [↓] keep parsing string until done.*/ + parse var $$ '' price '' $$ + prices=prices price /*add/append the price to the list. */ end /*until*/ say -say center('prices:',length(space(prices)),'─') /*show a nice header*/ +say center('prices:',length(space(prices)),'─') /*display a nice header.*/ say space(prices) - /* [↓] show all NAMES in the doc*/ -names.= /*nullify the list and add to it.*/ -L=length(' names: ') /*maximum length of any one name.*/ -$$=$ /*start with a fresh copy of doc.*/ - do #=1 until $$='' /* [↓] keep parsing until done. */ - parse var $$ '' names.# '' $$ - L=max(L,length(names.#)) /*used to find the widest name. */ + /* [↓] show all NAMES in the document*/ +names.= /*nullify the list and add/append to it*/ +L=length(' names: ') /*maximum length of any one list name. */ +$$=$ /*start with a fresh copy of document. */ + do #=1 until $$='' /* [↓] keep parsing string until done.*/ + parse var $$ '' names.# '' $$ + L=max(L,length(names.#)) /*L: is used to find the widest name. */ end /*#*/ -names.0=#-1 /*adjust the # of names (DO loop)*/ -say -say center('names:',L,'─') /*show a nicely formatted header.*/ - do k=1 for names.0 /*show all the names in the list.*/ - say names.k /*show a name from the NAMES list*/ +names.0=#-1; say /*adjust the number of names (DO loop).*/ +say center('names:',L,'─') /*display a nicely formatted header. */ + do k=1 for names.0 /*display all the names in the list. */ + say names.k /*display a name from the NAMES list.*/ end /*k*/ -exit /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/XML-XPath/REXX/xml-xpath-2.rexx b/Task/XML-XPath/REXX/xml-xpath-2.rexx index 43726fd7bc..10ac03f0d3 100644 --- a/Task/XML-XPath/REXX/xml-xpath-2.rexx +++ b/Task/XML-XPath/REXX/xml-xpath-2.rexx @@ -1,34 +1,32 @@ -/*REXX program to parse various queries on an XML document (from a file)*/ -iFID='XPATH.XML' /*name of the input XML file(doc)*/ -$= /*string will contain file's text*/ - do j=1 while lines(iFID)\==0 /*read the entire file into a str*/ - $=$ linein(iFID) /*append the line to the $ string*/ - end /*j*/ +/*REXX program to parse various queries on an XML document (from a file). */ +iFID='XPATH.XML' /*name of the input XML file (doc). */ +$= /*string will contain the file's text. */ + do j=1 while lines(iFID)\==0 /*read the entire file into a string. */ + $=$ linein(iFID) /*append the line to the $ string. */ + end /*j*/ + /* [↓] display 1st ITEM in document. */ +call parser 'item', 0 /*go and parse the all the ITEMs. */ +say center('first item:',@L.1,'─') /*display a nicely formatted header. */ +say @.1; say /*display the first ITEM found. */ -call parser 'item', 0 /*go and parse the all ITEMs. */ -say center('first item:',@L.1,'─') /*show a nicely formatted header.*/ -say @.1 /*show the first ITEM found. */ -say - -call parser 'price' /*go and parse all the PRICEs. */ -say center('prices:',length(@@@),'─') /*show a nicely formatted header.*/ -say @@@ /*show a list of all the prices. */ -say +call parser 'price' /*go and parse all the PRICEs. */ +say center('prices:',length(@@@),'─') /*display a nicely formatted header. */ +say @@@; say /*display a list of all the prices. */ call parser 'name' -say center('names:',@L,'─') /*show a nicely formatted header.*/ - do k=1 for # /*show all the names in the list.*/ - say @.k /*show a name from the NAMES list*/ - end /*k*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────PARSER subroutine───────────────────*/ -parser: parse arg yy,tail,,@. @@. @@@; $$=$; @L=9; yb='<'yy; ye='" -tail=word(tail 1, 1) /*use a tail ">" or not?*/ - do #=1 until $$='' /*parse complete XML doc*/ - if tail then parse var $$ (yb) '>' @@.# (ye) $$ /*find meat*/ - else parse var $$ (yb) @@.# (ye) $$ /* " " */ - @.#=space(@@.#); @@@=space(@@@ @.#) /*shrink; @@@=list of YY*/ - @L.#=length(@.#); @L=max(@L,@L.#) /*YY length, max length.*/ +say center('names:',@L,'─') /*display a nicely formatted header. */ + do k=1 for # /*display all the names in the list. */ + say @.k /*display a name from the NAMES list.*/ + end /*k*/ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +parser: parse arg yy,tail,,@. @@. @@@; $$=$; @L=9; yb='<'yy; ye='" +tail=word(tail 1, 1) /*use a tail ">" or not?*/ + do #=1 until $$='' /*parse complete XML doc. */ + if tail then parse var $$ (yb) '>' @@.# (ye) $$ /*find meat.*/ + else parse var $$ (yb) @@.# (ye) $$ /* " " */ + @.#=space(@@.#); @@@=space(@@@ @.#) /*shrink; @@@=list of YY.*/ + @L.#=length(@.#); @L=max(@L,@L.#) /*length; maximum length. */ end /*#*/ -#=#-1 /*adjust # things found.*/ +#=#-1 /*adjust # of thing found.*/ return diff --git a/Task/XML-XPath/VBScript/xml-xpath.vb b/Task/XML-XPath/VBScript/xml-xpath.vb new file mode 100644 index 0000000000..ed86e7a8ed --- /dev/null +++ b/Task/XML-XPath/VBScript/xml-xpath.vb @@ -0,0 +1,29 @@ +Set objXMLDoc = CreateObject("msxml2.domdocument") + +objXMLDoc.load("In.xml") + +Set item_nodes = objXMLDoc.selectNodes("//item") +i = 1 +For Each item In item_nodes + If i = 1 Then + WScript.StdOut.Write item.xml + WScript.StdOut.WriteBlankLines(2) + Exit For + End If +Next + +Set price_nodes = objXMLDoc.selectNodes("//price") +list_price = "" +For Each price In price_nodes + list_price = list_price & price.text & ", " +Next +WScript.StdOut.Write list_price +WScript.StdOut.WriteBlankLines(2) + +Set name_nodes = objXMLDoc.selectNodes("//name") +list_name = "" +For Each name In name_nodes + list_name = list_name & name.text & ", " +Next +WScript.StdOut.Write list_name +WScript.StdOut.WriteBlankLines(2) diff --git a/Task/Y-combinator/C++/y-combinator-3.cpp b/Task/Y-combinator/C++/y-combinator-3.cpp new file mode 100644 index 0000000000..5aeae9d2fe --- /dev/null +++ b/Task/Y-combinator/C++/y-combinator-3.cpp @@ -0,0 +1,13 @@ +template +struct YFunctor { + const std::function(std::function)> f; + YFunctor(std::function(std::function)> _f) : f(_f) {} + B operator()(A x) const { + return f(*this)(x); + } +}; + +template +std::function Y (std::function(std::function)> f) { + return YFunctor(f); +} diff --git a/Task/Y-combinator/Elixir/y-combinator.elixir b/Task/Y-combinator/Elixir/y-combinator.elixir new file mode 100644 index 0000000000..df126988a3 --- /dev/null +++ b/Task/Y-combinator/Elixir/y-combinator.elixir @@ -0,0 +1,10 @@ +iex(1)> yc = fn f -> (fn x -> x.(x) end).(fn y -> f.(fn arg -> y.(y).(arg) end) end) end +#Function<6.90072148/1 in :erl_eval.expr/5> +iex(2)> fac = fn f -> fn n -> if n < 2 do 1 else n * f.(n-1) end end end +#Function<6.90072148/1 in :erl_eval.expr/5> +iex(3)> for i <- 0..9, do: yc.(fac).(i) +[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] +iex(4)> fib = fn f -> fn n -> if n == 0 do 0 else (if n == 1 do 1 else f.(n-1) + f.(n-2) end) end end end +#Function<6.90072148/1 in :erl_eval.expr/5> +iex(5)> for i <- 0..9, do: yc.(fib).(i) +[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Y-combinator/Java/y-combinator-3.java b/Task/Y-combinator/Java/y-combinator-3.java index 749a9a24b7..ce7ff2c042 100644 --- a/Task/Y-combinator/Java/y-combinator-3.java +++ b/Task/Y-combinator/Java/y-combinator-3.java @@ -1,53 +1,7 @@ -interface Function { - public B call(A x); -} - -public class YCombinator { - interface RecursiveFunc extends Function, F> { } - - public static Function fix(final Function, Function> f) { - RecursiveFunc> r = - new RecursiveFunc>() { - public Function call(final RecursiveFunc> w) { - return f.call(new Function() { - public B call(A x) { - return w.call(w).call(x); - } - }); - } - }; - return r.call(r); + public static Function Y(Function, Function> f) { + return new Function() { + public B apply(A x) { + return f.apply(this).apply(x); + } + }; } - - public static void main(String[] args) { - Function, Function> almost_fib = - new Function, Function>() { - public Function call(final Function f) { - return new Function() { - public Integer call(Integer n) { - if (n <= 2) return 1; - return f.call(n - 1) + f.call(n - 2); - } - }; - } - }; - - Function, Function> almost_fac = - new Function, Function>() { - public Function call(final Function f) { - return new Function() { - public Integer call(Integer n) { - if (n <= 1) return 1; - return n * f.call(n - 1); - } - }; - } - }; - - Function fib = fix(almost_fib); - Function fac = fix(almost_fac); - - System.out.println("fib(10) = " + fib.call(10)); - System.out.println("fac(10) = " + fac.call(10)); - } -} diff --git a/Task/Y-combinator/Java/y-combinator-4.java b/Task/Y-combinator/Java/y-combinator-4.java index 88c64c0356..749a9a24b7 100644 --- a/Task/Y-combinator/Java/y-combinator-4.java +++ b/Task/Y-combinator/Java/y-combinator-4.java @@ -1,8 +1,53 @@ -import java.util.function.Function; +interface Function { + public B call(A x); +} + +public class YCombinator { + interface RecursiveFunc extends Function, F> { } + + public static Function fix(final Function, Function> f) { + RecursiveFunc> r = + new RecursiveFunc>() { + public Function call(final RecursiveFunc> w) { + return f.call(new Function() { + public B call(A x) { + return w.call(w).call(x); + } + }); + } + }; + return r.call(r); + } + + public static void main(String[] args) { + Function, Function> almost_fib = + new Function, Function>() { + public Function call(final Function f) { + return new Function() { + public Integer call(Integer n) { + if (n <= 2) return 1; + return f.call(n - 1) + f.call(n - 2); + } + }; + } + }; + + Function, Function> almost_fac = + new Function, Function>() { + public Function call(final Function f) { + return new Function() { + public Integer call(Integer n) { + if (n <= 1) return 1; + return n * f.call(n - 1); + } + }; + } + }; + + Function fib = fix(almost_fib); + Function fac = fix(almost_fac); -@FunctionalInterface -public interface SelfApplicable extends Function, OUTPUT> { - public default OUTPUT selfApply() { - return apply(this); - } + System.out.println("fib(10) = " + fib.call(10)); + System.out.println("fac(10) = " + fac.call(10)); + } } diff --git a/Task/Y-combinator/Java/y-combinator-5.java b/Task/Y-combinator/Java/y-combinator-5.java index e8d7125f4b..88c64c0356 100644 --- a/Task/Y-combinator/Java/y-combinator-5.java +++ b/Task/Y-combinator/Java/y-combinator-5.java @@ -1,5 +1,8 @@ import java.util.function.Function; -import java.util.function.UnaryOperator; @FunctionalInterface -public interface FixedPoint extends Function, FUNCTION> {} +public interface SelfApplicable extends Function, OUTPUT> { + public default OUTPUT selfApply() { + return apply(this); + } +} diff --git a/Task/Y-combinator/Java/y-combinator-6.java b/Task/Y-combinator/Java/y-combinator-6.java index 08fdf7f640..e8d7125f4b 100644 --- a/Task/Y-combinator/Java/y-combinator-6.java +++ b/Task/Y-combinator/Java/y-combinator-6.java @@ -1,43 +1,5 @@ -import java.util.Arrays; -import java.util.Optional; import java.util.function.Function; -import java.util.function.BiFunction; +import java.util.function.UnaryOperator; @FunctionalInterface -public interface VarargsFunction extends Function { - @SuppressWarnings("unchecked") - public OUTPUT apply(INPUTS... inputs); - - public static VarargsFunction from(Function function) { - return function::apply; - } - - public static VarargsFunction upgrade(Function function) { - return inputs -> function.apply(inputs[0]); - } - - public static VarargsFunction upgrade(BiFunction function) { - return inputs -> function.apply(inputs[0], inputs[1]); - } - - @SuppressWarnings("unchecked") - public default VarargsFunction andThen( - VarargsFunction after) { - return inputs -> after.apply(apply(inputs)); - } - - @SuppressWarnings("unchecked") - public default Function toFunction() { - return input -> apply(input); - } - - @SuppressWarnings("unchecked") - public default BiFunction toBiFunction() { - return (input, input2) -> apply(input, input2); - } - - @SuppressWarnings("unchecked") - public default VarargsFunction transformArguments(Function transformer) { - return inputs -> apply((INPUTS[]) Arrays.stream(inputs).parallel().map(transformer).toArray()); - } -} +public interface FixedPoint extends Function, FUNCTION> {} diff --git a/Task/Y-combinator/Java/y-combinator-7.java b/Task/Y-combinator/Java/y-combinator-7.java index 8b7cb0ba0e..08fdf7f640 100644 --- a/Task/Y-combinator/Java/y-combinator-7.java +++ b/Task/Y-combinator/Java/y-combinator-7.java @@ -1,74 +1,43 @@ -import java.math.BigDecimal; -import java.math.BigInteger; import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; +import java.util.Optional; import java.util.function.Function; -import java.util.function.UnaryOperator; -import java.util.stream.Collectors; -import java.util.stream.LongStream; +import java.util.function.BiFunction; @FunctionalInterface -public interface Y extends SelfApplicable> { - public static void main(String... arguments) { - BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE); +public interface VarargsFunction extends Function { + @SuppressWarnings("unchecked") + public OUTPUT apply(INPUTS... inputs); - Function toLong = Number::longValue; - Function toBigInteger = toLong.andThen(BigInteger::valueOf); - - /* Based on https://gist.github.com/aruld/3965968/#comment-604392 */ - Y> combinator = y -> f -> x -> f.apply(y.selfApply().apply(f)).apply(x); - FixedPoint> fixedPoint = combinator.selfApply(); + public static VarargsFunction from(Function function) { + return function::apply; + } - VarargsFunction fibonacci = fixedPoint.apply( - f -> VarargsFunction.upgrade( - toBigInteger.andThen( - n -> (n.compareTo(TWO) <= 0) - ? 1 - : new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString()) - .add(new BigInteger(f.apply(n.subtract(TWO)).toString())) - ) - ) - ); + public static VarargsFunction upgrade(Function function) { + return inputs -> function.apply(inputs[0]); + } - VarargsFunction factorial = fixedPoint.apply( - f -> VarargsFunction.upgrade( - toBigInteger.andThen( - n -> (n.compareTo(BigInteger.ONE) <= 0) - ? 1 - : n.multiply(new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString())) - ) - ) - ); + public static VarargsFunction upgrade(BiFunction function) { + return inputs -> function.apply(inputs[0], inputs[1]); + } - VarargsFunction ackermann = fixedPoint.apply( - f -> VarargsFunction.upgrade( - (BigInteger m, BigInteger n) -> m.equals(BigInteger.ZERO) - ? n.add(BigInteger.ONE) - : f.apply( - m.subtract(BigInteger.ONE), - n.equals(BigInteger.ZERO) - ? BigInteger.ONE - : f.apply(m, n.subtract(BigInteger.ONE)) - ) - ).transformArguments(toBigInteger) - ); + @SuppressWarnings("unchecked") + public default VarargsFunction andThen( + VarargsFunction after) { + return inputs -> after.apply(apply(inputs)); + } - Map> functions = new HashMap<>(); - functions.put("fibonacci", fibonacci); - functions.put("factorial", factorial); - functions.put("ackermann", ackermann); + @SuppressWarnings("unchecked") + public default Function toFunction() { + return input -> apply(input); + } - Map, Number[]> parameters = new HashMap<>(); - parameters.put(functions.get("fibonacci"), new Number[]{20}); - parameters.put(functions.get("factorial"), new Number[]{10}); - parameters.put(functions.get("ackermann"), new Number[]{3, 2}); + @SuppressWarnings("unchecked") + public default BiFunction toBiFunction() { + return (input, input2) -> apply(input, input2); + } - functions.entrySet().stream().parallel().map( - entry -> entry.getKey() - + Arrays.toString(parameters.get(entry.getValue())) - + " = " - + entry.getValue().apply(parameters.get(entry.getValue())) - ).forEach(System.out::println); + @SuppressWarnings("unchecked") + public default VarargsFunction transformArguments(Function transformer) { + return inputs -> apply((INPUTS[]) Arrays.stream(inputs).parallel().map(transformer).toArray()); } } diff --git a/Task/Y-combinator/Java/y-combinator-8.java b/Task/Y-combinator/Java/y-combinator-8.java index 59f6175dd8..8b7cb0ba0e 100644 --- a/Task/Y-combinator/Java/y-combinator-8.java +++ b/Task/Y-combinator/Java/y-combinator-8.java @@ -1,3 +1,74 @@ -factorial[10] = 3628800 -ackermann[3, 2] = 29 -fibonacci[20] = 6765 +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + +@FunctionalInterface +public interface Y extends SelfApplicable> { + public static void main(String... arguments) { + BigInteger TWO = BigInteger.ONE.add(BigInteger.ONE); + + Function toLong = Number::longValue; + Function toBigInteger = toLong.andThen(BigInteger::valueOf); + + /* Based on https://gist.github.com/aruld/3965968/#comment-604392 */ + Y> combinator = y -> f -> x -> f.apply(y.selfApply().apply(f)).apply(x); + FixedPoint> fixedPoint = combinator.selfApply(); + + VarargsFunction fibonacci = fixedPoint.apply( + f -> VarargsFunction.upgrade( + toBigInteger.andThen( + n -> (n.compareTo(TWO) <= 0) + ? 1 + : new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString()) + .add(new BigInteger(f.apply(n.subtract(TWO)).toString())) + ) + ) + ); + + VarargsFunction factorial = fixedPoint.apply( + f -> VarargsFunction.upgrade( + toBigInteger.andThen( + n -> (n.compareTo(BigInteger.ONE) <= 0) + ? 1 + : n.multiply(new BigInteger(f.apply(n.subtract(BigInteger.ONE)).toString())) + ) + ) + ); + + VarargsFunction ackermann = fixedPoint.apply( + f -> VarargsFunction.upgrade( + (BigInteger m, BigInteger n) -> m.equals(BigInteger.ZERO) + ? n.add(BigInteger.ONE) + : f.apply( + m.subtract(BigInteger.ONE), + n.equals(BigInteger.ZERO) + ? BigInteger.ONE + : f.apply(m, n.subtract(BigInteger.ONE)) + ) + ).transformArguments(toBigInteger) + ); + + Map> functions = new HashMap<>(); + functions.put("fibonacci", fibonacci); + functions.put("factorial", factorial); + functions.put("ackermann", ackermann); + + Map, Number[]> parameters = new HashMap<>(); + parameters.put(functions.get("fibonacci"), new Number[]{20}); + parameters.put(functions.get("factorial"), new Number[]{10}); + parameters.put(functions.get("ackermann"), new Number[]{3, 2}); + + functions.entrySet().stream().parallel().map( + entry -> entry.getKey() + + Arrays.toString(parameters.get(entry.getValue())) + + " = " + + entry.getValue().apply(parameters.get(entry.getValue())) + ).forEach(System.out::println); + } +} diff --git a/Task/Y-combinator/Java/y-combinator-9.java b/Task/Y-combinator/Java/y-combinator-9.java new file mode 100644 index 0000000000..59f6175dd8 --- /dev/null +++ b/Task/Y-combinator/Java/y-combinator-9.java @@ -0,0 +1,3 @@ +factorial[10] = 3628800 +ackermann[3, 2] = 29 +fibonacci[20] = 6765 diff --git a/Task/Y-combinator/JavaScript/y-combinator-1.js b/Task/Y-combinator/JavaScript/y-combinator-1.js index 0341545078..a3e79094dc 100644 --- a/Task/Y-combinator/JavaScript/y-combinator-1.js +++ b/Task/Y-combinator/JavaScript/y-combinator-1.js @@ -12,3 +12,15 @@ function Y(f) { })); return g; } + +var fac = Y(function(f) { + return function (n) { + return n > 1 ? n * f(n - 1) : 1; + }; +}); + +var fib = Y(function(f) { + return function(n) { + return n > 1 ? f(n - 1) + f(n - 2) : n; + }; +}); diff --git a/Task/Y-combinator/JavaScript/y-combinator-5.js b/Task/Y-combinator/JavaScript/y-combinator-5.js new file mode 100644 index 0000000000..558d9ff2e7 --- /dev/null +++ b/Task/Y-combinator/JavaScript/y-combinator-5.js @@ -0,0 +1,5 @@ +function Y(f) { + return function() { + return f(arguments.callee).apply(this, arguments); + }; +} diff --git a/Task/Y-combinator/JavaScript/y-combinator-6.js b/Task/Y-combinator/JavaScript/y-combinator-6.js new file mode 100644 index 0000000000..116da5816a --- /dev/null +++ b/Task/Y-combinator/JavaScript/y-combinator-6.js @@ -0,0 +1,20 @@ +let + Y= // Except for the η-abstraction necessary for applicative order languages, this is the formal Y combinator. + f=>((g=>(f((...x)=>g(g)(...x)))) + (g=>(f((...x)=>g(g)(...x))))), + Y2= // Using β-abstraction to eliminate code repetition. + f=>((f=>f(f)) + (g=>(f((...x)=>g(g)(...x))))), + Y3= // Using β-abstraction to separate out the self application combinator δ. + ((δ=>f=>δ(g=>(f((...x)=>g(g)(...x))))) + ((f=>f(f)))), + fix= // β/η-equivalent fix point combinator. Easier to convert to memoise than the Y combinator. + (((f)=>(g)=>(h)=>(f(h)(g(h)))) // The Substitute combinator out of SKI calculus + ((f)=>(g)=>(...x)=>(f(g(g)))(...x)) // S((S(KS)K)S(S(KS)K))(KI) + ((f)=>(g)=>(...x)=>(f(g(g)))(...x))), + fix2= // β/η-converted form of fix above into a more compact form + f=>(f=>f(f))(g=>(...x)=>f(g(g))(...x)), + opentailfact= // Open version of the tail call variant of the factorial function + fact=>(n,m=1)=>n<2?m:fact(n-1,n*m); + tailfact= // Tail call version of factorial function + Y(parttailfact); diff --git a/Task/Y-combinator/JavaScript/y-combinator-7.js b/Task/Y-combinator/JavaScript/y-combinator-7.js new file mode 100644 index 0000000000..08780486a4 --- /dev/null +++ b/Task/Y-combinator/JavaScript/y-combinator-7.js @@ -0,0 +1,9 @@ +let + polyfix= // A version that takes an array instead of multiple arguments would simply use l instead of (...l) for parameter + (...l)=>( + (f=>f(f)) + (g=>l.map(f=>(...x)=>f(...g(g))(...x)))), + [even,odd]= // The new destructive assignment syntax for arrays + polyfix( + (even,odd)=>n=>(n===0)||odd(n-1), + (even,odd)=>n=>(n!==0)&&even(n-1)); diff --git a/Task/Y-combinator/Julia/y-combinator-1.julia b/Task/Y-combinator/Julia/y-combinator-1.julia index 2aa236a889..b359d6d8e0 100644 --- a/Task/Y-combinator/Julia/y-combinator-1.julia +++ b/Task/Y-combinator/Julia/y-combinator-1.julia @@ -1 +1,6 @@ -Y = f -> (x -> x(x))(y -> f((args...) -> y(y)(args...))) +julia> """ + # Y combinator + + * `λf. (λx. f (x x)) (λx. f (x x))` + """ + Y = f -> (x -> x(x))(y -> f((t...) -> y(y)(t...))) diff --git a/Task/Y-combinator/Julia/y-combinator-2.julia b/Task/Y-combinator/Julia/y-combinator-2.julia index 36caf3a7a7..51368f0d59 100644 --- a/Task/Y-combinator/Julia/y-combinator-2.julia +++ b/Task/Y-combinator/Julia/y-combinator-2.julia @@ -1,2 +1,31 @@ -fac = f -> (n -> if n<2 1 else n*f(n-1) end) -Y(fac)(3) +julia> "# Factorial" + fac = f -> (n -> n < 2 ? 1 : n * f(n - 1)) + +julia> "# Fibonacci" + fib = f -> (n -> n == 0 ? 0 : (n == 1 ? 1 : f(n - 1) + f(n - 2))) + +julia> [Y(fac)(i) for i = 1:10] +10-element Array{Any,1}: + 1 + 2 + 6 + 24 + 120 + 720 + 5040 + 40320 + 362880 + 3628800 + +julia> [Y(fib)(i) for i = 1:10] +10-element Array{Any,1}: + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 diff --git a/Task/Y-combinator/Mathematica/y-combinator.math b/Task/Y-combinator/Mathematica/y-combinator.math index 48011ecca0..4f5229d641 100644 --- a/Task/Y-combinator/Mathematica/y-combinator.math +++ b/Task/Y-combinator/Mathematica/y-combinator.math @@ -1,3 +1,3 @@ -Y = Function[f, #@# &@Function[x, f[x[x]@# &]]]; -factorial = Y@Function[f, If[# < 1, 1, # f[# - 1]] &]; -fibonacci = Y@Function[f, If[# < 2, #, f[# - 1] + f[# - 2]] &]; +Y = Function[f, #[#] &[Function[g, f[g[g][##] &]]]]; +factorial = Y[Function[f, If[# < 1, 1, # f[# - 1]] &]]; +fibonacci = Y[Function[f, If[# < 2, #, f[# - 1] + f[# - 2]] &]; diff --git a/Task/Y-combinator/Moonscript/y-combinator.moon b/Task/Y-combinator/Moonscript/y-combinator.moon new file mode 100644 index 0000000000..c7b7a7d9b2 --- /dev/null +++ b/Task/Y-combinator/Moonscript/y-combinator.moon @@ -0,0 +1,2 @@ +Z = (f using nil) -> ((x) -> x x) (x) -> f (...) -> (x x) ... +factorial = Z (f using nil) -> (n) -> if n == 0 then 1 else n * f n - 1 diff --git a/Task/Y-combinator/Perl-6/y-combinator-1.pl6 b/Task/Y-combinator/Perl-6/y-combinator-1.pl6 index 0852fef841..2cbf8180f8 100644 --- a/Task/Y-combinator/Perl-6/y-combinator-1.pl6 +++ b/Task/Y-combinator/Perl-6/y-combinator-1.pl6 @@ -1,4 +1,4 @@ -sub Y (&f) { { .($_) }( -> &y { f({ y(&y)(&^arg) }) } ) } +sub Y (&f) { { .($_) }( -> &y { f({ y(&y)($^arg) }) } ) } sub fac (&f) { sub ($n) { $n < 2 ?? 1 !! $n * f($n - 1) } } sub fib (&f) { sub ($n) { $n < 2 ?? $n !! f($n - 1) + f($n - 2) } } say map Y($_), ^10 for &fac, &fib; diff --git a/Task/Y-combinator/REXX/y-combinator.rexx b/Task/Y-combinator/REXX/y-combinator.rexx index 5e68608882..96e939bf33 100644 --- a/Task/Y-combinator/REXX/y-combinator.rexx +++ b/Task/Y-combinator/REXX/y-combinator.rexx @@ -1,24 +1,22 @@ -/*REXX program to implement a stateless Y combinator. */ -numeric digits 1000 /*allow big 'uns. */ - -say ' fib' Y(fib (50)) /*Fibonacci series*/ -say ' fib' Y(fib (12 11 10 9 8 7 6 5 4 3 2 1 0)) /*Fibonacci series*/ -say ' fact' Y(fact (60)) /*single fact. */ -say ' fact' Y(fact (0 1 2 3 4 5 6 7 8 9 10 11)) /*single fact. */ -say ' Dfact' Y(dfact (4 5 6 7 8 9 10 11 12 13)) /*double fact. */ -say ' Tfact' Y(tfact (4 5 6 7 8 9 10 11 12 13)) /*triple fact. */ -say ' Qfact' Y(qfact (4 5 6 7 8 40)) /*quadruple fact. */ -say ' length' Y(length (when for to where whenceforth)) /*lengths of words*/ -say 'reverse' Y(reverse (23 678 1007 45 MAS I MA)) /*reverses strings*/ -say ' trunc' Y(trunc (-7.0005 12 3.14159 6.4 78.999)) /*truncates numbs.*/ -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────subroutines─────────────────────────*/ - Y: lambda=; parse arg Y _; do j=1 for words(_); interpret , - 'lambda=lambda' Y'('word(_,j)')'; end; return lambda - fib: procedure; parse arg x; if x<2 then return x; s=0; a=0; b=1 - do j=2 to x; s=a+b; a=b; b=s; end; return s - dfact: procedure; arg x; !=1; do j=x to 2 by -2;!=!*j; end; return ! - tfact: procedure; arg x; !=1; do j=x to 2 by -3;!=!*j; end; return ! - qfact: procedure; arg x; !=1; do j=x to 2 by -4;!=!*j; end; return ! - fact: procedure; arg x; !=1; do j=2 to x ;!=!*j; end; return ! +/*REXX program implements and displays a stateless Y combinator. */ +numeric digits 1000 /*allow big numbers. */ +say ' fib' Y(fib (50)) /*Fibonacci series. */ +say ' fib' Y(fib (12 11 10 9 8 7 6 5 4 3 2 1 0)) /*Fibonacci series. */ +say ' fact' Y(fact (60)) /*single factorial*/ +say ' fact' Y(fact (0 1 2 3 4 5 6 7 8 9 10 11)) /*single factorial*/ +say ' Dfact' Y(dfact (4 5 6 7 8 9 10 11 12 13)) /*double factorial*/ +say ' Tfact' Y(tfact (4 5 6 7 8 9 10 11 12 13)) /*triple factorial*/ +say ' Qfact' Y(qfact (4 5 6 7 8 40)) /*quadruple factorial*/ +say ' length' Y(length (when for to where whenceforth)) /*lengths of words.*/ +say 'reverse' Y(reverse (23 678 1007 45 MAS I MA)) /*reverses strings. */ +say ' trunc' Y(trunc (-7.0005 12 3.14159 6.4 78.999)) /*truncates numbers. */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ + Y: parse arg Y _; $= /*the Y combinator.*/ + do j=1 for words(_); interpret '$=$' Y"("word(_,j)')'; end; return $ + fib: procedure; parse arg x; if x<2 then return x; s=0; a=0; b=1 + s=0; a=0; b=1; do j=2 to x; s=a+b; a=b; b=s; end; return s +dfact: procedure; parse arg x; !=1; do j=x to 2 by -2; !=!*j; end; return ! +tfact: procedure; parse arg x; !=1; do j=x to 2 by -3; !=!*j; end; return ! +qfact: procedure; parse arg x; !=1; do j=x to 2 by -4; !=!*j; end; return ! + fact: procedure; parse arg x; !=1; do j=2 to x ; !=!*j; end; return ! diff --git a/Task/Y-combinator/Rust/y-combinator.rust b/Task/Y-combinator/Rust/y-combinator.rust index 6bd3a3c529..c5f3fac444 100644 --- a/Task/Y-combinator/Rust/y-combinator.rust +++ b/Task/Y-combinator/Rust/y-combinator.rust @@ -1,21 +1,44 @@ -enum Mu { Roll(@fn(Mu) -> T) } -fn unroll(Roll(f): Mu) -> @fn(Mu) -> T { f } +use std::sync::Arc; +use std::boxed::Box; +use std::clone::Clone; -type RecFunc = @fn(@fn(A) -> B) -> @fn(A) -> B; +//Arc> +#[macro_export] +macro_rules! abc { + ($x:expr) => (Arc::new(Box::new($x))); +} + +#[derive(Clone)] +pub enum Mu { + Roll(Arc)->T>>), +} -fn fix(f: RecFunc) -> @fn(A) -> B { - let g: @fn(Mu<@fn(A) -> B>) -> @fn(A) -> B = - |x| |a| f(unroll(x)(x))(a); - g(Roll(g)) +pub fn unroll(Mu::Roll(f): Mu) -> Arc)->T>> {f.clone()} + +pub type Func = ArcB>>; +pub type RecFunc = Arc) -> Func>>; + +pub fn y(f: RecFunc) -> Func { + let g:Arc>)->Func>> = abc!(move |x : Mu>| -> Func { + let f = f.clone(); + abc!(move |a:A| -> B { + let f = f.clone(); + f(unroll(x.clone())(x.clone()))(a) + }) + }); + g(Mu::Roll(g.clone())) } -fn main() { - let fac: RecFunc = - |f| |x| if (x==0) { 1 } else { f(x-1) * x }; - let fib : RecFunc = - |f| |x| if (x<2) { 1 } else { f(x-1) + f(x-2) }; +#[test] +fn fib_test() { + let fib : RecFunc = abc!(|f| abc!(move |x| if (x<2) { 1 } else { f(x-1) + f(x-2)})); + let b = y(fib)(10); + assert_eq!(b, 89); +} - let ns = std::vec::from_fn(20, |i| i); - println(fmt!("%?", ns.map(|&n| fix(fac)(n)))); - println(fmt!("%?", ns.map(|&n| fix(fib)(n)))); +#[test] +fn fac_test() { + let fac : RecFunc = abc!(|f| abc!(move |x| if (x==0) { 1 } else { f(x-1) * x })); + let c = y(fac)(10); + assert_eq!(c, 3628800); } diff --git a/Task/Y-combinator/Vim-Script/y-combinator.vim b/Task/Y-combinator/Vim-Script/y-combinator.vim new file mode 100644 index 0000000000..6712bcefda --- /dev/null +++ b/Task/Y-combinator/Vim-Script/y-combinator.vim @@ -0,0 +1,22 @@ +" Translated from Python. Works with: Vim 7.0 + +func! Lambx(sig, expr, dict) + let fanon = {'d': a:dict} + exec printf(" + \func fanon.f(%s) dict\n + \ return %s\n + \endfunc", + \ a:sig, a:expr) + return fanon +endfunc + +func! Callx(fanon, arglist) + return call(a:fanon.f, a:arglist, a:fanon.d) +endfunc + +let g:Y = Lambx('f', 'Callx(Lambx("x", "Callx(a:x, [a:x])", {}), [Lambx("y", ''Callx(self.f, [Lambx("...", "Callx(Callx(self.y, [self.y]), a:000)", {"y": a:y})])'', {"f": a:f})])', {}) + +let g:fac = Lambx('f', 'Lambx("n", "a:n<2 ? 1 : a:n * Callx(self.f, [a:n-1])", {"f": a:f})', {}) + +echo Callx(Callx(g:Y, [g:fac]), [5]) +echo map(range(10), 'Callx(Callx(Y, [fac]), [v:val])') diff --git a/Task/Yin-and-yang/Batch-File/yin-and-yang.bat b/Task/Yin-and-yang/Batch-File/yin-and-yang.bat new file mode 100644 index 0000000000..e20bb36b07 --- /dev/null +++ b/Task/Yin-and-yang/Batch-File/yin-and-yang.bat @@ -0,0 +1,34 @@ +@echo off + + %== Set the dimension of the SVG 'image' that will be created ==% +set pic_width=30 +set pic_height=30 + + %== Redirect the SVG stdout to 'YINYANG.SVG' in the same directory ==% + +echo.^>YINYANG.SVG +echo.^>YINYANG.SVG +echo. 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'^>>>YINYANG.SVG +echo.^>YINYANG.SVG +echo. xmlns:xlink='http://www.w3.org/1999/xlink'>>YINYANG.SVG +echo. width='%pic_width%' height='%pic_height%'^>>>YINYANG.SVG +echo. ^^>>YINYANG.SVG +echo. ^>YINYANG.SVG +echo. fill='white' stroke-width='1'/^>>>YINYANG.SVG +echo. ^>>YINYANG.SVG +echo. ^>>YINYANG.SVG +echo. ^>>YINYANG.SVG +echo. ^^>>YINYANG.SVG + + %== Create the yin-yang symbol ==% +call :draw_yinyang 20 0.05 +call :draw_yinyang 8 0.02 + +echo.^>>YINYANG.SVG +exit /b 0 + +:draw_yinyang +echo.^>>YINYANG.SVG +goto :EOF diff --git a/Task/Yin-and-yang/Befunge/yin-and-yang.bf b/Task/Yin-and-yang/Befunge/yin-and-yang.bf new file mode 100644 index 0000000000..3b6c0ff7ba --- /dev/null +++ b/Task/Yin-and-yang/Befunge/yin-and-yang.bf @@ -0,0 +1,8 @@ +55+:#. 00p:2*10p:2/20p6/30p01v +@#!`g01:+1g07,+55$v> ^ v1_:70g00 +2+*:-g02-g00g07:_ 1v v!`*:g0 +g-:*+00g:*`#v_$:0`!0\v0_:70g00 +0#+g#1,#$< > 2 #^>#g>#04#1+#: diff --git a/Task/Yin-and-yang/REXX/yin-and-yang.rexx b/Task/Yin-and-yang/REXX/yin-and-yang.rexx new file mode 100644 index 0000000000..ec00b54e7e --- /dev/null +++ b/Task/Yin-and-yang/REXX/yin-and-yang.rexx @@ -0,0 +1,31 @@ +/*REXX program creates/displays an ASCII art version of the Yin-Yang symbol.*/ +parse arg s1 s2 . /*obtain optional arguments from the CL*/ +if s1=='' | s1==',' then s1=17 /*Not defined? Then use the default. */ +if s2=='' | s2==',' then s2= 8 /* " " " " " " */ +if s1>0 then call yin_yang s1 /*create and display the 1st Yin-Yang. */ +if s2>0 then call yin_yang s2 /* " " " " 2nd " */ +exit /*stick a fork in it, we're all done. */ +/*────────────────────────────────────────────────────────────────────────────*/ +in@: procedure; parse arg cy,r,x,y; return x**2 + (y-cy)**2 <= r**2 +big@: /*in big circle.*/ return in@( 0, r, x, y ) +semi@: /*in semi circle.*/ return in@( r/2, r/2, x, y ) +sBK@: /*in small black circle.*/ return in@( r/2, r/6, x, y ) +sWH@: /*in small white circle.*/ return in@( 0-r/2, r/6, x, y ) +BK_semi@: /*in black semi circle.*/ return in@( 0-r/2, r/2, x, y ) +/*────────────────────────────────────────────────────────────────────────────*/ +yin_yang: procedure; parse arg r; mY=1; mX=2 /*scale multiplier for X,Y axis.*/ +WH='·'; BL='@'; zz=' ' /*define some symbol shading (glyphs). */ + + do sy=+r*mY by -1 while sy >= -r*mY; $= /*$: is the output line.*/ + do sx=-r*mX by +1 while sx <= +r*mX; x=sx/mX; y=sy/mY + if big@() then if semi@() then if sBK@() then $=$||BL + else $=$||WH + else if BK_semi@() then if sWH@() then $=$||WH + else $=$||BL + else if x<0 then $=$||WH + else $=$||BL + else $=$ || zz + end /*sy*/ + say $ /*display a single line of the symbol. */ + end /*sx*/ +return diff --git a/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 b/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 index d1d4e839c6..9f08ce8814 100644 --- a/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 +++ b/Task/Zeckendorf-arithmetic/Perl-6/zeckendorf-arithmetic.pl6 @@ -22,14 +22,16 @@ sub infix:($a, $b) { $a ne $b }; # post increment sub postfix:<++z>($a is rw) { - $a = ("$z0$z0"~$a).subst(/("$z0$z0")($z1+ %% $z0)?$/, -> $/ { "$z0$z1" ~ $z0 x $1.chars }); + $a = ("$z0$z0"~$a).subst(/("$z0$z0")($z1+ %% $z0)?$/, + -> $/ { "$z0$z1" ~ ($1 ?? $z0 x $1.chars !! '') }); $a ~~ s/^$z0+//; $a } # post decrement sub postfix:<--z>($a is rw) { - $a.=subst(/$z1($z0*)$/, -> $/ {$z0 ~ "$z1$z0" x $0.chars div 2 ~ $z1 x $0.chars mod 2}); + $a.=subst(/$z1($z0*)$/, + -> $/ {$z0 ~ "$z1$z0" x $0.chars div 2 ~ $z1 x $0.chars mod 2}); $a ~~ s/^$z0+(.+)$/$0/; $a } diff --git a/Task/Zeckendorf-number-representation/J/zeckendorf-number-representation.j b/Task/Zeckendorf-number-representation/J/zeckendorf-number-representation.j index f7b7e68d1b..f3e3eae44e 100644 --- a/Task/Zeckendorf-number-representation/J/zeckendorf-number-representation.j +++ b/Task/Zeckendorf-number-representation/J/zeckendorf-number-representation.j @@ -4,7 +4,9 @@ fib=: 3 : 0 " 0 ) phi=: -:1+%:5 + fi =: 3 : 'n - y.(1=y)-~>.(phi^.%:5)+phi^.y' + fsum=: 3 : 0 z=. 0$r=. y while. 3N /*build a list of Fib numbers. */ - w=words(#) /*number of words in list of Fib#*/ - #=# (word(#,w-1) +word(#,w)) /*add the last two Fib numbers. */ - end /*until*/ /* [↑] #: contains a Fib list.*/ +/*REXX program calculates and displays the first N Zeckendorf numbers. */ +numeric digits 100000 /*just in case user gets real ka─razy. */ +parse arg N .; if N=='' then n=20 /*let user specify the upper limit. */ +#=1 2; do until w>N /*build a list of Fibonacci numbers. */ + w=words(#) /*number of words in list of Fibonacci#*/ + #=# (word(#,w-1) +word(#,w)) /*add the last two Fibonacci numbers. */ + end /*until*/ /* [↑] #: contains a Fibonacci list.*/ - do j=0 to N; parse var j x z /*task: process zero ──► N */ - do k=w by -1 for w; _=word(#,k) /*process all the Fibonacci nums.*/ - if x>=_ then do /*is X > the next Fib number? */ - z=z'1' /* ··· then append unity (1). */ - x=x-_ /*subtract this fib# from index. */ + do j=0 to N; parse var j x z /*task: process zero ──► N numbers.*/ + do k=w by -1 for w; _=word(#,k) /*process all the Fibonacci numbers. */ + if x>=_ then do; z=z'1' /*is X>the next Fibonacci #? Append 1.*/ + x=x-_ /*subtract this Fibonacci # from index.*/ end - else z=z'0' /* append zero (0) to the number.*/ + else z=z'0' /* append zero (0) to the Fibonacci #.*/ end /*k*/ - say ' Zeckendorf' right(j,length(N)) '= ' right(z+0,30) /*show #.*/ + say ' Zeckendorf' right(j,length(N)) '= ' right(z+0,30) /*show #.*/ end /*j*/ - /*stick a fork in it, we're done.*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-3.rexx b/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-3.rexx index 1092e681ba..2b5b7e2aa6 100644 --- a/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-3.rexx +++ b/Task/Zeckendorf-number-representation/REXX/zeckendorf-number-representation-3.rexx @@ -1,10 +1,10 @@ -/*REXX pgm calculates and displays the first N Zeckendorf numbers. */ -numeric digits 1000 /*just in case user gets ka─razy.*/ -parse arg n .; if n=='' then n=20 /*let user specify upper limit. */ -z=0 /*index of a Zeckendorf number. */ - do j=0 until z>n; _=x2b(d2x(j)) /*task: process zero ──► N. */ - if pos(11,_)\==0 then iterate /*two consecutive ones (1s) ? */ - say ' Zeckendorf' right(z,length(n)) '= ' right(_+0,30) /*show #.*/ - z=z+1 /*bump the Zeckendorf # counter.*/ - end /*j*/ /* [↑] compute/show Zeckendorf #s*/ - /*stick a fork in it, we're done.*/ +/*REXX program calculates and displays the first N Zeckendorf numbers. */ +numeric digits 100000 /*just in case user gets real ka─razy. */ +parse arg N .; if N=='' then n=20 /*let user specify the upper limit. */ +z=0 /*the index of a Zeckendorf number. */ + do j=0 until z>N; _=x2b(d2x(j)) /*task: process zero ──► N. */ + if pos(11,_)\==0 then iterate /*are there two consecutive ones (1s) ?*/ + say ' Zeckendorf' right(z,length(N)) '= ' right(_+0,30) /*show #*/ + z=z+1 /*bump the Zeckendorf number counter.*/ + end /*j*/ /* [↑] compute/display Zeckendorf #s. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/Zeckendorf-number-representation/VBScript/zeckendorf-number-representation.vb b/Task/Zeckendorf-number-representation/VBScript/zeckendorf-number-representation.vb new file mode 100644 index 0000000000..f9166dafb9 --- /dev/null +++ b/Task/Zeckendorf-number-representation/VBScript/zeckendorf-number-representation.vb @@ -0,0 +1,25 @@ +Function Zeckendorf(n) + num = n + Set fibonacci = CreateObject("System.Collections.Arraylist") + fibonacci.Add 1 : fibonacci.Add 2 + i = 1 + Do While fibonacci(i) < num + fibonacci.Add fibonacci(i) + fibonacci(i-1) + i = i + 1 + Loop + tmp = "" + For j = fibonacci.Count-1 To 0 Step -1 + If fibonacci(j) <= num And (tmp = "" Or Left(tmp,1) <> "1") Then + tmp = tmp & "1" + num = num - fibonacci(j) + Else + tmp = tmp & "0" + End If + Next + Zeckendorf = CLng(tmp) +End Function + +'testing the function +For k = 0 To 20 + WScript.StdOut.WriteLine k & ": " & Zeckendorf(k) +Next diff --git a/Task/Zero-to-the-zero-power/BBC-BASIC/zero-to-the-zero-power.bbc b/Task/Zero-to-the-zero-power/BBC-BASIC/zero-to-the-zero-power.bbc new file mode 100644 index 0000000000..d872c44f80 --- /dev/null +++ b/Task/Zero-to-the-zero-power/BBC-BASIC/zero-to-the-zero-power.bbc @@ -0,0 +1 @@ + PRINT 0^0 diff --git a/Task/Zero-to-the-zero-power/Befunge/zero-to-the-zero-power.bf b/Task/Zero-to-the-zero-power/Befunge/zero-to-the-zero-power.bf new file mode 100644 index 0000000000..e644e9c387 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Befunge/zero-to-the-zero-power.bf @@ -0,0 +1 @@ +"PDPF"4#@(0F0FYP)@ diff --git a/Task/Zero-to-the-zero-power/Burlesque/zero-to-the-zero-power.blq b/Task/Zero-to-the-zero-power/Burlesque/zero-to-the-zero-power.blq new file mode 100644 index 0000000000..b043f50069 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Burlesque/zero-to-the-zero-power.blq @@ -0,0 +1,4 @@ +blsq ) 0.0 0.0?^ +1.0 +blsq ) 0 0?^ +1 diff --git a/Task/Zero-to-the-zero-power/Eiffel/zero-to-the-zero-power.e b/Task/Zero-to-the-zero-power/Eiffel/zero-to-the-zero-power.e new file mode 100644 index 0000000000..61845fb4a3 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Eiffel/zero-to-the-zero-power.e @@ -0,0 +1 @@ +print (0^0) diff --git a/Task/Zero-to-the-zero-power/Elixir/zero-to-the-zero-power.elixir b/Task/Zero-to-the-zero-power/Elixir/zero-to-the-zero-power.elixir new file mode 100644 index 0000000000..400d58aa68 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Elixir/zero-to-the-zero-power.elixir @@ -0,0 +1 @@ +:math.pow(0,0) diff --git a/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia b/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia new file mode 100644 index 0000000000..c11150d34d --- /dev/null +++ b/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia @@ -0,0 +1,9 @@ +zs = Any[zero(Complex), + zero(FloatingPoint), + zero(Rational), + zero(Integer), + zero(Bool)] + +for i in zs, j in zs + println(i, "^", j, " = ", i^j, " (", typeof(i^j), ")") +end diff --git a/Task/Zero-to-the-zero-power/MATLAB/zero-to-the-zero-power.m b/Task/Zero-to-the-zero-power/MATLAB/zero-to-the-zero-power.m new file mode 100644 index 0000000000..b906ee0d2d --- /dev/null +++ b/Task/Zero-to-the-zero-power/MATLAB/zero-to-the-zero-power.m @@ -0,0 +1 @@ +0^0 diff --git a/Task/Zero-to-the-zero-power/Mercury/zero-to-the-zero-power.mercury b/Task/Zero-to-the-zero-power/Mercury/zero-to-the-zero-power.mercury new file mode 100644 index 0000000000..913e3da1ff --- /dev/null +++ b/Task/Zero-to-the-zero-power/Mercury/zero-to-the-zero-power.mercury @@ -0,0 +1,18 @@ +:- module zero_to_the_zero_power. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module float, int, integer, list, string. + +main(!IO) :- + io.format(" int.pow(0, 0) = %d\n", [i(pow(0, 0))], !IO), + io.format("integer.pow(zero, zero) = %s\n", + [s(to_string(pow(zero, zero)))], !IO), + io.format(" float.pow(0.0, 0) = %.1f\n", [f(pow(0.0, 0))], !IO). + +:- end_module zero_to_the_zero_power. diff --git a/Task/Zero-to-the-zero-power/Pascal/zero-to-the-zero-power.pascal b/Task/Zero-to-the-zero-power/Pascal/zero-to-the-zero-power.pascal new file mode 100644 index 0000000000..6f8396762d --- /dev/null +++ b/Task/Zero-to-the-zero-power/Pascal/zero-to-the-zero-power.pascal @@ -0,0 +1,7 @@ +program ZToZ; +uses + math; +begin + write('0.0 ^ 0 :',IntPower(0.0,0):4:2); + writeln(' 0.0 ^ 0.0 :',Power(0.0,0.0):4:2); +end. diff --git a/Task/Zero-to-the-zero-power/PicoLisp/zero-to-the-zero-power.l b/Task/Zero-to-the-zero-power/PicoLisp/zero-to-the-zero-power.l new file mode 100644 index 0000000000..ce22c94f4c --- /dev/null +++ b/Task/Zero-to-the-zero-power/PicoLisp/zero-to-the-zero-power.l @@ -0,0 +1 @@ +(** 0 0) 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 index 5ef041ddef..bf2cb580f3 100644 --- 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 @@ -1,5 +1,3 @@ -use std::num::Int; - fn main() { - println!("{}", 0i.pow(0)); + println!("{}",0u32.pow(0)); } diff --git a/Task/Zero-to-the-zero-power/SQL/zero-to-the-zero-power.sql b/Task/Zero-to-the-zero-power/SQL/zero-to-the-zero-power.sql new file mode 100644 index 0000000000..558073dea4 --- /dev/null +++ b/Task/Zero-to-the-zero-power/SQL/zero-to-the-zero-power.sql @@ -0,0 +1 @@ +SQL> select power(0,0) from dual; diff --git a/Task/Zero-to-the-zero-power/VBScript/zero-to-the-zero-power.vb b/Task/Zero-to-the-zero-power/VBScript/zero-to-the-zero-power.vb new file mode 100644 index 0000000000..4c7fbbe6be --- /dev/null +++ b/Task/Zero-to-the-zero-power/VBScript/zero-to-the-zero-power.vb @@ -0,0 +1 @@ +WScript.Echo 0 ^ 0 diff --git a/Task/Zhang-Suen-thinning-algorithm/Lua/zhang-suen-thinning-algorithm.lua b/Task/Zhang-Suen-thinning-algorithm/Lua/zhang-suen-thinning-algorithm.lua new file mode 100644 index 0000000000..13a2893828 --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/Lua/zhang-suen-thinning-algorithm.lua @@ -0,0 +1,140 @@ +function zhangSuenThin(img) + local dirs={ + { 0,-1}, + { 1,-1}, + { 1, 0}, + { 1, 1}, + { 0, 1}, + {-1, 1}, + {-1, 0}, + {-1,-1}, + { 0,-1}, + } + + local black=1 + local white=0 + + function A(x, y) + local c=0 + local current=img[y+dirs[1][2]][x+dirs[1][1]] + for i=2,#dirs do + local to_compare=img[y+dirs[i][2]][x+dirs[i][1]] + if current==white and to_compare==black then + c=c+1 + end + current=to_compare + end + return c + end + + function B(x, y) + local c=0 + for i=2,#dirs do + local value=img[y+dirs[i][2]][x+dirs[i][1]] + if value==black then + c=c+1 + end + end + return c + end + + function common_step(x, y) + if img[y][x]~=black or x<=1 or x>=#img[y] or y<=1 or y>=#img then + return false + end + + local b_value=B(x, y) + if b_value<2 or b_value>6 then + return false + end + + local a_value=A(x, y) + if a_value~=1 then + return false + end + return true + end + + function step_one(x, y) + if not common_step(x, y) then + return false + end + local p2=img[y+dirs[1][2]][x+dirs[1][1]] + local p4=img[y+dirs[3][2]][x+dirs[3][1]] + local p6=img[y+dirs[5][2]][x+dirs[5][1]] + local p8=img[y+dirs[7][2]][x+dirs[7][1]] + + if p4==white or p6==white or p2==white and p8==white then + return true + end + return false + end + + function step_two(x, y) + if not common_step(x, y) then + return false + end + local p2=img[y+dirs[1][2]][x+dirs[1][1]] + local p4=img[y+dirs[3][2]][x+dirs[3][1]] + local p6=img[y+dirs[5][2]][x+dirs[5][1]] + local p8=img[y+dirs[7][2]][x+dirs[7][1]] + + if p2==white or p8==white or p4==white and p6==white then + return true + end + return false + end + + function convert(to_do) + for k,v in pairs(to_do) do + img[v[2]][v[1]]=white + end + end + + function do_step_on_all(step) + local to_convert={} + for y=1,#img do + for x=1,#img[y] do + if step(x, y) then + table.insert(to_convert, {x,y}) + end + end + end + convert(to_convert) + return #to_convert>0 + end + + local continue=true + while continue do + continue=false + if do_step_on_all(step_one) then + continue=true + end + + if do_step_on_all(step_two) then + continue=true + end + end + + for y=1,#img do + for x=1,#img[y] do + io.write(img[y][x]==black and '#' or ' ') + end + io.write('\n') + end +end + +local image = { + {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, + {0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0}, + {0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,1,0,0,1,1,1,1,0,0,0,0,0,0}, + {0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0}, + {0,1,1,1,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, + {0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0}, + {0,1,1,1,0,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,0,0,0}, + {0,1,1,1,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,0,1,1,1,0,0}, + {0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0}, + {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, +} + +zhangSuenThin(image) diff --git a/Task/Zig-zag-matrix/360-Assembly/zig-zag-matrix.360 b/Task/Zig-zag-matrix/360-Assembly/zig-zag-matrix.360 new file mode 100644 index 0000000000..e98badb551 --- /dev/null +++ b/Task/Zig-zag-matrix/360-Assembly/zig-zag-matrix.360 @@ -0,0 +1,81 @@ +* Zig-zag matrix 15/08/2015 +ZIGZAGMA CSECT + USING ZIGZAGMA,R12 set base register + LR R12,R15 establish addressability + LA R9,N n : matrix size + LA R6,1 i=1 + LA R7,1 j=1 + LR R11,R9 n + MR R10,R9 *n + BCTR R11,0 R11=n**2-1 + SR R8,R8 k=0 +LOOPK CR R8,R11 do k=0 to n**2-1 + BH ELOOPK k>limit + LR R1,R6 i + BCTR R1,0 -1 + MR R0,R9 *n + LR R2,R7 j + BCTR R2,0 -1 + AR R1,R2 (i-1)*n+(j-1) + SLA R1,1 index=((i-1)*n+j-1)*2 + STH R8,T(R1) t(i,j)=k + LR R2,R6 i + AR R2,R7 i+j + LA R1,2 2 + SRDA R2,32 shift right r1 to r2 + DR R2,R1 (i+j)/2 + LTR R2,R2 if mod(i+j,2)=0 + BNZ ELSEMOD + CR R7,R9 if j1 + BNH NOT1 + BCTR R6,0 i=i-1 +NOT1 B NOT2 +ELSEMOD CR R6,R9 if i1 + BNH NOT2 + BCTR R7,0 j=j-1 +NOT2 LA R8,1(R8) k=k+1 + B LOOPK +ELOOPK LA R6,1 end k; i=1 +LOOPI CR R6,R9 do i=1 to n + BH ELOOPI i>n + LA R10,0 ibuf=0 buffer index + MVC BUFFER,=CL80' ' + LA R7,1 j=1 +LOOPJ CR R7,R9 do j=1 to n + BH ELOOPJ j>n + LR R1,R6 i + BCTR R1,0 -1 + MR R0,R9 *n + LR R2,R7 j + BCTR R2,0 -1 + AR R1,R2 (i-1)*n+(j-1) + SLA R1,1 index=((i-1)*n+j-1)*2 + LH R2,T(R1) t(i,j) + LA R3,BUFFER + AR R3,R10 + XDECO R2,XDEC edit t(i,j) length=12 + MVC 0(4,R3),XDEC+8 move in buffer length=4 + LA R10,4(R10) ibuf=ibuf+1 + LA R7,1(R7) j=j+1 + B LOOPJ +ELOOPJ XPRNT BUFFER,80 end j + LA R6,1(R6) i=i+1 + B LOOPI +ELOOPI XR R15,R15 end i; return_code=0 + BR R14 return to caller +N EQU 5 matrix size +BUFFER DS CL80 +XDEC DS CL12 +T DS (N*N)H t(n,n) matrix + YREGS + END ZIGZAGMA diff --git a/Task/Zig-zag-matrix/Befunge/zig-zag-matrix.bf b/Task/Zig-zag-matrix/Befunge/zig-zag-matrix.bf new file mode 100644 index 0000000000..bf939c56ef --- /dev/null +++ b/Task/Zig-zag-matrix/Befunge/zig-zag-matrix.bf @@ -0,0 +1,3 @@ +>> 5 >>00p0010p:1:>20p030pv >0g-:0`*:*-:00g:*1-55+/>\55+/:v v:,*84< +v:++!\**2p01:+1g01:g02$$_>>#^4#00#+p#1:#+1#g0#0g#3<^/+ 55\_$:>55+/\| +>55+,20g!00g10g`>#^_$$$@^!`g03g00!g04++**2p03:+1g03!\*+1*2g01:g04.$< diff --git a/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp b/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp index 5db0a96be4..2cb3293bba 100644 --- a/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp +++ b/Task/Zig-zag-matrix/C++/zig-zag-matrix.cpp @@ -16,6 +16,7 @@ auto_ptr< IntTable > getZigZagArray( int dimension ) // fill along diagonal stripes (oriented as "/") int lastValue = dimension * dimension - 1; + int currNum = 0; int currDiag = 0; int loopFrom; int loopTo; diff --git a/Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir b/Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir new file mode 100644 index 0000000000..a574ce3985 --- /dev/null +++ b/Task/Zig-zag-matrix/Elixir/zig-zag-matrix.elixir @@ -0,0 +1,14 @@ +defmodule RC do + require Integer + def zigzag(n) do + indices = for x <- 1..n, y <- 1..n, do: {x,y} + sorted = Enum.sort_by(indices, fn{x,y}->{x+y, if(Integer.is_even(x+y), do: y, else: x)} end) + sorted2 = Enum.sort(Enum.with_index(sorted)) + Enum.each(sorted2, fn {{_x,y},i} -> + IO.write "#{i} " + if y==n, do: IO.puts "" + end) + end +end + +RC.zigzag(5) diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia new file mode 100644 index 0000000000..105985f121 --- /dev/null +++ b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-1.julia @@ -0,0 +1,59 @@ +immutable ZigZag + m::Int + n::Int + diag::Array{Int,1} + cmax::Int + numd::Int + lohi::(Int,Int) +end + +function zigzag(m::Int, n::Int) + 0 zz.cmax + +function Base.next(zz::ZigZag, zzs::ZZState) + s = sub2ind((zz.m, zz.n), zzs.cell[1], zzs.cell[2]) + if zzs.dcnt == zzs.dlen + if isodd(zzs.dnum) + if zzs.cell[2] < zz.n + zzs.cell[2] += 1 + else + zzs.cell[1] += 1 + end + else + if zzs.cell[1] < zz.m + zzs.cell[1] += 1 + else + zzs.cell[2] += 1 + end + end + zzs.dcnt = 1 + zzs.dnum += 1 + zzs.dir = -zzs.dir + if zzs.dnum <= zz.lohi[1] + zzs.dlen += 1 + elseif zz.lohi[2] < zzs.dnum + zzs.dlen -= 1 + end + else + zzs.cell += zzs.dir*zz.diag + zzs.dcnt += 1 + end + zzs.cnt += 1 + return (s, zzs) +end diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia new file mode 100644 index 0000000000..de8b6dbdab --- /dev/null +++ b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-2.julia @@ -0,0 +1,24 @@ +using Formatting + +function width{T<:Integer}(n::T) + w = ndigits(n) + n < 0 || return w + return w + 1 +end + +function pretty{T<:Integer}(a::Array{T,2}, indent::Int=4) + lo, hi = extrema(a) + w = max(width(lo), width(hi)) + id = " "^indent + fe = FormatExpr(@sprintf(" {:%dd}", w)) + s = id + nrow = size(a)[1] + for i in 1:nrow + for j in a[i,:] + s *= format(fe, j) + end + i != nrow || continue + s *= "\n"*id + end + return s +end diff --git a/Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.julia b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.julia new file mode 100644 index 0000000000..9acae7501c --- /dev/null +++ b/Task/Zig-zag-matrix/Julia/zig-zag-matrix-3.julia @@ -0,0 +1,26 @@ +n = 5 +println("The n = ", n, " zig-zag matrix:") +a = zeros(Int, (n, n)) +for (i, s) in enumerate(zigzag(n)) + a[s] = i-1 +end +println(pretty(a)) + +m = 3 +println() +println("Generalize to a non-square matrix (", m, "x", n, "):") +a = zeros(Int, (m, n)) +for (i, s) in enumerate(zigzag(m, n)) + a[s] = i-1 +end +println(pretty(a)) + +p = primes(10^3) +n = 7 +println() +println("An n = ", n, " prime spiral matrix:") +a = zeros(Int, (n, n)) +for (i, s) in enumerate(zigzag(n)) + a[s] = p[i] +end +println(pretty(a)) diff --git a/Task/Zig-zag-matrix/Perl/zig-zag-matrix-1.pl b/Task/Zig-zag-matrix/Perl/zig-zag-matrix-1.pl new file mode 100644 index 0000000000..d8fe79fe46 --- /dev/null +++ b/Task/Zig-zag-matrix/Perl/zig-zag-matrix-1.pl @@ -0,0 +1,24 @@ +use 5.010; + +sub zig_zag { + my $n = shift; + my $max_number = $n**2; + my @matrix; + my $number = 0; + for my $j ( 0 .. --$n ) { + for my $i ( + $j % 2 + ? 0 .. $j + : reverse 0 .. $j + ) + { + $matrix[$i][ $j - $i ] = $number++; + #next if $j == $n; + $matrix[ $n - $i ][ $n - ( $j - $i ) ] = $max_number - $number; + } + } + return @matrix; +} + +my @zig_zag_matrix = zig_zag(5); +say join "\t", @{$_} foreach @zig_zag_matrix; diff --git a/Task/Zig-zag-matrix/Perl/zig-zag-matrix.pl b/Task/Zig-zag-matrix/Perl/zig-zag-matrix-2.pl similarity index 100% rename from Task/Zig-zag-matrix/Perl/zig-zag-matrix.pl rename to Task/Zig-zag-matrix/Perl/zig-zag-matrix-2.pl diff --git a/Task/Zig-zag-matrix/REXX/zig-zag-matrix.rexx b/Task/Zig-zag-matrix/REXX/zig-zag-matrix.rexx index f2accafc92..9045e2edae 100644 --- a/Task/Zig-zag-matrix/REXX/zig-zag-matrix.rexx +++ b/Task/Zig-zag-matrix/REXX/zig-zag-matrix.rexx @@ -1,28 +1,26 @@ -/*REXX program to produce a zig-zag matrix (array) and display it. */ +/*REXX program produces and displays a zig─zag matrix (a square array). */ +parse arg n start inc . /*obtain optional arguments from the CL*/ +if n=='' then n=5 /*Not specified? Then use the default.*/ +if start=='' then start=0 /* " " " " " " */ +if inc=='' then inc=1 /* " " " " " " */ +row=1; col=1 /*start with the 1st row, 1st column.*/ +size=n**2 /*size of array.*/ + do j=start by inc for size; @.row.col=j + if (row+col)//2==0 then do + if col 1 Then + i = i - 1 + End If + Else + If i < n Then + i = i + 1 + Else + j = j + 2 + End If + If j > 1 Then + j = j - 1 + End If + End If + Next + For k = 0 To n-1 + For l = 0 To n-1 + WScript.StdOut.Write Right(" " & arrZ(k,l),3) + Next + WScript.StdOut.WriteLine + Next +End Function

US Naval Observatory + + diff --git a/Task/Web-scraping/Perl-6/web-scraping.pl6 b/Task/Web-scraping/Perl-6/web-scraping.pl6 index b8d62ab73c..ea3955e702 100644 --- a/Task/Web-scraping/Perl-6/web-scraping.pl6 +++ b/Task/Web-scraping/Perl-6/web-scraping.pl6 @@ -1,3 +1,3 @@ -use HTTP::Client; # http://github.com/carlins/http-client/ +use HTTP::Client; # https://github.com/supernovus/perl6-http-client/ my $site = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"; HTTP::Client.new.get($site).match(/'
'( .+? UTC )/)[0].say diff --git a/Task/Web-scraping/VBScript/web-scraping.vb b/Task/Web-scraping/VBScript/web-scraping.vb new file mode 100644 index 0000000000..ce3a48fd10 --- /dev/null +++ b/Task/Web-scraping/VBScript/web-scraping.vb @@ -0,0 +1,29 @@ +Function GetUTC() + url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" + With CreateObject("MSXML2.XMLHTTP.6.0") + .open "GET", url, False + .send + arrt = Split(.responseText,vbLf) + End With + For Each t In arrt + If InStr(t,"UTC") Then + GetUTC = StripHttpTags(t) + Exit For + End If + Next +End Function + +Function StripHttpTags(s) + With New RegExp + .Global = True + .Pattern = "\<.+?\>" + If .Test(s) Then + StripHttpTags = .Replace(s,"") + Else + StripHttpTags = s + End If + End With +End Function + +WScript.StdOut.Write GetUTC +WScript.StdOut.WriteLine diff --git a/Task/Window-creation-X11/Mathematica/window-creation-x11.math b/Task/Window-creation-X11/Mathematica/window-creation-x11.math new file mode 100644 index 0000000000..5ba63b874d --- /dev/null +++ b/Task/Window-creation-X11/Mathematica/window-creation-x11.math @@ -0,0 +1,8 @@ + Needs["GUIKit`"] + ref = GUIRun[Widget["Panel", { + Widget[ + "ImageLabel", {"data" -> + Script[ExportString[Graphics[Rectangle[{0, 0}, {1, 1}]], + "GIF"]]}], + Widget["Label", { "text" -> "Hello World!"}]} + ]] diff --git a/Task/Wireworld/REXX/wireworld.rexx b/Task/Wireworld/REXX/wireworld.rexx index 5f205f5224..8724bbbc9d 100644 --- a/Task/Wireworld/REXX/wireworld.rexx +++ b/Task/Wireworld/REXX/wireworld.rexx @@ -1,65 +1,65 @@ -/*REXX program displays a wire world cartesuab grid of four─state cells.*/ -signal on halt /*handle cell growth interruptus.*/ -parse arg iFID . '(' generations rows cols bare eHead eTail conductor clearScreen repeats -if iFID=='' then iFID='WIREWORLD.TXT' /*use the default file for input?*/ - blank = 'BLANK' /*the "name" for blank*/ -generations = p(generations 100) /*#generations allowed*/ - rows = p(rows 3) /*number of cell rows.*/ - cols = p(cols 3) /* " " " cols.*/ - bare = pickChar(bare blank) /*an empty cell thingy*/ -clearScreen = p(clearScreen 0) /*1 = clear the screen*/ - eHead = pickchar(eHead 'H') - eTail = pickchar(eTail 't') - conductor = pickchar(conductor . ) - repeats = p(repeats 2) /*stop if 2 repeats.*/ -fents=max(linesize()-1,cols) /*fence width shown after display*/ -#repeats=0; $.=bare /*the universe is new, and barren*/ -gens=abs(generations) /*use this for convenience. */ - /* [↓] read the input file. */ - do r=1 while lines(iFID)\==0 /*keep reading until end-of-file.*/ - q=strip(linein(iFID),'T') /*get a single line from the file*/ - _=length(q) /*obtain the length of this row. */ - cols=max(cols,_) /*calculate the maximum # of cols*/ - do c=1 for _; $.r.c=substr(q,c,1); end /*assign row cells*/ +/*REXX program displays a wire world cartesian grid of four─state cells. */ +signal on halt /*handle any cell growth interruptus. */ +parse arg iFID . '(' generations rows cols bare head tail wire clearScreen reps +if iFID=='' then iFID='WIREWORLD.TXT' /*should default input file be used? */ + blank = 'BLANK' /*the "name" for a blank. */ +generations = p(generations 100 ) /*number generations allowed. */ + rows = p(rows 3 ) /*the number of cell rows. */ + cols = p(cols 3 ) /* " " " " cols. */ + bare = pickChar(bare blank ) /*an empty cell character. */ +clearScreen = p(clearScreen 0 ) /*1 means to clear the screen*/ + head = pickchar(head 'H' ) /*pick the char for the head.*/ + tail = pickchar(tail 't' ) /* " " " " " tail.*/ + wire = pickchar(wire . ) /* " " " " " wire.*/ + reps = p(reps 2 ) /*stop program if two repeats.*/ +fents=max(linesize()-1,cols) /*the fence width used after displaying*/ +#reps=0; $.=bare /*at start, universe is new and barren.*/ +gens=abs(generations) /*use for convenience (and short name).*/ + /* [↓] read the input file. */ + do r=1 while lines(iFID)\==0 /*keep reading until the End─Of─File. */ + q=strip(linein(iFID),'T') /*get single line from the input file. */ + _=length(q) /*obtain the length of this (input) row*/ + cols=max(cols,_) /*calculate the maximum number of cols.*/ + do c=1 for _; $.r.c=substr(q,c,1); end /*assign the row cells.*/ end /*r*/ -rows=r-1 -cycle=0; !.=0; call showCells /*show initial state of the cells*/ -/*─────────────────────────────────────watch cells evolve 4 poss. states*/ - do cycle=1 for gens; @.=bare - do r=1 for rows - do c=1 for cols; ?=$.r.c; ??=? - select - when ?==eHead then ??=eTail - when ?==eTail then ??=conductor - when ?==conductor then do; n=neighbors() - if n==1 | n==2 then ??=eHead - end - otherwise nop - end /*select*/ - @.r.c=?? - end /*c*/ - end /*r*/ - call assign$ /*assign alternate cells ──► real*/ - if generations>0 | cycle==gens then call showCells - end /*cycle*/ -/*─────────────────────────────────────stop watching the universe (life)*/ -halt: cycles=life-1; if cycles\==gens then say 'REXX program interrupted.' -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────SHOWCELLS subroutine───────────────────*/ -showCells: if clearScreen then 'CLS' /* ◄─── change this for your OS.*/ -call showRows /*show the rows in proper order. */ -say right(copies('═',fents)cycle,fents) /*show&tell for a bunch of cells*/ -if _=='' then exit /*if no life, then stop the run. */ -if !._ then #repeats=#repeats+1 /*we detected a repeated pattern.*/ -!._=1 /*existence state & compare later*/ -if repeats\==0 & #repeats<=repeats then return /*so far, so good.*/ -say '"Wireworld" repeated itself' repeats "times, program is stopping." -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────1─liner subroutines───────────────────────────────────────────────────────────────────────*/ -$: parse arg _row,_col; return $._row._col==eHead -assign$: do r=1 for rows; do c=1 for cols; $.r.c=@.r.c; end; end; return -err: say;say;say center(' error! ',max(40,linesize()%2),"*");say;do j=1 for arg();say arg(j);say;end;say;exit 13 -neighbors: return $(r-1,c-1)+$(r-1,c)+$(r-1,c+1)+$(r,c-1)+$(r,c+1)+$(r+1,c-1)+$(r+1,c)+$(r+1,c+1) -p: return word(arg(1),1) +rows=r-1 /*adjust the row number (from DO loop).*/ +life=0; !.=0; call showCells /*display initial state of the cells. */ + /*watch cells evolve, 4 possible states*/ + do life=1 for gens; @.=bare /*perform for the number of generations*/ + + do r=1 for rows /*process each of the rows.*/ + do c=1 for cols; ?=$.r.c; ??=? /* " " " " cols.*/ + select /*determine type of cell. */ + when ?==head then ??=tail + when ?==tail then ??=wire + when ?==wire then do; n=hood(); if n==1|n==2 then ??=head; end + otherwise nop + end /*select*/ + @.r.c=?? + end /*c*/ + end /*r*/ + + call assign$ /*assign alternate cells ──► real world*/ + if generations>0 | life==gens then call showCells + end /*life*/ + /*stop watching the universe (or life).*/ +halt: if life-1\==gens then say 'The ~~~Wireworld~~~ program was interrupted.' +done: exit /*stick a fork in it, we are all done.*/ +/*────────────────────────────────────────────────────────────────────────────*/ +showCells: if clearScreen then 'CLS' /*◄──change this for the OS.*/ + call showRows /*show rows in proper order.*/ + say right(copies('═',fents)life,fents) /*display a bunch of cells. */ + if _=='' then signal done /*No life? Then stop run. */ + if !._ then #reps=#reps+1 /*detected repeated pattern.*/ + !._=1 /*it is now existence state.*/ + if reps\==0 & #reps<=reps then return /*so far, so good, no reps. */ + say '"Wireworld" repeated itself' reps "times, program is stopping." + signal done /*exit program, we're done. */ +/*───────────────────────────────one─liner subroutines─────────────────────────────────────────────────────────────────────*/ +$: parse arg _row,_col; return ($._row._col==head) +assign$: do r=1 for rows; do c=1 for cols; $.r.c=@.r.c; end; end; return +err: say; say center(' error! ',max(40,linesize()%2),"*"); say; do j=1 for arg(); say arg(j); say; end; say; exit 13 +hood: return $(r-1,c-1) + $(r-1,c) + $(r-1,c+1) + $(r,c-1) + $(r,c+1) + $(r+1,c-1) + $(r+1,c) + $(r+1,c+1) +p: return word(arg(1), 1) pickChar: _=p(arg(1));if translate(_)==blank then _=' ';if length(_)==3 then _=d2c(_);if length(_)==2 then _=x2c(_);return _ -showRows: _=; do r=1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T'); say z; _=_||z; end; return +showRows: _=; do r=1 for rows; z=; do c=1 for cols; z=z || $.r.c; end; z=strip(z,'T'); say z; _=_ || z; end; return diff --git a/Task/Word-wrap/Elixir/word-wrap.elixir b/Task/Word-wrap/Elixir/word-wrap.elixir new file mode 100644 index 0000000000..14177a59d2 --- /dev/null +++ b/Task/Word-wrap/Elixir/word-wrap.elixir @@ -0,0 +1,27 @@ +defmodule Word_wrap do + def paragraph( string, max_line_length ) do + [word | rest] = String.split( string, ~r/\s+/, trim: true ) + lines_assemble( rest, max_line_length, String.length(word), word, [] ) + |> Enum.join( "\n" ) + end + + defp lines_assemble( [], _, _, line, acc ), do: [line | acc] |> Enum.reverse + defp lines_assemble( [word | rest], max, line_length, line, acc ) do + if line_length + 1 + String.length(word) > max do + lines_assemble( rest, max, String.length(word), word, [line | acc] ) + else + lines_assemble( rest, max, line_length + 1 + String.length(word), line <> " " <> word, acc ) + end + end +end + +text = """ +Even today, with proportional fonts and complex layouts, there are still cases where you need to +wrap text at a specified column. The basic task is to wrap a paragraph of text in a simple way in +your language. If there is a way to do this that is built-in, trivial, or provided in a standard +library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. +""" +Enum.each([72, 80], fn len -> + IO.puts String.duplicate("-", len) + IO.puts Word_wrap.paragraph(text, len) +end) diff --git a/Task/Word-wrap/JavaScript/word-wrap-1.js b/Task/Word-wrap/JavaScript/word-wrap-1.js new file mode 100644 index 0000000000..50e2c1a959 --- /dev/null +++ b/Task/Word-wrap/JavaScript/word-wrap-1.js @@ -0,0 +1,12 @@ +function wrap (text, limit) { + if (text.length > limit) { + // find the last space within limit + var edge = text.slice(0, limit).lastIndexOf(' '); + if (edge > 0) { + var line = text.slice(0, edge); + var remainder = text.slice(edge + 1); + return line + '\n' + wrap(remainder, limit); + } + } + return text; +} diff --git a/Task/Word-wrap/JavaScript/word-wrap-2.js b/Task/Word-wrap/JavaScript/word-wrap-2.js new file mode 100644 index 0000000000..72f5f81e5a --- /dev/null +++ b/Task/Word-wrap/JavaScript/word-wrap-2.js @@ -0,0 +1 @@ +console.log(wrap(text, 80)); diff --git a/Task/Word-wrap/JavaScript/word-wrap-3.js b/Task/Word-wrap/JavaScript/word-wrap-3.js new file mode 100644 index 0000000000..b57e5f636f --- /dev/null +++ b/Task/Word-wrap/JavaScript/word-wrap-3.js @@ -0,0 +1 @@ +console.log(wrap(text, 42)); diff --git a/Task/Word-wrap/PowerShell/word-wrap.psh b/Task/Word-wrap/PowerShell/word-wrap.psh new file mode 100644 index 0000000000..bd834a0664 --- /dev/null +++ b/Task/Word-wrap/PowerShell/word-wrap.psh @@ -0,0 +1,29 @@ +function wrap{ +$divide=$args[0] -split " " +$width=$args[1] +$spaceleft=$width + +foreach($word in $divide){ + if($word.length+1 -gt $spaceleft){ + $output+="`n$word " + $spaceleft=$width-($word.length+1) + } else { + $output+="$word " + $spaceleft-=$word.length+1 + } +} + +return "$output`n" +} + +### The Main Thing... + +$paragraph="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur." + +"`nLine width:30`n" +wrap $paragraph 30 +"=========================================================" +"Line width:100`n" +wrap $paragraph 100 + +### End script diff --git a/Task/Word-wrap/PureBasic/word-wrap.purebasic b/Task/Word-wrap/PureBasic/word-wrap.purebasic new file mode 100644 index 0000000000..f39d314cdf --- /dev/null +++ b/Task/Word-wrap/PureBasic/word-wrap.purebasic @@ -0,0 +1,46 @@ +DataSection + Data.s "In olden times when wishing still helped one, there lived a king "+ + "whose daughters were all beautiful, but the youngest was so beautiful "+ + "that the sun itself, which has seen so much, was astonished whenever "+ + "it shone-in-her-face. Close-by-the-king's castle lay a great dark "+ + "forest, and under an old lime-tree in the forest was a well, and when "+ + "the day was very warm, the king's child went out into the forest and "+ + "sat down by the side of the cool-fountain, and when she was bored she "+ + "took a golden ball, and threw it up on high and caught it, and this "+ + "ball was her favorite plaything." +EndDataSection + +Procedure.i ww_pos(txt$,l.i) + While Mid(txt$,l,1)<>Chr(32) And l>0 And Len(txt$)>l : l-1 : Wend + If l>0 : ProcedureReturn l : Else : ProcedureReturn Len(Trim(txt$)) : EndIf +EndProcedure + +Procedure WriteLine(txt$,ls.i) + Shared d$,lw + Select LCase(d$) + Case "l" : PrintN(Mid(txt$,1,ls)) + Case "r" : PrintN(RSet(Trim(Mid(txt$,1,ls)),lw,Chr(32))) + EndSelect +EndProcedure + +Procedure main(txt$,lw.i) + If Len(txt$) + p=ww_pos(txt$,lw) : WriteLine(txt$,p) : ProcedureReturn main(LTrim(Right(txt$,Len(txt$)-p)),lw) + EndIf +EndProcedure + +Procedure.i MaxWordLen(txt$) + For i=1 To CountString(txt$,Chr(32))+1 + wrd$=LTrim(StringField(txt$,i,Chr(32))) + wrdl=Len(wrd$)+1 : If wrdl>l : l=wrdl : EndIf + Next + ProcedureReturn l +EndProcedure + +OpenConsole() +Read.s t$ +Print("Input line width: ") : lw=Val(Input()) : minL=MaxWordLen(t$) +If lw 0 Then + WScript.StdOut.WriteLine row + End If +End Sub diff --git a/Task/World-Cup-group-stage/00DESCRIPTION b/Task/World-Cup-group-stage/00DESCRIPTION index 085ef45d63..6bb573c1ba 100644 --- a/Task/World-Cup-group-stage/00DESCRIPTION +++ b/Task/World-Cup-group-stage/00DESCRIPTION @@ -1,4 +1,4 @@ -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. +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 [[wp:Round-robin tournament|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. diff --git a/Task/World-Cup-group-stage/Elixir/world-cup-group-stage.elixir b/Task/World-Cup-group-stage/Elixir/world-cup-group-stage.elixir new file mode 100644 index 0000000000..a6f3482e66 --- /dev/null +++ b/Task/World-Cup-group-stage/Elixir/world-cup-group-stage.elixir @@ -0,0 +1,32 @@ +defmodule World_Cup do + def group_stage do + results = [[3,0],[1,1],[0,3]] + teams = [0,1,2,3] + allresults = combos(2,teams) |> combinations(results) + allpoints = for list <- allresults, do: (for {l1,l2} <- list, do: Enum.zip(l1,l2)) |> List.flatten + totalpoints = for list <- allpoints, do: (for t <- teams, do: {t, Enum.sum(for {t_,points} <- list, t_==t, do: points)} ) + sortedtotalpoints = for list <- totalpoints, do: Enum.sort(list,fn({_,a},{_,b}) -> a > b end) + pointsposition = for n <- teams, do: (for list <- sortedtotalpoints, do: elem(Enum.at(list,n),1)) + for n <- teams do + for points <- 0..9 do + Enum.at(pointsposition,n) |> Enum.filter(&(&1 == points)) |> length + end + end + end + + defp combos(1, list), do: (for x <- list, do: [x]) + defp combos(k, list) when k == length(list), do: [list] + defp combos(k, [h|t]) do + (for subcombos <- combos(k-1, t), do: [h | subcombos]) ++ (combos(k, t)) + end + + defp combinations([h],list2), do: (for item <- list2, do: [{h,item}]) + defp combinations([h|t],list2) do + for item <- list2, comb <- combinations(t,list2), do: [{h,item} | comb] + end +end + +format = String.duplicate("~4w", 10) <> "~n" +:io.format(format, Enum.to_list(0..9)) +IO.puts String.duplicate(" ---", 10) +Enum.each(World_Cup.group_stage, fn x -> :io.format(format, x) end) diff --git a/Task/Write-float-arrays-to-a-text-file/PL-I/write-float-arrays-to-a-text-file.pli b/Task/Write-float-arrays-to-a-text-file/PL-I/write-float-arrays-to-a-text-file.pli index 2c2644b7db..f2aa2a4378 100644 --- a/Task/Write-float-arrays-to-a-text-file/PL-I/write-float-arrays-to-a-text-file.pli +++ b/Task/Write-float-arrays-to-a-text-file/PL-I/write-float-arrays-to-a-text-file.pli @@ -1,9 +1,13 @@ -declare X(5) float (9) initial (1, 2, 3, 4, 5), - Y(5) float (18) initial (9, 8, 7, 6, 1e9); -declare (x_precision, y_precision) fixed binary; -open file (out) title ('/OUT.TXT,type(text),recsize(100)'); -x_precision = 9; -y_precision = 16; -put file (out) edit ((X(i), Y(i) do i = 1 to 5)) - (skip, e(16, x_precision), - x(2), e(20, y_precision) ); +*Process source attributes xref; + aaa: Proc Options(main); + declare X(5) float (9) initial (1, 2, 3, 4, 5), + Y(5) float (18) initial (9, 8, 7, 6, 1e9); + declare (x_precision, y_precision) fixed binary; + Dcl out stream output; + open file(out) title('/OUT.TXT,type(text),recsize(100)'); + x_precision = 9; + y_precision = 16; + put file(out) edit((X(i),Y(i) do i=1 to 5)) + (skip,e(19,x_precision), + x(2),e(24,y_precision)); + end; diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-6.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-6.basic index ec0c10912b..649adfbd2b 100644 --- a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-6.basic +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-6.basic @@ -1,48 +1,7 @@ -10 LET s$="BASIC": REM our language name -20 DIM b(5,5):REM our bigmap characters -30 FOR l = 1 TO 5: REM 5 characters -40 FOR m = 1 TO 5: REM 5 rows -50 READ b(l,m) -60 NEXT m -70 NEXT l - -100 PAPER 0: REM black background -110 INK 2: REM our shadow will be red -120 CLS -130 LET r=9: REM shadow will start on row 5 -140 LET c=2: REM shadow will start at column 2 -150 GO SUB 2000: REM draw shadow -160 INK 6: REM our forground will be yellow -170 LET r=10: REM foreground will start on row 6 -180 LET c=3: REM foreground will start on column 3 -190 GO SUB 2000: REM display the language name - -999 STOP - -1000 REM convert to binary bigmap -1010 LET t=n: REM temporary variable -1020 LET g$="": REM this will contain our 5 character binary bigmap -1040 FOR z=5 TO 0 STEP -1 -1050 LET d$=" ": REM assume next digit is zero (draw a space) -1060 IF t>=(2^z) THEN LET d$=CHR$(143): LET t=t-(2^z): LET sf=1: REM 143 is a block -1070 LET g$=g$+d$ -1080 NEXT z -1090 RETURN - -2000 REM display the big letters -2010 FOR l=1 TO 5: REM our 5 rows -2020 PRINT AT r+l-1,c; -2030 FOR m=1 TO 5: REM bigmap for each character -2040 LET n=b(l,m) -2050 GO SUB 1000 -2060 PRINT g$;: REM 5 character bigmap -2070 PRINT " ";: REM space between each letter -2080 NEXT m -2090 NEXT l -2100 RETURN - -9000 DATA 30,17,30,17,30: REM B -9010 DATA 14,17,31,17,17: REM A -9020 DATA 15,16,14,1,30: REM S -9030 DATA 31,4,4,4,31: REM I -9040 DATA 14,17,16,17,14: REM C +Disp “ .....+ .....+ +Disp “ +o+ooo +o+ooo +Disp “ .o .o +Disp “ .o ...+.+ +Disp “ +o +ooooo +Disp “ +Disp “ BASIC diff --git a/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-7.basic b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-7.basic new file mode 100644 index 0000000000..ec0c10912b --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/BASIC/write-language-name-in-3d-ascii-7.basic @@ -0,0 +1,48 @@ +10 LET s$="BASIC": REM our language name +20 DIM b(5,5):REM our bigmap characters +30 FOR l = 1 TO 5: REM 5 characters +40 FOR m = 1 TO 5: REM 5 rows +50 READ b(l,m) +60 NEXT m +70 NEXT l + +100 PAPER 0: REM black background +110 INK 2: REM our shadow will be red +120 CLS +130 LET r=9: REM shadow will start on row 5 +140 LET c=2: REM shadow will start at column 2 +150 GO SUB 2000: REM draw shadow +160 INK 6: REM our forground will be yellow +170 LET r=10: REM foreground will start on row 6 +180 LET c=3: REM foreground will start on column 3 +190 GO SUB 2000: REM display the language name + +999 STOP + +1000 REM convert to binary bigmap +1010 LET t=n: REM temporary variable +1020 LET g$="": REM this will contain our 5 character binary bigmap +1040 FOR z=5 TO 0 STEP -1 +1050 LET d$=" ": REM assume next digit is zero (draw a space) +1060 IF t>=(2^z) THEN LET d$=CHR$(143): LET t=t-(2^z): LET sf=1: REM 143 is a block +1070 LET g$=g$+d$ +1080 NEXT z +1090 RETURN + +2000 REM display the big letters +2010 FOR l=1 TO 5: REM our 5 rows +2020 PRINT AT r+l-1,c; +2030 FOR m=1 TO 5: REM bigmap for each character +2040 LET n=b(l,m) +2050 GO SUB 1000 +2060 PRINT g$;: REM 5 character bigmap +2070 PRINT " ";: REM space between each letter +2080 NEXT m +2090 NEXT l +2100 RETURN + +9000 DATA 30,17,30,17,30: REM B +9010 DATA 14,17,31,17,17: REM A +9020 DATA 15,16,14,1,30: REM S +9030 DATA 31,4,4,4,31: REM I +9040 DATA 14,17,16,17,14: REM C diff --git a/Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii-1.bf b/Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii-1.bf new file mode 100644 index 0000000000..10c3f2821f --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii-1.bf @@ -0,0 +1,9 @@ +0" &7&%h&'&%| &7&%7%&%&'&%&'&%&7&%"v +v"'%$%'%$%3$%$%7% 0%&7&%&7&(%$%'%$"< +>"%$%7%$%&%$%&'&%7%$%7%$%, '&+(%$%"v +v"+&'&%+('%$%$%'%$%$%$%$%$%$%$%'%$"< +>"(%$%$%'%$%$%( %$+(%&%$+(%&%$+(%&"v +v"(; $%$%(+$%&%(+$%$%'%$%+&%$%$%$%"< +? ";(;(+(+$%+(%&(;(3%$%&$ 7`+( ":v > +^v!:-1<\,:g7+*63%4 \/_#4:_v#:-*84_$@ +$_\:,\^ >55+,$:^:$ diff --git a/Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii.bf b/Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii-2.bf similarity index 100% rename from Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii.bf rename to Task/Write-language-name-in-3D-ASCII/Befunge/write-language-name-in-3d-ascii-2.bf diff --git a/Task/Write-language-name-in-3D-ASCII/Brainf---/write-language-name-in-3d-ascii.bf b/Task/Write-language-name-in-3D-ASCII/Brainf---/write-language-name-in-3d-ascii.bf new file mode 100644 index 0000000000..670e159e9c --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Brainf---/write-language-name-in-3d-ascii.bf @@ -0,0 +1,16 @@ +++++[>++++>++<[>>++>+++>++++++> ++++++<<<<<-]<-]>>++>..>->----> +-...[<]<+++[>++++[>>...<<-]<-]> >>..>>>.....<<<..>>>...[<]++[>> +.....>>>...<<<<<-]>.>.>.>.<<..> >.[<]<+++++[>++++[>>.<<-]<-]>>> +..>>>...[<]+++++[>>..<<-]+++>>. >.<..>>>...<.[[>]<.<.<<..>>.>.. +<<<.<<-]+++>.>.>>.<<.>>.<<..>>. >....<<<.>>>...<<<..>>>...<<<.> +>>......<<.>.>..<.<<..>>>..<<<. .>>>....<.<<..>>.>..<<.[[>]<<.> +..<<<...>>>.<.<<<<-]+++>.>..>>. <<.>>.<<...>>>..<<<.>>..<<..>>. +<.<.>>>..<..>...<<<...>>.<<.>>> .<<.>>.<<.<..>>.<.<.>>>.<<<..>> +.>.<<<...>>>..<.>.<<.>.>..<.<.. >>.<<.>.>..<.<..>>.<<.>.>..<.<. +<<.>...>>.<<.>>.<<..>>.<.>.<<.> >..<<...>.>>..<<..>>...<.<<...> +>..<<..>>..<<...>.<.>>.<<..>>.. <<..>>.>.<<.<[[>]<<<<.>>.<.>>.. +<<.<..<<-]>.>....>>.<<.>>.<<..> >.>.<.<<.>>..<<..>>.<<...>.>.<< +..>>>.<<<....>>..<<..>>..<<..>> ..<<.>>.<<..>>..<<..>>.<<<.>... +..>>.<<.>>.>......<..>..<.<<..> >.<<.>>.>...<<.>.>..<..>..<..>. +.<..<<.>>.>..<..>..<.<<<.>..... .>>.<.>>......<<..>>..<<.<...>> +.<.>>..<<.>.<.>>..<<..>>..<<..> >..<<.<.>>.<.>>..<<..>>..<<.<<. diff --git a/Task/Write-language-name-in-3D-ASCII/Common-Lisp/write-language-name-in-3d-ascii.lisp b/Task/Write-language-name-in-3D-ASCII/Common-Lisp/write-language-name-in-3d-ascii.lisp new file mode 100644 index 0000000000..8eb5c4af4f --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Common-Lisp/write-language-name-in-3d-ascii.lisp @@ -0,0 +1,12 @@ +(ql:quickload :cl-ppcre) +(defvar txt +" + xxxx xxxx x x x x xxxx x x x x xxxx xxxxx +x x x x xx xx xx xx x x xx x x x x x x +x x x x xx x x xx x x x x x x x x xxx x x +x x x x x x x x x x x x x x xxx xxxxx +x x x x x x x x x x x xx x x x x x + xxxx xxxx x x x x xxxx x x xxxxx x xxxx x +" +) +(princ (cl-ppcre:regex-replace-all " " (cl-ppcre:regex-replace-all "x" txt "_/") " " )) diff --git a/Task/Write-language-name-in-3D-ASCII/Elixir/write-language-name-in-3d-ascii.elixir b/Task/Write-language-name-in-3D-ASCII/Elixir/write-language-name-in-3d-ascii.elixir new file mode 100644 index 0000000000..e8b62a7438 --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Elixir/write-language-name-in-3d-ascii.elixir @@ -0,0 +1,13 @@ +defmodule ASCII3D do + def decode(str) do + Regex.scan(~r/(\d+)(\D+)/, str) + |> Enum.map_join(fn[_,n,s] -> String.duplicate(s, String.to_integer(n)) end) + |> String.replace("B", "\\") # Backslash + end +end + +data = "1 12_4 2_1\n1/B2 9_1B2 1/2B 3 2_18 2_1\nB2 B8_1/ 3 B2 1/B_B4 2_6 2_2 1/B_B6 4_1 +3 B7_3 4 B2/_2 1/2B_1_2 1/B_B B2/_4 1/ 3_1B\n 2 B2 6_1B3 3 B2 1/B2 B1/_/B_B3/ 2 1/2B 1 /B B2_1/ +2 3 B5_1/4 6 B3 1B/_/2 /1_2 6 B1\n3 3 B10_6 B3 3 /2B_1_6 B1 +4 2 B11_2B 1B_B2 B1_B 3 /1B/_/B_B2 B B_B1\n6 1B/11_1/3 B/_/2 3 B/_/" +IO.puts ASCII3D.decode(data) diff --git a/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl b/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl index a5e7f42281..f0c298b785 100644 --- a/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl +++ b/Task/Write-language-name-in-3D-ASCII/Erlang/write-language-name-in-3d-ascii.erl @@ -3,4 +3,4 @@ -export([main/0]). main() -> - io:format(" _____ _ \n| ___| | | \n| |__ _ __| | __ _ _ __ __ _ \n| __| '__| |/ _` | '_ \ / _` |\n| |__| | | | (_| | | | | (_| |\n\____/_| |_|\__,_|_| | _|\__, |\n __/ |\n |___/ "). + io:format(" _____ _ \n| ___| | | \n| |__ _ __| | __ _ _ __ __ _ \n| __| '__| |/ _` | '_ \\ / _` |\n| |__| | | | (_| | | | | (_| |\n|____/_| |_|\\__,_|_| |_|\\__, |\n __/ |\n |___/\n"). diff --git a/Task/Write-language-name-in-3D-ASCII/Pascal/write-language-name-in-3d-ascii.pascal b/Task/Write-language-name-in-3D-ASCII/Pascal/write-language-name-in-3d-ascii.pascal new file mode 100644 index 0000000000..014a99ef0d --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Pascal/write-language-name-in-3d-ascii.pascal @@ -0,0 +1,25 @@ +program WritePascal; + +const + i64: int64 = 1055120232691680095; (* This defines "Pascal" *) + cc: array[-1..15] of string = (* Here are all string-constants *) + ('_______v---', + '__', '\_', '___', '\__', + ' ', ' ', ' ', ' ', + '/ ', ' ', '_/ ', '\/ ', + ' _', '__', ' _', ' _'); +var + x, y: integer; + +begin + for y := 0 to 7 do + begin + Write(StringOfChar(cc[(not y and 1) shl 2][1], 23 - y and 6)); + Write(cc[((i64 shr (y div 2)) and 1) shl 3 + (not y and 1) shl 2 + 2]); + for x := 0 to 15 do + Write(cc[((i64 shr ((x and 15) * 4 + y div 2)) and 1) + + ((i64 shr (((x + 1) and 15) * 4 + y div 2)) and 1) shl 3 + + (x mod 3) and 2 + (not y and 1) shl 2]); + writeln(cc[1 + (not y and 1) shl 2] + cc[(not y and 1) shl 3 - 1]); + end; +end. diff --git a/Task/Write-language-name-in-3D-ASCII/PureBasic/write-language-name-in-3d-ascii.purebasic b/Task/Write-language-name-in-3D-ASCII/PureBasic/write-language-name-in-3d-ascii.purebasic new file mode 100644 index 0000000000..94c656028f --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/PureBasic/write-language-name-in-3d-ascii.purebasic @@ -0,0 +1,18 @@ +If OpenConsole() + PrintN(" ////\ ////\ ////| ") + PrintN(" //// \ __ //// \ __ |XX|_/ ") + PrintN(" //// /| | ////\ ////\//// |//// /| | //// | ////\ ////\ ") + PrintN("|XX| |X| ////\X| ////\// //// /||XX| |X| |//// /|| //// _| ////\ //// \ ") + PrintN("|XX| |X||XX| |X||XX| |/ |XX| |X||XX| |/ /|XX| |X||//// / |XX| | //// /\ |") + PrintN("|XX| |/ |XX| |X||XX| /|XX| |//|XX| \|XX|/// |XX| |/\ |XX| ||XX| |XX\|") + PrintN("|XX| /|XX| |X||XX| / |XX| //|XX| /| |//// |XX| ||XX| ||XX| | ") + PrintN("|$$| / |$$| |&||$$| | |$$| |&||$$| |&| |$$| /||\\\\/| ||$$| ||$$| |///|") + PrintN("|%%| | |%%| |i||%%| | |%%| |/ |%%| |i| |%%| |i|| |%%| ||%%| ||%%| |// |") + PrintN("|ii| | |ii| |/ |ii| | |ii| /|ii| |/ /|ii| \/|/ |ii| /|ii| ||ii| |/ / ") + PrintN("|::| | \\\\ /|::| | |::| / |::| / |::| / //// / |::| | \\\\ / ") + PrintN("|..| | \\\\/ |..|/ \\\\/ |..| / \\\\/ \\\\ / |..|/ \\\\/ ") + PrintN(" \\\\| \\\\/ ") + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Write-language-name-in-3D-ASCII/Ruby/write-language-name-in-3d-ascii-1.rb b/Task/Write-language-name-in-3D-ASCII/Ruby/write-language-name-in-3d-ascii-1.rb new file mode 100644 index 0000000000..26467f94ed --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Ruby/write-language-name-in-3d-ascii-1.rb @@ -0,0 +1,65 @@ +text = <NUL>NUL +EventCreate /t WARNING /id 456 /l APPLICATION /so BlaBla /d "This is found in apps log" 2>NUL>NUL +::That "2>NUL>NUL" trick actually works in any command! diff --git a/Task/Write-to-Windows-event-log/VBScript/write-to-windows-event-log.vb b/Task/Write-to-Windows-event-log/VBScript/write-to-windows-event-log.vb new file mode 100644 index 0000000000..d954715b82 --- /dev/null +++ b/Task/Write-to-Windows-event-log/VBScript/write-to-windows-event-log.vb @@ -0,0 +1,21 @@ +Sub write_event(event_type,msg) + Set objShell = CreateObject("WScript.Shell") + Select Case event_type + Case "SUCCESS" + n = 0 + Case "ERROR" + n = 1 + Case "WARNING" + n = 2 + Case "INFORMATION" + n = 4 + Case "AUDIT_SUCCESS" + n = 8 + Case "AUDIT_FAILURE" + n = 16 + End Select + objShell.LogEvent n, msg + Set objShell = Nothing +End Sub + +Call write_event("INFORMATION","This is a test information.") diff --git a/Task/XML-DOM-serialization/ABAP/xml-dom-serialization.abap b/Task/XML-DOM-serialization/ABAP/xml-dom-serialization.abap new file mode 100644 index 0000000000..fb106b5e43 --- /dev/null +++ b/Task/XML-DOM-serialization/ABAP/xml-dom-serialization.abap @@ -0,0 +1,19 @@ +DATA: xml_string TYPE string. + +DATA(xml) = cl_ixml=>create( ). +DATA(doc) = xml->create_document( ). +DATA(root) = doc->create_simple_element( name = 'root' + parent = doc ). + +doc->create_simple_element( name = 'element' + parent = root + value = 'Some text here' ). + +DATA(stream_factory) = xml->create_stream_factory( ). +DATA(stream) = stream_factory->create_ostream_cstring( string = xml_string ). +DATA(renderer) = xml->create_renderer( document = doc + ostream = stream ). +stream->set_pretty_print( abap_true ). +renderer->render( ). + +cl_demo_output=>display_text( xml_string ). diff --git a/Task/XML-XPath/CoffeeScript/xml-xpath-1.coffee b/Task/XML-XPath/CoffeeScript/xml-xpath-1.coffee new file mode 100644 index 0000000000..a7fd9931e8 --- /dev/null +++ b/Task/XML-XPath/CoffeeScript/xml-xpath-1.coffee @@ -0,0 +1,28 @@ +doc = new DOMParser().parseFromString ' + +