diff --git a/Conf/lang.yaml b/Conf/lang.yaml index f6193f18c1..3e0d8b7106 100644 --- a/Conf/lang.yaml +++ b/Conf/lang.yaml @@ -17,6 +17,7 @@ A+: .a+ AArch64 Assembly: .aarch64 ABAP: .abap ACL2: .acl2 +Acornsoft Lisp: .lisp Action!: .action ActionScript: .as Acurity Architect: .acurity diff --git a/Lang/ALGOL-68/Arithmetic-derivative b/Lang/ALGOL-68/Arithmetic-derivative new file mode 120000 index 0000000000..73196718b1 --- /dev/null +++ b/Lang/ALGOL-68/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Bulls-and-cows-Player b/Lang/ALGOL-68/Bulls-and-cows-Player new file mode 120000 index 0000000000..6ce927089c --- /dev/null +++ b/Lang/ALGOL-68/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Faulhabers-triangle b/Lang/ALGOL-68/Faulhabers-triangle new file mode 120000 index 0000000000..902d8dc449 --- /dev/null +++ b/Lang/ALGOL-68/Faulhabers-triangle @@ -0,0 +1 @@ +../../Task/Faulhabers-triangle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Kronecker-product-based-fractals b/Lang/ALGOL-68/Kronecker-product-based-fractals new file mode 120000 index 0000000000..7531f0ec6e --- /dev/null +++ b/Lang/ALGOL-68/Kronecker-product-based-fractals @@ -0,0 +1 @@ +../../Task/Kronecker-product-based-fractals/ALGOL-68 \ No newline at end of file diff --git a/Lang/APL/Arithmetic-numbers b/Lang/APL/Arithmetic-numbers new file mode 120000 index 0000000000..6e1869f653 --- /dev/null +++ b/Lang/APL/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/Arithmetic-numbers b/Lang/ARM-Assembly/Arithmetic-numbers new file mode 120000 index 0000000000..b3332e6dc9 --- /dev/null +++ b/Lang/ARM-Assembly/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Miller-Rabin-primality-test b/Lang/ARM-Assembly/Miller-Rabin-primality-test new file mode 120000 index 0000000000..195623d60d --- /dev/null +++ b/Lang/ARM-Assembly/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Primality-by-trial-division b/Lang/ARM-Assembly/Primality-by-trial-division new file mode 120000 index 0000000000..1ed40416b3 --- /dev/null +++ b/Lang/ARM-Assembly/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Sequence-of-primes-by-trial-division b/Lang/ARM-Assembly/Sequence-of-primes-by-trial-division new file mode 120000 index 0000000000..c698f6de3b --- /dev/null +++ b/Lang/ARM-Assembly/Sequence-of-primes-by-trial-division @@ -0,0 +1 @@ +../../Task/Sequence-of-primes-by-trial-division/ARM-Assembly \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/00-LANG.txt b/Lang/Acornsoft-Lisp/00-LANG.txt new file mode 100644 index 0000000000..320ec9f6cf --- /dev/null +++ b/Lang/Acornsoft-Lisp/00-LANG.txt @@ -0,0 +1,17 @@ +{{language|Acornsoft Lisp +|exec=interpreted +|parampass=value +|safety=safe +|checking=dynamic +|gc=yes}} +{{language programming paradigm|functional}} +{{language programming paradigm|procedural}} +{{implementation|Lisp}} + +'''Acornsoft Lisp''' is a dialect and implementation of [[derived from::Lisp]] developed in the early 1980s for the [[wp:BBC_Micro|BBC Micro]] and related machines. + +In the original, 1980s version, all built-in defined names were in upper case; however, versions that use lower case instead have become available. + +==References== +* Arthur Norman and Gillian Cattell, ''LISP on the BBC Microcomputer'' +* [[wp:Acornsoft_LISP|Wikipedia:Acornsoft Lisp]] \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/00-META.yaml b/Lang/Acornsoft-Lisp/00-META.yaml new file mode 100644 index 0000000000..4112cf5a63 --- /dev/null +++ b/Lang/Acornsoft-Lisp/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Acornsoft_Lisp diff --git a/Lang/Acornsoft-Lisp/Ackermann-function b/Lang/Acornsoft-Lisp/Ackermann-function new file mode 120000 index 0000000000..7bcda763dc --- /dev/null +++ b/Lang/Acornsoft-Lisp/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Church-numerals b/Lang/Acornsoft-Lisp/Church-numerals new file mode 120000 index 0000000000..0a130ebdda --- /dev/null +++ b/Lang/Acornsoft-Lisp/Church-numerals @@ -0,0 +1 @@ +../../Task/Church-numerals/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Closures-Value-capture b/Lang/Acornsoft-Lisp/Closures-Value-capture new file mode 120000 index 0000000000..f04f5686b2 --- /dev/null +++ b/Lang/Acornsoft-Lisp/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Combinations b/Lang/Acornsoft-Lisp/Combinations new file mode 120000 index 0000000000..e9cb9f1dde --- /dev/null +++ b/Lang/Acornsoft-Lisp/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Comma-quibbling b/Lang/Acornsoft-Lisp/Comma-quibbling new file mode 120000 index 0000000000..ffef14cd4d --- /dev/null +++ b/Lang/Acornsoft-Lisp/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Factorial b/Lang/Acornsoft-Lisp/Factorial new file mode 120000 index 0000000000..550aae0490 --- /dev/null +++ b/Lang/Acornsoft-Lisp/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Hello-world-Text b/Lang/Acornsoft-Lisp/Hello-world-Text new file mode 120000 index 0000000000..17be1edfa0 --- /dev/null +++ b/Lang/Acornsoft-Lisp/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Ordered-words b/Lang/Acornsoft-Lisp/Ordered-words new file mode 120000 index 0000000000..3bf5154d1c --- /dev/null +++ b/Lang/Acornsoft-Lisp/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Palindrome-detection b/Lang/Acornsoft-Lisp/Palindrome-detection new file mode 120000 index 0000000000..68d57e371f --- /dev/null +++ b/Lang/Acornsoft-Lisp/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Permutations-Derangements b/Lang/Acornsoft-Lisp/Permutations-Derangements new file mode 120000 index 0000000000..04cdd94720 --- /dev/null +++ b/Lang/Acornsoft-Lisp/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Quine b/Lang/Acornsoft-Lisp/Quine new file mode 120000 index 0000000000..effed68d44 --- /dev/null +++ b/Lang/Acornsoft-Lisp/Quine @@ -0,0 +1 @@ +../../Task/Quine/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/Acornsoft-Lisp/Set-puzzle b/Lang/Acornsoft-Lisp/Set-puzzle new file mode 120000 index 0000000000..8de80cf599 --- /dev/null +++ b/Lang/Acornsoft-Lisp/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Acornsoft-Lisp \ No newline at end of file diff --git a/Lang/C++/RIPEMD-160 b/Lang/C++/RIPEMD-160 new file mode 120000 index 0000000000..6d52fa405f --- /dev/null +++ b/Lang/C++/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/C++ \ No newline at end of file diff --git a/Lang/C++/Ramanujan-primes-twins b/Lang/C++/Ramanujan-primes-twins new file mode 120000 index 0000000000..3cd9279724 --- /dev/null +++ b/Lang/C++/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/C++ \ No newline at end of file diff --git a/Lang/C++/Search-in-paragraphs-text b/Lang/C++/Search-in-paragraphs-text new file mode 120000 index 0000000000..2ef4ef4a04 --- /dev/null +++ b/Lang/C++/Search-in-paragraphs-text @@ -0,0 +1 @@ +../../Task/Search-in-paragraphs-text/C++ \ No newline at end of file diff --git a/Lang/C++/Secure-temporary-file b/Lang/C++/Secure-temporary-file new file mode 120000 index 0000000000..24210e5146 --- /dev/null +++ b/Lang/C++/Secure-temporary-file @@ -0,0 +1 @@ +../../Task/Secure-temporary-file/C++ \ No newline at end of file diff --git a/Lang/Common-Lisp/Church-numerals b/Lang/Common-Lisp/Church-numerals new file mode 120000 index 0000000000..b8c32bb4d2 --- /dev/null +++ b/Lang/Common-Lisp/Church-numerals @@ -0,0 +1 @@ +../../Task/Church-numerals/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Currency b/Lang/Common-Lisp/Currency new file mode 120000 index 0000000000..ad64f56642 --- /dev/null +++ b/Lang/Common-Lisp/Currency @@ -0,0 +1 @@ +../../Task/Currency/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Permutations-Derangements b/Lang/Common-Lisp/Permutations-Derangements new file mode 120000 index 0000000000..a0538e7374 --- /dev/null +++ b/Lang/Common-Lisp/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Set-puzzle b/Lang/Common-Lisp/Set-puzzle new file mode 120000 index 0000000000..6f48d7bac7 --- /dev/null +++ b/Lang/Common-Lisp/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Common-Lisp \ No newline at end of file diff --git a/Lang/EasyLang/Amicable-pairs b/Lang/EasyLang/Amicable-pairs new file mode 120000 index 0000000000..445221e26c --- /dev/null +++ b/Lang/EasyLang/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Archimedean-spiral b/Lang/EasyLang/Archimedean-spiral new file mode 120000 index 0000000000..61f1f9fb04 --- /dev/null +++ b/Lang/EasyLang/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Arithmetic-evaluation b/Lang/EasyLang/Arithmetic-evaluation new file mode 120000 index 0000000000..cbf63cb359 --- /dev/null +++ b/Lang/EasyLang/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Catalan-numbers-Pascals-triangle b/Lang/EasyLang/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..08636a2ee3 --- /dev/null +++ b/Lang/EasyLang/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Circular-primes b/Lang/EasyLang/Circular-primes new file mode 120000 index 0000000000..8f738fed37 --- /dev/null +++ b/Lang/EasyLang/Circular-primes @@ -0,0 +1 @@ +../../Task/Circular-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Continued-fraction b/Lang/EasyLang/Continued-fraction new file mode 120000 index 0000000000..9f39488e59 --- /dev/null +++ b/Lang/EasyLang/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Cullen-and-Woodall-numbers b/Lang/EasyLang/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..d8702031ba --- /dev/null +++ b/Lang/EasyLang/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Farey-sequence b/Lang/EasyLang/Farey-sequence new file mode 120000 index 0000000000..ce155397f5 --- /dev/null +++ b/Lang/EasyLang/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Leonardo-numbers b/Lang/EasyLang/Leonardo-numbers new file mode 120000 index 0000000000..14bd56d652 --- /dev/null +++ b/Lang/EasyLang/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Numbers-with-equal-rises-and-falls b/Lang/EasyLang/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..56cab1b4aa --- /dev/null +++ b/Lang/EasyLang/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Palindrome-detection b/Lang/EasyLang/Palindrome-detection new file mode 120000 index 0000000000..0bc00641f5 --- /dev/null +++ b/Lang/EasyLang/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Polyspiral b/Lang/EasyLang/Polyspiral new file mode 120000 index 0000000000..56ca0cfce7 --- /dev/null +++ b/Lang/EasyLang/Polyspiral @@ -0,0 +1 @@ +../../Task/Polyspiral/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Recamans-sequence b/Lang/EasyLang/Recamans-sequence new file mode 120000 index 0000000000..9a09fd7e52 --- /dev/null +++ b/Lang/EasyLang/Recamans-sequence @@ -0,0 +1 @@ +../../Task/Recamans-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sequence-of-non-squares b/Lang/EasyLang/Sequence-of-non-squares new file mode 120000 index 0000000000..5a90eeec96 --- /dev/null +++ b/Lang/EasyLang/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Seven-sided-dice-from-five-sided-dice b/Lang/EasyLang/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..683da7030b --- /dev/null +++ b/Lang/EasyLang/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Shoelace-formula-for-polygonal-area b/Lang/EasyLang/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..3018474b33 --- /dev/null +++ b/Lang/EasyLang/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sum-digits-of-an-integer b/Lang/EasyLang/Sum-digits-of-an-integer new file mode 120000 index 0000000000..5cfc0b706a --- /dev/null +++ b/Lang/EasyLang/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sum-of-a-series b/Lang/EasyLang/Sum-of-a-series new file mode 120000 index 0000000000..47dcaccd14 --- /dev/null +++ b/Lang/EasyLang/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Totient-function b/Lang/EasyLang/Totient-function new file mode 120000 index 0000000000..8d52b6ae58 --- /dev/null +++ b/Lang/EasyLang/Totient-function @@ -0,0 +1 @@ +../../Task/Totient-function/EasyLang \ No newline at end of file diff --git a/Lang/F-Sharp/Secure-temporary-file b/Lang/F-Sharp/Secure-temporary-file new file mode 120000 index 0000000000..525cda7b5d --- /dev/null +++ b/Lang/F-Sharp/Secure-temporary-file @@ -0,0 +1 @@ +../../Task/Secure-temporary-file/F-Sharp \ No newline at end of file diff --git a/Lang/FutureBasic/24-game-Solve b/Lang/FutureBasic/24-game-Solve new file mode 120000 index 0000000000..a76d278fbc --- /dev/null +++ b/Lang/FutureBasic/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Anagrams-Deranged-anagrams b/Lang/FutureBasic/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..c509f2e9cb --- /dev/null +++ b/Lang/FutureBasic/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Attractive-numbers b/Lang/FutureBasic/Attractive-numbers new file mode 120000 index 0000000000..b110acda70 --- /dev/null +++ b/Lang/FutureBasic/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Median b/Lang/FutureBasic/Averages-Median new file mode 120000 index 0000000000..28a4ed2d20 --- /dev/null +++ b/Lang/FutureBasic/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Mode b/Lang/FutureBasic/Averages-Mode new file mode 120000 index 0000000000..446fa1a7b4 --- /dev/null +++ b/Lang/FutureBasic/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Eulers-constant-0.5772... b/Lang/FutureBasic/Eulers-constant-0.5772... new file mode 120000 index 0000000000..d1a8382d57 --- /dev/null +++ b/Lang/FutureBasic/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Filter b/Lang/FutureBasic/Filter new file mode 120000 index 0000000000..88c05eeeea --- /dev/null +++ b/Lang/FutureBasic/Filter @@ -0,0 +1 @@ +../../Task/Filter/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Globally-replace-text-in-several-files b/Lang/FutureBasic/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..3325af6ad4 --- /dev/null +++ b/Lang/FutureBasic/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/HTTPS b/Lang/FutureBasic/HTTPS new file mode 120000 index 0000000000..a95da65a60 --- /dev/null +++ b/Lang/FutureBasic/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Hex-words b/Lang/FutureBasic/Hex-words new file mode 120000 index 0000000000..91770acea5 --- /dev/null +++ b/Lang/FutureBasic/Hex-words @@ -0,0 +1 @@ +../../Task/Hex-words/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Menu b/Lang/FutureBasic/Menu new file mode 120000 index 0000000000..ca806045d7 --- /dev/null +++ b/Lang/FutureBasic/Menu @@ -0,0 +1 @@ +../../Task/Menu/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Odd-word-problem b/Lang/FutureBasic/Odd-word-problem new file mode 120000 index 0000000000..1566aea9a4 --- /dev/null +++ b/Lang/FutureBasic/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Program-termination b/Lang/FutureBasic/Program-termination new file mode 120000 index 0000000000..06060b592e --- /dev/null +++ b/Lang/FutureBasic/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Word-wheel b/Lang/FutureBasic/Word-wheel new file mode 120000 index 0000000000..033bef69bd --- /dev/null +++ b/Lang/FutureBasic/Word-wheel @@ -0,0 +1 @@ +../../Task/Word-wheel/FutureBasic \ No newline at end of file diff --git a/Lang/Java/Peripheral-drift-illusion b/Lang/Java/Peripheral-drift-illusion new file mode 120000 index 0000000000..cfa6ebe073 --- /dev/null +++ b/Lang/Java/Peripheral-drift-illusion @@ -0,0 +1 @@ +../../Task/Peripheral-drift-illusion/Java \ No newline at end of file diff --git a/Lang/Java/Quoting-constructs b/Lang/Java/Quoting-constructs new file mode 120000 index 0000000000..c3d5cbbdb2 --- /dev/null +++ b/Lang/Java/Quoting-constructs @@ -0,0 +1 @@ +../../Task/Quoting-constructs/Java \ No newline at end of file diff --git a/Lang/Java/Radical-of-an-integer b/Lang/Java/Radical-of-an-integer new file mode 120000 index 0000000000..096b38e858 --- /dev/null +++ b/Lang/Java/Radical-of-an-integer @@ -0,0 +1 @@ +../../Task/Radical-of-an-integer/Java \ No newline at end of file diff --git a/Lang/Java/Ramanujan-primes-twins b/Lang/Java/Ramanujan-primes-twins new file mode 120000 index 0000000000..e2441f82ea --- /dev/null +++ b/Lang/Java/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/Java \ No newline at end of file diff --git a/Lang/Java/Repunit-primes b/Lang/Java/Repunit-primes new file mode 120000 index 0000000000..e4bfc4b43a --- /dev/null +++ b/Lang/Java/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/Java \ No newline at end of file diff --git a/Lang/Java/Retrieve-and-search-chat-history b/Lang/Java/Retrieve-and-search-chat-history new file mode 120000 index 0000000000..03abb6efbc --- /dev/null +++ b/Lang/Java/Retrieve-and-search-chat-history @@ -0,0 +1 @@ +../../Task/Retrieve-and-search-chat-history/Java \ No newline at end of file diff --git a/Lang/Java/Search-in-paragraphs-text b/Lang/Java/Search-in-paragraphs-text new file mode 120000 index 0000000000..9f2944d059 --- /dev/null +++ b/Lang/Java/Search-in-paragraphs-text @@ -0,0 +1 @@ +../../Task/Search-in-paragraphs-text/Java \ No newline at end of file diff --git a/Lang/Koka/2048 b/Lang/Koka/2048 new file mode 120000 index 0000000000..e03966af5c --- /dev/null +++ b/Lang/Koka/2048 @@ -0,0 +1 @@ +../../Task/2048/Koka \ No newline at end of file diff --git a/Lang/Koka/Faces-from-a-mesh b/Lang/Koka/Faces-from-a-mesh new file mode 120000 index 0000000000..1ed1b6f6f2 --- /dev/null +++ b/Lang/Koka/Faces-from-a-mesh @@ -0,0 +1 @@ +../../Task/Faces-from-a-mesh/Koka \ No newline at end of file diff --git a/Lang/Koka/Gamma-function b/Lang/Koka/Gamma-function new file mode 120000 index 0000000000..1dc2a263a2 --- /dev/null +++ b/Lang/Koka/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Koka \ No newline at end of file diff --git a/Lang/Koka/Inverted-syntax b/Lang/Koka/Inverted-syntax new file mode 120000 index 0000000000..321dafb918 --- /dev/null +++ b/Lang/Koka/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Koka \ No newline at end of file diff --git a/Lang/Maxima/00-LANG.txt b/Lang/Maxima/00-LANG.txt index 71383750d5..d90dc35da7 100644 --- a/Lang/Maxima/00-LANG.txt +++ b/Lang/Maxima/00-LANG.txt @@ -1,5 +1,6 @@ -{{language|Maxima -|site=http://maxima.sourceforge.net/}} +{{language|Maxima|site=https://maxima.sourceforge.io/}} + Maxima is the language used in the computer algebra system of the same name. -[[Category:Mathematical programming languages]] \ No newline at end of file +[[Category:Mathematical programming languages]] +[[Category:Lisp related]] \ No newline at end of file diff --git a/Lang/Maxima/Additive-primes b/Lang/Maxima/Additive-primes new file mode 120000 index 0000000000..f1d1964a08 --- /dev/null +++ b/Lang/Maxima/Additive-primes @@ -0,0 +1 @@ +../../Task/Additive-primes/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Almost-prime b/Lang/Maxima/Almost-prime new file mode 120000 index 0000000000..4e8f7444f5 --- /dev/null +++ b/Lang/Maxima/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Archimedean-spiral b/Lang/Maxima/Archimedean-spiral new file mode 120000 index 0000000000..5b0cfe067f --- /dev/null +++ b/Lang/Maxima/Archimedean-spiral @@ -0,0 +1 @@ +../../Task/Archimedean-spiral/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Arithmetic-numbers b/Lang/Maxima/Arithmetic-numbers new file mode 120000 index 0000000000..3b55a6ea2b --- /dev/null +++ b/Lang/Maxima/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Blum-integer b/Lang/Maxima/Blum-integer new file mode 120000 index 0000000000..5dbc708d93 --- /dev/null +++ b/Lang/Maxima/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Cullen-and-Woodall-numbers b/Lang/Maxima/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..186684bd56 --- /dev/null +++ b/Lang/Maxima/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Curzon-numbers b/Lang/Maxima/Curzon-numbers new file mode 120000 index 0000000000..a2870f6ee8 --- /dev/null +++ b/Lang/Maxima/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Digital-root b/Lang/Maxima/Digital-root new file mode 120000 index 0000000000..7448f84d48 --- /dev/null +++ b/Lang/Maxima/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Disarium-numbers b/Lang/Maxima/Disarium-numbers new file mode 120000 index 0000000000..cf2db762f6 --- /dev/null +++ b/Lang/Maxima/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Draw-a-pixel b/Lang/Maxima/Draw-a-pixel new file mode 120000 index 0000000000..448820689d --- /dev/null +++ b/Lang/Maxima/Draw-a-pixel @@ -0,0 +1 @@ +../../Task/Draw-a-pixel/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Duffinian-numbers b/Lang/Maxima/Duffinian-numbers new file mode 120000 index 0000000000..a80ffd2cfb --- /dev/null +++ b/Lang/Maxima/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Farey-sequence b/Lang/Maxima/Farey-sequence new file mode 120000 index 0000000000..efb3aa398c --- /dev/null +++ b/Lang/Maxima/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Giuga-numbers b/Lang/Maxima/Giuga-numbers new file mode 120000 index 0000000000..bdad068f32 --- /dev/null +++ b/Lang/Maxima/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Julia-set b/Lang/Maxima/Julia-set new file mode 120000 index 0000000000..fb746fed1e --- /dev/null +++ b/Lang/Maxima/Julia-set @@ -0,0 +1 @@ +../../Task/Julia-set/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Koch-curve b/Lang/Maxima/Koch-curve new file mode 120000 index 0000000000..fcc3185034 --- /dev/null +++ b/Lang/Maxima/Koch-curve @@ -0,0 +1 @@ +../../Task/Koch-curve/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Mandelbrot-set b/Lang/Maxima/Mandelbrot-set new file mode 120000 index 0000000000..9adf858501 --- /dev/null +++ b/Lang/Maxima/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Perfect-totient-numbers b/Lang/Maxima/Perfect-totient-numbers new file mode 120000 index 0000000000..3bf621a66b --- /dev/null +++ b/Lang/Maxima/Perfect-totient-numbers @@ -0,0 +1 @@ +../../Task/Perfect-totient-numbers/Maxima \ No newline at end of file diff --git a/Lang/Maxima/Semiprime b/Lang/Maxima/Semiprime new file mode 120000 index 0000000000..a82ab9e37b --- /dev/null +++ b/Lang/Maxima/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Maxima \ No newline at end of file diff --git a/Lang/Mojo/00-LANG.txt b/Lang/Mojo/00-LANG.txt index a9a1e8e0cc..b8e8a54461 100644 --- a/Lang/Mojo/00-LANG.txt +++ b/Lang/Mojo/00-LANG.txt @@ -1 +1,12 @@ -{{stub}}{{language|Mojo}} \ No newline at end of file +{{stub}}{{language|Mojo}} + +== Mojo🔥 == + +:Mojo is a new programming language that bridges the gap between research and production by combining the best of Python syntax with systems programming and metaprogramming. + +:With Mojo, you can write portable code that’s faster than C and seamlessly inter-op with the Python ecosystem.[https://docs.modular.com/mojo/ Documentation] + +:Mojo is still very young, but [https://www.modular.com we] believe an active community and a strong feedback pipeline is key to its success.[https://docs.modular.com/mojo/community.html Community] + +=== References === + \ No newline at end of file diff --git a/Lang/Odin/Attractive-numbers b/Lang/Odin/Attractive-numbers new file mode 120000 index 0000000000..1d34f22709 --- /dev/null +++ b/Lang/Odin/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Odin \ No newline at end of file diff --git a/Lang/Odin/Leonardo-numbers b/Lang/Odin/Leonardo-numbers new file mode 120000 index 0000000000..e32b2575dc --- /dev/null +++ b/Lang/Odin/Leonardo-numbers @@ -0,0 +1 @@ +../../Task/Leonardo-numbers/Odin \ No newline at end of file diff --git a/Lang/QBasic/Chaocipher b/Lang/QBasic/Chaocipher new file mode 120000 index 0000000000..c14f3d4a0c --- /dev/null +++ b/Lang/QBasic/Chaocipher @@ -0,0 +1 @@ +../../Task/Chaocipher/QBasic \ No newline at end of file diff --git a/Lang/Quackery/Achilles-numbers b/Lang/Quackery/Achilles-numbers new file mode 120000 index 0000000000..419632fd00 --- /dev/null +++ b/Lang/Quackery/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Chinese-zodiac b/Lang/Quackery/Chinese-zodiac new file mode 120000 index 0000000000..f8f757024c --- /dev/null +++ b/Lang/Quackery/Chinese-zodiac @@ -0,0 +1 @@ +../../Task/Chinese-zodiac/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Factorial-primes b/Lang/Quackery/Factorial-primes new file mode 120000 index 0000000000..f2eae0eb91 --- /dev/null +++ b/Lang/Quackery/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Numbers-with-equal-rises-and-falls b/Lang/Quackery/Numbers-with-equal-rises-and-falls new file mode 120000 index 0000000000..e59869d460 --- /dev/null +++ b/Lang/Quackery/Numbers-with-equal-rises-and-falls @@ -0,0 +1 @@ +../../Task/Numbers-with-equal-rises-and-falls/Quackery \ No newline at end of file diff --git a/Lang/Quackery/Sorting-algorithms-Strand-sort b/Lang/Quackery/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..bef087fb6b --- /dev/null +++ b/Lang/Quackery/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Quackery \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Rosetta-Code-Rank-languages-by-popularity b/Lang/Visual-Basic-.NET/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..b6d7a40b99 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Whitespace/00-LANG.txt b/Lang/Whitespace/00-LANG.txt index 6d27343d2b..ade0ae2b4c 100644 --- a/Lang/Whitespace/00-LANG.txt +++ b/Lang/Whitespace/00-LANG.txt @@ -5,6 +5,8 @@ |hopl=no |LCT=no }} +{{alertbox|pink|WARNING: Whitespace code do not play well with this SyntaxHighlight, you have to click Edit on a Whitespace solution to access the code.}} + Whitespace is a language in which non whitespace characters are ignored; only spaces, tabs and newlines are considered syntax. [[Category:Esoteric_Languages]] \ No newline at end of file diff --git a/Lang/Zig/Polyspiral b/Lang/Zig/Polyspiral new file mode 120000 index 0000000000..b305844929 --- /dev/null +++ b/Lang/Zig/Polyspiral @@ -0,0 +1 @@ +../../Task/Polyspiral/Zig \ No newline at end of file diff --git a/Task/100-doors/EasyLang/100-doors.easy b/Task/100-doors/EasyLang/100-doors.easy index 984f7126a5..c34fdbedc2 100644 --- a/Task/100-doors/EasyLang/100-doors.easy +++ b/Task/100-doors/EasyLang/100-doors.easy @@ -1,13 +1,13 @@ len d[] 100 for p = 1 to 100 - i = p - while i <= 100 - d[i] = 1 - d[i] - i += p - . + i = p + while i <= 100 + d[i] = 1 - d[i] + i += p + . . for i = 1 to 100 - if d[i] = 1 - print i - . + if d[i] = 1 + print i + . . diff --git a/Task/100-doors/Zig/100-doors-3.zig b/Task/100-doors/Zig/100-doors-3.zig index 0ad88166d5..d0321bd20f 100644 --- a/Task/100-doors/Zig/100-doors-3.zig +++ b/Task/100-doors/Zig/100-doors-3.zig @@ -1,6 +1,6 @@ -const stdout = @import("std").io.getStdOut().writer(); - pub fn main() !void { + const stdout = @import("std").io.getStdOut().writer(); + var square: u8 = 1; var increment: u8 = 3; for (1..101) |door| { diff --git a/Task/100-doors/Zig/100-doors-4.zig b/Task/100-doors/Zig/100-doors-4.zig index c4cedc6e14..53b792a533 100644 --- a/Task/100-doors/Zig/100-doors-4.zig +++ b/Task/100-doors/Zig/100-doors-4.zig @@ -1,6 +1,6 @@ -const stdout = @import("std").io.getStdOut().writer(); - pub fn main() !void { + const stdout = @import("std").io.getStdOut().writer(); + var door: u8 = 1; while (door * door <= 100) : (door += 1) { try stdout.print("Door {d} is open\n", .{door * door}); diff --git a/Task/100-prisoners/EasyLang/100-prisoners.easy b/Task/100-prisoners/EasyLang/100-prisoners.easy index cd2b46cfa2..3435445f04 100644 --- a/Task/100-prisoners/EasyLang/100-prisoners.easy +++ b/Task/100-prisoners/EasyLang/100-prisoners.easy @@ -1,60 +1,60 @@ for i = 1 to 100 - drawer[] &= i - sampler[] &= i + drawer[] &= i + sampler[] &= i . subr shuffle_drawer - for i = len drawer[] downto 2 - r = random i - swap drawer[r] drawer[i] - . + for i = len drawer[] downto 2 + r = random i + swap drawer[r] drawer[i] + . . subr play_random - call shuffle_drawer - for prisoner = 1 to 100 - found = 0 - for i = 1 to 50 - r = random (100 - i) - card = drawer[sampler[r]] - swap sampler[r] sampler[100 - i - 1] - if card = prisoner - found = 1 - break 1 + shuffle_drawer + for prisoner = 1 to 100 + found = 0 + for i = 1 to 50 + r = random (100 - i) + card = drawer[sampler[r]] + swap sampler[r] sampler[100 - i - 1] + if card = prisoner + found = 1 + break 1 + . . - . - if found = 0 - break 1 - . - . + if found = 0 + break 1 + . + . . subr play_optimal - call shuffle_drawer - for prisoner = 1 to 100 - reveal = prisoner - found = 0 - for i = 1 to 50 - card = drawer[reveal] - if card = prisoner - found = 1 - break 1 + shuffle_drawer + for prisoner = 1 to 100 + reveal = prisoner + found = 0 + for i = 1 to 50 + card = drawer[reveal] + if card = prisoner + found = 1 + break 1 + . + reveal = card . - reveal = card - . - if found = 0 - break 1 - . - . + if found = 0 + break 1 + . + . . n = 10000 win = 0 for _ = 1 to n - call play_random - win += found + play_random + win += found . print "random: " & 100.0 * win / n & "%" # win = 0 for _ = 1 to n - call play_optimal - win += found + play_optimal + win += found . print "optimal: " & 100.0 * win / n & "%" diff --git a/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy b/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy index 49a8c1e630..56d3e27935 100644 --- a/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy +++ b/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy @@ -3,81 +3,101 @@ background 432 textsize 13 len f[] 16 proc draw . . - clear - for i = 1 to 16 - h = f[i] - if h < 16 - x = (i - 1) mod 4 * 24 + 3 - y = (i - 1) div 4 * 24 + 3 - color 210 - move x y - rect 22 22 - move x + 4 y + 6 - if h < 10 - move x + 6 y + 6 + clear + for i = 1 to 16 + h = f[i] + if h < 16 + x = (i - 1) mod 4 * 24 + 3 + y = (i - 1) div 4 * 24 + 3 + color 210 + move x y + rect 22 22 + move x + 4 y + 6 + if h < 10 + move x + 6 y + 6 + . + color 885 + text h . - color 885 - text h - . - . + . . global done . +proc smiley . . + s = 3.5 + x = 86 + y = 86 + move x y + color 983 + circle 2.8 * s + color 000 + move x - s y - s + circle s / 3 + move x + 3.5 y - 3.5 + circle s / 3 + linewidth s / 3 + curve [ x - s y + s x y + 2 * s x + s y + s ] +. proc init . . - done = 0 - for i = 1 to 16 - f[i] = i - . - # shuffle - for i = 15 downto 2 - r = random i - swap f[r] f[i] - . - # make it solvable - inv = 0 - for i = 1 to 15 - for j = 1 to i - 1 - if f[j] > f[i] - inv += 1 + done = 0 + for i = 1 to 16 + f[i] = i + . + # shuffle + for i = 15 downto 2 + r = random i + swap f[r] f[i] + . + # make it solvable + inv = 0 + for i = 1 to 15 + for j = 1 to i - 1 + if f[j] > f[i] + inv += 1 + . . - . - . - if inv mod 2 <> 0 - swap f[1] f[2] - . - textsize 12 - call draw + . + if inv mod 2 <> 0 + swap f[1] f[2] + . + textsize 12 + draw . proc move_tile . . - c = mouse_x div 25 - r = mouse_y div 25 - i = r * 4 + c + 1 - if c > 0 and f[i - 1] = 16 - swap f[i] f[i - 1] - elif r > 0 and f[i - 4] = 16 - swap f[i] f[i - 4] - elif r < 3 and f[i + 4] = 16 - swap f[i] f[i + 4] - elif c < 3 and f[i + 1] = 16 - swap f[i] f[i + 1] - . - call draw - done = 1 - for i = 1 to 15 - if f[i] > f[i + 1] - done = 0 - . - . - if done = 1 - clear - move 10 30 - text "Well done!" - . + c = mouse_x div 25 + r = mouse_y div 25 + i = r * 4 + c + 1 + if c > 0 and f[i - 1] = 16 + swap f[i] f[i - 1] + elif r > 0 and f[i - 4] = 16 + swap f[i] f[i - 4] + elif r < 3 and f[i + 4] = 16 + swap f[i] f[i + 4] + elif c < 3 and f[i + 1] = 16 + swap f[i] f[i + 1] + . + draw + for i = 1 to 15 + if f[i] > f[i + 1] + return + . + . + done = 1 + timer 0.5 . on mouse_down - if done = 1 - call init - else - call move_tile - . + if done = 0 + move_tile + elif done = 3 + init + . . -call init +on timer + if done = 1 + smiley + done = 2 + timer 2 + else + done = 3 + . +. +init diff --git a/Task/2048/Koka/2048.koka b/Task/2048/Koka/2048.koka new file mode 100644 index 0000000000..0c0621f70e --- /dev/null +++ b/Task/2048/Koka/2048.koka @@ -0,0 +1,126 @@ +import std/num/random +import std/os/readline + +val empty = list(0, 15).map(fn(_) 0) +fun win(l) + l.any(fn(x) x == 2048) + +fun stack(l) + match l + Cons(0, tl) -> tl.stack ++ [0] + Cons(hd, tl) -> Cons(hd, tl.stack) + Nil -> Nil + +fun join(l: list) + match l + Cons(a, Cons(b, c)) | a == b -> Cons((a + b), c.join) ++ [0] + Cons(a, b) -> Cons(a, b.join) + Nil -> Nil + +fun hit(l) + l.stack.join + +fun hitBack(l) + l.reverse.hit.reverse + +fun splitBy(l: list, i: int): div list> + val (a, b) = l.split(i) + match b + Cons -> Cons(a, b.splitBy(i)) + Nil -> Cons(a, Nil) + +fun transpose(l: list>): list> + match l + Cons(Cons(a, b), c) -> Cons(Cons(a, c.map(fn(x) x.head.unjust)), transpose(Cons(b, c.map(fn(x) x.tail)).unsafe-decreasing)) + Cons(Nil, b) -> transpose(b) + Nil -> Nil + +fun rows(l) + l.splitBy(4) + +fun left(l) + l.rows.map(hit).concat + +fun right(l) + l.rows.map(hitBack).concat + +fun up(l) + l.rows.transpose.map(hit).transpose.concat + +fun down(l) + l.rows.transpose.map(hitBack).transpose.concat + +fun (==)(l1: list, l2: list): bool + match l1 + Cons(a, b) -> match l2 + Cons(c, d) -> a == c && b == d + Nil -> False + Nil -> match l2 + Cons -> False + Nil -> True + +fun lose(l) + l.left == l && l.right == l && l.up == l && l.down == l + +fun numZeros(l: list): int + l.filter(fn(x) x == 0).length + +fun insert(l: list, what: int, toWhere: int) + match l + Cons(0, tail) | tail.numZeros == toWhere -> Cons(what, tail) + Cons(head, tail) -> Cons(head, tail.insert(what, toWhere)) + Nil -> Nil + +fun spawnOn(l) + val newTileValue = if random-int() % 10 == 0 then 4 else 2 + val newPosition = random-int() % (l.numZeros - 1) + l.insert(newTileValue, newPosition) + +fun show-board(l: list): div string + "\n" ++ l.rows.map(fn(r) r.map(fn(x) x.show.pad-left(4)).join("")).intersperse("\n").join("") ++ "\n" + +fun quit(l) + [] + +fun quitted(l) + l.is-nil + +fun dispatch(c) + match c + 'i' -> up + 'j' -> left + 'k' -> down + 'l' -> right + 'q' -> quit + _ -> + println("Unknown command: keys are ijkl to move, q to quit") + id + +fun key() + readline().head-char.default('_') + +fun turn(l) + l.show-board.println + val next = dispatch(key())(l) + if !(next == l) && next.quitted.not then + spawnOn(next) + else + next + +fun play(state) + if state.win || state.lose || state.quitted then + if state.quitted then + "You quit!".println + else if state.win then + "You won!".println + else + "You lost!".println + else + "play".println + play(turn(state)) + +fun main() + print("ijkl to move, q to quit\n") + val initial = empty.spawnOn + println("Starting game...") + play(initial) diff --git a/Task/24-game-Solve/FutureBasic/24-game-solve.basic b/Task/24-game-Solve/FutureBasic/24-game-solve.basic new file mode 100644 index 0000000000..5a2f9b5cf2 --- /dev/null +++ b/Task/24-game-Solve/FutureBasic/24-game-solve.basic @@ -0,0 +1,53 @@ +begin globals +Short k +end globals + +void local fn eval( t as CFStringRef ) + CFMutableStringRef s = fn MutableStringNew + ExpressionRef x = fn ExpressionWithFormat( t ) + CFRange r = fn CFRangeMake(0, fn StringLength( t ) ) + CFNumberRef n = fn ExpressionValueWithObject( x, Null, Null ) + Float f = dblval( n ) + if f = 24 // found, so clean up + MutableStringSetString( s, t ) // duplicate string and pretend it was integers all along + MutableStringReplaceOccurrencesOfString( s, @".000000", @"", Null, r ) + print s; @" = 24" : k ++ + end if +end fn + + +clear local fn work( t as CFStringRef ) + Short a, b, c, d, e, f, g + CGFloat n(3) + CFStringRef s, os = @"*/+-", o(3) + print t, : k = 0 + // Put digits (as floats) and operators (as strings) in arrays + for a = 0 to 3 : s = mid( t, a, 1 ) : n(a) = fn StringFloatValue( s ) : o(a) = mid( os, a, 1 ) : next + // Permutions for the digits ... + for d = 0 to 3 : for e = 0 to 3 : for f = 0 to 3 : for g = 0 to 3 + if d != e and d != f and d != g and e != f and e != g and f != g // ... without duplications + // Combinations for the operators (3 from 4, with replacement) + for a = 0 to 3 : for b = 0 to 3 : for c = 0 to 3 + fn eval( fn StringWithFormat( @"%f %@ %f %@ %f %@ %f", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"%f %@ ( %f %@ %f ) %@ %f", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"%f %@ %f %@ ( %f %@ %f )", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"%f %@ ( %f %@ %f %@ %f )", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"( %f %@ %f ) %@ %f %@ %f", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"( %f %@ %f %@ %f ) %@ %f", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"%f %@ ( %f %@ ( %f %@ %f ) )", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"( %f %@ %f ) %@ ( %f %@ %f )", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"( %f %@ ( %f %@ %f )) %@ %f", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"( ( %f %@ %f ) %@ %f ) %@ %f", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + fn eval( fn StringWithFormat( @"%f %@ ( ( %f %@ %f ) %@ %f )", n(d), o(a), n(e), o(b), n(f), o(c), n(g) ) ) : if k > 0 then exit fn + next : next : next + end if + next : next : next : next +end fn + + +window 1, @"24 Game", ( 0, 0, 250, 250 ) +fn work(@"3388") +fn work(@"1346") +fn work(@"8752") + +handleevents diff --git a/Task/99-bottles-of-beer/EasyLang/99-bottles-of-beer.easy b/Task/99-bottles-of-beer/EasyLang/99-bottles-of-beer.easy index 6de268230b..f1f30f9082 100644 --- a/Task/99-bottles-of-beer/EasyLang/99-bottles-of-beer.easy +++ b/Task/99-bottles-of-beer/EasyLang/99-bottles-of-beer.easy @@ -1,21 +1,18 @@ -proc checkPlural num . word$ . +func$ bottle num . if num = 1 - word$ = "bottle" - else - word$ = "bottles" + return "bottle" . + return "bottles" . # -for i = 99 step -1 to 1 - call checkPlural i pluralWord$ - print i & " " & pluralWord$ & " of beer on the wall" - print i & " " & pluralWord$ & " of beer" +i = 99 +repeat + print i & " " & bottle i & " of beer on the wall" + print i & " " & bottle i & " of beer" print "Take one down, pass it around" - call checkPlural i - 1 pluralWord$ - if i - 1 = 0 - print "No more bottles of beer on the wall" - else - print i - 1 & " " & pluralWord$ & " of beer on the wall" - . + i -= 1 + until i = 0 + print i & " " & bottle i & " of beer on the wall" print "" . +print "No more bottles of beer on the wall" diff --git a/Task/AKS-test-for-primes/Zig/aks-test-for-primes.zig b/Task/AKS-test-for-primes/Zig/aks-test-for-primes.zig index 21d8d7999c..0a2f921dee 100644 --- a/Task/AKS-test-for-primes/Zig/aks-test-for-primes.zig +++ b/Task/AKS-test-for-primes/Zig/aks-test-for-primes.zig @@ -1,11 +1,12 @@ const std = @import("std"); const assert = std.debug.assert; -const stdout = std.io.getStdOut().writer(); pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var i: u6 = 0; while (i < 8) : (i += 1) - try showBinomial(i); + try showBinomial(stdout, i); try stdout.print("\nThe primes upto 50 (via AKS) are: ", .{}); i = 2; @@ -14,26 +15,26 @@ pub fn main() !void { try stdout.print("\n", .{}); } -fn showBinomial(n: u6) !void { +fn showBinomial(writer: anytype, n: u6) !void { const row = binomial(n).?; var sign: u8 = '+'; var exp = row.len; - try stdout.print("(x - 1)^{} =", .{n}); + try writer.print("(x - 1)^{} =", .{n}); for (row) |coef| { - try stdout.print(" ", .{}); + try writer.print(" ", .{}); if (exp != row.len) - try stdout.print("{c} ", .{sign}); + try writer.print("{c} ", .{sign}); exp -= 1; if (coef != 1 or exp == 0) - try stdout.print("{}", .{coef}); + try writer.print("{}", .{coef}); if (exp >= 1) { - try stdout.print("x", .{}); + try writer.print("x", .{}); if (exp > 1) - try stdout.print("^{}", .{exp}); + try writer.print("^{}", .{exp}); } sign = if (sign == '+') '-' else '+'; } - try stdout.print("\n", .{}); + try writer.print("\n", .{}); } fn aksPrime(n: u6) bool { @@ -54,6 +55,7 @@ pub fn binomial(n: u32) ?[]const u64 { const rmax = 68; +// evaluated and created at compile-time const pascal = build: { @setEvalBranchQuota(100_000); var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined; diff --git a/Task/Abelian-sandpile-model/00-META.yaml b/Task/Abelian-sandpile-model/00-META.yaml index 8c3aaa651c..5696ada613 100644 --- a/Task/Abelian-sandpile-model/00-META.yaml +++ b/Task/Abelian-sandpile-model/00-META.yaml @@ -1,2 +1,4 @@ --- +category: +- Cellular automata from: http://rosettacode.org/wiki/Abelian_sandpile_model diff --git a/Task/Achilles-numbers/Quackery/achilles-numbers.quackery b/Task/Achilles-numbers/Quackery/achilles-numbers.quackery new file mode 100644 index 0000000000..6ffaf8e4c4 --- /dev/null +++ b/Task/Achilles-numbers/Quackery/achilles-numbers.quackery @@ -0,0 +1,58 @@ + [ ' [ 1 ] swap + behead swap witheach + [ dup dip + [ = iff + [ -1 pluck + 1+ join ] + else + [ 1 join ] ] ] + drop ] is runs ( [ --> [ ) + + [ 1 over find swap found not ] is powerful ( [ --> b ) + + [ behead swap witheach gcd + 1 = ] is imperfect ( [ --> b ) + + [ dup 2 < iff + [ drop false ] done + primefactors runs + dup powerful iff + imperfect + else [ drop false ] ] is achilles ( [ --> b ) + + [ dup achilles iff + [ totient achilles ] + else [ drop false ] ] is strong ( [ --> b ) + + [] 0 + [ 1+ dup achilles if + [ tuck join swap ] + over size 50 = until ] + drop + say "First fifty achilles numbers:" cr + echo + cr cr + [] 0 + [ 1+ dup strong if + [ tuck join swap ] + over size 20 = until ] + drop + say "First twenty strong achilles numbers:" cr + echo + cr cr + 0 100 times + [ i^ achilles if 1+ ] + say "Achilles numbers with 2 digits: " echo + cr + 0 900 times + [ i^ 100 + achilles if 1+ ] + say "Achilles numbers with 3 digits: " echo + cr + 0 9000 times + [ i^ 1000 + achilles if 1+ ] + say "Achilles numbers with 4 digits: " echo + cr + 0 90000 times + [ i^ 10000 + achilles if 1+ ] + say "Achilles numbers with 5 digits: " echo + cr diff --git a/Task/Ackermann-function/Acornsoft-Lisp/ackermann-function.lisp b/Task/Ackermann-function/Acornsoft-Lisp/ackermann-function.lisp new file mode 100644 index 0000000000..cb2d8394ac --- /dev/null +++ b/Task/Ackermann-function/Acornsoft-Lisp/ackermann-function.lisp @@ -0,0 +1,4 @@ +(defun ack (m n) + (cond ((zerop m) (add1 n)) + ((zerop n) (ack (sub1 m) 1)) + (t (ack (sub1 m) (ack m (sub1 n)))))) diff --git a/Task/Ackermann-function/EasyLang/ackermann-function.easy b/Task/Ackermann-function/EasyLang/ackermann-function.easy index f8c5660900..db743b8970 100644 --- a/Task/Ackermann-function/EasyLang/ackermann-function.easy +++ b/Task/Ackermann-function/EasyLang/ackermann-function.easy @@ -1,12 +1,10 @@ -proc ackerm m n . r . - if m = 0 - r = n + 1 - elif n = 0 - call ackerm m - 1 1 r - else - call ackerm m n - 1 h - call ackerm m - 1 h r - . +func ackerm m n . + if m = 0 + return n + 1 + elif n = 0 + return ackerm (m - 1) 1 + else + return ackerm (m - 1) ackerm m (n - 1) + . . -call ackerm 3 6 r -print r +print ackerm 3 6 diff --git a/Task/Additive-primes/EasyLang/additive-primes.easy b/Task/Additive-primes/EasyLang/additive-primes.easy index 9675ae58f3..9185e69366 100644 --- a/Task/Additive-primes/EasyLang/additive-primes.easy +++ b/Task/Additive-primes/EasyLang/additive-primes.easy @@ -1,25 +1,28 @@ -proc isprime x . r . - r = 1 - for i = 2 to sqrt x - if x mod i = 0 - r = 0 - break 2 - . +func prime n . + if n mod 2 = 0 and n > 2 + return 0 . + i = 3 + sq = sqrt n + while i <= sq + if n mod i = 0 + return 0 + . + i += 2 + . + return 1 . -proc digsum n . sum . - sum = 0 +func digsum n . while n > 0 sum += n mod 10 n = n div 10 . + return sum . for i = 2 to 500 - call isprime i r - if r = 1 - call digsum i s - call isprime s r - if r = 1 + if prime i = 1 + s = digsum i + if prime s = 1 write i & " " . . diff --git a/Task/Additive-primes/Maxima/additive-primes.maxima b/Task/Additive-primes/Maxima/additive-primes.maxima new file mode 100644 index 0000000000..1e8becc662 --- /dev/null +++ b/Task/Additive-primes/Maxima/additive-primes.maxima @@ -0,0 +1,17 @@ +/* Function that returns a list of digits given a nonnegative integer */ +decompose(num) := block([digits, remainder], + digits: [], + while num > 0 do + (remainder: mod(num, 10), + digits: cons(remainder, digits), + num: floor(num/10)), + digits +)$ + +/* Routine that extracts from primes between 2 and 500, inclusive, the additive primes */ +block( + primes(2,500), + sublist(%%,lambda([x],primep(apply("+",decompose(x)))))); + +/* Number of additive primes in the rank */ +length(%); diff --git a/Task/Address-of-a-variable/Zig/address-of-a-variable.zig b/Task/Address-of-a-variable/Zig/address-of-a-variable.zig index 53d9e30a49..88fd6ff5ee 100644 --- a/Task/Address-of-a-variable/Zig/address-of-a-variable.zig +++ b/Task/Address-of-a-variable/Zig/address-of-a-variable.zig @@ -5,5 +5,5 @@ pub fn main() !void { var i: i32 = undefined; var address_of_i: *i32 = &i; - try stdout.print("{x}\n", .{@ptrToInt(address_of_i)}); + try stdout.print("{x}\n", .{@intFromPtr(address_of_i)}); } diff --git a/Task/Almost-prime/Maxima/almost-prime.maxima b/Task/Almost-prime/Maxima/almost-prime.maxima new file mode 100644 index 0000000000..70f1b0b09a --- /dev/null +++ b/Task/Almost-prime/Maxima/almost-prime.maxima @@ -0,0 +1,16 @@ +/* Predicate function that checks k-almost primality for given integer n and parameter k */ +k_almost_primep(n,k):=if integerp((n)^(1/k)) and primep((n)^(1/k)) then true else +lambda([x],(length(ifactors(x))=k and unique(map(second,ifactors(x)))=[1]) or (length(ifactors(x)) n + if sumdivs m = n + print n & " " & m + . + . +. diff --git a/Task/Anagrams-Deranged-anagrams/FutureBasic/anagrams-deranged-anagrams-1.basic b/Task/Anagrams-Deranged-anagrams/FutureBasic/anagrams-deranged-anagrams-1.basic new file mode 100644 index 0000000000..0147ff08d3 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/FutureBasic/anagrams-deranged-anagrams-1.basic @@ -0,0 +1,3 @@ +Anagrams + length ZzYyXx WwVvUuTt SsRrQqPp OoNnMmLl KkJjIiHh GgFfEeDd CcBbAa +00001000 00000000 00000000 01010000 00010100 00000000 01000000 00001100 diff --git a/Task/Anagrams-Deranged-anagrams/FutureBasic/anagrams-deranged-anagrams-2.basic b/Task/Anagrams-Deranged-anagrams/FutureBasic/anagrams-deranged-anagrams-2.basic new file mode 100644 index 0000000000..5cbb4c9c79 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/FutureBasic/anagrams-deranged-anagrams-2.basic @@ -0,0 +1,100 @@ +#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES} +defstr long +begin globals +xref xwords( 210000 ) as char +long gAvatars( 26000 ) +uint32 gwordNum, gfilen, gcount = 0, gOffset( 26000 ) +uint16 gndx( 26000 ), deranged( 600, 1 ) +long sh : sh = system( _scrnHeight ) -100 +long sw : sw = (system( _scrnWidth ) -360 ) / 2 +CFTimeInterval t +_len = 56 +end globals + +local fn loadDictionary + CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ) + CFStringRef dictStr = fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL ) + dictStr = fn StringByAppendingString( @" ", dictStr ) + xwords = fn StringUTF8String( dictstr ) + gfilen = len(dictstr) +end fn + +local fn deranagrams + uint64 ch, p, wordStart = 0 + long avatar = 0 + uint32 med, bot, top + byte chk, L + + for p = 1 to gfilen + ch = xwords(p) //build avatar + if ch > _" " then avatar += (long) 1 << ( ch and 31 ) * 2: continue + + avatar += (long)(p - wordStart - 1) << _len //complete avatar by adding word length + gAvatars(gWordNum) = avatar //store the avatar in list + gOffset( gWordNum) = wordStart //store offset to the word + + //Insert into ordered list of avatars + bot = 0 : top = gwordNum //quick search for place to insert + while (top - bot) > 1 + med = ( top + bot ) >> 1 + if avatar > gAvatars(gndx(med)) then bot = med else top = med + wend + blockmove( @gndx( top ), @gndx( top + 1 ), ( gwordNum - top ) * 2 ) + gndx(top) = gWordNum + + gwordNum++ : wordStart = p : avatar = 0 //ready for new word + next p + + //Check for matching avatars + for p = gWordNum to 1 step -1 + chk = 1 //to make sure each word is compared with all matching avatars + while gAvatars( gndx( p ) ) == gAvatars( gndx( p - chk ) ) + + // found anagram; now check for chars in same position + L = ( gAvatars( gndx( p ) ) >> _len ) //get word length + while L + if xwords(gOffset(gndx(p)) +L) == xwords(gOffset(gndx(p-chk)) +L) then break + L-- + wend + if L == 0 + + //no matching chars: found Deranged Anagram! + deranged( gcount, 0 ) = gndx( p ) + deranged( gcount, 1 ) = gndx( p - chk ) + gcount++ + end if + chk++ + wend + next +end fn + +local fn printPair( ndx as uint32, chrsToCntr as byte ) + ptr p : str255 pair : pair = "" + short n = ( gAvatars( deranged( ndx, 0 ) ) >> _len ) + if n < chrsToCntr then print string$( chrsToCntr - n, " " ); + p = xwords + gOffset( deranged( ndx, 0 ) ) + p.0`` = n : print p.0$; " "; + p = xwords + gOffset( deranged( ndx, 1 ) ) + p.0`` = n : print p.0$ +end fn + +local fn doDialog(evt as long) + if evt == _btnclick + long r + button -1 : window 1,,(sw,50,335,sh-50) + for r = 1 to gcount-1 + fn printPair( r, 21 ) + next + end if +end fn + +fn loadDictionary : t = fn CACurrentMediaTime +fn deranagrams : t = fn CACurrentMediaTime - t + +window 1, @"Deranged Anagrams in FutureBasic",(sw,sh-130,335,130) +printf @"\n %u deranged anagrams found among \n %u words ¬ +in %.2f ms.\n", gcount, gWordNum, t * 1000 +print " Longest:";: fn printPair( 0, 11 ) +button 1,,,fn StringWithFormat(@"Show remaining %u deranged anagrams.",gcount-1),(24,20,285,34) +on dialog fn doDialog +handleevents diff --git a/Task/Anonymous-recursion/00-TASK.txt b/Task/Anonymous-recursion/00-TASK.txt index 943e4bd5fd..c2ad70dd03 100644 --- a/Task/Anonymous-recursion/00-TASK.txt +++ b/Task/Anonymous-recursion/00-TASK.txt @@ -15,5 +15,8 @@ Anonymous recursion can also be accomplished using the   [[Y combinator]]. ;Task: If possible, demonstrate this by writing the recursive version of the fibonacci function   (see [[Fibonacci sequence]])   which checks for a negative argument before doing the actual recursion. +;Related tasks: +:*   [[Y combinator]] +

diff --git a/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy b/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy new file mode 100644 index 0000000000..fb16cc5cc2 --- /dev/null +++ b/Task/Archimedean-spiral/EasyLang/archimedean-spiral.easy @@ -0,0 +1,9 @@ +linewidth 0.2 +x = 50 +y = 50 +move x y +while r < 50 + line r * cos t + x r * sin t + y + r += 0.1 + t += 6 +. diff --git a/Task/Archimedean-spiral/Maxima/archimedean-spiral.maxima b/Task/Archimedean-spiral/Maxima/archimedean-spiral.maxima new file mode 100644 index 0000000000..2d3cfa9c6c --- /dev/null +++ b/Task/Archimedean-spiral/Maxima/archimedean-spiral.maxima @@ -0,0 +1,2 @@ +archi_spi(a,b):=wxdraw2d(nticks=200,polar(a+b*theta,theta,1,10*%pi))$ +archi_spi(1,1); diff --git a/Task/Arithmetic-derivative/00-TASK.txt b/Task/Arithmetic-derivative/00-TASK.txt index d2396e4273..7e36aa263c 100644 --- a/Task/Arithmetic-derivative/00-TASK.txt +++ b/Task/Arithmetic-derivative/00-TASK.txt @@ -33,4 +33,3 @@ Find (the arithmetic derivative of 10^m) then divided by 7, where m is from 1 to ;* [[oeis:A003415|OEIS:A003415 - a(n) = n' = arithmetic derivative of n.]] ;*[[wp:Arithmetic_derivative|Wikipedia: Arithmetic Derivative]] - diff --git a/Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative.alg b/Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative.alg new file mode 100644 index 0000000000..5579ac5c82 --- /dev/null +++ b/Task/Arithmetic-derivative/ALGOL-68/arithmetic-derivative.alg @@ -0,0 +1,22 @@ +BEGIN PROC lagarias = (LONG INT n) LONG INT: # Lagarias arithmetic derivative # + IF n < 0 + THEN -lagarias (-n) + ELIF n = 0 OR n = 1 + THEN 0 + ELIF PROC small pf = (LONG INT j, k) LONG INT: # Smallest prime factor # + (j %* k = 0 | k | small pf (j, k + 1)); + LONG INT f = small pf (n, 2); LONG INT q = n % f; + q = 1 + THEN 1 + ELSE q * lagarias (f) + f * lagarias (q) + FI; + + FOR n FROM -99 TO 100 + DO print (("D(", whole (n, 0), ") = ", whole (lagarias (n), 0), new line)) + OD; + new line (standout); + FOR n TO 20 + DO LONG INT m = LONG 10 ^ n; + print (("D(", whole (m, 0), ") / 7 = ", whole (lagarias (m) % 7, 0), new line)) + OD +END diff --git a/Task/Arithmetic-evaluation/EasyLang/arithmetic-evaluation.easy b/Task/Arithmetic-evaluation/EasyLang/arithmetic-evaluation.easy new file mode 100644 index 0000000000..f8bbf4ec53 --- /dev/null +++ b/Task/Arithmetic-evaluation/EasyLang/arithmetic-evaluation.easy @@ -0,0 +1,142 @@ +subr nch + if inp_ind > len inp$[] + ch$ = strchar 0 + else + ch$ = inp$[inp_ind] + inp_ind += 1 + . + ch = strcode ch$ +. +# +subr ntok + while ch$ = " " + nch + . + if ch >= 48 and ch <= 58 + tok$ = "n" + s$ = "" + while ch >= 48 and ch <= 58 or ch$ = "." + s$ &= ch$ + nch + . + tokv = number s$ + elif ch = 0 + tok$ = "end of text" + else + tok$ = ch$ + nch + . +. +subr init0 + astop$[] = [ ] + astleft[] = [ ] + astright[] = [ ] + err = 0 +. +proc init s$ . . + inp$[] = strchars s$ + inp_ind = 1 + nch + ntok + init0 +. +proc ast_print nd . . + write "AST:" + for i to len astop$[] + write " ( " + write astop$[i] & " " + write astleft[i] & " " + write astright[i] + write " )" + . + print " Start: " & nd +. +func node . + astop$[] &= "" + astleft[] &= 0 + astright[] &= 0 + return len astop$[] +. +# +funcdecl parse_expr . +# +func parse_factor . + if tok$ = "n" + nd = node + astop$[nd] = "n" + astleft[nd] = tokv + ntok + elif tok$ = "(" + ntok + nd = parse_expr + if tok$ <> ")" + err = 1 + print "error: ) expected, got " & tok$ + . + ntok + else + err = 1 + print "error: factor expected, got " & tok$ + . + return nd +. +func parse_term . + ndx = parse_factor + while tok$ = "*" or tok$ = "/" + nd = node + astleft[nd] = ndx + astop$[nd] = tok$ + ntok + astright[nd] = parse_factor + ndx = nd + . + return ndx +. +func parse_expr . + ndx = parse_term + while tok$ = "+" or tok$ = "-" + nd = node + astleft[nd] = ndx + astop$[nd] = tok$ + ntok + astright[nd] = parse_term + ndx = nd + . + return ndx +. +func parse s$ . + init s$ + return parse_expr +. +func eval nd . + if astop$[nd] = "n" + return astleft[nd] + . + le = eval astleft[nd] + ri = eval astright[nd] + a$ = astop$[nd] + if a$ = "+" + return le + ri + elif a$ = "-" + return le - ri + elif a$ = "*" + return le * ri + elif a$ = "/" + return le / ri + . +. +repeat + inp$ = input + until inp$ = "" + print "Inp: " & inp$ + nd = parse inp$ + ast_print nd + if err = 0 + print "Eval: " & eval nd + . + print "" +. +input_data +4 * +4.2 * ((5.3+8)*3 + 4) +2.5 * 2 + 2 * 3.14 diff --git a/Task/Arithmetic-numbers/APL/arithmetic-numbers.apl b/Task/Arithmetic-numbers/APL/arithmetic-numbers.apl new file mode 100644 index 0000000000..10aa3234e5 --- /dev/null +++ b/Task/Arithmetic-numbers/APL/arithmetic-numbers.apl @@ -0,0 +1,15 @@ +task←{ + facs ← ⍸0=⍳|⊢ + aritm ← (0=≢|+/)∘facs + comp ← 2<(≢facs) + aritms ← ⍸aritm¨⍳15000 + + ⎕←'First 100 arithmetic numbers:' + ⎕←10 10⍴aritms + { + ⎕←'' + ⎕←'The ',(⍕⍵),'th arithmetic number: ',(⍕aritms[⍵]) + ncomps ← +/comp¨⍵↑aritms + ⎕←'Of the first ',(⍕⍵),' arithmetic numbers, ',(⍕ncomps),' are composite.' + }¨10*3 4 +} diff --git a/Task/Arithmetic-numbers/ARM-Assembly/arithmetic-numbers.arm b/Task/Arithmetic-numbers/ARM-Assembly/arithmetic-numbers.arm new file mode 100644 index 0000000000..ffb4b32649 --- /dev/null +++ b/Task/Arithmetic-numbers/ARM-Assembly/arithmetic-numbers.arm @@ -0,0 +1,406 @@ +/* ARM assembly Raspberry PI */ +/* program arithnumber.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../constantes.inc" + +.equ NBDIVISORS, 2000 + +//.include "../../ficmacros32.inc" @ use for developper debugging +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessStartPgm: .asciz "Program 32 bits start. \n" +szMessEndPgm: .asciz "Program normal end.\n" +szMessErrorArea: .asciz "\033[31mError : area divisors too small.\n" +szMessError: .asciz "\033[31mError !!!\n" +szMessErrGen: .asciz "Error end program.\n" +szMessResultFact: .asciz "@ " + +szCarriageReturn: .asciz "\n" + +szMessEntete: .asciz "The first 150 arithmetic numbers are:\n" +szMessResult: .asciz " @ " + +szMessEntete1: .asciz "The 1000 aritmetic number :" +szMessEntete2: .asciz "The 10000 aritmetic number :" +szMessEntete3: .asciz "The 100000 aritmetic number :" +szMessEntete4: .asciz "The 1000000 aritmetic number :" +szMessComposite: .asciz "Composite number : " +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +.align 4 +sZoneConv: .skip 24 +tbZoneDecom: .skip 4 * NBDIVISORS // facteur 4 octets +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: @ program start + ldr r0,iAdrszMessStartPgm @ display start message + bl affichageMess + + ldr r0,iAdrszMessEntete @ display result message + bl affichageMess + mov r2,#1 @ start number + mov r3,#0 @ counter result + mov r6,#0 @ counter result by line +1: + mov r0,r2 @ number + ldr r1,iAdrtbZoneDecom + bl testNbArith @ test + cmp r0,#1 @ ok ? + bne 3f + add r3,#1 + mov r0,r2 @ number + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + ldr r0,iAdrszMessResult + ldr r1,iAdrsZoneConv + bl strInsertAtCharInc @ and put in message + + bl affichageMess + add r6,r6,#1 + cmp r6,#6 + blt 3f + mov r6,#0 + ldr r0,iAdrszCarriageReturn + bl affichageMess +3: + add r2,r2,#1 + cmp r3,#100 + blt 1b + ldr r0,iAdrszCarriageReturn + bl affichageMess + + /* count arithmetic number */ + mov r2,#1 + mov r3,#0 + ldr r5,iN10P4 + ldr r6,iN10P5 + ldr r7,iN10P6 + mov r8,#0 @ counter composite +4: + mov r0,r2 @ number + ldr r1,iAdrtbZoneDecom + bl testNbArith + cmp r0,#1 + bne 6f + cmp r1,#1 + bne 5f + add r8,r8,#1 +5: + add r3,#1 +6: + cmp r3,#1000 + beq 7f + cmp r3,r5 @ 10000 + beq 8f + cmp r3,r6 @ 100000 + beq 9f + cmp r3,r7 @ 1000000 + beq 10f + b 11f + +7: + ldr r0,iAdrszMessEntete1 + bl affichageMess + mov r0,r2 + mov r4,r1 @ save sum + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + mov r0,r1 + bl affichageMess + ldr r0,iAdrszMessComposite + bl affichageMess + mov r0,r8 + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + mov r0,r1 + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + b 11f +8: + ldr r0,iAdrszMessEntete2 + bl affichageMess + mov r0,r2 + mov r4,r1 @ save sum + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + mov r0,r1 + bl affichageMess + ldr r0,iAdrszMessComposite + bl affichageMess + mov r0,r8 + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + mov r0,r1 + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + b 11f + 9: + ldr r0,iAdrszMessEntete3 + bl affichageMess + mov r0,r2 + mov r4,r1 @ save sum + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + mov r0,r1 + bl affichageMess + ldr r0,iAdrszMessComposite + bl affichageMess + mov r0,r8 + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + mov r0,r1 + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + b 11f + 10: + ldr r0,iAdrszMessEntete4 + bl affichageMess + mov r0,r2 + mov r4,r1 @ save sum + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + mov r0,r1 + bl affichageMess + ldr r0,iAdrszMessComposite + bl affichageMess + mov r0,r8 + ldr r1,iAdrsZoneConv + bl conversion10 @ convert ascii string + mov r0,r1 + bl affichageMess + ldr r0,iAdrszCarriageReturn + bl affichageMess + b 12f +11: + add r2,r2,#1 + b 4b +12: + ldr r0,iAdrszMessEndPgm @ display end message + bl affichageMess + b 100f +99: @ display error message + ldr r0,iAdrszMessError + bl affichageMess +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform system call +iAdrszMessStartPgm: .int szMessStartPgm +iAdrszMessEndPgm: .int szMessEndPgm +iAdrszMessError: .int szMessError +iAdrszCarriageReturn: .int szCarriageReturn +iAdrtbZoneDecom: .int tbZoneDecom +iAdrszMessEntete: .int szMessEntete +iAdrszMessEntete1: .int szMessEntete1 +iAdrszMessEntete2: .int szMessEntete2 +iAdrszMessEntete3: .int szMessEntete3 +iAdrszMessEntete4: .int szMessEntete4 +iAdrszMessResult: .int szMessResult +iAdrszMessComposite: .int szMessComposite +iAdrsZoneConv: .int sZoneConv +iN10P4: .int 10000 +iN10P5: .int 100000 +iN10P6: .int 1000000 + + +/******************************************************************/ +/* test if number is aritmetic number */ +/******************************************************************/ +/* r0 contains number */ +/* r1 contains address of divisors area */ +/* r0 return 1 if ok else return 0 */ +/* r1 return 1 if composite */ +testNbArith: + push {r2-r11,lr} @ save registers + cmp r0,#1 @ 1 is arithmetique + moveq r0,#1 + moveq r1,#0 + beq 100f + cmp r0,#2 @ 2 is not aritmetic + moveq r0,#0 + moveq r1,#0 + beq 100f + mov r5,r1 + mov r8,r0 @ save number + bl isPrime @ prime ? + cmp r0,#1 + moveq r0,#1 @ yes is prime and arithmetic + moveq r1,#0 @ but not composite + beq 100f @ end + mov r1,#1 + str r1,[r5] @ first factor + mov r11,#1 @ divisors sum + mov r4,#1 @ indice divisors table + mov r1,#2 @ first divisor + mov r6,#0 @ previous divisor + mov r7,#0 @ number of same divisors +1: + mov r0,r8 @ dividende + bl division @ r1 divisor r2 quotient r3 remainder + cmp r3,#0 + bne 6f @ if remainder <> zero -> no divisor + mov r8,r2 @ else quotient -> new dividende + cmp r1,r6 @ same divisor ? + beq 3f @ yes + mov r7,r4 @ number factors in table + mov r9,#0 @ indice +2: @ for each new prime factor compute all factors of number + ldr r10,[r5,r9,lsl #2 ] @ load one factor + mul r10,r1,r10 @ multiply + str r10,[r5,r7,lsl #2] @ and store in the table + add r11,r10 @ sum of factors + add r7,r7,#1 @ and increment counter + add r9,r9,#1 @ increment index + cmp r9,r4 @ end array factors ? + blt 2b + mov r4,r7 + mov r6,r1 @ new divisor + b 7f +3: @ same divisor + sub r9,r4,#1 + mov r7,r4 +4: @ for each prime factor compute all factors of number + ldr r10,[r5,r9,lsl #2 ] @ this prime factor is in factor array ? + cmp r10,r1 + subne r9,#1 + bne 4b + sub r9,r4,r9 +5: + ldr r10,[r5,r9,lsl #2 ] + mul r10,r1,r10 + str r10,[r5,r7,lsl #2] @ and store in the table + add r11,r10 + add r7,r7,#1 @ and increment counter + add r9,r9,#1 + cmp r9,r4 + blt 5b + mov r4,r7 + b 7f @ and loop + + /* not divisor -> increment next divisor */ +6: + cmp r1,#2 @ if divisor = 2 -> add 1 + addeq r1,#1 + addne r1,#2 @ else add 2 + b 1b @ and loop + + /* divisor -> test if new dividende is prime */ +7: + mov r3,r1 @ save divisor + cmp r8,#1 @ dividende = 1 ? -> end + beq 13f + mov r0,r8 @ new dividende is prime ? + mov r1,#0 + bl isPrime @ the new dividende is prime ? + cmp r0,#1 + bne 12f @ the new dividende is not prime + + cmp r8,r6 @ else new dividende prime is same divisor ? + beq 9f @ yes + @ no -> compute all factors + mov r7,r4 @ number factors in table + mov r9,#0 @ indice +8: + ldr r10,[r5,r9,lsl #2 ] @ load one factor + mul r10,r8,r10 @ multiply + str r10,[r5,r7,lsl #2] @ and store in the table + add r11,r10 + add r7,r7,#1 @ and increment counter + add r9,r9,#1 + cmp r9,r4 + blt 8b + mov r4,r7 + mov r7,#0 + b 13f +9: + sub r9,r4,#1 + mov r7,r4 +10: + ldr r10,[r5,r9,lsl #2 ] + cmp r10,r8 + subne r9,#1 + bne 10b + sub r9,r4,r9 +11: + ldr r10,[r5,r9,lsl #2 ] + mul r10,r8,r10 + str r10,[r5,r7,lsl #2] @ and store in the table + add r11,r10 + add r7,r7,#1 @ and increment counter + add r9,r9,#1 + cmp r9,r4 + blt 11b + mov r4,r7 + b 13f + +12: + mov r1,r3 @ current divisor = new divisor + cmp r1,r8 @ current divisor > new dividende ? + ble 1b @ no -> loop + + /* end decomposition */ +13: + mov r1,r4 @ control if arithmetic + mov r0,r11 @ compute average + bl division + mov r1,#1 + cmp r3,#0 @ no remainder + moveq r0,#1 @ average is integer + beq 100f @ no -> end + mov r0,#0 + mov r1,#0 + +100: + pop {r2-r11,pc} @ restaur registers +//iAdrszMessNbPrem: .int szMessNbPrem + +/******************************************************************/ +/* test if number is prime trial test */ +/******************************************************************/ +/* r0 contains the number */ +/* r0 return 1 if prime else return 0 */ +isPrime: + push {r4,lr} @ save registers + cmp r0,#1 @ <= 1 ? + movls r0,#0 @ not prime + bls 100f + cmp r0,#3 @ 2 and 3 prime + movls r0,#1 + bls 100f + tst r0,#1 @ even ? + moveq r0,#0 @ not prime + beq 100f + mov r4,r0 @ save number + mov r1,#3 @ first divisor +1: + mov r0,r4 @ number + bl division + add r1,r1,#2 @ increment divisor + cmp r3,#0 @ remainder = zero ? + moveq r0,#0 @ not prime + beq 100f + cmp r1,r2 @ divisors<=quotient ? + ble 1b @ loop + mov r0,#1 @ return prime + +100: + pop {r4,pc} @ restaur registers +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../affichage.inc" diff --git a/Task/Arithmetic-numbers/Maxima/arithmetic-numbers.maxima b/Task/Arithmetic-numbers/Maxima/arithmetic-numbers.maxima new file mode 100644 index 0000000000..2f5f1df599 --- /dev/null +++ b/Task/Arithmetic-numbers/Maxima/arithmetic-numbers.maxima @@ -0,0 +1,24 @@ +/* Predicate function that checks wether a positive integer is arithmetic or not */ +arith_nump(n):=block(listify(divisors(n)),apply("+",%%)/length(%%),if integerp(%%) then true)$ + +/* Function that returns a list of the first len arithmetic numbers */ +arith_num_count(len):=block( + [i:1,count:0,result:[]], + while count t1 + COMPUTE int-field OF table-one(tally) = tally * 3 + END-PERFORM + MOVE 3 TO t2 + PERFORM VARYING tally FROM 1 BY 1 UNTIL tally > t2 + COMPUTE int-field OF table-two(tally) = tally * 6 + END-PERFORM. - 77 show pic z(4). +concatenate-tables. + PERFORM VARYING tally FROM 1 BY 1 UNTIL tally > t1 + ADD 1 TO t2 + MOVE int-field OF table-one(tally) + TO int-field OF table-two(t2) + END-PERFORM. - procedure division. - array-concat-main. - perform initialize-tables - perform concatenate-tables - perform display-result - goback. +display-result. + PERFORM VARYING tally FROM 1 BY 1 UNTIL tally = t2 + MOVE int-field OF table-two(tally) TO show + DISPLAY FUNCTION TRIM(show) ", " WITH NO ADVANCING + END-PERFORM + MOVE int-field OF table-two(tally) TO show + DISPLAY FUNCTION TRIM(show). - initialize-tables. - move 4 to t1 - perform varying tally from 1 by 1 until tally > t1 - compute int-field of table-one(tally) = tally * 3 - end-perform - - move 3 to t2 - perform varying tally from 1 by 1 until tally > t2 - compute int-field of table-two(tally) = tally * 6 - end-perform - . - - concatenate-tables. - perform varying tally from 1 by 1 until tally > t1 - add 1 to t2 - move int-field of table-one(tally) - to int-field of table-two(t2) - end-perform - . - - display-result. - perform varying tally from 1 by 1 until tally = t2 - move int-field of table-two(tally) to show - display trim(show) ", " with no advancing - end-perform - move int-field of table-two(tally) to show - display trim(show) - . - - end program array-concat. +END PROGRAM array-concat. diff --git a/Task/Array-concatenation/Zig/array-concatenation.zig b/Task/Array-concatenation/Zig/array-concatenation.zig index 7608339f46..fc98da803d 100644 --- a/Task/Array-concatenation/Zig/array-concatenation.zig +++ b/Task/Array-concatenation/Zig/array-concatenation.zig @@ -1,16 +1,23 @@ const std = @import("std"); -fn concat(allocator: std.mem.Allocator, a: []const u32, b: []const u32) ![]u32 { - const result = try allocator.alloc(u32, a.len + b.len); - std.mem.copy(u32, result, a); - std.mem.copy(u32, result[a.len..], b); - return result; -} -pub fn main() void { - var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; - const gpa = general_purpose_allocator.allocator(); - var array1 = [_]u32{ 1, 2, 3, 4, 5 }; - var array2 = [_]u32{ 6, 7, 8, 9, 10, 11, 12 }; - const array3 = concat(gpa, &array1, &array2); - std.debug.print("Array 1: {any}\nArray 2: {any}\nArray 3: {any}", .{ array1, array2, array3 }); +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + + const allocator = gpa.allocator(); + + var array1 = [_]u32{ 1, 2, 3, 4, 5 }; + var array2 = [_]u32{ 6, 7, 8, 9, 10, 11, 12 }; + + const slice3 = try std.mem.concat(allocator, u32, &[_][]const u32{ &array1, &array2 }); + defer allocator.free(slice3); + + // Same result, alternative syntax + const slice4 = try std.mem.concat(allocator, u32, &[_][]const u32{ array1[0..], array2[0..] }); + defer allocator.free(slice4); + + std.debug.print( + "Array 1: {any}\nArray 2: {any}\nSlice 3: {any}\nSlice 4: {any}\n", + .{ array1, array2, slice3, slice4 }, + ); } diff --git a/Task/Assertions/Zig/assertions.zig b/Task/Assertions/Zig/assertions.zig index bb578e41ee..cbed1987f6 100644 --- a/Task/Assertions/Zig/assertions.zig +++ b/Task/Assertions/Zig/assertions.zig @@ -1,5 +1,6 @@ const assert = @import("std").debug.assert; pub fn main() void { - assert(1 == 0); // On failure, an `unreachable` is reached + const n: i64 = 43; + assert(n == 42); // On failure, an `unreachable` is reached } diff --git a/Task/Attractive-numbers/FutureBasic/attractive-numbers.basic b/Task/Attractive-numbers/FutureBasic/attractive-numbers.basic new file mode 100644 index 0000000000..307f9f527a --- /dev/null +++ b/Task/Attractive-numbers/FutureBasic/attractive-numbers.basic @@ -0,0 +1,35 @@ +local fn IsPrime( n as NSUInteger ) as BOOL + NSUInteger i + + if ( n < 2 ) then exit fn = NO + if ( n = 2 ) then exit fn = YES + if ( n mod 2 == 0 ) then exit fn = NO + for i = 3 to int(n^.5) step 2 + if ( n mod i == 0 ) then exit fn = NO + next +end fn = YES + +local fn Factors( n as NSInteger ) as NSInteger + NSInteger count = 0, f = 2 + + do + if n mod f == 0 then count++ : n /= f else f++ + until ( f > n ) +end fn = count + +void local fn AttractiveNumbers( limit as NSInteger ) + NSInteger c = 0, n + + printf @"Attractive numbers through %d are:", limit + for n = 4 to limit + if fn IsPrime( fn Factors( n ) ) + printf @"%4d \b", n + c++ + if ( c mod 10 == 0 ) then print + end if + next +end fn + +fn AttractiveNumbers( 120 ) + +HandleEvents diff --git a/Task/Attractive-numbers/Maxima/attractive-numbers.maxima b/Task/Attractive-numbers/Maxima/attractive-numbers-1.maxima similarity index 100% rename from Task/Attractive-numbers/Maxima/attractive-numbers.maxima rename to Task/Attractive-numbers/Maxima/attractive-numbers-1.maxima diff --git a/Task/Attractive-numbers/Maxima/attractive-numbers-2.maxima b/Task/Attractive-numbers/Maxima/attractive-numbers-2.maxima new file mode 100644 index 0000000000..c1bfc99d29 --- /dev/null +++ b/Task/Attractive-numbers/Maxima/attractive-numbers-2.maxima @@ -0,0 +1,2 @@ +attractivep(n):=block(ifactors(n),apply("+",map(second,%%)),if primep(%%) then true)$ +sublist(makelist(i,i,120),attractivep); diff --git a/Task/Attractive-numbers/Odin/attractive-numbers.odin b/Task/Attractive-numbers/Odin/attractive-numbers.odin new file mode 100644 index 0000000000..c151f376a3 --- /dev/null +++ b/Task/Attractive-numbers/Odin/attractive-numbers.odin @@ -0,0 +1,69 @@ +import "core:fmt" +main :: proc() { + const_max :: 120 + fmt.println("\nAttractive numbers up to and including", const_max, "are: ") + count := 0 + for i in 1 ..= const_max { + n := countPrimeFactors(i) + if isPrime(n) { + fmt.print(i, " ") + count += 1 + if count % 20 == 0 { + fmt.println() + } + } + } + fmt.println() +} +/* definitions */ +isPrime :: proc(n: int) -> bool { + switch { + case n < 2: + return false + case n % 2 == 0: + return n == 2 + case n % 3 == 0: + return n == 3 + case: + d := 5 + for d * d <= n { + if n % d == 0 { + return false + } + d += 2 + if n % d == 0 { + return false + } + d += 4 + } + return true + } +} +countPrimeFactors :: proc(n: int) -> int { + n := n + switch { + case n == 1: + return 0 + case isPrime(n): + return 1 + case: + count, f := 0, 2 + for { + if n % f == 0 { + count += 1 + n /= f + if n == 1 { + return count + } + if isPrime(n) { + f = n + } + } else if f >= 3 { + f += 2 + } else { + f = 3 + } + } + return count + } +} diff --git a/Task/Average-loop-length/Wren/average-loop-length.wren b/Task/Average-loop-length/Wren/average-loop-length.wren index 9bc9d63d07..eb76092086 100644 --- a/Task/Average-loop-length/Wren/average-loop-length.wren +++ b/Task/Average-loop-length/Wren/average-loop-length.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/fmt" for Fmt +import "./fmt" for Fmt var nmax = 20 var rand = Random.new() @@ -35,10 +35,6 @@ System.print("=== ========= ============ =========") for (n in 1..nmax) { var a = avg.call(n) var b = ana.call(n) - var ns = Fmt.d(3, n) - var as = Fmt.f(9, a, 4) - var bs = Fmt.f(12, b, 4) var e = (a - b).abs/ b * 100 - var es = Fmt.f(6, e, 2) - System.print("%(ns) %(as) %(bs) (%(es)\%)") + Fmt.print("$3d $9.4f $12.4f ($6.2f\%)", n, a, b, e) } diff --git a/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy b/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy index 3edae10d45..e14e43c02e 100644 --- a/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy +++ b/Task/Averages-Arithmetic-mean/EasyLang/averages-arithmetic-mean.easy @@ -1,9 +1,9 @@ -func mean . f[] r . - for i = 1 to len f[] - s += f[i] - . - r = s / len f[] +proc mean . f[] r . + for i = 1 to len f[] + s += f[i] + . + r = s / len f[] . f[] = [ 1 2 3 4 5 6 7 8 ] -call mean f[] r +mean f[] r print r diff --git a/Task/Averages-Median/EasyLang/averages-median.easy b/Task/Averages-Median/EasyLang/averages-median.easy index 5daa7e0b76..51e508db90 100644 --- a/Task/Averages-Median/EasyLang/averages-median.easy +++ b/Task/Averages-Median/EasyLang/averages-median.easy @@ -1,40 +1,40 @@ proc quickselect k . list[] res . - # - subr partition - mid = left - for i = left + 1 to right - if list[i] < list[left] - mid += 1 - swap list[i] list[mid] + # + subr partition + mid = left + for i = left + 1 to right + if list[i] < list[left] + mid += 1 + swap list[i] list[mid] + . . - . - swap list[left] list[mid] - . - left = 1 - right = len list[] - while left < right - call partition - if mid < k - left = mid + 1 - elif mid > k - right = mid - 1 - else - left = right - . - . - res = list[k] + swap list[left] list[mid] + . + left = 1 + right = len list[] + while left < right + partition + if mid < k + left = mid + 1 + elif mid > k + right = mid - 1 + else + left = right + . + . + res = list[k] . proc median . list[] res . - h = len list[] div 2 + 1 - call quickselect h list[] res - if len list[] mod 2 = 0 - call quickselect h - 1 list[] h - res = (res + h) / 2 - . + h = len list[] div 2 + 1 + quickselect h list[] res + if len list[] mod 2 = 0 + quickselect h - 1 list[] h + res = (res + h) / 2 + . . test[] = [ 4.1 5.6 7.2 1.7 9.3 4.4 3.2 ] -call median test[] med +median test[] med print med test[] = [ 4.1 7.2 1.7 9.3 4.4 3.2 ] -call median test[] med +median test[] med print med diff --git a/Task/Averages-Median/FutureBasic/averages-median.basic b/Task/Averages-Median/FutureBasic/averages-median.basic new file mode 100644 index 0000000000..48625537ca --- /dev/null +++ b/Task/Averages-Median/FutureBasic/averages-median.basic @@ -0,0 +1,13 @@ +local fn MedianAverage( arguments as CFArrayRef ) as CFStringRef + ExpressionRef expRef = fn ExpressionForFunction( @"median:", @[fn ExpressionForConstantValue( arguments )] ) + CFNumberRef result = fn ExpressionValueWithObject( expRef, NULL, NULL ) + CFStringRef median = fn NumberStringValue( result ) +end fn = median + +print fn MedianAverage( @[@1, @9, @2] ) // 2 +print fn MedianAverage( @[@1, @9, @2, @4] ) // 3 +print fn MedianAverage( @[@5.961475, @2.025856, @7.262835, @1.814272, @2.281911, @4.854716] ) // 3.5683135 +print fn MedianAverage( @[@4.1, @5.6, @7.2, @1.7, @9.3, @4.4, @3.2] ) // 4.4 +print fn MedianAverage( @[@40.12, @860.77, @960.29, @920.13] ) // 890.45 + +HandleEvents diff --git a/Task/Averages-Mode/FutureBasic/averages-mode.basic b/Task/Averages-Mode/FutureBasic/averages-mode.basic new file mode 100644 index 0000000000..064ecb22b5 --- /dev/null +++ b/Task/Averages-Mode/FutureBasic/averages-mode.basic @@ -0,0 +1,13 @@ +local fn ModeAverage( arguments as CFArrayRef ) as CFStringRef + ExpressionRef expRef = fn ExpressionForFunction( @"mode:", @[fn ExpressionForConstantValue( arguments )] ) + CFArrayRef modeArray = fn ExpressionValueWithObject( expRef, NULL, NULL ) + CFNumberRef number + CFMutableStringRef modeStr = fn MutableStringNew + for number in modeArray + MutableStringAppendFormat( modeStr, @"value = %@\n", number ) + next +end fn = modeStr + +print fn ModeAverage( @[@1, @3, @6, @6, @6, @6, @7, @7, @12, @12, @12, @12, @17] ) + +HandleEvents diff --git a/Task/Binary-digits/EasyLang/binary-digits.easy b/Task/Binary-digits/EasyLang/binary-digits.easy index c066642577..f8bc72d15f 100644 --- a/Task/Binary-digits/EasyLang/binary-digits.easy +++ b/Task/Binary-digits/EasyLang/binary-digits.easy @@ -1,16 +1,14 @@ -proc toBinary num . binary$ . - binary$ = "" +func$ bin num . + b$ = "" if num = 0 - binary$ = "0" + b$ = "0" . while num > 0 - binary$ = num mod 2 & binary$ + b$ = num mod 2 & b$ num = num div 2 . + return b$ . -call toBinary 2 binary$ -print binary$ -call toBinary 50 binary$ -print binary$ -call toBinary 9000 binary$ -print binary$ +print bin 2 +print bin 50 +print bin 9000 diff --git a/Task/Binary-search/EasyLang/binary-search.easy b/Task/Binary-search/EasyLang/binary-search.easy index 3863c26562..c9318c5647 100644 --- a/Task/Binary-search/EasyLang/binary-search.easy +++ b/Task/Binary-search/EasyLang/binary-search.easy @@ -1,18 +1,18 @@ -proc bin_search val . a[] res . - low = 1 - high = len a[] - res = 0 - while low <= high and res = 0 - mid = (low + high) div 2 - if a[mid] > val - high = mid - 1 - elif a[mid] < val - low = mid + 1 - else - res = mid - . - . +proc binSearch val . a[] res . + low = 1 + high = len a[] + res = 0 + while low <= high and res = 0 + mid = (low + high) div 2 + if a[mid] > val + high = mid - 1 + elif a[mid] < val + low = mid + 1 + else + res = mid + . + . . a[] = [ 2 4 6 8 9 ] -call bin_search 8 a[] r +binSearch 8 a[] r print r diff --git a/Task/Blum-integer/Maxima/blum-integer.maxima b/Task/Blum-integer/Maxima/blum-integer.maxima new file mode 100644 index 0000000000..6877a3c783 --- /dev/null +++ b/Task/Blum-integer/Maxima/blum-integer.maxima @@ -0,0 +1,15 @@ +/* Predicate functions that checks wether an integer is a Blum integer or not */ +blum_p(n):=lambda([x],length(ifactors(x))=2 and unique(map(second,ifactors(x)))=[1] and mod(ifactors(x)[1][1],4)=3 and mod(ifactors(x)[2][1],4)=3)(n)$ + +/* Function that returns a list of the first len Blum integers */ +blum_count(len):=block( + [i:1,count:0,result:[]], + while count= 360) d -= 360; - const index: usize = @floatToInt(usize, @divFloor(d, 11.25)); + const index: usize = @intFromFloat(@divFloor(d, 11.25)); - // Concatenation to overcome the inability of "zig fmt" to nicely format long arrays. - const points: [32][]const u8 = comptime .{} ++ - .{ "North", "North by east", "North-northeast", "Northeast by north" } ++ - .{ "Northeast", "Northeast by east", "East-northeast", "East by north" } ++ - .{ "East", "East by south", "East-southeast", "Southeast by east" } ++ - .{ "Southeast", "Southeast by south", "South-southeast", "South by east" } ++ - .{ "South", "South by west", "South-southwest", "Southwest by south" } ++ - .{ "Southwest", "Southwest by west", "West-southwest", "West by south" } ++ - .{ "West", "West by north", "West-northwest", "Northwest by west" } ++ - .{ "Northwest", "Northwest by north", "North-northwest", "North by west" }; + const points: [32][]const u8 = comptime .{ + "North", "North by east", "North-northeast", "Northeast by north", + "Northeast", "Northeast by east", "East-northeast", "East by north", + "East", "East by south", "East-southeast", "Southeast by east", + "Southeast", "Southeast by south", "South-southeast", "South by east", + "South", "South by west", "South-southwest", "Southwest by south", + "Southwest", "Southwest by west", "West-southwest", "West by south", + "West", "West by north", "West-northwest", "Northwest by west", + "Northwest", "Northwest by north", "North-northwest", "North by west", + }; return points[index]; } diff --git a/Task/Box-the-compass/Zig/box-the-compass-3.zig b/Task/Box-the-compass/Zig/box-the-compass-3.zig index 6e78fb4022..b6f2b3d30b 100644 --- a/Task/Box-the-compass/Zig/box-the-compass-3.zig +++ b/Task/Box-the-compass/Zig/box-the-compass-3.zig @@ -1,16 +1,16 @@ pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); - _ = try stdout.print("Index Heading Compass point\n", .{}); + try stdout.print("Index Heading Compass point\n", .{}); for (0..33) |i| { - var heading = @intToFloat(f32, i) * 11.25; + var heading = @as(f32, @floatFromInt(i)) * 11.25; heading += switch (i % 3) { 1 => 5.62, 2 => -5.62, else => 0, }; const index = i % 32 + 1; - _ = try stdout.print(" {d:2} {d:>6.2}° {s}\n", .{ index, heading, degreesToCompassPoint(heading) }); + try stdout.print(" {d:2} {d:>6.2}° {s}\n", .{ index, heading, degreesToCompassPoint(heading) }); } } diff --git a/Task/Brazilian-numbers/EasyLang/brazilian-numbers.easy b/Task/Brazilian-numbers/EasyLang/brazilian-numbers.easy index bda8457dfd..7fe5b6cc1a 100644 --- a/Task/Brazilian-numbers/EasyLang/brazilian-numbers.easy +++ b/Task/Brazilian-numbers/EasyLang/brazilian-numbers.easy @@ -1,56 +1,46 @@ -proc sameDigits n b . r . - r = 1 +func sameDigits n b . f = n mod b repeat n = n div b until n = 0 if n mod b <> f - r = 0 - break 1 + return 0 . . + return 1 . -proc isBrazilian7 n . r . +func isBrazilian7 n . # n >= 7 - r = 0 if n mod 2 = 0 - r = 1 - break 1 + return 1 . for b = 2 to n - 2 - call sameDigits n b h - if h = 1 - r = 1 - break 2 + if sameDigits n b = 1 + return 1 . . + return 0 . -proc isPrime4 n . r . - # n >= 4 - r = 0 - if n mod 2 = 0 or n mod 3 = 0 - break 1 +func prime n . + if n mod 2 = 0 and n > 2 + return 0 . - d = 5 - while d * d <= n - if n mod d = 0 - break 2 + i = 3 + sq = sqrt n + while i <= sq + if n mod i = 0 + return 0 . - d += 2 - if n mod d = 0 - break 2 - . - d += 4 + i += 2 . - r = 1 + return 1 . for kind$ in [ "" "odd" "prime" ] print "First 20 " & kind$ & " Brazilian numbers:" n = 7 cnt = 1 while cnt <= 20 - call isBrazilian7 n r - if r = 1 + if isBrazilian7 n = 1 write n & " " cnt += 1 . @@ -61,8 +51,7 @@ for kind$ in [ "" "odd" "prime" ] else repeat n += 2 - call isPrime4 n r - until r = 1 + until prime n = 1 . . . diff --git a/Task/Bulls-and-cows-Player/ALGOL-68/bulls-and-cows-player.alg b/Task/Bulls-and-cows-Player/ALGOL-68/bulls-and-cows-player.alg new file mode 100644 index 0000000000..d74f46ec5a --- /dev/null +++ b/Task/Bulls-and-cows-Player/ALGOL-68/bulls-and-cows-player.alg @@ -0,0 +1,64 @@ +# This breaks a unique code of `n' pegs and `m' colours you think of. # + +INT pegs = 4, colours = 6; + +MODE LIST = FLEX [1 : 0] COMBINATION, + COMBINATION = [pegs] COLOUR, + COLOUR = INT; + +OP +:= = (REF LIST u, COMBINATION v) REF LIST: + # Add one combination to a list. # + ([UPB u + 1] COMBINATION w; w[ : UPB u] := u; w[UPB w] := v; u := w); + +PROC gen = (REF COMBINATION part, INT peg) VOID: + # Generate all unique [colours!/(colours-pegs)!] combinations. # + IF peg > pegs + THEN all combs +:= part + ELSE FOR i TO colours + DO IF BOOL unique := TRUE; + FOR j TO peg - 1 WHILE unique + DO unique := part[j] ~= i + OD; + unique + THEN part[peg] := i; + gen (part, peg + 1) + FI + OD + FI; + +LIST all combs; +gen (LOC COMBINATION, 1); + +PROC break code = (LIST sieved) VOID: + # Present a trial and sieve the list with the entered score. # + CASE UPB sieved + 1 + IN # No elements. # printf ($l"Inconsistent scores"l$), + # One element. # printf (($l"Solution is "4(xd)l$, sieved[1])) + OUT printf (($l4(dx)$, sieved[1])); + # Read the score as a sequence of "c" and "b". # + INT col ok := 0, pos ok := 0, STRING z := ""; + WHILE z = "" + DO read ((z, new line)) + OD; + FOR i TO UPB z + DO (z[i] = "c" | col ok |: z[i] = "b" | pos ok) +:= 1 + OD; + (pos ok = pegs | stop); + # Survivors are combinations with score as entered. # + LIST survivors; + FOR i FROM 2 TO UPB sieved + DO INT col ok i := 0, pos ok i := 0; + FOR u TO pegs + DO FOR v TO pegs + DO IF sieved[1][u] = sieved[i][v] + THEN (u = v | pos ok i | col ok i) +:= 1 + FI + OD + OD; + (col ok = col ok i AND pos ok = pos ok i | survivors +:= sieved[i]) + OD; + # Solution must be among the survivors. # + break code (survivors) + ESAC; + +break code (all combs) diff --git a/Task/Calculating-the-value-of-e/EasyLang/calculating-the-value-of-e.easy b/Task/Calculating-the-value-of-e/EasyLang/calculating-the-value-of-e.easy index a233fa0c49..eef33599f1 100644 --- a/Task/Calculating-the-value-of-e/EasyLang/calculating-the-value-of-e.easy +++ b/Task/Calculating-the-value-of-e/EasyLang/calculating-the-value-of-e.easy @@ -1,4 +1,4 @@ -numfmt 0 5 +numfmt 5 0 fact = 1 n = 2 e = 2 diff --git a/Task/Calkin-Wilf-sequence/00-TASK.txt b/Task/Calkin-Wilf-sequence/00-TASK.txt index bb081ab778..b95cba45ba 100644 --- a/Task/Calkin-Wilf-sequence/00-TASK.txt +++ b/Task/Calkin-Wilf-sequence/00-TASK.txt @@ -26,6 +26,8 @@ The fraction   '''9/4'''   has odd continued fraction representation & ;Task part 2: * Find the position of the number   '''83116''''''/''''''51639'''   in the Calkin-Wilf sequence. +;Related tasks: +:*   [[Fusc sequence]]. ;See also: * Wikipedia entry: [[wp:Calkin%E2%80%93Wilf_tree|Calkin-Wilf tree]] diff --git a/Task/Calkin-Wilf-sequence/Maxima/calkin-wilf-sequence.maxima b/Task/Calkin-Wilf-sequence/Maxima/calkin-wilf-sequence.maxima index 56c2a7934e..3f2b19f793 100644 --- a/Task/Calkin-Wilf-sequence/Maxima/calkin-wilf-sequence.maxima +++ b/Task/Calkin-Wilf-sequence/Maxima/calkin-wilf-sequence.maxima @@ -12,7 +12,7 @@ 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)), + 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)), /* decoding part begins here */ apply(append,%%), apply("+",makelist(2^i,i,0,length(%%)-1)*reverse(%%)))$ diff --git a/Task/Call-a-function/EasyLang/call-a-function.easy b/Task/Call-a-function/EasyLang/call-a-function.easy index c241ec1909..68e19af6c4 100644 --- a/Task/Call-a-function/EasyLang/call-a-function.easy +++ b/Task/Call-a-function/EasyLang/call-a-function.easy @@ -1,3 +1,18 @@ -call somesubr # call a subroutine -call someproc1 # call a procedure with no arguments -call someproc2 arg1 arg2 res # call a procedure with in-arguments and an inout-argument +func sqr n . + return n * n +. +sqr 3 +# +proc divmod a b . q r . + q = a div b + r = a mod b +. +divmod 11 3 q r +print q & " " & r +# +subr sqr2 + a = a * a +. +a = 5 +sqr2 +print a diff --git a/Task/Call-an-object-method/Zig/call-an-object-method.zig b/Task/Call-an-object-method/Zig/call-an-object-method.zig index 41556376f9..5a2009f4b0 100644 --- a/Task/Call-an-object-method/Zig/call-an-object-method.zig +++ b/Task/Call-an-object-method/Zig/call-an-object-method.zig @@ -1,4 +1,4 @@ -const assert = @import("std").debug.assert; +const testing = @import("std").testing; pub const ID = struct { name: []const u8, @@ -28,6 +28,7 @@ test "call an object method" { .age = 20, }; - assert(person1.getAge() == 18); - assert(ID.getAge(person2) == 20); + // test getAge() method call + try testing.expectEqual(@as(u7, 18), person1.getAge()); + try testing.expectEqual(@as(u7, 20), ID.getAge(person2)); } diff --git a/Task/Catalan-numbers-Pascals-triangle/EasyLang/catalan-numbers-pascals-triangle.easy b/Task/Catalan-numbers-Pascals-triangle/EasyLang/catalan-numbers-pascals-triangle.easy new file mode 100644 index 0000000000..173d2c018e --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/EasyLang/catalan-numbers-pascals-triangle.easy @@ -0,0 +1,11 @@ +print 1 +for n = 2 to 15 + num = 1 + den = 1 + for k = 2 to n + num *= n + k + den *= k + cat = num / den + . + print cat +. diff --git a/Task/Catalan-numbers-Pascals-triangle/Zig/catalan-numbers-pascals-triangle.zig b/Task/Catalan-numbers-Pascals-triangle/Zig/catalan-numbers-pascals-triangle.zig index 2ba220bc07..326e414c5c 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Zig/catalan-numbers-pascals-triangle.zig +++ b/Task/Catalan-numbers-Pascals-triangle/Zig/catalan-numbers-pascals-triangle.zig @@ -1,7 +1,8 @@ const std = @import("std"); -const stdout = std.io.getStdOut().outStream(); pub fn main() !void { + const stdout = std.io.getStdOut().writer(); + var n: u32 = 1; while (n <= 15) : (n += 1) { const row = binomial(n * 2).?; @@ -20,6 +21,7 @@ pub fn binomial(n: u32) ?[]const u64 { const rmax = 68; +// evaluated and created at compile-time const pascal = build: { @setEvalBranchQuota(100_000); var coefficients: [(rmax * (rmax + 1)) / 2]u64 = undefined; diff --git a/Task/Catalan-numbers/EasyLang/catalan-numbers.easy b/Task/Catalan-numbers/EasyLang/catalan-numbers.easy index 09b1b73a08..6ec582b534 100644 --- a/Task/Catalan-numbers/EasyLang/catalan-numbers.easy +++ b/Task/Catalan-numbers/EasyLang/catalan-numbers.easy @@ -1,12 +1,9 @@ -proc catalan n . ans . - if n = 0 - ans = 1 - else - call catalan n - 1 h - ans = 2 * (2 * n - 1) * h div (1 + n) - . +func catalan n . + if n = 0 + return 1 + . + return 2 * (2 * n - 1) * catalan (n - 1) div (1 + n) . for i = 0 to 14 - call catalan i h - print h + print catalan i . diff --git a/Task/Chaocipher/QBasic/chaocipher.basic b/Task/Chaocipher/QBasic/chaocipher.basic new file mode 100644 index 0000000000..25bdb7945c --- /dev/null +++ b/Task/Chaocipher/QBasic/chaocipher.basic @@ -0,0 +1,142 @@ +DECLARE FUNCTION AlphaLeft$ (ct$, pt$, CharPos!) +DECLARE FUNCTION AlphaRight$ (ct$, pt$, CharPos!) +DECLARE FUNCTION Decode$ (Text$, ct$, pt$) +DECLARE FUNCTION Encode$ (Text$, ct$, pt$) + +CLS + +' 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 + +' Start of Main Code + +' LEFT (Cipher Text$): HXUCZVAMDSLKPEFJRIGTWOBNYQ +tLeft$ = "HXUCZVAMDSLKPEFJRIGTWOBNYQ" + +' RIGHT (Plain Text$): PTLNBQDEOYSFAVZKGJRIHWXUMC +tRight$ = "PTLNBQDEOYSFAVZKGJRIHWXUMC" + +' Cipher Message (Used to verify a good encoding) +cText$ = "OAHQHCNYNXTSZJRRHJBYHQKSOUJY" + +' Plain Text$ Message +pText$ = "WELLDONEISBETTERTHANWELLSAID" +PRINT " Plain Text$: "; pText$ +PRINT + +ctLeft$ = tLeft$ +ptRight$ = tRight$ + +' Final Cipher Text$ +eText$ = Encode$(pText$, ctLeft$, ptRight$) +PRINT " Cipher Text$: "; eText$ +PRINT + +IF eText$ = cText$ THEN PRINT "Successful" ELSE PRINT "Failed" + +ctLeft$ = tLeft$ +ptRight$ = tRight$ +dText$ = Decode$(eText$, ctLeft$, ptRight$) +PRINT +PRINT " Plain Text$: "; dText$ +PRINT + +IF dText$ = pText$ THEN PRINT "Successful" ELSE PRINT "Failed" +END + +' Left Alphabet +FUNCTION AlphaLeft$ (ct$, pt$, CharPos) + 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$" + + 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$, pt$, CharPos) + 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$". + + 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 Decode$ (Text$, ct$, pt$) + tStr$ = "" + + FOR t = 1 TO LEN(Text$) + Char$ = MID$(Text$, t, 1) + CharPos = INSTR(ct$, Char$) + + ct$ = AlphaLeft$(ct$, pt$, CharPos) + pt$ = AlphaRight$(ct$, pt$, CharPos) + + tStr$ = tStr$ + RIGHT$(pt$, 1) + NEXT + + Decode$ = tStr$ +END FUNCTION + +FUNCTION Encode$ (Text$, ct$, pt$) + tStr$ = "" + + FOR t = 1 TO LEN(Text$) + Char$ = MID$(Text$, t, 1) + CharPos = INSTR(pt$, Char$) + + ct$ = AlphaLeft$(ct$, pt$, CharPos) + pt$ = AlphaRight$(ct$, pt$, CharPos) + + tStr$ = tStr$ + LEFT$(ct$, 1) + NEXT + + Encode$ = tStr$ +END FUNCTION diff --git a/Task/Character-codes/Zig/character-codes.zig b/Task/Character-codes/Zig/character-codes.zig index 59a034168e..697afa9b08 100644 --- a/Task/Character-codes/Zig/character-codes.zig +++ b/Task/Character-codes/Zig/character-codes.zig @@ -1,31 +1,38 @@ const std = @import("std"); - -const debug = std.debug; const unicode = std.unicode; -test "character codes" { - debug.warn("\n", .{}); +pub fn main() !void { + const stdout = std.io.getStdOut().writer(); - // Zig's string is just an array of bytes (u8). - const message = "ABCabc"; - - for (message) |val| { - debug.warn(" '{c}' code: {} [hexa: 0x{x}]\n", .{ val, val, val }); - } + try characterAsciiCodes(stdout); + try characterUnicodeCodes(stdout); } -test "character (uni)codes" { - debug.warn("\n", .{}); +fn characterAsciiCodes(writer: anytype) !void { + try writer.writeAll("Sample ASCII characters and codes:\n"); - const message = "あいうえお"; + // Zig's string is just an array of bytes (u8). + const message: []const u8 = "ABCabc"; + + for (message) |val| { + try writer.print(" '{c}' code: {d} [hexa: 0x{x}]\n", .{ val, val, val }); + } + try writer.writeByte('\n'); +} + +fn characterUnicodeCodes(writer: anytype) !void { + try writer.writeAll("Sample Unicode characters and codes:\n"); + + const message: []const u8 = "あいうえお"; const utf8_view = unicode.Utf8View.initUnchecked(message); var iter = utf8_view.iterator(); while (iter.nextCodepoint()) |val| { var array: [4]u8 = undefined; - var slice = array[0..try unicode.utf8Encode(val, &array)]; + const slice = array[0..try unicode.utf8Encode(val, &array)]; - debug.warn(" '{}' code: {} [hexa: U+{x}]\n", .{ slice, val, val }); + try writer.print(" '{s}' code: {d} [hexa: U+{x}]\n", .{ slice, val, val }); } + try writer.writeByte('\n'); } diff --git a/Task/Chinese-remainder-theorem/EasyLang/chinese-remainder-theorem.easy b/Task/Chinese-remainder-theorem/EasyLang/chinese-remainder-theorem.easy index f2988acc91..bd49a7065b 100644 --- a/Task/Chinese-remainder-theorem/EasyLang/chinese-remainder-theorem.easy +++ b/Task/Chinese-remainder-theorem/EasyLang/chinese-remainder-theorem.easy @@ -1,35 +1,35 @@ -proc mul_inv a b . x1 . - b0 = b - x1 = 1 - if b <> 1 - while a > 1 - q = a div b - t = b - b = a mod b - a = t - t = x0 - x0 = x1 - q * x0 - x1 = t - . - if x1 < 0 - x1 += b0 - . - . +func mul_inv a b . + b0 = b + x1 = 1 + if b <> 1 + while a > 1 + q = a div b + t = b + b = a mod b + a = t + t = x0 + x0 = x1 - q * x0 + x1 = t + . + if x1 < 0 + x1 += b0 + . + . + return x1 . proc remainder . n[] a[] r . - prod = 1 - sum = 0 - for i = 1 to len n[] - prod *= n[i] - . - for i = 1 to len n[] - p = prod / n[i] - call mul_inv p n[i] h - sum += a[i] * h * p - r = sum mod prod - . + prod = 1 + sum = 0 + for i = 1 to len n[] + prod *= n[i] + . + for i = 1 to len n[] + p = prod / n[i] + sum += a[i] * (mul_inv p n[i]) * p + r = sum mod prod + . . n[] = [ 3 5 7 ] a[] = [ 2 3 2 ] -call remainder n[] a[] h +remainder n[] a[] h print h diff --git a/Task/Chinese-zodiac/Quackery/chinese-zodiac.quackery b/Task/Chinese-zodiac/Quackery/chinese-zodiac.quackery new file mode 100644 index 0000000000..71a940951e --- /dev/null +++ b/Task/Chinese-zodiac/Quackery/chinese-zodiac.quackery @@ -0,0 +1,21 @@ + [ dup echo + say " is the year of the " + 4 - dup 10 mod 2 / + [ table $ "Wood" $ "Fire" $ "Earth" + $ "Metal" $ "Water" ] + do echo$ + sp + dup 12 mod + [ table + $ "Rat" $ "Ox" $ "Tiger" $ "Rabbit" + $ "Dragon" $ "Snake" $ "Horse" $ "Goat" + $ "Monkey" $ "Rooster" $ "Dog" $ "Pig" ] + do echo$ + say " (" + 2 mod + [ table $ "yang" $ "yin" ] + do echo$ + say ")." cr ] is zodiac ( $ --> ) + + ' [ 1935 1938 1968 1972 1976 1984 1985 2017 ] + witheach zodiac diff --git a/Task/Chowla-numbers/EasyLang/chowla-numbers.easy b/Task/Chowla-numbers/EasyLang/chowla-numbers.easy index 829ae64303..612642b535 100644 --- a/Task/Chowla-numbers/EasyLang/chowla-numbers.easy +++ b/Task/Chowla-numbers/EasyLang/chowla-numbers.easy @@ -1,90 +1,88 @@ -proc chowla n . sum . - sum = 0 - i = 2 - while i * i <= n - if n mod i = 0 - j = n div i - if i = j - sum += i - else - sum += i + j +fastfunc chowla n . + sum = 0 + i = 2 + while i * i <= n + if n mod i = 0 + j = n div i + if i = j + sum += i + else + sum += i + j + . . - . - i += 1 - . + i += 1 + . + return sum . proc sieve . c[] . - i = 3 - while i * 3 <= len c[] - if c[i] = 0 - call chowla i h - if h = 0 - j = 3 * i - while j <= len c[] - c[j] = 1 - j += 2 * i - . + i = 3 + while i * 3 <= len c[] + if c[i] = 0 + if chowla i = 0 + j = 3 * i + while j <= len c[] + c[j] = 1 + j += 2 * i + . + . . - . - i += 2 - . + i += 2 + . . proc commatize n . s$ . - s$[] = strchars n - s$ = "" - l = len s$[] - for i = 1 to len s$[] - if i > 1 and l mod 3 = 0 - s$ &= "," - . - l -= 1 - s$ &= s$[i] - . + s$[] = strchars n + s$ = "" + l = len s$[] + for i = 1 to len s$[] + if i > 1 and l mod 3 = 0 + s$ &= "," + . + l -= 1 + s$ &= s$[i] + . . print "chowla number from 1 to 37" for i = 1 to 37 - call chowla i h - print " " & i & ": " & h + print " " & i & ": " & chowla i . proc main . . - print "" - len c[] 10000000 - count = 1 - call sieve c[] - power = 100 - i = 3 - while i <= len c[] - if c[i] = 0 - count += 1 - . - if i = power - 1 - call commatize power p$ - call commatize count c$ - print "There are " & c$ & " primes up to " & p$ - power *= 10 - . - i += 2 - . - print "" - limit = 35000000 - count = 0 - i = 2 - k = 2 - kk = 3 - repeat - p = k * kk - until p > limit - call chowla p h - if h = p - 1 - call commatize p s$ - print s$ & " is a perfect number" - count += 1 - . - k = kk + 1 - kk += k - i += 1 - . - call commatize limit s$ - print "There are " & count & " perfect mumbers up to " & s$ + print "" + len c[] 10000000 + count = 1 + sieve c[] + power = 100 + i = 3 + while i <= len c[] + if c[i] = 0 + count += 1 + . + if i = power - 1 + commatize power p$ + commatize count c$ + print "There are " & c$ & " primes up to " & p$ + power *= 10 + . + i += 2 + . + print "" + limit = 35000000 + count = 0 + i = 2 + k = 2 + kk = 3 + repeat + p = k * kk + until p > limit + if chowla p = p - 1 + commatize p s$ + print s$ & " is a perfect number" + count += 1 + . + k = kk + 1 + kk += k + i += 1 + . + commatize limit s$ + print "There are " & count & " perfect mumbers up to " & s$ . -call main +main diff --git a/Task/Church-numerals/Acornsoft-Lisp/church-numerals.lisp b/Task/Church-numerals/Acornsoft-Lisp/church-numerals.lisp new file mode 100644 index 0000000000..1a5aa882c5 --- /dev/null +++ b/Task/Church-numerals/Acornsoft-Lisp/church-numerals.lisp @@ -0,0 +1,38 @@ +(setq zero '(lambda (f x) x)) + +(defun succ (n) + (freeze '(n) '(lambda (f x) (f (n f x))))) + +(defun add (m n) + (freeze '(m n) '(lambda (f x) (m f (n f x))))) + +(defun mul (m n) + (n (freeze '(m) '(lambda (sum) (add m sum))) zero)) + +(defun pow (m n) + (n (freeze '(m) '(lambda (product) (mul m product))) one)) + +(defun church (i) + (cond ((zerop i) zero) + (t (succ (church (sub1 i)))))) + +(defun unchurch (n) + (n add1 0)) + +(setq one (succ zero)) +(setq two (succ one)) +(setq three (succ two)) +(setq four (succ three)) + +(defun show (example) + (prin example) + (princ '! =>! ) + (print (unchurch (eval example)))) + +(defun examples () + (show '(church 3)) + (show '(add three four)) + (show '(mul three four)) + (show '(pow three four)) + (show '(pow four three)) + (show '(pow (pow two two) (add two one)))) diff --git a/Task/Church-numerals/Common-Lisp/church-numerals-1.lisp b/Task/Church-numerals/Common-Lisp/church-numerals-1.lisp new file mode 100644 index 0000000000..16d61e3a89 --- /dev/null +++ b/Task/Church-numerals/Common-Lisp/church-numerals-1.lisp @@ -0,0 +1,34 @@ +(defvar zero (lambda (f x) x)) + +(defun succ (n) (lambda (f x) (funcall f (funcall n f x)))) + +(defun plus (m n) + (lambda (f x) (funcall m f (funcall n f x)))) + +(defun times (m n) + (funcall n (lambda (sum) (plus m sum)) zero)) + +(defun power (m n) + (funcall n (lambda (product) (times m product)) one)) + +(defun church (i) ; int -> Church + (if (zerop i) zero (succ (church (1- i))))) + +(defun unchurch (n) ; Church -> int + (funcall n #'1+ 0)) + +(defun show (example) + (format t "~(~S => ~S~)~%" + example (unchurch (eval example)))) + +(defvar one (succ zero)) +(defvar two (succ one)) +(defvar three (succ two)) +(defvar four (succ three)) + +(show '(church 3)) +(show '(plus three four)) +(show '(times three four)) +(show '(power three four)) +(show '(power four three)) +(show '(power (power two two) (plus two one))) diff --git a/Task/Church-numerals/Common-Lisp/church-numerals-2.lisp b/Task/Church-numerals/Common-Lisp/church-numerals-2.lisp new file mode 100644 index 0000000000..a48017a748 --- /dev/null +++ b/Task/Church-numerals/Common-Lisp/church-numerals-2.lisp @@ -0,0 +1,21 @@ +(defvar zero (lambda (f) (lambda (x) x))) + +(defun succ (n) (lambda (f) (compose f (funcall n f)))) + +(defun plus (m n) + (lambda (f) (compose (funcall m f) (funcall n f)))) + +(defun times (m n) + (compose m n)) + +(defun power (m n) + (funcall n m)) + +(defun compose (f g) + (lambda (x) (funcall f (funcall g x)))) + +(defun church (i) ; int -> Church + (if (zerop i) zero (succ (church (1- i))))) + +(defun unchurch (n) ; Church -> int + (funcall (funcall n #'1+) 0)) diff --git a/Task/Church-numerals/Common-Lisp/church-numerals-3.lisp b/Task/Church-numerals/Common-Lisp/church-numerals-3.lisp new file mode 100644 index 0000000000..d4ea88113f --- /dev/null +++ b/Task/Church-numerals/Common-Lisp/church-numerals-3.lisp @@ -0,0 +1,10 @@ +(defun pred (n) + (flet ((value (v) (lambda (h) (funcall h v))) + (extract (k) (funcall k (lambda (u) u)))) + (lambda (f x) + (let ((inc (lambda (g) (value (funcall g f)))) + (const (lambda (u) x))) + (extract (funcall n inc const)))))) + +(defun minus (m n) + (funcall n #'pred m)) diff --git a/Task/Church-numerals/Common-Lisp/church-numerals-4.lisp b/Task/Church-numerals/Common-Lisp/church-numerals-4.lisp new file mode 100644 index 0000000000..129936e655 --- /dev/null +++ b/Task/Church-numerals/Common-Lisp/church-numerals-4.lisp @@ -0,0 +1,5 @@ +(defmacro church-if (test then else) + `(funcall ,test (lambda () ,then) (lambda () ,else))) + +(defvar true (lambda (f g) (funcall f))) +(defvar false (lambda (f g) (funcall g))) diff --git a/Task/Church-numerals/Common-Lisp/church-numerals-5.lisp b/Task/Church-numerals/Common-Lisp/church-numerals-5.lisp new file mode 100644 index 0000000000..1c209d0e91 --- /dev/null +++ b/Task/Church-numerals/Common-Lisp/church-numerals-5.lisp @@ -0,0 +1,11 @@ +(defun is-zero (n) + (funcall n (lambda (x) false) true)) + +(defun divide (m n) + (divide1 (succ m) n)) + +(defun divide1 (m n) + (let ((d (minus m n))) + (church-if (is-zero d) + zero + (succ (divide1 d n))))) diff --git a/Task/Church-numerals/Common-Lisp/church-numerals-6.lisp b/Task/Church-numerals/Common-Lisp/church-numerals-6.lisp new file mode 100644 index 0000000000..cd635c51d0 --- /dev/null +++ b/Task/Church-numerals/Common-Lisp/church-numerals-6.lisp @@ -0,0 +1,4 @@ +(show '(pred four)) +(show '(minus (church 11) three)) +(show '(divide (church 11) three)) +(show '(divide (church 12) three)) diff --git a/Task/Church-numerals/Common-Lisp/church-numerals-7.lisp b/Task/Church-numerals/Common-Lisp/church-numerals-7.lisp new file mode 100644 index 0000000000..3086f0efc7 --- /dev/null +++ b/Task/Church-numerals/Common-Lisp/church-numerals-7.lisp @@ -0,0 +1,18 @@ +(defun pred (n) + (flet ((value (v) (lambda (h) (funcall h v))) + (extract (k) (funcall k (lambda (u) u)))) + (lambda (f) + (lambda (x) + (let ((inc (lambda (g) (value (funcall g f)))) + (const (lambda (u) x))) + (extract (funcall (funcall n inc) const))))))) + +(defun minus (m n) + (funcall (funcall n #'pred) m)) + +... + +(defun is-zero (n) + (funcall (funcall n (lambda (x) false)) true)) + +... diff --git a/Task/Circular-primes/EasyLang/circular-primes.easy b/Task/Circular-primes/EasyLang/circular-primes.easy new file mode 100644 index 0000000000..3cc63fb8ed --- /dev/null +++ b/Task/Circular-primes/EasyLang/circular-primes.easy @@ -0,0 +1,44 @@ +fastfunc prime n . + if n mod 2 = 0 and n > 2 + return 0 + . + i = 3 + sq = sqrt n + while i <= sq + if n mod i = 0 + return 0 + . + i += 2 + . + return 1 +. +func cycle n . + m = n + p = 1 + while m >= 10 + p *= 10 + m = m div 10 + . + return m + n mod p * 10 +. +func circprime p . + if prime p = 0 + return 0 + . + p2 = cycle p + while p2 <> p + if p2 < p or prime p2 = 0 + return 0 + . + p2 = cycle p2 + . + return 1 +. +p = 2 +while count < 19 + if circprime p = 1 + print p + count += 1 + . + p += 1 +. diff --git a/Task/Circular-primes/Zig/circular-primes.zig b/Task/Circular-primes/Zig/circular-primes.zig index e277acafe9..6a0d79b702 100644 --- a/Task/Circular-primes/Zig/circular-primes.zig +++ b/Task/Circular-primes/Zig/circular-primes.zig @@ -1,15 +1,18 @@ const std = @import("std"); const math = std.math; const heap = std.heap; -const stdout = std.io.getStdOut().writer(); pub fn main() !void { var arena = heap.ArenaAllocator.init(heap.page_allocator); defer arena.deinit(); - var candidates = std.PriorityQueue(u32).init(&arena.allocator, u32cmp); + const allocator = arena.allocator(); + + var candidates = std.PriorityQueue(u32, void, u32cmp).init(allocator, {}); defer candidates.deinit(); + const stdout = std.io.getStdOut().writer(); + try stdout.print("The circular primes are:\n", .{}); try stdout.print("{:10}" ** 4, .{ 2, 3, 5, 7 }); @@ -33,19 +36,19 @@ pub fn main() !void { try stdout.print("\n", .{}); } -fn u32cmp(a: u32, b: u32) math.Order { +fn u32cmp(_: void, a: u32, b: u32) math.Order { return math.order(a, b); } fn circular(n0: u32) bool { - if (!isprime(n0)) + if (!isPrime(n0)) return false else { var n = n0; - var d = @floatToInt(u32, @log10(@intToFloat(f32, n))); + var d: u32 = @intFromFloat(@log10(@as(f32, @floatFromInt(n)))); return while (d > 0) : (d -= 1) { n = rotate(n); - if (n < n0 or !isprime(n)) + if (n < n0 or !isPrime(n)) break false; } else true; } @@ -55,13 +58,13 @@ fn rotate(n: u32) u32 { if (n == 0) return 0 else { - const d = @floatToInt(u32, @log10(@intToFloat(f32, n))); // digit count - 1 + const d: u32 = @intFromFloat(@log10(@as(f32, @floatFromInt(n)))); // digit count - 1 const m = math.pow(u32, 10, d); return (n % m) * 10 + n / m; } } -fn isprime(n: u32) bool { +fn isPrime(n: u32) bool { if (n < 2) return false; diff --git a/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-1.lisp b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-1.lisp new file mode 100644 index 0000000000..908c30abb1 --- /dev/null +++ b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-1.lisp @@ -0,0 +1 @@ +(freeze '(a b) '(lambda (c) (list a b c))) diff --git a/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-2.lisp b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-2.lisp new file mode 100644 index 0000000000..cf3944b229 --- /dev/null +++ b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-2.lisp @@ -0,0 +1,3 @@ +(lambda (c) + ((lambda ((a . 1) (b . 2)) + (list a b c)))) diff --git a/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-3.lisp b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-3.lisp new file mode 100644 index 0000000000..93c6216493 --- /dev/null +++ b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-3.lisp @@ -0,0 +1,2 @@ +( (lambda ((a . 1) (b . 2)) + (list a b c)) ) diff --git a/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-4.lisp b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-4.lisp new file mode 100644 index 0000000000..4fb5bf07ef --- /dev/null +++ b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-4.lisp @@ -0,0 +1,9 @@ +(defun freeze (_fvars_ _lambda-expr_) + (freeze-vars + (mapc cons _fvars_ (mapc eval _fvars_)) + (cadr _lambda-expr_) + (cddr _lambda-expr_))) + +(defun freeze-vars (bindings lvars lbody) + (list 'lambda lvars + (list (cons 'lambda (cons bindings lbody))))) diff --git a/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-5.lisp b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-5.lisp new file mode 100644 index 0000000000..d98729aa44 --- /dev/null +++ b/Task/Closures-Value-capture/Acornsoft-Lisp/closures-value-capture-5.lisp @@ -0,0 +1,9 @@ +(defun range (from to) + (cond ((greaterp from to) '()) + (t (cons from (range (add1 from) to))))) + +(defun example () + (mapc '(lambda (f) (f)) + (mapc '(lambda (i) + (freeze '(i) '(lambda () (times i i)))) + (range 1 10)))) diff --git a/Task/Combinations-with-repetitions/EasyLang/combinations-with-repetitions.easy b/Task/Combinations-with-repetitions/EasyLang/combinations-with-repetitions.easy index 62bd2cbdd8..0e2be62a85 100644 --- a/Task/Combinations-with-repetitions/EasyLang/combinations-with-repetitions.easy +++ b/Task/Combinations-with-repetitions/EasyLang/combinations-with-repetitions.easy @@ -1,20 +1,36 @@ -proc combine pos val . . - if pos > k - call output - else - for i = val to n - result[pos] = i - call combine pos + 1 i - . - . +items$[] = [ "iced" "jam" "plain" ] +n = len items$[] +k = 2 +len result[] k +n_results = 0 +# +proc output . . + n_results += 1 + if len items$[] > 0 + s$ = "" + for i = 1 to k + s$ &= items$[result[i]] & " " + . + print s$ + . . -call combine 1 1 +proc combine pos val . . + if pos > k + output + else + for i = val to n + result[pos] = i + combine pos + 1 i + . + . +. +combine 1 1 # n = 10 k = 3 len result[] k items$[] = [ ] n_results = 0 -call combine 1 1 +combine 1 1 print "" print n_results & " results with 10 donuts" diff --git a/Task/Combinations-with-repetitions/Phix/combinations-with-repetitions-3.phix b/Task/Combinations-with-repetitions/Phix/combinations-with-repetitions-3.phix new file mode 100644 index 0000000000..345317e20b --- /dev/null +++ b/Task/Combinations-with-repetitions/Phix/combinations-with-repetitions-3.phix @@ -0,0 +1,4 @@ +(phixonline)--> + ?join(combinations_with_repetitions("ijp",2),',') + ?length(combinations_with_repetitions(tagset(10),3)) + + ?join(combinations("12345",3),',') + ) + + [] 0 + [ 1+ dup ! + dup dip + [ 1 - isprime if + [ tuck negate join swap ] ] + 1+ isprime if + [ tuck join swap ] + over size 9 > until ] + drop 10 split drop + witheach + [ i^ 1+ + recho say ": " + dup abs tuck recho + 0 < iff + [ say "! - 1 = " -1 ] + else + [ say "! + 1 = " 1 ] + swap ! + echo cr ] diff --git a/Task/Factorial/Acornsoft-Lisp/factorial-1.lisp b/Task/Factorial/Acornsoft-Lisp/factorial-1.lisp new file mode 100644 index 0000000000..e188cec74f --- /dev/null +++ b/Task/Factorial/Acornsoft-Lisp/factorial-1.lisp @@ -0,0 +1,3 @@ +(defun factorial (n) + (cond ((zerop n) 1) + (t (times n (factorial (sub1 n)))))) diff --git a/Task/Factorial/Acornsoft-Lisp/factorial-2.lisp b/Task/Factorial/Acornsoft-Lisp/factorial-2.lisp new file mode 100644 index 0000000000..85bea1e0b4 --- /dev/null +++ b/Task/Factorial/Acornsoft-Lisp/factorial-2.lisp @@ -0,0 +1,5 @@ +(defun factorial (n (result . 1)) + (loop + (until (zerop n) result) + (setq result (times n result)) + (setq n (sub1 n)))) diff --git a/Task/Factorial/EasyLang/factorial.easy b/Task/Factorial/EasyLang/factorial.easy index 986d3ce909..1ad66bdb70 100644 --- a/Task/Factorial/EasyLang/factorial.easy +++ b/Task/Factorial/EasyLang/factorial.easy @@ -1,8 +1,8 @@ -proc factorial n . r . - r = 1 - for i = 2 to n - r *= i - . +func factorial n . + r = 1 + for i = 2 to n + r *= i + . + return r . -call factorial 7 r -print r +print factorial 7 diff --git a/Task/Factors-of-an-integer/Quackery/factors-of-an-integer.quackery b/Task/Factors-of-an-integer/Quackery/factors-of-an-integer.quackery index cee3347982..82e9ede02d 100644 --- a/Task/Factors-of-an-integer/Quackery/factors-of-an-integer.quackery +++ b/Task/Factors-of-an-integer/Quackery/factors-of-an-integer.quackery @@ -1,25 +1,12 @@ - [ 1 - [ 2dup < not while - 2 << again ] - 0 - [ over 1 > while - dip [ 2 >> 2dup - ] - dup 1 >> unrot - - dup 0 < iff drop - else - [ 2swap nip - rot over + ] - again ] nip swap ] is isqrt ( n --> n n ) - [ [] swap - dup isqrt 0 = dip + dup sqrt 0 = dip [ times [ dup i^ 1+ /mod iff drop done rot join i^ 1+ join swap ] - drop - dup size 2 / split ] + drop + dup size 2 / split ] if [ -1 split drop ] swap join ] is factors ( n --> [ ) diff --git a/Task/Fairshare-between-two-and-more/EasyLang/fairshare-between-two-and-more.easy b/Task/Fairshare-between-two-and-more/EasyLang/fairshare-between-two-and-more.easy index 978264c4cb..df7b39a402 100644 --- a/Task/Fairshare-between-two-and-more/EasyLang/fairshare-between-two-and-more.easy +++ b/Task/Fairshare-between-two-and-more/EasyLang/fairshare-between-two-and-more.easy @@ -1,20 +1,19 @@ -proc fairshare ind base . r . - r = 0 +func fairshare ind base . while ind > 0 - r = r + ind mod base + r += ind mod base ind = ind div base . r = r mod base + return r . proc sequence n base . . write base & ": " for ind range0 n - call fairshare ind base r - write r & " " + write (fairshare ind base) & " " . print "" . -call sequence 25 2 -call sequence 25 3 -call sequence 25 5 -call sequence 25 11 +sequence 25 2 +sequence 25 3 +sequence 25 5 +sequence 25 11 diff --git a/Task/Farey-sequence/EasyLang/farey-sequence.easy b/Task/Farey-sequence/EasyLang/farey-sequence.easy new file mode 100644 index 0000000000..a16f529e1c --- /dev/null +++ b/Task/Farey-sequence/EasyLang/farey-sequence.easy @@ -0,0 +1,25 @@ +proc farey n . . + b = 1 ; c = 1 ; d = n + write n & ": " + repeat + if n <= 11 + write " " & a & "/" & b + . + until c > n + k = (n + b) div d + aa = c ; bb = d ; cc = k * c - a ; dd = k * d - b + a = aa ; b = bb ; c = cc ; d = dd + items += 1 + . + if n > 11 + print items & " items" + else + print "" + . +. +for i = 1 to 11 + farey i +. +for i = 100 step 100 to 1000 + farey i +. diff --git a/Task/Farey-sequence/Maxima/farey-sequence.maxima b/Task/Farey-sequence/Maxima/farey-sequence.maxima new file mode 100644 index 0000000000..b2f6a657db --- /dev/null +++ b/Task/Farey-sequence/Maxima/farey-sequence.maxima @@ -0,0 +1,33 @@ +farey(n):=if n=1 then ["0/1","1/1"] else block( + create_list([i,j],i,0,n-1,j,1,n), + map(lambda([x],if x[1]=0 and x[2]#1 then false else if x[1]=x[2] and x[1]#1 then false else if x[1]<=x[2] then x),%%), + delete(false,%%), + unique(map(lambda([x],x[1]/x[2]),%%)), + append(rest(append(["0/1"],rest(%%)),-1),["1/1"]) +)$ + +/* Test cases */ +/* Sequences from order 1 through 11 */ +farey(1); +farey(2); +farey(3); +farey(4); +farey(5); +farey(6); +farey(7); +farey(8); +farey(9); +farey(10); +farey(11); + +/* Length of sequences from order 100 through, 1000 by hundreds */ +length(farey(100)); +length(farey(200)); +length(farey(300)); +length(farey(400)); +length(farey(500)); +length(farey(600)); +length(farey(700)); +length(farey(800)); +length(farey(900)); +length(farey(1000)); diff --git a/Task/Faulhabers-triangle/ALGOL-68/faulhabers-triangle.alg b/Task/Faulhabers-triangle/ALGOL-68/faulhabers-triangle.alg new file mode 100644 index 0000000000..98b8bcf1c5 --- /dev/null +++ b/Task/Faulhabers-triangle/ALGOL-68/faulhabers-triangle.alg @@ -0,0 +1,131 @@ +BEGIN # show some rows of Faulhaber's triangle # + + # utility operators # + OP LENGTH = ( STRING a )INT: ( UPB a - LWB a ) + 1; + 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; + + MODE INTEGER = LONG LONG INT; # mode for FRAC numberator & denominator # + OP TOINTEGER = ( INT n )INTEGER: n; # force widening n to INTEGER # + + # Code from the Arithmetic/Rational task # + + MODE FRAC = STRUCT( INTEGER num #erator#, den #ominator#); + + PROC gcd = (INTEGER a, b) INTEGER: # greatest common divisor # + (a = 0 | b |: b = 0 | a |: ABS a > ABS b | gcd(b, a MOD b) | gcd(a, b MOD a)); + + PROC lcm = (INTEGER a, b)INTEGER: # least common multiple # + a OVER gcd(a, b) * b; + + PRIO // = 9; # higher then the ** operator # + OP // = (INTEGER num, den)FRAC: ( # initialise and normalise # + INTEGER common = gcd(num, den); + IF den < 0 THEN + ( -num OVER common, -den OVER common) + ELSE + ( num OVER common, den OVER common) + FI + ); + + OP + = (FRAC a, b)FRAC: ( + INTEGER common = lcm(den OF a, den OF b); + FRAC result := ( common OVER den OF a * num OF a + common OVER den OF b * num OF b, common ); + num OF result//den OF result + ); + + OP - = (FRAC a, b)FRAC: a + -b, + * = (FRAC a, b)FRAC: ( + INTEGER num = num OF a * num OF b, + den = den OF a * den OF b; + INTEGER common = gcd(num, den); + (num OVER common) // (den OVER common) + ); + + OP - = (FRAC frac)FRAC: (-num OF frac, den OF frac); + + # end code from the Arithmetic/Rational task # + + # alternative // operator for standard size INT values # + OP // = (INT num, den)FRAC: TOINTEGER num // TOINTEGER den; + # returns a * b # + OP * = ( INT a, FRAC b )FRAC: ( num OF b * a ) // den OF b; + OP * = ( INTEGER a, FRAC b )FRAC: ( num OF b * a ) // den OF b; + # sets a to a + b and returns a # + OP +:= = ( REF FRAC a, FRAC b )FRAC: a := a + b; + # sets a to - a and returns a # + OP -=: = ( REF FRAC a )FRAC: BEGIN num OF a := - num OF a; a END; + + # returns the nth Bernoulli number, n must be >= 0 # + OP BERNOULLI = ( INT n )FRAC: + IF n < 0 + THEN # n is out of range # 0 // 1 + ELSE # n is valid # + [ 0 : n ]FRAC a; + FOR m FROM 0 TO n DO + a[ m ] := 1 // ( m + 1 ); + FOR j FROM m BY -1 TO 1 DO + a[ j - 1 ] := j * ( a[ j - 1 ] - a[ j ] ) + OD + OD; + IF n = 1 THEN - a[ 0 ] ELSE a[ 0 ] FI + FI # BERNOULLI # ; + + # returns n! / k! # + PROC factorial over factorial = ( INT n, k )INTEGER: + IF k > n THEN 0 + ELIF k = n THEN 1 + ELSE # k < n # + INTEGER f := 1; + FOR i FROM k + 1 TO n DO f *:= i OD; + f + FI # factorial over Factorial # ; + + # returns n! # + PROC factorial = ( INT n )INTEGER: + BEGIN + INTEGER f := 1; + FOR i FROM 2 TO n DO f *:= i OD; + f + END # factorial # ; + + # returns the binomial coefficient of (n k) # + PROC binomial coefficient = ( INT n, k )INTEGER: + IF n - k > k + THEN factorial over factorial( n, n - k ) OVER factorial( k ) + ELSE factorial over factorial( n, k ) OVER factorial( n - k ) + FI # binomial coefficient # ; + + # returns a string representation of a # + OP TOSTRING = ( FRAC a )STRING: + whole( num OF a, 0 ) + IF den OF a = 1 THEN "" ELSE "/" + whole( den OF a, 0 ) FI; + + # returns the pth row of Faulhaber's triangle # + OP FAULHABER = ( INT p )[]FRAC: + BEGIN + FRAC q := -1 // ( p + 1 ); + [ 0 : p ]FRAC coeffs; + FOR j FROM 0 TO p DO + coeffs[ p - j ] := binomial coefficient( p + 1, j ) * BERNOULLI j * -=: q + OD; + coeffs + END # faulhaber # ; + + FOR i FROM 0 TO 9 DO # show the triabngle's first 10 rows # + []FRAC frow = FAULHABER i; + FOR j FROM LWB frow TO UPB frow DO + print( ( " ", 6 PAD TOSTRING frow[ j ] ) ) + OD; + print( ( newline ) ) + OD; + BEGIN # compute the sum of k^17 for k = 1 to 1000 using triangle row 18 # + []FRAC frow = FAULHABER 17; + FRAC sum := 0 // 1; + INTEGER kn := 1; + FOR j FROM LWB frow TO UPB frow DO + VOID( sum +:= ( kn *:= 1000 ) * frow[ j ] ) + OD; + print( ( TOSTRING sum, newline ) ) + END +END diff --git a/Task/Faulhabers-triangle/Maxima/faulhabers-triangle.maxima b/Task/Faulhabers-triangle/Maxima/faulhabers-triangle.maxima index b4e944ddf0..3da505f703 100644 --- a/Task/Faulhabers-triangle/Maxima/faulhabers-triangle.maxima +++ b/Task/Faulhabers-triangle/Maxima/faulhabers-triangle.maxima @@ -2,20 +2,8 @@ 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); + 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] - ) -*/ +triangle_faulhaber_first_ten_rows:block(makelist(faulhaber_row(i),i,0,9),table_form(%%)); diff --git a/Task/Fibonacci-sequence/EasyLang/fibonacci-sequence-1.easy b/Task/Fibonacci-sequence/EasyLang/fibonacci-sequence-1.easy index 599f7f9493..07398538a5 100644 --- a/Task/Fibonacci-sequence/EasyLang/fibonacci-sequence-1.easy +++ b/Task/Fibonacci-sequence/EasyLang/fibonacci-sequence-1.easy @@ -1,14 +1,14 @@ -proc fib n . res . - if n < 2 - res = n - . - prev = 0 - val = 1 - for _ = 0 to n - 2 - res = prev + val - prev = val - val = res - . +func fib n . + if n < 2 + return n + . + prev = 0 + val = 1 + for i = 2 to n + h = prev + val + prev = val + val = h + . + return val . -call fib 36 r -print r +print fib 36 diff --git a/Task/Fibonacci-sequence/EasyLang/fibonacci-sequence-2.easy b/Task/Fibonacci-sequence/EasyLang/fibonacci-sequence-2.easy index 1e913c377c..bd5bacc9ea 100644 --- a/Task/Fibonacci-sequence/EasyLang/fibonacci-sequence-2.easy +++ b/Task/Fibonacci-sequence/EasyLang/fibonacci-sequence-2.easy @@ -1,11 +1,7 @@ -proc fib n . res . - if n < 2 - res = n - else - call fib n - 1 a - call fib n - 2 b - res = a + b - . +func fib n . + if n < 2 + return n + . + return fib (n - 2) + fib (n - 1) . -call fib 36 r -print r +print fib 36 diff --git a/Task/Filter/FutureBasic/filter-1.basic b/Task/Filter/FutureBasic/filter-1.basic new file mode 100644 index 0000000000..c0c64d557f --- /dev/null +++ b/Task/Filter/FutureBasic/filter-1.basic @@ -0,0 +1,11 @@ +include "NSLog.incl" + +local fn EvenNumbersFromArrayToNewArray + CFArrayRef numbersArray = @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12] + PredicateRef isEvenPred = fn PredicateWithFormat( @"modulus:by:(SELF, 2) == 0" ) + CFArrayRef evensArray = fn ArrayFilteredArrayUsingPredicate( numbersArray, isEvenPred ) + NSLog( @"Array of odd and even numbers before sort:\n\t%@\n", numbersArray ) + NSLog( @"New array of even numbers after sort:\n\t%@\n", evensArray ) +end fn +fn EvenNumbersFromArrayToNewArray +NSLogScrollToTop diff --git a/Task/Filter/FutureBasic/filter-2.basic b/Task/Filter/FutureBasic/filter-2.basic new file mode 100644 index 0000000000..1818eedaf1 --- /dev/null +++ b/Task/Filter/FutureBasic/filter-2.basic @@ -0,0 +1,12 @@ +local fn OddNumbersRemovedFromArray + CFMutablearrayRef mutableNumbersArray = fn MutableArrayWithArray( @[@1,@2,@3,@4,@5,@6,@7,@8,@9,@10,@11,@12] ) + NSLog( @"Mutable array of odd and even numbers before sort:\n\t%@\n", mutableNumbersArray ) + PredicateRef isEvenPred = fn PredicateWithFormat( @"modulus:by:(SELF, 2) == 0" ) + MutableArrayFilterUsingPredicate( mutableNumbersArray, isEvenPred ) + NSLog( @"Mutable array with odd numbers removed:\n\t%@\n", mutableNumbersArray ) +end fn + +fn OddNumbersRemovedFromArray +NSLogScrollToTop + +HandleEvents diff --git a/Task/Find-limit-of-recursion/EasyLang/find-limit-of-recursion.easy b/Task/Find-limit-of-recursion/EasyLang/find-limit-of-recursion.easy index 0b60301023..050dea43eb 100644 --- a/Task/Find-limit-of-recursion/EasyLang/find-limit-of-recursion.easy +++ b/Task/Find-limit-of-recursion/EasyLang/find-limit-of-recursion.easy @@ -1,7 +1,7 @@ proc recurse i . . - if i mod 100 = 0 - print i - . - call recurse i + 1 + if i mod 10 = 0 + print i + . + recurse i + 1 . -call recurse 1 +recurse 1 diff --git a/Task/Forest-fire/EasyLang/forest-fire.easy b/Task/Forest-fire/EasyLang/forest-fire.easy index ff4e9a848e..e524ca0c60 100644 --- a/Task/Forest-fire/EasyLang/forest-fire.easy +++ b/Task/Forest-fire/EasyLang/forest-fire.easy @@ -6,64 +6,64 @@ len p[] len f[] background 100 clear for r = 0 to 99 - for c = 0 to 99 - i = r * 102 + c + 104 - if randomf < 0.5 - f[i] = 1 - . - . + for c = 0 to 99 + i = r * 102 + c + 104 + if randomf < 0.5 + f[i] = 1 + . + . . timer 0 # subr show - for r = 0 to 99 - for c = 0 to 99 - i = r * 102 + c + 104 - h = f[i] - if h <> p[i] - move c + 0.5 r + 0.5 - if h = 0 - color 100 - circle 0.6 - elif h = 1 - color 151 - circle 0.5 - else - color 9 * 100 + (18 - 2 * h) * 10 - circle 0.5 - . + for r = 0 to 99 + for c = 0 to 99 + i = r * 102 + c + 104 + h = f[i] + if h <> p[i] + move c + 0.5 r + 0.5 + if h = 0 + color 100 + circle 0.6 + elif h = 1 + color 151 + circle 0.5 + else + color 9 * 100 + (18 - 2 * h) * 10 + circle 0.5 + . + . . - . - . + . . subr update - swap f[] p[] - for r = 0 to 99 - for c = 0 to 99 - i = r * 102 + c + 104 - if p[i] = 0 - f[i] = 0 - if randomf < p_tree - f[i] = 1 - . - elif p[i] = 1 - f[i] = 1 - s = p[i - 103] + p[i - 102] + p[i - 101] - s += p[i - 1] + p[i + 1] - s += p[i + 101] + p[i + 102] + p[i + 103] - if s >= 9 or randomf < p_fire - f[i] = 9 - . - elif p[i] = 4 - f[i] = 0 - else - f[i] = p[i] - 1 + swap f[] p[] + for r = 0 to 99 + for c = 0 to 99 + i = r * 102 + c + 104 + if p[i] = 0 + f[i] = 0 + if randomf < p_tree + f[i] = 1 + . + elif p[i] = 1 + f[i] = 1 + s = p[i - 103] + p[i - 102] + p[i - 101] + s += p[i - 1] + p[i + 1] + s += p[i + 101] + p[i + 102] + p[i + 103] + if s >= 9 or randomf < p_fire + f[i] = 9 + . + elif p[i] = 4 + f[i] = 0 + else + f[i] = p[i] - 1 + . . - . - . + . . on timer - call show - call update - timer 0.2 + show + update + timer 0.2 . diff --git a/Task/Forest-fire/Raku/forest-fire-1.raku b/Task/Forest-fire/Raku/forest-fire-1.raku index 1234d9707d..f4565b0456 100644 --- a/Task/Forest-fire/Raku/forest-fire-1.raku +++ b/Task/Forest-fire/Raku/forest-fire-1.raku @@ -1,7 +1,9 @@ -my $RED = "\e[1;31m"; -my $YELLOW = "\e[1;33m"; -my $GREEN = "\e[1;32m"; -my $CLEAR = "\e[0m"; +constant $RED = "\e[1;31m"; +constant $YELLOW = "\e[1;33m"; +constant $GREEN = "\e[1;32m"; +constant $CLEAR = "\e[0m"; +# make sure we clear colors at the end +END print $CLEAR; enum Cell-State ; my @pix = ' ', $GREEN ~ '木', $YELLOW ~ '木', $RED ~ '木'; diff --git a/Task/Four-is-the-number-of-letters-in-the-.../00-TASK.txt b/Task/Four-is-the-number-of-letters-in-the-.../00-TASK.txt index 55b0dfabc4..a936b6f0b2 100644 --- a/Task/Four-is-the-number-of-letters-in-the-.../00-TASK.txt +++ b/Task/Four-is-the-number-of-letters-in-the-.../00-TASK.txt @@ -11,7 +11,8 @@ letters in the words of the (never─ending) sentence: :*   '''twenty─three'''   has eleven letters. :*   '''twenty─three'''   is considered one word   (which is hyphenated). :*   no   ''' ''and'' '''   words are to be used when spelling a (English) word for a number. -:*   The American version of numbers will be used here in this task   (as opposed to the British version). +:*   The short scale numbering system (i.e. 2,000,000,000 is two billion) will be used here. [[wp:Long and short scales]] + '''2,000,000,000'''   is two billion,   ''not''   two milliard. diff --git a/Task/Fractal-tree/EasyLang/fractal-tree.easy b/Task/Fractal-tree/EasyLang/fractal-tree.easy index 0b243b8f9a..8bf8452006 100644 --- a/Task/Fractal-tree/EasyLang/fractal-tree.easy +++ b/Task/Fractal-tree/EasyLang/fractal-tree.easy @@ -1,17 +1,20 @@ +# Fractal tree +# +color 555 proc tree x y deg n . . - if n > 0 - linewidth n * 0.4 - move x y - x += cos deg * n * 1.3 * (randomf + 0.5) - y += sin deg * n * 1.3 * (randomf + 0.5) - line x y - call tree x y deg - 20 n - 1 - call tree x y deg + 20 n - 1 - . + if n > 0 + linewidth n * 0.4 + move x y + x += cos deg * n * 1.3 * (randomf + 0.5) + y += sin deg * n * 1.3 * (randomf + 0.5) + line x y + tree x y deg - 20 n - 1 + tree x y deg + 20 n - 1 + . . timer 0 on timer - clear - call tree 50 90 -90 10 - timer 1 + clear + tree 50 10 90 10 + timer 2 . diff --git a/Task/Function-definition/EasyLang/function-definition.easy b/Task/Function-definition/EasyLang/function-definition.easy index 4c70f02eab..3f70bb95f9 100644 --- a/Task/Function-definition/EasyLang/function-definition.easy +++ b/Task/Function-definition/EasyLang/function-definition.easy @@ -1,5 +1,4 @@ -proc multiply a b . r . - r = a * b +func multiply a b . + return a * b . -call multiply 7 5 res -print res +print multiply 7 5 diff --git a/Task/Fusc-sequence/00-TASK.txt b/Task/Fusc-sequence/00-TASK.txt index 570b1bddb7..8bc89fe7a5 100644 --- a/Task/Fusc-sequence/00-TASK.txt +++ b/Task/Fusc-sequence/00-TASK.txt @@ -35,7 +35,8 @@ Fusc numbers are also known as: ;Related task: -::*   [[Stern-Brocot_sequence|RosettaCode Stern-Brocot sequence]] +:*   [[Stern-Brocot sequence]] +:*   [[Calkin-Wilf sequence]]. diff --git a/Task/Gamma-function/Koka/gamma-function.koka b/Task/Gamma-function/Koka/gamma-function.koka new file mode 100644 index 0000000000..cdf0d4fddb --- /dev/null +++ b/Task/Gamma-function/Koka/gamma-function.koka @@ -0,0 +1,45 @@ +import std/num/float64 + +fun gamma-lanczos(x) + val g = 7.0 + // Coefficients used by the GNU Scientific Library + val c = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7] + fun ag(z: float64, d: int) + if d == 0 then c[0].unjust + ag(z, 1) + elif d < 8 then c[d].unjust / (z + d.float64) + ag(z, d.inc) + else c[d].unjust / (z + d.float64) + fun gamma(z) + val z' = z - 1.0 + val p = z' + g + 0.5 + sqrt(2.0 * pi) * pow(p, (z' + 0.5)) * exp(0.0 - p) * ag(z', 0) + gamma(x) + +val e = exp(1.0) +fun gamma-stirling(x) + sqrt(2.0 * pi / x) * pow(x / e, x) + +fun gamma-stirling2(x') + // Extended Stirling method seen in Abramowitz and Stegun + val d = [1.0/12.0, 1.0/288.0, -139.0/51840.0, -571.0/2488320.0] + fun corr(z, x, n) + if n < d.length - 1 then d[n].unjust / x + corr(z, x*z, n.inc) + else d[n].unjust / x + fun gamma(z) + gamma-stirling(z)*(1.0 + corr(z, z, 0)) + gamma(x') + +fun mirror(gma, z) + if z > 0.5 then gma(z) else pi / sin(pi * z) / gma(1.0 - z) + +fun main() + println("z\tLanczos\t\t\tStirling\t\tStirling2") + for(1, 20) fn(i) + val z = i.float64 / 10.0 + println(z.show(1) ++ "\t" ++ mirror(gamma-lanczos, z).show ++ "\t" ++ + mirror(gamma-stirling, z).show ++ "\t" ++ mirror(gamma-stirling2, z).show) + for(1, 7) fn(i) + val z = 10.0 * i.float64 + println(z.show ++ "\t" ++ gamma-lanczos(z).show ++ "\t" ++ + gamma-stirling(z).show ++ "\t" ++ gamma-stirling2(z).show) diff --git a/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet-1.easy b/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet-1.easy deleted file mode 100644 index 94375ff0ed..0000000000 --- a/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet-1.easy +++ /dev/null @@ -1,3 +0,0 @@ -for i = 97 to 122 - alphabet$[] &= strchar i -. diff --git a/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet-2.easy b/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet-2.easy deleted file mode 100644 index cdeb8fe508..0000000000 --- a/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet-2.easy +++ /dev/null @@ -1,3 +0,0 @@ -for i = 97 to 122 - alphabet$ &= strchar i -. diff --git a/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet.easy b/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet.easy new file mode 100644 index 0000000000..0680e8a6d8 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/EasyLang/generate-lower-case-ascii-alphabet.easy @@ -0,0 +1,10 @@ +# Generated on an array +for i = 97 to 122 + alphabet$[] &= strchar i +. +print alphabet$[] +# Generated on a string +for i = 97 to 122 + alphabet$ &= strchar i +. +print alphabet$ diff --git a/Task/Giuga-numbers/EasyLang/giuga-numbers.easy b/Task/Giuga-numbers/EasyLang/giuga-numbers.easy index 2e9ef5cabc..565fceea59 100644 --- a/Task/Giuga-numbers/EasyLang/giuga-numbers.easy +++ b/Task/Giuga-numbers/EasyLang/giuga-numbers.easy @@ -1,23 +1,20 @@ -proc giuga m . r . +func giuga m . n = m - r = 0 for f = 2 to sqrt n while n mod f = 0 if (m div f - 1) mod f <> 0 - break 2 + return 0 . n = n div f if f > n - r = 1 - break 2 + return 1 . . . . n = 3 while cnt < 4 - call giuga n r - if r = 1 + if giuga n = 1 cnt += 1 print n . diff --git a/Task/Giuga-numbers/Maxima/giuga-numbers.maxima b/Task/Giuga-numbers/Maxima/giuga-numbers.maxima new file mode 100644 index 0000000000..b6b46d8619 --- /dev/null +++ b/Task/Giuga-numbers/Maxima/giuga-numbers.maxima @@ -0,0 +1,12 @@ +/* Predicate function that checks wether an integer is a Giuga number or not */ +giugap(n):=if not primep(n) then block(ifactors(n),map(lambda([x],mod((n/x)-1,x)=0),map(first,%%)), + if length(unique(%%))=1 and apply(lhs,unique(%%))=0 then true)$ + +/* Function that returns a list of the first len Giuga integers */ +giuga_count(len):=block( + [i:1,count:0,result:[]], + while count 2 + return 0 . - if n mod 2 = 0 - if n = 2 - break 1 - . - r = 0 - break 1 - . - for i = 3 step 2 to sqrt n + i = 3 + sq = sqrt n + while i <= sq if n mod i = 0 - r = 0 - break 2 + return 0 . + i += 2 . + return 1 . -proc goldbach n . cnt . - cnt = 0 - for i = 1 to n div 2 - call isprime i r - if r = 1 - call isprime n - i r - cnt += r +func goldbach n . + for i = 2 to n div 2 + if isprim i = 1 + cnt += isprim (n - i) . . + return cnt . numfmt 0 3 for n = 4 step 2 to 202 - call goldbach n r - write r + write goldbach n if n mod 20 = 2 print "" . . -call goldbach 1000000 r -print r +print goldbach 1000000 diff --git a/Task/Greatest-common-divisor/EasyLang/greatest-common-divisor.easy b/Task/Greatest-common-divisor/EasyLang/greatest-common-divisor.easy index 56852717f9..92078d6b8b 100644 --- a/Task/Greatest-common-divisor/EasyLang/greatest-common-divisor.easy +++ b/Task/Greatest-common-divisor/EasyLang/greatest-common-divisor.easy @@ -1,10 +1,9 @@ -proc gcd a b . res . - while b <> 0 - h = b - b = a mod b - a = h - . - res = a +func gcd a b . + while b <> 0 + h = b + b = a mod b + a = h + . + return a . -call gcd 120 35 r -print r +print gcd 120 35 diff --git a/Task/Greyscale-bars-Display/EasyLang/greyscale-bars-display.easy b/Task/Greyscale-bars-Display/EasyLang/greyscale-bars-display.easy index 8fa747da58..cd8133e96a 100644 --- a/Task/Greyscale-bars-Display/EasyLang/greyscale-bars-display.easy +++ b/Task/Greyscale-bars-Display/EasyLang/greyscale-bars-display.easy @@ -9,7 +9,7 @@ for row = 0 to 3 color3 c c c move sz * i 75 - row * 25 rect sz + 1 25 - sleep 0.1 + sleep 0.02 . n *= 2 . diff --git a/Task/Guess-the-number-With-feedback/EasyLang/guess-the-number-with-feedback.easy b/Task/Guess-the-number-With-feedback/EasyLang/guess-the-number-with-feedback.easy index 0e3c58406b..32a353df16 100644 --- a/Task/Guess-the-number-With-feedback/EasyLang/guess-the-number-with-feedback.easy +++ b/Task/Guess-the-number-With-feedback/EasyLang/guess-the-number-with-feedback.easy @@ -1,15 +1,15 @@ print "Guess a number between 1 and 100!" n = random 100 repeat - g = number input - write g - if error = 1 - print "You must enter a number!" - elif g > n - print " is too high" - elif g < n - print " is too low" - . - until g = n + g = number input + write g + if error = 1 + print "You must enter a number!" + elif g > n + print " is too high" + elif g < n + print " is too low" + . + until g = n . print " is correct" diff --git a/Task/HTTPS/FutureBasic/https.basic b/Task/HTTPS/FutureBasic/https.basic new file mode 100644 index 0000000000..4a6b3312d4 --- /dev/null +++ b/Task/HTTPS/FutureBasic/https.basic @@ -0,0 +1,13 @@ +include "NSLog.incl" + +local fn GET_HTTPS + CFStringRef response = unix @"curl -ksL https://sourceforge.net/" + CFDataRef dta = fn StringData( response, NSUTF8StringEncoding ) + CFDictionaryRef options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} + CFAttributedStringRef aStr = fn AttributedStringWithHTML( dta, options ) + NSLog( @"%@", aStr ) +end fn + +fn GET_HTTPS + +HandleEvents diff --git a/Task/Hello-world-Text/Acornsoft-Lisp/hello-world-text.lisp b/Task/Hello-world-Text/Acornsoft-Lisp/hello-world-text.lisp new file mode 100644 index 0000000000..4dd362f387 --- /dev/null +++ b/Task/Hello-world-Text/Acornsoft-Lisp/hello-world-text.lisp @@ -0,0 +1 @@ +(printc 'Hello! world!!) diff --git a/Task/Hex-words/FutureBasic/hex-words.basic b/Task/Hex-words/FutureBasic/hex-words.basic new file mode 100644 index 0000000000..798017bdb9 --- /dev/null +++ b/Task/Hex-words/FutureBasic/hex-words.basic @@ -0,0 +1,84 @@ +#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES} + +include "NSLog.incl" + +local fn ConvertHexToInt( hexNumberStr as CFStringRef ) as NSUInteger + NSUInteger outVal = 0 + ScannerRef scanner = fn ScannerWithString( hexNumberStr ) + fn ScannerScanHexInt( scanner, @outVal ) +end fn = outVal + + +local fn DigitalRoot( n as NSUInteger ) as NSUInteger + while ( n > 9 ) + NSUInteger tot = 0 + while ( n > 0 ) + tot += n mod 10 + n = fn floor( n / 10 ) + wend + n = tot + wend +end fn = n + + +local fn HasDistinctLetters( hexNumberStr as CFStringRef ) as BOOL + NSUInteger A = 0, B = 0, C = 0, D = 0, E = 0, F = 0, length = len( hexNumberStr ) + + while ( length > 0 ) + length-- + unichar aChar = fn StringCharacterAtIndex( hexNumberStr, length ) + select ( aChar ) + case _"a" : if A = 0 then A = 1 + case _"b" : if B = 0 then B = 1 + case _"c" : if C = 0 then C = 1 + case _"d" : if D = 0 then D = 1 + case _"e" : if E = 0 then E = 1 + case _"f" : if F = 0 then F = 1 + end select + wend + if ( A + B + C + D + E + F ) > 3 then exit fn = YES +end fn = NO + + +local fn ParseDictionaryHexWords as CFArrayRef + CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ) + CFStringRef string = lcase( fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL ) ) + CFArrayRef tempArr = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet ) + CFMutableArrayRef dictArr = fn MutableArrayNew + CFStringRef tempStr + + for tempStr in tempArr + if ( fn StringLength( tempStr ) > 3 ) // Keep four letter words and longer + CFRange range = fn StringRangeOfStringWithOptions( tempStr, @"^[a-f]+$", NSRegularExpressionSearch ) // Keep wordss with letters a to f + if range.location != NSNotFound then MutableArrayAddObject( dictArr, tempStr ) + end if + next +end fn = fn ArrayWithArray( dictArr ) + + +local fn ConvertWordsToHexValues as CFStringRef + CFArrayRef hexWordArray = fn ParseDictionaryHexWords + CFStringRef wordStr + CFMutableArrayRef mutArr = fn MutableArrayNew //fn MutableStringWithString( @"Root Word Base 10\n ---------------------------\n" ) + CFMutableArrayRef lngArr = fn MutableArrayNew + + for wordStr in hexWordArray + NSUInteger uintFromHex = fn ConvertHexToInt( wordStr ) + NSUInteger digitalRoot = fn DigitalRoot( uintFromHex ) + CFStringREf formatStr = fn StringWithFormat( @"%2lu %-8s %lu", digitalRoot, fn StringUTF8String( wordStr ), uintFromHex ) + MutableArrayAddObject( mutArr, formatStr ) + if ( fn HasDistinctLetters( wordStr ) == YES ) + MutableArrayAddObject( lngArr, formatStr ) + end if + next + CFStringRef headerStr = @"\nRoot Word Base 10\n ---------------------------\n" + CFArrayRef resultArr = fn ArraySortedArrayUsingSelector( mutArr, @"localizedCompare:" ) + CFStringRef resultStr = fn ArrayComponentsJoinedByString( resultArr, @"\n" ) + CFArrayRef uniquetArr = fn ArraySortedArrayUsingSelector( lngArr, @"localizedCompare:" ) + CFStringRef uniqueStr = fn ArrayComponentsJoinedByString( uniquetArr, @"\n" ) + CFStringRef finalStr = fn StringWithFormat( @"%@%@\n\nHex words with 3 > distinct letters:%@%@", headerStr, resultStr, headerStr, uniqueStr ) +end fn = finalStr + +NSLog( @"%@", fn ConvertWordsToHexValues ) + +HandleEvents diff --git a/Task/Horizontal-sundial-calculations/EasyLang/horizontal-sundial-calculations.easy b/Task/Horizontal-sundial-calculations/EasyLang/horizontal-sundial-calculations.easy index 6728d67435..a474da85f0 100644 --- a/Task/Horizontal-sundial-calculations/EasyLang/horizontal-sundial-calculations.easy +++ b/Task/Horizontal-sundial-calculations/EasyLang/horizontal-sundial-calculations.easy @@ -1,11 +1,12 @@ -proc getn s$ . v . - write s$ - v = number input - print v +func getn s$ . + write s$ + v = number input + print v + return v . -call getn "Enter latitude: " lat -call getn "Enter longitude: " lng -call getn "Enter legal meridian: " merid +lat = getn "Enter latitude: " +lng = getn "Enter longitude: " +merid = getn "Enter legal meridian: " slat = sin lat diff = lng - merid print "" @@ -14,7 +15,7 @@ print " diff longitude: " & diff print "" print "Hour\tSun hour angle\tDial hour line angle" for h = -6 to 6 - hra = 15 * h - diff - hla = atan2 (slat * sin hra) cos hra - print h + 12 & "\t" & hra & "\t\t" & hla + hra = 15 * h - diff + hla = atan2 (slat * sin hra) cos hra + print h + 12 & "\t" & hra & "\t\t" & hla . diff --git a/Task/ISBN13-check-digit/EasyLang/isbn13-check-digit.easy b/Task/ISBN13-check-digit/EasyLang/isbn13-check-digit.easy index 41f9a14e9f..baf40297f7 100644 --- a/Task/ISBN13-check-digit/EasyLang/isbn13-check-digit.easy +++ b/Task/ISBN13-check-digit/EasyLang/isbn13-check-digit.easy @@ -1,27 +1,24 @@ -proc ISBN13check ISBN$ . valid . - for i = 1 to len ISBN$ - currentChar$ = substr ISBN$ i 1 - if currentChar$ <> "-" - digitCounter += 1 +func ISBN13check isbn$ . + for c$ in strchars isbn$ + if c$ <> "-" + ndigs += 1 . - currentDigit = number currentChar$ - if digitCounter mod 2 = 0 - currentDigit *= 3 + dig = number c$ + if ndigs mod 2 = 0 + dig *= 3 . - sum += currentDigit + sum += dig . - if sum mod 10 = 0 - valid = 1 + if sum mod 10 <> 0 + return 0 + . + return 1 +. +codes$[] = [ "978-0596528126" "978-0596528120" "978-1788399081" "978-1788399083" ] +for code$ in codes$[] + if ISBN13check code$ = 1 + print code$ & " is a valid ISBN" else - valid = 0 - . -. -ISBNcodes$[] = [ "978-0596528126" "978-0596528120" "978-1788399081" "978-1788399083" ] -for ISBN$ in ISBNcodes$[] - call ISBN13check ISBN$ valid - if valid = 1 - print ISBN$ & " is a valid ISBN" - else - print ISBN$ & " is not a valid ISBN" + print code$ & " is not a valid ISBN" . . diff --git a/Task/Im-a-software-engineer-get-me-out-of-here/00-TASK.txt b/Task/Im-a-software-engineer-get-me-out-of-here/00-TASK.txt index 47b75cbb37..ea9e3d204a 100644 --- a/Task/Im-a-software-engineer-get-me-out-of-here/00-TASK.txt +++ b/Task/Im-a-software-engineer-get-me-out-of-here/00-TASK.txt @@ -37,3 +37,6 @@ Related tasks: # [[Dijkstra's algorithm]] # [[Floyd-Warshall algorithm]] +;See also: +*   [https://en.wikipedia.org/wiki/Back_from_the_Klondike Back from the Klondike]. + diff --git a/Task/Integer-sequence/EasyLang/integer-sequence.easy b/Task/Integer-sequence/EasyLang/integer-sequence.easy index d3bcc6068c..ff87b9eebc 100644 --- a/Task/Integer-sequence/EasyLang/integer-sequence.easy +++ b/Task/Integer-sequence/EasyLang/integer-sequence.easy @@ -2,7 +2,8 @@ max = pow 2 53 repeat print i if i = 10 - print ".\n." + print "." + print "." i = max - 10 . until i = max diff --git a/Task/Inverted-syntax/Koka/inverted-syntax.koka b/Task/Inverted-syntax/Koka/inverted-syntax.koka new file mode 100644 index 0000000000..0429c9371c --- /dev/null +++ b/Task/Inverted-syntax/Koka/inverted-syntax.koka @@ -0,0 +1,14 @@ +fun (=:)(c: c, v: local-var): > () + v := c + +fun (?)(c: c, b: bool): e maybe + if b then Just(c) else Nothing + +fun main() + var x := 4 + 6 =: std/core/types/byref(x) + x.println + val res = "Yes" ? True + match res + Just(a) -> println(a) + Nothing -> throw("Nothing") diff --git a/Task/Julia-set/Maxima/julia-set.maxima b/Task/Julia-set/Maxima/julia-set.maxima new file mode 100644 index 0000000000..4683ecd20f --- /dev/null +++ b/Task/Julia-set/Maxima/julia-set.maxima @@ -0,0 +1,2 @@ +julia (-0.786, 0.147, [iterations, 255], [x, -1.5, 1.5], + [y, -1, 1], [grid, 320, 320])$ diff --git a/Task/K-means++-clustering/C/k-means++-clustering.c b/Task/K-means++-clustering/C/k-means++-clustering.c index 1ef8901609..d064ac6513 100644 --- a/Task/K-means++-clustering/C/k-means++-clustering.c +++ b/Task/K-means++-clustering/C/k-means++-clustering.c @@ -108,7 +108,8 @@ double nearestDistance(POINT * pt, POINT * cent, int n_cluster) greater than the search value passed as a parameter. This code is adapted from code by Andy Allinger given to the public - domain. + domain, which was in turn adapted from public domain code for spline + evaluation by Rondall Jones (Sandia National Laboratories). Input: x A pointer to an array of values in increasing order to be searched. @@ -153,7 +154,7 @@ int bisectionSearch(double *x, int n, double v) } /* end of bisectionSearch */ /*------------------------------------------------------- - kppAllinger + kppFaster This function uses the K-Means++ method to select the cluster centroids. @@ -170,7 +171,7 @@ int bisectionSearch(double *x, int n, double v) Output: centroids A pointer to the array of centroids found. -------------------------------------------------------*/ -void kppAllinger(POINT * pts, int num_pts, POINT * centroids, +void kppFaster(POINT * pts, int num_pts, POINT * centroids, int num_clusters) { int j; @@ -230,7 +231,7 @@ void kppAllinger(POINT * pts, int num_pts, POINT * centroids, free(cumulativeDistances); return; -} /* end, kppAllinger */ +} /* end, kppFaster */ /*------------------------------------------------------- kpp @@ -327,8 +328,8 @@ POINT * lloyd(POINT * pts, int num_pts, int num_clusters, int maxTimes) /* Original version kpp(pts, num_pts, centroids, num_clusters); */ - /* Faster Allinger version */ - kppAllinger(pts, num_pts, centroids, num_clusters); + /* Faster version */ + kppFaster(pts, num_pts, centroids, num_clusters); do { /* Calculate the centroid of each cluster. diff --git a/Task/Knapsack-problem-0-1/EasyLang/knapsack-problem-0-1.easy b/Task/Knapsack-problem-0-1/EasyLang/knapsack-problem-0-1.easy index 5f7a51188f..fe345ece1a 100644 --- a/Task/Knapsack-problem-0-1/EasyLang/knapsack-problem-0-1.easy +++ b/Task/Knapsack-problem-0-1/EasyLang/knapsack-problem-0-1.easy @@ -4,28 +4,28 @@ value[] = [ 150 35 200 160 60 45 60 40 30 10 70 30 15 10 40 70 75 80 20 12 50 10 max_w = 400 # proc solve i maxw . items[] wres vres . - if i <= 0 - wres = 0 - vres = 0 - items[] = [ ] - elif weight[i] > maxw - call solve i - 1 maxw items[] wres vres - else - call solve i - 1 maxw items[] wres vres - call solve i - 1 maxw - weight[i] items1[] w1 v1 - v1 += value[i] - if v1 > vres - swap items[] items1[] - items[] &= i - wres = w1 + weight[i] - vres = v1 - . - . + if i <= 0 + wres = 0 + vres = 0 + items[] = [ ] + elif weight[i] > maxw + solve i - 1 maxw items[] wres vres + else + solve i - 1 maxw items[] wres vres + solve i - 1 maxw - weight[i] items1[] w1 v1 + v1 += value[i] + if v1 > vres + swap items[] items1[] + items[] &= i + wres = w1 + weight[i] + vres = v1 + . + . . -call solve len weight[] max_w items[] w v +solve len weight[] max_w items[] w v print "weight: " & w print "value: " & v print "items:" -for i = 1 to len items[] - print " " & name$[items[i]] +for item in items[] + print " " & name$[item] . diff --git a/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy b/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy index 07c691e280..ea070c7fe5 100644 --- a/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy +++ b/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy @@ -1,9 +1,9 @@ proc shuffle . a[] . - for i = len a[] downto 2 - r = random i - swap a[r] a[i] - . + for i = len a[] downto 2 + r = random i + swap a[r] a[i] + . . arr[] = [ 1 2 3 ] -call shuffle arr[] +shuffle arr[] print arr[] diff --git a/Task/Koch-curve/EasyLang/koch-curve.easy b/Task/Koch-curve/EasyLang/koch-curve.easy index c4ef79631e..ab72dbe553 100644 --- a/Task/Koch-curve/EasyLang/koch-curve.easy +++ b/Task/Koch-curve/EasyLang/koch-curve.easy @@ -7,10 +7,10 @@ proc koch x1 y1 x2 y2 iter . . y5 = y3 - (x4 - x3) * sin 60 + (y4 - y3) * cos 60 if iter > 0 iter -= 1 - call koch x1 y1 x3 y3 iter - call koch x3 y3 x5 y5 iter - call koch x5 y5 x4 y4 iter - call koch x4 y4 x2 y2 iter + koch x1 y1 x3 y3 iter + koch x3 y3 x5 y5 iter + koch x5 y5 x4 y4 iter + koch x4 y4 x2 y2 iter else line x1 y1 line x3 y3 @@ -26,7 +26,7 @@ move x1 y1 for ang = 0 step 120 to 240 x2 = x1 + 70 * cos ang y2 = y1 + 70 * sin ang - call koch x1 y1 x2 y2 4 + koch x1 y1 x2 y2 4 x1 = x2 y1 = y2 . diff --git a/Task/Koch-curve/Maxima/koch-curve.maxima b/Task/Koch-curve/Maxima/koch-curve.maxima new file mode 100644 index 0000000000..9740b4902e --- /dev/null +++ b/Task/Koch-curve/Maxima/koch-curve.maxima @@ -0,0 +1,25 @@ +set_draw_defaults( + terminal = svg, + dimensions = [350,350], + proportional_axes = xy) $ + +wxdraw2d( + turtle( + to(koch_snowflake, [n, len], + ifelse(n = 0, + [forward(len)], + [koch_snowflake(n - 1, len), + right(60), + koch_snowflake(n - 1, len), + left(120), + koch_snowflake(n - 1, len), + right(60), + koch_snowflake(n - 1, len)] + ) + ), + repeat(6, + koch_snowflake(5, 300), + right(60) + ) + ) +); diff --git a/Task/Kronecker-product-based-fractals/ALGOL-68/kronecker-product-based-fractals.alg b/Task/Kronecker-product-based-fractals/ALGOL-68/kronecker-product-based-fractals.alg new file mode 100644 index 0000000000..d03db0338f --- /dev/null +++ b/Task/Kronecker-product-based-fractals/ALGOL-68/kronecker-product-based-fractals.alg @@ -0,0 +1,55 @@ +BEGIN # Kronecker product based fractals - translated from the Kotlin sample # + + MODE MATRIX = FLEX[ 1 : 0, 1 : 0 ]INT; + + PROC kronecker product = ( MATRIX a in, b in )MATRIX: + BEGIN + MATRIX a = a in[ AT 0, AT 0 ], b = b in[ AT 0, AT 0 ]; + INT m = 1 UPB a + 1, n = 2 UPB a + 1; + INT p = 1 UPB b + 1, q = 2 UPB b + 1; + INT rtn = m * p, ctn = n * q; + [ 0 : rtn - 1, 0 : ctn - 1 ]INT r; + FOR i FROM 0 TO rtn - 1 DO FOR j FROM 0 TO ctn - 1 DO r[ i, j ] := 0 OD OD; + FOR i FROM 0 TO m - 1 DO + FOR j FROM 0 TO n - 1 DO + FOR k FROM 0 TO p - 1 DO + FOR l FROM 0 TO q - 1 DO + r[ p * i + k, q * j + l ] := a[ i, j ] * b[ k, l ] + OD + OD + OD + OD; + r + END # kronecker product # ; + + PROC kronecker power = ( MATRIX a, INT n )MATRIX: + BEGIN + MATRIX pow := a; + FOR i TO n - 1 DO pow := kronecker product( pow, a ) OD; + pow + END # kronecker power # ; + + PROC print matrix = ( STRING text, MATRIX m )VOID: + BEGIN + print( ( text, " fractal :", newline ) ); + FOR i FROM 1 LWB m TO 1 UPB m DO + FOR j FROM 2 LWB m TO 2 UPB m DO + print( ( IF m[ i, j ] = 1 THEN "*" ELSE " " FI ) ) + OD; + print( ( newline ) ) + OD; + print( ( newline ) ) + END # print matrix # ; + + MATRIX a := MATRIX( ( 0, 1, 0 ) + , ( 1, 1, 1 ) + , ( 0, 1, 0 ) + ); + print matrix( "Vicsek", kronecker power( a, 4 ) ); + + a := MATRIX( ( 1, 1, 1 ) + , ( 1, 0, 1 ) + , ( 1, 1, 1 ) + ); + print matrix( "Sierpinski carpet", kronecker power( a, 4 ) ) +END diff --git a/Task/Langtons-ant/00-TASK.txt b/Task/Langtons-ant/00-TASK.txt index fab39c7f0b..d0ddb93073 100644 --- a/Task/Langtons-ant/00-TASK.txt +++ b/Task/Langtons-ant/00-TASK.txt @@ -25,6 +25,7 @@ The problem has received some analysis; for more details, please take a look at ;Related task: -*   Rosetta Code:   [[Conway's Game of Life]]. +*   [[Conway%27s_Game_of_Life|Conway's Game of Life]]. +*   [[Elementary_cellular_automaton|Elementary cellular automaton]]

diff --git a/Task/Langtons-ant/EasyLang/langtons-ant.easy b/Task/Langtons-ant/EasyLang/langtons-ant.easy index ff8cbacc6d..24011e0fa8 100644 --- a/Task/Langtons-ant/EasyLang/langtons-ant.easy +++ b/Task/Langtons-ant/EasyLang/langtons-ant.easy @@ -1,24 +1,24 @@ len f[] 100 * 100 proc show . . - for y = 0 to 99 - for x = 0 to 99 - if f[y * 100 + x + 1] = 1 - move x y - rect 1 1 + for y = 0 to 99 + for x = 0 to 99 + if f[y * 100 + x + 1] = 1 + move x y + rect 1 1 + . . - . - . + . . proc run x y dir . . - dx[] = [ 0 1 0 -1 ] - dy[] = [ -1 0 1 0 ] - while x >= 0 and x < 100 and y >= 0 and y < 100 - v = f[y * 100 + x + 1] - f[y * 100 + x + 1] = 1 - v - dir = (dir + 2 * v) mod 4 + 1 - x += dx[dir] - y += dy[dir] - . + dx[] = [ 0 1 0 -1 ] + dy[] = [ -1 0 1 0 ] + while x >= 0 and x < 100 and y >= 0 and y < 100 + v = f[y * 100 + x + 1] + f[y * 100 + x + 1] = 1 - v + dir = (dir + 2 * v) mod 4 + 1 + x += dx[dir] + y += dy[dir] + . . -call run 70 40 0 -call show +run 70 40 0 +show diff --git a/Task/Largest-number-divisible-by-its-digits/EasyLang/largest-number-divisible-by-its-digits.easy b/Task/Largest-number-divisible-by-its-digits/EasyLang/largest-number-divisible-by-its-digits.easy index ead95c8036..b3697e1722 100644 --- a/Task/Largest-number-divisible-by-its-digits/EasyLang/largest-number-divisible-by-its-digits.easy +++ b/Task/Largest-number-divisible-by-its-digits/EasyLang/largest-number-divisible-by-its-digits.easy @@ -5,7 +5,7 @@ proc test . . . for i to len dig[] if n mod dig[i] <> 0 - break 2 + return . . found = 1 @@ -14,16 +14,16 @@ proc test . . len use[] 9 proc perm pos . . if found = 1 - break 1 + return . for i = 9 downto 1 dig[pos] = i if use[i] = 0 use[i] = 1 if pos = len dig[] - call test + test else - call perm pos + 1 + perm pos + 1 . use[i] = 0 . @@ -31,5 +31,5 @@ proc perm pos . . . for ndig = 9 downto 1 len dig[] ndig - call perm 1 + perm 1 . diff --git a/Task/Largest-proper-divisor-of-n/EasyLang/largest-proper-divisor-of-n.easy b/Task/Largest-proper-divisor-of-n/EasyLang/largest-proper-divisor-of-n.easy index 1378fbc414..f1defbc5d5 100644 --- a/Task/Largest-proper-divisor-of-n/EasyLang/largest-proper-divisor-of-n.easy +++ b/Task/Largest-proper-divisor-of-n/EasyLang/largest-proper-divisor-of-n.easy @@ -1,15 +1,15 @@ -proc lpdiv v . r . +func lpdiv v . r = 1 for i = 2 to v div 2 if v mod i = 0 r = i . . + return r . numfmt 0 3 for i = 1 to 100 - call lpdiv i res - write res + write lpdiv i if i mod 10 = 0 print "" . diff --git a/Task/Leonardo-numbers/EasyLang/leonardo-numbers.easy b/Task/Leonardo-numbers/EasyLang/leonardo-numbers.easy new file mode 100644 index 0000000000..c8752fcccf --- /dev/null +++ b/Task/Leonardo-numbers/EasyLang/leonardo-numbers.easy @@ -0,0 +1,14 @@ +proc leonardo L0 L1 add . . + print "L0:" & L0 & " L1:" & L1 & " add:" & add + write L0 & " " + write L1 & " " + for i = 2 to 24 + tmp = L0 + L0 = L1 + L1 = tmp + L1 + add + write L1 & " " + . + print "" +. +leonardo 1 1 1 +leonardo 0 1 0 diff --git a/Task/Leonardo-numbers/Odin/leonardo-numbers.odin b/Task/Leonardo-numbers/Odin/leonardo-numbers.odin new file mode 100644 index 0000000000..ad9a9509f8 --- /dev/null +++ b/Task/Leonardo-numbers/Odin/leonardo-numbers.odin @@ -0,0 +1,24 @@ +package main +/* imports */ +import "core:fmt" +/* main */ +main :: proc() { + fmt.println("\nThe first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:") + result := leonardo(25, 1, 1, 1) + fmt.println(result) + delete(result) + fmt.println("\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:") + result = leonardo(25, 0, 1, 0) + fmt.println(result) + delete(result) +} +/* definitions */ +leonardo :: proc(n, l0, l1, add: int) -> []int { + leo := make([]int, n) + leo[0] = l0 + leo[1] = l1 + for i in 2 ..< n { + leo[i] = leo[i - 1] + leo[i - 2] + add + } + return leo +} diff --git a/Task/List-comprehensions/Python/list-comprehensions-1.py b/Task/List-comprehensions/Python/list-comprehensions-1.py deleted file mode 100644 index be23bc3d93..0000000000 --- a/Task/List-comprehensions/Python/list-comprehensions-1.py +++ /dev/null @@ -1 +0,0 @@ -[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2] diff --git a/Task/List-comprehensions/Python/list-comprehensions-2.py b/Task/List-comprehensions/Python/list-comprehensions-2.py deleted file mode 100644 index 3cb2fe8180..0000000000 --- a/Task/List-comprehensions/Python/list-comprehensions-2.py +++ /dev/null @@ -1 +0,0 @@ -((x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2) diff --git a/Task/List-comprehensions/Python/list-comprehensions-3.py b/Task/List-comprehensions/Python/list-comprehensions-3.py deleted file mode 100644 index 83ebbbf616..0000000000 --- a/Task/List-comprehensions/Python/list-comprehensions-3.py +++ /dev/null @@ -1 +0,0 @@ -[(x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z] diff --git a/Task/List-comprehensions/Python/list-comprehensions-4.py b/Task/List-comprehensions/Python/list-comprehensions-4.py deleted file mode 100644 index e1614674d0..0000000000 --- a/Task/List-comprehensions/Python/list-comprehensions-4.py +++ /dev/null @@ -1 +0,0 @@ -((x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z) diff --git a/Task/List-comprehensions/Python/list-comprehensions-5.py b/Task/List-comprehensions/Python/list-comprehensions-5.py deleted file mode 100644 index 72cc85c6bd..0000000000 --- a/Task/List-comprehensions/Python/list-comprehensions-5.py +++ /dev/null @@ -1,5 +0,0 @@ -def triplets(n): - for x in xrange(1, n + 1): - for y in xrange(x, n + 1): - for z in xrange(y, n + 1): - yield x, y, z diff --git a/Task/List-comprehensions/Python/list-comprehensions-6.py b/Task/List-comprehensions/Python/list-comprehensions-6.py deleted file mode 100644 index c02b3d1b26..0000000000 --- a/Task/List-comprehensions/Python/list-comprehensions-6.py +++ /dev/null @@ -1 +0,0 @@ -[(x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2] diff --git a/Task/List-comprehensions/Python/list-comprehensions-7.py b/Task/List-comprehensions/Python/list-comprehensions-7.py deleted file mode 100644 index 4621e59ef6..0000000000 --- a/Task/List-comprehensions/Python/list-comprehensions-7.py +++ /dev/null @@ -1 +0,0 @@ -((x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2) diff --git a/Task/List-comprehensions/Python/list-comprehensions-8.py b/Task/List-comprehensions/Python/list-comprehensions-8.py deleted file mode 100644 index f0318a6671..0000000000 --- a/Task/List-comprehensions/Python/list-comprehensions-8.py +++ /dev/null @@ -1,59 +0,0 @@ -from functools import (reduce) -from operator import (add) - - -# pts :: Int -> [(Int, Int, Int)] -def pts(n): - m = 1 + n - return [(x, y, z) for x in xrange(1, m) - for y in xrange(x, m) - for z in xrange(y, m) if x**2 + y**2 == z**2] - - -# pts2 :: Int -> [(Int, Int, Int)] -def pts2(n): - m = 1 + n - return bindList( - xrange(1, m) - )(lambda x: bindList( - xrange(x, m) - )(lambda y: bindList( - xrange(y, m) - )(lambda z: [(x, y, z)] if x**2 + y**2 == z**2 else []))) - - -# pts3 :: Int -> [(Int, Int, Int)] -def pts3(n): - m = 1 + n - return concatMap( - lambda x: concatMap( - lambda y: concatMap( - lambda z: [(x, y, z)] if x**2 + y**2 == z**2 else [] - )(xrange(y, m)) - )(xrange(x, m)) - )(xrange(1, m)) - - -# GENERIC --------------------------------------------------------- - -# concatMap :: (a -> [b]) -> [a] -> [b] -def concatMap(f): - return lambda xs: ( - reduce(add, map(f, xs), []) - ) - - -# (flip concatMap) -# bindList :: [a] -> (a -> [b]) -> [b] -def bindList(xs): - return lambda f: ( - reduce(add, map(f, xs), []) - ) - - -def main(): - for f in [pts, pts2, pts3]: - print (f(20)) - - -main() diff --git a/Task/List-comprehensions/Python/list-comprehensions.py b/Task/List-comprehensions/Python/list-comprehensions.py new file mode 100644 index 0000000000..18ad591f27 --- /dev/null +++ b/Task/List-comprehensions/Python/list-comprehensions.py @@ -0,0 +1,95 @@ +import itertools +n = 20 + +# List comprehension: +[(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2] + +# A Python generator expression (note the outer round brackets), +# returns an iterator over the same result rather than an explicit list: +((x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2) + +# A slower but more readable version: +[(x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z] + +# Or as an iterator: +((x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z) + +# Alternatively we shorten the initial list comprehension but this time without compromising on speed. +# First we introduce a generator which generates all triplets: +def triplets(n): + for x in xrange(1, n + 1): + for y in xrange(x, n + 1): + for z in xrange(y, n + 1): + yield x, y, z + +# Apply this to our list comprehension gives: +[(x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2] + +# Or as an iterator: +((x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2) + +# More generally, the list comprehension syntax can be understood as a concise syntactic sugaring +# of a use of the list monad, in which non-matches are returned as empty lists, matches are wrapped +# as single-item lists, and concatenation flattens the output, eliminating the empty lists. + +# The monadic 'bind' operator for lists is concatMap, traditionally used with its first two arguments flipped. +# The following three formulations of a '''pts''' (pythagorean triangles) function are equivalent: + +from functools import (reduce) +from operator import (add) + +# pts :: Int -> [(Int, Int, Int)] +def pts(n): + m = 1 + n + return [(x, y, z) for x in xrange(1, m) + for y in xrange(x, m) + for z in xrange(y, m) if x**2 + y**2 == z**2] + + +# pts2 :: Int -> [(Int, Int, Int)] +def pts2(n): + m = 1 + n + return bindList( + xrange(1, m) + )(lambda x: bindList( + xrange(x, m) + )(lambda y: bindList( + xrange(y, m) + )(lambda z: [(x, y, z)] if x**2 + y**2 == z**2 else []))) + + +# pts3 :: Int -> [(Int, Int, Int)] +def pts3(n): + m = 1 + n + return concatMap( + lambda x: concatMap( + lambda y: concatMap( + lambda z: [(x, y, z)] if x**2 + y**2 == z**2 else [] + )(xrange(y, m)) + )(xrange(x, m)) + )(xrange(1, m)) + + +# GENERIC --------------------------------------------------------- + +# concatMap :: (a -> [b]) -> [a] -> [b] +def concatMap(f): + return lambda xs: ( + reduce(add, map(f, xs), []) + ) + + +# (flip concatMap) +# bindList :: [a] -> (a -> [b]) -> [b] +def bindList(xs): + return lambda f: ( + reduce(add, map(f, xs), []) + ) + + +def main(): + for f in [pts, pts2, pts3]: + print (f(20)) + + +main() diff --git a/Task/List-comprehensions/Raku/list-comprehensions.raku b/Task/List-comprehensions/Raku/list-comprehensions.raku index 063532ea14..452dd94585 100644 --- a/Task/List-comprehensions/Raku/list-comprehensions.raku +++ b/Task/List-comprehensions/Raku/list-comprehensions.raku @@ -1,5 +1,5 @@ my $n = 20; -gather for 1..$n -> $x { +say gather for 1..$n -> $x { for $x..$n -> $y { for $y..$n -> $z { take $x,$y,$z if $x*$x + $y*$y == $z*$z; diff --git a/Task/Logical-operations/EasyLang/logical-operations.easy b/Task/Logical-operations/EasyLang/logical-operations.easy index f562b7d259..535a6d5b4a 100644 --- a/Task/Logical-operations/EasyLang/logical-operations.easy +++ b/Task/Logical-operations/EasyLang/logical-operations.easy @@ -1,16 +1,16 @@ proc logic a b . . - if a = 1 and b = 1 - r1 = 1 - . - if a = 1 or b = 1 - r2 = 1 - . - if a = 0 - r3 = 1 - . - print r1 & " " & r2 & " " & r3 + if a = 1 and b = 1 + r1 = 1 + . + if a = 1 or b = 1 + r2 = 1 + . + if a = 0 + r3 = 1 + . + print r1 & " " & r2 & " " & r3 . -call logic 0 0 -call logic 0 1 -call logic 1 0 -call logic 1 1 +logic 0 0 +logic 0 1 +logic 1 0 +logic 1 1 diff --git a/Task/Long-multiplication/EasyLang/long-multiplication.easy b/Task/Long-multiplication/EasyLang/long-multiplication.easy index 2d96153353..f33808a158 100644 --- a/Task/Long-multiplication/EasyLang/long-multiplication.easy +++ b/Task/Long-multiplication/EasyLang/long-multiplication.easy @@ -1,4 +1,4 @@ -proc mult a$ b$ . r$ . +func$ mult a$ b$ . a[] = number strchars a$ b[] = number strchars b$ len r[] len a[] + len b[] @@ -17,6 +17,6 @@ proc mult a$ b$ . r$ . r$ &= r[i] . . + return r$ . -call mult "18446744073709551616" "18446744073709551616" r$ -print r$ +print mult "18446744073709551616" "18446744073709551616" diff --git a/Task/Loops-Do-while/EasyLang/loops-do-while.easy b/Task/Loops-Do-while/EasyLang/loops-do-while.easy index 8b171912e3..c01591f4f2 100644 --- a/Task/Loops-Do-while/EasyLang/loops-do-while.easy +++ b/Task/Loops-Do-while/EasyLang/loops-do-while.easy @@ -2,5 +2,5 @@ value = 0 repeat value += 1 print value - until not (value mod 6 <> 0) + until value mod 6 = 0 . diff --git a/Task/Loops-For-with-a-specified-step/EasyLang/loops-for-with-a-specified-step.easy b/Task/Loops-For-with-a-specified-step/EasyLang/loops-for-with-a-specified-step.easy index 1ec266751a..befc83a04a 100644 --- a/Task/Loops-For-with-a-specified-step/EasyLang/loops-for-with-a-specified-step.easy +++ b/Task/Loops-For-with-a-specified-step/EasyLang/loops-for-with-a-specified-step.easy @@ -2,7 +2,3 @@ for i = 0 step 2 to 100 print i . -# Decimal step value -for i = 0 step 1.23 to 100 - print i -. diff --git a/Task/Loops-Infinite/EasyLang/loops-infinite.easy b/Task/Loops-Infinite/EasyLang/loops-infinite.easy index 763fa68e4f..6f5a9f1c6e 100644 --- a/Task/Loops-Infinite/EasyLang/loops-infinite.easy +++ b/Task/Loops-Infinite/EasyLang/loops-infinite.easy @@ -1,3 +1,3 @@ -while 0 = 0 +while 1 = 1 print "SPAM" . diff --git a/Task/MD5-Implementation/EasyLang/md5-implementation.easy b/Task/MD5-Implementation/EasyLang/md5-implementation.easy index 2177ef13d2..2db0a4b538 100644 --- a/Task/MD5-Implementation/EasyLang/md5-implementation.easy +++ b/Task/MD5-Implementation/EasyLang/md5-implementation.easy @@ -4,7 +4,7 @@ proc md5init . . md5k[i] = floor (0x100000000 * abs sin (i * 180 / pi)) . . -call md5init +md5init # proc md5 inp$ . s$ . subr addinp @@ -22,18 +22,18 @@ proc md5 inp$ . s$ . inp4 = 1 for i = 1 to len inp$ b = strcode substr inp$ i 1 - call addinp + addinp . b = 0x80 - call addinp + addinp while len inp[] mod 16 <> 14 or inp4 <> 1 b = 0 - call addinp + addinp . h = len inp$ * 8 for i = 1 to 4 b = h mod 0x100 - call addinp + addinp h = h div 0x100 . inp[] &= 0 @@ -92,11 +92,10 @@ proc md5 inp$ . s$ . repeat s$ = input until error = 1 - call md5 s$ h$ + md5 s$ h$ print h$ . input_data - a abc message digest diff --git a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy index 894493d598..d11005b78e 100644 --- a/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy +++ b/Task/Mandelbrot-set/EasyLang/mandelbrot-set.easy @@ -1,3 +1,5 @@ +# Mandelbrot +# res = 4 maxiter = 200 # @@ -14,14 +16,15 @@ scale = mid background 000 textsize 2 # -fastproc iter cx cy . it . - while xx + yy < 4 and it > 0 +fastfunc iter cx cy maxiter . + while xx + yy < 4 and it < maxiter y = 2 * x * y + cy x = xx - yy + cx xx = x * x yy = y * y - it -= 1 + it += 1 . + return it . proc draw . . clear @@ -29,10 +32,8 @@ proc draw . . cy = (scr_y - center_y) / scale for scr_x = 0 to 2 * mid - 1 cx = (scr_x - center_x) / scale - it = maxiter - call iter cx cy it - if it > 0 - it = maxiter - it + it = iter cx cy maxiter + if it < maxiter color3 it / 20 it / 100 it / 150 move scr_x / res scr_y / res rect 1 / res 1 / res @@ -58,6 +59,6 @@ on mouse_up center_y += (mid - center_y) * 3 / 4 scale /= 4 . - call draw + draw . -call draw +draw diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia index e6a1a7726a..92ddc5c85b 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-5.julia @@ -4,7 +4,7 @@ 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 light +direction, height = 45.0, 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) diff --git a/Task/Mandelbrot-set/Maxima/mandelbrot-set.maxima b/Task/Mandelbrot-set/Maxima/mandelbrot-set.maxima new file mode 100644 index 0000000000..ac49d35b09 --- /dev/null +++ b/Task/Mandelbrot-set/Maxima/mandelbrot-set.maxima @@ -0,0 +1,2 @@ +mandelbrot ([iterations, 30], [x, -2.4, 0.75], [y, -1.2, 1.2], + [grid,320,320])$ diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py index e930bc32ed..36cd656b0d 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-6.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-6.py @@ -4,7 +4,7 @@ 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 light +direction, height = 45.0, 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) diff --git a/Task/Mandelbrot-set/Raku/mandelbrot-set-1.raku b/Task/Mandelbrot-set/Raku/mandelbrot-set-1.raku index 9d7695417f..71cefc5251 100644 --- a/Task/Mandelbrot-set/Raku/mandelbrot-set-1.raku +++ b/Task/Mandelbrot-set/Raku/mandelbrot-set-1.raku @@ -1,9 +1,8 @@ constant MAX-ITERATIONS = 1000; my $width = +(@*ARGS[0] // 800); my $height = $width + $width %% 2; -say "P3"; +say "P1"; say "$width $height"; -say "255"; sub cut(Range $r, UInt $n where $n > 1 --> Seq) { $r.min, * + ($r.max - $r.min) / ($n - 1) ... $r.max @@ -15,17 +14,14 @@ 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 if $z.abs > 2; } - return 0; + return 1; } 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 + mandelbrot(0i, $_); }.rotor($width); .put for @lines[1..*].reverse; -.put for @lines[0]; -.put for @lines[1..*]; +.put for @lines; diff --git a/Task/Mastermind/EasyLang/mastermind.easy b/Task/Mastermind/EasyLang/mastermind.easy index 98e33877b8..0ad14ab4a5 100644 --- a/Task/Mastermind/EasyLang/mastermind.easy +++ b/Task/Mastermind/EasyLang/mastermind.easy @@ -1,3 +1,5 @@ +# Mastermind:w90 +# col[] = [ 802 990 171 229 950 808 ] len code[] 4 len guess[] 4 @@ -46,7 +48,7 @@ proc next_row . . linewidth 11 move 17 row * 11.5 + 7.5 line 60 row * 11.5 + 7.5 - call draw_guess + draw_guess move 73.5 row * 11.5 + 7.5 color 310 circle 5.0 @@ -77,28 +79,28 @@ proc rate . . . . . - call draw_rate row black white + draw_rate row black white color 531 linewidth 12 move 17 row * 11.5 + 7.5 line 60 row * 11.5 + 7.5 - call draw_guess + draw_guess row += 1 if black = 4 row = 8 . if row = 8 - call show_code + show_code timer 2 else - call next_row + next_row . . on timer row = -2 . proc new . . - call init_vars + init_vars for i to 4 code[i] = random 6 . @@ -132,28 +134,28 @@ proc new . . move c * 12 + 20 r * 11.5 + 7.5 circle 2 . - call draw_rate r 0 0 + draw_rate r 0 0 . guess[1] = 1 guess[2] = 1 guess[3] = 2 guess[4] = 2 - call next_row + next_row . proc do_move . . c = (mouse_x - 15) div 12 guess[c + 1] = guess[c + 1] mod 6 + 1 - call draw_guess + draw_guess . on mouse_down if row = -2 - call new + new elif mouse_y > row * 11.5 + 0.5 and mouse_y < row * 11.5 + 10.5 and row < 8 if mouse_x > 15 and mouse_x < 61 - call do_move + do_move elif mouse_x > 67 and mouse_x < 80 - call rate + rate . . . -call new +new diff --git a/Task/Maze-generation/EasyLang/maze-generation.easy b/Task/Maze-generation/EasyLang/maze-generation.easy index 557d4d3c68..cc5c352028 100644 --- a/Task/Maze-generation/EasyLang/maze-generation.easy +++ b/Task/Maze-generation/EasyLang/maze-generation.easy @@ -21,15 +21,15 @@ offs[] = [ 1 n -1 (-n) ] # proc m_maze pos . . m[pos] = 0 - call show_maze + show_maze d[] = [ 1 2 3 4 ] for i = 4 downto 1 d = random i dir = offs[d[d]] d[d] = d[i] - if m[pos + dir] = 1 and m[pos + 2 * dir] <> 0 + if m[pos + dir] = 1 and m[pos + 2 * dir] = 1 m[pos + dir] = 0 - call m_maze pos + 2 * dir + m_maze pos + 2 * dir . . . @@ -45,9 +45,9 @@ proc make_maze . . m[n * n - n + i] = 2 . h = 2 * random 15 - n + n * 2 * random 15 - call m_maze h + m_maze h m[endpos] = 0 endpos += n . -call make_maze -call show_maze +make_maze +show_maze diff --git a/Task/Maze-solving/EasyLang/maze-solving.easy b/Task/Maze-solving/EasyLang/maze-solving.easy index 12e7366be8..52f27f223c 100644 --- a/Task/Maze-solving/EasyLang/maze-solving.easy +++ b/Task/Maze-solving/EasyLang/maze-solving.easy @@ -20,7 +20,7 @@ proc show_maze . . offs[] = [ 1 n -1 (-n) ] proc m_maze pos . . m[pos] = 0 - call show_maze + show_maze d[] = [ 1 2 3 4 ] for i = 4 downto 1 d = random i @@ -28,7 +28,7 @@ proc m_maze pos . . d[d] = d[i] if m[pos + dir] = 1 and m[pos + 2 * dir] = 1 m[pos + dir] = 0 - call m_maze pos + 2 * dir + m_maze pos + 2 * dir . . . @@ -44,11 +44,11 @@ proc make_maze . . m[n * n - n + i] = 2 . h = 2 * random 15 - n + n * 2 * random 15 - call m_maze h + m_maze h m[endpos] = 0 . -call make_maze -call show_maze +make_maze +show_maze # proc mark pos col . . x = (pos - 1) mod n @@ -57,25 +57,29 @@ proc mark pos col . . move x * f + f / 4 y * f + f / 4 circle f / 3.5 . -proc solve dir0 pos . found . - call mark pos 900 +global found . +proc solve dir0 pos . . + if found = 1 + return + . + mark pos 900 sleep 0.05 if pos = endpos found = 1 - break 1 + return . of = random 4 - 1 for h = 1 to 4 dir = (h + of) mod1 4 posn = pos + offs[dir] - if dir <> dir0 and m[posn] = 0 and found = 0 - call solve (dir + 1) mod 4 + 1 posn found + if dir <> dir0 and m[posn] = 0 + solve (dir + 1) mod 4 + 1 posn if found = 0 - call mark posn 888 + mark posn 888 sleep 0.08 . . . . sleep 1 -call solve 0 n + 2 found +solve 0 n + 2 diff --git a/Task/Menu/FutureBasic/menu.basic b/Task/Menu/FutureBasic/menu.basic new file mode 100644 index 0000000000..b62b4c6a98 --- /dev/null +++ b/Task/Menu/FutureBasic/menu.basic @@ -0,0 +1,47 @@ +_window = 1 +begin enum 1 + _response + _popupBtn +end enum + +void local fn BuildPopUpMenu + menu 101 + menu 101, 0,, @"Select numbered menu item from the Three Pigs" + menu 101, 1,, @"1. fee fie" + menu 101, 2,, @"2. huff and puff" + menu 101, 3,, @"3. mirror mirror" + menu 101, 4,, @"4. tick tock" + menu 101, 5,, @" ?????????" +end fn + +void local fn BuildWindow + CGRect r = fn CGRectMake( 0, 0, 480, 360 ) + window _window, @"Rosetta Code Menu Task", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable + NSWindowStyleMaskMiniaturizable + + r = fn CGRectMake( 45, 240, 380, 34 ) + textlabel _response,, r, _window + ControlSetAlignment( _response, NSTextAlignmentCenter ) + + r = fn CGRectMake( 65, 200, 340, 34 ) + popupbutton _popupBtn,,,, r, YES + PopUpButtonSetMenu( _popupBtn, 101 ) +end fn + +void local fn DoMenu( menuID as long, itemID as long ) + select (menuID) + select (ItemID) + case 1 : ControlSetStringValue( _response, @"1. Sorry, wrong: From Jack the Giant Killer." ) + case 2 : ControlSetStringValue( _response, @"2. CORRECT!: From The Three Little Pigs." ) + case 3 : ControlSetStringValue( _response, @"3. Sorry, wrong: From Snow White and the Seven Dwarfs." ) + case 4 : ControlSetStringValue( _response, @"4. Sorry, wrong: From Tick Tock Goes the Clock Rhyme." ) + case 5 : ControlSetStringValue( _response, @"Surely you could just make a guess! Try again." ) + end select + end select +end fn + +fn BuildPopUpMenu +fn BuildWindow + +on menu fn DoMenu + +HandleEvents 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 index 07e5b79186..0d36d2ff25 100644 --- a/Task/Merge-and-aggregate-datasets/Harbour/merge-and-aggregate-datasets.harbour +++ b/Task/Merge-and-aggregate-datasets/Harbour/merge-and-aggregate-datasets.harbour @@ -1,66 +1,61 @@ -&& SQL-like INSERT command (note the variable number of arguments) -#xcommand INSERT INTO ( [, ] ) VALUES ( [, ] ) => ; -
->(dbAppend());
-> := [;
-> := ] +#xcommand INSERT INTO
( [, ] ) VALUE ( [, ] ) => ; +
->(dbAppend());
-> := [;
-> := ] +#xcommand INSERT INTO
( ) VALUES ( ) [, ( )] => ; + INSERT INTO
( ) VALUE ( ) ; + [; INSERT INTO
( ) VALUE ( )] +&& Singular cases (so we can use VALUES for all instances) +#xcommand INSERT INTO
() VALUE () => ; +
->(dbAppend());
-> := +#xcommand INSERT INTO
( ) VALUES ( ) => ; + INSERT INTO
( ) VALUE ( ) 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") + INSERT INTO patient (patient_id, lastname) VALUES (1001, "Hopper"), (4004, "Wirth"), ; + (3003, "Kemeny"), (2002, "Gosling"), (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) + INSERT INTO visit (patient_id, visit_date, score) VALUES (2002, ctod("2020-09-10"), 6.8), ; + (1001, ctod("2020-09-17"), 5.5), (4004, ctod("2020-09-24"), 8.4), ; + (2002, ctod("2020-10-08"), -999), (1001, ctod("1900-01-01"), 6.6), ; + (3003, ctod("2020-11-12"), -999), (4004, ctod("2020-11-05"), 7.0), ; + (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}, ; + rStruct := { {"patient_id", "n", 8, 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 + SELECT visit 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 + aAgg := {0, 0, 0.0, ctod("1900-01-01")} && initial values + DO WHILE ! Eof() .AND. xCurId == patient_id + aAgg := {1+aAgg[1], iif(score==-999,aAgg[2],1+aAgg[2]), ; + iif(score==-999, aAgg[3], score+aAgg[3]), max(visit_date, aAgg[4])} && update + SKIP + ENDDO + INSERT INTO report (patient_id, n, sum_score, avg_score, max_date) ; + VALUES (xCurId, aAgg[1], aAgg[3], aAgg[3]/aAgg[2], aAgg[4]) ENDDO SELECT report + INDEX ON patient_id TO report_id + + SELECT patient + SET RELATION TO patient_id INTO report ? "NUM", "PATIENT_ID", "LASTNAME", "N", "SUM_SCORE", "AVG_SCORE", "MAX_DATE" - LIST patient_id, lastname, n, sum_score, avg_score, max_date + LIST patient_id, lastname, report->n, report->sum_score, report->avg_score, report->max_date RETURN diff --git a/Task/Middle-three-digits/EasyLang/middle-three-digits.easy b/Task/Middle-three-digits/EasyLang/middle-three-digits.easy index a75abbb921..abd2af01a9 100644 --- a/Task/Middle-three-digits/EasyLang/middle-three-digits.easy +++ b/Task/Middle-three-digits/EasyLang/middle-three-digits.easy @@ -1,13 +1,13 @@ -proc midThreeDigits num . result$ . +func$ midThreeDigits num . trueNumber$ = abs num if (len trueNumber$ < 3) or (len trueNumber$ mod 2 = 0) - result$ = "error" + r$ = "error" else - result$ = substr trueNumber$ ((len trueNumber$ - 3) / 2 + 1) 3 + r$ = substr trueNumber$ ((len trueNumber$ - 3) / 2 + 1) 3 . + return r$ . numbers[] = [ 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 ] for i in numbers[] - call midThreeDigits i result$ - print result$ + print midThreeDigits i . diff --git a/Task/Miller-Rabin-primality-test/ARM-Assembly/miller-rabin-primality-test.arm b/Task/Miller-Rabin-primality-test/ARM-Assembly/miller-rabin-primality-test.arm new file mode 100644 index 0000000000..f17bdf9a30 --- /dev/null +++ b/Task/Miller-Rabin-primality-test/ARM-Assembly/miller-rabin-primality-test.arm @@ -0,0 +1,286 @@ +/* ARM assembly Raspberry PI */ +/* program testmiller.s */ + +/* for constantes see task include a file in arm assembly */ +/************************************/ +/* Constantes */ +/************************************/ +.include "../constantes.inc" + +.equ NBDIVISORS, 2000 + +//.include "../../ficmacros32.inc" @ use for developper debugging +/*******************************************/ +/* Initialized data */ +/*******************************************/ +.data +szMessStartPgm: .asciz "Program 32 bits start \n" +szMessEndPgm: .asciz "Program normal end.\n" +szMessErrorArea: .asciz "\033[31mError : area divisors too small.\n" +szMessPrime: .asciz " is prime !!!.\n" +szMessNotPrime: .asciz " is not prime !!!.\n" +szCarriageReturn: .asciz "\n" + +.align 4 +iGraine: .int 123456 +/*******************************************/ +/* UnInitialized data */ +/*******************************************/ +.bss +.align 4 +sZoneConv: .skip 24 +/*******************************************/ +/* code section */ +/*******************************************/ +.text +.global main +main: @ program start + ldr r0,iAdrszMessStartPgm @ display start message + bl affichageMess + ldr r4,iStart @ start number + ldr r5,iLimit @ end number + tst r4,#1 + addeq r4,#1 @ start with odd number +1: + mov r0,r4 + ldr r1,iAdrsZoneConv + bl conversion10 @ decimal conversion + ldr r0,iAdrsZoneConv + bl affichageMess + mov r0,r4 + bl isPrimeMiller @ test miller rabin + cmp r0,#0 + beq 2f + ldr r0,iAdrszMessPrime + bl affichageMess + b 3f +2: + ldr r0,iAdrszMessNotPrime + bl affichageMess +3: + add r4,r4,#2 + cmp r4,r5 + ble 1b + + ldr r0,iAdrszMessEndPgm @ display end message + bl affichageMess + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc 0 @ perform system call +iAdrszMessStartPgm: .int szMessStartPgm +iAdrszMessEndPgm: .int szMessEndPgm +iAdrszCarriageReturn: .int szCarriageReturn +iAdrsZoneConv: .int sZoneConv +iAdrszMessPrime: .int szMessPrime +iAdrszMessNotPrime: .int szMessNotPrime +iStart: .int 4294967270 +iLimit: .int 4294967295 + + +/***************************************************/ +/* check if a number is prime test miller rabin */ +/***************************************************/ +/* r0 contains the number */ +/* r0 return 1 if prime 0 else */ +@2147483647 +@4294967297 +@131071 +isPrimeMiller: + push {r1-r6,lr} @ save registers + cmp r0,#1 @ control 0 or 1 + movls r0,#0 + bls 100f + cmp r0,#2 @ control = 2 + moveq r0,#1 + beq 100f + tst r0,#1 + moveq r0,#0 @ even + beq 100f + mov r1,#5 @ loop number + bl testMiller +100: + pop {r1-r6,pc} +/***************************************************/ +/* test miller rabin algorithme wikipedia */ +/* unsigned */ +/***************************************************/ +/* r0 contains number */ +/* r1 contains parameter */ +/* r0 return 1 if prime 0 if composite */ +testMiller: + push {r1-r9,lr} @ save registers + mov r4,r0 @ N + mov r7,r1 @ loop maxi + sub r3,r0,#1 @ D + mov r2,#2 + mov r6,#0 @ S +1: @ compute D * 2 power S + lsr r3,#1 @ D= D/2 + add r6,r6,#1 @ increment S + tst r3,#1 @ D even ? + beq 1b +2: + mov r8,#0 @ loop counter + sub r5,r0,#3 +3: + mov r0,r5 + bl genereraleas + add r0,r0,#2 @ alea (entre 2 et n-1) + mov r1,r3 @ exposant = D + mov r2,r4 @ modulo N + bl moduloPuR32 + cmp r0,#1 + beq 5f + sub r1,r4,#1 @ n -1 + cmp r0,r1 + beq 5f + sub r9,r6,#1 @ S - 1 +4: + mov r2,r0 + umull r0,r1,r2,r0 @ compute square + mov r2,r4 @ and compute modulo N + bl division32R2023 + mov r0,r2 + cmp r0,#1 + moveq r0,#0 @ composite + beq 100f + sub r1,r4,#1 @ n -1 + cmp r0,r1 + beq 5f + subs r9,r9,#1 + bge 4b + mov r0,#0 @ composite + b 100f +5: + add r8,r8,#1 + cmp r8,r7 + blt 3b + mov r0,#1 @ prime +100: + pop {r1-r9,pc} +/********************************************************/ +/* Calcul modulo de b puissance e modulo m */ +/* Exemple 4 puissance 13 modulo 497 = 445 */ +/* */ +/********************************************************/ +/* r0 nombre */ +/* r1 exposant */ +/* r2 modulo */ +/* r0 return result */ +moduloPuR32: + push {r1-r6,lr} @ save registers + cmp r0,#0 @ control <> zero + beq 100f + cmp r2,#0 @ control <> zero + beq 100f +1: + mov r4,r2 @ save modulo + mov r5,r1 @ save exposant + mov r6,r0 @ save base + mov r3,#1 @ start result + + mov r1,#0 @ division r0,r1 by r2 + bl division32R2023 + mov r6,r2 @ base <- remainder +2: + tst r5,#1 @ exposant even or odd + beq 3f + umull r0,r1,r6,r3 @ multiplication base + mov r2,r4 @ and compute modulo N + bl division32R2023 + mov r3,r2 @ result <- remainder +3: + umull r0,r1,r6,r6 @ compute base square + mov r2,r4 @ and compute modulo N + bl division32R2023 + mov r6,r2 @ base <- remainder + + lsr r5,#1 @ left shift 1 bit + cmp r5,#0 @ end ? + bne 2b + mov r0,r3 +100: + pop {r1-r6,pc} + +/***************************************************/ +/* division number 64 bits in 2 registers by number 32 bits */ +/* unsigned */ +/***************************************************/ +/* r0 contains lower part dividende */ +/* r1 contains upper part dividende */ +/* r2 contains divisor */ +/* r0 return lower part quotient */ +/* r1 return upper part quotient */ +/* r2 return remainder */ +division32R2023: + push {r3-r6,lr} @ save registers + mov r4,r2 @ save divisor + mov r5,#0 @ init upper part divisor + mov r2,r0 @ save dividende + mov r3,r1 + mov r0,#0 @ init result + mov r1,#0 + mov r6,#0 @ init shift counter +1: @ loop shift divisor + cmp r5,#0 @ upper divisor <0 + blt 2f + cmp r5,r3 + cmpeq r4,r2 + bhs 2f @ new divisor > dividende + lsl r5,#1 @ shift left one bit upper divisor + lsls r4,#1 @ shift left one bit lower divisor + orrcs r5,r5,#1 @ move bit 31 lower on upper + add r6,r6,#1 @ increment shift counter + b 1b +2: @ loop 2 + lsl r1,#1 @ shift left one bit upper quotient + lsls r0,#1 @ shift left one bit lower quotient + orrcs r1,#1 @ move bit 31 lower on upper + cmp r5,r3 @ compare divisor and dividende + cmpeq r4,r2 + bhi 3f + subs r2,r2,r4 @ < sub divisor from dividende lower + sbc r3,r3,r5 @ and upper + orr r0,r0,#1 @ move 1 on quotient +3: + lsr r4,r4,#1 @ shift right one bit upper divisor + lsrs r5,#1 @ and lower + orrcs r4,#0x80000000 @ move bit 0 upper to 31 bit lower + subs r6,#1 @ decrement shift counter + bge 2b @ if > 0 loop 2 + +100: + pop {r3-r6,pc} + + +/***************************************************/ +/* 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/Minesweeper-game/EasyLang/minesweeper-game.easy b/Task/Minesweeper-game/EasyLang/minesweeper-game.easy index 5cce1654f2..96d2a19eb8 100644 --- a/Task/Minesweeper-game/EasyLang/minesweeper-game.easy +++ b/Task/Minesweeper-game/EasyLang/minesweeper-game.easy @@ -8,11 +8,12 @@ subr initvars indx = -1 no_time = 0 . -proc getind r c . ind . +func getind r c . ind = -1 if r >= 0 and r <= 6 and c >= 0 and c <= 7 ind = r * 8 + c + 1 . + return ind . proc draw_cell ind h . . ind -= 1 @@ -54,7 +55,7 @@ proc open ind . . cell[ind] = 2 flag[ind] = 0 color 686 - call draw_cell ind cnt[ind] + draw_cell ind cnt[ind] if cnt[ind] = 0 ind -= 1 r0 = ind div 8 @@ -62,8 +63,7 @@ proc open ind . . for r = r0 - 1 to r0 + 1 for c = c0 - 1 to c0 + 1 if r <> r0 or c <> c0 - call getind r c ind - call open ind + open getind r c . . . @@ -77,7 +77,7 @@ proc show_mines m . . if m = -1 color 353 . - call draw_cell ind m + draw_cell ind m . . . @@ -97,24 +97,24 @@ proc upd_info . . . . if nc = 8 - call outp 484 "Well done" - call show_mines -1 + outp 484 "Well done" + show_mines -1 state = 1 else - call outp 464 8 - nm & " mines left" + outp 464 8 - nm & " mines left" . . proc test ind . . if cell[ind] < 2 and flag[ind] = 0 if cell[ind] = 1 - call show_mines -1 + show_mines -1 color 686 - call draw_cell ind -2 - call outp 844 "B O O M !" + draw_cell ind -2 + outp 844 "B O O M !" state = 1 else - call open ind - call upd_info + open ind + upd_info . . . @@ -126,7 +126,7 @@ proc start . . cnt[ind] = 0 cell[ind] = 0 flag[ind] = 0 - call draw_cell ind 0 + draw_cell ind 0 . n = 8 while n > 0 @@ -138,7 +138,7 @@ proc start . . cell[ind] = 1 for rx = r - 1 to r + 1 for cx = c - 1 to c + 1 - call getind rx cx ind + ind = getind rx cx if ind > -1 cnt[ind] += 1 . @@ -146,8 +146,8 @@ proc start . . . . . - call initvars - call outp 464 "" + initvars + outp 464 "" textsize 4 move 5 93 text "Minesweeper - 8 mines" @@ -164,15 +164,15 @@ on mouse_down color 464 rect 33 11 . - call getind (mouse_y - 2) div 12 (mouse_x - 2) div 12 indx + indx = getind ((mouse_y - 2) div 12) ((mouse_x - 2) div 12) ticks0 = ticks elif state = 3 - call start + start . . on mouse_up if state = 0 and indx <> -1 - call test indx + test indx . indx = -1 . @@ -183,8 +183,8 @@ on timer elif state = 2 state = 3 elif no_time = 0 and ticks > 3000 - call outp 844 "B O O M !" - call show_mines -2 + outp 844 "B O O M !" + show_mines -2 state = 2 timer 1 else @@ -196,8 +196,8 @@ on timer if flag[indx] = 1 opt = -3 . - call draw_cell indx opt - call upd_info + draw_cell indx opt + upd_info . indx = -1 . @@ -216,4 +216,4 @@ on timer timer 0.1 . . -call start +start diff --git a/Task/Modular-inverse/EasyLang/modular-inverse.easy b/Task/Modular-inverse/EasyLang/modular-inverse.easy index 595869e5bc..d2e7ab6e22 100644 --- a/Task/Modular-inverse/EasyLang/modular-inverse.easy +++ b/Task/Modular-inverse/EasyLang/modular-inverse.easy @@ -1,8 +1,8 @@ -proc mod_inv a b . x1 . +func mod_inv a b . b0 = b x1 = 1 if b = 1 - break 1 + return 1 . while a > 1 q = a div b @@ -16,6 +16,6 @@ proc mod_inv a b . x1 . if x1 < 0 x1 += b0 . + return x1 . -call mod_inv 42 2017 r -print r +print mod_inv 42 2017 diff --git a/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy b/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy index df7733167a..0fe197b75a 100644 --- a/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy +++ b/Task/Monte-Carlo-methods/EasyLang/monte-carlo-methods.easy @@ -1,4 +1,4 @@ -proc mc n . . +func mc n . for i = 1 to n x = randomf y = randomf @@ -6,10 +6,10 @@ proc mc n . . hit += 1 . . - print 4.0 * hit / n + return 4.0 * hit / n . numfmt 4 0 -call mc 10000 -call mc 100000 -call mc 1000000 -call mc 10000000 +print mc 10000 +print mc 100000 +print mc 1000000 +print mc 10000000 diff --git a/Task/Morse-code/EasyLang/morse-code.easy b/Task/Morse-code/EasyLang/morse-code.easy index 25bb272e6f..c84662ff1a 100644 --- a/Task/Morse-code/EasyLang/morse-code.easy +++ b/Task/Morse-code/EasyLang/morse-code.easy @@ -27,5 +27,5 @@ proc morse ch$ . . . . for ch$ in strchars txt$ - call morse ch$ + morse ch$ . diff --git a/Task/N-queens-problem/EasyLang/n-queens-problem.easy b/Task/N-queens-problem/EasyLang/n-queens-problem.easy index cd29b0eb23..2106313a4f 100644 --- a/Task/N-queens-problem/EasyLang/n-queens-problem.easy +++ b/Task/N-queens-problem/EasyLang/n-queens-problem.easy @@ -1,49 +1,49 @@ subr show_sol - print "Solution " & n_sol - print "" - for i = 1 to n - write " " - for j = 1 to n - if j = x[i] - write "Q " - else - write ". " + print "Solution " & n_sol + print "" + for i = 1 to n + write " " + for j = 1 to n + if j = x[i] + write "Q " + else + write ". " + . . - . - print "" - . - print "" + print "" + . + print "" . subr test - ok = 1 - for i = 1 to y - 1 - if x[y] = x[i] or abs (x[i] - x[y]) = abs (y - i) - ok = 0 - . - . + ok = 1 + for i = 1 to y - 1 + if x[y] = x[i] or abs (x[i] - x[y]) = abs (y - i) + ok = 0 + . + . . n = 8 len x[] n y = 1 x[1] = 1 while y >= 1 - call test - if ok = 1 and y + 1 <= n - y += 1 - x[y] = 1 - else - if ok = 1 - n_sol += 1 - if n_sol <= 1 - call show_sol + test + if ok = 1 and y + 1 <= n + y += 1 + x[y] = 1 + else + if ok = 1 + n_sol += 1 + if n_sol <= 1 + show_sol + . . - . - while y >= 1 and x[y] = n - y -= 1 - . - if y >= 1 - x[y] += 1 - . - . + while y >= 1 and x[y] = n + y -= 1 + . + if y >= 1 + x[y] += 1 + . + . . print n_sol & " solutions" diff --git a/Task/Nth-root/EasyLang/nth-root.easy b/Task/Nth-root/EasyLang/nth-root.easy index 05ffee2fc4..7cc72ab579 100644 --- a/Task/Nth-root/EasyLang/nth-root.easy +++ b/Task/Nth-root/EasyLang/nth-root.easy @@ -1,19 +1,20 @@ -proc power x n . r . +func power x n . r = 1 for i = 1 to n r *= x . + return r . -proc nth_root x n . r . +func nth_root x n . r = 2 repeat - call power r n - 1 p + p = power r (n - 1) d = (x / p - r) / n r += d until abs d < 0.0001 . + return r . -call power 3.1416 10 x -call nth_root x 10 r numfmt 4 0 -print r +x = power 3.1416 10 +print nth_root x 10 diff --git a/Task/Nth/EasyLang/nth.easy b/Task/Nth/EasyLang/nth.easy index 8b999cc977..4375f85a68 100644 --- a/Task/Nth/EasyLang/nth.easy +++ b/Task/Nth/EasyLang/nth.easy @@ -1,36 +1,29 @@ -proc nth num . ordinal$ . - num$ = num - lastTwoDigits$ = substr num$ len num$ - 1 2 - lastDigit$ = substr num$ len num$ 1 - if lastTwoDigits$ = "11" or lastTwoDigits$ = "12" or lastTwoDigits$ = "13" - ordinal$ = num$ & "th" - elif lastDigit$ = "1" - ordinal$ = num$ & "st" - elif lastDigit$ = "2" - ordinal$ = num$ & "nd" - elif lastDigit$ = "3" - ordinal$ = num$ & "rd" +func$ nth num . + last2 = num mod 100 + last = num mod 10 + if last2 >= 11 and last2 <= 13 + return num & "th" + elif last = 1 + return num & "st" + elif last = 2 + return num & "nd" + elif last = 3 + return num & "rd" else - ordinal$ = num$ & "th" + return num & "th" . . print "0 to 25:" for i = 0 to 25 - call nth i ordinal$ - write ordinal$ - write " " + write nth i & " " . print "" print "250 to 265:" for i = 250 to 265 - call nth i ordinal$ - write ordinal$ - write " " + write nth i & " " . print "" print "1000 to 1025:" for i = 1000 to 1025 - call nth i ordinal$ - write ordinal$ - write " " + write nth i & " " . diff --git a/Task/Numbers-with-equal-rises-and-falls/EasyLang/numbers-with-equal-rises-and-falls.easy b/Task/Numbers-with-equal-rises-and-falls/EasyLang/numbers-with-equal-rises-and-falls.easy new file mode 100644 index 0000000000..c1f119b1a6 --- /dev/null +++ b/Task/Numbers-with-equal-rises-and-falls/EasyLang/numbers-with-equal-rises-and-falls.easy @@ -0,0 +1,39 @@ +fastfunc risefall n . + if n < 10 + return 1 + . + prev = -1 + while n > 0 + d = n mod 10 + if prev >= 0 + if d < prev + rises += 1 + elif d > prev + falls += 1 + . + . + prev = d + n = n div 10 + . + if rises = falls + return 1 + . + return 0 +. +numfmt 0 4 +n = 1 +repeat + if risefall n = 1 + cnt += 1 + if cnt <= 200 + write n + if cnt mod 20 = 0 + print "" + . + . + . + until cnt = 1e7 + n += 1 +. +print "" +print n diff --git a/Task/Numbers-with-equal-rises-and-falls/Quackery/numbers-with-equal-rises-and-falls.quackery b/Task/Numbers-with-equal-rises-and-falls/Quackery/numbers-with-equal-rises-and-falls.quackery new file mode 100644 index 0000000000..0328fc698b --- /dev/null +++ b/Task/Numbers-with-equal-rises-and-falls/Quackery/numbers-with-equal-rises-and-falls.quackery @@ -0,0 +1,35 @@ + [ [] swap + [ 10 /mod + rot join swap + dup 0 = until ] + drop ] is digits ( n --> [ ) + + [ stack ] is rises + [ stack ] is falls + + [ 0 rises put + 0 falls put + digits + behead swap witheach + [ tuck 2dup < iff + [ 1 rises tally + 2drop ] done + > if + [ 1 falls tally ] ] + drop + rises take + falls take = ] is equal ( n --> b ) + + [] 0 + [ 1+ dup equal if + [ tuck join swap ] + over size 200 = until ] + drop + echo + cr cr + 0 0 + [ 1+ dup equal if + [ dip 1+ ] + over 10000000 = until ] + nip + echo diff --git a/Task/Odd-word-problem/FutureBasic/odd-word-problem.basic b/Task/Odd-word-problem/FutureBasic/odd-word-problem.basic new file mode 100644 index 0000000000..0d9f293f4c --- /dev/null +++ b/Task/Odd-word-problem/FutureBasic/odd-word-problem.basic @@ -0,0 +1,29 @@ +begin globals +short ndx : bool odd : cfstringref stream +end globals + +local fn recursion + cfstringref ch = mid( stream, ndx, 1 ) + if fn StringContainsString( @",;:. ", ch ) == no + ndx++ + if odd then fn recursion : print ch; ¬ + else print ch; : fn recursion + end if +end fn + +local fn oddWordTask( s as cfstringref ) + ndx = 0 : odd = no : stream = s + print : print, stream : print, + while ndx < len( stream ) + fn recursion : print mid( stream, ndx, 1 ); + odd = yes - odd : ndx++ + wend + print +end fn + +window 1, @"Odd word task in FutureBasic", (0,0,310,155) +fn oddWordTask( @"what,is,the;meaning,of:life." ) +fn oddWordTask( @"we,are;not,in,kansas;any,more." ) +fn oddWordTask( @"This also works with normal spaces." ) + +HandleEvents diff --git a/Task/One-dimensional-cellular-automata/00-TASK.txt b/Task/One-dimensional-cellular-automata/00-TASK.txt index 4949d54e36..0a11f75a5b 100644 --- a/Task/One-dimensional-cellular-automata/00-TASK.txt +++ b/Task/One-dimensional-cellular-automata/00-TASK.txt @@ -14,3 +14,6 @@ If, in the following table, a live cell is represented by 1 and a dead cell by 0 1'''1'''0 -> 1 # Needs one neighbour to survive 1'''1'''1 -> 0 # Starved to death. +;Related tasks: +* [[Elementary_cellular_automaton|Elementary cellular automaton]] + diff --git a/Task/Ordered-words/Acornsoft-Lisp/ordered-words.lisp b/Task/Ordered-words/Acornsoft-Lisp/ordered-words.lisp new file mode 100644 index 0000000000..9a710d057a --- /dev/null +++ b/Task/Ordered-words/Acornsoft-Lisp/ordered-words.lisp @@ -0,0 +1,28 @@ +(defun longest-ordered-words () + (find-longest-ordered-words + (open 'notes/unixdict!.txt t))) + +(defun find-longest-ordered-words + (h (len . 0) (word) (words)) + (loop + (until (eof h) + (close h) + words) + (setq word (readline h)) + (cond ((lessp (chars word) len)) + ((not (ordered-p word))) + ((eq (chars word) len) + (setq words (cons word words))) + (t + (setq len (chars word)) + (setq words (list word)))))) + +(defun ordered-p (word) + (nondecreasing-p + (mapc ordinal (explode word)))) + +(defun nondecreasing-p (numbers) + (or (null numbers) + (null (cdr numbers)) + (and (not (greaterp (car numbers) (cadr numbers))) + (nondecreasing-p (cdr numbers))))) diff --git a/Task/Palindrome-detection/Acornsoft-Lisp/palindrome-detection.lisp b/Task/Palindrome-detection/Acornsoft-Lisp/palindrome-detection.lisp new file mode 100644 index 0000000000..83adae5ae6 --- /dev/null +++ b/Task/Palindrome-detection/Acornsoft-Lisp/palindrome-detection.lisp @@ -0,0 +1,59 @@ +(defun palindrome-type (text) + (cond ((exact-palindrom-p text) 'exact) + ((inexact-palindrome-p text) 'inexact) + (t 'not-a-palindrome))) + +(defun exact-palindrom-p (text) + (eq text (implode (reverse (explode text))))) + +(defun inexact-palindrome-p (text) + (exact-palindrom-p (implode (normalise (explode text))))) + +(defun reverse (list (result . ())) + (map '(lambda (e) (setq result (cons e result))) + list) + result) + +(defun normalise (chars) + (cond ((null chars) + nil) + ((not (alphanumeric-p (car chars))) + (normalise (cdr chars))) + ((upper-case-p (car chars)) + (cons (to-lower-case (car chars)) + (normalise (cdr chars)))) + (t + (cons (car chars) (normalise (cdr chars)))))) + +(defun between-p (lowest-value n highest-value) + (not (or (lessp n lowest-value) + (greaterp n highest-value)))) + +(defun alphanumeric-p (ch) + (or (lower-case-p ch) (upper-case-p ch) (digit-p ch))) + +(defun digit-p (ch) + (between-p (add1 (ordinal '/)) + (ordinal ch) + (sub1 (ordinal ':)))) + +(defun upper-case-p (ch) + (between-p (ordinal 'A) (ordinal ch) (ordinal 'Z))) + +(defun lower-case-p (ch) + (between-p (ordinal 'a) (ordinal ch) (ordinal 'z))) + +(defun to-lower-case (ch) + (character (plus (ordinal ch) + (difference (ordinal 'a) (ordinal 'A))))) + +(defun examples () + (map '(lambda (text) + (printc '!" text '!" + '! is! (palindrome-type text))) + '(a + abba Abba + abcba + baba + Able! was! I! ere! I! saw! Elba!! + In! girum! imus! nocte,! et! consumimur! igni))) diff --git a/Task/Palindrome-detection/EasyLang/palindrome-detection.easy b/Task/Palindrome-detection/EasyLang/palindrome-detection.easy new file mode 100644 index 0000000000..5a80f5f29d --- /dev/null +++ b/Task/Palindrome-detection/EasyLang/palindrome-detection.easy @@ -0,0 +1,20 @@ +func$ reverse s$ . + a$[] = strchars s$ + for i = 1 to len a$[] div 2 + swap a$[i] a$[len a$[] - i + 1] + . + return strjoin a$[] +. +func palin s$ . + if s$ = reverse s$ + return 1 + . + return 0 +. +for s$ in [ "rotor" "rosetta" "step on no pets" "été" "🦊😀🦊" ] + if palin s$ = 1 + print s$ & " is a palindrome" + else + print s$ & " is not a palindrome" + . +. diff --git a/Task/Perfect-totient-numbers/Maxima/perfect-totient-numbers.maxima b/Task/Perfect-totient-numbers/Maxima/perfect-totient-numbers.maxima new file mode 100644 index 0000000000..762191fa86 --- /dev/null +++ b/Task/Perfect-totient-numbers/Maxima/perfect-totient-numbers.maxima @@ -0,0 +1,17 @@ +totientseq(n):=block( + [depth:1,L:n], + while totient(L)#1 do (L:totient(L),depth:depth+1), + j:n, + makelist(j:totient(j),depth), + append([n],%%))$ + +perfect_totient_p(n):=if n=1 then false else is(equal(n,apply("+",rest(totientseq(n)))))$ + +/* Function that returns a list of the first len perfect totient numbers */ +perfect_totient_count(len):=block( + [i:1,count:0,result:[]], + while count { + JFrame.setDefaultLookAndFeelDecorated(true); + JFrame frame = new JFrame("Peripheral Drift Illusion"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.add( new PeripheralDrift() ); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setResizable(false); + frame.setVisible(true); + } ); + } +} + +final class PeripheralDrift extends JPanel { + + public PeripheralDrift() { + setPreferredSize( new Dimension(600, 600) ); + setBackground(LIGHT_OLIVE); + } + + @Override + public void paintComponent(Graphics aGraphics) { + super.paintComponent(aGraphics); + Graphics2D graphics2D = (Graphics2D) aGraphics; + graphics2D.setStroke( new BasicStroke(3.0F) ); + drawPeripheralDrift(graphics2D); + } + + private void drawPeripheralDrift(Graphics2D aGraphics2D) { + final int panelWidth = getWidth(); + final int outerSquare = panelWidth * 80 / 100; + final int border = ( panelWidth - outerSquare ) / 2; + final int cellSize = outerSquare / 12; + final int boxSize = cellSize * 75 / 100; + final int margin = ( cellSize - boxSize ) / 2; + + for ( int row = 0; row < 12; row++ ) { + int x = border + margin + row * cellSize; + for ( int col = 0; col < 12; col++ ) { + int y = border + margin + col * cellSize; + drawBox(x, y, boxSize, EDGES.get(col).get(row), aGraphics2D); + } + } + } + + private void drawBox(int aX, int aY, int aSize, Edg aEdge, Graphics2D aGraphics2D) { + aGraphics2D.setColor(PALE_BLUE); + aGraphics2D.fillRect(aX, aY, aSize, aSize); + + aGraphics2D.setColor(COLORS.get(aEdge.index).get(0)); + aGraphics2D.drawLine(aX, aY, aX + aSize, aY); + aGraphics2D.setColor(COLORS.get(aEdge.index).get(1)); + aGraphics2D.drawLine(aX + aSize, aY, aX + aSize, aY + aSize); + aGraphics2D.setColor(COLORS.get(aEdge.index).get(2)); + aGraphics2D.drawLine(aX + aSize, aY + aSize, aX, aY + aSize); + aGraphics2D.setColor(COLORS.get(aEdge.index).get(3)); + aGraphics2D.drawLine(aX, aY + aSize, aX, aY); + } + + private enum Edg { + + TL(0), TR(1), BR(2), BL(3); + + private Edg(int aIndex) { + index = aIndex; + } + + private final int index; + + } + + private static final List> EDGES = List.of( + List.of( Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR ), + List.of( Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL ), + List.of( Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL ), + List.of( Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL ), + List.of( Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL ), + List.of( Edg.BR, Edg.BR, Edg.TR, Edg.BR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR ), + List.of( Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR ), + List.of( Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR ), + List.of( Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR ), + List.of( Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL ), + List.of( Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL ), + List.of( Edg.TR, Edg.TR, Edg.TL, Edg.TL, Edg.BL, Edg.BL, Edg.BR, Edg.BR, Edg.TR, Edg.TR, Edg.TL, Edg.TL ) ); + + private static final List> COLORS = List.of( + List.of( Color.WHITE, Color.BLACK, Color.BLACK, Color.WHITE ), + List.of( Color.WHITE, Color.WHITE, Color.BLACK, Color.BLACK ), + List.of( Color.BLACK, Color.WHITE, Color.WHITE, Color.BLACK ), + List.of( Color.BLACK, Color.BLACK, Color.WHITE, Color.WHITE ) ); + + private static final Color PALE_BLUE = new Color(51, 77, 255); + private static final Color LIGHT_OLIVE = new Color(204, 204, 0); + +} diff --git a/Task/Permutations-Derangements/Acornsoft-Lisp/permutations-derangements.lisp b/Task/Permutations-Derangements/Acornsoft-Lisp/permutations-derangements.lisp new file mode 100644 index 0000000000..87d055076a --- /dev/null +++ b/Task/Permutations-Derangements/Acornsoft-Lisp/permutations-derangements.lisp @@ -0,0 +1,68 @@ +(defun subfact (n) + (cond + ((eq n 0) 1) + ((eq n 1) 0) + (t (times (sub1 n) + (plus (subfact (sub1 n)) + (subfact (sub1 (sub1 n)))))))) + +(defun count-derangements (n (count . 0)) + (visit-derangements (range 1 n) + '(lambda (d) (setq count (add1 count)))) + count) + +(defun visit-derangements (original-items d-visitor) + (visit-permutations original-items + '(lambda (p) + (cond ((derangement-p original-items p) + (d-visitor p)))))) + +(defun derangement-p (original d (fail . nil)) + (map '(lambda (a b) (cond ((eq a b) (setq fail t)))) + original + d) + (not fail)) + +(defun visit-permutations (items p-visitor) + (visit-permutations-1 items '())) + +(defun visit-permutations-1 (items perm) + (cond + ((null items) (p-visitor (reverse perm))) + (t + (map '(lambda (i) + (visit-permutations-1 + (without i items) + (cons i perm))) + items)))) + +'( Utilities ) + +(defun without (i items) + (cond ((null items) '()) + ((eq (car items) i) (cdr items)) + (t (cons (car items) (without i (cdr items)))))) + +(defun reverse (list (result . ())) + (map '(lambda (e) (setq result (cons e result))) + list) + result) + +(defun range (from to) + (cond ((greaterp from to) '()) + (t (cons from (range (add1 from) to))))) + +'( Examples ) + +(defun examples () + (show-derangements '(1 2 3 4)) + (printc) + (map '(lambda (i) + (printc i + '! (count-derangements i) + '! (subfact i))) + (range 0 8))) + +(defun show-derangements (items) + (printc 'Derangements! of! items) + (visit-derangements items print)) diff --git a/Task/Permutations-Derangements/Common-Lisp/permutations-derangements.lisp b/Task/Permutations-Derangements/Common-Lisp/permutations-derangements.lisp new file mode 100644 index 0000000000..731610123c --- /dev/null +++ b/Task/Permutations-Derangements/Common-Lisp/permutations-derangements.lisp @@ -0,0 +1,53 @@ +(defun subfact (n) + (cond + ((= n 0) 1) + ((= n 1) 0) + (t (* (- n 1) + (+ (subfact (- n 1)) + (subfact (- n 2))))))) + +(defun count-derangements (n) + (let ((count 0)) + (visit-derangements (range 1 n) + (lambda (d) (declare (ignore d)) (incf count))) + count)) + +(defun visit-derangements (items visitor) + (visit-permutations items + (lambda (p) + (when (derangement-p items p) + (funcall visitor p))))) + +(defun derangement-p (original d) + (notany #'equal original d)) + +(defun visit-permutations (items visitor) + (labels + ((vp (items perm) + (cond ((null items) + (funcall visitor (reverse perm))) + (t + (mapc (lambda (i) + (vp (remove i items) + (cons i perm))) + items))))) + (vp items '()))) + +(defun range (start end) + (loop for i from start to end collect i)) + +(defun examples () + (show-derangements '(1 2 3 4)) + (format t "~%n counted !n~%") + (dotimes (i 10) + (format t "~S ~7@S ~7@S~%" + i + (count-derangements i) + (subfact i))) + (format t "~%!20 = ~S~2%" (subfact 20))) + +(defun show-derangements (items) + (format t "~%Derangements of ~S~%" items) + (visit-derangements items + (lambda (d) + (format t " ~S~%" d)))) diff --git a/Task/Permutations/EasyLang/permutations.easy b/Task/Permutations/EasyLang/permutations.easy index 2213c82a0b..ea80f9b9db 100644 --- a/Task/Permutations/EasyLang/permutations.easy +++ b/Task/Permutations/EasyLang/permutations.easy @@ -1,7 +1,7 @@ proc permlist k . list[] . for i = k to len list[] swap list[i] list[k] - call permlist k + 1 list[] + permlist k + 1 list[] swap list[k] list[i] . if k = len list[] @@ -9,4 +9,4 @@ proc permlist k . list[] . . . l[] = [ 1 2 3 ] -call permlist 1 l[] +permlist 1 l[] diff --git a/Task/Polyspiral/EasyLang/polyspiral.easy b/Task/Polyspiral/EasyLang/polyspiral.easy new file mode 100644 index 0000000000..62be7e4f19 --- /dev/null +++ b/Task/Polyspiral/EasyLang/polyspiral.easy @@ -0,0 +1,20 @@ +color 944 +linewidth 0.3 +on animate + clear + incr = (incr + 0.05) mod 360 + x1 = 50 + y1 = 50 + length = 1 + angle = incr + move x1 y1 + for i = 1 to 150 + x2 = x1 + cos angle * length + y2 = y1 + sin angle * length + line x2 y2 + x1 = x2 + y1 = y2 + length += 1 + angle = (angle + incr) mod 360 + . +. diff --git a/Task/Polyspiral/Zig/polyspiral.zig b/Task/Polyspiral/Zig/polyspiral.zig new file mode 100644 index 0000000000..f6828deff9 --- /dev/null +++ b/Task/Polyspiral/Zig/polyspiral.zig @@ -0,0 +1,50 @@ +const std = @import("std"); +const rl = @cImport({ + @cInclude("raylib.h"); + @cInclude("raymath.h"); +}); + +const SCREEN_WIDTH = 640; +const SCREEN_HEIGHT = 480; +var incr: f32 = 0; + +pub fn main() void { + rl.SetConfigFlags(rl.FLAG_WINDOW_RESIZABLE | rl.FLAG_VSYNC_HINT); + rl.SetTargetFPS(60); + + rl.InitWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Polyspiral"); + + while (!rl.WindowShouldClose()) + updateDrawFrame(); + + rl.CloseWindow(); +} + +fn updateDrawFrame() void { + rl.BeginDrawing(); + + rl.ClearBackground(rl.BLACK); + + incr = @mod(incr + 0.001, 360); + + drawSpiral(5, std.math.degreesToRadians(f32, incr)); + + rl.EndDrawing(); +} + +fn drawSpiral(_length: f32, _angle: f32) void { + const width = rl.GetScreenWidth(); + const height = rl.GetScreenHeight(); + var point0 = rl.Vector2{ .x = @as(f32, @floatFromInt(width)) / 2, .y = @as(f32, @floatFromInt(height)) / 2 }; + var length = _length; + var angle = _angle; + for (0..150) |_| { + const line_vector = rl.Vector2Rotate(rl.Vector2{ .x = length, .y = 0 }, angle); + const point1 = rl.Vector2Add(point0, line_vector); + rl.DrawLineV(point0, point1, rl.LIME); + point0 = point1; + length += 3; + angle += incr; + angle = @mod(angle, comptime @as(f32, (2.0 * std.math.pi))); + } +} diff --git a/Task/Primality-by-trial-division/ARM-Assembly/primality-by-trial-division.arm b/Task/Primality-by-trial-division/ARM-Assembly/primality-by-trial-division.arm new file mode 100644 index 0000000000..62cb5647c1 --- /dev/null +++ b/Task/Primality-by-trial-division/ARM-Assembly/primality-by-trial-division.arm @@ -0,0 +1,110 @@ +/* ARM assembly Raspberry PI */ +/* program testtrialprime.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../constantes.inc" + +//.include "../../ficmacros32.inc" @ for debugging developper +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessPrime: .asciz " is prime.\n" +szMessNotPrime: .asciz " is not prime.\n" +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 + mov r0,#19 + bl testPrime + + ldr r0,iStart @ number + bl testPrime + ldr r0,iStart1 @ number + bl testPrime + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdrsZoneConv: .int sZoneConv + +iAdrszMessPrime: .int szMessPrime +iAdrszMessNotPrime: .int szMessNotPrime +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessStart: .int szMessStart +iStart: .int 2600002183 +iStart1: .int 4124163031 +/******************************************************************/ +/* test if number is prime */ +/******************************************************************/ +/* r0 contains the number */ +testPrime: + push {r1,r2,lr} @ save registers + mov r2,r0 + ldr r1,iAdrsZoneConv + bl conversion10 @ decimal conversion + ldr r0,iAdrsZoneConv + bl affichageMess + mov r0,r2 + bl isPrime + cmp r0,#0 + beq 1f + ldr r0,iAdrszMessPrime + bl affichageMess + b 100f +1: + ldr r0,iAdrszMessNotPrime + bl affichageMess +100: + pop {r1,r2,pc} @ restaur registers +/******************************************************************/ +/* test if number is prime */ +/******************************************************************/ +/* r0 contains the number */ +/* r0 return 1 if prime else return 0 */ +isPrime: + push {r4,lr} @ save registers + cmp r0,#1 @ <= 1 ? + movls r0,#0 @ not prime + bls 100f + cmp r0,#3 @ 2 and 3 prime + movls r0,#1 + bls 100f + tst r0,#1 @ even ? + moveq r0,#0 @ not prime + beq 100f + mov r4,r0 @ save number + mov r1,#3 @ first divisor +1: + mov r0,r4 @ number + bl division + add r1,r1,#2 @ increment divisor + cmp r3,#0 @ remainder = zero ? + moveq r0,#0 @ not prime + beq 100f + cmp r1,r2 @ divisors<=quotient ? + ble 1b @ loop + mov r0,#1 @ return prime + +100: + pop {r4,pc} @ restaur registers +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../affichage.inc" diff --git a/Task/Primality-by-trial-division/EasyLang/primality-by-trial-division.easy b/Task/Primality-by-trial-division/EasyLang/primality-by-trial-division.easy index 1fe29c6b90..845cca8af4 100644 --- a/Task/Primality-by-trial-division/EasyLang/primality-by-trial-division.easy +++ b/Task/Primality-by-trial-division/EasyLang/primality-by-trial-division.easy @@ -1,17 +1,18 @@ -proc isPrime num . result . - if num < 2 - result = 0 - break 1 +func isprim n . + if n < 2 + return 0 . - if num mod 2 = 0 and num > 2 - result = 0 - break 1 + if n mod 2 = 0 and n > 2 + return 0 . - for i = 3 step 2 to sqrt num - if num mod i = 0 - result = 0 - break 2 + i = 3 + sq = sqrt n + while i <= sq + if n mod i = 0 + return 0 . + i += 2 . - result = 1 + return 1 . +print isprim 1995937 diff --git a/Task/Prime-decomposition/EasyLang/prime-decomposition.easy b/Task/Prime-decomposition/EasyLang/prime-decomposition.easy index df84c78ca7..bfa472b58e 100644 --- a/Task/Prime-decomposition/EasyLang/prime-decomposition.easy +++ b/Task/Prime-decomposition/EasyLang/prime-decomposition.easy @@ -11,5 +11,5 @@ proc decompose num . primes[] . . primes[] &= num . -call decompose 9007199254740991 r[] +decompose 9007199254740991 r[] print r[] diff --git a/Task/Program-termination/FutureBasic/program-termination.basic b/Task/Program-termination/FutureBasic/program-termination.basic new file mode 100644 index 0000000000..67ef290512 --- /dev/null +++ b/Task/Program-termination/FutureBasic/program-termination.basic @@ -0,0 +1 @@ +if condition then end diff --git a/Task/Pseudo-random-numbers-Middle-square-method/EasyLang/pseudo-random-numbers-middle-square-method.easy b/Task/Pseudo-random-numbers-Middle-square-method/EasyLang/pseudo-random-numbers-middle-square-method.easy index 4876281c32..8b2ea05c97 100644 --- a/Task/Pseudo-random-numbers-Middle-square-method/EasyLang/pseudo-random-numbers-middle-square-method.easy +++ b/Task/Pseudo-random-numbers-Middle-square-method/EasyLang/pseudo-random-numbers-middle-square-method.easy @@ -1,6 +1,6 @@ global seed . seed = 675248 -proc rand . randNum . +func rand . strSeed$ = seed s$ = seed * seed while not len s$ = len strSeed$ * 2 @@ -8,8 +8,8 @@ proc rand . randNum . . seed = number substr s$ (len strSeed$ / 2 + 1) len strSeed$ randNum = seed + return randNum . for i = 1 to 5 - call rand randNum - print randNum + print rand . diff --git a/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy b/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy index 40f8706564..bcba9c01e1 100644 --- a/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy +++ b/Task/Pythagoras-tree/EasyLang/pythagoras-tree.easy @@ -11,8 +11,8 @@ proc tree x1 y1 x2 y2 depth . . color3 0.3 0.2 + depth / 18 0.1 polygon [ x1 y1 x2 y2 x3 y3 x4 y4 ] polygon [ x3 y3 x4 y4 x5 y5 ] - call tree x4 y4 x5 y5 depth + 1 - call tree x5 y5 x3 y3 depth + 1 + tree x4 y4 x5 y5 depth + 1 + tree x5 y5 x3 y3 depth + 1 . . -call tree 41 10 59 10 0 +tree 41 10 59 10 0 diff --git a/Task/QR-decomposition/C++/qr-decomposition.cpp b/Task/QR-decomposition/C++/qr-decomposition-1.cpp similarity index 100% rename from Task/QR-decomposition/C++/qr-decomposition.cpp rename to Task/QR-decomposition/C++/qr-decomposition-1.cpp diff --git a/Task/QR-decomposition/C++/qr-decomposition-2.cpp b/Task/QR-decomposition/C++/qr-decomposition-2.cpp new file mode 100644 index 0000000000..683546beb2 --- /dev/null +++ b/Task/QR-decomposition/C++/qr-decomposition-2.cpp @@ -0,0 +1,280 @@ +#include +#include +#include +#include +#include +#include +#include + +class Matrix { +public: + Matrix(const std::vector>& data) : data(data) { + initialise(); + } + + Matrix(const Matrix& matrix) : data(matrix.data) { + initialise(); + } + + Matrix(const uint64_t& row_count, const uint64_t& column_count) { + data.assign(row_count, std::vector(column_count, 0.0)); + initialise(); + } + + Matrix add(const Matrix& other) { + if ( other.row_count != row_count || other.column_count != column_count ) { + throw std::invalid_argument("Incompatible matrix dimensions."); + } + + Matrix result(data); + for ( int32_t i = 0; i < row_count; ++i ) { + for ( int32_t j = 0; j < column_count; ++j ) { + result.data[i][j] = data[i][j] + other.data[i][j]; + } + } + return result; + } + + Matrix multiply(const Matrix& other) { + if ( column_count != other.row_count ) { + throw std::invalid_argument("Incompatible matrix dimensions."); + } + + Matrix result(row_count, other.column_count); + for ( int32_t i = 0; i < row_count; ++i ) { + for ( int32_t j = 0; j < other.column_count; ++j ) { + for ( int32_t k = 0; k < row_count; k++ ) { + result.data[i][j] += data[i][k] * other.data[k][j]; + } + } + } + return result; + } + + Matrix transpose() { + Matrix result(column_count, row_count); + for ( int32_t i = 0; i < row_count; ++i ) { + for ( int32_t j = 0; j < column_count; ++j ) { + result.data[j][i] = data[i][j]; + } + } + return result; + } + + Matrix minor(const int32_t& index) { + Matrix result(row_count, column_count); + for ( int32_t i = 0; i < index; ++i ) { + result.set_entry(i, i, 1.0); + } + + for ( int32_t i = index; i < row_count; ++i ) { + for ( int32_t j = index; j < column_count; ++j ) { + result.set_entry(i, j, data[i][j]); + } + } + return result; + } + + Matrix column(const int32_t& index) { + Matrix result(row_count, 1); + for ( int32_t i = 0; i < row_count; ++i ) { + result.set_entry(i, 0, data[i][index]); + } + return result; + } + + Matrix scalarMultiply(const double& value) { + if ( column_count != 1 ) { + throw std::invalid_argument("Incompatible matrix dimension."); + } + + Matrix result(row_count, column_count); + for ( int32_t i = 0; i < row_count; ++i ) { + result.data[i][0] = data[i][0] * value; + } + return result; + } + + Matrix unit() { + if ( column_count != 1 ) { + throw std::invalid_argument("Incompatible matrix dimensions."); + } + + const double the_magnitude = magnitude(); + Matrix result(row_count, column_count); + for ( int32_t i = 0; i < row_count; ++i ) { + result.data[i][0] = data[i][0] / the_magnitude; + } + return result; + } + + double magnitude() { + if ( column_count != 1 ) { + throw std::invalid_argument("Incompatible matrix dimensions."); + } + + double norm = 0.0; + for ( int32_t i = 0; i < row_count; ++i ) { + norm += data[i][0] * data[i][0]; + } + return std::sqrt(norm); + } + + int32_t size() { + if ( column_count != 1 ) { + throw std::invalid_argument("Incompatible matrix dimensions."); + } + return row_count; + } + + void display(const std::string& title) { + std::cout << title << std::endl; + for ( int32_t i = 0; i < row_count; ++i ) { + for ( int32_t j = 0; j < column_count; ++j ) { + std::cout << std::setw(9) << std::fixed << std::setprecision(4) << data[i][j]; + } + std::cout << std::endl; + } + std::cout << std::endl; + } + + double get_entry(const int32_t& row, const int32_t& col) { + return data[row][col]; + } + + void set_entry(const int32_t& row, const int32_t& col, const double& value) { + data[row][col] = value; + } + + int32_t get_row_count() { + return row_count; + } + + int32_t get_column_count() { + return column_count; + } + +private: + void initialise() { + row_count = data.size(); + column_count = data[0].size(); + } + + int32_t row_count; + int32_t column_count; + std::vector> data; +}; + +typedef std::pair matrix_pair; + +Matrix householder_factor(Matrix vector) { + if ( vector.get_column_count() != 1 ) { + throw std::invalid_argument("Incompatible matrix dimensions."); + } + + const int32_t size = vector.size(); + Matrix result(size, size); + for ( int32_t i = 0; i < size; ++i ) { + for ( int32_t j = 0; j < size; ++j ) { + result.set_entry(i, j, -2 * vector.get_entry(i, 0) * vector.get_entry(j, 0)); + } + } + + for ( int32_t i = 0; i < size; ++i ) { + result.set_entry(i, i, result.get_entry(i, i) + 1.0); + } + return result; +} + +matrix_pair householder(Matrix matrix) { + const int32_t row_count = matrix.get_row_count(); + const int32_t column_count = matrix.get_column_count(); + std::vector versions_of_Q; + Matrix z(matrix); + Matrix z1(row_count, column_count); + + for ( int32_t k = 0; k < column_count && k < row_count - 1; ++k ) { + Matrix vectorE(row_count, 1); + z1 = z.minor(k); + Matrix vectorX = z1.column(k); + double magnitudeX = vectorX.magnitude(); + if ( matrix.get_entry(k, k) > 0 ) { + magnitudeX = -magnitudeX; + } + + for ( int32_t i = 0; i < vectorE.size(); ++i ) { + vectorE.set_entry(i, 0, ( i == k ) ? 1 : 0); + } + vectorE = vectorE.scalarMultiply(magnitudeX).add(vectorX).unit(); + versions_of_Q.emplace_back(householder_factor(vectorE)); + z = versions_of_Q[k].multiply(z1); + } + + Matrix Q = versions_of_Q[0]; + for ( int32_t i = 1; i < column_count && i < row_count - 1; ++i ) { + Q = versions_of_Q[i].multiply(Q); + } + + Matrix R = Q.multiply(matrix); + Q = Q.transpose(); + return matrix_pair(R, Q); +} + +Matrix solve_upper_triangular(Matrix r, Matrix b) { + const int32_t column_count = r.get_column_count(); + Matrix result(column_count, 1); + + for ( int32_t k = column_count - 1; k >= 0; --k ) { + double total = 0.0; + for ( int32_t j = k + 1; j < column_count; ++j ) { + total += r.get_entry(k, j) * result.get_entry(j, 0); + } + result.set_entry(k, 0, ( b.get_entry(k, 0) - total ) / r.get_entry(k, k)); + } + return result; +} + +Matrix least_squares(Matrix vandermonde, Matrix b) { + matrix_pair pair = householder(vandermonde); + return solve_upper_triangular(pair.first, pair.second.transpose().multiply(b)); +} + +Matrix fit_polynomial(Matrix x, Matrix y, const int32_t& polynomial_degree) { + Matrix vandermonde(x.get_column_count(), polynomial_degree + 1); + for ( int32_t i = 0; i < x.get_column_count(); ++i ) { + for ( int32_t j = 0; j < polynomial_degree + 1; ++j ) { + vandermonde.set_entry(i, j, std::pow(x.get_entry(0, i), j)); + } + } + return least_squares(vandermonde, y.transpose()); +} + +int main() { + const std::vector> data = { { 12.0, -51.0, 4.0 }, + { 6.0, 167.0, -68.0 }, + { -4.0, 24.0, -41.0 }, + { -1.0, 1.0, 0.0 }, + { 2.0, 0.0, 3.0 } }; + + // Task 1 + Matrix A(data); + A.display("Initial matrix A:"); + + matrix_pair pair = householder(A); + Matrix Q = pair.second; + Matrix R = pair.first; + + Q.display("Matrix Q:"); + R.display("Matrix R:"); + + Matrix result = Q.multiply(R); + result.display("Matrix Q * R:"); + + // Task 2 + Matrix x( std::vector>{ { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 } } ); + Matrix y( std::vector>{ + { 1.0, 6.0, 17.0, 34.0, 57.0, 86.0, 121.0, 162.0, 209.0, 262.0, 321.0 } } ); + + result = fit_polynomial(x, y, 2); + result.display("Result of fitting polynomial:"); +} diff --git a/Task/QR-decomposition/Java/qr-decomposition-5.java b/Task/QR-decomposition/Java/qr-decomposition-5.java index 70239642a0..3b81bbb6fe 100644 --- a/Task/QR-decomposition/Java/qr-decomposition-5.java +++ b/Task/QR-decomposition/Java/qr-decomposition-5.java @@ -41,7 +41,7 @@ public final class QRDecomposition { Matrix z1 = new Matrix(rowCount, columnCount); for ( int k = 0; k < columnCount && k < rowCount - 1; k++ ) { - Matrix vectorE = new Matrix( new double[rowCount][1] ); + Matrix vectorE = new Matrix(rowCount, 1); z1 = z.minor(k); Matrix vectorX = z1.column(k); double magnitudeX = vectorX.magnitude(); @@ -52,8 +52,7 @@ public final class QRDecomposition { for ( int i = 0; i < vectorE.size(); i++ ) { vectorE.setEntry(i, 0, ( i == k ) ? 1 : 0); } - vectorE = vectorE.scalarMultiply(magnitudeX).add(vectorX); - vectorE = vectorE.unit(); + vectorE = vectorE.scalarMultiply(magnitudeX).add(vectorX).unit(); versionsOfQ.add(householderFactor(vectorE)); z = versionsOfQ.get(k).multiply(z1); } @@ -74,17 +73,17 @@ public final class QRDecomposition { } final int size = aVector.size(); - double[][] newData = new double[size][size]; + Matrix result = new Matrix(size, size); for ( int i = 0; i < size; i++ ) { for ( int j = 0; j < size; j++ ) { - newData[i][j] = -2 * aVector.getEntry(i, 0) * aVector.getEntry(j, 0); + result.setEntry(i, j, -2 * aVector.getEntry(i, 0) * aVector.getEntry(j, 0)); } } for ( int i = 0; i < size; i++ ) { - newData[i][i] += 1; + result.setEntry(i, i, result.getEntry(i, i) + 1.0); } - return new Matrix(newData); + return result; } private static Matrix fitPolynomial(Matrix aX, Matrix aY, int aPolynomialDegree) { @@ -137,8 +136,8 @@ final class Matrix { this(aMatrix.data); } - public Matrix(int aRows, int aCols) { - this( new double[aRows][aCols] ); + public Matrix(int aRowCount, int aColumnCount) { + this( new double[aRowCount][aColumnCount] ); } public Matrix add(Matrix aOther) { @@ -195,10 +194,10 @@ final class Matrix { return result; } - public Matrix column(int aColumn) { + public Matrix column(int aIndex) { Matrix result = new Matrix(rowCount, 1); for ( int i = 0; i < rowCount; i++ ) { - result.setEntry(i, 0, data[i][aColumn]); + result.setEntry(i, 0, data[i][aIndex]); } return result; } @@ -209,7 +208,7 @@ final class Matrix { } Matrix result = new Matrix(rowCount, columnCount); - for ( int i = 0; i < data.length; i++ ) { + for ( int i = 0; i < rowCount; i++ ) { result.data[i][0] = data[i][0] * aValue; } return result; @@ -222,7 +221,7 @@ final class Matrix { final double magnitude = magnitude(); Matrix result = new Matrix(rowCount, columnCount); - for ( int i = 0; i < data.length; i++ ) { + for ( int i = 0; i < rowCount; i++ ) { result.data[i][0] = data[i][0] / magnitude; } return result; @@ -244,7 +243,7 @@ final class Matrix { if ( columnCount != 1 ) { throw new IllegalArgumentException("Incompatible matrix dimensions."); } - return data.length; + return rowCount; } public void display(String aTitle) { @@ -258,12 +257,12 @@ final class Matrix { System.out.println(); } - public double getEntry(int aRow, int aCol) { - return data[aRow][aCol]; + public double getEntry(int aRow, int aColumn) { + return data[aRow][aColumn]; } - public void setEntry(int aRow, int aCol, double aValue) { - data[aRow][aCol] = aValue; + public void setEntry(int aRow, int aColumn, double aValue) { + data[aRow][aColumn] = aValue; } public int getRowCount() { diff --git a/Task/Quickselect-algorithm/EasyLang/quickselect-algorithm.easy b/Task/Quickselect-algorithm/EasyLang/quickselect-algorithm.easy index a0f63ffcbe..79f18b94cf 100644 --- a/Task/Quickselect-algorithm/EasyLang/quickselect-algorithm.easy +++ b/Task/Quickselect-algorithm/EasyLang/quickselect-algorithm.easy @@ -13,7 +13,7 @@ proc qselect k . list[] res . left = 1 right = len list[] while left < right - call partition + partition if mid < k left = mid + 1 elif mid > k @@ -26,6 +26,6 @@ proc qselect k . list[] res . . d[] = [ 9 8 7 6 5 0 1 2 3 4 ] for i = 1 to len d[] - call qselect i d[] r + qselect i d[] r print r . diff --git a/Task/Quine/Acornsoft-Lisp/quine.lisp b/Task/Quine/Acornsoft-Lisp/quine.lisp new file mode 100644 index 0000000000..78a9c1c12c --- /dev/null +++ b/Task/Quine/Acornsoft-Lisp/quine.lisp @@ -0,0 +1,2 @@ +((lambda (s) (list s (list (quote quote) s))) + (quote (lambda (s) (list s (list (quote quote) s))))) diff --git a/Task/Quoting-constructs/Java/quoting-constructs.java b/Task/Quoting-constructs/Java/quoting-constructs.java new file mode 100644 index 0000000000..57fe1314f6 --- /dev/null +++ b/Task/Quoting-constructs/Java/quoting-constructs.java @@ -0,0 +1,32 @@ +import java.util.List; + +public final class QuotingConstructs { + + public static void main(String[] args) { + // Java uses double quotes for strings and single quotes for characters. + String simple = "This is a simple string"; + char letter = 'A'; + + // A Text Block is denoted by triple quotes. + String multiLineString = """ + This is an example of multi-line string. + Text formatting is preserved. + Text blocks can be used for multi-line string. + """; + System.out.println(multiLineString); + + // Java's primitive data types: boolean, byte, char double, float, int, long, short, + // can be used to to store data, for example, + final int blockLength = 64; + + // Arrays or lists of these data types are possible, for example, + double[] state = new double[] { 1.0, 2.0, 3.0 }; + + // Custom data types can be stored in a record or a class, for example, + record Circle(int centreX, int centreY, double radius) {} + + // A list of custom data types: + List circles = List.of( new Circle(1, 2, 1.25), new Circle(-2, 3, 2.50) ); + } + +} diff --git a/Task/RIPEMD-160/C++/ripemd-160.cpp b/Task/RIPEMD-160/C++/ripemd-160.cpp new file mode 100644 index 0000000000..722a222404 --- /dev/null +++ b/Task/RIPEMD-160/C++/ripemd-160.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +class RIPEMD160 { +public: + std::string message_digest(const std::string& message) { + std::vector state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; + + std::vector bytes = add_padding(message); + for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) { + std::vector schedule(16, 0); + for ( uint32_t j = 0; j < BLOCK_LENGTH; ++j ) { + schedule[j / 4] |= ( bytes[i + j] ) << ( j % 4 * 8 ); + } + + int32_t a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; + int32_t aa = state[0], bb = state[1], cc = state[2], dd = state[3], ee = state[4]; + int32_t t = 0, tt = 0; + + for ( uint32_t j = 0; j < 80; ++j ) { + uint32_t jj = j / 16; + t = std::rotl(a + ff(jj + 1, b, c, d) + schedule[RL[j]] + KL[jj], SL[j]) + e; + tt = std::rotl(aa + ff(5 - jj, bb, cc, dd) + schedule[RR[j]] + KR[jj], SR[j]) + ee; + + a = e; e = d; d = std::rotl(static_cast(c), 10); c = b; b = t; + aa = ee; ee = dd; dd = std::rotl(static_cast(cc), 10); cc = bb; bb = tt; + } + + t = state[1] + c + dd; + state[1] = state[2] + d + ee; + state[2] = state[3] + e + aa; + state[3] = state[4] + a + bb; + state[4] = state[0] + b + cc; + state[0] = t; + } + + std::stringstream stream; + for ( uint32_t i = 0; i < state.size() * 4; ++i ) { + int8_t byte_value = static_cast(unsigned_right_shift(state[i / 4], i % 4 * 8)); + stream << std::setfill('0') << std::setw(2) << std::hex << ( byte_value & 0xff ); + } + return stream.str(); + } + +private: + const uint64_t TWO_POWER_32 = 4'294'967'296; + const uint32_t BLOCK_LENGTH = 64; + + const std::vector SR = { 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 }; + + const std::vector SL = { 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 }; + + const std::vector RR = { 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 }; + + const std::vector RL = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 }; + + const std::vector KL = { 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e }; + const std::vector KR = { 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000 }; + + 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; + } + + uint32_t ff(const uint32_t& group, const uint32_t& x, const uint32_t& y, const uint32_t& z) { + uint32_t result; + switch ( group ) { + case 1: result = x ^ y ^ z; break; + case 2: result = ( x & y ) | ( ~x & z ); break; + case 3: result = ( x | ~y ) ^ z; break; + case 4: result = ( x & z ) | ( y & ~z ); break; + case 5: result = x ^ ( y | ~z ); break; + default: throw std::invalid_argument("Unexpected argument: " + group); + }; + return result; + } + + std::vector add_padding(const std::string& message) { + std::vector bytes(message.begin(), message.end()); + bytes.emplace_back(static_cast(0x80)); + + uint32_t padding = BLOCK_LENGTH - ( bytes.size() % BLOCK_LENGTH ); + if ( padding < 8 ) { + padding += BLOCK_LENGTH; + } + bytes.resize(bytes.size() + padding - 8, static_cast(0x0)); + + const uint64_t bit_length = 8 * message.length(); + for ( uint32_t i = 0; i < 8; ++i ) { + bytes.emplace_back(static_cast( bit_length >> ( 8 * i ) )); + } + return bytes; + } +}; + +int main() { + RIPEMD160 ripemd160; + std::cout << ripemd160.message_digest("Rosetta Code") << std::endl; +} diff --git a/Task/RIPEMD-160/Java/ripemd-160.java b/Task/RIPEMD-160/Java/ripemd-160-1.java similarity index 100% rename from Task/RIPEMD-160/Java/ripemd-160.java rename to Task/RIPEMD-160/Java/ripemd-160-1.java diff --git a/Task/RIPEMD-160/Java/ripemd-160-2.java b/Task/RIPEMD-160/Java/ripemd-160-2.java new file mode 100644 index 0000000000..151733e7a5 --- /dev/null +++ b/Task/RIPEMD-160/Java/ripemd-160-2.java @@ -0,0 +1,111 @@ +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +public final class RIPEMD160Task { + + public static void main(String[] aArgs) { + System.out.println(RIPEMD160.messageDigest("Rosetta Code")); + } + +} + +final class RIPEMD160 { + + public static String messageDigest(String aMessage) { + int[] state = { 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 }; + + byte[] bytes = addPadding(aMessage); + for ( int i = 0; i < bytes.length / BLOCK_LENGTH; i++ ) { + int[] schedule = new int[16]; + for ( int j = 0; j < BLOCK_LENGTH; j++ ) { + schedule[j / 4] |= ( bytes[i + j] & 0xff ) << ( j % 4 * 8 ); + } + + int a = state[0], b = state[1], c = state[2], d = state[3], e = state[4]; + int aa = state[0], bb = state[1], cc = state[2], dd = state[3], ee = state[4]; + int t = 0, tt = 0; + + for ( int j = 0; j < 80; j++ ) { + int jj = j / 16; + t = Integer.rotateLeft(a + ff(jj + 1, b, c, d) + schedule[RL[j]] + KL[jj], SL[j]) + e; + tt = Integer.rotateLeft(aa + ff(5 - jj, bb, cc, dd) + schedule[RR[j]] + KR[jj], SR[j]) + ee; + + a = e; e = d; d = Integer.rotateLeft(c, 10); c = b; b = t; + aa = ee; ee = dd; dd = Integer.rotateLeft(cc, 10); cc = bb; bb = tt; + } + + t = state[1] + c + dd; + state[1] = state[2] + d + ee; + state[2] = state[3] + e + aa; + state[3] = state[4] + a + bb; + state[4] = state[0] + b + cc; + state[0] = t; + } + + String result = ""; + for ( int i = 0; i < state.length * 4; i++ ) { + result += String.format("%02x", (byte) ( state[i / 4] >>> ( i % 4 * 8 ) )); + } + return result; + } + + private static byte[] addPadding(String aMessage) { + byte[] bytes = aMessage.getBytes(StandardCharsets.UTF_8); + bytes = Arrays.copyOf(bytes, bytes.length + 1); + bytes[bytes.length - 1] = (byte) 0x80; + + final int length = aMessage.length(); + int padding = BLOCK_LENGTH - ( (length + 1 ) % BLOCK_LENGTH ); + if ( padding < 8 ) { + padding += BLOCK_LENGTH; + } + bytes = Arrays.copyOf(bytes, bytes.length + padding); + + final long bitLength = 8 * length; + for ( int i = 0; i < 8; i++ ) { + bytes[bytes.length - 8 + i] = (byte) ( bitLength >>> ( 8 * i ) ); + } + return bytes; + } + + private static int ff(int aGroup, int aX, int aY, int aZ) { + return switch ( aGroup ) { + case 1 -> aX ^ aY ^ aZ; + case 2 -> ( aX & aY ) | ( ~aX & aZ ); + case 3 -> ( aX | ~aY ) ^ aZ; + case 4 -> ( aX & aZ ) | ( aY & ~aZ ); + case 5 -> aX ^ ( aY | ~aZ ); + default -> throw new IllegalArgumentException("Unexpected argument: " + aGroup); + }; + } + + private static final int[] KL = new int[] { 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e }; + private static final int[] KR = new int [] { 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000 }; + + private static final int[] RL = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, + 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, + 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, + 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 }; + + private static final int[] RR = new int[] { 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, + 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, + 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, + 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, + 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 }; + + private static final int[] SL = new int[] { 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, + 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, + 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, + 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, + 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 }; + + private static final int[] SR = new int[] { 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, + 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, + 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, + 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, + 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 }; + + private static final int BLOCK_LENGTH = 64; + +} diff --git a/Task/Radical-of-an-integer/Java/radical-of-an-integer.java b/Task/Radical-of-an-integer/Java/radical-of-an-integer.java new file mode 100644 index 0000000000..e87950e3d4 --- /dev/null +++ b/Task/Radical-of-an-integer/Java/radical-of-an-integer.java @@ -0,0 +1,85 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public final class RadicalOfAnInteger { + + public static void main(String[] aArgs) { + sievePrimes(); + distinctPrimeFactors(); + + System.out.println("Radical of first 50 positive integers:"); + for ( int n = 1; n <= 50; n++ ) { + System.out.print(String.format("%3d%s", radical(n), ( n % 10 == 0 ? "\n" : "" ))); + } + System.out.println(); + + for ( int n : List.of( 99_999, 499_999, 999_999 ) ) { + System.out.println(String.format("%s%7d%s%7d", "Radical for ", n, ":", radical(n))); + } + System.out.println(); + + System.out.print("Distribution of the first one million positive "); + System.out.println("integers by numbers of distinct prime factors:"); + List counts = IntStream.rangeClosed(0, 7).boxed().map( i -> 0 ).collect(Collectors.toList()); + for ( int n = 1; n <= LIMIT; n++ ) { + counts.set(distinctPrimeFactorCount(n), counts.get(distinctPrimeFactorCount(n)) + 1); + } + for ( int n = 0; n < counts.size(); n++ ) { + System.out.println(String.format("%d%s%7d", n, ":", counts.get(n))); + } + System.out.println(); + + System.out.println("Number of primes and powers of primes less than or equal to one million:"); + int count = 0; + final double logOfLimit = Math.log(LIMIT); + for ( int p : primes ) { + count += logOfLimit / Math.log(p); + } + System.out.println(count); + } + + private static int radical(int aNumber) { + return distinctPrimeFactors.get(aNumber).stream().reduce(1, Math::multiplyExact); + } + + private static int distinctPrimeFactorCount(int aNumber) { + return distinctPrimeFactors.get(aNumber).size(); + } + + private static void distinctPrimeFactors() { + distinctPrimeFactors = IntStream.rangeClosed(0, LIMIT).boxed() + .map( i -> new ArrayList() ).collect(Collectors.toList()); + for ( int p : primes ) { + for ( int n = p; n <= LIMIT; n += p ) { + distinctPrimeFactors.get(n).add(p); + } + } + } + + private static void sievePrimes() { + List markedPrime = IntStream.rangeClosed(0, LIMIT).boxed() + .map( i -> true ).collect(Collectors.toList()); + for ( int p = 2; p * p <= LIMIT; p++ ) { + if ( markedPrime.get(p) ) { + for ( int i = p * p; i <= LIMIT; i += p ) { + markedPrime.set(i, false); + } + } + } + + primes = new ArrayList(); + for ( int p = 2; p <= LIMIT; p++ ) { + if ( markedPrime.get(p) ) { + primes.add(p); + } + } + } + + private static List primes; + private static List> distinctPrimeFactors; + + private static final int LIMIT = 1_000_000; + +} diff --git a/Task/Ramanujan-primes-twins/00-TASK.txt b/Task/Ramanujan-primes-twins/00-TASK.txt index e89e98bc82..2a769523c8 100644 --- a/Task/Ramanujan-primes-twins/00-TASK.txt +++ b/Task/Ramanujan-primes-twins/00-TASK.txt @@ -1,2 +1,6 @@ In a manner similar to twin primes, twin Ramanujan primes may be explored. The task is to determine how many of the first million Ramanujan primes are twins. ;Related Task: [[Twin primes]] + + + + diff --git a/Task/Ramanujan-primes-twins/C++/ramanujan-primes-twins.cpp b/Task/Ramanujan-primes-twins/C++/ramanujan-primes-twins.cpp new file mode 100644 index 0000000000..8ff6e51d5c --- /dev/null +++ b/Task/Ramanujan-primes-twins/C++/ramanujan-primes-twins.cpp @@ -0,0 +1,104 @@ +#include +#include +#include +#include + +int32_t ramanujan_maximum(const int32_t& number) { + return ceil(4 * number * log(4 * number)); +} + +std::vector initialise_prime_pi(const int32_t& limit) { + std::vector result(limit, 1); + result[0] = 0; + result[1] = 0; + for ( int32_t i = 4; i < limit; i += 2 ) { + result[i] = 0; + } + for ( int32_t p = 3, square = 9; square < limit; p += 2 ) { + if ( result[p] != 0 ) { + for ( int32_t q = square; q < limit; q += p << 1 ) { + result[q] = 0; + } + } + square += ( p + 1 ) << 2; + } + + for ( uint64_t i = 1; i < result.size(); ++i ) { + result[i] += result[i - 1]; + } + return result; +} + +int32_t ramanujan_prime(const std::vector& prime_pi, const int32_t& number) { + int32_t maximum = ramanujan_maximum(number); + if ( ( maximum & 1) == 1 ) { + maximum -= 1; + } + + int32_t index = maximum; + while ( prime_pi[index] - prime_pi[index / 2] >= number ) { + index -= 1; + } + return index + 1; +} + +std::vector list_primes_less_than(const int32_t& limit) { + std::vector composite(limit, false); + int32_t n = 3; + int32_t nSquared = 9; + while ( nSquared <= limit ) { + if ( ! composite[n] ) { + for ( int32_t k = nSquared; k < limit; k += 2 * n ) { + composite[k] = true; + } + } + nSquared += ( n + 1 ) << 2; + n += 2; + } + + std::vector result; + result.emplace_back(2); + for ( int32_t i = 3; i < limit; i += 2 ) { + if ( ! composite[i] ) { + result.emplace_back(i); + } + } + return result; +} + +int main() { + const int32_t limit = 1'000'000; + const std::vector prime_pi = initialise_prime_pi(ramanujan_maximum(limit) + 1); + const int32_t millionth_ramanujan_prime = ramanujan_prime(prime_pi, limit); + std::cout << "The 1_000_000th Ramanujan prime is " << millionth_ramanujan_prime << std::endl; + + std::vector primes = list_primes_less_than(millionth_ramanujan_prime); + std::vector ramanujan_prime_indexes(primes.size()); + for ( uint64_t i = 0; i < ramanujan_prime_indexes.size(); ++i ) { + ramanujan_prime_indexes[i] = prime_pi[primes[i]] - prime_pi[primes[i] / 2]; + } + + int32_t lowerLimit = ramanujan_prime_indexes[ramanujan_prime_indexes.size() - 1]; + for ( int32_t i = ramanujan_prime_indexes.size() - 2; i >= 0; --i ) { + if ( ramanujan_prime_indexes[i] < lowerLimit ) { + lowerLimit = ramanujan_prime_indexes[i]; + } else { + ramanujan_prime_indexes[i] = 0; + } + } + + std::vector ramanujan_primes; + for ( uint64_t i = 0; i < ramanujan_prime_indexes.size(); ++i ) { + if ( ramanujan_prime_indexes[i] != 0 ) { + ramanujan_primes.emplace_back(primes[i]); + } + } + + int32_t twins_count = 0; + for ( uint64_t i = 0; i < ramanujan_primes.size() - 1; ++i ) { + if ( ramanujan_primes[i] + 2 == ramanujan_primes[i + 1] ) { + twins_count++; + } + } + std::cout << "There are " << twins_count << " twins in the first " << limit << " Ramanujan primes." << std::endl; +} diff --git a/Task/Ramanujan-primes-twins/Java/ramanujan-primes-twins.java b/Task/Ramanujan-primes-twins/Java/ramanujan-primes-twins.java new file mode 100644 index 0000000000..780203b2a4 --- /dev/null +++ b/Task/Ramanujan-primes-twins/Java/ramanujan-primes-twins.java @@ -0,0 +1,104 @@ +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public final class RamanujanPrimesTwins { + + public static void main(String[] aArgs) { + final int limit = 1_000_000; + final int[] primePi = initialisePrimePi(ramanujanMaximum(limit) + 1); + final int millionthRamanujanPrime = ramanujanPrime(primePi, limit); + System.out.println("The 1_000_000th Ramanujan prime is " + millionthRamanujanPrime); + + List primes = listPrimesLessThan(millionthRamanujanPrime); + int[] ramanujanPrimeIndexes = new int[primes.size()]; + for ( int i = 0; i < ramanujanPrimeIndexes.length; i++ ) { + ramanujanPrimeIndexes[i] = primePi[primes.get(i)] - primePi[primes.get(i) / 2]; + } + int lowerLimit = ramanujanPrimeIndexes[ramanujanPrimeIndexes.length - 1]; + for ( int i = ramanujanPrimeIndexes.length - 2; i >= 0; i-- ) { + if ( ramanujanPrimeIndexes[i] < lowerLimit ) { + lowerLimit = ramanujanPrimeIndexes[i]; + } else { + ramanujanPrimeIndexes[i] = 0; + } + } + + List ramanujanPrimes = new ArrayList(); + for ( int i = 0; i < ramanujanPrimeIndexes.length; i++ ) { + if ( ramanujanPrimeIndexes[i] != 0 ) { + ramanujanPrimes.add(primes.get(i)); + } + } + + int twinsCount = 0; + for ( int i = 0; i < ramanujanPrimes.size() - 1; i++ ) { + if ( ramanujanPrimes.get(i) + 2 == ramanujanPrimes.get(i + 1) ) { + twinsCount += 1; + } + } + System.out.println("There are " + twinsCount + " twins in the first " + limit + " Ramanujan primes."); + } + + private static List listPrimesLessThan(int aLimit) { + boolean[] composite = new boolean[aLimit + 1]; + int n = 3; + int nSquared = 9; + while ( nSquared <= aLimit ) { + if ( ! composite[n] ) { + for ( int k = nSquared; k < aLimit; k += 2 * n ) { + composite[k] = true; + } + } + nSquared += ( n + 1 ) << 2; + n += 2; + } + + List result = new ArrayList(); + result.add(2); + for ( int i = 3; i < aLimit; i += 2 ) { + if ( ! composite[i] ) { + result.add(i); + } + } + return result; + } + + private static int ramanujanPrime(int[] aPrimePi, int aNumber) { + int maximum = ramanujanMaximum(aNumber); + if ( ( maximum & 1) == 1 ) { + maximum -= 1; + } + + int index = maximum; + while ( aPrimePi[index] - aPrimePi[index / 2] >= aNumber ) { + index -= 1; + } + return index + 1; + } + + private static int[] initialisePrimePi(int aLimit) { + int[] result = new int[aLimit]; + Arrays.fill(result, 1); + result[0] = 0; + result[1] = 0; + for ( int i = 4; i < aLimit; i += 2 ) { + result[i] = 0; + } + for ( int p = 3, square = 9; square < aLimit; p += 2 ) { + if ( result[p] != 0 ) { + for ( int q = square; q < aLimit; q += p << 1 ) { + result[q] = 0; + } + } + square += ( p + 1 ) << 2; + } + Arrays.parallelPrefix(result, Integer::sum); + return result; + } + + private static int ramanujanMaximum(int aNumber) { + return (int) Math.ceil(4 * aNumber * Math.log(4 * aNumber)); + } + +} diff --git a/Task/Ramanujans-constant/Raku/ramanujans-constant-1.raku b/Task/Ramanujans-constant/Raku/ramanujans-constant-1.raku index cb6405f24e..bdf002c71a 100644 --- a/Task/Ramanujans-constant/Raku/ramanujans-constant-1.raku +++ b/Task/Ramanujans-constant/Raku/ramanujans-constant-1.raku @@ -18,8 +18,8 @@ multi infix:<**> (FatRat $base, FatRat $exp where * < 1 --> FatRat) { while (abs($mid - $exp) > ε) { $sqr = sqrt($sqr); - if ($mid <= $exp) { $low = $mid; $acc *= $sqr } - else { $high = $mid; $acc *= 1/$sqr } + if ($mid <= $exp) { $low = $mid; $acc ×= $sqr } + else { $high = $mid; $acc ××= 1/$sqr } $mid = ($low + $high) / 2; } $acc.substr(0, D).FatRat; @@ -33,8 +33,8 @@ sub π (--> FatRat) { my $pi; for ^d { - given [ ($a + $g)/2, sqrt $a * $g ] { - $z -= (.[0] - $a)**2 * $n; + given [ ($a + $g)/2, sqrt $a × $g ] { + $z -= (.[0] - $a)**2 × $n; $n += $n; ($a, $g) = @$_; $pi = ($a ** 2 / $z).substr: 0, 2 + D; @@ -44,7 +44,7 @@ sub π (--> FatRat) { } multi sqrt(FatRat $r --> FatRat) { - FatRat.new: sqrt($r.nude[0] * 10**(D*2) div $r.nude[1]), 10**D; + FatRat.new: sqrt($r.nude[0] × 10**(D×2) div $r.nude[1]), 10**D; } # integer roots @@ -59,7 +59,7 @@ multi sqrt(Int $n) { sub prefix:<√> (Int $n) { sqrt($n.FatRat) } # calculation of 𝑒 -sub postfix: (Int $n) { (constant f = 1, |[\*] 1..*)[$n] } +sub postfix: (Int $n) { (constant f = 1, |[\×] 1..*)[$n] } sub 𝑒 (--> FatRat) { sum map { FatRat.new(1,.!) }, ^D } # inputs, and their difference, formatted decimal-aligned @@ -77,14 +77,14 @@ sub format ($a,$b) { constant π = &π(); constant 𝑒 = &𝑒(); -my $Ramanujan = 𝑒**(π*√163); +my $Ramanujan = 𝑒**(π × √163); say "Ramanujan's constant to 32 decimal places:\nActual: " ~ "262537412640768743.99999999999925007259719818568888\n" ~ "Calculated: ", $Ramanujan.precise(32, :z), "\n"; say "Heegner numbers yielding 'almost' integers"; for 19, 96, 43, 960, 67, 5280, 163, 640320 -> $heegner, $x { - my $almost = 𝑒**(π*√$heegner); + my $almost = 𝑒**(π × √$heegner); my $exact = $x³ + 744; say format($exact, $almost); } diff --git a/Task/Recamans-sequence/EasyLang/recamans-sequence.easy b/Task/Recamans-sequence/EasyLang/recamans-sequence.easy new file mode 100644 index 0000000000..3c3394e248 --- /dev/null +++ b/Task/Recamans-sequence/EasyLang/recamans-sequence.easy @@ -0,0 +1,21 @@ +arrbase a[] 0 +arrbase seen[] 0 +len seen[] 100 +# +a[] &= 0 +seen[0] = 1 +i = 1 +repeat + h = a[i - 1] - i + if h <= 0 or seen[h] = 1 + h = a[i - 1] + i + . + until seen[h] = 1 + seen[h] = 1 + a[] &= h + if i = 14 + print a[] + . + i += 1 +. +print h diff --git a/Task/Rep-string/C++/rep-string.cpp b/Task/Rep-string/C++/rep-string-1.cpp similarity index 100% rename from Task/Rep-string/C++/rep-string.cpp rename to Task/Rep-string/C++/rep-string-1.cpp diff --git a/Task/Rep-string/C++/rep-string-2.cpp b/Task/Rep-string/C++/rep-string-2.cpp new file mode 100644 index 0000000000..82578b7928 --- /dev/null +++ b/Task/Rep-string/C++/rep-string-2.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include +#include + +std::string repeat(const std::string& text, const int32_t& repetitions) { + std::stringstream stream; + std::fill_n(std::ostream_iterator(stream), repetitions, text); + return stream.str(); +} + +std::vector rep_string(const std::string& text) { + std::vector repetitions; + + for ( uint64_t len = 1; len <= text.length() / 2; ++len ) { + std::string possible = text.substr(0, len); + uint64_t quotient = text.length() / len; + uint64_t remainder = text.length() % len; + std::string candidate = repeat(possible, quotient) + possible.substr(0, remainder); + if ( candidate == text ) { + repetitions.emplace_back(possible); + } + } + return repetitions; +} + +int main() { + const std::vector tests = { "1001110011", "1110111011", "0010010010", + "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" }; + + std::cout << "The longest rep-strings are:" << std::endl; + for ( const std::string& test : tests ) { + std::vector repeats = rep_string(test); + std::string result = repeats.empty() ? "Not a rep-string" : repeats.back(); + std::cout << std::setw(10) << test << " -> " << result << std::endl; + } +} diff --git a/Task/Rep-string/Java/rep-string.java b/Task/Rep-string/Java/rep-string-1.java similarity index 100% rename from Task/Rep-string/Java/rep-string.java rename to Task/Rep-string/Java/rep-string-1.java diff --git a/Task/Rep-string/Java/rep-string-2.java b/Task/Rep-string/Java/rep-string-2.java new file mode 100644 index 0000000000..45881d679b --- /dev/null +++ b/Task/Rep-string/Java/rep-string-2.java @@ -0,0 +1,33 @@ +import java.util.ArrayList; +import java.util.List; + +public final class RepStrings { + + public static void main(String[] aArgs) { + List tests = List.of( "1001110011", "1110111011", "0010010010", + "1010101010", "1111111111", "0100101101", "0100100", "101", "11", "00", "1" ); + + System.out.println("The longest rep-strings are:"); + for ( String test : tests ) { + List repeats = repString(test); + String result = repeats.isEmpty() ? "Not a rep-string" : repeats.get(repeats.size() - 1); + System.out.println(String.format("%10s%s%s", test, " -> ", result)); + } + } + + private static List repString(String aText) { + List repetitions = new ArrayList(); + + for ( int length = 1; length <= aText.length() / 2; length++ ) { + String possible = aText.substring(0, length); + int quotient = aText.length() / length; + int remainder = aText.length() % length; + String candidate = possible.repeat(quotient) + possible.substring(0, remainder); + if ( candidate.equals(aText) ) { + repetitions.add(possible); + } + } + return repetitions; + } + +} diff --git a/Task/Repunit-primes/Java/repunit-primes.java b/Task/Repunit-primes/Java/repunit-primes.java new file mode 100644 index 0000000000..28447f8a9e --- /dev/null +++ b/Task/Repunit-primes/Java/repunit-primes.java @@ -0,0 +1,26 @@ +import java.math.BigInteger; + +public final class RepunitPrimes { + + public static void main(String[] aArgs) { + final int limit = 2_700; + System.out.println("Repunit primes, up to " + limit + " digits, in:"); + for ( int base = 2; base <= 16; base++ ) { + System.out.print(String.format("%s%2s%s", "Base ", base, ": ")); + String repunit = ""; + while ( repunit.length() < limit ) { + repunit += "1"; + if ( BigInteger.valueOf(repunit.length()).isProbablePrime(CERTAINTY_LEVEL) ) { + BigInteger value = new BigInteger(repunit, base); + if ( value.isProbablePrime(CERTAINTY_LEVEL) ) { + System.out.print(repunit.length() + " "); + } + } + } + System.out.println(); + } + } + + private static final int CERTAINTY_LEVEL = 20; + +} diff --git a/Task/Retrieve-and-search-chat-history/Java/retrieve-and-search-chat-history.java b/Task/Retrieve-and-search-chat-history/Java/retrieve-and-search-chat-history.java new file mode 100644 index 0000000000..b66be7063c --- /dev/null +++ b/Task/Retrieve-and-search-chat-history/Java/retrieve-and-search-chat-history.java @@ -0,0 +1,38 @@ +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.time.LocalDate; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +public final class RetrieveAndSearchChatHistory { + + public static void main(String[] aArgs) throws URISyntaxException, IOException { + String subjectOfSearch = aArgs[0]; // The string 'available' was used to produce the displayed output. + + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + LocalDate tomorrow = now.toLocalDate().plusDays(1); + LocalDate testDate = tomorrow.minusDays(10); + + while ( ! testDate.equals(tomorrow ) ) { + URL address = new URI("http://tclers.tk/conferences/tcl/" + testDate + ".tcl").toURL(); + HttpURLConnection connection = (HttpURLConnection) address.openConnection(); + BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream()) ); + + System.out.println("Searching chat logs for " + testDate); + String line = ""; + while ( ( line = reader.readLine() ).contains(subjectOfSearch) ) { + System.out.println(line); + } + + reader.close(); + connection.disconnect(); + testDate = testDate.plusDays(1); + } + } + +} diff --git a/Task/Return-multiple-values/EasyLang/return-multiple-values.easy b/Task/Return-multiple-values/EasyLang/return-multiple-values.easy index b47adfed5f..7888ec771b 100644 --- a/Task/Return-multiple-values/EasyLang/return-multiple-values.easy +++ b/Task/Return-multiple-values/EasyLang/return-multiple-values.easy @@ -2,6 +2,6 @@ proc addSubtract a b . sum diff . sum = a + b diff = a - b . -call addSubtract 7 5 sum diff +addSubtract 7 5 sum diff print "Sum: " & sum print "Difference: " & diff diff --git a/Task/Reverse-a-string/EasyLang/reverse-a-string.easy b/Task/Reverse-a-string/EasyLang/reverse-a-string.easy index b828a1157d..749257002d 100644 --- a/Task/Reverse-a-string/EasyLang/reverse-a-string.easy +++ b/Task/Reverse-a-string/EasyLang/reverse-a-string.easy @@ -1,10 +1,8 @@ -proc reverse . s$ . +func$ reverse s$ . a$[] = strchars s$ for i = 1 to len a$[] div 2 swap a$[i] a$[len a$[] - i + 1] . - s$ = strjoin a$[] + return strjoin a$[] . -s$ = "hello" -call reverse s$ -print s$ +print reverse "hello" diff --git a/Task/Roman-numerals-Decode/EasyLang/roman-numerals-decode.easy b/Task/Roman-numerals-Decode/EasyLang/roman-numerals-decode.easy index 4b93732c47..946d28df92 100644 --- a/Task/Roman-numerals-Decode/EasyLang/roman-numerals-decode.easy +++ b/Task/Roman-numerals-Decode/EasyLang/roman-numerals-decode.easy @@ -1,4 +1,4 @@ -proc rom2dec rom$ . val . +func rom2dec rom$ . symbols$[] = [ "M" "D" "C" "L" "X" "V" "I" ] values[] = [ 1000 500 100 50 10 5 1 ] val = 0 @@ -14,10 +14,8 @@ proc rom2dec rom$ . val . . oldv = v . + return val . -call rom2dec "MCMXC" v -print v -call rom2dec "MMVIII" v -print v -call rom2dec "MDCLXVI" v -print v +print rom2dec "MCMXC" +print rom2dec "MMVIII" +print rom2dec "MDCLXVI" diff --git a/Task/Roman-numerals-Encode/EasyLang/roman-numerals-encode.easy b/Task/Roman-numerals-Encode/EasyLang/roman-numerals-encode.easy index 5a2e06cec7..5b53e50e09 100644 --- a/Task/Roman-numerals-Encode/EasyLang/roman-numerals-encode.easy +++ b/Task/Roman-numerals-Encode/EasyLang/roman-numerals-encode.easy @@ -1,17 +1,14 @@ -proc dec2rom dec . rom$ . +func$ dec2rom dec . values[] = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ] symbol$[] = [ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX" "V" "IV" "I" ] - rom$ = "" for i = 1 to len values[] while dec >= values[i] rom$ &= symbol$[i] dec -= values[i] . . + return rom$ . -call dec2rom 1990 r$ -print r$ -call dec2rom 2008 r$ -print r$ -call dec2rom 1666 r$ -print r$ +print dec2rom 1990 +print dec2rom 2008 +print dec2rom 1666 diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/C-sharp/rosetta-code-rank-languages-by-popularity-1.cs b/Task/Rosetta-Code-Rank-languages-by-popularity/C-sharp/rosetta-code-rank-languages-by-popularity-1.cs index 907e66b07c..4d74120af1 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/C-sharp/rosetta-code-rank-languages-by-popularity-1.cs +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/C-sharp/rosetta-code-rank-languages-by-popularity-1.cs @@ -9,32 +9,52 @@ class Program { static void Main(string[] args) { - string get1 = new WebClient().DownloadString("http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json"); - string get2 = new WebClient().DownloadString("http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000"); + string get2 = new WebClient().DownloadString("http://www.rosettacode.org/w/index.php?" + +"title=Special:Categories&limit=5000" + ); ArrayList langs = new ArrayList(); Dictionary qtdmbr = new Dictionary(); - MatchCollection match1 = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1); - MatchCollection match2 = new Regex("title=\"Category:(.+?)\">.+?[^(]*\\((\\d+) members\\)").Matches(get2); + string cmcontinue = ""; - foreach (Match lang in match1) langs.Add(lang.Groups[1].Value); + do + { + string get1 = new WebClient().DownloadString("http://www.rosettacode.org/w/api.php?" + +"action=query&list=categorymembers" + +"&cmtitle=Category:Programming_Languages" + +"&cmlimit=500&format=json" + +cmcontinue + ); + cmcontinue = ""; + MatchCollection languageMatch = new Regex("\"title\":\"Category:(.+?)\"").Matches(get1); + MatchCollection cmcontinueMatch = new Regex("cmcontinue\":\"([a-z0-9A-Z|]*)\"").Matches(get1); + foreach (Match lang in languageMatch) langs.Add(lang.Groups[1].Value); + foreach (Match more in cmcontinueMatch) cmcontinue = "&cmcontinue=" + more.Groups[1].Value; + } + while( cmcontinue != "" ); + + MatchCollection match2 = + new Regex("title=\"Category:(.+?)\">.+?[^(]*\\(([\\d,.]+) members\\)").Matches(get2); foreach (Match match in match2) { if (langs.Contains(match.Groups[1].Value)) { - qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value)); + qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value + .Replace(",",string.Empty) + .Replace(".",string.Empty))); } } - string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,3} - {1}", x.Value, x.Key)).ToArray(); + string[] test = + qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format("{0,4} {1}", x.Value, x.Key)).ToArray(); int count = 1; foreach (string i in test) { - Console.WriteLine("{0,3}. {1}", count, i); + Console.WriteLine("{0,4}: {1}", count, i); count++; } } diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Visual-Basic-.NET/rosetta-code-rank-languages-by-popularity.vb b/Task/Rosetta-Code-Rank-languages-by-popularity/Visual-Basic-.NET/rosetta-code-rank-languages-by-popularity.vb new file mode 100644 index 0000000000..31a07c8a36 --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Visual-Basic-.NET/rosetta-code-rank-languages-by-popularity.vb @@ -0,0 +1,82 @@ +Imports System.Collections +Imports System.Collections.Generic +Imports System.Net +Imports System.Text.RegularExpressions + +Module RankLanguagesByPopularity + + Private Class LanguageStat + Public name As String + Public count As Integer + Public Sub New(name As String, count As Integer) + Me.name = name + Me.count = count + End Sub + End Class + + Private Function CompareLanguages(x As LanguageStat, y As languageStat) As Integer + Dim result As Integer = 0 + If x IsNot Nothing Or y IsNot Nothing Then + If x Is Nothing Then + result = -1 + ElseIf y Is Nothing + result = 1 + Else + result = - x.count.CompareTo(y.count) ' Sort descending count + If result = 0 Then + result = x.name.CompareTo(y.name) ' Sort ascending name + End If + End If + End If + Return result + End Function + + Public Sub Main(ByVal args As String()) + + Dim languages As New List(Of LanguageStat) + Dim basePage As String = "https://rosettacode.org/wiki/Category:Programming_Languages" + Dim nextPage As String = basePage + + Dim nextPageEx = New RegEx("([^<]+?)[^<]* "" + Dim wc As New WebClient() + Dim page As String = wc.DownloadString(nextPage) + + nextPage = "" + For Each link In nextPageEx.Matches(page) + nextPage = basePage & link.Groups(1).Value + Next link + + For Each language In languageStatEx.Matches(page) + Dim lCount As Integer = 0 + Dim lName As String = language.Groups(1).Value + Dim countText As String = language.Groups(2).Value.Replace(",", "").Replace(".", "") + If Not Integer.TryParse(countText, lCount) + Console.Out.WriteLine(lName & "Invalid page count: <<" & countText & ">>") + Else + languages.Add(New LanguageStat(lName, lCount)) + End If + Next language + Loop + + languages.Sort(AddressOf CompareLanguages) + + Dim prevCount As Integer = -1 + Dim prevPosition As Integer = -1 + Dim position As Integer = 0 + For Each stat As LanguageStat In languages + position += 1 + If stat.count <> prevCount Then + prevPosition = position + prevCount = stat.Count + End If + Console.Out.WriteLine(prevPosition.ToString.PadLeft(4) & ": " & + stat.count.ToString.PadLeft(4) & " " & stat.name) + Next stat + + End Sub + +End Module diff --git a/Task/Rot-13/EasyLang/rot-13.easy b/Task/Rot-13/EasyLang/rot-13.easy index e08f3fbc74..a06cff2cf8 100644 --- a/Task/Rot-13/EasyLang/rot-13.easy +++ b/Task/Rot-13/EasyLang/rot-13.easy @@ -1,23 +1,21 @@ -proc rot13 string$ . encodedString$ . - encodedString$ = "" - for i = 1 to len string$ - code = strcode substr string$ i 1 +func$ rot13 str$ . + for c$ in strchars str$ + code = strcode c$ if code >= 65 and code <= 90 - encodedCode = code + 13 - if encodedCode > 90 - encodedCode = 64 + encodedCode - 90 + encCode = code + 13 + if encCode > 90 + encCode = 64 + encCode - 90 . elif code >= 97 and code <= 122 - encodedCode = code + 13 - if encodedCode > 122 - encodedCode = 96 + encodedCode - 122 + encCode = code + 13 + if encCode > 122 + encCode = 96 + encCode - 122 . else - encodedCode = code + encCode = code . - encodedString$ &= strchar encodedCode + encStr$ &= strchar encCode . + return encStr$ . -# -call rot13 "Rosetta Code" result$ -print result$ +print rot13 "Rosetta Code" diff --git a/Task/Rot-13/Raku/rot-13.raku b/Task/Rot-13/Raku/rot-13-1.raku similarity index 100% rename from Task/Rot-13/Raku/rot-13.raku rename to Task/Rot-13/Raku/rot-13-1.raku diff --git a/Task/Rot-13/Raku/rot-13-2.raku b/Task/Rot-13/Raku/rot-13-2.raku new file mode 100644 index 0000000000..4085b3f0d1 --- /dev/null +++ b/Task/Rot-13/Raku/rot-13-2.raku @@ -0,0 +1 @@ +$ raku -pe '.=trans: {$_ => $_».rotate(13)}({[$_».uc, @$_]}("a".."z"))' diff --git a/Task/Run-length-encoding/EasyLang/run-length-encoding.easy b/Task/Run-length-encoding/EasyLang/run-length-encoding.easy index ca409017a7..c7a32c6124 100644 --- a/Task/Run-length-encoding/EasyLang/run-length-encoding.easy +++ b/Task/Run-length-encoding/EasyLang/run-length-encoding.easy @@ -1,5 +1,4 @@ -proc enc in$ . out$ . - out$ = "" +func$ rlenc in$ . for c$ in strchars in$ if c$ = c0$ cnt += 1 @@ -12,21 +11,22 @@ proc enc in$ . out$ . . . out$ &= cnt & c0$ + return out$ . -proc dec in$ . out$ . - out$ = "" +func$ rldec in$ . for h$ in strsplit in$ " " c$ = substr h$ len h$ 1 for i to number h$ out$ &= c$ . . + return out$ . s$ = input print s$ -call enc s$ s$ +s$ = rlenc s$ print s$ -call dec s$ s$ +s$ = rldec s$ print s$ # input_data diff --git a/Task/Search-in-paragraphs-text/C++/search-in-paragraphs-text.cpp b/Task/Search-in-paragraphs-text/C++/search-in-paragraphs-text.cpp new file mode 100644 index 0000000000..ded597e8ca --- /dev/null +++ b/Task/Search-in-paragraphs-text/C++/search-in-paragraphs-text.cpp @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include +#include +#include + +const std::string PARAGRAPH_SEPARATOR = "\n\n"; + +int main() { + std::ifstream file; + file.open("../Traceback.txt"); + std::stringstream stream; + stream << file.rdbuf(); + std::string file_contents = stream.str(); + + std::vector paragraphs; + uint64_t start; + uint64_t end = 0; + while ( ( start = file_contents.find_first_not_of(PARAGRAPH_SEPARATOR, end) ) != std::string::npos ) { + end = file_contents.find(PARAGRAPH_SEPARATOR, start); + paragraphs.emplace_back(file_contents.substr(start, end - start)); + } + + for ( const std::string& paragraph : paragraphs ) { + if ( paragraph.find("SystemError") != std::string::npos ) { + int32_t index = paragraph.find("Traceback (most recent call last):"); + if ( index >= 0 ) { + std::cout << paragraph.substr(index) << std::endl; + std::cout << "----------------" << std::endl; + } + } + } +} diff --git a/Task/Search-in-paragraphs-text/Java/search-in-paragraphs-text.java b/Task/Search-in-paragraphs-text/Java/search-in-paragraphs-text.java new file mode 100644 index 0000000000..2b9dcf77a9 --- /dev/null +++ b/Task/Search-in-paragraphs-text/Java/search-in-paragraphs-text.java @@ -0,0 +1,25 @@ +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +public final class SearchInParagraphsText { + + public static void main(String[] args) throws IOException { + Path filePath = Path.of("./Traceback.txt"); + String fileContents = Files.readString(filePath, StandardCharsets.UTF_8); + String[] paragraphs = fileContents.split(PARAGRAPH_SEPARATOR); + for ( String paragraph : paragraphs ) { + if ( paragraph.contains("SystemError") ) { + int index = paragraph.indexOf("Traceback (most recent call last):"); + if ( index >= 0 ) { + System.out.println(paragraph.substring(index)); + System.out.println("----------------"); + } + } + } + } + + private static final String PARAGRAPH_SEPARATOR = "\r\n\r\n"; + +} diff --git a/Task/Secure-temporary-file/C++/secure-temporary-file.cpp b/Task/Secure-temporary-file/C++/secure-temporary-file.cpp new file mode 100644 index 0000000000..8d6e535a71 --- /dev/null +++ b/Task/Secure-temporary-file/C++/secure-temporary-file.cpp @@ -0,0 +1,15 @@ +#include + +int main() { + // Creates and opens a temporary file with a unique auto-generated filename. + // If the program closes the file, the file is automatically deleted. + // The file is also automatically deleted if the program exits normally. + std::FILE* temp_file_pointer = std::tmpfile(); + + // Using functions which take a file pointer as an argument + std::fputs("Hello world", temp_file_pointer); + std::rewind(temp_file_pointer); + char buffer[12]; + std::fgets(buffer, sizeof buffer, temp_file_pointer); + printf(buffer); +} diff --git a/Task/Secure-temporary-file/F-Sharp/secure-temporary-file.fs b/Task/Secure-temporary-file/F-Sharp/secure-temporary-file.fs new file mode 100644 index 0000000000..a1b2d08cb1 --- /dev/null +++ b/Task/Secure-temporary-file/F-Sharp/secure-temporary-file.fs @@ -0,0 +1 @@ +printfn $"%s{System.IO.Path.GetTempFileName()}" diff --git a/Task/Secure-temporary-file/Java/secure-temporary-file.java b/Task/Secure-temporary-file/Java/secure-temporary-file-1.java similarity index 100% rename from Task/Secure-temporary-file/Java/secure-temporary-file.java rename to Task/Secure-temporary-file/Java/secure-temporary-file-1.java diff --git a/Task/Secure-temporary-file/Java/secure-temporary-file-2.java b/Task/Secure-temporary-file/Java/secure-temporary-file-2.java new file mode 100644 index 0000000000..5459b3cb07 --- /dev/null +++ b/Task/Secure-temporary-file/Java/secure-temporary-file-2.java @@ -0,0 +1,25 @@ +import java.io.BufferedWriter; +import java.nio.file.Files; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; + +public final class SecureTemporaryFile { + + public static void main(String[] args) throws IOException { + // Create a temporary file in the directory D:\. + // We should use java.nio.file.Files instead of the old java.io.File, as it is more secure. + // If the file cannot be created, it will throw an exception. + Path temporaryFilePath = Files.createTempFile(Path.of("D:/"), "example", ".tmp"); + + // For uniqueness, the Java API will insert a random number between the given prefix + // and the file extension. + System.out.println("Temporary file created: " + temporaryFilePath); + + // Opening it with the following option will cause the file to be deleted when it is closed. + BufferedWriter tempFileWriter = Files.newBufferedWriter( + temporaryFilePath, StandardOpenOption.DELETE_ON_CLOSE); + // ... write to file, read it back in, close it... + } + +} diff --git a/Task/Secure-temporary-file/Kotlin/secure-temporary-file.kotlin b/Task/Secure-temporary-file/Kotlin/secure-temporary-file.kotlin index 4c736dfcb6..771a45988b 100644 --- a/Task/Secure-temporary-file/Kotlin/secure-temporary-file.kotlin +++ b/Task/Secure-temporary-file/Kotlin/secure-temporary-file.kotlin @@ -1,14 +1,8 @@ -// version 1.1.2 +import kotlin.io.path.createTempFile +import kotlin.io.path.deleteExisting -import java.io.File - -fun main(args: Array) { - try { - val tf = File.createTempFile("temp", ".tmp") - println(tf.absolutePath) - tf.delete() - } - catch (ex: Exception) { - println(ex.message) - } +fun main() { + val tempFilePath = createTempFile("example", ".tmp") + println("Temporary file created: $tempFilePath") + tempFilePath.deleteExisting() } diff --git a/Task/Self-describing-numbers/EasyLang/self-describing-numbers.easy b/Task/Self-describing-numbers/EasyLang/self-describing-numbers.easy index 636297ce24..c3c8f85f75 100644 --- a/Task/Self-describing-numbers/EasyLang/self-describing-numbers.easy +++ b/Task/Self-describing-numbers/EasyLang/self-describing-numbers.easy @@ -5,7 +5,7 @@ proc test d[] . . . for i to len d[] if cnt[i] <> d[i] - break 2 + return . . # found @@ -16,17 +16,17 @@ proc test d[] . . . proc backtr ind max . d[] . if ind > len d[] - call test d[] - break 1 + test d[] + return . for d = 0 to max if d < 10 d[ind] = d - call backtr ind + 1 max - d d[] + backtr ind + 1 max - d d[] . . . for i = 1 to 10 len d[] i - call backtr 1 len d[] d[] + backtr 1 len d[] d[] . diff --git a/Task/Semiprime/Maxima/semiprime.maxima b/Task/Semiprime/Maxima/semiprime.maxima new file mode 100644 index 0000000000..f2d085500d --- /dev/null +++ b/Task/Semiprime/Maxima/semiprime.maxima @@ -0,0 +1,5 @@ +/* The first part consider the cases of squares of primes, the second part the remaining cases */ +semiprimep(n):=if integerp(sqrt(n)) and primep(sqrt(n)) then true else lambda([x],length(ifactors(x))=2 and unique(map(second,ifactors(x)))=[1])(n)$ + +/* Example */ +sublist(makelist(i,i,100),semiprimep); diff --git a/Task/Semordnilap/EchoLisp/semordnilap.l b/Task/Semordnilap/EchoLisp/semordnilap.l index ed42bda984..3ef572acc5 100644 --- a/Task/Semordnilap/EchoLisp/semordnilap.l +++ b/Task/Semordnilap/EchoLisp/semordnilap.l @@ -23,8 +23,3 @@ w ))) (writeln 'pairs '→ (length semordnilap)) (writeln 'longest '→ (take semordnilap 5))) - -{{out}} -(task) - pairs → 345 - longest → (rengager tresser strasse reveler retrace) diff --git a/Task/Sequence-of-non-squares/C++/sequence-of-non-squares.cpp b/Task/Sequence-of-non-squares/C++/sequence-of-non-squares-1.cpp similarity index 100% rename from Task/Sequence-of-non-squares/C++/sequence-of-non-squares.cpp rename to Task/Sequence-of-non-squares/C++/sequence-of-non-squares-1.cpp diff --git a/Task/Sequence-of-non-squares/C++/sequence-of-non-squares-2.cpp b/Task/Sequence-of-non-squares/C++/sequence-of-non-squares-2.cpp new file mode 100644 index 0000000000..c1d21f7fe1 --- /dev/null +++ b/Task/Sequence-of-non-squares/C++/sequence-of-non-squares-2.cpp @@ -0,0 +1,24 @@ +#include +#include +#include + +uint32_t non_square(const uint32_t& n) { + return n + static_cast(0.5 + sqrt(n)); +} + +int main() { + std::cout << "The first 22 non-square numbers:" << std::endl; + for ( uint32_t i = 1; i <= 22; ++i ) { + std::cout << non_square(i) << " "; + } + std::cout << std::endl << std::endl; + + uint32_t count = 0; + for ( uint32_t i = 1; i < 1'000'000; ++i ) { + double square_root = sqrt(non_square(i)); + if ( square_root == floor(square_root) ) { + count++; + } + } + std::cout << "Number of squares less than 1'000'000 produced by the formula: " << count << std::endl; +} diff --git a/Task/Sequence-of-non-squares/EasyLang/sequence-of-non-squares.easy b/Task/Sequence-of-non-squares/EasyLang/sequence-of-non-squares.easy new file mode 100644 index 0000000000..bb08700f1a --- /dev/null +++ b/Task/Sequence-of-non-squares/EasyLang/sequence-of-non-squares.easy @@ -0,0 +1,15 @@ +func nonSqu n . + return n + floor (0.5 + sqrt n) +. +for i = 1 to 22 + print nonSqu i +. +for i = 1 to 1e6 + j = sqrt nonSqu i + if j = floor j + found = 1 + . +. +if found = 0 + print "No squares found" +. diff --git a/Task/Sequence-of-primes-by-trial-division/ARM-Assembly/sequence-of-primes-by-trial-division.arm b/Task/Sequence-of-primes-by-trial-division/ARM-Assembly/sequence-of-primes-by-trial-division.arm new file mode 100644 index 0000000000..b64b38d557 --- /dev/null +++ b/Task/Sequence-of-primes-by-trial-division/ARM-Assembly/sequence-of-primes-by-trial-division.arm @@ -0,0 +1,103 @@ +/* ARM assembly Raspberry PI */ +/* program trialprime.s */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../constantes.inc" + +//.include "../../ficmacros32.inc" @ for debugging developper +/************************************/ +/* Initialized data */ +/************************************/ +.data +szMessPrime: .asciz " is prime.\n" +szMessNotPrime: .asciz " is not prime.\n" +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 r4,iStart @ start number + ldr r5,iLimit @ end number + tst r4,#1 + addeq r4,#1 +1: + mov r0,r4 + ldr r1,iAdrsZoneConv + bl conversion10 @ decimal conversion + ldr r0,iAdrsZoneConv + bl affichageMess + mov r0,r4 + bl isPrime + cmp r0,#0 + beq 2f + ldr r0,iAdrszMessPrime + bl affichageMess + b 3f +2: + ldr r0,iAdrszMessNotPrime + bl affichageMess +3: + add r4,r4,#2 + cmp r4,r5 + blt 1b + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdrsZoneConv: .int sZoneConv +iAdrszMessPrime: .int szMessPrime +iAdrszMessNotPrime: .int szMessNotPrime +iAdrszCarriageReturn: .int szCarriageReturn +iAdrszMessStart: .int szMessStart +iStart: .int 4000000000 +iLimit: .int 4000000020 +/******************************************************************/ +/* test if number is prime */ +/******************************************************************/ +/* r0 contains the number */ +/* r0 return 1 if prime else return 0 */ +isPrime: + push {r4,lr} @ save registers + cmp r0,#1 @ <= 1 ? + movls r0,#0 @ not prime + bls 100f + cmp r0,#3 @ 2 and 3 prime + movls r0,#1 + bls 100f + tst r0,#1 @ even ? + moveq r0,#0 @ not prime + beq 100f + mov r4,r0 @ save number + mov r1,#3 @ first divisor +1: + mov r0,r4 @ number + bl division + add r1,r1,#2 @ increment divisor + cmp r3,#0 @ remainder = zero ? + moveq r0,#0 @ not prime + beq 100f + cmp r1,r2 @ divisors<=quotient ? + ble 1b @ loop + mov r0,#1 @ return prime + +100: + pop {r4,pc} @ restaur registers +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly*/ +.include "../affichage.inc" diff --git a/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy b/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy index 76bc6077c9..62bcc99d7a 100644 --- a/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy +++ b/Task/Sequence-of-primes-by-trial-division/EasyLang/sequence-of-primes-by-trial-division.easy @@ -1,25 +1,22 @@ -proc isPrime num . result . - result = 0 - if num < 2 - break 1 +func prime n . + if n mod 2 = 0 and n > 2 + return 0 . - if num mod 2 = 0 and num > 2 - break 1 - . - for i = 3 step 2 to sqrt num - if num mod i = 0 - break 2 + i = 3 + while i <= sqrt n + if n mod i = 0 + return 0 . + i += 2 . - result = 1 + return 1 . -proc primeSequence first last . sequence[] . +proc primeSequ first last . sequ[] . for i = first to last - call isPrime i result - if result = 1 - sequence[] &= i + if prime i = 1 + sequ[] &= i . . . -call primeSequence 1 100 seq[] +primeSequ 2 100 seq[] print seq[] diff --git a/Task/Set-puzzle/Acornsoft-Lisp/set-puzzle.lisp b/Task/Set-puzzle/Acornsoft-Lisp/set-puzzle.lisp new file mode 100644 index 0000000000..2962d3ce9f --- /dev/null +++ b/Task/Set-puzzle/Acornsoft-Lisp/set-puzzle.lisp @@ -0,0 +1,109 @@ +(setq numbers '(one two three)) +(setq shadings '(solid open striped)) +(setq colours '(red green purple)) +(setq symbols '(oval squiggle diamond)) + +(defun play ((n-cards . 9)) + (find-enough-sets n-cards (quotient n-cards 2))) + +(defun find-enough-sets (n-cards enough (deal) (sets)) + (loop + (setq deal (random-sample n-cards (deck))) + (setq sets (find-sets deal)) + (while (lessp (length sets) enough) + (show-cards deal) + (printc) + (show-sets sets)))) + +(defun show-cards (cards) + (printc (length cards) '! cards) + (map printc cards)) + +(defun show-sets (sets) + (printc (length sets) '! sets) + (map '(lambda (set) + (printc) + (map printc set)) + sets)) + +(defun find-sets (deal) + (keep-if is-set (combinations 3 deal))) + +(defun is-set (cards) + (every feature-makes-set (transpose cards))) + +(defun feature-makes-set (feature-values) + (or (all-same feature-values) + (all-different feature-values))) + +(defun combinations (n items) + (cond + ((zerop n) '(())) + ((null items) '()) + (t (append + (mapc '(lambda (c) (cons (car items) c)) + (combinations (sub1 n) (cdr items))) + (combinations n (cdr items)))))) + +'( Making a deck ) + +(defun deck () + ' ( The deck has to be made only once ) + (cond ((get 'deck 'cards)) + (t (put 'deck 'cards (make-deck))))) + +(defun make-deck () + (add-feature numbers + (add-feature shadings + (add-feature colours + (add-feature symbols + (list '())))))) + +(defun add-feature (values deck) + (flatmap '(lambda (value) + (mapc '(lambda (card) (cons value card)) + deck)) + values)) + +'( Utilities ) + +(defun all-same (values) + (every '(lambda (v) (eq v (car values))) + values)) + +(defun all-different (values) + (every '(lambda (v) (onep (count v values))) + values)) + +(defun count (v values (n . 0)) + (loop (until (null values) n) + (cond ((eq (car values) v) (setq n (add1 n)))) + (setq values (cdr values)))) + +(defun every (test suspects) + (or (null suspects) + (and (test (car suspects)) + (every test (cdr suspects))))) + +(defun transpose (rows) + (apply mapc (cons list rows))) + +(defun reverse (list (result . ())) + (map '(lambda (e) (setq result (cons e result))) + list) + result) + +(defun append (a b) + (reverse (reverse a) b)) + +(defun flatmap (_f_ _list_) + (cond ((null _list_) '()) + (t (append (_f_ (car _list_)) + (flatmap _f_ (cdr _list_)))))) + +(defun keep-if (_p_ _items_ (_to_keep_)) + (map '(lambda (_i_) + (cond ((_p_ _i_) + (setq _to_keep_ (cons _i_ _to_keep_))))) + _items_) + (reverse _to_keep_)) diff --git a/Task/Set-puzzle/Common-Lisp/set-puzzle.lisp b/Task/Set-puzzle/Common-Lisp/set-puzzle.lisp new file mode 100644 index 0000000000..32e0b86208 --- /dev/null +++ b/Task/Set-puzzle/Common-Lisp/set-puzzle.lisp @@ -0,0 +1,86 @@ +(defparameter numbers '(one two three)) +(defparameter shadings '(solid open striped)) +(defparameter colours '(red green purple)) +(defparameter symbols '(oval squiggle diamond)) + +(defun play (&optional (n-cards 9)) + (find-enough-sets n-cards (floor n-cards 2))) + +(defun find-enough-sets (n-cards enough) + (loop + (let* ((deal (random-sample n-cards (deck))) + (sets (find-sets deal))) + (when (>= (length sets) enough) + (show-cards deal) + (show-sets sets) + (return t))))) + +(defun show-cards (cards) + (format t "~D cards~%~{~(~{~10S~}~)~%~}~%" + (length cards) cards)) + +(defun show-sets (sets) + (format t "~D sets~2%~:{~(~@{~{~8S~}~%~}~)~%~}" + (length sets) sets)) + +(defun find-sets (deal) + (remove-if-not #'is-set (combinations 3 deal))) + +(defun is-set (cards) + (every #'feature-makes-set (transpose cards))) + +(defun feature-makes-set (feature-values) + (or (all-same feature-values) + (all-different feature-values))) + +(defun combinations (n items) + (cond + ((zerop n) '(())) + ((null items) '()) + (t (append + (mapcar (lambda (c) (cons (car items) c)) + (combinations (1- n) (cdr items))) + (combinations n (cdr items)))))) + +;;; Making a deck + +(defun deck () + ;; The deck has to be made only once + (or (get 'deck 'cards) + (setf (get 'deck 'cards) (make-deck)))) + +(defun make-deck () + (add-feature numbers + (add-feature shadings + (add-feature colours + (add-feature symbols + (list '())))))) + +(defun add-feature (values deck) + (mapcan (lambda (value) + (mapcar (lambda (card) (cons value card)) + deck)) + values)) + +;;; Utilities + +(defun random-sample (n items) + (let ((len (length items)) + (taken '())) + (dotimes (_ n) + (loop + (let ((i (random len))) + (unless (find i taken) + (setq taken (cons i taken)) + (return))))) + (mapcar (lambda (i) (nth i items)) taken))) + +(defun all-same (values) + (every #'eql values (rest values))) + +(defun all-different (values) + (every (lambda (v) (= (count v values) 1)) + values)) + +(defun transpose (rows) + (apply #'mapcar #'list rows)) diff --git a/Task/Seven-sided-dice-from-five-sided-dice/EasyLang/seven-sided-dice-from-five-sided-dice.easy b/Task/Seven-sided-dice-from-five-sided-dice/EasyLang/seven-sided-dice-from-five-sided-dice.easy new file mode 100644 index 0000000000..7bfb89acf3 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/EasyLang/seven-sided-dice-from-five-sided-dice.easy @@ -0,0 +1,46 @@ +func dice5 . + return random 5 +. +func dice25 . + return (dice5 - 1) * 5 + dice5 +. +func dice7a . + return dice25 mod1 7 +. +func dice7b . + repeat + h = dice25 + until h <= 21 + . + return h mod1 7 +. +numfmt 3 0 +n = 1000000 +len dist[] 7 +# +proc checkdist . . + for i to len dist[] + h = dist[i] / n * 7 + if abs (h - 1) > 0.01 + bad = 1 + . + dist[i] = 0 + print h + . + if bad = 1 + print "-> not uniform" + else + print "-> uniform" + . +. +# +for i to n + dist[dice7a] += 1 +. +checkdist +# +print "" +for i to n + dist[dice7b] += 1 +. +checkdist diff --git a/Task/Shoelace-formula-for-polygonal-area/EasyLang/shoelace-formula-for-polygonal-area.easy b/Task/Shoelace-formula-for-polygonal-area/EasyLang/shoelace-formula-for-polygonal-area.easy new file mode 100644 index 0000000000..327b4c349d --- /dev/null +++ b/Task/Shoelace-formula-for-polygonal-area/EasyLang/shoelace-formula-for-polygonal-area.easy @@ -0,0 +1,13 @@ +proc shoelace . p[][] res . + sum = 0 + for i = 1 to len p[][] - 1 + sum += p[i][1] * p[i + 1][2] + sum -= p[i + 1][1] * p[i][2] + . + sum += p[i][1] * p[1][2] + sum -= p[1][1] * p[i][2] + res = abs sum / 2 +. +data[][] = [ [ 3 4 ] [ 5 11 ] [ 12 8 ] [ 9 5 ] [ 5 6 ] ] +shoelace data[][] res +print res diff --git a/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy b/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy index 9c0c5f849d..265b0204e3 100644 --- a/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy +++ b/Task/Sierpinski-arrowhead-curve/EasyLang/sierpinski-arrowhead-curve.easy @@ -11,12 +11,12 @@ proc curv o l a . . else o -= 1 l /= 2 - call curv o l (-a) + curv o l (-a) ang += a - call curv o l a + curv o l a ang += a - call curv o l (-a) + curv o l (-a) . . move x y -call curv 7 90 -60 +curv 7 90 -60 diff --git a/Task/Sierpinski-carpet/EasyLang/sierpinski-carpet.easy b/Task/Sierpinski-carpet/EasyLang/sierpinski-carpet.easy index 35ce0ddc0d..d4bf14c923 100644 --- a/Task/Sierpinski-carpet/EasyLang/sierpinski-carpet.easy +++ b/Task/Sierpinski-carpet/EasyLang/sierpinski-carpet.easy @@ -3,17 +3,17 @@ proc carp x y sz . . rect sz sz if sz > 0.5 h = sz / 3 - call carp x - sz y - sz h - call carp x - sz y h - call carp x - sz y + sz h - call carp x + sz y - sz h - call carp x + sz y h - call carp x + sz y + sz h - call carp x y - sz h - call carp x y + sz h + carp x - sz y - sz h + carp x - sz y h + carp x - sz y + sz h + carp x + sz y - sz h + carp x + sz y h + carp x + sz y + sz h + carp x y - sz h + carp x y + sz h . . background 000 clear color 633 -call carp 50 50 100 / 3 +carp 50 50 100 / 3 diff --git a/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy b/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy index c689efd7d1..385eed3747 100644 --- a/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy +++ b/Task/Sierpinski-pentagon/EasyLang/sierpinski-pentagon.easy @@ -1,8 +1,6 @@ order = 5 # -background 005 clear -color 999 linewidth 0.2 scale = 1 / (2 + cos 72 * 2) # @@ -20,8 +18,8 @@ proc pentagon x y side depth . . for angle = 0 step 72 to 288 x += cos angle * dist y += sin angle * dist - call pentagon x y side depth - 1 + pentagon x y side depth - 1 . . . -call pentagon 25 15 50 order - 1 +pentagon 25 15 50 order - 1 diff --git a/Task/Sierpinski-triangle-Graphical/EasyLang/sierpinski-triangle-graphical.easy b/Task/Sierpinski-triangle-Graphical/EasyLang/sierpinski-triangle-graphical.easy index b347eac868..94d4deb12c 100644 --- a/Task/Sierpinski-triangle-Graphical/EasyLang/sierpinski-triangle-graphical.easy +++ b/Task/Sierpinski-triangle-Graphical/EasyLang/sierpinski-triangle-graphical.easy @@ -5,9 +5,9 @@ proc triang lev x y size . . else lev -= 1 size /= 2 - call triang lev x + size y size - call triang lev x + size / 2 y + size size - call triang lev x y size + triang lev x + size y size + triang lev x + size / 2 y + size size + triang lev x y size . . -call triang 8 5 5 90 +triang 8 5 5 90 diff --git a/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy b/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy index 98485e5816..ad6606a423 100644 --- a/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy +++ b/Task/Simple-turtle-graphics/EasyLang/simple-turtle-graphics.easy @@ -5,7 +5,7 @@ subr home down = 0 move x y . -call home +home # proc forward n . . x += cos deg * n @@ -22,31 +22,31 @@ proc turn a . . . # proc house . . - call turn 180 - call forward 45 - call turn 180 + turn 180 + forward 45 + turn 180 down = 1 # - call forward 30 - call turn 90 - call forward 30 - call turn 90 - call forward 30 - call turn 90 - call forward 30 + forward 30 + turn 90 + forward 30 + turn 90 + forward 30 + turn 90 + forward 30 # - call turn 30 - call forward 30 - call turn 120 - call forward 30 - call home + turn 30 + forward 30 + turn 120 + forward 30 + home . -call house +house # proc bar a[] . . - call turn 90 - call forward 30 - call turn -90 + turn 90 + forward 30 + turn -90 down = 1 for i to len a[] max = higher max a[i] @@ -54,16 +54,16 @@ proc bar a[] . . for i to len a[] h = a[i] / max * 50 w = 45 / len a[] - call turn -90 - call forward h - call turn 90 - call forward w - call turn 90 - call forward h - call turn -90 + turn -90 + forward h + turn 90 + forward w + turn 90 + forward h + turn -90 . - call turn 180 - call forward 45 - call home + turn 180 + forward 45 + home . -call bar [ 50 33 200 130 50 ] +bar [ 50 33 200 130 50 ] diff --git a/Task/Singleton/Forth/singleton.fth b/Task/Singleton/Forth/singleton.fth index eb488c1db4..99c90690f0 100644 --- a/Task/Singleton/Forth/singleton.fth +++ b/Task/Singleton/Forth/singleton.fth @@ -1,4 +1,4 @@ -include FMS-SI.f +include FMS2VT.f \ A singleton is created by using normal Forth data \ allocation words such as value or variable as instance variables. diff --git a/Task/Singleton/Java/singleton-3.java b/Task/Singleton/Java/singleton-3.java index 988f5eef53..23f0ab888c 100644 --- a/Task/Singleton/Java/singleton-3.java +++ b/Task/Singleton/Java/singleton-3.java @@ -1,20 +1,15 @@ -class Singleton -{ - private static Singleton myInstance; - public static Singleton getInstance() - { - if (myInstance == null) - { - myInstance = new Singleton(); - } +public enum Singleton { + INSTANCE; - return myInstance; + // Fields, constructors and methods... + private int value; + Singleton() { + value = 0; } - - protected Singleton() - { - // Constructor code goes here. + public int getValue() { + return value; + } + public void setValue(int value) { + this.value = value; } - - // Any other methods } diff --git a/Task/Singleton/Java/singleton-4.java b/Task/Singleton/Java/singleton-4.java new file mode 100644 index 0000000000..988f5eef53 --- /dev/null +++ b/Task/Singleton/Java/singleton-4.java @@ -0,0 +1,20 @@ +class Singleton +{ + private static Singleton myInstance; + public static Singleton getInstance() + { + if (myInstance == null) + { + myInstance = new Singleton(); + } + + return myInstance; + } + + protected Singleton() + { + // Constructor code goes here. + } + + // Any other methods +} diff --git a/Task/Singly-linked-list-Element-definition/Nim/singly-linked-list-element-definition.nim b/Task/Singly-linked-list-Element-definition/Nim/singly-linked-list-element-definition.nim index 6f3296f68f..bc00cad447 100644 --- a/Task/Singly-linked-list-Element-definition/Nim/singly-linked-list-element-definition.nim +++ b/Task/Singly-linked-list-Element-definition/Nim/singly-linked-list-element-definition.nim @@ -1,5 +1,6 @@ -type +import std/strutils # for join +type Node[T] = ref object next: Node[T] data: T @@ -44,4 +45,4 @@ var list: SinglyLinkedList[int] for i in 1..5: list.append(i) for i in 6..10: list.prepend(i) -echo "List: ", list +echo "List: ", $list diff --git a/Task/Snake/EasyLang/snake.easy b/Task/Snake/EasyLang/snake.easy index f7f98bdbd4..2d02ed3bc0 100644 --- a/Task/Snake/EasyLang/snake.easy +++ b/Task/Snake/EasyLang/snake.easy @@ -3,7 +3,7 @@ subr fruit ry = (random 20 - 1) * 5 + 2.5 . subr start - call fruit + fruit game = 1 sx[] = [ 52.5 0 0 0 0 ] sy[] = [ 52.5 0 0 0 0 ] @@ -17,7 +17,7 @@ color 997 text "SNAKE" textsize 5 move 10 40 -text "Arrow keys for control" +text "Arrow keys for controlling" move 10 30 text "Press space to to start" # @@ -31,7 +31,7 @@ on key elif keybkey = "ArrowLeft" and dir <> 2 dir = 4 elif keybkey = " " and game = 0 - call start + start . . on timer @@ -85,7 +85,7 @@ on timer if sx = rx and sy = ry len sx[] len sx[] + 3 len sy[] len sy[] + 3 - call fruit + fruit . sx[1] = sx ; sy[1] = sy if game = 1 diff --git a/Task/Sorting-algorithms-Bubble-sort/EasyLang/sorting-algorithms-bubble-sort.easy b/Task/Sorting-algorithms-Bubble-sort/EasyLang/sorting-algorithms-bubble-sort.easy index ef9f3fe4e1..ba48a009ef 100644 --- a/Task/Sorting-algorithms-Bubble-sort/EasyLang/sorting-algorithms-bubble-sort.easy +++ b/Task/Sorting-algorithms-Bubble-sort/EasyLang/sorting-algorithms-bubble-sort.easy @@ -11,5 +11,5 @@ proc bubbleSort . a[] . . . array[] = [ 5 1 19 25 12 1 14 7 ] -call bubbleSort array[] +bubbleSort array[] print array[] diff --git a/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.ada b/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.ada index a9eae3558e..c969d8080b 100644 --- a/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.ada +++ b/Task/Sorting-algorithms-Counting-sort/Ada/sorting-algorithms-counting-sort.ada @@ -1,16 +1,47 @@ -with Ada.Text_Io; use Ada.Text_Io; +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Numerics; use Ada.Numerics; +with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random; procedure Counting_Sort is type Data is array (Integer range <>) of Natural; - procedure Sort(Item : out Data) is + procedure Sort(Item : in out Data) is + minValue, maxValue: Natural; begin - for I in Item'range loop - Item(I) := I; + minValue := Item(Item'First); maxValue := Item(Item'First); + for I in Item'Range loop + if Item(I) < minValue then minValue := Item(I); end if; + if Item(I) > maxValue then maxValue := Item(I); end if; end loop; + declare + Count : Data(minValue .. maxValue); + itemPos : Integer range Item'First - 1 .. Item'Last; + begin + for I in Count'Range loop + Count(I) := 0; + end loop; + for I in Item'Range loop + Count(Item(I)) := Count(Item(I)) + 1; + end loop; + itemPos := 0; + for I in Count'Range loop + for J in 1..Count(I) loop + itemPos := itemPos + 1; + Item(itemPos) := I; + end loop; + end loop; + end; end Sort; - Stuff : Data(1..140); + Stuff : Data(1..30); + Seed : Generator; begin + Put("Before: "); + for I in Stuff'Range loop + Stuff(I) := Integer( Float'Truncation( Random( seed ) * 100.0 ) ); + Put(Natural'Image(Stuff(I))); + end loop; + New_Line; Sort(Stuff); + Put("After : "); for I in Stuff'range loop Put(Natural'Image(Stuff(I))); end loop; diff --git a/Task/Sorting-algorithms-Heapsort/EasyLang/sorting-algorithms-heapsort.easy b/Task/Sorting-algorithms-Heapsort/EasyLang/sorting-algorithms-heapsort.easy index 0c21d1843d..8c699020bb 100644 --- a/Task/Sorting-algorithms-Heapsort/EasyLang/sorting-algorithms-heapsort.easy +++ b/Task/Sorting-algorithms-Heapsort/EasyLang/sorting-algorithms-heapsort.easy @@ -29,5 +29,5 @@ proc sort . d[] . . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] -call sort data[] +sort data[] print data[] diff --git a/Task/Sorting-algorithms-Insertion-sort/EasyLang/sorting-algorithms-insertion-sort.easy b/Task/Sorting-algorithms-Insertion-sort/EasyLang/sorting-algorithms-insertion-sort.easy index eadd92d63d..ae0c415130 100644 --- a/Task/Sorting-algorithms-Insertion-sort/EasyLang/sorting-algorithms-insertion-sort.easy +++ b/Task/Sorting-algorithms-Insertion-sort/EasyLang/sorting-algorithms-insertion-sort.easy @@ -10,5 +10,5 @@ proc sort . d[] . . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] -call sort data[] +sort data[] print data[] diff --git a/Task/Sorting-algorithms-Merge-sort/EasyLang/sorting-algorithms-merge-sort.easy b/Task/Sorting-algorithms-Merge-sort/EasyLang/sorting-algorithms-merge-sort.easy index 4774c8ad74..784d954f34 100644 --- a/Task/Sorting-algorithms-Merge-sort/EasyLang/sorting-algorithms-merge-sort.easy +++ b/Task/Sorting-algorithms-Merge-sort/EasyLang/sorting-algorithms-merge-sort.easy @@ -31,5 +31,5 @@ proc sort . d[] . . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] -call sort data[] +sort data[] print data[] diff --git a/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy b/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy index d080d923a6..4838d2105f 100644 --- a/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy +++ b/Task/Sorting-algorithms-Quicksort/EasyLang/sorting-algorithms-quicksort.easy @@ -12,17 +12,17 @@ proc qsort left right . d[] . swap d[left] d[mid] # if mid < (right + left) / 2 - call qsort left mid - 1 d[] + qsort left mid - 1 d[] left = mid + 1 else - call qsort mid + 1 right d[] + qsort mid + 1 right d[] right = mid - 1 . . . -func sort . d[] . - call qsort 1 len d[] d[] +proc sort . d[] . + qsort 1 len d[] d[] . d[] = [ 29 4 72 44 55 26 27 77 92 5 ] -call sort d[] +sort d[] print d[] diff --git a/Task/Sorting-algorithms-Radix-sort/EasyLang/sorting-algorithms-radix-sort.easy b/Task/Sorting-algorithms-Radix-sort/EasyLang/sorting-algorithms-radix-sort.easy index e60d2b9d75..71f9c57887 100644 --- a/Task/Sorting-algorithms-Radix-sort/EasyLang/sorting-algorithms-radix-sort.easy +++ b/Task/Sorting-algorithms-Radix-sort/EasyLang/sorting-algorithms-radix-sort.easy @@ -28,5 +28,5 @@ proc sort . d[] . . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] -call sort data[] +sort data[] print data[] diff --git a/Task/Sorting-algorithms-Selection-sort/EasyLang/sorting-algorithms-selection-sort.easy b/Task/Sorting-algorithms-Selection-sort/EasyLang/sorting-algorithms-selection-sort.easy index 357c9c40a4..36082f6d15 100644 --- a/Task/Sorting-algorithms-Selection-sort/EasyLang/sorting-algorithms-selection-sort.easy +++ b/Task/Sorting-algorithms-Selection-sort/EasyLang/sorting-algorithms-selection-sort.easy @@ -8,5 +8,5 @@ proc sort . d[] . . . data[] = [ 29 4 72 44 55 26 27 77 92 5 ] -call sort data[] +sort data[] print data[] 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 index cb4a0e6514..9a3272083b 100644 --- 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 @@ -1,81 +1,100 @@ --- Return a deep copy of theList with items l thru r sorted ascending. +-- Sort items l thru r of theList in place, ascending. on strandSort(theList, l, r) - -- Resolve negative and/or transposed range index parameters. + -- Deal with 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." + 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 dest : theList -- Original list. + property src : my dest's items l thru r -- The items in the sort range. 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 + -- Individually list-wrap the items in o's src to avoid having to + -- hard-code their actual class in the line marked ** below. + repeat with i from 1 to (r - l + 1) + set o's src's item i to {o's src's item i} + end repeat + -- Extract "strands" of existing order from the sort range items + -- and write the resulting runs over the range in the original list. 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 + set jv to o's src's beginning's beginning -- The value in src's first sublist. + set o's dest's item j to jv -- Store it in the next original-list slot + set o's src's item 1 to missing value -- Replace the sublist with a placeholder. + -- Do the same with any later values that are sequentially greater or equal. + repeat with k from 2 to (count o's src) + set kv to o's src's item k's beginning + if (kv < jv) 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 + set o's dest's item j to kv + set jv to kv + set o's src's item k to missing value end if end repeat - set o's ranges's end to {i, j} + set o's ranges's end to {i, j} -- Note this strand's range in the list. + set o's src to o's src's lists -- Lose src's zapped sublists. ** 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. + set strandCount to (count o's ranges) + if (strandCount = 1) then return -- The input list was 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 + -- Work out how many passes the iterative merge will take and from this whether + -- the auxiliary list has to be the source or the destination during the first pass. + -- The destination in the final pass has to be the original list. + set passCount to 0 + repeat while (2 ^ passCount < strandCount) + set passCount to passCount + 1 + end repeat + if (passCount mod 2 = 0) then + set o's src to o's dest + set o's dest to o's dest's items + else + set o's src to o's dest's items + end if + + -- Merge the strands. + repeat passCount times + set k to l -- Destination index. + repeat with rr from 2 to strandCount by 2 -- Per pair of ranges. 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 + set iv to o's src's item i + set jv 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 + if (iv > jv) then + set o's dest's item k to jv + if (j < jx) then + set j to j + 1 + set jv to o's src's item j + else 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 + set o's dest's item k to iv + if (i < ix) then + set i to i + 1 + set iv to o's src's item i + else 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 + if (rr < strandCount) then -- Odd range at the end of this pass? 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 @@ -83,10 +102,14 @@ on strandSort(theList, l, r) end if set o's ranges to o's ranges's lists - set rangeCount to (rangeCount + 1) div 2 + set strandCount to (strandCount + 1) div 2 + set {o's src, o's dest} to {o's dest, o's src} end repeat - return o's dest + return -- nothing. end strandSort -strandSort({5, 1, 4, 37, 2, 0, 9, 6, -44, 3, 8, 7}, 1, -1) +local lst +set lst to {5, 1, 4, 37, 2, 0, 9, 6, -44, 3, 8, 7} +strandSort(lst, 1, -1) +return lst diff --git a/Task/Sorting-algorithms-Strand-sort/Quackery/sorting-algorithms-strand-sort.quackery b/Task/Sorting-algorithms-Strand-sort/Quackery/sorting-algorithms-strand-sort.quackery new file mode 100644 index 0000000000..c0fba1c08b --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/Quackery/sorting-algorithms-strand-sort.quackery @@ -0,0 +1,32 @@ + [ [] swap + 1 split witheach + [ over -1 peek + over > iff + [ swap dip join ] + else join ] ] is sift ( [ --> [ [ ) + + [ [] temp put + [ dup [] != while + over [] != while + over 0 peek + over 0 peek + > not if dip + [ behead + temp take + swap join + temp put ] + again ] + join + temp take swap join ] is merge ( [ [ --> [ ) + + [ [] swap + [ sift + rot merge swap + dup [] = until ] + drop ] is strandsort ( [ --> [ ) + + [] 25 times + [ 89 random 10 + join ] + say "Before: " dup echo cr + strandsort + say "After: " echo cr diff --git a/Task/Spelling-of-ordinal-numbers/00-TASK.txt b/Task/Spelling-of-ordinal-numbers/00-TASK.txt index bdea779930..365980d571 100644 --- a/Task/Spelling-of-ordinal-numbers/00-TASK.txt +++ b/Task/Spelling-of-ordinal-numbers/00-TASK.txt @@ -14,7 +14,7 @@ For this task, the following (English-spelled form) will be used: first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth -Furthermore, the American version of numbers will be used here   (as opposed to the British). +Furthermore, the short scale numbering system (i.e. 2,000,000,000 is two billion) will be used here. [[wp:Long and short scales]] '''2,000,000,000'''   is two billion,   ''not''   two milliard. diff --git a/Task/Split-a-character-string-based-on-change-of-character/EasyLang/split-a-character-string-based-on-change-of-character.easy b/Task/Split-a-character-string-based-on-change-of-character/EasyLang/split-a-character-string-based-on-change-of-character.easy index 24b67e4768..26a42c995b 100644 --- a/Task/Split-a-character-string-based-on-change-of-character/EasyLang/split-a-character-string-based-on-change-of-character.easy +++ b/Task/Split-a-character-string-based-on-change-of-character/EasyLang/split-a-character-string-based-on-change-of-character.easy @@ -2,10 +2,10 @@ a$ = "gHHH5YY++///\\" a$[] = strchars a$ cp$ = a$[1] for c$ in a$[] - if c$ <> cp$ - s$ &= ", " - cp$ = c$ - . - s$ &= c$ + if c$ <> cp$ + s$ &= ", " + cp$ = c$ + . + s$ &= c$ . print s$ diff --git a/Task/Steffensens-method/EasyLang/steffensens-method.easy b/Task/Steffensens-method/EasyLang/steffensens-method.easy index d8f3daf392..0dddcc4f9c 100644 --- a/Task/Steffensens-method/EasyLang/steffensens-method.easy +++ b/Task/Steffensens-method/EasyLang/steffensens-method.easy @@ -1,52 +1,52 @@ -proc deCasteljau c0 c1 c2 t . r . +func deCasteljau c0 c1 c2 t . s = 1 - t c01 = s * c0 + t * c1 c12 = s * c1 + t * c2 - r = s * c01 + t * c12 + return s * c01 + t * c12 . -proc xConvexLeftPar t . r . - call deCasteljau 2 (-8) 2 t r +func xConvexLeftPar t . + return deCasteljau 2 (-8) 2 t . -proc yConvexRightPar t . r . - call deCasteljau 1 2 3 t r +func yConvexRightPar t . + return deCasteljau 1 2 3 t . -proc implicitEq x y . r . - r = 5 * x * x + y - 5 +func implicitEq x y . + return 5 * x * x + y - 5 . -proc f t . r . - call xConvexLeftPar t x - call yConvexRightPar t y - call implicitEq x y r - r += t +func f t r . + x = xConvexLeftPar t + y = yConvexRightPar t + r = implicitEq x y + return r + t . -proc aitken p0 . r . - call f p0 p1 - call f p1 p2 +func aitken p0 . + p1 = f p0 p1 + p2 = f p1 p2 p1m0 = p1 - p0 - r = p0 - p1m0 * p1m0 / (p2 - 2 * p1 + p0) + return p0 - p1m0 * p1m0 / (p2 - 2 * p1 + p0) . -proc steffAitken p0 tol maxiter . p . +func steffAitken p0 tol maxiter . for i to maxiter - call aitken p0 p + p = aitken p0 if abs (p - p0) < tol - break 2 + return p . p0 = p . - p = number "nan" + return number "nan" . for i to 11 numfmt 1 0 write "t0 = " & t0 & " : " - call steffAitken t0 0.00000001 1000 t + t = steffAitken t0 0.00000001 1000 numfmt 3 0 if t <> t # nan print "no answer" else - call xConvexLeftPar t x - call yConvexRightPar t y - call implicitEq x y r + x = xConvexLeftPar t + y = yConvexRightPar t + r = implicitEq x y if abs r <= 0.000001 print "intersection at (" & x & " " & y & ")" else diff --git a/Task/String-case/EasyLang/string-case.easy b/Task/String-case/EasyLang/string-case.easy index 957b14e2a7..749f1ab348 100644 --- a/Task/String-case/EasyLang/string-case.easy +++ b/Task/String-case/EasyLang/string-case.easy @@ -1,25 +1,24 @@ -proc toUppercase string$ . result$ . - for i = 1 to len string$ - code = strcode substr string$ i 1 +func$ toUpper s$ . + for c$ in strchars s$ + code = strcode c$ if code >= 97 and code <= 122 code -= 32 . - result$ &= strchar code + res$ &= strchar code . + return res$ . -proc toLowercase string$ . result$ . - for i = 1 to len string$ - code = strcode substr string$ i 1 +func$ toLower s$ . + for c$ in strchars s$ + code = strcode c$ if code >= 65 and code <= 90 code += 32 . - result$ &= strchar code + res$ &= strchar code . + return res$ . string$ = "alphaBETA" print string$ -call toUppercase string$ result$ -print result$ -result$ = "" -call toLowercase string$ result$ -print result$ +print toUpper string$ +print toLower string$ diff --git a/Task/String-comparison/EasyLang/string-comparison.easy b/Task/String-comparison/EasyLang/string-comparison.easy index b1315d76d5..ad492b5ebe 100644 --- a/Task/String-comparison/EasyLang/string-comparison.easy +++ b/Task/String-comparison/EasyLang/string-comparison.easy @@ -1,9 +1,16 @@ -stringA$ = "String" -stringB$ = "string" -stringC$ = "string" -if stringB$ = stringC$ - print "\"" & stringB$ & "\" is equal to \"" & stringC$ & "\"" +a$ = "hello" +if a$ = "hello" + print "equal" . -if stringA$ <> stringB$ - print "\"" & stringA$ & "\" is not equal to \"" & stringB$ & "\"" +if a$ <> "hello2" + print "not equal" +. +if strcmp a$ "hello" = 0 + print "equal" +. +if strcmp a$ "world" < 0 + print "lexically before" +. +if number "10" > number "2" + print "numerically after" . diff --git a/Task/Sudoku/EasyLang/sudoku.easy b/Task/Sudoku/EasyLang/sudoku.easy index 77ad3c905d..fe0cbf2195 100644 --- a/Task/Sudoku/EasyLang/sudoku.easy +++ b/Task/Sudoku/EasyLang/sudoku.easy @@ -29,7 +29,7 @@ proc init . . . . . -call init +init # proc display . . for i = 1 to 81 @@ -52,8 +52,8 @@ proc solve pos . . . if pos > 81 # solved - call display - break 1 + display + return . r = (pos - 1) div 9 c = (pos - 1) mod 9 @@ -67,7 +67,7 @@ proc solve pos . . row[r + d] = 1 col[c + d] = 1 box[b + d] = 1 - call solve pos + 1 + solve pos + 1 row[r + d] = 0 col[c + d] = 0 box[b + d] = 0 @@ -75,7 +75,7 @@ proc solve pos . . . grid[pos] = 0 . -call solve 1 +solve 1 # input_data 5 3 0 0 2 4 7 0 0 diff --git a/Task/Sum-digits-of-an-integer/EasyLang/sum-digits-of-an-integer.easy b/Task/Sum-digits-of-an-integer/EasyLang/sum-digits-of-an-integer.easy new file mode 100644 index 0000000000..17f15465d6 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/EasyLang/sum-digits-of-an-integer.easy @@ -0,0 +1,14 @@ +func sumdig s$ . + for c$ in strchars s$ + h = strcode c$ - 48 + if h >= 10 + h -= 39 + . + r += h + . + return r +. +print sumdig "1" +print sumdig "1234" +print sumdig "fe" +print sumdig "f0e" diff --git a/Task/Sum-of-a-series/EasyLang/sum-of-a-series.easy b/Task/Sum-of-a-series/EasyLang/sum-of-a-series.easy new file mode 100644 index 0000000000..539c8d6c05 --- /dev/null +++ b/Task/Sum-of-a-series/EasyLang/sum-of-a-series.easy @@ -0,0 +1,5 @@ +numfmt 8 0 +for i = 1 to 1000 + s += 1 / (i * i) +. +print s diff --git a/Task/Sum-of-squares/Common-Lisp/sum-of-squares.lisp b/Task/Sum-of-squares/Common-Lisp/sum-of-squares-1.lisp similarity index 100% rename from Task/Sum-of-squares/Common-Lisp/sum-of-squares.lisp rename to Task/Sum-of-squares/Common-Lisp/sum-of-squares-1.lisp diff --git a/Task/Sum-of-squares/Common-Lisp/sum-of-squares-2.lisp b/Task/Sum-of-squares/Common-Lisp/sum-of-squares-2.lisp new file mode 100644 index 0000000000..45eab47c0d --- /dev/null +++ b/Task/Sum-of-squares/Common-Lisp/sum-of-squares-2.lisp @@ -0,0 +1,2 @@ +(defun sum-of-squares (vec) + (reduce #'+ (map 'vector (lambda (x) (* x x)) vec))) diff --git a/Task/Summarize-primes/EasyLang/summarize-primes.easy b/Task/Summarize-primes/EasyLang/summarize-primes.easy index 4b28a73529..b570895107 100644 --- a/Task/Summarize-primes/EasyLang/summarize-primes.easy +++ b/Task/Summarize-primes/EasyLang/summarize-primes.easy @@ -1,19 +1,21 @@ -proc prime x . r . - for i = 2 to sqrt x - if x mod i = 0 - r = 0 - break 2 - . +func prime n . + if n mod 2 = 0 and n > 2 + return 0 . - r = 1 + i = 3 + while i <= sqrt n + if n mod i = 0 + return 0 + . + i += 2 + . + return 1 . for i = 2 to 999 - call prime i r - if r = 1 + if prime i = 1 ind += 1 sum += i - call prime sum r - if r = 1 + if prime sum = 1 print ind & ": " & sum . . diff --git a/Task/The-Name-Game/EasyLang/the-name-game.easy b/Task/The-Name-Game/EasyLang/the-name-game.easy index 383a83e19b..f8f74ff252 100644 --- a/Task/The-Name-Game/EasyLang/the-name-game.easy +++ b/Task/The-Name-Game/EasyLang/the-name-game.easy @@ -11,18 +11,18 @@ proc findInStrArray array$[] item$ . index . for i = 1 to len array$[] if array$[i] = item$ index = i - break 2 + return . . index = 0 . # This version actually handles consonant clusters name$ = input -call toLowercase name$ lowerName$ +toLowercase name$ lowerName$ vowels$[] = [ "a" "e" "i" "o" "u" ] for i = 1 to len lowerName$ letter$ = substr lowerName$ i 1 - call findInStrArray vowels$[] letter$ index + findInStrArray vowels$[] letter$ index if index <> 0 truncName1$ = substr lowerName$ i len lowerName$ break 1 diff --git a/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy b/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy index 9db0b0d141..fffa6c4109 100644 --- a/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy +++ b/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy @@ -55,13 +55,13 @@ proc sum3 a d . st . proc rate . res done . res = 0 for i = 1 step 3 to 7 - call sum3 i 1 res + sum3 i 1 res . for i = 1 to 3 - call sum3 i 3 res + sum3 i 3 res . - call sum3 1 4 res - call sum3 3 2 res + sum3 1 4 res + sum3 3 2 res cnt = 1 for i = 1 to 9 if f[i] = 0 @@ -75,7 +75,7 @@ proc rate . res done . . . proc minmax player alpha beta . rval rmov . - call rate rval done + rate rval done if done = 1 if player = 1 rval = -rval @@ -87,7 +87,7 @@ proc minmax player alpha beta . rval rmov . repeat if f[mov] = 0 f[mov] = player - call minmax (5 - player) (-beta) (-rval) val h + minmax (5 - player) (-beta) (-rval) val h val = -val f[mov] = 0 if val > rval @@ -114,40 +114,40 @@ proc show_result val . . state += 2 . proc computer . . - call minmax 4 -11 11 val mov + minmax 4 -11 11 val mov f[mov] = 4 - call draw mov - call rate val done + draw mov + rate val done state = 0 if done = 1 - call show_result val + show_result val . . proc human . . mov = floor ((mouse_x - 6) / 28) + 3 * floor ((mouse_y - 16) / 28) + 1 if f[mov] = 0 f[mov] = 1 - call draw mov + draw mov state = 1 timer 0.5 . . on timer - call rate val done + rate val done if done = 1 - call show_result val + show_result val else - call computer + computer . . on mouse_down if state = 0 if mouse_x > 6 and mouse_x < 90 and mouse_y > 16 - call human + human . elif state >= 2 state -= 2 - call init + init . . -call init +init diff --git a/Task/Totient-function/ALGOL-68/totient-function.alg b/Task/Totient-function/ALGOL-68/totient-function.alg index 5b31048304..bb47c955dc 100644 --- a/Task/Totient-function/ALGOL-68/totient-function.alg +++ b/Task/Totient-function/ALGOL-68/totient-function.alg @@ -24,7 +24,10 @@ BEGIN print( ( " n phi(n) remarks", newline ) ); FOR n TO 25 DO INT tn = totient( n ); - print( ( whole( n, -2 ), ": ", whole( tn, -5 ), IF tn = n - 1 AND tn /= 0 THEN " n is prime" ELSE "" FI, newline ) ) + print( ( whole( n, -2 ), ": ", whole( tn, -5 ) + , IF tn = n - 1 AND tn /= 0 THEN " n is prime" ELSE "" FI, newline + ) + ) OD; # use the totient function to count primes # INT n100 := 0, n1000 := 0, n10000 := 0, n100000 := 0; diff --git a/Task/Totient-function/EasyLang/totient-function.easy b/Task/Totient-function/EasyLang/totient-function.easy new file mode 100644 index 0000000000..89d13455e1 --- /dev/null +++ b/Task/Totient-function/EasyLang/totient-function.easy @@ -0,0 +1,40 @@ +func totient n . + tot = n + i = 2 + while i <= sqrt n + if n mod i = 0 + while n mod i = 0 + n = n div i + . + tot -= tot div i + . + if i = 2 + i = 1 + . + i += 2 + . + if n > 1 + tot -= tot div n + . + return tot +. +numfmt 0 3 +print " N Prim Phi" +for n = 1 to 25 + tot = totient n + x$ = " " + if n - 1 = tot + x$ = " x " + . + print n & x$ & tot +. +print "" +for n = 1 to 100000 + tot = totient n + if n - 1 = tot + cnt += 1 + . + if n = 100 or n = 1000 or n = 10000 or n = 100000 + print n & " - " & cnt & " primes" + . +. diff --git a/Task/Totient-function/Lua/totient-function.lua b/Task/Totient-function/Lua/totient-function-1.lua similarity index 100% rename from Task/Totient-function/Lua/totient-function.lua rename to Task/Totient-function/Lua/totient-function-1.lua diff --git a/Task/Totient-function/Lua/totient-function-2.lua b/Task/Totient-function/Lua/totient-function-2.lua new file mode 100644 index 0000000000..c8689c4256 --- /dev/null +++ b/Task/Totient-function/Lua/totient-function-2.lua @@ -0,0 +1,44 @@ +do + function totient( n ) -- returns the number of integers k where 1 <= k <= n that are mutually prime to n + if n < 3 then return 1 + elseif n == 3 then return 2 + else + local result, v, i = n, n, 2 + while i * i <= v do + if v % i == 0 then + while v % i == 0 do v = math.floor( v / i ) end + result = result - math.floor( result / i ) + end + if i == 2 then + i = 1 + end + i = i + 2 + end + if v > 1 then result = result - math.floor( result / v ) end + return result + end + end + -- show the totient function values for the first 25 integers + io.write( " n phi(n) remarks\n" ) + for n = 1,25 do + local tn = totient( n ) + io.write( string.format( "%2d", n ), ": ", string.format( "%5d", tn ) + , ( tn == n - 1 and tn ~= 0 and " n is prime" or "" ) + , "\n" + ) + end + -- use the totient function to count primes + local n100, n1000, n10000, n100000 = 0, 0, 0, 0 + for n = 1,100000 do + if totient( n ) == n - 1 then + if n <= 100 then n100 = n100 + 1 end + if n <= 1000 then n1000 = n1000 + 1 end + if n <= 10000 then n10000 = n10000 + 1 end + if n <= 100000 then n100000 = n100000 + 1 end + end + end + io.write( "There are ", string.format( "%6d", n100 ), " primes below 100\n" ) + io.write( "There are ", string.format( "%6d", n1000 ), " primes below 1 000\n" ) + io.write( "There are ", string.format( "%6d", n10000 ), " primes below 10 000\n" ) + io.write( "There are ", string.format( "%6d", n100000 ), " primes below 100 000\n" ) +end diff --git a/Task/Totient-function/Quackery/totient-function.quackery b/Task/Totient-function/Quackery/totient-function.quackery index c524a44680..2ddcad2d78 100644 --- a/Task/Totient-function/Quackery/totient-function.quackery +++ b/Task/Totient-function/Quackery/totient-function.quackery @@ -1,8 +1,3 @@ - [ [ dup while - tuck mod again ] - drop abs ] is gcd ( n n --> n ) - - [ 0 swap dup times [ i over gcd 1 = rot + swap ] diff --git a/Task/Towers-of-Hanoi/EasyLang/towers-of-hanoi.easy b/Task/Towers-of-Hanoi/EasyLang/towers-of-hanoi.easy index f994d9c518..80116bb093 100644 --- a/Task/Towers-of-Hanoi/EasyLang/towers-of-hanoi.easy +++ b/Task/Towers-of-Hanoi/EasyLang/towers-of-hanoi.easy @@ -1,8 +1,8 @@ proc hanoi n src dst aux . . if n >= 1 - call hanoi n - 1 src aux dst + hanoi n - 1 src aux dst print "Move " & src & " to " & dst - call hanoi n - 1 aux dst src + hanoi n - 1 aux dst src . . -call hanoi 5 1 2 3 +hanoi 5 1 2 3 diff --git a/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy b/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy index 4b8b888001..7a271b0f1e 100644 --- a/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy +++ b/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy @@ -13,50 +13,49 @@ proc unload . . . proc load . . while cyl[1] = 1 - call rshift + rshift . cyl[1] = 1 - call rshift + rshift . proc spin . . lim = random 6 for i = 1 to lim - 1 - call rshift + rshift . . -proc fire . shot . +func fire . shot = cyl[1] - call rshift + rshift + return shot . -proc method m[] . shot . - call unload - shot = 0 +func method m[] . + unload for m in m[] if m = 1 - call load + load elif m = 2 - call spin + spin elif m = 3 - call fire shot - if shot = 1 - break 1 + if fire = 1 + return 1 . . . + return 0 . method$[] = [ "load" "spin" "fire" ] proc test m[] . . n = 100000 for i = 1 to n - call method m[] shot - sum += shot + sum += method m[] . for i = 1 to len m[] write method$[m[i]] & " " . print "-> " & 100 * sum / n & "% death" . -call test [ 1 2 1 2 3 2 3 ] -call test [ 1 2 1 2 3 3 ] -call test [ 1 1 2 3 2 3 ] -call test [ 1 1 2 3 3 ] +test [ 1 2 1 2 3 2 3 ] +test [ 1 2 1 2 3 3 ] +test [ 1 1 2 3 2 3 ] +test [ 1 1 2 3 3 ] diff --git a/Task/Van-der-Corput-sequence/EasyLang/van-der-corput-sequence.easy b/Task/Van-der-Corput-sequence/EasyLang/van-der-corput-sequence.easy index f7c10b94b1..e1b4bed116 100644 --- a/Task/Van-der-Corput-sequence/EasyLang/van-der-corput-sequence.easy +++ b/Task/Van-der-Corput-sequence/EasyLang/van-der-corput-sequence.easy @@ -1,18 +1,17 @@ -proc vdc b n . v . +func vdc b n . s = 1 - v = 0 while n > 0 s *= b m = n mod b v += m / s n = n div b . + return v . for b = 2 to 5 write "base " & b & ":" for n range0 10 - call vdc b n v - write " " & v + write " " & vdc b n . print "" . diff --git a/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence.lua b/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-1.lua similarity index 100% rename from Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence.lua rename to Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-1.lua diff --git a/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-2.lua b/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-2.lua new file mode 100644 index 0000000000..725c98f38f --- /dev/null +++ b/Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence-2.lua @@ -0,0 +1,27 @@ +function vdc( nth, base ) -- returns the numerator & denominator of the sequence element n in base + local p, q, n = 0, 1, nth + while n ~= 0 do + p = p * base + p = p + n % base; + q = q * base; + n = math.floor( n / base ) + end + local num, denom = p, q; + -- reduce the numerator and denominator by their gcd + while p ~= 0 do + n = p + p = q % p + q = n + end + num = math.floor( num / q ) + denom = math.floor( denom / q ) + return num, denom +end +for b = 2,5 do + io.write( "base ", b, ": " ) + for n = 0,9 do + local num, denom = vdc( n, b ) + io.write( " ", num ) if num ~= 0 then io.write( "/", denom ) end + end + io.write( "\n" ) +end diff --git a/Task/Variables/EasyLang/variables.easy b/Task/Variables/EasyLang/variables.easy index 048215c055..abeb717bc5 100644 --- a/Task/Variables/EasyLang/variables.easy +++ b/Task/Variables/EasyLang/variables.easy @@ -12,7 +12,7 @@ proc foo . . print a[i] . . -call foo +foo # # string domain$ = "easylang.dev" diff --git a/Task/Vigen-re-cipher/EasyLang/vigen-re-cipher.easy b/Task/Vigen-re-cipher/EasyLang/vigen-re-cipher.easy index 0c5229dd01..9d7830421b 100644 --- a/Task/Vigen-re-cipher/EasyLang/vigen-re-cipher.easy +++ b/Task/Vigen-re-cipher/EasyLang/vigen-re-cipher.easy @@ -1,5 +1,4 @@ -proc encr txt$ pw$ d . r$ . - r$ = "" +func$ encr txt$ pw$ d . txt$[] = strchars txt$ for c$ in strchars pw$ pw[] &= strcode c$ - 65 @@ -15,10 +14,10 @@ proc encr txt$ pw$ d . r$ . r$ &= strchar c . . + return r$ . s$ = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" pw$ = "VIGENERECIPHER" -call encr s$ pw$ 1 r$ -print r$ -call encr r$ pw$ -1 r$ +r$ = encr s$ pw$ 1 print r$ +print encr r$ pw$ -1 diff --git a/Task/Vigen-re-cipher/Zig/vigen-re-cipher-2.zig b/Task/Vigen-re-cipher/Zig/vigen-re-cipher-2.zig index cc79f4ea3a..38fa2272be 100644 --- a/Task/Vigen-re-cipher/Zig/vigen-re-cipher-2.zig +++ b/Task/Vigen-re-cipher/Zig/vigen-re-cipher-2.zig @@ -1,16 +1,4 @@ -/// Caller owns the returned slice memory. -fn vigenere(allocator: Allocator, text: []const u8, key: []const u8, encrypt: bool) Allocator.Error![]u8 { - var dynamic_string = std.ArrayList(u8).init(allocator); - var key_index: usize = 0; - for (text) |letter| { - const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter; - if (std.ascii.isUpper(c)) { - const k = key[key_index]; - const n = if (encrypt) ((c - 'A') + (k - 'A')) else 26 + c - k; - try dynamic_string.append(n % 26 + 'A'); // A-Z - key_index += 1; - key_index %= key.len; - } - } - return dynamic_string.toOwnedSlice(); -} +const Vigenere = enum { + encode, + decode, +}; diff --git a/Task/Vigen-re-cipher/Zig/vigen-re-cipher-3.zig b/Task/Vigen-re-cipher/Zig/vigen-re-cipher-3.zig index cc6b75eb25..f99985e230 100644 --- a/Task/Vigen-re-cipher/Zig/vigen-re-cipher-3.zig +++ b/Task/Vigen-re-cipher/Zig/vigen-re-cipher-3.zig @@ -1,22 +1,22 @@ pub fn main() anyerror!void { - // allocator + // ------------------------------------------ allocator var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { const ok = gpa.deinit(); std.debug.assert(ok == .ok); } const allocator = gpa.allocator(); - // + // --------------------------------------------- stdout const stdout = std.io.getStdOut().writer(); - // + // ---------------------------------------------------- const key = "VIGENERECIPHER"; const text = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!"; - const encoded = try vigenere(allocator, text, key, true); + const encoded = try vigenere(allocator, text, key, .encode); defer allocator.free(encoded); try stdout.print("{s}\n", .{encoded}); - const decoded = try vigenere(allocator, encoded, key, false); + const decoded = try vigenere(allocator, encoded, key, .decode); defer allocator.free(decoded); try stdout.print("{s}\n", .{decoded}); } diff --git a/Task/Vigen-re-cipher/Zig/vigen-re-cipher-4.zig b/Task/Vigen-re-cipher/Zig/vigen-re-cipher-4.zig new file mode 100644 index 0000000000..deb20372a1 --- /dev/null +++ b/Task/Vigen-re-cipher/Zig/vigen-re-cipher-4.zig @@ -0,0 +1,19 @@ +/// Caller owns the returned slice memory. +fn vigenere(allocator: Allocator, text: []const u8, key: []const u8, mode: Vigenere) Allocator.Error![]u8 { + var dynamic_string = std.ArrayList(u8).init(allocator); + var key_index: usize = 0; + for (text) |letter| { + const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter; + if (std.ascii.isUpper(c)) { + const k = key[key_index]; + const n = switch (mode) { + .encode => ((c - 'A') + (k - 'A')), + .decode => 26 + c - k, + }; + try dynamic_string.append(n % 26 + 'A'); // A-Z + key_index += 1; + key_index %= key.len; + } + } + return dynamic_string.toOwnedSlice(); +} diff --git a/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy b/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy index eadf46db12..c334acb4e8 100644 --- a/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy +++ b/Task/Wagstaff-primes/EasyLang/wagstaff-primes.easy @@ -1,29 +1,22 @@ -proc prime v . r . - r = 1 - if v mod 2 = 0 or v mod 3 = 0 - if v <> 2 and v <> 3 - r = 0 - . - break 1 +func prime n . + if n mod 2 = 0 and n > 2 + return 0 . - d = 5 - while d * d <= v - if v mod d = 0 - r = 0 - break 2 + i = 3 + while i <= sqrt n + if n mod i = 0 + return 0 . - d += 2 + i += 2 . + return 1 . pri = 1 -nwag = 0 while nwag <> 10 pri += 2 - call prime pri r - if r = 1 + if prime pri = 1 wag = (pow 2 pri + 1) / 3 - call prime wag r - if r = 1 + if prime wag = 1 nwag += 1 print pri & " => " & wag . diff --git a/Task/War-card-game/C++/war-card-game.cpp b/Task/War-card-game/C++/war-card-game.cpp index 7c174560fa..2de81fba82 100644 --- a/Task/War-card-game/C++/war-card-game.cpp +++ b/Task/War-card-game/C++/war-card-game.cpp @@ -89,7 +89,7 @@ private: int main() { war_game wargame; - + srand((unsigned) time(NULL)); while ( ! wargame.game_over() ) { wargame.next_turn(); } diff --git a/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy b/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy index 8b9cab7577..f46f7dcf15 100644 --- a/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy +++ b/Task/Water-collected-between-towers/EasyLang/water-collected-between-towers.easy @@ -19,7 +19,7 @@ proc water h[] . . repeat s$ = input until s$ = "" - call water number strsplit s$ " " + water number strsplit s$ " " . # input_data diff --git a/Task/Word-wheel/FutureBasic/word-wheel.basic b/Task/Word-wheel/FutureBasic/word-wheel.basic new file mode 100644 index 0000000000..828963d772 --- /dev/null +++ b/Task/Word-wheel/FutureBasic/word-wheel.basic @@ -0,0 +1,39 @@ +#plist NSAppTransportSecurity @{NSAllowsArbitraryLoads:YES} + +include "NSLog.incl" + +local fn CountCharacterInString( string as CFStringRef, character as CFStringRef ) as NSUInteger +end fn = len(string) - len( fn StringByReplacingOccurrencesOfString( string, character, @"" ) ) + +local fn IsLegal( wordStr as CFStringRef ) as BOOL + NSUInteger i, count = len( wordStr ) + CFStringRef letters = @"ndeokgelw" + + if count < 3 || fn StringContainsString( wordStr, @"k" ) == NO then exit fn = NO + for i = 0 to count - 1 + if fn CountCharacterInString( letters, mid( wordStr, i, 1 ) ) < fn CountCharacterInString( wordStr, mid( wordStr, i, 1 ) ) + exit fn = NO + end if + next +end fn = YES + +local fn ArrayOfDictionaryWords as CFArrayRef + CFURLRef url = fn URLWithString( @"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ) + CFStringRef string = lcase( fn StringWithContentsOfURL( url, NSUTF8StringEncoding, NULL ) ) + CFArrayRef wordArr = fn StringComponentsSeparatedByCharactersInSet( string, fn CharacterSetNewlineSet ) +end fn = wordArr + +void local fn FindWheelWords + CFArrayRef wordArr = fn ArrayOfDictionaryWords + CFStringRef wordStr + CFMutableStringRef mutStr = fn MutableStringNew + + for wordStr in wordArr + if fn IsLegal( wordStr ) then MutableStringAppendFormat( mutStr, fn StringWithFormat( @"%@\n", wordStr ) ) + next + NSLog( @"%@", mutStr ) +end fn + +fn FindWheelWords + +HandleEvents diff --git a/Task/Yellowstone-sequence/00-TASK.txt b/Task/Yellowstone-sequence/00-TASK.txt index ecca17fa9d..85742b0057 100644 --- a/Task/Yellowstone-sequence/00-TASK.txt +++ b/Task/Yellowstone-sequence/00-TASK.txt @@ -28,6 +28,7 @@ a(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence tha ;Related tasks: :*   [https://rosettacode.org/wiki/Greatest_common_divisor Greatest common divisor]. :*   [https://rosettacode.org/wiki/Plot_coordinate_pairs Plot coordinate pairs]. +:*   [[EKG sequence convergence]] ;See also: diff --git a/bin/rcd-api-list-all-langs b/bin/rcd-api-list-all-langs index 85815aa2d0..2217c3a1db 100755 --- a/bin/rcd-api-list-all-langs +++ b/bin/rcd-api-list-all-langs @@ -16,7 +16,7 @@ url=https://rosettacode.org/w/api.php?$(IFS='&'; echo "${params[*]}") more='' while true; do - json=$(curl -s "$url$more") + json=$(curl -Ls "$url$more") <<<"$json" jq -r '.query .categorymembers | .[] .title' | grep -E '^Category:[.a-zA-Z0-9]' | diff --git a/bin/rcd-api-list-all-tasks b/bin/rcd-api-list-all-tasks index bc1094241b..f3526b1303 100755 --- a/bin/rcd-api-list-all-tasks +++ b/bin/rcd-api-list-all-tasks @@ -16,7 +16,7 @@ url=https://rosettacode.org/w/api.php?$(IFS='&'; echo "${params[*]}") more='' while true; do - json=$(curl -s "$url$more") + json=$(curl -Ls "$url$more") <<<"$json" jq -r '.query .categorymembers | .[] .title'