diff --git a/Conf/lang.yaml b/Conf/lang.yaml index 0525999c55..f6193f18c1 100644 --- a/Conf/lang.yaml +++ b/Conf/lang.yaml @@ -205,6 +205,7 @@ DMS: .dms Dodo0: .dodo0 Draco: .draco Dragon: .dragon +Dt: .dt DUP: .dup DWScript: .dw Dyalect: .dyalect @@ -244,6 +245,7 @@ Es: .es ESQL: .esql Euler: .euler Euphoria: .euphoria +Evaldraw: .evaldraw Excel: .excel Explore: .explore Extended BrainF***: .ebf @@ -498,6 +500,7 @@ MLite: .mlite MMIX: .mmix Modula-2: .mod2 Modula-3: .mod3 +Mojo: .mojo Mond: .mond Monicelli: .monicelli Monkey: .monkey diff --git a/Lang/11l/Selectively-replace-multiple-instances-of-a-character-within-a-string b/Lang/11l/Selectively-replace-multiple-instances-of-a-character-within-a-string new file mode 120000 index 0000000000..fd76e458f8 --- /dev/null +++ b/Lang/11l/Selectively-replace-multiple-instances-of-a-character-within-a-string @@ -0,0 +1 @@ +../../Task/Selectively-replace-multiple-instances-of-a-character-within-a-string/11l \ No newline at end of file diff --git a/Lang/11l/Set-right-adjacent-bits b/Lang/11l/Set-right-adjacent-bits new file mode 120000 index 0000000000..8aa56e4c7e --- /dev/null +++ b/Lang/11l/Set-right-adjacent-bits @@ -0,0 +1 @@ +../../Task/Set-right-adjacent-bits/11l \ No newline at end of file diff --git a/Lang/AArch64-Assembly/ADFGVX-cipher b/Lang/AArch64-Assembly/ADFGVX-cipher new file mode 120000 index 0000000000..7d98e5eba8 --- /dev/null +++ b/Lang/AArch64-Assembly/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Bioinformatics-base-count b/Lang/AArch64-Assembly/Bioinformatics-base-count new file mode 120000 index 0000000000..77532b44f2 --- /dev/null +++ b/Lang/AArch64-Assembly/Bioinformatics-base-count @@ -0,0 +1 @@ +../../Task/Bioinformatics-base-count/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Count-occurrences-of-a-substring b/Lang/AArch64-Assembly/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..5199f80ebc --- /dev/null +++ b/Lang/AArch64-Assembly/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Jewels-and-stones b/Lang/AArch64-Assembly/Jewels-and-stones new file mode 120000 index 0000000000..0605fcd226 --- /dev/null +++ b/Lang/AArch64-Assembly/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/Letter-frequency b/Lang/AArch64-Assembly/Letter-frequency new file mode 120000 index 0000000000..c225fbca5f --- /dev/null +++ b/Lang/AArch64-Assembly/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/AArch64-Assembly \ No newline at end of file diff --git a/Lang/AArch64-Assembly/String-case b/Lang/AArch64-Assembly/String-case new file mode 120000 index 0000000000..ec1194b1f0 --- /dev/null +++ b/Lang/AArch64-Assembly/String-case @@ -0,0 +1 @@ +../../Task/String-case/AArch64-Assembly \ No newline at end of file diff --git a/Lang/ALGOL-68/Determine-if-two-triangles-overlap b/Lang/ALGOL-68/Determine-if-two-triangles-overlap new file mode 120000 index 0000000000..7543dc4fab --- /dev/null +++ b/Lang/ALGOL-68/Determine-if-two-triangles-overlap @@ -0,0 +1 @@ +../../Task/Determine-if-two-triangles-overlap/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Diversity-prediction-theorem b/Lang/ALGOL-68/Diversity-prediction-theorem new file mode 120000 index 0000000000..d2ff7024e1 --- /dev/null +++ b/Lang/ALGOL-68/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-M/Create-a-two-dimensional-array-at-runtime b/Lang/ALGOL-M/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..87ccfbe67e --- /dev/null +++ b/Lang/ALGOL-M/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/ALGOL-M \ No newline at end of file diff --git a/Lang/ALGOL-W/Count-in-factors b/Lang/ALGOL-W/Count-in-factors new file mode 120000 index 0000000000..a14f8ef196 --- /dev/null +++ b/Lang/ALGOL-W/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/ALGOL-W \ No newline at end of file diff --git a/Lang/ANSI-BASIC/00-LANG.txt b/Lang/ANSI-BASIC/00-LANG.txt index ad9d3273cb..9ae71a4883 100644 --- a/Lang/ANSI-BASIC/00-LANG.txt +++ b/Lang/ANSI-BASIC/00-LANG.txt @@ -2,8 +2,17 @@ |tags=basic}}{{language programming paradigm|Imperative}} {{Implementation|BASIC}} -'''ANSI BASIC''' is a standard for the [[BASIC]] programming language. It is specified in ANSI X3.113-1987 ("Programming Languages Full BASIC"). The same standard was specified in INCITS/ISO/IEC 10279-1991 ("Information Technology – Programming Languages – Full BASIC"). The standard is called "Full BASIC" to distinguish it from [[Minimal BASIC]] which is another standard established by ANSI, ISO, and ECMA. +'''ANSI BASIC''' ('''Full BASIC''') is a standard for the [[BASIC]] programming language. It is specified in ANSI X3.113-1987 ("Programming Languages Full BASIC"). The same standard was specified in INCITS/ISO/IEC 10279-1991 ("Information Technology – Programming Languages – Full BASIC"). The standard is called "Full BASIC" to distinguish it from [[Minimal BASIC]] which is another standard established by ANSI, ISO, and ECMA. ECMA, in ECMA-116 (1986), defined a subset of the ANSI BASIC Standard, ANSI X3.113-198X. The specification is divided into three parts: ECMA BASIC-1, ECMA BASIC-2, and ECMA Graphics Module. ECMA Standard is fully upward compatible with corresponding implementations of the ANSI Standard. +== Main features == +* MAT keywords for matrix manipulation +* Optional use of decimal [[floating point]] (''radix 10'') to improve numerical presentation. + +== Implementations == +* [[True BASIC]] +* [[Decimal BASIC]] +* [http://www.moria.de/~michael/bas/ Bas] + [[Category:Standards]] \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Brazilian-numbers b/Lang/ANSI-BASIC/Brazilian-numbers new file mode 120000 index 0000000000..b5ea63630e --- /dev/null +++ b/Lang/ANSI-BASIC/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/ANSI-BASIC \ No newline at end of file diff --git a/Lang/APL/Duffinian-numbers b/Lang/APL/Duffinian-numbers new file mode 120000 index 0000000000..da1810e24a --- /dev/null +++ b/Lang/APL/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/ADFGVX-cipher b/Lang/ARM-Assembly/ADFGVX-cipher new file mode 120000 index 0000000000..acb7dd15a4 --- /dev/null +++ b/Lang/ARM-Assembly/ADFGVX-cipher @@ -0,0 +1 @@ +../../Task/ADFGVX-cipher/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Bioinformatics-base-count b/Lang/ARM-Assembly/Bioinformatics-base-count new file mode 120000 index 0000000000..baff8c16a9 --- /dev/null +++ b/Lang/ARM-Assembly/Bioinformatics-base-count @@ -0,0 +1 @@ +../../Task/Bioinformatics-base-count/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Count-occurrences-of-a-substring b/Lang/ARM-Assembly/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..e3696ad70d --- /dev/null +++ b/Lang/ARM-Assembly/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Jewels-and-stones b/Lang/ARM-Assembly/Jewels-and-stones new file mode 120000 index 0000000000..629d907643 --- /dev/null +++ b/Lang/ARM-Assembly/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Letter-frequency b/Lang/ARM-Assembly/Letter-frequency new file mode 120000 index 0000000000..16abb3b275 --- /dev/null +++ b/Lang/ARM-Assembly/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/String-case b/Lang/ARM-Assembly/String-case new file mode 120000 index 0000000000..08688552ec --- /dev/null +++ b/Lang/ARM-Assembly/String-case @@ -0,0 +1 @@ +../../Task/String-case/ARM-Assembly \ No newline at end of file diff --git a/Lang/AWK/00-LANG.txt b/Lang/AWK/00-LANG.txt index 1ae6ff2ef6..8c5a32efdd 100644 --- a/Lang/AWK/00-LANG.txt +++ b/Lang/AWK/00-LANG.txt @@ -26,7 +26,7 @@ A few decades later, Kernighan continues to maintain the [[nawk|reference implem *[http://awk.info AWK Community Portal] ==Online-Execution== -* [http://ideone.com ideone.com] - gawk, mawk (both are kept up to date) +* [https://ideone.com ideone.com] - gawk, mawk (both are kept up to date) ==Todo== -[[Reports:Tasks_not_implemented_in_AWK]] \ No newline at end of file +[[Tasks_not_implemented_in_AWK]] \ No newline at end of file diff --git a/Lang/AppleScript/Sorting-algorithms-Strand-sort b/Lang/AppleScript/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..b6b771e075 --- /dev/null +++ b/Lang/AppleScript/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Cartesian-product-of-two-or-more-lists b/Lang/Applesoft-BASIC/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..199613d315 --- /dev/null +++ b/Lang/Applesoft-BASIC/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/McNuggets-problem b/Lang/Applesoft-BASIC/McNuggets-problem new file mode 120000 index 0000000000..6db3b9c1b1 --- /dev/null +++ b/Lang/Applesoft-BASIC/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Permutations b/Lang/Applesoft-BASIC/Permutations new file mode 120000 index 0000000000..05f071bf7d --- /dev/null +++ b/Lang/Applesoft-BASIC/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Asymptote/McNuggets-problem b/Lang/Asymptote/McNuggets-problem new file mode 120000 index 0000000000..3a4a3bc974 --- /dev/null +++ b/Lang/Asymptote/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Asymptote \ No newline at end of file diff --git a/Lang/BASIC/Chaocipher b/Lang/BASIC/Chaocipher new file mode 120000 index 0000000000..634a8f59a4 --- /dev/null +++ b/Lang/BASIC/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Magnanimous-numbers b/Lang/BASIC/Magnanimous-numbers new file mode 120000 index 0000000000..9eb654340c --- /dev/null +++ b/Lang/BASIC/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Cartesian-product-of-two-or-more-lists b/Lang/BASIC256/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..4e3c13585b --- /dev/null +++ b/Lang/BASIC256/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Damm-algorithm b/Lang/BASIC256/Damm-algorithm new file mode 120000 index 0000000000..9a4557a341 --- /dev/null +++ b/Lang/BASIC256/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Digital-root b/Lang/BASIC256/Digital-root new file mode 120000 index 0000000000..499e6c27a3 --- /dev/null +++ b/Lang/BASIC256/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/McNuggets-problem b/Lang/BASIC256/McNuggets-problem new file mode 120000 index 0000000000..9fb9d7be2d --- /dev/null +++ b/Lang/BASIC256/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/BASIC256 \ No newline at end of file diff --git a/Lang/BCPL/Duffinian-numbers b/Lang/BCPL/Duffinian-numbers new file mode 120000 index 0000000000..c8e35dac97 --- /dev/null +++ b/Lang/BCPL/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/BCPL \ No newline at end of file diff --git a/Lang/BCPL/Magnanimous-numbers b/Lang/BCPL/Magnanimous-numbers new file mode 120000 index 0000000000..20df81cce1 --- /dev/null +++ b/Lang/BCPL/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/BCPL \ No newline at end of file diff --git a/Lang/BQN/00-LANG.txt b/Lang/BQN/00-LANG.txt index 5a9029cbd2..e77f39a3a0 100644 --- a/Lang/BQN/00-LANG.txt +++ b/Lang/BQN/00-LANG.txt @@ -7,6 +7,6 @@ |safety=safe |bnf=https://mlochbaum.github.io/BQN/spec/grammar.html}}{{language programming paradigm|functional}}[[Category:Programming paradigm/Tacit]] -BQN is a new [[wp:Array programming|array oriented]], [[functional_programming|functional]] programming language in the [[APL]] lineage, which aims to remove irregular and burdensome aspects of the APL tradition and put the great ideas on a firmer footing. While its use demands a solid understanding of functions and multidimensional arrays, BQN's focus on providing simple, consistent, and powerful array operations (and documentation!) makes it a good language for learning array programming and building stronger array intuition. +BQN is a new (initially released 2020) [[wp:Array programming|array oriented]], [[functional_programming|functional]] programming language in the [[APL]] lineage, which aims to remove irregular and burdensome aspects of the APL tradition and put the great ideas on a firmer footing. While its use demands a solid understanding of functions and multidimensional arrays, BQN's focus on providing simple, consistent, and powerful array operations (and documentation!) makes it a good language for learning array programming and building stronger array intuition. Documentation can be found at https://mlochbaum.github.io/BQN. \ No newline at end of file diff --git a/Lang/BQN/Munching-squares b/Lang/BQN/Munching-squares new file mode 120000 index 0000000000..1ef4cb44d9 --- /dev/null +++ b/Lang/BQN/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/BQN \ No newline at end of file diff --git a/Lang/Babel/00-LANG.txt b/Lang/Babel/00-LANG.txt index c41d0351b4..bf16b12a25 100644 --- a/Lang/Babel/00-LANG.txt +++ b/Lang/Babel/00-LANG.txt @@ -1,4 +1,6 @@ {{alertbox|#ffffe0|''Were you looking for the [[Common Lisp]] library? That category has now been [[:Category:Babel (library)|renamed]].''}} -{{language}}[https://github.com/claytonkb/clean_babel Babel] is an interpreted language designed by Clayton Bauman. It is an untyped, stack-based, postfix language with support for arrays, lists, matrices and maps (dictionaries). Babel 1.0 will support built-in crypto-based verification of code in order to enable safer remote code execution. +{{language}} +{{language programming paradigm|concatenative}} +[https://gitlab.com/claytonkb/Babel Babel] is an interpreted language designed by Clayton Bauman. It is an untyped, stack-based, postfix language with support for arrays, lists, matrices and maps (dictionaries). Babel 1.0 will support built-in crypto-based verification of code in order to enable safer remote code execution. Babel is implemented in [[C]] and compiles with MinGW32. It is still under development, so please excuse the dust and debris in the current implementation. To get started quickly on Windows, clone the repository and run bin/babel.exe from the repo directory. This will start Babel in interactive mode and the examples given on RC are for interactive mode, unless otherwise noted. Since this is a development build, you can type '0 dev' to view the dev options. To build on Windows, use MinGW32; on Linux, use gcc. \ No newline at end of file diff --git a/Lang/Bc/Mandelbrot-set b/Lang/Bc/Mandelbrot-set new file mode 120000 index 0000000000..4b8fac7b05 --- /dev/null +++ b/Lang/Bc/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Bc \ No newline at end of file diff --git a/Lang/Bc/Zeckendorf-number-representation b/Lang/Bc/Zeckendorf-number-representation new file mode 120000 index 0000000000..f3a1eeba63 --- /dev/null +++ b/Lang/Bc/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Bc \ No newline at end of file diff --git a/Lang/Blue/00-LANG.txt b/Lang/Blue/00-LANG.txt index 32b7a80de4..c95d4ccb01 100644 --- a/Lang/Blue/00-LANG.txt +++ b/Lang/Blue/00-LANG.txt @@ -3,6 +3,7 @@ |site=https://github.com/jbirddog/blue |gc=no |untyped=yes}} +{{language programming paradigm|concatenative}} Blue is a compiled low level [[Forth]]-like language that is designed for building programs without a standard library. Currently the x86-64 instruction set is supported. Example programs utilize Linux system calls but nothing in the language requires or assumes an operating system. diff --git a/Lang/C++/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/C++/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..f464173750 --- /dev/null +++ b/Lang/C++/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k @@ -0,0 +1 @@ +../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C++ \ No newline at end of file diff --git a/Lang/C++/Cullen-and-Woodall-numbers b/Lang/C++/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..d42755d636 --- /dev/null +++ b/Lang/C++/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/C++ \ No newline at end of file diff --git a/Lang/C++/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/C++/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..908d4e7ad6 --- /dev/null +++ b/Lang/C++/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/C++ \ No newline at end of file diff --git a/Lang/C++/Graph-colouring b/Lang/C++/Graph-colouring new file mode 120000 index 0000000000..8c4ffa4219 --- /dev/null +++ b/Lang/C++/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/C++ \ No newline at end of file diff --git a/Lang/C++/Knapsack-problem-Unbounded b/Lang/C++/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..9f78e2dcbd --- /dev/null +++ b/Lang/C++/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/C++ \ No newline at end of file diff --git a/Lang/C++/Levenshtein-distance-Alignment b/Lang/C++/Levenshtein-distance-Alignment new file mode 120000 index 0000000000..7c11f353ab --- /dev/null +++ b/Lang/C++/Levenshtein-distance-Alignment @@ -0,0 +1 @@ +../../Task/Levenshtein-distance-Alignment/C++ \ No newline at end of file diff --git a/Lang/C++/Long-literals-with-continuations b/Lang/C++/Long-literals-with-continuations new file mode 120000 index 0000000000..911214b251 --- /dev/null +++ b/Lang/C++/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/C++ \ No newline at end of file diff --git a/Lang/C++/Loops-Wrong-ranges b/Lang/C++/Loops-Wrong-ranges new file mode 120000 index 0000000000..96b90678c9 --- /dev/null +++ b/Lang/C++/Loops-Wrong-ranges @@ -0,0 +1 @@ +../../Task/Loops-Wrong-ranges/C++ \ No newline at end of file diff --git a/Lang/C++/MD4 b/Lang/C++/MD4 new file mode 120000 index 0000000000..403f4ef081 --- /dev/null +++ b/Lang/C++/MD4 @@ -0,0 +1 @@ +../../Task/MD4/C++ \ No newline at end of file diff --git a/Lang/C++/Magic-constant b/Lang/C++/Magic-constant new file mode 120000 index 0000000000..442fba4633 --- /dev/null +++ b/Lang/C++/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/C++ \ No newline at end of file diff --git a/Lang/C++/Matrix-chain-multiplication b/Lang/C++/Matrix-chain-multiplication new file mode 120000 index 0000000000..dd51839476 --- /dev/null +++ b/Lang/C++/Matrix-chain-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-chain-multiplication/C++ \ No newline at end of file diff --git a/Lang/C++/Mayan-calendar b/Lang/C++/Mayan-calendar new file mode 120000 index 0000000000..3283cc776d --- /dev/null +++ b/Lang/C++/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/C++ \ No newline at end of file diff --git a/Lang/C++/Mayan-numerals b/Lang/C++/Mayan-numerals new file mode 120000 index 0000000000..b2152a3f38 --- /dev/null +++ b/Lang/C++/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/C++ \ No newline at end of file diff --git a/Lang/C++/McNuggets-problem b/Lang/C++/McNuggets-problem new file mode 120000 index 0000000000..26315fdf5f --- /dev/null +++ b/Lang/C++/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/C++ \ No newline at end of file diff --git a/Lang/C++/Meissel-Mertens-constant b/Lang/C++/Meissel-Mertens-constant new file mode 120000 index 0000000000..3242c970c7 --- /dev/null +++ b/Lang/C++/Meissel-Mertens-constant @@ -0,0 +1 @@ +../../Task/Meissel-Mertens-constant/C++ \ No newline at end of file diff --git a/Lang/C++/Metronome b/Lang/C++/Metronome new file mode 120000 index 0000000000..64cb1fbb2c --- /dev/null +++ b/Lang/C++/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/C++ \ No newline at end of file diff --git a/Lang/C++/Miller-Rabin-primality-test b/Lang/C++/Miller-Rabin-primality-test new file mode 120000 index 0000000000..615ee001e8 --- /dev/null +++ b/Lang/C++/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/C++ \ No newline at end of file diff --git a/Lang/C++/Mind-boggling-card-trick b/Lang/C++/Mind-boggling-card-trick new file mode 120000 index 0000000000..2a21de96ed --- /dev/null +++ b/Lang/C++/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/C++ \ No newline at end of file diff --git a/Lang/C++/Minimal-steps-down-to-1 b/Lang/C++/Minimal-steps-down-to-1 new file mode 120000 index 0000000000..024c7cb7fa --- /dev/null +++ b/Lang/C++/Minimal-steps-down-to-1 @@ -0,0 +1 @@ +../../Task/Minimal-steps-down-to-1/C++ \ No newline at end of file diff --git a/Lang/C++/Minkowski-question-mark-function b/Lang/C++/Minkowski-question-mark-function new file mode 120000 index 0000000000..b52b1b784c --- /dev/null +++ b/Lang/C++/Minkowski-question-mark-function @@ -0,0 +1 @@ +../../Task/Minkowski-question-mark-function/C++ \ No newline at end of file diff --git a/Lang/C++/Modified-random-distribution b/Lang/C++/Modified-random-distribution new file mode 120000 index 0000000000..216ea99a69 --- /dev/null +++ b/Lang/C++/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/C++ \ No newline at end of file diff --git a/Lang/C++/Mouse-position b/Lang/C++/Mouse-position new file mode 120000 index 0000000000..a68146f1b0 --- /dev/null +++ b/Lang/C++/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/C++ \ No newline at end of file diff --git a/Lang/C++/Numbers-which-are-not-the-sum-of-distinct-squares b/Lang/C++/Numbers-which-are-not-the-sum-of-distinct-squares new file mode 120000 index 0000000000..0383a88d34 --- /dev/null +++ b/Lang/C++/Numbers-which-are-not-the-sum-of-distinct-squares @@ -0,0 +1 @@ +../../Task/Numbers-which-are-not-the-sum-of-distinct-squares/C++ \ No newline at end of file diff --git a/Lang/C++/OpenWebNet-password b/Lang/C++/OpenWebNet-password new file mode 120000 index 0000000000..8ebe3bb3ea --- /dev/null +++ b/Lang/C++/OpenWebNet-password @@ -0,0 +1 @@ +../../Task/OpenWebNet-password/C++ \ No newline at end of file diff --git a/Lang/C++/Padovan-n-step-number-sequences b/Lang/C++/Padovan-n-step-number-sequences new file mode 120000 index 0000000000..7ac07bcd12 --- /dev/null +++ b/Lang/C++/Padovan-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Padovan-n-step-number-sequences/C++ \ No newline at end of file diff --git a/Lang/C++/Paraffins b/Lang/C++/Paraffins new file mode 120000 index 0000000000..97f2318ced --- /dev/null +++ b/Lang/C++/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/C++ \ No newline at end of file diff --git a/Lang/C++/Pentomino-tiling b/Lang/C++/Pentomino-tiling new file mode 120000 index 0000000000..ed8fbc82bd --- /dev/null +++ b/Lang/C++/Pentomino-tiling @@ -0,0 +1 @@ +../../Task/Pentomino-tiling/C++ \ No newline at end of file diff --git a/Lang/C++/Periodic-table b/Lang/C++/Periodic-table new file mode 120000 index 0000000000..ed19cc1b0e --- /dev/null +++ b/Lang/C++/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/C++ \ No newline at end of file diff --git a/Lang/C++/Perlin-noise b/Lang/C++/Perlin-noise new file mode 120000 index 0000000000..7b0cb9e4f7 --- /dev/null +++ b/Lang/C++/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/C++ \ No newline at end of file diff --git a/Lang/C++/Permutations-Derangements b/Lang/C++/Permutations-Derangements new file mode 120000 index 0000000000..bd96da6362 --- /dev/null +++ b/Lang/C++/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/C++ \ No newline at end of file diff --git a/Lang/C++/Permutations-Rank-of-a-permutation b/Lang/C++/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..8154150665 --- /dev/null +++ b/Lang/C++/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/C++ \ No newline at end of file diff --git a/Lang/C++/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/C++/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..3fdfaf7ab6 --- /dev/null +++ b/Lang/C++/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/C++ \ No newline at end of file diff --git a/Lang/C++/Problem-of-Apollonius b/Lang/C++/Problem-of-Apollonius new file mode 120000 index 0000000000..7195179aa2 --- /dev/null +++ b/Lang/C++/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/C++ \ No newline at end of file diff --git a/Lang/C++/Radical-of-an-integer b/Lang/C++/Radical-of-an-integer new file mode 120000 index 0000000000..4918741eda --- /dev/null +++ b/Lang/C++/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/C++ \ No newline at end of file diff --git a/Lang/C++/Sisyphus-sequence b/Lang/C++/Sisyphus-sequence new file mode 120000 index 0000000000..9d0b48977f --- /dev/null +++ b/Lang/C++/Sisyphus-sequence @@ -0,0 +1 @@ +../../Task/Sisyphus-sequence/C++ \ No newline at end of file diff --git a/Lang/CLU/Magnanimous-numbers b/Lang/CLU/Magnanimous-numbers new file mode 120000 index 0000000000..58e31b3004 --- /dev/null +++ b/Lang/CLU/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/CLU \ No newline at end of file diff --git a/Lang/COBOL/00-LANG.txt b/Lang/COBOL/00-LANG.txt index b08d403c2d..f233e74072 100644 --- a/Lang/COBOL/00-LANG.txt +++ b/Lang/COBOL/00-LANG.txt @@ -12,12 +12,15 @@ COBOL, an acronym for 'COmmon Business Oriented Language', is one of the oldest programming languages, being created in 1959. It was designed by a CODASYL (Conference on Data System Languages) committee with Grace Hopper. It is primarily used in business, finance and administration for companies and governments. It is primarily an imperative, structured language, with support for object-oriented programming added in 2002. ===Versions=== -* '''COBOL 1965''' added some new features to the original specification. -* '''ANS COBOL 1968''' is the first COBOL standard and was published by [[ANSI]]. It was created to improve compatibility between the different versions of the language. -* '''COBOL 1974''' added a few more features to the language, including the ability to ACCEPT the date, day and time, and the file organization clause. -* '''COBOL 1985''' added many new features to COBOL, notably including: scope terminators (END-IF, END-READ, etc.), the EVALUATE verb, the CONTINUE verb, inline PERFORM statements, the ability to pass arguments by content, and the deprecation of the infamous ALTER verb. This standard was followed by the intrinsic functions amendment and a clarifications amendment in 1989 and 1991, respectively. -* '''COBOL 2002''' was published by [[ISO]] as ISO/IEC 1989. It included a host of new features, most notably including object-oriented programming. However, there were also other features, including: floating-point support, portable arithmetic results, pointers, calling conventions to other languages, function prototypes, [[XML]] facilities and support for execution within framework environments. This standard has suffered from poor vendor support, due to little commercial demand for the new features.John Billman & Huib Klink, 'Thoughts on the Future of COBOL Standardization', [https://www.cobolstandard.info/j4/files/08-0034.pdf] -* '''COBOL 2014''' is the latest version of the standard, published on July 8th, 2014 and accepted by [[ISO]] early that summer, and then adopted by [[ANSI]] on Oct 31st, 2014. ISO/IEC 1989:2014 Information technology – Programming languages, their environments and system software interfaces – Programming language COBOL', [https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=51416] It includes numeric definitions following the [[IEEE]] 754 standard. +* '''COBOL 60''' was the first version of the language. +* '''COBOL-65''' added some new features to the original specification. +* '''COBOL-68''' is the first COBOL standard and was published by [[ANSI]]. It was created to improve compatibility between the different versions of the language. +* '''COBOL-74''' added a few more features to the language, including the ability to ACCEPT the date, day and time, and the file organization clause. +* '''COBOL-85''' added many new features to COBOL, notably including: excplicit scope terminators (END-IF, END-READ, etc.), the EVALUATE verb, the CONTINUE verb, inline PERFORM statements, the ability to pass arguments by content, and the deprecation of the infamous ALTER verb. This standard was followed by the intrinsic functions amendment and a clarifications amendment in 1989 and 1991, respectively. +* '''X/Open COBOL''' was a technical standard published by the X/Open Group in 1991 to facilitate uniformity of implementations and program portability. Based on COBOL-85, it excluded much of its optional modules and obsolete features, and also specified some common non-ANSI extensions that would later become incorporated into the standard, such as the screen section for TUI programming, and record locking.{{Cite book|author=X/Open|title=Technical Standard: COBOL Language|url=https://pubs.opengroup.org/onlinepubs/009680799/toc.pdf}} +* '''COBOL 2002''' was published by [[ISO]] as ISO/IEC 1989. It included a host of new features, most notably including object-oriented programming. However, there were also other features, including: floating-point support, portable arithmetic results, pointers, calling conventions to other languages, function prototypes, [[XML]] facilities and support for execution within framework environments. This standard has suffered from poor vendor support, due to little commercial demand for the new features.{{Cite book|author=John Billman & Huib Klink|title=Thoughts on the Future of COBOL Standardization|url=https://web.archive.org/web/20090711032647/http://www.cobolstandard.info/j4/files/08-0034.pdf}} +* '''COBOL 2014''' was published on July 8th, 2014 and accepted by [[ISO]] early that summer, and then adopted by [[ANSI]] on Oct 31st, 2014.{{Cite book|title=ISO/IEC 1989:2014 Information technology – Programming languages, their environments and system software interfaces – Programming language COBOL|url=https://www.iso.org/iso/home/store/catalogue_tc/catalogue_detail.htm?csnumber=51416}} It includes numeric definitions following the [[IEEE]] 754 standard. +* '''COBOL 2023''' is the latest version of the standard, adopted in January 2023. It includes the standardizations of many previously nonstandard extensions, including transaction processing, asynchronous messaging, line sequential file organization, enhanced string manipulation, boolean shifting operators and a sleep statement. ===References=== diff --git a/Lang/Chipmunk-Basic/Cartesian-product-of-two-or-more-lists b/Lang/Chipmunk-Basic/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..ad9ddbf01c --- /dev/null +++ b/Lang/Chipmunk-Basic/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Draw-a-rotating-cube b/Lang/Chipmunk-Basic/Draw-a-rotating-cube new file mode 120000 index 0000000000..b24865ccdc --- /dev/null +++ b/Lang/Chipmunk-Basic/Draw-a-rotating-cube @@ -0,0 +1 @@ +../../Task/Draw-a-rotating-cube/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Feigenbaum-constant-calculation b/Lang/Chipmunk-Basic/Feigenbaum-constant-calculation new file mode 120000 index 0000000000..9738d507b3 --- /dev/null +++ b/Lang/Chipmunk-Basic/Feigenbaum-constant-calculation @@ -0,0 +1 @@ +../../Task/Feigenbaum-constant-calculation/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Gapful-numbers b/Lang/Chipmunk-Basic/Gapful-numbers new file mode 120000 index 0000000000..62261c33f8 --- /dev/null +++ b/Lang/Chipmunk-Basic/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/McNuggets-problem b/Lang/Chipmunk-Basic/McNuggets-problem new file mode 120000 index 0000000000..6e8e21fec0 --- /dev/null +++ b/Lang/Chipmunk-Basic/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Chipmunk-Basic/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors b/Lang/Chipmunk-Basic/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors new file mode 120000 index 0000000000..1a4494cec0 --- /dev/null +++ b/Lang/Chipmunk-Basic/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors @@ -0,0 +1 @@ +../../Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/Chipmunk-Basic \ No newline at end of file diff --git a/Lang/Cowgol/Magnanimous-numbers b/Lang/Cowgol/Magnanimous-numbers new file mode 120000 index 0000000000..fec44e9f41 --- /dev/null +++ b/Lang/Cowgol/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/Cowgol \ No newline at end of file diff --git a/Lang/Craft-Basic/Almost-prime b/Lang/Craft-Basic/Almost-prime new file mode 120000 index 0000000000..837e60bb02 --- /dev/null +++ b/Lang/Craft-Basic/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Craft-Basic \ No newline at end of file diff --git a/Lang/Craft-Basic/Averages-Median b/Lang/Craft-Basic/Averages-Median new file mode 120000 index 0000000000..6ffc8a044e --- /dev/null +++ b/Lang/Craft-Basic/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Craft-Basic \ No newline at end of file diff --git a/Lang/Craft-Basic/Loops-Infinite b/Lang/Craft-Basic/Loops-Infinite new file mode 120000 index 0000000000..186bbe7bcc --- /dev/null +++ b/Lang/Craft-Basic/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Craft-Basic \ No newline at end of file diff --git a/Lang/Craft-Basic/Wagstaff-primes b/Lang/Craft-Basic/Wagstaff-primes new file mode 120000 index 0000000000..93b06b7da0 --- /dev/null +++ b/Lang/Craft-Basic/Wagstaff-primes @@ -0,0 +1 @@ +../../Task/Wagstaff-primes/Craft-Basic \ No newline at end of file diff --git a/Lang/D/Own-digits-power-sum b/Lang/D/Own-digits-power-sum new file mode 120000 index 0000000000..937ef98bff --- /dev/null +++ b/Lang/D/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/D \ No newline at end of file diff --git a/Lang/Dc/Arithmetic-geometric-mean b/Lang/Dc/Arithmetic-geometric-mean new file mode 120000 index 0000000000..a4f9246885 --- /dev/null +++ b/Lang/Dc/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Dc \ No newline at end of file diff --git a/Lang/Dc/Continued-fraction b/Lang/Dc/Continued-fraction new file mode 120000 index 0000000000..d81af848ce --- /dev/null +++ b/Lang/Dc/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Dc \ No newline at end of file diff --git a/Lang/Dc/Increment-a-numerical-string b/Lang/Dc/Increment-a-numerical-string new file mode 120000 index 0000000000..946a96ac1a --- /dev/null +++ b/Lang/Dc/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Dc \ No newline at end of file diff --git a/Lang/Dc/Sieve-of-Eratosthenes b/Lang/Dc/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ac1e159057 --- /dev/null +++ b/Lang/Dc/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Dc \ No newline at end of file diff --git a/Lang/Draco/Duffinian-numbers b/Lang/Draco/Duffinian-numbers new file mode 120000 index 0000000000..ffc5f5f29b --- /dev/null +++ b/Lang/Draco/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Draco \ No newline at end of file diff --git a/Lang/Draco/Magnanimous-numbers b/Lang/Draco/Magnanimous-numbers new file mode 120000 index 0000000000..8cea312423 --- /dev/null +++ b/Lang/Draco/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/Draco \ No newline at end of file diff --git a/Lang/Draco/Yin-and-yang b/Lang/Draco/Yin-and-yang new file mode 120000 index 0000000000..77445e0f51 --- /dev/null +++ b/Lang/Draco/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Draco \ No newline at end of file diff --git a/Lang/Dt/00-LANG.txt b/Lang/Dt/00-LANG.txt new file mode 100644 index 0000000000..334761ebe6 --- /dev/null +++ b/Lang/Dt/00-LANG.txt @@ -0,0 +1,5 @@ +{{stub}} +{{language|dt|site=https://dt.plumbing/|tags=dt}} +{{Language programming paradigm|Concatenative}} + +"dt is duct tape for your Unix pipes. A programming language for doing small stuff fast, easy, and readable." \ No newline at end of file diff --git a/Lang/Dt/00-META.yaml b/Lang/Dt/00-META.yaml new file mode 100644 index 0000000000..9d58ae2101 --- /dev/null +++ b/Lang/Dt/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Dt diff --git a/Lang/Dt/Array-length b/Lang/Dt/Array-length new file mode 120000 index 0000000000..8bf9a963d9 --- /dev/null +++ b/Lang/Dt/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/Dt \ No newline at end of file diff --git a/Lang/Dt/Binary-digits b/Lang/Dt/Binary-digits new file mode 120000 index 0000000000..8249525c7c --- /dev/null +++ b/Lang/Dt/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Dt \ No newline at end of file diff --git a/Lang/Dt/Greatest-common-divisor b/Lang/Dt/Greatest-common-divisor new file mode 120000 index 0000000000..4c746aac43 --- /dev/null +++ b/Lang/Dt/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Dt \ No newline at end of file diff --git a/Lang/Dt/Hello-world-Newline-omission b/Lang/Dt/Hello-world-Newline-omission new file mode 120000 index 0000000000..3620ed3017 --- /dev/null +++ b/Lang/Dt/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Dt \ No newline at end of file diff --git a/Lang/Dt/Hello-world-Standard-error b/Lang/Dt/Hello-world-Standard-error new file mode 120000 index 0000000000..697f7d4651 --- /dev/null +++ b/Lang/Dt/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Dt \ No newline at end of file diff --git a/Lang/Dt/Hello-world-Text b/Lang/Dt/Hello-world-Text new file mode 120000 index 0000000000..afdb9e5013 --- /dev/null +++ b/Lang/Dt/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Dt \ No newline at end of file diff --git a/Lang/Dt/Increment-a-numerical-string b/Lang/Dt/Increment-a-numerical-string new file mode 120000 index 0000000000..975bccc02f --- /dev/null +++ b/Lang/Dt/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Dt \ No newline at end of file diff --git a/Lang/Dt/Phrase-reversals b/Lang/Dt/Phrase-reversals new file mode 120000 index 0000000000..4f2999eeab --- /dev/null +++ b/Lang/Dt/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Dt \ No newline at end of file diff --git a/Lang/Dt/Program-termination b/Lang/Dt/Program-termination new file mode 120000 index 0000000000..2132c13c46 --- /dev/null +++ b/Lang/Dt/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Dt \ No newline at end of file diff --git a/Lang/Dt/Reverse-a-string b/Lang/Dt/Reverse-a-string new file mode 120000 index 0000000000..305497c558 --- /dev/null +++ b/Lang/Dt/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Dt \ No newline at end of file diff --git a/Lang/Dt/Tokenize-a-string b/Lang/Dt/Tokenize-a-string new file mode 120000 index 0000000000..c12dc3ceea --- /dev/null +++ b/Lang/Dt/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Dt \ No newline at end of file diff --git a/Lang/EasyLang/00-LANG.txt b/Lang/EasyLang/00-LANG.txt index e4d3b910bf..aa156f93c8 100644 --- a/Lang/EasyLang/00-LANG.txt +++ b/Lang/EasyLang/00-LANG.txt @@ -13,4 +13,7 @@ [https://easylang.dev/ide/ A browser IDE] with different tutorials, one for beginners, makes programming and learning to program as easy as possible. -The finished programs can be easily integrated into a [https://easylang.dev/apps/ website]. \ No newline at end of file +The finished programs can be easily integrated into a [https://easylang.dev/apps/ website]. + +==Todo== +[[Tasks not implemented in EasyLang]] \ No newline at end of file diff --git a/Lang/Elixir/Arithmetic-evaluation b/Lang/Elixir/Arithmetic-evaluation new file mode 120000 index 0000000000..421d00b13e --- /dev/null +++ b/Lang/Elixir/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Continued-fraction b/Lang/Elixir/Continued-fraction new file mode 120000 index 0000000000..03e2722a4e --- /dev/null +++ b/Lang/Elixir/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Elixir \ No newline at end of file diff --git a/Lang/Elm/ABC-problem b/Lang/Elm/ABC-problem new file mode 120000 index 0000000000..9dc41045b3 --- /dev/null +++ b/Lang/Elm/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Elm \ No newline at end of file diff --git a/Lang/Evaldraw/00-LANG.txt b/Lang/Evaldraw/00-LANG.txt new file mode 100644 index 0000000000..5031d48124 --- /dev/null +++ b/Lang/Evaldraw/00-LANG.txt @@ -0,0 +1,102 @@ + +{{language +|exec=machine +|gc=no +|safety=unsafe +|parampass=value +|checking=static +|strength=weak +|tags=c +}}{{language programming paradigm|Imperative}} + +'''EVALDRAW''' is a quirky little programming tool that can be used to make small applications and games, or even do 1D, 2D or 3D graphs, or create custom musical instruments. +Evaldraw is technically a tool and not the language, however, since RSCRIPT and Evaldraw are tied together, we can consider Evaldraw a programming language in itself. From this point, this article will refer to the capabilities of RSCRIPT and Evaldraw together. + +==Compiler modes== + +* '''EVAL''' the initially bundled compiler, developed by Ken Silverman. Had only doubles and arrays of doubles. +* '''RSCRIPT''' added in 2010 and created by Robert Rodgers. Added support for structs, making entities to handle. Easier to translate to C. + +==Overview== + +Evaldraw has syntax similar to C. + +===Curly Braces=== + +EVALDRAW supports grouping multiple statements in curly braces. They are not needed for single statements. + +===Semicolons=== + +All statements, except for the last statement in a function must end with a semicolon; + +===Functions=== + +Functions all return an implicit double value from the last statement in the function. +Parameters passed to functions can be doubles, arrays or structs. + +===Statements=== + +The following statements are supported: +* IF and IF-ELSE (but no SWITCH-case) +* Loop constructs such as DO{ codeblock }WHILE(condition); WHILE(cond){ block } and the FOR-loop as in C. +* goto label and label: declaration similar to C. +* a RETURN statement can at any point in a function return a floating point number. The last value is implicitly returned. +* BREAK and CONTINUE statements. Loops can be exited with BREAK, or remainder of code body can be skipped with CONTINUE. +* ENUMs allow the programmer to give numerical constants names. Dependencies between enum values are possible, allowing the programmer to make one enum a calculation based on previous enum values. +* Variables can be declared automatically on the local stack, or using the STATIC modifier to make a variable global. + +===Case insensitive=== +All names and keywords are case insensitive. This can create some confusion when porting from- or to C. + +===All you need is 64-bit float=== + +All variables, also those declared in structs are double. If no type is supplied, double is assumed. +All functions return a double. + +===Arrays=== +Arrays that are power of two are wrapped, non power-of-two arrays set index zero if accessed out of bounds. +For example, if we define static xcoords[4]; and try to access xcoords[5] we the returned value is at index 5%4 which is xcoords[1]. + +===Structs=== +Structs can be declared and be passed as function parameters. +A struct may doubles, arrays of doubles and other structs. + +For example struct vec{x,y,z;}; defines a struct with 3 fields. +struct boid_t{ vec pos; vec dir; } defines a struct that contains substructs pos and dir. + +===Pass by value or pass by ref=== +Doubles are passed by value, but can be passed by ref by prefixing a & symbol. +All other variables, arrays and structs are passed by ref. + +===Builtins=== +There are many built in functions. +The EVAL and RSCRIPT compiler modes support the following 1-param functions: +* ABS - gives the absolute value. Same as fabs in C. +* ACOS - arcos in radians +* ASIN - arsin in radians +* ATAN - arctan in radians +* ATN - alias for atan +* CEIL - round a value up to nearest integer. +* COS - cosine in radians +* EXP - raise Eulers number to some power. EXP(1) = 2.718281 +* FABS - alias for ABS +* FACT - factorial. FACT(5) = 5! +* FLOOR - round a value down to nearest integer. +* INT - different from floor, truncates (removes decimals). +* LOG - returns the natural logarithm of x. LOG(x) = ln(x) +* SGN - returns the sign of a number. -1, 0 or +1 +* SIN - sine in radians +* SQRT - square root +* TAN - tan in radians +* UNIT - returns the unit function of x. Returns 0.0 for x<0, 0.5 for x==0 and 1.0 for x>0. + +And the following two param functions: +* ATAN2(x,y) - gives angle in radians from positive x-axis to some point x,y. +* FADD - eval and rscript compatibility. +* FMOD - alternative to modulus % operator. +* LOG(x,b) - return log of x with base b. +* MIN(a,b) - return smallest +* MAX(a,b) - return largest +* POW(a,b) - raise a to power b + +There is no concept of include statements or libraries. It is assumed evaldraw programs are small scripts to try out ideas that later will be integrated into a professional programming language such as C. \ No newline at end of file diff --git a/Lang/Evaldraw/00-META.yaml b/Lang/Evaldraw/00-META.yaml new file mode 100644 index 0000000000..4dff698a21 --- /dev/null +++ b/Lang/Evaldraw/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Evaldraw diff --git a/Lang/Evaldraw/Bitmap-Midpoint-circle-algorithm b/Lang/Evaldraw/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..732c70e6bd --- /dev/null +++ b/Lang/Evaldraw/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Brownian-tree b/Lang/Evaldraw/Brownian-tree new file mode 120000 index 0000000000..0f66f104b4 --- /dev/null +++ b/Lang/Evaldraw/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Draw-a-cuboid b/Lang/Evaldraw/Draw-a-cuboid new file mode 120000 index 0000000000..ad6b9a59e0 --- /dev/null +++ b/Lang/Evaldraw/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Draw-a-pixel b/Lang/Evaldraw/Draw-a-pixel new file mode 120000 index 0000000000..f0b3d6eb37 --- /dev/null +++ b/Lang/Evaldraw/Draw-a-pixel @@ -0,0 +1 @@ +../../Task/Draw-a-pixel/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Draw-a-rotating-cube b/Lang/Evaldraw/Draw-a-rotating-cube new file mode 120000 index 0000000000..db1cc3c9ca --- /dev/null +++ b/Lang/Evaldraw/Draw-a-rotating-cube @@ -0,0 +1 @@ +../../Task/Draw-a-rotating-cube/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Draw-a-sphere b/Lang/Evaldraw/Draw-a-sphere new file mode 120000 index 0000000000..47572e62bb --- /dev/null +++ b/Lang/Evaldraw/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Find-if-a-point-is-within-a-triangle b/Lang/Evaldraw/Find-if-a-point-is-within-a-triangle new file mode 120000 index 0000000000..ba57b42d05 --- /dev/null +++ b/Lang/Evaldraw/Find-if-a-point-is-within-a-triangle @@ -0,0 +1 @@ +../../Task/Find-if-a-point-is-within-a-triangle/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Find-the-intersection-of-a-line-with-a-plane b/Lang/Evaldraw/Find-the-intersection-of-a-line-with-a-plane new file mode 120000 index 0000000000..b0041d3a8e --- /dev/null +++ b/Lang/Evaldraw/Find-the-intersection-of-a-line-with-a-plane @@ -0,0 +1 @@ +../../Task/Find-the-intersection-of-a-line-with-a-plane/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Forest-fire b/Lang/Evaldraw/Forest-fire new file mode 120000 index 0000000000..757c62c9b4 --- /dev/null +++ b/Lang/Evaldraw/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Fractal-tree b/Lang/Evaldraw/Fractal-tree new file mode 120000 index 0000000000..ce7aebb8a5 --- /dev/null +++ b/Lang/Evaldraw/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Munching-squares b/Lang/Evaldraw/Munching-squares new file mode 120000 index 0000000000..ba05ebca80 --- /dev/null +++ b/Lang/Evaldraw/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Perlin-noise b/Lang/Evaldraw/Perlin-noise new file mode 120000 index 0000000000..91b7dec527 --- /dev/null +++ b/Lang/Evaldraw/Perlin-noise @@ -0,0 +1 @@ +../../Task/Perlin-noise/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Sierpinski-triangle-Graphical b/Lang/Evaldraw/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..fd95d1d620 --- /dev/null +++ b/Lang/Evaldraw/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Sutherland-Hodgman-polygon-clipping b/Lang/Evaldraw/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..3381508835 --- /dev/null +++ b/Lang/Evaldraw/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Evaldraw \ No newline at end of file diff --git a/Lang/Evaldraw/Yin-and-yang b/Lang/Evaldraw/Yin-and-yang new file mode 120000 index 0000000000..ba36a16954 --- /dev/null +++ b/Lang/Evaldraw/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Evaldraw \ No newline at end of file diff --git a/Lang/F-Sharp/Kronecker-product b/Lang/F-Sharp/Kronecker-product new file mode 120000 index 0000000000..683005869b --- /dev/null +++ b/Lang/F-Sharp/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Sorting-algorithms-Strand-sort b/Lang/F-Sharp/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..0a9c6a6f0f --- /dev/null +++ b/Lang/F-Sharp/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/F-Sharp \ No newline at end of file diff --git a/Lang/FOCAL/Magic-8-ball b/Lang/FOCAL/Magic-8-ball new file mode 120000 index 0000000000..4e734aa073 --- /dev/null +++ b/Lang/FOCAL/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/FOCAL \ No newline at end of file diff --git a/Lang/Factor/00-LANG.txt b/Lang/Factor/00-LANG.txt index 2eaeb516fd..bb19ed678a 100644 --- a/Lang/Factor/00-LANG.txt +++ b/Lang/Factor/00-LANG.txt @@ -1,6 +1,6 @@ {{language |exec=machine -|site=http://factorcode.org +|site=https://factorcode.org |gc=yes |parampass=reference |safety=safe @@ -12,9 +12,9 @@ |LCT=yes}} Factor is a stack-based, concatenative, general-purpose programming language with a focus on practicality. -Initially developed by Slava Pestov, Factor began life in 2003 as a scripting language written for a game. The implementation was originally an interpreter written in [[Java]], but has since gained an optimizing compiler and has been rewritten in Factor with a minimal [[C++]] core. Read more about Factor's implementation history [http://concatenative.org/wiki/view/Factor/Implementation%20history here]. As of June 2020, Factor is still being developed by several contributors, with the latest [http://re-factor.blogspot.com/2018/07/factor-098-now-available.html stable release] in July 2018. +Initially developed by Slava Pestov, Factor began life in 2003 as a scripting language written for a game. The implementation was originally an interpreter written in [[Java]], but has since gained an optimizing compiler and has been rewritten in Factor with a minimal [[C++]] core. Read more about Factor's implementation history [https://concatenative.org/wiki/view/Factor/Implementation%20history here]. Factor is still being developed by dozens of contributors, with the latest [https://re.factorcode.org/2023/08/factor-0-99-now-available.html stable release] in August 2023. -Factor is a stack language similar to, but of a higher level than, [[Forth]]. Factor is a [http://concatenative.org/wiki/view/Concatenative%20language concatenative language], meaning that rather than applying functions to arguments (applicative languages) to evaluate things, we compose functions to evaluate a single piece of data — the entire program up until that particular point. In Factor, the basic structure of data flow is function composition. That is, foo bar baz is equivalent to baz(bar(foo())) in an applicative language. This offers a nice left-to-right style of reading and data flow. +Factor is a stack language similar to, but of a higher level than, [[Forth]]. Factor is a [https://concatenative.org/wiki/view/Concatenative%20language concatenative language], meaning that rather than applying functions to arguments (applicative languages) to evaluate things, we compose functions to evaluate a single piece of data — the entire program up until that particular point. In Factor, the basic structure of data flow is function composition. That is, foo bar baz is equivalent to baz(bar(foo())) in an applicative language. This offers a nice left-to-right style of reading and data flow. In Factor, we tend to name data flow operations rather than values. In an applicative language, you might write var x = ...; @@ -24,11 +24,11 @@ In Factor this is a data flow pattern called bi. [ foo ] [ bar ] bi This says, "apply foo to the object at the top of the data stack, and apply bar to it as well." Rather than naming the values x, y, and z, we named the data flow pattern. -Factor comes with many practical features, including a REPL, a self-contained help browser, an object inspector, a debugger/code walker, a deployment tool, editor integration for most popular text editors and IDEs, and introspection capabilities useful for developers. Factor has a fully-featured library, including things such as an HTTP server/client, bindings to graphics libraries and databases, a C FFI, a cross-platform GUI framework, on down to niche things like polynomial arithmetic. Factor features an object system that takes inspiration from [[Common Lisp]] and [[Self]]. +Factor comes with many practical features, including a [[Interactive programming (repl)#Factor|REPL]], a self-contained help browser, an object inspector, a debugger/code walker, a deployment tool, editor integration for most popular text editors and [[IDE]]s, and introspection capabilities useful for developers. Factor has a fully-featured library, including things such as an HTTP server/client, bindings to graphics libraries and databases, a [[C]] [[FFI]], a cross-platform [[GUI]] framework, on down to niche things like polynomial arithmetic. Factor features an object system that takes inspiration from [[Common Lisp]] and [[Self]]. Most code tends to be expressed naturally in a functional manner. Factor comes with combinators (higher-order functions) typically seen in functional languages, such as map, filter, reduce, and many more. Although most things can be done efficiently without mutation, Factor doesn't shy away from it when it's useful. Mutating words end with exclamation points (by convention). Factor provides lexical and dynamic variables which can make writing imperative code more natural, or allows one to clean up code that performs a lot of stack shuffling. -One of Factor's greatest strengths is its ability to factor words into smaller words. Due to the nature of concatenative programming, this is typically a cut and paste job that can be done almost anywhere there is whitespace. Factor also has impressive metaprogramming capabilities. Since Factor is almost entirely written in Factor, there is full introspection support, including seamless access to Factor's parser, allowing one to define new syntax. Factor also offers Lisp-style macros, and in general, Factor code can be treated like a collection ([https://en.wikipedia.org/wiki/Homoiconicity homoiconicity]). +One of Factor's greatest strengths is its ability to factor words into smaller words. Due to the nature of [[concatenative programming]], this is typically a cut and paste job that can be done almost anywhere there is whitespace. Factor also has impressive metaprogramming capabilities. Since Factor is almost entirely written in Factor, there is full introspection support, including seamless access to Factor's parser, allowing one to define new syntax. Factor also offers [[Lisp]]-style macros, and in general, Factor code can be treated like a collection ([https://en.wikipedia.org/wiki/Homoiconicity homoiconicity]). ==About Factor examples on Rosetta Code== Most of the newer examples are meant to be copied and pasted directly into the listener (Factor's REPL) where they should run without issue. In order to deploy the examples to binaries or run them as scripts, you'll need to put them in a vocabulary (e.g. IN: myvocab and set a MAIN: word which acts as the entry point for the program. If an example doesn't run, it probably means that the example only works in an older version of Factor. Most of the time, this is because certain words have been changed without maintaining backwards compatibility (e.g. iota became in Factor 0.98). @@ -37,10 +37,13 @@ For this reason, it is advised that examples use the works with tem
{{works with|Factor|0.98}}
becomes {{works with|Factor|0.98}} +==Todo== +[https://rosettacode.org/wiki/Tasks_not_implemented_in_Factor Tasks not implemented in Factor] + ==Links== -*[http://factorcode.org Factor programming language] -*[http://planet.factorcode.org Planet Factor] -*[http://concatenative.org/wiki/view/Factor Factor on concatenative.org] +*[https://factorcode.org Factor programming language] +*[https://planet.factorcode.org Planet Factor] +*[https://concatenative.org/wiki/view/Factor Factor on concatenative.org] *[https://en.wikipedia.org/wiki/Factor_(programming_language) Factor on Wikipedia] {{Language programming paradigm|Concatenative}} \ No newline at end of file diff --git a/Lang/Factor/Brownian-tree b/Lang/Factor/Brownian-tree deleted file mode 120000 index a93650256d..0000000000 --- a/Lang/Factor/Brownian-tree +++ /dev/null @@ -1 +0,0 @@ -../../Task/Brownian-tree/Factor \ No newline at end of file diff --git a/Lang/FreeBASIC/Brilliant-numbers b/Lang/FreeBASIC/Brilliant-numbers new file mode 120000 index 0000000000..0a570d15e7 --- /dev/null +++ b/Lang/FreeBASIC/Brilliant-numbers @@ -0,0 +1 @@ +../../Task/Brilliant-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FutureBasic/00-LANG.txt b/Lang/FutureBasic/00-LANG.txt index e75d6d7fb0..d3dbdba2ec 100644 --- a/Lang/FutureBasic/00-LANG.txt +++ b/Lang/FutureBasic/00-LANG.txt @@ -4,7 +4,7 @@ |safety=safe |parampass=both |exec=machine -|gc=no +|gc=yes |site=http://www.brilorsoftware.com/fb |tags=futurebasic}} {{language programming paradigm|procedural}} @@ -84,4 +84,7 @@ FB has a small but dedicated group of programmers ranging from amateurs to comme Also, there is an active and friendly support list where questions are welcomed and help readily available without a critical eye. Registration is required to post to the list: -[http://www.brilorsoftware.com/fb/pages/support.html FB Support List] \ No newline at end of file +[http://www.brilorsoftware.com/fb/pages/support.html FB Support List] + +==Todo== +* [https://rosettacode.org/wiki/Tasks_not_implemented_in_FutureBasic Tasks not implemented in FutureBasic] \ No newline at end of file diff --git a/Lang/FutureBasic/Almost-prime b/Lang/FutureBasic/Almost-prime new file mode 120000 index 0000000000..705326c32e --- /dev/null +++ b/Lang/FutureBasic/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Animate-a-pendulum b/Lang/FutureBasic/Animate-a-pendulum new file mode 120000 index 0000000000..57aff63b0a --- /dev/null +++ b/Lang/FutureBasic/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Append-a-record-to-the-end-of-a-text-file b/Lang/FutureBasic/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..d79f30e31e --- /dev/null +++ b/Lang/FutureBasic/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Arithmetic-evaluation b/Lang/FutureBasic/Arithmetic-evaluation new file mode 120000 index 0000000000..46bc418d8a --- /dev/null +++ b/Lang/FutureBasic/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Atomic-updates b/Lang/FutureBasic/Atomic-updates new file mode 120000 index 0000000000..29950a19fc --- /dev/null +++ b/Lang/FutureBasic/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Chaocipher b/Lang/FutureBasic/Chaocipher new file mode 120000 index 0000000000..5bcaa1c111 --- /dev/null +++ b/Lang/FutureBasic/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Chaos-game b/Lang/FutureBasic/Chaos-game new file mode 120000 index 0000000000..d0c3bc3fb7 --- /dev/null +++ b/Lang/FutureBasic/Chaos-game @@ -0,0 +1 @@ +../../Task/Chaos-game/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Chowla-numbers b/Lang/FutureBasic/Chowla-numbers new file mode 120000 index 0000000000..66ee109f11 --- /dev/null +++ b/Lang/FutureBasic/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Circular-primes b/Lang/FutureBasic/Circular-primes new file mode 120000 index 0000000000..4fc937418e --- /dev/null +++ b/Lang/FutureBasic/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Compound-data-type b/Lang/FutureBasic/Compound-data-type new file mode 120000 index 0000000000..834bc2c53f --- /dev/null +++ b/Lang/FutureBasic/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Currency b/Lang/FutureBasic/Currency new file mode 120000 index 0000000000..9dda5c7aa0 --- /dev/null +++ b/Lang/FutureBasic/Currency @@ -0,0 +1 @@ +../../Task/Currency/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Cyclops-numbers b/Lang/FutureBasic/Cyclops-numbers new file mode 120000 index 0000000000..2a1c57a1c4 --- /dev/null +++ b/Lang/FutureBasic/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Date-manipulation b/Lang/FutureBasic/Date-manipulation new file mode 120000 index 0000000000..71c992ee3e --- /dev/null +++ b/Lang/FutureBasic/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Events b/Lang/FutureBasic/Events new file mode 120000 index 0000000000..5cbcb61e7f --- /dev/null +++ b/Lang/FutureBasic/Events @@ -0,0 +1 @@ +../../Task/Events/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/File-modification-time b/Lang/FutureBasic/File-modification-time new file mode 120000 index 0000000000..48239bc690 --- /dev/null +++ b/Lang/FutureBasic/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Fractal-tree b/Lang/FutureBasic/Fractal-tree new file mode 120000 index 0000000000..92326e6aad --- /dev/null +++ b/Lang/FutureBasic/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/General-FizzBuzz b/Lang/FutureBasic/General-FizzBuzz new file mode 120000 index 0000000000..3204cd192e --- /dev/null +++ b/Lang/FutureBasic/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Holidays-related-to-Easter b/Lang/FutureBasic/Holidays-related-to-Easter new file mode 120000 index 0000000000..54bd05a9da --- /dev/null +++ b/Lang/FutureBasic/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Loop-over-multiple-arrays-simultaneously b/Lang/FutureBasic/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..e1fe35f0cd --- /dev/null +++ b/Lang/FutureBasic/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Loops-Nested b/Lang/FutureBasic/Loops-Nested new file mode 120000 index 0000000000..b9dae9f6dc --- /dev/null +++ b/Lang/FutureBasic/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Permutations b/Lang/FutureBasic/Permutations new file mode 120000 index 0000000000..f99b764905 --- /dev/null +++ b/Lang/FutureBasic/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/FutureBasic \ No newline at end of file diff --git a/Lang/GW-BASIC/Caesar-cipher b/Lang/GW-BASIC/Caesar-cipher new file mode 120000 index 0000000000..5ed5d306c3 --- /dev/null +++ b/Lang/GW-BASIC/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Cartesian-product-of-two-or-more-lists b/Lang/GW-BASIC/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..f0e7b36b95 --- /dev/null +++ b/Lang/GW-BASIC/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Draw-a-rotating-cube b/Lang/GW-BASIC/Draw-a-rotating-cube new file mode 120000 index 0000000000..4f262f6402 --- /dev/null +++ b/Lang/GW-BASIC/Draw-a-rotating-cube @@ -0,0 +1 @@ +../../Task/Draw-a-rotating-cube/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Gapful-numbers b/Lang/GW-BASIC/Gapful-numbers new file mode 120000 index 0000000000..ca21514c7f --- /dev/null +++ b/Lang/GW-BASIC/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/Almost-prime b/Lang/Gambas/Almost-prime new file mode 120000 index 0000000000..454b65d205 --- /dev/null +++ b/Lang/Gambas/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Cartesian-product-of-two-or-more-lists b/Lang/Gambas/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..cc6198bb67 --- /dev/null +++ b/Lang/Gambas/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Gapful-numbers b/Lang/Gambas/Gapful-numbers new file mode 120000 index 0000000000..fb27701171 --- /dev/null +++ b/Lang/Gambas/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Gambas \ No newline at end of file diff --git a/Lang/Harbour/Merge-and-aggregate-datasets b/Lang/Harbour/Merge-and-aggregate-datasets new file mode 120000 index 0000000000..0afe8d92f4 --- /dev/null +++ b/Lang/Harbour/Merge-and-aggregate-datasets @@ -0,0 +1 @@ +../../Task/Merge-and-aggregate-datasets/Harbour \ No newline at end of file diff --git a/Lang/Hy/Rot-13 b/Lang/Hy/Rot-13 new file mode 120000 index 0000000000..cbb6bb644d --- /dev/null +++ b/Lang/Hy/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Hy \ No newline at end of file diff --git a/Lang/Insitux/Factorial b/Lang/Insitux/Factorial new file mode 120000 index 0000000000..d0283b9e43 --- /dev/null +++ b/Lang/Insitux/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Insitux \ No newline at end of file diff --git a/Lang/J/00-LANG.txt b/Lang/J/00-LANG.txt index 28ea05c233..f665b8789e 100644 --- a/Lang/J/00-LANG.txt +++ b/Lang/J/00-LANG.txt @@ -18,9 +18,9 @@ == The J language == -A frequent reaction when one first encounters a J program is often something along the lines of "that's cheating". The thought here is that the problem could not possibly be that simple, so -- instead -- the issue must be that J was specifically designed to tackle that problem. +A frequent reaction when one first encounters a J program is often something along the lines of "that's cheating". The thought here is that the problem could not possibly be that simple, so — instead — the issue must be that J was specifically designed to tackle that problem. -The flip side of this issue is that J is a dialect of APL -- a language whose development started in the 1950s and which was implemented in the early 1960s. And, originally, APL was designed as a language to describe computer architecture. The implementation as a programming language was motivated by its original successes in documenting computer hardware and instructions, and the relative simplicity of its concepts. +The flip side of this issue is that J is a dialect of APL — a language whose development started in the 1950s and which was implemented in the early 1960s. And, originally, APL was designed as a language to describe computer architecture. The implementation as a programming language was motivated by its original successes in documenting computer hardware and instructions, and the relative simplicity of its concepts. == Introduction == @@ -32,7 +32,7 @@ It is a functional language; creation and composition of functions is emphasized 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 J programming language was designed and developed by [[wp: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.) @@ -48,12 +48,15 @@ If you want to understand how to experiment with alternative expressions you sho For example, the phrase (+/ % #) finds the average of a list of numbers. - (+/ % #) 1 2 3 -2 + + (+/ % #) 1 2 3 +2 + To understand how this works, you might try working with simpler sentences and their variations. - +/ 1 2 3 + + +/ 1 2 3 6 +/4 5 6 15 @@ -66,11 +69,12 @@ To understand how this works, you might try working with simpler sentences and t 15 % 3 5 (+/ % #) 4 5 6 -5 +5 +
By themselves, these experiments mean nothing, but if you know that +/ was finding the sum of a list and # was finding the length of a list and that % was dividing the two quantities (and looks almost like one of the old school division symbols) then these experiments might help confirm that you have understood things properly. -== Some Perspective == +== Some perspective == If you wish to use J you will also have to learn a few grammatical rules (J's parser has [http://www.jsoftware.com/help/dictionary/dicte.htm 9 reduction rules] and "shift" and "accept" - the above examples use four of those rules). J verbs have two definitions - a single argument "monadic" definition and a two argument "dyadic" definition. These terms are borrowed from music and are distinct from Haskell's use of the word "monad". @@ -97,7 +101,6 @@ J would be considered dynamically typed because of the generality of its arrays. Discussion of the goals of the J community on RC and general guidelines for presenting J solutions takes place at [[J/HouseStyle|House Style]]. - == Jedi on RosettaCode == *[[User:Roger_Hui|Roger Hui]]: [[Special:Contributions/Roger_Hui|contributions]], [[j:User:RogerHui|J wiki]] *[[User:TBH|Tracy Harms]]: [[Special:Contributions/TBH|contributions]], [[j:User:TracyHarms|J wiki]] diff --git a/Lang/Java/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- b/Lang/Java/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- new file mode 120000 index 0000000000..fabe8d433d --- /dev/null +++ b/Lang/Java/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Java \ No newline at end of file diff --git a/Lang/Java/Elliptic-Curve-Digital-Signature-Algorithm b/Lang/Java/Elliptic-Curve-Digital-Signature-Algorithm new file mode 120000 index 0000000000..9f3bbf0450 --- /dev/null +++ b/Lang/Java/Elliptic-Curve-Digital-Signature-Algorithm @@ -0,0 +1 @@ +../../Task/Elliptic-Curve-Digital-Signature-Algorithm/Java \ No newline at end of file diff --git a/Lang/Java/Function-prototype b/Lang/Java/Function-prototype new file mode 120000 index 0000000000..423ec942b0 --- /dev/null +++ b/Lang/Java/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Java \ No newline at end of file diff --git a/Lang/Java/Graph-colouring b/Lang/Java/Graph-colouring new file mode 120000 index 0000000000..7b2be318a5 --- /dev/null +++ b/Lang/Java/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/Java \ No newline at end of file diff --git a/Lang/Java/Juggler-sequence b/Lang/Java/Juggler-sequence new file mode 120000 index 0000000000..7ea49bb600 --- /dev/null +++ b/Lang/Java/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/Java \ No newline at end of file diff --git a/Lang/Java/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Java/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..f868aa73e5 --- /dev/null +++ b/Lang/Java/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Java \ No newline at end of file diff --git a/Lang/Java/Largest-proper-divisor-of-n b/Lang/Java/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..be351bae4e --- /dev/null +++ b/Lang/Java/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/Java \ No newline at end of file diff --git a/Lang/Java/Long-literals-with-continuations b/Lang/Java/Long-literals-with-continuations new file mode 120000 index 0000000000..4f5a8cd857 --- /dev/null +++ b/Lang/Java/Long-literals-with-continuations @@ -0,0 +1 @@ +../../Task/Long-literals-with-continuations/Java \ No newline at end of file diff --git a/Lang/Java/Magic-constant b/Lang/Java/Magic-constant new file mode 120000 index 0000000000..498e92cbfc --- /dev/null +++ b/Lang/Java/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Java \ No newline at end of file diff --git a/Lang/Java/Mastermind b/Lang/Java/Mastermind new file mode 120000 index 0000000000..b8c9d1fc85 --- /dev/null +++ b/Lang/Java/Mastermind @@ -0,0 +1 @@ +../../Task/Mastermind/Java \ No newline at end of file diff --git a/Lang/Java/Mayan-calendar b/Lang/Java/Mayan-calendar new file mode 120000 index 0000000000..d3fe6a0e93 --- /dev/null +++ b/Lang/Java/Mayan-calendar @@ -0,0 +1 @@ +../../Task/Mayan-calendar/Java \ No newline at end of file diff --git a/Lang/Java/Memory-layout-of-a-data-structure b/Lang/Java/Memory-layout-of-a-data-structure new file mode 120000 index 0000000000..4fb57c3700 --- /dev/null +++ b/Lang/Java/Memory-layout-of-a-data-structure @@ -0,0 +1 @@ +../../Task/Memory-layout-of-a-data-structure/Java \ No newline at end of file diff --git a/Lang/Java/Minkowski-question-mark-function b/Lang/Java/Minkowski-question-mark-function new file mode 120000 index 0000000000..f96b47301b --- /dev/null +++ b/Lang/Java/Minkowski-question-mark-function @@ -0,0 +1 @@ +../../Task/Minkowski-question-mark-function/Java \ No newline at end of file diff --git a/Lang/Java/Monads-List-monad b/Lang/Java/Monads-List-monad new file mode 120000 index 0000000000..0d57cf03c6 --- /dev/null +++ b/Lang/Java/Monads-List-monad @@ -0,0 +1 @@ +../../Task/Monads-List-monad/Java \ No newline at end of file diff --git a/Lang/Java/Multi-base-primes b/Lang/Java/Multi-base-primes new file mode 120000 index 0000000000..510123a7e5 --- /dev/null +++ b/Lang/Java/Multi-base-primes @@ -0,0 +1 @@ +../../Task/Multi-base-primes/Java \ No newline at end of file diff --git a/Lang/Java/Naming-conventions b/Lang/Java/Naming-conventions new file mode 120000 index 0000000000..2b7717eb6a --- /dev/null +++ b/Lang/Java/Naming-conventions @@ -0,0 +1 @@ +../../Task/Naming-conventions/Java \ No newline at end of file diff --git a/Lang/Java/Numbers-which-are-not-the-sum-of-distinct-squares b/Lang/Java/Numbers-which-are-not-the-sum-of-distinct-squares new file mode 120000 index 0000000000..844a5207fe --- /dev/null +++ b/Lang/Java/Numbers-which-are-not-the-sum-of-distinct-squares @@ -0,0 +1 @@ +../../Task/Numbers-which-are-not-the-sum-of-distinct-squares/Java \ No newline at end of file diff --git a/Lang/Java/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors b/Lang/Java/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors new file mode 120000 index 0000000000..a346e320cb --- /dev/null +++ b/Lang/Java/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors @@ -0,0 +1 @@ +../../Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/Java \ No newline at end of file diff --git a/Lang/Java/OpenWebNet-password b/Lang/Java/OpenWebNet-password new file mode 120000 index 0000000000..f4e7584bf9 --- /dev/null +++ b/Lang/Java/OpenWebNet-password @@ -0,0 +1 @@ +../../Task/OpenWebNet-password/Java \ No newline at end of file diff --git a/Lang/Java/Ormiston-triples b/Lang/Java/Ormiston-triples new file mode 120000 index 0000000000..3714b37d99 --- /dev/null +++ b/Lang/Java/Ormiston-triples @@ -0,0 +1 @@ +../../Task/Ormiston-triples/Java \ No newline at end of file diff --git a/Lang/Java/Pell-numbers b/Lang/Java/Pell-numbers new file mode 120000 index 0000000000..a33f29b042 --- /dev/null +++ b/Lang/Java/Pell-numbers @@ -0,0 +1 @@ +../../Task/Pell-numbers/Java \ No newline at end of file diff --git a/Lang/Java/Percolation-Bond-percolation b/Lang/Java/Percolation-Bond-percolation new file mode 120000 index 0000000000..170a3b1f60 --- /dev/null +++ b/Lang/Java/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Java \ No newline at end of file diff --git a/Lang/Java/Periodic-table b/Lang/Java/Periodic-table new file mode 120000 index 0000000000..c2d47a1f3a --- /dev/null +++ b/Lang/Java/Periodic-table @@ -0,0 +1 @@ +../../Task/Periodic-table/Java \ No newline at end of file diff --git a/Lang/Java/Play-recorded-sounds b/Lang/Java/Play-recorded-sounds new file mode 120000 index 0000000000..6cf5c344df --- /dev/null +++ b/Lang/Java/Play-recorded-sounds @@ -0,0 +1 @@ +../../Task/Play-recorded-sounds/Java \ No newline at end of file diff --git a/Lang/Java/Pragmatic-directives b/Lang/Java/Pragmatic-directives new file mode 120000 index 0000000000..e95bd1ac38 --- /dev/null +++ b/Lang/Java/Pragmatic-directives @@ -0,0 +1 @@ +../../Task/Pragmatic-directives/Java \ No newline at end of file diff --git a/Lang/Java/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/Java/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..e8365ce1a9 --- /dev/null +++ b/Lang/Java/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/Java \ No newline at end of file diff --git a/Lang/Joy/Increment-a-numerical-string b/Lang/Joy/Increment-a-numerical-string new file mode 120000 index 0000000000..94d9b8ca9e --- /dev/null +++ b/Lang/Joy/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Joy \ No newline at end of file diff --git a/Lang/Joy/Show-the-epoch b/Lang/Joy/Show-the-epoch new file mode 120000 index 0000000000..a4c9059659 --- /dev/null +++ b/Lang/Joy/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Joy \ No newline at end of file diff --git a/Lang/Jq/00-LANG.txt b/Lang/Jq/00-LANG.txt index 7b9095bc61..70c9eddfba 100644 --- a/Lang/Jq/00-LANG.txt +++ b/Lang/Jq/00-LANG.txt @@ -6,6 +6,7 @@ jq was originally designed and developed by Stephen Dolan. ==jq Modules at rosettacode.org== +* [[:Category:Jq/assert.jq|assert.jq]] - module to support assertions * [[:Category:Jq/peg.jq|peg.jq]] - Parsing Expression Grammar foundations ==Todo== diff --git a/Lang/Jq/Execute-Computer-Zero b/Lang/Jq/Execute-Computer-Zero new file mode 120000 index 0000000000..6408355347 --- /dev/null +++ b/Lang/Jq/Execute-Computer-Zero @@ -0,0 +1 @@ +../../Task/Execute-Computer-Zero/Jq \ No newline at end of file diff --git a/Lang/Jq/Steffensens-method b/Lang/Jq/Steffensens-method new file mode 120000 index 0000000000..7afdaa6d2a --- /dev/null +++ b/Lang/Jq/Steffensens-method @@ -0,0 +1 @@ +../../Task/Steffensens-method/Jq \ No newline at end of file diff --git a/Lang/Klingphix/00-LANG.txt b/Lang/Klingphix/00-LANG.txt index ea0e38fc4d..fbf5bc613e 100644 --- a/Lang/Klingphix/00-LANG.txt +++ b/Lang/Klingphix/00-LANG.txt @@ -2,6 +2,7 @@ |Klingphix |hopl=no }} +{{language programming paradigm|concatenative}} Klingphix is a pure interpreter developed in Phix (http://phix.x10.mx/). It is based on the use of a stack for the passage of data between words (the equivalent of traditional procedures) and uses reverse Polish notation, being procedural and imperative. The stack have global scope, and there is only one word separator sign: white space. Since Phix is interpreted, although fast, it does not allow Klingphix (also an interpreter) to be fast. However, it's useful for making small and, above all, stimulating and fun programs... at least for me (which, after all, is what I wanted it for). diff --git a/Lang/Koka/00-LANG.txt b/Lang/Koka/00-LANG.txt index 3ce2998509..96ea39de13 100644 --- a/Lang/Koka/00-LANG.txt +++ b/Lang/Koka/00-LANG.txt @@ -1,5 +1,22 @@ -{{stub}} +'''Koka Compilers''' + +Releases: +- https://github.com/koka-lang/koka/releases + +Latest: v2.4.2 + +'''Language Reference''' + +https://koka-lang.github.io/koka/doc/book.html + +'''Tasks to Implement in Koka''' + +Recommend implementing examples in both a C like 'effectful' way as well as in a Haskell or pure functional way. + +https://rosettacode.org/wiki/Tasks_not_implemented_in_Koka + {{language |Koka |hopl=no -}} \ No newline at end of file +}} +{{implementation|Koka}} \ No newline at end of file diff --git a/Lang/Koka/100-doors b/Lang/Koka/100-doors new file mode 120000 index 0000000000..56e3644435 --- /dev/null +++ b/Lang/Koka/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Koka \ No newline at end of file diff --git a/Lang/Koka/100-prisoners b/Lang/Koka/100-prisoners new file mode 120000 index 0000000000..5c30cc2baf --- /dev/null +++ b/Lang/Koka/100-prisoners @@ -0,0 +1 @@ +../../Task/100-prisoners/Koka \ No newline at end of file diff --git a/Lang/Koka/15-puzzle-game b/Lang/Koka/15-puzzle-game new file mode 120000 index 0000000000..ab830a7c9e --- /dev/null +++ b/Lang/Koka/15-puzzle-game @@ -0,0 +1 @@ +../../Task/15-puzzle-game/Koka \ No newline at end of file diff --git a/Lang/Koka/21-game b/Lang/Koka/21-game new file mode 120000 index 0000000000..f2e87bc36c --- /dev/null +++ b/Lang/Koka/21-game @@ -0,0 +1 @@ +../../Task/21-game/Koka \ No newline at end of file diff --git a/Lang/Koka/24-game b/Lang/Koka/24-game new file mode 120000 index 0000000000..b050a3a6fb --- /dev/null +++ b/Lang/Koka/24-game @@ -0,0 +1 @@ +../../Task/24-game/Koka \ No newline at end of file diff --git a/Lang/Koka/4-rings-or-4-squares-puzzle b/Lang/Koka/4-rings-or-4-squares-puzzle new file mode 120000 index 0000000000..df29a7a5d2 --- /dev/null +++ b/Lang/Koka/4-rings-or-4-squares-puzzle @@ -0,0 +1 @@ +../../Task/4-rings-or-4-squares-puzzle/Koka \ No newline at end of file diff --git a/Lang/Koka/ABC-problem b/Lang/Koka/ABC-problem new file mode 120000 index 0000000000..b43592a1ee --- /dev/null +++ b/Lang/Koka/ABC-problem @@ -0,0 +1 @@ +../../Task/ABC-problem/Koka \ No newline at end of file diff --git a/Lang/Koka/Balanced-ternary b/Lang/Koka/Balanced-ternary new file mode 120000 index 0000000000..3a3ced0e06 --- /dev/null +++ b/Lang/Koka/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Koka \ No newline at end of file diff --git a/Lang/Koka/Caesar-cipher b/Lang/Koka/Caesar-cipher new file mode 120000 index 0000000000..b653da9ef3 --- /dev/null +++ b/Lang/Koka/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Koka \ No newline at end of file diff --git a/Lang/Koka/Day-of-the-week b/Lang/Koka/Day-of-the-week new file mode 120000 index 0000000000..bb89b6889d --- /dev/null +++ b/Lang/Koka/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Koka \ No newline at end of file diff --git a/Lang/Ksh/00-LANG.txt b/Lang/Ksh/00-LANG.txt index 1c09770f9a..9aee7ac5ec 100644 --- a/Lang/Ksh/00-LANG.txt +++ b/Lang/Ksh/00-LANG.txt @@ -1 +1,3 @@ -{{stub}}{{language|Ksh}} \ No newline at end of file +{{language|ksh}} +Task solutions which might use extensions of the [[Korn Shell]]. See [[UNIX Shell]] for further solutions. +{{stub}} \ No newline at end of file diff --git a/Lang/Ksh/Bitmap-Bresenhams-line-algorithm b/Lang/Ksh/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..ca7e27f08f --- /dev/null +++ b/Lang/Ksh/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Ksh \ No newline at end of file diff --git a/Lang/Ksh/Loops-For b/Lang/Ksh/Loops-For new file mode 120000 index 0000000000..0cadf15a58 --- /dev/null +++ b/Lang/Ksh/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Ksh \ No newline at end of file diff --git a/Lang/Ksh/Loops-For-with-a-specified-step b/Lang/Ksh/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..610f4f3d71 --- /dev/null +++ b/Lang/Ksh/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Ksh \ No newline at end of file diff --git a/Lang/Ksh/Temperature-conversion b/Lang/Ksh/Temperature-conversion new file mode 120000 index 0000000000..8dd7b42716 --- /dev/null +++ b/Lang/Ksh/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Ksh \ No newline at end of file diff --git a/Lang/LDPL/00-LANG.txt b/Lang/LDPL/00-LANG.txt index 4e0d7e8a79..4d9ee594d6 100644 --- a/Lang/LDPL/00-LANG.txt +++ b/Lang/LDPL/00-LANG.txt @@ -1,5 +1,6 @@ {{language|LDPL |exec=machine +|site=https://www.ldpl-lang.org |strength=strong |checking=static |safety=strong @@ -12,5 +13,8 @@ }} '''LDPL''', an acronym for 'Lartu's Definitive Programming Language' is a programming language created in 2019, designed from the ground up to be excessively expressive, fast, readable and easy to learn. It mimics English in the likeness of older languages like [[COBOL]]. It's highly portable and runs on a plethora of different architectures and operating systems including AMD-64, ARMv8 and PowerPC Linux and Mac OS X. It is primarily an imperative, structured language. It even supports UTF-8 out of the box. +=== Todo === +[[Tasks not implemented in LDPL]] + {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} \ No newline at end of file diff --git a/Lang/LDPL/Arithmetic-Integer b/Lang/LDPL/Arithmetic-Integer new file mode 120000 index 0000000000..440cce50f4 --- /dev/null +++ b/Lang/LDPL/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Array-concatenation b/Lang/LDPL/Array-concatenation new file mode 120000 index 0000000000..6b1df3d83d --- /dev/null +++ b/Lang/LDPL/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Array-length b/Lang/LDPL/Array-length new file mode 120000 index 0000000000..538a5d75d6 --- /dev/null +++ b/Lang/LDPL/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Arrays b/Lang/LDPL/Arrays new file mode 120000 index 0000000000..9e6675078a --- /dev/null +++ b/Lang/LDPL/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Factorial b/Lang/LDPL/Factorial new file mode 120000 index 0000000000..52bc7b61ce --- /dev/null +++ b/Lang/LDPL/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/LDPL \ No newline at end of file diff --git a/Lang/LDPL/FizzBuzz b/Lang/LDPL/FizzBuzz new file mode 120000 index 0000000000..b6b91003b4 --- /dev/null +++ b/Lang/LDPL/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Function-definition b/Lang/LDPL/Function-definition new file mode 120000 index 0000000000..1365757e18 --- /dev/null +++ b/Lang/LDPL/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Greatest-element-of-a-list b/Lang/LDPL/Greatest-element-of-a-list new file mode 120000 index 0000000000..7a44da7870 --- /dev/null +++ b/Lang/LDPL/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Loops-Continue b/Lang/LDPL/Loops-Continue new file mode 120000 index 0000000000..77e5cdca05 --- /dev/null +++ b/Lang/LDPL/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Loops-Downward-for b/Lang/LDPL/Loops-Downward-for new file mode 120000 index 0000000000..73099917aa --- /dev/null +++ b/Lang/LDPL/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Loops-For b/Lang/LDPL/Loops-For new file mode 120000 index 0000000000..2a1f66736b --- /dev/null +++ b/Lang/LDPL/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Loops-For-with-a-specified-step b/Lang/LDPL/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..3485b472f3 --- /dev/null +++ b/Lang/LDPL/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Loops-Foreach b/Lang/LDPL/Loops-Foreach new file mode 120000 index 0000000000..3510c9edd8 --- /dev/null +++ b/Lang/LDPL/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Loops-Infinite b/Lang/LDPL/Loops-Infinite new file mode 120000 index 0000000000..b87050e4b0 --- /dev/null +++ b/Lang/LDPL/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Loops-While b/Lang/LDPL/Loops-While new file mode 120000 index 0000000000..37e3c876b1 --- /dev/null +++ b/Lang/LDPL/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Munchausen-numbers b/Lang/LDPL/Munchausen-numbers new file mode 120000 index 0000000000..1d1a014199 --- /dev/null +++ b/Lang/LDPL/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/LDPL \ No newline at end of file diff --git a/Lang/LDPL/RPG-attributes-generator b/Lang/LDPL/RPG-attributes-generator new file mode 120000 index 0000000000..f14208790c --- /dev/null +++ b/Lang/LDPL/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/LDPL \ No newline at end of file diff --git a/Lang/LDPL/String-append b/Lang/LDPL/String-append new file mode 120000 index 0000000000..ac42082250 --- /dev/null +++ b/Lang/LDPL/String-append @@ -0,0 +1 @@ +../../Task/String-append/LDPL \ No newline at end of file diff --git a/Lang/LDPL/User-input-Text b/Lang/LDPL/User-input-Text new file mode 120000 index 0000000000..79158db8c7 --- /dev/null +++ b/Lang/LDPL/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/LDPL \ No newline at end of file diff --git a/Lang/LDPL/Zero-to-the-zero-power b/Lang/LDPL/Zero-to-the-zero-power new file mode 120000 index 0000000000..81fb0869b1 --- /dev/null +++ b/Lang/LDPL/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/LDPL \ No newline at end of file diff --git a/Lang/Lua/Magic-constant b/Lang/Lua/Magic-constant new file mode 120000 index 0000000000..270c0b2185 --- /dev/null +++ b/Lang/Lua/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/Lua \ No newline at end of file diff --git a/Lang/MAD/Duffinian-numbers b/Lang/MAD/Duffinian-numbers new file mode 120000 index 0000000000..944339bfac --- /dev/null +++ b/Lang/MAD/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/MAD \ No newline at end of file diff --git a/Lang/MSX-Basic/Draw-a-rotating-cube b/Lang/MSX-Basic/Draw-a-rotating-cube new file mode 120000 index 0000000000..a516f5f30a --- /dev/null +++ b/Lang/MSX-Basic/Draw-a-rotating-cube @@ -0,0 +1 @@ +../../Task/Draw-a-rotating-cube/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Feigenbaum-constant-calculation b/Lang/MSX-Basic/Feigenbaum-constant-calculation new file mode 120000 index 0000000000..3ad02bb978 --- /dev/null +++ b/Lang/MSX-Basic/Feigenbaum-constant-calculation @@ -0,0 +1 @@ +../../Task/Feigenbaum-constant-calculation/MSX-Basic \ No newline at end of file diff --git a/Lang/MSX-Basic/Greatest-element-of-a-list b/Lang/MSX-Basic/Greatest-element-of-a-list new file mode 120000 index 0000000000..4e6f13d81a --- /dev/null +++ b/Lang/MSX-Basic/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/MSX-Basic \ No newline at end of file diff --git a/Lang/Maxima/AKS-test-for-primes b/Lang/Maxima/AKS-test-for-primes new file mode 120000 index 0000000000..75ba94a797 --- /dev/null +++ b/Lang/Maxima/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Abundant-deficient-and-perfect-number-classifications b/Lang/Maxima/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..35b938b7db --- /dev/null +++ b/Lang/Maxima/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Bell-numbers b/Lang/Maxima/Bell-numbers new file mode 120000 index 0000000000..ab54be9465 --- /dev/null +++ b/Lang/Maxima/Bell-numbers @@ -0,0 +1 @@ +../../Task/Bell-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Bernoulli-numbers b/Lang/Maxima/Bernoulli-numbers new file mode 120000 index 0000000000..87a17d617e --- /dev/null +++ b/Lang/Maxima/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Calkin-Wilf-sequence b/Lang/Maxima/Calkin-Wilf-sequence new file mode 120000 index 0000000000..2eefafc1fa --- /dev/null +++ b/Lang/Maxima/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Cartesian-product-of-two-or-more-lists b/Lang/Maxima/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..b2b9530e71 --- /dev/null +++ b/Lang/Maxima/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Chinese-remainder-theorem b/Lang/Maxima/Chinese-remainder-theorem new file mode 120000 index 0000000000..94d53961f6 --- /dev/null +++ b/Lang/Maxima/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Deceptive-numbers b/Lang/Maxima/Deceptive-numbers new file mode 120000 index 0000000000..836886a303 --- /dev/null +++ b/Lang/Maxima/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Ethiopian-multiplication b/Lang/Maxima/Ethiopian-multiplication new file mode 120000 index 0000000000..f2d18b7a07 --- /dev/null +++ b/Lang/Maxima/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Faulhabers-triangle b/Lang/Maxima/Faulhabers-triangle new file mode 120000 index 0000000000..55eece562f --- /dev/null +++ b/Lang/Maxima/Faulhabers-triangle @@ -0,0 +1 @@ +../../Task/Faulhabers-triangle/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Happy-numbers b/Lang/Maxima/Happy-numbers new file mode 120000 index 0000000000..af5ac460fd --- /dev/null +++ b/Lang/Maxima/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Hofstadter-Q-sequence b/Lang/Maxima/Hofstadter-Q-sequence new file mode 120000 index 0000000000..31923f99df --- /dev/null +++ b/Lang/Maxima/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Increment-a-numerical-string b/Lang/Maxima/Increment-a-numerical-string new file mode 120000 index 0000000000..671d5c54ad --- /dev/null +++ b/Lang/Maxima/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Josephus-problem b/Lang/Maxima/Josephus-problem new file mode 120000 index 0000000000..4887caf946 --- /dev/null +++ b/Lang/Maxima/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Kronecker-product b/Lang/Maxima/Kronecker-product new file mode 120000 index 0000000000..ee02e3dc41 --- /dev/null +++ b/Lang/Maxima/Kronecker-product @@ -0,0 +1 @@ +../../Task/Kronecker-product/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Kronecker-product-based-fractals b/Lang/Maxima/Kronecker-product-based-fractals new file mode 120000 index 0000000000..cfdc702c81 --- /dev/null +++ b/Lang/Maxima/Kronecker-product-based-fractals @@ -0,0 +1 @@ +../../Task/Kronecker-product-based-fractals/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Largest-int-from-concatenated-ints b/Lang/Maxima/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..4581d0f440 --- /dev/null +++ b/Lang/Maxima/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Leonardo-numbers b/Lang/Maxima/Leonardo-numbers new file mode 120000 index 0000000000..c9a9ffcdf0 --- /dev/null +++ b/Lang/Maxima/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Loop-over-multiple-arrays-simultaneously b/Lang/Maxima/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..291296bc66 --- /dev/null +++ b/Lang/Maxima/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Pascal-matrix-generation b/Lang/Maxima/Pascal-matrix-generation new file mode 120000 index 0000000000..b949b8eac6 --- /dev/null +++ b/Lang/Maxima/Pascal-matrix-generation @@ -0,0 +1 @@ +../../Task/Pascal-matrix-generation/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Pythagorean-triples b/Lang/Maxima/Pythagorean-triples new file mode 120000 index 0000000000..cc3bfe7ae5 --- /dev/null +++ b/Lang/Maxima/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Sorting-algorithms-Bubble-sort b/Lang/Maxima/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..1aec58a2e9 --- /dev/null +++ b/Lang/Maxima/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Twin-primes b/Lang/Maxima/Twin-primes new file mode 120000 index 0000000000..2a0b6645ce --- /dev/null +++ b/Lang/Maxima/Twin-primes @@ -0,0 +1 @@ +../../Task/Twin-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Ulam-spiral-for-primes- b/Lang/Maxima/Ulam-spiral-for-primes- new file mode 120000 index 0000000000..77dd683966 --- /dev/null +++ b/Lang/Maxima/Ulam-spiral-for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral-for-primes-/Maxima \ No newline at end of file diff --git a/Lang/Maxima/User-input-Text b/Lang/Maxima/User-input-Text new file mode 120000 index 0000000000..94f222bde9 --- /dev/null +++ b/Lang/Maxima/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Maxima \ No newline at end of file diff --git a/Lang/Minimal-BASIC/Greatest-element-of-a-list b/Lang/Minimal-BASIC/Greatest-element-of-a-list new file mode 120000 index 0000000000..1cbb3bcf31 --- /dev/null +++ b/Lang/Minimal-BASIC/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Minimal-BASIC/McNuggets-problem b/Lang/Minimal-BASIC/McNuggets-problem new file mode 120000 index 0000000000..5361c29284 --- /dev/null +++ b/Lang/Minimal-BASIC/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Minimal-BASIC \ No newline at end of file diff --git a/Lang/Modula-2/Brazilian-numbers b/Lang/Modula-2/Brazilian-numbers new file mode 120000 index 0000000000..f88e2e81be --- /dev/null +++ b/Lang/Modula-2/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Duffinian-numbers b/Lang/Modula-2/Duffinian-numbers new file mode 120000 index 0000000000..9ddda77a6d --- /dev/null +++ b/Lang/Modula-2/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Magnanimous-numbers b/Lang/Modula-2/Magnanimous-numbers new file mode 120000 index 0000000000..608ec56eb7 --- /dev/null +++ b/Lang/Modula-2/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Mojo/00-LANG.txt b/Lang/Mojo/00-LANG.txt new file mode 100644 index 0000000000..a9a1e8e0cc --- /dev/null +++ b/Lang/Mojo/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|Mojo}} \ No newline at end of file diff --git a/Lang/Mojo/00-META.yaml b/Lang/Mojo/00-META.yaml new file mode 100644 index 0000000000..49d12734d2 --- /dev/null +++ b/Lang/Mojo/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Mojo diff --git a/Lang/Nascom-BASIC/Brazilian-numbers b/Lang/Nascom-BASIC/Brazilian-numbers new file mode 120000 index 0000000000..c54ac400c0 --- /dev/null +++ b/Lang/Nascom-BASIC/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/Nascom-BASIC \ No newline at end of file diff --git a/Lang/Nim/Own-digits-power-sum b/Lang/Nim/Own-digits-power-sum new file mode 120000 index 0000000000..584b154541 --- /dev/null +++ b/Lang/Nim/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/Nim \ No newline at end of file diff --git a/Lang/Odin/Almost-prime b/Lang/Odin/Almost-prime new file mode 120000 index 0000000000..f84f8453de --- /dev/null +++ b/Lang/Odin/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Odin \ No newline at end of file diff --git a/Lang/Odin/Array-concatenation b/Lang/Odin/Array-concatenation new file mode 120000 index 0000000000..2617aae691 --- /dev/null +++ b/Lang/Odin/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Odin \ No newline at end of file diff --git a/Lang/Odin/Golden-ratio-Convergence b/Lang/Odin/Golden-ratio-Convergence new file mode 120000 index 0000000000..86e9063cb7 --- /dev/null +++ b/Lang/Odin/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/Odin \ No newline at end of file diff --git a/Lang/Odin/Two-bullet-roulette b/Lang/Odin/Two-bullet-roulette new file mode 120000 index 0000000000..178fc5793d --- /dev/null +++ b/Lang/Odin/Two-bullet-roulette @@ -0,0 +1 @@ +../../Task/Two-bullet-roulette/Odin \ No newline at end of file diff --git a/Lang/PARI-GP/Own-digits-power-sum b/Lang/PARI-GP/Own-digits-power-sum new file mode 120000 index 0000000000..086bc5985b --- /dev/null +++ b/Lang/PARI-GP/Own-digits-power-sum @@ -0,0 +1 @@ +../../Task/Own-digits-power-sum/PARI-GP \ No newline at end of file diff --git a/Lang/PL-I/Duffinian-numbers b/Lang/PL-I/Duffinian-numbers new file mode 120000 index 0000000000..50f8077589 --- /dev/null +++ b/Lang/PL-I/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/PL-I \ No newline at end of file diff --git a/Lang/PL-M/Duffinian-numbers b/Lang/PL-M/Duffinian-numbers new file mode 120000 index 0000000000..7dbb3f8528 --- /dev/null +++ b/Lang/PL-M/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/PL-M \ No newline at end of file diff --git a/Lang/Perl/Jordan-P-lya-numbers b/Lang/Perl/Jordan-P-lya-numbers new file mode 120000 index 0000000000..a331bd4ebf --- /dev/null +++ b/Lang/Perl/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Perl \ No newline at end of file diff --git a/Lang/Phix/00-LANG.txt b/Lang/Phix/00-LANG.txt index 08270c8834..f89816a59f 100644 --- a/Lang/Phix/00-LANG.txt +++ b/Lang/Phix/00-LANG.txt @@ -39,7 +39,7 @@ Technically Phix does not have a garbage collector, instead it is reference coun The fundamental goal of Phix is to make debugging easier, a whole subject area that does not seem to get the attention it deserves, despite several studies finding that most programmers actually spend between 70 and 90% of their time debugging. Most of us tend to think that getting just-written code to work is somehow not debugging, but that clipboard-toting researcher stood behind you would disagree. -Since 1.0.0 you can also run (many/most) Phix programs in a browser, by using pwa/p2js (as included in the distro) to transpile the program to JavaScript (plus a bit of standard HTML and CSS). If you see "'''with javascript_semantics'''" it means the program has been tested and works fine, both on the (Windows/Linux) desktop/Phix and in a browser via pwa/p2js, and in fact unix_dict() has been added to avoid reading unixdict.txt. Conversely, "without js" being present on a rosettacode entry means that (for instance) it uses the local file system, and is therefore desktop/Phix only. It is worth pointing out that "with js" and deep_copy() have proved ''staggeringly'' effective and nowhere near as painful as first feared. In just a few months (1.0.0 was released in July 2021) I have tested, fixed where necessary, and marked as javascript compatible ''[https://rosettacode.org/w/index.php?search=phixonline&title=Special%3ASearch&wprov=acrw1 over 1,100 rosettacode entries]'' for Phix, and only ''[https://rosettacode.org/w/index.php?search=notonline&title=Special%3ASearch&wprov=acrw1 one seventh]'' of that have as yet been marked incompatible, despite things like file i/o being prohibited within a web browser. The [https://rosettacode.org/wiki/Category:Phix/online Phix/online] subcategory currently lists 78 entries deemed interesting enough to bother (manually) uploading to the Phix website (ping me should any stop working), and the next goal is to get pwa/p2js itself runnning online, but obviously without using file i/o directly. +Since 1.0.0 you can also run (many/most) Phix programs in a browser, by using pwa/p2js (as included in the distro) to transpile the program to JavaScript (plus a bit of standard HTML and CSS). If you see "'''with javascript_semantics'''" it means the program has been tested and works fine, both on the (Windows/Linux) desktop/Phix and in a browser via pwa/p2js, and in fact unix_dict() has been added to avoid reading unixdict.txt. Conversely, "without js" being present on a rosettacode entry means that (for instance) it uses the local file system, and is therefore desktop/Phix only. It is worth pointing out that "with js" and deep_copy() have proved ''staggeringly'' effective and nowhere near as painful as first feared. In just a few months (1.0.0 was released in July 2021) I have tested, fixed where necessary, and marked as javascript compatible ''[https://rosettacode.org/w/index.php?search=phixonline&title=Special%3ASearch&wprov=acrw1 over 1,200 rosettacode entries]'' for Phix, and only ''[https://rosettacode.org/w/index.php?search=notonline&title=Special%3ASearch&wprov=acrw1 one seventh]'' of that have as yet been marked incompatible, despite things like file i/o being prohibited within a web browser. The [https://rosettacode.org/wiki/Category:Phix/online Phix/online] subcategory currently lists 99 entries deemed interesting enough to bother (manually) uploading to the Phix website (ping me should any stop working), and the next goal is to get pwa/p2js itself runnning online, but obviously without using file i/o directly. Another long term goal is to get Phix running on ARM, and since that would be utterly pointless without a viable GUI, I am currently elbow deep in writing a new cross-platform GUI, as a stepping stone (for both ARM and p2js/online). ==See also== * [http://phix.x10.mx Phix site] diff --git a/Lang/Plain-English/Color-wheel b/Lang/Plain-English/Color-wheel new file mode 120000 index 0000000000..8a23b5caba --- /dev/null +++ b/Lang/Plain-English/Color-wheel @@ -0,0 +1 @@ +../../Task/Color-wheel/Plain-English \ No newline at end of file diff --git a/Lang/Pointless/FizzBuzz b/Lang/Pointless/FizzBuzz new file mode 120000 index 0000000000..ac5ae42fc3 --- /dev/null +++ b/Lang/Pointless/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Pointless \ No newline at end of file diff --git a/Lang/Pointless/Hello-world-Text b/Lang/Pointless/Hello-world-Text new file mode 120000 index 0000000000..aa092ad5a5 --- /dev/null +++ b/Lang/Pointless/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Pointless \ No newline at end of file diff --git a/Lang/Pointless/The-Twelve-Days-of-Christmas b/Lang/Pointless/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..41cc0127a2 --- /dev/null +++ b/Lang/Pointless/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Pointless \ No newline at end of file diff --git a/Lang/PureBasic/McNuggets-problem b/Lang/PureBasic/McNuggets-problem new file mode 120000 index 0000000000..1ac54f4669 --- /dev/null +++ b/Lang/PureBasic/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/PureBasic \ No newline at end of file diff --git a/Lang/Python/00-LANG.txt b/Lang/Python/00-LANG.txt index c89c97ceab..71ecbf3dd5 100644 --- a/Lang/Python/00-LANG.txt +++ b/Lang/Python/00-LANG.txt @@ -1,6 +1,6 @@ {{language |exec=interpreted -|site=http://www.python.org +|site=https://www.python.org |strength=strong |safety=safe |express=implicit @@ -8,15 +8,15 @@ |parampass=object reference |gc=yes |LCT=yes -|bnf=http://docs.python.org/py3k/reference/grammar.html}}{{language programming paradigm|Dynamic}}{{language programming paradigm|Object-oriented}}{{codepad}}From the official [http://www.python.org Python] website: "Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs." +|bnf=https://docs.python.org/3/reference/grammar.html}}{{language programming paradigm|Dynamic}}{{language programming paradigm|Object-oriented}}{{codepad}}From the official [https://www.python.org Python] website: "Python is a programming language that lets you work more quickly and integrate your systems more effectively. You can learn to use Python and see almost immediate gains in productivity and lower maintenance costs." It is easy to create clean bug-free programs in Python due to the motto: "Errors should never pass silently." Python is an [[wp:Interpreter (computing)|interpreter]]. Python source files (.py files) are typically compiled to an intermediate [[bytecode]] language (.pyc files) and executed by a Python Virtual Machine. ===Notes=== -Because Python uses whitespace for structure, do not format long code examples with leading whitespace, instead use
tags, or, preferably, tags. This will make it easier to copy code into and out of the wiki. Example: -:print('this line must not have leading indentation!') +Because Python uses whitespace for structure, do not format long code examples with leading whitespace, instead use
tags, or, preferably, tags. This will make it easier to copy code into and out of the wiki. Example: +print('this line must not have leading indentation!') if True: - print('example: ', foo(3), len(bar))
+ print('example: ', foo(3), len(bar)) Some Python examples may deviate from idiomatic Python because they may be written to work in Python 3.X as well as Python 2.X environments. This includes doing things like: * Using brackets in print statements/functions of one expression. @@ -31,4 +31,4 @@ The command line is often used in Python for short pieces of code, and so, again * [[wp:python_(programming_language)|Wikipedia: Python]] ==Todo== -[[Reports:Tasks_not_implemented_in_Python]] \ No newline at end of file +[[Tasks_not_implemented_in_Python]] \ No newline at end of file diff --git a/Lang/Python/Duffinian-numbers b/Lang/Python/Duffinian-numbers new file mode 120000 index 0000000000..fe6aa62978 --- /dev/null +++ b/Lang/Python/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Python \ No newline at end of file diff --git a/Lang/Python/Wilson-primes-of-order-n b/Lang/Python/Wilson-primes-of-order-n new file mode 120000 index 0000000000..f98acffbcf --- /dev/null +++ b/Lang/Python/Wilson-primes-of-order-n @@ -0,0 +1 @@ +../../Task/Wilson-primes-of-order-n/Python \ No newline at end of file diff --git a/Lang/QBasic/Cartesian-product-of-two-or-more-lists b/Lang/QBasic/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..e2b8072a28 --- /dev/null +++ b/Lang/QBasic/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/QBasic \ No newline at end of file diff --git a/Lang/QBasic/Gapful-numbers b/Lang/QBasic/Gapful-numbers new file mode 120000 index 0000000000..376603cd82 --- /dev/null +++ b/Lang/QBasic/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/QBasic \ No newline at end of file diff --git a/Lang/Quackery/00-LANG.txt b/Lang/Quackery/00-LANG.txt index 317a036c03..ca017e1b3c 100644 --- a/Lang/Quackery/00-LANG.txt +++ b/Lang/Quackery/00-LANG.txt @@ -1,7 +1,7 @@ {{language|Quackery}} -{{language programming paradigm|concatenative}} -{{language programming paradigm|imperative}} -Quackery is an open source, lightweight, entry level concatenative language for educational and recreational programming. +{{language programming paradigm|Concatenative}} +{{language programming paradigm|Imperative}} +Quackery is an open-source, lightweight, entry-level concatenative language for educational and recreational programming. It is coded as a Python 3 function in under 48k of Pythonscript, about half of which is a string of Quackery code. @@ -15,18 +15,21 @@ The Quackiverse consists of operators (i.e. op-codes or "primitives"), numbers ( Quackery in a nutshell. -To compile this definition of quackery, build takes a string of Quackscript and turns it into a nest. The left and right brackets delimit a nest, which will contain pointers to the dictionary items called build and do, in that order. Quackery code is evaluated from left to right, one item after another, traversing a tree of nests in depth first order. Once build has compiled the string, it passes the resultant nest via the Quackery stack, which is used to carry arguments and results from one word to the next, to do for evaluation. The second stack, the return stack, manages do's depth first traversal of nested nests. +To compile this definition of quackery, build takes a string of Quackscript and turns it into a nest. The left and right brackets delimit a nest, which will contain pointers to the dictionary items called build and do, in that order. Quackery code is evaluated from left to right, one item after another, traversing a tree of nests in depth-first order. Once build has compiled the string, it passes the resultant nest via the Quackery stack, which is used to carry arguments and results from one word to the next, to do for evaluation. The second stack, the return stack, manages do's depth-first traversal of nested nests. The words is, [, and ] are builders; they can be found in the builders dictionary, which extends the functionality of build beyond building a flat nest for do to evaluate. is takes the item that do most recently added to its output nest, and adds it to the names dictionary, along with the string that follows it, "quackery" as its name. The syntax of Quackery is; words and numbers are sequences of printable characters, separated by spaces and carriage returns unless a builder treats the text that follows it otherwise. The builder builds is equivalent to is for adding new words and behaviours to the builders dictionary. Evaluation of a nest proceeds from left to right unless a control flow operator redirects it. done causes doto stop evaluating a nest and return to the nest that pointed to it immediately, rather than at the end of the nest. again restarts the evaluation of that nest, non-recursively. The word recurse does it recursively. if and iff conditionally (depending on the item on the top of the Quackery stack) skip over the next one and two items in the nest respectively. else skips over one item, unconditionally. As with the other provided control flow operators, these words are nests, not operators, that make use of the "meta-control flow" operators, which grant the behaviours described above to words that use them. (They modify items on the return stack, rather than acting on the Quackery engine's various pointers registers directly, so their changes are enacted upon exiting the nest that called them.) -There are no variables in Quackery. Instead there are stack management words to rearrange the uppermost items on the Quackery stack as required, and nameable ancillary stacks that fulfil the roles of variables. +There are no variables in Quackery. Instead, there are stack management words to rearrange the uppermost items on the Quackery stack as required, and nameable ancillary stacks that fulfil the roles of variables. Everything is code except when it is data. When do does a number, the behaviour of the number is to put its numerical value on the stack. Operators do the heavy lifting; there are operators that treat numbers as integers, or as booleans, or as sequences of bits, or as characters, and there are operators to edit nests, interface with the real-world host computer for I/O, and so on. Nests give structure to code and data alike. -Conceptually, the Quackery engine is a stack based processor which does not have direct access to physical memory, but has a memory management co-processor that intermediates, that takes care of the nests and bignums, provides pointers to the Quackery engine CPU on request, and garbage collects continuously. +Conceptually, the Quackery engine is a stack based processor which does not have direct access to physical memory but has a memory management co-processor that intermediates, that takes care of the nests and bignums, provides pointers to the Quackery engine CPU on request, and garbage collects continuously. -Quackery is not intended to be a super-fast enterprise level language; it is intended as a fun programming project straight out of a textbook. (The textbook is included in the download.) +Quackery is not intended to be a super-fast enterprise-level language; it is intended as a fun programming project straight out of a textbook. (The textbook is included in the download.) -If your language supports bignums, first class functions and dynamic arrays of bignums, functions and dynamic arrays, and has automatic garbage collection, and if you can code depth first traversal of a tree you can implement Quackery in your preferred language with reasonable ease, and modify it as you please. \ No newline at end of file +If your language supports bignums, first-class functions and dynamic arrays of bignums, functions and dynamic arrays, and has automatic garbage collection, and if you can code depth-first traversal of a tree you can implement Quackery in your preferred language with reasonable ease, and modify it as you please. + +Or try your hand at one of the [https://rosettacode.org/wiki/Tasks_not_implemented_in_Quackery Tasks not implemented in Quackery] +. \ No newline at end of file diff --git a/Lang/Quackery/Currency b/Lang/Quackery/Currency new file mode 120000 index 0000000000..4a8cb67d23 --- /dev/null +++ b/Lang/Quackery/Currency @@ -0,0 +1 @@ +../../Task/Currency/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Deceptive-numbers b/Lang/Quackery/Deceptive-numbers new file mode 120000 index 0000000000..cf4dca9c46 --- /dev/null +++ b/Lang/Quackery/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Equal-prime-and-composite-sums b/Lang/Quackery/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..620e26fd4b --- /dev/null +++ b/Lang/Quackery/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/Quackery \ No newline at end of file diff --git a/Lang/Quackery/General-FizzBuzz b/Lang/Quackery/General-FizzBuzz new file mode 120000 index 0000000000..c3ad2ff754 --- /dev/null +++ b/Lang/Quackery/General-FizzBuzz @@ -0,0 +1 @@ +../../Task/General-FizzBuzz/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Greatest-subsequential-sum b/Lang/Quackery/Greatest-subsequential-sum new file mode 120000 index 0000000000..45082a8d30 --- /dev/null +++ b/Lang/Quackery/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Magnanimous-numbers b/Lang/Quackery/Magnanimous-numbers new file mode 120000 index 0000000000..60533f1e1f --- /dev/null +++ b/Lang/Quackery/Magnanimous-numbers @@ -0,0 +1 @@ +../../Task/Magnanimous-numbers/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Smith-numbers b/Lang/Quackery/Smith-numbers new file mode 120000 index 0000000000..156a12b59c --- /dev/null +++ b/Lang/Quackery/Smith-numbers @@ -0,0 +1 @@ +../../Task/Smith-numbers/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Sort-disjoint-sublist b/Lang/Quackery/Sort-disjoint-sublist new file mode 120000 index 0000000000..9117c6f305 --- /dev/null +++ b/Lang/Quackery/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Quackery \ No newline at end of file diff --git a/Lang/Quite-BASIC/Greatest-element-of-a-list b/Lang/Quite-BASIC/Greatest-element-of-a-list new file mode 120000 index 0000000000..c60341ae1b --- /dev/null +++ b/Lang/Quite-BASIC/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Quite-BASIC \ No newline at end of file diff --git a/Lang/RISC-V-Assembly/Wireworld b/Lang/RISC-V-Assembly/Wireworld new file mode 120000 index 0000000000..0ba7c463ac --- /dev/null +++ b/Lang/RISC-V-Assembly/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/RISC-V-Assembly \ No newline at end of file diff --git a/Lang/RPL/00-LANG.txt b/Lang/RPL/00-LANG.txt index f59bf80730..baf7c8a3a4 100644 --- a/Lang/RPL/00-LANG.txt +++ b/Lang/RPL/00-LANG.txt @@ -1,5 +1,3 @@ -{{stub|language}} - {{language|RPL |exec=interpreted |gc=yes diff --git a/Lang/Ruby/Bifid-cipher b/Lang/Ruby/Bifid-cipher new file mode 120000 index 0000000000..9cf14434b2 --- /dev/null +++ b/Lang/Ruby/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Duffinian-numbers b/Lang/Ruby/Duffinian-numbers new file mode 120000 index 0000000000..08f70be87f --- /dev/null +++ b/Lang/Ruby/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Ruby \ No newline at end of file diff --git a/Lang/Run-BASIC/Cartesian-product-of-two-or-more-lists b/Lang/Run-BASIC/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..ff1f9c1751 --- /dev/null +++ b/Lang/Run-BASIC/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/Gapful-numbers b/Lang/Run-BASIC/Gapful-numbers new file mode 120000 index 0000000000..6a538cb088 --- /dev/null +++ b/Lang/Run-BASIC/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/Run-BASIC \ No newline at end of file diff --git a/Lang/Run-BASIC/McNuggets-problem b/Lang/Run-BASIC/McNuggets-problem new file mode 120000 index 0000000000..3ce85b81a9 --- /dev/null +++ b/Lang/Run-BASIC/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Run-BASIC \ No newline at end of file diff --git a/Lang/Rust/00-LANG.txt b/Lang/Rust/00-LANG.txt index 6880a4525f..5909a4170e 100644 --- a/Lang/Rust/00-LANG.txt +++ b/Lang/Rust/00-LANG.txt @@ -28,6 +28,9 @@ From the official website: * minimal runtime * efficient C bindings +== Not yet implemented examples == +[[Tasks_not_implemented_in_Rust]] + {{language programming paradigm|functional}} {{language programming paradigm|imperative}} {{language programming paradigm|Object-oriented}} diff --git a/Lang/Scala/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/Scala/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..5b28371c54 --- /dev/null +++ b/Lang/Scala/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k @@ -0,0 +1 @@ +../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Scala \ No newline at end of file diff --git a/Lang/Shale/00-LANG.txt b/Lang/Shale/00-LANG.txt index 36f8031db2..691eb8b6b9 100644 --- a/Lang/Shale/00-LANG.txt +++ b/Lang/Shale/00-LANG.txt @@ -1,4 +1,5 @@ {{language}} +{{language programming paradigm|concatenative}} Shale is a stack-based reverse-polish notation language. It has a simple yet powerful set of features, including dynamically loaded libraries, conditional logical AND and OR operators (in an RPN language!) and POSIX threads. Compiles on Linux and Mac OS X. diff --git a/Lang/Sidef/Ramanujan-primes-twins b/Lang/Sidef/Ramanujan-primes-twins new file mode 120000 index 0000000000..8205d74b1b --- /dev/null +++ b/Lang/Sidef/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/Sidef \ No newline at end of file diff --git a/Lang/True-BASIC/Caesar-cipher b/Lang/True-BASIC/Caesar-cipher new file mode 120000 index 0000000000..87d28d3914 --- /dev/null +++ b/Lang/True-BASIC/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Digital-root b/Lang/True-BASIC/Digital-root new file mode 120000 index 0000000000..4e97f3c40e --- /dev/null +++ b/Lang/True-BASIC/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/True-BASIC \ No newline at end of file diff --git a/Lang/True-BASIC/Gapful-numbers b/Lang/True-BASIC/Gapful-numbers new file mode 120000 index 0000000000..7a9a86748d --- /dev/null +++ b/Lang/True-BASIC/Gapful-numbers @@ -0,0 +1 @@ +../../Task/Gapful-numbers/True-BASIC \ No newline at end of file diff --git a/Lang/UNIX-Shell/Zeckendorf-number-representation b/Lang/UNIX-Shell/Zeckendorf-number-representation new file mode 120000 index 0000000000..201a17f38d --- /dev/null +++ b/Lang/UNIX-Shell/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/UNIX-Shell \ No newline at end of file diff --git a/Lang/Wren/00-LANG.txt b/Lang/Wren/00-LANG.txt index e9670b8aad..240a2360ed 100644 --- a/Lang/Wren/00-LANG.txt +++ b/Lang/Wren/00-LANG.txt @@ -15,9 +15,9 @@ It is under development on [https://github.com/wren-lang/wren GitHub] and is ful The CLI tool (Wren CLI) has its own repository and is the main focus of examples written for RC. The latest version 0.4.0 is available as a pre-built standalone executable for 64-bit Linux, MacOS and Windows and can be downloaded from [https://github.com/wren-lang/wren-cli/releases here]. -Following the migration to Miraheze, RC now uses [https://pygments.org Pygments] (rather than GeSHi) for syntax highlighting and I have written a lexer for Wren which is included in version 2.14.0. However, at the time of writing (June 2023), RC is still using version 2.11.2 and it is not known when this will be updated to the latest version. +Following the migration to Miraheze and then WikiTide, RC now uses [https://pygments.org Pygments] (rather than GeSHi) for syntax highlighting and I have written a lexer for Wren which is included in version 2.14.0. However, at the time of writing (August 2023), RC is still using version 2.11.2 and it is not known when this will be updated to the latest version. -In the meantime 'ecmascript', which we currently use for the 'lang' attribute, is supported by virtue of a GeSHi mapping to the 'javascript' lexer and highlights all Wren 0.4.0 keywords except: ''is'', ''construct'' and ''foreign''. I suggest we continue to use that until the Wren lexer is available after which we can use the latter for new tasks and when updating existing tasks. A major effort would be needed to update all existing tasks straightaway given that there are more than 1,600 of them as at June 2023. +In the meantime 'ecmascript', which we currently use for the 'lang' attribute, is supported by virtue of a GeSHi mapping to the 'javascript' lexer and highlights all Wren 0.4.0 keywords except: ''is'', ''construct'' and ''foreign''. I suggest we continue to use that until the Wren lexer is available after which we can use the latter for new tasks and when updating existing tasks. A major effort would be needed to update all existing tasks straightaway given that there are more than 1,600 of them as at August 2023. As a language mainly designed for embedding, Wren's standard library is (of necessity) quite small and I have therefore decided to create some additional modules to assist with writing Rosetta Code tasks so the same code does not have to be written or copy/pasted time and time again thereby bloating a task's script code unnecessarily. The ones written so far are listed below: diff --git a/Lang/XBasic/McNuggets-problem b/Lang/XBasic/McNuggets-problem new file mode 120000 index 0000000000..025b43c289 --- /dev/null +++ b/Lang/XBasic/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/XBasic \ No newline at end of file diff --git a/Lang/Yabasic/Digital-root b/Lang/Yabasic/Digital-root new file mode 120000 index 0000000000..7f2a0dbb65 --- /dev/null +++ b/Lang/Yabasic/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Yabasic \ No newline at end of file diff --git a/Lang/Yabasic/McNuggets-problem b/Lang/Yabasic/McNuggets-problem new file mode 120000 index 0000000000..eabc4f7f36 --- /dev/null +++ b/Lang/Yabasic/McNuggets-problem @@ -0,0 +1 @@ +../../Task/McNuggets-problem/Yabasic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Ulam-spiral-for-primes- b/Lang/ZX-Spectrum-Basic/Ulam-spiral-for-primes- new file mode 120000 index 0000000000..ca6e1533cd --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Ulam-spiral-for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral-for-primes-/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/Zig/CRC-32 b/Lang/Zig/CRC-32 new file mode 120000 index 0000000000..bf07247732 --- /dev/null +++ b/Lang/Zig/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Zig \ No newline at end of file diff --git a/Lang/Zig/RPG-attributes-generator b/Lang/Zig/RPG-attributes-generator new file mode 120000 index 0000000000..94fabed1e8 --- /dev/null +++ b/Lang/Zig/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/Zig \ No newline at end of file diff --git a/Task/100-doors/ALGOL-68/100-doors-1.alg b/Task/100-doors/ALGOL-68/100-doors-1.alg index 6c5343b067..8b4fc67b17 100644 --- a/Task/100-doors/ALGOL-68/100-doors-1.alg +++ b/Task/100-doors/ALGOL-68/100-doors-1.alg @@ -1,7 +1,4 @@ -# declare some constants # -INT limit = 100; - -PROC doors = VOID: +PROC doors = (INT limit)VOID: ( MODE DOORSTATE = BOOL; BOOL closed = FALSE; @@ -12,14 +9,12 @@ PROC doors = VOID: FOR i FROM LWB the doors TO UPB the doors DO the doors[i]:=closed OD; FOR i FROM LWB the doors TO UPB the doors DO - FOR j FROM LWB the doors TO UPB the doors DO - IF j MOD i = 0 THEN - the doors[j] := NOT the doors[j] - FI + FOR j FROM LWB the doors BY i TO UPB the doors DO + the doors[j] := NOT the doors[j] OD OD; FOR i FROM LWB the doors TO UPB the doors DO - printf(($g" is "gl$,i,(the doors[i]|"opened"|"closed"))) + print((whole(i,-12)," is ",(the doors[i]|"opened"|"closed"),newline)) OD ); -doors; +doors(100) diff --git a/Task/100-doors/Koka/100-doors-1.koka b/Task/100-doors/Koka/100-doors-1.koka new file mode 100644 index 0000000000..dbf72cbe1e --- /dev/null +++ b/Task/100-doors/Koka/100-doors-1.koka @@ -0,0 +1,23 @@ +type state + Open + Closed + +fun toggle(self: state): state + match self + Open -> Closed + Closed -> Open + +inline extern unsafe-assign : forall ( v : vector, i : ssize_t, x : a ) -> total () + c "kk_vector_unsafe_assign" + +fun main() + val doors = vector(100, Closed) + for(0,99) fn(pass) + var door := pass + while { door < 99 } + doors.unsafe-assign(door.ssize_t, doors[door].toggle) + door := door + (pass+1) + doors.foreach-indexed fn(idx, it) + match it + Open -> println("door " ++ (idx + 1).show ++ " is open") + Closed -> println("door " ++ (idx + 1).show ++ " is closed") diff --git a/Task/100-doors/Koka/100-doors-2.koka b/Task/100-doors/Koka/100-doors-2.koka new file mode 100644 index 0000000000..3c79b41fee --- /dev/null +++ b/Task/100-doors/Koka/100-doors-2.koka @@ -0,0 +1,9 @@ +fun main() + val doors = list(0,99,1,fn(i) Closed) + val transformed = list(1,99).foldl(doors) fn(drs, pass) + drs.map-indexed fn(i, door) + if ((i + 1) % pass) == 0 then door.toggle else door + transformed.foreach-indexed fn(idx, it) + match it + Open -> println("door " ++ (idx + 1).show ++ " is open") + Closed -> println("door " ++ (idx + 1).show ++ " is closed") diff --git a/Task/100-doors/MATLAB/100-doors-3.m b/Task/100-doors/MATLAB/100-doors-3.m index e1e5c60067..50fa0e873c 100644 --- a/Task/100-doors/MATLAB/100-doors-3.m +++ b/Task/100-doors/MATLAB/100-doors-3.m @@ -1,5 +1,5 @@ -a = zeros(100,1); -for counter = 1:sqrt(100); - a(counter^2) = 1; +doors = zeros(1,100); // 0: closed 1: open +for i = 1:100 + doors(i:i:100) = 1-doors(i:i:100) end -a +doors diff --git a/Task/100-doors/MATLAB/100-doors-4.m b/Task/100-doors/MATLAB/100-doors-4.m index 4e7da60177..e1e5c60067 100644 --- a/Task/100-doors/MATLAB/100-doors-4.m +++ b/Task/100-doors/MATLAB/100-doors-4.m @@ -1,15 +1,5 @@ -function [doors,opened,closed] = hundredDoors() - - %Initialize the doors, make them booleans for easy vectorization - doors = logical( (1:1:100) ); - - %Go through the flipping process, ignore the 1 case because the doors - %array is already initialized to all open - for initialPosition = (2:100) - doors(initialPosition:initialPosition:100) = not( doors(initialPosition:initialPosition:100) ); - end - - opened = find(doors); %Stores the numbers of the open doors - closed = find( not(doors) ); %Stores the numbers of the closed doors - +a = zeros(100,1); +for counter = 1:sqrt(100); + a(counter^2) = 1; end +a diff --git a/Task/100-doors/MATLAB/100-doors-5.m b/Task/100-doors/MATLAB/100-doors-5.m index cbe97b4f9b..4e7da60177 100644 --- a/Task/100-doors/MATLAB/100-doors-5.m +++ b/Task/100-doors/MATLAB/100-doors-5.m @@ -1,3 +1,15 @@ -doors((1:10).^2) = 1; +function [doors,opened,closed] = hundredDoors() -doors + %Initialize the doors, make them booleans for easy vectorization + doors = logical( (1:1:100) ); + + %Go through the flipping process, ignore the 1 case because the doors + %array is already initialized to all open + for initialPosition = (2:100) + doors(initialPosition:initialPosition:100) = not( doors(initialPosition:initialPosition:100) ); + end + + opened = find(doors); %Stores the numbers of the open doors + closed = find( not(doors) ); %Stores the numbers of the closed doors + +end diff --git a/Task/100-doors/MATLAB/100-doors-6.m b/Task/100-doors/MATLAB/100-doors-6.m new file mode 100644 index 0000000000..cbe97b4f9b --- /dev/null +++ b/Task/100-doors/MATLAB/100-doors-6.m @@ -0,0 +1,3 @@ +doors((1:10).^2) = 1; + +doors diff --git a/Task/100-prisoners/Koka/100-prisoners.koka b/Task/100-prisoners/Koka/100-prisoners.koka new file mode 100644 index 0000000000..73b8b0b56a --- /dev/null +++ b/Task/100-prisoners/Koka/100-prisoners.koka @@ -0,0 +1,90 @@ +import std/num/random + +value struct drawer + num: int + open: bool = False + +inline extern unsafe-assign : forall ( v : vector, i : ssize_t, x : a ) -> total () + c "kk_vector_unsafe_assign" + +fun createDrawers() + val drawers = vector(100, Drawer(0,open=True)) + for(0, 99) fn(i) + var found := False + while {!found} + val r = random-int() % 100 + if drawers[r].open then + drawers.unsafe-assign(r.ssize_t, Drawer(i)) + found := True + else + () + drawers + +fun closeAll(d:vector) + for(0,99) fn(i) + d.unsafe-assign(i.ssize_t, d[i](open=False)) + +effect fail + final ctl failed(): a + +fun open-random(drawers: vector) + val r = random-int() % 100 + val opened = drawers[r] + if opened.open then + open-random(drawers) + else + drawers.unsafe-assign(r.ssize_t, opened(open=True)) + opened.num + +fun random-approach(drawers: vector) + for(0, 99) fn(i) + var found := False + for(0, 49) fn(j) + val opened = open-random(drawers) + if opened == i then + found := True + else + () + if !found then + failed() + else + drawers.closeAll() + +fun optimal-approach(drawers: vector) + for(0, 99) fn(i) + var found := False + var drawer := i; + for(0, 49) fn(j) + val opened = drawers[drawer] + if opened.open then + failed() + if opened.num == i then + found := True + else + drawers.unsafe-assign(drawer.ssize_t, opened(open=True)) + drawer := opened.num + if !found then + failed() + else + drawers.closeAll() + () + +fun run-trials(f, num-trials) + var num_success := 0 + for(0,num-trials - 1) fn(i) + val drawers = createDrawers() + with handler + return(x) -> + num_success := num_success + 1 + final ctl failed() -> + () + f(drawers) + num_success + +fun main() + val num_trials = 1000 + val num_success_random = run-trials(random-approach, num_trials) + val num_success_optimal = run-trials(optimal-approach, num_trials) + println("Number of trials: " ++ num_trials.show) + println("Random approach: wins " ++ num_success_random.show ++ " (" ++ (num_success_random.float64 * 100.0 / num_trials.float64).show(2) ++ "%)") + println("Optimal approach: wins " ++ num_success_optimal.show ++ " (" ++ (num_success_optimal.float64 * 100.0 / num_trials.float64).show(2) ++ "%)") diff --git a/Task/15-puzzle-game/Koka/15-puzzle-game.koka b/Task/15-puzzle-game/Koka/15-puzzle-game.koka new file mode 100644 index 0000000000..0e444d20b1 --- /dev/null +++ b/Task/15-puzzle-game/Koka/15-puzzle-game.koka @@ -0,0 +1,100 @@ +import std/num/random +import std/os/readline +struct board + cells: vector> + hole-pos: (int, int) + size: (int, int) + +type move + MUp + MDown + MLeft + MRight + +fun delta(move: move): (int, int) + match move + MUp -> (0, 1) + MDown -> (0, -1) + MLeft -> (1, 0) + MRight -> (-1, 0) + +inline extern unsafe-assign : forall ( v : vector, i : ssize_t, x : a ) -> total () + c "kk_vector_unsafe_assign" + +fun update(game: board, move: move): exn board + val (dx, dy) = move.delta + val (hx, hy) = game.hole-pos + val (nx, ny) = (hx + dx, hy + dy) + val (w, h) = game.size + if nx >= 0 && nx < w && ny >= 0 && ny < h then + game.cells[hx].unsafe-assign(hy.ssize_t, game.cells[nx][ny]) + game.cells[nx].unsafe-assign(ny.ssize_t, 0) + game(hole-pos=(nx, ny)) + else + game + +val num_shuffles = 100 + +fun random-move(): random move + match random-int() % 4 + 0 -> MUp + 1 -> MDown + 2 -> MLeft + _ -> MRight + +fun setup(size: (int, int)): board + val (w, h) = size + val cells = vector-init(w, fn(x) vector-init(h, fn(y) x*h + y + 1)) + var game := Board(cells, (w - 1, h - 1), size) + for(0,num_shuffles) fn(_) + game := game.update(random-move()) + game + +effect break + final ctl break(a: a) : b + +fun finished(game: board): exn bool + val (w, h) = game.size + var i := 1 + with final ctl break(a:bool) + a + for(0,w - 1) fn(x) + for(0,h - 1) fn(y) + if game.cells[x][y] != i then + break(False) + else + i := i + 1 + True + +fun display(game: board): () + println("") + val (w, h) = game.size + for(0, h - 1) fn(y) + for(0, w - 1) fn(x) + val c = game.cells[x][y] + if c == 0 then + print(" ") + else + print(" " ++ c.show ++ " ") + println("") + println("") + +fun get_move(): > move + val c = readline() + match c.trim() + "w" -> MUp + "s" -> MDown + "a" -> MLeft + "d" -> MRight + "q" -> break("Finished") + _ -> get_move() + +fun main() + var game := setup((4, 4)) + with final ctl break(a:string) + a.println + while {!game.finished} + game.display + val move = get_move() + game := game.update(move) + println("You won!") diff --git a/Task/21-game/Fortran/21-game-3.f b/Task/21-game/Fortran/21-game-3.f new file mode 100644 index 0000000000..1135a113fd --- /dev/null +++ b/Task/21-game/Fortran/21-game-3.f @@ -0,0 +1,104 @@ +begin globals +begin enum 1 + _btn1 + _btn2 + _btn3 + _sum + _msg + _popup + _skill + _human = 0 + _robot +end enum +str15 cr : cr = chr$(13) +str255 string(1) : short who = _human +byte best(3), sum, num, skill = 1 //Medium skill +poke int @best(0), 33751297 //Initialize computer responses +end globals + +local fn buildWindow + subclass window 1, @"21 Game in FutureBasic" , ( 0, 0,640,200 ) + popupbutton _popup,, 1, @"Minimum;Medium;Maximum" , ( 80, 17,100, 32 ) + textlabel _msg , @"Original code: J. Reeve", ( 20,160,600, 32 ) + textlabel _skill , @"Skill level:", ( 20, 12, 75, 32 ) + textfield _sum ,, @"0",( 530,85,90,60 ) + button _btn1 ,, , @"1",( 245,20,50,50 ),,NSBezelStyleRegularSquare + button _btn2 ,, , @"2",( 295,20,50,50 ),,NSBezelStyleRegularSquare + button _btn3 ,, , @"3",( 345,20,50,50 ),,NSBezelStyleRegularSquare + ControlSetAlignment( _msg, NSTextAlignmentCenter ) + ControlSetAlignment( _sum, NSTextAlignmentCenter ) + TextFieldSetEditable( _sum, no ) + ControlSetFontWithName( _msg, @"Menlo", 15.0 ) + ControlSetFontWithName( _btn1, @"Menlo", 20.0 ) + ControlSetFontWithName( _btn2, @"Menlo", 20.0 ) + ControlSetFontWithName( _btn3, @"Menlo", 20.0 ) + ControlSetFontWithName( _sum, @"Menlo", 32.0 ) + text @"menlo", 15.0 +end fn + +local fn show( add as byte ) + CFStringRef msg + if (sum + add) > 21 then beep : exit fn + button 1, who : button 2, who : button 3, who + sum += add : cls + ControlSetIntegerValue( _sum, sum ) + string( who ) += "+" + chr$( add or 48 ) + " " + print cr;cr;cr;string( _human );cr;cr;string( _robot ) + if sum < 21 + if who == _robot then msg = @"Your turn..." else msg = @"My turn..." + else + if who == _robot + msg = @"Too bad. I win. Press any key to play again." + else + msg = @"Congratulations! YOU WIN! Press any key to play again." + end if + end if + if peek( @string( who ) ) > 20 then textlabel _msg, msg + who = who xor _robot +end fn + +local fn play( add as byte ) + if sum + add > 21 then beep : exit fn + fn show( add ) //Show human's play + if sum < 21 + if (skill + maybe) > 0 then num = best(sum mod 4) else num = rnd(3) + if sum + num > 21 then num = 21 - sum + timerbegin 1.0, NO //wait a sec before playing + fn show( num ) //Show computer's play + timerend + end if +end fn + +local fn start + sum = 0 : cls + string( _human ) = " You: " : string( _robot ) = " Computer: " + string( 1-who ) += " " + if who == _robot + if skill == 2 then num = 1 else num = rnd( 3 ) + textlabel _msg, fn StringWithFormat( @"I'll start with %i.", num ) + fn show( num ) + else + ControlSetIntegerValue( _sum, sum ) + textlabel _msg, @"You start. Type or click 1, 2, or 3." + end if +end fn + +local fn DoDialog( evt as long, tag as long) + byte key + select ( evt ) + case _windowKeyUp + if sum == 21 then fn start : exit fn + if who == _robot then exit fn + key = intval( fn EventCharacters ) + if key > 0 && key < 4 then fn play( key ) + case _btnClick + if tag < _popup then beep : fn play( tag ) : exit fn + skill = popupbutton( _popup ) + case _windowWillClose : end + end select +end fn + +fn buildWindow +fn start +on dialog fn doDialog +handleevents diff --git a/Task/21-game/Koka/21-game.koka b/Task/21-game/Koka/21-game.koka new file mode 100644 index 0000000000..cc632672f6 --- /dev/null +++ b/Task/21-game/Koka/21-game.koka @@ -0,0 +1,58 @@ +import std/num/random +import std/os/readline + +effect exit + final ctl exit(): () + +type player + Player + Computer + +fun other(p: player): player + match p + Player -> Computer + Computer -> Player + +fun show(p: player): string + match p + Player -> "Player" + Computer -> "Computer" + +fun get-selection(max-int: int) + val i = readline().trim().parse-int() + match i + Just(x) | x >= 1 && x <= max-int -> x + _ -> + println("Please enter a number between 1 and " ++ max-int.show ++ " or press q to quit") + get-selection(max-int) + +fun play(p: player, total: int) + println("Total: " ++ total.show) + match total + 21 -> + // The player who reaches 21 wins the game, which is the player in the last loop + println(p.other.show ++ " wins!") + return () + _ -> () + val max = if total + 3 > 21 then 21 - total else 3 + match p + Player -> + println("Player's turn") + val selection = get-selection(max) + play(p.other, total + selection) + Computer -> + println("Computer's turn") + val selection = (random-int() % max) + 1 + println("Computer chooses " ++ selection.show) + play(p.other, total + selection) + +fun main() + with final ctl exit() () + "21 is a two player game. The game is played by choosing a number (1, 2, 3) to".println + "be added to the running total. The game is won by the player whose chosen number".println + "causes the running total to reach exactly 21. The running total starts at zero.".println + "".println + "You can quit the game at any time by typing 'q'.".println + val playerGoesFirst = random-bool() + val p1 = if playerGoesFirst then Player else Computer + play(p1, 0) diff --git a/Task/24-game/Koka/24-game.koka b/Task/24-game/Koka/24-game.koka new file mode 100644 index 0000000000..80b9b221ea --- /dev/null +++ b/Task/24-game/Koka/24-game.koka @@ -0,0 +1,97 @@ +import std/num/random +import std/os/readline + +type expr + Num(i: int) + Add(e1: expr, e2: expr) + Sub(e1: expr, e2: expr) + Mul(e1: expr, e2: expr) + Div(e1: expr, e2: expr) + +fun genNum() + random-int() % 9 + 1 + +fun parseFact(s: string): (expr, string) + match s.head + "(" -> + val (e, rest) = s.tail.parseExpr() + match rest.head + ")" -> (e, rest.tail) + _ -> throw("expected ')'") + x | x.head-char.default('_').is-digit -> (Num(x.parse-int.unjust), s.tail) + _ -> throw("No factor") + +fun parseTerm(s): (expr, string) + val (e', n) = s.parseFact() + match n.head + "*" -> + val (e'', n') = n.tail.parseTerm() + (Mul(e', e''), n') + "/" -> + val (e'', n') = n.tail.parseTerm() + (Div(e', e''), n') + _ -> (e', n) + +fun parseExpr(s): (expr, string) + val (e', n) = s.parseTerm() + match n.head + "+" -> + val (e'', n') = n.tail.parseExpr() + (Add(e', e''), n') + "-" -> + val (e'', n') = n.tail.parseExpr() + (Sub(e', e''), n') + _ -> (e', n) + +fun numbers(e: expr): div list + match e + Num(i) -> [i] + Add(e1, e2) -> numbers(e1) ++ numbers(e2) + Sub(e1, e2) -> numbers(e1) ++ numbers(e2) + Mul(e1, e2) -> numbers(e1) ++ numbers(e2) + Div(e1, e2) -> numbers(e1) ++ numbers(e2) + +fun check(e: expr, l: list): () + val ns = numbers(e) + if (ns.length == 4) then + if l.all(fn(n) ns.any(fn(x) x == n)) then + () + else + throw("wrong numbers") + else + throw("wrong number of numbers") + +fun evaluate(e: expr): float64 + match e + Num(i) -> i.float64 + Add(e1, e2) -> evaluate(e1) + evaluate(e2) + Sub(e1, e2) -> evaluate(e1) - evaluate(e2) + Mul(e1, e2) -> evaluate(e1) * evaluate(e2) + Div(e1, e2) -> evaluate(e1) / evaluate(e2) + +fun main() + println("\nGoal: ") + println("- Create an expression that evaluates to 24") + println("- Using the four given numbers each number once") + println("- Using the operators (+-/*) with no spaces") + println("Example 2 3 4 1: (2+3)*4*1\n") + println("Here are your numbers!") + var l: list := Nil + repeat(4) fn() + val n = genNum() + l := Cons(n, l) + (n.show ++ " ").print + println("") + var found := False + while { !found } fn() + val (expr, r) = readline().parseExpr() + if r.count > 0 then + println("Expected EOF but got: " ++ r ++ " please try again") + return () + expr.check(l) + val result = expr.evaluate() + if result == 24.0 then + println("You got it!") + found := True + else + println("Try again, your expression evaluated to: " ++ result.show) diff --git a/Task/4-rings-or-4-squares-puzzle/Koka/4-rings-or-4-squares-puzzle.koka b/Task/4-rings-or-4-squares-puzzle/Koka/4-rings-or-4-squares-puzzle.koka new file mode 100644 index 0000000000..866197f29e --- /dev/null +++ b/Task/4-rings-or-4-squares-puzzle/Koka/4-rings-or-4-squares-puzzle.koka @@ -0,0 +1,39 @@ +fun is_unique(a: int, b: int, c: int, d: int, e: int, f: int, g: int) + a != b && a != c && a != d && a != e && a != f && a != g && + b != c && b != d && b != e && b != f && b != g && + c != d && c != e && c != f && c != g && + d != e && d != f && d != g && + e != f && e != g && + f != g + +fun is_solution(a: int, b: int, c: int, d: int, e: int, f: int, g: int) + val bcd = b + c + d + val ab = a + b + if ab != bcd then return False + val def = d + e + f + if bcd != def then return False + val fg = f + g + return def == fg + +fun four_squares(low: int, high: int, unique:bool=True) + var count := 0 + for(low, high) fn(a) + for(low, high) fn(b) + for(low, high) fn(c) + for(low, high) fn(d) + for(low, high) fn(e) + for(low, high) fn(f) + for(low, high) fn(g) + if (!unique || is_unique(a, b, c, d, e, f, g)) && is_solution(a, b, c, d, e, f, g) then + count := count + 1 + if unique then + println([a, b, c, d, e, f, g].show) + else + () + val uniquestr = if unique then "unique" else "non-unique" + println(count.show ++ " " ++ uniquestr ++ " solutions in " ++ low.show ++ " to " ++ high.show ++ " range\n") + +fun main() + four_squares(1, 7) + four_squares(3, 9) + four_squares(0, 9, False) diff --git a/Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer.st b/Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer-1.st similarity index 100% rename from Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer.st rename to Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer-1.st diff --git a/Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer-2.st b/Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer-2.st new file mode 100644 index 0000000000..464c4f3a9f --- /dev/null +++ b/Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer-2.st @@ -0,0 +1,11 @@ +|bottles plurals | +Transcript clear. +bottles:='{1} bottle{2} of beer on the wall +{1} bottle{2} of beer +Take one down, pass it around +{3} bottle{4} of beer on the wall'. +plurals := #('' 's'). +99 to: 1 by: -1 do:[:v | + Transcript show: (bottles format: {(v asString) . (plurals atPin:v) . ((v -1) asString). (plurals atPin:v) }); cr; cr]. + +Transcript show: 'hic!'; cr. diff --git a/Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer-3.st b/Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer-3.st new file mode 100644 index 0000000000..edd0d9d884 --- /dev/null +++ b/Task/99-bottles-of-beer/Smalltalk/99-bottles-of-beer-3.st @@ -0,0 +1,13 @@ + | bottles | + Transcript clear. + bottles := '{1} {2} of beer on the wall + {1} {2} of beer + Take one down, pass it around + {3} {4} of beer on the wall'. + 99 to: 1 by: -1 do: [:i | + Transcript + show: (bottles format: { + i. 'bottle' asPluralBasedOn: i. + i - 1. 'bottle' asPluralBasedOn: i - 1}); + cr; cr]. + Transcript show: 'hic!'; cr. diff --git a/Task/ABC-problem/Elm/abc-problem.elm b/Task/ABC-problem/Elm/abc-problem.elm new file mode 100644 index 0000000000..6dc7d8a27b --- /dev/null +++ b/Task/ABC-problem/Elm/abc-problem.elm @@ -0,0 +1,59 @@ +import Html exposing (div, p, text) + + +type alias Block = (Char, Char) + + +writtenWithBlock : Char -> Block -> Bool +writtenWithBlock letter (firstLetter, secondLetter) = + letter == firstLetter || letter == secondLetter + + +canMakeWord : List Block -> String -> Bool +canMakeWord blocks word = + let + checkWord w examinedBlocks blocksToExamine = + case (String.uncons w, blocksToExamine) of + (Nothing, _) -> True + (Just _, []) -> False + (Just (firstLetter, restOfWord), firstBlock::restOfBlocks) -> + if writtenWithBlock firstLetter firstBlock + then checkWord restOfWord [] (examinedBlocks ++ restOfBlocks) + else checkWord w (firstBlock::examinedBlocks) restOfBlocks + in + checkWord (String.toUpper word) [] blocks + + +exampleBlocks = + [ ('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') + ] + + +exampleWords = + ["", "A", "bark", "BoOK", "TrEAT", "COmMoN", "Squad", "conFUsE"] + + +main = + let resultStr (word, canBeWritten) = "\"" ++ word ++ "\"" ++ ": " ++ if canBeWritten then "True" else "False" in + List.map (\ word -> (word, canMakeWord exampleBlocks word) |> resultStr) exampleWords + |> List.map (\result -> p [] [ text result ]) + |> div [] diff --git a/Task/ABC-problem/FutureBasic/abc-problem-1.basic b/Task/ABC-problem/FutureBasic/abc-problem-1.basic new file mode 100644 index 0000000000..5097485aa6 --- /dev/null +++ b/Task/ABC-problem/FutureBasic/abc-problem-1.basic @@ -0,0 +1,30 @@ +include "NSLog.incl" + +local fn CanBlocksSpell( w as CFStringRef ) as CFStringRef +NSUInteger i, j +CFStringRef s = @"", t1, t2 : if fn StringIsEqual( w, @"" ) then exit fn = @"YES" else w = ucase(w) + +mda(0) = {@"BO",@"XK",@"DQ",@"CP",@"NA",@"GT",@"RE",@"TG",@"QD",¬ +@"FS",@"JW",@"HU",@"VI",@"AN",@"OB",@"ER",@"FS",@"LY",@"PC",@"ZM"} + +for i = 0 to len(w) - 1 +for j = 0 to mda_count - 1 +t1 = mid( mda(j), 0, 1 ) : t2 = mid( mda(j), 1, 1 ) +if ( fn StringIsEqual( mid( w, i, 1 ), t1 ) ) then s = fn StringByAppendingString( s, t1 ) : mda(j) = @" " : break +if ( fn StringIsEqual( mid( w, i, 1 ), t2 ) ) then s = fn StringByAppendingString( s, t2 ) : mda(j) = @" " : break +next +next +if fn StringIsEqual( s, w ) then exit fn = @"YES" +end fn = @"NO" + +NSUInteger i +CFArrayRef words +CFStringRef w +words = @[@"", @"a",@"Bark",@"BOOK",@"TrEaT",@"COMMON",@"Squad",@"conFUse",@"ABBA",@"aUtO"] +for w in words +printf @"Can blocks spell %7s : %@", fn StringUTF8String( w ), fn CanBlocksSpell( w ) +next + +NSLog( @"%@", fn WindowPrintViewString( 1 ) ) + +HandleEvents diff --git a/Task/ABC-problem/FutureBasic/abc-problem-2.basic b/Task/ABC-problem/FutureBasic/abc-problem-2.basic new file mode 100644 index 0000000000..0919078013 --- /dev/null +++ b/Task/ABC-problem/FutureBasic/abc-problem-2.basic @@ -0,0 +1,18 @@ +local fn blocks( wordList as str255 ) + sint16 found, r, x = 3, y = -9 : str63 ch, blocks : ch = " " : blocks = " " + for r = 1 to len$( wordList ) +1 + found = instr$( 1, blocks, ch ) + select found + case > 3: mid$( blocks, found and -2, 2 ) = "__" : text , , fn ColorYellow + rect fill ( x, y + 5.5, 15, 15 ), fn ColorBrown + case 0: text , , fn ColorLightGray + case < 4: blocks=" ,;BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM": x=3: y+=26: ch="" + end select + text @"Courier New Bold", 16 : print %( x + 2.5, y ) ch : x += 17 + ch = ucase$( mid$( wordList, r, 1 ) ) + next +end fn + +window 1, @"ABC problem in FutureBasic", ( 0, 0, 300, 300 ) +fn blocks( "a baRk booK;treat,COMMON squad Confused comparable incomparable nondeductibles" ) +handleevents diff --git a/Task/ABC-problem/FutureBasic/abc-problem.basic b/Task/ABC-problem/FutureBasic/abc-problem.basic deleted file mode 100644 index fd1ef5c0ef..0000000000 --- a/Task/ABC-problem/FutureBasic/abc-problem.basic +++ /dev/null @@ -1,41 +0,0 @@ -include "NSLog.incl" - -local fn CanBlocksSpell( w as CFStringRef ) as CFStringRef - NSUInteger i, j - CFStringRef cFinal = @"", result = @"NO" - CFMutableArrayRef blocks - - blocks = fn MutableArrayWithArray( @[@"BO", @"XK", @"DQ", @"CP",¬ - @"NA", @"GT", @"RE", @"TG", @"QD", @"FS", @"JW", @"HU", @"VI",¬ - @"AN", @"OB", @"ER", @"FS", @"LY", @"PC", @"ZM"] ) - - CFStringRef cfStr = fn StringUppercaseString( w ) - NSUInteger length = fn StringLength( cfStr ) - NSUInteger count = fn ArrayCount( blocks ) - - for i = 0 to length - 1 - for j = 0 to count - 1 - CFStringRef charStr = mid( cfStr, i, 1 ) - CFStringRef compareStr = fn ArrayObjectAtIndex( blocks, j ) - CFStringRef testStr1 = mid( compareStr, 0, 1 ) - CFStringRef testStr2 = mid( compareStr, 1, 1 ) - if ( fn StringIsEqual( charStr, testStr1 ) == YES ) - cFinal = fn StringByAppendingString( cFinal, testStr1 ) : MutableArrayReplaceObjectAtIndex( blocks, @" ", j ) : exit for - end if - if ( fn StringIsEqual( charStr, testStr2 ) == YES ) - cFinal = fn StringByAppendingString( cFinal, testStr2 ) : MutableArrayReplaceObjectAtIndex( blocks, @" ", j ) : exit for - end if - next - next - if fn StringIsEqual( cFinal, cfStr ) == YES then result = @"YES" -end fn = result - -NSLog( @"a: Can blocks spell? %@", fn CanBlocksSpell( @"a" ) ) -NSLog( @"Bark: Can blocks spell? %@", fn CanBlocksSpell( @"Bark" ) ) -NSLog( @"BOOK: Can blocks spell? %@", fn CanBlocksSpell( @"BOOK" ) ) -NSLog( @"TrEaT: Can blocks spell? %@", fn CanBlocksSpell( @"TrEaT" ) ) -NSLog( @"COMMON: Can blocks spell? %@", fn CanBlocksSpell( @"COMMON" ) ) -NSLog( @"Squad: Can blocks spell? %@", fn CanBlocksSpell( @"Squad" ) ) -NSLog( @"conFUse: Can blocks spell? %@", fn CanBlocksSpell( @"conFUse" ) ) - -HandleEvents diff --git a/Task/ABC-problem/Koka/abc-problem.koka b/Task/ABC-problem/Koka/abc-problem.koka new file mode 100644 index 0000000000..0657cb3cbe --- /dev/null +++ b/Task/ABC-problem/Koka/abc-problem.koka @@ -0,0 +1,42 @@ +val 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")] + +pub fun get-remove( xs : list, pred : a -> bool, acc: ctx>) : (maybe, list) + match xs + Cons(x,xx) -> if !pred(x) then xx.get-remove(pred, acc ++ ctx Cons(x, _)) else (Just(x), acc ++. xx) + Nil -> (Nothing, acc ++. Nil) + +fun check-word(word: string, blocks: list<(string, string)>) + match word.head + "" -> True + x -> + val (a, l) = blocks.get-remove(fn(a) a.fst == x || a.snd == x, ctx _) + match a + Nothing -> False + Just(_) -> check-word(word.tail, l) + +fun can-make-word(word, blocks: list<(string, string)>) + check-word(word.to-upper, blocks) + +fun main() + val words = ["", "a", "baRk", "booK", "treat", "COMMON", "squad", "Confused"] + words.map(fn(a) (a, can-make-word(a, blocks))).foreach fn((w, b)) + println(w.show ++ " " ++ (if b then "can" else "cannot") ++ " be made") diff --git a/Task/ADFGVX-cipher/AArch64-Assembly/adfgvx-cipher.aarch64 b/Task/ADFGVX-cipher/AArch64-Assembly/adfgvx-cipher.aarch64 new file mode 100644 index 0000000000..9ef36ef4d6 --- /dev/null +++ b/Task/ADFGVX-cipher/AArch64-Assembly/adfgvx-cipher.aarch64 @@ -0,0 +1,792 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program adfgvx64.s */ +/* remark 1 : At each launch, the random values are identical. + To change them, modify the value of the seed (graine) */ +/* remark 2 : this program not run in android with termux + because the call system stats is not find */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +.equ SIZE, 6 +.equ SIZEC, SIZE * SIZE +.equ KEYSIZE, 9 +.equ FSTAT, 80 +.equ O_RDWR, 0x0002 // open for reading and writing + +/*******************************************/ +/* Structures **/ +/*******************************************/ +/* structure de type stat 64 bits : infos fichier */ + .struct 0 +Stat_dev_t: // ID of device containing file + .struct Stat_dev_t + 8 +Stat_ino_t: // inode + .struct Stat_ino_t + 4 +Stat_mode_t: // File type and mode + .struct Stat_mode_t + 4 +Stat_nlink_t: // Number of hard links + .struct Stat_nlink_t + 4 +Stat_uid_t: // User ID of owner + .struct Stat_uid_t + 8 +Stat_gid_t: // Group ID of owner + .struct Stat_gid_t + 8 +Stat_rdev_t: // Device ID (if special file) + .struct Stat_rdev_t + 8 +Stat_size_deb: // la taille est sur 8 octets si gros fichiers + .struct Stat_size_deb + 4 +Stat_size_t: // Total size, in bytes + .struct Stat_size_t + 4 +Stat_blksize_t: // Block size for filesystem I/O + .struct Stat_blksize_t + 4 +Stat_blkcnt_t: // Number of 512B blocks allocated + .struct Stat_blkcnt_t + 4 +Stat_atime: // date et heure fichier + .struct Stat_atime + 8 +Stat_mtime: // date et heure modif fichier + .struct Stat_atime + 8 +Stat_ctime: // date et heure creation fichier + .struct Stat_atime + 8 +Stat_Fin: + + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szText: .asciz "ATTACKAT1200AM" +//szText: .asciz "ABCDEFGHIJ" +szMessOpen: .asciz "File open error.\n" +szMessStat: .asciz "File information error.\n" +szMessRead: .asciz "File read error.\n" +szMessClose: .asciz "File close error.\n" +szMessDecryptText: .asciz "Decrypted text :\n" +szMessCryptText: .asciz "Encrypted text :\n" +szMessErrorChar: .asciz "Character text not Ok!\n" +szFileName: .asciz "unixdict.txt" +szMessPolybius: .asciz "6 x 6 Polybius square:\n" +szTitle: .asciz " | A D F G V X\n---------------\n" +szLine1: .asciz "A | \n" +szLine2: .asciz "D | \n" +szLine3: .asciz "F | \n" +szLine4: .asciz "G | \n" +szLine5: .asciz "V | \n" +szLine6: .asciz "X | \n" +szListCharCode: .asciz "ADFGVX" +szListChar: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" +.equ LGLISTCHAR, . - szListChar - 1 +szMessStart: .asciz "Program 64 bits start.\n" +szCarriageReturn: .asciz "\n" +.align 4 + +qGraine: .quad 1234567 // random init + +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sKeyWord: .skip 16 +sKeyWordSorted: .skip 16 +tabPolybius: .skip SIZE * SIZE + 4 +sBuffer: .skip 1000 +sBuffex1: .skip 1000 +sBuffex2: .skip 1000 +tabPosit: .skip 16 +tabPositInv: .skip 16 +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: // entry of program + ldr x0,qAdrszMessStart + bl affichageMess + bl createPolybius // create 6*6 polybius + + ldr x0,qAdrsKeyWord + bl generateKey // generate key + cmp x0,#-1 // file error ? + beq 100f + bl affichageMess // display key + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessCryptText + bl affichageMess + ldr x0,qAdrszText // text encrypt + ldr x1,qAdrtabPolybius + ldr x2,qAdrsKeyWord + ldr x3,qAdrsBuffer // result buffer + bl encryption + cmp x0,#-1 // error if unknow character in text + beq 100f + bl affichageMess // display text encrypted + ldr x0,qAdrszCarriageReturn + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + ldr x0,qAdrszMessDecryptText + bl affichageMess + ldr x0,qAdrsBuffer // text decrypt + ldr x1,qAdrtabPolybius + ldr x2,qAdrsKeyWord + ldr x3,qAdrsBuffex1 // result buffer + bl decryption + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + +100: // standard end of the program + mov x0, #0 // return code + mov x8, #EXIT // request to exit program + svc #0 // perform the system call + +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessDecryptText: .quad szMessDecryptText +qAdrszMessCryptText: .quad szMessCryptText +qAdrszMessStart: .quad szMessStart +qAdrsKeyWord: .quad sKeyWord +qAdrszText: .quad szText +/***************************************************/ +/* create 6 * 6 polybius */ +/***************************************************/ +createPolybius: + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + ldr x0,qAdrszListChar // character list address + mov x1,#LGLISTCHAR // character list size + ldr x2,qAdrtabPolybius + bl shufflestrings // shuffle list + ldr x0,qAdrszMessPolybius + bl affichageMess + ldr x0,qAdrszTitle // display polybius lines + bl affichageMess + ldr x0,qAdrszLine1 + mov x3,#0 + mov x4,#4 +1: + ldrb w1,[x2,x3] + strb w1,[x0,x4] + add x4,x4,#2 + add x3,x3,#1 + cmp x3,#SIZE + blt 1b + bl affichageMess + ldr x0,qAdrszLine2 + mov x3,#SIZE + mov x4,#4 +2: + ldrb w1,[x2,x3] + strb w1,[x0,x4] + add x4,x4,#2 + add x3,x3,#1 + cmp x3,#SIZE * 2 + blt 2b + bl affichageMess + ldr x0,qAdrszLine3 + mov x3,#SIZE * 2 + mov x4,#4 +3: + ldrb w1,[x2,x3] + strb w1,[x0,x4] + add x4,x4,#2 + add x3,x3,#1 + cmp x3,#SIZE * 3 + blt 3b + bl affichageMess + ldr x0,qAdrszLine4 + mov x3,#SIZE * 3 + mov x4,#4 +4: + ldrb w1,[x2,x3] + strb w1,[x0,x4] + add x4,x4,#2 + add x3,x3,#1 + cmp x3,#SIZE * 4 + blt 4b + bl affichageMess + ldr x0,qAdrszLine5 + mov x3,#SIZE * 4 + mov x4,#4 +5: + ldrb w1,[x2,x3] + strb w1,[x0,x4] + add x4,x4,#2 + add x3,x3,#1 + cmp x3,#SIZE * 5 + blt 5b + bl affichageMess + ldr x0,qAdrszLine6 + mov x3,#SIZE * 5 + mov x4,#4 +6: + ldrb w1,[x2,x3] + strb w1,[x0,x4] + add x4,x4,#2 + add x3,x3,#1 + cmp x3,#SIZE * 6 + blt 6b + bl affichageMess + +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +qAdrszListChar: .quad szListChar +qAdrtabPolybius: .quad tabPolybius +qAdrszMessPolybius: .quad szMessPolybius +qAdrszTitle: .quad szTitle +qAdrszLine1: .quad szLine1 +qAdrszLine2: .quad szLine2 +qAdrszLine3: .quad szLine3 +qAdrszLine4: .quad szLine4 +qAdrszLine5: .quad szLine5 +qAdrszLine6: .quad szLine6 +/***************************************************/ +/* generate key word */ +/***************************************************/ +/* x0 key word address */ +generateKey: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + stp x10,x11,[sp,-16]! + stp x12,x13,[sp,-16]! + mov x9,x0 + mov x0,AT_FDCWD + ldr x1,qAdrszFileName // file name + mov x2,#O_RDWR // flags + mov x3,#0 // mode + mov x8,#OPEN // file open + svc 0 + cmp x0,#0 // error ? + ble 99f + mov x11,x0 // FD save + ldr x1,qAdrsBuffer // buffer address + mov x8, #FSTAT // call systeme NEWFSTAT + svc 0 + cmp x0,#0 + blt 98f + // load file size + ldr x1,qAdrsBuffer // buffer address + ldr w6,[x1,#Stat_size_t] // file size + //ldr w6,[x1,mbox_data_size] + lsr x12,x6,#5 // align size to multiple 16 for stack alignement + lsl x12,x12,#5 + add x12,x12,#32 // add for great buffer + sub sp,sp,x12 // reserve buffer on stack + mov fp,sp // address save + mov x0,x11 + mov x1,fp + mov x2,x12 + mov x8,#READ // call system read file + svc 0 + cmp x0,#0 // error read ? + blt 97f + mov x0,x11 + mov x8,#CLOSE // call system close file + svc 0 + cmp x0,#0 // error close ? + blt 96f + sub sp,sp,#0x1000 // create array word address on stack + mov x10,sp // save address array + mov x1,#0 + mov x2,fp + mov x5,#0 // index word ok + mov x3,#0 // word length +1: + ldrb w4,[fp,x1] // load character + cmp w4,#0x0D // end word ? + beq 2f // yes + add x1,x1,#1 + add x3,x3,#1 + b 1b +2: + cmp x3,#KEYSIZE // word length = key length ? + bne 3f // no ? + mov x0,x2 + bl wordControl // contril if all letters are différent ? + cmp x0,#1 + bne 3f + str x2,[x10,x5,lsl #3] // if ok store word address in array on stack + add x5,x5,#1 // increment word counter +3: + add x1,x1,#2 + cmp x1,x6 // end ? + beq 4f + add x2,fp,x1 // new word begin + mov x3,#0 // init word length + b 1b // and loop +4: + mov x0,x5 // number random to total words + bl genereraleas + ldr x2,[x10,x0,lsl #3] // load address word + mov x1,#0 +5: // copy random word in word result + ldrb w3,[x2,x1] + strb w3,[x9,x1] + add x1,x1,#1 + cmp x1,#KEYSIZE + blt 5b + strb wzr,[x9,x1] // zero final + mov x0,x9 + b 100f + // display errors +96: + ldr x0,qAdrszMessClose + bl affichageMess + mov x0,#-1 // error + b 100f +97: + ldr x0,qAdrszMessRead + bl affichageMess + mov x0,#-1 // error + b 100f +98: + ldr x0,qAdrszMessStat + bl affichageMess + mov x0,#-1 // error + b 101f +99: + ldr x0,qAdrszMessOpen + bl affichageMess + mov x0,#-1 // error + b 101f +100: + add sp,sp,x12 + add sp,sp,#0x1000 +101: + ldp x12,x13,[sp],16 + ldp x10,x11,[sp],16 + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +qAdrszFileName: .quad szFileName +qAdrszMessOpen: .quad szMessOpen +qAdrszMessRead: .quad szMessRead +qAdrszMessStat: .quad szMessStat +qAdrszMessClose: .quad szMessClose +qAdrsBuffer: .quad sBuffer +/******************************************************************/ +/* control if letters are diferents */ +/******************************************************************/ +/* x0 contains the address of the string */ +/* x0 return 1 if Ok else return 0 */ +wordControl: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + mov x1,#0 // init index 1 +1: + ldrb w3,[x0,x1] // load one character + cmp x3,#0x0D // end word ? + mov x5,#1 + csel x0,x5,x0,eq // yes is ok + //moveq x0,#1 // yes is ok + beq 100f // -> end + add x2,x1,#1 // init index two +2: + ldrb w4,[x0,x2] // load one character + cmp w4,#0x0D // end word ? + add x5,x1,1 + csel x1,x5,x1,eq // yes increment index 1 + beq 1b // and loop1 + cmp x3,x4 // caracters equals ? + csel x0,xzr,x0,eq // yes is not good + beq 100f // and end + add x2,x2,#1 // else increment index 2 + b 2b // and loop 2 +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/******************************************************************/ +/* key sort by insertion sort */ +/******************************************************************/ +/* x0 contains the address of String */ +/* x1 contains the first element */ +/* x2 contains the number of element */ +/* x3 contains result address */ +keySort: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + stp x10,x11,[sp,-16]! + ldr x7,qAdrtabPosit + mov x10,x3 + mov x3,#0 +0: // init position array and copy key + strb w3,[x7,x3] // in result array + ldrb w4,[x0,x3] + strb w4,[x10,x3] + add x3,x3,#1 + cmp x3,#KEYSIZE + blt 0b + + add x3,x1,#1 // start index i +1: // start loop + ldrb w4,[x10,x3] // load value A[i] + ldrb w8,[x7,x3] // load position + sub x5,x3,#1 // index j +2: + ldrb w6,[x10,x5] // load value A[j] + ldrb w9,[x7,x5] // load position + cmp x6,x4 // compare value + ble 3f + add x5,x5,#1 // increment index j + strb w6,[x10,x5] // store value A[j+1] + strb w9,[x7,x5] // store position + subs x5,x5,#2 // j = j - 1 + bge 2b // loop if j >= 0 +3: + add x5,x5,#1 // increment index j + strb w4,[x10,x5] // store value A[i] in A[j+1] + strb w8,[x7,x5] + add x3,x3,#1 // increment index i + cmp x3,x2 // end ? + blt 1b // no -> loop + + ldr x1,qAdrtabPositInv // inverse position + mov x2,#0 // index +4: + ldrb w3,[x7,x2] // load position index + strb w2,[x1,x3] // store index in position + add x2,x2,#1 // increment index + cmp x2,#KEYSIZE // end ? + blt 4b + mov x0,x10 +100: + ldp x10,x11,[sp],16 + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // TODO: retaur à completer + ret +qAdrtabPosit: .quad tabPosit +qAdrtabPositInv: .quad tabPositInv +/******************************************************************/ +/* text encryption */ +/******************************************************************/ +/* x0 contains the address of text */ +/* x1 contains polybius address +/* x2 contains the key address */ +/* x3 contains result buffer address */ +encryption: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + stp x10,x11,[sp,-16]! + mov x9,x0 // save text address + mov x8,x3 + mov x10,x1 // save address polybius + mov x0,x2 // key address + mov x1,#0 // first character + mov x2,#KEYSIZE // key length + ldr x3,qAdrsKeyWordSorted // result address + bl keySort // sort leters of key + // bl affichageMess // if you want display sorted key + // ldr x0,qAdrszCarriageReturn + // bl affichageMess + ldr x3,qAdrsBuffex1 + mov x5,#0 // init text index + mov x4,#0 // init result index +1: + ldrb w0,[x9,x5] // load a byte to text + cmp x0,#0 // end ? + beq 4f + mov x6,#0 // init index polybius +2: + ldrb w7,[x10,x6] // load character polybius + cmp x7,x0 // equal ? + beq 3f + add x6,x6,#1 // increment index + cmp x6,#SIZEC // not find -> error + bge 99f + b 2b // and loop +3: + mov x0,x6 + bl convPosCode // convert position in code character + strb w0,[x3,x4] // line code character + add x4,x4,#1 + strb w1,[x3,x4] // column code character + add x4,x4,#1 + + add x5,x5,#1 // increment text index + b 1b +4: + mov x0,#0 // zero final -> text result + strb w0,[x3,x4] + mov x5,x3 + mov x1,#0 // index position column + mov x7,#0 // index text + ldr x2,qAdrtabPositInv +5: + ldrb w0,[x2,x1] // load position text +7: // loop to characters transposition + + ldrb w6,[x5,x0] // load character + strb w6,[x8,x7] // store position final + add x7,x7,#1 // increment final index + add x0,x0,#KEYSIZE // add size key + cmp x0,x4 // end ? + blt 7b + add x1,x1,#1 // add index column + cmp x1,#KEYSIZE // < key size + blt 5b // yes -> loop + + mov x6,#0 // zero final + strb w6,[x8,x7] + mov x0,x8 // return address encrypted text + + b 100f +99: // display error + ldr x0,qAdrszMessErrorChar + bl affichageMess + mov x0,#-1 +100: + ldp x10,x11,[sp],16 + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +qAdrsBuffex1: .quad sBuffex1 +qAdrsKeyWordSorted: .quad sKeyWordSorted +qAdrszMessErrorChar: .quad szMessErrorChar +/******************************************************************/ +/* text decryption */ +/******************************************************************/ +/* x0 contains the address of text */ +/* x1 contains polybius address +/* x2 contains the key */ +/* x3 contains result buffer */ +/* x0 return decoded text */ +decryption: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + stp x10,x11,[sp,-16]! + stp x12,x13,[sp,-16]! + mov x4,#0 +1: // compute text length + ldrb w5,[x0,x4] + cmp x5,#0 + add x11,x4,1 + csel x4,x11,x4,ne + bne 1b + mov x12,x0 + mov x11,x1 + mov x10,x2 + mov x13,x3 + // compute line number and remainder + mov x1,#KEYSIZE // compute line number and remainder + udiv x8,x4,x1 // line number + msub x7,x8,x1,x4 // remainder characters last line + mov x0,x10 // key address + mov x1,#0 // first character + mov x2,#KEYSIZE // size + ldr x3,qAdrsKeyWordSorted // result address + bl keySort // sort key + ldr x10,qAdrtabPositInv // inverse position + mov x2,#0 // index colonne tabposit + mov x5,#0 // text index + mov x0,#0 // index line store text + mov x1,#0 // counter line + + ldr x9,qAdrsBuffex2 +1: + ldrb w3,[x10,x2] // load position + ldrb w6,[x12,x5] // load text character + add x3,x3,x0 // compute position with index line + strb w6,[x9,x3] // store character in good position + + add x5,x5,#1 // increment index text + cmp x5,x4 // end ? + bge 4f + add x1,x1,#1 // increment line + cmp x1,x8 // line < line size + blt 2f + bgt 11f // line = line size + sub x3,x3,x0 // restaure position column + cmp x3,x7 // position < remainder so add character other line + blt 2f +11: + mov x1,#0 // init ligne + mov x0,#0 // init line shift + add x2,x2,#1 // increment index array position inverse + cmp x2,#KEYSIZE // end ? + csel x2,xzr,x2,ge // init index + b 3f +2: + add x0,x0,#KEYSIZE +3: + b 1b +4: // convertir characters with polybius + mov x3,#0 + mov x5,#0 + +5: + mov x0,x11 + ldrb w1,[x9,x3] // load a first character + add x3,x3,#1 + ldrb w2,[x9,x3] // load a 2ieme character + bl decodPosCode // decode + strb w0,[x13,x5] // store result in final result + add x5,x5,#1 // increment final result index + add x3,x3,#1 // increment index text + cmp x3,x4 // end ? + blt 5b + mov x0,#0 // final zero + strb w0,[x13,x5] + mov x0,x13 // return final result address +100: + ldp x12,x13,[sp],16 + ldp x10,x11,[sp],16 + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // TODO: retaur à completer + ret +qAdrsBuffex2: .quad sBuffex2 +/******************************************************************/ +/* convertir position en code */ +/******************************************************************/ +/* x0 contains the position in polybius */ +/* x0 return code1 */ +/* x1 return code2 */ +convPosCode: + stp x2,lr,[sp,-16]! + stp x3,x4,[sp,-16]! + ldr x4,qAdrszListCharCode + mov x1,#SIZE + udiv x2,x0,x1 + msub x3,x2,x1,x0 + //bl division + ldrb w0,[x4,x2] + ldrb w1,[x4,x3] +100: + ldp x3,x4,[sp],16 + ldp x2,lr,[sp],16 + ret +qAdrszListCharCode: .quad szListCharCode +/******************************************************************/ +/* convertir code en character */ +/******************************************************************/ +/* x0 polybius address */ +/* x1 code 1 */ +/* x2 code 2 */ +/* x0 return character */ +decodPosCode: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + ldr x4,qAdrszListCharCode + mov x3,#0 +1: + ldrb w5,[x4,x3] + cmp x5,#0 + beq 2f + cmp x5,x1 + csel x1,x3,x1,eq + cmp x5,x2 + csel x2,x3,x2,eq + add x3,x3,#1 + b 1b +2: + mov x5,#SIZE + mul x1,x5,x1 + add x1,x1,x2 + ldrb w0,[x0,x1] +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret + +/******************************************************************/ +/* shuffle strings algorithme Fisher-Yates */ +/******************************************************************/ +/* x0 contains the address of the string */ +/* x1 contains string length */ +/* x2 contains address result string */ +shufflestrings: + stp x1,lr,[sp,-16]! // TODO: save à completer + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + mov x3,#0 +1: // loop copy string in result + ldrb w4,[x0,x3] + strb w4,[x2,x3] + add x3,x3,#1 + cmp x3,x1 + ble 1b + sub x1,x1,#1 // last element +2: + mov x0,x1 + bl genereraleas // call random + ldrb w4,[x2,x1] // load byte string index loop + ldrb w3,[x2,x0] // load byte string random index + strb w3,[x2,x1] // and exchange + strb w4,[x2,x0] + subs x1,x1,#1 + cmp x1,#1 + bge 2b + +100: + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret + +/***************************************************/ +/* Generation random number */ +/***************************************************/ +/* x0 contains limit */ +genereraleas: + stp x1,lr,[sp,-16]! // save registers + stp x2,x3,[sp,-16]! // save registers + ldr x1,qAdrqGraine + ldr x2,[x1] + ldr x3,qNbDep1 + mul x2,x3,x2 + ldr x3,qNbDep2 + add x2,x2,x3 + str x2,[x1] // maj de la graine pour l appel suivant + cmp x0,#0 + beq 100f + udiv x3,x2,x0 + msub x0,x3,x0,x2 // résult = remainder + +100: // end function + ldp x2,x3,[sp],16 // restaur 2 registers + ldp x1,lr,[sp],16 // restaur 2 registers + ret // return to address lr x30 +qAdrqGraine: .quad qGraine +qNbDep1: .quad 0x0019660d +qNbDep2: .quad 0x3c6ef35f + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../includeARM64.inc" diff --git a/Task/ADFGVX-cipher/ARM-Assembly/adfgvx-cipher.arm b/Task/ADFGVX-cipher/ARM-Assembly/adfgvx-cipher.arm new file mode 100644 index 0000000000..c301c68cea --- /dev/null +++ b/Task/ADFGVX-cipher/ARM-Assembly/adfgvx-cipher.arm @@ -0,0 +1,715 @@ +/* ARM assembly Raspberry PI */ +/* program adfgvx.s */ +/* remark 1 : At each launch, the random values are identical. + To change them, modify the value of the seed (graine) */ +/* remark 2 : this program not run in android with termux + because the call system stats is not find */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for constantes see task include a file in arm assembly */ +.include "../constantes.inc" + +.equ SIZE, 6 +.equ SIZEC, SIZE * SIZE +.equ KEYSIZE, 9 +.equ READ, 3 +.equ WRITE, 4 +.equ OPEN, 5 +.equ CLOSE, 6 +.equ FSTAT, 0x6C +.equ O_RDWR, 0x0002 @ open for reading and writing + +/**********************************************/ +/* structure de type stat : infos fichier */ +/**********************************************/ + .struct 0 +Stat_dev_t: @ ID of device containing file + .struct Stat_dev_t + 4 +Stat_ino_t: @ inode + .struct Stat_ino_t + 2 +Stat_mode_t: @ File type and mode + .struct Stat_mode_t + 2 +Stat_nlink_t: @ Number of hard links + .struct Stat_nlink_t + 2 +Stat_uid_t: @ User ID of owner + .struct Stat_uid_t + 2 +Stat_gid_t: @ Group ID of owner + .struct Stat_gid_t + 2 +Stat_rdev_t: @ Device ID (if special file) + .struct Stat_rdev_t + 2 +Stat_size_deb: @ la taille est sur 8 octets si gros fichiers + .struct Stat_size_deb + 4 +Stat_size_t: @ Total size, in bytes + .struct Stat_size_t + 4 +Stat_blksize_t: @ Block size for filesystem I/O + .struct Stat_blksize_t + 4 +Stat_blkcnt_t: @ Number of 512B blocks allocated + .struct Stat_blkcnt_t + 4 +Stat_atime: @ date et heure fichier + .struct Stat_atime + 8 +Stat_mtime: @ date et heure modif fichier + .struct Stat_atime + 8 +Stat_ctime: @ date et heure creation fichier + .struct Stat_atime + 8 +Stat_Fin: + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szText: .asciz "ATTACKAT1200AM" +//szText: .asciz "ABCDEFGHIJ" +szMessOpen: .asciz "File open error.\n" +szMessStat: .asciz "File information error.\n" +szMessRead: .asciz "File read error.\n" +szMessClose: .asciz "File close error.\n" +szMessDecryptText: .asciz "Decrypted text :\n" +szMessCryptText: .asciz "Encrypted text :\n" +szMessErrorChar: .asciz "Character text not Ok!\n" +szFileName: .asciz "unixdict.txt" +szMessPolybius: .asciz "6 x 6 Polybius square:\n" +szTitle: .asciz " | A D F G V X\n---------------\n" +szLine1: .asciz "A | \n" +szLine2: .asciz "D | \n" +szLine3: .asciz "F | \n" +szLine4: .asciz "G | \n" +szLine5: .asciz "V | \n" +szLine6: .asciz "X | \n" +szListCharCode: .asciz "ADFGVX" +szListChar: .asciz "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" +.equ LGLISTCHAR, . - szListChar - 1 +szMessStart: .asciz "Program 32 bits start.\n" +szCarriageReturn: .asciz "\n" +.align 4 + +iGraine: .int 1234567 // random init + +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sKeyWord: .skip 16 +sKeyWordSorted: .skip 16 +tabPolybius: .skip SIZE * SIZE + 4 +sBuffer: .skip 1000 +sBuffer1: .skip 1000 +sBuffer2: .skip 1000 +tabPosit: .skip 16 +tabPositInv: .skip 16 +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: @ entry of program + ldr r0,iAdrszMessStart + bl affichageMess + bl createPolybius @ create 6*6 polybius + + ldr r0,iAdrsKeyWord + bl generateKey @ generate key + cmp r0,#-1 @ file error ? + beq 100f + bl affichageMess @ display key + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessCryptText + bl affichageMess + ldr r0,iAdrszText @ text encrypt + ldr r1,iAdrtabPolybius + ldr r2,iAdrsKeyWord + ldr r3,iAdrsBuffer @ result buffer + bl encryption + cmp r0,#-1 @ error if unknow character in text + beq 100f + bl affichageMess @ display text encrypted + ldr r0,iAdrszCarriageReturn + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + ldr r0,iAdrszMessDecryptText + bl affichageMess + ldr r0,iAdrsBuffer @ text decrypt + ldr r1,iAdrtabPolybius + ldr r2,iAdrsKeyWord + ldr r3,iAdrsBuffer1 @ result buffer + bl decryption + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc #0 @ perform the system call + +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessDecryptText: .int szMessDecryptText +iAdrszMessCryptText: .int szMessCryptText +iAdrszMessStart: .int szMessStart +iAdrsKeyWord: .int sKeyWord +iAdrszText: .int szText +/***************************************************/ +/* create 6 * 6 polybius */ +/***************************************************/ +createPolybius: + push {r1-r4,lr} @ save des registres + ldr r0,iAdrszListChar @ character list address + mov r1,#LGLISTCHAR @ character list size + ldr r2,iAdrtabPolybius + bl shufflestrings @ shuffle list + ldr r0,iAdrszMessPolybius + bl affichageMess + ldr r0,iAdrszTitle @ display polybius lines + bl affichageMess + ldr r0,iAdrszLine1 + mov r3,#0 + mov r4,#4 +1: + ldrb r1,[r2,r3] + strb r1,[r0,r4] + add r4,r4,#2 + add r3,r3,#1 + cmp r3,#SIZE + blt 1b + bl affichageMess + ldr r0,iAdrszLine2 + mov r3,#SIZE + mov r4,#4 +2: + ldrb r1,[r2,r3] + strb r1,[r0,r4] + add r4,r4,#2 + add r3,r3,#1 + cmp r3,#SIZE * 2 + blt 2b + bl affichageMess + ldr r0,iAdrszLine3 + mov r3,#SIZE * 2 + mov r4,#4 +3: + ldrb r1,[r2,r3] + strb r1,[r0,r4] + add r4,r4,#2 + add r3,r3,#1 + cmp r3,#SIZE * 3 + blt 3b + bl affichageMess + ldr r0,iAdrszLine4 + mov r3,#SIZE * 3 + mov r4,#4 +4: + ldrb r1,[r2,r3] + strb r1,[r0,r4] + add r4,r4,#2 + add r3,r3,#1 + cmp r3,#SIZE * 4 + blt 4b + bl affichageMess + ldr r0,iAdrszLine5 + mov r3,#SIZE * 4 + mov r4,#4 +5: + ldrb r1,[r2,r3] + strb r1,[r0,r4] + add r4,r4,#2 + add r3,r3,#1 + cmp r3,#SIZE * 5 + blt 5b + bl affichageMess + ldr r0,iAdrszLine6 + mov r3,#SIZE * 5 + mov r4,#4 +6: + ldrb r1,[r2,r3] + strb r1,[r0,r4] + add r4,r4,#2 + add r3,r3,#1 + cmp r3,#SIZE * 6 + blt 6b + bl affichageMess + +100: + pop {r1-r4,pc} +iAdrszListChar: .int szListChar +iAdrtabPolybius: .int tabPolybius +iAdrszMessPolybius: .int szMessPolybius +iAdrszTitle: .int szTitle +iAdrszLine1: .int szLine1 +iAdrszLine2: .int szLine2 +iAdrszLine3: .int szLine3 +iAdrszLine4: .int szLine4 +iAdrszLine5: .int szLine5 +iAdrszLine6: .int szLine6 +/***************************************************/ +/* generate key word */ +/***************************************************/ +/* r0 key word address */ +generateKey: + push {r1-r12,lr} @ save registers + mov r9,r0 + ldr r0,iAdrszFileName @ file name + mov r1,#O_RDWR @ flags + mov r2,#0 @ mode + mov r7,#OPEN @ file open + svc 0 + cmp r0,#0 @ error ? + ble 99f + mov r8,r0 @ FD save + ldr r1,iAdrsBuffer @ buffer address + mov r7, #FSTAT @ call systeme NEWFSTAT + svc 0 + cmp r0,#0 + blt 98f + @ load file size + ldr r1,iAdrsBuffer @ buffer address + ldr r6,[r1,#Stat_size_t] @ file size + lsr r12,r6,#3 @ align size to multiple 4 + lsl r12,#3 + add r12,#8 @ add for great buffer + sub sp,sp,r12 @ reserve buffer on stack + mov fp,sp @ address save + mov r0,r8 + mov r1,fp + mov r2,r12 + mov r7,#READ @ call system read file + svc 0 + cmp r0,#0 @ error read ? + blt 97f + mov r0,r8 + mov r7,#CLOSE @ call system close file + svc 0 + cmp r0,#0 @ error close ? + blt 96f + sub sp,sp,#0x1000 @ create array word address on stack + mov r10,sp @ save address array + mov r1,#0 + mov r2,fp + mov r5,#0 @ index word ok + mov r3,#0 @ word length +1: + ldrb r4,[fp,r1] @ load character + cmp r4,#0x0D @ end word ? + beq 2f @ yes + add r1,r1,#1 + add r3,r3,#1 + b 1b +2: + cmp r3,#KEYSIZE @ word length = key length ? + bne 3f @ no ? + mov r0,r2 + bl wordControl @ contril if all letters are différent ? + cmp r0,#1 + streq r2,[r10,r5,lsl #2] @ if ok store word address in array on stack + addeq r5,r5,#1 @ increment word counter +3: + add r1,r1,#2 + cmp r1,r6 @ end ? + beq 4f + add r2,fp,r1 @ new word begin + mov r3,#0 @ init word length + b 1b @ and loop +4: + mov r0,r5 @ number random to total words + bl genereraleas + ldr r2,[r10,r0,lsl #2] @ load address word + mov r1,#0 +5: @ copy random word in word result + ldrb r3,[r2,r1] + strb r3,[r9,r1] + add r1,r1,#1 + cmp r1,#KEYSIZE + blt 5b + mov r3,#0 @ zero final + strb r3,[r9,r1] + mov r0,r9 + b 100f + @ display errors +96: + ldr r0,iAdrszMessClose + bl affichageMess + mov r0,#-1 @ error + b 100f +97: + ldr r0,iAdrszMessRead + bl affichageMess + mov r0,#-1 @ error + b 100f +98: + ldr r0,iAdrszMessStat + bl affichageMess + mov r0,#-1 @ error + b 101f +99: + ldr r0,iAdrszMessOpen + bl affichageMess + mov r0,#-1 @ error + b 101f +100: + add sp,sp,r12 + add sp,sp,#0x1000 +101: + pop {r1-r12,pc} +iAdrszFileName: .int szFileName +iAdrszMessOpen: .int szMessOpen +iAdrszMessRead: .int szMessRead +iAdrszMessStat: .int szMessStat +iAdrszMessClose: .int szMessClose +iAdrsBuffer: .int sBuffer +/******************************************************************/ +/* control if letters are diferents */ +/******************************************************************/ +/* r0 contains the address of the string */ +/* r0 return 1 if Ok else return 0 */ +wordControl: + push {r1-r4,lr} @ save registers + mov r1,#0 @ init index 1 +1: + ldrb r3,[r0,r1] @ load one character + cmp r3,#0x0D @ end word ? + moveq r0,#1 @ yes is ok + beq 100f @ -> end + add r2,r1,#1 @ init index two +2: + ldrb r4,[r0,r2] @ load one character + cmp r4,#0x0D @ end word ? + addeq r1,r1,#1 @ yes increment index 1 + beq 1b @ and loop1 + cmp r3,r4 @ caracters equals ? + moveq r0,#0 @ yes is not good + beq 100f @ and end + add r2,r2,#1 @ else increment index 2 + b 2b @ and loop 2 +100: + pop {r1-r4,pc} +/******************************************************************/ +/* key sort by insertion sort */ +/******************************************************************/ +/* r0 contains the address of String */ +/* r1 contains the first element */ +/* r2 contains the number of element */ +/* r3 contains result address */ +keySort: + push {r2-r10,lr} @ save registers + ldr r7,iAdrtabPosit + mov r10,r3 + mov r3,#0 +0: @ init position array and copy key + strb r3,[r7,r3] @ in result array + ldrb r4,[r0,r3] + strb r4,[r10,r3] + add r3,r3,#1 + cmp r3,#KEYSIZE + blt 0b + + add r3,r1,#1 @ start index i +1: @ start loop + ldrb r4,[r10,r3] @ load value A[i] + ldrb r8,[r7,r3] @ load position + sub r5,r3,#1 @ index j +2: + ldrb r6,[r10,r5] @ load value A[j] + ldrb r9,[r7,r5] @ load position + cmp r6,r4 @ compare value + ble 3f + add r5,#1 @ increment index j + strb r6,[r10,r5] @ store value A[j+1] + strb r9,[r7,r5] @ store position + subs r5,#2 @ j = j - 1 + bge 2b @ loop if j >= 0 +3: + add r5,#1 @ increment index j + strb r4,[r10,r5] @ store value A[i] in A[j+1] + strb r8,[r7,r5] + add r3,#1 @ increment index i + cmp r3,r2 @ end ? + blt 1b @ no -> loop + + ldr r1,iAdrtabPositInv @ inverse position + mov r2,#0 @ index +4: + ldrb r3,[r7,r2] @ load position index + strb r2,[r1,r3] @ store index in position + add r2,r2,#1 @ increment index + cmp r2,#KEYSIZE @ end ? + blt 4b + mov r0,r10 +100: + pop {r2-r10,pc} +iAdrtabPosit: .int tabPosit +iAdrtabPositInv: .int tabPositInv +/******************************************************************/ +/* text encryption */ +/******************************************************************/ +/* r0 contains the address of text */ +/* r1 contains polybius address +/* r2 contains the key address */ +/* r3 contains result buffer address */ +encryption: + push {r2-r10,lr} @ save registers + mov r9,r0 @ save text address + mov r8,r3 + mov r10,r1 @ save address polybius + mov r0,r2 @ key address + mov r1,#0 @ first character + mov r2,#KEYSIZE @ key length + ldr r3,iAdrsKeyWordSorted @ result address + bl keySort @ sort leters of key + //bl affichageMess @ if you want display sorted key + //ldr r0,iAdrszCarriageReturn + //bl affichageMess + ldr r3,iAdrsBuffer1 + mov r5,#0 @ init text index + mov r4,#0 @ init result index +1: + ldrb r0,[r9,r5] @ load a byte to text + cmp r0,#0 @ end ? + beq 4f + mov r6,#0 @ init index polybius +2: + ldrb r7,[r10,r6] @ load character polybius + cmp r7,r0 @ equal ? + beq 3f + add r6,r6,#1 @ increment index + cmp r6,#SIZEC @ not find -> error + bge 99f + b 2b @ and loop +3: + mov r0,r6 + bl convPosCode @ convert position in code character + strb r0,[r3,r4] @ line code character + add r4,r4,#1 + strb r1,[r3,r4] @ column code character + add r4,r4,#1 + + add r5,r5,#1 @ increment text index + b 1b +4: + mov r0,#0 @ zero final -> text result + strb r0,[r3,r4] + mov r5,r3 + mov r1,#0 @ index position column + mov r7,#0 @ index text + ldr r2,iAdrtabPositInv +5: + ldrb r0,[r2,r1] @ load position text +7: @ loop to characters transposition + + ldrb r6,[r5,r0] @ load character + strb r6,[r8,r7] @ store position final + add r7,r7,#1 @ increment final index + add r0,r0,#KEYSIZE @ add size key + cmp r0,r4 @ end ? + blt 7b + add r1,r1,#1 @ add index column + cmp r1,#KEYSIZE @ < key size + blt 5b @ yes -> loop + + mov r6,#0 @ zero final + strb r6,[r8,r7] + mov r0,r8 @ return address encrypted text + + b 100f +99: @ display error + ldr r0,iAdrszMessErrorChar + bl affichageMess + mov r0,#-1 +100: + pop {r2-r10,pc} +iAdrsBuffer1: .int sBuffer1 +iAdrsKeyWordSorted: .int sKeyWordSorted +iAdrszMessErrorChar: .int szMessErrorChar +/******************************************************************/ +/* text decryption */ +/******************************************************************/ +/* r0 contains the address of text */ +/* r1 contains polybius address +/* r2 contains the key */ +/* r3 contains result buffer */ +/* r0 return decoded text */ +decryption: + push {r1-r12,lr} @ save registers + mov r4,#0 +1: @ compute text length + ldrb r5,[r0,r4] + cmp r5,#0 + addne r4,r4,#1 + bne 1b + mov r12,r0 + mov r11,r1 + mov r10,r2 + mov r9,r3 + mov r0,r4 @ compute line number and remainder + mov r1,#KEYSIZE + bl division + mov r8,r2 @ line number + mov r7,r3 @ remainder characters last line + mov r0,r10 @ key address + mov r1,#0 @ first character + mov r2,#KEYSIZE @ size + ldr r3,iAdrsKeyWordSorted @ result address + bl keySort @ sort key + ldr r10,iAdrtabPositInv @ inverse position + mov r2,#0 @ index colonne tabposit + mov r5,#0 @ text index + mov r0,#0 @ index line store text + mov r1,#0 @ counter line + push {r9} @ save final result address + ldr r9,iAdrsBuffer2 +1: + ldrb r3,[r10,r2] @ load position + ldrb r6,[r12,r5] @ load text character + add r3,r3,r0 @ compute position with index line + strb r6,[r9,r3] @ store character in good position + + add r5,r5,#1 @ increment index text + cmp r5,r4 @ end ? + bge 4f + add r1,r1,#1 @ increment line + cmp r1,r8 @ line < line size + blt 2f + bgt 11f @ line = line size + sub r3,r3,r0 @ restaure position column + cmp r3,r7 @ position < remainder so add character other line + blt 2f +11: + mov r1,#0 @ init ligne + mov r0,#0 @ init line shift + add r2,r2,#1 @ increment index array position inverse + cmp r2,#KEYSIZE @ end ? + movge r2,#0 @ init index + b 3f +2: + add r0,#KEYSIZE +3: + b 1b +4: @ convertir characters with polybius + mov r3,#0 + mov r5,#0 + pop {r6} @ restaur final address result +5: + mov r0,r11 + ldrb r1,[r9,r3] @ load a first character + add r3,r3,#1 + ldrb r2,[r9,r3] @ load a 2ieme character + bl decodPosCode @ decode + strb r0,[r6,r5] @ store result in final result + add r5,r5,#1 @ increment final result index + add r3,r3,#1 @ increment index text + cmp r3,r4 @ end ? + blt 5b + mov r0,#0 @ final zero + strb r0,[r6,r5] + mov r0,r6 @ return final result address +100: + pop {r1-r12,pc} +iAdrsBuffer2: .int sBuffer2 +/******************************************************************/ +/* convertir position en code */ +/******************************************************************/ +/* r0 contains the position in polybius */ +/* r0 return code1 */ +/* r1 return code2 */ +convPosCode: + push {r2-r4,lr} @ save registers + ldr r4,iAdrszListCharCode + mov r1,#SIZE + bl division + ldrb r0,[r4,r2] + ldrb r1,[r4,r3] +100: + pop {r2-r4,pc} +iAdrszListCharCode: .int szListCharCode +/******************************************************************/ +/* convertir code en character */ +/******************************************************************/ +/* r0 polybius address */ +/* r1 code 1 */ +/* r2 code 2 */ +/* r0 return character */ +decodPosCode: + push {r1-r5,lr} @ save registers + ldr r4,iAdrszListCharCode + mov r3,#0 +1: + ldrb r5,[r4,r3] + cmp r5,#0 + beq 2f + cmp r5,r1 + moveq r1,r3 + cmp r5,r2 + moveq r2,r3 + add r3,r3,#1 + b 1b +2: + mov r5,#SIZE + mul r1,r5,r1 + add r1,r1,r2 + ldrb r0,[r0,r1] +100: + pop {r1-r5,pc} + +/******************************************************************/ +/* shuffle strings algorithme Fisher-Yates */ +/******************************************************************/ +/* r0 contains the address of the string */ +/* r1 contains string length */ +/* r2 contains address result string */ +shufflestrings: + push {r1-r4,lr} @ save registers + mov r3,#0 +1: @ loop copy string in result + ldrb r4,[r0,r3] + strb r4,[r2,r3] + add r3,r3,#1 + cmp r3,r1 + ble 1b + sub r1,r1,#1 @ last element +2: + mov r0,r1 @ limit random number + bl genereraleas @ call random + ldrb r4,[r2,r1] @ load byte string index loop + ldrb r3,[r2,r0] @ load byte string random index + strb r3,[r2,r1] @ and exchange + strb r4,[r2,r0] + subs r1,r1,#1 + cmp r1,#1 + bge 2b + +100: + pop {r1-r4,pc} @ restaur registers + +/***************************************************/ +/* Generation random number */ +/***************************************************/ +/* r0 contains limit */ +genereraleas: + push {r1-r4,lr} @ save registers + ldr r4,iAdriGraine + ldr r2,[r4] + ldr r3,iNbDep1 + mul r2,r3,r2 + ldr r3,iNbDep1 + add r2,r2,r3 + str r2,[r4] @ save seed for next call + cmp r0,#0 + beq 100f + mov r1,r0 @ divisor + mov r0,r2 @ dividende + bl division + mov r0,r3 @ résult = remainder + +100: @ end function + pop {r1-r4,pc} @ restaur registers +iAdriGraine: .int iGraine +iNbDep1: .int 0x343FD +iNbDep2: .int 0x269EC3 + +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +.include "../affichage.inc" diff --git a/Task/AKS-test-for-primes/Maxima/aks-test-for-primes.maxima b/Task/AKS-test-for-primes/Maxima/aks-test-for-primes.maxima new file mode 100644 index 0000000000..289e0f9e9d --- /dev/null +++ b/Task/AKS-test-for-primes/Maxima/aks-test-for-primes.maxima @@ -0,0 +1,22 @@ +/* Function that lists coefficients given the exponent */ +pol_to_list(n):=if n=0 then [1] else block(pol:expand((x-1)^n), + makelist(numfactor(part(pol,i)),i,1,length(pol)))$ + +/* Function to expand the polynomial (x-1)^n */ +expansion(n):=block( + coeflist:pol_to_list(n), + makelist(x^(length(%%)-i),i,1,length(%%)), + %%*coeflist, + apply("+",%%))$ + +/* AKS based predicate function */ +aks_primep(n):=if n=1 then false else block(sample:expansion(n)-(x^n-1), + makelist(numfactor(part(sample,i)),i,1,length(sample)), + if not member(false,makelist(integerp(%%[i]/n),i,1,length(%%))) then true)$ + +/* Test cases */ +makelist(expansion(i),i,0,7); + +block( + makelist(aks_primep(i),i,1,50), + sublist_indices(%%,lambda([x],x=true))); diff --git a/Task/Abstract-type/COBOL/abstract-type.cobol b/Task/Abstract-type/COBOL/abstract-type.cobol index 51da04507e..3010951b3c 100644 --- a/Task/Abstract-type/COBOL/abstract-type.cobol +++ b/Task/Abstract-type/COBOL/abstract-type.cobol @@ -1,7 +1,9 @@ + IDENTIFICATION DIVISION. INTERFACE-ID. Shape. PROCEDURE DIVISION. + IDENTIFICATION DIVISION. METHOD-ID. perimeter. DATA DIVISION. LINKAGE SECTION. @@ -9,6 +11,7 @@ PROCEDURE DIVISION RETURNING ret. END METHOD perimeter. + IDENTIFICATION DIVISION. METHOD-ID. shape-area. DATA DIVISION. LINKAGE SECTION. @@ -19,6 +22,7 @@ END INTERFACE Shape. + IDENTIFICATION DIVISION. CLASS-ID. Rectangle. ENVIRONMENT DIVISION. @@ -26,6 +30,7 @@ REPOSITORY. INTERFACE Shape. + IDENTIFICATION DIVISION. OBJECT IMPLEMENTS Shape. DATA DIVISION. WORKING-STORAGE SECTION. @@ -34,25 +39,30 @@ PROCEDURE DIVISION. + IDENTIFICATION DIVISION. METHOD-ID. perimeter. DATA DIVISION. LINKAGE SECTION. 01 ret USAGE FLOAT-LONG. PROCEDURE DIVISION RETURNING ret. - COMPUTE ret = width * 2.0 + height * 2.0 - GOBACK - . + COMPUTE + ret = width * 2.0 + height * 2.0 + END-COMPUTE + GOBACK. END METHOD perimeter. + IDENTIFICATION DIVISION. METHOD-ID. shape-area. DATA DIVISION. LINKAGE SECTION. 01 ret USAGE FLOAT-LONG. PROCEDURE DIVISION RETURNING ret. - COMPUTE ret = width * height - GOBACK - . + COMPUTE + ret = width * height + END-COMPUTE + GOBACK. END METHOD shape-area. + END OBJECT. END CLASS Rectangle. diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Julia/abundant-deficient-and-perfect-number-classifications-3.julia b/Task/Abundant-deficient-and-perfect-number-classifications/Julia/abundant-deficient-and-perfect-number-classifications-3.julia new file mode 100644 index 0000000000..992a5f6b4b --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Julia/abundant-deficient-and-perfect-number-classifications-3.julia @@ -0,0 +1,15 @@ +using Primes + +""" Return tuple of (perfect, abundant, deficient) counts from 1 up to nmax """ +function per_abu_def_classify(nmax::Int) + results = [0, 0, 0] + for n in 1:nmax + results[sign(sum(divisors(n)) - 2 * n) + 2] += 1 + end + return (perfect, abundant, deficient) = results +end + +let MAX = 20_000 + NPE, NAB, NDE = per_abu_def_classify(MAX) + println("$NPE perfect, $NAB abundant, and $NDE deficient numbers in 1:$MAX.") +end diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Maxima/abundant-deficient-and-perfect-number-classifications.maxima b/Task/Abundant-deficient-and-perfect-number-classifications/Maxima/abundant-deficient-and-perfect-number-classifications.maxima new file mode 100644 index 0000000000..47e395c364 --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Maxima/abundant-deficient-and-perfect-number-classifications.maxima @@ -0,0 +1,9 @@ +/* Given a number it returns wether it is perfect, deficient or abundant */ +number_class(n):=if divsum(n)-n=n then "perfect" else if divsum(n)-nn then "abundant"$ + +/* Function that displays the number of each kind below n */ +classification_count(n):=block(makelist(number_class(i),i,1,n), + [[length(sublist(%%,lambda([x],x="deficient")))," deficient"],[length(sublist(%%,lambda([x],x="perfect")))," perfect"],[length(sublist(%%,lambda([x],x="abundant")))," abundant"]])$ + +/* Test case */ +classification_count(20000); diff --git a/Task/Address-of-a-variable/COBOL/address-of-a-variable-1.cobol b/Task/Address-of-a-variable/COBOL/address-of-a-variable-1.cobol index b4657bd3ec..2bde5d6a6e 100644 --- a/Task/Address-of-a-variable/COBOL/address-of-a-variable-1.cobol +++ b/Task/Address-of-a-variable/COBOL/address-of-a-variable-1.cobol @@ -1,7 +1,7 @@ -data division. -working-storage section. -01 ptr usage pointer. -01 var pic x(64). + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 ptr USAGE POINTER. + 01 var PIC X(64). -procedure division. -set ptr to address of var. + PROCEDURE DIVISION. + SET ptr TO ADDRESS OF var. diff --git a/Task/Address-of-a-variable/COBOL/address-of-a-variable-2.cobol b/Task/Address-of-a-variable/COBOL/address-of-a-variable-2.cobol index 932d23a87e..86e2b0b3f2 100644 --- a/Task/Address-of-a-variable/COBOL/address-of-a-variable-2.cobol +++ b/Task/Address-of-a-variable/COBOL/address-of-a-variable-2.cobol @@ -1,12 +1,17 @@ OCOBOL*> Rosetta Code set address example *> tectonics: cobc -x setaddr.cob && ./setaddr - program-id. setaddr. - data division. - working-storage section. - 01 prealloc pic x(8) value 'somedata'. - 01 var pic x(8) based. - procedure division. - set address of var to address of prealloc - display var end-display - goback. - end program setaddr. + IDENTIFICATION DIVISION. + PROGRAM-ID. setaddr. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 prealloc PIC X(8) VALUE 'somedata'. + 01 var PIC X(8) BASED. + + PROCEDURE DIVISION. + SET ADDRESS OF var TO ADDRESS OF prealloc + DISPLAY var END-DISPLAY + *> 'somedata' + GOBACK. + + END PROGRAM setaddr. diff --git a/Task/Almost-prime/Craft-Basic/almost-prime.basic b/Task/Almost-prime/Craft-Basic/almost-prime.basic new file mode 100644 index 0000000000..6ed644286a --- /dev/null +++ b/Task/Almost-prime/Craft-Basic/almost-prime.basic @@ -0,0 +1,64 @@ +for k = 1 to 5 + + print "k = ", k, ": ", + + let e = 2 + let c = 0 + + do + + if c < 10 then + + let n = e + gosub kprime + + if r then + + print tab, e, + let c = c + 1 + + endif + + let e = e + 1 + + endif + + loop c < 10 + + print + +next k + +end + +sub kprime + + let f = 0 + + for i = 2 to n + + do + + if n mod i = 0 then + + if f = k then + + let r = 0 + return + + endif + + let f = f + 1 + let n = n / i + + wait + + endif + + loop n mod i = 0 + + next i + + let r = f = k + +return diff --git a/Task/Almost-prime/FutureBasic/almost-prime.basic b/Task/Almost-prime/FutureBasic/almost-prime.basic new file mode 100644 index 0000000000..9a56661276 --- /dev/null +++ b/Task/Almost-prime/FutureBasic/almost-prime.basic @@ -0,0 +1,32 @@ +local fn K_Prime( n as long, k as long ) as BOOL + long f = 0, i = 0 + BOOL result + + for i = 2 to n + while ( n mod i == 0 ) + if f = k then exit fn = NO + f += 1 + n /= i + wend + next + result = f = k +end fn = result + + +long i, c, k + +for k = 1 to 5 + printf @"k = %ld:\b", k + i = 2 + c = 0 + while ( c < 10 ) + if ( fn K_Prime( i, k ) ) + printf @"%4ld\b", i + c++ + end if + i++ + wend + print +next + +HandleEvents diff --git a/Task/Almost-prime/Gambas/almost-prime.gambas b/Task/Almost-prime/Gambas/almost-prime.gambas new file mode 100644 index 0000000000..05625e382e --- /dev/null +++ b/Task/Almost-prime/Gambas/almost-prime.gambas @@ -0,0 +1,33 @@ +Public Sub Main() + + Dim i As Integer, c As Integer, k As Integer + + For k = 1 To 5 + Print "k = "; k; " : "; + i = 2 + c = 0 + While c < 10 + If kPrime(i, k) Then + Print Format$(Str$(i), "### "); + c += 1 + End If + i += 1 + Wend + Print + Next + +End + +Function kPrime(n As Integer, k As Integer) As Boolean + + Dim f As Integer = 0 + For i As Integer = 2 To n + While n Mod i = 0 + If f = k Then Return False + f += 1 + n \= i + Wend + Next + Return f = k + +End Function diff --git a/Task/Almost-prime/Odin/almost-prime.odin b/Task/Almost-prime/Odin/almost-prime.odin new file mode 100644 index 0000000000..d8a0a051df --- /dev/null +++ b/Task/Almost-prime/Odin/almost-prime.odin @@ -0,0 +1,26 @@ +package almostprime +import "core:fmt" +main :: proc() { + i, c, k: int + for k in 1 ..= 5 { + fmt.printf("k = %d:", k) + for i, c := 2, 0; c < 10; i += 1 { + if kprime(i, k) { + fmt.printf(" %v", i) + c += 1 + } + } + fmt.printf("\n") + } +} +kprime :: proc(n: int, k: int) -> bool { + p, f: int = 0, 0 + n := n + for p := 2; f < k && p * p <= n; p += 1 { + for (0 == n % p) { + n /= p + f += 1 + } + } + return f + (n > 1 ? 1 : 0) == k +} diff --git a/Task/Anagrams-Deranged-anagrams/COBOL/anagrams-deranged-anagrams.cobol b/Task/Anagrams-Deranged-anagrams/COBOL/anagrams-deranged-anagrams.cobol index c837967bb3..f5f7ac6e85 100644 --- a/Task/Anagrams-Deranged-anagrams/COBOL/anagrams-deranged-anagrams.cobol +++ b/Task/Anagrams-Deranged-anagrams/COBOL/anagrams-deranged-anagrams.cobol @@ -1,181 +1,181 @@ - ****************************************************************** - * COBOL solution to Anagrams Deranged challange - * The program was run on OpenCobolIDE - * Input data is stored in file 'Anagrams.txt' on my PC - ****************************************************************** - IDENTIFICATION DIVISION. - PROGRAM-ID. DERANGED. +****************************************************************** +* COBOL solution to Anagrams Deranged challange +* The program was run on OpenCobolIDE +* Input data is stored in file 'Anagrams.txt' on my PC +****************************************************************** +IDENTIFICATION DIVISION. +PROGRAM-ID. DERANGED. - ENVIRONMENT DIVISION. - INPUT-OUTPUT SECTION. - FILE-CONTROL. - SELECT IN-FILE ASSIGN TO 'C:\Both\Rosetta\Anagrams.txt' - ORGANIZATION IS LINE SEQUENTIAL. +ENVIRONMENT DIVISION. +INPUT-OUTPUT SECTION. +FILE-CONTROL. + SELECT IN-FILE ASSIGN TO 'C:\Both\Rosetta\Anagrams.txt' + ORGANIZATION IS LINE SEQUENTIAL. - DATA DIVISION. - FILE SECTION. - FD IN-FILE. - 01 IN-RECORD PIC X(22). +DATA DIVISION. +FILE SECTION. +FD IN-FILE. +01 IN-RECORD PIC X(22). - WORKING-STORAGE SECTION. - 01 SWITCHES. - 05 WS-EOF PIC X VALUE 'N'. - 05 WS-FND PIC X VALUE 'N'. - 05 WS-EXIT PIC X VALUE 'N'. +WORKING-STORAGE SECTION. +01 SWITCHES. + 05 WS-EOF PIC X VALUE 'N'. + 05 WS-FND PIC X VALUE 'N'. + 05 WS-EXIT PIC X VALUE 'N'. - 01 COUNTERS. - 05 WS-TOT-RECS PIC 9(5) COMP-3 VALUE 0. - 05 WS-SEL-RECS PIC 9(5) COMP-3 VALUE 0. - 05 WT-REC-NBR PIC 9(5) COMP-3 VALUE 0. +01 COUNTERS. + 05 WS-TOT-RECS PIC 9(5) USAGE PACKED-DECIMAL VALUE 0. + 05 WS-SEL-RECS PIC 9(5) USAGE PACKED-DECIMAL VALUE 0. + 05 WT-REC-NBR PIC 9(5) USAGE PACKED-DECIMAL VALUE 0. - * Extra byte to guarentee a space at end - needed in sort logic. - 01 WS-WORD-TEMP PIC X(23). - 01 FILLER REDEFINES WS-WORD-TEMP. - 05 WS-LETTER OCCURS 23 TIMES PIC X. - 77 WS-LETTER-HLD PIC X. +* Extra byte to guarentee a space at end - needed in sort logic. +01 WS-WORD-TEMP PIC X(23). +01 FILLER REDEFINES WS-WORD-TEMP. + 05 WS-LETTER OCCURS 23 TIMES PIC X. +77 WS-LETTER-HLD PIC X. - 77 WS-WORD-IN PIC X(22). - 77 WS-WORD-KEY PIC X(22). +77 WS-WORD-IN PIC X(22). +77 WS-WORD-KEY PIC X(22). - 01 WS-WORD-TABLE. - 05 WT-RECORD OCCURS 0 to 24000 TIMES - DEPENDING ON WT-REC-NBR - DESCENDING KEY IS WT-WORD-LEN - INDEXED BY WT-IDX. - 10 WT-WORD-KEY PIC X(22). - 10 WT-WORD-LEN PIC 9(2). - 10 WT-ANAGRAM-CNT PIC 9(5) COMP-3. - 10 WT-ANAGRAMS OCCURS 6 TIMES. - 15 WT-ANAGRAM PIC X(22). +01 WS-WORD-TABLE. + 05 WT-RECORD OCCURS 0 to 24000 TIMES + DEPENDING ON WT-REC-NBR + DESCENDING KEY IS WT-WORD-LEN + INDEXED BY WT-IDX. + 10 WT-WORD-KEY PIC X(22). + 10 WT-WORD-LEN PIC 9(2). + 10 WT-ANAGRAM-CNT PIC 9(5) USAGE PACKED-DECIMAL. + 10 WT-ANAGRAMS OCCURS 6 TIMES. + 15 WT-ANAGRAM PIC X(22). - 01 WS-WORD-TEMP1 PIC X(22). - 01 FILLER REDEFINES WS-WORD-TEMP1. - 05 WS-LETTER1 OCCURS 22 TIMES PIC X. +01 WS-WORD-TEMP1 PIC X(22). +01 FILLER REDEFINES WS-WORD-TEMP1. + 05 WS-LETTER1 PIC X OCCURS 22 TIMES. - 01 WS-WORD-TEMP2 PIC X(22). - 01 FILLER REDEFINES WS-WORD-TEMP2. - 05 WS-LETTER2 OCCURS 22 TIMES PIC X. +01 WS-WORD-TEMP2 PIC X(22). +01 FILLER REDEFINES WS-WORD-TEMP2. + 05 WS-LETTER2 OCCURS 22 TIMES PIC X. - 77 WS-I PIC 99999 COMP-3. - 77 WS-J PIC 99999 COMP-3. - 77 WS-K PIC 99999 COMP-3. - 77 WS-L PIC 99999 COMP-3. - 77 WS-BEG PIC 99999 COMP-3. - 77 WS-MAX PIC 99999 COMP-3. +77 WS-I PIC 9(5) USAGE PACKED-DECIMAL. +77 WS-J PIC 9(5) USAGE PACKED-DECIMAL. +77 WS-K PIC 9(5) USAGE PACKED-DECIMAL. +77 WS-L PIC 9(5) USAGE PACKED-DECIMAL. +77 WS-BEG PIC 9(5) USAGE PACKED-DECIMAL. +77 WS-MAX PIC 9(5) USAGE PACKED-DECIMAL. - PROCEDURE DIVISION. - 000-MAIN. - PERFORM 100-INITIALIZE. - PERFORM 200-PROCESS-RECORD - UNTIL WS-EOF = 'Y'. - SORT WT-RECORD ON DESCENDING KEY WT-WORD-LEN. - PERFORM 500-FIND-DERANGED. - PERFORM 900-TERMINATE. - STOP RUN. +PROCEDURE DIVISION. +000-MAIN. + PERFORM 100-INITIALIZE. + PERFORM 200-PROCESS-RECORD UNTIL WS-EOF = 'Y'. + SORT WT-RECORD ON DESCENDING KEY WT-WORD-LEN. + PERFORM 500-FIND-DERANGED. + PERFORM 900-TERMINATE. + STOP RUN. - 100-INITIALIZE. - OPEN INPUT IN-FILE. - PERFORM 150-READ-RECORD. +100-INITIALIZE. + OPEN INPUT IN-FILE. + PERFORM 150-READ-RECORD. - 150-READ-RECORD. - READ IN-FILE INTO WS-WORD-IN - AT END - MOVE 'Y' TO WS-EOF - NOT AT END - COMPUTE WS-TOT-RECS = WS-TOT-RECS + 1 - END-READ. +150-READ-RECORD. + READ IN-FILE INTO WS-WORD-IN + AT END + MOVE 'Y' TO WS-EOF + NOT AT END + COMPUTE WS-TOT-RECS = WS-TOT-RECS + 1 + END-READ. - 200-PROCESS-RECORD. - IF WS-WORD-IN IS ALPHABETIC - COMPUTE WS-SEL-RECS = WS-SEL-RECS + 1 - MOVE WS-WORD-IN TO WS-WORD-TEMP - PERFORM 300-SORT-WORD - MOVE WS-WORD-TEMP TO WS-WORD-KEY - PERFORM 400-ADD-TO-TABLE - END-IF. +200-PROCESS-RECORD. + IF WS-WORD-IN IS ALPHABETIC + COMPUTE WS-SEL-RECS = WS-SEL-RECS + 1 END-COMPUTE + MOVE WS-WORD-IN TO WS-WORD-TEMP + PERFORM 300-SORT-WORD + MOVE WS-WORD-TEMP TO WS-WORD-KEY + PERFORM 400-ADD-TO-TABLE + END-IF. + PERFORM 150-READ-RECORD. - PERFORM 150-READ-RECORD. +* bubble sort: +300-SORT-WORD. + PERFORM VARYING WS-MAX FROM 1 BY 1 + UNTIL WS-LETTER(WS-MAX) = SPACE + END-PERFORM. + PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I = WS-MAX + PERFORM VARYING WS-J FROM WS-I BY 1 + UNTIL WS-J > WS-MAX - 1 + IF WS-LETTER(WS-J) < WS-LETTER(WS-I) THEN + MOVE WS-LETTER(WS-I) TO WS-LETTER-HLD + MOVE WS-LETTER(WS-J) TO WS-LETTER(WS-I) + MOVE WS-LETTER-HLD TO WS-LETTER(WS-J) + END-IF + END-PERFORM + END-PERFORM. - * bubble sort: - 300-SORT-WORD. - PERFORM VARYING WS-MAX FROM 1 BY 1 - UNTIL WS-LETTER(WS-MAX) = SPACE - END-PERFORM. +400-ADD-TO-TABLE. + SET WT-IDX TO 1. + SEARCH WT-RECORD + AT END + PERFORM 420-ADD-RECORD + WHEN WT-WORD-KEY(WT-IDX) = WS-WORD-KEY + PERFORM 440-UPDATE-RECORD + END-SEARCH. - PERFORM VARYING WS-I FROM 1 BY 1 UNTIL WS-I = WS-MAX - PERFORM VARYING WS-J FROM WS-I BY 1 - UNTIL WS-J > WS-MAX - 1 - IF WS-LETTER(WS-J) < WS-LETTER(WS-I) THEN - MOVE WS-LETTER(WS-I) TO WS-LETTER-HLD - MOVE WS-LETTER(WS-J) TO WS-LETTER(WS-I) - MOVE WS-LETTER-HLD TO WS-LETTER(WS-J) - END-IF - END-PERFORM - END-PERFORM. +420-ADD-RECORD. + ADD 1 To WT-REC-NBR. + MOVE WS-WORD-KEY TO WT-WORD-KEY(WT-REC-NBR). + COMPUTE WT-WORD-LEN(WT-REC-NBR) = WS-MAX - 1 END-COMPUTE. + MOVE 1 TO WT-ANAGRAM-CNT(WT-REC-NBR). + MOVE WS-WORD-IN TO + WT-ANAGRAM(WT-REC-NBR, WT-ANAGRAM-CNT(WT-REC-NBR)). - 400-ADD-TO-TABLE. - SET WT-IDX TO 1. - SEARCH WT-RECORD - AT END - PERFORM 420-ADD-RECORD - WHEN WT-WORD-KEY(WT-IDX) = WS-WORD-KEY - PERFORM 440-UPDATE-RECORD - END-SEARCH. +440-UPDATE-RECORD. + ADD 1 TO WT-ANAGRAM-CNT(WT-IDX). + MOVE WS-WORD-IN TO + WT-ANAGRAM(WT-IDX, WT-ANAGRAM-CNT(WT-IDX)). - 420-ADD-RECORD. - ADD 1 To WT-REC-NBR. - MOVE WS-WORD-KEY TO WT-WORD-KEY(WT-REC-NBR). - COMPUTE WT-WORD-LEN(WT-REC-NBR) = WS-MAX - 1. - MOVE 1 TO WT-ANAGRAM-CNT(WT-REC-NBR). - MOVE WS-WORD-IN TO - WT-ANAGRAM(WT-REC-NBR, WT-ANAGRAM-CNT(WT-REC-NBR)). +500-FIND-DERANGED. + PERFORM VARYING WS-I FROM 1 BY 1 + UNTIL WS-I > WT-REC-NBR OR WS-FND = 'Y' + PERFORM VARYING WS-J FROM 1 BY 1 + UNTIL WS-J > WT-ANAGRAM-CNT(WS-I) - 1 OR WS-FND = 'Y' + COMPUTE WS-BEG = WS-J + 1 END-COMPUTE + PERFORM VARYING WS-K FROM WS-BEG BY 1 + UNTIL WS-K > WT-ANAGRAM-CNT(WS-I) OR WS-FND = 'Y' + MOVE WT-ANAGRAM(WS-I, WS-J) TO WS-WORD-TEMP1 + MOVE WT-ANAGRAM(WS-I, WS-K) To WS-WORD-TEMP2 + PERFORM 650-CHECK-DERANGED + END-PERFORM + END-PERFORM + END-PERFORM. - 440-UPDATE-RECORD. - ADD 1 TO WT-ANAGRAM-CNT(WT-IDX). - MOVE WS-WORD-IN TO - WT-ANAGRAM(WT-IDX, WT-ANAGRAM-CNT(WT-IDX)). +650-CHECK-DERANGED. + MOVE 'N' TO WS-EXIT. + PERFORM VARYING WS-L FROM 1 BY 1 + UNTIL WS-L > WT-WORD-LEN(WS-I) OR WS-EXIT = 'Y' + IF WS-LETTER1(WS-L) = WS-LETTER2(WS-L) + MOVE 'Y' TO WS-EXIT + END-IF + END-PERFORM. + IF WS-EXIT = 'N' + DISPLAY + WS-WORD-TEMP1(1:WT-WORD-LEN(WS-I)) ' ' WS-WORD-TEMP2 + END-DISPLAY + MOVE 'Y' TO WS-FND + END-IF. - 500-FIND-DERANGED. - PERFORM VARYING WS-I FROM 1 BY 1 - UNTIL WS-I > WT-REC-NBR OR WS-FND = 'Y' - PERFORM VARYING WS-J FROM 1 BY 1 - UNTIL WS-J > WT-ANAGRAM-CNT(WS-I) - 1 OR WS-FND = 'Y' - COMPUTE WS-BEG = WS-J + 1 - PERFORM VARYING WS-K FROM WS-BEG BY 1 - UNTIL WS-K > WT-ANAGRAM-CNT(WS-I) OR WS-FND = 'Y' - MOVE WT-ANAGRAM(WS-I, WS-J) TO WS-WORD-TEMP1 - MOVE WT-ANAGRAM(WS-I, WS-K) To WS-WORD-TEMP2 - PERFORM 650-CHECK-DERANGED - END-PERFORM - END-PERFORM - END-PERFORM. +900-TERMINATE. + DISPLAY 'RECORDS READ: ' WS-TOT-RECS. + DISPLAY 'RECORDS SELECTED ' WS-SEL-RECS. + DISPLAY 'RECORD KEYS: ' WT-REC-NBR. + CLOSE IN-FILE. - 650-CHECK-DERANGED. - MOVE 'N' TO WS-EXIT. - PERFORM VARYING WS-L FROM 1 BY 1 - UNTIL WS-L > WT-WORD-LEN(WS-I) OR WS-EXIT = 'Y' - IF WS-LETTER1(WS-L) = WS-LETTER2(WS-L) - MOVE 'Y' TO WS-EXIT - END-PERFORM. - IF WS-EXIT = 'N' - DISPLAY WS-WORD-TEMP1(1:WT-WORD-LEN(WS-I)) - ' ' - WS-WORD-TEMP2 - MOVE 'Y' TO WS-FND - END-IF. +END PROGRAM DERANGED. - 900-TERMINATE. - DISPLAY 'RECORDS READ: ' WS-TOT-RECS. - DISPLAY 'RECORDS SELECTED ' WS-SEL-RECS. - DISPLAY 'RECORD KEYS: ' WT-REC-NBR. - CLOSE IN-FILE. +*> OUTPUT: - *> OUTPUT: +*> excitation intoxicate +*> RECORDS READ: 25104 +*> RECORDS SELECTED 24978 +*> RECORD KEYS: 23441 - *> excitation intoxicate - *> RECORDS READ: 25104 - *> RECORDS SELECTED 24978 - *> RECORD KEYS: 23441 - - *> BUBBLE SORT REFERENCE: - *> https://mainframegeek.wordpress.com/tag/bubble-sort-in-cobol +*> BUBBLE SORT REFERENCE: +*> https://mainframegeek.wordpress.com/tag/bubble-sort-in-cobol diff --git a/Task/Animate-a-pendulum/FutureBasic/animate-a-pendulum.basic b/Task/Animate-a-pendulum/FutureBasic/animate-a-pendulum.basic new file mode 100644 index 0000000000..f6e7e096dc --- /dev/null +++ b/Task/Animate-a-pendulum/FutureBasic/animate-a-pendulum.basic @@ -0,0 +1,46 @@ +void local fn BuildWindow + window 1, @"Animated Pendulum in FutureBasic", ( 0, 0, 640, 400 ) + WindowSetBackgroundColor( 1, fn ColorBlack ) + WindowSetMinSize( 1, fn CGSizeMake( 640, 400 ) ) + WindowSetMaxSize( 1, fn CGSizeMake( 640, 400 ) ) +end fn + +local fn AnimatedPendulum + block double theta, gravity, length, accel, speed, weight, tempo, px, py, bx, by + block ColorRef color = fn ColorWithRGB( 0.164, 0.793, 0.075, 1.0 ) + theta = pi/2.0 // Denominator of 2.0 = 180-degree swing, < 2.0 narrows inscribed arc, > 2.0 widens it. + gravity = 9.90 // Adjusts effect of gravity on swing. Smaller values slow arc swing. + length = 0.95 // Tweak for length of pendulum arm + speed = 0 // Zero this or you get a propellor! + px = 320 // Pivot horizontal center x point (half window width) + py = 30 // Pivot y center y point from top + weight = 42 // Diameter of pendulum weight + tempo = 75 // Smaller value increases pendulum tempo, larger value slows it. + + timerbegin, 0.02, YES + bx = px + length * 300 * sin(theta) // Pendulum bottom x point + by = py - length * 300 * cos(theta) // Pendulum bottom y point + cls + pen 6.0, color + line px, py to bx, by + oval fill bx -weight/2, by -weight/2, weight, weight, color // Traveling weight + pen 4.0 + oval fill 313, 20, 16, 16, fn ColorGray // Top center point + accel = gravity * sin(theta) / length / tempo + speed += accel / tempo + theta += speed + timerEnd +end fn + +void local fn DoDialog( ev as long, tag as long, wnd as long ) + select ( ev ) + case _windowWillClose : end + end select +end fn + +on dialog fn DoDialog + +fn BuildWindow +fn AnimatedPendulum + +HandleEvents diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/FutureBasic/append-a-record-to-the-end-of-a-text-file.basic b/Task/Append-a-record-to-the-end-of-a-text-file/FutureBasic/append-a-record-to-the-end-of-a-text-file.basic new file mode 100644 index 0000000000..209a750fb4 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/FutureBasic/append-a-record-to-the-end-of-a-text-file.basic @@ -0,0 +1,45 @@ +local fn AppendRecordToFile( pwStr as CFStringRef, url as CFURLRef ) as BOOL + ErrorRef err = NULL + BOOL success = YES + CFDataRef pwData = fn StringData( pwStr, NSUTF8StringEncoding ) + FileHandleRef fh = fn FileHandleForWritingToURL( url, @err ) + if ( err ) + success = fn FileManagerFileExistsAtURL( url ) + if success == NO then fn FileManagerCreateFileAtURL( url, pwData, NULL ) : success = YES : exit fn + end if + success = fn FileHandleSeekToEnd( fh, NULL, @err ) + if success == NO then print fn ErrorLocalizedDescription( err ) : exit fn + success = fn FileHandleWriteData( fh, pwData, @err ) + if success == NO then print fn ErrorLocalizedDescription( err ) : exit fn + success = fn FileHandleClose( fh, @err ) + if success == NO then print fn ErrorLocalizedDescription( err ) : exit fn +end fn = success + +local fn ReadFileRecords( url as CFURLRef ) + ErrorRef err = NULL + + CFDataRef pwData = fn DataWithContentsOfURL( url, NSDataReadingMappedIfSafe, @err ) + if err then print fn ErrorLocalizedDescription( err ) : exit fn + print fn StringWithData( pwData, NSUTF8StringEncoding ) +end fn + +local fn ProcessRecords + BOOL success = NO + CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) + CFURLRef url = fn URLByAppendingPathComponent( desktopURL, @"passwords.txt" ) + CFArrayRef pwRecords = @[@"account:password:UID:GID:fullname,office,extension,homephone,email:directory:shell\n",¬ + @"jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash\n",¬ + @"jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash\n"] + NSUInteger i, count = len(pwRecords) + + for i = 0 to count - 1 + success = fn AppendRecordToFile( pwRecords[i], url ) + if success then printf @"Record appended to file." else printf @"Failed to append record." + next + + fn ReadFileRecords( url ) +end fn + +fn ProcessRecords + +HandleEvents diff --git a/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol b/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol index 6f5c473b5e..03a628f073 100644 --- a/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol +++ b/Task/Apply-a-callback-to-an-array/COBOL/apply-a-callback-to-an-array.cobol @@ -1,23 +1,20 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. Map. + >>SOURCE FORMAT IS FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. map. - DATA DIVISION. - WORKING-STORAGE SECTION. - 01 Table-Size CONSTANT 30. +DATA DIVISION. +LOCAL-STORAGE SECTION. +01 i USAGE IS INDEX. +01 table-size CONSTANT AS 30. +LINKAGE SECTION. +01 table-param. + 03 table-values USAGE IS FLOAT-LONG, OCCURS table-size TIMES. +01 func-ptr USAGE IS PROGRAM-POINTER. - LOCAL-STORAGE SECTION. - 01 I USAGE UNSIGNED-INT. +PROCEDURE DIVISION USING BY REFERENCE table-param, BY VALUE func-ptr. + PERFORM VARYING i FROM 1 BY 1 UNTIL i IS GREATER THAN table-size + CALL func-ptr USING BY REFERENCE table-values(i) + END-PERFORM + GOBACK. - LINKAGE SECTION. - 01 Table-Param. - 03 Table-Values USAGE COMP-2 OCCURS Table-Size TIMES. - - 01 Func-Id PIC X(30). - - PROCEDURE DIVISION USING Table-Param Func-Id. - PERFORM VARYING I FROM 1 BY 1 UNTIL Table-Size < I - CALL Func-Id USING BY REFERENCE Table-Values (I) - END-PERFORM - - GOBACK - . +END PROGRAM map. diff --git a/Task/Arithmetic-Integer/LDPL/arithmetic-integer.ldpl b/Task/Arithmetic-Integer/LDPL/arithmetic-integer.ldpl new file mode 100644 index 0000000000..d87f053672 --- /dev/null +++ b/Task/Arithmetic-Integer/LDPL/arithmetic-integer.ldpl @@ -0,0 +1,23 @@ +data: +x is number +y is number +result is number + +procedure: +display "Enter x: " +accept x +display "Enter y: " +accept y +add x and y in result +display "x + y = " result lf +subtract y from x in result +display "x - y = " result lf +multiply x by y in result +display "x * y = " result lf +divide x by y in result # There is no integer division but +floor result # floor rounds toward negative infinity +display "x / y = " result lf +modulo x by y in result +display "x % y = " result lf # Returns the sign of the 2nd argument +raise x to y in result +display "x ^ y = " result lf diff --git a/Task/Arithmetic-Rational/00-TASK.txt b/Task/Arithmetic-Rational/00-TASK.txt index deb926c95a..c2d1c64a6d 100644 --- a/Task/Arithmetic-Rational/00-TASK.txt +++ b/Task/Arithmetic-Rational/00-TASK.txt @@ -15,7 +15,8 @@ Finally test the operators: Use the new type '''frac''' to find all [[Perfect Numbers|perfect numbers]] less than 219 by summing the reciprocal of the factors. -;Related task: +;Related tasks: *   [[Perfect Numbers]] +*   [[Check Machin-like formulas]]

diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena index 7ca328b4e4..5e072298d5 100644 --- a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena +++ b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena @@ -4,338 +4,340 @@ import extensions'text; class Token { - object theValue; + object _value; - rprop int Level; + int Level : rprop; - constructor new(int level) - { - theValue := new StringWriter(); - Level := level + 9; - } + constructor new(int level) + { + _value := new StringWriter(); + Level := level + 9; + } - append(ch) - { - theValue.write(ch) - } + append(ch) + { + _value.write(ch) + } - Number = theValue.toReal(); + Number = _value.toReal(); } class Node { - prop object Left; - prop object Right; - rprop int Level; + object Left : prop; + object Right : prop; + int Level : rprop; - constructor new(int level) - { - Level := level - } + constructor new(int level) + { + Level := level + } } class SummaryNode : Node { - constructor new(int level) - <= new(level + 1); + constructor new(int level) + <= super new(level + 1); - Number = Left.Number + Right.Number; + Number = Left.Number + Right.Number; } class DifferenceNode : Node { - constructor new(int level) - <= new(level + 1); + constructor new(int level) + <= super new(level + 1); - Number = Left.Number - Right.Number; + Number = Left.Number - Right.Number; } class ProductNode : Node { - constructor new(int level) - <= new(level + 2); + constructor new(int level) + <= super new(level + 2); - Number = Left.Number * Right.Number; + Number = Left.Number * Right.Number; } class FractionNode : Node { - constructor new(int level) - <= new(level + 2); + constructor new(int level) + <= super new(level + 2); - Number = Left.Number / Right.Number; + Number = Left.Number / Right.Number; } class Expression { - rprop int Level; - prop object Top; + int Level :rprop; + object Top :prop; - constructor new(int level) - { - Level := level - } + constructor new(int level) + { + Level := level + } - Right - { - get() = Top; + object Right + { + get() = Top; - set(object node) - { - Top := node - } - } + set(object node) + { + Top := node + } + } - get Number() => Top; + get Number() => Top; } singleton operatorState { - eval(ch) - { - ch => - $40 { // ( - ^ __target.newBracket().gotoStarting() - } - : { - ^ __target.newToken().append(ch).gotoToken() - } - } + eval(ch) + { + ch => + $40 { // ( + ^ weak self.newBracket().gotoStarting() + } + : { + ^ weak self.newToken().append(ch).gotoToken() + } + } } singleton tokenState { - eval(ch) - { - ch => - $41 { // ) - ^ __target.closeBracket().gotoToken() - } - $42 { // * - ^ __target.newProduct().gotoOperator() - } - $43 { // + - ^ __target.newSummary().gotoOperator() - } - $45 { // - - ^ __target.newDifference().gotoOperator() - } - $47 { // / - ^ __target.newFraction().gotoOperator() - } - : { - ^ __target.append:ch - } - } + eval(ch) + { + ch => + $41 { // ) + ^ weak self.closeBracket().gotoToken() + } + $42 { // * + ^ weak self.newProduct().gotoOperator() + } + $43 { // + + ^ weak self.newSummary().gotoOperator() + } + $45 { // - + ^ weak self.newDifference().gotoOperator() + } + $47 { // / + ^ weak self.newFraction().gotoOperator() + } + : { + ^ weak self.append:ch + } + } } singleton startState { - eval(ch) - { - ch => - $40 { // ( - ^ __target.newBracket().gotoStarting() - } - $45 { // - - ^ __target.newToken().append("0").newDifference().gotoOperator() - } - : { - ^ __target.newToken().append:ch.gotoToken() - } - } + eval(ch) + { + ch => + $40 { // ( + ^ weak self.newBracket().gotoStarting() + } + $45 { // - + ^ weak self.newToken().append("0").newDifference().gotoOperator() + } + : { + ^ weak self.newToken().append:ch.gotoToken() + } + } } class Scope { - object theState; - int theLevel; - object theParser; - object theToken; - object theExpression; + object _state; + int _level; + object _parser; + object _token; + object _expression; - constructor new(parser) - { - theState := startState; - theLevel := 0; - theExpression := Expression.new(0); - theParser := parser - } + constructor new(parser) + { + _state := startState; + _level := 0; + _expression := Expression.new(0); + _parser := parser + } - newToken() - { - theToken := theParser.appendToken(theExpression, theLevel) - } + newToken() + { + _token := _parser.appendToken(_expression, _level) + } - newSummary() - { - theToken := nil; + newSummary() + { + _token := nil; - theParser.appendSummary(theExpression, theLevel) - } + _parser.appendSummary(_expression, _level) + } - newDifference() - { - theToken := nil; + newDifference() + { + _token := nil; - theParser.appendDifference(theExpression, theLevel) - } + _parser.appendDifference(_expression, _level) + } - newProduct() - { - theToken := nil; + newProduct() + { + _token := nil; - theParser.appendProduct(theExpression, theLevel) - } + _parser.appendProduct(_expression, _level) + } - newFraction() - { - theToken := nil; + newFraction() + { + _token := nil; - theParser.appendFraction(theExpression, theLevel) - } + _parser.appendFraction(_expression, _level) + } - newBracket() - { - theToken := nil; + newBracket() + { + _token := nil; - theLevel := theLevel + 10; + _level := _level + 10; - theParser.appendSubexpression(theExpression, theLevel) - } + _parser.appendSubexpression(_expression, _level) + } - closeBracket() - { - if (theLevel < 10) - { InvalidArgumentException.new:"Invalid expression".raise() }; + closeBracket() + { + if (_level < 10) + { InvalidArgumentException.new:"Invalid expression".raise() }; - theLevel := theLevel - 10 - } + _level := _level - 10 + } - append(ch) - { - if(ch >= $48 && ch < $58) - { - theToken.append:ch - } - else - { - InvalidArgumentException.new:"Invalid expression".raise() - } - } + append(ch) + { + if(ch >= $48 && ch < $58) + { + _token.append:ch + } + else + { + InvalidArgumentException.new:"Invalid expression".raise() + } + } - append(string s) - { - s.forEach:(ch){ self.append:ch } - } + append(string s) + { + s.forEach:(ch){ self.append:ch } + } - gotoStarting() - { - theState := startState - } + gotoStarting() + { + _state := startState + } - gotoToken() - { - theState := tokenState - } + gotoToken() + { + _state := tokenState + } - gotoOperator() - { - theState := operatorState - } + gotoOperator() + { + _state := operatorState + } - get Number() => theExpression; + get Number() => _expression; - dispatch() => theState; + dispatch() => _state; } class Parser { - appendToken(object expression, int level) - { - var token := Token.new(level); + appendToken(object expression, int level) + { + var token := Token.new(level); - expression.Top := self.append(expression.Top, token); + expression.Top := self.append(expression.Top, token); - ^ token - } + ^ token + } - appendSummary(object expression, int level) - { - expression.Top := self.append(expression.Top, SummaryNode.new(level)) - } + appendSummary(object expression, int level) + { + var t := expression.Top; - appendDifference(object expression, int level) - { - expression.Top := self.append(expression.Top, DifferenceNode.new(level)) - } + expression.Top := self.append(/*expression.Top*/t, SummaryNode.new(level)) + } - appendProduct(object expression, int level) - { - expression.Top := self.append(expression.Top, ProductNode.new(level)) - } + appendDifference(object expression, int level) + { + expression.Top := self.append(expression.Top, DifferenceNode.new(level)) + } - appendFraction(object expression, int level) - { - expression.Top := self.append(expression.Top, FractionNode.new(level)) - } + appendProduct(object expression, int level) + { + expression.Top := self.append(expression.Top, ProductNode.new(level)) + } - appendSubexpression(object expression, int level) - { - expression.Top := self.append(expression.Top, Expression.new(level)) - } + appendFraction(object expression, int level) + { + expression.Top := self.append(expression.Top, FractionNode.new(level)) + } - append(lastNode, newNode) - { - if(nil == lastNode) - { ^ newNode }; + appendSubexpression(object expression, int level) + { + expression.Top := self.append(expression.Top, Expression.new(level)) + } - if (newNode.Level <= lastNode.Level) - { newNode.Left := lastNode; ^ newNode }; + append(object lastNode, object newNode) + { + if(nil == lastNode) + { ^ newNode }; - var parent := lastNode; - var current := lastNode.Right; - while (nil != current && newNode.Level > current.Level) - { parent := current; current := current.Right }; + if (newNode.Level <= lastNode.Level) + { newNode.Left := lastNode; ^ newNode }; - if (nil == current) - { - parent.Right := newNode - } - else - { - newNode.Left := current; parent.Right := newNode - }; + var parent := lastNode; + var current := lastNode.Right; + while (nil != current && newNode.Level > current.Level) + { parent := current; current := current.Right }; - ^ lastNode - } + if (nil == current) + { + parent.Right := newNode + } + else + { + newNode.Left := current; parent.Right := newNode + }; - run(text) - { - var scope := Scope.new(self); + ^ lastNode + } - text.forEach:(ch){ scope.eval:ch }; + run(text) + { + var scope := Scope.new(self); - ^ scope.Number - } + text.forEach:(ch){ scope.eval:ch }; + + ^ scope.Number + } } public program() { - var text := new StringWriter(); - var parser := new Parser(); + var text := new StringWriter(); + var parser := new Parser(); - while (console.readLine().saveTo(text).Length > 0) - { - try - { - console.printLine("=",parser.run:text) - } - catch(Exception e) - { - console.writeLine:"Invalid Expression" - }; + while (console.readLine().writeTo(text).Length > 0) + { + try + { + console.printLine("=",parser.run:text) + } + catch(Exception e) + { + console.writeLine:"Invalid Expression" + }; - text.clear() - } + text.clear() + } } diff --git a/Task/Arithmetic-evaluation/Elixir/arithmetic-evaluation.elixir b/Task/Arithmetic-evaluation/Elixir/arithmetic-evaluation.elixir new file mode 100644 index 0000000000..a530438634 --- /dev/null +++ b/Task/Arithmetic-evaluation/Elixir/arithmetic-evaluation.elixir @@ -0,0 +1,13 @@ +defmodule Ast do + def main do + expr = IO.gets("Give an expression:\n") |> String.Chars.to_string |> String.trim + case Code.string_to_quoted(expr) do + {:ok, ast} -> + IO.puts("AST is: " <> inspect(ast)) + {result, _} = Code.eval_quoted(ast) + IO.puts("Result = #{result}") + {:error, {_meta, message_info, _token}} -> + IO.puts(message_info) + end + end +end diff --git a/Task/Arithmetic-evaluation/FutureBasic/arithmetic-evaluation.basic b/Task/Arithmetic-evaluation/FutureBasic/arithmetic-evaluation.basic new file mode 100644 index 0000000000..9fcbf95f74 --- /dev/null +++ b/Task/Arithmetic-evaluation/FutureBasic/arithmetic-evaluation.basic @@ -0,0 +1,32 @@ +_window = 1 +begin enum 1 + _expressionLabel + _expressionFld + _resultLabel +end enum + +void local fn BuildUI + editmenu 1 + window _window, @"Arithmetic Evaluation", (0,0,522,61) + textlabel _expressionLabel, @"Expression:", (18,23,74,16) + textfield _expressionFld,,, (98,20,300,21) + textlabel _resultLabel,, (404,23,100,16) + WindowMakeFirstResponder( _window, _expressionFld ) +end fn + +void local fn EvaluateExpression( string as CFStringRef ) + ExpressionRef expression = fn ExpressionWithFormat( string ) + textlabel _resultlabel, fn StringWithFormat( @"= %@", fn ExpressionValueWithObject( expression, NULL, NULL ) ) +end fn + +void local fn DoDialog( ev as long, tag as long ) + select ( ev ) + case _btnClick : fn EvaluateExpression( textfield(tag) ) + end select +end fn + +fn BuildUI + +on dialog fn DoDialog + +HandleEvents diff --git a/Task/Arithmetic-geometric-mean/Dc/arithmetic-geometric-mean.dc b/Task/Arithmetic-geometric-mean/Dc/arithmetic-geometric-mean.dc new file mode 100644 index 0000000000..7363e853e4 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Dc/arithmetic-geometric-mean.dc @@ -0,0 +1,2 @@ +>>> 200 k ? sbsa [lalb +2/ lalb *vsb dsa lb - 0!=:]ds:xlap +?> 1 1 2 v / diff --git a/Task/Array-concatenation/LDPL/array-concatenation.ldpl b/Task/Array-concatenation/LDPL/array-concatenation.ldpl new file mode 100644 index 0000000000..6cc9d3d40e --- /dev/null +++ b/Task/Array-concatenation/LDPL/array-concatenation.ldpl @@ -0,0 +1,13 @@ +include "std-list.ldpl" + +data: +arr1 is number list +arr2 is number list + +procedure: +push 1 to arr1 +push 2 to arr1 +push 3 to arr2 +push 4 to arr2 +append list arr2 to list arr1 +display list arr1 diff --git a/Task/Array-concatenation/Odin/array-concatenation-1.odin b/Task/Array-concatenation/Odin/array-concatenation-1.odin new file mode 100644 index 0000000000..417991a7ae --- /dev/null +++ b/Task/Array-concatenation/Odin/array-concatenation-1.odin @@ -0,0 +1,15 @@ +package main + +import "core:fmt" +import "core:slice" + +main :: proc() { + x: [3]int = {1, 2, 3} + y: [3]int = {4, 5, 6} + + xy: [len(x) + len(y)]int + copy(xy[:], x[:]) + copy(xy[len(x):], y[:]) + + fmt.println(xy) +} diff --git a/Task/Array-concatenation/Odin/array-concatenation-2.odin b/Task/Array-concatenation/Odin/array-concatenation-2.odin new file mode 100644 index 0000000000..f1649311dc --- /dev/null +++ b/Task/Array-concatenation/Odin/array-concatenation-2.odin @@ -0,0 +1,14 @@ +package main + +import "core:fmt" +import "core:slice" + +main :: proc() { + x: [3]int = {1, 2, 3} + y: [3]int = {4, 5, 6} + + xy := slice.concatenate([][]int{x[:], y[:]}) + defer delete(xy) + + fmt.println(xy) +} diff --git a/Task/Array-length/Dt/array-length.dt b/Task/Array-length/Dt/array-length.dt new file mode 100644 index 0000000000..439206766f --- /dev/null +++ b/Task/Array-length/Dt/array-length.dt @@ -0,0 +1 @@ +[ "apple" "orange" ] len diff --git a/Task/Array-length/Elm/array-length.elm b/Task/Array-length/Elm/array-length.elm index 3121363868..6c40fca914 100644 --- a/Task/Array-length/Elm/array-length.elm +++ b/Task/Array-length/Elm/array-length.elm @@ -6,5 +6,5 @@ main = ["apple", "orange"] |> Array.fromList |> Array.length - |> Basics.toString + |> String.fromInt |> Html.text diff --git a/Task/Array-length/LDPL/array-length.ldpl b/Task/Array-length/LDPL/array-length.ldpl new file mode 100644 index 0000000000..7b6aaea20e --- /dev/null +++ b/Task/Array-length/LDPL/array-length.ldpl @@ -0,0 +1,9 @@ +data: +fruits is text list +len is number + +procedure: +push "apple" to fruits +push "orange" to fruits +get length of fruits in len +display len lf diff --git a/Task/Arrays/FutureBasic/arrays.basic b/Task/Arrays/FutureBasic/arrays.basic index 073b785c0a..b339560cb2 100644 --- a/Task/Arrays/FutureBasic/arrays.basic +++ b/Task/Arrays/FutureBasic/arrays.basic @@ -1,4 +1,4 @@ -window 1, @"FutureBasic Arrays" +window 1, @"FutureBasic Arrays", (0,0,480,450) begin globals dynamic gA1(10) as long @@ -58,31 +58,31 @@ void local fn CTypeDynamic gA1(1) = 38 gA1(10) = 67 for i = 0 to fn DynamicNextElement( dynamic(gA1) ) - 1 - print gA1(i), - next - print + print gA1(i), +next +print - gA1(5) = 19 - gA1(10) = 22 - for i = 0 to fn DynamicNextElement( dynamic(gA1) ) - 1 - print gA1(i), - next - print +gA1(5) = 19 +gA1(10) = 22 +for i = 0 to fn DynamicNextElement( dynamic(gA1) ) - 1 +print gA1(i), +next +print - gA2(0) = "Kilo" - gA2(1) = "Lima" - gA2(5) = "Mike" - for i = 0 to fn DynamicNextElement( dynamic(gA2) ) - 1 - print gA2(i), - next - print +gA2(0) = "Kilo" +gA2(1) = "Lima" +gA2(5) = "Mike" +for i = 0 to fn DynamicNextElement( dynamic(gA2) ) - 1 +print gA2(i), +next +print - gA2(1) = "November" - gA2(6) = "Oscar" - for i = 0 to fn DynamicNextElement( dynamic(gA2) ) - 1 - print gA2(i), - next - print : print +gA2(1) = "November" +gA2(6) = "Oscar" +for i = 0 to fn DynamicNextElement( dynamic(gA2) ) - 1 +print gA2(i), +next +print : print end fn void local fn CoreFoundationImmutable @@ -163,6 +163,33 @@ void local fn CoreFoundationMutableDynamic for i = 0 to len(a1) - 1 print a1[i], next + + print : print +end fn + +void local fn FB_MDA + long i + + text ,, fn ColorGray + print @"// FB MDA - mutable, dynamic, multi-dimensional" + text + + mda_add = @"Alpha" + mda_add = @"Romeo" + mda_add = @"Mike" + + for i = 0 to mda_count - 1 + print mda(i), + next + + print + + mda_swap(0),(2) + mda(1) = @"Delta" + + for i = 0 to mda_count - 1 + print mda(i), + next end fn fn CType @@ -170,5 +197,6 @@ fn CTypeDynamic fn CoreFoundationImmutable fn CoreFoundationMutableFixedLength fn CoreFoundationMutableDynamic +fn FB_MDA HandleEvents diff --git a/Task/Arrays/LDPL/arrays.ldpl b/Task/Arrays/LDPL/arrays.ldpl new file mode 100644 index 0000000000..bb675af05a --- /dev/null +++ b/Task/Arrays/LDPL/arrays.ldpl @@ -0,0 +1,21 @@ +data: +myArray is list of numbers + +procedure: +# add elements +push 1 to myArray +push 2 to myArray +push 3 to myArray + +# access elements +display myArray:0 lf + +# store elements +store 99 in myArray:0 + +# remove elements +remove element at 1 from myArray +delete last element of myArray + +# clear array +clear myArray diff --git a/Task/Atomic-updates/FutureBasic/atomic-updates.basic b/Task/Atomic-updates/FutureBasic/atomic-updates.basic new file mode 100644 index 0000000000..dfcc276341 --- /dev/null +++ b/Task/Atomic-updates/FutureBasic/atomic-updates.basic @@ -0,0 +1,50 @@ +local fn PopulateArrayWithRandomNumbers + NSUInteger i + + for i = 0 to 9 + mda (i) = rnd(90) + next +end fn + +local fn Display( title as CFStringRef ) as NSUInteger + NSUInteger i, worth = 0 + CFStringRef comma = @"," + + printf @"%@ [\b", title + for i = 0 to 9 + worth += mda_integer (i) + if i == 9 then comma = @"" + printf @"%2lu%@\b", mda_integer (i), comma + next + printf @"] Sum = %lu", worth +end fn = worth + +local fn Flatten( f as NSUInteger ) + NSUInteger i, f1 = int((f / 10) + .5 ), f2 = 0, temp + + for i = 0 to 9 + mda (i) = f1 + f2 += f1 + next + temp = mda_integer (9) + mda (9) = temp + f - f2 +end fn + +local fn Transfer( a1 as NSUInteger, a2 as NSUInteger ) + NSUInteger t, temp = int( rnd( mda_integer ( a1 ) ) ) + + t = mda_integer ( a1 ) : mda ( a1 ) = t -temp + t = mda_integer ( a2 ) : mda ( a2 ) = t +temp +end fn + +NSUInteger a, i + +random +fn PopulateArrayWithRandomNumbers +a = fn Display( @" Initial array:" ) +fn Flatten( a ) +a = fn Display( @" Current values:" ) +fn Transfer( 3, 5 ) +fn Display( @" 19 from 3 to 5:" ) + +HandleEvents diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index 4fe7752986..11d1006f7a 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -11,7 +11,7 @@ extension op while (enumerator.next()) { - sum += enumerator.get(); + sum += *enumerator; count += 1; }; diff --git a/Task/Averages-Median/Craft-Basic/averages-median.basic b/Task/Averages-Median/Craft-Basic/averages-median.basic new file mode 100644 index 0000000000..372c51dc6c --- /dev/null +++ b/Task/Averages-Median/Craft-Basic/averages-median.basic @@ -0,0 +1,152 @@ +define limit = 10, iterations = 6 +define iteration, size, middle, plusone +define point, top, high, low, pivot + +dim list[limit] +dim stack[limit] + +for iteration = 1 to iterations + + gosub fill + gosub median + +next iteration + +end + +sub fill + + print "list: ", + + erasearray list + + let size = int(rnd * limit) + 1 + + if size <= 2 then + + let size = 3 + + endif + + for i = 0 to size - 1 + + let list[i] = rnd * 1000 + rnd + print list[i], + + gosub printcomma + + next i + +return + +sub median + + gosub sort + + print newline, "size: ", size, tab, + + let middle = int((size - 1)/ 2) + print "middle: ", middle + 1, tab, + + if size mod 2 then + + print "median: ", list[middle] + + else + + let plusone = middle + 1 + print "median: ", (list[middle] + list[plusone]) / 2 + + endif + + print + +return + +sub sort + + let low = 0 + let high = size - 1 + let top = -1 + + let top = top + 1 + let stack[top] = low + let top = top + 1 + let stack[top] = high + + do + + if top < 0 then + + break + + endif + + let high = stack[top] + let top = top - 1 + let low = stack[top] + let top = top - 1 + + let i = low - 1 + + for j = low to high - 1 + + if list[j] <= list[high] then + + let i = i + 1 + let t = list[i] + let list[i] = list[j] + let list[j] = t + + endif + + next j + + let point = i + 1 + let t = list[point] + let list[point] = list[high] + let list[high] = t + let pivot = i + 1 + + if pivot - 1 > low then + + let top = top + 1 + let stack[top] = low + let top = top + 1 + let stack[top] = pivot - 1 + + endif + + if pivot + 1 < high then + + let top = top + 1 + let stack[top] = pivot + 1 + let top = top + 1 + let stack[top] = high + + endif + + wait + + loop top >= 0 + + print newline, "sorted: ", + + for i = 0 to size - 1 + + print list[i], + gosub printcomma + + next i + +return + +sub printcomma + + if i < size - 1 then + + print comma, " ", + + endif + +return diff --git a/Task/Babbage-problem/COBOL/babbage-problem.cobol b/Task/Babbage-problem/COBOL/babbage-problem.cobol index fa7c3b67d9..3649fdb16e 100644 --- a/Task/Babbage-problem/COBOL/babbage-problem.cobol +++ b/Task/Babbage-problem/COBOL/babbage-problem.cobol @@ -1,28 +1,32 @@ -IDENTIFICATION DIVISION. -PROGRAM-ID. BABBAGE-PROGRAM. + IDENTIFICATION DIVISION. + PROGRAM-ID. BABBAGE-PROGRAM. * A line beginning with an asterisk is an explanatory note. * The machine will disregard any such line. -DATA DIVISION. -WORKING-STORAGE SECTION. + + DATA DIVISION. + WORKING-STORAGE SECTION. * In this part of the program we reserve the storage space we shall * be using for our variables, using a 'PICTURE' clause to specify * how many digits the machine is to keep free. * The prefixed number 77 indicates that these variables do not form part * of any larger 'record' that we might want to deal with as a whole. -77 N PICTURE 99999. + 77 N PICTURE 99999. * We know that 99,736 is a valid answer. -77 N-SQUARED PICTURE 9999999999. -77 LAST-SIX PICTURE 999999. -PROCEDURE DIVISION. + 77 N-SQUARED PICTURE 9999999999. + 77 LAST-SIX PICTURE 999999. + + PROCEDURE DIVISION. * Here we specify the calculations that the machine is to carry out. -CONTROL-PARAGRAPH. - PERFORM COMPUTATION-PARAGRAPH VARYING N FROM 1 BY 1 - UNTIL LAST-SIX IS EQUAL TO 269696. - STOP RUN. -COMPUTATION-PARAGRAPH. - MULTIPLY N BY N GIVING N-SQUARED. - MOVE N-SQUARED TO LAST-SIX. + CONTROL-PARAGRAPH. + PERFORM COMPUTATION-PARAGRAPH VARYING N FROM 1 BY 1 + UNTIL LAST-SIX IS EQUAL TO 269696. + STOP RUN. + COMPUTATION-PARAGRAPH. + MULTIPLY N BY N GIVING N-SQUARED. + MOVE N-SQUARED TO LAST-SIX. * Since the variable LAST-SIX can hold a maximum of six digits, * only the final six digits of N-SQUARED will be moved into it: * the rest will not fit and will simply be discarded. - IF LAST-SIX IS EQUAL TO 269696 THEN DISPLAY N. + IF LAST-SIX IS EQUAL TO 269696 THEN DISPLAY N. + + END PROGRAM BABBAGE-PROGRAM. diff --git a/Task/Balanced-brackets/Factor/balanced-brackets-1.factor b/Task/Balanced-brackets/Factor/balanced-brackets-1.factor index aba286a551..cac885eef8 100644 --- a/Task/Balanced-brackets/Factor/balanced-brackets-1.factor +++ b/Task/Balanced-brackets/Factor/balanced-brackets-1.factor @@ -1,22 +1,20 @@ -USING: io formatting locals kernel math sequences unicode.case ; -IN: balanced-brackets +USING: combinators formatting kernel math random sequences strings ; +IN: rosetta-code.balanced-brackets -:: balanced ( str -- ) - 0 :> counter! - 1 :> ok! - str - [ dup length 0 > ] - [ 1 cut swap - "[" = [ counter 1 + counter! ] [ counter 1 - counter! ] if - counter 0 < [ 0 ok! ] when - ] - while - drop - ok 0 = - [ "NO" ] - [ counter 0 > [ "NO" ] [ "YES" ] if ] - if - print ; +: balanced? ( str -- ? ) + 0 swap [ + { + { CHAR: [ [ 1 + t ] } + { CHAR: ] [ 1 - dup 0 >= ] } + [ drop t ] + } case + ] all? swap zero? and ; -readln -balanced +: bracket-pairs ( n -- str ) + [ "[]" ] replicate "" concat-as ; + +: balanced-brackets-main ( -- ) + 5 bracket-pairs randomize dup balanced? "" "not " ? + "String \"%s\" is %sbalanced.\n" printf ; + +MAIN: balanced-brackets-main diff --git a/Task/Balanced-brackets/Factor/balanced-brackets-2.factor b/Task/Balanced-brackets/Factor/balanced-brackets-2.factor index 5be66f2984..aba286a551 100644 --- a/Task/Balanced-brackets/Factor/balanced-brackets-2.factor +++ b/Task/Balanced-brackets/Factor/balanced-brackets-2.factor @@ -1,20 +1,22 @@ USING: io formatting locals kernel math sequences unicode.case ; IN: balanced-brackets -: map-braces ( -- qout ) - [ - { - { "[" [ drop 1 ] } - { "]" [ drop -1 ] } - [ drop 0 ] - } case - ] -; +:: balanced ( str -- ) + 0 :> counter! + 1 :> ok! + str + [ dup length 0 > ] + [ 1 cut swap + "[" = [ counter 1 + counter! ] [ counter 1 - counter! ] if + counter 0 < [ 0 ok! ] when + ] + while + drop + ok 0 = + [ "NO" ] + [ counter 0 > [ "NO" ] [ "YES" ] if ] + if + print ; -: balanced? ( str -- ? ) - map-braces map sum 0 = -; - -"[1+2*[3+4*[5+6]-3]*4-[3*[3+3]]]" balanced? --- Data stack: -t +readln +balanced diff --git a/Task/Balanced-ternary/Koka/balanced-ternary.koka b/Task/Balanced-ternary/Koka/balanced-ternary.koka new file mode 100644 index 0000000000..6ec56bd7b9 --- /dev/null +++ b/Task/Balanced-ternary/Koka/balanced-ternary.koka @@ -0,0 +1,86 @@ +type btdigit + Pos + Zero + Neg + +alias btern = list + +fun to_string(n: btern): string + join( + n.reverse.map fn(d) + match d + Pos -> "+" + Zero -> "0" + Neg -> "-" + ) + +fun from_string(s: string): exn btern + var sl := Nil + s.foreach fn(c) + match c + '+' -> sl := Cons(Pos, sl) + '0' -> sl := Cons(Zero, sl) + '-' -> sl := Cons(Neg, sl) + _ -> throw("Invalid Character") + sl + +fun to_int(n: btern): int + match n + Nil -> 0 + Cons(Zero, Nil) -> 0 + Cons(Pos, rst) -> 1+3*rst.to_int + Cons(Neg, rst) -> -1+3*rst.to_int + Cons(Zero, rst) -> 3*rst.to_int + +fun from_int(n: int): btern + if n == 0 then [] else + match n % 3 + 0 -> Cons(Zero, from_int((n/3).unsafe-decreasing)) + 1 -> Cons(Pos, from_int(((n - 1)/3).unsafe-decreasing)) + 2 -> Cons(Neg, from_int(((n+1)/3).unsafe-decreasing)) + _ -> throw("Impossible") + +fun (+)(n1: btern, n2: btern): btern + match (n1, n2) + ([], a) -> a + (a, []) -> a + (Cons(Pos, t1), Cons(Neg, t2)) -> + val sum = t1 + t2 + if sum.is-nil then [] else Cons(Zero, sum) + (Cons(Neg, t1), Cons(Pos, t2)) -> + val sum = t1 + t2 + if sum.is-nil then [] else Cons(Zero, sum) + (Cons(Zero, t1), Cons(Zero, t2)) -> + val sum = t1 + t2 + if sum.is-nil then [] else Cons(Zero, sum) + (Cons(Pos, t1), Cons(Pos, t2)) -> Cons(Neg, t1 + t2 + [Pos]) + (Cons(Neg, t1), Cons(Neg, t2)) -> Cons(Pos, t1 + t2 + [Neg]) + (Cons(Zero, t1), Cons(h, t2)) -> Cons(h, t1 + t2) + (Cons(h, t1), Cons(Zero, t2)) -> Cons(h, t1 + t2) + _ -> throw("Impossible") + +fun neg(n: btern) + n.map fn(d) + match d + Pos -> Neg + Zero -> Zero + Neg -> Pos + +fun (-)(n1: btern, n2: btern): btern + n1 + neg(n2) + +fun (*)(n1, n2) + match n2 + [] -> [] + [Pos] -> n1 + [Neg] -> n1.neg + (Cons(Pos, t)) -> Cons(Zero, t*n1) + n1 + (Cons(Neg, t)) -> Cons(Zero, t*n1) - n1 + (Cons(Zero, t)) -> Cons(Zero, t*n1) + +fun main() + val a = "+-0++0+".from_string + val b = (-436).from_int + val c = "+-++-".from_string + val d = a * (b - c) + println("a = " ++ a.to_int.show ++ "\nb = " ++ b.to_string ++ "\nc = " ++ c.to_int.show ++ "\na * (b - c) = " ++ d.to_string ++ " = " ++ d.to_int.show ) diff --git a/Task/Barnsley-fern/Nim/barnsley-fern.nim b/Task/Barnsley-fern/Nim/barnsley-fern.nim index 29c7ead873..be73324201 100644 --- a/Task/Barnsley-fern/Nim/barnsley-fern.nim +++ b/Task/Barnsley-fern/Nim/barnsley-fern.nim @@ -1,4 +1,4 @@ -import nimPNG, random +import nimPNG, std/random randomize() @@ -46,7 +46,7 @@ proc drawPixel(x,y:float) = var x, y: float = 0.0 for i in 1..iterations: - var r = random(101) + var r = rand(101) var nx, ny: float if r <= 85: nx = 0.85 * x + 0.04 * y diff --git a/Task/Bell-numbers/Maxima/bell-numbers.maxima b/Task/Bell-numbers/Maxima/bell-numbers.maxima new file mode 100644 index 0000000000..e44867a735 --- /dev/null +++ b/Task/Bell-numbers/Maxima/bell-numbers.maxima @@ -0,0 +1,15 @@ +/* Subfactorial numbers */ +subfactorial(n):=block( +subf[0]:1, +subf[n]:n*subf[n-1]+(-1)^n, +subf[n])$ + +/* Bell numbers implementation */ +my_bell(n):=if n=0 then 1 else block( +makelist((1/((n-1)!))*subfactorial(j)*binomial(n-1,j)*(n-j)^(n-1),j,0,n-1), +apply("+",%%))$ + +/* First 50 */ +block( +makelist(my_bell(u),u,0,49), +table_form(%%)); diff --git a/Task/Bernoulli-numbers/Maxima/bernoulli-numbers.maxima b/Task/Bernoulli-numbers/Maxima/bernoulli-numbers.maxima new file mode 100644 index 0000000000..74bc015c53 --- /dev/null +++ b/Task/Bernoulli-numbers/Maxima/bernoulli-numbers.maxima @@ -0,0 +1,3 @@ +block(makelist([sconcat("B","(",i,")","="),bern(i)],i,0,60), +sublist(%%,lambda([x],x[2]#0)), +table_form(%%)) diff --git a/Task/Bifid-cipher/Ruby/bifid-cipher.rb b/Task/Bifid-cipher/Ruby/bifid-cipher.rb new file mode 100644 index 0000000000..9acddd33c4 --- /dev/null +++ b/Task/Bifid-cipher/Ruby/bifid-cipher.rb @@ -0,0 +1,65 @@ +def cleanMsg(msg, square) + msg.upcase! + msg.delete!(' ') + msg.delete!('J') if square.index('J') == nil +end + +def encrypt(msg, square) + cleanMsg msg, square + sq_size = (square.length ** 0.5).to_i + rows = [0] * msg.length + cols = [0] * msg.length + (0...msg.length).each do |i| + p = square.index(msg[i]) + rows[i], cols[i] = p / sq_size, p % sq_size + end + result = "" + rows.concat(cols).each_slice(2) do |coord| + result += square[coord[0]*sq_size + coord[1]] + end + return result +end + +def decrypt(msg, square) + msg.upcase!; square.upcase! + sq_size = (square.length ** 0.5).to_i + coords = [] + result = "" + (0...msg.length).each do |i| + p = square.index(msg[i]) + coords << p / sq_size + coords << p % sq_size + end + for i in (0...coords.length/2) do + row, col = coords[i], coords[i+coords.length/2] + result += square[row*sq_size + col] + end + return result +end + +def printSquare(square) + sq_size = (square.length ** 0.5).to_i + (0..square.length).step(sq_size).each do |i| + print square[i...(i+sq_size)], "\n" + end +end + +tests = [["ATTACKATDAWN" , "ABCDEFGHIKLMNOPQRSTUVWXYZ"], + ["FLEEATONCE" , "BGWKZQPNDSIOAXEFCLUMTHYVR"], + ["ATTACKATDAWN" , "ABCDEFGHIKLMNOPQRSTUVWXYZ"], + ["the invasion will start on the first of january", "BGWKZQPNDSIOAXEFCLUMTHYVR"], + ["THIS MESSAGE HAS NUMBERS 2023", "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"], +] + +for test in tests + message = test[0]; square = test[1]; + encrypted = encrypt(message, square) + decrypted = decrypt(encrypted, square) + + puts "using the polybius:" + printSquare(square) + puts "the plain message:", message + puts "encrypted:", encrypted + puts "decrypted:", decrypted + puts "====================================================" +end diff --git a/Task/Binary-digits/Dt/binary-digits.dt b/Task/Binary-digits/Dt/binary-digits.dt new file mode 100644 index 0000000000..225080e529 --- /dev/null +++ b/Task/Binary-digits/Dt/binary-digits.dt @@ -0,0 +1,5 @@ +[dup 1 gt? [dup 2 % swap 2 / loop] swap do?] \loop def + +[\loop doin rev \to-string map "" join] \bin def + +[0 1 2 5 50 9000] \bin map " " join pl diff --git a/Task/Bioinformatics-base-count/AArch64-Assembly/bioinformatics-base-count.aarch64 b/Task/Bioinformatics-base-count/AArch64-Assembly/bioinformatics-base-count.aarch64 new file mode 100644 index 0000000000..b30438145a --- /dev/null +++ b/Task/Bioinformatics-base-count/AArch64-Assembly/bioinformatics-base-count.aarch64 @@ -0,0 +1,239 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program cptAdn64.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" +.equ LIMIT, 30 +.equ SHIFT, 8 + +//.include "../../ficmacros64.inc" // use for debugging +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessResult: .asciz "Result: " +szDNA1: .ascii "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + .ascii "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + .ascii "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + .ascii "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + .ascii "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + .ascii "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + .ascii "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + .ascii "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + .ascii "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + .asciz "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" + +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 64 bits start.\n" +szMessCounterA: .asciz "Base A : " +szMessCounterC: .asciz "Base C : " +szMessCounterG: .asciz "Base G : " +szMessCounterT: .asciz "Base T : " +szMessTotal: .asciz "Total : " +sPrintLine: .fill LIMIT + SHIFT + 2,1,' ' // init line with spaces +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sZoneConv: .skip 24 +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: // entry of program + ldr x0,qAdrszMessStart + bl affichageMess + + ldr x0,qAdrszDNA1 + bl printDNA + ldr x0,qAdrszDNA1 + bl countBase + + +100: // standard end of the program + mov x0, #0 // return code + mov x8, #EXIT // request to exit program + svc 0 // perform the system call +qAdrszDNA1: .quad szDNA1 +qAdrsZoneConv: .quad sZoneConv +qAdrszMessResult: .quad szMessResult +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessStart: .quad szMessStart +/***************************************************/ +/* count dna line and print */ +/***************************************************/ +/* x0 contains dna string address */ +printDNA: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + stp x8,x9,[sp,-16]! + mov x8,x0 // save address + mov x4,#0 // counter + mov x3,#0 // index string + mov x4,#0 // byte line counter + mov x5,#1 // start line value + ldr x7,qAdrsPrintLine + ldr x9,qAdrsZoneConv +1: + ldrb w6,[x8,x3] // load byte of dna + cmp x6,#0 // end string ? + beq 4f // yes -> end + add x1,x7,#SHIFT + strb w6,[x1,x4] // store byte in display line + add x4,x4,#1 // increment index line + cmp x4,#LIMIT // end line ? + blt 3f + mov x0,x5 // convert decimal counter base + mov x1,x9 + bl conversion10 + mov x2,xzr +2: // copy decimal conversion in display line + ldrb w6,[x9,x2] + strb w6,[x7,x2] + add x2,x2,1 + cmp x2,x0 + blt 2b + + mov x0,#0 // Zero final + add x1,x7,#LIMIT + add x1,x1,#SHIFT + 1 + strb w0,[x1] + mov x0,x7 // line display + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + add x5,x5,#LIMIT // add line size to counter + mov x4,#0 // and init line index +3: + add x3,x3,#1 // increment index string + b 1b // and loop +4: // display end line if line contains base + cmp x4,#0 + beq 100f + mov x0,x5 + mov x1,x9 + bl conversion10 + mov x2,xzr +5: // copy decimal conversion in display line + ldrb w6,[x9,x2] + strb w6,[x7,x2] + add x2,x2,1 + cmp x2,x0 + blt 5b + + mov x0,#0 // Zero final + add x1,x7,x4 + add x1,x1,#SHIFT + strb w0,[x1] + mov x0,x7 // last line display + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + 100: + ldp x8,x9,[sp],16 + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret + qAdrsPrintLine: .quad sPrintLine + /***************************************************/ +/* count bases */ +/***************************************************/ +/* x0 contains dna string address */ +countBase: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + mov x2,#0 // string index + mov x3,#0 // A counter + mov x4,#0 // C counter + mov x5,#0 // G counter + mov x6,#0 // T counter +1: + ldrb w1,[x0,x2] // load byte of dna + cmp x1,#0 // end string ? + beq 2f + cmp x1,#'A' + cinc x3,x3,eq + cmp x1,#'C' + cinc x4,x4,eq + cmp x1,#'G' + cinc x5,x5,eq + cmp x1,#'T' + cinc x6,x6,eq + + add x2,x2,#1 + b 1b +2: + mov x0,x3 // convert decimal counter A + ldr x1,qAdrsZoneConv + bl conversion10 + ldr x0,qAdrszMessCounterA + bl affichageMess + ldr x0,qAdrsZoneConv + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + mov x0,x4 // convert decimal counter C + ldr x1,qAdrsZoneConv + bl conversion10 + ldr x0,qAdrszMessCounterC + bl affichageMess + ldr x0,qAdrsZoneConv + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + mov x0,x5 // convert decimal counter G + ldr x1,qAdrsZoneConv + bl conversion10 + ldr x0,qAdrszMessCounterG + bl affichageMess + ldr x0,qAdrsZoneConv + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + mov x0,x6 // convert decimal counter T + ldr x1,qAdrsZoneConv + bl conversion10 + ldr x0,qAdrszMessCounterT + bl affichageMess + ldr x0,qAdrsZoneConv + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + add x0,x3,x4 // convert decimal total + add x0,x0,x5 + add x0,x0,x6 + ldr x1,qAdrsZoneConv + bl conversion10 + ldr x0,qAdrszMessTotal + bl affichageMess + ldr x0,qAdrsZoneConv + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess +100: + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // TODO: retaur à completer + ret +qAdrszMessCounterA: .quad szMessCounterA +qAdrszMessCounterC: .quad szMessCounterC +qAdrszMessCounterG: .quad szMessCounterG +qAdrszMessCounterT: .quad szMessCounterT +qAdrszMessTotal: .quad szMessTotal +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Bioinformatics-base-count/ARM-Assembly/bioinformatics-base-count.arm b/Task/Bioinformatics-base-count/ARM-Assembly/bioinformatics-base-count.arm new file mode 100644 index 0000000000..ba43f79a56 --- /dev/null +++ b/Task/Bioinformatics-base-count/ARM-Assembly/bioinformatics-base-count.arm @@ -0,0 +1,205 @@ +/* ARM assembly Raspberry PI */ +/* program cptAdn.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../constantes.inc" +.equ LIMIT, 50 +.equ SHIFT, 11 + +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessResult: .asciz "Result: " +szDNA1: .ascii "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG" + .ascii "CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG" + .ascii "AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT" + .ascii "GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT" + .ascii "CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG" + .ascii "TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA" + .ascii "TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT" + .ascii "CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG" + .ascii "TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC" + .asciz "GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT" + +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 32 bits start.\n" +szMessCounterA: .asciz "Base A : " +szMessCounterC: .asciz "Base C : " +szMessCounterG: .asciz "Base G : " +szMessCounterT: .asciz "Base T : " +szMessTotal: .asciz "Total : " +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sZoneConv: .skip 24 +sPrintLine: .skip LIMIT + SHIFT + 2 +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: @ entry of program + ldr r0,iAdrszMessStart + bl affichageMess + + ldr r0,iAdrszDNA1 + bl printDNA + ldr r0,iAdrszDNA1 + bl countBase + + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform the system call +iAdrszDNA1: .int szDNA1 +iAdrsZoneConv: .int sZoneConv +iAdrszMessResult: .int szMessResult +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessStart: .int szMessStart +/***************************************************/ +/* count dna line and print */ +/***************************************************/ +/* r0 contains dna string address */ +printDNA: + push {r1-r8,lr} @ save registers + mov r8,r0 @ save address + mov r4,#0 @ counter + mov r3,#0 @ index stone + mov r4,#0 + mov r5,#1 + ldr r7,iAdrsPrintLine +1: + ldrb r6,[r8,r3] @ load byte of dna + cmp r6,#0 @ end string ? + beq 4f + add r1,r7,#SHIFT + strb r6,[r1,r4] @ store byte in display line + add r4,r4,#1 @ increment index line + cmp r4,#LIMIT @ end line ? + blt 3f + mov r0,r5 @ convert decimal counter base + mov r1,r7 + bl conversion10 + mov r0,#0 @ Zero final + add r1,r7,#LIMIT + add r1,r1,#SHIFT + 1 + strb r0,[r1] + mov r0,r7 @ line display + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + add r5,r5,#LIMIT @ add line size to counter + mov r4,#0 @ and init line index +3: + add r3,r3,#1 @ increment index string + b 1b @ and loop +4: @ display end line if line contains base + cmp r4,#0 + beq 100f + mov r0,r5 + mov r1,r7 + bl conversion10 + mov r0,#0 @ Zero final + add r1,r7,r4 + add r1,r1,#SHIFT + strb r0,[r1] + mov r0,r7 @ last line display + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + 100: + pop {r1-r8,pc} + iAdrsPrintLine: .int sPrintLine + /***************************************************/ +/* count bases */ +/***************************************************/ +/* r0 contains dna string address */ +countBase: + push {r1-r6,lr} @ save registers + mov r2,#0 @ string index + mov r3,#0 @ A counter + mov r4,#0 @ C counter + mov r5,#0 @ G counter + mov r6,#0 @ T counter +1: + ldrb r1,[r0,r2] @ load byte of dna + cmp r1,#0 @ end string ? + beq 2f + cmp r1,#'A' + addeq r3,r3,#1 + cmp r1,#'C' + addeq r4,r4,#1 + cmp r1,#'G' + addeq r5,r5,#1 + cmp r1,#'T' + addeq r6,r6,#1 + + add r2,r2,#1 + b 1b +2: + mov r0,r3 @ convert decimal counter A + ldr r1,iAdrsZoneConv + bl conversion10 + ldr r0,iAdrszMessCounterA + bl affichageMess + ldr r0,iAdrsZoneConv + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + mov r0,r4 @ convert decimal counter C + ldr r1,iAdrsZoneConv + bl conversion10 + ldr r0,iAdrszMessCounterC + bl affichageMess + ldr r0,iAdrsZoneConv + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + mov r0,r5 @ convert decimal counter G + ldr r1,iAdrsZoneConv + bl conversion10 + ldr r0,iAdrszMessCounterG + bl affichageMess + ldr r0,iAdrsZoneConv + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + mov r0,r6 @ convert decimal counter T + ldr r1,iAdrsZoneConv + bl conversion10 + ldr r0,iAdrszMessCounterT + bl affichageMess + ldr r0,iAdrsZoneConv + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + add r0,r3,r4 @ convert decimal total + add r0,r0,r5 + add r0,r0,r6 + ldr r1,iAdrsZoneConv + bl conversion10 + ldr r0,iAdrszMessTotal + bl affichageMess + ldr r0,iAdrsZoneConv + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess +100: + pop {r1-r6,pc} +iAdrszMessCounterA: .int szMessCounterA +iAdrszMessCounterC: .int szMessCounterC +iAdrszMessCounterG: .int szMessCounterG +iAdrszMessCounterT: .int szMessCounterT +iAdrszMessTotal: .int szMessTotal +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../affichage.inc" diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Ksh/bitmap-bresenhams-line-algorithm.ksh b/Task/Bitmap-Bresenhams-line-algorithm/Ksh/bitmap-bresenhams-line-algorithm.ksh new file mode 100644 index 0000000000..861da35a04 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Ksh/bitmap-bresenhams-line-algorithm.ksh @@ -0,0 +1,34 @@ +function line { + typeset x0=$1 y0=$2 x1=$3 y1=$4 + + if ((x0 > x1)) + then + ((dx = x0 - x1)); ((sx = -1)) + else + ((dx = x1 - x0)); ((sx = 1)) + fi + + if ((y0 > y1)) + then + ((dy = y0 - y1)); ((sy = -1)) + else + ((dy = y1 - y0)); ((sy = 1)) + fi + + if ((dx > dy)) + then + ((err = dx)) + else + ((err = -dy)) + fi + ((err /= 2)); ((e2 = 0)) + + while : + do + echo $x0 $y0 + ((x0 == x1 && y0 == y1)) && return + ((e2 = err)) + ((e2 > -dx)) && { ((err -= dy)); ((x0 += sx)) } + ((e2 < dy)) && { ((err += dx)); ((y0 += sy)) } + done +} diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Evaldraw/bitmap-midpoint-circle-algorithm.evaldraw b/Task/Bitmap-Midpoint-circle-algorithm/Evaldraw/bitmap-midpoint-circle-algorithm.evaldraw new file mode 100644 index 0000000000..4348d39d0c --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Evaldraw/bitmap-midpoint-circle-algorithm.evaldraw @@ -0,0 +1,42 @@ +() +{ + cls(0); + setcol(0xffffff); + srand(1234); + for(i=0; i<1000; i++) { + rad = int( abs(nrnd*10) ); + x=rnd*xres; + y=rnd*yres; + drawcircle(x,y,rad); + //drawsph(x,y,-rad); + } +} + +drawcircle(cx,cy,r) { + if (cx+r < 0 || cy+r < 0) return; + if (cx-r > xres || cy-r > yres) return; + r = int(r); + if (r<=0) return; + r2 = r+r; + x = r; y = 0; + dy = -2; dx = r2+r2 - 4; + d = r2-1; + while(y<=x) { + setpix(cx-x, cy-y); + setpix(cx+x, cy-y); + setpix(cx-x, cy+y); + setpix(cx+x, cy+y); + setpix(cx-y, cy-x); + setpix(cx+y, cy-x); + setpix(cx-y, cy+x); + setpix(cx+y, cy+x); + d += dy; + dy -= 4; + ++y; + if (d<0) { + d += dx; + dx -= 4; + --x; + } + } +} diff --git a/Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol b/Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol index bf708dadd2..2c7db9603d 100644 --- a/Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol +++ b/Task/Bitwise-operations/COBOL/bitwise-operations-1.cobol @@ -5,10 +5,9 @@ LOCAL-STORAGE SECTION. 01 a PIC 1(32) USAGE BIT. 01 b PIC 1(32) USAGE BIT. - 01 result PIC 1(32) USAGE BIT. - 01 result-disp REDEFINES result PIC S9(9) COMP. - + 01 result-disp REDEFINES result + PIC S9(9) USAGE COMPUTATIONAL. LINKAGE SECTION. 01 a-int USAGE BINARY-LONG. 01 b-int USAGE BINARY-LONG. @@ -29,7 +28,28 @@ COMPUTE result = a B-XOR b DISPLAY "a exclusive-or b is " result-disp - *> COBOL does not have shift or rotation operators. + *> More complex operations can be constructed from these. - GOBACK - . + COMPUTE result = B-NOT (a B-XOR b) + DISPLAY "Logical equivalence of a and b is " result-disp + + COMPUTE result = (B-NOT a) B-AND b + DISPLAY "Logical implication of a and b is " result-disp + + *> Shift and rotation operators were only added in COBOL 2023. + + COMPUTE result = a B-SHIFT-L b + DISPLAY "a shifted left by b is " result-disp + + COMPUTE result = b B-SHIFT-R a + DISPLAY "b shifted right by a is " result-disp + + COMPUTE result = a B-SHIFT-LC b + DISPLAY "a rotated left by b is " result-disp + + COMPUTE result = b B-SHIFT-RC a + DISPLAY "b rotated right by a is " result-disp + + GOBACK. + + END PROGRAM bitwise-ops. diff --git a/Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol b/Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol index c0193cafc5..08d7cdc4d6 100644 --- a/Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol +++ b/Task/Bitwise-operations/COBOL/bitwise-operations-2.cobol @@ -4,7 +4,6 @@ DATA DIVISION. LOCAL-STORAGE SECTION. 01 result USAGE BINARY-LONG. - 78 arg-len VALUE LENGTH OF result. LINKAGE SECTION. @@ -37,5 +36,6 @@ CALL "CBL_IMP" USING a, result, VALUE arg-len DISPLAY "Logical implication of a and b is " result - GOBACK - . + GOBACK. + + END PROGRAM mf-bitwise-ops. diff --git a/Task/Bitwise-operations/Elena/bitwise-operations.elena b/Task/Bitwise-operations/Elena/bitwise-operations.elena index 22b95e17d0..941e955022 100644 --- a/Task/Bitwise-operations/Elena/bitwise-operations.elena +++ b/Task/Bitwise-operations/Elena/bitwise-operations.elena @@ -4,10 +4,10 @@ extension testOp { bitwiseTest(y) { - console.printLine(self," and ",y," = ",self.and(y)); - console.printLine(self," or ",y," = ",self.or(y)); - console.printLine(self," xor ",y," = ",self.xor(y)); - console.printLine("not ",self," = ",self.Inverted); + console.printLine(self," and ",y," = ",self & y); + console.printLine(self," or ",y," = ",self | y); + console.printLine(self," xor ",y," = ",self ^ y); + console.printLine("not ",self," = ",self.BInverted); console.printLine(self," shr ",y," = ",self.shiftRight(y)); console.printLine(self," shl ",y," = ",self.shiftLeft(y)); } diff --git a/Task/Brazilian-numbers/ANSI-BASIC/brazilian-numbers.basic b/Task/Brazilian-numbers/ANSI-BASIC/brazilian-numbers.basic new file mode 100644 index 0000000000..44fcc8874b --- /dev/null +++ b/Task/Brazilian-numbers/ANSI-BASIC/brazilian-numbers.basic @@ -0,0 +1,112 @@ +1000 REM Brazilian numbers +1010 DECLARE EXTERNAL FUNCTION IsBrazilian +1020 DECLARE EXTERNAL FUNCTION SameDigits +1030 DECLARE EXTERNAL FUNCTION IsPrime +1040 PRINT "First 20 Brazilian numbers:" +1050 LET C = 0 +1060 LET N = 7 +1070 DO WHILE C < 20 +1080 IF IsBrazilian(N) <> 0 THEN +1090 PRINT N; +1100 LET C = C + 1 +1110 END IF +1120 LET N = N + 1 +1130 LOOP +1140 PRINT +1150 PRINT +1160 PRINT "First 20 odd Brazilian numbers:" +1170 LET C = 0 +1180 LET N = 7 +1190 DO WHILE C < 20 +1200 IF IsBrazilian(N) <> 0 THEN +1210 PRINT N; +1220 LET C = C + 1 +1230 END IF +1240 LET N = N + 2 +1250 LOOP +1260 PRINT +1270 PRINT +1280 PRINT "First 20 prime Brazilian numbers:" +1290 LET C = 0 +1300 LET N = 7 +1310 DO WHILE C < 20 +1320 IF IsBrazilian(N) <> 0 THEN +1330 PRINT N; +1340 LET C = C + 1 +1350 END IF +1360 DO +1370 LET N = N + 2 +1380 LOOP WHILE IsPrime(N) = 0 +1390 LOOP +1400 PRINT +1410 END +1420 REM +1430 EXTERNAL FUNCTION IsBrazilian(N) +1440 REM Result: 1 if N is Brazilian, 0 otherwise +1450 IF N < 7 THEN +1460 LET IsBrazilian = 0 +1470 ELSEIF (MOD(N, 2) = 0) AND (N >= 8) THEN +1480 LET IsBrazilian = 1 +1490 ELSE +1500 FOR B = 2 TO N - 2 +1510 IF SameDigits(N, B) <> 0 THEN +1520 LET IsBrazilian = 1 +1530 EXIT FUNCTION +1540 END IF +1550 NEXT B +1560 LET IsBrazilian = 0 +1570 END IF +1580 END FUNCTION +1590 REM +1600 EXTERNAL FUNCTION SameDigits(N, B) +1610 REM Result: 1 if N has same digits in the base B, 0 otherwise +1620 LET NL = N ! Local N +1630 LET F = MOD(NL, B) +1640 LET NL = INT(NL / B) +1650 DO WHILE NL > 0 +1660 IF MOD(NL, B) <> F THEN +1670 LET SameDigits = 0 +1680 EXIT FUNCTION +1690 END IF +1700 LET NL = INT(NL / B) +1710 LOOP +1720 LET SameDigits = 1 +1730 END FUNCTION +1740 REM +1750 EXTERNAL FUNCTION IsPrime(N) +1760 REM Result: non-zero if N is prime, 0 otherwise +1770 IF N < 2 THEN +1780 LET IsPrime = 0 +1790 ELSEIF MOD(N, 2) = 0 THEN +1800 REM IsPrime = (N = 2) +1810 IF N = 2 THEN +1820 LET IsPrime = 1 +1830 ELSE +1840 LET IsPrime = 0 +1850 END IF +1860 ELSEIF MOD(N, 3) = 0 THEN +1870 REM IsPrime = (N = 3) +1880 IF N = 3 THEN +1890 LET IsPrime = 1 +1900 ELSE +1910 LET IsPrime = 0 +1920 END IF +1930 ELSE +1940 LET D = 5 +1950 DO WHILE D * D <= N +1960 IF MOD(N, D) = 0 THEN +1970 LET IsPrime = 0 +1980 EXIT FUNCTION +1990 ELSE +2000 LET D = D + 2 +2010 IF MOD(N, D) = 0 THEN +2020 LET IsPrime = 0 +2030 EXIT FUNCTION +2040 ELSE +2050 LET D = D + 4 +2060 END IF +2070 END IF +2080 LOOP +2090 LET IsPrime = 1 +2100 END IF +2110 END FUNCTION diff --git a/Task/Brazilian-numbers/Modula-2/brazilian-numbers.mod2 b/Task/Brazilian-numbers/Modula-2/brazilian-numbers.mod2 new file mode 100644 index 0000000000..bb3a66600c --- /dev/null +++ b/Task/Brazilian-numbers/Modula-2/brazilian-numbers.mod2 @@ -0,0 +1,111 @@ +MODULE BrazilianNumbers; + +FROM STextIO IMPORT + WriteLn, WriteString; +FROM SWholeIO IMPORT + WriteInt; + +VAR + C, N: CARDINAL; + +PROCEDURE SameDigits(N, B: CARDINAL): BOOLEAN; +VAR + F: CARDINAL; +BEGIN + F := N MOD B; + N := N / B; + WHILE N > 0 DO + IF N MOD B <> F THEN + RETURN FALSE; + END; + N := N / B; + END; + RETURN TRUE; +END SameDigits; + +PROCEDURE IsBrazilian(N: CARDINAL): BOOLEAN; +VAR + B: CARDINAL; +BEGIN + IF N < 7 THEN + RETURN FALSE + ELSIF (N MOD 2 = 0) AND (N >= 8) THEN + RETURN TRUE + ELSE + FOR B := 2 TO N - 2 DO + IF SameDigits(N, B) THEN + RETURN TRUE + END + END; + RETURN FALSE; + END +END IsBrazilian; + +PROCEDURE IsPrime(N: CARDINAL): BOOLEAN; +VAR + D: CARDINAL; +BEGIN + IF N < 2 THEN + RETURN FALSE; + ELSIF N MOD 2 = 0 THEN + RETURN N = 2; + ELSIF N MOD 3 = 0 THEN + RETURN N = 3; + ELSE + D := 5; + WHILE D * D <= N DO + IF N MOD D = 0 THEN + RETURN FALSE + ELSE + D := D + 2; + IF N MOD D = 0 THEN + RETURN FALSE + ELSE + D := D + 4 + END + END + END; + RETURN TRUE; + END +END IsPrime; + +BEGIN + WriteString("First 20 Brazilian numbers:"); + WriteLn; + C := 0; N := 7; + WHILE C < 20 DO + IF IsBrazilian(N) THEN + WriteInt(N, 1); + WriteString(" "); + C := C + 1; + END; + N := N + 1; + END; + WriteLn; WriteLn; + WriteString("First 20 odd Brazilian numbers:"); + WriteLn; + C := 0; N := 7; + WHILE C < 20 DO + IF IsBrazilian(N) THEN + WriteInt(N, 1); + WriteString(" "); + C := C + 1; + END; + N := N + 2; + END; + WriteLn; WriteLn; + WriteString("First 20 prime Brazilian numbers:"); + WriteLn; + C := 0; N := 7; + WHILE C < 20 DO + IF IsBrazilian(N) THEN + WriteInt(N, 1); + WriteString(" "); + C := C + 1; + END; + REPEAT + N := N + 2 + UNTIL IsPrime(N); + END; + WriteLn; +END BrazilianNumbers. diff --git a/Task/Brazilian-numbers/Nascom-BASIC/brazilian-numbers.basic b/Task/Brazilian-numbers/Nascom-BASIC/brazilian-numbers.basic new file mode 100644 index 0000000000..f17b46a162 --- /dev/null +++ b/Task/Brazilian-numbers/Nascom-BASIC/brazilian-numbers.basic @@ -0,0 +1,62 @@ +10 REM Brazilian numbers +20 PRINT "First 20 Brazilian numbers:" +30 C=0:N=7 +40 IF C>=20 THEN 90 +50 GOSUB 320 +60 IF BR THEN PRINT N;:C=C+1 +70 N=N+1 +80 GOTO 40 +90 PRINT:PRINT +100 PRINT "First 20 odd Brazilian numbers:" +110 C=0:N=7 +120 IF C>=20 THEN 170 +130 GOSUB 320 +140 IF BR THEN PRINT N;:C=C+1 +150 N=N+2 +160 GOTO 120 +170 PRINT:PRINT +180 PRINT "First 12 prime Brazilian numbers:" +190 C=0:N=7 +200 IF C>=12 THEN 270 +210 GOSUB 320 +220 IF BR THEN PRINT N;:C=C+1 +230 N=N+2 +240 GOSUB 530 +250 IF NOT PRM THEN 230 +260 GOTO 200 +270 PRINT +280 END +290 REM ** Is Brazilian? +300 REM Result: BR=-1 if N is Brazilian +310 REM 0 otherwise +320 IF N<7 THEN BR=0:RETURN +330 IF INT(N/2)*2=N AND N>=8 THEN BR=-1:RETURN +340 FOR B=2 TO N-2 +350 GOSUB 430 +360 IF SMD THEN BR=-1:RETURN +370 NEXT B +380 BR=0 +390 RETURN +400 REM ** Same digits? +410 REM Result: SMD=-1 if N has same digits in B, +420 REM 0 otherwise +430 NL=N:REM "Local" N +440 NDB=INT(NL/B) +450 F=NL-NDB*B +460 NL=NDB:NDB=INT(NL/B) +470 IF NL<=0 THEN SMD=-1:RETURN +480 IF NL-NDB*B<>F THEN SMD=0:RETURN +490 NL=INT(NL/B):NDB=INT(NL/B) +500 GOTO 470 +510 REM ** Is prime? +520 REM Result: PRM=-1 if N prime, 0 otherwise +530 IF N<2 THEN PRM=0:RETURN +540 IF INT(N/2)*2=N THEN PRM=N=2:RETURN +550 IF INT(N/3)*3=N THEN PRM=N=3:RETURN +560 D=5 +570 IF D*D>N THEN PRM=-1:RETURN +580 IF INT(N/D)*D=N THEN PRM=0:RETURN +590 D=D+2 +600 IF INT(N/D)*D=N THEN PRM=0:RETURN +610 D=D+4 +620 GOTO 570 diff --git a/Task/Brazilian-numbers/Scala/brazilian-numbers-2.scala b/Task/Brazilian-numbers/Scala/brazilian-numbers-2.scala index 9ed9639dce..1fd5369c4d 100644 --- a/Task/Brazilian-numbers/Scala/brazilian-numbers-2.scala +++ b/Task/Brazilian-numbers/Scala/brazilian-numbers-2.scala @@ -31,6 +31,6 @@ object Brazilian extends App { println(s"$listStr: " + stream.filter(isBrazilian(_)).take(limit).toList) println("be a little patient, it will take some time") - val bigElement = LazyList.from(7).filter(isBrazilian(_)).drop(bigLimit - 1).take(1).head + val bigElement = LazyList.from(7).filter(isBrazilian(_)).drop(bigLimit - 1).head println(s"brazilian($bigLimit): $bigElement") } diff --git a/Task/Brilliant-numbers/FreeBASIC/brilliant-numbers.basic b/Task/Brilliant-numbers/FreeBASIC/brilliant-numbers.basic new file mode 100644 index 0000000000..35919cbc6d --- /dev/null +++ b/Task/Brilliant-numbers/FreeBASIC/brilliant-numbers.basic @@ -0,0 +1,46 @@ +function is_prime( n as uinteger ) as boolean + if n = 2 then return true + if n<2 or n mod 2 = 0 then return false + for i as uinteger = 3 to sqr(n) step 2 + if (n mod i) = 0 then return false + next i + return true +end function + +function first_prime_factor( n as uinteger ) as uinteger + if n mod 2 = 0 then return 2 + for i as uinteger = 3 to sqr(n) step 2 + if (n mod i) = 0 then return i + next i + return n +end function + +dim as uinteger count = 0, n = 0, ff, sf, expo = 0 + +while count<100 + ff = first_prime_factor(n) + sf = n/ff + if is_prime(sf) and len(str(ff)) = len(str(sf)) then + print n, + count = count + 1 + if count mod 6 = 0 then print + end if + n = n + 1 +wend +print +count = 0 + +n = 0 +do + ff = first_prime_factor(n) + sf = n/ff + if is_prime(sf) and len(str(ff)) = len(str(sf)) then + count = count + 1 + if n > 10^expo then + print n;" is brilliant #"; count + expo = expo + 1 + if expo = 9 then end + end if + end if + n = n + 1 +loop diff --git a/Task/Brilliant-numbers/Scala/brilliant-numbers.scala b/Task/Brilliant-numbers/Scala/brilliant-numbers.scala index c50d4039ac..ea17044fe7 100644 --- a/Task/Brilliant-numbers/Scala/brilliant-numbers.scala +++ b/Task/Brilliant-numbers/Scala/brilliant-numbers.scala @@ -28,7 +28,7 @@ def brilliantSemiPrimes(limit: Int): Seq[Int] = { val (bril, index) = brilliantSemiPrimes((limit * 1.25).toInt) .zipWithIndex .dropWhile((b, _i) => b < limit) - .take(1).head + .head val duration = System.currentTimeMillis - start println(f"first >= $limit%7d is $bril%7d at position ${index+1}%5d [time(ms) $duration%2d]") } diff --git a/Task/Brownian-tree/Evaldraw/brownian-tree.evaldraw b/Task/Brownian-tree/Evaldraw/brownian-tree.evaldraw new file mode 100644 index 0000000000..8745f0fac3 --- /dev/null +++ b/Task/Brownian-tree/Evaldraw/brownian-tree.evaldraw @@ -0,0 +1,62 @@ +enum{SIZE=256, PARTICLES_PER_FRAME=10, PARTICLE_OK, GIVE_UP}; +static world[SIZE][SIZE]; +() +{ + // set the seed + if (numframes==0) world[SIZE/2][SIZE/2] = 1; + + t = klock(); + simulate_brownian_tree(t); + + cls(0); + for (y = 0; y < SIZE; y++){ + for (x = 0; x < SIZE; x++){ + cell = world[y][x]; + if ( cell ) { + s = 100; // color scale + setcol(128+(s*cell % 128), 128+(s*.7*cell % 128), 128+(s*.1*cell % 128) ); + setpix(x,y); + } + } + } + moveto(0,SIZE+15); + setcol(0xffffff); + printf("%g frames", numframes); +} + +plop_particle(&px, &py) { + for (try=0; try<1000; try++) { + px = int(rnd*SIZE); + py = int(rnd*SIZE); + if (world[py][px] == 0) return PARTICLE_OK; + } + return GIVE_UP; +} + +simulate_brownian_tree(time){ + for(iter=0; iter= SIZE || dy + py < 0 || dy + py >= SIZE) + { + // Restart if outside of screen + if ( plop_particle(px,py) == GIVE_UP ) return; + }else if (world[py + dy][px + dx]){ + // bumped into something + world[py][px] = time; + break; + }else{ + py += dy; + px += dx; + } + } + } +} diff --git a/Task/Brownian-tree/Factor/brownian-tree.factor b/Task/Brownian-tree/Factor/brownian-tree.factor deleted file mode 100644 index 5762e2a3a7..0000000000 --- a/Task/Brownian-tree/Factor/brownian-tree.factor +++ /dev/null @@ -1,48 +0,0 @@ -USING: accessors images images.loader kernel literals math -math.vectors random sets ; -FROM: sets => in? ; -EXCLUDE: sequences => move ; -IN: rosetta-code.brownian-tree - -CONSTANT: size 512 -CONSTANT: num-particles 30000 -CONSTANT: seed { 256 256 } -CONSTANT: spawns { { 10 10 } { 502 10 } { 10 502 } { 502 502 } } -CONSTANT: bg-color B{ 0 0 0 255 } -CONSTANT: fg-color B{ 255 255 255 255 } - -: in-bounds? ( loc -- ? ) - dup { 0 0 } ${ size 1 - dup } vclamp = ; - -: move ( loc -- loc' ) - dup 2 [ { 1 -1 } random ] replicate v+ dup in-bounds? - [ nip ] [ drop ] if ; - -: grow ( particles -- particles' ) - spawns random dup - [ 2over swap in? ] [ drop dup move swap ] until nip - swap [ adjoin ] keep ; - -: brownian-data ( -- seq ) - HS{ $ seed } clone num-particles 1 - [ grow ] times { } - set-like ; - -: blank-bitmap ( -- bitmap ) - size sq [ bg-color ] replicate B{ } concat-as ; - -: init-img ( -- img ) - - ${ size size } >>dim - BGRA >>component-order - ubyte-components >>component-type - blank-bitmap >>bitmap ; - -: brownian-img ( -- img ) - init-img dup brownian-data - [ swap [ fg-color swap first2 ] dip set-pixel-at ] with each - ; - -: save-brownian-tree-image ( -- ) - brownian-img "brownian.png" save-graphic-image ; - -MAIN: save-brownian-tree-image diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index 940fa9ab43..09afc896c0 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -3,88 +3,90 @@ import extensions; class GameMaster { - object theNumbers; - object theAttempt; + field _numbers; + field _attempt; - constructor() - { - // generate secret number - var randomNumbers := new int[]{1,2,3,4,5,6,7,8,9}.randomize(9); + constructor() + { + // generate secret number + var randomNumbers := new int[]{1,2,3,4,5,6,7,8,9}.randomize(9); - theNumbers := randomNumbers.Subarray(0, 4); - theAttempt := new Integer(1); - } + _numbers := randomNumbers.Subarray(0, 4); + _attempt := new Integer(1); + } - ask() - { - var row := console.print("Your Guess #",theAttempt," ?").readLine(); + ask() + { + var row := console.print("Your Guess #",_attempt," ?").readLine(); - ^ row.toArray() - } + ^ row.toArray() + } - proceed(guess) - { - int cows := 0; - int bulls := 0; + proceed(guess) + { + int cows := 0; + int bulls := 0; - if (guess.Length != 4) - { + if (guess.Length != 4) + { + bulls := -1 + } + else + { + try + { + for (int i := 0, i < 4, i+=1) { + var ch := guess[i]; + var number := ch.toString().toInt(); + + // check range + ifnot (number > 0 && number < 10) + { InvalidArgumentException.raise() }; + + // check duplicates + var duplicate := guess.seekEach:(x => (x == ch)&&(x.equalReference(ch).Inverted)); + if (nil != duplicate) + { + InvalidArgumentException.raise() + }; + + if (number == _numbers[i]) + { + bulls += 1 + } + else + { + if (_numbers.ifExists(number)) + { cows += 1 } + } + } + } + catch(Exception e) + { bulls := -1 - } - else - { - try - { - for (int i := 0, i < 4, i+=1) { - var ch := guess[i]; - var number := ch.toString().toInt(); + } + }; - // check range - ifnot (number > 0 && number < 10) - { InvalidArgumentException.raise() }; + bulls => + -1 { console.printLine:"Not a valid guess."; ^ true } + 4 { console.printLine:"Congratulations! You have won!"; ^ false } + : { + _attempt.append(1); - // check duplicates - var duplicate := guess.seekEach:(x => (x == ch)&&(x.equalReference(ch).Inverted)); - if (nil != duplicate) - { - InvalidArgumentException.raise() - }; + console.printLine("Your Score is ",bulls," bulls and ",cows," cows"); - if (number == theNumbers[i]) - { - bulls += 1 - } - else - { - if (theNumbers.ifExists(number)) - { cows += 1 } - } - } - } - catch(Exception e) - { - bulls := -1 - } - }; - - bulls => - -1 { console.printLine:"Not a valid guess."; ^ true } - 4 { console.printLine:"Congratulations! You have won!"; ^ false } - : { - theAttempt.append(1); - - console.printLine("Your Score is ",bulls," bulls and ",cows," cows"); - - ^ true - } - } + ^ true + } + } } public program() { - var gameMaster := new GameMaster(); + var gameMaster := new GameMaster(); - (lazy:gameMaster.proceed(gameMaster.ask())).doWhile(); + var process := $lazy gameMaster.proceed(gameMaster.ask()); - console.readChar() + process.doWhile(); + + console.readChar() } diff --git a/Task/CRC-32/Zig/crc-32.zig b/Task/CRC-32/Zig/crc-32.zig new file mode 100644 index 0000000000..10a6bf31c1 --- /dev/null +++ b/Task/CRC-32/Zig/crc-32.zig @@ -0,0 +1,7 @@ +const std = @import("std"); +const Crc32Ieee = std.hash.Crc32; + +pub fn main() !void { + var res: u32 = Crc32Ieee.hash("The quick brown fox jumps over the lazy dog"); + std.debug.print("{x}\n", .{res}); +} diff --git a/Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol b/Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol index af62e5229c..02c1bfd4bd 100644 --- a/Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol +++ b/Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol @@ -1,37 +1,36 @@ - identification division. - program-id. caesar. - data division. - 1 msg pic x(50) - value "The quick brown fox jumped over the lazy dog.". - 1 offset binary pic 9(4) value 7. - 1 from-chars pic x(52). - 1 to-chars pic x(52). - 1 tabl. - 2 pic x(26) value "abcdefghijklmnopqrstuvwxyz". - 2 pic x(26) value "ABCDEFGHIJKLMNOPQRSTUVWXYZ". - 2 pic x(26) value "abcdefghijklmnopqrstuvwxyz". - 2 pic x(26) value "ABCDEFGHIJKLMNOPQRSTUVWXYZ". - procedure division. - begin. - display msg - perform encrypt - display msg - perform decrypt - display msg - stop run - . + IDENTIFICATION DIVISION. + PROGRAM-ID. CAESAR. - encrypt. - move tabl (1:52) to from-chars - move tabl (1 + offset:52) to to-chars - inspect msg converting from-chars - to to-chars - . + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 MSG PIC X(50) + VALUE "The quick brown fox jumped over the lazy dog.". + 01 OFFSET PIC 9(4) VALUE 7 USAGE BINARY. + 01 FROM-CHARS PIC X(52). + 01 TO-CHARS PIC X(52). + 01 TABL. + 02 PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz". + 02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ". + 02 PIC X(26) VALUE "abcdefghijklmnopqrstuvwxyz". + 02 PIC X(26) VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ". - decrypt. - move tabl (1 + offset:52) to from-chars - move tabl (1:52) to to-chars - inspect msg converting from-chars - to to-chars - . - end program caesar. + PROCEDURE DIVISION. + BEGIN. + DISPLAY MSG + PERFORM ENCRYPT + DISPLAY MSG + PERFORM DECRYPT + DISPLAY MSG + STOP RUN. + + ENCRYPT. + MOVE TABL (1:52) TO FROM-CHARS + MOVE TABL (1 + OFFSET:52) TO TO-CHARS + INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS. + + DECRYPT. + MOVE TABL (1 + OFFSET:52) TO FROM-CHARS + MOVE TABL (1:52) TO TO-CHARS + INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS. + + END PROGRAM CAESAR. diff --git a/Task/Caesar-cipher/COBOL/caesar-cipher-2.cobol b/Task/Caesar-cipher/COBOL/caesar-cipher-2.cobol index e287e5b7aa..20f86ddb95 100644 --- a/Task/Caesar-cipher/COBOL/caesar-cipher-2.cobol +++ b/Task/Caesar-cipher/COBOL/caesar-cipher-2.cobol @@ -1,86 +1,84 @@ >>SOURCE FORMAT IS FREE +IDENTIFICATION DIVISION. PROGRAM-ID. caesar-cipher. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION encrypt - FUNCTION decrypt - . + FUNCTION decrypt. + DATA DIVISION. WORKING-STORAGE SECTION. 01 plaintext PIC X(50). -01 offset PIC 99. - +01 offset USAGE BINARY-CHAR. 01 encrypted-str PIC X(50). PROCEDURE DIVISION. - DISPLAY "Enter a message to encrypt: " NO ADVANCING + DISPLAY "Enter a message to encrypt: " WITH NO ADVANCING ACCEPT plaintext - DISPLAY "Enter the amount to shift by: " NO ADVANCING + DISPLAY "Enter the amount to shift by: " WITH NO ADVANCING ACCEPT offset - - MOVE FUNCTION encrypt(offset, plaintext) TO encrypted-str + MOVE encrypt(offset, plaintext) TO encrypted-str DISPLAY "Encrypted: " encrypted-str - DISPLAY "Decrypted: " FUNCTION decrypt(offset, encrypted-str) - . + DISPLAY "Decrypted: " decrypt(offset, encrypted-str). + END PROGRAM caesar-cipher. - +IDENTIFICATION DIVISION. FUNCTION-ID. encrypt. +ENVIRONMENT DIVISION. +CONFIGURATION SECTION. +REPOSITORY. + FUNCTION ALL INTRINSIC. + DATA DIVISION. LOCAL-STORAGE SECTION. -01 i PIC 9(3). - -01 a PIC 9(3). - +01 i USAGE INDEX. +01 a USAGE BINARY-CHAR. LINKAGE SECTION. -01 offset PIC 99. +01 offset USAGE BINARY-CHAR. 01 str PIC X(50). - 01 encrypted-str PIC X(50). PROCEDURE DIVISION USING offset, str RETURNING encrypted-str. - MOVE str TO encrypted-str - PERFORM VARYING i FROM 1 BY 1 UNTIL i > FUNCTION LENGTH(str) - IF encrypted-str (i:1) IS NOT ALPHABETIC OR encrypted-str (i:1) = SPACE + PERFORM VARYING i FROM 1 BY 1 UNTIL i > LENGTH(str) + IF str(i:1) IS NOT ALPHABETIC OR str(i:1) = SPACE + MOVE str(i:1) TO encrypted-str(i:1) EXIT PERFORM CYCLE END-IF - - IF encrypted-str (i:1) IS ALPHABETIC-UPPER - MOVE FUNCTION ORD("A") TO a + IF str(i:1) IS ALPHABETIC-UPPER + MOVE ORD("A") TO a ELSE - MOVE FUNCTION ORD("a") TO a + MOVE ORD("a") TO a END-IF - - MOVE FUNCTION CHAR(FUNCTION MOD(FUNCTION ORD(encrypted-str (i:1)) - - a + offset, 26) + a) - TO encrypted-str (i:1) + MOVE CHAR(MOD(ORD(str(i:1)) - a + offset, 26) + a) + TO encrypted-str(i:1) END-PERFORM - . + EXIT FUNCTION. + END FUNCTION encrypt. - +IDENTIFICATION DIVISION. FUNCTION-ID. decrypt. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. - FUNCTION encrypt - . + FUNCTION encrypt. + DATA DIVISION. LOCAL-STORAGE SECTION. -01 decrypt-offset PIC 99. - +01 decrypt-offset USAGE BINARY-CHAR. LINKAGE SECTION. -01 offset PIC 99. +01 offset USAGE BINARY-CHAR. 01 str PIC X(50). - 01 decrypted-str PIC X(50). PROCEDURE DIVISION USING offset, str RETURNING decrypted-str. - SUBTRACT 26 FROM offset GIVING decrypt-offset - MOVE FUNCTION encrypt(decrypt-offset, str) TO decrypted-str - . + SUBTRACT offset FROM 26 GIVING decrypt-offset + MOVE encrypt(decrypt-offset, str) TO decrypted-str + EXIT FUNCTION. + END FUNCTION decrypt. diff --git a/Task/Caesar-cipher/Elena/caesar-cipher.elena b/Task/Caesar-cipher/Elena/caesar-cipher.elena index b87575f5f6..4a89a12e15 100644 --- a/Task/Caesar-cipher/Elena/caesar-cipher.elena +++ b/Task/Caesar-cipher/Elena/caesar-cipher.elena @@ -10,37 +10,37 @@ const int Key = 12; class Encrypting : Enumerator { - int theKey; - Enumerator theEnumerator; + int _key; + Enumerator _enumerator; constructor(int key, string text) { - theKey := key; - theEnumerator := text.enumerator(); + _key := key; + _enumerator := text.enumerator(); } - bool next() => theEnumerator; + bool next() => _enumerator; - reset() => theEnumerator; + reset() => _enumerator; - enumerable() => theEnumerator; + enumerable() => _enumerator; - get() + get Value() { - var ch := theEnumerator.get(); + var ch := *_enumerator; var index := Letters.indexOf(0, ch); if (-1 < index) { - ^ Letters[(theKey+index).mod:26] + ^ Letters[(_key+index).mod:26] } else { index := BigLetters.indexOf(0, ch); if (-1 < index) { - ^ BigLetters[(theKey+index).mod:26] + ^ BigLetters[(_key+index).mod:26] } else { diff --git a/Task/Caesar-cipher/GW-BASIC/caesar-cipher.basic b/Task/Caesar-cipher/GW-BASIC/caesar-cipher.basic new file mode 100644 index 0000000000..e1601d38fa --- /dev/null +++ b/Task/Caesar-cipher/GW-BASIC/caesar-cipher.basic @@ -0,0 +1,16 @@ +10 REM Caesar cipher +20 CLS +30 DEC$ = "" +40 TYPE$ = "cleartext " +50 PRINT "If decrypting enter "+" "+" -- else press enter "; : INPUT DEC$ +60 INPUT "Enter offset > "; IOFFSET +70 IF DEC$ = "d" THEN IOFFSET = 26-IOFFSET: TYPE$ = "ciphertext " +110 PRINT "Enter "+TYPE$+"> "; +120 INPUT CAD$ +140 LONGITUD = LEN(CAD$) +150 FOR I = 1 TO LONGITUD +160 ITEMP = ASC(MID$(CAD$,I,1)) +170 IF ITEMP > 64 AND ITEMP < 91 THEN ITEMP = ((ITEMP-65)+IOFFSET) MOD 26 : PRINT CHR$(ITEMP+65); : ELSE PRINT CHR$(ITEMP); +230 NEXT I +240 PRINT +250 END diff --git a/Task/Caesar-cipher/Koka/caesar-cipher.koka b/Task/Caesar-cipher/Koka/caesar-cipher.koka new file mode 100644 index 0000000000..75887f40dc --- /dev/null +++ b/Task/Caesar-cipher/Koka/caesar-cipher.koka @@ -0,0 +1,21 @@ +fun encode(s : string, shift : int) + fun encode-char(c) + if c < 'A' || (c > 'Z' && c < 'a') || c > 'z' return c + val base = if c < 'Z' then (c - 'A').int else (c - 'a').int + val rot = (base + shift) % 26 + (rot.char + (if c < 'Z' then 'A' else 'a')) + s.map(encode-char) + +fun decode(s: string, shift: int) + s.encode(0 - shift) + +fun trip(s: string, shift: int) + s.encode(shift).decode(shift) + +fun main() + "HI".encode(2).println + "HI".encode(20).println + "HI".trip(10).println + val enc = "The quick brown fox jumped over the lazy dog".encode(11) + enc.println + enc.decode(11).println diff --git a/Task/Caesar-cipher/True-BASIC/caesar-cipher.basic b/Task/Caesar-cipher/True-BASIC/caesar-cipher.basic new file mode 100644 index 0000000000..506d9002d2 --- /dev/null +++ b/Task/Caesar-cipher/True-BASIC/caesar-cipher.basic @@ -0,0 +1,32 @@ +LET dec$ = "" +LET tipo$ = "cleartext " + +PRINT "If decrypting enter 'd' -- else press enter "; +INPUT dec$ +PRINT "Enter offset "; +INPUT llave + +IF dec$ = "d" THEN + LET llave = 26 - llave + LET tipo$ = "ciphertext " +END IF + +PRINT "Enter "; tipo$; +INPUT cadena$ + +LET cadena$ = UCASE$(cadena$) +LET longitud = LEN(cadena$) + +FOR i = 1 TO longitud + !LET iTemp = ASC(MID$(cadena$,i,1)) 'QBasic + LET itemp = ORD((cadena$)[i:i+1-1][1:1]) !'True BASIC + + IF iTemp > 64 AND iTemp < 91 THEN + !LET iTemp = ((iTemp - 65) + llave) MOD 26 'QBasic + LET iTemp = MOD(((iTemp - 65) + llave), 26) !'True BASIC + PRINT CHR$(iTemp + 65); + ELSE + PRINT CHR$(iTemp); + END IF +NEXT i +END diff --git a/Task/Calculating-the-value-of-e/Kotlin/calculating-the-value-of-e.kotlin b/Task/Calculating-the-value-of-e/Kotlin/calculating-the-value-of-e-1.kotlin similarity index 100% rename from Task/Calculating-the-value-of-e/Kotlin/calculating-the-value-of-e.kotlin rename to Task/Calculating-the-value-of-e/Kotlin/calculating-the-value-of-e-1.kotlin diff --git a/Task/Calculating-the-value-of-e/Kotlin/calculating-the-value-of-e-2.kotlin b/Task/Calculating-the-value-of-e/Kotlin/calculating-the-value-of-e-2.kotlin new file mode 100644 index 0000000000..947bdcd030 --- /dev/null +++ b/Task/Calculating-the-value-of-e/Kotlin/calculating-the-value-of-e-2.kotlin @@ -0,0 +1,7 @@ +fun main() { + val e = (1..17).runningFold(1L, Long::times) + .asReversed() // summing smaller values first improves accuracy + .sumOf { 1.0 / it } + println(e) + println(e == kotlin.math.E) +} diff --git a/Task/Calculating-the-value-of-e/Zig/calculating-the-value-of-e.zig b/Task/Calculating-the-value-of-e/Zig/calculating-the-value-of-e.zig index bcff75fb23..5cac61ef8f 100644 --- a/Task/Calculating-the-value-of-e/Zig/calculating-the-value-of-e.zig +++ b/Task/Calculating-the-value-of-e/Zig/calculating-the-value-of-e.zig @@ -1,8 +1,8 @@ const std = @import("std"); -const math = std.math; -const stdout = std.io.getStdOut().writer(); pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var n: u32 = 0; var state: u2 = 0; var p0: u64 = 0; @@ -30,17 +30,19 @@ pub fn main() !void { state = 1; }, } - var p2: u64 = undefined; - var q2: u64 = undefined; - if (@mulWithOverflow(u64, a, p1, &p2) or - @addWithOverflow(u64, p2, p0, &p2) or - @mulWithOverflow(u64, a, q1, &q2) or - @addWithOverflow(u64, q2, q0, &q2)) - { - break; - } - try stdout.print("e ~= {d:>19} / {d:>19} = ", .{p2, q2}); - try dec_print(stdout, p2, q2, 36); + const ov1 = @mulWithOverflow(a, p1); + if (ov1[1] != 0) break; + const ov2 = @addWithOverflow(ov1[0], p0); + if (ov2[1] != 0) break; + const ov3 = @mulWithOverflow(a, q1); + if (ov3[1] != 0) break; + const ov4 = @addWithOverflow(ov3[0], q0); + if (ov4[1] != 0) break; + const p2 = ov2[0]; + const q2 = ov4[0]; + + try stdout.print("e ~= {d:>19} / {d:>19} = ", .{ p2, q2 }); + try decPrint(stdout, p2, q2, 36); try stdout.writeByte('\n'); p0 = p1; p1 = p2; @@ -49,21 +51,21 @@ pub fn main() !void { } } -fn dec_print(ostream: anytype, num: u64, den: u64, prec: usize) !void { +fn decPrint(ostream: anytype, num: u64, den: u64, prec: usize) !void { // print out integer part. try ostream.print("{}.", .{num / den}); // arithmetic with the remainders is done with u128, as the // multiply by 10 could potentially overflow a u64. // - const m = @intCast(u128, den); + const m: u128 = @intCast(den); var r = @as(u128, num) % m; var dec: usize = 0; // decimal place we're in. while (dec < prec and r > 0) { const n = 10 * r; r = n % m; dec += 1; - const ch = @intCast(u8, n / m) + '0'; + const ch = @as(u8, @intCast(n / m)) + '0'; try ostream.writeByte(ch); } } diff --git a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena index 19b2fe6735..83b29c7efe 100644 --- a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena +++ b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena @@ -4,158 +4,158 @@ import system'calendar; import extensions; import extensions'routines; -const MonthNames = new string[]{"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER", - "NOVEMBER","DECEMBER"}; +const MonthNames = new string[]{"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"}; const DayNames = new string[]{"MO", "TU", "WE", "TH", "FR", "SA", "SU"}; class CalendarMonthPrinter { - Date theDate; - TextBuilder theLine; - int theMonth; - int theYear; - ref theRow; + Date _date; + TextBuilder _line; + int _month; + int _year; + Reference _row; - constructor(year, month) - { - theMonth := month; - theYear := year; - theLine := new TextBuilder(); - theRow := 0; - } + constructor(year, month) + { + _month := month; + _year := year; + _line := new TextBuilder(); + _row := 0; + } - writeTitle() - { - theRow.Value := 0; - theDate := Date.new(theYear, theMonth, 1); - DayNames.forEach:(name) - { theLine.print(" ",name) } - } + writeTitle() + { + _row.Value := 0; + _date := Date.new(_year, _month, 1); - writeLine() - { - theLine.clear(); + DayNames.forEach:(name) + { _line.print(" ",name) } + } - if (theDate.Month == theMonth) - { - var dw := theDate.DayOfWeek; + writeLine() + { + _line.clear(); - theLine.writeCopies(" ",theDate.DayOfWeek == 0 ? 6 : (theDate.DayOfWeek - 1)); + if (_date.Month == _month) + { + var dw := _date.DayOfWeek; - do - { - theLine.writePaddingLeft(theDate.Day.toPrintable(), $32, 3); + _line.writeCopies(" ",_date.DayOfWeek == 0 ? 6 : (_date.DayOfWeek - 1)); - theDate := theDate.addDays:1 - } - until(theDate.Month != theMonth || theDate.DayOfWeek == 1) - }; + do + { + _line.writePaddingLeft(_date.Day.toPrintable(), $32, 3); - int length := theLine.Length; - if (length < 21) - { theLine.writeCopies(" ", 21 - length) }; + _date := _date.addDays:1 + } + until(_date.Month != _month || _date.DayOfWeek == 1) + }; - theRow.append(1) - } + int length := _line.Length; + if (length < 21) + { _line.writeCopies(" ", 21 - length) }; - indexer() = new Indexer - { - bool Available = theRow < 7; + _row.append(1) + } - int Index - { - get() = theRow.Value; + indexer() = new Indexer + { + bool Available = _row < 7; - set(int index) - { - if (index <= theRow) - { self.writeTitle() }; + int Index + { + get() = _row.Value; - while (index > theRow) - { self.writeLine() } - } - } + set(int index) + { + if (index <= _row) + { self.writeTitle() }; - appendIndex(int index) - { - this self.Index := theRow.Value + index - } + while (index > _row) + { self.writeLine() } + } + } - get int Length() { ^ 7 } + appendIndex(int index) + { + this self.Index := _row.Value + index + } - get() = self; + get int Length() { ^ 7 } - set(o) { NotSupportedException.raise() } - }; + get Value() = self; - printTitleTo(output) - { - output.writePadding(MonthNames[theMonth - 1], $32, 21) - } + set Value(o) { NotSupportedException.raise() } + }; - printTo(output) - { - output.write(theLine.Value) - } + printTitleTo(output) + { + output.writePadding(MonthNames[_month - 1], $32, 21) + } + + printTo(output) + { + output.write(_line.Value) + } } class Calendar { - int theYear; - int theRowLength; + int _year; + int _rowLength; - constructor new(int year) - { - theYear := year; - theRowLength := 3 - } + constructor new(int year) + { + _year := year; + _rowLength := 3 + } - printTo(output) - { - output.writePadding("[SNOOPY]", $32, theRowLength * 25); - output.writeLine(); - output.writePadding(theYear.toPrintable(), $32, theRowLength * 25); - output.writeLine().writeLine(); + printTo(output) + { + output.writePadding("[SNOOPY]", $32, _rowLength * 25); + output.writeLine(); + output.writePadding(_year.toPrintable(), $32, _rowLength * 25); + output.writeLine().writeLine(); - var rowCount := 12 / theRowLength; - var months := Array.allocate(rowCount).populate:(i => - Array.allocate(theRowLength) + var rowCount := 12 / _rowLength; + var months := Array.allocate(rowCount).populate:(i => + Array.allocate(_rowLength) .populate:(j => - new CalendarMonthPrinter(theYear, i * theRowLength + j + 1))); + new CalendarMonthPrinter(_year, i * _rowLength + j + 1))); - months.forEach:(row) - { - var r := row; + months.forEach:(row) + { + var r := row; - row.forEach:(month) + row.forEach:(month) + { + month.printTitleTo:output; + + output.write:" " + }; + + output.writeLine(); + + ParallelEnumerator.new(row).forEach:(line) + { + line.forEach:(printer) { - month.printTitleTo:output; + printer.printTo:output; - output.write:" " + output.write:" " }; - output.writeLine(); - - ParallelEnumerator.new(row).forEach:(line) - { - line.forEach:(printer) - { - printer.printTo:output; - - output.write:" " - }; - - output.writeLine() - } - } - } + output.writeLine() + } + } + } } public program() { - var calender := Calendar.new(console.write:"ENTER THE YEAR:".readLine().toInt()); + var calender := Calendar.new(console.write:"ENTER THE YEAR:".readLine().toInt()); - calender.printTo:console; + calender.printTo:console; - console.readChar() + console.readChar() } diff --git a/Task/Calkin-Wilf-sequence/Maxima/calkin-wilf-sequence.maxima b/Task/Calkin-Wilf-sequence/Maxima/calkin-wilf-sequence.maxima new file mode 100644 index 0000000000..56c2a7934e --- /dev/null +++ b/Task/Calkin-Wilf-sequence/Maxima/calkin-wilf-sequence.maxima @@ -0,0 +1,25 @@ +/* The function fusc is related to Calkin-Wilf sequence */ +fusc(n):=block( + [k:n,a:1,b:0], + while k>0 do (if evenp(k) then (k:k/2,a:a+b) else (k:(k-1)/2,b:a+b)), + b)$ + +/* Calkin-Wilf function using fusc */ +calkin_wilf(n):=fusc(n)/fusc(n+1)$ + +/* Function that given a nonnegative rational returns its position in the Calkin-Wilf sequence */ +cf_bin(fracti):=block( + cf_list:cf(fracti), + cf_len:length(cf_list), + if oddp(cf_len) then cf_list:reverse(cf_list) else cf_list:reverse(append(at(cf_list,[cf_list[cf_len]=cf_list[cf_len]-1]),[1])), + makelist(lambda([x],if oddp(x) then makelist(1,j,1,cf_list[x]) else makelist(0,j,1,cf_list[x]))(i),i,1,length(cf_list)), + apply(append,%%), + apply("+",makelist(2^i,i,0,length(%%)-1)*reverse(%%)))$ + +/* Test cases */ +/* 20 first terms of the sequence */ +makelist(calkin_wilf(i),i,1,20); + +/* Position of 83116/51639 in Calkin-Wilf sequence */ +83116/51639$ +cf_bin(%); diff --git a/Task/Call-an-object-method/COBOL/call-an-object-method-1.cobol b/Task/Call-an-object-method/COBOL/call-an-object-method-1.cobol index e8eee82db7..a661f29ef1 100644 --- a/Task/Call-an-object-method/COBOL/call-an-object-method-1.cobol +++ b/Task/Call-an-object-method/COBOL/call-an-object-method-1.cobol @@ -1,7 +1,11 @@ -*> INVOKE -INVOKE FooClass "someMethod" RETURNING bar *> Factory object -INVOKE foo-instance "anotherMethod" RETURNING bar *> Instance object +*> INVOKE statements. +INVOKE my-class "some-method" *> Factory object + USING BY REFERENCE some-parameter + RETURNING foo +INVOKE my-instance "another-method" *> Instance object + USING BY REFERENCE some-parameter + RETURNING foo -*> Inline method invocation -MOVE FooClass::"someMethod" TO bar *> Factory object -MOVE foo-instance::"anotherMethod" TO bar *> Instance object +*> Inline method invocation. +MOVE my-class::"some-method"(some-parameter) TO foo *> Factory object +MOVE my-instance::"another-method"(some-parameter) TO foo *> Instance object diff --git a/Task/Call-an-object-method/COBOL/call-an-object-method-2.cobol b/Task/Call-an-object-method/COBOL/call-an-object-method-2.cobol index a4434322d6..a15053b585 100644 --- a/Task/Call-an-object-method/COBOL/call-an-object-method-2.cobol +++ b/Task/Call-an-object-method/COBOL/call-an-object-method-2.cobol @@ -1,3 +1,3 @@ -INVOKE foo-instance "FactoryObject" RETURNING foo-factory +INVOKE some-instance "FactoryObject" RETURNING foo-factory *> foo-factory can be treated like a normal object reference. INVOKE foo-factory "someMethod" diff --git a/Task/Cartesian-product-of-two-or-more-lists/Applesoft-BASIC/cartesian-product-of-two-or-more-lists.basic b/Task/Cartesian-product-of-two-or-more-lists/Applesoft-BASIC/cartesian-product-of-two-or-more-lists.basic new file mode 100644 index 0000000000..ce7e06a98c --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Applesoft-BASIC/cartesian-product-of-two-or-more-lists.basic @@ -0,0 +1,30 @@ +100 HOME : rem 10 CLS FOR Chipmunk Basic & GW-BASIC +110 DIM array(2,2) +120 array(1,1) = 1 : array(1,2) = 2 +130 array(2,1) = 3 : array(2,2) = 4 +140 GOSUB 190 +150 array(1,1) = 3 : array(1,2) = 4 +160 array(2,1) = 1 : array(2,2) = 2 +170 GOSUB 190 +180 END +190 rem SUB cartesian(list) +200 u1 = 2 : u2 = 2 +210 FOR i = 1 TO u1 +220 PRINT "{ "; +230 FOR j = 1 TO u2 +240 PRINT array(i,j); +250 IF j < u1 THEN PRINT ", "; +260 NEXT j +270 PRINT "}"; +280 IF i < u2 THEN PRINT " x "; +290 NEXT i +300 PRINT " = { "; +310 FOR i = 1 TO u1 +320 FOR j = 1 TO u2 +330 PRINT "{ "; array(1,i); ", "; array(2,j); "} "; +340 IF i < u2 THEN PRINT ", "; +350 IF i => u2 THEN IF j < u1 THEN PRINT ", "; +360 NEXT j +370 NEXT i +380 PRINT "}" +390 RETURN diff --git a/Task/Cartesian-product-of-two-or-more-lists/BASIC256/cartesian-product-of-two-or-more-lists.basic b/Task/Cartesian-product-of-two-or-more-lists/BASIC256/cartesian-product-of-two-or-more-lists.basic new file mode 100644 index 0000000000..d0dc247dec --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/BASIC256/cartesian-product-of-two-or-more-lists.basic @@ -0,0 +1,33 @@ +arraybase 1 +subroutine cartesian(list) + u1 = list[?][] + u2 = list[][?] + + for i = 1 to u1 + print "{"; + for j = 1 to u2 + print list[i,j]; + if j < u1 then print ", "; + next + print "}"; + if i < u2 then print " x "; + next i + print " = { "; + for i = 1 to u1 + for j = 1 to u2 + print "{"; list[1, i]; ", "; list[2, j]; "} "; + if i < u2 then + print ", "; + else + if j < u1 then print ", "; + end if + next j + next i + print "}" +end subroutine + +dim list1 = {{1,2},{3,4}} +dim list2 = {{3,4},{1,2}} +call cartesian(list1) +call cartesian(list2) +end diff --git a/Task/Cartesian-product-of-two-or-more-lists/Chipmunk-Basic/cartesian-product-of-two-or-more-lists.basic b/Task/Cartesian-product-of-two-or-more-lists/Chipmunk-Basic/cartesian-product-of-two-or-more-lists.basic new file mode 100644 index 0000000000..88cdee2143 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Chipmunk-Basic/cartesian-product-of-two-or-more-lists.basic @@ -0,0 +1,33 @@ +100 cls +110 dim array(2,2) +120 array(1,1) = 1 : array(1,2) = 2 +130 array(2,1) = 3 : array(2,2) = 4 +140 gosub 190 +150 array(1,1) = 3 : array(1,2) = 4 +160 array(2,1) = 1 : array(2,2) = 2 +170 gosub 190 +180 end +190 rem sub cartesian(list) +200 u1 = 2 : u2 = 2 +210 for i = 1 to u1 +220 print "{ "; +230 for j = 1 to u2 +240 print array(i,j); +250 if j < u1 then print ", "; +260 next j +270 print "}"; +280 if i < u2 then print " x "; +290 next i +300 print " = { "; +310 for i = 1 to u1 +320 for j = 1 to u2 +330 print "{ ";array(1,i);", ";array(2,j);"} "; +340 if i < u2 then +350 print ", "; +360 else +370 if j < u1 then print ", "; +380 endif +390 next j +400 next i +410 print "}" +420 return diff --git a/Task/Cartesian-product-of-two-or-more-lists/GW-BASIC/cartesian-product-of-two-or-more-lists.basic b/Task/Cartesian-product-of-two-or-more-lists/GW-BASIC/cartesian-product-of-two-or-more-lists.basic new file mode 100644 index 0000000000..e4758b7b93 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/GW-BASIC/cartesian-product-of-two-or-more-lists.basic @@ -0,0 +1,30 @@ +100 CLS +110 DIM ARR(2,2) +120 ARR(1,1) = (1) : ARR(1,2) = (2) +130 ARR(2,1) = (3) : ARR(2,2) = (4) +140 GOSUB 190 +150 ARR(1,1) = 3 : ARR(1,2) = 4 +160 ARR(2,1) = 1 : ARR(2,2) = 2 +170 GOSUB 190 +180 END +190 REM SUB cartesian(list) +200 U1 = 2 : U2 = 2 +210 FOR I = 1 TO U1 +220 PRINT "{"; +230 FOR J = 1 TO U2 +240 PRINT ARR(I,J); +250 IF J < U1 THEN PRINT ","; +260 NEXT J +270 PRINT "}"; +280 IF I < U2 THEN PRINT " x "; +290 NEXT I +300 PRINT " = {"; +310 FOR I = 1 TO U1 +320 FOR J = 1 TO U2 +330 PRINT "{"; ARR(1,I); ","; ARR(2,J); "}"; +340 IF I < U2 THEN PRINT ", "; +350 IF I => U2 THEN IF J < U1 THEN PRINT ","; +360 NEXT J +370 NEXT I +380 PRINT "}" +390 RETURN diff --git a/Task/Cartesian-product-of-two-or-more-lists/Gambas/cartesian-product-of-two-or-more-lists.gambas b/Task/Cartesian-product-of-two-or-more-lists/Gambas/cartesian-product-of-two-or-more-lists.gambas new file mode 100644 index 0000000000..9440d271b4 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Gambas/cartesian-product-of-two-or-more-lists.gambas @@ -0,0 +1,46 @@ +Public array[2, 2] As Integer + +Public Sub Main() + + array[0, 0] = 1 + array[0, 1] = 2 + array[1, 0] = 3 + array[1, 1] = 4 + cartesian(array) + array[0, 0] = 3 + array[0, 1] = 4 + array[1, 0] = 1 + array[1, 1] = 2 + cartesian(array) + +End + +Sub cartesian(arr As Integer[]) + + Dim u1 As Integer = arr.Max - 2 + Dim u2 As Integer = arr.Max - 2 + Dim i As Integer, j As Integer + + For i = 0 To u1 + Print "{"; + For j = 0 To u2 + Print arr[i, j]; + If j < u1 Then Print ","; + Next + Print "}"; + If i < u2 Then Print " x "; + Next + Print " = {"; + For i = 0 To u1 + For j = 0 To u2 + Print "{"; arr[0, i]; ","; arr[1, j]; "}"; + If i < u2 Then + Print ", "; + Else + If j < u1 Then Print ", "; + End If + Next + Next + Print "}" + +End Sub diff --git a/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-1.maxima b/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-1.maxima new file mode 100644 index 0000000000..bb6e137ae3 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-1.maxima @@ -0,0 +1,8 @@ +cartesian_product({1,2},{3,4}); +/* {[1,3],[1,4],[2,3],[2,4]} */ +cartesian_product({3,4},{1,2}); +/* {[3,1],[3,2],[4,1],[4,2]} */ +cartesian_product({1,2},{}); +/* {} */ +cartesian_product({},{1,2}); +/* {} */ diff --git a/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-2.maxima b/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-2.maxima new file mode 100644 index 0000000000..1ad69da204 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-2.maxima @@ -0,0 +1,8 @@ +cartesian_product_list([1,2],[3,4]); +/* [[1,3],[1,4],[2,3],[2,4]] */ +cartesian_product_list([3,4],[1,2]); +/* [[3,1],[3,2],[4,1],[4,2]] */ +cartesian_product_list([1,2],[]); +/* [] */ +cartesian_product_list([],[1,2]); +/* [] */ diff --git a/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-3.maxima b/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-3.maxima new file mode 100644 index 0000000000..ac9d9ec0e1 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-3.maxima @@ -0,0 +1,8 @@ +create_list([i,j],i,[1,2],j,[3,4]); +/* [[1,3],[1,4],[2,3],[2,4]] */ +create_list([i,j],i,[3,4],j,[1,2]); +/* [[3,1],[3,2],[4,1],[4,2]] */ +create_list([i,j],i,[1,2],j,[]); +/* [] */ +create_list([i,j],i,[],j,[1,2]); +/* [] */ diff --git a/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-4.maxima b/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-4.maxima new file mode 100644 index 0000000000..fba7009454 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Maxima/cartesian-product-of-two-or-more-lists-4.maxima @@ -0,0 +1,14 @@ +my_cartesian(lst1,lst2):=create_list([i,j],i,lst1,j,lst2); +n_ary_cartesian(singleargument):=block(lreduce(my_cartesian,singleargument),map(flatten,%%)); + +[[1776,1789],[7,12],[4,14,23],[0,1]]$ +n_ary_cartesian(%); +/* [[1776,7,4,0],[1776,7,4,1],[1776,7,14,0],[1776,7,14,1],[1776,7,23,0],[1776,7,23,1],[1776,12,4,0],[1776,12,4,1],[1776,12,14,0],[1776,12,14,1],[1776,12,23,0],[1776,12,23,1],[1789,7,4,0],[1789,7,4,1],[1789,7,14,0],[1789,7,14,1],[1789,7,23,0],[1789,7,23,1],[1789,12,4,0],[1789,12,4,1],[1789,12,14,0],[1789,12,14,1],[1789,12,23,0],[1789,12,23,1]] */ + +[[1,2,3],[30],[500,100]]$ +n_ary_cartesian(%); +/* [[1,30,500],[1,30,100],[2,30,500],[2,30,100],[3,30,500],[3,30,100]] */ + +[[1,2,3],[],[500,100]]$ +n_ary_cartesian(%); +/* [] */ diff --git a/Task/Cartesian-product-of-two-or-more-lists/QBasic/cartesian-product-of-two-or-more-lists.basic b/Task/Cartesian-product-of-two-or-more-lists/QBasic/cartesian-product-of-two-or-more-lists.basic new file mode 100644 index 0000000000..39f6e02a0a --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/QBasic/cartesian-product-of-two-or-more-lists.basic @@ -0,0 +1,36 @@ +DECLARE SUB cartesian (arr!()) + +CLS +DIM array(2, 2) +array(1, 1) = 1: array(1, 2) = 2 +array(2, 1) = 3: array(2, 2) = 4 +CALL cartesian(array()) +array(1, 1) = 3: array(1, 2) = 4 +array(2, 1) = 1: array(2, 2) = 2 +CALL cartesian(array()) +END + +SUB cartesian (arr()) +u1 = 2: u2 = 2 +FOR i = 1 TO u1 + PRINT "{"; + FOR j = 1 TO u2 + PRINT arr(i, j); + IF j < u1 THEN PRINT ","; + NEXT j + PRINT "}"; + IF i < u2 THEN PRINT " x "; +NEXT i +PRINT " = {"; +FOR i = 1 TO u1 + FOR j = 1 TO u2 + PRINT "{"; arr(1, i); ","; arr(2, j); "}"; + IF i < u2 THEN + PRINT ", "; + ELSE + IF j < u1 THEN PRINT ", "; + END IF + NEXT j +NEXT i +PRINT "}" +END SUB diff --git a/Task/Cartesian-product-of-two-or-more-lists/Run-BASIC/cartesian-product-of-two-or-more-lists.basic b/Task/Cartesian-product-of-two-or-more-lists/Run-BASIC/cartesian-product-of-two-or-more-lists.basic new file mode 100644 index 0000000000..43093c62c7 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/Run-BASIC/cartesian-product-of-two-or-more-lists.basic @@ -0,0 +1,34 @@ +cls +dim array(2,2) +array(1,1) = 1 : array(1,2) = 2 +array(2,1) = 3 : array(2,2) = 4 +gosub [cartesian] +array(1,1) = 3 : array(1,2) = 4 +array(2,1) = 1 : array(2,2) = 2 +gosub [cartesian] +end + +[cartesian] +u1 = 2 : u2 = 2 +for i = 1 to u1 + print "{"; + for j = 1 to u2 + print array(i,j); + if j < u1 then print ","; + next j + print "}"; + if i < u2 then print " x "; +next i +print " = {"; +for i = 1 to u1 + for j = 1 to u2 + print "{"; array(1,i); ","; array(2,j); "}"; + if i < u2 then + print ","; + else + if j < u1 then print ","; + end if + next j +next i +print "}" +return diff --git a/Task/Chaocipher/BASIC/chaocipher.basic b/Task/Chaocipher/BASIC/chaocipher.basic new file mode 100644 index 0000000000..6b072d9972 --- /dev/null +++ b/Task/Chaocipher/BASIC/chaocipher.basic @@ -0,0 +1,137 @@ +' Caocipher Example +' Rosetta Code +' This code was made in Power Basic 3.5 for DOS + +CLS + +' Left Alphabet +Function AlphaLeft(ct as String, pt as String, CharPos as Integer) as String + + Dim tStr as String: tStr=ct + + ' 1. Shift the entire left alphabet cyclically so the ciphertext letter + ' just enciphered is positioned at the zenith (i.e., position 1). + tStr=Right$(ct, Len(ct)-CharPos+1)+Left$(ct, CharPos-1) + + ' 2. Extract the letter found at position zenith+1 (i.e., the letter to + ' the right of the zenith), taking it out of the alphabet, temporarily + ' leaving an unfilled "hole" + + Dim Hole as String: Hole=Mid$(tStr, 2, 1): Mid$(tStr, 2, 1)=" " + + ' 3. Shift all letters in positions zenith+2 up to, and including, the + ' nadir (zenith+13), moving them one position to the left + + tStr=Left$(tStr, 1)+Mid$(tStr, 3, 12)+" "+Right$(tStr, 12) + + ' 4. Insert the just-extracted letter into the nadir position + ' (i.e., zenith+13) + + Mid$(tStr, 14, 1)=Hole + + AlphaLeft=tStr +End Function + +' Right Alphabet +Function AlphaRight(ct as String, pt as String, CharPos as Integer) as String + + Dim tStr as String: tStr=pt + + ' 1. Shift the entire right alphabet cyclically so the plaintext letter + ' just enciphered is positioned at the zenith. + + tStr=Right$(tStr, Len(tStr)-CharPos+1)+Left$(tStr, CharPos-1) + + ' 2. Now shift the entire alphabet one more position to the left (i.e., + ' the leftmost letter moves cyclically to the far right), moving a new + ' letter into the zenith position. + + tStr=Right$(tStr, 25)+Left$(tStr, 1) + + ' 3. Extract the letter at position zenith+2, taking it out of the + ' alphabet, temporarily leaving an unfilled "hole". + + Dim Hole as String: Hole=Mid$(tStr, 3, 1): Mid$(tStr, 3, 1)=" ": + + ' 4. Shift all letters beginning with zenith+3 up to, and including, the + ' nadir (zenith+13), moving them one position to the left. + + tStr=Left$(tStr, 2)+Mid$(tStr, 4, 11)+" "+Right$(tStr, 12) + + ' 5. Insert the just-extracted letter into the nadir position (zenith+13) + + Mid$(tStr, 14, 1)=Hole + + AlphaRight=tStr +End Function + +Function Encode(Text as String, ct as String, pt as String) as String + Dim t as Integer + Dim tStr as String: tStr="" + + For t=1 to Len(Text) + Dim Char as String: Char=Mid$(Text, t, 1) + Dim CharPos as Integer: CharPos=Instr(pt, Char) + + ct=AlphaLeft(ct, pt, CharPos) + pt=AlphaRight(ct, pt, CharPos) + + tStr=tStr+Left$(ct, 1) + Next + + Encode=tStr +End Function + +' Deciphering a Chaocipher-encrypted message is identical to the steps used +' for enciphering. The sole difference is that the decipherer locates the +' known ciphertext letter in the left (ct) alphabet, with the plaintext +' letter being the corresponding letter in the right (pt) alphabet +' +' Alphabet permuting is identical in enciphering and deciphering + +Function Decode(Text as String, ct as String, pt as String) as String + Dim t as Integer + Dim tStr as String: tStr="" + + For t=1 to Len(Text) + Dim Char as String: Char=Mid$(Text, t, 1) + Dim CharPos as Integer: CharPos=Instr(ct, Char) + + ct=AlphaLeft(ct, pt, CharPos) + pt=AlphaRight(ct, pt, CharPos) + + tStr=tStr+Right$(pt, 1) + Next + + Decode=tStr +End Function + +' Start of Main Code + +' LEFT (Cipher Text): HXUCZVAMDSLKPEFJRIGTWOBNYQ +Dim tLeft as String: tLeft="HXUCZVAMDSLKPEFJRIGTWOBNYQ" + +' RIGHT (Plain Text): PTLNBQDEOYSFAVZKGJRIHWXUMC +Dim tRight as String: tRight="PTLNBQDEOYSFAVZKGJRIHWXUMC" + +' Cipher Message (Used to verify a good encoding) +Dim cText as String: cText="OAHQHCNYNXTSZJRRHJBYHQKSOUJY" + +' Plain Text Message +Dim pText as String: pText="WELLDONEISBETTERTHANWELLSAID" +Print " Plain Text: "; pText: Print + +Dim ctLeft as String: ctLeft=tLeft +Dim ptRight as String: ptRight=tRight + +' Final Cipher Text +Dim eText as String: eText=Encode(pText, ctLeft, ptRight) +Print " Cipher Text: "; eText: Print + +If eText=cText then Print "Successful" else Print "Failed" + +ctLeft=tLeft: ptRight=tRight +Dim dText as String: dText=Decode(eText, ctLeft, ptRight) +Print: Print " Plain Text: "; dText: Print + +If dText=pText then Print "Successful" else Print "Failed" diff --git a/Task/Chaocipher/FutureBasic/chaocipher.basic b/Task/Chaocipher/FutureBasic/chaocipher.basic new file mode 100644 index 0000000000..567293f7cd --- /dev/null +++ b/Task/Chaocipher/FutureBasic/chaocipher.basic @@ -0,0 +1,47 @@ +begin enum + _encrypt + _decrypt +end enum + +local fn chaocipher(orig as str255, action as byte, show as bool) as str255 + str255 leftStr, rightStr, out + short i, index + leftStr = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" + rightStr = "PTLNBQDEOYSFAVZKGJRIHWXUMC" + orig = ucase$(orig) + out[0] = orig[0] + + if show then print:print,"The left and right alphabets during encryption are:":print + + for i = 1 to orig[0] + if show then print ,leftStr,,rightStr + if action == _encrypt + index = instr$(0, rightStr, mid$(orig, i, 1)) + out[i] = leftStr[index] + else + index = instr$(0, leftStr, mid$(orig, i, 1)) + out[i] = rightStr[index] + end if + + //leftStr permutation + leftStr = mid$(leftStr, index) + left$(leftStr, index-1) + leftStr = left$(leftStr, 1) + mid$(leftStr, 3, 12) + mid$(leftStr, 2, 1) + mid$(leftStr, 15) + + //rightStr permutation + rightStr = mid$(rightStr, index+1) + left$(rightStr, index-1) + mid$(rightStr, index, 1) + rightStr = left$(rightStr, 2) + mid$(rightStr, 4, 11) + mid$(rightStr, 3, 1) + mid$(rightStr, 15) + next + +end fn = out + + +str255 original, encrypted, decrypted +original = "WellDoneIsBetterThanWellSaid" + +window 1, @"Chaocipher", ( 0, 0, 475, 550 ) +print : print ,"The original text is: """; original; """" +encrypted = fn chaocipher(original, _encrypt, yes) +print : print ,"The encrypted text is: """; encrypted; """" +decrypted = fn chaocipher(encrypted, _decrypt, no) +print : print ,"The decrypted text is: """; decrypted; """" +handleevents diff --git a/Task/Chaos-game/FutureBasic/chaos-game.basic b/Task/Chaos-game/FutureBasic/chaos-game.basic new file mode 100644 index 0000000000..d864811fed --- /dev/null +++ b/Task/Chaos-game/FutureBasic/chaos-game.basic @@ -0,0 +1,27 @@ +void local fn DoIt + long w = 460, h = 400, i, x = rnd(w), y = rnd(h) + for i = 1 to 50000 + select ( rnd(3)-1 ) + case 1 + x = w/2+(w/2-x)/2 + y = h-(h-y)/2 + pen ,fn ColorRed + case 2 + x = w-(w-x)/2 + y = y/2 + pen ,fn ColorGreen + case else + x = x/2 + y = y/2 + pen ,fn ColorBlue + end select + line x-0.5,y-0.5,x+0.5,y+0.5 + next +end fn + +window 1, @"Chaos Game", (0,0,460,400) +WindowSetBackgroundColor( 1, fn ColorWhite ) + +fn DoIt + +HandleEvents diff --git a/Task/Chinese-remainder-theorem/Maxima/chinese-remainder-theorem.maxima b/Task/Chinese-remainder-theorem/Maxima/chinese-remainder-theorem.maxima new file mode 100644 index 0000000000..49abdab856 --- /dev/null +++ b/Task/Chinese-remainder-theorem/Maxima/chinese-remainder-theorem.maxima @@ -0,0 +1,17 @@ +/* Function that checks pairwise coprimality */ +check_pwc(lst):=block( +sublist(cartesian_product_list(makelist(i,i,length(lst)),makelist(i,i,length(lst))),lambda([x],x[1]#x[2])), + makelist([lst[%%[i][1]],lst[%%[i][2]]],i,length(%%)), + makelist(apply('gcd,%%[i]),i,length(%%)), + if length(unique(%%))=1 and first(unique(%%))=1 then true)$ + +/* Chinese remainder function */ +c_remainder(A,N):=if check_pwc(N)=false then "chinese remainder theorem not applicable" else block( + cn:apply("*",N), + makelist(gcdex(cn/N[i],N[i]),i,1,length(N)), + makelist(A[i]*%%[i][1]*cn/N[i],i,1,length(N)), + apply("+",%%), + mod(%%,cn)); +Alis:[2,3,2]$ +Nlis:[3,5,7]$ +c_remainder(Alis,Nlis); diff --git a/Task/Chowla-numbers/FutureBasic/chowla-numbers.basic b/Task/Chowla-numbers/FutureBasic/chowla-numbers.basic new file mode 100644 index 0000000000..426b5f4722 --- /dev/null +++ b/Task/Chowla-numbers/FutureBasic/chowla-numbers.basic @@ -0,0 +1,46 @@ +local fn Chowla( n as NSUInteger ) as NSUInteger + NSUInteger i, j, r = 0 + + i = 2 + while ( i * i <= n ) + j = n / i + if ( n mod i == 0 ) + r += i + if ( i != j ) + r += j + end if + end if + i++ + wend +end fn = r + +local fn DoIt + NSUInteger n, count = 0, power = 100, limit, k, kk, p = 0 + + for n = 1 to 37 + printf @"chowla(%u) = %u", n, fn Chowla( n ) + next + + for n = 2 to 10000000 + if ( fn Chowla(n) == 0 ) then count ++ + if ( n mod power == 0 ) then printf @"There are %u primes < %-7u", count, power : power *= 10 + next + + count = 0 + limit = 350000000 + k = 2 : kk = 3 + do + p = k * kk + if ( fn Chowla( p ) == p - 1 ) + printf @"%9u is a perfect number", p + count++ + end if + k = kk + 1 + kk = kk + k + until ( p > limit ) + printf @"There are %u perfect numbers < %u", count, limit +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Circular-primes/C++/circular-primes.cpp b/Task/Circular-primes/C++/circular-primes.cpp index d63248712b..296c1fdc89 100644 --- a/Task/Circular-primes/C++/circular-primes.cpp +++ b/Task/Circular-primes/C++/circular-primes.cpp @@ -1,7 +1,6 @@ #include #include #include -#include #include typedef mpz_class integer; @@ -10,16 +9,10 @@ bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); } -std::string to_string(const integer& n) { - std::ostringstream out; - out << n; - return out.str(); -} - bool is_circular_prime(const integer& p) { if (!is_prime(p)) return false; - std::string str(to_string(p)); + std::string str = p.get_str(); for (size_t i = 0, n = str.size(); i + 1 < n; ++i) { std::rotate(str.begin(), str.begin() + 1, str.end()); integer p2(str, 10); @@ -63,7 +56,7 @@ int main() { std::cout << '\n'; std::cout << "Next 4 circular primes:\n"; p = next_repunit(p); - std::string str(to_string(p)); + std::string str = p.get_str(); int digits = str.size(); for (int count = 0; count < 4; ) { if (is_prime(p, 15)) { diff --git a/Task/Circular-primes/FutureBasic/circular-primes.basic b/Task/Circular-primes/FutureBasic/circular-primes.basic new file mode 100644 index 0000000000..8e0a9cb244 --- /dev/null +++ b/Task/Circular-primes/FutureBasic/circular-primes.basic @@ -0,0 +1,67 @@ +begin globals +_last1 = 7 +CFTimeInterval t +byte n(_last1 +1) //array of digits +uint64 list(20), p10 = 1 +short count, digits, first1 = _last1 +n(_last1) = 2 //First number to check +end globals + +local fn convertToNumber as uint64 + short i = first1 + uint64 nr = n(i) + while i < _last1 + i++ : nr = nr * 10 + n(i) + wend +end fn = nr + +void local fn increment( dgt as short ) + select n(dgt) + case 1, 7, 5 : n(dgt) += 2 + case 3 : if digits then n(dgt) = 7 else n(dgt) = 5 + case 9 : n(dgt) = 1 + if dgt == first1 then first1-- : digits++ : p10 *= 10 + fn increment( dgt -1 ) + case else : n(dgt)++ + end select +end fn + +local fn isPrime( v as uint64 ) as bool + if v < 4 then exit fn = yes + if v mod 3 == 0 then exit fn = no + uint64 f = 5 + while f*f <= v + if v mod f == 0 then exit fn = no + f += 2 + if v mod f == 0 then exit fn = no + f += 4 + wend +end fn = yes + +void local fn circularPrimes + uint64 num, nr + short r + while ( count < 19 ) + num = fn convertToNumber + if fn isPrime( num ) + nr = num + for r = 1 to digits + nr = 10 * ( nr mod p10 ) + ( nr / p10 ) //Rotate + if nr < num then break //Rotation of lower number + if fn isPrime( nr ) == no then break //Not prime + next + if r > digits then list( count ) = num : count++ + end if + fn increment( _last1 ) + wend +end fn + +window 1, @"Circular Primes in FutureBasic", (0, 0, 280, 320) +t = fn CACurrentMediaTime +fn circularPrimes +t = fn CACurrentMediaTime - t +for count = 0 to 18 + printf @"%22u",list(count) +next +printf @"\n Compute time: %.3f ms", t * 1000 +handleevents diff --git a/Task/Classes/Elena/classes.elena b/Task/Classes/Elena/classes.elena index e3398f782e..4faedc117f 100644 --- a/Task/Classes/Elena/classes.elena +++ b/Task/Classes/Elena/classes.elena @@ -2,7 +2,7 @@ import extensions; class MyClass { - prop int Variable; + int Variable : prop; someMethod() { diff --git a/Task/Closures-Value-capture/Elena/closures-value-capture.elena b/Task/Closures-Value-capture/Elena/closures-value-capture.elena index f4c976d396..374171bdfd 100644 --- a/Task/Closures-Value-capture/Elena/closures-value-capture.elena +++ b/Task/Closures-Value-capture/Elena/closures-value-capture.elena @@ -3,7 +3,7 @@ import extensions; public program() { - var functions := Array.allocate(10).populate:(int i => {^ i * i} ); + var functions := Array.allocate(10).populate:(int i => { ^ i * i} ); functions.forEach:(func) { console.printLine(func()) } } diff --git a/Task/Color-wheel/Plain-English/color-wheel.plain b/Task/Color-wheel/Plain-English/color-wheel.plain new file mode 100644 index 0000000000..0ff3cb7dae --- /dev/null +++ b/Task/Color-wheel/Plain-English/color-wheel.plain @@ -0,0 +1,18 @@ +To draw the color wheel: + Start with the red color. + Turn right 80 points. + Loop. + If the user clicks on the screen, break. + Move to the center of the screen. + Draw a line 2 inches long. + Refresh the screen. + Change the current hue by 10 points. + Turn right 10 points. + Add 1 to a count. + If the count is 384, break. \ Plain English uses a circle divided into 384 degrees + Repeat. + Start in the middle of the screen facing north minus 80 points. + Use medium-sized letters. + Write "RED......YELLOW.....GREEN......CYAN......BLUE.....MAGENTA......" with the white pen 2-1/4 inches from the screen's center. + Refresh the screen. + Shut down. diff --git a/Task/Compiler-syntax-analyzer/ALGOL-W/compiler-syntax-analyzer.alg b/Task/Compiler-syntax-analyzer/ALGOL-W/compiler-syntax-analyzer.alg index 7377c5fde0..bd0a358f99 100644 --- a/Task/Compiler-syntax-analyzer/ALGOL-W/compiler-syntax-analyzer.alg +++ b/Task/Compiler-syntax-analyzer/ALGOL-W/compiler-syntax-analyzer.alg @@ -296,7 +296,10 @@ begin % syntax analyser % stmtNode := null; while begin if tkType = tString then begin - stmtNode := opNode( nSequence, stmtNode, opNode( nPrts, operandNode( nString, tkIntegerValue ), null ) ); + stmtNode := opNode( nSequence + , stmtNode + , opNode( nPrts, operandNode( nString, tkIntegerValue ), null ) + ); readToken end else stmtNode := opNode( nSequence, stmtNode, opNode( nPrti, parseExpr( 0 ), null ) ); @@ -325,23 +328,26 @@ begin % syntax analyser % reference(node) procedure parseStatementList ( integer value terminator ) ; begin reference(node) listNode; listNode := null; - while tkType not = terminator and tkType not = tEnd_of_input do listNode := opNode( nSequence, listNode, parseStatement ); + while tkType not = terminator + and tkType not = tEnd_of_input do listNode := opNode( nSequence, listNode, parseStatement ); listNode end parseStatementList ; - nIdentifier := 1; ndName( nIdentifier ) := "Identifier"; nString := 2; ndName( nString ) := "String"; - nInteger := 3; ndName( nInteger ) := "Integer"; nSequence := 4; ndName( nSequence ) := "Sequence"; - nIf := 5; ndName( nIf ) := "If"; nPrtc := 6; ndName( nPrtc ) := "Prtc"; - nPrts := 7; ndName( nPrts ) := "Prts"; nPrti := 8; ndName( nPrti ) := "Prti"; - nWhile := 9; ndName( nWhile ) := "While"; nAssign := 10; ndName( nAssign ) := "Assign"; - nNegate := 11; ndName( nNegate ) := "Negate"; nNot := 12; ndName( nNot ) := "Not"; - nMultiply := 13; ndName( nMultiply ) := "Multiply"; nDivide := 14; ndName( nDivide ) := "Divide"; - nMod := 15; ndName( nMod ) := "Mod"; nAdd := 16; ndName( nAdd ) := "Add"; - nSubtract := 17; ndName( nSubtract ) := "Subtract"; nLess := 18; ndName( nLess ) := "Less"; - nLessEqual := 19; ndName( nLessEqual ) := "LessEqual" ; nGreater := 20; ndName( nGreater ) := "Greater"; - nGreaterEqual := 21; ndName( nGreaterEqual ) := "GreaterEqual"; nEqual := 22; ndName( nEqual ) := "Equal"; - nNotEqual := 23; ndName( nNotEqual ) := "NotEqual"; nAnd := 24; ndName( nAnd ) := "And"; - nOr := 25; ndName( nOr ) := "Or"; + % sets a node code and name % + procedure setNode ( integer result nd; integer value ndCode; string(14) value name ) ; + begin nd := ndCode; ndName( ndCode ) := name end; + + setNode( nIdentifier, 1, "Identifier" ); setNode( nString, 2, "String" ); + setNode( nInteger, 3, "Integer" ); setNode( nSequence, 4, "Sequence" ); setNode( nIf, 5, "If" ); + setNode( nPrtc, 6, "Prtc" ); setNode( nPrts, 7, "Prts" ); + setNode( nPrti, 8, "Prti" ); setNode( nWhile, 9, "While" ); + setNode( nAssign, 10, "Assign" ); setNode( nNegate, 11, "Negate" ); setNode( nNot, 12, "Not" ); + setNode( nMultiply, 13, "Multiply" ); setNode( nDivide, 14, "Divide" ); setNode( nMod, 15, "Mod" ); + setNode( nAdd, 16, "Add" ); setNode( nSubtract, 17, "Subtract" ); + setNode( nLess, 18, "Less" ); setNode( nLessEqual, 19, "LessEqual" ); + setNode( nGreater, 20, "Greater" ); + setNode( nGreaterEqual, 21, "GreaterEqual" ); setNode( nEqual, 22, "Equal" ); + setNode( nNotEqual, 23, "NotEqual" ); setNode( nAnd, 24, "And" ); setNode( nOr, 25, "Or" ); tOp_multiply := 1; tkName( tOp_multiply ) := "Op_multiply"; tkPrec( tOp_multiply ) := 5; tOp_divide := 2; tkName( tOp_divide ) := "Op_divide"; tkPrec( tOp_divide ) := 5; tOp_mod := 3; tkName( tOp_mod ) := "Op_mod"; tkPrec( tOp_mod ) := 5; @@ -377,7 +383,8 @@ begin % syntax analyser % for tkPos := 1 until MAX_TOKEN_TYPE do tkNode( tkPos ) := - tkPos; tkNode( tOp_multiply ) := nMultiply; tkNode( tOp_divide ) := nDivide; tkNode( tOp_mod ) := nMod; tkNode( tOp_add ) := nAdd; tkNode( tOp_subtract ) := nSubtract; tkNode( tOp_less ) := nLess; - tkNode( tOp_lessequal ) := nLessEqual; tkNode( tOp_greater ) := nGreater; tkNode( tOp_greaterequal ) := nGreaterEqual; + tkNode( tOp_lessequal ) := nLessEqual; tkNode( tOp_greater ) := nGreater; + tkNode( tOp_greaterequal ) := nGreaterEqual; tkNode( tOp_equal ) := nEqual; tkNode( tOp_notequal ) := nNotEqual; tkNode( tOp_not ) := nNot; tkNode( tOp_and ) := nAnd; tkNode( tOp_or ) := nOr; stList := idList := null; diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C++/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.cpp b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C++/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.cpp new file mode 100644 index 0000000000..dd1e4342a4 --- /dev/null +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C++/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include + +std::vector primes; + +void sieve_primes(const uint32_t& limit) { + std::vector marked_prime(limit + 1, true); + + for ( uint32_t p = 2; p * p <= limit; ++p ) { + if ( marked_prime[p] ) { + for ( uint32_t i = p * p; i <= limit; i += p ) { + marked_prime[i] = false; + } + } + } + + for ( uint32_t p = 2; p <= limit; ++p ) { + if ( marked_prime[p] ) { + primes.emplace_back(p); + } + } +} + +bool is_substring(const uint32_t& k, const uint32_t& factor) { + const std::string string_k = std::to_string(k); + const std::string string_factor = std::to_string(factor); + return string_k.find(string_factor) != std::string::npos; +} + +int main() { + sieve_primes(30'000'000); + + std::unordered_set distinct_factors; + std::vector result; + uint32_t k = 11 * 11; + + while ( result.size() < 10 ) { + while ( k % 3 == 0 || k % 5 == 0 || k % 7 == 0 ) { + k += 2; + } + + distinct_factors.clear(); + uint32_t copy_k = k; + uint32_t index = 4; + + while ( copy_k > 1 ) { + while ( copy_k % primes[index] == 0 ) { + distinct_factors.insert(primes[index]); + copy_k /= primes[index]; + } + index += 1; + } + + if ( distinct_factors.size() > 1 ) { + if ( std::all_of(distinct_factors.begin(), distinct_factors.end(), + [&k](uint32_t factor) { return is_substring(k, factor); }) ) { + result.emplace_back(k); + } + } + + k += 2; + } + + for ( uint64_t i = 0; i < result.size(); ++i ) { + std::cout << result[i] << " "; + } + std::cout << std::endl; +} diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.java b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.java index a7399b3eae..4eeda2f25e 100644 --- a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.java +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.java @@ -30,7 +30,7 @@ public final class CompositeNumbersK { } private static List primeFactors(int aK) { - ArrayList result = new ArrayList(); + List result = new ArrayList(); if ( aK <= 1 ) { return result; } @@ -41,7 +41,7 @@ public final class CompositeNumbersK { return result; } - int divisor = pollardsRho(bigK).intValueExact(); + final int divisor = pollardsRho(bigK).intValueExact(); result.addAll(primeFactors(divisor)); result.addAll(primeFactors(aK / divisor)); Collections.sort(result); diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Scala/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.scala b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Scala/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.scala new file mode 100644 index 0000000000..a6977c0cf2 --- /dev/null +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Scala/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.scala @@ -0,0 +1,25 @@ +def isComposite(num: Int): Boolean = { + val numStr = num.toString + def iter(n: Int, start: Int): Boolean = { + val limit = math.sqrt(n).floor.toInt + (start to limit by 2).dropWhile(n % _ > 0).headOption match { + case Some(v) if v < 10 => false + case Some(v) => + if (v == start || numStr.contains(v.toString)) iter(n / v, v) + else false + case None => n < num && numStr.contains(n.toString) + } + } + iter(num, 3) +} + +def composites = Iterator.from(121, 2).filter(isComposite(_)) + +@main def main = { + val start = System.currentTimeMillis + composites.take(20) + .grouped(10) + .foreach(grp => println(grp.map("%8d".format(_)).mkString(" "))) + val time = System.currentTimeMillis - start + println(s"time elapsed: $time ms") +} diff --git a/Task/Compound-data-type/COBOL/compound-data-type.cobol b/Task/Compound-data-type/COBOL/compound-data-type.cobol index b6511042f2..d95947f535 100644 --- a/Task/Compound-data-type/COBOL/compound-data-type.cobol +++ b/Task/Compound-data-type/COBOL/compound-data-type.cobol @@ -1,3 +1,5 @@ -01 Point. - 05 x pic 9(3). - 05 y pic 9(3). + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 Point. + 05 x USAGE IS BINARY-SHORT. + 05 y USAGE IS BINARY-SHORT. diff --git a/Task/Compound-data-type/Elena/compound-data-type.elena b/Task/Compound-data-type/Elena/compound-data-type.elena index 889f49a5a5..a68ae4a549 100644 --- a/Task/Compound-data-type/Elena/compound-data-type.elena +++ b/Task/Compound-data-type/Elena/compound-data-type.elena @@ -1,8 +1,8 @@ struct Point { - prop int X; + int X : prop; - prop int Y; + int Y : prop; constructor new(int x, int y) { diff --git a/Task/Compound-data-type/FutureBasic/compound-data-type.basic b/Task/Compound-data-type/FutureBasic/compound-data-type.basic new file mode 100644 index 0000000000..b2789d1cc1 --- /dev/null +++ b/Task/Compound-data-type/FutureBasic/compound-data-type.basic @@ -0,0 +1,4 @@ +CGRect r = {0, 0, 250, 100} +printf @"x = %.f : y = %.f : width = %.f : height = %.f", r.origin.x, r.origin.y, r.size.width, r.size.height + +HandleEvents diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Java/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.java b/Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Java/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.java new file mode 100644 index 0000000000..3c1630ec49 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-ng-continued-fraction-n-/Java/continued-fraction-arithmetic-g-matrix-ng-continued-fraction-n-.java @@ -0,0 +1,154 @@ +import java.util.List; + +public final class ContinuedFractionArithmeticG1 { + + public static void main(String[] aArgs) { + List cfData = List.of( + new CFData("[1; 5, 2] + 1 / 2 ", new int[] { 2, 1, 0, 2 }, (CFIterator) new R2cfIterator(13, 11) ), + new CFData("[3; 7] + 1 / 2 ", new int[] { 2, 1, 0, 2 }, (CFIterator) new R2cfIterator(22, 7) ), + new CFData("[3; 7] divided by 4 ", new int[] { 1, 0, 0, 4 }, (CFIterator) new R2cfIterator(22, 7) ), + new CFData("sqrt(2) ", new int[] { 0, 1, 1, 0 }, (CFIterator) new ReciprocalRoot2() ), + new CFData("1 / sqrt(2) ", new int[] { 0, 1, 1, 0 }, (CFIterator) new Root2() ), + new CFData("(1 + sqrt(2)) / 2 ", new int[] { 1, 1, 0, 2 }, (CFIterator) new Root2() ), + new CFData("(1 + 1 / sqrt(2)) / 2", new int[] { 1, 1, 0, 2 }, (CFIterator) new ReciprocalRoot2() ) ); + + for ( CFData data : cfData ) { + System.out.print(data.text + " -> "); + NG ng = new NG(data.arguments); + CFIterator iterator = data.iterator; + int nextTerm = 0; + + for ( int i = 1; i <= 20 && iterator.hasNext(); i++ ) { + nextTerm = iterator.next(); + if ( ! ng.needsTerm() ) { + System.out.print(ng.egress() + " "); + } + ng.ingress(nextTerm); + } + + while ( ! ng.done() ) { + System.out.print(ng.egressDone() + " "); + } + System.out.println(); + } + + } + + private static class NG { + + public NG(int[] aArgs) { + a1 = aArgs[0]; a = aArgs[1]; b1 = aArgs[2]; b = aArgs[3]; + } + + public void ingress(int aN) { + int temp = a; a = a1; a1 = temp + a1 * aN; + temp = b; b = b1; b1 = temp + b1 * aN; + } + + public int egress() { + final int n = a / b; + int temp = a; a = b; b = temp - b * n; + temp = a1; a1 = b1; b1 = temp - b1 * n; + return n; + } + + public boolean needsTerm() { + return ( b == 0 || b1 == 0 ) || ( a * b1 != a1 * b ); + } + + public int egressDone() { + if ( needsTerm() ) { + a = a1; + b = b1; + } + return egress(); + } + + public boolean done() { + return ( b == 0 || b1 == 0 ); + } + + private int a1, a, b1, b; + } + + private static abstract class CFIterator { + + public abstract boolean hasNext(); + public abstract int next(); + + } + + private static class R2cfIterator extends CFIterator { + + public R2cfIterator(int aNumerator, int aDenominator) { + numerator = aNumerator; denominator = aDenominator; + } + + public boolean hasNext() { + return denominator != 0; + } + + public int next() { + int div = numerator / denominator; + int rem = numerator % denominator; + numerator = denominator; + denominator = rem; + return div; + } + + private int numerator, denominator; + + } + + private static class Root2 extends CFIterator { + + public Root2() { + firstReturn = true; + } + + public boolean hasNext() { + return true; + } + + public int next() { + if ( firstReturn ) { + firstReturn = false; + return 1; + } + return 2; + } + + private boolean firstReturn; + + } + + private static class ReciprocalRoot2 extends CFIterator { + + public ReciprocalRoot2() { + firstReturn = true; + secondReturn = true; + } + + public boolean hasNext() { + return true; + } + + public int next() { + if ( firstReturn ) { + firstReturn = false; + return 0; + } + if ( secondReturn ) { + secondReturn = false; + return 1; + } + return 2; + } + + private boolean firstReturn, secondReturn; + + } + + private static record CFData(String text, int[] arguments, CFIterator iterator) {} + +} diff --git a/Task/Continued-fraction/Dc/continued-fraction.dc b/Task/Continued-fraction/Dc/continued-fraction.dc new file mode 100644 index 0000000000..2b0bb00c99 --- /dev/null +++ b/Task/Continued-fraction/Dc/continued-fraction.dc @@ -0,0 +1,9 @@ +[20k 0 200 si [li lbx r li lax + / li 1 - dsi 0<:]ds:x 0 lax +]sf + +[[2q]s2[0<2 1]sa[R1]sb]sr # sqrt(2) +[[R2q]s2[d 0=2]sa[R1q]s1[d 1=1 1-]sb]se # e +[[3q]s3[0=3 6]sa[2*1-d*]sb]sp # pi + +c lex lfx p +lrx lfx p +lpx lfx p diff --git a/Task/Continued-fraction/Elixir/continued-fraction.elixir b/Task/Continued-fraction/Elixir/continued-fraction.elixir new file mode 100644 index 0000000000..202b51073a --- /dev/null +++ b/Task/Continued-fraction/Elixir/continued-fraction.elixir @@ -0,0 +1,22 @@ +defmodule CFrac do + def compute([a | _], []), do: a + def compute([a | as], [b | bs]), do: a + b/compute(as, bs) + + def sqrt2 do + a = [1 | Stream.cycle([2]) |> Enum.take(1000)] + b = Stream.cycle([1]) |> Enum.take(1000) + IO.puts compute(a, b) + end + + def exp1 do + a = [2 | Stream.iterate(1, &(&1 + 1)) |> Enum.take(1000)] + b = [1 | Stream.iterate(1, &(&1 + 1)) |> Enum.take(999)] + IO.puts compute(a, b) + end + + def pi do + a = [3 | Stream.cycle([6]) |> Enum.take(1000)] + b = 1..1000 |> Enum.map(fn k -> (2*k - 1)**2 end) + IO.puts compute(a, b) + end +end diff --git a/Task/Count-in-factors/ALGOL-68/count-in-factors.alg b/Task/Count-in-factors/ALGOL-68/count-in-factors.alg index d8f510f5da..3e2a2b5947 100644 --- a/Task/Count-in-factors/ALGOL-68/count-in-factors.alg +++ b/Task/Count-in-factors/ALGOL-68/count-in-factors.alg @@ -1,8 +1,8 @@ OP +:= = (REF FLEX []INT a, INT b) VOID: BEGIN - [⌈a + 1] INT c; - c[:⌈a] := a; - c[⌈a+1:] := b; + [UPB a + 1] INT c; + c[:UPB a] := a; + c[UPB a+1:] := b; a := c END; diff --git a/Task/Count-in-factors/ALGOL-W/count-in-factors.alg b/Task/Count-in-factors/ALGOL-W/count-in-factors.alg new file mode 100644 index 0000000000..a5de671b5e --- /dev/null +++ b/Task/Count-in-factors/ALGOL-W/count-in-factors.alg @@ -0,0 +1,34 @@ +begin % show numbers and their prime factors % + % shows nand its prime factors % + procedure showFactors ( integer value n ) ; + if n <= 3 then write( i_w := 1, s_w := 0, n, ": ", n ) + else begin + integer v, f; logical first; + first := true; + v := n; + write( i_w := 1, s_w := 0, n, ": " ); + while not odd( v ) and v > 1 do begin + if not first then writeon( s_w := 0, " x " ); + writeon( i_w := 1, s_w := 0, 2 ); + v := v div 2; + first := false + end while_not_odd_v ; + f := 1; + while v > 1 do begin + f := f + 2; + while v rem f = 0 do begin + if not first then writeon( s_w := 0, " x " ); + writeon( i_w := 1, s_w := 0, f ); + v := v div f; + first := false + end while_v_rem_f_eq_0 + end while_v_gt_0_and_f_le_v + end showFactors ; + + % show the factors of various ranges - same as Wren % + for i := 1 until 9 do showFactors( i ); + write( "... " ); + for i := 2144 until 2154 do showFactors( i ); + write( "... " ); + for i := 9987 until 9999 do showFactors( i ) +end. diff --git a/Task/Count-occurrences-of-a-substring/AArch64-Assembly/count-occurrences-of-a-substring.aarch64 b/Task/Count-occurrences-of-a-substring/AArch64-Assembly/count-occurrences-of-a-substring.aarch64 new file mode 100644 index 0000000000..25730262c3 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/AArch64-Assembly/count-occurrences-of-a-substring.aarch64 @@ -0,0 +1,110 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program strcptsub64.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessResult: .asciz "Result: " +szString: .asciz "the three truths" +szSubString: .asciz "th" +szString1: .asciz "ababababab" +szSubString1: .asciz "abab" +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 64 bits start.\n" +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sZoneConv: .skip 24 +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: // entry of program + ldr x0,qAdrszMessStart + bl affichageMess + ldr x0,qAdrszString + ldr x1,qAdrszSubString + bl countSubString + ldr x0,qAdrszString1 + ldr x1,qAdrszSubString1 + bl countSubString + +100: // standard end of the program + mov x0, #0 // return code + mov x8, #EXIT // request to exit program + svc 0 // perform the system call +qAdrszString: .quad szString +qAdrszSubString: .quad szSubString +qAdrszString1: .quad szString1 +qAdrszSubString1: .quad szSubString1 +qAdrsZoneConv: .quad sZoneConv +qAdrszMessResult: .quad szMessResult +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessStart: .quad szMessStart +/***************************************************/ +/* count sub string of string */ +/***************************************************/ +/* r0 contains a string */ +/* r1 contains a substring */ +/* r0 return substring count */ +countSubString: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + mov x4,#0 // counter + mov x3,#0 // index string + mov x5,#0 // index substring +1: + ldrb w6,[x0,x5] // load byte of string + ldrb w7,[x1,x3] // load byte of substring + cmp x6,x7 // compare byte + bne 2f // not equal + cmp x6,#0 // string end ? + beq 3f // yes + add x5,x5,#1 // else increment index + add x3,x3,#1 + b 1b // and loop +2: // characters not equal + cmp x6,#0 // end string ? + beq 4f + cmp x7,#0 // end substring ? + add x6,x4,1 + csel x4,x6,x4,eq // yes -> increment counter + mov x3,#0 // raz index substring + add x5,x5,#1 // increment string index + b 1b // and loop +3: // end string and end substring + add x4,x4,#1 // increment counter +4: // result display + mov x0,x4 + ldr x1,qAdrsZoneConv + bl conversion10 + ldr x0,qAdrszMessResult + bl affichageMess + ldr x0,qAdrsZoneConv + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + mov x0,x4 + 100: + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Count-occurrences-of-a-substring/ARM-Assembly/count-occurrences-of-a-substring.arm b/Task/Count-occurrences-of-a-substring/ARM-Assembly/count-occurrences-of-a-substring.arm new file mode 100644 index 0000000000..5e796f3575 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/ARM-Assembly/count-occurrences-of-a-substring.arm @@ -0,0 +1,102 @@ +/* ARM assembly Raspberry PI */ +/* program strcptsub.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../constantes.inc" + +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessResult: .asciz "Result: " +szString: .asciz "the three truths" +szSubString: .asciz "th" +szString1: .asciz "ababababab" +szSubString1: .asciz "abab" +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 32 bits start.\n" +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sZoneConv: .skip 24 +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: @ entry of program + ldr r0,iAdrszMessStart + bl affichageMess + ldr r0,iAdrszString + ldr r1,iAdrszSubString + bl countSubString + ldr r0,iAdrszString1 + ldr r1,iAdrszSubString1 + bl countSubString + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform the system call +iAdrszString: .int szString +iAdrszSubString: .int szSubString +iAdrszString1: .int szString1 +iAdrszSubString1: .int szSubString1 +iAdrsZoneConv: .int sZoneConv +iAdrszMessResult: .int szMessResult +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessStart: .int szMessStart +/***************************************************/ +/* count sub string of string */ +/***************************************************/ +/* r0 contains a string */ +/* r1 contains a substring */ +/* r0 return substring count */ +countSubString: + push {r1-r7,lr} @ save registers + mov r4,#0 @ counter + mov r3,#0 @ index string + Mov r5,#0 @ index substring +1: + ldrb r6,[r0,r5] @ load byte of string + ldrb r7,[r1,r3] @ load byte of substring + cmp r6,r7 @ compare byte + bne 2f @ not equal + cmp r6,#0 @ string end ? + beq 3f @ yes + add r5,r5,#1 @ else increment index + add r3,r3,#1 + b 1b @ and loop +2: @ characters not equal + cmp r6,#0 @ end string ? + beq 4f + cmp r7,#0 @ end substring ? + addeq r4,r4,#1 @ yes -> increment counter + mov r3,#0 @ raz index substring + add r5,r5,#1 @ increment string index + b 1b @ and loop +3: @ end string and end substring + add r4,r4,#1 @ increment counter +4: @ result display + mov r0,r4 + ldr r1,iAdrsZoneConv + bl conversion10 + ldr r0,iAdrszMessResult + bl affichageMess + ldr r0,iAdrsZoneConv + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + mov r0,r4 + 100: + pop {r1-r7,pc} +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../affichage.inc" diff --git a/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-M/create-a-two-dimensional-array-at-runtime.alg b/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-M/create-a-two-dimensional-array-at-runtime.alg new file mode 100644 index 0000000000..d1fd208203 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/ALGOL-M/create-a-two-dimensional-array-at-runtime.alg @@ -0,0 +1,17 @@ +begin + +integer first, second; + +write("Two Dimensional Array Exercise"); +write("Length of first dimension:"); +read(first); +write("Length of second dimension:"); +read(second); + +begin % we need to start a new block % + integer array test[1:first, 1:second]; + test[1,1] := 99; + write("Stored value at 1,1 =",test[1,1]); +end; % array is now out of scope % + +end diff --git a/Task/Cullen-and-Woodall-numbers/C++/cullen-and-woodall-numbers.cpp b/Task/Cullen-and-Woodall-numbers/C++/cullen-and-woodall-numbers.cpp new file mode 100644 index 0000000000..e0a18f37a4 --- /dev/null +++ b/Task/Cullen-and-Woodall-numbers/C++/cullen-and-woodall-numbers.cpp @@ -0,0 +1,37 @@ +#include +#include +#include + +uint32_t number, power; + +void number_initialise() { + number = 0; + power = 1; +} + +enum NumberType { Cullen, Woodhall }; + +uint32_t next_number(const NumberType& number_type) { + number += 1; + power <<= 1; + switch ( number_type ) { + case Cullen: return number * power + 1; + case Woodhall: return number * power - 1; + }; + return 0; +} + +void number_sequence(const uint32_t& count, const NumberType& number_type) { + std::string type = ( number_type == Cullen ) ? "Cullen" : "Woodhall"; + std::cout << "The first " << count << " " << type << " numbers are:" << std::endl; + number_initialise(); + for ( uint32_t index = 1; index <= count; ++index ) { + std::cout << next_number(number_type) << " "; + } + std::cout << std::endl << std::endl; +} + +int main() { + number_sequence(20, Cullen); + number_sequence(20, Woodhall); +} diff --git a/Task/Cumulative-standard-deviation/C++/cumulative-standard-deviation.cpp b/Task/Cumulative-standard-deviation/C++/cumulative-standard-deviation.cpp index d66a4e51cd..f08823fd51 100644 --- a/Task/Cumulative-standard-deviation/C++/cumulative-standard-deviation.cpp +++ b/Task/Cumulative-standard-deviation/C++/cumulative-standard-deviation.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include #include diff --git a/Task/Currency/FutureBasic/currency.basic b/Task/Currency/FutureBasic/currency.basic new file mode 100644 index 0000000000..00aaf4aa92 --- /dev/null +++ b/Task/Currency/FutureBasic/currency.basic @@ -0,0 +1,32 @@ +local fn Lunch_Invoice( burger_price as CFStringRef, burger_amount as CFStringRef, shake_price as CFStringRef, shake_amount as CFStringRef, tax as CFStringRef ) +'~'1 +DecimalNumberRef burgerPriceDecimal = fn DecimalNumberWithString( burger_price ) +DecimalNumberRef burgerAmountDecimal = fn DecimalNumberWithString( burger_amount ) +DecimalNumberRef burgersDecimal = fn DecimalNumberByMultiplyingBy( burgerPriceDecimal, burgerAmountDecimal ) +DecimalNumberRef shakePriceDecimal = fn DecimalNumberWithString( shake_price ) +DecimalNumberRef shakeAmountDecimal = fn DecimalNumberWithString( shake_amount ) +DecimalNumberRef shakesDecimal = fn DecimalNumberByMultiplyingBy( shakePriceDecimal, shakeAmountDecimal ) +DecimalNumberRef taxDecimal = fn DecimalNumberWithString( tax ) +DecimalNumberRef subtotalDecimal = fn DecimalNumberByAdding( burgersDecimal, shakesDecimal ) +DecimalNumberRef taxTotalDecimal = fn DecimalNumberByMultiplyingBy( subtotalDecimal, taxDecimal ) +DecimalNumberRef adjTaxTotalDecimal = fn DecimalNumberByAdding( taxTotalDecimal, fn DecimalNumberWithString( @"0.01" ) ) +DecimalNumberRef billTotalDecimal = fn DecimalNumberByAdding( subtotalDecimal, adjTaxTotalDecimal ) + +CFStringRef burgersString = fn DecimalNumberString( burgersDecimal ) +CFStringRef shakesString = fn DecimalNumberString( shakesDecimal ) +CFStringRef taxTotalString = fn DecimalNumberString( adjTaxTotalDecimal ) +CFStringRef billTotalString = fn DecimalNumberString( billTotalDecimal ) + +printf @"%@", fn StringByPaddingToLength( @"", 55, @"-", 0 ) +printf @"Item Price Quantity Cost" +printf @"Hamburgers %6s %18s %18s", fn StringUTF8String( burger_price ), fn StringUTF8String( burger_amount ), fn StringUTF8String( burgersString ) +printf @"Milkshakes %6s %18s %18s", fn StringUTF8String( shake_price ), fn StringUTF8String( shake_amount ), fn StringUTF8String( shakesString ) +printf @"%@", fn StringByPaddingToLength( @"", 55, @"-", 0 ) +printf @"%34s %@", fn StringUTF8String( @"Subtotal:" ), fn DecimalNumberString( subtotalDecimal ) +printf @"%35s %@", fn StringUTF8String( @" Tax: " ), fn StringSubstringToIndex( taxTotalString, len(taxTotalString) - 3 ) +printf @"%34s %@", fn StringUTF8String( @" Total:" ), fn StringSubstringToIndex( billTotalString, len(billTotalString) - 3 ) +end fn + +NSLog( @"%@", fn WindowPrintViewString( 1 ) ) + +HandleEvents diff --git a/Task/Currency/Phix/currency.phix b/Task/Currency/Phix/currency-1.phix similarity index 82% rename from Task/Currency/Phix/currency.phix rename to Task/Currency/Phix/currency-1.phix index c19a13cb7d..3b906681e6 100644 --- a/Task/Currency/Phix/currency.phix +++ b/Task/Currency/Phix/currency-1.phix @@ -1,6 +1,5 @@ (phixonline)--> - with javascript_semantics - requires("1.0.0") -- (mpfr_set_default_prec[ision] has been renamed) + requires("1.0.4") -- (mpfr_get_fixed() busted in 1.0.2|3) include mpfr.e mpfr_set_default_precision(-20) -- ensure accuracy to at least 20 d.p. @@ -14,7 +13,7 @@ mpfr_add(total_price,total_price,tmp) mpfr_mul(tax,total_price,tax) mpfr_add(total,total_price,tax) - printf(1,"Total before tax:%21s\n",{mpfr_get_fixed(total_price,2)}) - printf(1," Tax:%21s\n",{mpfr_get_fixed(tax,2)}) - printf(1," Total:%21s\n",{mpfr_get_fixed(total,2)}) + printf(1,"Total before tax:%26s\n",{mpfr_get_fixed(total_price,2,comma_fill:=true)}) + printf(1," Tax:%26s\n",{mpfr_get_fixed(tax,2,comma_fill:=true)}) + printf(1," Total:%26s\n",{mpfr_get_fixed(total,2,comma_fill:=true)}) + requires(64) + atom total_price = 4000000000000000*5.5+2.86*2, + tax = total_price*0.0765, + total = total_price+tax + printf(1,"Total before tax:%,26.2f\n",{total_price}) + printf(1," Tax:%,26.2f\n",{tax}) + printf(1," Total:%,26.2f\n",{total}) + n/d ) + + [ n->v v+ ] is cents ( n/d n --> n/d ) + + [ rot n->v v* ] is cost ( n n/d --> n/d ) + + [ $->v drop v* 100 n->v v/ ] is tax ( n/d $ --> n/d ) + + [ 100 n->v v/ + 2 point$ + $ " $" swap join + ' [ 2 split nip ] ]do[ + dup -3 peek + char . = if done + dup -2 peek + char . = iff + [ char 0 join ] + done + $ ".00" join ] is currency$ ( n/d --> $ ) + + [ currency$ echo$ ] is echocurrency ( n/d --> ) + + + 4000000000000000 5 dollars 50 cents cost + 2 2 dollars 86 cents cost v+ + + say "Total price before tax: " 2dup echocurrency cr + + 2dup $ "7.65" tax + + say "Tax: " 2dup echocurrency cr + + v+ + say "Total price with tax: " echocurrency cr diff --git a/Task/Cyclops-numbers/FutureBasic/cyclops-numbers.basic b/Task/Cyclops-numbers/FutureBasic/cyclops-numbers.basic new file mode 100644 index 0000000000..243e3df01e --- /dev/null +++ b/Task/Cyclops-numbers/FutureBasic/cyclops-numbers.basic @@ -0,0 +1,126 @@ +begin globals +CFTimeInterval t +long n(16), clops(52), primes(52), blinds(52), pals(52) +long num, iClop, iPrime, iBlind, iPal +short first1, last1, midPt +xref show(50) as long +midPt = 8 +end globals + +local fn convertToNumber as long + long p10 = 1, nr = 0 + short c2 = last1 + do + nr += n(c2) * p10 + if c2 == midPt then p10 *= 100 else p10 *= 10 //Add 0 if at midPoint + c2-- + until c2 < first1 +end fn = nr + +void local fn increment( dgt as short ) + if n(dgt) < 9 then n(dgt)++ : exit fn + n(dgt) = 1 + if dgt > first1 then fn increment( dgt - 1 ) : exit fn //Carry + first1-- : last1 ++ + for dgt = first1 to last1 //New width: set all digits to 1 + n(dgt) = 1 + next +end fn + +local fn isPrime( v as long ) as bool + //Skip check for 2 and 3 because we're starting at 101 + if v mod 2 == 0 then exit fn = no + if v mod 3 == 0 then exit fn = no + long f = 5 + while f*f <= v + if v mod f == 0 then exit fn = no + f += 2 + if v mod f == 0 then exit fn = no + f += 4 + wend +end fn = yes + +local fn isBlind as bool + short temp = 0 + swap temp, midPt //Keep fn convertToNumber from adding 0 at midPt + bool rslt = fn isPrime( fn convertToNumber ) + swap temp, midPt +end fn = rslt + +local fn isPalindrome as bool + short a = first1, b = last1 + while b > a + if n(a) <> n(b) then exit fn = no + a++ : b-- + wend +end fn = yes + +void local fn print50( title as cfstringref, addr as ptr ) + short r = 0 + show = addr //Set array address to param + print : print title + while r < 50 + printf @"%9ld\b",show(r) + r++ : if r mod 10 == 0 then print + wend +end fn + +void local fn display + window 1, @"Cyclopean numbers", (0, 0, 680, 515 ) + fn print50( @" First 50 Cyclopean numbers:", @clops( 0)) + fn print50( @" First 50 Cyclopean primes:", @primes(0)) + fn print50( @" First 50 blind Cyclopean primes:", @blinds(0)) + fn print50( @" First 50 palindromic Cyclopean primes:",@pals( 0)) + print + printf @" First Cyclopean number above 10,000,000 is %ld at index %ld", clops(50), clops(51) + printf @" First Cyclopean prime above 10,000,000 is %ld at index %ld", primes(50),primes(51) + printf @" First blind Cyclopean prime above 10,000,000 is %ld at index %ld", blinds(50),blinds(51) + printf @" First palindromic Cyclopean prime above 10,000,000 is %ld at index %ld", pals(50), pals(51) + print + printf @" Compute time: %.3f sec", t +end fn + +void local fn cyclops + clops( 0 ) = 0 : iClop = 1 : iPrime = 0 : iBlind = 0 : iPal = 0 + first1 = midPt-1 : last1 = midPt : n(first1) = 1 : n(last1) = 1 + + // Record first 50 numbers in each category + while ( iPal ) < 50 + num = fn convertToNumber + if iClop < 50 then clops(iClop) = num + iClop++ + if fn isPrime( num ) + if iPrime < 50 then primes(iPrime) = num : iPrime++ + if iBlind < 50 then if fn isBlind then blinds(iBlind) = num : iBlind++ + if iPal < 50 then if fn isPalindrome then pals(iPal) = num : iPal++ + end if + num++ + fn increment( last1 ) + wend + + // Keep counting Cyclops numbers until 10,000,000 + while fn convertToNumber < 10000000 + fn increment( last1 ) : iClop++ + wend + + // Find next number in each category + clops(50) = fn convertToNumber : clops(51) = iClop + iPrime = 1 : iBlind = 1 : iPal = 1 + while (iPrime or iBlind or iPal) + num = fn convertToNumber + iClop++ + if fn isPrime( num ) + if iPrime then primes(50) = num : primes(51) = iClop : iPrime-- + if iBlind then if fn isBlind then blinds(50) = num : blinds(51) = iClop : iBlind-- + if iPal then if fn isPalindrome then pals(50) = num : pals(51) = iClop : ipal-- + end if + fn increment( last1 ) + wend +end fn + +t = fn CACurrentMediaTime +fn cyclops +t = fn CACurrentMediaTime - t +fn display + +handleevents diff --git a/Task/DNS-query/FutureBasic/dns-query-1.basic b/Task/DNS-query/FutureBasic/dns-query-1.basic new file mode 100644 index 0000000000..349234de0d --- /dev/null +++ b/Task/DNS-query/FutureBasic/dns-query-1.basic @@ -0,0 +1,2 @@ +print unix @"nslookup -querytype=A www.kame.net" +HandleEvents diff --git a/Task/DNS-query/FutureBasic/dns-query.basic b/Task/DNS-query/FutureBasic/dns-query-2.basic similarity index 100% rename from Task/DNS-query/FutureBasic/dns-query.basic rename to Task/DNS-query/FutureBasic/dns-query-2.basic diff --git a/Task/Damm-algorithm/BASIC256/damm-algorithm.basic b/Task/Damm-algorithm/BASIC256/damm-algorithm.basic new file mode 100644 index 0000000000..0308df2075 --- /dev/null +++ b/Task/Damm-algorithm/BASIC256/damm-algorithm.basic @@ -0,0 +1,22 @@ +arraybase 1 +global matrix +matrix = {{0, 3, 1, 7, 5, 9, 8, 6, 4, 2}, {7, 0, 9, 2, 1, 5, 4, 8, 6, 3}, {4, 2, 0, 6, 8, 7, 1, 3, 5, 9}, {1, 7, 5, 0, 9, 8, 3, 4, 2, 6}, {6, 1, 2, 3, 0, 4, 5, 9, 7, 8}, {3, 6, 7, 4, 2, 0, 9, 5, 8, 1}, {5, 8, 6, 9, 7, 2, 0, 1, 3, 4}, {8, 9, 4, 5, 3, 6, 2, 0, 1, 7}, {9, 4, 3, 8, 6, 1, 7, 2, 0, 5}, {2, 5, 8, 1, 4, 3, 6, 7, 9, 0}} +test = {5724, 5727, 112946} + +for i = 1 to 3 + print "Checksum test: "; rjust(string(test[i]),8); encode(test[i]) +next i +end + +function encode(n) + cad = string(n) + check = 0 + for d = 1 to length(cad) + check = matrix[int(mid(cad, d, 1)), d] + next d + if check = 0 then + return " is valid" + else + return " is invalid" + end if +end function diff --git a/Task/Damm-algorithm/BCPL/damm-algorithm.bcpl b/Task/Damm-algorithm/BCPL/damm-algorithm.bcpl index db5de4be4a..e45de93a5f 100644 --- a/Task/Damm-algorithm/BCPL/damm-algorithm.bcpl +++ b/Task/Damm-algorithm/BCPL/damm-algorithm.bcpl @@ -1,6 +1,6 @@ get "libhdr" -let damm(ns) = valof +let Damm(ns) = valof $( let dt = table 0,3,1,7,5,9,8,6,4,2, 7,0,9,2,1,5,4,8,6,3, diff --git a/Task/Date-manipulation/FutureBasic/date-manipulation.basic b/Task/Date-manipulation/FutureBasic/date-manipulation.basic new file mode 100644 index 0000000000..5de4979f43 --- /dev/null +++ b/Task/Date-manipulation/FutureBasic/date-manipulation.basic @@ -0,0 +1,45 @@ +void local fn DoIt + CFStringRef monthString, zoneString, ampmString + long month, day, year, hour, minute + + CFStringRef dateString = @"March 7 2009 7:30pm EST" + + DateFormatterRef df = fn DateFormatterInit + DateFormatterSetDateStyle( df, NSDateFormatterMediumStyle ) + DateFormatterSetTimeStyle( df, NSDateFormatterMediumStyle ) + DateFormatterSetDateFormat( df, @"MMMM d YYYY h:ma" ) + + CFArrayRef months = fn DateFormatterMonthSymbols( df ) + CFCharacterSetRef spaceSet = fn CharacterSetWhitespaceSet + + ScannerRef scanner = fn ScannerWithString( dateString ) + ScannerSetCharactersToBeSkipped( scanner, fn CharacterSetWithCharactersInString(@": ") ) + + fn ScannerScanUpToCharactersFromSet( scanner, spaceSet, @monthString ) + fn ScannerScanInteger( scanner, @day ) + fn ScannerScanInteger( scanner, @year ) + fn ScannerScanInteger( scanner, @hour ) + fn ScannerScanInteger( scanner, @minute ) + fn ScannerScanUpToCharactersFromSet( scanner, spaceSet, @ampmString ) + fn ScannerScanUpToCharactersFromSet( scanner, spaceSet, @zoneString ) + + month = fn ArrayIndexOfObject( months, monthString ) + 1 + if ( fn StringIsEqual( ampmString, @"pm" ) ) then hour += 12 + + DateComponentsRef comps = fn DateComponentsInit + DateComponentsSetMonth( comps, month ) + DateComponentsSetDay( comps, day ) + DateComponentsSetYear( comps, year ) + DateComponentsSetHour( comps, hour + 12 ) + DateComponentsSetMinute( comps, minute ) + + CFDateRef dt = fn CalendarDateFromComponents( fn CalendarCurrent, comps ) + CFStringRef string = fn DateFormatterStringFromDate( df, dt ) + string = fn StringByAppendingFormat( string, @" %@", zoneString ) + + print string +end fn + +fn DoIt + +HandleEvents diff --git a/Task/Day-of-the-week/Koka/day-of-the-week.koka b/Task/Day-of-the-week/Koka/day-of-the-week.koka new file mode 100644 index 0000000000..e74c4d453f --- /dev/null +++ b/Task/Day-of-the-week/Koka/day-of-the-week.koka @@ -0,0 +1,12 @@ +import std/time/date +import std/time/calendar +import std/time/instant +import std/time/utc + +fun main() + for(2008, 2121) fn(year) + val i = instant(year, 12, 25, cal=cal-gregorian) + val dow = (i.days+6)%7 // plus 6 since 2000-01-01 epoch was a Saturday + match dow.weekday + Sun -> println(year.show) + _ -> () diff --git a/Task/Deceptive-numbers/C++/deceptive-numbers.cpp b/Task/Deceptive-numbers/C++/deceptive-numbers-1.cpp similarity index 100% rename from Task/Deceptive-numbers/C++/deceptive-numbers.cpp rename to Task/Deceptive-numbers/C++/deceptive-numbers-1.cpp diff --git a/Task/Deceptive-numbers/C++/deceptive-numbers-2.cpp b/Task/Deceptive-numbers/C++/deceptive-numbers-2.cpp new file mode 100644 index 0000000000..fed3eb8c72 --- /dev/null +++ b/Task/Deceptive-numbers/C++/deceptive-numbers-2.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +#include + +uint64_t power_modulus(uint64_t base, uint64_t exponent, uint64_t modulus) { + if ( modulus == 1 ) { + return 0; + } + + base %= modulus; + uint64_t result = 1; + while ( exponent > 0 ) { + if ( ( exponent & 1 ) == 1 ) { + result = ( result * base ) % modulus; + } + base = ( base * base ) % modulus; + exponent >>= 1; + } + return result; +} + +bool is_deceptive(uint32_t n) { + if ( n % 2 != 0 && n % 3 != 0 && n % 5 != 0 && power_modulus(10, n - 1, n) == 1 ) { + for ( uint32_t divisor = 7; divisor < sqrt(n); divisor += 6 ) { + if ( n % divisor == 0 || n % ( divisor + 4 ) == 0 ) { + return true; + } + } + } + return false; +} + +int main() { + uint32_t n = 7; + uint32_t count = 0; + while ( count < 100 ) { + if ( is_deceptive(n) ) { + std::cout << std::setw(6) << n << ( ++count % 10 == 0 ? "\n" : " " ); + } + n += 1; + } +} diff --git a/Task/Deceptive-numbers/Maxima/deceptive-numbers.maxima b/Task/Deceptive-numbers/Maxima/deceptive-numbers.maxima new file mode 100644 index 0000000000..afeb61c4f5 --- /dev/null +++ b/Task/Deceptive-numbers/Maxima/deceptive-numbers.maxima @@ -0,0 +1,10 @@ +/* Function for repunit numbers */ +repunit(n):=(10^n-1)/9; + +/* Function that checks if property is satisfied */ +repunit_property(n):=is(mod(repunit(n-1),n)=0); + +/* Function to list the first n deceptive numbers */ +deceptive_list(n):=block([deceptives:[],count:0,i:5], +while count n ) + + [] 0 + [ 2 + dup 1+ isprime if again + dup rep over 1+ mod if again + tuck 1+ join + tuck size 20 = until ] + drop echo diff --git a/Task/Delete-a-file/COBOL/delete-a-file-1.cobol b/Task/Delete-a-file/COBOL/delete-a-file-1.cobol index 9f0db641dc..5c4fc1105e 100644 --- a/Task/Delete-a-file/COBOL/delete-a-file-1.cobol +++ b/Task/Delete-a-file/COBOL/delete-a-file-1.cobol @@ -1,11 +1,22 @@ IDENTIFICATION DIVISION. PROGRAM-ID. Delete-Files. - PROCEDURE DIVISION. - CALL "CBL_DELETE_FILE" USING "input.txt" - CALL "CBL_DELETE_DIR" USING "docs" - CALL "CBL_DELETE_FILE" USING "/input.txt" - CALL "CBL_DELETE_DIR" USING "/docs" + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT Local-File ASSIGN TO "input.txt". + SELECT Root-File ASSIGN TO "/input.txt". - GOBACK - . + DATA DIVISION. + FILE SECTION. + FD Local-File. + 01 Local-Record PIC X. + FD Root-File. + 01 Root-Record PIC X. + + PROCEDURE DIVISION. + DELETE FILE Local-File + DELETE FILE Root-File + GOBACK. + + END PROGRAM Delete-Files. diff --git a/Task/Delete-a-file/COBOL/delete-a-file-2.cobol b/Task/Delete-a-file/COBOL/delete-a-file-2.cobol index 9094f5a7ea..6c69dd0a47 100644 --- a/Task/Delete-a-file/COBOL/delete-a-file-2.cobol +++ b/Task/Delete-a-file/COBOL/delete-a-file-2.cobol @@ -1,23 +1,12 @@ IDENTIFICATION DIVISION. - PROGRAM-ID. Delete-Files-2. - - ENVIRONMENT DIVISION. - INPUT-OUTPUT SECTION. - FILE-CONTROL. - SELECT Local-File ASSIGN TO "input.txt". - SELECT Root-File ASSIGN TO "/input.txt". - - DATA DIVISION. - FILE SECTION. - FD Local-File. - 01 Local-Record PIC X. - - FD Root-File. - 01 Root-Record PIC X. + PROGRAM-ID. Delete-Files. PROCEDURE DIVISION. - DELETE FILE Local-File - DELETE FILE Root-File + CALL "CBL_DELETE_FILE" USING "input.txt" + CALL "CBL_DELETE_DIR" USING "docs" + CALL "CBL_DELETE_FILE" USING "/input.txt" + CALL "CBL_DELETE_DIR" USING "/docs" - GOBACK - . + GOBACK. + + END PROGRAM Delete-Files. diff --git a/Task/Demings-funnel/C++/demings-funnel.cpp b/Task/Demings-funnel/C++/demings-funnel.cpp index 8498ce3ff1..23eacc865c 100644 --- a/Task/Demings-funnel/C++/demings-funnel.cpp +++ b/Task/Demings-funnel/C++/demings-funnel.cpp @@ -69,8 +69,8 @@ int main() { 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032 }; - experiment("Rule 1:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return 0.0; }); - experiment("Rule 2:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return -dz; }); - experiment("Rule 3:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return -( z + dz ); }); - experiment("Rule 4:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return z + dz; }); + experiment("Rule 1:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return 0.0; }); + experiment("Rule 2:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return -dz; }); + experiment("Rule 3:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return -(z + dz); }); + experiment("Rule 4:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return z + dz; }); } diff --git a/Task/Detect-division-by-zero/FutureBasic/detect-division-by-zero.basic b/Task/Detect-division-by-zero/FutureBasic/detect-division-by-zero.basic index 1f6d0e277a..afc3cda133 100644 --- a/Task/Detect-division-by-zero/FutureBasic/detect-division-by-zero.basic +++ b/Task/Detect-division-by-zero/FutureBasic/detect-division-by-zero.basic @@ -1,5 +1,5 @@ -include "ConsoleWindow" - on error stop -dim as long a +long a print a / 0 + +HandleEvents diff --git a/Task/Determine-if-a-string-is-numeric/Fantom/determine-if-a-string-is-numeric.fantom b/Task/Determine-if-a-string-is-numeric/Fantom/determine-if-a-string-is-numeric-1.fantom similarity index 100% rename from Task/Determine-if-a-string-is-numeric/Fantom/determine-if-a-string-is-numeric.fantom rename to Task/Determine-if-a-string-is-numeric/Fantom/determine-if-a-string-is-numeric-1.fantom diff --git a/Task/Determine-if-a-string-is-numeric/Fantom/determine-if-a-string-is-numeric-2.fantom b/Task/Determine-if-a-string-is-numeric/Fantom/determine-if-a-string-is-numeric-2.fantom new file mode 100644 index 0000000000..fe5c2a26dc --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Fantom/determine-if-a-string-is-numeric-2.fantom @@ -0,0 +1,18 @@ +/* gary chike 08/27/2023 */ + +class Main { + static Void main() { + inputs := ["152\n", "-3.141", "Foo123", "-0", "456bar", "1.0E10"] + + inputs.each |Str input| { echo("$input.trim \tis " + (isNumeric(input) ? "numeric" : "not numeric"))} + + static Bool isNumeric(Str input) { + try { + input.toFloat + return true + } + catch(Err e) { + return false + } + } +} diff --git a/Task/Determine-if-a-string-is-numeric/Free-Pascal-Lazarus/determine-if-a-string-is-numeric.pas b/Task/Determine-if-a-string-is-numeric/Free-Pascal-Lazarus/determine-if-a-string-is-numeric-1.pas similarity index 100% rename from Task/Determine-if-a-string-is-numeric/Free-Pascal-Lazarus/determine-if-a-string-is-numeric.pas rename to Task/Determine-if-a-string-is-numeric/Free-Pascal-Lazarus/determine-if-a-string-is-numeric-1.pas diff --git a/Task/Determine-if-a-string-is-numeric/Free-Pascal-Lazarus/determine-if-a-string-is-numeric-2.pas b/Task/Determine-if-a-string-is-numeric/Free-Pascal-Lazarus/determine-if-a-string-is-numeric-2.pas new file mode 100644 index 0000000000..63993e644e --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Free-Pascal-Lazarus/determine-if-a-string-is-numeric-2.pas @@ -0,0 +1,35 @@ +program IsNumeric; + +type + TDynamicArrayItem = record + StrValue: string; + end; + +var + myDynamicArray: array of TDynamicArrayItem; + i: Integer; + Value: Extended; + Code: Integer; + +begin + // Initialize the dynamic array with different data types + SetLength(myDynamicArray, 7); + myDynamicArray[0].StrValue := 'Hello'; + myDynamicArray[1].StrValue := '42'; + myDynamicArray[2].StrValue := '3.14159'; + myDynamicArray[3].StrValue := 'World'; + myDynamicArray[4].StrValue := '99'; + myDynamicArray[5].StrValue := '0777'; // Octal representation for 511 + myDynamicArray[6].StrValue := '$A1'; // Hexadecimal representation for 161 + + // Iterate through the dynamic array and determine data type + for i := Low(myDynamicArray) to High(myDynamicArray) do + begin + Val(myDynamicArray[i].StrValue, Value, Code); + if Code = 0 then // The value 0 for Code indicates that the conversion was successful. + Writeln('Element ', i, ': Numeric Value ', Chr(9),' - ', Value) // Chr(9) = tab + else + Writeln('Element ', i, ': Non-Numeric Value ', Chr(9), ' - ', myDynamicArray[i].StrValue); + end; +end. +{ Val converts the value represented in the string 'StrValue' to a numerical value or an enumerated value, and stores this value in the variable 'Value', which can be of type Longint, Real and Byte or any enumerated type. If the conversion isn't successful, then the parameter 'Code' contains the index of the character in 'StrValue' which prevented the conversion. } diff --git a/Task/Determine-if-two-triangles-overlap/ALGOL-68/determine-if-two-triangles-overlap.alg b/Task/Determine-if-two-triangles-overlap/ALGOL-68/determine-if-two-triangles-overlap.alg new file mode 100644 index 0000000000..3610ca5ac6 --- /dev/null +++ b/Task/Determine-if-two-triangles-overlap/ALGOL-68/determine-if-two-triangles-overlap.alg @@ -0,0 +1,128 @@ +BEGIN # test for overlapping 2D triangles - using the code from the Algol 68 # + # sample for the Check if two polygons overlap task, the code of which # + # is based on a translation of that tasks' Go which is a translation # + # of Wren # + + # In the following a polygon is represented as a row of vertices # + # and a vertex ( POINT ) by a pair of x, y coordinates in the plane # + + MODE POINT = STRUCT( REAL x, y ); + MODE PROJECTION = STRUCT( REAL min, max ); + MODE POLYGON = FLEX[ 1 : 0 ]POINT; + + PRIO DOT = 3; + OP DOT = ( POINT v, other )REAL: + ( x OF v * x OF other ) + ( y OF v * y OF other ); + + # returns the axes of the polygon defined by poly # + OP AXES = ( POLYGON poly )[]POINT: + BEGIN + [ LWB poly : UPB poly ]POINT result; + FOR i FROM LWB poly TO UPB poly DO + INT j = IF i = UPB poly THEN LWB poly ELSE i + 1 FI; + POINT vertex1 = poly[ i ]; + POINT vertex2 = poly[ j ]; + POINT edge = ( x OF vertex1 - x OF vertex2, y OF vertex1 - y OF vertex2 ); + result[ i ] := ( - y OF edge, x OF edge ) + OD; + result + END # AXES # ; + + # returns the projection of poly onto axis # + PRIO PROJECTONTO = 3; + OP PROJECTONTO = ( POLYGON poly, POINT axis )PROJECTION: + BEGIN + REAL min := axis DOT poly[ LWB poly ]; + REAL max := min; + FOR i FROM LWB poly + 1 TO UPB poly DO + REAL p = axis DOT poly[ i ]; + IF p < min THEN + min := p + ELIF p > max THEN + max := p + FI + OD; + PROJECTION( min, max ) + END # PROJECTONTO # ; + + PRIO OVERLAPS = 5; + # returns TRUE if the projections proj1 and proj2 overlap, # + # FALSE otherrwise # + OP OVERLAPS = ( PROJECTION proj1, proj2 )BOOL: + IF max OF proj1 < min OF proj2 THEN FALSE + ELIF max OF proj2 < min OF proj1 THEN FALSE + ELSE TRUE + FI # OVERLAPS # ; + + # returns TRUE if the ppolygons poly1 and poly2 overlap, # + # FALSE otherrwise # + OP OVERLAPS = ( POLYGON poly1, poly2 )BOOL: + BEGIN + []POINT axes1 = AXES poly1, axes2 = AXES poly2; + BOOL does overlap := TRUE; + FOR a FROM LWB axes1 TO UPB axes1 WHILE does overlap DO + does overlap := ( poly1 PROJECTONTO axes1[ a ] ) + OVERLAPS ( poly2 PROJECTONTO axes1[ a ] ) + OD; + FOR a FROM LWB axes2 TO UPB axes2 WHILE does overlap DO + does overlap := ( poly1 PROJECTONTO axes2[ a ] ) + OVERLAPS ( poly2 PROJECTONTO axes2[ a ] ) + OD; + does overlap + END # OVERLAPS # ; + + # returns x as a string without trailing 0 decoimals # + OP TOSTRING = ( REAL x )STRING: + BEGIN + STRING v := fixed( x, -14, 11 ); + INT end pos := UPB v; + WHILE IF end pos < LWB v THEN FALSE ELSE v[ end pos ] = "0" FI DO + end pos -:= 1 + OD; + IF end pos >= LWB v THEN + IF v[ end pos ] = "." THEN end pos -:= 1 FI + FI; + INT start pos := LWB v; + WHILE IF start pos > end pos THEN FALSE ELSE v[ start pos ] = " " FI DO + start pos +:= 1 + OD; + IF end pos < start pos THEN "0" ELSE v[ start pos : end pos ] FI + END # TOSTRING # ; + + # returns a string representation of the POINT p # + OP TOSTRING = ( POINT p )STRING: "( " + TOSTRING x OF p + ", " + TOSTRING y OF p + " )"; + + # returns a string representation of the points of p # + OP TOSTRING = ( POLYGON p )STRING: + BEGIN + STRING result := "(", separator := ""; + FOR i FROM LWB p TO UPB p DO + result +:= separator + " " + TOSTRING p[ i ]; + separator := "," + OD; + result + " )" + END # TOSTRING # ; + + # code specific to thius task # + # test cases - using the general POLYGON MODE to represent triangles # + [,]POLYGON triangle pairs + = ( ( ( ( 0, 0 ), ( 5, 0 ), ( 0, 5 ) ), ( ( 0, 0 ), ( 5, 0 ), ( 0, 6 ) ) ) + , ( ( ( 0, 0 ), ( 0, 5 ), ( 5, 0 ) ), ( ( 0, 0 ), ( 0, 5 ), ( 5, 0 ) ) ) + , ( ( ( 0, 0 ), ( 5, 0 ), ( 0, 5 ) ), ( (-10, 0 ), ( -5, 0 ), ( -1, 6 ) ) ) + , ( ( ( 0, 0 ), ( 5, 0 ), ( 2.5, 5 ) ), ( ( 0, 4 ), ( 2.5, -1 ), ( 5, 4 ) ) ) + , ( ( ( 0, 0 ), ( 1, 1 ), ( 0, 2 ) ), ( ( 2, 1 ), ( 3, 0 ), ( 3, 2 ) ) ) + , ( ( ( 0, 0 ), ( 1, 1 ), ( 0, 2 ) ), ( ( 2, 1 ), ( 3, -2 ), ( 3, 4 ) ) ) + , ( ( ( 0, 0 ), ( 1, 0 ), ( 0, 1 ) ), ( ( 1, 0 ), ( 2, 0 ), ( 1, 1 ) ) ) + ); + FOR t pos FROM LWB triangle pairs TO UPB triangle pairs DO + []POLYGON tpair = triangle pairs[ t pos, : ]; + POLYGON t1 = tpair[ LWB tpair ]; + POLYGON t2 = tpair[ UPB tpair ]; + print( ( TOSTRING t1 + , IF t1 OVERLAPS t2 THEN " overlaps " ELSE " does not overlap " FI + , TOSTRING t2 + , newline + ) + ) + OD +END diff --git a/Task/Digital-root/BASIC256/digital-root.basic b/Task/Digital-root/BASIC256/digital-root.basic new file mode 100644 index 0000000000..ba8bf0d48e --- /dev/null +++ b/Task/Digital-root/BASIC256/digital-root.basic @@ -0,0 +1,24 @@ +global dr +global ap + +dim a = {627615, 39390, 588225} + +for i = 0 to a[?]-1 + dr = digitalRoot(a[i]) + print a[i], "Additive Persistence = "; ap, "Digital root = "; dr +next i +end + +function digitalRoot(n) + ap = 0 + do + dr = 0 + while n > 0 + dr += n mod 10 + n = n \ 10 + end while + ap += 1 + n = dr + until dr < 10 + return dr +end function diff --git a/Task/Digital-root/True-BASIC/digital-root.basic b/Task/Digital-root/True-BASIC/digital-root.basic new file mode 100644 index 0000000000..f6a31c23b5 --- /dev/null +++ b/Task/Digital-root/True-BASIC/digital-root.basic @@ -0,0 +1,22 @@ +SUB digitalroot (what) + LET dr = ABS(what) + IF dr > 10 THEN + LET ap = 0 + DO + LET ap = ap + 1 + DO WHILE dr <> 0 + LET t = t + REMAINDER(dr, 10) + LET dr = IP(dr / 10) + LOOP + LET dr = t + LET t = 0 + LOOP WHILE dr > 9 + END IF + PRINT what, "Additive persistance ="; ap, "Digital root ="; dr +END SUB + +CALL digitalroot (627615) +CALL digitalroot (39390) +CALL digitalroot (588225) +CALL digitalroot (393900588225) +END diff --git a/Task/Digital-root/Yabasic/digital-root.basic b/Task/Digital-root/Yabasic/digital-root.basic new file mode 100644 index 0000000000..7927abdb59 --- /dev/null +++ b/Task/Digital-root/Yabasic/digital-root.basic @@ -0,0 +1,21 @@ +dim a(2) +a(0) = 627615 : a(1) = 39390 : a(2) = 588225 +for i = 0 to arraysize(a(),1) + dr = digitalRoot(a(i)) + print a(i), "\tAdditive persistence = ", ap, "\tDigital root = ", dr +next i +end + +sub digitalRoot(n) + ap = 0 + repeat + dr = 0 + while n > 0 + dr = dr + mod(n, 10) + n = int(n / 10) + wend + ap = ap + 1 + n = dr + until dr < 10 + return dr +end sub diff --git a/Task/Diversity-prediction-theorem/ALGOL-68/diversity-prediction-theorem.alg b/Task/Diversity-prediction-theorem/ALGOL-68/diversity-prediction-theorem.alg new file mode 100644 index 0000000000..a44a44127a --- /dev/null +++ b/Task/Diversity-prediction-theorem/ALGOL-68/diversity-prediction-theorem.alg @@ -0,0 +1,65 @@ +BEGIN # Diversity Prediction Theorem # + + # utility operators # + OP LENGTH = ( []REAL a )INT: ( UPB a - LWB a ) + 1; + OP LENGTH = ( STRING a )INT: ( UPB a - LWB a ) + 1; + OP SUM = ( []REAL a )REAL: + BEGIN + REAL result := 0; + FOR i FROM LWB a TO UPB a DO result +:= a[ i ] OD; + result + END # SUM # ; + PRIO PAD = 9; + OP PAD = ( INT width, STRING v )STRING: # left blank pad v to width # + IF LENGTH v >= width THEN v ELSE ( " " * ( width - LENGTH v ) ) + v FI; + OP - = ( []REAL a, REAL v )[]REAL: # return a with elements - v # + BEGIN + [ LWB a : UPB a ]REAL result; + FOR i FROM LWB a TO UPB a DO result[ i ] := v - a[ i ] OD; + result + END # - # ; + OP ^ = ( []REAL a, INT p )[]REAL: # return a with elements raised to p # + BEGIN + [ LWB a : UPB a ]REAL result; + FOR i FROM LWB a TO UPB a DO result[ i ] := a[ i ] ^ p OD; + result + END # |^ # ; + PRIO FMT = 1; + OP FMT = ( REAL v, INT d )STRING: # formats v with up to d decimals # + BEGIN + STRING result := fixed( v, -0, d ); + IF result[ LWB result ] = "." THEN "0" +=: result FI; + WHILE result[ UPB result ] = "0" DO result := result[ : UPB result - 1 ] OD; + IF result[ UPB result ] = "." THEN result := result[ : UPB result - 1 ] FI; + " " + result + END # FMT # ; + + # task # + + MODE NAMEDVALUE = STRUCT( STRING name, REAL value ); + + PROC mean = ( []REAL s )REAL: SUM s / LENGTH s; + + PROC variance = ( []REAL s, REAL d )REAL: mean( ( s - d ) ^ 2 ); + + PROC diversity theorem = ( REAL reference, []REAL observations )[]NAMEDVALUE: + BEGIN + REAL average = mean( observations ); + ( ( "average_error", variance( observations, reference ) ) + , ( "crowd_error", ( reference - average ) ^ 2 ) + , ( "diversity", variance( observations, average ) ) + ) + END # diversity theorem # ; + + PROC test = ( REAL reference, []REAL observations )VOID: + BEGIN + []NAMEDVALUE res = diversity theorem( reference, observations ); + FOR i FROM LWB res TO UPB res DO + print( ( 14 PAD name OF res[ i ], " : ", value OF res[ i ] FMT 6, newline ) ) + OD + END # test # ; + + test( 49, ( 48, 47, 51 ) ); + test( 49, ( 48, 47, 51, 42 ) ) + +END diff --git a/Task/Draw-a-cuboid/Evaldraw/draw-a-cuboid-1.evaldraw b/Task/Draw-a-cuboid/Evaldraw/draw-a-cuboid-1.evaldraw new file mode 100644 index 0000000000..c46cf5542d --- /dev/null +++ b/Task/Draw-a-cuboid/Evaldraw/draw-a-cuboid-1.evaldraw @@ -0,0 +1,53 @@ +static points_x[8] = {-2.0, +2.0, +2.0, -2.0, -2.0, +2.0, +2.0, -2.0}; +static points_y[8] = {-1.5, -1.5, +1.5, +1.5, -1.5, -1.5, +1.5, +1.5}; +static points_z[8] = {-1.0, -1.0, -1.0, -1.0, +1.0, +1.0, +1.0, +1.0}; +static segment[2*12] = {0,1, 1,2, 2,3, 3,0, 4,5, 5,6, 6,7, 7,4, 0,4, 1,5, 2,6, 3,7}; +static size=50, sz=0.008, sx=-0.013; // drawing size and tumbling speeds +() { + mind = 0.0; si=0; + for(i=0; i<8; i++) { + if (points_z[i] < mind) { mind=points_z[i]; si=i;} + } + cls(0); // Clear Color Buffer + + for(i=0; i<2*12-1; i+=2) { + j=segment[i]; + x0 = points_x[j]*size + xres/2; + y0 = points_y[j]*size + yres/2; + k=segment[i+1]; + x1 = points_x[k]*size + xres/2; + y1 = points_y[k]*size + yres/2; + + if (j!=si && k!=si) { + setcol(255,0,0); + moveto(x0,y0); lineto(x1,y1); + } else { + setcol(255,255,0); + drawLineStipple(x0,y0,x1,y1,8); + } + } + sleep(16); // Sleep for 16 millis so cube tumbles slowly + for(i=0; i<8; i++) { + points_x[i] = points_x[i] + points_y[i]*Sz; //rotate vertices in X-Y plane + points_y[i] = points_y[i] - points_x[i]*Sz; + points_y[i] = points_y[i] + points_z[i]*Sx; //rotate vertices in Y-Z plane + points_z[i] = points_z[i] - points_y[i]*Sx; + } +} + +drawLineStipple(x1,y1,x2,y2,stipple_dist) { + xdist = x1-x2; ydist=y1-y2; + stipple_dist2 = stipple_dist / 2; + if ( abs(xdist^2 + ydist^2) < stipple_dist2^2 ) return; + if(xdist < 0) xdist=-xdist; + if(ydist < 0) ydist=-ydist; + mv=0; if(ydist > xdist) mv = ydist; else mv = xdist; + x = x1; y = y1; + stepx = xdist/mv; if(x1 > x2) stepx = -stepx; + stepy = ydist/mv; if(y1 > y2) stepy = -stepy; + + for(nc=0; nc1+⊢)⊢ + ⎕←'First 50 Duffinian numbers:' + ⎕←5 10⍴(⊢(/⍨)duff¨)⍳220 + ⎕←'First 15 Duffinian triplets:' + ⎕←(0 1 2∘.+⍨⊢(/⍨)0 1 2(⊃∧.⌽)(⊂duff¨))⍳8500 +} diff --git a/Task/Duffinian-numbers/BCPL/duffinian-numbers.bcpl b/Task/Duffinian-numbers/BCPL/duffinian-numbers.bcpl new file mode 100644 index 0000000000..ce5c01c911 --- /dev/null +++ b/Task/Duffinian-numbers/BCPL/duffinian-numbers.bcpl @@ -0,0 +1,45 @@ +get "libhdr" + +let calcsigmas(sig, n) be +$( sig!0 := 0 + for i = 0 to n do sig!i := 0 + for i = 1 to n/2 do + $( let j = i + while 0 < j <= n do + $( sig!j := sig!j + i + j := j + i + $) + $) +$) + +let gcd(m, n) = n=0 -> m, gcd(n, m rem n) + +let duff(sig, n) = sig!n > n+1 & gcd(n, sig!n) = 1 +let triple(sig, n) = duff(sig, n) & duff(sig, n+1) & duff(sig, n+2) + +let first(sig, f, max, cb) be +$( let n = 0 + for i = 1 to max + $( n := n+1 repeatuntil f(sig, n) + cb(i, n) + $) +$) + +let start() be +$( let showsingle(i, n) be + $( writef("%I4", n) + if i rem 10=0 then wrch('*N') + $) + + let showtriple(i, n) be writef("%I2: %I6 %I6 %I6*N", i, n, n+1, n+2) + + let sig = getvec(20000) + calcsigmas(sig, 20000) + + writes("First 50 Duffinian numbers:*N") + first(sig, duff, 50, showsingle) + + writes("*NFirst 15 Duffinian triples:*N") + first(sig, triple, 15, showtriple) + freevec(sig) +$) diff --git a/Task/Duffinian-numbers/Draco/duffinian-numbers.draco b/Task/Duffinian-numbers/Draco/duffinian-numbers.draco new file mode 100644 index 0000000000..a2732a600e --- /dev/null +++ b/Task/Duffinian-numbers/Draco/duffinian-numbers.draco @@ -0,0 +1,58 @@ +word MAXSIGMA = 10000; +[MAXSIGMA+1]word sigma; + +proc calcsigma() void: + word i, j; + for i from 0 upto MAXSIGMA do sigma[i] := 0 od; + for i from 1 upto MAXSIGMA do + for j from i by i upto MAXSIGMA do + sigma[j] := sigma[j] + i + od + od +corp + +proc gcd(word a, b) word: + word c; + while b > 0 do + c := a % b; + a := b; + b := c; + od; + a +corp + +proc duff(word n) bool: + sigma[n] > n+1 and gcd(n, sigma[n]) = 1 +corp + +proc triplet(word n) bool: + duff(n) and duff(n+1) and duff(n+2) +corp + +proc first(word n; proc(word n)bool pred; proc(word i,n)void cb) void: + word i, cur; + cur := 0; + for i from 1 upto n do + while cur := cur + 1; not pred(cur) do od; + cb(i, cur) + od +corp + +proc tablenum(word i, n) void: + write(n:5); + if i%10 = 0 then writeln() fi +corp + +proc tripletline(word i, n) void: + writeln(i:2, ' ', n:6, n+1:6, n+2:6) +corp + +proc main() void: + calcsigma(); + writeln("First 50 Duffinian numbers:"); + first(50, duff, tablenum); + writeln(); + + writeln("First 15 Duffinian triplets:"); + first(15, triplet, tripletline) +corp diff --git a/Task/Duffinian-numbers/FutureBasic/duffinian-numbers.basic b/Task/Duffinian-numbers/FutureBasic/duffinian-numbers.basic index e90088f53d..9a313e155a 100644 --- a/Task/Duffinian-numbers/FutureBasic/duffinian-numbers.basic +++ b/Task/Duffinian-numbers/FutureBasic/duffinian-numbers.basic @@ -34,7 +34,7 @@ end fn = result local fn IsDuffinian( n as NSUInteger) as BOOL BOOL result = NO - if ( fn IsPrime(n) == NO and fn GCD( fn SumDiv(n), n ) == 1 ) then exit fn = YES + if ( fn IsPrime(n) == NO && fn GCD( fn SumDiv(n), n ) == 1 ) then exit fn = YES end fn = result local fn FindDuffinians diff --git a/Task/Duffinian-numbers/MAD/duffinian-numbers.mad b/Task/Duffinian-numbers/MAD/duffinian-numbers.mad new file mode 100644 index 0000000000..d665371ab0 --- /dev/null +++ b/Task/Duffinian-numbers/MAD/duffinian-numbers.mad @@ -0,0 +1,51 @@ + NORMAL MODE IS INTEGER + DIMENSION SIGMA(10000),OUTROW(10) + + INTERNAL FUNCTION(AA,BB) + ENTRY TO GCD. + A = AA + B = BB +STEP WHENEVER A.E.B, FUNCTION RETURN A + WHENEVER A.G.B, A = A-B + WHENEVER A.L.B, B = B-A + TRANSFER TO STEP + END OF FUNCTION + + INTERNAL FUNCTION(N) + ENTRY TO DUFF. + SIG = SIGMA(N) + FUNCTION RETURN SIG.G.N+1 .AND. GCD.(N,SIG).E.1 + END OF FUNCTION + + INTERNAL FUNCTION(N) + ENTRY TO TRIP. + FUNCTION RETURN DUFF.(N) .AND. + 0 DUFF.(N+1) .AND. DUFF.(N+2) + END OF FUNCTION + + THROUGH SZERO, FOR I=1, 1, I.G.10000 +SZERO SIGMA(I) = 0 + THROUGH SCALC, FOR I=1, 1, I.G.10000 + THROUGH SCALC, FOR J=I, I, J.G.10000 +SCALC SIGMA(J) = SIGMA(J) + I + + PRINT COMMENT $ FIRST 50 DUFFINIAN NUMBERS$ + CAND = 0 + THROUGH DUFROW, FOR R=0, 1, R.GE.5 + THROUGH DUFCOL, FOR C=0, 1, C.GE.10 +SCHDUF THROUGH SCHDUF, FOR CAND=CAND+1, 1, DUFF.(CAND) +DUFCOL OUTROW(C) = CAND +DUFROW PRINT FORMAT ROWFMT,OUTROW(0),OUTROW(1),OUTROW(2), + 0 OUTROW(3),OUTROW(4),OUTROW(5),OUTROW(6), + 1 OUTROW(7),OUTROW(8),OUTROW(9) + + PRINT COMMENT $ $ + PRINT COMMENT $ FIRST 15 DUFFINIAN TRIPLETS$ + CAND = 0 + THROUGH DUFTRI, FOR S=0, 1, S.GE.15 +SCHTRP THROUGH SCHTRP, FOR CAND=CAND+1, 1, TRIP.(CAND) +DUFTRI PRINT FORMAT TRIFMT,CAND,CAND+1,CAND+2 + + VECTOR VALUES ROWFMT = $10(I5)*$ + VECTOR VALUES TRIFMT = $3(I7)*$ + END OF PROGRAM diff --git a/Task/Duffinian-numbers/Modula-2/duffinian-numbers.mod2 b/Task/Duffinian-numbers/Modula-2/duffinian-numbers.mod2 new file mode 100644 index 0000000000..f6d06d3784 --- /dev/null +++ b/Task/Duffinian-numbers/Modula-2/duffinian-numbers.mod2 @@ -0,0 +1,69 @@ +MODULE DuffinianNumbers; +FROM InOut IMPORT WriteCard, WriteString, WriteLn; + +CONST + MaxSigma = 10000; + +VAR + seen, cur: CARDINAL; + sigma: ARRAY [1..MaxSigma] OF CARDINAL; + +PROCEDURE CalculateSigmaTable; + VAR i, j: CARDINAL; +BEGIN + FOR i := 1 TO MaxSigma DO + sigma[i] := 0 + END; + FOR i := 1 TO MaxSigma DO + j := i; + WHILE j <= MaxSigma DO + INC(sigma[j], i); + INC(j, i); + END + END +END CalculateSigmaTable; + +PROCEDURE GCD(a, b: CARDINAL): CARDINAL; + VAR c: CARDINAL; +BEGIN + WHILE b # 0 DO + c := a MOD b; + a := b; + b := c + END; + RETURN a +END GCD; + +PROCEDURE IsDuffinian(n: CARDINAL): BOOLEAN; +BEGIN + RETURN (sigma[n] > n+1) AND (GCD(n, sigma[n]) = 1) +END IsDuffinian; + +PROCEDURE IsDuffinianTriple(n: CARDINAL): BOOLEAN; +BEGIN + RETURN IsDuffinian(n) AND IsDuffinian(n+1) AND IsDuffinian(n+2) +END IsDuffinianTriple; + +BEGIN + CalculateSigmaTable; + WriteString("First 50 Duffinian numbers:"); + WriteLn; + cur := 0; + FOR seen := 1 TO 50 DO + REPEAT INC(cur) UNTIL IsDuffinian(cur); + WriteCard(cur, 4); + IF seen MOD 10 = 0 THEN WriteLn END + END; + + WriteLn; + WriteString("First 15 Duffinian triples:"); + WriteLn; + cur := 0; + FOR seen := 1 TO 15 DO + REPEAT INC(cur) UNTIL IsDuffinianTriple(cur); + WriteCard(cur, 6); + WriteCard(cur+1, 6); + WriteCard(cur+2, 6); + WriteLn + END +END DuffinianNumbers. diff --git a/Task/Duffinian-numbers/PL-I/duffinian-numbers.pli b/Task/Duffinian-numbers/PL-I/duffinian-numbers.pli new file mode 100644 index 0000000000..d23d50c2bd --- /dev/null +++ b/Task/Duffinian-numbers/PL-I/duffinian-numbers.pli @@ -0,0 +1,58 @@ +duffinianNumbers: procedure options(main); + %replace MAXSIGMA by 10000; + declare sigma (1:MAXSIGMA) fixed; + + calculateSigmaTable: procedure; + declare (i, j) fixed; + do i=1 to MAXSIGMA; + sigma(i) = 0; + end; + do i=1 to MAXSIGMA; + do j=i to MAXSIGMA by i; + sigma(j) = sigma(j) + i; + end; + end; + end calculateSigmaTable; + + gcd: procedure(aa,bb) returns(fixed); + declare (a, aa, b, bb, c) fixed; + a = aa; + b = bb; + do while(b > 0); + c = mod(a,b); + a = b; + b = c; + end; + return(a); + end gcd; + + duffinian: procedure(n) returns(bit); + declare n fixed; + return(sigma(n) > n+1 & gcd(n, sigma(n)) = 1); + end duffinian; + + triplet: procedure(n) returns(bit); + declare n fixed; + return(duffinian(n) & duffinian(n+1) & duffinian(n+2)); + end triplet; + + declare (i, n) fixed; + + call calculateSigmaTable; + put skip list('First 50 Duffinian numbers:'); + put skip; + n=0; + do i=1 to 50; + do n=n+1 repeat(n+1) while(^duffinian(n)); end; + put edit(n) (F(5)); + if mod(i,10) = 0 then put skip; + end; + + put skip; + put skip list('First 15 Duffinian triplets:'); + n=0; + do i=1 to 15; + do n=n+1 repeat(n+1) while(^triplet(n)); end; + put skip edit(n, n+1, n+2) (F(7),F(7),F(7)); + end; +end duffinianNumbers; diff --git a/Task/Duffinian-numbers/PL-M/duffinian-numbers.plm b/Task/Duffinian-numbers/PL-M/duffinian-numbers.plm new file mode 100644 index 0000000000..0e3eeefe87 --- /dev/null +++ b/Task/Duffinian-numbers/PL-M/duffinian-numbers.plm @@ -0,0 +1,80 @@ +100H: +BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS; +EXIT: PROCEDURE; GO TO 0; END EXIT; +PR$CHAR: PROCEDURE (C); DECLARE C BYTE; CALL BDOS(2,C); END PR$CHAR; +PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT; + +PR$NUM: PROCEDURE (N, WIDTH); + DECLARE N ADDRESS, WIDTH BYTE; + DECLARE S (6) BYTE INITIAL ('.....$'); + DECLARE P ADDRESS, DG BASED P BYTE; + P = .S(5); +DIGIT: + P = P - 1; + DG = '0' + N MOD 10; + IF WIDTH > 0 THEN WIDTH = WIDTH - 1; + IF (N := N / 10) > 0 THEN GO TO DIGIT; + CALL PRINT(P); + DO WHILE WIDTH > 0; + CALL PR$CHAR(' '); + WIDTH = WIDTH - 1; + END; +END PR$NUM; + +DECLARE MAX$SIGMA LITERALLY '10$001'; +DECLARE SIGMA (MAX$SIGMA) ADDRESS; +CALC$SIGMA: PROCEDURE; + DECLARE (I, J) ADDRESS; + DO I = 1 TO MAX$SIGMA-1; + SIGMA(I) = 0; + END; + DO I = 1 TO MAX$SIGMA-1; + DO J = I TO MAX$SIGMA-1 BY I; + SIGMA(J) = SIGMA(J) + I; + END; + END; +END CALC$SIGMA; + +GCD: PROCEDURE (X, Y) ADDRESS; + DECLARE (X, Y, Z) ADDRESS; + DO WHILE Y > 0; + Z = X MOD Y; + X = Y; + Y = Z; + END; + RETURN X; +END GCD; + +DUFF: PROCEDURE (N) BYTE; + DECLARE N ADDRESS; + RETURN SIGMA(N) > N+1 AND GCD(N, SIGMA(N)) = 1; +END DUFF; + +DUFF$TRIPLE: PROCEDURE (N) BYTE; + DECLARE N ADDRESS; + RETURN DUFF(N) AND DUFF(N+1) AND DUFF(N+2); +END DUFF$TRIPLE; + +DECLARE N ADDRESS, I BYTE; + +CALL CALC$SIGMA; +CALL PRINT(.('FIRST 50 DUFFINIAN NUMBERS:',13,10,'$')); +N = 0; +DO I = 1 TO 50; + DO WHILE NOT DUFF(N := N+1); END; + CALL PR$NUM(N, 4); + IF I MOD 10 = 0 THEN CALL PRINT(.(13,10,'$')); +END; + +CALL PRINT(.(13,10,'FIRST 15 DUFFINIAN TRIPLES:',13,10,'$')); +N = 0; +DO I = 1 TO 15; + DO WHILE NOT DUFF$TRIPLE(N := N+1); END; + CALL PR$NUM(N, 6); + CALL PR$NUM(N+1, 6); + CALL PR$NUM(N+2, 6); + CALL PRINT(.(13,10,'$')); +END; + +CALL EXIT; +EOF diff --git a/Task/Duffinian-numbers/Python/duffinian-numbers.py b/Task/Duffinian-numbers/Python/duffinian-numbers.py new file mode 100644 index 0000000000..e27a0586d0 --- /dev/null +++ b/Task/Duffinian-numbers/Python/duffinian-numbers.py @@ -0,0 +1,30 @@ +# duffinian.py by xing216 + +def factors(n): + factors = [] + for i in range(1, n + 1): + if n % i == 0: + factors.append(i) + return factors +def gcd(a, b): + while b != 0: + a, b = b, a % b + return a +is_relively_prime = lambda a, b: gcd(a, b) == 1 +sigma_sum = lambda x: sum(factors(x)) +is_duffinian = lambda x: is_relively_prime(x, sigma_sum(x)) and len(factors(x)) > 2 +count = 0 +i = 0 +while count < 50: + if is_duffinian(i): + print(i, end=' ') + count += 1 + i+=1 +count2 = 0 +j = 0 +while count2 < 20: + if is_duffinian(j) and is_duffinian(j+1) and is_duffinian(j+2): + print(f"({j},{j+1},{j+2})", end=' ') + count2 += 1 + j+=3 + j+=1 diff --git a/Task/Duffinian-numbers/Ruby/duffinian-numbers.rb b/Task/Duffinian-numbers/Ruby/duffinian-numbers.rb new file mode 100644 index 0000000000..e20e2fdf47 --- /dev/null +++ b/Task/Duffinian-numbers/Ruby/duffinian-numbers.rb @@ -0,0 +1,30 @@ +require "prime" + +class Integer + + def proper_divisors(prim_div = prime_division) + return [] if self == 1 + primes = prim_div.flat_map{|prime, freq| [prime] * freq} + (1...primes.size).each_with_object([1]) do |n, res| + primes.combination(n).map{|combi| res << combi.inject(:*)} + end.flatten.uniq + end + + def duffinian? + pd = prime_division + return false if pd.sum(&:last) < 2 + gcd(proper_divisors(pd).sum + self) == 1 + end + +end + +n = 50 +puts "The first #{n} Duffinian numbers:" +(1..).lazy.select(&:duffinian?).first(n).each_slice(10) do |slice| + puts "%4d" * slice.size % slice +end + +puts "\nThe first #{n} Duffinian triplets:" +(1..).each_cons(3).lazy.select{|slice| slice.all?(&:duffinian?)}.first(n).each do |group| + puts "%8d" * group.size % group +end diff --git a/Task/Dynamic-variable-names/Wren/dynamic-variable-names.wren b/Task/Dynamic-variable-names/Wren/dynamic-variable-names.wren index 19260ccddb..c2926585e1 100644 --- a/Task/Dynamic-variable-names/Wren/dynamic-variable-names.wren +++ b/Task/Dynamic-variable-names/Wren/dynamic-variable-names.wren @@ -1,18 +1,14 @@ -import "io" for Stdin, Stdout +import "./ioutil" for Input +import "./trait" for Var -var userVars = {} System.print("Enter three variables:") for (i in 0..2) { - System.write("\n name : ") - Stdout.flush() - var name = Stdin.readLine() - System.write(" value: ") - Stdout.flush() - var value = Num.fromString(Stdin.readLine()) - userVars[name] = value + var name = Input.text("\n name : ") + var value = Input.text(" value : ") + Var[name] = Num.fromString(value) } System.print("\nYour variables are:\n") -for (kv in userVars) { +for (kv in Var.entries) { System.print(" %(kv.key) = %(kv.value)") } diff --git a/Task/Elliptic-Curve-Digital-Signature-Algorithm/00-TASK.txt b/Task/Elliptic-Curve-Digital-Signature-Algorithm/00-TASK.txt index 2f174c1b58..fa956941e4 100644 --- a/Task/Elliptic-Curve-Digital-Signature-Algorithm/00-TASK.txt +++ b/Task/Elliptic-Curve-Digital-Signature-Algorithm/00-TASK.txt @@ -1,7 +1,7 @@ ;Elliptic curves. An [[wp:Elliptic_curve|elliptic curve]] E over ℤp (p ≥ 5) is defined by an equation of the form -'''y^2 = x^3 + ax + b''', where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), +'''y²= x³ + ax + b''', where a, b ∈ ℤp and the discriminant ≢ 0 (mod p), together with a special point 𝒪 called the point at infinity. The set '''E(ℤp)''' consists of all points (x, y), with x, y ∈ ℤp, which satisfy the above defining equation, together with 𝒪. diff --git a/Task/Elliptic-Curve-Digital-Signature-Algorithm/C++/elliptic-curve-digital-signature-algorithm.cpp b/Task/Elliptic-Curve-Digital-Signature-Algorithm/C++/elliptic-curve-digital-signature-algorithm.cpp new file mode 100644 index 0000000000..54e05b8357 --- /dev/null +++ b/Task/Elliptic-Curve-Digital-Signature-Algorithm/C++/elliptic-curve-digital-signature-algorithm.cpp @@ -0,0 +1,300 @@ +#include +#include +#include +#include +#include +#include +#include + +const int32_t MAX_MODULUS = 1073741789; +const int32_t MAX_ORDER_G = MAX_MODULUS + 65536; + +std::random_device random; +std::mt19937 generator(random()); +std::uniform_real_distribution distribution(0.0F, 1.0F); + +class Point { +public: + Point(const int64_t& x, const int64_t& y) : x(x), y(y) {} + + Point() : x(0),y(0) {} + + bool isZero() { + return x == INT64_MAX && y == 0; + } + + int64_t x, y; +}; + +const Point ZERO_POINT(INT64_MAX, 0); + +class Pair { +public: + Pair(const int64_t& a, const int64_t& b) : a(a), b(b) {} + + const int64_t a, b; +}; + +class Parameter { +public: + Parameter(const int64_t& a, const int64_t& b, const int64_t& n, const Point& g, const int64_t& r) + : a(a), b(b), n(n), g(g), r(r) {} + + const int64_t a, b, n; + const Point g; + const int64_t r; +}; + +int64_t signum(const int64_t& x) { + return ( x < 0 ) ? -1 : ( x > 0 ) ? 1 : 0; +} + +int64_t floor_mod(const int64_t& num, const int64_t& mod) { + const int64_t signs = ( signum(num % mod) == -signum(mod) ) ? 1 : 0; + return ( num % mod ) + signs * mod; +} + +int64_t floor_div(const int64_t& number, const int64_t& modulus) { + const int32_t signs = ( signum(number % modulus) == -signum(modulus) ) ? 1 : 0; + return ( number / modulus ) - signs; +} + +// Return 1 / aV modulus aU +int64_t extended_GCD(int64_t v, int64_t u) { + if ( v < 0 ) { + v += u; + } + + int64_t result = 0; + int64_t s = 1; + while ( v != 0 ) { + const int64_t quotient = floor_div(u, v); + u = floor_mod(u, v); + std::swap(u, v); + result -= quotient * s; + std::swap(result, s); + } + + if ( u != 1 ) { + throw std::runtime_error("Cannot inverse modulo N, gcd = " + u); + } + return result; +} + +class Elliptic_Curve { +public: + Elliptic_Curve(const Parameter& parameter) { + n = parameter.n; + if ( n < 5 || n > MAX_MODULUS ) { + throw std::invalid_argument("Invalid value for modulus: " + n); + } + + a = floor_mod(parameter.a, n); + b = floor_mod(parameter.b, n); + g = parameter.g; + r = parameter.r; + + if ( r < 5 || r > MAX_ORDER_G ) { + throw std::invalid_argument("Invalid value for the order of g: " + r); + } + + std::cout << std::endl; + std::cout << "Elliptic curve: y^2 = x^3 + " << a << "x + " << b << " (mod " << n << ")" << std::endl; + print_point_with_prefix(g, "base point G"); + std::cout << "order(G, E) = " << r << std::endl; + } + + Point add(Point p, Point q) { + if ( p.isZero() ) { + return q; + } + if ( q.isZero() ) { + return p; + } + + int64_t la; + if ( p.x != q.x ) { + la = floor_mod(( p.y - q.y ) * extended_GCD(p.x - q.x, n), n); + } else if ( p.y == q.y && p.y != 0 ) { + la = floor_mod(floor_mod(floor_mod(p.x * p.x, n) * 3 + a, n) * extended_GCD(2 * p.y, n), n); + } else { + return ZERO_POINT; + } + + const int64_t x_coord = floor_mod(la * la - p.x - q.x, n); + const int64_t y_coord = floor_mod(la * ( p.x - x_coord ) - p.y, n); + return Point(x_coord, y_coord); + } + + Point multiply(Point point, int64_t k) { + Point result = ZERO_POINT; + + while ( k != 0 ) { + if ( ( k & 1 ) == 1 ) { + result = add(result, point); + } + point = add(point, point); + k >>= 1; + } + return result; + } + + bool contains(Point point) { + if ( point.isZero() ) { + return true; + } + + int64_t r = floor_mod(floor_mod(a + point.x * point.x, n) * point.x + b, n); + int64_t s = floor_mod(point.y * point.y, n); + return r == s; + } + + uint64_t discriminant() { + const int64_t constant = 4 * floor_mod(a * a, n) * floor_mod(a, n); + return floor_mod(-16 * ( floor_mod(b * b, n) * 27 + constant ), n); + } + + void print_point_with_prefix(Point point, const std::string& prefix) { + int64_t y = point.y; + if ( point.isZero() ) { + std::cout << prefix + " (0)" << std::endl; + } else { + if ( y > n - y ) { + y -= n; + } + std::cout << prefix + " (" << point.x << ", " << y << ")" << std::endl; + } + } + + int64_t a, b, n, r; + Point g; +}; + +double random_number() { + return distribution(generator); +} + +Pair signature(Elliptic_Curve curve, const int64_t& s, const int64_t& f) { + int64_t c, d, u; + Point v; + + while ( true ) { + while ( true ) { + u = 1 + (int64_t) ( random_number() * (double) ( curve.r - 1 ) ); + v = curve.multiply(curve.g, u); + c = floor_mod(v.x, curve.r); + if ( c != 0 ) { + break; + } + } + + d = floor_mod(extended_GCD(u, curve.r) * floor_mod(f + s * c, curve.r), curve.r); + if ( d != 0 ) { + break; + } + } + + std::cout << "one-time u = " << u << std::endl; + curve.print_point_with_prefix(v, "V = uG"); + return Pair(c, d); +} + +bool verify(Elliptic_Curve curve, Point point, const int64_t& f, const Pair& signature) { + if ( signature.a < 1 || signature.a >= curve.r || signature.b < 1 || signature.b >= curve.r ) { + return false; + } + + std::cout << "\n" << "signature verification" << std::endl; + const int64_t h = extended_GCD(signature.b, curve.r); + const int64_t h1 = floor_mod(f * h, curve.r); + const int64_t h2 = floor_mod(signature.a * h, curve.r); + std::cout << "h1, h2 = " << h1 << ", " << h2 << std::endl; + Point v = curve.multiply(curve.g, h1); + Point v2 = curve.multiply(point, h2); + curve.print_point_with_prefix(v, "h1G"); + curve.print_point_with_prefix(v2, "h2W"); + v = curve.add(v, v2); + curve.print_point_with_prefix(v, "+ ="); + + if ( v.isZero() ) { + return false; + } + int64_t c1 = floor_mod(v.x, curve.r); + std::cout << "c' = " << c1 << std::endl; + return c1 == signature.a; +} + +// Build the digital signature for a message using the hash aF with error bit aD +void ecdsa(Elliptic_Curve curve, int64_t f, int32_t d) { + Point point = curve.multiply(curve.g, curve.r); + + if ( curve.discriminant() == 0 || curve.g.isZero() || ! point.isZero() || ! curve.contains(curve.g) ) { + throw std::invalid_argument("Invalid parameter in the method ecdsa"); + } + + std::cout << "\n" << "key generation" << std::endl; + const int64_t s = 1 + (int64_t) ( random_number() * (double) ( curve.r - 1 ) ); + point = curve.multiply(curve.g, s); + std::cout << "private key s = " << s << std::endl; + curve.print_point_with_prefix(point, "public key W = sG"); + + // Find the next highest power of two minus one. + int64_t t = curve.r; + int64_t i = 1; + while ( i < 64 ) { + t |= t >> i; + i <<= 1; + } + while ( f > t ) { + f >>= 1; + } + std::cout << "\n" << "aligned hash " << std::hex << std::setfill('0') << std::setw(8) << f + << std::dec << std::endl; + + const Pair signature_pair = signature(curve, s, f); + std::cout << "signature c, d = " << signature_pair.a << ", " << signature_pair.b << std::endl; + + if ( d > 0 ) { + while ( d > t ) { + d >>= 1; + } + f ^= d; + std::cout << "\n" << "corrupted hash " << std::hex << std::setfill('0') << std::setw(8) << f + << std::dec << std::endl; + } + + std::cout << ( verify(curve, point, f, signature_pair) ? "Valid" : "Invalid" ) << std::endl; + std::cout << "-----------------" << std::endl; +} + +int main() { + // Test parameters for elliptic curve digital signature algorithm, + // using the short Weierstrass model: y^2 = x^3 + ax + b (mod N). + // + // Parameter: a, b, modulus N, base point G, order of G in the elliptic curve. + + const std::vector parameters { + Parameter( 355, 671, 1073741789, Point(13693, 10088), 1073807281 ), + Parameter( 0, 7, 67096021, Point( 6580, 779), 16769911 ), + Parameter( -3, 1, 877073, Point( 0, 1), 878159 ), + Parameter( 0, 14, 22651, Point( 63, 30), 151 ), + Parameter( 3, 2, 5, Point( 2, 1), 5 ) }; + + // Parameters which cause failure of the algorithm for the given reasons + // the base point is of composite order +// Parameter( 0, 7, 67096021, Point( 2402, 6067), 33539822 ), + // the given order is of composite order +// Parameter( 0, 7, 67096021, Point( 6580, 779), 67079644 ), + // the modulus is not prime (deceptive example) +// Parameter( 0, 7, 877069, Point( 3, 97123), 877069 ), + // fails if the modulus divides the discriminant +// Parameter( 39, 387, 22651, Point( 95, 27), 22651 ) ); + + const int64_t f = 0x789abcde; // The message's digital signature hash which is to be verified + const int32_t d = 0; // Set d > 0 to simulate corrupted data + + for ( const Parameter& parameter : parameters ) { + Elliptic_Curve elliptic_curve(parameter); + ecdsa(elliptic_curve, f, d); + } +} diff --git a/Task/Elliptic-Curve-Digital-Signature-Algorithm/Java/elliptic-curve-digital-signature-algorithm.java b/Task/Elliptic-Curve-Digital-Signature-Algorithm/Java/elliptic-curve-digital-signature-algorithm.java new file mode 100644 index 0000000000..529dde307b --- /dev/null +++ b/Task/Elliptic-Curve-Digital-Signature-Algorithm/Java/elliptic-curve-digital-signature-algorithm.java @@ -0,0 +1,278 @@ +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public final class EllipticCurveDigitalSignatureAlgorithm { + + public static void main(String[] aArgs) { + // Test parameters for elliptic curve digital signature algorithm, + // using the short Weierstrass model: y^2 = x^3 + ax + b (mod N). + // + // Parameter: a, b, modulus N, base point G, order of G in the elliptic curve. + + List parameters = List.of( + new Parameter( 355, 671, 1073741789, new Point(13693, 10088), 1073807281 ), + new Parameter( 0, 7, 67096021, new Point( 6580, 779), 16769911 ), + new Parameter( -3, 1, 877073, new Point( 0, 1), 878159 ), + new Parameter( 0, 14, 22651, new Point( 63, 30), 151 ), + new Parameter( 3, 2, 5, new Point( 2, 1), 5 ) ); + + // Parameters which cause failure of the algorithm for the given reasons + // the base point is of composite order +// new Parameter( 0, 7, 67096021, new Point( 2402, 6067), 33539822 ), + // the given order is of composite order +// new Parameter( 0, 7, 67096021, new Point( 6580, 779), 67079644 ), + // the modulus is not prime (deceptive example) +// new Parameter( 0, 7, 877069, new Point( 3, 97123), 877069 ), + // fails if the modulus divides the discriminant +// new Parameter( 39, 387, 22651, new Point( 95, 27), 22651 ) ); + + final long f = 0x789abcde; // The message's digital signature hash which is to be verified + final int d = 0; // Set d > 0 to simulate corrupted data + + for ( Parameter parameter : parameters ) { + EllipticCurve ellipticCurve = new EllipticCurve(parameter); + ecdsa(ellipticCurve, f, d); + } + } + + // Build the digital signature for a message using the hash aF with error bit aD + private static void ecdsa(EllipticCurve aCurve, long aF, int aD) { + Point point = aCurve.multiply(aCurve.g, aCurve.r); + + if ( aCurve.discriminant() == 0 || aCurve.g.isZero() || ! point.isZero() || ! aCurve.contains(aCurve.g) ) { + throw new AssertionError("Invalid parameter in method ecdsa"); + } + + System.out.println(System.lineSeparator() + "key generation"); + final long s = 1 + (long) ( random() * (double) ( aCurve.r - 1 ) ); + point = aCurve.multiply(aCurve.g, s); + System.out.println("private key s = " + s); + aCurve.printPointWithPrefix(point, "public key W = sG"); + + // Find the next highest power of two minus one. + long t = aCurve.r; + long i = 1; + while ( i < 64 ) { + t |= t >> i; + i <<= 1; + } + long f = aF; + while ( f > t ) { + f >>= 1; + } + System.out.println(System.lineSeparator() + "aligned hash " + String.format("%08x", f)); + + Pair signature = signature(aCurve, s, f); + System.out.println("signature c, d = " + signature.a + ", " + signature.b); + + long d = aD; + if ( d > 0 ) { + while ( d > t ) { + d >>= 1; + } + f ^= d; + System.out.println(System.lineSeparator() + "corrupted hash " + String.format("%08x", f)); + } + + System.out.println(verify(aCurve, point, f, signature) ? "Valid" : "Invalid"); + System.out.println("-----------------"); + } + + private static boolean verify(EllipticCurve aCurve, Point aPoint, long aF, Pair aSignature) { + if ( aSignature.a < 1 || aSignature.a >= aCurve.r || aSignature.b < 1 || aSignature.b >= aCurve.r ) { + return false; + } + + System.out.println(System.lineSeparator() + "signature verification"); + final long h = extendedGCD(aSignature.b, aCurve.r); + final long h1 = Math.floorMod(aF * h, aCurve.r); + final long h2 = Math.floorMod(aSignature.a * h, aCurve.r); + System.out.println("h1, h2 = " + h1 + ", " + h2); + Point v = aCurve.multiply(aCurve.g, h1); + Point v2 = aCurve.multiply(aPoint, h2); + aCurve.printPointWithPrefix(v, "h1G"); + aCurve.printPointWithPrefix(v2, "h2W"); + v = aCurve.add(v, v2); + aCurve.printPointWithPrefix(v, "+ ="); + + if ( v.isZero() ) { + return false; + } + long c1 = Math.floorMod(v.x, aCurve.r); + System.out.println("c' = " + c1); + return c1 == aSignature.a; + } + + private static Pair signature(EllipticCurve aCurve, long aS, long aF) { + long c = 0; + long d = 0; + long u; + Point v; + System.out.println("Signature computation"); + + while ( true ) { + while ( true ) { + u = 1 + (long) ( random() * (double) ( aCurve.r - 1 ) ); + v = aCurve.multiply(aCurve.g, u); + c = Math.floorMod(v.x, aCurve.r); + if ( c != 0 ) { + break; + } + } + + d = Math.floorMod(extendedGCD(u, aCurve.r) * Math.floorMod(aF + aS * c, aCurve.r), aCurve.r); + if ( d != 0 ) { + break; + } + } + + System.out.println("one-time u = " + u); + aCurve.printPointWithPrefix(v, "V = uG"); + return new Pair(c, d); + } + + // Return 1 / aV modulus aU + private static long extendedGCD(long aV, long aU) { + if ( aV < 0 ) { + aV += aU; + } + + long result = 0; + long s = 1; + while ( aV != 0 ) { + final long quotient = Math.floorDiv(aU, aV); + aU = Math.floorMod(aU, aV); + long temp = aU; aU = aV; aV = temp; + result -= quotient * s; + temp = result; result = s; s = temp; + } + + if ( aU != 1 ) { + throw new AssertionError("Cannot inverse modulo N, gcd = " + aU); + } + return result; + } + + private static double random() { + return RANDOM.nextDouble(); + } + + private static class EllipticCurve { + + public EllipticCurve(Parameter aParameter) { + n = aParameter.n; + if ( n < 5 || n > MAX_MODULUS ) { + throw new AssertionError("Invalid value for modulus: " + n); + } + + a = Math.floorMod(aParameter.a, n); + b = Math.floorMod(aParameter.b, n); + g = aParameter.g; + r = aParameter.r; + + if ( r < 5 || r > MAX_ORDER_G ) { + throw new AssertionError("Invalid value for the order of g: " + r); + } + + System.out.println(); + System.out.println("Elliptic curve: y^2 = x^3 + " + a + "x + " + b + " (mod " + n + ")"); + printPointWithPrefix(g, "base point G"); + System.out.println("order(G, E) = " + r); + } + + private Point add(Point aP, Point aQ) { + if ( aP.isZero() ) { + return aQ; + } + if ( aQ.isZero() ) { + return aP; + } + + long la; + if ( aP.x != aQ.x ) { + la = Math.floorMod(( aP.y - aQ.y ) * extendedGCD(aP.x - aQ.x, n), n); + } else if ( aP.y == aQ.y && aP.y != 0 ) { + la = Math.floorMod(Math.floorMod(Math.floorMod( + aP.x * aP.x, n) * 3 + a, n) * extendedGCD(2 * aP.y, n), n); + } else { + return Point.ZERO; + } + + final long xCoordinate = Math.floorMod(la * la - aP.x - aQ.x, n); + final long yCoordinate = Math.floorMod(la * ( aP.x - xCoordinate ) - aP.y, n); + return new Point(xCoordinate, yCoordinate); + } + + public Point multiply(Point aPoint, long aK) { + Point result = Point.ZERO; + + while ( aK != 0 ) { + if ( ( aK & 1 ) == 1 ) { + result = add(result, aPoint); + } + aPoint = add(aPoint, aPoint); + aK >>= 1; + } + return result; + } + + public boolean contains(Point aPoint) { + if ( aPoint.isZero() ) { + return true; + } + + final long r = Math.floorMod(Math.floorMod(a + aPoint.x * aPoint.x, n) * aPoint.x + b, n); + final long s = Math.floorMod(aPoint.y * aPoint.y, n); + return r == s; + } + + public long discriminant() { + final long constant = 4 * Math.floorMod(a * a, n) * Math.floorMod(a, n); + return Math.floorMod(-16 * ( Math.floorMod(b * b, n) * 27 + constant ), n); + } + + public void printPointWithPrefix(Point aPoint, String aPrefix) { + long y = aPoint.y; + if ( aPoint.isZero() ) { + System.out.println(aPrefix + " (0)"); + } else { + if ( y > n - y ) { + y -= n; + } + System.out.println(aPrefix + " (" + aPoint.x + ", " + y + ")"); + } + } + + private final long a, b, n, r; + private final Point g; + + } + + private static class Point { + + public Point(long aX, long aY) { + x = aX; + y = aY; + } + + public boolean isZero() { + return x == INFINITY && y == 0; + } + + private long x, y; + + private static final long INFINITY = Long.MAX_VALUE; + private static final Point ZERO = new Point(INFINITY, 0); + + } + + private static record Pair(long a, long b) {} + + private static record Parameter(long a, long b, long n, Point g, long r) {} + + private static final int MAX_MODULUS = 1073741789; + private static final int MAX_ORDER_G = MAX_MODULUS + 65536; + + private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current(); + +} diff --git a/Task/Elliptic-Curve-Digital-Signature-Algorithm/Raku/elliptic-curve-digital-signature-algorithm.raku b/Task/Elliptic-Curve-Digital-Signature-Algorithm/Raku/elliptic-curve-digital-signature-algorithm.raku index 468ad356b4..1bff057061 100644 --- a/Task/Elliptic-Curve-Digital-Signature-Algorithm/Raku/elliptic-curve-digital-signature-algorithm.raku +++ b/Task/Elliptic-Curve-Digital-Signature-Algorithm/Raku/elliptic-curve-digital-signature-algorithm.raku @@ -1,89 +1,101 @@ -use Digest::SHA256::Native; +module EC { + use FiniteField; -# Following data taken from the C entry -our (\A,\B,\P,\O,\Gx,\Gy) = (355, 671, 1073741789, 1073807281, 13693, 10088); + our class Point { + has ($.x, $.y); + submethod TWEAK { fail unless $!y**2 == $!x**3 + $*a*$!x + $*b } + multi method gist(::?CLASS:U:) { "Point at Horizon" } + multi method new($x, $y) { samewith :$x, :$y } + } + multi infix:<==>(Point:D $A, Point:D $B) is export { $A.x == $B.x and $A.y == $B.y } -#`{ Following data taken from the Julia entry; 256-bit; tested -our (\A,\B,\P,\O,\Gx,\Gy) = (0, 7, # https://en.bitcoin.it/wiki/Secp256k1 -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F, -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141, -0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, -0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8); # } + multi prefix:<->(Point $P) returns Point is export { Point.new: $P.x, -$P.y } + multi infix:<+>(Point $A, Point:U) is export { $A } + multi infix:<+>(Point:U, Point $B) is export { $B } + multi infix:<+>(Point:D $A, Point:D $B) returns Point is export { + my $λ; + if $A.x == $B.x and $A.y == -$B.y { return Point } + elsif $A == $B { + return Point if $A.y == 0; + $λ = (3*$A.x² + $*a) / (2*$A.y); + } + else { $λ = ($A.y - $B.y) / ($A.x - $B.x); } -role Horizon { method gist { 'EC Point at horizon' } } - -class Point { # modified from the Elliptic_curve_arithmetic entry - has ($.x, $.y); # handle modular arithmetic only - multi method new( \x, \y ) { self.bless(:x, :y) } - method gist { "EC Point at x=$.x, y=$.y" } - method isOn { modP(B + $.x * modP(A+$.x²)) == modP($.y²) } - sub modP ($a is copy) { ( $a %= P ) < 0 ?? ($a += P) !! $a } + given $λ**2 - $A.x - $B.x { + return Point.new: $_, $λ*($A.x - $_) - $A.y; + } + } + multi infix:<*>(0, Point ) is export { Point } + multi infix:<*>(1, Point $p) is export { $p } + multi infix:<*>(2, Point:D $p) is export { $p + $p } + multi infix:<*>(Int $n, Point $p) is export { 2*(($n div 2)*$p) + ($n mod 2)*$p } } -multi infix:<⊞>(Point \p, Point \q) { - my \λ = $; # slope - if p.x ~~ q.x and p.y ~~ q.y { - return Horizon if p.y == 0 ; - λ = (3*p.x²+ A) * mult_inv(2*p.y, :modulo(P)) - } else { - λ = (p.y - q.y) * mult_inv(p.x - q.x, :modulo(P)) - } - my \xr = (λ²- p.x - q.x); - my \yr = (λ*(p.x - xr) - p.y); - return Point.bless: x => xr % P, y => yr % P -} +import EC; -multi infix:<⊠>(Int \n, Point \p) { - return 0 if n == 0 ; - return p if n == 1 ; - return p ⊞ ((n-1) ⊠ p ) if n % 2 == 1 ; - return ( n div 2 ) ⊠ ( p ⊞ p ) -} - -sub mult_inv($n, :$modulo) { # rosettacode.org/wiki/Modular_inverse#Raku - my ($c, $d, $uc, $vd, $vc, $ud, $q) = $n % $modulo, $modulo, 1, 1, 0, 0, 0; - while $c != 0 { - ($q, $c, $d) = ($d div $c, $d % $c, $c); - ($uc, $vc, $ud, $vd) = ($ud - $q*$uc, $vd - $q*$vc, $uc, $vc); - } - return $ud % $modulo; -} - -class Signature { - - has ($.n, Point $.G); # Order and Generator point - - method generate_signature(Int \private_key, Str \msg) { - my \z = :16(sha256-hex msg) % $.n; # self ref: Blob.list.fmt("%02X",'') - loop ( my $k = my $s = my $r = 0 ; $s == 0 ; ) { - loop ( $r = $s = 0 ; $r == 0 ; ) { - $r = (( $k = (1..^$.n).roll ) ⊠ $.G).x % $.n; - } - $s = ((z + $r*private_key) * mult_inv $k, :modulo($.n)) % $.n; +module ECDSA { + use Digest::SHA256::Native; + our class Signature { + has UInt ($.c, $.d); + multi method new(Str $message, UInt :$private-key) { + my $z = :16(sha256-hex $message) % $*n; + loop (my $k = my $s = my $r = 0; $r == 0; ) { + loop ( $r = $s = 0 ; $r == 0 ; ) { + $r = (( $k = (1..^$*n).roll ) * $*G).x % $*n; + } + { + use FiniteField; my $*modulus = $*n; + $s = ($z + $r*$private-key) / $k; + } } - return $r, $s, private_key ⊠ $.G ; - } - - method verify_signature(\msg, \r, \s, \public_key) { - my \z = :16(sha256-hex msg) % $.n; - my \w = mult_inv s, :modulo($.n); - my (\u1,\u2) = (z*w, r*w).map: { $_ % $.n } - my \p = (u1 ⊠ $.G ) ⊞ (u2 ⊠ public_key); - return (p.x % $.n) == (r % $.n) - } + samewith c => $r, d => $s; + } + multi method verify(Str $message, EC::Point :$public-key) { + my $z = :16(sha256-hex $message) % $*n; + my ($u1, $u2); + { + use FiniteField; + my $*modulus = $*n; + my $w = 1/$!d; + ($u1, $u2) = $z*$w, $!c*$w; + } + my $p = ($u1 * $*G) + ($u2 * $public-key); + die unless ($p.x mod $*n) == ($!c mod $*n); + } + } } -print "The Curve E is : "; -"𝑦² = 𝑥³ + %s 𝑥 + %s (mod %s) \n".printf(A,B,P); -"with Generator G at : (%s,%s)\n".printf(Gx,Gy); -my $ec = Signature.new: n => O, G => Point.new: x => Gx, y => Gy ; -say "Order(G, E) is : ", O; -say "Is G ∈ E ? : ", $ec.G.isOn; -say "Message : ", my \message = "Show me the monKey"; -say "The private key dA is : ", my \dA = (1..^O).roll; -my ($r, $s, \Qa) = $ec.generate_signature(dA, message); -say "The public key Qa is : ", Qa; -say "Is Qa ∈ E ? : ", Qa.isOn; -say "Is signature valid? : ", $ec.verify_signature(message, $r, $s, Qa); -say "Message (Tampered) : ", my \altered = "Show me the money"; -say "Is signature valid? : ", $ec.verify_signature(altered, $r, $s, Qa) +my ($*a, $*b) = 355, 671; +my $*modulus = my $*p = 1073741789; + +my $*G = EC::Point.new: 13693, 10088; +my $*n = 1073807281; + +die "G is not of order n" if $*n*$*G; + +my $private-key = ^$*n .pick; +my $public-key = $private-key*$*G; + +my $message = "Show me the monKey"; +my $signature = ECDSA::Signature.new: $message, :$private-key; + +printf "The curve E is : 𝑦² = 𝑥³ + %s 𝑥 + %s (mod %s)\n", $*a, $*b, $*p; +printf "with generator G at : (%s, %s)\n", $*G.x, $*G.y; +printf "G's order is : %d\n", $*n; +printf "The private key is : %d\n", $private-key; +printf "The public key is at : (%s, %s)\n", $public-key.x, $public-key.y; +printf "The message is : %s\n", $message; +printf "The signature is : (%s, %s)\n", $signature.c, $signature.d; + +{ + use Test; + + lives-ok { + $signature.verify: $message, :$public-key; + }, "good signature for <$message>"; + + my $altered = $message.subst(/monKey/, "money"); + dies-ok { + $signature.verify: $altered, :$public-key + }, "wrong signature for <$altered>"; +} diff --git a/Task/Elliptic-curve-arithmetic/Raku/elliptic-curve-arithmetic.raku b/Task/Elliptic-curve-arithmetic/Raku/elliptic-curve-arithmetic.raku index d3737225c2..d7277acd16 100644 --- a/Task/Elliptic-curve-arithmetic/Raku/elliptic-curve-arithmetic.raku +++ b/Task/Elliptic-curve-arithmetic/Raku/elliptic-curve-arithmetic.raku @@ -1,49 +1,53 @@ -unit module EC; -our ($A, $B) = (0, 7); +module EC { + our ($A, $B) = (0, 7); -role Horizon { method gist { 'EC Point at horizon' } } -class Point { + our class Point { has ($.x, $.y); multi method new( - $x, $y where $y**2 ~~ $x**3 + $A*$x + $B - ) { self.bless(:$x, :$y) } - multi method new(Horizon $) { self.bless but Horizon } - method gist { "EC Point at x=$.x, y=$.y" } -} + $x, $y where $y**2 == $x**3 + $A*$x + $B + ) { samewith :$x, :$y } + multi method gist { "EC Point at x=$.x, y=$.y" } + multi method gist(::?CLASS:U:) { 'Point at horizon' } + } -multi prefix:<->(Point $p) { Point.new: x => $p.x, y => -$p.y } -multi prefix:<->(Horizon $) { Horizon } -multi infix:<->(Point $a, Point $b) { $a + -$b } + multi prefix:<->(Point $p) is export { Point.new: x => $p.x, y => -$p.y } + multi prefix:<->(Point:U) is export { Point } + multi infix:<->(Point $a, Point $b) is export { $a + -$b } -multi infix:<+>(Horizon $, Point $p) { $p } -multi infix:<+>(Point $p, Horizon) { $p } + multi infix:<+>(Point:U $, Point $p) is export { $p } + multi infix:<+>(Point $p, Point:U) is export { $p } -multi infix:<*>(Point $u, Int $n) { $n * $u } -multi infix:<*>(Int $n, Horizon) { Horizon } -multi infix:<*>(0, Point) { Horizon } -multi infix:<*>(1, Point $p) { $p } -multi infix:<*>(2, Point $p) { + multi infix:<*>(Point $u, Int $n) is export { $n * $u } + multi infix:<*>(Int $n, Point:U) is export { Point } + multi infix:<*>(0, Point) is export { Point } + multi infix:<*>(1, Point $p) is export { $p } + multi infix:<*>(2, Point $p) is export { my $l = (3*$p.x**2 + $A) / (2 *$p.y); my $y = $l*($p.x - my $x = $l**2 - 2*$p.x) - $p.y; - $p.bless(:$x, :$y); -} -multi infix:<*>(Int $n where $n > 2, Point $p) { + $p.new(:$x, :$y); + } + multi infix:<*>(Int $n where $n > 2, Point $p) is export { 2 * ($n div 2 * $p) + $n % 2 * $p; -} + } -multi infix:<+>(Point $p, Point $q) { + multi infix:<+>(Point $p, Point $q) is export { if $p.x ~~ $q.x { - return $p.y ~~ $q.y ?? 2 * $p !! Horizon; + return $p.y ~~ $q.y ?? 2 * $p !! Point; } else { - my $slope = ($q.y - $p.y) / ($q.x - $p.x); - my $y = $slope*($p.x - my $x = $slope**2 - $p.x - $q.x) - $p.y; - return $p.new(:$x, :$y); + my $slope = ($q.y - $p.y) / ($q.x - $p.x); + my $y = $slope*($p.x - my $x = $slope**2 - $p.x - $q.x) - $p.y; + return $p.new(:$x, :$y); } + } + } -say my $p = Point.new: x => $_, y => sqrt(abs($_**3 + $A*$_ + $B)) given 1; -say my $q = Point.new: x => $_, y => sqrt(abs($_**3 + $A*$_ + $B)) given 2; +import EC; + +say my $p = EC::Point.new: x => $_, y => sqrt(abs($_**3 + $EC::A*$_ + $EC::B)) given 1; +say my $q = EC::Point.new: x => $_, y => sqrt(abs($_**3 + $EC::A*$_ + $EC::B)) given 2; say my $s = $p + $q; -say "checking alignment: ", abs ($p.x - $q.x)*(-$s.y - $q.y) - ($p.y - $q.y)*($s.x - $q.x); +use Test; +is abs(($p.x - $q.x)*(-$s.y - $q.y) - ($p.y - $q.y)*($s.x - $q.x)), 0, "S, P and Q are aligned"; diff --git a/Task/Equal-prime-and-composite-sums/Quackery/equal-prime-and-composite-sums.quackery b/Task/Equal-prime-and-composite-sums/Quackery/equal-prime-and-composite-sums.quackery new file mode 100644 index 0000000000..51ad69e76d --- /dev/null +++ b/Task/Equal-prime-and-composite-sums/Quackery/equal-prime-and-composite-sums.quackery @@ -0,0 +1,60 @@ + [ swap number$ + tuck size - + space swap of + swap join echo$ ] is r-echo ( n n --> $ ) + + [ stack ] is primecount ( --> s ) + [ stack ] is recentprime ( --> s ) + [ stack ] is primesum ( --> s ) + [ stack ] is compcount ( --> s ) + [ stack ] is recentcomp ( --> s ) + [ stack ] is compsum ( --> s ) + + [ recentprime take + [ 1+ dup isprime iff + [ 1 primecount tally + dup recentprime put + primesum tally ] + done + again ] ] is nextprime ( --> ) + + [ recentcomp take + [ 1+ dup isprime not iff + [ 1 compcount tally + dup recentcomp put + compsum tally ] + done + again ] ] is nextcomp ( --> ) + + 1 primecount put + 2 recentprime put + 2 primesum put + 1 compcount put + 4 recentcomp put + 4 compsum put + [] + [ primesum share + compsum share + 2dup > iff + [ 2drop nextcomp ] + again + < iff nextprime again + compsum share + primecount share + compcount share + join join nested join + dup size 7 < while + nextcomp + nextprime + again ] + primecount release + recentprime release + primesum release + compcount release + recentcomp release + compsum release + say " sum prime composite" cr + witheach + [ witheach + [ 11 r-echo ] + cr ] diff --git a/Task/Ethiopian-multiplication/Maxima/ethiopian-multiplication.maxima b/Task/Ethiopian-multiplication/Maxima/ethiopian-multiplication.maxima new file mode 100644 index 0000000000..a39f137c36 --- /dev/null +++ b/Task/Ethiopian-multiplication/Maxima/ethiopian-multiplication.maxima @@ -0,0 +1,16 @@ +/* Function to halve */ +halve(n):=floor(n/2)$ + +/* Function to double */ +double(n):=2*n$ + +/* Predicate function to check wether an integer is even */ +my_evenp(n):=if mod(n,2)=0 then true$ + +/* Function that implements ethiopian function using the three previously defined functions */ +ethiopian(n1,n2):=block(cn1:n1,cn2:n2,list_w:[], + while cn1>0 do (list_w:endcons(cn1,list_w),cn1:halve(cn1)), + n2_list:append([cn2],makelist(cn2:double(cn2),length(list_w)-1)), + sublist_indices(list_w,lambda([x],not my_evenp(x))), + makelist(n2_list[i],i,%%), + apply("+",%%))$ diff --git a/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java b/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java index cd1a31d838..0acc583224 100644 --- a/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java +++ b/Task/Euclid-Mullin-sequence/Java/euclid-mullin-sequence.java @@ -4,19 +4,19 @@ import java.util.BitSet; import java.util.List; import java.util.concurrent.ThreadLocalRandom; -public final class EulerMullinSequence { +public final class EuclidMullinSequence { public static void main(String[] aArgs) { primes = listPrimesUpTo(1_000_000); - System.out.println("The first 27 terms of the Euler-Mullin sequence:"); + System.out.println("The first 27 terms of the Euclid-Mullin sequence:"); System.out.print(2 + " "); for ( int i = 1; i < 27; i++ ) { - System.out.print(String.format("%s%s", nextEulerMullin(), ( i == 14 || i == 27 ) ? "\n" : " ")); + System.out.print(String.format("%s%s", nextEuclidMullin(), ( i == 14 || i == 27 ) ? "\n" : " ")); } } - private static BigInteger nextEulerMullin() { + private static BigInteger nextEuclidMullin() { BigInteger smallestPrime = smallestPrimeFactor(product.add(BigInteger.ONE)); product = product.multiply(smallestPrime); @@ -66,8 +66,7 @@ public final class EulerMullinSequence { BitSet sieve = new BitSet(aLimit + 1); sieve.set(2, aLimit + 1); - final int squareRoot = (int) Math.sqrt(aLimit); - for ( int i = 2; i <= squareRoot; i = sieve.nextSetBit(i + 1) ) { + for ( int i = 2; i * i <= aLimit; i = sieve.nextSetBit(i + 1) ) { for ( int j = i * i; j <= aLimit; j = j + i ) { sieve.clear(j); } diff --git a/Task/Events/FutureBasic/events.basic b/Task/Events/FutureBasic/events.basic new file mode 100644 index 0000000000..b1138f1074 --- /dev/null +++ b/Task/Events/FutureBasic/events.basic @@ -0,0 +1,5 @@ +timerbegin, 0.1, YES + cls : printf @"%@", time(@"h:mm:ss a zzz") +timerend + +HandleEvents diff --git a/Task/Evolutionary-algorithm/ALGOL-68/evolutionary-algorithm.alg b/Task/Evolutionary-algorithm/ALGOL-68/evolutionary-algorithm.alg index a3cf92424b..0c866fc0c9 100644 --- a/Task/Evolutionary-algorithm/ALGOL-68/evolutionary-algorithm.alg +++ b/Task/Evolutionary-algorithm/ALGOL-68/evolutionary-algorithm.alg @@ -34,7 +34,7 @@ PROC evolve = VOID: [100]FLEX[UPB target]CHAR kid; INT iters := 0; kid[LWB kid] := LOC[UPB target]CHAR; - REAL mutate rate; + REAL mutate rate = 0.05; # initialize # FOR i FROM LWB parent TO UPB parent DO @@ -42,10 +42,9 @@ PROC evolve = VOID: OD; fits := fitness(parent); - WHILE fits < 100.0 DO + WHILE INT j; REAL kf; - mutate rate := 1.0 - exp(- (100.0 - fits)/400.0); FOR j FROM LWB kid TO UPB kid DO mutate(kid[j], parent, mutate rate) OD; @@ -56,9 +55,9 @@ PROC evolve = VOID: parent := kid[j] FI OD; - IF iters MOD 100 = 0 THEN - kewe( parent, iters, fits, mutate rate ) - FI; + fits < 100.0 + DO + kewe( parent, iters, fits, mutate rate ); iters+:=1 OD; kewe( parent, iters, fits, mutate rate ) diff --git a/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm.js b/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-1.js similarity index 100% rename from Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm.js rename to Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-1.js diff --git a/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-2.js b/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-2.js new file mode 100644 index 0000000000..19c61c1e13 --- /dev/null +++ b/Task/Evolutionary-algorithm/JavaScript/evolutionary-algorithm-2.js @@ -0,0 +1,125 @@ +"use strict" +const TARGET = "METHINKS IT IS LIKE A WEASEL"; +const GENE_POOL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ '; +const C = 100; +const MUTATION_RATE = 0.3; + +function randomIdGenerator(length) { + return Math.floor(Math.random() * length); +} +function getGene() { + return GENE_POOL[randomIdGenerator(GENE_POOL.length)]; +} + +class Parent { + _arrayLength; + _genePool; + _geneGenerator; + + constructor(arrayLength, genePool, geneGenerator) { + if (typeof arrayLength === 'number' && arrayLength > 0) { + this._arrayLength = arrayLength; + } + + if (typeof genePool === 'string' && genePool.length > 0) { + this._genePool = [...genePool]; + } + + if (typeof geneGenerator === 'function') { + this._geneGenerator = geneGenerator; + } + } + generate() { + const letters = []; + + while (letters.length < this._arrayLength) { + letters.push(this._geneGenerator()); + } + + return letters.join(''); + } +} + +function fitness(needle, target) { + if (needle.length !== target.length) return 0; + + const needleArray = [...needle]; + let count = 0; + + [...target].forEach((item, index) => { + if (item === needleArray[index]) count++; + }); + + return count; +} + +function mutate({ source, mutationRate }) { + if (typeof source !== 'string' || source.length === 0) return ''; + const sourceLength = source.length; + const iterations = Math.floor(sourceLength * mutationRate); + const stringArray = [...source]; + + for(let i = 0; i < iterations; i++) { + const shouldReplace = Boolean(Math.floor(Math.random() * 2)); + + if(shouldReplace) { + const id = randomIdGenerator(sourceLength); + stringArray[id] = getGene(); + } + } + + return stringArray.join(''); +} + +function createMutants(parent, mutantNumber) { + const mutantArray = []; + + for (let i = 0; i < mutantNumber; i++) { + const mutant = mutate({source: parent, mutationRate: MUTATION_RATE}); + + mutantArray.push( + { + mutant, + fitness: fitness(mutant, TARGET), + }, + ); + } + + return mutantArray; +} + +function helperInit(parentString, parentFitness) { + const mutant = createMutants(parentString, C) + .sort( (a,b) => a.fitness - b.fitness ).pop(); + + if (mutant.fitness >= parentFitness) { + return { + string: mutant.mutant, + fitness: mutant.fitness, + }; + } + + return { + string: parentString, + fitness: parentFitness, + }; +} + +function run() { + const parent = new Parent(TARGET.length, GENE_POOL, getGene); + let parentString = parent.generate(); + let parentFitness = fitness(parentString, TARGET); + let genCount = 0; + + while(parentString !== TARGET) { + const init = helperInit(parentString, parentFitness); + parentString = init.string; + parentFitness = init.fitness; + console.log(init.string); + genCount++; + } + + console.log(`Ended in ${genCount} generations`); +} + +run(); diff --git a/Task/Execute-Computer-Zero/Jq/execute-computer-zero.jq b/Task/Execute-Computer-Zero/Jq/execute-computer-zero.jq new file mode 100644 index 0000000000..db6265f630 --- /dev/null +++ b/Task/Execute-Computer-Zero/Jq/execute-computer-zero.jq @@ -0,0 +1,75 @@ +### Utility +def trim: sub("^ +";"") | sub(" +$";""); + +### Computer/Zero +def NOP: 0; +def LDA: 1; +def STA: 2; +def ADD: 3; +def SUB: 4; +def BRZ: 5; +def JMP: 6; +def STP: 7; + +def ops: {"NOP": NOP, "LDA": LDA, "STA": STA, "ADD": ADD, + "SUB": SUB, "BRZ": BRZ, "JMP": JMP, "STP": STP}; + +# Input: the program in the form of an array of strings, +# each string corresponding to an input line of the form +# "INSTR N" or "N" +# Output: an array of integers +def load: + map([splits(" *")] as $split + | $split[0] as $instr + | (if ($split|length == 2) then $split[1]|tonumber + else 0 + end) as $addr + | if ops[$instr] + then ops[$instr] * 32 + $addr + else try ($instr|tonumber) catch 0 + end ); + +# input: an array as produced by `load` +def interp: + { acc: 0, pc: 0, mem: .} + | until(.break; + (.mem[.pc] % 32) as $addr + | ((.mem[.pc] - $addr) / 32) as $instr + | .pc += 1 + | if $instr == LDA then .acc = .mem[$addr] + elif $instr == STA then .mem[$addr] = .acc + elif $instr == ADD then .acc += .mem[$addr] + | if .acc > 255 then .acc += -256 else . end + elif $instr == SUB then .acc += (- .mem[$addr]) + | if .acc < 0 then .acc += 256 else . end + elif $instr == BRZ + then if .acc == 0 then .pc = $addr else . end + elif $instr == JMP then .pc = $addr + else . + end + | .break = $instr == STP or .pc > 31 ) + | .acc; + +# Assume the input file consists of several programs, each structured as: +# ; program name +# one instruction per line +# +def task: + def init: map_values(null); + + foreach (inputs, null) as $line ({}; + if $line == null then .program = .buffer + elif $line[0:1] == ";" then init | .title = $line + else ($line|trim) as $line + | if $line == "" then .program = .buffer | .buffer = [] + else .buffer += [$line] + end + end) + | .title as $title + | .program + | if length == 0 then empty + else + $title, (load|interp) + end ; + +task diff --git a/Task/Execute-a-system-command/FutureBasic/execute-a-system-command-1.basic b/Task/Execute-a-system-command/FutureBasic/execute-a-system-command-1.basic new file mode 100644 index 0000000000..ea3d5ec4ce --- /dev/null +++ b/Task/Execute-a-system-command/FutureBasic/execute-a-system-command-1.basic @@ -0,0 +1 @@ +print unix(@"ls -A") diff --git a/Task/Execute-a-system-command/FutureBasic/execute-a-system-command.basic b/Task/Execute-a-system-command/FutureBasic/execute-a-system-command-2.basic similarity index 80% rename from Task/Execute-a-system-command/FutureBasic/execute-a-system-command.basic rename to Task/Execute-a-system-command/FutureBasic/execute-a-system-command-2.basic index c2af16f1dd..2d7ac2df38 100644 --- a/Task/Execute-a-system-command/FutureBasic/execute-a-system-command.basic +++ b/Task/Execute-a-system-command/FutureBasic/execute-a-system-command-2.basic @@ -1,7 +1,5 @@ -include "ConsoleWindow" - local fn DoUnixCommand( cmd as str255 ) - dim as str255 s + str255 s open "Unix", 2, cmd while ( not eof(2) ) diff --git a/Task/Execute-a-system-command/FutureBasic/execute-a-system-command-3.basic b/Task/Execute-a-system-command/FutureBasic/execute-a-system-command-3.basic new file mode 100644 index 0000000000..f5c125ea63 --- /dev/null +++ b/Task/Execute-a-system-command/FutureBasic/execute-a-system-command-3.basic @@ -0,0 +1,39 @@ +include "NSLog.incl" + +// For remote uses like curl +// #plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES} + +local fn RunTerminalCommand( cmd as CFStringRef ) as CFStringRef +———————————————————————————————————————————————————————————————————————————————————————————————————— + ErrorRef err = NULL + CFStringRef outputStr = NULL + + TaskRef task = fn TaskInit + TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/zsh" ) ) + CFStringRef cmdStr = fn StringWithFormat( @"%@", cmd ) + CFArrayRef args = fn ArrayWithObjects( @"-c", cmdStr, NULL ) + TaskSetArguments( task, args ) + + PipeRef p = fn PipeInit + TaskSetStandardOutput( task, p ) + TaskSetStandardError( task, p ) + FileHandleRef fh = fn PipeFileHandleForReading( p ) + + fn TaskLaunch( task, NULL ) + TaskWaitUntilExit( task ) + + CFDataRef dta = fn FileHandleReadDataToEndOfFile( fh, @err ) + if err then NSLog( @"Error reading file: %@", fn ErrorLocalizedDescription( err ) ) : exit fn + + fn FileHandleClose( fh, @err ) + if err then NSLog( @"Error closing file: %@", fn ErrorLocalizedDescription( err ) ) : exit fn + + outputStr = fn StringWithData( dta, NSUTF8StringEncoding ) +end fn = outputStr + +CFStringRef cmd + +cmd = @"cal 2023" +NSLog( @"%@", fn RunTerminalCommand( cmd ) ) + +HandleEvents diff --git a/Task/Factorial/Insitux/factorial.insitux b/Task/Factorial/Insitux/factorial.insitux new file mode 100644 index 0000000000..9efd9c1e05 --- /dev/null +++ b/Task/Factorial/Insitux/factorial.insitux @@ -0,0 +1,3 @@ +(function factorial n + (return-when (< n 2) 1) + (... * (range 1 (inc n)))) diff --git a/Task/Factorial/LDPL/factorial.ldpl b/Task/Factorial/LDPL/factorial.ldpl new file mode 100644 index 0000000000..e5e0354fc6 --- /dev/null +++ b/Task/Factorial/LDPL/factorial.ldpl @@ -0,0 +1,22 @@ +data: +n is number + +procedure: +sub factorial + parameters: + n is number + result is number + local data: + i is number + m is number + procedure: + store 1 in result + in m solve n + 1 + for i from 1 to m step 1 do + multiply result by i in result + repeat +end sub +create statement "get factorial of $ in $" executing factorial + +get factorial of 5 in n +display n lf diff --git a/Task/Factorial/UNIX-Shell/factorial.sh b/Task/Factorial/UNIX-Shell/factorial.sh deleted file mode 100644 index f64f3b8b46..0000000000 --- a/Task/Factorial/UNIX-Shell/factorial.sh +++ /dev/null @@ -1,10 +0,0 @@ -factorial() -{ - if [ $1 -le 1 ] - then - echo 1 - else - result=$(factorial $[$1-1]) - echo $((result*$1)) - fi -} diff --git a/Task/Faulhabers-triangle/Maxima/faulhabers-triangle.maxima b/Task/Faulhabers-triangle/Maxima/faulhabers-triangle.maxima new file mode 100644 index 0000000000..b4e944ddf0 --- /dev/null +++ b/Task/Faulhabers-triangle/Maxima/faulhabers-triangle.maxima @@ -0,0 +1,21 @@ +faulhaber_fraction(n, k) := + if n = 0 and k = 1 then 1 + else if k >= 2 and k <= n + 1 then (n/k) * faulhaber_fraction(n-1, k-1) + else if k = 1 then 1 - sum(faulhaber_fraction(n, i), i, 2, n+1) + else 0; +faulhaber_row(n):=makelist(faulhaber_fraction(n,k),k,1,n+1); +/* Example */ +/* triangle_faulhaber_first_ten_rows:block(makelist(faulhaber_row(i),i,0,9),table_form(%%)); + matrix( + [1, , , , , , , , , ], + [1/2, 1/2, , , , , , , , ], + [1/6, 1/2, 1/3, , , , , , , ], + [0, 1/4, 1/2, 1/4, , , , , , ], + [-1/30, 0, 1/3, 1/2, 1/5, , , , , ], + [0, -1/12, 0, 5/12, 1/2, 1/6, , , , ], + [1/42, 0, -1/6, 0, 1/2, 1/2, 1/7, , , ], + [0, 1/12, 0, -7/24, 0, 7/12, 1/2, 1/8, , ], + [-1/30, 0, 2/9, 0, -7/15, 0, 2/3, 1/2, 1/9, ], + [0, -3/20, 0, 1/2, 0, -7/10, 0, 3/4, 1/2, 1/10] + ) +*/ diff --git a/Task/Feigenbaum-constant-calculation/Chipmunk-Basic/feigenbaum-constant-calculation.basic b/Task/Feigenbaum-constant-calculation/Chipmunk-Basic/feigenbaum-constant-calculation.basic new file mode 100644 index 0000000000..2caecba0c4 --- /dev/null +++ b/Task/Feigenbaum-constant-calculation/Chipmunk-Basic/feigenbaum-constant-calculation.basic @@ -0,0 +1,30 @@ +100 cls +110 mit = 13 +120 mitj = 13 +130 a1 = 1 +140 a2 = 0 +150 d = 0 +160 d1 = 3.2 +170 print "Feigenbaum constant calculation:" +180 print +190 print " i d" +200 print "===================" +210 for i = 2 to mit +220 a = a1+(a1-a2)/d1 +230 for j = 1 to mitj +240 x = 0 +250 y = 0 +260 for k = 1 to 2^i +270 y = 1-2*y*x +280 x = a-x*x +290 next k +300 a = a-(x/y) +310 next j +320 d = (a1-a2)/(a-a1) +330 print using "###";i;" "; +335 print using "##.#########";d +340 d1 = d +350 a2 = a1 +360 a1 = a +370 next i +380 end diff --git a/Task/Feigenbaum-constant-calculation/MSX-Basic/feigenbaum-constant-calculation.basic b/Task/Feigenbaum-constant-calculation/MSX-Basic/feigenbaum-constant-calculation.basic new file mode 100644 index 0000000000..065bb36b1f --- /dev/null +++ b/Task/Feigenbaum-constant-calculation/MSX-Basic/feigenbaum-constant-calculation.basic @@ -0,0 +1,29 @@ +100 CLS +110 mit = 13 +120 mitj = 13 +130 a1 = 1 +140 a2 = 0 +150 d = 0 +160 d1 = 3.2 +170 PRINT "Feigenbaum constant calculation:" +180 PRINT +190 PRINT " i d" +200 PRINT "===================" +210 FOR i = 2 TO mit +220 a = a1 + (a1 - a2) / d1 +230 FOR j = 1 TO mitj +240 x = 0 +250 y = 0 +260 FOR k = 1 TO 2 ^ i +270 y = 1 - 2 * y * x +280 x = a - x * x +290 NEXT k +300 a = a - (x / y) +310 NEXT j +320 d = (a1 - a2) / (a - a1) +330 PRINT USING "### ##.#########"; i; d +340 d1 = d +350 a2 = a1 +360 a1 = a +370 NEXT i +380 END diff --git a/Task/File-modification-time/FutureBasic/file-modification-time.basic b/Task/File-modification-time/FutureBasic/file-modification-time.basic new file mode 100644 index 0000000000..1402ef2ee5 --- /dev/null +++ b/Task/File-modification-time/FutureBasic/file-modification-time.basic @@ -0,0 +1,8 @@ +CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask ) +CFURLRef url = fn URLByAppendingPathComponent( desktopURL, @"file.txt" ) +CFDictionaryRef dict = fn FileManagerAttributesOfItemAtURL( url ) + +print dict[@NSFileModificationDate] // Read file's current date + +// Reset file date to current +fn FileManagerSetAttributesOfItemAtURL( CFURLRef url, @{NSFileModificationDate:fn DateNow ) diff --git a/Task/Find-if-a-point-is-within-a-triangle/Evaldraw/find-if-a-point-is-within-a-triangle.evaldraw b/Task/Find-if-a-point-is-within-a-triangle/Evaldraw/find-if-a-point-is-within-a-triangle.evaldraw new file mode 100644 index 0000000000..f76fa4ef4b --- /dev/null +++ b/Task/Find-if-a-point-is-within-a-triangle/Evaldraw/find-if-a-point-is-within-a-triangle.evaldraw @@ -0,0 +1,78 @@ +struct vec2{x,y;}; +struct line_t{a,b,c;}; +struct triangle_calc_t{ + vec2 origin; + line_t lines[3]; + vec2 vertices[3]; + double area2; + winding_dir; // +1 if clockwise (positive angle) -1 if negative. +}; +//static vec2 dat[3] = {0,-2, -2,2, 4,0}; +static vec2 dat[3] = {-3,7, -6,-5, 2,2}; +static triangle_calc_t tri; +enum{TRI_OUT=0, TRI_EDGE=1, TRI_INSIDE=2} +(x,y,t,&r,&g,&b) +{ + if (numframes==0) + { + precalc_tri( tri, dat); + } + + d0 = d1 = d2 = 0; + side = isPointInsideTriangle(x,y,tri,d0,d1,d2); + if (side == TRI_EDGE) { + r=255; g=255; b=0; + return 1; + } + else if (side == TRI_INSIDE) { + if (tri.winding_dir == -1) { + swap(d0,d1); + } + factor = 255; + div = tri.winding_dir * tri.area2; + r = factor*( d1 / div); + g = factor*( d2 / div); + b = factor*( d0 / div); + return 1; + } + r=0; g=0; b=0; return 0; // Set color to 0 if outside. +} + +precalc_tri(triangle_calc_t t, vec2 verts[3]) { + t.origin = verts[0]; + for(i=0; i<3; i++) { + t.vertices[i].x = verts[i].x + t.origin.x; + t.vertices[i].y = verts[i].y + t.origin.y; + } + makeLine(t.lines[0], t.vertices[0], t.vertices[1]); + makeLine(t.lines[1], t.vertices[1], t.vertices[2]); + makeLine(t.lines[2], t.vertices[2], t.vertices[0]); + t.area2 = areaTriangleX2(t.vertices[0], t.vertices[1], t.vertices[2]); + t.winding_dir = sgn(tri.area2); +} +areaTriangleX2(vec2 a, vec2 b, vec2 c) { // Same as the determinant, but dont div by 2 + s = c.x*(a.y-b.y)+a.x*(b.y-c.y)+b.x*(-a.y+c.y); +} +isPointInsideTriangle(x,y, triangle_calc_t t, &d0,&d1,&d2) { + vec2 p = {x + t.origin.x, y + t.origin.y }; + d0 = t.winding_dir * lineDist( t.lines[0], p.x, p.y); + if (d0==0) { return TRI_EDGE; }else if ( sgn(d0) < 0 ) return TRI_OUT; + + d1 = t.winding_dir * lineDist( t.lines[1], p.x, p.y); + if (d1==0) { return TRI_EDGE; } else if ( sgn(d1) < 0 ) return TRI_OUT; + + d2 = t.winding_dir * lineDist( t.lines[2], p.x, p.y); + if (d2==0) { return TRI_EDGE; } else if ( sgn(d2) < 0 ) return TRI_OUT; + + return TRI_INSIDE; // on inside +} + +makeLine(line_t line, vec2 a, vec2 b) { // -dy,dx,axby-aybx + line.a = -(b.y - a.y); + line.b = (b.x - a.x); + line.c = a.x*b.y - a.y*b.x; +} +lineDist(line_t line, x,y) { + x*line.a + y*line.b + line.c; +} +swap(&a,&b) {tmp = a; a=b; b=tmp; } diff --git a/Task/Find-if-a-point-is-within-a-triangle/FutureBasic/find-if-a-point-is-within-a-triangle.basic b/Task/Find-if-a-point-is-within-a-triangle/FutureBasic/find-if-a-point-is-within-a-triangle.basic index e6de7804fe..c3d22daa01 100644 --- a/Task/Find-if-a-point-is-within-a-triangle/FutureBasic/find-if-a-point-is-within-a-triangle.basic +++ b/Task/Find-if-a-point-is-within-a-triangle/FutureBasic/find-if-a-point-is-within-a-triangle.basic @@ -1,47 +1,43 @@ _window = 1 begin enum 1 -_textLabel + _textLabel end enum void local fn BuildWindow -'~'1 -window _window, @"Find if a point is within a triangle", (0, 0, 340, 360 ) -WindowCenter(_window) -WindowSubclassContentView(_window) -ViewSetFlipped( _windowContentViewTag, YES ) -ViewSetNeedsDisplay( _windowContentViewTag ) + window _window, @"Find if a point is within a triangle", (0, 0, 340, 360 ) + WindowCenter(_window) + WindowSubclassContentView(_window) + ViewSetFlipped( _windowContentViewTag, YES ) + ViewSetNeedsDisplay( _windowContentViewTag ) -subclass textLabel _textLabel, @"", ( 20, 320, 300, 20 ), _window + subclass textLabel _textLabel, @"", ( 20, 320, 300, 20 ), _window end fn void local fn DrawInView( tag as NSInteger ) -'~'1 -BezierPathRef path = fn BezierPathInit -BezierPathMoveToPoint( path, fn CGPointMake( 30, 300 ) ) -BezierPathLineToPoint( path, fn CGPointMake( 300, 300 ) ) -BezierPathLineToPoint( path, fn CGPointMake( 150, 30 ) ) -BezierPathClose( path ) -BezierPathStrokeFill( path, 3.0, fn ColorBlack, fn ColorGreen ) -AppSetProperty( @"path", path ) + BezierPathRef path = fn BezierPathInit + BezierPathMoveToPoint( path, fn CGPointMake( 30, 300 ) ) + BezierPathLineToPoint( path, fn CGPointMake( 300, 300 ) ) + BezierPathLineToPoint( path, fn CGPointMake( 150, 30 ) ) + BezierPathClose( path ) + BezierPathStrokeFill( path, 3.0, fn ColorBlack, fn ColorGreen ) + AppSetProperty( @"path", path ) end fn void local fn DoMouse( tag as NSInteger ) -'~'1 -CGPoint pt = fn EventLocationInView( tag ) -if ( fn BezierPathContainsPoint( fn AppProperty( @"path" ), pt ) ) -ControlSetStringValue( _textLabel, fn StringWithFormat( @"Inside triangle: x = %.f y = %.f", pt.x, pt.y ) ) -else -ControlSetStringValue( _textLabel, fn StringWithFormat( @"Outside triangle: x = %.f y = %.f", pt.x, pt.y ) ) -end if + CGPoint pt = fn EventLocationInView( tag ) + if ( fn BezierPathContainsPoint( fn AppProperty( @"path" ), pt ) ) + ControlSetStringValue( _textLabel, fn StringWithFormat( @"Inside triangle: x = %.f y = %.f", pt.x, pt.y ) ) + else + ControlSetStringValue( _textLabel, fn StringWithFormat( @"Outside triangle: x = %.f y = %.f", pt.x, pt.y ) ) + end if end fn void local fn DoDialog( ev as long, tag as long ) -'~'1 -select ( ev ) -case _viewDrawRect : fn DrawInView(tag) -case _viewMouseDown : fn DoMouse( tag ) -case _viewMouseMoved : fn DoMouse( tag ) -end select + select ( ev ) + case _viewDrawRect : fn DrawInView(tag) + case _viewMouseDown : fn DoMouse( tag ) + case _viewMouseMoved : fn DoMouse( tag ) + end select end fn fn BuildWindow diff --git a/Task/Find-the-intersection-of-a-line-with-a-plane/Evaldraw/find-the-intersection-of-a-line-with-a-plane.evaldraw b/Task/Find-the-intersection-of-a-line-with-a-plane/Evaldraw/find-the-intersection-of-a-line-with-a-plane.evaldraw new file mode 100644 index 0000000000..b707d3197c --- /dev/null +++ b/Task/Find-the-intersection-of-a-line-with-a-plane/Evaldraw/find-the-intersection-of-a-line-with-a-plane.evaldraw @@ -0,0 +1,108 @@ +struct vec{x,y,z;}; +enum{GRIDRES=3} // Keep a NxN grid of intersection results. +static vec intersections[GRIDRES][GRIDRES]; +static vec ipos = {0,5,-15}; +static vec ileft = {-1,0,0}; +static vec iup = {0,-1,0}; +static vec ifor = {0,0,1}; +() +{ + cls(0); clz(1e32); + + setcam( ipos.x, ipos.y, ipos.z, + ileft.x, ileft.y, ileft.z, // flip right basis to left + iup.x, iup.y, iup.z, // flip down basis to up + ifor.x, ifor.y, ifor.z); + + t=klock(0); + vec planePoint = {0,5,0}; // Plane Position + vec pN = {cos(t),1,sin(t)}; // PlaneNormal, un-normalized + normalize(pN); + + for(x=0; x (&𝑔, &𝑓) { -> \x { 𝑔 𝑓 x } } - my \𝐴 = &sin, &cos, { $_ ** <3/1> } my \𝐵 = &asin, &acos, { $_ ** <1/3> } diff --git a/Task/FizzBuzz/Factor/fizzbuzz-3.factor b/Task/FizzBuzz/Factor/fizzbuzz-3.factor new file mode 100644 index 0000000000..16b9ef4955 --- /dev/null +++ b/Task/FizzBuzz/Factor/fizzbuzz-3.factor @@ -0,0 +1,24 @@ +USING: io kernel math math.functions math.parser ranges +sequences ; +IN: rosetta-code.fizz-buzz + +PREDICATE: fizz < integer 3 divisor? ; +PREDICATE: buzz < integer 5 divisor? ; + +INTERSECTION: fizzbuzz fizz buzz ; + +GENERIC: fizzbuzz>string ( n -- str ) + +M: fizz fizzbuzz>string + drop "Fizz" ; + +M: buzz fizzbuzz>string + drop "Buzz" ; + +M: fizzbuzz fizzbuzz>string + drop "FizzBuzz" ; + +M: integer fizzbuzz>string + number>string ; + +MAIN: [ 1 100 [a..b] [ fizzbuzz>string print ] each ] diff --git a/Task/FizzBuzz/LDPL/fizzbuzz.ldpl b/Task/FizzBuzz/LDPL/fizzbuzz.ldpl new file mode 100644 index 0000000000..3deeed8d9e --- /dev/null +++ b/Task/FizzBuzz/LDPL/fizzbuzz.ldpl @@ -0,0 +1,23 @@ +data: +i is number +n is number + +procedure: +for i from 1 to 101 step 1 do + modulo i by 15 in n + if n is equal to 0 then + display "FizzBuzz" lf + continue + end if + modulo i by 5 in n + if n is equal to 0 then + display "Buzz" lf + continue + end if + modulo i by 3 in n + if n is equal to 0 then + display "Fizz" lf + continue + end if + display i lf +repeat diff --git a/Task/FizzBuzz/MATLAB/fizzbuzz-3.m b/Task/FizzBuzz/MATLAB/fizzbuzz-3.m new file mode 100644 index 0000000000..28970d241f --- /dev/null +++ b/Task/FizzBuzz/MATLAB/fizzbuzz-3.m @@ -0,0 +1,4 @@ +x = string(1:100); +x(3:3:$) = 'Fizz'; +x(5:5:$) = 'Buzz'; +x(3*5:3*5:$) = 'FizzBuzz' diff --git a/Task/FizzBuzz/Pointless/fizzbuzz.pointless b/Task/FizzBuzz/Pointless/fizzbuzz.pointless new file mode 100644 index 0000000000..c0022138f7 --- /dev/null +++ b/Task/FizzBuzz/Pointless/fizzbuzz.pointless @@ -0,0 +1,12 @@ +output = + range(1, 100) + |> map(fizzBuzz) + |> printLines + +fizzBuzz(n) = + if result == "" then n else result + where result = fizzBuzzString(n) + +fizzBuzzString(n) = + (if n % 3 == 0 then "Fizz" else "") + + (if n % 5 == 0 then "Buzz" else "") diff --git a/Task/FizzBuzz/Quackery/fizzbuzz.quackery b/Task/FizzBuzz/Quackery/fizzbuzz.quackery index d4cab98940..95e4e2f432 100644 --- a/Task/FizzBuzz/Quackery/fizzbuzz.quackery +++ b/Task/FizzBuzz/Quackery/fizzbuzz.quackery @@ -1,15 +1,8 @@ - [ times - [ i^ 1+ - ' echo - over 3 mod 0 = if - [ say "Fizz" - drop ' drop ] - over 5 mod 0 = if - [ say "Buzz" - drop ' drop ] - do - sp ] - cr ] is fizzbuzz ( n --> ) - - say 'First 100 turns in the game of fizzbuzz:' cr cr - 100 fizzbuzz cr + 100 times + [ i^ 1+ true + over 3 mod not + if [ say "fizz" drop false ] + over 5 mod not + if [ say "buzz" drop false ] + iff echo else drop + sp ] diff --git a/Task/Forest-fire/Evaldraw/forest-fire.evaldraw b/Task/Forest-fire/Evaldraw/forest-fire.evaldraw new file mode 100644 index 0000000000..99685af681 --- /dev/null +++ b/Task/Forest-fire/Evaldraw/forest-fire.evaldraw @@ -0,0 +1,99 @@ +enum{XSIZ=255, YSIZ=XSIZ} // size of forest +enum{EMPTY=0, TREE=1, BURN=2} // possible states of a cell +static prob_ignite = .000001; // very rare, but remember we have many trees. +static prob_spread = .25; // Fire spread speed/probability if neighbor on fire +static prob_sprout = 0.25; // probability of new tree to sprout +static MAX_NEIGHBORS = 6; // tree refuses to sprout if overcrowded +static forest[2][YSIZ][XSIZ]; // state of pixel +static fuel[2][YSIZ][XSIZ]; // stores fuel (wood) 0-255 +static heat[2][YSIZ][XSIZ]; // tree refuses to spout if heat!=0, also, sets draw color. +static arr_numburn[YSIZ][XSIZ]; // number of burning trees for this cell +static arr_numtree[YSIZ][XSIZ]; // number of neighbor trees for this cell +static xoff[8] = {-1,+0,+1,-1,/*NA*/1,-1,+0,+1}; // offsets to find 8-connected neighbors +static yoff[8] = {-1,-1,-1,+0,/*NA*/0,+1,+1,+1}; +() { // Main in evaldraw scripts is a unnamed function. + static otim; + tim = klock(); // Time since program start in seconds. + dt=tim-otim; // Deltatime. 1/dt is FPS. 0 in first frame. + otim=tim; // store old time for next dt. + simulate(); // simulate and draw are coupled, since draw also ping-pongs state. + draw(); + setcol(0); fillrect(0,YSIZ,XSIZ,15); + setcol(0xffffff); moveto(0,YSIZ); printf("%4.0ffps generation %5.0f", 1 /dt, numframes); + if (bstatus>0) setFire(mousx,mousy); +}// end main + +draw() { + for(y=0; y XSIZ-1)continue; + if (ypos<0 || ypos > YSIZ-1)continue; + cell = forest[1][ypos][xpos]; + if (cell==BURN) numburn++; + else if (cell==TREE) numtree++; + } + arr_numburn[y][x] = numburn; + arr_numtree[y][x] = numtree; + } +} + +fillrect(x0,y0,w,h) { + x0=int(x0); y0=int(y0); w=int(w) + 1; h=int(h); + for(y=y0;y<=y0+h;y++) { moveto(x0,y); lineto(x0+w,y); } +} + +simulate() { + for(y=0; y 0 && rand < prob_spread) setFire(x,y); + else if(cellfuel < 255) fuel[1][y][x] = cellfuel + 1; + } + else if (cell == EMPTY) { + if ( celltemp > 0 ) heat[1][y][x] = celltemp - 1; + else if (numburn==0 && rand < prob_sprout && numtree <= MAX_NEIGHBORS) setTree(x,y); + } + } +} // end sim + +setFire(x,y) { + forest[1][y][x] = BURN; +} + +setTree(x,y) { + forest[1][y][x] = TREE; +} diff --git a/Task/Forward-difference/Arturo/forward-difference.arturo b/Task/Forward-difference/Arturo/forward-difference.arturo index 9929f0bb2d..f526682f3b 100644 --- a/Task/Forward-difference/Arturo/forward-difference.arturo +++ b/Task/Forward-difference/Arturo/forward-difference.arturo @@ -7,7 +7,7 @@ vsub: function [u v][ differences: function [block][ order: attr "order" if order = null -> order: 1 - loop 1..order 'n -> block: vsub block drop block 1 + loop 1..order 'n -> block: vsub block drop block return block ] diff --git a/Task/Fractal-tree/Evaldraw/fractal-tree.evaldraw b/Task/Fractal-tree/Evaldraw/fractal-tree.evaldraw new file mode 100644 index 0000000000..f4f6aa05f4 --- /dev/null +++ b/Task/Fractal-tree/Evaldraw/fractal-tree.evaldraw @@ -0,0 +1,76 @@ +static ratio = .75; +static branchlength = 60; +static max_branches = 4; +struct vec3{x,y,z;}; +() +{ + t=klock(); + srand(t * 1); + zero1 = .5+.5*cos(t); + maxbranches = int( 1+1 + zero1*5); + + + cls(0); clz(1e32); + distcam = -70; + camrot = .5 * t; + ca=distcam * cos(camrot); + sa=distcam * sin(camrot); + setcam(sa,-50,ca,camrot,0); + + angle = 2*pi / 8; + branchlen = 10+50 * zero1; + tree(maxbranches, 0, branchlen, 0,0,0, pi / 2, 0, angle); + + moveto(0,0); + printf("N=%g, frame=%5.0f, cam:%3.0f", maxbranches, numframes, camrot / pi * 180); + printf("\n%gx%g",xres,yres); + sleep(16); +} + + +tree(mb, n, blen, x,y,z, ang_yx, ang_yz, angle) { + n++; if( n> mb ) return; + len = blen / n * ratio; + c = 64 + 128 * n/7; setcol(100,c,38); + + dx=0; dy=0; dz=0; + double mat[9]; + vec3 axis = {0,0,1}; + ang2mat(ang_yz, ang_yx, mat); + transformPoint(axis,mat); + dx=axis.x; + dy=-axis.y; + dz=axis.z; + + ox = x; oy = y; oz = z; + x += len * dx; + y += -len * dy; + z += len * dz; + + rd = 8 / n; + rd2 = 7 / (n+1); + drawcone(ox,oy,oz,rd,x,y,z,rd2,DRAWCONE_FLAT + DRAWCONE_NOPHONG); + + nextangle = /*(-.5+1*rnd*pi) * */angle; + tree(mb, n, blen, x, y, z, ang_yx - angle, ang_yz, nextangle); + tree(mb, n, blen, x, y, z, ang_yx + angle, ang_yz, nextangle); + + tree(mb, n, blen, x, y, z, ang_yx, ang_yz - angle, nextangle); + tree(mb, n, blen, x, y, z, ang_yx, ang_yz + angle, nextangle); +} + +ang2mat(hang,vang,mat[9]) { + mat[6] = cos(vang)*sin(hang); mat[0] = cos(hang); + mat[7] = sin(vang); mat[1] = 0; + mat[8] = cos(vang)*cos(hang); mat[2] =-sin(hang); + mat[3] = mat[7]*mat[2] - mat[8]*mat[1]; + mat[4] = mat[8]*mat[0] - mat[6]*mat[2]; + mat[5] = mat[6]*mat[1] - mat[7]*mat[0]; +} + +transformPoint(vec3 v, thisRot[9]) { + NewX = v.x * thisRot[0] + v.y * thisRot[1] + v.z * thisRot[2]; + NewY = v.x * thisRot[3] + v.y * thisRot[4] + v.z * thisRot[5]; + NewZ = v.x * thisRot[6] + v.y * thisRot[7] + v.z * thisRot[8]; + v.x=newx; v.y=newy; v.z=newz; +} diff --git a/Task/Fractal-tree/FutureBasic/fractal-tree.basic b/Task/Fractal-tree/FutureBasic/fractal-tree.basic new file mode 100644 index 0000000000..bb6c0dae30 --- /dev/null +++ b/Task/Fractal-tree/FutureBasic/fractal-tree.basic @@ -0,0 +1,40 @@ +_window = 1 +_wndWidth = 680 + +void local fn BuildWindow + window _window, @"Fractal Tree", ( 0, 0, _wndWidth, 600 ) + WindowSetBackgroundColor( _window, fn ColorBlack ) + WindowSubclassContentView( _window ) +end fn + +local fn PlotFractalTree( x1 as double, y1 as double, size as long, angle as double, spread as long, depth as long, scale as double ) + double x2, y2 + pen 1.0, fn ColorGreen, NSLineCapStyleSquare + + // Convert angle to radians + x2 = x1 + size * cos(angle * pi / 180) + y2 = y1 + size * sin(angle * pi / 180) + + line x1, y1, x2, y2 + if ( depth > 0 ) + fn PlotFractalTree( x2, y2, size * scale, angle - spread, spread, depth - 1, scale ) + fn PlotFractalTree( x2, y2, size * scale, angle + spread, spread, depth - 1, scale ) + end if +end fn + +void local fn DoDialog( ev as long, tag as long ) + select ( tag ) + case _windowContentViewTag + double spread = ( 80.0 / (_wndWidth / 2 ) ) * 90 + fn PlotFractalTree( _wndWidth / 2, 550, 140, -90, spread, 10, 0.75 ) + end select + select ( ev ) + case _windowWillClose : end + end select +end fn + +on dialog fn DoDialog + +fn BuildWindow + +HandleEvents diff --git a/Task/Fractran/Nim/fractran-1.nim b/Task/Fractran/Nim/fractran-1.nim index 232894e918..2dbc6b6ea7 100644 --- a/Task/Fractran/Nim/fractran-1.nim +++ b/Task/Fractran/Nim/fractran-1.nim @@ -20,7 +20,7 @@ func toFractions(fractList: string): seq[Rat] = for f in fractList.split(): result.add(newRat(f)) -proc run(progStr: string; init, maxSteps: Natural = 0) = +proc run(progStr: string; init: Natural; maxSteps: Natural = 0) = ## Run the program described by string "progStr" with initial value "init", ## stopping after "maxSteps" (0 means for ever). ## Display the value after each step. @@ -39,7 +39,7 @@ iterator primes(n: Natural): int = for val in prog.values(2): if isZero(val and (val - 1)): # This is a power of two. - yield val.digits(2) - 1 # Compute the exponent as number of binary digits minus one. + yield val.digits(2).int - 1 # Compute the exponent as number of binary digits minus one. inc count if count == n: break diff --git a/Task/Function-definition/COBOL/function-definition-1.cobol b/Task/Function-definition/COBOL/function-definition-1.cobol index 7c00afbef6..36b6fec7b7 100644 --- a/Task/Function-definition/COBOL/function-definition-1.cobol +++ b/Task/Function-definition/COBOL/function-definition-1.cobol @@ -2,9 +2,9 @@ PROGRAM-ID. myTest. DATA DIVISION. WORKING-STORAGE SECTION. - 01 x PIC 9(3) VALUE 3. - 01 y PIC 9(3) VALUE 2. - 01 z PIC 9(9). + 01 x PICTURE IS 9(3) VALUE IS 3. + 01 y PICTURE IS 9(3) VALUE IS 2. + 01 z PICTURE IS 9(9). PROCEDURE DIVISION. CALL "myMultiply" USING BY CONTENT x, BY CONTENT y, @@ -17,10 +17,10 @@ PROGRAM-ID. myMultiply. DATA DIVISION. LINKAGE SECTION. - 01 x PIC 9(3). - 01 y PIC 9(3). - 01 z PIC 9(9). - PROCEDURE DIVISION USING x, y, z. + 01 x PICTURE IS 9(3). + 01 y PICTURE IS 9(3). + 01 z PICTURE IS 9(9). + PROCEDURE DIVISION USING BY REFERENCE x, y, z. MULTIPLY x BY y GIVING z. EXIT PROGRAM. END PROGRAM myMultiply. diff --git a/Task/Function-definition/COBOL/function-definition-2.cobol b/Task/Function-definition/COBOL/function-definition-2.cobol index 6c12bbfc1a..45cb3574b1 100644 --- a/Task/Function-definition/COBOL/function-definition-2.cobol +++ b/Task/Function-definition/COBOL/function-definition-2.cobol @@ -6,8 +6,8 @@ FUNCTION myMultiply. DATA DIVISION. WORKING-STORAGE SECTION. - 01 x PIC 9(3) VALUE 3. - 01 y PIC 9(3) VALUE 2. + 01 x PICTURE IS 9(3) VALUE IS 3. + 01 y PICTURE IS 9(3) VALUE IS 2. PROCEDURE DIVISION. DISPLAY myMultiply(x, y). STOP RUN. @@ -17,10 +17,10 @@ FUNCTION-ID. myMultiply. DATA DIVISION. LINKAGE SECTION. - 01 x PIC 9(3). - 01 y PIC 9(3). - 01 z pic 9(9). + 01 x PICTURE IS 9(3). + 01 y PICTURE IS 9(3). + 01 z PICTURE IS 9(9). PROCEDURE DIVISION USING x, y RETURNING z. MULTIPLY x BY y GIVING z. - EXIT FUNCTION. + GOBACK. END FUNCTION myMultiply. diff --git a/Task/Function-definition/LDPL/function-definition.ldpl b/Task/Function-definition/LDPL/function-definition.ldpl new file mode 100644 index 0000000000..2c00e8327d --- /dev/null +++ b/Task/Function-definition/LDPL/function-definition.ldpl @@ -0,0 +1,22 @@ +data: +n is number + +procedure: +sub multiply + parameters: + x is number + y is number + result is number + procedure: + in result solve x * y +end sub + +# call the bare sub-procedure +call multiply with 3 4 n +display n lf + +# create a statement for it +create statement "multiply $ by $ in $" executing multiply + +multiply 3 by 4 in n +display n lf diff --git a/Task/Function-prototype/Java/function-prototype.java b/Task/Function-prototype/Java/function-prototype.java new file mode 100644 index 0000000000..5be1b82833 --- /dev/null +++ b/Task/Function-prototype/Java/function-prototype.java @@ -0,0 +1,55 @@ +public final class FunctionPrototype { + + public static void main(String[] aArgs) { + Rectangle rectangle = new Rectangle(10.0, 20.0); + System.out.println("Area = " + rectangle.area()); + + Calculator calculator = new Calculator(); + System.out.println("Sum = " + calculator.sum(2, 2)); + calculator.version(); + } + + private static class Rectangle implements Shape { + + public Rectangle(double aWidth, double aLength) { + width = aWidth; length = aLength; + } + + @Override + public double area() { + return length * width; + } + + private final double width, length; + + } + + private static class Calculator extends Arithmetic { + + public Calculator() { + // Statements to create the graphical + // representation of the calculator + } + + @Override + public int sum(int aOne, int aTwo) { + return aOne + aTwo; + } + + @Override + public void version() { + System.out.println("0.0.1"); + } + + } + +} + +interface Shape { + public double area(); +} + +abstract class Arithmetic { + public abstract int sum(int aOne, int aTwo); + public abstract void version(); +} diff --git a/Task/Gapful-numbers/BASIC256/gapful-numbers.basic b/Task/Gapful-numbers/BASIC256/gapful-numbers.basic index 01689f1714..25aa52e421 100644 --- a/Task/Gapful-numbers/BASIC256/gapful-numbers.basic +++ b/Task/Gapful-numbers/BASIC256/gapful-numbers.basic @@ -9,7 +9,7 @@ end function subroutine muestra_gapful(n, gaps) inc = 0 - print "Primeros "; gaps; " números gapful >= "; n + print "First "; gaps; " gapful numbers >= "; n while inc < gaps if n mod is_gapful(n) = 0 then print " " ; n ; diff --git a/Task/Gapful-numbers/Chipmunk-Basic/gapful-numbers.basic b/Task/Gapful-numbers/Chipmunk-Basic/gapful-numbers.basic new file mode 100644 index 0000000000..1dccb80ed3 --- /dev/null +++ b/Task/Gapful-numbers/Chipmunk-Basic/gapful-numbers.basic @@ -0,0 +1,25 @@ +100 muestragapful(100,30) +110 muestragapful(1000000,15) +120 muestragapful(1000000000,10) +130 muestragapful(7123,25) +140 end +150 function isgapful(n) +160 m = n +170 l = n mod 10 +180 while (m >= 10) +190 m = int(m/10) +200 wend +210 isgapful = (m*10)+l +220 end function +230 sub muestragapful(n,gaps) +240 inc = 0 +250 print "First ";gaps;" gapful numbers >= ";n +260 while inc < gaps +270 if n mod isgapful(n) = 0 then +280 print " ";n; +290 inc = inc+1 +300 endif +310 n = n+1 +320 wend +330 print chr$(10) +340 end sub diff --git a/Task/Gapful-numbers/GW-BASIC/gapful-numbers.basic b/Task/Gapful-numbers/GW-BASIC/gapful-numbers.basic new file mode 100644 index 0000000000..fed60b0e79 --- /dev/null +++ b/Task/Gapful-numbers/GW-BASIC/gapful-numbers.basic @@ -0,0 +1,23 @@ +100 CLS +110 N = 100 : GAPS = 30 : GOSUB 230 +120 N = 10000 : GAPS = 15 : GOSUB 230 +130 N = 7123 : GAPS = 25 : GOSUB 230 +140 END +150 REM isgapful(n) +160 M = N +170 L = N MOD 10 +180 WHILE (M >= 10) +190 M = INT(M/10) +200 WEND +210 ISGAPFUL = (M*10)+L +220 RETURN 'end function +230 REM muestragapful(n,gaps) +240 INC = 0 +250 PRINT "First "; GAPS; " gapful numbers >= "; N +260 WHILE INC < GAPS +270 GOSUB 150 +280 IF N MOD ISGAPFUL = 0 THEN PRINT " "; N; : INC = INC + 1 +290 N = N+1 +300 WEND +310 PRINT CHR$(10) +320 RETURN diff --git a/Task/Gapful-numbers/Gambas/gapful-numbers.gambas b/Task/Gapful-numbers/Gambas/gapful-numbers.gambas new file mode 100644 index 0000000000..fc7a0416e7 --- /dev/null +++ b/Task/Gapful-numbers/Gambas/gapful-numbers.gambas @@ -0,0 +1,35 @@ +Public Sub Main() + + muestraGapful(100, 30) + muestraGapful(1000000, 15) + muestraGapful(1000000000, 10) + muestraGapful(7123, 25) + +End + +Function isGapful(n As Integer) As Integer + + Dim m As Integer = n, l As Integer = n Mod 10 + + While (m >= 10) + m \= 10 'm = Int(m / 10) + Wend + Return (m * 10) + l + +End Function + +Sub muestraGapful(n As Integer, gaps As Integer) + + Dim incr As Integer = 0 + + Print "First "; gaps; " gapful numbers >= "; n; ": " + While incr < gaps + If n Mod isGapful(n) = 0 Then + Print n; " "; + Inc incr '+= 1 + End If + n += 1 + Wend + Print Chr(10) + +End Sub diff --git a/Task/Gapful-numbers/QBasic/gapful-numbers.basic b/Task/Gapful-numbers/QBasic/gapful-numbers.basic new file mode 100644 index 0000000000..4dd7340163 --- /dev/null +++ b/Task/Gapful-numbers/QBasic/gapful-numbers.basic @@ -0,0 +1,26 @@ +FUNCTION isGapful (n) + m = n + l = n MOD 10 + WHILE (m >= 10) + m = INT(m / 10) + WEND + isGapful = (m * 10) + l +END FUNCTION + +SUB muestraGapful (n, gaps) + inc = 0 + PRINT "First "; gaps; "gapful numbers >= "; n; ":" + WHILE inc < gaps + IF n MOD isGapful(n) = 0 THEN + PRINT ; n; " "; + inc = inc + 1 + END IF + n = n + 1 + WEND + PRINT CHR$(10) +END SUB + +CALL muestraGapful(100, 30) +CALL muestraGapful(1000000, 15) +CALL muestraGapful(1000000000, 10) +CALL muestraGapful(7123, 25) diff --git a/Task/Gapful-numbers/Run-BASIC/gapful-numbers.basic b/Task/Gapful-numbers/Run-BASIC/gapful-numbers.basic new file mode 100644 index 0000000000..aafdca8103 --- /dev/null +++ b/Task/Gapful-numbers/Run-BASIC/gapful-numbers.basic @@ -0,0 +1,28 @@ +call muestraGapful 100, 30 +call muestraGapful 1000000, 15 +call muestraGapful 1000000000, 10 +call muestraGapful 7123,25 +end + +function isGapful(n) + m = n + l = n mod 10 + while (m >= 10) + m = int(m / 10) + wend + isGapful = (m * 10) + l +end function + +sub muestraGapful n, gaps + inc = 0 + print + print "First "; gaps; " gapful numbers >= "; n + while inc < gaps + if n mod isGapful(n) = 0 then + print " " ; n ; + inc = inc + 1 + end if + n = n + 1 + wend + print +end sub diff --git a/Task/Gapful-numbers/True-BASIC/gapful-numbers.basic b/Task/Gapful-numbers/True-BASIC/gapful-numbers.basic new file mode 100644 index 0000000000..f3e39a8e1b --- /dev/null +++ b/Task/Gapful-numbers/True-BASIC/gapful-numbers.basic @@ -0,0 +1,28 @@ +FUNCTION isgapful(n) + LET m = n + LET l = remainder(n,10) + DO WHILE (m >= 10) + LET m = INT(m/10) + LOOP + LET isgapful = (m*10)+l +END FUNCTION + +SUB muestragapful (n,gaps) + LET inc = 0 + PRINT + PRINT "First"; gaps; "gapful numbers >="; n + DO WHILE inc < gaps + IF remainder(n, isgapful(n)) = 0 THEN + PRINT ; n; " "; + LET inc = inc+1 + END IF + LET n = n+1 + LOOP + PRINT +END SUB + +CALL muestragapful (100, 30) +CALL muestragapful (1000000, 15) +CALL muestragapful (1000000000, 10) +CALL muestragapful (7123, 25) +END diff --git a/Task/General-FizzBuzz/FutureBasic/general-fizzbuzz.basic b/Task/General-FizzBuzz/FutureBasic/general-fizzbuzz.basic new file mode 100644 index 0000000000..01392f4c1c --- /dev/null +++ b/Task/General-FizzBuzz/FutureBasic/general-fizzbuzz.basic @@ -0,0 +1,108 @@ +include "NSLog.incl" + +_mfile = 1 +begin enum + _iNewGame + _ + _iClose +end enum +_mEdit = 2 + +_window = 1 +begin enum 1 + _maxNumLabel + _maxNumFld + _f1Label + _f1Fld + _wd1Label + _wd1Fld + _f2Label + _f2Fld + _wd2Label + _wd2Fld + _f3Label + _f3Fld + _wd3Label + _wd3Fld + _playBtn +end enum + +void local fn BuildMenu + menu _mFile,,, @"File" + menu _mFile, _iNewGame,, @"New Game" + menu _mFile, _iClose,, @"Close", @"w" + MenuItemSetAction( _mFile, _iClose, @"performClose:" ) + editmenu _mEdit +end fn + +void local fn BuildWindow + window _window, @"General FizzBuzz", (0,0,362,188), NSWindowStyleMaskTitled + + textlabel _maxNumLabel, @"Maximum number:", (18,150,116,16) + textfield _maxNumFld,, @"20", (140,147,202,21) + ControlSetFormat( _maxNumFld, @"0123456789", YES, 0, 0 ) + + textlabel _f1Label, @"Factor 1:", (18,121,58,16) + textfield _f1Fld,, @"3", (80,118,54,21) + ControlSetFormat( _f1Fld, @"0123456789", YES, 0, 0 ) + textlabel _wd1Label, @"Word 1:", (138,121,52,16) + textfield _wd1Fld,, @"Fizz", (196,118,146,21) + + textlabel _f2Label, @"Factor 2:", (18,92,58,16) + textfield _f2Fld,, @"5", (80,89,54,21) + ControlSetFormat( _f2Fld, @"0123456789", YES, 0, 0 ) + textlabel _wd2Label, @"Word 2:", (138,92,52,16) + textfield _wd2Fld,, @"Buzz", (196,89,146,21) + + textlabel _f3Label, @"Factor 3:", (18,63,58,16) + textfield _f3Fld,, @"7", (80,60,54,21) + ControlSetFormat( _f3Fld, @"0123456789", YES, 0, 0 ) + textlabel _wd3Label, @"Word 3:", (138,63,52,16) + textfield _wd3Fld,, @"Baxx", (196,60,146,21) + + button _playBtn,,, @"Play FizzBuzz", (122,13,118,32) + + WindowMakeFirstResponder( _window, _maxNumFld ) +end fn + +void local fn PlayFizzBuzz + long maxNum = intval(textfield(_maxNumFld)) + + long f1 = intval(textfield(_f1Fld)) + long f2 = intval(textfield(_f2Fld)) + long f3 = intval(textfield(_f3Fld)) + + CFStringRef f1Word = textfield(_wd1Fld) + CFStringRef f2Word = textfield(_wd2Fld) + CFStringRef f3Word = textfield(_wd3Fld) + CFStringRef string = NULL + + NSLogClear + + long i + for i = 1 to maxNum + string = @"" + if ( i mod f1 == 0 ) then string = f1Word + if ( i mod f2 == 0 ) then string = fn StringByAppendingString( string, f2Word ) + if ( i mod f3 == 0 ) then string = fn StringByAppendingString( string, f3Word ) + if ( len(string) == 0 ) then string = fn StringWithFormat( @"%ld", i ) + NSLog(@"%@",string) + next +end fn + + +void local fn DoDialog( ev as long, tag as long ) + select ( ev ) + case _btnClick + select ( tag ) + case _playBtn : fn PlayFizzBuzz + end select + end select +end fn + +fn BuildMenu +fn BuildWindow + +on dialog fn DoDialog + +HandleEvents diff --git a/Task/General-FizzBuzz/Quackery/general-fizzbuzz.quackery b/Task/General-FizzBuzz/Quackery/general-fizzbuzz.quackery new file mode 100644 index 0000000000..16f6159cf9 --- /dev/null +++ b/Task/General-FizzBuzz/Quackery/general-fizzbuzz.quackery @@ -0,0 +1,27 @@ + [ sortwith + [ dip [ 1 peek ] + 1 peek > ] + $ "" swap rot + times + [ i^ 1+ + over $ "" unrot + witheach + [ dip dup do + dip swap mod + iff drop + else + [ rot swap + join swap ] ] + over $ "" = + iff [ number$ join ] + else drop + rot swap join + space join swap ] + drop + -1 split drop ] is generalfizzbuzz ( n [ --> $ ) + + 105 + ' [ [ $ "fizz" 3 ] + [ $ "baxx" 7 ] + [ $ "buzz" 5 ] ] generalfizzbuzz + nest$ 60 wrap$ cr diff --git a/Task/Golden-ratio-Convergence/Odin/golden-ratio-convergence.odin b/Task/Golden-ratio-Convergence/Odin/golden-ratio-convergence.odin new file mode 100644 index 0000000000..4704230834 --- /dev/null +++ b/Task/Golden-ratio-Convergence/Odin/golden-ratio-convergence.odin @@ -0,0 +1,26 @@ +package golden +import "core:fmt" +import "core:math" +/* main block */ +main :: proc() { + iterate() +} +/* definitions */ +iterate :: proc() { + count := 0 + phi0: f64 = 1.0 + difference: f64 = 1.0 + phi1: f64 + fmt.println("\nGolden ratio/Convergence") + fmt.println("-----------------------------------------") + for 1.0e-5 < difference { + phi1 = 1.0 + (1.0 / phi0) + difference = abs(phi1 - phi0) + phi0 = phi1 + count += 1 + fmt.printf("Iteration %2d : Estimate : %.8f\n", count, phi1) + } + fmt.println("-----------------------------------------") + fmt.printf("Result: %.8f after %d iterations", phi1, count) + fmt.printf("\nThe error is approximately %.10f\n", (phi1 - (0.5 * (1.0 + math.sqrt_f64(5.0))))) +} diff --git a/Task/Graph-colouring/C++/graph-colouring.cpp b/Task/Graph-colouring/C++/graph-colouring.cpp new file mode 100644 index 0000000000..376601c7c9 --- /dev/null +++ b/Task/Graph-colouring/C++/graph-colouring.cpp @@ -0,0 +1,113 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const std::vector all_colours = { "PINK", "ORANGE", "CYAN", "YELLOW", "RED", "GREEN", "BLUE" }; + +class Node { +public: + Node(const int32_t& aID, const int32_t& aSaturation, const std::string& aColour) + : id(aID), saturation(aSaturation), colour(aColour) {} + + Node() : id(0), saturation(0), colour("NO_COLOUR") {} + + int32_t id, saturation; + std::string colour; + bool excluded_from_search = false; +}; + +int main() { + std::map graph; + + std::map, + decltype([](const int32_t& a, const int32_t& b) { return a < b; })> neighbours; + + const std::vector graph_representations = { "0-1 1-2 2-0 3", + "1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7", + "1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6", + "1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7" }; + + for ( const std::string& graph_representation : graph_representations ) { + graph.clear(); + neighbours.clear(); + std::stringstream stream(graph_representation); + std::string element; + while ( stream >> element ) { + if ( element.find("-") != std::string::npos ) { + const int32_t id1 = element[0] - '0'; + const int32_t id2 = element[element.length() - 1] - '0'; + + if ( ! graph.contains(id1) ) { + graph[id1] = Node(id1, 0, "NO_COLOUR"); + } + Node node1 = graph[id1]; + + if ( ! graph.contains(id2) ) { + graph[id2] = Node(id2, 0, "NO_COLOUR"); + } + Node node2 = graph[id2]; + + neighbours[id1].emplace(id2); + neighbours[id2].emplace(id1); + } else { + const int32_t id = element[0] - '0'; + if ( ! graph.contains(id) ) { + graph[id] = Node(id, 0, "NO_COLOUR"); + } + } + } + + for ( uint64_t i = 0; i < graph.size(); ++i ) { + int32_t max_node_id = -1; + int32_t max_saturation = -1; + for ( const auto& [key, value] : graph ) { + if ( ! value.excluded_from_search && value.saturation > max_saturation ) { + max_saturation = value.saturation; + max_node_id = key; + } + } + + std::unordered_set colours_used; + for ( const int32_t& neighbour : neighbours[max_node_id] ) { + colours_used.emplace(graph[neighbour].colour); + } + + std::string min_colour; + for ( const std::string& colour : all_colours ) { + if ( ! colours_used.contains(colour) ) { + min_colour = colour; + } + } + + graph[max_node_id].excluded_from_search = true; + graph[max_node_id].colour = min_colour; + + for ( int32_t neighbour : neighbours[max_node_id] ) { + if ( graph[neighbour].colour == "NO_COLOUR" ) { + graph[neighbour].saturation = colours_used.size(); + } + } + } + + std::unordered_set graph_colours; + for ( const auto& [key, value] : graph ) { + graph_colours.emplace(value.colour); + std::cout << "Node " << key << ": colour = " + value.colour; + + if ( ! neighbours[key].empty() ) { + std::cout << std::string(8 - value.colour.length(), ' ') << "neighbours = "; + for ( const int32_t& neighbour : neighbours[key] ) { + std::cout << neighbour << " "; + } + } + std::cout << std::endl; + } + std::cout << "Number of colours used: " << graph_colours.size() << std::endl << std::endl; + } +} diff --git a/Task/Graph-colouring/Java/graph-colouring.java b/Task/Graph-colouring/Java/graph-colouring.java new file mode 100644 index 0000000000..61736e4589 --- /dev/null +++ b/Task/Graph-colouring/Java/graph-colouring.java @@ -0,0 +1,109 @@ +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; + +public final class GraphColoring { + + public static void main(String[] aArgs) { + colourise("0-1 1-2 2-0 3"); + colourise("1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7"); + colourise("1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6"); + colourise("1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7"); + } + + private static void colourise(String aGraphRepresentation) { + List graph = initialiseGraph(aGraphRepresentation); + List nodes = new ArrayList(graph); + while ( ! nodes.isEmpty() ) { + Node maxNode = nodes.stream().max( (one, two) -> Integer.compare(one.saturation, two.saturation) ).get(); + maxNode.colour = minColour(maxNode); + updateSaturation(maxNode); + nodes.remove(maxNode); + } + + System.out.println("Graph: " + aGraphRepresentation); + display(graph); + } + + private static Colour minColour(Node aNode) { + Set coloursUsed = coloursUsed(aNode); + for ( Colour colour : Colour.values() ) { + if ( ! coloursUsed.contains(colour) ) { + return colour; + } + } + return Colour.NO_COLOUR; + } + + private static Set coloursUsed(Node aNode) { + Set coloursUsed = new HashSet(); + for ( Node neighbour : aNode.neighbours ) { + coloursUsed.add(neighbour.colour); + } + return coloursUsed; + } + + private static void updateSaturation(Node aNode) { + for ( Node neighbour : aNode.neighbours ) { + if ( neighbour.colour == Colour.NO_COLOUR ) { + neighbour.saturation = coloursUsed(aNode).size(); + } + } + } + + private static void display(List aNodes) { + Set graphColours = new HashSet(); + for ( Node node : aNodes ) { + graphColours.add(node.colour); + System.out.print("Node " + node.index + ": colour = " + node.colour); + + if ( ! node.neighbours.isEmpty() ) { + List indexes = node.neighbours.stream().map( n -> n.index ).toList(); + System.out.print(" ".repeat(8 - String.valueOf(node.colour).length()) + "neighbours = " + indexes); + } + System.out.println(); + } + + System.out.println("Number of colours used: " + graphColours.size()); + System.out.println(); + } + + private static List initialiseGraph(String aGraphRepresentation) { + Map map = new TreeMap(); + for ( String element : aGraphRepresentation.split(" ") ) { + if ( element.contains("-") ) { + final int index1 = Integer.valueOf(element.substring(0, 1)); + final int index2 = Integer.valueOf(element.substring(element.length() - 1)); + Node node1 = map.computeIfAbsent(index1, k -> new Node(index1, 0, Colour.NO_COLOUR) ); + Node node2 = map.computeIfAbsent(index2, k -> new Node(index2, 0, Colour.NO_COLOUR) ); + node1.neighbours.add(node2); + node2.neighbours.add(node1); + } else { + final int index = Integer.valueOf(element); + map.computeIfAbsent(index, k -> new Node(index, 0, Colour.NO_COLOUR)); + } + } + + List graph = new ArrayList(map.values()); + return graph; + } + + private enum Colour { BLUE, GREEN, RED, YELLOW, CYAN, ORANGE, NO_COLOUR } + + private static class Node { + + public Node(int aIndex, int aSaturation, Colour aColour) { + index = aIndex; saturation = aSaturation; colour = aColour; + } + + private int index, saturation; + private Colour colour; + private Set neighbours = new TreeSet( (one, two) -> Integer.compare(one.index, two.index) ); + + } + +} diff --git a/Task/Greatest-common-divisor/Dt/greatest-common-divisor.dt b/Task/Greatest-common-divisor/Dt/greatest-common-divisor.dt new file mode 100644 index 0000000000..e95a926f1c --- /dev/null +++ b/Task/Greatest-common-divisor/Dt/greatest-common-divisor.dt @@ -0,0 +1,3 @@ +[dup [dup rot % loop] swap do?] \loop def + +[loop drop] \gcd def diff --git a/Task/Greatest-common-divisor/FutureBasic/greatest-common-divisor.basic b/Task/Greatest-common-divisor/FutureBasic/greatest-common-divisor.basic index 7bc6a13114..5ec8eb36e6 100644 --- a/Task/Greatest-common-divisor/FutureBasic/greatest-common-divisor.basic +++ b/Task/Greatest-common-divisor/FutureBasic/greatest-common-divisor.basic @@ -35,7 +35,7 @@ void local fn DoDialog( ev as Long, tag as long ) //This makes it interactive case _textFieldDidchange //Find GCD of edit fields' contents a = fn ControlIntegerValue( _fldA ) b = fn ControlIntegerValue( _fldB ) - if a + b == 0 then textlabel _ansA, @"=" : textlabel _ansB, @"=" : exit fn + if a + b == 0 then textlabel _ansA, @"= 0" : textlabel _ansB, @"= 0" : exit fn c = fn GCD( a, b ) textlabel _ansA, fn stringwithformat(@"= %ld x %ld", c, a / c ) textlabel _ansB, fn stringwithformat(@"= %ld x %ld", c, b / c ) diff --git a/Task/Greatest-common-divisor/Swift/greatest-common-divisor.swift b/Task/Greatest-common-divisor/Swift/greatest-common-divisor.swift index 6061407791..339eb14c44 100644 --- a/Task/Greatest-common-divisor/Swift/greatest-common-divisor.swift +++ b/Task/Greatest-common-divisor/Swift/greatest-common-divisor.swift @@ -1,8 +1,9 @@ // Iterative -func gcd(var a: Int, var b: Int) -> Int { +func gcd(a: Int, b: Int) -> Int { - a = abs(a); b = abs(b) + var a = abs(a) + var b = abs(b) if (b > a) { swap(&a, &b) } @@ -13,9 +14,10 @@ func gcd(var a: Int, var b: Int) -> Int { // Recursive -func gcdr (var a: Int, var b: Int) -> Int { +func gcdr (a: Int, b: Int) -> Int { - a = abs(a); b = abs(b) + var a = abs(a) + var b = abs(b) if (b > a) { swap(&a, &b) } diff --git a/Task/Greatest-element-of-a-list/LDPL/greatest-element-of-a-list.ldpl b/Task/Greatest-element-of-a-list/LDPL/greatest-element-of-a-list.ldpl new file mode 100644 index 0000000000..fc74137c3f --- /dev/null +++ b/Task/Greatest-element-of-a-list/LDPL/greatest-element-of-a-list.ldpl @@ -0,0 +1,33 @@ +data: +values is number list +n is number + +procedure: +sub max + parameters: + x is number list + result is number + local data: + i is number + procedure: + store x:0 in result + for each i in values do + if i is greater than result then + store i in result + end if + repeat +end sub +create statement "get maximum of list $ in $" executing max + +# Now let's use the sub-procedure. +push 1 to values +push 11 to values +push 5 to values +push 33 to values +push 99 to values +push 13 to values +push 37 to values +push 50 to values + +get maximum of list values in n +display "The maximum is " n lf diff --git a/Task/Greatest-element-of-a-list/MSX-Basic/greatest-element-of-a-list.basic b/Task/Greatest-element-of-a-list/MSX-Basic/greatest-element-of-a-list.basic new file mode 100644 index 0000000000..84c5b041f4 --- /dev/null +++ b/Task/Greatest-element-of-a-list/MSX-Basic/greatest-element-of-a-list.basic @@ -0,0 +1,12 @@ +10 INPUT "How many items"; N% +20 DIM ARR(N%) +30 FOR I% = 0 TO N% - 1 +40 PRINT "Value of item #"; I% +50 INPUT ARR(I%) +60 NEXT I% +70 CHAMP = ARR(0) : INDEX = 0 +80 FOR I% = 1 TO N% - 1 +90 IF ARR(I%) > CHAMP THEN CHAMP = ARR(I%): INDEX = I% +100 NEXT I% +110 PRINT "The maximum value was "; CHAMP; " at index "; INDEX; "." +120 END diff --git a/Task/Greatest-element-of-a-list/Minimal-BASIC/greatest-element-of-a-list.basic b/Task/Greatest-element-of-a-list/Minimal-BASIC/greatest-element-of-a-list.basic new file mode 100644 index 0000000000..8d69818dad --- /dev/null +++ b/Task/Greatest-element-of-a-list/Minimal-BASIC/greatest-element-of-a-list.basic @@ -0,0 +1,17 @@ +10 PRINT "HOW MANY ITEMS? " +20 INPUT N +30 FOR J = 0 TO N-1 +40 PRINT "VALUE OF ITEM #";J +50 INPUT T +60 LET A(J) = T +70 NEXT J +80 LET C = A(0) +90 LET I = 0 +100 FOR J = 1 TO N-1 +110 IF A(J) > C THEN 130 +120 GOTO 150 +130 LET C = A(J) +140 LET I = J +150 NEXT J +160 PRINT "THE MAXIMUM VALUE WAS ";C;" AT INDEX ";I;"." +170 END diff --git a/Task/Greatest-element-of-a-list/Quite-BASIC/greatest-element-of-a-list.basic b/Task/Greatest-element-of-a-list/Quite-BASIC/greatest-element-of-a-list.basic new file mode 100644 index 0000000000..d38bd0b389 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Quite-BASIC/greatest-element-of-a-list.basic @@ -0,0 +1,14 @@ +10 INPUT "How many items? "; n +20 ARRAY a +30 FOR j = 0 TO n-1 +40 PRINT "Value of item #"; j +50 INPUT ""; t +60 LET a(j) = t +70 NEXT j +80 LET c = a(0) +90 LET i = 0 +100 FOR j = 1 TO n-1 +110 IF a(j) > c THEN LET c = a(j) : LET i = j +120 NEXT j +130 PRINT "The maximum value was "; c; " at index "; i; "." +140 END diff --git a/Task/Greatest-subsequential-sum/Quackery/greatest-subsequential-sum.quackery b/Task/Greatest-subsequential-sum/Quackery/greatest-subsequential-sum.quackery new file mode 100644 index 0000000000..875c424923 --- /dev/null +++ b/Task/Greatest-subsequential-sum/Quackery/greatest-subsequential-sum.quackery @@ -0,0 +1,31 @@ + [ stack ] is maxseq ( --> s ) + [ stack ] is maxsum ( --> s ) + + [ [] maxseq put + 0 maxsum put + dup dup size times + [ [] 0 rot + witheach + [ rot over join + unrot + + dup maxsum share > + if + [ dup maxsum replace + over maxseq replace ] ] + 2drop behead drop dup ] + 2drop + maxsum take + maxseq take ] is maxsubseqsum ( [ --> n [ ) + + + ' [ [ 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 ] + [ ] ] + witheach + [ dup + say "Sequence: " echo cr + maxsubseqsum + say "Subsequence: " echo cr + say "Sum: " echo cr + cr ] diff --git a/Task/Happy-numbers/00-TASK.txt b/Task/Happy-numbers/00-TASK.txt index 1201ba43c3..ff58f52d73 100644 --- a/Task/Happy-numbers/00-TASK.txt +++ b/Task/Happy-numbers/00-TASK.txt @@ -14,6 +14,9 @@ Find and print the first   '''8'''   happy numbers. Display an example of your output here on this page. +;Related tasks: +* [[Iterated digits squaring]] + ;See also: *   The OEIS entry:   [[oeis:A007770|The     happy numbers:   A007770]] *   The OEIS entry:   [[oeis:A031177|The unhappy numbers;   A031177]] diff --git a/Task/Happy-numbers/Maxima/happy-numbers.maxima b/Task/Happy-numbers/Maxima/happy-numbers.maxima new file mode 100644 index 0000000000..48ff21b660 --- /dev/null +++ b/Task/Happy-numbers/Maxima/happy-numbers.maxima @@ -0,0 +1,25 @@ +/* Function that decomposes te number into a list */ +decompose(N) := block( + digits: [], + while N > 0 do + (remainder: mod(N, 10), + digits: cons(remainder, digits), + N: floor(N/10)), + digits +)$ + +/* Function that given a number returns the sum of their digits */ +sum_squares_digits(n):=block( + decompose(n), + map(lambda([x],x^2),%%), + apply("+",%%))$ + +/* Predicate function based on the task iterated digits squaring */ +happyp(n):=if n=1 then true else if n=89 then false else block(iter:n,while not member(iter,[1,89]) do iter:sum_squares_digits(iter),iter,if iter=1 then true)$ + +/* Test case */ +/* First eight happy numbers */ +block( + happy:[],i:1, + while length(happy)<8 do (if happyp(i) then happy:endcons(i,happy),i:i+1), + happy); diff --git a/Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer.edsac b/Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer-1.edsac similarity index 100% rename from Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer.edsac rename to Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer-1.edsac diff --git a/Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer-2.edsac b/Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer-2.edsac new file mode 100644 index 0000000000..45eee3791e --- /dev/null +++ b/Task/Hello-world-Line-printer/EDSAC-order-code/hello-world-line-printer-2.edsac @@ -0,0 +1,39 @@ +[Alternative "Hello World" for Rosetta Code] + +[Subroutine to print a string.] +[Parameter: A order for first character follows subroutine call (G order).] +[Modified 2022-07-13: A order for first character was formerly passed in 0F.] +[String is terminated with EDSAC null, which is printed] + T56K GK [load at 56; set relative addressing] + A18@ U17@ [plant return link, increasing address by 3 + instead of 2 as usual] + S19@ [make A order to load A order after subroutine call] + T4@ [plant in code] + [4] AF [(planted) load A order after subroutine call] + [5] T6@ [loop: plant A order for next character] + [6] AF [load next character] + UF [to 0F for printing; keep it in acc] + OF [output to teleprinter] + E12@ [if char >= 0, not EDSAC null] + A20@ [if char < 0, add 15 to test for EDSAC null] + G16@ [jump to exit if null] + [12] TF [clear acc] + A6@ A2F [inc address in A order above] + G5@ [loop back, because top 5 bits = A = 11100] + [16] TF [clear acc on exit (EDSAC convention)] + [17] ZF [(planted) jump back to caller] + [18] U3F [constant for making return link] + [19] U1F [constant for picking up parameter] + [20] K2048F [constant for testing final null] + +[Main routine] + T96K GK [load at 96; set relative addressing +[Enter with acc = 0] + [0] A@ G56F [call print subroutine] + A4@ [A order for first character of string] + ZF [subroutine returns here; halt machine] + [4] K2048F HF EF LF LF OF !F WF OF RF LF DF @F &F K4096F +[The above string is: letter shift, 'HELLO WORLD', CR, LF, null] + EZ [define entry point] + PF [acc = 0 on entry] +[end] diff --git a/Task/Hello-world-Newline-omission/Dt/hello-world-newline-omission.dt b/Task/Hello-world-Newline-omission/Dt/hello-world-newline-omission.dt new file mode 100644 index 0000000000..b9af2138c7 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Dt/hello-world-newline-omission.dt @@ -0,0 +1 @@ +"Goodbye, World!" p diff --git a/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom b/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom index ef17c4b16a..30f70c3d8d 100644 --- a/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom +++ b/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom @@ -1,5 +1,20 @@ class Main { Void main() { - echo("Goodbye, World!") + // Print with newline + echo("Hello, World!") + // Or + Env.cur.out.printLine("Hello, World!") + + // Print without a newline + Env.cur.out.print("Goodbye, world!") + + // Also can get a reference to the standard output stream + out := Env.cur.out + + out.print("Goodbye, world!") + out.flush() // and flush buffer if needed + // or method chain + out.print("Goodbye, world!").flush() + } } diff --git a/Task/Hello-world-Standard-error/Dt/hello-world-standard-error.dt b/Task/Hello-world-Standard-error/Dt/hello-world-standard-error.dt new file mode 100644 index 0000000000..d8ba568f3f --- /dev/null +++ b/Task/Hello-world-Standard-error/Dt/hello-world-standard-error.dt @@ -0,0 +1 @@ +"Goodbye, World!" epl diff --git a/Task/Hello-world-Text/Dt/hello-world-text.dt b/Task/Hello-world-Text/Dt/hello-world-text.dt new file mode 100644 index 0000000000..0a03519c22 --- /dev/null +++ b/Task/Hello-world-Text/Dt/hello-world-text.dt @@ -0,0 +1 @@ +"Hello world!" pl diff --git a/Task/Hello-world-Text/Koka/hello-world-text.koka b/Task/Hello-world-Text/Koka/hello-world-text-1.koka similarity index 100% rename from Task/Hello-world-Text/Koka/hello-world-text.koka rename to Task/Hello-world-Text/Koka/hello-world-text-1.koka diff --git a/Task/Hello-world-Text/Koka/hello-world-text-2.koka b/Task/Hello-world-Text/Koka/hello-world-text-2.koka new file mode 100644 index 0000000000..c25d3ff45c --- /dev/null +++ b/Task/Hello-world-Text/Koka/hello-world-text-2.koka @@ -0,0 +1,2 @@ +fun main() + "Hello world!".println diff --git a/Task/Hello-world-Text/Pointless/hello-world-text.pointless b/Task/Hello-world-Text/Pointless/hello-world-text.pointless new file mode 100644 index 0000000000..1fd4d73b0b --- /dev/null +++ b/Task/Hello-world-Text/Pointless/hello-world-text.pointless @@ -0,0 +1 @@ +output = println("Hello world!") diff --git a/Task/Heronian-triangles/FutureBasic/heronian-triangles.basic b/Task/Heronian-triangles/FutureBasic/heronian-triangles.basic index 36af35eae2..8a5539c21b 100644 --- a/Task/Heronian-triangles/FutureBasic/heronian-triangles.basic +++ b/Task/Heronian-triangles/FutureBasic/heronian-triangles.basic @@ -1,16 +1,13 @@ -include "ConsoleWindow" - -// Set width of tabs -def tab 10 +text,,,,,70// Set width of tabs local fn gcd( a as long, b as long ) -dim as long result + dim as long result -if ( b != 0 ) - result = fn gcd( b, a mod b) -else - result = abs(a) -end if + if ( b != 0 ) + result = fn gcd( b, a mod b) + else + result = abs(a) + end if end fn = result begin globals @@ -18,32 +15,32 @@ dim as long triangleInfo( 600, 4 ) end globals local fn CalculateHeronianTriangles( numberToCheck as long ) as long -dim as long c, b, a, result, count : count = 0 -dim as double s, area + dim as long c, b, a, result, count : count = 0 + dim as double s, area -for c = 1 to numberToCheck - for b = 1 to c + for c = 1 to numberToCheck + for b = 1 to c for a = 1 to b - s = ( a + b + c ) / 2 - area = s * ( s - a ) * ( s - b ) * ( s - c ) - if area > 0 - area = sqr( area ) - if area = int( area ) - result = fn gcd( b, c ) - result = fn gcd( a, result ) - if result == 1 - count++ - triangleInfo( count, 0 ) = a - triangleInfo( count, 1 ) = b - triangleInfo( count, 2 ) = c - triangleInfo( count, 3 ) = 2 * s - triangleInfo( count, 4 ) = area - end if - end if - end if + s = ( a + b + c ) / 2 + area = s * ( s - a ) * ( s - b ) * ( s - c ) + if area > 0 + area = sqr( area ) + if area = int( area ) + result = fn gcd( b, c ) + result = fn gcd( a, result ) + if result == 1 + count++ + triangleInfo( count, 0 ) = a + triangleInfo( count, 1 ) = b + triangleInfo( count, 2 ) = c + triangleInfo( count, 3 ) = 2 * s + triangleInfo( count, 4 ) = area + end if + end if + end if next - next -next + next + next end fn = count dim as long i, k, count @@ -60,27 +57,29 @@ print "---------------------------------------------" // Sort array dim as Boolean flips : flips = _true while ( flips = _true ) - flips = _false - for i = 1 to count - 1 - if triangleInfo( i, 4 ) > triangleInfo( i + 1, 4 ) - for k = 0 to 4 - swap triangleInfo( i, k ), triangleInfo( i + 1, k ) - next + flips = _false + for i = 1 to count - 1 + if triangleInfo( i, 4 ) > triangleInfo( i + 1, 4 ) + for k = 0 to 4 + swap triangleInfo( i, k ), triangleInfo( i + 1, k ) + next flips = _true - end if - next + end if + next wend // Find first 10 heronian triangles for i = 1 to 10 - print triangleInfo( i, 0 ), triangleInfo( i, 1 ), triangleInfo( i, 2 ), triangleInfo( i, 3 ), triangleInfo( i, 4 ) + print triangleInfo( i, 0 ), triangleInfo( i, 1 ), triangleInfo( i, 2 ), triangleInfo( i, 3 ), triangleInfo( i, 4 ) next print print "Triangles with an area of 210:" print // Search for triangle with area of 210 for i = 1 to count - if triangleInfo( i, 4 ) == 210 - print triangleInfo( i, 0 ), triangleInfo( i, 1 ), triangleInfo( i, 2 ), triangleInfo( i, 3 ), triangleInfo( i, 4 ) - end if + if triangleInfo( i, 4 ) == 210 + print triangleInfo( i, 0 ), triangleInfo( i, 1 ), triangleInfo( i, 2 ), triangleInfo( i, 3 ), triangleInfo( i, 4 ) + end if next + +HandleEvents diff --git a/Task/Hofstadter-Q-sequence/Maxima/hofstadter-q-sequence.maxima b/Task/Hofstadter-Q-sequence/Maxima/hofstadter-q-sequence.maxima new file mode 100644 index 0000000000..9516c7747d --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Maxima/hofstadter-q-sequence.maxima @@ -0,0 +1,11 @@ +/* Function that return the terms of the Hofstadter Q sequence */ +hofstadter(n):=block( + if member(n,[1,2]) then L[n]:1 else L[n]:L[n-L[n-1]]+L[n-L[n-2]], + L[n])$ + +/* Test cases */ +/* First ten terms */ +makelist(hofstadter(i),i,1,10); + +/* 1000th term */ +last(makelist(hofstadter(i),i,1,1000)); diff --git a/Task/Holidays-related-to-Easter/FutureBasic/holidays-related-to-easter.basic b/Task/Holidays-related-to-Easter/FutureBasic/holidays-related-to-easter.basic new file mode 100644 index 0000000000..14a98a2d12 --- /dev/null +++ b/Task/Holidays-related-to-Easter/FutureBasic/holidays-related-to-easter.basic @@ -0,0 +1,80 @@ +begin enum 1 + _window : _scroll : _showOff + _clmYear : _clmEaster : _lblYear : _lblEaster + _inField : _outField +end enum + +void local fn buildInterface + window _window, @"Easter dates", ( 0, 0, 200, 200 ), 3 + scrollview _scroll, ( 20, 80, 170, 91 ) + textview _showOff, , _scroll + textlabel _clmYear, @"Year", ( 21, 168, 60, 22 ) + textlabel _clmEaster, @"Easter", ( 92, 168, 140, 22 ) + textlabel _lblYear, @"Year:", ( 40, 40, 100, 22 ) + textlabel _lblEaster, @"Easter:", ( 31, 10, 100, 22 ) + textlabel _outField, @"14 April", ( 87, 10, 100, 22 ) + textfield _inField, , @"14250", ( 85, 42, 70, 22 ) + ControlSetFormat ( _inField, @"0123456789", YES, 7, 0 ) + TextSetFont( _showOff, fn FontMonospacedDigitSystemFontOfSize( 12 , 0 ) ) + menu 1, , , @"File" : menu 1, 0, , @"Close", @"w" + MenuItemSetAction(1, 0, @"performClose:") + editmenu 2 + WindowMakeFirstResponder( _window, _inField ) +end fn + +clear local fn easter( year as NSInteger) as CFStringRef + NSInteger goldenNumber, leapDays, century, epact + NSInteger moonAdjust, leapAdjust,fullMoon, easter + CFStringRef s = @"" + goldenNumber = year mod 19 + 1 ' moon phase on 1 Jan + if year < 1583 + // Algorithm by Dionysius Exiguus, 525 + leapDays = 5 * year / 4 ' one leap year every four years + epact = ( 11 * goldenNumber - 4 ) mod 30 ' moon phase on 22 March + else + // Algorithm by Christoph Clavius, 1582 (see D. Knuth: CACM 1962;5:209) + century = int( year / 100 ) + 1 + leapAdjust = int( ( 3 * century / 4 ) - 12 ) ' correct leap years + leapDays = int( 5 * year / 4 ) - leapAdjust - 10 ' new calculation of leap days + moonAdjust = int( ( 8 * century + 5 ) / 25 ) - 5 ' correct moon cycle + epact = ( 11 * goldenNumber + moonAdjust - leapAdjust + 20 ) mod 30 ' new calculation of moon phase + if epact < 0 then epact += 30 + if ( epact = 24 or ( epact = 25 and goldenNumber > 11 ) ) then epact ++ ' final tweaks + end if + fullMoon = 44 - epact ' find first full moon in March + if fullMoon < 21 then fullMoon += 30 ' not before 21 March + easter = fullMoon + 7 - ( ( leapDays + fullMoon ) mod 7 ) ' find Sunday after first full moon in March + if easter < 32 + s = fn StringWithFormat( @"%u March", easter ) + else + s = fn StringWithFormat( @"%u April", easter - 31 ) + end if +end fn = s + +void local fn showOff + NSInteger year + CFMutableStringRef s = @"", t + for year = 532 to 2100 ' 532 is first year of Dionysius' tables + t = fn StringWithFormat( @"%u%@%@\n", year, @" ", fn easter( year) ) + s = fn StringByAppendingString( s, t ) + next + s = left( s, len( s ) - 1 ) ' cosmetic: remove last line feed + TextSetString( _showOff, s ) +end fn + +void local fn doEvents( evt as Long, tag as Long ) + NSInteger t + select evt + case _textFieldDidChange + ControlSetStringValue ( _outField, @"" ) + t = fn ControlIntegerValue( _inField ) + if t > 531 then ControlSetStringValue ( _outField, fn easter( t ) ) + case _windowShouldClose : end + end select +end fn + +fn buildInterface +fn showOff +on dialog fn doEvents + +handleevents diff --git a/Task/Image-noise/C++/image-noise.cpp b/Task/Image-noise/C++/image-noise-1.cpp similarity index 100% rename from Task/Image-noise/C++/image-noise.cpp rename to Task/Image-noise/C++/image-noise-1.cpp diff --git a/Task/Image-noise/C++/image-noise-2.cpp b/Task/Image-noise/C++/image-noise-2.cpp new file mode 100644 index 0000000000..0449890c11 --- /dev/null +++ b/Task/Image-noise/C++/image-noise-2.cpp @@ -0,0 +1,103 @@ +// Standard C++ stuff +#include +#include +#include + +// SDL2 stuff +#include "SDL2/SDL.h" + +// Other crazy stuffs +#define SCREEN_WIDTH 320 +#define SCREEN_HEIGHT 240 +#define COLOUR_BLACK 0, 0, 0, 0xff +#define COLOUR_WHITE 0xff, 0xff, 0xff, 0xff + +// Compile: g++ -std=c++20 -Wall -Wextra -pedantic ImageNoise.cpp -o ImageNoise -lSDL2 + +template +void BlitNoise(SDL_Renderer *r, int width, int height, auto &dist, RandomGenerator &generator) { + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { + // Use the random number generator in C++ Standard Library to determine draw colour + if (dist(generator) == 0) + // Set colour to black + SDL_SetRenderDrawColor(r, COLOUR_BLACK); + else if (dist(generator) == 1) + // Set colour to white + SDL_SetRenderDrawColor(r, COLOUR_WHITE); + // Go through every scanline, and put pixels + SDL_RenderDrawPoint(r, x, y); + } + } +} + +void UpdateFPS(unsigned &frame_count, unsigned &timer, SDL_Window *window) { + static Uint64 LastTime = 0; + std::string NewWindowTitle; + Uint64 Time = SDL_GetTicks(), + Delta = Time - LastTime; + timer += Delta; + if (timer > 1000) { + unsigned ElapsedTime = timer / 1000; + NewWindowTitle = "Image noise - " + std::to_string((int)((float)frame_count/(float)ElapsedTime)) + " FPS"; // Dirty string trick + SDL_SetWindowTitle(window, const_cast(NewWindowTitle.c_str())); + timer = 0; + frame_count = 0; + NewWindowTitle.clear(); + } + LastTime = Time; +} + +int main() { + std::random_device Device; // Random number device + std::mt19937_64 Generator(Device()); // Random number generator + std::uniform_int_distribution ColourState(0, 1); // Colour state + unsigned Frames = 0, + Timer = 0; + + SDL_Window *Window = NULL; // Define window + SDL_Renderer *Renderer = NULL; // Define renderer + + // Init everything just for sure + SDL_Init(SDL_INIT_EVERYTHING); + + // Set window size to 320x240, always shown + Window = SDL_CreateWindow("Image noise - ?? FPS", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); + Renderer = SDL_CreateRenderer(Window, -1, SDL_RENDERER_ACCELERATED); + + // Set background colour to white + SDL_SetRenderDrawColor(Renderer, COLOUR_WHITE); + SDL_RenderClear(Renderer); + + // Create an event handler and a "quit" flag + SDL_Event e; + bool KillWindow = false; + + // The window runs until the "quit" flag is set to true + while (!KillWindow) { + while (SDL_PollEvent(&e) != 0) { + // Go through the events in the queue + switch (e.type) { + // Event: user hits a key + case SDL_QUIT: case SDL_KEYDOWN: + // Destroy window + KillWindow = true; + break; + } + } + // Render the noise + BlitNoise(Renderer, SCREEN_WIDTH, SCREEN_HEIGHT, ColourState, Generator); + SDL_RenderPresent(Renderer); + // Increment the "Frames" variable. + // Then show the FPS count in the window title. + ++Frames; + UpdateFPS(Frames, Timer, Window); + } + + // Destroy renderer and window + SDL_DestroyRenderer(Renderer); + SDL_DestroyWindow(Window); + SDL_Quit(); + + return 0; +} diff --git a/Task/Increment-a-numerical-string/ARM-Assembly/increment-a-numerical-string.arm b/Task/Increment-a-numerical-string/ARM-Assembly/increment-a-numerical-string.arm index d56a8e442d..c6f0b72b6f 100644 --- a/Task/Increment-a-numerical-string/ARM-Assembly/increment-a-numerical-string.arm +++ b/Task/Increment-a-numerical-string/ARM-Assembly/increment-a-numerical-string.arm @@ -200,4 +200,3 @@ divisionpar10: bx lr /* leave function */ .align 4 .Ls_magic_number_10: .word 0x66666667 - diff --git a/Task/Increment-a-numerical-string/Dc/increment-a-numerical-string-1.dc b/Task/Increment-a-numerical-string/Dc/increment-a-numerical-string-1.dc new file mode 100644 index 0000000000..146b51f3c1 --- /dev/null +++ b/Task/Increment-a-numerical-string/Dc/increment-a-numerical-string-1.dc @@ -0,0 +1 @@ +? 1 + p diff --git a/Task/Increment-a-numerical-string/Dc/increment-a-numerical-string-2.dc b/Task/Increment-a-numerical-string/Dc/increment-a-numerical-string-2.dc new file mode 100644 index 0000000000..e78d792443 --- /dev/null +++ b/Task/Increment-a-numerical-string/Dc/increment-a-numerical-string-2.dc @@ -0,0 +1 @@ +echo '12345678899' | dc inc.dc diff --git a/Task/Increment-a-numerical-string/Dt/increment-a-numerical-string.dt b/Task/Increment-a-numerical-string/Dt/increment-a-numerical-string.dt new file mode 100644 index 0000000000..b969c8ee12 --- /dev/null +++ b/Task/Increment-a-numerical-string/Dt/increment-a-numerical-string.dt @@ -0,0 +1 @@ +"1234567889" to-int 1 + to-string diff --git a/Task/Increment-a-numerical-string/Joy/increment-a-numerical-string.joy b/Task/Increment-a-numerical-string/Joy/increment-a-numerical-string.joy new file mode 100644 index 0000000000..1513ef7734 --- /dev/null +++ b/Task/Increment-a-numerical-string/Joy/increment-a-numerical-string.joy @@ -0,0 +1,3 @@ +DEFINE incstr == 10 strtol succ 'd 1 1 format. + +"1234567889" incstr. diff --git a/Task/Increment-a-numerical-string/Maxima/increment-a-numerical-string.maxima b/Task/Increment-a-numerical-string/Maxima/increment-a-numerical-string.maxima new file mode 100644 index 0000000000..080c1a35ad --- /dev/null +++ b/Task/Increment-a-numerical-string/Maxima/increment-a-numerical-string.maxima @@ -0,0 +1,3 @@ +inc_string(str):=if stringp(str) and numberp(eval_string(str)) then string(eval_string(str)+1)$ +"12345"$ +inc_string(%); diff --git a/Task/Increment-a-numerical-string/Raku/increment-a-numerical-string.raku b/Task/Increment-a-numerical-string/Raku/increment-a-numerical-string.raku index 9a9d64805d..9a3455d32a 100644 --- a/Task/Increment-a-numerical-string/Raku/increment-a-numerical-string.raku +++ b/Task/Increment-a-numerical-string/Raku/increment-a-numerical-string.raku @@ -1,2 +1,7 @@ -my $s = "12345"; -$s++; +say my $s = "12345"; +say ++$s; + +# or Unicode. How about Sinhala? + +say "෧෨෩෪෫ ", +"෧෨෩෪෫"; +say "෧෨෩෪෫".succ, ' ', +"෧෨෩෪෫".succ; diff --git a/Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol b/Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol index ffdf7abb72..c497454597 100644 --- a/Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol +++ b/Task/Inheritance-Multiple/COBOL/inheritance-multiple.cobol @@ -1,12 +1,16 @@ + IDENTIFICATION DIVISION. CLASS-ID. Camera. *> ... END CLASS Camera. + IDENTIFICATION DIVISION. CLASS-ID. Mobile-Phone. *> ... END CLASS Mobile-Phone. - CLASS-ID. Camera-Phone INHERITS Camera, Mobile-Phone. + IDENTIFICATION DIVISION. + CLASS-ID. Camera-Phone + INHERITS FROM Camera, Mobile-Phone. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. diff --git a/Task/Inheritance-Single/COBOL/inheritance-single.cobol b/Task/Inheritance-Single/COBOL/inheritance-single.cobol index b0291f50fa..ef8431fdba 100644 --- a/Task/Inheritance-Single/COBOL/inheritance-single.cobol +++ b/Task/Inheritance-Single/COBOL/inheritance-single.cobol @@ -1,8 +1,11 @@ + IDENTIFICATION DIVISION. CLASS-ID. Animal. *> ... END CLASS Animal. - CLASS-ID. Dog INHERITS Animal. + IDENTIFICATION DIVISION. + CLASS-ID. Dog + INHERITS FROM Animal. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. @@ -11,7 +14,9 @@ *> ... END CLASS Dog. - CLASS-ID. Cat INHERITS Animal. + IDENTIFICATION DIVISION. + CLASS-ID. Cat + INHERITS FROM Animal. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. @@ -20,7 +25,9 @@ *> ... END CLASS Cat. - CLASS-ID. Lab INHERITS Dog. + IDENTIFICATION DIVISION. + CLASS-ID. Lab + INHERITS FROM Dog. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. @@ -29,7 +36,9 @@ *> ... END CLASS Lab. - CLASS-ID. Collie INHERITS Dog. + IDENTIFICATION DIVISION. + CLASS-ID. Collie + INHERITS FROM Dog. ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. diff --git a/Task/Iterated-digits-squaring/00-TASK.txt b/Task/Iterated-digits-squaring/00-TASK.txt index 48501e938e..11f77daf98 100644 --- a/Task/Iterated-digits-squaring/00-TASK.txt +++ b/Task/Iterated-digits-squaring/00-TASK.txt @@ -24,5 +24,6 @@ For a quick algorithm for this task see [[Talk:Iterated_digits_squaring|the talk * [[Combinations with repetitions]] * [[Digital root]] * [[Digital root/Multiplicative digital root]] +* [[Happy numbers]]

diff --git a/Task/Jewels-and-stones/AArch64-Assembly/jewels-and-stones.aarch64 b/Task/Jewels-and-stones/AArch64-Assembly/jewels-and-stones.aarch64 new file mode 100644 index 0000000000..b994d646a3 --- /dev/null +++ b/Task/Jewels-and-stones/AArch64-Assembly/jewels-and-stones.aarch64 @@ -0,0 +1,106 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program jewels64.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessResult: .asciz "Result: " +szStone1: .asciz "aAAbbbb" +szJewels1: .asciz "aA" +szStone2: .asciz "ZZ" +szJewels2: .asciz "z" +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 64 bits start.\n" +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sZoneConv: .skip 24 +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: // entry of program + ldr x0,qAdrszMessStart + bl affichageMess + + ldr x0,qAdrszStone1 + ldr x1,qAdrszJewels1 + bl countJewels + ldr x0,qAdrszStone2 + ldr x1,qAdrszJewels2 + bl countJewels + +100: // standard end of the program + mov x0, #0 // return code + mov x8, #EXIT // request to exit program + svc 0 // perform the system call +qAdrszStone1: .quad szStone1 +qAdrszJewels1: .quad szJewels1 +qAdrszStone2: .quad szStone2 +qAdrszJewels2: .quad szJewels2 +qAdrsZoneConv: .quad sZoneConv +qAdrszMessResult: .quad szMessResult +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessStart: .quad szMessStart +/***************************************************/ +/* count jewels in stone */ +/***************************************************/ +/* r0 contains stone address */ +/* r1 contains jewels address */ +/* r0 return jewels count */ +countJewels: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + mov x4,#0 // counter + mov x3,#0 // index stone +1: + ldrb w6,[x0,x3] // load byte of stone + cmp x6,#0 // end stone ? + beq 3f + mov x5,#0 // index jewels +2: + ldrb w2,[x1,x5] // load byte of jewels + cmp x2,#0 // end jewels ? + cinc x3,x3,eq // yes -> increment index stone + beq 1b // and loop + cmp x6,x2 // compare byte + cinc x5,x5,ne // not equal -> increment jewels index + bne 2b // and loop + add x4,x4,#1 // else increment counter + add x3,x3,#1 // incremente index stone + b 1b // and loop + +3: // result display + mov x0,x4 + ldr x1,qAdrsZoneConv + bl conversion10 + ldr x0,qAdrszMessResult + bl affichageMess + ldr x0,qAdrsZoneConv + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + + mov x0,x4 + 100: + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 + ret +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Jewels-and-stones/ARM-Assembly/jewels-and-stones.arm b/Task/Jewels-and-stones/ARM-Assembly/jewels-and-stones.arm new file mode 100644 index 0000000000..4a347030a9 --- /dev/null +++ b/Task/Jewels-and-stones/ARM-Assembly/jewels-and-stones.arm @@ -0,0 +1,99 @@ +/* ARM assembly Raspberry PI */ +/* program jewels.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../constantes.inc" + +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessResult: .asciz "Result: " +szStone1: .asciz "aAAbbbb" +szJewels1: .asciz "aA" +szStone2: .asciz "ZZ" +szJewels2: .asciz "z" +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 32 bits start.\n" +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sZoneConv: .skip 24 +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: @ entry of program + ldr r0,iAdrszMessStart + bl affichageMess + + ldr r0,iAdrszStone1 + ldr r1,iAdrszJewels1 + bl countJewels + ldr r0,iAdrszStone2 + ldr r1,iAdrszJewels2 + bl countJewels + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform the system call +iAdrszStone1: .int szStone1 +iAdrszJewels1: .int szJewels1 +iAdrszStone2: .int szStone2 +iAdrszJewels2: .int szJewels2 +iAdrsZoneConv: .int sZoneConv +iAdrszMessResult: .int szMessResult +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessStart: .int szMessStart +/***************************************************/ +/* count jewels in stone */ +/***************************************************/ +/* r0 contains stone address */ +/* r1 contains jewels address */ +/* r0 return jewels count */ +countJewels: + push {r1-r6,lr} @ save registers + mov r4,#0 @ counter + mov r3,#0 @ index stone +1: + ldrb r6,[r0,r3] @ load byte of stone + cmp r6,#0 @ end stone ? + beq 3f + mov r5,#0 @ index jewels +2: + ldrb r2,[r1,r5] @ load byte of jewels + cmp r2,#0 @ end jewels ? + addeq r3,r3,#1 @ yes -> increment index stone + beq 1b @ and loop + cmp r6,r2 @ compare byte + addne r5,r5,#1 @ not equal -> increment jewels index + bne 2b @ and loop + add r4,r4,#1 @ else increment counter + add r3,r3,#1 @ incremente index stone + b 1b @ and loop + +3: @ result display + mov r0,r4 + ldr r1,iAdrsZoneConv + bl conversion10 + ldr r0,iAdrszMessResult + bl affichageMess + ldr r0,iAdrsZoneConv + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + + mov r0,r4 + 100: + pop {r1-r6,pc} +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../affichage.inc" diff --git a/Task/Jordan-P-lya-numbers/Perl/jordan-p-lya-numbers.pl b/Task/Jordan-P-lya-numbers/Perl/jordan-p-lya-numbers.pl new file mode 100644 index 0000000000..e413d6d42e --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Perl/jordan-p-lya-numbers.pl @@ -0,0 +1,34 @@ +use strict; +use warnings; +use feature 'say'; + +use ntheory 'factorial'; +use List::AllUtils ; + +sub table { my $t = 10 * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr } + +sub Jordan_Polya { + my $limit = shift; + my($k,@JP) = (2); + push @JP, factorial $_ for 0..18; + + while ($k < @JP) { + my $rk = $JP[$k]; + for my $l (2 .. @JP) { + my $kl = $JP[$l] * $rk; + last if $kl > $limit; + LOOP: { + my $p = firstidx { $_ >= $kl } @JP; + if ($p < $#JP and $JP[$p] != $kl) { splice @JP, $p, 0, $kl } + elsif ($p == $#JP ) { push @JP, $kl } + $kl > $limit/$rk ? last LOOP : ($kl *= $rk) + } + } + $k++ + } + shift @JP; return @JP +} + +my @JP = Jordan_Polya 2**27; +say "First 50 Jordan-Pólya numbers:\n" . table @JP[0..49]; +say 'The largest Jordan-Pólya number before 100 million: ' . $JP[-1 + firstidx { $_ > 1e8 } @JP]; diff --git a/Task/Jordan-P-lya-numbers/Raku/jordan-p-lya-numbers.raku b/Task/Jordan-P-lya-numbers/Raku/jordan-p-lya-numbers.raku index c69a328db1..12f2ace7f7 100644 --- a/Task/Jordan-P-lya-numbers/Raku/jordan-p-lya-numbers.raku +++ b/Task/Jordan-P-lya-numbers/Raku/jordan-p-lya-numbers.raku @@ -14,7 +14,7 @@ sub JordanPolya (\limit) { loop { my \p = @res.keys.first: { @res[$_] >= kl } # performance if p < @res.elems and @res[p] != kl { - @res = |@res[^p], kl, |@res[p..*] + @res.splice: p, 0, kl } elsif p == @res.elems { @res.append: kl } diff --git a/Task/Josephus-problem/Maxima/josephus-problem.maxima b/Task/Josephus-problem/Maxima/josephus-problem.maxima new file mode 100644 index 0000000000..fb8fda3045 --- /dev/null +++ b/Task/Josephus-problem/Maxima/josephus-problem.maxima @@ -0,0 +1,6 @@ +josephus_list(n,k):=(result:[],pos:1,ref:makelist(i,i,n),while ref#[] do (pos:mod(pos+k-2,length(ref))+1,push(ref[pos],result),ref:delete(ref[pos],ref)), + reverse(result)); +/* Example */ +/* last_survivor:last(josephus_list(41,3)); + 31 +*/ diff --git a/Task/Juggler-sequence/Java/juggler-sequence.java b/Task/Juggler-sequence/Java/juggler-sequence.java new file mode 100644 index 0000000000..013cd3c3a4 --- /dev/null +++ b/Task/Juggler-sequence/Java/juggler-sequence.java @@ -0,0 +1,47 @@ +import java.math.BigInteger; +import java.util.List; + +public final class JugglerSequence { + + public static void main(String[] aArgs) { + System.out.println(" n l[n] i[n] h[n]"); + System.out.println("---------------------------------"); + for ( int number = 20; number <= 39; number++ ) { + JugglerData result = juggler(number); + System.out.println(String.format("%2d%7d%6d%17d", + number, result.aCount, result.aMaxCount, result.aMaxNumber)); + } + System.out.println(); + + List values = List.of( 113, 173, 193, 2183, 11229, 15065, 15845, 30817 ); + System.out.println(" n l[n] i[n] d[n]"); + System.out.println("----------------------------"); + for ( int value : values ) { + JugglerData result = juggler(value); + System.out.println(String.format("%5d%8d%7d%7d", + value, result.aCount, result.aMaxCount, result.aDigitCount)); + } + } + + private static JugglerData juggler(int aNumber) { + if ( aNumber < 1 ) { + throw new IllegalArgumentException("Starting value must be >= 1: " + aNumber); + } + BigInteger number = BigInteger.valueOf(aNumber); + int count = 0; + int maxCount = 0; + BigInteger maxNumber = number; + while ( ! number.equals(BigInteger.ONE) ) { + number = number.testBit(0) ? number.pow(3).sqrt() : number.sqrt(); + count = count + 1; + if ( number.compareTo(maxNumber) > 0 ) { + maxNumber = number; + maxCount = count; + } + } + return new JugglerData(count, maxCount, maxNumber, String.valueOf(maxNumber).length()); + } + + private static record JugglerData(int aCount, int aMaxCount, BigInteger aMaxNumber, int aDigitCount) {} + +} diff --git a/Task/Jump-anywhere/COBOL/jump-anywhere-1.cobol b/Task/Jump-anywhere/COBOL/jump-anywhere-1.cobol index 6aab3bba2a..bf93cb8fd8 100644 --- a/Task/Jump-anywhere/COBOL/jump-anywhere-1.cobol +++ b/Task/Jump-anywhere/COBOL/jump-anywhere-1.cobol @@ -1,24 +1,32 @@ -IDENTIFICATION DIVISION. -PROGRAM-ID. JUMPS-PROGRAM. + IDENTIFICATION DIVISION. + PROGRAM-ID. jumps-program. * Nobody writes like this, of course; but... -PROCEDURE DIVISION. + + PROCEDURE DIVISION. + * You can jump anywhere you like. -START-PARAGRAPH. - GO TO AN-ARBITRARY-PARAGRAPH. -YET-ANOTHER-PARAGRAPH. - ALTER START-PARAGRAPH TO PROCEED TO A-PARAGRAPH-SOMEWHERE. + start-paragraph. + GO TO an-arbitrary-paragraph. + + yet-another-paragraph. + ALTER start-paragraph TO PROCEED TO a-paragraph-somewhere. * That's right, folks: we don't just have GO TOs, we have GO TOs whose * destinations can be changed at will, from anywhere in the program, * at run time. - GO TO START-PARAGRAPH. + GO TO start-paragraph. * But bear in mind: once you get there, the GO TO no longer goes to * where it says it goes to. -A-PARAGRAPH-SOMEWHERE. - DISPLAY 'Never heard of him.' - STOP RUN. -SOME-OTHER-PARAGRAPH. + + a-paragraph-somewhere. + DISPLAY 'Never heard of him.' + STOP RUN. + + some-other-paragraph. * You think that's bad? You ain't seen nothing. - GO TO YET-ANOTHER-PARAGRAPH. -AN-ARBITRARY-PARAGRAPH. - DISPLAY 'Edsger who now?' - GO TO SOME-OTHER-PARAGRAPH. + GO TO yet-another-paragraph. + + an-arbitrary-paragraph. + DISPLAY 'Edsger who now?' + GO TO some-other-paragraph. + + END PROGRAM jumps-program. diff --git a/Task/Jump-anywhere/COBOL/jump-anywhere-2.cobol b/Task/Jump-anywhere/COBOL/jump-anywhere-2.cobol index 085c474889..fcfea66a67 100644 --- a/Task/Jump-anywhere/COBOL/jump-anywhere-2.cobol +++ b/Task/Jump-anywhere/COBOL/jump-anywhere-2.cobol @@ -1,2 +1,7 @@ -01 province pic 99 value 2. -GO TO quebec, ontario, manitoba DEPENDING ON province + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 province PICTURE IS 99 VALUE IS 2. + + PROCEDURE DIVISION. + GO TO quebec, ontario, manitoba DEPENDING ON province. +* Jumps to section or paragraph named 'ontario'. diff --git a/Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-1.cobol b/Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-1.cobol index 1467920456..843028801b 100644 --- a/Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-1.cobol +++ b/Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-1.cobol @@ -1,86 +1,85 @@ - *> - *> Kernighan large earthquake problem - *> Tectonics: cobc -xj kernighan-earth-quakes.cob - *> quakes.txt with the 3 sample lines - *> ./kernighan-earth-quakes - *> - >>SOURCE FORMAT IS FREE - identification division. - program-id. quakes. +*> +*> Kernighan large earthquake problem +*> Tectonics: cobc -xj kernighan-earth-quakes.cob +*> quakes.txt with the 3 sample lines +*> ./kernighan-earth-quakes +*> + >>SOURCE FORMAT IS FREE + IDENTIFICATION DIVISION. + PROGRAM-ID. quakes. - environment division. - configuration section. - repository. - function all intrinsic. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + REPOSITORY. + FUNCTION ALL INTRINSIC. - input-output section. - file-control. - select quake-data - assign to command-filename - organization is line sequential - status is quake-fd-status - . + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT quake-data + ASSIGN TO command-filename + ORGANIZATION IS LINE SEQUENTIAL + STATUS IS quake-fd-status. - data division. - file section. - fd quake-data record varying depending on line-length. - 01 data-line pic x(32768). + DATA DIVISION. + FILE SECTION. + FD quake-data RECORD VARYING DEPENDING ON line-length. + 01 data-line PICTURE IS X(32768). - working-storage section. - 01 quake-fd-status pic xx. - 88 ok values "00", "01", "02", "03", "04", - "05", "06", "07", "08", "09". - 88 no-more value "10". - 88 io-error value high-value. + WORKING-STORAGE SECTION. + 01 quake-fd-status PICTURE IS XX. + 88 ok VALUES ARE "00", "01", "02", "03", "04", + "05", "06", "07", "08", "09". + 88 no-more VALUE IS "10". + 88 io-error VALUE IS HIGH-VALUE. - 01 line-length usage binary-long. + 01 line-length USAGE IS BINARY-LONG. - 01 date-time pic x(10). - 01 quake pic x(20). - 01 magnitude pic 99v99. + 01 date-time PICTURE IS X(10). + 01 quake PICTURE IS X(20). + 01 magnitude PICTURE IS 99V99. - 01 command-filename pic x(80). + 01 command-filename PICTURE IS X(80). - procedure division. - show-big-ones. + PROCEDURE DIVISION. + show-big-ones. - accept command-filename from command-line - if command-filename equal spaces then - move "data.txt" to command-filename - end-if + ACCEPT command-filename FROM COMMAND-LINE + IF command-filename IS EQUAL TO SPACES THEN + MOVE "data.txt" TO command-filename + END-IF - open input quake-data - perform status-check - if io-error then - display trim(command-filename) " not found" upon syserr - goback - end-if + OPEN INPUT quake-data + PERFORM status-check + IF io-error THEN + DISPLAY TRIM(command-filename) " not found" UPON SYSERR + GOBACK + END-IF - read quake-data - perform status-check - perform until no-more or io-error - unstring data-line delimited by all spaces - into date-time quake magnitude - end-unstring + READ quake-data + PERFORM status-check + PERFORM UNTIL no-more OR io-error + UNSTRING data-line DELIMITED BY ALL SPACES + INTO date-time quake magnitude + END-UNSTRING - if magnitude greater than 6 - display date-time space quake space magnitude - end-if + IF magnitude IS GREATER THAN 6 + DISPLAY date-time SPACE quake SPACE magnitude + END-IF - read quake-data - perform status-check - end-perform + READ quake-data + PERFORM status-check + END-PERFORM - close quake-data - perform status-check - goback. - *> **** + CLOSE quake-data + PERFORM status-check + GOBACK. +*> **** - status-check. - if not ok and not no-more then *> not normal status, bailing - display "io error: " quake-fd-status upon syserr - set io-error to true - end-if - . + status-check. + IF NOT ok AND NOT no-more THEN *> not normal status, bailing + DISPLAY "io error: " quake-fd-status UPON SYSERR + SET io-error TO TRUE + END-IF + EXIT PARAGRAPH. - end program quakes. + END PROGRAM quakes. diff --git a/Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-2.cobol b/Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-2.cobol index 152c0d2b7c..f9c324bad3 100644 --- a/Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-2.cobol +++ b/Task/Kernighans-large-earthquake-problem/COBOL/kernighans-large-earthquake-problem-2.cobol @@ -1,33 +1,33 @@ *> *> Tectonics: ./kerighan-earth-quakes { new Test("Obtain Y or N"); } ); + } + +} + +final class Test extends JFrame { + + public Test(String aTitle) { + super(aTitle); + addKeyListener( new YesOrNoKeyAdapter() ); + setVisible(true); + + try { + while ( System.in.available() > 0 ) { + System.in.read(); + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + + System.out.println("Do you want to quit the program? Y / N"); + } + +} + +final class YesOrNoKeyAdapter extends KeyAdapter { + + @Override + public void keyPressed(KeyEvent aKeyEvent) { + if ( aKeyEvent.getKeyCode() == KeyEvent.VK_Y ) { + System.out.println("Y was pressed, quitting the program"); + Runtime.getRuntime().exit(0); + } else if ( aKeyEvent.getKeyCode() == KeyEvent.VK_N ) { + System.out.println("N was pressed, but the program is about to end anyway"); + Runtime.getRuntime().exit(0); + } else { + System.out.println("Please try again, only Y or N are acceptable"); + } + } + +} diff --git a/Task/Knapsack-problem-Unbounded/C++/knapsack-problem-unbounded.cpp b/Task/Knapsack-problem-Unbounded/C++/knapsack-problem-unbounded.cpp new file mode 100644 index 0000000000..dc582802b3 --- /dev/null +++ b/Task/Knapsack-problem-Unbounded/C++/knapsack-problem-unbounded.cpp @@ -0,0 +1,85 @@ +#include +#include +#include +#include +#include +#include +#include + +struct Item { + std::string name; + int32_t value; + double weight; + double volume; +}; + +const std::vector items = { + Item("panacea", 3000, 0.3, 0.025), + Item("ichor", 1800, 0.2, 0.015), + Item("gold", 2500, 2.0, 0.002) +}; +constexpr double MAX_WEIGHT = 25.0; +constexpr double MAX_VOLUME = 0.25; + +std::vector count(items.size(), 0); +std::vector best(items.size(), 0); +int32_t best_value = 0; + +void knapsack(const uint64_t& i, const int32_t& value, const double& weight, const double& volume) { + if ( i == items.size() ) { + if ( value > best_value ) { + best_value = value; + best = count; + } + return; + } + + int32_t measure1 = (int32_t) std::floor( weight / items[i].weight ); + int32_t measure2 = (int32_t) std::floor( volume / items[i].volume ); + int32_t measure = std::min(measure1, measure2); + count[i] = measure; + + while ( count[i] >= 0 ) { + knapsack( + i + 1, + value + count[i] * items[i].value, + weight - count[i] * items[i].weight, + volume - count[i] * items[i].volume + ); + count[i]--; + } +} + +int main() { + knapsack(0, 0, MAX_WEIGHT, MAX_VOLUME); + std::cout << "Item Chosen Number Value Weight Volume" << std::endl; + std::cout << "----------- ------ ----- ------ ------" << std::endl; + int32_t item_count = 0; + int32_t number_sum = 0; + double weight_sum = 0.0; + double volume_sum = 0.0; + + for ( uint64_t i = 0; i < items.size(); ++i ) { + if ( best[i] == 0 ) { + continue; + } + + item_count++; + std::string name = items[i].name; + int32_t number = best[i]; + int32_t value = items[i].value * number; + double weight = items[i].weight * number; + double volume = items[i].volume * number; + number_sum += number; + weight_sum += weight; + volume_sum += volume; + + std::cout << std::setw(11) << name << std::setw(6) << number << std::setw(8) << value << std::fixed + << std::setw(8) << std::setprecision(2) << weight + << std::setw(8) << std::setprecision(2) << volume << std::endl; + } + + std::cout << "----------- ------ ----- ------ ------" << std::endl; + std::cout << std::setw(5) << item_count << " items" << std::setw(6) << number_sum << std::setw(8) << best_value + << std::setw(8) << weight_sum << std::setw(8) << volume_sum << std::endl; +} diff --git a/Task/Kronecker-product-based-fractals/Maxima/kronecker-product-based-fractals.maxima b/Task/Kronecker-product-based-fractals/Maxima/kronecker-product-based-fractals.maxima new file mode 100644 index 0000000000..636fd7335d --- /dev/null +++ b/Task/Kronecker-product-based-fractals/Maxima/kronecker-product-based-fractals.maxima @@ -0,0 +1,17 @@ +pow_kron(matr,n):=block(MATR:copymatrix(matr), +for i from 1 thru n do MATR:altern_kronecker(matr,MATR), +MATR); + +/* Examples (images are shown in format png)*/ +/* A to generate Vicsek fractal */ +/* B to generate Sierpinski carpet fractal */ +A:matrix([0,1,0],[1,1,1],[0,1,0])$ +B:matrix([1,1,1],[1,0,1],[1,1,1])$ + +/* Vicsek */ +pow_kron(A,3)$ +at(%,[0="",1="x"]); + +/* Sierpinski carpet */ +pow_kron(B,3)$ +at(%,[0="",1="x"]); diff --git a/Task/Kronecker-product/F-Sharp/kronecker-product.fs b/Task/Kronecker-product/F-Sharp/kronecker-product.fs new file mode 100644 index 0000000000..0424218a2f --- /dev/null +++ b/Task/Kronecker-product/F-Sharp/kronecker-product.fs @@ -0,0 +1,6 @@ +// Kronecker product. Nigel Galloway: August 31st., 2023 +open MathNet.Numerics +open MathNet.Numerics.LinearAlgebra +let m1,m2,m3,m4=matrix [[1.0;2.0];[3.0;4.0]],matrix [[0.0;5.0];[6.0;7.0]],matrix [[0.0;1.0;0.0];[1.0;1.0;1.0];[0.0;1.0;0.0]],matrix [[1.0;1.0;1.0;1.0];[1.0;0.0;0.0;1.0];[1.0;1.0;1.0;1.0]] +printfn $"{(m1.KroneckerProduct m2).ToMatrixString()}" +printfn $"{(m3.KroneckerProduct m4).ToMatrixString()}" diff --git a/Task/Kronecker-product/Maxima/kronecker-product-1.maxima b/Task/Kronecker-product/Maxima/kronecker-product-1.maxima new file mode 100644 index 0000000000..1a8d860257 --- /dev/null +++ b/Task/Kronecker-product/Maxima/kronecker-product-1.maxima @@ -0,0 +1,18 @@ +/* Function to map first, second and so on, over a list of lists without recurring corresponding built-in functions */ +auxkron(n,lst):=makelist(lst[k][n],k,1,length(lst)); + +/* Function to subdivide a list into lists of equal lengths */ +lst_equally_subdivided(lst,n):=if mod(length(lst),n)=0 then makelist(makelist(lst[i],i,j,j+n-1),j,1,length(lst)-1,n); + +/* Kronecker product implementation */ +alternative_kronecker(MatA,MatB):=block(auxlength:length(first(args(MatA))),makelist(i*args(MatB),i,flatten(args(MatA))), +makelist(apply(matrix,%%[i]),i,1,length(%%)), +lst_equally_subdivided(%%,auxlength), +makelist(map(args,%%[i]),i,1,length(%%)), +makelist(auxkron(j,%%),j,1,auxlength), +makelist(apply(append,%%[i]),i,1,length(%%)), +apply(matrix,%%), +transpose(%%), +args(%%), +makelist(apply(append,%%[i]),i,1,length(%%)), +apply(matrix,%%)); diff --git a/Task/Kronecker-product/Maxima/kronecker-product-2.maxima b/Task/Kronecker-product/Maxima/kronecker-product-2.maxima new file mode 100644 index 0000000000..b211401910 --- /dev/null +++ b/Task/Kronecker-product/Maxima/kronecker-product-2.maxima @@ -0,0 +1,8 @@ +altern_kronecker(MatA,MatB):=block(auxlength:length(first(args(MatA))), +makelist(i*args(MatB),i,flatten(args(MatA))), +makelist(apply(matrix,%%[i]),i,1,length(%%)), +lst_equally_subdivided(%%,auxlength), +makelist(apply(addcol,%%[i]),i,1,length(%%)), +map(args,%%), +apply(append,%%), +apply(matrix,%%)); diff --git a/Task/Largest-int-from-concatenated-ints/Maxima/largest-int-from-concatenated-ints.maxima b/Task/Largest-int-from-concatenated-ints/Maxima/largest-int-from-concatenated-ints.maxima new file mode 100644 index 0000000000..6608ba81c7 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Maxima/largest-int-from-concatenated-ints.maxima @@ -0,0 +1,19 @@ +/* Function that decompose a number into a list of its digits using conversions between numbers and strings */ +decompose_n_s(n):=block( +string(n), +charlist(%%), +map(eval_string,%%))$ + +/* Function that orders the list obtained by decompose_n_ according to ordergreat and then orders the result to reached what is needed to solve the problem */ +largest_from_list(lst):=( + sort(map(decompose_n_s,lst),ordergreatp), + sort(%%,lambda([a,b],if last(a)>last(b) then rest(b,-1)=a else rest(a,-1)=b)), + map(string,flatten(%%)), + simplode(%%), + eval_string(%%)); + +/* Test cases */ +test1: [1, 34, 3, 98, 9, 76, 45, 4]$ +test2: [54, 546, 548, 60]$ +largest_from_list(test1); +largest_from_list(test2); diff --git a/Task/Largest-proper-divisor-of-n/Java/largest-proper-divisor-of-n.java b/Task/Largest-proper-divisor-of-n/Java/largest-proper-divisor-of-n.java new file mode 100644 index 0000000000..a9b35d5d39 --- /dev/null +++ b/Task/Largest-proper-divisor-of-n/Java/largest-proper-divisor-of-n.java @@ -0,0 +1,25 @@ +public final class LargestProperDivisor { + + public static void main(String[] aArgs) { + for ( int n = 1; n < 101; n++ ) { + System.out.print(String.format("%2d%s", largestProperDivisor(n), ( n % 10 == 0 ? "\n" : " " ))); + } + } + + private static int largestProperDivisor(int aNumber) { + if ( aNumber < 1 ) { + throw new IllegalArgumentException("Argument must be >= 1: " + aNumber); + } + + if ( ( aNumber & 1 ) == 0 ) { + return aNumber >> 1; + } + for ( int p = 3; p * p <= aNumber; p += 2 ) { + if ( aNumber % p == 0 ) { + return aNumber / p; + } + } + return 1; + } + +} diff --git a/Task/Leonardo-numbers/Maxima/leonardo-numbers.maxima b/Task/Leonardo-numbers/Maxima/leonardo-numbers.maxima new file mode 100644 index 0000000000..eac1c812fc --- /dev/null +++ b/Task/Leonardo-numbers/Maxima/leonardo-numbers.maxima @@ -0,0 +1,11 @@ +/* Function that return the terms of an specified Leonardo sequence */ +leo_specified(n,L0,L1,add):=block( + if n=0 then L[n]:L0 else if n=1 then L[n]:L1 else L[n]:L[n-1]+L[n-2]+add, + L[n])$ + +/* Test cases */ +/* First 25 terms of Leonardo numbers (specification (1,1,1)) */ +makelist(leo_specified(i,1,1,1),i,0,25); + +/* First 25 terms of Fibonacci numbers (specification (0,1,0)) */ +makelist(leo_specified(i,0,1,0),i,0,25); diff --git a/Task/Letter-frequency/AArch64-Assembly/letter-frequency.aarch64 b/Task/Letter-frequency/AArch64-Assembly/letter-frequency.aarch64 new file mode 100644 index 0000000000..b6a3df826b --- /dev/null +++ b/Task/Letter-frequency/AArch64-Assembly/letter-frequency.aarch64 @@ -0,0 +1,174 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program cptletters64.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" +.equ BUFFERSIZE, 300000 + +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessOpen: .asciz "File open error.\n" +szMessStat: .asciz "File information error.\n" +szMessRead: .asciz "File read error.\n" +szMessClose: .asciz "File close error.\n" +szMessDecryptText: .asciz "Decrypted text :\n" +szMessCryptText: .asciz "Encrypted text :\n" +szMessErrorChar: .asciz "Character text not Ok!\n" +szFileName: .asciz "unixdict.txt" +//szFileName: .asciz "test1.txt" +szMessResult: .asciz "Result: = " +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 64 bits start.\n" +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sZoneConv: .skip 24 +tabCptLetters: .skip 8 * 52 // (A-Z a-z) counter array +sBuffer: .skip BUFFERSIZE // file buffer +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: // entry of program + ldr x0,qAdrszMessStart + bl affichageMess + mov x0,AT_FDCWD + ldr x1,qAdrszFileName // file name + mov x2,#O_RDWR // flags + mov x3,#0 // mode + mov x8,#OPEN // file open + svc 0 + cmp x0,#0 // error ? + ble 99f + mov x9,x0 // FD save + + mov x0,x9 + ldr x1,qAdrsBuffer + ldr x2,#iBufferSize + mov x8,#READ // call system read file + svc 0 + cmp x0,#0 // error read ? + blt 97f + mov x6,x0 // file size + mov x0,x9 + mov x8,#CLOSE // call system close file + svc 0 + cmp x0,#0 // error close ? + blt 96f + ldr x0,qAdrsBuffer + mov x1,x6 + bl cptLetters + + b 100f +96: + ldr x0,qAdrszMessClose + bl affichageMess + mov x0,#-1 // error + b 100f +97: + ldr x0,qAdrszMessRead + bl affichageMess + mov x0,#-1 // error + b 100f +99: + ldr x0,qAdrszMessOpen + bl affichageMess + mov x0,#-1 // error + +100: // standard end of the program + mov x0, #0 // return code + mov x8, #EXIT // request to exit program + svc 0 // perform the system call + +qAdrsZoneConv: .quad sZoneConv +qAdrszMessResult: .quad szMessResult +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessStart: .quad szMessStart +qAdrszFileName: .quad szFileName +qAdrszMessOpen: .quad szMessOpen +qAdrszMessRead: .quad szMessRead +qAdrszMessStat: .quad szMessStat +qAdrszMessClose: .quad szMessClose +qAdrsBuffer: .quad sBuffer +iBufferSize: .quad BUFFERSIZE +/***************************************************/ +/* letters frequency */ +/***************************************************/ +/* r0 contains a file buffer */ +/* r1 contains string length */ +cptLetters: + stp x1,lr,[sp,-16]! + stp x2,x3,[sp,-16]! + stp x4,x5,[sp,-16]! + stp x6,x7,[sp,-16]! + ldr x4,qAdrtabCptLetters // counter array + mov x3,#0 // index string +1: + ldrb w2,[x0,x3] // load byte of string + cmp x2,#'A' // select alpha characters lower or upper + blt 5f + cmp x2,#'Z' + bgt 2f + sub x5,x2,#65 // convert ascii upper in index array (0-25) + b 3f +2: + cmp x2,#'z' + bgt 5f + cmp x2,#'a' + blt 5f + sub x5,x2,#97 - 26 // convert ascii lower in index array (26,52] +3: + ldr x7,[x4,x5,lsl #3] // load counter of load character + add x7,x7,#1 // increment counter + str x7,[x4,x5,lsl #3] // and store +5: + add x3,x3,#1 // increment text index + cmp x3,x1 // end ? + blt 1b // and loop + + ldr x7,qAdrszMessResult + mov x2,65 // for upper ascci character + mov x3,#0 +6: // result display + ldr x1,[x4,x3,lsl #3] // load counter + cmp x1,#0 // if zero not display + beq 7f + cmp x3,#25 // upper ? + add x2,x3,65 // for upper ascci character + add x8,x3,#97 - 26 // lower + csel x6,x2,x8,le // compute ascii character + strb w6,[x7,#9] // store in message + mov x0,x1 // convert count in decimal + ldr x1,qAdrsZoneConv + bl conversion10 + ldr x0,qAdrszMessResult // and display + bl affichageMess + ldr x0,qAdrsZoneConv + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess +7: + add x3,x3,#1 + cmp x3,#52 + blt 6b + + + 100: + ldp x6,x7,[sp],16 + ldp x4,x5,[sp],16 + ldp x2,x3,[sp],16 + ldp x1,lr,[sp],16 // TODO: retaur à completer + ret +qAdrtabCptLetters: .quad tabCptLetters +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/Letter-frequency/ARM-Assembly/letter-frequency.arm b/Task/Letter-frequency/ARM-Assembly/letter-frequency.arm new file mode 100644 index 0000000000..d338ab2db0 --- /dev/null +++ b/Task/Letter-frequency/ARM-Assembly/letter-frequency.arm @@ -0,0 +1,168 @@ +/* ARM assembly Raspberry PI */ +/* program cptletters.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../constantes.inc" +.equ READ, 3 +.equ WRITE, 4 +.equ OPEN, 5 +.equ CLOSE, 6 +.equ O_RDWR, 0x0002 @ open for reading and writing +.equ BUFFERSIZE, 300000 +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessOpen: .asciz "File open error.\n" +szMessStat: .asciz "File information error.\n" +szMessRead: .asciz "File read error.\n" +szMessClose: .asciz "File close error.\n" +szMessDecryptText: .asciz "Decrypted text :\n" +szMessCryptText: .asciz "Encrypted text :\n" +szMessErrorChar: .asciz "Character text not Ok!\n" +szFileName: .asciz "unixdict.txt" +//szFileName: .asciz "test1.txt" +szMessResult: .asciz "Result: = " +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 32 bits start.\n" +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sZoneConv: .skip 24 +tabCptLetters: .skip 4 * 52 @ (A-Z a-z) counter array +sBuffer: .skip BUFFERSIZE @ file buffer +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: @ entry of program + ldr r0,iAdrszMessStart + bl affichageMess + ldr r0,iAdrszFileName @ file name + mov r1,#O_RDWR @ flags + mov r2,#0 @ mode + mov r7,#OPEN @ file open + svc 0 + cmp r0,#0 @ error ? + ble 99f + mov r8,r0 @ FD save + + mov r0,r8 + ldr r1,iAdrsBuffer + ldr r2,#iBufferSize + mov r7,#READ @ call system read file + svc 0 + cmp r0,#0 @ error read ? + blt 97f + mov r6,r0 @ file size + mov r0,r8 + mov r7,#CLOSE @ call system close file + svc 0 + cmp r0,#0 @ error close ? + blt 96f + ldr r0,iAdrsBuffer + mov r1,r6 + bl cptLetters + + b 100f +96: + ldr r0,iAdrszMessClose + bl affichageMess + mov r0,#-1 @ error + b 100f +97: + ldr r0,iAdrszMessRead + bl affichageMess + mov r0,#-1 @ error + b 100f +99: + ldr r0,iAdrszMessOpen + bl affichageMess + mov r0,#-1 @ error + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform the system call + +iAdrsZoneConv: .int sZoneConv +iAdrszMessResult: .int szMessResult +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessStart: .int szMessStart +iAdrszFileName: .int szFileName +iAdrszMessOpen: .int szMessOpen +iAdrszMessRead: .int szMessRead +iAdrszMessStat: .int szMessStat +iAdrszMessClose: .int szMessClose +iAdrsBuffer: .int sBuffer +iBufferSize: .int BUFFERSIZE +/***************************************************/ +/* letters frequency */ +/***************************************************/ +/* r0 contains a file buffer */ +/* r1 contains string length */ +cptLetters: + push {r1-r7,lr} @ save registers + ldr r4,iAdrtabCptLetters @ counter array + mov r3,#0 @ index string +1: + ldrb r2,[r0,r3] @ load byte of string + cmp r2,#'A' @ select alpha characters lower or upper + blt 5f + cmp r2,#'Z' + bgt 2f + sub r5,r2,#65 @ convert ascii upper in index array (0-25) + b 3f +2: + cmp r2,#'z' + bgt 5f + cmp r2,#'a' + blt 5f + sub r5,r2,#97 - 26 @ convert ascii lower in index array (26,52] +3: + ldr r7,[r4,r5,lsl #2] @ load counter of load character + add r7,r7,#1 @ increment counter + str r7,[r4,r5,lsl #2] @ and store +5: + add r3,r3,#1 @ increment text index + cmp r3,r1 @ end ? + blt 1b @ and loop + + ldr r7,iAdrszMessResult + mov r3,#0 +6: @ result display + ldr r1,[r4,r3,lsl #2] @ load counter + cmp r1,#0 @ if zero not display + beq 7f + cmp r3,#25 @ upper ? + addle r6,r3,#65 @ yes compute ascci character + addgt r6,r3,#97 - 26 @ lower + strb r6,[r7,#9] @ store in message + mov r0,r1 @ convert count in decimal + ldr r1,iAdrsZoneConv + bl conversion10 + ldr r0,iAdrszMessResult @ and display + bl affichageMess + ldr r0,iAdrsZoneConv + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess +7: + add r3,r3,#1 + cmp r3,#52 + blt 6b + + + 100: + pop {r1-r7,pc} +iAdrtabCptLetters: .int tabCptLetters +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../affichage.inc" diff --git a/Task/Levenshtein-distance-Alignment/C++/levenshtein-distance-alignment.cpp b/Task/Levenshtein-distance-Alignment/C++/levenshtein-distance-alignment.cpp new file mode 100644 index 0000000000..78d0a6d5e8 --- /dev/null +++ b/Task/Levenshtein-distance-Alignment/C++/levenshtein-distance-alignment.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include + +std::string to_lower_case(const std::string& text) { + std::string result = text; + std::transform(result.begin(), result.end(), result.begin(), + [](char ch){ return std::tolower(ch); }); + return result; +} + +std::vector levenshtein_alignment(std::string a, std::string b) { + a = to_lower_case(a); + b = to_lower_case(b); + + std::vector> costs{ a.length() + 1, std::vector( b.length() + 1, 0 ) }; + for ( uint64_t j = 0; j <= b.length(); ++j ) + costs[0][j] = j; + for ( uint64_t i = 1; i <= a.length(); ++i ) { + costs[i][0] = i; + for ( uint64_t j = 1; j <= b.length(); ++j ) { + costs[i][j] = std::min(std::min( costs[i - 1][j], costs[i][j - 1]) + 1, + a[i - 1] == b[j - 1] ? costs[i - 1][j - 1] : costs[i - 1][j - 1] + 1); + } + } + + std::string a_path_reversed, b_path_reversed; + uint64_t i = a.length(), j = b.length(); + while ( i != 0 && j != 0 ) { + if ( costs[i][j] == ( a[i - 1] == b[j - 1] ? costs[i - 1][j - 1] : costs[i - 1][j - 1] + 1 ) ) { + a_path_reversed += a[--i]; + b_path_reversed += b[--j]; + } else if ( costs[i][j] == costs[i - 1][j] + 1 ) { + a_path_reversed += a[--i]; + b_path_reversed += "-"; + } else if ( costs[i][j] == costs[i][j - 1] + 1 ) { + a_path_reversed += "-"; + b_path_reversed += b[--j]; + } + } + + std::reverse(a_path_reversed.begin(), a_path_reversed.end()); + std::reverse(b_path_reversed.begin(), b_path_reversed.end()); + return std::vector{ a_path_reversed, b_path_reversed }; +} + +int main() { + std::vector result = levenshtein_alignment("place", "palace"); + std::cout << result[0] << std::endl; + std::cout << result[1] << std::endl; + std::cout << std::endl; + + result = levenshtein_alignment("rosettacode", "raisethysword"); + std::cout << result[0] << std::endl; + std::cout << result[1] << std::endl; +} diff --git a/Task/Long-literals-with-continuations/C++/long-literals-with-continuations.cpp b/Task/Long-literals-with-continuations/C++/long-literals-with-continuations.cpp new file mode 100644 index 0000000000..4c0ec18a95 --- /dev/null +++ b/Task/Long-literals-with-continuations/C++/long-literals-with-continuations.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include +#include + +const std::string ELEMENTS = R"( + hydrogen helium lithium beryllium + boron carbon nitrogen oxygen + fluorine neon sodium magnesium + aluminum silicon phosphorous sulfur + chlorine argon potassium calcium + scandium titanium vanadium chromium + manganese iron cobalt nickel + copper zinc gallium germanium + arsenic selenium bromine krypton + rubidium strontium yttrium zirconium + niobium molybdenum technetium ruthenium + rhodium palladium silver cadmium + indium tin antimony tellurium + iodine xenon cesium barium + lanthanum cerium praseodymium neodymium + promethium samarium europium gadolinium + terbium dysprosium holmium erbium + thulium ytterbium lutetium hafnium + tantalum tungsten rhenium osmium + iridium platinum gold mercury + thallium lead bismuth polonium + astatine radon francium radium + actinium thorium protactinium uranium + neptunium plutonium americium curium + berkelium californium einsteinium fermium + mendelevium nobelium lawrencium rutherfordium + dubnium seaborgium bohrium hassium + meitnerium darmstadtium roentgenium copernicium + nihonium flerovium moscovium livermorium + tennessine oganesson + )"; + +const std::string UNNAMED_ELEMENTS = R"( + ununennium unquadnilium triunhexium penthextrium + penthexpentium septhexunium octenntrium ennennbium + )"; + +std::vector rawstring_to_vector(const std::string& text, const char& delimiter) { + std::regex regx("\\s+"); + std::string delimit(1, delimiter); + std::string elements = std::regex_replace(text, regx, delimit); + elements = elements.substr(1, elements.size() - 2); + + std::vector result; + std::stringstream stream(elements); + std::string item; + while ( getline(stream, item, delimiter) ) { + result.push_back (item); + } + return result; +} + +int main() { + std::vector elements = rawstring_to_vector(ELEMENTS, ' '); + std::vector unnamed = rawstring_to_vector(UNNAMED_ELEMENTS, ' '); + + elements.erase(std::remove_if(elements.begin(), elements.end(), + [unnamed](std::string text){ return std::find(unnamed.begin(), unnamed.end(), text) != unnamed.end(); }), + elements.end()); + + const std::string zone = "Asia/Shanghai"; + const std::chrono::zoned_time zoned_time { zone, std::chrono::system_clock::now() }; + + std::cout << "Last revision Date: " << std::format("{:%Y-%m-%d Time %H:%M}", zoned_time) + << " " << zone << std::endl; + std::cout << "Number of elements: " << elements.size() << std::endl; + std::cout << "Last element : " << elements[elements.size() - 1] << std::endl; +} diff --git a/Task/Long-literals-with-continuations/Java/long-literals-with-continuations.java b/Task/Long-literals-with-continuations/Java/long-literals-with-continuations.java new file mode 100644 index 0000000000..325a0091b9 --- /dev/null +++ b/Task/Long-literals-with-continuations/Java/long-literals-with-continuations.java @@ -0,0 +1,65 @@ +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Arrays; +import java.util.List; + +public final class LongLiteralsWithContinuations { + + public static void main(String[] aArgs) { + ZoneId zoneID = ZoneId.of("Asia/Shanghai"); + ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneID); + String dateTime = zonedDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a")); + + List elements = splitToList(ELEMENTS).stream(). + filter( s -> ! splitToList(UNNAMED_ELEMENTS).contains(s) ).toList(); + + System.out.println("Last revision Date: " + dateTime + " " + zoneID); + System.out.println("Number of elements: " + elements.size()); + System.out.println("Last element : " + elements.get(elements.size() - 1)); + } + + private static List splitToList(String aText) { + String excessWhiteSpaceRemoved = aText.trim().replaceAll("\\s+", " "); + return Arrays.stream(excessWhiteSpaceRemoved.split(" ")).toList(); + } + + private static final String ELEMENTS = """ + hydrogen helium lithium beryllium + boron carbon nitrogen oxygen + fluorine neon sodium magnesium + aluminum silicon phosphorous sulfur + chlorine argon potassium calcium + scandium titanium vanadium chromium + manganese iron cobalt nickel + copper zinc gallium germanium + arsenic selenium bromine krypton + rubidium strontium yttrium zirconium + niobium molybdenum technetium ruthenium + rhodium palladium silver cadmium + indium tin antimony tellurium + iodine xenon cesium barium + lanthanum cerium praseodymium neodymium + promethium samarium europium gadolinium + terbium dysprosium holmium erbium + thulium ytterbium lutetium hafnium + tantalum tungsten rhenium osmium + iridium platinum gold mercury + thallium lead bismuth polonium + astatine radon francium radium + actinium thorium protactinium uranium + neptunium plutonium americium curium + berkelium californium einsteinium fermium + mendelevium nobelium lawrencium rutherfordium + dubnium seaborgium bohrium hassium + meitnerium darmstadtium roentgenium copernicium + nihonium flerovium moscovium livermorium + tennessine oganesson + """; + + private static final String UNNAMED_ELEMENTS = """ + ununennium unquadnilium triunhexium penthextrium + penthexpentium septhexunium octenntrium ennennbium + """; + +} diff --git a/Task/Look-and-say-sequence/Maxima/look-and-say-sequence.maxima b/Task/Look-and-say-sequence/Maxima/look-and-say-sequence-1.maxima similarity index 100% rename from Task/Look-and-say-sequence/Maxima/look-and-say-sequence.maxima rename to Task/Look-and-say-sequence/Maxima/look-and-say-sequence-1.maxima diff --git a/Task/Look-and-say-sequence/Maxima/look-and-say-sequence-2.maxima b/Task/Look-and-say-sequence/Maxima/look-and-say-sequence-2.maxima new file mode 100644 index 0000000000..50b5b81dd5 --- /dev/null +++ b/Task/Look-and-say-sequence/Maxima/look-and-say-sequence-2.maxima @@ -0,0 +1,25 @@ +ciphers(n):=block(makelist(floor(mod(n, 10^(k+1)) / 10^k), k, 0,floor(log(n)/log(10))),reverse(%%)); + +collect(a) := block( + [n: length(ciphers(a)), b: [ ], x: ciphers(a)[1], m: 1], + for i from 2 thru n do + (if ciphers(a)[i] = x then m: m + 1 else (b: endcons([x, m], b), x: ciphers(a)[i], m: 1)), + b: endcons([x, m], b), + map(reverse,%%), + flatten(%%), + at(sum((part(%%,k))*y^(length(%%)-k),k,1,length(%%)),y=10) + )$ + +block(i:1,append([i],makelist(i:collect(i),9)),table_form(%%)); +/* matrix( + [1], + [11], + [21], + [1211], + [111221], + [312211], + [13112221], + [1113213211], + [31131211131221], + [13211311123113112211] + ) */ diff --git a/Task/Loop-over-multiple-arrays-simultaneously/FutureBasic/loop-over-multiple-arrays-simultaneously.basic b/Task/Loop-over-multiple-arrays-simultaneously/FutureBasic/loop-over-multiple-arrays-simultaneously.basic new file mode 100644 index 0000000000..cf430d50b3 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/FutureBasic/loop-over-multiple-arrays-simultaneously.basic @@ -0,0 +1,14 @@ +void local fn DoIt + CFArrayRef a1 = @[@"a",@"b",@"c"] + CFArrayRef a2 = @[@"A",@"B",@"C"] + CFArrayRef a3 = @[@"1",@"2",@"3"] + + long i, count = len(a1) + for i = 0 to count - 1 + print a1[i]a2[i]a3[i] + next +end fn + +fn DoIt + +HandleEvents 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 index 61eece3d70..9b2ceb927a 100644 --- 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 @@ -1,2 +1,10 @@ {-# LANGUAGE ParallelListComp #-} -main = sequence [ putStrLn [x, y, z] | x <- "abc" | y <- "ABC" | z <- "123"] + +main :: IO [()] +main = + sequence + [ putStrLn [x, y, z] + | x <- "abc" + | y <- "ABC" + | z <- "123" + ] diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Maxima/loop-over-multiple-arrays-simultaneously.maxima b/Task/Loop-over-multiple-arrays-simultaneously/Maxima/loop-over-multiple-arrays-simultaneously.maxima new file mode 100644 index 0000000000..a439a32d92 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Maxima/loop-over-multiple-arrays-simultaneously.maxima @@ -0,0 +1,8 @@ +/* Function that loops over multiple arrays simultaneously depending on the list with less length */ +lomas(L):=block( + minlen:lmin(map(length,L)), + makelist(makelist(L[i][j],i,1,length(L)),j,1,minlen))$ + +/* Test case */ +lst:[[a,b,c],[A,B,C],[1,2,3]]$ +lomas(lst); diff --git a/Task/Loops-Break/Kotlin/loops-break.kotlin b/Task/Loops-Break/Kotlin/loops-break-1.kotlin similarity index 100% rename from Task/Loops-Break/Kotlin/loops-break.kotlin rename to Task/Loops-Break/Kotlin/loops-break-1.kotlin diff --git a/Task/Loops-Break/Kotlin/loops-break-2.kotlin b/Task/Loops-Break/Kotlin/loops-break-2.kotlin new file mode 100644 index 0000000000..9b49afefda --- /dev/null +++ b/Task/Loops-Break/Kotlin/loops-break-2.kotlin @@ -0,0 +1,4 @@ +fun main() { + while ((0..19).random().also { println(it) } != 10) + println((0..19).random()) +} diff --git a/Task/Loops-Continue/LDPL/loops-continue.ldpl b/Task/Loops-Continue/LDPL/loops-continue.ldpl new file mode 100644 index 0000000000..b8aad0a80d --- /dev/null +++ b/Task/Loops-Continue/LDPL/loops-continue.ldpl @@ -0,0 +1,14 @@ +data: +i is number +n is number + +procedure: +for i from 1 to 11 step 1 do + display i + modulo i by 5 in n + if n is equal to 0 then + display lf + continue + end if + display ", " +repeat diff --git a/Task/Loops-Continue/Maxima/loops-continue.maxima b/Task/Loops-Continue/Maxima/loops-continue-1.maxima similarity index 100% rename from Task/Loops-Continue/Maxima/loops-continue.maxima rename to Task/Loops-Continue/Maxima/loops-continue-1.maxima diff --git a/Task/Loops-Continue/Maxima/loops-continue-2.maxima b/Task/Loops-Continue/Maxima/loops-continue-2.maxima new file mode 100644 index 0000000000..9fb1af0fb2 --- /dev/null +++ b/Task/Loops-Continue/Maxima/loops-continue-2.maxima @@ -0,0 +1,3 @@ +for n:1 thru 10 do ( + sprint(n), + if n=5 then newline())$ diff --git a/Task/Loops-Downward-for/LDPL/loops-downward-for.ldpl b/Task/Loops-Downward-for/LDPL/loops-downward-for.ldpl new file mode 100644 index 0000000000..900440d858 --- /dev/null +++ b/Task/Loops-Downward-for/LDPL/loops-downward-for.ldpl @@ -0,0 +1,7 @@ +data: +i is number + +procedure: +for i from 10 to -1 step -1 do + display i lf +repeat diff --git a/Task/Loops-For-with-a-specified-step/FutureBasic/loops-for-with-a-specified-step.basic b/Task/Loops-For-with-a-specified-step/FutureBasic/loops-for-with-a-specified-step.basic index faa79e7121..38baf98c95 100644 --- a/Task/Loops-For-with-a-specified-step/FutureBasic/loops-for-with-a-specified-step.basic +++ b/Task/Loops-For-with-a-specified-step/FutureBasic/loops-for-with-a-specified-step.basic @@ -1,7 +1,5 @@ -include "ConsoleWindow" - -dim as Str15 s(11) -dim as long i +Str15 s(11) +long i s(0) = "Somewhere" s(2) = " over" @@ -13,3 +11,5 @@ s(10) = " fly." for i = 0 to 10 step 2 print s(i); next + +HandleEvents diff --git a/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-1.ksh b/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-1.ksh new file mode 100644 index 0000000000..72b5d0b783 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-1.ksh @@ -0,0 +1,5 @@ +x=0 +while (((x += 2) <= 8)) +do + print -r "$x" +done diff --git a/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-2.ksh b/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-2.ksh new file mode 100644 index 0000000000..375f6ac847 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-2.ksh @@ -0,0 +1,4 @@ +for x in {2..8..2} +do + print -r "$x" +done diff --git a/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-3.ksh b/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-3.ksh new file mode 100644 index 0000000000..6d8ebc4f80 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-3.ksh @@ -0,0 +1,3 @@ +for (( x=2; $x<=8; x=$x+2 )); do + printf "%d, " $x +done diff --git a/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-4.ksh b/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-4.ksh new file mode 100644 index 0000000000..65675d30fc --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Ksh/loops-for-with-a-specified-step-4.ksh @@ -0,0 +1,4 @@ +for x in {2..8..2} +do + echo $x +done diff --git a/Task/Loops-For-with-a-specified-step/LDPL/loops-for-with-a-specified-step.ldpl b/Task/Loops-For-with-a-specified-step/LDPL/loops-for-with-a-specified-step.ldpl new file mode 100644 index 0000000000..bddb10a458 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/LDPL/loops-for-with-a-specified-step.ldpl @@ -0,0 +1,9 @@ +# Display the even numbers up to twenty. + +data: +i is number + +procedure: +for i from 0 to 21 step 2 do + display i lf +repeat diff --git a/Task/Loops-For/Ksh/loops-for.ksh b/Task/Loops-For/Ksh/loops-for.ksh new file mode 100644 index 0000000000..61f4f92d73 --- /dev/null +++ b/Task/Loops-For/Ksh/loops-for.ksh @@ -0,0 +1,8 @@ +for ((x = 1; x <= 5; x += 1)) +do + for ((y = 0; y < x; y += 1)) + do + print -n '*' + done + print +done diff --git a/Task/Loops-For/LDPL/loops-for.ldpl b/Task/Loops-For/LDPL/loops-for.ldpl new file mode 100644 index 0000000000..f4898dc945 --- /dev/null +++ b/Task/Loops-For/LDPL/loops-for.ldpl @@ -0,0 +1,11 @@ +data: +i is number +j is number + +procedure: +for i from 1 to 6 step 1 do + for j from 0 to i step 1 do + display "*" + repeat + display lf +repeat diff --git a/Task/Loops-Foreach/ALGOL-68/loops-foreach-2.alg b/Task/Loops-Foreach/ALGOL-68/loops-foreach-2.alg index a985805593..bef9cfffde 100644 --- a/Task/Loops-Foreach/ALGOL-68/loops-foreach-2.alg +++ b/Task/Loops-Foreach/ALGOL-68/loops-foreach-2.alg @@ -1,3 +1,3 @@ -FORALL index IN collection DO - print((collection[index]," ")) +FORALL c IN collection DO + print((c," ")) OD diff --git a/Task/Loops-Foreach/LDPL/loops-foreach.ldpl b/Task/Loops-Foreach/LDPL/loops-foreach.ldpl new file mode 100644 index 0000000000..249c2dacb6 --- /dev/null +++ b/Task/Loops-Foreach/LDPL/loops-foreach.ldpl @@ -0,0 +1,9 @@ +data: +fruits is text list +fruit is text + +procedure: +split "apple banana orange" by " " in fruits +for each fruit in fruits do + display fruit lf +repeat diff --git a/Task/Loops-Infinite/Craft-Basic/loops-infinite.basic b/Task/Loops-Infinite/Craft-Basic/loops-infinite.basic new file mode 100644 index 0000000000..43199461ac --- /dev/null +++ b/Task/Loops-Infinite/Craft-Basic/loops-infinite.basic @@ -0,0 +1,3 @@ +do + print "SPAM" +loop diff --git a/Task/Loops-Infinite/LDPL/loops-infinite.ldpl b/Task/Loops-Infinite/LDPL/loops-infinite.ldpl new file mode 100644 index 0000000000..dd2454b3a9 --- /dev/null +++ b/Task/Loops-Infinite/LDPL/loops-infinite.ldpl @@ -0,0 +1,4 @@ +procedure: +label spam +display "SPAM" lf +goto spam diff --git a/Task/Loops-N-plus-one-half/00-TASK.txt b/Task/Loops-N-plus-one-half/00-TASK.txt index dff9175149..70489992a9 100644 --- a/Task/Loops-N-plus-one-half/00-TASK.txt +++ b/Task/Loops-N-plus-one-half/00-TASK.txt @@ -1,32 +1,28 @@ Quite often one needs loops which, in the last iteration, execute only part of the loop body. - ;Goal: Demonstrate the best way to do this. - ;Task: Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 using separate output statements for the number and the comma from within the body of the loop. - ;Related tasks: -*   [[Loop over multiple arrays simultaneously]] -*   [[Loops/Break]] -*   [[Loops/Continue]] -*   [[Loops/Do-while]] -*   [[Loops/Downward for]] -*   [[Loops/For]] -*   [[Loops/For with a specified step]] -*   [[Loops/Foreach]] -*   [[Loops/Increment loop index within loop body]] -*   [[Loops/Infinite]] -*   [[Loops/N plus one half]] -*   [[Loops/Nested]] -*   [[Loops/While]] -*   [[Loops/with multiple ranges]] -*   [[Loops/Wrong ranges]] -

+* [[Loop over multiple arrays simultaneously]] +* [[Loops/Break]] +* [[Loops/Continue]] +* [[Loops/Do-while]] +* [[Loops/Downward for]] +* [[Loops/For]] +* [[Loops/For with a specified step]] +* [[Loops/Foreach]] +* [[Loops/Increment loop index within loop body]] +* [[Loops/Infinite]] +* [[Loops/N plus one half]] +* [[Loops/Nested]] +* [[Loops/While]] +* [[Loops/with multiple ranges]] +* [[Loops/Wrong ranges]] diff --git a/Task/Loops-Nested/FutureBasic/loops-nested.basic b/Task/Loops-Nested/FutureBasic/loops-nested.basic new file mode 100644 index 0000000000..68f867b9dd --- /dev/null +++ b/Task/Loops-Nested/FutureBasic/loops-nested.basic @@ -0,0 +1,18 @@ +long a(9,9), i, j +BOOL done = NO + +for i = 0 to 9 + for j = 0 to 9 + a(i,j) = rnd(20) + next +next + +for i = 0 to 9 + for j = 0 to 9 + print a(i,j) + if ( a(i,j) == 20 ) then done = YES : break + next + if ( done ) then break +next + +HandleEvents diff --git a/Task/Loops-While/LDPL/loops-while.ldpl b/Task/Loops-While/LDPL/loops-while.ldpl new file mode 100644 index 0000000000..1faefe309d --- /dev/null +++ b/Task/Loops-While/LDPL/loops-while.ldpl @@ -0,0 +1,10 @@ +data: +n is number + +procedure: +store 1024 in n +while n is greater than 0 do + display n lf + divide n by 2 in n + floor n +repeat diff --git a/Task/Loops-Wrong-ranges/Arturo/loops-wrong-ranges.arturo b/Task/Loops-Wrong-ranges/Arturo/loops-wrong-ranges.arturo index 46c99ea7b6..1d3aad1ba5 100644 --- a/Task/Loops-Wrong-ranges/Arturo/loops-wrong-ranges.arturo +++ b/Task/Loops-Wrong-ranges/Arturo/loops-wrong-ranges.arturo @@ -1,19 +1,18 @@ print "start stop increment" loop @[ - 0-2 2 1 - 0-2 2 0 - 0-2 2 0-1 - 0-2 2 10 - 2 0-2 1 - 2 2 1 - 2 2 0-1 - 2 2 0 - 0 0 0 -] [start stop increment] -> + neg 2 2 1 + neg 2 2 0 + neg 2 2 neg 1 + neg 2 2 10 + 2 neg 2 1 + 2 2 1 + 2 2 neg 1 + 2 2 0 + 0 0 0 ] +[start stop increment] -> print [ pad ~"|start|" 2 pad ~"|stop|" 7 pad ~"|increment|" 7 - pad "->" 9 - try? -> @range.step: increment start stop - else -> "Error" + pad "->" 9 try? -> @range.step: increment start stop + else -> "Error" ] diff --git a/Task/Loops-Wrong-ranges/C++/loops-wrong-ranges.cpp b/Task/Loops-Wrong-ranges/C++/loops-wrong-ranges.cpp new file mode 100644 index 0000000000..ef6a43fd98 --- /dev/null +++ b/Task/Loops-Wrong-ranges/C++/loops-wrong-ranges.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include + +struct LoopData { + int32_t start; + int32_t stop; + int32_t increment; + std::string comment; +}; + +void print_vector(const std::vector& list) { + std::cout << "["; + for ( uint64_t i = 0; i < list.size(); ++i ) { + std::cout << list[i]; + if ( i < list.size() - 1 ) { + std::cout << ", "; + } + } + std::cout << "]"; +} + +void runTest(const LoopData& loop_data) { + std::vector values{}; + for ( int32_t i = loop_data.start; i <= loop_data.stop; i += loop_data.increment ) { + values.emplace_back(i); + if ( values.size() >= 10 ) { + break; + } + } + + std::cout << std::left << std::setw(45) << loop_data.comment; print_vector(values); + std::cout << ( values.size() == 10 ? " (loops forever)" : "" ) << std::endl; +} + +int main() { + runTest(LoopData(-2, 2, 1, "Normal")); + runTest(LoopData(-2, 2, 0, "Zero increment")); + runTest(LoopData(-2, 2, -1, "Increments away from stop value")); + runTest(LoopData(-2, 2, 10, "First increment is beyond stop value")); + runTest(LoopData(2, -2, 1, "Start more than stop: positive increment")); + runTest(LoopData(2, 2, 1, "Start equal stop: positive increment")); + runTest(LoopData(2, 2, -1, "Start equal stop: negative increment")); + runTest(LoopData(2, 2, 0, "Start equal stop: zero increment")); + runTest(LoopData(0, 0, 0, "Start equal stop equal zero: zero increment")); +} diff --git a/Task/MD4/C++/md4.cpp b/Task/MD4/C++/md4.cpp new file mode 100644 index 0000000000..8158e2c879 --- /dev/null +++ b/Task/MD4/C++/md4.cpp @@ -0,0 +1,178 @@ +#include +#include +#include +#include +#include +#include + +class MD4 { +public: + MD4() { + engine_reset(); + } + + std::vector engine_digest(const std::string& text) { + engine_update(string_to_byte_vector(text), 0, text.length()); + + const int32_t buffer_index = static_cast(count % BLOCK_LENGTH); + const int32_t padding_length = ( buffer_index < 56 ) ? 56 - buffer_index : 120 - buffer_index; + + std::vector tail(padding_length + 8, 0); + tail[0] = static_cast(0x80); + + for ( int32_t i = 0; i < 8; ++i ) { + tail[padding_length + i] = static_cast(unsigned_right_shift(count * 8, 8 * i)); + } + + engine_update(tail, 0, tail.size()); + + std::vector result(16, 0); + for ( int32_t i = 0; i < 4; ++i ) { + for ( int32_t j = 0; j < 4; ++j ) { + result[i * 4 + j] = static_cast(unsigned_right_shift(context[i], 8 * j)); + } + } + + engine_reset(); + return result; + } + +private: + void engine_update(const std::vector& message_bytes, + const int32_t& offset, const int32_t& message_length) { + if ( offset < 0 || message_length < 0 + || (int64_t) offset + message_length > (int64_t) message_bytes.size() ) { + throw std::invalid_argument("Incorrect arguments for function engine_update"); + } + + int32_t buffer_index = static_cast(count % BLOCK_LENGTH); + count += message_length; + const int32_t partial_length = BLOCK_LENGTH - buffer_index; + int32_t i = 0; + + if ( message_length >= partial_length ) { + for ( int32_t j = 0; j < partial_length; ++j ) { + buffer[buffer_index + j] = message_bytes[offset + j]; + } + transform(buffer, 0); + i = partial_length; + while ( i + BLOCK_LENGTH - 1 < message_length ) { + transform(message_bytes, offset + i); + i += BLOCK_LENGTH; + } + buffer_index = 0; + } + + if ( i < message_length ) { + for ( int32_t j = 0; j < message_length - i; ++j ) { + buffer[buffer_index + j] = message_bytes[offset + i + j]; + } + } + } + + void transform(const std::vector& buffer, int32_t offset) { + for ( int32_t i = 0; i < 16; ++i ) { + extra[i] = ( ( buffer[offset + 0] & 0xff ) ) | + ( ( buffer[offset + 1] & 0xff ) << 8 ) | + ( ( buffer[offset + 2] & 0xff ) << 16 ) | + ( ( buffer[offset + 3] & 0xff ) << 24 ); + offset += 4; + } + + int32_t a = context[0]; + int32_t b = context[1]; + int32_t c = context[2]; + int32_t d = context[3]; + + for ( const int32_t& i : { 0, 4, 8, 12 } ) { + a = ff(a, b, c, d, extra[i + 0], 3); + d = ff(d, a, b, c, extra[i + 1], 7); + c = ff(c, d, a, b, extra[i + 2], 11); + b = ff(b, c, d, a, extra[i + 3], 19); + } + + for ( const int32_t& i : { 0, 1, 2, 3 } ) { + a = gg(a, b, c, d, extra[i + 0], 3); + d = gg(d, a, b, c, extra[i + 4], 5); + c = gg(c, d, a, b, extra[i + 8], 9); + b = gg(b, c, d, a, extra[i + 12], 13); + } + + for ( const int32_t& i : { 0, 2, 1, 3 } ) { + a = hh(a, b, c, d, extra[i + 0], 3); + d = hh(d, a, b, c, extra[i + 8], 9); + c = hh(c, d, a, b, extra[i + 4], 11); + b = hh(b, c, d, a, extra[i + 12], 15); + } + + context[0] += a; + context[1] += b; + context[2] += c; + context[3] += d; + } + + void engine_reset() { + count = 0; + context.assign(4, 0); + context[0] = 0x67452301; + context[1] = 0xefcdab89; + context[2] = 0x98badcfe; + context[3] = 0x10325476; + extra.assign(16, 0); + buffer.assign(BLOCK_LENGTH, 0); + } + + std::vector string_to_byte_vector(const std::string& text) { + std::vector bytes; + bytes.reserve(text.size()); + + std::transform(text.begin(), text.end(), std::back_inserter(bytes), + [](char ch){ return static_cast(ch); }); + + return bytes; + } + + int32_t unsigned_right_shift(const int32_t& base, const int32_t& shift) { + if ( base == 0 || shift >= 32 ) { + return 0; + } + return ( base > 0 ) ? base >> shift : ( base + TWO_POWER_32 ) >> shift; + } + + int32_t rotate(const int32_t& t, const int32_t& s) { + return ( t << s ) | unsigned_right_shift(t, 32 - s); + } + + int32_t ff(const int32_t& a, const int32_t& b, const int32_t& c, + const int32_t& d, const int32_t& x, const int32_t& s) { + return rotate(a + ( ( b & c ) | ( ~b & d ) ) + x, s); + } + + int32_t gg(const int32_t& a, const int32_t& b, const int32_t& c, + const int32_t& d, const int32_t& x, const int32_t& s) { + return rotate(a + ( ( b & ( c | d ) ) | ( c & d ) ) + x + 0x5A827999, s); + } + + int32_t hh(const int32_t& a, const int32_t& b, const int32_t& c, + const int32_t& d, const int32_t& x, const int32_t& s) { + return rotate(a + ( b ^ c ^ d ) + x + 0x6ED9EBA1, s); + } + + uint64_t count; + std::vector context; + std::vector extra; + std::vector buffer; + + const int32_t BLOCK_LENGTH = 64; + const int64_t TWO_POWER_32 = 4'294'967'296; +}; + +int main() { + MD4 md4; + std::vector result = md4.engine_digest("Rosetta Code"); + + for ( const int8_t& bb : result ) { + std::cout << std::hex << std::setfill('0') << std::setw(2) << ( bb & 0xff ); + } + std::cout << std::endl; +} diff --git a/Task/MD4/Java/md4.java b/Task/MD4/Java/md4-1.java similarity index 100% rename from Task/MD4/Java/md4.java rename to Task/MD4/Java/md4-1.java diff --git a/Task/MD4/Java/md4-2.java b/Task/MD4/Java/md4-2.java new file mode 100644 index 0000000000..136223d49e --- /dev/null +++ b/Task/MD4/Java/md4-2.java @@ -0,0 +1,152 @@ +import java.util.Arrays; +import java.util.List; + +public final class MD4Task { + + public static void main(String[] aArgs) { + String text = "Rosetta Code"; + + MD4 md4 = new MD4(); + byte[] result = md4.engineDigest(text); + + StringBuilder stringBuilder = new StringBuilder(); + for ( byte bb : result ) { + stringBuilder.append(String.format("%02x", bb)); + } + System.out.println(stringBuilder.toString()); + } + +} + +final class MD4 { + + public MD4() { + engineReset(); + } + + public byte[] engineDigest(String aText) { + engineUpdate(aText.getBytes(), 0, aText.length()); + + final int bufferIndex = (int) ( count % BLOCK_LENGTH ); + final int paddingLength = ( bufferIndex < 56 ) ? 56 - bufferIndex : 120 - bufferIndex; + + byte[] tail = new byte[paddingLength + 8]; + tail[0] = (byte) 0x80; + + for ( int i = 0; i < 8; i++ ) { + tail[paddingLength + i] = (byte) ( ( count * 8 ) >>> ( 8 * i ) ); + } + + engineUpdate(tail, 0, tail.length); + + byte[] result = new byte[16]; + for ( int i = 0; i < 4; i++ ) { + for ( int j = 0; j < 4; j++ ) { + result[i * 4 + j] = (byte) ( context[i] >>> ( 8 * j ) ); + } + } + + engineReset(); + return result; + } + + private void engineUpdate(byte[] aMessageBytes, int aOffset, int aMessageLength) { + if ( aOffset < 0 || aMessageLength < 0 || (long) aOffset + aMessageLength > (long) aMessageBytes.length ) { + throw new ArrayIndexOutOfBoundsException("Incorrect arguments for method engineUpdate"); + } + + int bufferIndex = (int) ( count % BLOCK_LENGTH ); + count += aMessageLength; + final int partialLength = BLOCK_LENGTH - bufferIndex; + int i = 0; + + if ( aMessageLength >= partialLength ) { + System.arraycopy(aMessageBytes, aOffset, buffer, bufferIndex, partialLength); + transform(buffer, 0); + i = partialLength; + while ( i + BLOCK_LENGTH - 1 < aMessageLength ) { + transform(aMessageBytes, aOffset + i); + i += BLOCK_LENGTH; + } + bufferIndex = 0; + } + + if ( i < aMessageLength ) { + System.arraycopy(aMessageBytes, aOffset + i, buffer, bufferIndex, aMessageLength - i); + } + } + + private void transform (byte[] aBuffer, int aOffset) { + for ( int i = 0; i < 16; i++ ) { + extra[i] = ( ( aBuffer[aOffset++] & 0xff ) ) | + ( ( aBuffer[aOffset++] & 0xff ) << 8 ) | + ( ( aBuffer[aOffset++] & 0xff ) << 16 ) | + ( ( aBuffer[aOffset++] & 0xff ) << 24 ); + } + + int a = context[0]; + int b = context[1]; + int c = context[2]; + int d = context[3]; + + for ( int i : List.of( 0, 4, 8, 12 ) ) { + a = ff(a, b, c, d, extra[i + 0], 3); + d = ff(d, a, b, c, extra[i + 1], 7); + c = ff(c, d, a, b, extra[i + 2], 11); + b = ff(b, c, d, a, extra[i + 3], 19); + } + + for ( int i : List.of( 0, 1, 2, 3 ) ) { + a = gg(a, b, c, d, extra[i + 0], 3); + d = gg(d, a, b, c, extra[i + 4], 5); + c = gg(c, d, a, b, extra[i + 8], 9); + b = gg(b, c, d, a, extra[i + 12], 13); + } + + for ( int i : List.of( 0, 2, 1, 3 ) ) { + a = hh(a, b, c, d, extra[i + 0], 3); + d = hh(d, a, b, c, extra[i + 8], 9); + c = hh(c, d, a, b, extra[i + 4], 11); + b = hh(b, c, d, a, extra[i + 12], 15); + } + + context[0] += a; + context[1] += b; + context[2] += c; + context[3] += d; + } + + private void engineReset() { + count = 0; + context[0] = 0x67452301; + context[1] = 0xefcdab89; + context[2] = 0x98badcfe; + context[3] = 0x10325476; + Arrays.fill(extra, 0); + Arrays.fill(buffer, (byte) 0); + } + + private static int rotate(int t, int s) { + return t << s | t >>> ( 32 - s ); + } + + private static int ff(int a, int b, int c, int d, int x, int s) { + return rotate(a + ( ( b & c ) | ( ~b & d ) ) + x, s); + } + + private static int gg(int a, int b, int c, int d, int x, int s) { + return rotate(a + ( ( b & ( c | d ) ) | ( c & d ) ) + x + 0x5A827999, s); + } + + private static int hh(int a, int b, int c, int d, int x, int s) { + return rotate(a + ( b ^ c ^ d ) + x + 0x6ED9EBA1, s); + } + + private static final int BLOCK_LENGTH = 64; + + private long count; + private int[] context = new int[4]; + private int[] extra = new int[16]; + private byte[] buffer = new byte[BLOCK_LENGTH]; + +} diff --git a/Task/Magic-8-ball/FOCAL/magic-8-ball.focal b/Task/Magic-8-ball/FOCAL/magic-8-ball.focal new file mode 100644 index 0000000000..cda7b414a0 --- /dev/null +++ b/Task/Magic-8-ball/FOCAL/magic-8-ball.focal @@ -0,0 +1,35 @@ +1.09 S FRAN(-1);C randomize +1.10 S FISL(80,A$);C set length to 80 char. +1.20 T !"Magic 8-Ball (Q to quit)"!! +1.30 T "What would you like to know?"! +1.40 S FSTI(80,A$(0),13);C input from console to A$, CR delimited +1.42 S Z=A$(0);I (Z-81) , 50.1;C Capital Q, if first char = then branch +1.44 S Z=A$(0);I (Z-113) , 50.1;C lowercase q, if first char = then branch + +1.50 T ! +1.60 S R=FINT(FRAN(0)*20+1);C get a random integer 1-20 +1.70 D R*2;C 'do' calculated response subroutine +1.80 T !!"What else would you like to know?"!;G 1.4;C loop up to A$ input + +2.10 T "It is certain.";R;C print a response and return from subroutine +4.10 T "It is decidedly so.";R;C etc..... +6.10 T "Without a doubt.";R +8.10 T "Yes - definitely.";R +10.10 T "You may rely on it.";R +12.10 T "As I see it, yes.";R +14.10 T "Most likely.";R +16.10 T "Outlook good.";R +18.10 T "Yes.";R +20.10 T "Signs point to yes.";R +22.10 T "Reply hazy, try again.";R +24.10 T "Ask again later.";R +26.10 T "Better not tell you now.";R +28.10 T "Cannot predict now.";R +30.10 T "Concentrate and ask again.";R +32.10 T "Don't count on it.";R +34.10 T "My reply is no.";R +36.10 T "My sources say no.";R +38.10 T "Outlook not so good.";R +40.10 T "Very doubtful.";R +50.10 T !"Thanks for consulting Magic 8-Ball for your life choices."! +50.20 Q diff --git a/Task/Magic-constant/C++/magic-constant.cpp b/Task/Magic-constant/C++/magic-constant.cpp new file mode 100644 index 0000000000..92b802661e --- /dev/null +++ b/Task/Magic-constant/C++/magic-constant.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include + +constexpr int32_t ORDER_FIRST_MAGIC_SQUARE = 3; +constexpr double LN2 = log(2.0); +constexpr double LN10 = log(10.0); + +// Return the magic constant for a magic square of the given order +int32_t magicConstant(int32_t n) { + return n * ( n * n + 1 ) / 2; +} + +// Return the smallest order of a magic square such that its magic constant is greater than 10 to the given power +int32_t minimumOrder(int32_t n) { + return (int) exp( ( LN2 + n * LN10 ) / 3 ) + 1; +} + +// Return the order of the magic square at the given index +int32_t order(int32_t index) { + return ORDER_FIRST_MAGIC_SQUARE + index - 1; +} + +int main() { + std::cout << "The first 20 magic constants:" << std::endl; + for ( int32_t i = 1; i <= 20; ++i ) { + std::cout << " " << magicConstant(order(i)); + } + std::cout << std::endl << std::endl; + + std::cout << "The 1,000th magic constant: " << magicConstant(order(1'000)) << std::endl << std::endl; + + std::cout << "Order of the smallest magic square whose constant is greater than:" << std::endl; + for ( int32_t i = 1; i <= 20; ++i ) { + std::string power_of_10 = "10^" + std::to_string(i) + ":"; + std::cout << std::setw(6) << power_of_10 << std::setw(8) << minimumOrder(i) << std::endl; + } +} diff --git a/Task/Magic-constant/Java/magic-constant.java b/Task/Magic-constant/Java/magic-constant.java new file mode 100644 index 0000000000..a4490c487f --- /dev/null +++ b/Task/Magic-constant/Java/magic-constant.java @@ -0,0 +1,38 @@ +public final class MagicConstant { + + public static void main(String[] aArgs) { + System.out.println("The first 20 magic constants:"); + for ( int i = 1; i <= 20; i++ ) { + System.out.print(" " + magicConstant(order(i))); + } + System.out.println(System.lineSeparator()); + + System.out.println("The 1,000th magic constant: " + magicConstant(order(1_000)) + System.lineSeparator()); + + System.out.println("Order of the smallest magic square whose constant is greater than:"); + for ( int i = 1; i <= 20; i++ ) { + String powerOf10 = "10^" + i + ":"; + System.out.println(String.format("%6s%8s", powerOf10, minimumOrder(i))); + } + } + + // Return the magic constant for a magic square of the given order + private static int magicConstant(int aN) { + return aN * ( aN * aN + 1 ) / 2; + } + + // Return the smallest order of a magic square such that its magic constant is greater than 10 to the given power + private static int minimumOrder(int aN) { + return (int) Math.exp( ( LN2 + aN * LN10 ) / 3 ) + 1; + } + + // Return the order of the magic square at the given index + private static int order(int aIndex) { + return ORDER_FIRST_MAGIC_SQUARE + aIndex - 1; + } + + private static final int ORDER_FIRST_MAGIC_SQUARE = 3; + private static final double LN2 = Math.log(2.0); + private static final double LN10 = Math.log(10.0); + +} diff --git a/Task/Magic-constant/Lua/magic-constant.lua b/Task/Magic-constant/Lua/magic-constant.lua new file mode 100644 index 0000000000..aa85cdf410 --- /dev/null +++ b/Task/Magic-constant/Lua/magic-constant.lua @@ -0,0 +1,20 @@ +function magic (x) + return x * (1 + x^2) / 2 +end + +print("Magic constants of orders 3 to 22:") +for i = 3, 22 do + io.write(magic(i) .. " ") +end + +print("\n\nMagic constant 1003: " .. magic(1003) .. "\n") + +print("Orders of smallest magic constant greater than...") +print("-----\t-----\nValue\tOrder\n-----\t-----") +local order = 1 +for i = 1, 20 do + repeat + order = order + 1 + until magic(order) > 10 ^ i + print("10^" .. i, order) +end diff --git a/Task/Magnanimous-numbers/BASIC/magnanimous-numbers.basic b/Task/Magnanimous-numbers/BASIC/magnanimous-numbers.basic new file mode 100644 index 0000000000..6dc800fe82 --- /dev/null +++ b/Task/Magnanimous-numbers/BASIC/magnanimous-numbers.basic @@ -0,0 +1,19 @@ +10 DEFINT A-Z +20 L = N : R = 0 : S = 1 +30 IF L < 10 GOTO 140 +40 R = R + (L MOD 10) * S +50 L = L \ 10 +60 S = S * 10 +70 P = R + L +80 IF P = 1 GOTO 120 ELSE FOR D = 2 TO SQR(P) +90 IF P MOD D = 0 GOTO 120 +100 NEXT D +110 GOTO 30 +120 N = N + 1 +130 GOTO 20 +140 I = I + 1 +150 IF I = 1 THEN PRINT "1 - 45:" ELSE IF I = 241 THEN PRINT "241 - 250:" +160 IF I <= 45 OR I > 240 THEN PRINT N, +170 N = N + 1 +180 IF I < 250 GOTO 20 +190 END diff --git a/Task/Magnanimous-numbers/BCPL/magnanimous-numbers.bcpl b/Task/Magnanimous-numbers/BCPL/magnanimous-numbers.bcpl new file mode 100644 index 0000000000..6a62937db9 --- /dev/null +++ b/Task/Magnanimous-numbers/BCPL/magnanimous-numbers.bcpl @@ -0,0 +1,39 @@ +get "libhdr" + +let prime(n) = valof +$( let d = 5 + if n<2 resultis false + if n rem 2=0 resultis n=2 + if n rem 3=0 resultis n=3 + while d*d <= n + $( if n rem d=0 resultis false + d := d+2 + if n rem d=0 resultis false + d := d+4 + $) + resultis true +$) + +let magnanimous(n) = valof +$( let left = n and right = 0 and shift = 1 + while left >= 10 + $( right := right + (left rem 10) * shift + shift := shift * 10 + left := left / 10 + unless prime(left + right) resultis false + $) + resultis true +$) + +let start() be +$( let n = -1 + for i = 1 to 250 + $( n := n+1 repeatuntil magnanimous(n) + if i=1 then writes("1 - 45:*N") + if i=241 then writes("241 - 250:*N") + if 0= 10 do + r := r + (l // 10) * 10 ** s + s := s + 1 + l := l / 10 + yield(l + r) + end +end sum_parts + +magnanimous = proc (n: int) returns (bool) + for s: int in sum_parts(n) do + if ~prime(s) then return(false) end + end + return(true) +end magnanimous + +start_up = proc () + po: stream := stream$primary_output() + n: int := 0 + i: int := 0 + c: int := 0 + + while i <= 400 do + while ~magnanimous(n) do n := n+1 end + i := i+1 + + if i=1 then stream$putl(po, "1-45:") c := 0 + elseif i=241 then stream$putl(po, "\n241-250:") c := 0 + elseif i=391 then stream$putl(po, "391-400:") c := 0 + end + + if i <= 45 cor (i > 240 cand i <= 250) cor (i > 390 cand i <= 400) then + stream$putright(po, int$unparse(n), 7) + c := c+1 + if c = 10 then stream$putl(po, "") c := 0 end + end + n := n+1 + end +end start_up diff --git a/Task/Magnanimous-numbers/Cowgol/magnanimous-numbers.cowgol b/Task/Magnanimous-numbers/Cowgol/magnanimous-numbers.cowgol new file mode 100644 index 0000000000..4926b0ad6d --- /dev/null +++ b/Task/Magnanimous-numbers/Cowgol/magnanimous-numbers.cowgol @@ -0,0 +1,58 @@ +include "cowgol.coh"; + +sub prime(n: uint32): (r: uint32) is + r := 0; + if n <= 4 or n & 1 == 0 or n % 3 == 0 then + if n == 2 or n == 3 then + r := 1; + end if; + return; + end if; + + var d: uint32 := 5; + while d*d <= n loop + if n % d == 0 then return; end if; + d := d+2; + if n % d == 0 then return; end if; + d := d+4; + end loop; + r := 1; +end sub; + +sub magnanimous(n: uint32): (r: uint32) is + r := 1; + var left: uint32 := n; + var right: uint32 := 0; + var shift: uint32 := 1; + + while left >= 10 loop + right := right + (left % 10) * shift; + shift := shift * 10; + left := left / 10; + if prime(left + right) == 0 then + r := 0; + break; + end if; + end loop; +end sub; + +var i: uint16 := 0; +var n: uint32 := 0; + +while i <= 400 loop + while magnanimous(n) == 0 loop n := n+1; end loop; + i := i + 1; + + if i == 1 then print("1 - 45:\n"); + elseif i == 241 then print("241 - 250:\n"); + elseif i == 391 then print("390 - 400:\n"); + end if; + + if i<=45 or (i>240 and i<=250) or (i>390 and i<=400) then + print_i32(n); + if i % 5 == 0 then print_nl(); + else print_char('\t'); + end if; + end if; + n := n + 1; +end loop; diff --git a/Task/Magnanimous-numbers/Draco/magnanimous-numbers.draco b/Task/Magnanimous-numbers/Draco/magnanimous-numbers.draco new file mode 100644 index 0000000000..01c62089d7 --- /dev/null +++ b/Task/Magnanimous-numbers/Draco/magnanimous-numbers.draco @@ -0,0 +1,49 @@ +proc isprime(word n) bool: + word d; + bool prime; + if n<2 then false + elif n%2=0 then n=2 + elif n%3=0 then n=3 + else + prime := true; + d := 5; + while prime and d*d <= n do + if n%d=0 then prime := false fi; + d := d+2; + if n%d=0 then prime := false fi; + d := d+4 + od; + prime + fi +corp + +proc magnanimous(word n) bool: + word left, right, shift; + bool magn; + left := n; + right := 0; + shift := 1; + magn := true; + while magn and left >= 10 do + right := right + (left % 10) * shift; + shift := shift * 10; + left := left / 10; + magn := magn and isprime(left + right) + od; + magn +corp + +proc main() void: + word n, i; + n := 0; + for i from 1 upto 250 do + while not magnanimous(n) do n := n+1 od; + if i=1 then writeln("1 - 45:") fi; + if i=241 then writeln("241 - 250:") fi; + if i<=45 or i>=241 then + write(n:7); + if i%5 = 0 then writeln() fi + fi; + n := n+1 + od +corp diff --git a/Task/Magnanimous-numbers/Modula-2/magnanimous-numbers.mod2 b/Task/Magnanimous-numbers/Modula-2/magnanimous-numbers.mod2 new file mode 100644 index 0000000000..4cbc1fc0a1 --- /dev/null +++ b/Task/Magnanimous-numbers/Modula-2/magnanimous-numbers.mod2 @@ -0,0 +1,52 @@ +MODULE MagnanimousNumbers; +FROM InOut IMPORT WriteString, WriteCard, WriteLn; + +VAR n, i: CARDINAL; + +PROCEDURE prime(n: CARDINAL): BOOLEAN; + VAR d: CARDINAL; +BEGIN + IF n<2 THEN RETURN FALSE END; + IF n MOD 2 = 0 THEN RETURN n = 2 END; + IF n MOD 3 = 0 THEN RETURN n = 3 END; + d := 5; + WHILE d*d <= n DO + IF n MOD d = 0 THEN RETURN FALSE END; + INC(d, 2); + IF n MOD d = 0 THEN RETURN FALSE END; + INC(d, 4) + END; + RETURN TRUE +END prime; + +PROCEDURE magnanimous(n: CARDINAL): BOOLEAN; + VAR left, right, shift: CARDINAL; +BEGIN + left := n; + right := 0; + shift := 1; + WHILE left >= 10 DO + INC(right, (left MOD 10) * shift); + shift := shift * 10; + left := left DIV 10; + IF NOT prime(left + right) THEN RETURN FALSE END + END; + RETURN TRUE +END magnanimous; + +BEGIN + n := 0; + FOR i := 1 TO 250 DO + WHILE NOT magnanimous(n) DO INC(n) END; + + IF i=1 THEN WriteString("1 - 45:"); WriteLn + ELSIF i=240 THEN WriteString("241 - 250:"); WriteLn + END; + + IF (i <= 45) OR (i > 240) THEN + WriteCard(n, 7); + IF i MOD 5 = 0 THEN WriteLn END + END; + INC(n) + END +END MagnanimousNumbers. diff --git a/Task/Magnanimous-numbers/Quackery/magnanimous-numbers.quackery b/Task/Magnanimous-numbers/Quackery/magnanimous-numbers.quackery new file mode 100644 index 0000000000..55ca4e4904 --- /dev/null +++ b/Task/Magnanimous-numbers/Quackery/magnanimous-numbers.quackery @@ -0,0 +1,22 @@ + [ 10 + [ 2dup /mod + over 0 = iff + [ 2drop true ] + done + + isprime not iff + false done + 10 * again ] + unrot 2drop ] is magnanimous ( n --> b ) + + [] 0 + [ dup magnanimous + if [ tuck join swap ] + 1+ + over size 250 = + until ] + drop + say "First 45 magnanimous numbers:" cr + 45 split swap echo cr cr + say "Magnanimous numbers 241-250:" cr + -10 split echo cr cr + drop diff --git a/Task/Mandelbrot-set/Bc/mandelbrot-set.bc b/Task/Mandelbrot-set/Bc/mandelbrot-set.bc new file mode 100644 index 0000000000..5d931d8520 --- /dev/null +++ b/Task/Mandelbrot-set/Bc/mandelbrot-set.bc @@ -0,0 +1,46 @@ +max_iter = 50 +width = 400; height = 401 +scale = 10 +xmin = -2; xmax = 1/2 +ymin = -5/4; ymax = 5/4 + +define mandelbrot(c_re, c_im) { + auto i + + # z = 0 + z_re = 0; z_im = 0 + z2_re = 0; z2_im = 0 + + for (i=0; i 4) return i + } + return 0 +} + +print "P2\n", width, " ", height, "\n255\n" + +for (i = 0; i < height; i++) { + y = ymin + (ymax - ymin) / height * i + for (j = 0; j < width; j++) { + x = xmin + (xmax - xmin) / width * j + tmp_scale = scale + scale = 0 + m = (255 * mandelbrot(x, y) + max_iter + 1) / max_iter + print m + if ( j < width - 1 ) print " " + scale = tmp_scale + + } + print "\n" +} + +quit diff --git a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy index 182dffa61c..894493d598 100644 --- a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy +++ b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy @@ -1,29 +1,41 @@ -center_x = 220 -center_y = 150 -scale = 150 +res = 4 +maxiter = 200 +# +# better but slower: +# res = 8 +# maxiter = 300 +# +# +mid = res * 50 +center_x = 3 * mid / 2 +center_y = mid +scale = mid +# background 000 textsize 2 # +fastproc iter cx cy . it . + while xx + yy < 4 and it > 0 + y = 2 * x * y + cy + x = xx - yy + cx + xx = x * x + yy = y * y + it -= 1 + . +. proc draw . . clear - for scr_y = 0 to 299 + for scr_y = 0 to 2 * mid - 1 cy = (scr_y - center_y) / scale - for scr_x = 0 to 299 + for scr_x = 0 to 2 * mid - 1 cx = (scr_x - center_x) / scale - x = 0 ; y = 0 ; iter = 0 - repeat - xx = x * x - yy = y * y - until xx + yy >= 4 or iter = 128 - h = xx - yy + cx - y = 2 * x * y + cy - x = h - iter += 1 - . - if iter < 128 - color3 iter / 32 iter / 128 0 - move scr_x / 3 scr_y / 3 - rect 0.4 0.4 + it = maxiter + call iter cx cy it + if it > 0 + it = maxiter - it + color3 it / 20 it / 100 it / 150 + move scr_x / res scr_y / res + rect 1 / res 1 / res . . . @@ -35,16 +47,16 @@ on mouse_down time0 = systime . on mouse_up - center_x += 150 - mouse_x * 3 - center_y += 150 - mouse_y * 3 + center_x += mid - mouse_x * res + center_y += mid - mouse_y * res if systime - time0 < 0.3 - center_x -= 150 - center_x - center_y -= 150 - center_y + center_x -= mid - center_x + center_y -= mid - center_y scale *= 2 else - center_x += (150 - center_x) / 2 - center_y += (150 - center_y) / 2 - scale /= 2 + center_x += (mid - center_x) * 3 / 4 + center_y += (mid - center_y) * 3 / 4 + scale /= 4 . call draw . diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia index efe3fe78ef..931311a1b2 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia @@ -34,7 +34,7 @@ D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) heatmap(D .^ 0.1, c=:balance) savefig("Mandelbrot_set_3.png") -N, thickness = D .> 0, 0.01 # boundary detection and interpolation +N, thickness = D .> 0, 0.01 # boundary detection D[N] = max.(1 .- D[N] ./ thickness, 0) heatmap(D .^ 2.0, c=:binary) diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia index b2c8d1371d..e6a1a7726a 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia @@ -4,8 +4,8 @@ gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) d, h = 800, 500 # pixel density (= image width) and image height n, r = 200, 500 # number of iterations and escape radius (r > 2) -direction, height = 45, 1.5 # direction and height of the incoming light -stripes, damping = 4.0, 2.0 # stripe density and damping parameter +direction, height = 45, 1.5 # direction and height of the light +density, intensity = 4.0, 0.5 # density and intensity of the stripes x = range(0, 2, length=d+1) y = range(0, 2 * h / d, length=h+1) @@ -18,23 +18,22 @@ D, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C)) for k in 1:n M = abs.(Z) .< r - S[M], T[M] = S[M] .+ cos.(stripes .* angle.(Z[M])), T[M] .+ 1 + S[M], T[M] = S[M] .+ sin.(density .* angle.(Z[M])), T[M] .+ 1 Z[M], dZ[M], ddZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1, 2 .* (dZ[M] .^ 2 .+ Z[M] .* ddZ[M]) end -N = abs.(Z) .>= r # normal map effect 1 (equipotential lines) -P, Q = S[N] ./ T[N], (S[N] .+ cos.(stripes .* angle.(Z[N]))) ./ (T[N] .+ 1) -R = Q .+ (P .- Q) .* log2.(log.(abs.(Z[N])) ./ log(r)) # linear interpolation -U, V = Z[N] ./ dZ[N], 1 .+ R ./ damping # normal vectors and variations in inclination -U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit vectors +N = abs.(Z) .>= r # basic normal map effect and stripe average coloring (potential function) +P, Q = S[N] ./ T[N], (S[N] .+ sin.(density .* angle.(Z[N]))) ./ (T[N] .+ 1) +U, V = Z[N] ./ dZ[N], 1 .+ (log2.(log.(abs.(Z[N])) ./ log(r)) .* (P .- Q) .+ Q) .* intensity +U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and light vector D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ V .* height) ./ (1 + height), 0) heatmap(D .^ 1.0, c=:bone_1) savefig("Mandelbrot_normal_map_1.png") -N = abs.(Z) .> 2 # normal map effect 2 (equidistant lines) +N = abs.(Z) .> 2 # advanced normal map effect using higher derivatives (distance estimation) U = Z[N] .* dZ[N] .* ((1 .+ log.(abs.(Z[N]))) .* conj.(dZ[N] .^ 2) .- log.(abs.(Z[N])) .* conj.(Z[N] .* ddZ[N])) -U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit vectors +U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and light vector D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0) heatmap(D .^ 1.0, c=:afmhot) diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia index 70cc90c56c..b67d3b0276 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-6.julia @@ -4,8 +4,8 @@ gr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200) d, h = 200, 1200 # pixel density (= image width) and image height n, r = 8000, 10000 # number of iterations and escape radius (r > 2) -a = -.743643887037158704752191506114774 # try: a, b, n = -1.748764520194788535, 3e-13, 800 -b = 0.131825904205311970493132056385139 # https://mathr.co.uk/web/m-location-analysis.html +a = -.743643887037158704752191506114774 # https://mathr.co.uk/web/m-location-analysis.html +b = 0.131825904205311970493132056385139 # try: a, b, n = -1.748764520194788535, 3e-13, 800 x = range(0, 2, length=d+1) y = range(0, 2 * h / d, length=h+1) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py index 8a36ca94df..80841dd274 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py @@ -33,7 +33,7 @@ D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) plt.imshow(D ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower") plt.savefig("Mandelbrot_set_3.png", dpi=200) -N, thickness = D > 0, 0.01 # boundary detection and interpolation +N, thickness = D > 0, 0.01 # boundary detection D[N] = np.maximum(1 - D[N] / thickness, 0) plt.imshow(D ** 2.0, cmap=plt.cm.binary, origin="lower") diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py index 02ca4a2693..e930bc32ed 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py @@ -4,8 +4,8 @@ import matplotlib.pyplot as plt d, h = 800, 500 # pixel density (= image width) and image height n, r = 200, 500 # number of iterations and escape radius (r > 2) -direction, height = 45, 1.5 # direction and height of the incoming light -stripes, damping = 4.0, 2.0 # stripe density and damping parameter +direction, height = 45, 1.5 # direction and height of the light +density, intensity = 4.0, 0.5 # density and intensity of the stripes x = np.linspace(0, 2, num=d+1) y = np.linspace(0, 2 * h / d, num=h+1) @@ -18,22 +18,21 @@ D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape) for k in range(n): M = abs(Z) < r - S[M], T[M] = S[M] + np.cos(stripes * np.angle(Z[M])), T[M] + 1 + S[M], T[M] = S[M] + np.sin(density * np.angle(Z[M])), T[M] + 1 Z[M], dZ[M], ddZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1, 2 * (dZ[M] ** 2 + Z[M] * ddZ[M]) -N = abs(Z) >= r # normal map effect 1 (equipotential lines) -P, Q = S[N] / T[N], (S[N] + np.cos(stripes * np.angle(Z[N]))) / (T[N] + 1) -R = Q + (P - Q) * np.log2(np.log(np.abs(Z[N])) / np.log(r)) # linear interpolation -U, V = Z[N] / dZ[N], 1 + R / damping # normal vectors and variations in inclination -U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit vectors +N = abs(Z) >= r # basic normal map effect and stripe average coloring (potential function) +P, Q = S[N] / T[N], (S[N] + np.sin(density * np.angle(Z[N]))) / (T[N] + 1) +U, V = Z[N] / dZ[N], 1 + (np.log2(np.log(np.abs(Z[N])) / np.log(r)) * (P - Q) + Q) * intensity +U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and light vector D[N] = np.maximum((U.real * v.real + U.imag * v.imag + V * height) / (1 + height), 0) plt.imshow(D ** 1.0, cmap=plt.cm.bone, origin="lower") plt.savefig("Mandelbrot_normal_map_1.png", dpi=200) -N = abs(Z) > 2 # normal map effect 2 (equidistant lines) +N = abs(Z) > 2 # advanced normal map effect using higher derivatives (distance estimation) U = Z[N] * dZ[N] * ((1 + np.log(abs(Z[N]))) * np.conj(dZ[N] ** 2) - np.log(abs(Z[N])) * np.conj(Z[N] * ddZ[N])) -U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit vectors +U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and light vector D[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0) plt.imshow(D ** 1.0, cmap=plt.cm.afmhot, origin="lower") diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-7.py b/Task/Mandelbrot-set/Python/mandelbrot-set-7.py index 5c47bb5708..90e9a2d739 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-7.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-7.py @@ -4,8 +4,8 @@ import matplotlib.pyplot as plt d, h = 200, 1200 # pixel density (= image width) and image height n, r = 8000, 10000 # number of iterations and escape radius (r > 2) -a = -.743643887037158704752191506114774 # try: a, b, n = -1.748764520194788535, 3e-13, 800 -b = 0.131825904205311970493132056385139 # https://mathr.co.uk/web/m-location-analysis.html +a = -.743643887037158704752191506114774 # https://mathr.co.uk/web/m-location-analysis.html +b = 0.131825904205311970493132056385139 # try: a, b, n = -1.748764520194788535, 3e-13, 800 x = np.linspace(0, 2, num=d+1) y = np.linspace(0, 2 * h / d, num=h+1) diff --git a/Task/Mandelbrot-set/Raku/mandelbrot-set-1.raku b/Task/Mandelbrot-set/Raku/mandelbrot-set-1.raku index e855c8d0ce..9d7695417f 100644 --- a/Task/Mandelbrot-set/Raku/mandelbrot-set-1.raku +++ b/Task/Mandelbrot-set/Raku/mandelbrot-set-1.raku @@ -1,49 +1,31 @@ -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 -fc7c7c fc9c7c fcbc7c fcdc7c fcfc7c dcfc7c bcfc7c 9cfc7c 7cfc7c 7cfc9c 7cfcbc -7cfcdc 7cfcfc 7cdcfc 7cbcfc 7c9cfc b4b4fc c4b4fc d8b4fc e8b4fc fcb4fc fcb4e8 -fcb4d8 fcb4c4 fcb4b4 fcc4b4 fcd8b4 fce8b4 fcfcb4 e8fcb4 d8fcb4 c4fcb4 b4fcb4 -b4fcc4 b4fcd8 b4fce8 b4fcfc b4e8fc b4d8fc b4c4fc 000070 1c0070 380070 540070 -700070 700054 700038 70001c 700000 701c00 703800 705400 707000 547000 387000 -1c7000 007000 00701c 007038 007054 007070 005470 003870 001c70 383870 443870 -543870 603870 703870 703860 703854 703844 703838 704438 705438 706038 707038 -607038 547038 447038 387038 387044 387054 387060 387070 386070 385470 384470 -505070 585070 605070 685070 705070 705068 705060 705058 705050 705850 706050 -706850 707050 687050 607050 587050 507050 507058 507060 507068 507070 506870 -506070 505870 000040 100040 200040 300040 400040 400030 400020 400010 400000 -401000 402000 403000 404000 304000 204000 104000 004000 004010 004020 004030 -004040 003040 002040 001040 202040 282040 302040 382040 402040 402038 402030 -402028 402020 402820 403020 403820 404020 384020 304020 284020 204020 204028 -204030 204038 204040 203840 203040 202840 2c2c40 302c40 342c40 3c2c40 402c40 -402c3c 402c34 402c30 402c2c 40302c 40342c 403c2c 40402c 3c402c 34402c 30402c -2c402c 2c4030 2c4034 2c403c 2c4040 2c3c40 2c3440 2c3040 ->; - -constant MAX_ITERATIONS = 50; -my $width = my $height = +(@*ARGS[0] // 31); - -sub cut(Range $r, UInt $n where $n > 1) { - $r.min, * + ($r.max - $r.min) / ($n - 1) ... $r.max -} - -my @re = cut(-2 .. 1/2, $height); -my @im = cut( 0 .. 5/4, $width div 2 + 1) X* 1i; - -sub mandelbrot(Complex $z is copy, Complex $c) { - for 1 .. MAX_ITERATIONS { - $z = $z*$z + $c; - return $_ if $z.abs > 2; - } - return 0; -} - +constant MAX-ITERATIONS = 1000; +my $width = +(@*ARGS[0] // 800); +my $height = $width + $width %% 2; say "P3"; say "$width $height"; say "255"; -for @re -> $re { - put @color_map[|.reverse, |.[1..*]][^$width] given - my @ = map &mandelbrot.assuming(0i, *), $re «+« @im; +sub cut(Range $r, UInt $n where $n > 1 --> Seq) { + $r.min, * + ($r.max - $r.min) / ($n - 1) ... $r.max } + +my @re = cut(-2 .. 1/2, $width); +my @im = cut( 0 .. 5/4, 1 + ($height div 2)) X* 1i; + +sub mandelbrot(Complex $z is copy, Complex $c --> Int) { + for 1 .. MAX-ITERATIONS { + $z = $z*$z + $c; + return $_ if $z.abs > 2; + } + return 0; +} + +my @lines = hyper for @im X+ @re { + use Color; + my $i = (255 * sqrt(mandelbrot(0i, $_) / (MAX-ITERATIONS + 1))).Int; + (state @)[$i] //= Color.new(hsv => $i xx 3).rgb +}.rotor($width); + +.put for @lines[1..*].reverse; +.put for @lines[0]; +.put for @lines[1..*]; diff --git a/Task/Mandelbrot-set/UNIX-Shell/mandelbrot-set.sh b/Task/Mandelbrot-set/UNIX-Shell/mandelbrot-set.sh index 009e0c4101..31f2f65efc 100644 --- a/Task/Mandelbrot-set/UNIX-Shell/mandelbrot-set.sh +++ b/Task/Mandelbrot-set/UNIX-Shell/mandelbrot-set.sh @@ -1,25 +1,36 @@ -((xmin=-8601)) # int(-2.1*4096) -((xmax=2867)) # int( 0.7*4096) +function mandelbrot() { + local -ir maxiter=100 + local -i i j {x,y}m{in,ax} d{x,y} + local -ra C=( {0..9} ) + local -i lC=${#C[*]} + local -i columns=${COLUMNS:-72} lines=${LINES:-24} -((ymin=-4915)) # int(-1.2*4096) -((ymax=4915)) # int( 1.2*4096) + (( + xmin=-21*4096/10, + xmax= 7*4096/10, -((maxiter=30)) + ymin=-12*4096/10, + ymax= 12*4096/10, -((dx=(xmax-xmin)/72)) -((dy=(ymax-ymin)/24)) + dx=(xmax-xmin)/columns, + dy=(ymax-ymin)/lines + )) -C='0123456789' -((lC=${#C})) - -for((cy=ymax;cy>=ymin;cy-=dy)) ; do - for((cx=xmin;cx<=xmax;cx+=dx)) ; do - ((x=0,y=0,x2=0,y2=0)) - for((iter=0;iter>11)+cy,x=x2-y2+cx,x2=(x*x)>>12,y2=(y*y)>>12)) - done - ((c=iter%lC)) - echo -n ${C:$c:1} - done - echo -done + for ((cy=ymax, i=0; i>11)+cy, + x=x2-y2+cx, + x2=(x*x)>>12, + y2=(y*y)>>12 + )) + done + ((c=iter%lC)) + echo -n "${C[c]}" + done + echo + done +} diff --git a/Task/Mastermind/Java/mastermind.java b/Task/Mastermind/Java/mastermind.java new file mode 100644 index 0000000000..60319dd5db --- /dev/null +++ b/Task/Mastermind/Java/mastermind.java @@ -0,0 +1,182 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Scanner; +import java.util.concurrent.ThreadLocalRandom; + +public final class MastermindTask { + + public static void main(String[] aArgs) { + Mastermind mastermind = new Mastermind(4, 8, 12, false); + mastermind.play(); + } + + private static final class Mastermind { + + public Mastermind(int aCodeLength, int aLetterCount, int aGuessCount, boolean aRepeatLetters) { + if ( aCodeLength < 4 ) { + aCodeLength = 4; + } else if ( aCodeLength > 10 ) { + aCodeLength = 10; + } + + if ( aLetterCount < 2 ) { + aLetterCount = 2; + } else if ( aLetterCount > 20 ) { + aLetterCount = 20; + } + + if ( aGuessCount < 7 ) { + aGuessCount = 7; + } else if ( aGuessCount > 20 ) { + aGuessCount = 20; + } + + if ( ! aRepeatLetters && aLetterCount < aCodeLength ) { + aLetterCount = aCodeLength; + } + + codeLength = aCodeLength; + letterCount = aLetterCount; + guessCount = aGuessCount; + repeatLetters = aRepeatLetters; + + String validLetters = "ABCDEFGHIJKLMNOPQRST"; + letters = ""; + for ( int i = 0; i < letterCount; i++ ) { + letters += validLetters.charAt(i); + } + } + + public void play() { + boolean playerWin = false; + goal = createGoal(); + + while ( guessCount > 0 && ! playerWin ) { + showBoard(); + if ( checkUserInput(obtainUserGuess()) ) { + playerWin = true; + reader.close(); + } + guessCount--; + } + + if ( playerWin ) { + System.out.println(newLine + newLine + "--------------------------------" + newLine + + "Very well done! " + newLine + "You found the code: " + goal + + newLine + "--------------------------------" + newLine + newLine); + } else { + System.out.println(newLine + newLine + "--------------------------------" + newLine + + "I'm sorry, you couldn't make it! " + newLine + "The code was: " + goal + + newLine + "--------------------------------" + newLine + newLine); + } + } + + private void showBoard() { + for ( int i = 0; i < guesses.size(); i++ ) { + System.out.print(newLine + "--------------------------------" + newLine); + System.out.print(( i + 1 ) + ": "); + for ( char ch : guesses.get(i) ) { + System.out.print(ch + " "); + } + + System.out.print(" : "); + for ( char ch : results.get(i) ) { + System.out.print(ch + " "); + } + + final int errorCount = codeLength - results.get(i).size(); + for ( int j = 0; j < errorCount; j++ ) { + System.out.print("- "); + } + } + System.out.print(newLine + newLine); + } + + private String obtainUserGuess() { + String result = ""; + do { + System.out.print("Enter your guess (" + letters + "): "); + result = reader.nextLine().toUpperCase(); + if ( result.length() != codeLength ) { + System.out.println("Please try again, your guess should have " + codeLength + " letters"); + } + } while ( result.length() != codeLength ); + return result; + } + + private boolean checkUserInput(String aUserInput) { + List userInputCharacters = new ArrayList(); + for ( char ch : aUserInput.toCharArray() ) { + userInputCharacters.add(ch); + } + guesses.add(userInputCharacters); + + int xCount = 0; + int oCount = 0; + List fullMatches = new ArrayList(Collections.nCopies(codeLength, false)); + List partialMatches = new ArrayList(Collections.nCopies(codeLength, false)); + + for ( int i = 0; i < codeLength; i++ ) { + if ( aUserInput.charAt(i) == goal.charAt(i) ) { + fullMatches.set(i, true); + partialMatches.set(i, true); + xCount++; + } + } + + for ( int i = 0; i < codeLength; i++ ) { + if ( fullMatches.get(i) ) { + continue; + } + for ( int j = 0; j < codeLength; j++ ) { + if ( i == j || partialMatches.get(j) ) { + continue; + } + if ( aUserInput.charAt(i) == goal.charAt(j) ) { + partialMatches.set(j, true); + oCount++; + break; + } + } + } + + List nextResult = new ArrayList(); + for ( int i = 0; i < xCount; i++ ) { + nextResult.add('X'); + } + for ( int i = 0; i < oCount; i++ ) { + nextResult.add('O'); + } + results.add(nextResult); + + return xCount == codeLength; + } + + private String createGoal() { + String result = ""; + String lettersCopy = letters; + + for ( int i = 0; i < codeLength; i++ ) { + final int index = random.nextInt(lettersCopy.length()); + result += lettersCopy.charAt(index); + if ( ! repeatLetters ) { + lettersCopy = lettersCopy.substring(0, index) + lettersCopy.substring(index + 1); + } + } + return result; + } + + private int codeLength, letterCount, guessCount; + private String letters, goal; + private boolean repeatLetters; + private Scanner reader = new Scanner(System.in); + private List> guesses = new ArrayList>(); + private List> results = new ArrayList>(); + + private final ThreadLocalRandom random = ThreadLocalRandom.current(); + private final String newLine = System.lineSeparator(); + + } + +} diff --git a/Task/Matrix-chain-multiplication/C++/matrix-chain-multiplication.cpp b/Task/Matrix-chain-multiplication/C++/matrix-chain-multiplication.cpp new file mode 100644 index 0000000000..ff35026acc --- /dev/null +++ b/Task/Matrix-chain-multiplication/C++/matrix-chain-multiplication.cpp @@ -0,0 +1,66 @@ +#include +#include +#include +#include +#include + +constexpr int32_t MAXIMUM_VALUE = 2'147'483'647; + +std::vector> cost; +std::vector> order; + +void print_vector(const std::vector& list) { + std::cout << "["; + for ( uint64_t i = 0; i < list.size() - 1; ++i ) { + std::cout << list[i] << ", "; + } + std::cout << list.back() << "]" << std::endl; +} + +int32_t matrix_chain_order(const std::vector& dimensions) { + const uint64_t size = dimensions.size() - 1; + cost = { size, std::vector(size, 0) }; + order = { size, std::vector(size, 0) }; + + for ( uint64_t m = 1; m < size; ++m ) { + for ( uint64_t i = 0; i < size - m; ++i ) { + int32_t j = i + m; + cost[i][j] = MAXIMUM_VALUE; + for ( int32_t k = i; k < j; ++k ) { + int32_t current_cost = cost[i][k] + cost[k + 1][j] + + dimensions[i] * dimensions[k + 1] * dimensions[j + 1]; + if ( current_cost < cost[i][j] ) { + cost[i][j] = current_cost; + order[i][j] = k; + } + } + } + } + return cost[0][size - 1]; +} + +std::string get_optimal_parenthesizations(const std::vector>& order, + const uint64_t& i, const uint64_t& j) { + if ( i == j ) { + std::string result(1, char(i + 65)); + return result; + } else { + std::stringstream stream; + stream << "(" << get_optimal_parenthesizations(order, i, order[i][j]) + << " * " << get_optimal_parenthesizations(order, order[i][j] + 1, j) << ")"; + return stream.str(); + } +} + +void matrix_chain_multiplication(const std::vector& dimensions) { + std::cout << "Array Dimension = "; print_vector(dimensions); + std::cout << "Cost = " << matrix_chain_order(dimensions) << std::endl; + std::cout << "Optimal Multiply = " + << get_optimal_parenthesizations(order, 0, order.size() - 1) << std::endl << std::endl; +} + +int main() { + matrix_chain_multiplication({ 5, 6, 3, 1 }); + matrix_chain_multiplication({ 1, 5, 25, 30, 100, 70, 2, 1, 100, 250, 1, 1000, 2 }); + matrix_chain_multiplication({ 1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10 }); +} diff --git a/Task/Mayan-calendar/C++/mayan-calendar.cpp b/Task/Mayan-calendar/C++/mayan-calendar.cpp new file mode 100644 index 0000000000..4417afac42 --- /dev/null +++ b/Task/Mayan-calendar/C++/mayan-calendar.cpp @@ -0,0 +1,90 @@ +#include +#include +#include +#include +#include +#include + +const std::vector Tzolkin = { "Imix'", "Ik'", "Ak'bal", "K'an", "Chikchan", "Kimi", "Manik'", + "Lamat", "Muluk", "Ok", "Chuwen", "Eb", "Ben", "Hix", "Men", "K'ib'", "Kaban", "Etz'nab'", "Kawak", "Ajaw" }; + +const std::vector Haab = { "Pop", "Wo'", "Sip", "Sotz'", "Sek", "Xul", "Yaxk'in", "Mol", + "Ch'en", "Yax", "Sak'", "Keh", "Mak", "K'ank'in", "Muwan", "Pax", "K'ayab", "Kumk'u", "Wayeb'" }; + + +int32_t positive_modulus(const int32_t& base, const int32_t& modulus) { + const int32_t result = base % modulus; + return ( result < 0 ) ? result + modulus : result; +} + +std::chrono::sys_days create_date(const std::string& iso_date) { + const int year = std::stoi(iso_date.substr(0, 4)); + const unsigned int month = std::stoi(iso_date.substr(5, 7)); + const unsigned int day = std::stoi(iso_date.substr(8, 10)); + + std::chrono::year_month_day date{std::chrono::year{year}, std::chrono::month{month}, std::chrono::day{day}}; + return std::chrono::sys_days(date); +} + +const std::chrono::sys_days CREATION_TZOLKIN = create_date("2012-12-21"); +const std::chrono::sys_days ZERO_HAAB = create_date("2019-04-02"); + +int32_t days_per_mayan_month(const std::string& month) { + return ( month == "Wayeb'" ) ? 5 : 20; +} + +std::string tzolkin(const std::chrono::sys_days& gregorian) { + const int32_t days_between = ( gregorian - CREATION_TZOLKIN ).count(); + int32_t remainder = positive_modulus(days_between, 13); + remainder += ( remainder <= 9 ) ? 4 : -9; + return std::to_string(remainder) + " " + Tzolkin[positive_modulus(days_between - 1, 20)]; +} + +std::string haab(const std::chrono::sys_days& gregorian) { + const int32_t days_between = ( gregorian - ZERO_HAAB ).count(); + int32_t remainder = positive_modulus(days_between, 365); + const std::string month = Haab[positive_modulus(remainder + 1, 20)]; + const int32_t day_of_month = remainder % 20 + 1; + return ( day_of_month < days_per_mayan_month(month) ) ? + std::to_string(day_of_month) + " " + month : "Chum " + month; +} + +std::string long_count(const std::chrono::sys_days& gregorian) { + int32_t days_between = ( gregorian - CREATION_TZOLKIN ).count() + 13 * 360 * 400; + const int32_t baktun = positive_modulus(days_between, 360 * 400); + days_between = days_between % ( 360 * 400 ); + const int32_t katun = days_between / ( 20 * 360 ); + days_between = days_between % ( 20 * 360 ); + const int32_t tun = days_between / 360; + days_between = days_between % 360; + const int32_t winal = days_between / 20; + const int32_t kin = days_between % 20; + + std::string result = ""; + for ( int32_t number : { baktun, katun, tun, winal, kin } ) { + std::string value = std::to_string(number) + "."; + result += ( number <= 9 ) ? "0" + value : value; + } + return result.substr(0, result.length() - 1); +} + +std::string lords_of_the_night(const std::chrono::sys_days& gregorian) { + const int32_t days_between = ( gregorian - CREATION_TZOLKIN ).count(); + const int32_t remainder = days_between % 9; + return "G" + std::to_string( ( remainder <= 0 ) ? remainder + 9 : remainder ); +} + +int main() { + const std::vector iso_dates = { "2004-06-19", "2012-12-18", "2012-12-21", "2019-01-19", + "2019-03-27", "2020-02-29", "2020-03-01", "2071-05-16", "2020-02-02" }; + + std::cout << "Gregorian Long Count Tzolk'in Haab' Lords of the Night" << std::endl; + std::cout << "------------------------------------------------------------------------------" << std::endl; + for ( const std::string& iso_date : iso_dates ) { + const std::chrono::sys_days date = create_date(iso_date); + + std::cout << std::left << std::setw(15) << iso_date << std::setw(19) << long_count(date) + << std::setw(12) << tzolkin(date) << std::setw(18) << haab(date) + << lords_of_the_night(date) << std::endl; + } +} diff --git a/Task/Mayan-calendar/Java/mayan-calendar.java b/Task/Mayan-calendar/Java/mayan-calendar.java new file mode 100644 index 0000000000..34ad28e327 --- /dev/null +++ b/Task/Mayan-calendar/Java/mayan-calendar.java @@ -0,0 +1,79 @@ +import java.time.LocalDate; +import java.time.temporal.ChronoUnit; +import java.util.List; + +public final class MayanCalendar { + + public static void main(String[] aArgs) { + List testDates = List.of( LocalDate.parse("2004-06-19"), + LocalDate.parse("2012-12-18"), + LocalDate.parse("2012-12-21"), + LocalDate.parse("2019-01-19"), + LocalDate.parse("2019-03-27"), + LocalDate.parse("2020-02-29"), + LocalDate.parse("2020-03-01"), + LocalDate.parse("2071-05-16"), + LocalDate.parse("2020-02-02") ); + + System.out.println("Gregorian Long Count Tzolk'in Haab' Lords of the Night"); + System.out.println("------------------------------------------------------------------------------"); + for ( LocalDate date : testDates ) { + System.out.println(String.format("%-15s%-19s%-12s%-18s%s", + date.toString(), longCount(date), tzolkin(date), haab(date), lordsOfTheNight(date))); + } + } + + private static String lordsOfTheNight(LocalDate aGregorian) { + long daysBetween = ChronoUnit.DAYS.between(CREATION_TZOLKIN, aGregorian); + long remainder = Math.floorMod(daysBetween, 9); + return "G" + ( ( remainder <= 0 ) ? remainder + 9 : remainder ); + } + + private static String longCount(LocalDate aGregorian) { + long daysBetween = ChronoUnit.DAYS.between(CREATION_TZOLKIN, aGregorian) + 13 * 360 * 400; + long baktun = Math.floorDiv(daysBetween, 360 * 400); + daysBetween = Math.floorMod(daysBetween, 360 * 400); + long katun = Math.floorDiv(daysBetween, 20 * 360); + daysBetween = Math.floorMod(daysBetween, 20 * 360); + long tun = Math.floorDiv(daysBetween, 360); + daysBetween = Math.floorMod(daysBetween, 360); + long winal = Math.floorDiv(daysBetween, 20); + long kin = Math.floorMod(daysBetween, 20); + + StringBuilder result = new StringBuilder(); + for ( long number : List.of( baktun, katun, tun, winal, kin ) ) { + String value = String.valueOf(number) + "."; + result.append( number <= 9 ? "0" + value : value ); + } + return result.toString().substring(0, result.length() - 1); + } + + private static String haab(LocalDate aGregorian) { + long daysBetween = ChronoUnit.DAYS.between(ZERO_HAAB, aGregorian); + int remainder = Math.floorMod(daysBetween, 365); + String month = Haab.get(Math.floorDiv(remainder + 1, 20)); + int dayOfMonth = Math.floorMod(remainder, 20) + 1; + return ( dayOfMonth < daysPerMayanMonth(month) ) ? dayOfMonth + " " + month : "Chum " + month; + } + + private static String tzolkin(LocalDate aGregorian) { + long daysBetween = ChronoUnit.DAYS.between(CREATION_TZOLKIN, aGregorian); + int remainder = Math.floorMod(daysBetween, 13); + remainder += ( remainder <= 9 ) ? 4 : -9; + return remainder + " " + Tzolkin.get(Math.floorMod(daysBetween - 1, 20)); + } + + private static int daysPerMayanMonth(String aMonth) { + return ( aMonth == "Wayeb'" ) ? 5 : 20; + } + + private static List Tzolkin = List.of( "Imix'", "Ik'", "Ak'bal", "K'an", "Chikchan", "Kimi", "Manik'", + "Lamat", "Muluk", "Ok", "Chuwen", "Eb", "Ben", "Hix", "Men", "K'ib'", "Kaban", "Etz'nab'", "Kawak", "Ajaw" ); + + private static List Haab = List.of( "Pop", "Wo'", "Sip", "Sotz'", "Sek", "Xul", "Yaxk'in", "Mol", + "Ch'en", "Yax", "Sak'", "Keh", "Mak", "K'ank'in", "Muwan", "Pax", "K'ayab", "Kumk'u", "Wayeb'" ); + + private static final LocalDate CREATION_TZOLKIN = LocalDate.parse("2012-12-21"); + private static final LocalDate ZERO_HAAB = LocalDate.parse("2019-04-02"); + +} diff --git a/Task/Mayan-numerals/C++/mayan-numerals.cpp b/Task/Mayan-numerals/C++/mayan-numerals.cpp new file mode 100644 index 0000000000..2c148ef1fc --- /dev/null +++ b/Task/Mayan-numerals/C++/mayan-numerals.cpp @@ -0,0 +1,94 @@ +#include +#include +#include +#include +#include +#include + +const std::vector MAYAN_DIGITS = { " Θ ", " ∙ ", " ∙∙ ", "∙∙∙ ", "∙∙∙∙", "────" }; +const std::string BLANK = " "; + +std::unordered_map BORDER { { "horizontal_beam", "═" }, { "vertical_beam", "║" }, + { "lower_left", "╚" }, { "lower_central", "╩" }, { "lower_right", "╝" }, + { "upper_left", "╔" }, { "upper_central", "╦" }, { "upper_right", "╗" } }; + +std::vector to_base20(const int32_t& number) { + std::vector result; + result.emplace_back(number % 20); + int32_t n = number / 20; + while ( n != 0 ) { + result.emplace_back(n % 20); + n /= 20; + } + std::reverse(result.begin(), result.end()); + return result; +} + +std::vector to_mayan_numeral(int32_t digit) { + std::vector result(4, BLANK); + if ( digit == 0 ) { + result[3] = MAYAN_DIGITS[0]; + return result; + } + + for ( int32_t i = 3; i >= 0; --i ) { + if ( digit >= 5 ) { + result[i] = MAYAN_DIGITS[5]; + digit -= 5; + } else { + result[i] = ( digit == 0 ) ? BLANK : MAYAN_DIGITS[digit]; + break; + } + } + return result; +} + +void display(const std::vector>& numerals) { + const int32_t index = numerals.size() - 1; + + std::cout << BORDER["upper_left"]; + for ( int32_t i = 0; i <= index; ++i ) { + for ( int32_t j = 0; j <= 3; ++j ) { + std::cout << BORDER["horizontal_beam"]; + } + if ( i < index ) { + std::cout << BORDER["upper_central"]; + } else { + std::cout << BORDER["upper_right"] << std::endl; + } + } + + for ( int32_t i = 1; i <= 4; ++i ) { + std::cout << BORDER["vertical_beam"]; + for ( int32_t j = 0; j <= index; ++j ) { + std::cout << numerals[j][i - 1] + BORDER["vertical_beam"]; + } + std::cout << std::endl; + } + + std::cout << BORDER["lower_left"]; + for ( int32_t i = 0; i <= index; ++i ) { + for ( int32_t j = 0; j <= 3; ++j ) { + std::cout << BORDER["horizontal_beam"]; + } + if ( i < index ) { + std::cout << BORDER["lower_central"]; + } else { + std::cout << BORDER["lower_right"] << std::endl; + } + } + } + +int main() { + for ( const int32_t& base10 : { 4'005, 8'017, 326'205, 886'205, 1'081'439'556 } ) { + std::cout << "Base 10 number, " << base10 << " to Mayan:" << std::endl; + std::vector digits = to_base20(base10); + std::vector> mayans; + for ( const int32_t& digit : digits ) { + std::vector mayan = to_mayan_numeral(digit); + mayans.push_back(mayan); + } + display(mayans); + std::cout << std::endl; + } +} diff --git a/Task/McNuggets-problem/Applesoft-BASIC/mcnuggets-problem.basic b/Task/McNuggets-problem/Applesoft-BASIC/mcnuggets-problem.basic new file mode 100644 index 0000000000..c23f3c9a85 --- /dev/null +++ b/Task/McNuggets-problem/Applesoft-BASIC/mcnuggets-problem.basic @@ -0,0 +1,13 @@ +100 dim nuggets(100) +110 for six = 0 to 100/6 +120 for nine = 0 to 100/9 +130 for twenty = 0 to 100/20 +140 n = six*6+nine*9+twenty*20 +150 if n <= 100 then nuggets(n) = 1 +160 next twenty +170 next nine +180 next six +190 for n = 100 to 1 step -1 +200 if nuggets(n) <> 1 then print "Maximum non-McNuggets number is: ";n : goto 250 +240 next n +250 end diff --git a/Task/McNuggets-problem/Asymptote/mcnuggets-problem.asymptote b/Task/McNuggets-problem/Asymptote/mcnuggets-problem.asymptote new file mode 100644 index 0000000000..f9dbadf8a5 --- /dev/null +++ b/Task/McNuggets-problem/Asymptote/mcnuggets-problem.asymptote @@ -0,0 +1,19 @@ +bool[] n; +for(int i = 0; i <= 100; ++i) { n[i] = false; } +int k; + +for (int a = 0; a < 100/6; ++a) { + for (int b = 0; b < 100/9; ++b) { + for (int c = 0; c < 100/20; ++c) { + k = a*6 + b*9 + c*20; + if (k <= 100) { n[k] = true; } + } + } +} + +for (int k = 100; k >= 0; --k) { + if (n[k] != true) { + write("Maximum non-McNuggets number is: ", k); + break; + } +} diff --git a/Task/McNuggets-problem/BASIC256/mcnuggets-problem.basic b/Task/McNuggets-problem/BASIC256/mcnuggets-problem.basic new file mode 100644 index 0000000000..e78054a85a --- /dev/null +++ b/Task/McNuggets-problem/BASIC256/mcnuggets-problem.basic @@ -0,0 +1,18 @@ +arraybase 1 +dim nuggets(100) + +for six = 0 To 100/6 + for nine = 0 To 100/9 + for twenty = 0 To 100/20 + n = six*6 + nine*9 + twenty*20 + if n <= 100 then nuggets[n] = true + next twenty + next nine +next six + +for n = 100 to 1 step -1 + if nuggets[n] = false then + print "Maximum non-McNuggets number is: "; n + exit for + end if +next n diff --git a/Task/McNuggets-problem/C++/mcnuggets-problem.cpp b/Task/McNuggets-problem/C++/mcnuggets-problem.cpp new file mode 100644 index 0000000000..5656655bd8 --- /dev/null +++ b/Task/McNuggets-problem/C++/mcnuggets-problem.cpp @@ -0,0 +1,25 @@ +#include +#include +#include + +void mcnuggets(int32_t limit) { + std::vector mcnuggets_numbers(limit + 1, false); + for ( int32_t small = 0; small <= limit; small += 6 ) { + for ( int32_t medium = small; medium <= limit; medium += 9 ) { + for ( int32_t large = medium; large <= limit; large += 20 ) { + mcnuggets_numbers[large] = true; + } + } + } + + for ( int32_t i = limit; i >= 0; --i ) { + if ( ! mcnuggets_numbers[i] ) { + std::cout << "Maximum non-McNuggets number is " << i << std::endl; + return; + } + } +} + +int main() { + mcnuggets(100); +} diff --git a/Task/McNuggets-problem/Chipmunk-Basic/mcnuggets-problem.basic b/Task/McNuggets-problem/Chipmunk-Basic/mcnuggets-problem.basic new file mode 100644 index 0000000000..4d7dca1e95 --- /dev/null +++ b/Task/McNuggets-problem/Chipmunk-Basic/mcnuggets-problem.basic @@ -0,0 +1,16 @@ +100 dim nuggets(100) +110 for six = 0 to 100/6 +120 for nine = 0 to 100/9 +130 for twenty = 0 to 100/20 +140 n = six*6+nine*9+twenty*20 +150 if n <= 100 then nuggets(n) = 1 +160 next twenty +170 next nine +180 next six +190 for n = 100 to 1 step -1 +200 if nuggets(n) <> 1 then +210 print "Maximum non-McNuggets number is: ";n +220 end +230 endif +240 next n +250 end diff --git a/Task/McNuggets-problem/Minimal-BASIC/mcnuggets-problem.basic b/Task/McNuggets-problem/Minimal-BASIC/mcnuggets-problem.basic new file mode 100644 index 0000000000..15142a04cc --- /dev/null +++ b/Task/McNuggets-problem/Minimal-BASIC/mcnuggets-problem.basic @@ -0,0 +1,17 @@ +10 DIM N(100) : rem 10 ARRAY N for Quite BASIC +20 FOR A = 0 TO 100/6 +30 FOR B = 0 TO 100/9 +40 FOR C = 0 TO 100/20 +50 LET K = A*6+B*9+C*20 +60 IF K <= 100 THEN 80 +70 GOTO 90 +80 LET N(K) = 1 +90 NEXT C +100 NEXT B +110 NEXT A +120 FOR K = 100 TO 1 STEP -1 +130 IF N(K) <> 1 THEN 160 +140 NEXT K +150 STOP +160 PRINT "Maximum non-McNuggets number is: "; K +170 END diff --git a/Task/McNuggets-problem/PureBasic/mcnuggets-problem.basic b/Task/McNuggets-problem/PureBasic/mcnuggets-problem.basic new file mode 100644 index 0000000000..0261a196c0 --- /dev/null +++ b/Task/McNuggets-problem/PureBasic/mcnuggets-problem.basic @@ -0,0 +1,24 @@ +OpenConsole() +Define n.i +Dim nuggets.i(100) + +For six.i = 0 To 100/6 + For nine.i = 0 To 100/9 + For twenty.i = 0 To 100/20 + n = six*6 + nine*9 + twenty*20 + If n <= 100 + nuggets(n) = #True + EndIf + Next twenty + Next nine +Next six + +For n = 100 To 1 Step -1 + If nuggets(n) = #False + PrintN("Maximum non-McNuggets number is: " + Str(n)) + Break + EndIf +Next n + +PrintN(#CRLF$ + "Press ENTER to exit"): Input() +CloseConsole() diff --git a/Task/McNuggets-problem/Run-BASIC/mcnuggets-problem.basic b/Task/McNuggets-problem/Run-BASIC/mcnuggets-problem.basic new file mode 100644 index 0000000000..8f43ab1786 --- /dev/null +++ b/Task/McNuggets-problem/Run-BASIC/mcnuggets-problem.basic @@ -0,0 +1,17 @@ +dim nuggets(100) + +for six = 0 to 100/6 + for nine = 0 to 100/9 + for twenty = 0 to 100/20 + n = six*6 + nine*9 + twenty*20 + if n <= 100 then nuggets(n) = 1 + next twenty + next nine +next six + +for n = 100 to 1 step -1 + if nuggets(n) <> 1 then + print "Maximum non-McNuggets number is: "; n + end + end if +next n diff --git a/Task/McNuggets-problem/XBasic/mcnuggets-problem.basic b/Task/McNuggets-problem/XBasic/mcnuggets-problem.basic new file mode 100644 index 0000000000..f46a35e15e --- /dev/null +++ b/Task/McNuggets-problem/XBasic/mcnuggets-problem.basic @@ -0,0 +1,23 @@ +PROGRAM "McNuggets problem" +VERSION "0.0000" + +DECLARE FUNCTION Entry () + +FUNCTION Entry () +DIM N[100] + +FOR A = 0 TO 100/6 + FOR B = 0 TO 100/9 + FOR C = 0 TO 100/20 + K = A*6+B*9+C*20 + IF K <= 100 THEN N[K] = 1 + NEXT C + NEXT B +NEXT A + +FOR K = 100 TO 1 STEP -1 + IF N[K] <> 1 THEN PRINT "Maximum non-McNuggets number is: "; K : EXIT FOR +NEXT K + +END FUNCTION +END PROGRAM diff --git a/Task/McNuggets-problem/Yabasic/mcnuggets-problem.basic b/Task/McNuggets-problem/Yabasic/mcnuggets-problem.basic new file mode 100644 index 0000000000..36ec982314 --- /dev/null +++ b/Task/McNuggets-problem/Yabasic/mcnuggets-problem.basic @@ -0,0 +1,17 @@ +dim nuggets(100) + +for six = 0 to 100/6 + for nine = 0 to 100/9 + for twenty = 0 to 100/20 + n = six*6 + nine*9 + twenty*20 + if n <= 100 nuggets(n) = true + next twenty + next nine +next six + +for n = 100 to 1 step -1 + if nuggets(n) = false then + print "Maximum non-McNuggets number is: ", n + break + end if +next n diff --git a/Task/Meissel-Mertens-constant/C++/meissel-mertens-constant.cpp b/Task/Meissel-Mertens-constant/C++/meissel-mertens-constant.cpp new file mode 100644 index 0000000000..4d668b0a41 --- /dev/null +++ b/Task/Meissel-Mertens-constant/C++/meissel-mertens-constant.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include +#include + +std::vector list_prime_reciprocals(const int32_t& limit) { + const int32_t half_limit = ( limit % 2 == 0 ) ? limit / 2 : 1 + limit / 2; + std::vector composite(half_limit); + for ( int32_t i = 1, p = 3; i < half_limit; p += 2, ++i ) { + if ( ! composite[i] ) { + for ( int32_t a = i + p; a < half_limit; a = a + p ) { + composite[a] = true; + } + } + } + + std::vector result(composite.size()); + result[0] = 0.5; + for ( int32_t i = 1, p = 3; i < half_limit; p += 2, ++i ) { + if ( ! composite[i] ) { + result.emplace_back(1.0 / p); + } + } + return result; +} + +int main() { + std::vector prime_reciprocals = list_prime_reciprocals(100'000'000); + const double euler = 0.577'215'664'901'532'861; + double sum = 0.0; + for ( double reciprocal : prime_reciprocals ) { + sum += reciprocal + log(1.0 - reciprocal); + } + + const double meissel_mertens = euler + sum; + std::cout << "The Meissel-Mertens constant = " << std::setprecision(8) << meissel_mertens << std::endl; +} diff --git a/Task/Meissel-Mertens-constant/Java/meissel-mertens-constant.java b/Task/Meissel-Mertens-constant/Java/meissel-mertens-constant.java index 14b88f2c3c..b6c7c5a16f 100644 --- a/Task/Meissel-Mertens-constant/Java/meissel-mertens-constant.java +++ b/Task/Meissel-Mertens-constant/Java/meissel-mertens-constant.java @@ -2,9 +2,6 @@ import java.util.ArrayList; import java.util.BitSet; import java.util.List; -/** - * Calculates the Meissel-Mertens constant correct to 9 s.f. in approximately 15 seconds. - */ public final class MeisselMertensConstant { public static void main(String[] aArgs) { @@ -12,19 +9,18 @@ public final class MeisselMertensConstant { final double euler = 0.577_215_664_901_532_861; double sum = 0.0; for ( double reciprocal : primeReciprocals ) { - sum += reciprocal + Math.log(1.0 - reciprocal); + sum += reciprocal + Math.log(1.0 - reciprocal); } - final double constant = euler + sum; - System.out.println("The Meissel-Mertens constant = " + constant); + final double meisselMertens = euler + sum; + System.out.println(String.format("%s%.9f", "The Meissel-Mertens constant = ", meisselMertens)); } private static List listPrimeReciprocals(int aLimit) { BitSet sieve = new BitSet(aLimit + 1); sieve.set(2, aLimit + 1); - final int squareRoot = (int) Math.sqrt(aLimit); - for ( int i = 2; i <= squareRoot; i = sieve.nextSetBit(i + 1) ) { + for ( int i = 2; i <= Math.sqrt(aLimit); i = sieve.nextSetBit(i + 1) ) { for ( int j = i * i; j <= aLimit; j += i ) { sieve.clear(j); } diff --git a/Task/Memory-layout-of-a-data-structure/Java/memory-layout-of-a-data-structure.java b/Task/Memory-layout-of-a-data-structure/Java/memory-layout-of-a-data-structure.java new file mode 100644 index 0000000000..b6ec3047bb --- /dev/null +++ b/Task/Memory-layout-of-a-data-structure/Java/memory-layout-of-a-data-structure.java @@ -0,0 +1,74 @@ +public final class MemoryLayoutOfDataStructure { + + public static void main(String[] aArgs) { + RS232Pins9 plug = new RS232Pins9(); + System.out.println(plug.getPin("receivedData")); + plug.setPin(2, Status.ON); + System.out.println(plug.getPin("receivedData")); + plug.setPin("signalGround", Status.ON); + plug.displayPinStatus(); + } + +} + +enum Status { OFF, ON } + +final class RS232Pins9 { + + public Status getPin(int aPinNumber) { + for ( Pin pin : Pin.values() ) { + if ( pin.pinNumber == aPinNumber ) { + return pin.status; + } + } + throw new IllegalArgumentException("Unknown pin number: " + aPinNumber); + } + + public Status getPin(String aName) { + for ( Pin pin : Pin.values() ) { + if ( pin.name() == aName ) { + return pin.status; + } + } + throw new IllegalArgumentException("Unknown pin name: " + aName); + } + + public void setPin(int aPinNumber, Status aStatus) { + for ( Pin pin : Pin.values() ) { + if ( pin.pinNumber == aPinNumber ) { + pin.status = aStatus; + } + } + } + + public void setPin(String aName, Status aStatus) { + for ( Pin pin : Pin.values() ) { + if ( pin.name() == aName ) { + pin.status = aStatus; + } + } + } + + public void displayPinStatus() { + for ( Pin pin : Pin.values() ) { + System.out.println(String.format("%-29s%s", pin.name() + " has status ", pin.status)); + } + } + + private enum Pin { + + carrierDetect(1, Status.OFF), receivedData(2, Status.OFF), transmittedData(3, Status.OFF), + dataTerminalReady(4, Status.OFF), signalGround(5, Status.OFF), dataSetReady(6, Status.OFF), + requestToSend(7, Status.OFF), clearToSend(8, Status.OFF), ringIndicator(9, Status.OFF); + + private Pin(int aPinNumber, Status aStatus) { + pinNumber = aPinNumber; + status = aStatus; + } + + private int pinNumber; + private Status status; + + } + +} diff --git a/Task/Merge-and-aggregate-datasets/Harbour/merge-and-aggregate-datasets.harbour b/Task/Merge-and-aggregate-datasets/Harbour/merge-and-aggregate-datasets.harbour new file mode 100644 index 0000000000..07e5b79186 --- /dev/null +++ b/Task/Merge-and-aggregate-datasets/Harbour/merge-and-aggregate-datasets.harbour @@ -0,0 +1,66 @@ +&& SQL-like INSERT command (note the variable number of arguments) +#xcommand INSERT INTO ( [, ] ) VALUES ( [, ] ) => ; +
->(dbAppend());
-> := [;
-> := ] + +PROCEDURE Main() +LOCAL pStruct, vStruct, rStruct, xCurId, aAgg + + SET DATE FORMAT "yyyy-mm-dd" + SET SOFTSEEK ON + + && create and populate the patient table + pStruct := {{"patient_id", "n", 8, 0}, {"lastname", "c", 10, 0 }} + dbCreate( "patient", pStruct,, .T., "patient" ) + INSERT INTO patient (patient_id, lastname) VALUES (1001, "Hopper") + INSERT INTO patient (patient_id, lastname) VALUES (2002, "Wirth") + INSERT INTO patient (patient_id, lastname) VALUES (3003, "Kemeny") + INSERT INTO patient (patient_id, lastname) VALUES (4004, "Gosling") + INSERT INTO patient (patient_id, lastname) VALUES (5005, "Kurtz") + INDEX ON patient_id TO pat_id + + && create and populate the visit table + vStruct := {{"patient_id", "n", 8, 0}, {"visit_date", "d", 10, 0}, {"score", "n", 8, 1}} + dbCreate( "visit", vStruct,, .T., "visit" ) + INSERT INTO visit (patient_id, visit_date, score) VALUES (2002, ctod("2020-09-10"), 6.8) + INSERT INTO visit (patient_id, visit_date, score) VALUES (1001, ctod("2020-09-07"), 5.5) + INSERT INTO visit (patient_id, visit_date, score) VALUES (4004, ctod("2020-09-24"), 8.4) + INSERT INTO visit (patient_id, visit_date) VALUES (2002, ctod("2020-10-08")) + INSERT INTO visit (patient_id, score) VALUES (1001, 6.6) + INSERT INTO visit (patient_id, visit_date) VALUES (3003, ctod("2020-11-12")) + INSERT INTO visit (patient_id, visit_date, score) VALUES (4004, ctod("2020-11-12"), 7.0) + INSERT INTO visit (patient_id, visit_date, score) VALUES (1001, ctod("2020-11-19"), 5.3) + INDEX ON patient_id TO visit_id + + && create the result table + rStruct := { {"patient_id", "n", 8, 0}, {"lastname", "c", 10, 0}, ; + {"n", "i", 8, 0}, {"sum_score", "n", 8, 1}, ; + {"avg_score", "n", 8, 1}, {"max_date", "d", 10, 0}} + dbCreate("report", rStruct,, .T., "report") + + && left join: for each patient + SELECT patient + DO WHILE ! Eof() + xCurId := patient_id && grouping variable + SELECT visit + LOCATE FOR patient_id==xCurId + IF found() + && aggregate within visits for a given patient + aAgg := {0, 0.0, ctod("19000101")} && initial values + DO WHILE ! Eof() .AND. xCurId == patient_id + aAgg := {1+aAgg[1], score+aAgg[2], max(visit_date, aAgg[3])} && update + SKIP + ENDDO + INSERT INTO report (patient_id, lastname, n, sum_score, avg_score, max_date) ; + VALUES (xCurId, patient->lastname, aAgg[1], aAgg[2], aAgg[2]/aAgg[1], aAgg[3]) + ELSE + INSERT INTO report (patient_id, lastname) VALUES (xCurId, patient->lastname) + END IF + SELECT patient + SKIP + ENDDO + + SELECT report + ? "NUM", "PATIENT_ID", "LASTNAME", "N", "SUM_SCORE", "AVG_SCORE", "MAX_DATE" + LIST patient_id, lastname, n, sum_score, avg_score, max_date + + RETURN diff --git a/Task/Metronome/C++/metronome.cpp b/Task/Metronome/C++/metronome.cpp new file mode 100644 index 0000000000..4eb8d59e39 --- /dev/null +++ b/Task/Metronome/C++/metronome.cpp @@ -0,0 +1,41 @@ +#include +#include +#include +#include + +class Metronome { +public: + Metronome(const int32_t& aBeats_per_minute, const int32_t& aMeasure, const int32_t& aDuration_in_minutes) + : beats_per_minute(aBeats_per_minute), measure(aMeasure), duration_in_minutes(aDuration_in_minutes) { + counter = 0; + } + + void start() { + while ( counter < duration_in_minutes * beats_per_minute ) { + start_time = std::chrono::system_clock::now(); + + std::this_thread::sleep_until(time_to_awake()); + counter++; + if ( counter % measure != 0 ) { + std::cout << "Tick " << std::flush; + } else { + std::cout << "Tock" << std::endl; + } + } + } + +private: + std::chrono::system_clock::time_point time_to_awake() const { + return start_time + std::chrono::seconds(1); + } + + std::chrono::system_clock::time_point start_time; + int32_t counter; + + const int32_t beats_per_minute, measure, duration_in_minutes; +}; + +int main() { + Metronome metronome(60, 4, 1); + metronome.start(); +} diff --git a/Task/Metronome/Java/metronome.java b/Task/Metronome/Java/metronome-1.java similarity index 100% rename from Task/Metronome/Java/metronome.java rename to Task/Metronome/Java/metronome-1.java diff --git a/Task/Metronome/Java/metronome-2.java b/Task/Metronome/Java/metronome-2.java new file mode 100644 index 0000000000..7be10d3260 --- /dev/null +++ b/Task/Metronome/Java/metronome-2.java @@ -0,0 +1,113 @@ +import java.awt.Color; +import java.awt.Dimension; +import java.awt.EventQueue; +import java.io.IOException; +import java.net.URL; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.sound.sampled.AudioInputStream; +import javax.sound.sampled.AudioSystem; +import javax.sound.sampled.Clip; +import javax.sound.sampled.LineUnavailableException; +import javax.sound.sampled.UnsupportedAudioFileException; +import javax.swing.ImageIcon; +import javax.swing.JFrame; +import javax.swing.JPanel; + +public final class MetronomeTask { + + public static void main(String[] aArgs) { + EventQueue.invokeLater( () -> { new Metronome(60, 4, 1).start(); } ); + } + +} + +final class Metronome extends JPanel { + + public Metronome(int aBeatsPerMinute, int aMeasure, int aDurationInMinutes) { + beatsPerMinute = aBeatsPerMinute; measure = aMeasure; durationInMinutes = aDurationInMinutes; + SoundEffect.initialise(); + createAndShowGUI(); + } + + public void start() { + executorService = Executors.newSingleThreadScheduledExecutor(); + executorService.scheduleAtFixedRate(provideService, 1, 1, TimeUnit.SECONDS); + } + + private void createAndShowGUI() { + JFrame.setDefaultLookAndFeelDecorated(true); + frame = new JFrame("Metronome"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setIconImage( new ImageIcon("./metronomeJava.png").getImage() ); + frame.add(createPanel()); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setResizable(false); + frame.setVisible(true); + } + + private JPanel createPanel() { + setPreferredSize( new Dimension(800, 600) ); + setBackground(Color.CYAN); + return this; + } + + private JFrame frame; + private ScheduledExecutorService executorService; + private int beatsPerMinute, measure, durationInMinutes, counter; + + private Runnable provideService = () -> { + if ( counter < durationInMinutes * beatsPerMinute ) { + counter++; + if ( counter % measure != 0 ) { + SoundEffect.Tick.play(); + if ( getBackground() != Color.PINK ) { + setBackground(Color.PINK); + } else { + setBackground(Color.CYAN); + } + } else { + SoundEffect.Tock.play(); + setBackground(Color.ORANGE); + } + } else { + executorService.shutdown(); + frame.dispose(); + Runtime.getRuntime().exit(0); + } + }; + +} + +enum SoundEffect { + + Tick("./metronomeTickJava.wav"), Tock("./metronomeTockJava.wav"); + + public static void initialise() { + values(); + } + + public void play() { + if ( clip.isRunning() ) { + clip.stop(); + } + clip.setFramePosition(0); + clip.start(); + } + + private SoundEffect(String soundFileName) { + URL url = getClass().getClassLoader().getResource(soundFileName); + try ( AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url) ) { + clip = AudioSystem.getClip(); + clip.open(audioInputStream); + } catch (IOException | LineUnavailableException | UnsupportedAudioFileException ex) { + ex.printStackTrace(); + } + } + + private Clip clip; + +} diff --git a/Task/Miller-Rabin-primality-test/C++/miller-rabin-primality-test.cpp b/Task/Miller-Rabin-primality-test/C++/miller-rabin-primality-test.cpp new file mode 100644 index 0000000000..f4dab0632d --- /dev/null +++ b/Task/Miller-Rabin-primality-test/C++/miller-rabin-primality-test.cpp @@ -0,0 +1,132 @@ +#include +#include +#include +#include +#include + +std::vector small_primes{ 2, 3 }; + +uint64_t add_modulus(const uint64_t& a, const uint64_t& b, const uint64_t& modulus) { + uint64_t am = ( a < modulus ) ? a : a % modulus; + if ( b == 0 ) { + return am; + } + uint64_t bm = ( b < modulus ) ? b : b % modulus; + uint64_t b_from_m = modulus - bm; + if ( am >= b_from_m ) { + return am - b_from_m; + } + return am + bm; +} + +uint64_t multiply_modulus(const uint64_t& a, const uint64_t& b, const uint64_t& modulus) { + uint64_t am = ( a < modulus ) ? a : a % modulus; + uint64_t bm = ( b < modulus ) ? b : b % modulus; + if ( bm > am ) { + std::swap(am, bm); + } + uint64_t result; + while ( bm > 0 ) { + if ( ( bm & 1) == 1 ) { + result = add_modulus(result, am, modulus); + } + am = ( am << 1 ) - ( am >= ( modulus - am ) ? modulus : 0 ); + bm >>= 1; + } + return result; +} + +uint64_t exponentiation_modulus(const uint64_t& base, const uint64_t& exponent, const uint64_t& modulus) { + uint64_t b = base; + uint64_t e = exponent; + uint64_t result = 1; + while ( e > 0 ) { + if ( ( e & 1 ) == 1 ) { + result = multiply_modulus(result, b, modulus); + } + e >>= 1; + b = multiply_modulus(b, b, modulus); + } + return result; +} + +bool is_composite(const uint32_t& a, const uint64_t& d, const uint64_t& n, const uint32_t& s) { + if ( exponentiation_modulus(a, d, n) == 1 ) { + return false; + } + for ( uint64_t i = 0; i < s; ++i ) { + if ( exponentiation_modulus(a, pow(2, i) * d, n) == n - 1 ) { + return false; + } + } + return true; +} + +bool composite_test(const std::vector& primes, const uint64_t& d, const uint64_t& n, const uint32_t& s) { + for ( const uint32_t& prime : primes ) { + if ( is_composite(prime, d, n, s) ) { + return true; + } + } + return false; +} + +bool is_prime(const uint64_t& n) { + if ( n == 0 || n == 1 ) { + return false; + } + if ( std::find(small_primes.begin(), small_primes.end(), n) != small_primes.end() ) { + return true; + } + if ( std::any_of(small_primes.begin(), small_primes.end(), [n](uint32_t p) { return n % p == 0; }) ) { + return false; + } + + uint64_t d = n - 1; + uint32_t s = 0; + while ( ! d % 2 ) { + d >>= 1; + s++; + } + + if ( n < 1'373'653 ) { + return composite_test({ 2, 3 }, d, n, s); + } + if ( n < 25'326'001 ) { + return composite_test({ 2, 3, 5 }, d, n, s); + } + if ( n < 118'670'087'467 ) { + if ( n == 3'215'031'751 ) { + return false; + } + return composite_test({ 2, 3, 5, 7 }, d, n, s); + } + if ( n < 2'152'302'898'747 ) { + return composite_test({ 2, 3, 5, 7, 11 }, d, n, s); + } + if ( n < 3'474'749'660'383 ) { + return composite_test({ 2, 3, 5, 7, 11, 13 }, d, n, s); + } + if ( n < 341'550'071'728'321 ) { + return composite_test({ 2, 3, 5, 7, 11, 13, 17 }, d, n, s); + } + + const std::vector test_primes(small_primes.begin(), small_primes.begin() + 16); + return composite_test(test_primes, d, n, s); +} + +void create_small_primes() { + for ( uint32_t i = 5; i < 1'000; i += 2 ) { + if ( is_prime(i) ) { + small_primes.emplace_back(i); + } + } +} + +int main() { + create_small_primes(); + + for ( const uint64_t number : { 1'234'567'890'123'456'733, 1'234'567'890'123'456'737 } ) { + std::cout << "is_prime(" << number << ") = " << std::boolalpha << is_prime(number) << std::endl; + } +} diff --git a/Task/Mind-boggling-card-trick/C++/mind-boggling-card-trick.cpp b/Task/Mind-boggling-card-trick/C++/mind-boggling-card-trick.cpp new file mode 100644 index 0000000000..f6729e508c --- /dev/null +++ b/Task/Mind-boggling-card-trick/C++/mind-boggling-card-trick.cpp @@ -0,0 +1,100 @@ +#include +#include +#include +#include +#include +#include +#include + +template +void print_vector(const std::vector& list) { + std::cout << "["; + for ( uint64_t i = 0; i < list.size() - 1; ++i ) { + std::cout << list[i] << " "; + } + std::cout << list.back() << "]" << std::endl; +} + +int main() { + std::vector cards; + for ( int32_t i = 0; i < 26; ++i ) { + cards.emplace_back('R'); + cards.emplace_back('B'); + } + + std::random_device rand; + std::mt19937 mersenne_twister(rand()); + std::shuffle(cards.begin(), cards.end(), mersenne_twister); + + std::vector red_pile; + std::vector black_pile; + std::vector discard_pile; + + for ( int32_t i = 0; i < 52; i += 2 ) { + if ( cards[i] == 'R' ) { + red_pile.emplace_back(cards[i + 1]); + } else { + black_pile.emplace_back(cards[i + 1]); + } + discard_pile.emplace_back(cards[i]); + } + + std::cout << "A sample run." << "\n" << std::endl; + std::cout << "After dealing the cards the state of the piles is:" << std::endl; + std::cout << " Red : " << std::setw(2) << red_pile.size() << " cards -> "; print_vector(red_pile); + std::cout << " Black : " << std::setw(2) << black_pile.size() << " cards -> "; print_vector(black_pile); + std::cout << " Discard: " << std::setw(2) << discard_pile.size() + << " cards -> "; print_vector(discard_pile); + + const int32_t minimum_size = std::min(red_pile.size(), black_pile.size()); + std::uniform_int_distribution uniform_random{ 1, minimum_size }; + const int32_t choice = uniform_random(mersenne_twister); + + std::vector red_indexes(red_pile.size()); + std::iota(red_indexes.begin(), red_indexes.end(), 0); + std::vector black_indexes(black_pile.size()); + std::iota(black_indexes.begin(), black_indexes.end(), 0); + + std::shuffle(red_indexes.begin(), red_indexes.end(), mersenne_twister); + std::shuffle(black_indexes.begin(), black_indexes.end(), mersenne_twister); + + std::vector red_chosen_indexes(red_indexes.begin(), red_indexes.begin() + choice); + std::vector black_chosen_indexes(black_indexes.begin(), black_indexes.begin() + choice); + + std::cout << "\n" << "Number of cards are to be swapped: " << choice << std::endl; + std::cout << "The respective zero-based indices of the cards to be swapped are:" << std::endl; + std::cout << " Red : "; print_vector(red_chosen_indexes); + std::cout << " Black: "; print_vector(black_chosen_indexes); + + for ( int32_t i = 0; i < choice; ++i ) { + const char temp = red_pile[red_chosen_indexes[i]]; + red_pile[red_chosen_indexes[i]] = black_pile[black_chosen_indexes[i]]; + black_pile[black_chosen_indexes[i]] = temp; + } + + std::cout << "\n" << "After swapping cards the state of the red and black piles is:" << std::endl; + std::cout << " Red : "; print_vector(red_pile); + std::cout << " Black: "; print_vector(black_pile); + + int32_t red_count = 0; + for ( const char& ch : red_pile ) { + if ( ch == 'R' ) { + red_count++; + } + } + + int32_t black_count = 0; + for ( const char& ch : black_pile ) { + if ( ch == 'B' ) { + black_count++; + } + } + + std::cout << "\n" << "The number of red cards in the red pile: " << red_count << std::endl; + std::cout << "The number of black cards in the black pile: " << black_count << std::endl; + if ( red_count == black_count ) { + std::cout << "So the assertion is correct." << std::endl; + } else { + std::cout << "So the assertion is incorrect." << std::endl; + } +} diff --git a/Task/Mind-boggling-card-trick/Java/mind-boggling-card-trick.java b/Task/Mind-boggling-card-trick/Java/mind-boggling-card-trick.java index 185a5492d4..89e7c18ebb 100644 --- a/Task/Mind-boggling-card-trick/Java/mind-boggling-card-trick.java +++ b/Task/Mind-boggling-card-trick/Java/mind-boggling-card-trick.java @@ -45,8 +45,8 @@ public final class MindBogglingCardTrick { System.out.println(System.lineSeparator() + "Number of cards are to be swapped: " + choice); System.out.println("The respective zero-based indices of the cards to be swapped are:"); - System.out.println(" Red : " + redChosenIndexes); - System.out.println(" Black : " + blackChosenIndexes); + System.out.println(" Red : " + redChosenIndexes); + System.out.println(" Black: " + blackChosenIndexes); for ( int i = 0; i < choice; i++ ) { final char temp = redPile.get(redChosenIndexes.get(i)); @@ -54,9 +54,9 @@ public final class MindBogglingCardTrick { blackPile.set(blackChosenIndexes.get(i), temp); } - System.out.println(System.lineSeparator() + "After swapping cards the state of the red and black piless is:"); - System.out.println(" Red : " + redPile); - System.out.println(" Black : " + blackPile); + System.out.println(System.lineSeparator() + "After swapping cards the state of the red and black piles is:"); + System.out.println(" Red : " + redPile); + System.out.println(" Black: " + blackPile); int redCount = 0; for ( char ch : redPile ) { @@ -75,9 +75,9 @@ public final class MindBogglingCardTrick { System.out.println(System.lineSeparator() + "The number of red cards in the red pile: " + redCount); System.out.println("The number of black cards in the black pile: " + blackCount); if ( redCount == blackCount ) { - System.out.println("So the asssertion is correct."); + System.out.println("So the assertion is correct."); } else { - System.out.println("So the asssertion is incorrect."); + System.out.println("So the assertion is incorrect."); } } diff --git a/Task/Minimal-steps-down-to-1/C++/minimal-steps-down-to-1.cpp b/Task/Minimal-steps-down-to-1/C++/minimal-steps-down-to-1.cpp new file mode 100644 index 0000000000..590e923513 --- /dev/null +++ b/Task/Minimal-steps-down-to-1/C++/minimal-steps-down-to-1.cpp @@ -0,0 +1,106 @@ +#include +#include +#include +#include +#include + +const int32_t limit = 50'000; + +std::vector divisors; +std::vector subtractors; +std::vector> minimums; + +template +void print_vector(const std::vector& list) { + for ( uint64_t i = 0; i < list.size(); ++i ) { + std::cout << list[i]; + if ( i < list.size() - 1 ) { + std::cout << ", "; + } + } +} + +// Assumes that numbers are presented in ascending order up to 'limit'. +void minimum_steps(int32_t n) { + if ( n == 1 ) { + return; + } + + int32_t minimum = limit; + int32_t p = 0; + int32_t q = 0; + std::string operator_symbol = ""; + for ( int32_t divisor : divisors ) { + if ( n % divisor == 0 ) { + int32_t d = n / divisor; + int32_t steps = minimums[d].size() + 1; + if ( steps < minimum ) { + minimum = steps; + p = d; + q = divisor; + operator_symbol = "/"; + } + } + } + + for ( int32_t subtractor : subtractors ) { + int32_t d = n - subtractor; + if ( d >= 1 ) { + int32_t steps = minimums[d].size() + 1; + if ( steps < minimum ) { + minimum = steps; + p = d; + q = subtractor; + operator_symbol = "-"; + } + } + } + + minimums[n].emplace_back(operator_symbol + std::to_string(q) + " -> " + std::to_string(p)); + minimums[n].insert(minimums[n].end(), minimums[p].begin(), minimums[p].end()); +} + +int main() { + for ( int32_t item : { 0, 1 } ) { + divisors = { 2, 3 }; + subtractors = { item + 1 }; + minimums = std::vector(limit + 1, std::vector(0)); + std::cout << "With: Divisors: { "; print_vector(divisors); + std::cout << " }, Subtractors: { "; print_vector(subtractors); std::cout << " } =>" << std::endl; + std::cout << " Minimum number of steps to diminish the following numbers down to 1 is:" << std::endl; + for ( int32_t i = 1; i < limit; ++i ) { + minimum_steps(i); + if ( i <= 10 ) { + int32_t steps = minimums[i].size(); + const std::string plural = ( steps == 1 ) ? " : " : "s: "; + std::cout << " " << std::setw(2) << i << ": " << steps << " step" + plural; + print_vector(minimums[i]); std::cout << std::endl; + } + } + + for ( int32_t lim : { 2'000, 20'000, 50'000 } ) { + uint64_t max = 0; + for ( int32_t j = 1; j <= lim; ++j ) { + uint64_t m = minimums[j].size(); + if ( m > max ) { + max = m; + } + } + std::vector maxs; + for ( int32_t j = 1; j <= lim; ++j ) { + if ( minimums[j].size() == max ) { + maxs.emplace_back(j); + } + } + + int32_t size = maxs.size(); + std::string verb1 = ( size == 1 ) ? "is" : "are"; + std::string verb2 = ( size == 1 ) ? "has" : "have"; + std::string plural = ( size == 1 ) ? "" : "s"; + std::cout << " There " << verb1 << " " << size << " number" << plural << " in the range 1 - " << lim + << " that " << verb2 << " maximum 'minimal steps' of " << max << ":" << std::endl; + std::cout << " [ "; print_vector(maxs); std::cout << " ]" << std::endl; + } + std::cout << std::endl; + } +} diff --git a/Task/Minkowski-question-mark-function/C++/minkowski-question-mark-function.cpp b/Task/Minkowski-question-mark-function/C++/minkowski-question-mark-function.cpp new file mode 100644 index 0000000000..f0ba9f6367 --- /dev/null +++ b/Task/Minkowski-question-mark-function/C++/minkowski-question-mark-function.cpp @@ -0,0 +1,118 @@ +#include +#include +#include +#include +#include + +constexpr int32_t MAX_ITERATIONS = 151; + +double minkowski(const double& x) { + if ( x < 0 || x > 1 ) { + return floor(x) + minkowski(x - floor(x)); + } + + int64_t p = (int64_t) x; + int64_t q = 1; + int64_t r = p + 1; + int64_t s = 1; + double d = 1.0; + double y = (double) p; + + while ( true ) { + d /= 2; + if ( d == 0.0 ) { + break; + } + + int64_t m = p + r; + if ( m < 0 || p < 0 ) { + break; + } + + int64_t n = q + s; + if ( n < 0 ) { + break; + } + + if ( x < (double) m / n ) { + r = m; + s = n; + } else { + y += d; + p = m; + q = n; + } + } + return y + d; +} + +double minkowski_inverse(double x) { + if ( x < 0 || x > 1 ) { + return floor(x) + minkowski_inverse(x - floor(x)); + } + + if ( x == 0 || x == 1 ) { + return x; + } + + std::vector continued_fraction(1, 0); + int32_t current = 0; + int32_t count = 1; + int32_t i = 0; + + while ( true ) { + x *= 2; + if ( current == 0 ) { + if ( x < 1 ) { + count += 1; + } else { + continued_fraction.emplace_back(0); + continued_fraction[i] = count; + + i += 1; + count = 1; + current = 1; + x -= 1; + } + } else { + if ( x > 1 ) { + count += 1; + x -= 1; + } else { + continued_fraction.emplace_back(0); + continued_fraction[i] = count; + + i += 1; + count = 1; + current = 0; + } + } + + if ( x == floor(x) ) { + continued_fraction[i] = count; + break; + } + + if ( i == MAX_ITERATIONS ) { + break; + } + } + + double reciprocal = 1.0 / continued_fraction[i]; + for ( int32_t j = i - 1; j >= 0; --j ) { + reciprocal = continued_fraction[j] + 1.0 / reciprocal; + } + + return 1.0 / reciprocal; +} + +int main() { + std::cout << std::setw(20) << std::fixed << std::setprecision(16) << minkowski(0.5 * ( 1 + sqrt(5) )) + << std::setw(20) << 5.0 / 3.0 << std::endl; + std::cout << std::setw(20) << minkowski_inverse(-5.0 / 9.0) + << std::setw(20) << ( sqrt(13) - 7 ) / 6 << std::endl; + std::cout << std::setw(20) << minkowski(minkowski_inverse(0.718281828182818)) + << std::setw(20) << 0.718281828182818 << std::endl; + std::cout << std::setw(20) << minkowski_inverse(minkowski(0.1213141516271819)) + << std::setw(20) << 0.1213141516171819 << std::endl; +} diff --git a/Task/Minkowski-question-mark-function/Java/minkowski-question-mark-function.java b/Task/Minkowski-question-mark-function/Java/minkowski-question-mark-function.java new file mode 100644 index 0000000000..8167a0f1c1 --- /dev/null +++ b/Task/Minkowski-question-mark-function/Java/minkowski-question-mark-function.java @@ -0,0 +1,117 @@ +import java.util.ArrayList; +import java.util.List; + +public final class MinkowskiQuestionMarkFunction { + + public static void main(String[] aArgs) { + System.out.println(String.format("%20.16f%20.16f", minkowski(0.5 * ( 1 + Math.sqrt(5) )), 5.0 / 3.0)); + System.out.println(String.format("%20.16f%20.16f", minkowskiInverse(-5.0 / 9.0), ( Math.sqrt(13) - 7 ) / 6 )); + System.out.println(String.format("%20.16f%20.16f", minkowski(minkowskiInverse(0.718281828)), 0.718281828)); + System.out.println(String.format("%20.16f%20.16f", + minkowskiInverse(minkowski(0.1213141516271819)), 0.1213141516171819)); + } + + private static double minkowski(double aX) { + if ( aX < 0 || aX > 1 ) { + return Math.floor(aX) + minkowski(aX - Math.floor(aX)); + } + + long p = (long) aX; + long q = 1; + long r = p + 1; + long s = 1; + double d = 1.0; + double y = (double) p; + + while ( true ) { + d /= 2; + if ( d == 0.0 ) { + break; + } + + long m = p + r; + if ( m < 0 || p < 0 ) { + break; + } + + long n = q + s; + if ( n < 0 ) { + break; + } + + if ( aX < (double) m / n ) { + r = m; + s = n; + } else { + y += d; + p = m; + q = n; + } + } + return y + d; + } + + private static double minkowskiInverse(double aX) { + if ( aX < 0 || aX > 1 ) { + return Math.floor(aX) + minkowskiInverse(aX - Math.floor(aX)); + } + + if ( aX == 0 || aX == 1 ) { + return aX; + } + + List continuedFraction = new ArrayList(); + continuedFraction.add(0); + int current = 0; + int count = 1; + int i = 0; + + while ( true ) { + aX *= 2; + if ( current == 0 ) { + if ( aX < 1 ) { + count += 1; + } else { + continuedFraction.add(0); + continuedFraction.set(i, count); + + i += 1; + count = 1; + current = 1; + aX -= 1; + } + } else { + if ( aX > 1 ) { + count += 1; + aX -= 1; + } else { + continuedFraction.add(0); + continuedFraction.set(i, count); + + i += 1; + count = 1; + current = 0; + } + } + + if ( aX == Math.floor(aX) ) { + continuedFraction.set(i, count); + break; + } + + if ( i == MAX_ITERATIONS ) { + break; + } + } + + double reciprocal = 1.0 / continuedFraction.get(i); + for ( int j = i - 1; j >= 0; j-- ) { + reciprocal = continuedFraction.get(j) + 1.0 / reciprocal; + } + + return 1.0 / reciprocal; + } + + private static final int MAX_ITERATIONS = 150; + +} diff --git a/Task/Modified-random-distribution/C++/modified-random-distribution.cpp b/Task/Modified-random-distribution/C++/modified-random-distribution.cpp new file mode 100644 index 0000000000..c6cbf02c69 --- /dev/null +++ b/Task/Modified-random-distribution/C++/modified-random-distribution.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +std::random_device random; +std::mt19937 generator(random()); +std::uniform_real_distribution distribution(0.0F, 1.0F); + +double modifier(const double& x) { + return ( x < 0.5 ) ? 2 * ( 0.5 - x ) : 2 * ( x - 0.5 ); +} + +double modified_random(const std::function& modify) { + double result = -1.0; + + while ( result < 0.0 ) { + double random_one = distribution(generator); + double random_two = distribution(generator); + if ( random_two < modify(random_one) ) { + result = random_one; + } + } + return result; +} + +int main() { + const int32_t sample_size = 100'000; + const int32_t bin_count = 20; + const double bin_size = 1.0 / bin_count; + + std::vector bins(bin_count, 0); + + for ( int32_t i = 0; i < sample_size; ++i ) { + double random = modified_random(modifier); + int32_t bin_number = floor(random / bin_size); + bins[bin_number]++; + } + + std::cout << "Modified random distribution with " << sample_size << " samples in range [0, 1):" + << std::endl << std::endl; + std::cout << " Range Number of samples within range" << std::endl; + + const int32_t scale_factor = 125; + for ( float i = 0.0; i < bin_count; ++i ) { + std::string histogram = " " + std::string(bins[i] / scale_factor, '#') + " "; + std::cout << std::fixed << std::setw(4)<< std::setprecision(2) << i / bin_count << " ..< " + << std::setw(4) << ( i + 1.0 ) / bin_count << histogram << bins[i] << std::endl; + } +} diff --git a/Task/Modified-random-distribution/Java/modified-random-distribution.java b/Task/Modified-random-distribution/Java/modified-random-distribution.java index 9e0bff3d48..cc2f0d0c3a 100644 --- a/Task/Modified-random-distribution/Java/modified-random-distribution.java +++ b/Task/Modified-random-distribution/Java/modified-random-distribution.java @@ -1,5 +1,6 @@ import java.util.List; import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; import java.util.stream.Stream; interface ModifierInterface { @@ -13,7 +14,7 @@ public final class ModifiedRandomDistribution222 { final int binCount = 20; final double binSize = 1.0 / binCount; - List bins = Stream.generate( () -> 0 ).limit(binCount).toList(); + List bins = Stream.generate( () -> 0 ).limit(binCount).collect(Collectors.toList()); for ( int i = 0; i < sampleSize; i++ ) { double random = modifiedRandom(modifier); diff --git a/Task/Modular-inverse/Java/modular-inverse.java b/Task/Modular-inverse/Java/modular-inverse-1.java similarity index 100% rename from Task/Modular-inverse/Java/modular-inverse.java rename to Task/Modular-inverse/Java/modular-inverse-1.java diff --git a/Task/Modular-inverse/Java/modular-inverse-2.java b/Task/Modular-inverse/Java/modular-inverse-2.java new file mode 100644 index 0000000000..95d9d69a06 --- /dev/null +++ b/Task/Modular-inverse/Java/modular-inverse-2.java @@ -0,0 +1,22 @@ +public final class ModularInverse { + + public static void main(String[] aArgs) { + System.out.println(inverseModulus(42, 2017)); + } + + private static Egcd extendedGCD(int aOne, int aTwo) { + if ( aOne == 0 ) { + return new Egcd(aTwo, 0, 1); + } + Egcd value = extendedGCD(aTwo % aOne, aOne); + return new Egcd(value.aG, value.aY - ( aTwo / aOne ) * value.aX, value.aX); + } + + private static int inverseModulus(int aNumber, int aModulus) { + Egcd value = extendedGCD(aNumber, aModulus); + return ( value.aG == 1 ) ? ( value.aX + aModulus ) % aModulus : 0; + } + + private static record Egcd(int aG, int aX, int aY) {} + +} diff --git a/Task/Modular-inverse/Julia/modular-inverse-2.julia b/Task/Modular-inverse/Julia/modular-inverse-2.julia index 85f702fb31..9e198d8acb 100644 --- a/Task/Modular-inverse/Julia/modular-inverse-2.julia +++ b/Task/Modular-inverse/Julia/modular-inverse-2.julia @@ -1,4 +1,4 @@ -function modinv{T<:Integer}(a::T, b::T) +function modinv(a::T, b::T) where T <: Integer b0 = b x0, x1 = zero(T), one(T) while a > 1 diff --git a/Task/Monads-List-monad/Java/monads-list-monad.java b/Task/Monads-List-monad/Java/monads-list-monad.java new file mode 100644 index 0000000000..96c9f3bfbf --- /dev/null +++ b/Task/Monads-List-monad/Java/monads-list-monad.java @@ -0,0 +1,43 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; + +public final class MonadList { + + public static void main(String[] aArgs) { + Monad integers = Monad.unit(List.of( 2, 3, 4 )); + Monad strings = integers.bind(MonadList::doubler).bind(MonadList::letters); + System.out.println(strings.getValue()); + } + + private static Monad doubler(List aList) { + return Monad.unit(aList.stream().map( i -> 2 * i ).toList()); + } + + private static Monad letters(List aList) { + return Monad.unit(aList.stream().map( i -> Character.toString((char) (64 + i)).repeat(i) ).toList()); + } + +} + +final class Monad { + + public static Monad unit(List aList) { + return new Monad(aList); + } + + public Monad bind(Function, Monad> aFunction) { + return aFunction.apply(list); + } + + public List getValue() { + return list; + } + + private Monad(List aList) { + list = new ArrayList(aList); + } + + private List list; + +} diff --git a/Task/Morse-code/FutureBasic/morse-code.basic b/Task/Morse-code/FutureBasic/morse-code.basic index d14cc5b86f..4f84f21854 100644 --- a/Task/Morse-code/FutureBasic/morse-code.basic +++ b/Task/Morse-code/FutureBasic/morse-code.basic @@ -1,8 +1,6 @@ +include "NSLog.incl" include "Tlbx AVKit.incl" -toolbox fn sinf(float) = float - - #define VOLUME 0.2 #define HZ_FREQUENCY 440.0 _ditDelay = 100 @@ -11,138 +9,131 @@ _spcDelay = 300 void local fn PlayCodeDone( ref as AVAudioPlayerNodeRef, userData as ptr ) -'~'1 -NSLog(@"%@\b",userData) + NSLog(@"%@\b",userData) end fn local fn PlayFrequency( frequency as float, amplitude as float, character as CFStringRef ) as AVAudioPlayerNodeRef -'~'1 -static AVAudioEngineRef audioEngine + static AVAudioEngineRef audioEngine -audioEngine = fn AVAudioEngineInit -AVAudioPlayerNodeRef player = fn AVAudioPlayerNodeInit + audioEngine = fn AVAudioEngineInit + AVAudioPlayerNodeRef player = fn AVAudioPlayerNodeInit -AVAudioMixerNodeRef mixer = fn AVAudioEngineMainMixerNode( audioEngine ) -float sampleRate = fn AVAudioFormatSampleRate( fn AVAudioNodeOutputFormatForBus( mixer, 0 ) ) -AVAudioFrameCount frameBufferLength = fn floorf( sampleRate / frequency ) * 1 -AVAudioPCMBufferRef buffer = fn AVAudioPCMBufferWithFormat( fn AVAudioNodeOutputFormatForBus( player, 0 ), frameBufferLength ) -AVAudioPCMBufferSetFrameLength( buffer, frameBufferLength ) -NSInteger channelCount = fn AVAudioFormatChannelCount( fn AVAudioNodeOutputFormatForBus( mixer, 0 ) ) -AVAudioFrameCount frameLength = fn AVAudioPCMBufferFrameLength( buffer ) + AVAudioMixerNodeRef mixer = fn AVAudioEngineMainMixerNode( audioEngine ) + float sampleRate = fn AVAudioFormatSampleRate( fn AVAudioNodeOutputFormatForBus( mixer, 0 ) ) + AVAudioFrameCount frameBufferLength = fn floorf( sampleRate / frequency ) * 1 + AVAudioPCMBufferRef buffer = fn AVAudioPCMBufferWithFormat( fn AVAudioNodeOutputFormatForBus( player, 0 ), frameBufferLength ) + AVAudioPCMBufferSetFrameLength( buffer, frameBufferLength ) + NSInteger channelCount = fn AVAudioFormatChannelCount( fn AVAudioNodeOutputFormatForBus( mixer, 0 ) ) + AVAudioFrameCount frameLength = fn AVAudioPCMBufferFrameLength( buffer ) -ptr p = (ptr)fn AVAudioPCMBufferFloatChannelData(buffer) -xref floatChannelData(100) as ^float -floatChannelData = p + ptr p = (ptr)fn AVAudioPCMBufferFloatChannelData(buffer) + xref floatChannelData(100) as ^float + floatChannelData = p -long i, channelNumber -float theta, value -^float channelBuffer + long i, channelNumber + float theta, value + ^float channelBuffer -for i = 0 to frameLength - 1 -theta = frequency * i * 2.0 * M_PI / sampleRate -value = fn sinf(theta) -for channelNumber = 0 to channelCount - 1 -channelBuffer = floatChannelData(channelNumber) -cln channelBuffer[i] = value * amplitude; -next -next + for i = 0 to frameLength - 1 + theta = frequency * i * 2.0 * M_PI / sampleRate + value = fn sinf(theta) + for channelNumber = 0 to channelCount - 1 + channelBuffer = floatChannelData(channelNumber) + cln channelBuffer[i] = value * amplitude; + next + next -AVAudioEngineAttachNode( audioEngine, player ) -AVAudioEngineConnect( audioEngine, player, mixer, fn AVAudioNodeOutputFormatForBus( player, 0 ) ) -fn AVAudioEngineStart( audioEngine, NULL ) -AVAudioPlayerNodePlay( player ) -AVAudioPlayerNodeScheduleBufferAtTime( player, buffer, NULL, AVAudioPlayerNodeBufferLoops, @fn PlayCodeDone, (ptr)character ) + AVAudioEngineAttachNode( audioEngine, player ) + AVAudioEngineConnect( audioEngine, player, mixer, fn AVAudioNodeOutputFormatForBus( player, 0 ) ) + fn AVAudioEngineStart( audioEngine, NULL ) + AVAudioPlayerNodePlay( player ) + AVAudioPlayerNodeScheduleBufferAtTime( player, buffer, NULL, AVAudioPlayerNodeBufferLoops, @fn PlayCodeDone, (ptr)character ) end fn = player void local fn PlayMorseCode( play as BOOL, character as CFStringRef ) -'~'1 -static AVAudioPlayerNodeRef player + static AVAudioPlayerNodeRef player -select ( play ) -case YES : player = fn PlayFrequency( HZ_FREQUENCY, VOLUME, character ) -case NO : AVAudioPlayerNodeStop( player ) // : AppRemoveAllProperties -end select + select ( play ) + case YES : player = fn PlayFrequency( HZ_FREQUENCY, VOLUME, character ) + case NO : AVAudioPlayerNodeStop( player ) // : AppRemoveAllProperties + end select end fn local fn ParseCodeAndPlay( character as CFStringRef ) -'~'1 -dispatchmain -if fn StringIsEqual( character, @"." ) then timerbegin : fn PlayMorseCode( YES, character ) : delay _ditDelay : fn PlayMorseCode( NO, NULL ) : timerend -if fn StringIsEqual( character, @"-" ) then timerbegin : fn PlayMorseCode( YES, character ) : delay _dahDelay : fn PlayMorseCode( NO, NULL ) : timerend -if fn StringIsEqual( character, @" " ) then timerbegin : NSLog(@" \b") : delay _spcDelay : timerend -if fn StringIsEqual( character, @"\n" ) then timerbegin : NSLog(@"") : timerend -dispatchend + dispatchmain + if fn StringIsEqual( character, @"." ) then timerbegin : fn PlayMorseCode( YES, character ) : delay _ditDelay : fn PlayMorseCode( NO, NULL ) : timerend + if fn StringIsEqual( character, @"-" ) then timerbegin : fn PlayMorseCode( YES, character ) : delay _dahDelay : fn PlayMorseCode( NO, NULL ) : timerend + if fn StringIsEqual( character, @" " ) then timerbegin : NSLog(@" \b") : delay _spcDelay : timerend + if fn StringIsEqual( character, @"\n" ) then timerbegin : NSLog(@"") : timerend + dispatchend end fn local fn MorseCharacter( letter as CFStringRef ) as CFStringRef -CFDictionaryRef morseDict = @{ -@"a":@".-", @"b":@"-...", @"c":@"-.-.", -@"d":@"-..", @"e":@".", @"f":@"..-.", -@"g":@"--.", @"h":@"....", @"i":@"..", -@"j":@".---", @"k":@"-.-", @"l":@".-..", -@"m":@"--", @"n":@"-.", @"o":@"---", -@"p":@".--.", @"q":@"--.-", @"r":@".-.", -@"s":@"...", @"t":@"-", @"u":@"..-", -@"v":@"...-", @"w":@".--", @"x":@"-..-", -@"y":@"-.--", @"z":@"--..", @"0":@"-----", -@"1":@".----", @"2":@"..---", @"3":@"...--", -@"4":@"....-", @"5":@".....", @"6":@"-....", -@"7":@"--...", @"8":@"---..", @"9":@"----."} + CFDictionaryRef morseDict = @{ + @"a":@".-", @"b":@"-...", @"c":@"-.-.", + @"d":@"-..", @"e":@".", @"f":@"..-.", + @"g":@"--.", @"h":@"....", @"i":@"..", + @"j":@".---", @"k":@"-.-", @"l":@".-..", + @"m":@"--", @"n":@"-.", @"o":@"---", + @"p":@".--.", @"q":@"--.-", @"r":@".-.", + @"s":@"...", @"t":@"-", @"u":@"..-", + @"v":@"...-", @"w":@".--", @"x":@"-..-", + @"y":@"-.--", @"z":@"--..", @"0":@"-----", + @"1":@".----", @"2":@"..---", @"3":@"...--", + @"4":@"....-", @"5":@".....", @"6":@"-....", + @"7":@"--...", @"8":@"---..", @"9":@"----."} end fn = morseDict[letter] local fn BuildMorseString( asciiStr as CFStringRef ) as CFStringRef -'~'1 -NSInteger i + NSInteger i -CFStringRef processStr = fn StringLowerCaseString( asciiStr ) -CFMutableStringRef mutStr = fn MutableStringWithCapacity(0) + CFStringRef processStr = fn StringLowerCaseString( asciiStr ) + CFMutableStringRef mutStr = fn MutableStringWithCapacity(0) -NSInteger length = len( processStr ) -for i = 0 to length - 1 -CFStringRef temp = mid( processStr, i, 1 ) -select ( temp ) -case @"\n", @"\r" -MutableStringAppendString( mutStr, @"\n" ) -case else -CFStringRef code = fn MorseCharacter( temp ) -if ( code != NULL ) -MutableStringAppendString( mutStr, fn StringByAppendingString( code, @" " ) ) -else -MutableStringAppendString( mutStr, @" " ) -end if -end select -next + NSInteger length = len( processStr ) + for i = 0 to length - 1 + CFStringRef temp = mid( processStr, i, 1 ) + select ( temp ) + case @"\n", @"\r" + MutableStringAppendString( mutStr, @"\n" ) + case else + CFStringRef code = fn MorseCharacter( temp ) + if ( code != NULL ) + MutableStringAppendString( mutStr, fn StringByAppendingString( code, @" " ) ) + else + MutableStringAppendString( mutStr, @" " ) + end if + end select + next end fn = fn StringWithString( mutStr ) local fn MorseCodeAudio( morseStr as CFStringRef ) -'~'1 -NSInteger i + NSInteger i -NSInteger length = len( morseStr ) -for i = 0 to length - 1 -CFStringRef temp = mid( morseStr, i, 1 ) -fn ParseCodeAndPlay( temp ) -next + NSInteger length = len( morseStr ) + for i = 0 to length - 1 + CFStringRef temp = mid( morseStr, i, 1 ) + fn ParseCodeAndPlay( temp ) + next end fn local fn OutputMorseCode( morseStr as CFStringRef ) -'~'1 -NSLog( @"\nSample ham radio Morse Code transmission:\n\n%@", morseStr ) -CFStringRef codeStr = fn BuildMorseString( morseStr ) -NSLog( @"\n\nMorse Code:\n\n%@", codeStr ) + NSLog( @"\nSample ham radio Morse Code transmission:\n\n%@", morseStr ) + CFStringRef codeStr = fn BuildMorseString( morseStr ) + NSLog( @"\n\nMorse Code:\n\n%@", codeStr ) -NSLog( @"\n\nAudio playing...\n" ) + NSLog( @"\n\nAudio playing...\n" ) -dispatchglobal -fn MorseCodeAudio( codeStr ) -dispatchend + dispatchglobal + fn MorseCodeAudio( codeStr ) + dispatchend end fn CFStringRef morseStr = @"CQ CQ CQ DE K1XYZ K1XYZ K TRANSMIT K1XYZ DE W1ZZZ TKS FOR CALL UR RST 479 479 NAME KEN KEN QTH NR KENTUCKY KENTUCKY G3ZZY DE W1ZZZ K" diff --git a/Task/Mouse-position/C++/mouse-position.cpp b/Task/Mouse-position/C++/mouse-position.cpp new file mode 100644 index 0000000000..5e498b8924 --- /dev/null +++ b/Task/Mouse-position/C++/mouse-position.cpp @@ -0,0 +1,10 @@ +#include + +#include + +int main() { + POINT MousePoint; + if ( GetCursorPos(&MousePoint) ) { + std::cout << MousePoint.x << ", " << MousePoint.y << std::endl; + } +} diff --git a/Task/Multi-base-primes/Java/multi-base-primes.java b/Task/Multi-base-primes/Java/multi-base-primes.java new file mode 100644 index 0000000000..3ee4f6df05 --- /dev/null +++ b/Task/Multi-base-primes/Java/multi-base-primes.java @@ -0,0 +1,111 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public final class MultibasePrimes { + + public static void main(String[] aArgs) { + final int maxBase = 36; + final int maxLength = 5; + fillPrimes(maxBase, maxLength); + multibasePrimes(maxBase, maxLength); + } + + private static void multibasePrimes(int aMaxBase, int aMaxLength) { + for ( int length = 1; length <= aMaxLength; length++ ) { + int maxBasesCount = 0; + List maxStrings = new ArrayList(); + List digits = new ArrayList(Collections.nCopies(length, 0)); + digits.set(0, 1); + List bases = new ArrayList(); + + do { + final int maxDigit = digits.stream().max(Integer::compare).get(); + final int minBase = Math.max(2, maxDigit + 1); + if ( maxBasesCount > aMaxBase - minBase + 1 ) { + continue; + } + bases.clear(); + + for ( int base = minBase; base <= aMaxBase; base++ ) { + if ( aMaxBase - base + 1 + bases.size() < maxBasesCount ) { + break; + } + int number = 0; + for ( int digit : digits ) { + number = number * base + digit; + } + if ( primes[number] ) { + bases.add(base); + } + } + + if ( bases.size() > maxBasesCount ) { + maxBasesCount = bases.size(); + maxStrings.clear(); + } + if ( bases.size() == maxBasesCount ) { + maxStrings.add( new Tuple( new ArrayList(digits), new ArrayList(bases) ) ); + } + + } while ( increment(digits, aMaxBase) ); + + System.out.println(length + "-character strings which are prime in the most bases: " + maxBasesCount); + for ( Tuple tuple : maxStrings ) { + System.out.println(numberBase(tuple.first) + " -> " + tuple.second); + } + System.out.println(); + } + } + + private static boolean increment(List aDigits, int aMaxBase) { + for ( int i = aDigits.size() - 1; i >= 0; i-- ) { + if ( aDigits.get(i) + 1 != aMaxBase ) { + aDigits.set(i, aDigits.get(i) + 1); + return true; + } + aDigits.set(i, 0); + } + return false; + } + + private static String numberBase(List aList) { + final String digits = "0123456789abcdefghijklmnopqrstuvwxyz"; + StringBuilder result = new StringBuilder(); + for ( int number : aList ) { + result.append(digits.charAt(number)); + } + return result.toString(); + } + + private static void fillPrimes(int aMaxBase, int aMaxLength) { + final int limit = (int) Math.pow(aMaxBase, aMaxLength); + primes = new boolean[limit + 1]; + Arrays.fill(primes, true); + primes[0] = false; + primes[1] = false; + for ( int i = 2; i < Math.sqrt(limit); i++ ) { + if ( primes[i] ) { + int j = i * i; + while ( j <= limit ) { + primes[j] = false; + j += i; + } + } + } + } + + private static class Tuple { + + public Tuple(List aFirst, List aSecond) { + first = aFirst; second = aSecond; + } + + private List first, second; + + } + + private static boolean[] primes; + +} diff --git a/Task/Multiplication-tables/Maxima/multiplication-tables.maxima b/Task/Multiplication-tables/Maxima/multiplication-tables-1.maxima similarity index 100% rename from Task/Multiplication-tables/Maxima/multiplication-tables.maxima rename to Task/Multiplication-tables/Maxima/multiplication-tables-1.maxima diff --git a/Task/Multiplication-tables/Maxima/multiplication-tables-2.maxima b/Task/Multiplication-tables/Maxima/multiplication-tables-2.maxima new file mode 100644 index 0000000000..f37a0e73e3 --- /dev/null +++ b/Task/Multiplication-tables/Maxima/multiplication-tables-2.maxima @@ -0,0 +1,11 @@ +/* Auxiliar function */ +aux_table(n,k):=append([k],makelist(0,i,1,k-1),makelist(k*i,i,k,n))$ + +/* Function to construct the formatted table */ +table_mult(n):=block( + append([makelist(i,i,0,n)],makelist(aux_table(n,k),k,1,n)), + makelist(at(%%[i],0=""),i,2,length(%%)), + table_form(%%))$ + +/* Test case */ +table_mult(12); diff --git a/Task/Multiplicative-order/C/multiplicative-order.c b/Task/Multiplicative-order/C/multiplicative-order.c index 7ec76bfdde..3a4342596b 100644 --- a/Task/Multiplicative-order/C/multiplicative-order.c +++ b/Task/Multiplicative-order/C/multiplicative-order.c @@ -57,7 +57,7 @@ ulong multi_order(ulong a, ulong m) int main() { sieve(); - printf("%lu\n", multi_order(37, 1000)); - printf("%lu\n", multi_order(54, 100001)); + printf("The multiplicative order of %d related to %d is %lu \n", 37, 1000, multi_order(37, 1000)); + printf("The multiplicative order of %d related to %d is %lu \n", 54, 100001, multi_order(54, 100001)); return 0; } diff --git a/Task/Multisplit/C++/multisplit.cpp b/Task/Multisplit/C++/multisplit-1.cpp similarity index 100% rename from Task/Multisplit/C++/multisplit.cpp rename to Task/Multisplit/C++/multisplit-1.cpp diff --git a/Task/Multisplit/C++/multisplit-2.cpp b/Task/Multisplit/C++/multisplit-2.cpp new file mode 100644 index 0000000000..c562940a74 --- /dev/null +++ b/Task/Multisplit/C++/multisplit-2.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include + +struct Split_data { + std::string segment; + int32_t index; + std::string separator; +}; + +std::vector multi_split(const std::string& text, const std::vector& separators) { + std::vector result; + uint64_t i = 0; + std::string segment = ""; + while ( i < text.length() ) { + bool found = false; + for ( std::string separator : separators ) { + if ( text.substr(i, separator.length()) == separator ) { + found = true; + result.emplace_back(segment, i, separator); + i += separator.length(); + segment = ""; + break; + } + } + + if ( ! found ) { + segment += text[i]; + i += 1; + } + } + result.emplace_back(segment, i, ""); + return result; +} + +int main() { + for ( Split_data splits : multi_split("a!===b=!=c", { "==", "!=", "=" } ) ) { + std::cout << std::left << std::setw(3) << "\"" + splits.segment + "\"" + << std::setw(18) << " ( split with \"" + splits.separator + "\"" + << " at index " << splits.index << " )" << std::endl; + } +} diff --git a/Task/Munchausen-numbers/LDPL/munchausen-numbers.ldpl b/Task/Munchausen-numbers/LDPL/munchausen-numbers.ldpl new file mode 100644 index 0000000000..58e58f451c --- /dev/null +++ b/Task/Munchausen-numbers/LDPL/munchausen-numbers.ldpl @@ -0,0 +1,21 @@ +data: +d is number +i is number +n is number +sum is number + +procedure: +for i from 1 to 5001 step 1 do + store 0 in sum + store i in n + while n is greater than 0 do + modulo n by 10 in d + raise d to d in d + add sum and d in sum + divide n by 10 in n + floor n + repeat + if sum is equal to i then + display i lf + end if +repeat diff --git a/Task/Munchausen-numbers/Phix/munchausen-numbers.phix b/Task/Munchausen-numbers/Phix/munchausen-numbers-1.phix similarity index 100% rename from Task/Munchausen-numbers/Phix/munchausen-numbers.phix rename to Task/Munchausen-numbers/Phix/munchausen-numbers-1.phix diff --git a/Task/Munchausen-numbers/Phix/munchausen-numbers-2.phix b/Task/Munchausen-numbers/Phix/munchausen-numbers-2.phix new file mode 100644 index 0000000000..36bf76cd98 --- /dev/null +++ b/Task/Munchausen-numbers/Phix/munchausen-numbers-2.phix @@ -0,0 +1,32 @@ +(phixonline)--> + with javascript_semantics + function munchausen(integer lo, hi) + integer maxlen = length(sprint(hi)) + string digits = sprint(lo) + sequence res = {} + while length(digits)<=maxlen do + atom tot = 0 + for j=1 to length(digits) do + integer d = digits[j]-'0' + if d then tot += power(d,d) end if + end for + if sort(sprint(tot))=digits then + res &= tot + end if + for j=length(digits) to 0 by -1 do + if j=0 then + digits = repeat('0',length(digits)+1) + exit + elsif digits[j]<'9' then + digits[j..$] = digits[j]+1 + exit + end if + end for + end while + return res + end function + atom t0 = time() + ?munchausen(1,5000) + ?munchausen(0,500_000_000) + ?elapsed(time()-t0) + n ) + + [] + 10000 times + [ i^ primefactors + dup size 2 < + iff drop done + 0 swap witheach + [ digitsum + ] + i^ digitsum = + if [ i^ join ] ] + + say "There are " + dup size echo say " Smith numbers less than 10000." cr cr + 10 split swap + say "They start: " echo cr + -10 split + say "...and end: " echo cr + drop diff --git a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures.rexx b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures.rexx index 7058365c8d..8d1e1e406d 100644 --- a/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures.rexx +++ b/Task/Sort-an-array-of-composite-structures/REXX/sort-an-array-of-composite-structures.rexx @@ -1,34 +1,51 @@ -/*REXX program sorts an array of composite structures (which has two classes of data).*/ -#=0 /*number elements in structure (so far)*/ -name='tan' ; value= 0; call add name,value /*tan peanut M&M's are 0% of total*/ -name='orange'; value=10; call add name,value /*orange " " " 10% " " */ -name='yellow'; value=20; call add name,value /*yellow " " " 20% " " */ -name='green' ; value=20; call add name,value /*green " " " 20% " " */ -name='red' ; value=20; call add name,value /*red " " " 20% " " */ -name='brown' ; value=30; call add name,value /*brown " " " 30% " " */ -call show 'before sort', # -say copies('▒', 70) -call xSort # -call show ' after sort', # -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -add: procedure expose # @.; #=#+1 /*bump the number of structure entries.*/ - @.#.color=arg(1); @.#.pc=arg(2) /*construct a entry of the structure. */ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -show: procedure expose @.; do j=1 for arg(2) /*2nd arg≡number of structure elements.*/ - say right(arg(1),30) right(@.j.color,9) right(@.j.pc,4)'%' - end /*j*/ /* [↑] display what, name, value. */ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -xSort: procedure expose @.; parse arg N; h=N - do while h>1; h=h%2 - do i=1 for N-h; j=i; k=h+i - do while @.k.color<@.j.color /*swap elements.*/ - _=@.j.color; @.j.color=@.k.color; @.k.color=_ - _=@.j.pc; @.j.pc =@.k.pc; @.k.pc =_ - if h>=j then leave; j=j-h; k=k-h - end /*while @.k.color ···*/ - end /*i*/ - end /*while h>1*/ - return +/*REXX program sorts an array of composite structures */ +/* (which has two classes of data). */ +x.=0 /*number elements in structure (so far)*/ +Call add 'tan' , 0 /*tan peanut M&M's are 0% of total*/ +Call add 'orange',10 /*orange " " " 10% " " */ +Call add 'yellow',20 /*yellow " " " 20% " " */ +Call add 'green' ,20 /*green " " " 20% " " */ +Call add 'red' ,20 /*red " " " 20% " " */ +Call add 'brown' ,30 /*brown " " " 30% " " */ +Call show 'before sort' +Say copies('¦', 70) +Call xSort +call show ' after sort' +Exit /*stick a fork in it, we're all done. */ +/*--------------------------------------------------------------------*/ +add: Procedure Expose x. + z=x.0+1 /* bump the number of structure entry */ + x.z.color=arg(1) + x.z.pc=arg(2) /* construct an entry of the structure */ + x.0=z + Return +/*--------------------------------------------------------------------*/ +show: Procedure Expose x. + Do i=1 To x.0 + /* display what name value. */ + Say right(arg(1),30) right(x.i.color,9) right(x.i.pc,4)'%' + End + Return +/*--------------------------------------------------------------------*/ +xsort: Procedure Expose x. + h=x.0 + Do While h>1 + h=h%2 + Do i=1 For x.0-h + j=i + k=h+i + Do While x.k.color=j Then + Leave + j=j-h + k=k-h + End + End + End + Return diff --git a/Task/Sort-disjoint-sublist/Quackery/sort-disjoint-sublist.quackery b/Task/Sort-disjoint-sublist/Quackery/sort-disjoint-sublist.quackery new file mode 100644 index 0000000000..a4899d3264 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Quackery/sort-disjoint-sublist.quackery @@ -0,0 +1,12 @@ + [ sort tuck [] unrot + witheach + [ dip dup peek + rot join swap ] + swap sort + dip swap witheach + [ over i^ peek + dip rot poke + swap ] + drop ] is sortdisjointsublist ( [ [ --> [ ) + + ' [ 7 6 5 4 3 2 1 0 ] ' [ 6 1 7 ] sortdisjointsublist echo diff --git a/Task/Sorting-algorithms-Bubble-sort/Maxima/sorting-algorithms-bubble-sort.maxima b/Task/Sorting-algorithms-Bubble-sort/Maxima/sorting-algorithms-bubble-sort.maxima new file mode 100644 index 0000000000..d7f098da83 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Maxima/sorting-algorithms-bubble-sort.maxima @@ -0,0 +1,20 @@ +bubble_sort(u) := block( + [n: length(u), swapped: true, temp], + while swapped do ( + swapped: false, + for i: 1 thru n - 1 do ( + if u[i] > u[i + 1] then ( + temp: u[i], + u[i]: u[i + 1], + u[i + 1]: temp, + swapped: true + ) + ) + ), + u +); +/* Example */ +/* sample:[3,65,6,24,24,89,2,59,6]$ + bubble_sort(%); + [2,3,6,6,24,24,59,65,89] +*/ diff --git a/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-2.groovy b/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-2.groovy index 0e577fd5c3..95bc21e51e 100644 --- a/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-2.groovy +++ b/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-2.groovy @@ -1,2 +1,50 @@ -println (heapSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) -println (heapSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) +def makeSwap (list, element1, element2) { + //exchanges two elements in a list. + //print a dot for each swap. + print "." + list[[element2,element1]] = list[[element1,element2]] +} + +def checkSwap (list, child, parent) { + //check if parent is smaller than child, then swap. + if (list[parent] < list[child]) makeSwap(list, child, parent) +} + +def siftDown (list, start, end) { + //end represents the limit of how far down the heap to sift + //start is the head of the heap + def parent = start + while (parent*2 < end) { //While the root has at least one child + def child = parent*2 + 1 //root*2+1 points to the left child + //find the child with the higher value + //if the child has a sibling and the child's value is less than its sibling's.. + if (child + 1 <= end && list[child] < list[child+1]) child++ //point to the other child + if (checkSwap(list, child, parent)) { //check if parent is smaller than child and swap + parent = child //make child to next parent + } else { + return //The rest of the heap is in order - return. + } + } +} + +def heapify (list) { + // Create a heap out of a list + // run through all the heap parents and + // ensure that each parent is lager than the child for all parent/childs. + // (list.size() -2) / 2 = last parent in the heap. + for (start in ((list.size()-2).intdiv(2))..0 ) { + siftDown(list, start, list.size() - 1) + } +} + +def heapSort (list) { + //heap sort any unsorted list + heapify(list) //ensure that the list is in a binary heap state + //Run the list backwards and + //for end = (size of list -1 ) to 0 + for (end in (list.size()-1)..0 ) { + makeSwap(list, 0, end) //put the top of the heap to the end (largest element) + siftDown(list, 0, end-1) //ensure that the rest is a heap again + } + list +} diff --git a/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-3.groovy b/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-3.groovy new file mode 100644 index 0000000000..0e577fd5c3 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Groovy/sorting-algorithms-heapsort-3.groovy @@ -0,0 +1,2 @@ +println (heapSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])) +println (heapSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])) diff --git a/Task/Sorting-algorithms-Quicksort/Koka/sorting-algorithms-quicksort-1.koka b/Task/Sorting-algorithms-Quicksort/Koka/sorting-algorithms-quicksort-1.koka index 1d2a55fa92..1bf3ef874b 100644 --- a/Task/Sorting-algorithms-Quicksort/Koka/sorting-algorithms-quicksort-1.koka +++ b/Task/Sorting-algorithms-Quicksort/Koka/sorting-algorithms-quicksort-1.koka @@ -3,7 +3,7 @@ fun qsort( xs : list ) : div list { Cons(x,xx) -> { val ys = xx.filter fn(el) { el < x } val zs = xx.filter fn(el) { el >= x } - qsort(ys) + [x] + qsort(zs) + qsort(ys) ++ [x] ++ qsort(zs) } Nil -> Nil } diff --git a/Task/Sorting-algorithms-Quicksort/Koka/sorting-algorithms-quicksort-2.koka b/Task/Sorting-algorithms-Quicksort/Koka/sorting-algorithms-quicksort-2.koka index 260385bf39..f40375ab18 100644 --- a/Task/Sorting-algorithms-Quicksort/Koka/sorting-algorithms-quicksort-2.koka +++ b/Task/Sorting-algorithms-Quicksort/Koka/sorting-algorithms-quicksort-2.koka @@ -2,7 +2,7 @@ fun qsort( xs : list ) : div list { match(xs) { Cons(x,xx) -> { val (ys, zs) = xx.partition fn(el) { el < x } - qsort(ys) + [x] + qsort(zs) + qsort(ys) ++ [x] ++ qsort(zs) } Nil -> Nil } diff --git a/Task/Sorting-algorithms-Strand-sort/AppleScript/sorting-algorithms-strand-sort-1.applescript b/Task/Sorting-algorithms-Strand-sort/AppleScript/sorting-algorithms-strand-sort-1.applescript new file mode 100644 index 0000000000..cb4a0e6514 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/AppleScript/sorting-algorithms-strand-sort-1.applescript @@ -0,0 +1,92 @@ +-- Return a deep copy of theList with items l thru r sorted ascending. +on strandSort(theList, l, r) + -- Resolve negative and/or transposed range index parameters. + set listLength to (count theList) + if (l < 0) then set l to listLength + l + 1 + if (r < 0) then set r to listLength + r + 1 + if (l > r) then set {l, r} to {r, l} + if ((l < 1) or (r > listLength)) then ¬ + error "strandSort(): range index parameter(s) outside list range." + + script o + property src : missing value + property dest : missing value + property ranges : {} + end script + + -- Arrange a copy of the list into "strands" of exisiting ascending order + -- and get the strands' ranges within this arrangement. + copy theList to o's src + set i to l + repeat until (i > r) + set j to i + set jVal to o's src's item j + repeat with k from (j + 1) to r + set kVal to o's src's item k + if (kVal < jVal) then + else + set j to j + 1 + set o's src's item k to o's src's item j + set o's src's item j to kVal + set jVal to kVal + end if + end repeat + set o's ranges's end to {i, j} + set i to j + 1 + end repeat + set rangeCount to (count o's ranges) + if (rangeCount = 1) then return o's src -- Already in order. + + -- Merge the strands back and forth between this list and another duplicate. + set o's dest to o's src's items + repeat until (rangeCount = 1) + set {o's src, o's dest} to {o's dest, o's src} + set k to l + repeat with rr from 2 to rangeCount by 2 + set {{i, ix}, {j, jx}} to o's ranges's items (rr - 1) thru rr + set o's ranges's item (rr - 1) to {i, jx} + set o's ranges's item rr to missing value + + set iVal to o's src's item i + set jVal to o's src's item j + repeat until (k > jx) + if (iVal > jVal) then + set o's dest's item k to jVal + set j to j + 1 + if (j > jx) then + repeat with i from i to ix + set k to k + 1 + set o's dest's item k to o's src's item i + end repeat + else + set jVal to o's src's item j + end if + else + set o's dest's item k to iVal + set i to i + 1 + if (i > ix) then + repeat with k from j to jx + set o's dest's item k to o's src's item k + end repeat + else + set iVal to o's src's item i + end if + end if + set k to k + 1 + end repeat + end repeat + if (rr < rangeCount) then + set {i, ix} to o's ranges's end + repeat with k from i to ix + set o's dest's item k to o's src's item k + end repeat + end if + + set o's ranges to o's ranges's lists + set rangeCount to (rangeCount + 1) div 2 + end repeat + + return o's dest +end strandSort + +strandSort({5, 1, 4, 37, 2, 0, 9, 6, -44, 3, 8, 7}, 1, -1) diff --git a/Task/Sorting-algorithms-Strand-sort/AppleScript/sorting-algorithms-strand-sort-2.applescript b/Task/Sorting-algorithms-Strand-sort/AppleScript/sorting-algorithms-strand-sort-2.applescript new file mode 100644 index 0000000000..a6a975bb2d --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/AppleScript/sorting-algorithms-strand-sort-2.applescript @@ -0,0 +1 @@ +{-44, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37} diff --git a/Task/Sorting-algorithms-Strand-sort/F-Sharp/sorting-algorithms-strand-sort.fs b/Task/Sorting-algorithms-Strand-sort/F-Sharp/sorting-algorithms-strand-sort.fs new file mode 100644 index 0000000000..fa63c8be6c --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/F-Sharp/sorting-algorithms-strand-sort.fs @@ -0,0 +1,10 @@ +// Strand sort. Nigel Galloway: August 18th., 2023 +let fN g=let mutable n=g in fun g->if n>g then false else n<-g; true +let fI n=let fN=fN(List.head n) in List.partition fN n +let rec fG n g=[match n,g with [],g|g,[]->yield! g + |n::gn,i::ng when nyield n; yield! fG gn g + |n,g::ng->yield g; yield! fG n ng] +let rec fL n g=match n with []->g |_->let n,i=fI n in fL i (n::g) +let sort n=fL n []|>List.fold(fun n g->fG n g)[] +printfn "%A" (sort ["one";"two";"three";"four"]);; +printfn "%A" (sort [2;3;1;5;11;7;5]) diff --git a/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx b/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx index b5059aaedd..eb36ccc334 100644 --- a/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx +++ b/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx @@ -1,31 +1,57 @@ -/*REXX program sorts a random list of words (or numbers) using the strand sort algorithm*/ -parse arg size minv maxv old /*obtain optional arguments from the CL*/ -if size=='' | size=="," then size=20 /*Not specified? Then use the default.*/ -if minv=='' | minv=="," then minv= 0 /*Not specified? Then use the default.*/ -if maxv=='' | maxv=="," then maxv=size /*Not specified? Then use the default.*/ - do i=1 for size /*generate a list of random numbers. */ - old=old random(0,maxv-minv)+minv /*append a random number to a list. */ - end /*i*/ -old=space(old) /*elide extraneous blanks from the list*/ - say center('unsorted list', length(old), "─"); say old -new=strand_sort(old) /*sort the list of the random numbers. */ -say; say center('sorted list' , length(new), "─"); say new -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -strand_sort: procedure; parse arg x; y= - do while words(x)\==0; w=words(x) - do j=1 for w-1 /*anything out of order?*/ - if word(x,j)>word(x,j+1) then do; w=j; leave; end - end /*j*/ - y=merge(y,subword(x,1,w)); x=subword(x,w+1) - end /*while*/ - return y -/*──────────────────────────────────────────────────────────────────────────────────────*/ -merge: procedure; parse arg a.1,a.2; p= - do forever; w1=words(a.1); w2=words(a.2) /*do while 2 lists exist*/ - if w1==0 | if w2==0 then leave /*Any list empty? Stop.*/ - if word(a.1,w1) <= word(a.2,1) then leave /*lists are now sorted? */ - if word(a.2,w2) <= word(a.1,1) then return space(p a.2 a.1) - #=1+(word(a.1,1) >= word(a.2,1)); p=p word(a.#,1); a.#=subword(a.#,2) - end /*forever*/ - return space(p a.1 a.2) +/*REXX program sorts a random list of words (or numbers) */ +/* using the strand sort algorithm */ +Parse Arg size minv maxv old /* obtain optional arguments from CL*/ +if size=='' | size=="," then size=20 /*Not specified? use default.*/ +if minv=='' | minv=="," then minv= 0 /*Not specified? use default.*/ +if maxv=='' | maxv=="," then maxv=size /*Not specified? use default.*/ +Do i=1 To size + old=old random(0,maxv-minv)+minv/* append random numbers to the list*/ + End +old=space(old) +Say 'Unsorted list:' +Say old +new=strand_sort(old) /* sort given list (extended by random numbers) */ +Say +Say 'Sorted list:' +Say new +Exit /* stick a fork in it, we're all done */ +/*--------------------------------------------------------------------*/ +strand_sort: Procedure + Parse Arg source + sorted='' + Do While words(source)\==0 + w=words(source) + /* Find first word in source that is smaller Than its predecessor */ + Do j=1 To w-1 + If word(source,j)>word(source,j+1) Then + Leave + End + /* Elements source.1 trough source.j are in ascending order */ + head=subword(source,1,j) + source=subword(source,j+1) /* the rest starts with a smaller */ + /* value or is empty (j=w!) */ + sorted=merge(sorted,head) + End + Return sorted +/*--------------------------------------------------------------------*/ +merge: Procedure + Parse Arg a.1,a.2 + p='' + Do Forever + w1=words(a.1) + w2=words(a.2) + Select + When w1==0 | w2==0 Then + Return space(p a.1 a.2) + When word(a.1,w1)<=word(a.2,1) Then + Return space(p a.1 a.2) + When word(a.2,w2)<=word(a.1,1) Then + Return space(p a.2 a.1) + Otherwise Do + nn=1+(word(a.1,1)>=word(a.2,1)) + /* move the smaller first word of a.1 or a.2 to p */ + p=p word(a.nn,1) + a.nn=subword(a.nn,2) + End + End + End diff --git a/Task/Steffensens-method/Jq/steffensens-method.jq b/Task/Steffensens-method/Jq/steffensens-method.jq new file mode 100644 index 0000000000..71dd532c0d --- /dev/null +++ b/Task/Steffensens-method/Jq/steffensens-method.jq @@ -0,0 +1,49 @@ +def aitken(f): + . as $p0 + | f as $p1 + | ($p1|f) as $p2 + | ($p1 - $p0) as $p1m0 + | $p0 - $p1m0 * $p1m0 / ($p2 - 2 * $p1 + $p0); + +def steffensenAitken(f; $pinit; $tol; $maxiter): + { p0: $pinit} + | .p = (.p0|aitken(f)) + | .iter = 1 + | until( ((.p - .p0)|length) <= $tol or .iter >= $maxiter; + .p0 = .p + | .p = (.p0|aitken(f)) + | .iter += 1 ) + | if ((.p - .p0)|length > $tol) then null else .p end; + +def deCasteljau($c0; $c1; $c2): + (1 - .) as $s + | ($s * $c0 + . * $c1) as $c01 + | ($s * $c1 + . * $c2) as $c12 + | $s * $c01 + . * $c12; + +def xConvexLeftParabola: deCasteljau(2; -8; 2); +def yConvexRightParabola: deCasteljau(1; 2; 3); + +def implicitEquation($x; $y): 5 * $x * $x + $y - 5; + +def f: + xConvexLeftParabola as $x + | yConvexRightParabola as $y + | implicitEquation($x; $y) + . ; + +def pp: . * 100 | round / 100; + +foreach range (0; 11) as $i ( {t0:0}; + .emit = "t0 = \(.t0|pp): " + | steffensenAitken(f; .t0; 0.00000001; 1000) as $t + | if $t + then ($t | xConvexLeftParabola) as $x + | ($t | yConvexRightParabola) as $y + | if (implicitEquation($x; $y)|length) <= 0.000001 + then .emit += "intersection at \($x), \($y)" + else .emit += "spurious solution" + end + else .emit += "no answer" + end + | .t0 += 0.1 ) +| .emit diff --git a/Task/String-append/LDPL/string-append.ldpl b/Task/String-append/LDPL/string-append.ldpl new file mode 100644 index 0000000000..66365ebc61 --- /dev/null +++ b/Task/String-append/LDPL/string-append.ldpl @@ -0,0 +1,7 @@ +data: +myText is text + +procedure: +store "LD" in myText +in myText join myText "PL" +display myText lf diff --git a/Task/String-case/AArch64-Assembly/string-case.aarch64 b/Task/String-case/AArch64-Assembly/string-case.aarch64 new file mode 100644 index 0000000000..f89c5ff276 --- /dev/null +++ b/Task/String-case/AArch64-Assembly/string-case.aarch64 @@ -0,0 +1,84 @@ +/* ARM assembly AARCH64 Raspberry PI 3B */ +/* program strcase64.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeConstantesARM64.inc" + +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessResult: .asciz "Result: \n" +szString: .asciz "alphaBETA" +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 64 bits start.\n" +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sBuffer: .skip 80 +sBuffex1: .skip 80 +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: // entry of program + ldr x0,qAdrszMessStart + bl affichageMess + ldr x1,qAdrszString + ldr x3,qAdrsBuffer + ldr x4,qAdrsBuffex1 + mov x6,#0b100000 // 1 -> bit 5 + mov x2,#0 +1: + ldrb w0,[x1,x2] // load byte of string + mov x5,x0 + cmp x0,#'A' // select alpha characters lower or upper + blt 3f + cmp x0,#'z' + bgt 3f + cmp x0,#'Z' + ble 2f + cmp x0,#'a' + bge 2f + b 3f +2: + orr x0,x0,x6 // converion in lower case (1 -> bit 5) + bic x5,x0,x6 // converion in upper case (0 -> bit 5) +3: + strb w0,[x3,x2] // store lower character + strb w5,[x4,x2] // store upper character + cmp x0,#0 // end string ? + add x2,x2,#1 // increment index character + bne 1b // loop + + + ldr x0,qAdrszMessResult + bl affichageMess + ldr x0,qAdrsBuffer + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess + ldr x0,qAdrsBuffex1 + bl affichageMess + ldr x0,qAdrszCarriageReturn + bl affichageMess +100: // standard end of the program + mov x0, #0 // return code + mov x8, #EXIT // request to exit program + svc 0 // perform the system call +qAdrszString: .quad szString +qAdrsBuffer: .quad sBuffer +qAdrsBuffex1: .quad sBuffex1 +qAdrszMessResult: .quad szMessResult +qAdrszCarriageReturn: .quad szCarriageReturn +qAdrszMessStart: .quad szMessStart +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language AArch64 assembly*/ +.include "../includeARM64.inc" diff --git a/Task/String-case/ARM-Assembly/string-case.arm b/Task/String-case/ARM-Assembly/string-case.arm new file mode 100644 index 0000000000..7a9fb99479 --- /dev/null +++ b/Task/String-case/ARM-Assembly/string-case.arm @@ -0,0 +1,84 @@ +/* ARM assembly Raspberry PI */ +/* program strcase.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../constantes.inc" + +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessResult: .asciz "Result: \n" +szString: .asciz "alphaBETA" +szCarriageReturn: .asciz "\n" +szMessStart: .asciz "Program 32 bits start.\n" +/************************************/ +/* UnInitialized data */ +/************************************/ +.bss +sBuffer: .skip 80 +sBuffer1: .skip 80 +/************************************/ +/* code section */ +/************************************/ +.text +.global main +main: @ entry of program + ldr r0,iAdrszMessStart + bl affichageMess + ldr r1,iAdrszString + ldr r3,iAdrsBuffer + ldr r4,iAdrsBuffer1 + mov r6,#0b100000 @ 1 -> bit 5 + mov r2,#0 +1: + ldrb r0,[r1,r2] @ load byte of string + mov r5,r0 + cmp r0,#'A' @ select alpha characters lower or upper + blt 3f + cmp r0,#'z' + bgt 3f + cmp r0,#'Z' + ble 2f + cmp r0,#'a' + bge 2f + b 3f +2: + orr r0,r0,r6 @ converion in lower case (1 -> bit 5) + bic r5,r0,r6 @ converion in upper case (0 -> bit 5) +3: + strb r0,[r3,r2] @ store lower character + strb r5,[r4,r2] @ store upper character + cmp r0,#0 @ end string ? + add r2,r2,#1 @ increment index character + bne 1b @ loop + + + ldr r0,iAdrszMessResult + bl affichageMess + ldr r0,iAdrsBuffer + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + ldr r0,iAdrsBuffer1 + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdrszString: .int szString +iAdrsBuffer: .int sBuffer +iAdrsBuffer1: .int sBuffer1 +iAdrszMessResult: .int szMessResult +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessStart: .int szMessStart +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../affichage.inc" diff --git a/Task/String-concatenation/Fantom/string-concatenation.fantom b/Task/String-concatenation/Fantom/string-concatenation-1.fantom similarity index 100% rename from Task/String-concatenation/Fantom/string-concatenation.fantom rename to Task/String-concatenation/Fantom/string-concatenation-1.fantom diff --git a/Task/String-concatenation/Fantom/string-concatenation-2.fantom b/Task/String-concatenation/Fantom/string-concatenation-2.fantom new file mode 100644 index 0000000000..e27c392bad --- /dev/null +++ b/Task/String-concatenation/Fantom/string-concatenation-2.fantom @@ -0,0 +1,13 @@ +/* gary chike 08/27/2023 */ + +class Main +{ + static Void main() { + s1 := "Only The" + s2 := "knows" + s3 := s1 + " Fantom " + s2 + "!" // Concatenation + echo(s3) + s4 := "$s1 Fantom $s2!" // String interpolation + echo(s4) + } +} diff --git a/Task/Substring-Top-and-tail/Arturo/substring-top-and-tail.arturo b/Task/Substring-Top-and-tail/Arturo/substring-top-and-tail.arturo index d6ca00a77d..75c71379e5 100644 --- a/Task/Substring-Top-and-tail/Arturo/substring-top-and-tail.arturo +++ b/Task/Substring-Top-and-tail/Arturo/substring-top-and-tail.arturo @@ -2,12 +2,12 @@ knight: "knight" socks: "socks" brooms: "brooms" -print drop knight 1 ; strip first character +print drop knight. ; strip first character print slice knight 1 (size knight)-1 ; alternate way to strip first character print chop socks ; strip last character print take socks (size socks)-1 ; alternate way to strip last character print slice socks 0 (size socks)-2 ; yet another way to strip last character -print chop drop brooms 1 ; strip both first and last characters +print chop drop brooms ; strip both first and last characters print slice brooms 1 (size brooms)-2 ; alternate way to strip both first and last characters diff --git a/Task/Substring-Top-and-tail/Java/substring-top-and-tail.java b/Task/Substring-Top-and-tail/Java/substring-top-and-tail-1.java similarity index 100% rename from Task/Substring-Top-and-tail/Java/substring-top-and-tail.java rename to Task/Substring-Top-and-tail/Java/substring-top-and-tail-1.java diff --git a/Task/Substring-Top-and-tail/Java/substring-top-and-tail-2.java b/Task/Substring-Top-and-tail/Java/substring-top-and-tail-2.java new file mode 100644 index 0000000000..309ff06e47 --- /dev/null +++ b/Task/Substring-Top-and-tail/Java/substring-top-and-tail-2.java @@ -0,0 +1,16 @@ +public class SubstringTopAndTail { + public static void main( String[] args ){ + var s = "\uD83D\uDC0Eabc\uD83D\uDC0E"; // Horse emoji, a, b, c, horse emoji: "🐎abc🐎" + + var sizeOfFirstChar = Character.isSurrogate(s.charAt(0)) ? 2 : 1; + var sizeOfLastChar = Character.isSurrogate(s.charAt(s.length() - 1)) ? 2 : 1; + + var removeFirst = s.substring(sizeOfFirstChar); + var removeLast = s.substring(0, s.length() - sizeOfLastChar); + var removeBoth = s.substring(sizeOfFirstChar, s.length() - sizeOfLastChar); + + System.out.println(removeFirst); + System.out.println(removeLast); + System.out.println(removeBoth); + } +} diff --git a/Task/Sudoku/FutureBasic/sudoku.basic b/Task/Sudoku/FutureBasic/sudoku.basic index 10a258c158..cb029b50d1 100644 --- a/Task/Sudoku/FutureBasic/sudoku.basic +++ b/Task/Sudoku/FutureBasic/sudoku.basic @@ -1,94 +1,91 @@ -include "ConsoleWindow" -include "NSLog.incl" include "Util_Containers.incl" begin globals -dim as container gC +container gC end globals BeginCDeclaration -short solve_sudoku(short i); -short check_sudoku(short r, short c); -CFMutableStringRef print_sudoku(); + short solve_sudoku(short i); + short check_sudoku(short r, short c); + CFMutableStringRef print_sudoku(); EndC BeginCFunction -short sudoku[9][9] = { - {3,0,0,0,0,1,4,0,9}, - {7,0,0,0,0,4,2,0,0}, - {0,5,0,2,0,0,0,1,0}, - {5,7,0,0,4,3,0,6,0}, - {0,9,0,0,0,0,0,3,0}, - {0,6,0,7,9,0,0,8,5}, - {0,8,0,0,0,5,0,4,0}, - {0,0,6,4,0,0,0,0,7}, - {9,0,5,6,0,0,0,0,3}, - }; + short sudoku[9][9] = { + {3,0,0,0,0,1,4,0,9}, + {7,0,0,0,0,4,2,0,0}, + {0,5,0,2,0,0,0,1,0}, + {5,7,0,0,4,3,0,6,0}, + {0,9,0,0,0,0,0,3,0}, + {0,6,0,7,9,0,0,8,5}, + {0,8,0,0,0,5,0,4,0}, + {0,0,6,4,0,0,0,0,7}, + {9,0,5,6,0,0,0,0,3}, + }; -short check_sudoku( short r, short c ) -{ - short i; - short rr, cc; - - for (i = 0; i < 9; i++) + short check_sudoku( short r, short c ) { - if (i != c && sudoku[r][i] == sudoku[r][c]) return 0; - if (i != r && sudoku[i][c] == sudoku[r][c]) return 0; - rr = r/3 * 3 + i/3; - cc = c/3 * 3 + i%3; - if ((rr != r || cc != c) && sudoku[rr][cc] == sudoku[r][c]) return 0; - } - return -1; -} + short i; + short rr, cc; - -short solve_sudoku( short i ) -{ - short r, c; - - if (i < 0) return 0; - else if (i >= 81) return -1; - - r = i / 9; - c = i % 9; - - if (sudoku[r][c]) - return check_sudoku(r, c) && solve_sudoku(i + 1); - else - for (sudoku[r][c] = 9; sudoku[r][c] > 0; sudoku[r][c]--) + for (i = 0; i < 9; i++) { - if ( solve_sudoku(i) ) return -1; + if (i != c && sudoku[r][i] == sudoku[r][c]) return 0; + if (i != r && sudoku[i][c] == sudoku[r][c]) return 0; + rr = r/3 * 3 + i/3; + cc = c/3 * 3 + i%3; + if ((rr != r || cc != c) && sudoku[rr][cc] == sudoku[r][c]) return 0; } - return 0; -} + return -1; + } -CFMutableStringRef print_sudoku() -{ - short i, j; - CFMutableStringRef mutStr; + short solve_sudoku( short i ) + { + short r, c; - mutStr = CFStringCreateMutable( kCFAllocatorDefault, 0 ); + if (i < 0) return 0; + else if (i >= 81) return -1; - for (i = 0; i < 9; i++) - { - for (j = 0; j < 9; j++) - { - CFStringAppendFormat( mutStr, NULL, (CFStringRef)@" %d", sudoku[i][j] ); - } - CFStringAppendFormat( mutStr, NULL, (CFStringRef)@"\r" ); - } - return( mutStr ); -} + r = i / 9; + c = i % 9; + + if (sudoku[r][c]) + return check_sudoku(r, c) && solve_sudoku(i + 1); + else + for (sudoku[r][c] = 9; sudoku[r][c] > 0; sudoku[r][c]--) + { + if ( solve_sudoku(i) ) return -1; + } + return 0; + } + + + CFMutableStringRef print_sudoku() + { + short i, j; + CFMutableStringRef mutStr; + mutStr = CFStringCreateMutable( kCFAllocatorDefault, 0 ); + + for (i = 0; i < 9; i++) + { + for (j = 0; j < 9; j++) + { + CFStringAppendFormat( mutStr, NULL, (CFStringRef)@" %d", sudoku[i][j] ); + } + CFStringAppendFormat( mutStr, NULL, (CFStringRef)@"\r" ); + } + return( mutStr ); + } EndC toolbox fn solve_sudoku( short i ) = short toolbox fn check_sudoku( short r, short c ) = short toolbox fn print_sudoku() = CFMutableStringRef -dim as short solution -dim as CFMutableStringRef cfRef +short solution +CFMutableStringRef cfRef gC = " " cfRef = fn print_sudoku() @@ -99,10 +96,12 @@ solution = fn solve_sudoku(0) print : print "Sudoku solved:" : print if ( solution ) -gC = " " -cfRef = fn print_sudoku() -fn ContainerCreateWithCFString( cfRef, gC ) -print gC + gC = " " + cfRef = fn print_sudoku() + fn ContainerCreateWithCFString( cfRef, gC ) + print gC else -print "No solution found" + print "No solution found" end if + +HandleEvents diff --git a/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-1.j b/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-1.j index 31fc0ba745..28ac2cd2dd 100644 --- a/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-1.j +++ b/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-1.j @@ -1,13 +1,11 @@ -(X=. 0&{"1) (Y=. 1&{"1) -(S=. X + Y) (P=. X * Y) +(S=. X + Y) (P=. X * Y) (X=. 0&{"1) (Y=. 1&{"1) +(sd=. S : S o ]) and ((1 < X) and (1 < Y) (and=. *.) (X < Y)) o ]) filter0=. candidates o (constraints # ]) -(sd=. S "0 _ < o pmtod) ; o # sd) diff --git a/Task/Sum-of-squares/UNIX-Shell/sum-of-squares.sh b/Task/Sum-of-squares/UNIX-Shell/sum-of-squares.sh index 998ad340c6..6b2f576239 100644 --- a/Task/Sum-of-squares/UNIX-Shell/sum-of-squares.sh +++ b/Task/Sum-of-squares/UNIX-Shell/sum-of-squares.sh @@ -1,10 +1,10 @@ -$ cat toto -1 -2 -4 -8 -16 -$ cat toto toto | paste -sd* -1*2*4*8*16*1*2*4*8*16 -$ cat toto toto | paste -sd* | bc -l -1048576 +sum_squares () { + _r=0 + for _n + do + : "$((_r += _n * _n))" + done + echo "$_r" +} + +sum_squares 3 1 4 1 5 9 diff --git a/Task/Sutherland-Hodgman-polygon-clipping/Evaldraw/sutherland-hodgman-polygon-clipping.evaldraw b/Task/Sutherland-Hodgman-polygon-clipping/Evaldraw/sutherland-hodgman-polygon-clipping.evaldraw new file mode 100644 index 0000000000..f56d8eb940 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/Evaldraw/sutherland-hodgman-polygon-clipping.evaldraw @@ -0,0 +1,116 @@ +struct vec{ x, y; }; +enum{MAX_POLY_VERTS=32}; +enum{NUM_RECT_VERTS=4, NUM_SUBJECT_VERTS=9} +struct poly_t{ + len; // number of vertices + vec v[MAX_POLY_VERTS]; // wrap array of vertices inside struct +}; +() +{ + vec subject_verts[NUM_SUBJECT_VERTS] = { 50,150, 200,50, 350,150, 350,300,250,300,200,250, 150,350,100,250,100,200 }; + vec rectangle_vertices[NUM_RECT_VERTS] = {100,100, 300,100, 300,300, 100,300}; + + poly_t clipper; // This polygon will define the valid area + clipper.len = 0; + for(i=0; iMAX_POLY_VERTS) errno(100); +} +poly_copy(poly_t src, poly_t dst) { // This improves on assigning dst to src as + for(i=0; i a0 X da = b0 X da + s db X da -> s = (a0 - b0) X da / (db X da) */ + double dbXda = cross2D(db, da); + if (!dbXda) return 0; + s = cross2D(&d, &da) / dbXda; + if (s <= 0 || s >= 1) return 0; + isect.x = b0.x + s * db.x; + isect.y = b0.y + s * db.y; + return 1; +} +errno(code) { // Since we dont have asserts, halt and print an error code + while(1) { + cls(32,32,32); setcol(200,0,0); moveto(0,0); + printf("errno(%g)", code); refresh(); sleep(1); + } +} +drawpoly(poly_t p, show_verts) { + for(i=0; i0 + Say linein(notes) /* display a line of file --> screen. */ + End + End + Otherwise Do + timestamp=right(date(),11,0) time() date('W') /*create current date & time stamp */ + If 'f2'x==2 Then tab='05'x /* this is an EBCDIC system. */ + Else tab='09'x /* " " " ASCII " */ + Call lineout notes,timestamp /*append the timestamp to "notes" file.*/ + Call lineout notes,tab||arg(1) /* " " text " " " */ + End + End /*stick a fork in it, we're all Done. */ diff --git a/Task/Temperature-conversion/Ksh/temperature-conversion.ksh b/Task/Temperature-conversion/Ksh/temperature-conversion.ksh new file mode 100644 index 0000000000..6a93c8beae --- /dev/null +++ b/Task/Temperature-conversion/Ksh/temperature-conversion.ksh @@ -0,0 +1,11 @@ +#!/bin/ksh +# Temperature conversion +set -A tt 0.00 273.15 373.15 +for t in "${tt[@]}" +do + echo + echo "Kelvin: $t K" + echo "Celsius: $((t-273.15)) C" + echo "Fahrenheit: $((t*18/10-459.67)) F" + echo "Rankine: $((t*18/10)) R" +done diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol index 14732fb810..cb58f13bf9 100644 --- a/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol +++ b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-1.cobol @@ -1 +1,12 @@ -DISPLAY SPACE WITH BELL + IDENTIFICATION DIVISION. + PROGRAM-ID. ring-terminal-bell. + + DATA DIVISION. + SCREEN SECTION. + 01 ringer BELL. + + PROCEDURE DIVISION. + DISPLAY ringer + STOP RUN. + + END PROGRAM ring-terminal-bell. diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol index 9adfe242f6..44ce470ca5 100644 --- a/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol +++ b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-2.cobol @@ -1,13 +1,16 @@ + *> Tectonics: cobc -xj ring-terminal-bell.cob -std=cobol85 IDENTIFICATION DIVISION. - PROGRAM-ID. mf-bell. + PROGRAM-ID. ring-ascii-bell. - DATA DIVISION. - WORKING-STORAGE SECTION. - 01 bell-code PIC X USAGE COMP-X VALUE 22. - 01 dummy-param PIC X. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + OBJECT-COMPUTER. + PROGRAM COLLATING SEQUENCE IS ASCII. + SPECIAL-NAMES. + ALPHABET ASCII IS STANDARD-1. PROCEDURE DIVISION. - CALL X"AF" USING bell-code, dummy-param + DISPLAY FUNCTION CHAR(8) WITH NO ADVANCING + STOP RUN. - GOBACK - . + END PROGRAM ring-ascii-bell. diff --git a/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-3.cobol b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-3.cobol new file mode 100644 index 0000000000..266a4910c7 --- /dev/null +++ b/Task/Terminal-control-Ringing-the-terminal-bell/COBOL/terminal-control-ringing-the-terminal-bell-3.cobol @@ -0,0 +1,13 @@ + IDENTIFICATION DIVISION. + PROGRAM-ID. mf-bell. + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 bell-code PIC X USAGE COMP-X VALUE 22. + 01 dummy-param PIC X. + + PROCEDURE DIVISION. + CALL X"AF" USING bell-code, dummy-param + GOBACK. + + END PROGRAM mf-bell. diff --git a/Task/The-Name-Game/Arturo/the-name-game.arturo b/Task/The-Name-Game/Arturo/the-name-game.arturo index 4569b6c1ab..c43fddb114 100644 --- a/Task/The-Name-Game/Arturo/the-name-game.arturo +++ b/Task/The-Name-Game/Arturo/the-name-game.arturo @@ -1,7 +1,7 @@ nameGame: function [Name][ L: take Name 1 name: lower Name - unless in? L "AEIOU" -> drop 'name 1 + unless in? L "AEIOU" -> drop 'name [B F M]: ["b" "f" "m"] if L="B" -> B: "" diff --git a/Task/The-Twelve-Days-of-Christmas/Pointless/the-twelve-days-of-christmas.pointless b/Task/The-Twelve-Days-of-Christmas/Pointless/the-twelve-days-of-christmas.pointless new file mode 100644 index 0000000000..361c344417 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Pointless/the-twelve-days-of-christmas.pointless @@ -0,0 +1,50 @@ +output = + range(1, 12) + |> map(makeVerse) + |> join("\n\n") + |> print + +days = { + 1: "first", + 2: "second", + 3: "third", + 4: "fourth", + 5: "fifth", + 6: "sixth", + 7: "seventh", + 8: "eighth", + 9: "ninth", + 10: "tenth", + 11: "eleventh", + 12: "twelfth" +} + +verseFormat = """On the {} day of Christmas +My true love gave to me: +{}""" + +makeVerse(n) = + format(verseFormat, + [getDefault(days, "", n), + makeGifts(n)]) + +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", +] + +makeGifts(n) = + gifts + |> take(n) + |> reverse + |> join("\n") diff --git a/Task/Tokenize-a-string/Dt/tokenize-a-string.dt b/Task/Tokenize-a-string/Dt/tokenize-a-string.dt new file mode 100644 index 0000000000..02db0a4968 --- /dev/null +++ b/Task/Tokenize-a-string/Dt/tokenize-a-string.dt @@ -0,0 +1 @@ +"Hello,How,Are,You,Today" "," split "." join pl diff --git a/Task/Tokenize-a-string/Maxima/tokenize-a-string.maxima b/Task/Tokenize-a-string/Maxima/tokenize-a-string-1.maxima similarity index 100% rename from Task/Tokenize-a-string/Maxima/tokenize-a-string.maxima rename to Task/Tokenize-a-string/Maxima/tokenize-a-string-1.maxima diff --git a/Task/Tokenize-a-string/Maxima/tokenize-a-string-2.maxima b/Task/Tokenize-a-string/Maxima/tokenize-a-string-2.maxima new file mode 100644 index 0000000000..4adb65f661 --- /dev/null +++ b/Task/Tokenize-a-string/Maxima/tokenize-a-string-2.maxima @@ -0,0 +1,2 @@ +split("Hello,How,Are,You,Today",",")$ +simplode(%,"."); diff --git a/Task/Totient-function/ALGOL-M/totient-function.alg b/Task/Totient-function/ALGOL-M/totient-function.alg index abfa0bc25f..7cb664b2c4 100644 --- a/Task/Totient-function/ALGOL-M/totient-function.alg +++ b/Task/Totient-function/ALGOL-M/totient-function.alg @@ -32,22 +32,21 @@ INTEGER FUNCTION PHI(N); INTEGER N; BEGIN INTEGER I, COUNT; - COUNT := 1; - FOR I := 2 STEP 1 UNTIL N DO + COUNT := 1; + FOR I := 2 STEP 1 UNTIL N DO BEGIN IF GCD(N,I) = 1 THEN COUNT := COUNT + 1; END; PHI := COUNT; END; - COMMENT - EXERCISE THE FUNCTION; INTEGER N, TOTIENT, COUNT; WRITE(" N PHI(N) PRIME?"); FOR N := 1 STEP 1 UNTIL 25 DO BEGIN - WRITE(N, (TOTIENT := PHI(N))); - WRITEON(IF TOTIENT = (N-1) THEN " YES" ELSE " NO"); + WRITE(N, (TOTIENT := PHI(N))); + WRITEON(IF TOTIENT = (N-1) THEN " YES" ELSE " NO"); END; COMMENT - AND USE IT TO COUNT PRIMES; @@ -58,7 +57,7 @@ BEGIN IF PHI(N) = (N-1) THEN COUNT := COUNT + 1; IF N = 100 THEN WRITE("PRIMES UP TO 100 =", COUNT) - ELSE IF N = 1000 THEN + ELSE IF N = 1000 THEN WRITE("PRIMES UP TO 1000 =", COUNT); END; diff --git a/Task/Twin-primes/Maxima/twin-primes.maxima b/Task/Twin-primes/Maxima/twin-primes.maxima new file mode 100644 index 0000000000..b423cde883 --- /dev/null +++ b/Task/Twin-primes/Maxima/twin-primes.maxima @@ -0,0 +1,15 @@ +/* Function to count the number of pairs below n */ +twin_primes_under_n(n):=block( + L:makelist([6*i-1,6*i+1],i,1,floor(n/6)), + caching:length(L), + L1:[], + for i from 1 thru caching do if map(primep,L[i])=[true,true] then push(L[i],L1), + append([[3,5]],reverse(L1)), + length(%%)); + +/* Test cases */ +twin_primes_under_n(10); +twin_primes_under_n(100); +twin_primes_under_n(1000); +twin_primes_under_n(10000); +twin_primes_under_n(100000); diff --git a/Task/Two-bullet-roulette/Odin/two-bullet-roulette.odin b/Task/Two-bullet-roulette/Odin/two-bullet-roulette.odin new file mode 100644 index 0000000000..e0ed761e69 --- /dev/null +++ b/Task/Two-bullet-roulette/Odin/two-bullet-roulette.odin @@ -0,0 +1,78 @@ +/* imports */ +import "core:fmt" +import "core:strings" +import "core:math/rand" +/* globals */ +cylinder := [6]bool{} +/* main block */ +main :: proc() { + rand.set_global_seed(42) + tests := 100000 + sequence := [?]string{"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} + for m in sequence { + sum := 0 + for t in 0 ..< tests { + sum += method(m) + } + pc: f64 = cast(f64)sum * 100 / cast(f64)tests + fmt.printf("%-40s produces %6.3f%% deaths.\n", mstring(m), pc) + } +} +/* definitions */ +rshift :: proc() { + t := cylinder[len(cylinder) - 1] + copy(cylinder[1:], cylinder[0:]) + cylinder[0] = t +} +unload :: proc() { + cylinder = false // array programming +} +load :: proc() { + for cylinder[0] { + rshift() + } + cylinder[0] = true + rshift() +} +spin :: proc() { + data: []int = {1, 2, 3, 4, 5, 6} + lim := rand.choice(data[:]) + for i in 0 ..< lim { + rshift() + } +} +fire :: proc() -> bool { + shot := cylinder[0] + rshift() + return shot +} +method :: proc(s: string) -> int { + unload() + for character in s { + switch character { + case 'L': + load() + case 'S': + spin() + case 'F': + if fire() { + return 1 + } + } + } + return 0 +} +mstring :: proc(s: string) -> string { + l: [dynamic]string + for character in s { + switch character { + case 'L': + append(&l, "load") + case 'S': + append(&l, "spin") + case 'F': + append(&l, "fire") + } + } + return strings.join(l[:], ", ") +} diff --git a/Task/Ulam-spiral-for-primes-/Maxima/ulam-spiral-for-primes-.maxima b/Task/Ulam-spiral-for-primes-/Maxima/ulam-spiral-for-primes-.maxima new file mode 100644 index 0000000000..e0dded5653 --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/Maxima/ulam-spiral-for-primes-.maxima @@ -0,0 +1,6 @@ +/* Adapting the spiral to the problem requirements */ +spiral_from_center(n):=(n^2+1)*matrixmap(lambda([x],x+1),zeromatrix(n,n))-spiral(n)$ + +/* Testing */ +spiral_from_center(35)$ +matrixmap(lambda([x],if primep(x) then "O" else ""),%); diff --git a/Task/Ulam-spiral-for-primes-/ZX-Spectrum-Basic/ulam-spiral-for-primes-.basic b/Task/Ulam-spiral-for-primes-/ZX-Spectrum-Basic/ulam-spiral-for-primes-.basic new file mode 100644 index 0000000000..3df37aa7be --- /dev/null +++ b/Task/Ulam-spiral-for-primes-/ZX-Spectrum-Basic/ulam-spiral-for-primes-.basic @@ -0,0 +1,11 @@ + 1 IF nn/p): IF r THEN NEXT p + 2 IF p=n THEN LET pr=pr+1: LET kx=(255-xx AND k<3)+(xx AND k>2): LET ky=(175-yy AND (k=1 OR k=3)+(yy AND (k=2 OR k=4))): PLOT kx,ky: PRINT #0;AT 0,0;n;" pr";pr + 3 RETURN + 10 CLS : PRINT "ULAM SPIRAL OF PRIME's"'''"it takes DAYS at max level"'"and 3.5MHz" + 12 INPUT "square size= LxL"'"l: ";l: IF l<>INT l OR l<1 OR l>176 THEN GO TO 12 + 13 LET max=l*l: PRINT ''l;"x";l;"=";max;" positive integers" + 15 INPUT "0,0 orientation 1-4: ";k: IF k<1 OR k>4 THEN GO TO 15 + 20 CLS : LET xx=127: LET yy=88: LET n=0: LET pr=0: PRINT #0;AT 0,15;max + 40 FOR q=0 TO l: LET m=INT (q/2)=q/2: LET m=-1*m+NOT m + 60 FOR x=0 TO q*m STEP m: GO SUB 1 : LET xx=xx+m: NEXT x + 80 FOR y=0 TO q*m STEP m: GO SUB 1 : LET yy=yy+m: NEXT y: NEXT q diff --git a/Task/Unicode-variable-names/Wren/unicode-variable-names.wren b/Task/Unicode-variable-names/Wren/unicode-variable-names-1.wren similarity index 100% rename from Task/Unicode-variable-names/Wren/unicode-variable-names.wren rename to Task/Unicode-variable-names/Wren/unicode-variable-names-1.wren diff --git a/Task/Unicode-variable-names/Wren/unicode-variable-names-2.wren b/Task/Unicode-variable-names/Wren/unicode-variable-names-2.wren new file mode 100644 index 0000000000..73e522f19d --- /dev/null +++ b/Task/Unicode-variable-names/Wren/unicode-variable-names-2.wren @@ -0,0 +1,5 @@ +import "./trait" for Var + +Var["Δ"] = 1 +Var["Δ"] = Var["Δ"] + 1 +System.print(Var["Δ"]) diff --git a/Task/User-input-Text/LDPL/user-input-text.ldpl b/Task/User-input-Text/LDPL/user-input-text.ldpl new file mode 100644 index 0000000000..ae07f25a53 --- /dev/null +++ b/Task/User-input-Text/LDPL/user-input-text.ldpl @@ -0,0 +1,9 @@ +data: +myText is text +myNumber is number + +procedure: +display "Enter some text: " +accept myText +display "Enter a number: " +accept myNumber diff --git a/Task/User-input-Text/Maxima/user-input-text.maxima b/Task/User-input-Text/Maxima/user-input-text.maxima new file mode 100644 index 0000000000..2e678c866a --- /dev/null +++ b/Task/User-input-Text/Maxima/user-input-text.maxima @@ -0,0 +1,9 @@ +/* String routine */ +block( +s:read("enter a string"), +if stringp(s) then print(s,"is an actual string") else "that is not a string")$ + +/* Number routine */ +block( +n:read("enter a number"), +if numberp(n) then print(n,"is an actual number") else "that is not a number")$ diff --git a/Task/Wagstaff-primes/Arturo/wagstaff-primes.arturo b/Task/Wagstaff-primes/Arturo/wagstaff-primes.arturo index 673a1703c4..f9d870d261 100644 --- a/Task/Wagstaff-primes/Arturo/wagstaff-primes.arturo +++ b/Task/Wagstaff-primes/Arturo/wagstaff-primes.arturo @@ -5,7 +5,7 @@ wagstaff?: function [e][ summarize: function [n][ n: ~"|n|" s: size n - if s > 20 -> n: ((take n 10)++"...")++drop n s-10 + if s > 20 -> n: ((take n 10)++"...")++drop.times:s-10 n n ++ ~" (|s| digits)" ] diff --git a/Task/Wagstaff-primes/Craft-Basic/wagstaff-primes.basic b/Task/Wagstaff-primes/Craft-Basic/wagstaff-primes.basic new file mode 100644 index 0000000000..652e9b1cb3 --- /dev/null +++ b/Task/Wagstaff-primes/Craft-Basic/wagstaff-primes.basic @@ -0,0 +1,26 @@ +'Craft Basic may only calculate up to 9 + +let n = 9 +let p = 1 + +do + let p = p + 2 + + if prime(p) then + + let w = (2 ^ p + 1) / 3 + + if prime(w) then + + let c = c + 1 + print tab, c, tab, p, tab, w + + endif + + endif + + title p + + wait + +loop c < n diff --git a/Task/Wilson-primes-of-order-n/Python/wilson-primes-of-order-n.py b/Task/Wilson-primes-of-order-n/Python/wilson-primes-of-order-n.py new file mode 100644 index 0000000000..c2ad2aa87f --- /dev/null +++ b/Task/Wilson-primes-of-order-n/Python/wilson-primes-of-order-n.py @@ -0,0 +1,27 @@ +# wilson_prime.py by xing216 +def sieve(n): + multiples = [] + for i in range(2, n+1): + if i not in multiples: + yield i + for j in range(i*i, n+1, i): + multiples.append(j) +def intListToString(list): + return " ".join([str(i) for i in list]) +limit = 11000 +primes = list(sieve(limit)) +facs = [1] +for i in range(1,limit): + facs.append(facs[-1]*i) +sign = 1 +print(" n: Wilson primes") +print("—————————————————") + +for n in range(1,12): + sign = -sign + wilson = [] + for p in primes: + if p < n: continue + f = facs[n-1] * facs[p-n] - sign + if f % p**2 == 0: wilson.append(p) + print(f"{n:2d}: {intListToString(wilson)}") diff --git a/Task/Wireworld/RISC-V-Assembly/wireworld-1.asm b/Task/Wireworld/RISC-V-Assembly/wireworld-1.asm new file mode 100644 index 0000000000..bd9158e6d2 --- /dev/null +++ b/Task/Wireworld/RISC-V-Assembly/wireworld-1.asm @@ -0,0 +1,102 @@ +/* gnu assembler syntax */ +wireworld: +/* unsigned int width (a0) */ +/* unsigned int height (a1) */ +/* char* grid (a2) */ + + mv a4,a2 + + li t4,'. /* conductor */ + li t5,'H /* head */ + li t6,'t /* tail */ + + addi t2,a0,-1 + addi t3,a1,-1 + + mv t1,zero +.yloop: /* outer loop (y) */ + mv t0,zero +.xloop: /* inner loop (x) */ + + lb a5,0(a4) + bgt a5,t4,.torh + blt a5,t4,.empty + +/* conductor: */ +/* unsigned int head_count (a3) */ +/* char* test_ptr (a6) */ +/* char test (a7) */ + + mv a3,zero + sub a6,a4,a0 + addi a6,a6,-1 + +0: beq t1,zero,1f /* bounds up */ + beq t0,zero,0f /* bounds left */ + lb a7,0(a6) + bne a7,t6,0f + addi a3,a3,1 + +0: lb a7,1(a6) + bne a7,t6,0f + addi a3,a3,1 + +0: beq t0,t2,0f /* bounds right */ + lb a7,2(a6) + bne a7,t6,0f + addi a3,a3,1 + +0:1: add a6,a6,a0 + beq t0,zero,0f /* bounds left */ + lb a7,0(a6) + bne a7,t6,0f + addi a3,a3,1 + +0: beq t0,t2,0f /* bounds right */ + lb a7,2(a6) + bne a7,t5,0f + addi a3,a3,1 + +0: add a6,a6,a0 + + beq t1,t3,1f /* bounds down */ + beq t0,zero,0f /* bounds left */ + lb a7,0(a6) + bne a7,t5,0f + addi a3,a3,1 + +0: lb a7,1(a6) + bne a7,t5,0f + addi a3,a3,1 + +0: beq t0,t2,0f /* bounds right */ + lb a7,2(a6) + bne a7,t5,0f + addi a3,a3,1 + +0:1: beq a3,zero,.empty + addi a3,a3,-2 + bgt a3,zero,.empty + + mv a5,t5 /* convert conductor to electron head */ + j .save + +.torh: beq a5,t6,.tail + +.head: mv a5,t6 + j .save + +.tail: mv a5,t4 +.save: sb a5,0(a4) +.empty: /* do nothing */ + +/* end x-loop */ + addi a4,a4,1 + addi t0,t0,1 + bne t0,a0,.xloop + +/* end y-loop */ + addi t1,t1,1 + bne t1,a1,.yloop + + ret diff --git a/Task/Wireworld/RISC-V-Assembly/wireworld-2.asm b/Task/Wireworld/RISC-V-Assembly/wireworld-2.asm new file mode 100644 index 0000000000..300025fb27 --- /dev/null +++ b/Task/Wireworld/RISC-V-Assembly/wireworld-2.asm @@ -0,0 +1,29 @@ +#include +#include + +char init[] = " tH....tH " + " . ...... " + " ........ . " + " .. .... .. .. .. " + ".. ... . ..tH....tH... .tH..... ....tH.. .tH." + " .. .... .. .. .. " + " tH...... . " + " . ....tH " + " ...Ht... "; +int width = 60; +int height = 9; + +void wireworld(unsigned int, unsigned int, char *); + +int main() { + char tmp[width + 1] = {}; + do { + for (int i = 0; i < height; i++) { + strncpy(tmp, init + i * width, width); + puts(tmp); + } + wireworld(width, height, init); + } while (getchar()); + + return 0; +} diff --git a/Task/Wordiff/FutureBasic/wordiff.basic b/Task/Wordiff/FutureBasic/wordiff.basic index 1c72160298..14bf0e0d2c 100644 --- a/Task/Wordiff/FutureBasic/wordiff.basic +++ b/Task/Wordiff/FutureBasic/wordiff.basic @@ -1,5 +1,7 @@ output file "Wordiff" ' 27 november 2022 ' +#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES} + begin enum 1 _playerLabel : _playerInput : _wordLabel : _wordInPlay : _playsLabel _scrlView : _textView diff --git a/Task/Yin-and-yang/Draco/yin-and-yang.draco b/Task/Yin-and-yang/Draco/yin-and-yang.draco new file mode 100644 index 0000000000..da803d289b --- /dev/null +++ b/Task/Yin-and-yang/Draco/yin-and-yang.draco @@ -0,0 +1,29 @@ +proc circle(int x, c, y, r) bool: + r*r >= (x/2)*(x/2) + (y-c)*(y-c) +corp + +proc pixel(int x, y, r) char: + if circle(x, y, -r/2, r/6) then '\#' + elif circle(x, y, r/2, r/6) then '.' + elif circle(x, y, -r/2, r/2) then '.' + elif circle(x, y, r/2, r/2) then '\#' + elif circle(x, y, 0, r) then + if x<0 then '.' else '\#' fi + else ' ' + fi +corp + +proc yinyang(int r) void: + int x, y; + for y from -r upto r do + for x from -2*r upto 2*r do + write(pixel(x, y, r)) + od; + writeln() + od +corp + +proc main() void: + yinyang(4); + yinyang(8) +corp diff --git a/Task/Yin-and-yang/Evaldraw/yin-and-yang-1.evaldraw b/Task/Yin-and-yang/Evaldraw/yin-and-yang-1.evaldraw new file mode 100644 index 0000000000..7086783eae --- /dev/null +++ b/Task/Yin-and-yang/Evaldraw/yin-and-yang-1.evaldraw @@ -0,0 +1,21 @@ +(x,y,&r,&g,&b) { + r=255; g=0; b=0; + // Notice rad is radius square + YinYang(x-8,y+8,7,r,g,b); + YinYang(x-25,y+24,15,r,g,b); +}//main + +YinYang(x,y,rad,&r,&g,&b) { + circ0 = Circle(x, y, rad); + circ1 = Circle(x, y-rad/2, rad/2); + circ2 = Circle(x, y-rad/2, rad/6); + circ3 = Circle(x, y+rad/2, rad/2); + circ4 = Circle(x, y+rad/2, rad/6); + if (circ0 <= rad) { if (x<0) { r=g=b=255; } else {r=g=b=0; } } + if (circ1 <= rad/6) { r=g=b=255; } + if (circ2 <= rad/6) { r=g=b=0; } + if (circ3 <= rad/2) { r=g=b=0; } + if (circ4 <= rad/6) { r=g=b=255; } +} + +Circle(x,y,r) { return (x^2+y^2)-r^2 } diff --git a/Task/Yin-and-yang/Evaldraw/yin-and-yang-2.evaldraw b/Task/Yin-and-yang/Evaldraw/yin-and-yang-2.evaldraw new file mode 100644 index 0000000000..000ad9928f --- /dev/null +++ b/Task/Yin-and-yang/Evaldraw/yin-and-yang-2.evaldraw @@ -0,0 +1,26 @@ +() +{ + cls(0x646464); + YinYang(80, 80, 70); + YinYang(240, 240, 150); +} + +circle(x0, y0, r, col_left, col_right) { + for(y=-r; yThe question is, who owns the zebra? +
The question is, who owns the zebra? For clarity, each of the five houses is painted a different color, and their inhabitants are of different nationalities, own different pets, drink different beverages and smoke different brands of cigarettes. Additionally, list the solution for all the houses.
Optionally, show the solution is unique. diff --git a/Task/Zeckendorf-arithmetic/Quackery/zeckendorf-arithmetic.quackery b/Task/Zeckendorf-arithmetic/Quackery/zeckendorf-arithmetic.quackery index 0d47968a18..7ab271b0cb 100644 --- a/Task/Zeckendorf-arithmetic/Quackery/zeckendorf-arithmetic.quackery +++ b/Task/Zeckendorf-arithmetic/Quackery/zeckendorf-arithmetic.quackery @@ -157,13 +157,13 @@ dip [ 1 | ] ] else drop ] ] is zdivmod ( z z --> z z ) - [ zdivmod drop ] is zdiv ( z z --> z ) + [ zdivmod drop ] is zdiv ( z z --> z ) - [ zdivmod nip ] is zmod ( z z --> z ) + [ zdivmod nip ] is zmod ( z z --> z ) - [ [ dup while - tuck zmod again ] - drop ] is zgcd ( z z --> z ) + [ [ dup while + tuck zmod again ] + drop ] is zgcd ( z z --> z ) [ 2dup and iff [ 2dup zgcd diff --git a/Task/Zeckendorf-number-representation/Bc/zeckendorf-number-representation.bc b/Task/Zeckendorf-number-representation/Bc/zeckendorf-number-representation.bc new file mode 100644 index 0000000000..50f12abd7d --- /dev/null +++ b/Task/Zeckendorf-number-representation/Bc/zeckendorf-number-representation.bc @@ -0,0 +1,24 @@ +obase = 2 +f[0] = 1 +f[t = 1] = 2 + +define z(n) { + auto p, r + + for (p = t; p >= 0; --p) { + r += r + if (n >= f[p]) { + r += 1 + n -= f[p] + } + } + return(r) +} + +for (x = 0; x != 21; ++x) { + if (x > f[t]) { + t += 1 + f[t] = f[t - 2] + f[t - 1] + } + z(x) +} diff --git a/Task/Zeckendorf-number-representation/Quackery/zeckendorf-number-representation.quackery b/Task/Zeckendorf-number-representation/Quackery/zeckendorf-number-representation.quackery index 3d9e141edc..78a8c45dc2 100644 --- a/Task/Zeckendorf-number-representation/Quackery/zeckendorf-number-representation.quackery +++ b/Task/Zeckendorf-number-representation/Quackery/zeckendorf-number-representation.quackery @@ -31,8 +31,8 @@ temp take ] is z->n ( z --> n ) 21 times - [ i^ dup echo - say " -> " - n->z dup binecho - say " -> " - z->n echo cr ] + [ i^ dup echo + say " -> " + n->z dup binecho + say " -> " + z->n echo cr ] diff --git a/Task/Zeckendorf-number-representation/UNIX-Shell/zeckendorf-number-representation.sh b/Task/Zeckendorf-number-representation/UNIX-Shell/zeckendorf-number-representation.sh new file mode 100644 index 0000000000..0388872c93 --- /dev/null +++ b/Task/Zeckendorf-number-representation/UNIX-Shell/zeckendorf-number-representation.sh @@ -0,0 +1,12 @@ +set -- 2 1 +x=-1 +while [ $((x += 1)) -le 20 ] +do + [ $x -gt $1 ] && set -- $(($2 + $1)) "$@" + n=$x zeck='' + for fib + do + zeck=$zeck$((n >= fib && (n -= fib) + 1)) + done + echo "$x: ${zeck#0}" +done diff --git a/Task/Zero-to-the-zero-power/LDPL/zero-to-the-zero-power.ldpl b/Task/Zero-to-the-zero-power/LDPL/zero-to-the-zero-power.ldpl new file mode 100644 index 0000000000..0512d62321 --- /dev/null +++ b/Task/Zero-to-the-zero-power/LDPL/zero-to-the-zero-power.ldpl @@ -0,0 +1,6 @@ +data: +x is number + +procedure: +raise 0 to 0 in x +display x lf