diff --git a/Conf/lang.yaml b/Conf/lang.yaml index 425ffc3d94..e060b0f2f5 100644 --- a/Conf/lang.yaml +++ b/Conf/lang.yaml @@ -86,6 +86,7 @@ B: .b B4J: .b4j B4X: .b4x Babel: .pb +BabyCobol: .cobol BaCon: .bacon Bait: .bait Ballerina: .ballerina @@ -124,6 +125,7 @@ Bracmat: .bracmat Brainf***: .bf Brat: .brat Brlcad: .brlcad +Bruijn: .bruijn Burlesque: .blq C++: .cpp C: .c @@ -342,6 +344,7 @@ HLA: .hla HolyC: .holyc Hoon: .hoon Hope: .hope +Hopper: .hopper HPPPL: .hpppl HQ9+: .hq9+ Huginn: .huginn @@ -589,6 +592,7 @@ Oz: .oz Palo Alto Tiny BASIC: .basic Panda: .panda Panoramic: .panoramic +ParaCL: .paracl Pare: .pare PARI/GP: .parigp Pascal: .pas @@ -646,6 +650,7 @@ Processing: .processing Processing Python mode: .processing-py Processing.R: .processing-r ProDOS: .dos +Prog8: .prog8 Prolog: .pro PROMAL: .promal PSQL: .psql @@ -696,6 +701,7 @@ RISC-V Assembly: .asm RLaB: .rlab RLSL: .rlsl Robotic: .robotic +Roc: .roc Rockstar: .rockstar RPG: .rpg RPGIV: .rpgiv @@ -831,6 +837,7 @@ TXR: .txr Typed Racket: .rkt TypeScript: .ts UC++: .uc++ +Uiua: .uiua Ultimate++: .ultimate++ Unicon: .unicon Uniface: .uniface diff --git a/Lang/6502-Assembly/N-queens-problem b/Lang/6502-Assembly/N-queens-problem new file mode 120000 index 0000000000..6cb6d9c259 --- /dev/null +++ b/Lang/6502-Assembly/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/6502-Assembly \ No newline at end of file diff --git a/Lang/ALGOL-68/Angle-difference-between-two-bearings b/Lang/ALGOL-68/Angle-difference-between-two-bearings new file mode 120000 index 0000000000..78582e775d --- /dev/null +++ b/Lang/ALGOL-68/Angle-difference-between-two-bearings @@ -0,0 +1 @@ +../../Task/Angle-difference-between-two-bearings/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Angles-geometric-normalization-and-conversion b/Lang/ALGOL-68/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..e25f8337e6 --- /dev/null +++ b/Lang/ALGOL-68/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Averages-Mean-time-of-day b/Lang/ALGOL-68/Averages-Mean-time-of-day new file mode 120000 index 0000000000..e97106ed2d --- /dev/null +++ b/Lang/ALGOL-68/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Cheryls-birthday b/Lang/ALGOL-68/Cheryls-birthday new file mode 120000 index 0000000000..4a39e22573 --- /dev/null +++ b/Lang/ALGOL-68/Cheryls-birthday @@ -0,0 +1 @@ +../../Task/Cheryls-birthday/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Chinese-remainder-theorem b/Lang/ALGOL-68/Chinese-remainder-theorem new file mode 120000 index 0000000000..5c42550649 --- /dev/null +++ b/Lang/ALGOL-68/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Death-Star b/Lang/ALGOL-68/Death-Star new file mode 120000 index 0000000000..71a96e0b37 --- /dev/null +++ b/Lang/ALGOL-68/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Eban-numbers b/Lang/ALGOL-68/Eban-numbers new file mode 120000 index 0000000000..fa85ff0e58 --- /dev/null +++ b/Lang/ALGOL-68/Eban-numbers @@ -0,0 +1 @@ +../../Task/Eban-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Floyd-Warshall-algorithm b/Lang/ALGOL-68/Floyd-Warshall-algorithm new file mode 120000 index 0000000000..704f4ca44e --- /dev/null +++ b/Lang/ALGOL-68/Floyd-Warshall-algorithm @@ -0,0 +1 @@ +../../Task/Floyd-Warshall-algorithm/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Fortunate-numbers b/Lang/ALGOL-68/Fortunate-numbers new file mode 120000 index 0000000000..c6ecf1ee17 --- /dev/null +++ b/Lang/ALGOL-68/Fortunate-numbers @@ -0,0 +1 @@ +../../Task/Fortunate-numbers/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Long-primes b/Lang/ALGOL-68/Long-primes new file mode 120000 index 0000000000..5932549f9d --- /dev/null +++ b/Lang/ALGOL-68/Long-primes @@ -0,0 +1 @@ +../../Task/Long-primes/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Magic-squares-of-singly-even-order b/Lang/ALGOL-68/Magic-squares-of-singly-even-order new file mode 120000 index 0000000000..25b7aec11a --- /dev/null +++ b/Lang/ALGOL-68/Magic-squares-of-singly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-singly-even-order/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Modified-random-distribution b/Lang/ALGOL-68/Modified-random-distribution new file mode 120000 index 0000000000..1858012a62 --- /dev/null +++ b/Lang/ALGOL-68/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Number-reversal-game b/Lang/ALGOL-68/Number-reversal-game new file mode 120000 index 0000000000..243202f9d2 --- /dev/null +++ b/Lang/ALGOL-68/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Pisano-period b/Lang/ALGOL-68/Pisano-period new file mode 120000 index 0000000000..b012a168d9 --- /dev/null +++ b/Lang/ALGOL-68/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Pythagorean-triples b/Lang/ALGOL-68/Pythagorean-triples new file mode 120000 index 0000000000..8c48c48b1b --- /dev/null +++ b/Lang/ALGOL-68/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Range-consolidation b/Lang/ALGOL-68/Range-consolidation new file mode 120000 index 0000000000..51b0e5d75e --- /dev/null +++ b/Lang/ALGOL-68/Range-consolidation @@ -0,0 +1 @@ +../../Task/Range-consolidation/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Ray-casting-algorithm b/Lang/ALGOL-68/Ray-casting-algorithm new file mode 120000 index 0000000000..2c4b411219 --- /dev/null +++ b/Lang/ALGOL-68/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sequence:-nth-number-with-exactly-n-divisors b/Lang/ALGOL-68/Sequence:-nth-number-with-exactly-n-divisors new file mode 120000 index 0000000000..02fc9fe7df --- /dev/null +++ b/Lang/ALGOL-68/Sequence:-nth-number-with-exactly-n-divisors @@ -0,0 +1 @@ +../../Task/Sequence:-nth-number-with-exactly-n-divisors/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sort-numbers-lexicographically b/Lang/ALGOL-68/Sort-numbers-lexicographically new file mode 120000 index 0000000000..7da8e72755 --- /dev/null +++ b/Lang/ALGOL-68/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sum-and-product-puzzle b/Lang/ALGOL-68/Sum-and-product-puzzle new file mode 120000 index 0000000000..18865c2c45 --- /dev/null +++ b/Lang/ALGOL-68/Sum-and-product-puzzle @@ -0,0 +1 @@ +../../Task/Sum-and-product-puzzle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/Angles-geometric-normalization-and-conversion b/Lang/ALGOL-W/Angles-geometric-normalization-and-conversion new file mode 120000 index 0000000000..84598a2a10 --- /dev/null +++ b/Lang/ALGOL-W/Angles-geometric-normalization-and-conversion @@ -0,0 +1 @@ +../../Task/Angles-geometric-normalization-and-conversion/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Sierpinski-square-curve b/Lang/ALGOL-W/Sierpinski-square-curve new file mode 120000 index 0000000000..c787c64cbf --- /dev/null +++ b/Lang/ALGOL-W/Sierpinski-square-curve @@ -0,0 +1 @@ +../../Task/Sierpinski-square-curve/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Temperature-conversion b/Lang/ALGOL-W/Temperature-conversion new file mode 120000 index 0000000000..fa3a68b9d1 --- /dev/null +++ b/Lang/ALGOL-W/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/ALGOL-W \ No newline at end of file diff --git a/Lang/APL/The-Twelve-Days-of-Christmas b/Lang/APL/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..2bb4434d11 --- /dev/null +++ b/Lang/APL/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/APL \ No newline at end of file diff --git a/Lang/AWK/Textonyms b/Lang/AWK/Textonyms new file mode 120000 index 0000000000..0d5f8babd1 --- /dev/null +++ b/Lang/AWK/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/AWK \ No newline at end of file diff --git a/Lang/Amazing-Hopper/Long-year b/Lang/Amazing-Hopper/Long-year new file mode 120000 index 0000000000..67734f8564 --- /dev/null +++ b/Lang/Amazing-Hopper/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/Amazing-Hopper \ No newline at end of file diff --git a/Lang/Amazing-Hopper/Sort-three-variables b/Lang/Amazing-Hopper/Sort-three-variables new file mode 120000 index 0000000000..3adad4c634 --- /dev/null +++ b/Lang/Amazing-Hopper/Sort-three-variables @@ -0,0 +1 @@ +../../Task/Sort-three-variables/Amazing-Hopper \ No newline at end of file diff --git a/Lang/Amazing-Hopper/Split-a-character-string-based-on-change-of-character b/Lang/Amazing-Hopper/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..ac99345357 --- /dev/null +++ b/Lang/Amazing-Hopper/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/Amazing-Hopper \ No newline at end of file diff --git a/Lang/AppleScript/Arithmetic-numbers b/Lang/AppleScript/Arithmetic-numbers new file mode 120000 index 0000000000..3cefb4a617 --- /dev/null +++ b/Lang/AppleScript/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Textonyms b/Lang/AppleScript/Textonyms new file mode 120000 index 0000000000..e51af23b62 --- /dev/null +++ b/Lang/AppleScript/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Draw-a-pixel b/Lang/Applesoft-BASIC/Draw-a-pixel new file mode 120000 index 0000000000..7ca9518328 --- /dev/null +++ b/Lang/Applesoft-BASIC/Draw-a-pixel @@ -0,0 +1 @@ +../../Task/Draw-a-pixel/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/N-queens-problem b/Lang/Applesoft-BASIC/N-queens-problem new file mode 120000 index 0000000000..be2c30d0bc --- /dev/null +++ b/Lang/Applesoft-BASIC/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Phrase-reversals b/Lang/Applesoft-BASIC/Phrase-reversals new file mode 120000 index 0000000000..2fbcdc7099 --- /dev/null +++ b/Lang/Applesoft-BASIC/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Run-length-encoding b/Lang/Applesoft-BASIC/Run-length-encoding new file mode 120000 index 0000000000..a4ba69544f --- /dev/null +++ b/Lang/Applesoft-BASIC/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/BASIC/00-LANG.txt b/Lang/BASIC/00-LANG.txt index 7299250982..571cd2dd21 100644 --- a/Lang/BASIC/00-LANG.txt +++ b/Lang/BASIC/00-LANG.txt @@ -24,6 +24,7 @@ BASIC became popular, with many different implementations for various computers. **[[wp:PowerBASIC]] **[[wp:PureBasic]] **[[wp:Rocky Mountain BASIC]] +**[[wp:Sinclair BASIC]] **[[wp:SuperBASIC]] **[[wp:True BASIC]] {{language programming paradigm|Procedural}} \ No newline at end of file diff --git a/Lang/BASIC/Reverse-a-string b/Lang/BASIC/Reverse-a-string deleted file mode 120000 index db5bd211b7..0000000000 --- a/Lang/BASIC/Reverse-a-string +++ /dev/null @@ -1 +0,0 @@ -../../Task/Reverse-a-string/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Sum-and-product-puzzle b/Lang/BASIC256/Sum-and-product-puzzle new file mode 120000 index 0000000000..2b964ccfbc --- /dev/null +++ b/Lang/BASIC256/Sum-and-product-puzzle @@ -0,0 +1 @@ +../../Task/Sum-and-product-puzzle/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Validate-International-Securities-Identification-Number b/Lang/BASIC256/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..e6606941e4 --- /dev/null +++ b/Lang/BASIC256/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/BASIC256 \ No newline at end of file diff --git a/Lang/BBC-BASIC/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/BBC-BASIC/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..c061ef014a --- /dev/null +++ b/Lang/BBC-BASIC/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Narcissistic-decimal-number b/Lang/BBC-BASIC/Narcissistic-decimal-number new file mode 120000 index 0000000000..1a2b003e3a --- /dev/null +++ b/Lang/BBC-BASIC/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/BBC-BASIC \ No newline at end of file diff --git a/Lang/BCPL/Narcissistic-decimal-number b/Lang/BCPL/Narcissistic-decimal-number new file mode 120000 index 0000000000..e0ff77fa71 --- /dev/null +++ b/Lang/BCPL/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/BCPL \ No newline at end of file diff --git a/Lang/BQN/Sort-numbers-lexicographically b/Lang/BQN/Sort-numbers-lexicographically new file mode 120000 index 0000000000..c09eafb48d --- /dev/null +++ b/Lang/BQN/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/BQN \ No newline at end of file diff --git a/Lang/BabyCobol/00-LANG.txt b/Lang/BabyCobol/00-LANG.txt new file mode 100644 index 0000000000..b106508e3b --- /dev/null +++ b/Lang/BabyCobol/00-LANG.txt @@ -0,0 +1,7 @@ +{{language|BabyCobol + | site = https://slebok.github.io/baby/ + | gc = no + | parampass = both + | hopl = no +}} +'''BabyCobol''' is an experiment in language design: it is small enough to be quickly implementable (fully or partially) within any framework that can support its features, but complex enough to cover typical problems of legacy language processing. If you learn how to compile [[MiniJava]], you stand a good chance of implementing a reasonably good compiler for any contemporary programming language. If you show how your language extension works on [[Featherweight Java]], it has a good chance of being applicable to any reasonable modern object-oriented programming language. If you can handle BabyCobol with your tool and with your skills, you are ready to face the challenges of software modernisation, codebase migration and legacy language processing in general. \ No newline at end of file diff --git a/Lang/BabyCobol/00-META.yaml b/Lang/BabyCobol/00-META.yaml new file mode 100644 index 0000000000..59c8f2fb7e --- /dev/null +++ b/Lang/BabyCobol/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:BabyCobol diff --git a/Lang/BabyCobol/100-doors b/Lang/BabyCobol/100-doors new file mode 120000 index 0000000000..28c01ba1d4 --- /dev/null +++ b/Lang/BabyCobol/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/BabyCobol \ No newline at end of file diff --git a/Lang/BabyCobol/99-bottles-of-beer b/Lang/BabyCobol/99-bottles-of-beer new file mode 120000 index 0000000000..f2b7e0195f --- /dev/null +++ b/Lang/BabyCobol/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/BabyCobol \ No newline at end of file diff --git a/Lang/BabyCobol/A+B b/Lang/BabyCobol/A+B new file mode 120000 index 0000000000..12cf42c07d --- /dev/null +++ b/Lang/BabyCobol/A+B @@ -0,0 +1 @@ +../../Task/A+B/BabyCobol \ No newline at end of file diff --git a/Lang/BabyCobol/FizzBuzz b/Lang/BabyCobol/FizzBuzz new file mode 120000 index 0000000000..f3080a2a06 --- /dev/null +++ b/Lang/BabyCobol/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/BabyCobol \ No newline at end of file diff --git a/Lang/BabyCobol/Hello-world-Text b/Lang/BabyCobol/Hello-world-Text new file mode 120000 index 0000000000..c4b041271b --- /dev/null +++ b/Lang/BabyCobol/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/BabyCobol \ No newline at end of file diff --git a/Lang/BabyCobol/User-input-Text b/Lang/BabyCobol/User-input-Text new file mode 120000 index 0000000000..f1d99aff15 --- /dev/null +++ b/Lang/BabyCobol/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/BabyCobol \ No newline at end of file diff --git a/Lang/Bait/00-LANG.txt b/Lang/Bait/00-LANG.txt index 0900661567..18a243057f 100644 --- a/Lang/Bait/00-LANG.txt +++ b/Lang/Bait/00-LANG.txt @@ -1,11 +1,11 @@ {{ language|Bait -|site=https://github.com/tiabeast/bait +|site=https://github.com/bait-lang/bait |strength=strong |safety=safe |checking=static }} -Bait is a work-in-progress simple, compiled, general purpose programming language for building reliable software. +Bait is a simple programming language for building reliable software. -Solutions to RosettaCode are maintained at https://github.com/tiabeast/rosetta-bait. Please propose solutions there. \ No newline at end of file +Solutions are maintained at https://github.com/bait-lang/rosetta-bait. Please propose changes there. \ No newline at end of file diff --git a/Lang/Bait/CRC-32 b/Lang/Bait/CRC-32 new file mode 120000 index 0000000000..f40324a53c --- /dev/null +++ b/Lang/Bait/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Bait \ No newline at end of file diff --git a/Lang/Bait/Loops-Downward-for b/Lang/Bait/Loops-Downward-for new file mode 120000 index 0000000000..128e8218f3 --- /dev/null +++ b/Lang/Bait/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Bait \ No newline at end of file diff --git a/Lang/Bait/Loops-For b/Lang/Bait/Loops-For new file mode 120000 index 0000000000..79b044fb61 --- /dev/null +++ b/Lang/Bait/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Bait \ No newline at end of file diff --git a/Lang/Bait/Loops-For-with-a-specified-step b/Lang/Bait/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..941f926d61 --- /dev/null +++ b/Lang/Bait/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Bait \ No newline at end of file diff --git a/Lang/Bait/Loops-Foreach b/Lang/Bait/Loops-Foreach new file mode 120000 index 0000000000..80ae525d6d --- /dev/null +++ b/Lang/Bait/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Bait \ No newline at end of file diff --git a/Lang/Bait/Pascals-triangle b/Lang/Bait/Pascals-triangle new file mode 120000 index 0000000000..564eec1e1a --- /dev/null +++ b/Lang/Bait/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Bait \ No newline at end of file diff --git a/Lang/Befunge/Sorting-algorithms-Bubble-sort b/Lang/Befunge/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..8c2d1f0a86 --- /dev/null +++ b/Lang/Befunge/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Befunge \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/00-LANG.txt b/Lang/Binary-Lambda-Calculus/00-LANG.txt index b1d24e9edd..3f502204f1 100644 --- a/Lang/Binary-Lambda-Calculus/00-LANG.txt +++ b/Lang/Binary-Lambda-Calculus/00-LANG.txt @@ -6,5 +6,6 @@ {{language programming paradigm|functional}} '''Binary Lambda Calculus''' is a minimal, pure, functional, esoteric language based on lambda calculus. [[provides::Capability:First class functions| ]] ==External links== -* [[eso:Binary_lambda_calculus|Esoteric languages wiki page]] -[[Category:Esoteric Languages]] \ No newline at end of file +* https://tromp.github.io/cl/cl.html +* https://www.ioccc.org/2012/tromp/hint.html +* https://gist.github.com/tromp/86b3184f852f65bfb814e3ab0987d861 \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Hello-world-Newbie b/Lang/Binary-Lambda-Calculus/Hello-world-Newbie new file mode 120000 index 0000000000..290aaa1bd5 --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Hello-world-Text b/Lang/Binary-Lambda-Calculus/Hello-world-Text deleted file mode 120000 index b4dcf8b8a8..0000000000 --- a/Lang/Binary-Lambda-Calculus/Hello-world-Text +++ /dev/null @@ -1 +0,0 @@ -../../Task/Hello-world-Text/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Quine b/Lang/Binary-Lambda-Calculus/Quine deleted file mode 120000 index 2c1595a394..0000000000 --- a/Lang/Binary-Lambda-Calculus/Quine +++ /dev/null @@ -1 +0,0 @@ -../../Task/Quine/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Shell-one-liner b/Lang/Binary-Lambda-Calculus/Shell-one-liner new file mode 120000 index 0000000000..c3cce2be43 --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Bruijn/00-LANG.txt b/Lang/Bruijn/00-LANG.txt new file mode 100644 index 0000000000..c0c565d6e8 --- /dev/null +++ b/Lang/Bruijn/00-LANG.txt @@ -0,0 +1,10 @@ +{{language|bruijn + |exec=interpreted + |LCT=no + |site=https://bruijn.marvinborner.de}}{{language programming paradigm|functional}} + +Bruijn is a [[functional_programming|functional]] programming language based on pure [[wp:lambda_calculus|lambda calculus]]. It uses De Bruijn indices instead of named variables and square brackets for abstractions. Like pure lambda calculus, bruijn can be compiled to [https://tromp.github.io/cl/Binary_lambda_calculus.html Binary Lambda Calculus]. Unlike pure lambda calculus, you can define named substitution rules. Bruijn has a large standard library of such definitions. + +Bruijn does not have primitive functions or data types. Every function (including add, map, mul, etc.) is implemented in bruijn itself. Numbers, strings, or chars are syntactic sugar for data encoded as closed terms/abstractions. + +Documentation can be found at https://bruijn.marvinborner.de/wiki/. \ No newline at end of file diff --git a/Lang/Bruijn/00-META.yaml b/Lang/Bruijn/00-META.yaml new file mode 100644 index 0000000000..1ddd70ba76 --- /dev/null +++ b/Lang/Bruijn/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Bruijn diff --git a/Lang/Bruijn/99-bottles-of-beer b/Lang/Bruijn/99-bottles-of-beer new file mode 120000 index 0000000000..12eb60082e --- /dev/null +++ b/Lang/Bruijn/99-bottles-of-beer @@ -0,0 +1 @@ +../../Task/99-bottles-of-beer/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/A+B b/Lang/Bruijn/A+B new file mode 120000 index 0000000000..f6bd8616cf --- /dev/null +++ b/Lang/Bruijn/A+B @@ -0,0 +1 @@ +../../Task/A+B/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Ackermann-function b/Lang/Bruijn/Ackermann-function new file mode 120000 index 0000000000..e9f8313783 --- /dev/null +++ b/Lang/Bruijn/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Balanced-ternary b/Lang/Bruijn/Balanced-ternary new file mode 120000 index 0000000000..1c4c028d9c --- /dev/null +++ b/Lang/Bruijn/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Binary-search b/Lang/Bruijn/Binary-search new file mode 120000 index 0000000000..9cd581be5b --- /dev/null +++ b/Lang/Bruijn/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Comments b/Lang/Bruijn/Comments new file mode 120000 index 0000000000..e8f4b26296 --- /dev/null +++ b/Lang/Bruijn/Comments @@ -0,0 +1 @@ +../../Task/Comments/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Empty-program b/Lang/Bruijn/Empty-program new file mode 120000 index 0000000000..2f8df23d95 --- /dev/null +++ b/Lang/Bruijn/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Factorial b/Lang/Bruijn/Factorial new file mode 120000 index 0000000000..52a5a29667 --- /dev/null +++ b/Lang/Bruijn/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Fibonacci-sequence b/Lang/Bruijn/Fibonacci-sequence new file mode 120000 index 0000000000..0eac3a48a3 --- /dev/null +++ b/Lang/Bruijn/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/FizzBuzz b/Lang/Bruijn/FizzBuzz new file mode 120000 index 0000000000..c2194b65ee --- /dev/null +++ b/Lang/Bruijn/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Function-composition b/Lang/Bruijn/Function-composition new file mode 120000 index 0000000000..9f9efd944a --- /dev/null +++ b/Lang/Bruijn/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Hailstone-sequence b/Lang/Bruijn/Hailstone-sequence new file mode 120000 index 0000000000..6f6aabadc5 --- /dev/null +++ b/Lang/Bruijn/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Halt-and-catch-fire b/Lang/Bruijn/Halt-and-catch-fire new file mode 120000 index 0000000000..ee57eeb8b4 --- /dev/null +++ b/Lang/Bruijn/Halt-and-catch-fire @@ -0,0 +1 @@ +../../Task/Halt-and-catch-fire/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Hamming-numbers b/Lang/Bruijn/Hamming-numbers new file mode 120000 index 0000000000..d835227d4a --- /dev/null +++ b/Lang/Bruijn/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Hello-world-Text b/Lang/Bruijn/Hello-world-Text new file mode 120000 index 0000000000..f5faaa0772 --- /dev/null +++ b/Lang/Bruijn/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Higher-order-functions b/Lang/Bruijn/Higher-order-functions new file mode 120000 index 0000000000..490f30652f --- /dev/null +++ b/Lang/Bruijn/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Levenshtein-distance b/Lang/Bruijn/Levenshtein-distance new file mode 120000 index 0000000000..e4887437b4 --- /dev/null +++ b/Lang/Bruijn/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Loops-Infinite b/Lang/Bruijn/Loops-Infinite new file mode 120000 index 0000000000..038234feba --- /dev/null +++ b/Lang/Bruijn/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Palindrome-detection b/Lang/Bruijn/Palindrome-detection new file mode 120000 index 0000000000..928ca8c645 --- /dev/null +++ b/Lang/Bruijn/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Sorting-algorithms-Quicksort b/Lang/Bruijn/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..88bc24e9de --- /dev/null +++ b/Lang/Bruijn/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Sum-and-product-of-an-array b/Lang/Bruijn/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c56dea86f1 --- /dev/null +++ b/Lang/Bruijn/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Ternary-logic b/Lang/Bruijn/Ternary-logic new file mode 120000 index 0000000000..a4a336036c --- /dev/null +++ b/Lang/Bruijn/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Test-a-function b/Lang/Bruijn/Test-a-function new file mode 120000 index 0000000000..de62e05f97 --- /dev/null +++ b/Lang/Bruijn/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Bruijn \ No newline at end of file diff --git a/Lang/Bruijn/Y-combinator b/Lang/Bruijn/Y-combinator new file mode 120000 index 0000000000..3614ec75d6 --- /dev/null +++ b/Lang/Bruijn/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Bruijn \ No newline at end of file diff --git a/Lang/C-sharp/Aliquot-sequence-classifications b/Lang/C-sharp/Aliquot-sequence-classifications new file mode 120000 index 0000000000..2c0be649f4 --- /dev/null +++ b/Lang/C-sharp/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Arithmetic-numbers b/Lang/C-sharp/Arithmetic-numbers new file mode 120000 index 0000000000..7b33f4b583 --- /dev/null +++ b/Lang/C-sharp/Arithmetic-numbers @@ -0,0 +1 @@ +../../Task/Arithmetic-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/B-zier-curves-Intersections b/Lang/C-sharp/B-zier-curves-Intersections new file mode 120000 index 0000000000..9583a4224f --- /dev/null +++ b/Lang/C-sharp/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Bifid-cipher b/Lang/C-sharp/Bifid-cipher new file mode 120000 index 0000000000..53987e0c76 --- /dev/null +++ b/Lang/C-sharp/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Blum-integer b/Lang/C-sharp/Blum-integer new file mode 120000 index 0000000000..6e857dea48 --- /dev/null +++ b/Lang/C-sharp/Blum-integer @@ -0,0 +1 @@ +../../Task/Blum-integer/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Combinations-and-permutations b/Lang/C-sharp/Combinations-and-permutations new file mode 120000 index 0000000000..c322432e6c --- /dev/null +++ b/Lang/C-sharp/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Cut-a-rectangle b/Lang/C-sharp/Cut-a-rectangle new file mode 120000 index 0000000000..4cec3edeaa --- /dev/null +++ b/Lang/C-sharp/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Demings-funnel b/Lang/C-sharp/Demings-funnel new file mode 120000 index 0000000000..283a7555df --- /dev/null +++ b/Lang/C-sharp/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Determinant-and-permanent b/Lang/C-sharp/Determinant-and-permanent new file mode 120000 index 0000000000..fa8d657eeb --- /dev/null +++ b/Lang/C-sharp/Determinant-and-permanent @@ -0,0 +1 @@ +../../Task/Determinant-and-permanent/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Dice-game-probabilities b/Lang/C-sharp/Dice-game-probabilities new file mode 120000 index 0000000000..8f72eba47d --- /dev/null +++ b/Lang/C-sharp/Dice-game-probabilities @@ -0,0 +1 @@ +../../Task/Dice-game-probabilities/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Disarium-numbers b/Lang/C-sharp/Disarium-numbers new file mode 120000 index 0000000000..47381ac73c --- /dev/null +++ b/Lang/C-sharp/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Distribution-of-0-digits-in-factorial-series b/Lang/C-sharp/Distribution-of-0-digits-in-factorial-series new file mode 120000 index 0000000000..a7d175e94a --- /dev/null +++ b/Lang/C-sharp/Distribution-of-0-digits-in-factorial-series @@ -0,0 +1 @@ +../../Task/Distribution-of-0-digits-in-factorial-series/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Doomsday-rule b/Lang/C-sharp/Doomsday-rule new file mode 120000 index 0000000000..f572c2a651 --- /dev/null +++ b/Lang/C-sharp/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Erd-s-Nicolas-numbers b/Lang/C-sharp/Erd-s-Nicolas-numbers new file mode 120000 index 0000000000..2a21b589d2 --- /dev/null +++ b/Lang/C-sharp/Erd-s-Nicolas-numbers @@ -0,0 +1 @@ +../../Task/Erd-s-Nicolas-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Fairshare-between-two-and-more b/Lang/C-sharp/Fairshare-between-two-and-more new file mode 120000 index 0000000000..444efb1248 --- /dev/null +++ b/Lang/C-sharp/Fairshare-between-two-and-more @@ -0,0 +1 @@ +../../Task/Fairshare-between-two-and-more/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Fortunate-numbers b/Lang/C-sharp/Fortunate-numbers new file mode 120000 index 0000000000..5f6e57871d --- /dev/null +++ b/Lang/C-sharp/Fortunate-numbers @@ -0,0 +1 @@ +../../Task/Fortunate-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Fractran b/Lang/C-sharp/Fractran new file mode 120000 index 0000000000..e1ba558448 --- /dev/null +++ b/Lang/C-sharp/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Generate-Chess960-starting-position b/Lang/C-sharp/Generate-Chess960-starting-position new file mode 120000 index 0000000000..a44601322a --- /dev/null +++ b/Lang/C-sharp/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Golden-ratio-Convergence b/Lang/C-sharp/Golden-ratio-Convergence new file mode 120000 index 0000000000..ea91aeb897 --- /dev/null +++ b/Lang/C-sharp/Golden-ratio-Convergence @@ -0,0 +1 @@ +../../Task/Golden-ratio-Convergence/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Graph-colouring b/Lang/C-sharp/Graph-colouring new file mode 120000 index 0000000000..9124611f31 --- /dev/null +++ b/Lang/C-sharp/Graph-colouring @@ -0,0 +1 @@ +../../Task/Graph-colouring/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Harmonic-series b/Lang/C-sharp/Harmonic-series new file mode 120000 index 0000000000..621fdcd007 --- /dev/null +++ b/Lang/C-sharp/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Hickerson-series-of-almost-integers b/Lang/C-sharp/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..1409bf65fa --- /dev/null +++ b/Lang/C-sharp/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Jacobsthal-numbers b/Lang/C-sharp/Jacobsthal-numbers new file mode 120000 index 0000000000..8d875d3e3c --- /dev/null +++ b/Lang/C-sharp/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Jaro-similarity b/Lang/C-sharp/Jaro-similarity new file mode 120000 index 0000000000..76ee880028 --- /dev/null +++ b/Lang/C-sharp/Jaro-similarity @@ -0,0 +1 @@ +../../Task/Jaro-similarity/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Jordan-P-lya-numbers b/Lang/C-sharp/Jordan-P-lya-numbers new file mode 120000 index 0000000000..bdd5391b84 --- /dev/null +++ b/Lang/C-sharp/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Juggler-sequence b/Lang/C-sharp/Juggler-sequence new file mode 120000 index 0000000000..7c2e1e5df3 --- /dev/null +++ b/Lang/C-sharp/Juggler-sequence @@ -0,0 +1 @@ +../../Task/Juggler-sequence/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Levenshtein-distance-Alignment b/Lang/C-sharp/Levenshtein-distance-Alignment new file mode 120000 index 0000000000..4a86af53da --- /dev/null +++ b/Lang/C-sharp/Levenshtein-distance-Alignment @@ -0,0 +1 @@ +../../Task/Levenshtein-distance-Alignment/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Magic-constant b/Lang/C-sharp/Magic-constant new file mode 120000 index 0000000000..b74721e026 --- /dev/null +++ b/Lang/C-sharp/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Magic-squares-of-singly-even-order b/Lang/C-sharp/Magic-squares-of-singly-even-order new file mode 120000 index 0000000000..7c09d264d6 --- /dev/null +++ b/Lang/C-sharp/Magic-squares-of-singly-even-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-singly-even-order/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Main-step-of-GOST-28147-89 b/Lang/C-sharp/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..0d0396ff34 --- /dev/null +++ b/Lang/C-sharp/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Maze-solving b/Lang/C-sharp/Maze-solving new file mode 120000 index 0000000000..9a643105b4 --- /dev/null +++ b/Lang/C-sharp/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Metronome b/Lang/C-sharp/Metronome new file mode 120000 index 0000000000..d943840c54 --- /dev/null +++ b/Lang/C-sharp/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Mind-boggling-card-trick b/Lang/C-sharp/Mind-boggling-card-trick new file mode 120000 index 0000000000..65b695076e --- /dev/null +++ b/Lang/C-sharp/Mind-boggling-card-trick @@ -0,0 +1 @@ +../../Task/Mind-boggling-card-trick/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Minkowski-question-mark-function b/Lang/C-sharp/Minkowski-question-mark-function new file mode 120000 index 0000000000..b16d1e756c --- /dev/null +++ b/Lang/C-sharp/Minkowski-question-mark-function @@ -0,0 +1 @@ +../../Task/Minkowski-question-mark-function/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Next-highest-int-from-digits b/Lang/C-sharp/Next-highest-int-from-digits new file mode 120000 index 0000000000..2462971188 --- /dev/null +++ b/Lang/C-sharp/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Padovan-sequence b/Lang/C-sharp/Padovan-sequence new file mode 120000 index 0000000000..a90cb74ae7 --- /dev/null +++ b/Lang/C-sharp/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Pancake-numbers b/Lang/C-sharp/Pancake-numbers new file mode 120000 index 0000000000..5088584c71 --- /dev/null +++ b/Lang/C-sharp/Pancake-numbers @@ -0,0 +1 @@ +../../Task/Pancake-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Parse-an-IP-Address b/Lang/C-sharp/Parse-an-IP-Address new file mode 120000 index 0000000000..fe231a87e2 --- /dev/null +++ b/Lang/C-sharp/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Prime-numbers-whose-neighboring-pairs-are-tetraprimes b/Lang/C-sharp/Prime-numbers-whose-neighboring-pairs-are-tetraprimes new file mode 120000 index 0000000000..6222df483b --- /dev/null +++ b/Lang/C-sharp/Prime-numbers-whose-neighboring-pairs-are-tetraprimes @@ -0,0 +1 @@ +../../Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Pseudo-random-numbers-PCG32 b/Lang/C-sharp/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..c32a0bbbd9 --- /dev/null +++ b/Lang/C-sharp/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Ray-casting-algorithm b/Lang/C-sharp/Ray-casting-algorithm new file mode 120000 index 0000000000..67165907f8 --- /dev/null +++ b/Lang/C-sharp/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Rep-string b/Lang/C-sharp/Rep-string new file mode 120000 index 0000000000..0c89d0f939 --- /dev/null +++ b/Lang/C-sharp/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Solve-the-no-connection-puzzle b/Lang/C-sharp/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..f2a7bf3a0e --- /dev/null +++ b/Lang/C-sharp/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Spelling-of-ordinal-numbers b/Lang/C-sharp/Spelling-of-ordinal-numbers new file mode 120000 index 0000000000..f9129a4b80 --- /dev/null +++ b/Lang/C-sharp/Spelling-of-ordinal-numbers @@ -0,0 +1 @@ +../../Task/Spelling-of-ordinal-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Suffixation-of-decimal-numbers b/Lang/C-sharp/Suffixation-of-decimal-numbers new file mode 120000 index 0000000000..2db739988c --- /dev/null +++ b/Lang/C-sharp/Suffixation-of-decimal-numbers @@ -0,0 +1 @@ +../../Task/Suffixation-of-decimal-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Sylvesters-sequence b/Lang/C-sharp/Sylvesters-sequence new file mode 120000 index 0000000000..3899fa057e --- /dev/null +++ b/Lang/C-sharp/Sylvesters-sequence @@ -0,0 +1 @@ +../../Task/Sylvesters-sequence/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Topswops b/Lang/C-sharp/Topswops new file mode 120000 index 0000000000..3f10a6cb93 --- /dev/null +++ b/Lang/C-sharp/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Total-circles-area b/Lang/C-sharp/Total-circles-area new file mode 120000 index 0000000000..d1b9a6ffb2 --- /dev/null +++ b/Lang/C-sharp/Total-circles-area @@ -0,0 +1 @@ +../../Task/Total-circles-area/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Tropical-algebra-overloading b/Lang/C-sharp/Tropical-algebra-overloading new file mode 120000 index 0000000000..1b61aaaf8d --- /dev/null +++ b/Lang/C-sharp/Tropical-algebra-overloading @@ -0,0 +1 @@ +../../Task/Tropical-algebra-overloading/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Verify-distribution-uniformity-Chi-squared-test b/Lang/C-sharp/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..5101b70787 --- /dev/null +++ b/Lang/C-sharp/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Verify-distribution-uniformity-Naive b/Lang/C-sharp/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..c41f1e05f6 --- /dev/null +++ b/Lang/C-sharp/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/C-sharp \ No newline at end of file diff --git a/Lang/COBOL/Priority-queue b/Lang/COBOL/Priority-queue new file mode 120000 index 0000000000..23c7bff2c3 --- /dev/null +++ b/Lang/COBOL/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/COBOL \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Forest-fire b/Lang/Commodore-BASIC/Forest-fire new file mode 120000 index 0000000000..c384f7d98f --- /dev/null +++ b/Lang/Commodore-BASIC/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Reverse-a-string b/Lang/Commodore-BASIC/Reverse-a-string new file mode 120000 index 0000000000..db83958808 --- /dev/null +++ b/Lang/Commodore-BASIC/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Commodore-BASIC/The-Twelve-Days-of-Christmas b/Lang/Commodore-BASIC/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..cd67a05c16 --- /dev/null +++ b/Lang/Commodore-BASIC/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Cowgol/Narcissistic-decimal-number b/Lang/Cowgol/Narcissistic-decimal-number new file mode 120000 index 0000000000..3ff09189b6 --- /dev/null +++ b/Lang/Cowgol/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Cowgol \ No newline at end of file diff --git a/Lang/Crystal/Hello-world-Graphical b/Lang/Crystal/Hello-world-Graphical new file mode 120000 index 0000000000..aa3ccec00c --- /dev/null +++ b/Lang/Crystal/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Crystal \ No newline at end of file diff --git a/Lang/Dart/Burrows-Wheeler-transform b/Lang/Dart/Burrows-Wheeler-transform new file mode 120000 index 0000000000..d3c9f31111 --- /dev/null +++ b/Lang/Dart/Burrows-Wheeler-transform @@ -0,0 +1 @@ +../../Task/Burrows-Wheeler-transform/Dart \ No newline at end of file diff --git a/Lang/Dart/Euler-method b/Lang/Dart/Euler-method new file mode 120000 index 0000000000..6501c260ce --- /dev/null +++ b/Lang/Dart/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/Dart \ No newline at end of file diff --git a/Lang/Dart/Evolutionary-algorithm b/Lang/Dart/Evolutionary-algorithm new file mode 120000 index 0000000000..37e72623f8 --- /dev/null +++ b/Lang/Dart/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Dart \ No newline at end of file diff --git a/Lang/Dart/Fibonacci-word b/Lang/Dart/Fibonacci-word new file mode 120000 index 0000000000..5feb3092ca --- /dev/null +++ b/Lang/Dart/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Dart \ No newline at end of file diff --git a/Lang/Dart/Jordan-P-lya-numbers b/Lang/Dart/Jordan-P-lya-numbers new file mode 120000 index 0000000000..84c71f877c --- /dev/null +++ b/Lang/Dart/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Dart \ No newline at end of file diff --git a/Lang/Dart/Permutations-by-swapping b/Lang/Dart/Permutations-by-swapping new file mode 120000 index 0000000000..9009ddfa84 --- /dev/null +++ b/Lang/Dart/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Dart \ No newline at end of file diff --git a/Lang/Dart/Price-fraction b/Lang/Dart/Price-fraction new file mode 120000 index 0000000000..b65d52f099 --- /dev/null +++ b/Lang/Dart/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Dart \ No newline at end of file diff --git a/Lang/Dart/Primality-by-Wilsons-theorem b/Lang/Dart/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..6834b7d634 --- /dev/null +++ b/Lang/Dart/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/Dart \ No newline at end of file diff --git a/Lang/Dart/Pseudo-random-numbers-PCG32 b/Lang/Dart/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..40ec498984 --- /dev/null +++ b/Lang/Dart/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/Dart \ No newline at end of file diff --git a/Lang/Dart/Quaternion-type b/Lang/Dart/Quaternion-type new file mode 120000 index 0000000000..fb391b98d0 --- /dev/null +++ b/Lang/Dart/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Dart \ No newline at end of file diff --git a/Lang/Dart/Rot-13 b/Lang/Dart/Rot-13 new file mode 120000 index 0000000000..6136f05da5 --- /dev/null +++ b/Lang/Dart/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Dart \ No newline at end of file diff --git a/Lang/Dart/Validate-International-Securities-Identification-Number b/Lang/Dart/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..72bbf1cc0f --- /dev/null +++ b/Lang/Dart/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/Dart \ No newline at end of file diff --git a/Lang/Dart/Zeckendorf-arithmetic b/Lang/Dart/Zeckendorf-arithmetic new file mode 120000 index 0000000000..bfaf3b6837 --- /dev/null +++ b/Lang/Dart/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/Dart \ No newline at end of file diff --git a/Lang/Dart/Zeckendorf-number-representation b/Lang/Dart/Zeckendorf-number-representation new file mode 120000 index 0000000000..eb4adc0005 --- /dev/null +++ b/Lang/Dart/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Dart \ No newline at end of file diff --git a/Lang/Draco/Narcissistic-decimal-number b/Lang/Draco/Narcissistic-decimal-number new file mode 120000 index 0000000000..e893d928d6 --- /dev/null +++ b/Lang/Draco/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Draco \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Pythagorean-quadruples b/Lang/EDSAC-order-code/Pythagorean-quadruples new file mode 120000 index 0000000000..43dfaa296f --- /dev/null +++ b/Lang/EDSAC-order-code/Pythagorean-quadruples @@ -0,0 +1 @@ +../../Task/Pythagorean-quadruples/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EasyLang/Achilles-numbers b/Lang/EasyLang/Achilles-numbers new file mode 120000 index 0000000000..90c0643d0e --- /dev/null +++ b/Lang/EasyLang/Achilles-numbers @@ -0,0 +1 @@ +../../Task/Achilles-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Arithmetic-derivative b/Lang/EasyLang/Arithmetic-derivative new file mode 120000 index 0000000000..13a223ff6a --- /dev/null +++ b/Lang/EasyLang/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Box-the-compass b/Lang/EasyLang/Box-the-compass new file mode 120000 index 0000000000..4fd6c85d9d --- /dev/null +++ b/Lang/EasyLang/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Canonicalize-CIDR b/Lang/EasyLang/Canonicalize-CIDR new file mode 120000 index 0000000000..ef98b51c97 --- /dev/null +++ b/Lang/EasyLang/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Cartesian-product-of-two-or-more-lists b/Lang/EasyLang/Cartesian-product-of-two-or-more-lists new file mode 120000 index 0000000000..012d512db6 --- /dev/null +++ b/Lang/EasyLang/Cartesian-product-of-two-or-more-lists @@ -0,0 +1 @@ +../../Task/Cartesian-product-of-two-or-more-lists/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Create-a-two-dimensional-array-at-runtime b/Lang/EasyLang/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..9ab5d02120 --- /dev/null +++ b/Lang/EasyLang/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Cuban-primes b/Lang/EasyLang/Cuban-primes new file mode 120000 index 0000000000..602fb8a030 --- /dev/null +++ b/Lang/EasyLang/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Damm-algorithm b/Lang/EasyLang/Damm-algorithm new file mode 120000 index 0000000000..d7f6db29b1 --- /dev/null +++ b/Lang/EasyLang/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/De-Bruijn-sequences b/Lang/EasyLang/De-Bruijn-sequences new file mode 120000 index 0000000000..faba25f06a --- /dev/null +++ b/Lang/EasyLang/De-Bruijn-sequences @@ -0,0 +1 @@ +../../Task/De-Bruijn-sequences/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Deceptive-numbers b/Lang/EasyLang/Deceptive-numbers new file mode 120000 index 0000000000..eae8f8459d --- /dev/null +++ b/Lang/EasyLang/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Demings-funnel b/Lang/EasyLang/Demings-funnel new file mode 120000 index 0000000000..d19d38286f --- /dev/null +++ b/Lang/EasyLang/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Dijkstras-algorithm b/Lang/EasyLang/Dijkstras-algorithm new file mode 120000 index 0000000000..de47a7cc8f --- /dev/null +++ b/Lang/EasyLang/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Dinesmans-multiple-dwelling-problem b/Lang/EasyLang/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..09fc1d4edc --- /dev/null +++ b/Lang/EasyLang/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Diversity-prediction-theorem b/Lang/EasyLang/Diversity-prediction-theorem new file mode 120000 index 0000000000..794b1e0805 --- /dev/null +++ b/Lang/EasyLang/Diversity-prediction-theorem @@ -0,0 +1 @@ +../../Task/Diversity-prediction-theorem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Duffinian-numbers b/Lang/EasyLang/Duffinian-numbers new file mode 120000 index 0000000000..75befe0bb1 --- /dev/null +++ b/Lang/EasyLang/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Equal-prime-and-composite-sums b/Lang/EasyLang/Equal-prime-and-composite-sums new file mode 120000 index 0000000000..d416ab6d61 --- /dev/null +++ b/Lang/EasyLang/Equal-prime-and-composite-sums @@ -0,0 +1 @@ +../../Task/Equal-prime-and-composite-sums/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Equilibrium-index b/Lang/EasyLang/Equilibrium-index new file mode 120000 index 0000000000..165c2ae56a --- /dev/null +++ b/Lang/EasyLang/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Eulers-constant-0.5772... b/Lang/EasyLang/Eulers-constant-0.5772... new file mode 120000 index 0000000000..481b218714 --- /dev/null +++ b/Lang/EasyLang/Eulers-constant-0.5772... @@ -0,0 +1 @@ +../../Task/Eulers-constant-0.5772.../EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/FASTA-format b/Lang/EasyLang/FASTA-format new file mode 120000 index 0000000000..ca29d4ff3f --- /dev/null +++ b/Lang/EasyLang/FASTA-format @@ -0,0 +1 @@ +../../Task/FASTA-format/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Find-the-intersection-of-two-lines b/Lang/EasyLang/Find-the-intersection-of-two-lines new file mode 120000 index 0000000000..cffadf31bc --- /dev/null +++ b/Lang/EasyLang/Find-the-intersection-of-two-lines @@ -0,0 +1 @@ +../../Task/Find-the-intersection-of-two-lines/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Find-the-missing-permutation b/Lang/EasyLang/Find-the-missing-permutation new file mode 120000 index 0000000000..062fcb8e1c --- /dev/null +++ b/Lang/EasyLang/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Gauss-Jordan-matrix-inversion b/Lang/EasyLang/Gauss-Jordan-matrix-inversion new file mode 120000 index 0000000000..4edf8b08eb --- /dev/null +++ b/Lang/EasyLang/Gauss-Jordan-matrix-inversion @@ -0,0 +1 @@ +../../Task/Gauss-Jordan-matrix-inversion/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Gaussian-elimination b/Lang/EasyLang/Gaussian-elimination new file mode 120000 index 0000000000..3600b047b6 --- /dev/null +++ b/Lang/EasyLang/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Happy-numbers b/Lang/EasyLang/Happy-numbers new file mode 120000 index 0000000000..c4ab4d4ef3 --- /dev/null +++ b/Lang/EasyLang/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Hofstadter-Conway-$10-000-sequence b/Lang/EasyLang/Hofstadter-Conway-$10-000-sequence new file mode 120000 index 0000000000..13e3a43372 --- /dev/null +++ b/Lang/EasyLang/Hofstadter-Conway-$10-000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10-000-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Kaprekar-numbers b/Lang/EasyLang/Kaprekar-numbers new file mode 120000 index 0000000000..8b04bae44a --- /dev/null +++ b/Lang/EasyLang/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Least-common-multiple b/Lang/EasyLang/Least-common-multiple new file mode 120000 index 0000000000..4e6553c21f --- /dev/null +++ b/Lang/EasyLang/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Linear-congruential-generator b/Lang/EasyLang/Linear-congruential-generator new file mode 120000 index 0000000000..08ba24e5b7 --- /dev/null +++ b/Lang/EasyLang/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Long-primes b/Lang/EasyLang/Long-primes new file mode 120000 index 0000000000..7bcfe1337a --- /dev/null +++ b/Lang/EasyLang/Long-primes @@ -0,0 +1 @@ +../../Task/Long-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Long-year b/Lang/EasyLang/Long-year new file mode 120000 index 0000000000..c98469be44 --- /dev/null +++ b/Lang/EasyLang/Long-year @@ -0,0 +1 @@ +../../Task/Long-year/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Longest-common-subsequence b/Lang/EasyLang/Longest-common-subsequence new file mode 120000 index 0000000000..6cc703826c --- /dev/null +++ b/Lang/EasyLang/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Lucas-Lehmer-test b/Lang/EasyLang/Lucas-Lehmer-test new file mode 120000 index 0000000000..37ce43bc05 --- /dev/null +++ b/Lang/EasyLang/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Luhn-test-of-credit-card-numbers b/Lang/EasyLang/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..6cdbead8c8 --- /dev/null +++ b/Lang/EasyLang/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/MD5 b/Lang/EasyLang/MD5 new file mode 120000 index 0000000000..1974a8639d --- /dev/null +++ b/Lang/EasyLang/MD5 @@ -0,0 +1 @@ +../../Task/MD5/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Magic-8-ball b/Lang/EasyLang/Magic-8-ball new file mode 120000 index 0000000000..27f204a23e --- /dev/null +++ b/Lang/EasyLang/Magic-8-ball @@ -0,0 +1 @@ +../../Task/Magic-8-ball/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Magic-constant b/Lang/EasyLang/Magic-constant new file mode 120000 index 0000000000..e7bddcf034 --- /dev/null +++ b/Lang/EasyLang/Magic-constant @@ -0,0 +1 @@ +../../Task/Magic-constant/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Magic-squares-of-odd-order b/Lang/EasyLang/Magic-squares-of-odd-order new file mode 120000 index 0000000000..c1250ae803 --- /dev/null +++ b/Lang/EasyLang/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Matrix-multiplication b/Lang/EasyLang/Matrix-multiplication new file mode 120000 index 0000000000..210bca9988 --- /dev/null +++ b/Lang/EasyLang/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Meissel-Mertens-constant b/Lang/EasyLang/Meissel-Mertens-constant new file mode 120000 index 0000000000..2673a3a653 --- /dev/null +++ b/Lang/EasyLang/Meissel-Mertens-constant @@ -0,0 +1 @@ +../../Task/Meissel-Mertens-constant/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Mertens-function b/Lang/EasyLang/Mertens-function new file mode 120000 index 0000000000..9535db88d7 --- /dev/null +++ b/Lang/EasyLang/Mertens-function @@ -0,0 +1 @@ +../../Task/Mertens-function/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Munchausen-numbers b/Lang/EasyLang/Munchausen-numbers new file mode 120000 index 0000000000..82315ebcc3 --- /dev/null +++ b/Lang/EasyLang/Munchausen-numbers @@ -0,0 +1 @@ +../../Task/Munchausen-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Mutual-recursion b/Lang/EasyLang/Mutual-recursion new file mode 120000 index 0000000000..9dbd653e23 --- /dev/null +++ b/Lang/EasyLang/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Next-highest-int-from-digits b/Lang/EasyLang/Next-highest-int-from-digits new file mode 120000 index 0000000000..b3f44119a8 --- /dev/null +++ b/Lang/EasyLang/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Non-decimal-radices-Convert b/Lang/EasyLang/Non-decimal-radices-Convert new file mode 120000 index 0000000000..e286a4396d --- /dev/null +++ b/Lang/EasyLang/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Odd-word-problem b/Lang/EasyLang/Odd-word-problem new file mode 120000 index 0000000000..0886623884 --- /dev/null +++ b/Lang/EasyLang/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Old-Russian-measure-of-length b/Lang/EasyLang/Old-Russian-measure-of-length new file mode 120000 index 0000000000..f293c18a0a --- /dev/null +++ b/Lang/EasyLang/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Old-lady-swallowed-a-fly b/Lang/EasyLang/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..f3a3472099 --- /dev/null +++ b/Lang/EasyLang/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/One-of-n-lines-in-a-file b/Lang/EasyLang/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..683c0899da --- /dev/null +++ b/Lang/EasyLang/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/OpenWebNet-password b/Lang/EasyLang/OpenWebNet-password new file mode 120000 index 0000000000..1cfc17e776 --- /dev/null +++ b/Lang/EasyLang/OpenWebNet-password @@ -0,0 +1 @@ +../../Task/OpenWebNet-password/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Order-two-numerical-lists b/Lang/EasyLang/Order-two-numerical-lists new file mode 120000 index 0000000000..0574c3c6db --- /dev/null +++ b/Lang/EasyLang/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ormiston-triples b/Lang/EasyLang/Ormiston-triples new file mode 120000 index 0000000000..de3ff3dcf1 --- /dev/null +++ b/Lang/EasyLang/Ormiston-triples @@ -0,0 +1 @@ +../../Task/Ormiston-triples/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Padovan-sequence b/Lang/EasyLang/Padovan-sequence new file mode 120000 index 0000000000..d568888890 --- /dev/null +++ b/Lang/EasyLang/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Palindrome-dates b/Lang/EasyLang/Palindrome-dates new file mode 120000 index 0000000000..a27c75b0d5 --- /dev/null +++ b/Lang/EasyLang/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pascals-triangle b/Lang/EasyLang/Pascals-triangle new file mode 120000 index 0000000000..1c14b19dad --- /dev/null +++ b/Lang/EasyLang/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Perfect-totient-numbers b/Lang/EasyLang/Perfect-totient-numbers new file mode 120000 index 0000000000..73baaf8d08 --- /dev/null +++ b/Lang/EasyLang/Perfect-totient-numbers @@ -0,0 +1 @@ +../../Task/Perfect-totient-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Permutations-by-swapping b/Lang/EasyLang/Permutations-by-swapping new file mode 120000 index 0000000000..6fca752258 --- /dev/null +++ b/Lang/EasyLang/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pernicious-numbers b/Lang/EasyLang/Pernicious-numbers new file mode 120000 index 0000000000..2adf8c61c2 --- /dev/null +++ b/Lang/EasyLang/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pisano-period b/Lang/EasyLang/Pisano-period new file mode 120000 index 0000000000..03e71e0e0c --- /dev/null +++ b/Lang/EasyLang/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Playing-cards b/Lang/EasyLang/Playing-cards new file mode 120000 index 0000000000..65c563fef4 --- /dev/null +++ b/Lang/EasyLang/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Primality-by-Wilsons-theorem b/Lang/EasyLang/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..f47bc08707 --- /dev/null +++ b/Lang/EasyLang/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Prime-conspiracy b/Lang/EasyLang/Prime-conspiracy new file mode 120000 index 0000000000..5276eb838d --- /dev/null +++ b/Lang/EasyLang/Prime-conspiracy @@ -0,0 +1 @@ +../../Task/Prime-conspiracy/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Probabilistic-choice b/Lang/EasyLang/Probabilistic-choice new file mode 120000 index 0000000000..f4c8e2ec2b --- /dev/null +++ b/Lang/EasyLang/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Problem-of-Apollonius b/Lang/EasyLang/Problem-of-Apollonius new file mode 120000 index 0000000000..34ccacd36b --- /dev/null +++ b/Lang/EasyLang/Problem-of-Apollonius @@ -0,0 +1 @@ +../../Task/Problem-of-Apollonius/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Proper-divisors b/Lang/EasyLang/Proper-divisors new file mode 120000 index 0000000000..a6f15193a6 --- /dev/null +++ b/Lang/EasyLang/Proper-divisors @@ -0,0 +1 @@ +../../Task/Proper-divisors/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Pythagorean-triples b/Lang/EasyLang/Pythagorean-triples new file mode 120000 index 0000000000..ae5979164c --- /dev/null +++ b/Lang/EasyLang/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Quaternion-type b/Lang/EasyLang/Quaternion-type new file mode 120000 index 0000000000..fd590dabb6 --- /dev/null +++ b/Lang/EasyLang/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Queue-Definition b/Lang/EasyLang/Queue-Definition new file mode 120000 index 0000000000..60d84f451e --- /dev/null +++ b/Lang/EasyLang/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Queue-Usage b/Lang/EasyLang/Queue-Usage new file mode 120000 index 0000000000..0a07f759a8 --- /dev/null +++ b/Lang/EasyLang/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/RPG-attributes-generator b/Lang/EasyLang/RPG-attributes-generator new file mode 120000 index 0000000000..1bb6325d13 --- /dev/null +++ b/Lang/EasyLang/RPG-attributes-generator @@ -0,0 +1 @@ +../../Task/RPG-attributes-generator/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ramanujan-primes-twins b/Lang/EasyLang/Ramanujan-primes-twins new file mode 120000 index 0000000000..5e0a528dbb --- /dev/null +++ b/Lang/EasyLang/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Range-extraction b/Lang/EasyLang/Range-extraction new file mode 120000 index 0000000000..b10a21cd95 --- /dev/null +++ b/Lang/EasyLang/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Rate-counter b/Lang/EasyLang/Rate-counter new file mode 120000 index 0000000000..d4dfd5cedd --- /dev/null +++ b/Lang/EasyLang/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Reduced-row-echelon-form b/Lang/EasyLang/Reduced-row-echelon-form new file mode 120000 index 0000000000..7ab5f9f24b --- /dev/null +++ b/Lang/EasyLang/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Rep-string b/Lang/EasyLang/Rep-string new file mode 120000 index 0000000000..c011f2f49a --- /dev/null +++ b/Lang/EasyLang/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Reverse-words-in-a-string b/Lang/EasyLang/Reverse-words-in-a-string new file mode 120000 index 0000000000..ab8b42f790 --- /dev/null +++ b/Lang/EasyLang/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Roots-of-a-function b/Lang/EasyLang/Roots-of-a-function new file mode 120000 index 0000000000..184fd0b60d --- /dev/null +++ b/Lang/EasyLang/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Roots-of-unity b/Lang/EasyLang/Roots-of-unity new file mode 120000 index 0000000000..828ac953fa --- /dev/null +++ b/Lang/EasyLang/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Runge-Kutta-method b/Lang/EasyLang/Runge-Kutta-method new file mode 120000 index 0000000000..404f8f7a22 --- /dev/null +++ b/Lang/EasyLang/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Safe-primes-and-unsafe-primes b/Lang/EasyLang/Safe-primes-and-unsafe-primes new file mode 120000 index 0000000000..1a2584a87e --- /dev/null +++ b/Lang/EasyLang/Safe-primes-and-unsafe-primes @@ -0,0 +1 @@ +../../Task/Safe-primes-and-unsafe-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Set-right-adjacent-bits b/Lang/EasyLang/Set-right-adjacent-bits new file mode 120000 index 0000000000..ec9bf3c5a8 --- /dev/null +++ b/Lang/EasyLang/Set-right-adjacent-bits @@ -0,0 +1 @@ +../../Task/Set-right-adjacent-bits/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sexy-primes b/Lang/EasyLang/Sexy-primes new file mode 120000 index 0000000000..5323f1eac1 --- /dev/null +++ b/Lang/EasyLang/Sexy-primes @@ -0,0 +1 @@ +../../Task/Sexy-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Shortest-common-supersequence b/Lang/EasyLang/Shortest-common-supersequence new file mode 120000 index 0000000000..607dae8dd4 --- /dev/null +++ b/Lang/EasyLang/Shortest-common-supersequence @@ -0,0 +1 @@ +../../Task/Shortest-common-supersequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sieve-of-Pritchard b/Lang/EasyLang/Sieve-of-Pritchard new file mode 120000 index 0000000000..26c5587430 --- /dev/null +++ b/Lang/EasyLang/Sieve-of-Pritchard @@ -0,0 +1 @@ +../../Task/Sieve-of-Pritchard/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sleeping-Beauty-problem b/Lang/EasyLang/Sleeping-Beauty-problem new file mode 120000 index 0000000000..3221388f3b --- /dev/null +++ b/Lang/EasyLang/Sleeping-Beauty-problem @@ -0,0 +1 @@ +../../Task/Sleeping-Beauty-problem/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Smarandache-prime-digital-sequence b/Lang/EasyLang/Smarandache-prime-digital-sequence new file mode 120000 index 0000000000..5a92cc0ae9 --- /dev/null +++ b/Lang/EasyLang/Smarandache-prime-digital-sequence @@ -0,0 +1 @@ +../../Task/Smarandache-prime-digital-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Soloways-recurring-rainfall b/Lang/EasyLang/Soloways-recurring-rainfall new file mode 120000 index 0000000000..9662259f25 --- /dev/null +++ b/Lang/EasyLang/Soloways-recurring-rainfall @@ -0,0 +1 @@ +../../Task/Soloways-recurring-rainfall/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sorting-algorithms-Bogosort b/Lang/EasyLang/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..b0d8dd10f8 --- /dev/null +++ b/Lang/EasyLang/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Spinning-rod-animation-Text b/Lang/EasyLang/Spinning-rod-animation-Text new file mode 120000 index 0000000000..8d7a484a76 --- /dev/null +++ b/Lang/EasyLang/Spinning-rod-animation-Text @@ -0,0 +1 @@ +../../Task/Spinning-rod-animation-Text/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Spiral-matrix b/Lang/EasyLang/Spiral-matrix new file mode 120000 index 0000000000..6a306658a2 --- /dev/null +++ b/Lang/EasyLang/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Square-but-not-cube b/Lang/EasyLang/Square-but-not-cube new file mode 120000 index 0000000000..573451d99d --- /dev/null +++ b/Lang/EasyLang/Square-but-not-cube @@ -0,0 +1 @@ +../../Task/Square-but-not-cube/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Stack b/Lang/EasyLang/Stack new file mode 120000 index 0000000000..0038ea59db --- /dev/null +++ b/Lang/EasyLang/Stack @@ -0,0 +1 @@ +../../Task/Stack/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Start-from-a-main-routine b/Lang/EasyLang/Start-from-a-main-routine new file mode 120000 index 0000000000..6b5dd8c795 --- /dev/null +++ b/Lang/EasyLang/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Stern-Brocot-sequence b/Lang/EasyLang/Stern-Brocot-sequence new file mode 120000 index 0000000000..0fd407fbf1 --- /dev/null +++ b/Lang/EasyLang/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Strong-and-weak-primes b/Lang/EasyLang/Strong-and-weak-primes new file mode 120000 index 0000000000..7a0f4adcd7 --- /dev/null +++ b/Lang/EasyLang/Strong-and-weak-primes @@ -0,0 +1 @@ +../../Task/Strong-and-weak-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Substitution-cipher b/Lang/EasyLang/Substitution-cipher new file mode 120000 index 0000000000..08b863c199 --- /dev/null +++ b/Lang/EasyLang/Substitution-cipher @@ -0,0 +1 @@ +../../Task/Substitution-cipher/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sudan-function b/Lang/EasyLang/Sudan-function new file mode 120000 index 0000000000..00925b61cc --- /dev/null +++ b/Lang/EasyLang/Sudan-function @@ -0,0 +1 @@ +../../Task/Sudan-function/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/EasyLang/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..9d1f3d5072 --- /dev/null +++ b/Lang/EasyLang/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Superellipse b/Lang/EasyLang/Superellipse new file mode 120000 index 0000000000..cf8cdb08f6 --- /dev/null +++ b/Lang/EasyLang/Superellipse @@ -0,0 +1 @@ +../../Task/Superellipse/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Ternary-logic b/Lang/EasyLang/Ternary-logic new file mode 120000 index 0000000000..fbbe98ec9f --- /dev/null +++ b/Lang/EasyLang/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Test-integerness b/Lang/EasyLang/Test-integerness new file mode 120000 index 0000000000..e308fb8af8 --- /dev/null +++ b/Lang/EasyLang/Test-integerness @@ -0,0 +1 @@ +../../Task/Test-integerness/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/The-sieve-of-Sundaram b/Lang/EasyLang/The-sieve-of-Sundaram new file mode 120000 index 0000000000..873d444bf6 --- /dev/null +++ b/Lang/EasyLang/The-sieve-of-Sundaram @@ -0,0 +1 @@ +../../Task/The-sieve-of-Sundaram/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Thue-Morse b/Lang/EasyLang/Thue-Morse new file mode 120000 index 0000000000..9e3ae46e6c --- /dev/null +++ b/Lang/EasyLang/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Trabb-Pardo-Knuth-algorithm b/Lang/EasyLang/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..ca1b958ae3 --- /dev/null +++ b/Lang/EasyLang/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Trigonometric-functions b/Lang/EasyLang/Trigonometric-functions new file mode 120000 index 0000000000..387caf6602 --- /dev/null +++ b/Lang/EasyLang/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Truncatable-primes b/Lang/EasyLang/Truncatable-primes new file mode 120000 index 0000000000..4dcfac21ce --- /dev/null +++ b/Lang/EasyLang/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Unbias-a-random-generator b/Lang/EasyLang/Unbias-a-random-generator new file mode 120000 index 0000000000..964b26809c --- /dev/null +++ b/Lang/EasyLang/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Validate-International-Securities-Identification-Number b/Lang/EasyLang/Validate-International-Securities-Identification-Number new file mode 120000 index 0000000000..125038f3d2 --- /dev/null +++ b/Lang/EasyLang/Validate-International-Securities-Identification-Number @@ -0,0 +1 @@ +../../Task/Validate-International-Securities-Identification-Number/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Vector b/Lang/EasyLang/Vector new file mode 120000 index 0000000000..3185c7d539 --- /dev/null +++ b/Lang/EasyLang/Vector @@ -0,0 +1 @@ +../../Task/Vector/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Vector-products b/Lang/EasyLang/Vector-products new file mode 120000 index 0000000000..dd2b30f534 --- /dev/null +++ b/Lang/EasyLang/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Voronoi-diagram b/Lang/EasyLang/Voronoi-diagram new file mode 120000 index 0000000000..d875657141 --- /dev/null +++ b/Lang/EasyLang/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Wieferich-primes b/Lang/EasyLang/Wieferich-primes new file mode 120000 index 0000000000..51f8158742 --- /dev/null +++ b/Lang/EasyLang/Wieferich-primes @@ -0,0 +1 @@ +../../Task/Wieferich-primes/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Wireworld b/Lang/EasyLang/Wireworld new file mode 120000 index 0000000000..873d48f6a7 --- /dev/null +++ b/Lang/EasyLang/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Yellowstone-sequence b/Lang/EasyLang/Yellowstone-sequence new file mode 120000 index 0000000000..76abf29ac7 --- /dev/null +++ b/Lang/EasyLang/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Yin-and-yang b/Lang/EasyLang/Yin-and-yang new file mode 120000 index 0000000000..5eb9553382 --- /dev/null +++ b/Lang/EasyLang/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/EasyLang \ No newline at end of file diff --git a/Lang/EasyLang/Zumkeller-numbers b/Lang/EasyLang/Zumkeller-numbers new file mode 120000 index 0000000000..194eacc320 --- /dev/null +++ b/Lang/EasyLang/Zumkeller-numbers @@ -0,0 +1 @@ +../../Task/Zumkeller-numbers/EasyLang \ No newline at end of file diff --git a/Lang/Ecstasy/N-queens-problem b/Lang/Ecstasy/N-queens-problem new file mode 120000 index 0000000000..695c0416ee --- /dev/null +++ b/Lang/Ecstasy/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Ecstasy \ No newline at end of file diff --git a/Lang/Elixir/Padovan-sequence b/Lang/Elixir/Padovan-sequence new file mode 120000 index 0000000000..1b11fdfcb3 --- /dev/null +++ b/Lang/Elixir/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Shoelace-formula-for-polygonal-area b/Lang/Elixir/Shoelace-formula-for-polygonal-area new file mode 120000 index 0000000000..f28f8d7f49 --- /dev/null +++ b/Lang/Elixir/Shoelace-formula-for-polygonal-area @@ -0,0 +1 @@ +../../Task/Shoelace-formula-for-polygonal-area/Elixir \ No newline at end of file diff --git a/Lang/Elm/Greatest-common-divisor b/Lang/Elm/Greatest-common-divisor new file mode 120000 index 0000000000..b61057b86e --- /dev/null +++ b/Lang/Elm/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Elm \ No newline at end of file diff --git a/Lang/Elm/Prime-decomposition b/Lang/Elm/Prime-decomposition new file mode 120000 index 0000000000..a3a9b92e08 --- /dev/null +++ b/Lang/Elm/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Elm \ No newline at end of file diff --git a/Lang/Elm/Sum-of-a-series b/Lang/Elm/Sum-of-a-series new file mode 120000 index 0000000000..b1ba524bb3 --- /dev/null +++ b/Lang/Elm/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Elm \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Strip-a-set-of-characters-from-a-string b/Lang/Emacs-Lisp/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..901b18a4e0 --- /dev/null +++ b/Lang/Emacs-Lisp/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Zeckendorf-number-representation b/Lang/Erlang/Zeckendorf-number-representation new file mode 120000 index 0000000000..6a77e53f6b --- /dev/null +++ b/Lang/Erlang/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Erlang \ No newline at end of file diff --git a/Lang/Excel/Entropy b/Lang/Excel/Entropy new file mode 120000 index 0000000000..8d4e6441d6 --- /dev/null +++ b/Lang/Excel/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Excel \ No newline at end of file diff --git a/Lang/F-Sharp/Variadic-function b/Lang/F-Sharp/Variadic-function new file mode 120000 index 0000000000..d32ee2a40f --- /dev/null +++ b/Lang/F-Sharp/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Wireworld b/Lang/F-Sharp/Wireworld new file mode 120000 index 0000000000..32d571d649 --- /dev/null +++ b/Lang/F-Sharp/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/F-Sharp \ No newline at end of file diff --git a/Lang/Fish/The-Twelve-Days-of-Christmas b/Lang/Fish/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..b2ce6d5872 --- /dev/null +++ b/Lang/Fish/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Fish \ No newline at end of file diff --git a/Lang/Forth/21-game b/Lang/Forth/21-game new file mode 120000 index 0000000000..1f62421370 --- /dev/null +++ b/Lang/Forth/21-game @@ -0,0 +1 @@ +../../Task/21-game/Forth \ No newline at end of file diff --git a/Lang/Forth/Calendar b/Lang/Forth/Calendar new file mode 120000 index 0000000000..1dc0827699 --- /dev/null +++ b/Lang/Forth/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Forth \ No newline at end of file diff --git a/Lang/Forth/Calendar---for-REAL-programmers b/Lang/Forth/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..499105cf3a --- /dev/null +++ b/Lang/Forth/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/Forth \ No newline at end of file diff --git a/Lang/Forth/Determine-if-a-string-has-all-the-same-characters b/Lang/Forth/Determine-if-a-string-has-all-the-same-characters new file mode 120000 index 0000000000..79fb92f191 --- /dev/null +++ b/Lang/Forth/Determine-if-a-string-has-all-the-same-characters @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-has-all-the-same-characters/Forth \ No newline at end of file diff --git a/Lang/Forth/Dijkstras-algorithm b/Lang/Forth/Dijkstras-algorithm new file mode 120000 index 0000000000..a69ebc3263 --- /dev/null +++ b/Lang/Forth/Dijkstras-algorithm @@ -0,0 +1 @@ +../../Task/Dijkstras-algorithm/Forth \ No newline at end of file diff --git a/Lang/Forth/Flipping-bits-game b/Lang/Forth/Flipping-bits-game new file mode 120000 index 0000000000..2a3f084d3e --- /dev/null +++ b/Lang/Forth/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Forth \ No newline at end of file diff --git a/Lang/Forth/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Forth/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..d41fcd8680 --- /dev/null +++ b/Lang/Forth/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Forth \ No newline at end of file diff --git a/Lang/Forth/Undefined-values b/Lang/Forth/Undefined-values new file mode 120000 index 0000000000..ddddc28113 --- /dev/null +++ b/Lang/Forth/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Forth \ No newline at end of file diff --git a/Lang/Forth/Vampire-number b/Lang/Forth/Vampire-number new file mode 120000 index 0000000000..f6cacda517 --- /dev/null +++ b/Lang/Forth/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Forth \ No newline at end of file diff --git a/Lang/Forth/Variable-size-Set b/Lang/Forth/Variable-size-Set new file mode 120000 index 0000000000..b63c53f866 --- /dev/null +++ b/Lang/Forth/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Forth \ No newline at end of file diff --git a/Lang/Forth/Write-entire-file b/Lang/Forth/Write-entire-file new file mode 120000 index 0000000000..742c99d4f6 --- /dev/null +++ b/Lang/Forth/Write-entire-file @@ -0,0 +1 @@ +../../Task/Write-entire-file/Forth \ No newline at end of file diff --git a/Lang/Fortran/Cheryls-birthday b/Lang/Fortran/Cheryls-birthday new file mode 120000 index 0000000000..5e5ed5ef71 --- /dev/null +++ b/Lang/Fortran/Cheryls-birthday @@ -0,0 +1 @@ +../../Task/Cheryls-birthday/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Chowla-numbers b/Lang/Fortran/Chowla-numbers new file mode 120000 index 0000000000..7f0b9e01f2 --- /dev/null +++ b/Lang/Fortran/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Distance-and-Bearing b/Lang/Fortran/Distance-and-Bearing new file mode 120000 index 0000000000..7bc778a069 --- /dev/null +++ b/Lang/Fortran/Distance-and-Bearing @@ -0,0 +1 @@ +../../Task/Distance-and-Bearing/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Doomsday-rule b/Lang/Fortran/Doomsday-rule new file mode 120000 index 0000000000..da3d111050 --- /dev/null +++ b/Lang/Fortran/Doomsday-rule @@ -0,0 +1 @@ +../../Task/Doomsday-rule/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Knapsack-problem-0-1 b/Lang/Fortran/Knapsack-problem-0-1 new file mode 120000 index 0000000000..e042c7b894 --- /dev/null +++ b/Lang/Fortran/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Partition-an-integer-x-into-n-primes b/Lang/Fortran/Partition-an-integer-x-into-n-primes new file mode 120000 index 0000000000..0df6e16951 --- /dev/null +++ b/Lang/Fortran/Partition-an-integer-x-into-n-primes @@ -0,0 +1 @@ +../../Task/Partition-an-integer-x-into-n-primes/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Sorting-algorithms-Quicksort b/Lang/Fortran/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..8ce86e51d1 --- /dev/null +++ b/Lang/Fortran/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Fortran \ No newline at end of file diff --git a/Lang/FreeBASIC/Bitmap-Read-a-PPM-file b/Lang/FreeBASIC/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..c8c701a33a --- /dev/null +++ b/Lang/FreeBASIC/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Cheryls-birthday b/Lang/FreeBASIC/Cheryls-birthday new file mode 120000 index 0000000000..c637b5ee77 --- /dev/null +++ b/Lang/FreeBASIC/Cheryls-birthday @@ -0,0 +1 @@ +../../Task/Cheryls-birthday/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Church-numerals b/Lang/FreeBASIC/Church-numerals new file mode 120000 index 0000000000..36b5d4ddfd --- /dev/null +++ b/Lang/FreeBASIC/Church-numerals @@ -0,0 +1 @@ +../../Task/Church-numerals/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/FreeBASIC/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..ed1aa87962 --- /dev/null +++ b/Lang/FreeBASIC/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k @@ -0,0 +1 @@ +../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Cyclops-numbers b/Lang/FreeBASIC/Cyclops-numbers new file mode 120000 index 0000000000..b977c5acd5 --- /dev/null +++ b/Lang/FreeBASIC/Cyclops-numbers @@ -0,0 +1 @@ +../../Task/Cyclops-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Deceptive-numbers b/Lang/FreeBASIC/Deceptive-numbers new file mode 120000 index 0000000000..9ff51e1521 --- /dev/null +++ b/Lang/FreeBASIC/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Earliest-difference-between-prime-gaps b/Lang/FreeBASIC/Earliest-difference-between-prime-gaps new file mode 120000 index 0000000000..2facf16701 --- /dev/null +++ b/Lang/FreeBASIC/Earliest-difference-between-prime-gaps @@ -0,0 +1 @@ +../../Task/Earliest-difference-between-prime-gaps/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/First-class-functions-Use-numbers-analogously b/Lang/FreeBASIC/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..7a5134ceca --- /dev/null +++ b/Lang/FreeBASIC/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/First-perfect-square-in-base-n-with-n-unique-digits b/Lang/FreeBASIC/First-perfect-square-in-base-n-with-n-unique-digits new file mode 120000 index 0000000000..c5ae025a12 --- /dev/null +++ b/Lang/FreeBASIC/First-perfect-square-in-base-n-with-n-unique-digits @@ -0,0 +1 @@ +../../Task/First-perfect-square-in-base-n-with-n-unique-digits/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Legendre-prime-counting-function b/Lang/FreeBASIC/Legendre-prime-counting-function new file mode 120000 index 0000000000..e68c3452dc --- /dev/null +++ b/Lang/FreeBASIC/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Mayan-numerals b/Lang/FreeBASIC/Mayan-numerals new file mode 120000 index 0000000000..a931ce4cd8 --- /dev/null +++ b/Lang/FreeBASIC/Mayan-numerals @@ -0,0 +1 @@ +../../Task/Mayan-numerals/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Modular-arithmetic b/Lang/FreeBASIC/Modular-arithmetic new file mode 120000 index 0000000000..deab2b4adc --- /dev/null +++ b/Lang/FreeBASIC/Modular-arithmetic @@ -0,0 +1 @@ +../../Task/Modular-arithmetic/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Multi-base-primes b/Lang/FreeBASIC/Multi-base-primes new file mode 120000 index 0000000000..a5bd10f299 --- /dev/null +++ b/Lang/FreeBASIC/Multi-base-primes @@ -0,0 +1 @@ +../../Task/Multi-base-primes/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Ormiston-triples b/Lang/FreeBASIC/Ormiston-triples new file mode 120000 index 0000000000..d11a7380e3 --- /dev/null +++ b/Lang/FreeBASIC/Ormiston-triples @@ -0,0 +1 @@ +../../Task/Ormiston-triples/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Parallel-calculations b/Lang/FreeBASIC/Parallel-calculations new file mode 120000 index 0000000000..84d9dd900f --- /dev/null +++ b/Lang/FreeBASIC/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Prime-triangle b/Lang/FreeBASIC/Prime-triangle new file mode 120000 index 0000000000..3cbf1f6908 --- /dev/null +++ b/Lang/FreeBASIC/Prime-triangle @@ -0,0 +1 @@ +../../Task/Prime-triangle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Ramanujan-primes-twins b/Lang/FreeBASIC/Ramanujan-primes-twins new file mode 120000 index 0000000000..1ffd055b66 --- /dev/null +++ b/Lang/FreeBASIC/Ramanujan-primes-twins @@ -0,0 +1 @@ +../../Task/Ramanujan-primes-twins/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Rhonda-numbers b/Lang/FreeBASIC/Rhonda-numbers new file mode 120000 index 0000000000..cd2acf4828 --- /dev/null +++ b/Lang/FreeBASIC/Rhonda-numbers @@ -0,0 +1 @@ +../../Task/Rhonda-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Safe-addition b/Lang/FreeBASIC/Safe-addition new file mode 120000 index 0000000000..06b1afc7fe --- /dev/null +++ b/Lang/FreeBASIC/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Shortest-common-supersequence b/Lang/FreeBASIC/Shortest-common-supersequence new file mode 120000 index 0000000000..fec5965970 --- /dev/null +++ b/Lang/FreeBASIC/Shortest-common-supersequence @@ -0,0 +1 @@ +../../Task/Shortest-common-supersequence/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sphenic-numbers b/Lang/FreeBASIC/Sphenic-numbers new file mode 120000 index 0000000000..ab7e3a8e2d --- /dev/null +++ b/Lang/FreeBASIC/Sphenic-numbers @@ -0,0 +1 @@ +../../Task/Sphenic-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Sum-and-product-puzzle b/Lang/FreeBASIC/Sum-and-product-puzzle new file mode 120000 index 0000000000..51d37d0fd1 --- /dev/null +++ b/Lang/FreeBASIC/Sum-and-product-puzzle @@ -0,0 +1 @@ +../../Task/Sum-and-product-puzzle/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Super-d-numbers b/Lang/FreeBASIC/Super-d-numbers new file mode 120000 index 0000000000..194e6c4f2e --- /dev/null +++ b/Lang/FreeBASIC/Super-d-numbers @@ -0,0 +1 @@ +../../Task/Super-d-numbers/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/The-sieve-of-Sundaram b/Lang/FreeBASIC/The-sieve-of-Sundaram new file mode 120000 index 0000000000..04d6593f09 --- /dev/null +++ b/Lang/FreeBASIC/The-sieve-of-Sundaram @@ -0,0 +1 @@ +../../Task/The-sieve-of-Sundaram/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Two-bullet-roulette b/Lang/FreeBASIC/Two-bullet-roulette new file mode 120000 index 0000000000..cb9fa727f7 --- /dev/null +++ b/Lang/FreeBASIC/Two-bullet-roulette @@ -0,0 +1 @@ +../../Task/Two-bullet-roulette/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/War-card-game b/Lang/FreeBASIC/War-card-game new file mode 120000 index 0000000000..8c49d839ef --- /dev/null +++ b/Lang/FreeBASIC/War-card-game @@ -0,0 +1 @@ +../../Task/War-card-game/FreeBASIC \ No newline at end of file diff --git a/Lang/FutureBasic/Averages-Pythagorean-means b/Lang/FutureBasic/Averages-Pythagorean-means new file mode 120000 index 0000000000..76e7204f24 --- /dev/null +++ b/Lang/FutureBasic/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Bifid-cipher b/Lang/FutureBasic/Bifid-cipher new file mode 120000 index 0000000000..e40a4d935a --- /dev/null +++ b/Lang/FutureBasic/Bifid-cipher @@ -0,0 +1 @@ +../../Task/Bifid-cipher/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Conways-Game-of-Life b/Lang/FutureBasic/Conways-Game-of-Life new file mode 120000 index 0000000000..cc723d5af1 --- /dev/null +++ b/Lang/FutureBasic/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/FutureBasic \ No newline at end of file diff --git a/Lang/FutureBasic/Run-length-encoding b/Lang/FutureBasic/Run-length-encoding new file mode 120000 index 0000000000..e5f272bd61 --- /dev/null +++ b/Lang/FutureBasic/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/FutureBasic \ No newline at end of file diff --git a/Lang/GDScript/Null-object b/Lang/GDScript/Null-object new file mode 120000 index 0000000000..e2b2de9b21 --- /dev/null +++ b/Lang/GDScript/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/GDScript \ No newline at end of file diff --git a/Lang/GDScript/Sorting-algorithms-Bubble-sort b/Lang/GDScript/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..0c8ecc5b3e --- /dev/null +++ b/Lang/GDScript/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/GDScript \ No newline at end of file diff --git a/Lang/GDScript/Stack b/Lang/GDScript/Stack new file mode 120000 index 0000000000..8e1def2ef0 --- /dev/null +++ b/Lang/GDScript/Stack @@ -0,0 +1 @@ +../../Task/Stack/GDScript \ No newline at end of file diff --git a/Lang/Gambas/Sum-and-product-puzzle b/Lang/Gambas/Sum-and-product-puzzle new file mode 120000 index 0000000000..70ae337f46 --- /dev/null +++ b/Lang/Gambas/Sum-and-product-puzzle @@ -0,0 +1 @@ +../../Task/Sum-and-product-puzzle/Gambas \ No newline at end of file diff --git a/Lang/Haxe/Rot-13 b/Lang/Haxe/Rot-13 new file mode 120000 index 0000000000..fc9a0671f3 --- /dev/null +++ b/Lang/Haxe/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Haxe \ No newline at end of file diff --git a/Lang/Hopper/00-LANG.txt b/Lang/Hopper/00-LANG.txt new file mode 100644 index 0000000000..60fcfd7a6c --- /dev/null +++ b/Lang/Hopper/00-LANG.txt @@ -0,0 +1,58 @@ +{{language|Hopper +|gc=yes +|parampass=both +|express=explicit +|checking=static +|safety=safe +|strength=strong +|hopl=no +|site=https://www.hackster.io/michael-cartwright/projects +}} + +'''Hopper''' is a Java-like programming language and development environment designed for microcontrollers. A curly-brace semi-colon syntax, with a bytecode compiler, and development toolchain for Hopper bytecode virtual machine runtime implementations. + +The runtimes are usually flashed onto the development board for power up start. The IDE can upload a boot up program, (along with a little file system). Development machine and device interactions is accomplished by USB serial connections. Hopper blurs the line between IDE programmer and target device. The serial monitor and client/server communications is written in Hopper, which can be executed in the IDE and/or the target device. + +The Hopper Interactive Development Environment (IDE) runs on Windows, with outputs targeting Hopper Runtimes for +* 6502, an older 8bit microcontroller unit, (MCU). +* RP2040, a newer 32bit dual core Cortex M0+ MCU with General Purpose Input Output (GPIO) pins and modern internal peripherals, designed by the Raspberry Pi Foundation, (RPi). +** Pico +** Pico W +** Challenger RP2040 Wifi +* more to come + +Github repository: https://github.com/sillycowvalley/Hopper + +All Hopper Runtimes support a Hopper Monitor shell that implements feedback IO and a command language, the elements of which are Hopper programs. The Hopper Runtime virtual machine can also be used directly from the Hopper IDE on desktop PC, with the bootstrap Windows VM written in C# and the rest is self-hosted in Hopper. For the RP2040 at least. + +The 6502 Runtime is bootstrapped from assembly language sources, for both first run hopper and firmware, then hosted in Hopper VM bytecode and the development toolchain. + +Hopper is written in Hopper, with '''.hexe''' bytecode files in the '''Bin/''' directory of the IDE setup. +* Preprocess, Compile, Optimize, Codegen, DASM (Disassembler) +* Translate (Hopper to C) + +In support of the system shell and '''.cmd''' scripting, there is also: (non exhaustive list) + +* show, shell, debug (more on this below), cd, cls, dir, del +* see '''help''' for more + +=== Documentation === +The author has put early documentation efforts into a large set of YouTube videos, with the main page (and search) at: + +https://www.youtube.com/@biggertigger + +=== Development as of 2024 === + +In development by Michael Cartwright, with working samples for MOS Technology 6502 and Raspberry Pi RP2040. +There are various RunTime UF2's pre-built for quick starts. (UF2 is a hex file format for microcontroller firmware uploads): + +* Pico, Pico W (with Wifi networking implemented), Challenger RP2040 Wifi +* as is, the Pico firmware will at least minimally work on a fair number of RPi RP2040 development boards +* along with drivers (written in Hopper) for many MCU related display devices and module peripherals. + +=== Hopper Debugger === +The debugger is an important part of Hopper development. +'''TODO''' + +=== Links: === +* [[Reports:Tasks_not_implemented_in_Hopper|Tasks not yet implemented]] \ No newline at end of file diff --git a/Lang/Hopper/00-META.yaml b/Lang/Hopper/00-META.yaml new file mode 100644 index 0000000000..4850aa5735 --- /dev/null +++ b/Lang/Hopper/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:Hopper diff --git a/Lang/Hopper/Hello-world-Text b/Lang/Hopper/Hello-world-Text new file mode 120000 index 0000000000..2f126e55ad --- /dev/null +++ b/Lang/Hopper/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Hopper \ No newline at end of file diff --git a/Lang/Janet/00-LANG.txt b/Lang/Janet/00-LANG.txt index 7a05c0cca0..367ff871be 100644 --- a/Lang/Janet/00-LANG.txt +++ b/Lang/Janet/00-LANG.txt @@ -4,4 +4,24 @@ Janet is a C based, Clojure-like lisp for scripting and prototyping. From the website [https://janet-lang.org https://janet-lang.org] -Janet is a functional and imperative programming language. It runs on Windows, Linux, macOS, and should run on other systems with some porting. The entire language (core library, interpreter, compiler, assembler, PEG) is about 300-500 kB and should run on many constrained systems. \ No newline at end of file +Janet is a functional and imperative programming language. It runs on Windows, Linux, macOS, BSDs, and should run on other systems with some porting. The entire language (core library, interpreter, compiler, assembler, PEG) is less than 1MB. You can also add Janet scripting to an application by embedding a single C source file and a single header. + +===Features=== + Minimal setup - one binary and you are good to go! + Builtin support for threads, networking, and an event loop + First class closures + Garbage collection + First class green threads (continuations) + Mutable and immutable arrays (array/tuple) + Mutable and immutable hashtables (table/struct) + Mutable and immutable strings (buffer/string) + Macros + Tail call optimization + Direct interop with C via abstract types and C functions + Dynamically load C libraries + Lexical scoping + REPL and interactive debugger + Parsing Expression Grammars built in to the core library + 500+ functions and macros in the core library + Export your projects to standalone executables with a companion build tool, jpm + Add to a project with just janet.c and janet.h \ No newline at end of file diff --git a/Lang/Janet/Digital-root b/Lang/Janet/Digital-root new file mode 120000 index 0000000000..0234a87797 --- /dev/null +++ b/Lang/Janet/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Janet \ No newline at end of file diff --git a/Lang/Java/Simple-turtle-graphics b/Lang/Java/Simple-turtle-graphics new file mode 120000 index 0000000000..3bc3f93a70 --- /dev/null +++ b/Lang/Java/Simple-turtle-graphics @@ -0,0 +1 @@ +../../Task/Simple-turtle-graphics/Java \ No newline at end of file diff --git a/Lang/JavaScript/00-LANG.txt b/Lang/JavaScript/00-LANG.txt index 3906eaab39..a610363714 100644 --- a/Lang/JavaScript/00-LANG.txt +++ b/Lang/JavaScript/00-LANG.txt @@ -28,4 +28,7 @@ The inclusion of '''tail-call optimisation''' in the ES6 standard reflects incre * [https://developer.apple.com/library/mac/releasenotes/InterapplicationCommunication/RN-JavaScriptForAutomation/Articles/Introduction.html OS X JavaScript for Applications] JavaScript as an OS X scripting language – supported by the Safari debugger * [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Shells Other JavaScript shells] List maintained by Mozilla * [https://github.com/jashkenas/coffeescript/wiki/list-of-languages-that-compile-to-js List of languages that compile to JS] maintained on Github by Jeremy Ashenas – author of CoffeeScript, Underscore and Backbone -* [http://shop.oreilly.com/product/0636920028857.do Functional JavaScript] – Michael Fogus, O'Reilly 2013 \ No newline at end of file +* [http://shop.oreilly.com/product/0636920028857.do Functional JavaScript] – Michael Fogus, O'Reilly 2013 + +==To do== +[[Tasks not implemented in JavaScript]] \ No newline at end of file diff --git a/Lang/JavaScript/Eertree b/Lang/JavaScript/Eertree new file mode 120000 index 0000000000..60ff5de55f --- /dev/null +++ b/Lang/JavaScript/Eertree @@ -0,0 +1 @@ +../../Task/Eertree/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Modified-random-distribution b/Lang/JavaScript/Modified-random-distribution new file mode 120000 index 0000000000..e8810a8ff3 --- /dev/null +++ b/Lang/JavaScript/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Pisano-period b/Lang/JavaScript/Pisano-period new file mode 120000 index 0000000000..1e168befa1 --- /dev/null +++ b/Lang/JavaScript/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Primorial-numbers b/Lang/JavaScript/Primorial-numbers new file mode 120000 index 0000000000..82a58b78e9 --- /dev/null +++ b/Lang/JavaScript/Primorial-numbers @@ -0,0 +1 @@ +../../Task/Primorial-numbers/JavaScript \ No newline at end of file diff --git a/Lang/Jq/00-LANG.txt b/Lang/Jq/00-LANG.txt index 70c9eddfba..3eba7f05c0 100644 --- a/Lang/Jq/00-LANG.txt +++ b/Lang/Jq/00-LANG.txt @@ -1,13 +1,16 @@ {{language |site=http://stedolan.github.io/jq}} {{language programming paradigm|Functional}} -[https://en.wikipedia.org/wiki/Jq_(programming_language) jq] is a [[functional programming]] language that is oriented towards processing text files or [[JSON]]. jq is also the name of [https://stedolan.github.io/jq a portable executable] that compiles and runs jq programs. A [[Go]] implementation, [https://github.com/itchyny/gojq gojq], is also available. +[https://en.wikipedia.org/wiki/Jq_(programming_language) jq] is a [[functional programming]] language that is oriented towards processing text files or [[JSON]]. jq is also the name of [https://stedolan.github.io/jq a portable executable] that compiles and runs jq programs. A [[Go]] implementation, [https://github.com/itchyny/gojq gojq], is also available; and [https://github.com/01mf02/jaq jaq] implements a large subset of jq in [[Rust]]. jq was originally designed and developed by Stephen Dolan. ==jq Modules at rosettacode.org== * [[:Category:Jq/assert.jq|assert.jq]] - module to support assertions +* [[:Category:Jq/fibonacci.jq|fibonacci.jq]] - Fibonacci sequence and Fibonacci coding * [[:Category:Jq/peg.jq|peg.jq]] - Parsing Expression Grammar foundations +* [[:Category:Jq/polynomials.jq|polynomials.jq]] - polynomials as JSON arrays +* [[:Category:Jq/RealSet.jq|RealSet.jq]] - Union of finite real intervals ==Todo== [[Tasks_not_implemented_in_jq]] diff --git a/Lang/Jq/Evolutionary-algorithm b/Lang/Jq/Evolutionary-algorithm new file mode 120000 index 0000000000..3e237d59aa --- /dev/null +++ b/Lang/Jq/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Jq \ No newline at end of file diff --git a/Lang/Jq/Gray-code b/Lang/Jq/Gray-code new file mode 120000 index 0000000000..3dca8836bd --- /dev/null +++ b/Lang/Jq/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Jq \ No newline at end of file diff --git a/Lang/Jq/Index-finite-lists-of-positive-integers b/Lang/Jq/Index-finite-lists-of-positive-integers new file mode 120000 index 0000000000..da5139ae0d --- /dev/null +++ b/Lang/Jq/Index-finite-lists-of-positive-integers @@ -0,0 +1 @@ +../../Task/Index-finite-lists-of-positive-integers/Jq \ No newline at end of file diff --git a/Lang/Jq/Intersecting-number-wheels b/Lang/Jq/Intersecting-number-wheels new file mode 120000 index 0000000000..4bb7092aa3 --- /dev/null +++ b/Lang/Jq/Intersecting-number-wheels @@ -0,0 +1 @@ +../../Task/Intersecting-number-wheels/Jq \ No newline at end of file diff --git a/Lang/Jq/Parse-an-IP-Address b/Lang/Jq/Parse-an-IP-Address new file mode 120000 index 0000000000..141e962822 --- /dev/null +++ b/Lang/Jq/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Jq \ No newline at end of file diff --git a/Lang/Jq/Password-generator b/Lang/Jq/Password-generator new file mode 120000 index 0000000000..ef3ce417dc --- /dev/null +++ b/Lang/Jq/Password-generator @@ -0,0 +1 @@ +../../Task/Password-generator/Jq \ No newline at end of file diff --git a/Lang/Jq/Pseudo-random-numbers-Splitmix64 b/Lang/Jq/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..99474567aa --- /dev/null +++ b/Lang/Jq/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Jq \ No newline at end of file diff --git a/Lang/Jq/Set-of-real-numbers b/Lang/Jq/Set-of-real-numbers new file mode 120000 index 0000000000..4930cbfaeb --- /dev/null +++ b/Lang/Jq/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Jq \ No newline at end of file diff --git a/Lang/Jq/Start-from-a-main-routine b/Lang/Jq/Start-from-a-main-routine new file mode 120000 index 0000000000..04bfaaf631 --- /dev/null +++ b/Lang/Jq/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Jq \ No newline at end of file diff --git a/Lang/K/Array-length b/Lang/K/Array-length new file mode 120000 index 0000000000..713b43ae60 --- /dev/null +++ b/Lang/K/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/K \ No newline at end of file diff --git a/Lang/K/Entropy b/Lang/K/Entropy new file mode 120000 index 0000000000..ed297bc904 --- /dev/null +++ b/Lang/K/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/K \ No newline at end of file diff --git a/Lang/K/Jewels-and-stones b/Lang/K/Jewels-and-stones new file mode 120000 index 0000000000..e6b3ba2ffd --- /dev/null +++ b/Lang/K/Jewels-and-stones @@ -0,0 +1 @@ +../../Task/Jewels-and-stones/K \ No newline at end of file diff --git a/Lang/K/Sort-numbers-lexicographically b/Lang/K/Sort-numbers-lexicographically new file mode 120000 index 0000000000..11b8c47a3f --- /dev/null +++ b/Lang/K/Sort-numbers-lexicographically @@ -0,0 +1 @@ +../../Task/Sort-numbers-lexicographically/K \ No newline at end of file diff --git a/Lang/K/Split-a-character-string-based-on-change-of-character b/Lang/K/Split-a-character-string-based-on-change-of-character new file mode 120000 index 0000000000..719471c77a --- /dev/null +++ b/Lang/K/Split-a-character-string-based-on-change-of-character @@ -0,0 +1 @@ +../../Task/Split-a-character-string-based-on-change-of-character/K \ No newline at end of file diff --git a/Lang/K/Strip-a-set-of-characters-from-a-string b/Lang/K/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..2c6359b506 --- /dev/null +++ b/Lang/K/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/K \ No newline at end of file diff --git a/Lang/Koka/Leap-year b/Lang/Koka/Leap-year new file mode 120000 index 0000000000..9589417f53 --- /dev/null +++ b/Lang/Koka/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Koka \ No newline at end of file diff --git a/Lang/Kotlin/Almkvist-Giullera-formula-for-pi b/Lang/Kotlin/Almkvist-Giullera-formula-for-pi new file mode 120000 index 0000000000..e147780c53 --- /dev/null +++ b/Lang/Kotlin/Almkvist-Giullera-formula-for-pi @@ -0,0 +1 @@ +../../Task/Almkvist-Giullera-formula-for-pi/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Biorhythms b/Lang/Kotlin/Biorhythms new file mode 120000 index 0000000000..d93c9e81d0 --- /dev/null +++ b/Lang/Kotlin/Biorhythms @@ -0,0 +1 @@ +../../Task/Biorhythms/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Camel-case-and-snake-case b/Lang/Kotlin/Camel-case-and-snake-case new file mode 120000 index 0000000000..67b25b8962 --- /dev/null +++ b/Lang/Kotlin/Camel-case-and-snake-case @@ -0,0 +1 @@ +../../Task/Camel-case-and-snake-case/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Jordan-P-lya-numbers b/Lang/Kotlin/Jordan-P-lya-numbers new file mode 120000 index 0000000000..89b37f7823 --- /dev/null +++ b/Lang/Kotlin/Jordan-P-lya-numbers @@ -0,0 +1 @@ +../../Task/Jordan-P-lya-numbers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Minimal-steps-down-to-1 b/Lang/Kotlin/Minimal-steps-down-to-1 new file mode 120000 index 0000000000..65ab282625 --- /dev/null +++ b/Lang/Kotlin/Minimal-steps-down-to-1 @@ -0,0 +1 @@ +../../Task/Minimal-steps-down-to-1/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Padovan-sequence b/Lang/Kotlin/Padovan-sequence new file mode 120000 index 0000000000..18631de1be --- /dev/null +++ b/Lang/Kotlin/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/Kotlin \ No newline at end of file diff --git a/Lang/Langur/Check-that-file-exists b/Lang/Langur/Check-that-file-exists new file mode 120000 index 0000000000..d23d4fb2de --- /dev/null +++ b/Lang/Langur/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Langur \ No newline at end of file diff --git a/Lang/Langur/Convert-seconds-to-compound-duration b/Lang/Langur/Convert-seconds-to-compound-duration new file mode 120000 index 0000000000..542c4c4b83 --- /dev/null +++ b/Lang/Langur/Convert-seconds-to-compound-duration @@ -0,0 +1 @@ +../../Task/Convert-seconds-to-compound-duration/Langur \ No newline at end of file diff --git a/Lang/Langur/Sum-of-a-series b/Lang/Langur/Sum-of-a-series new file mode 120000 index 0000000000..4e4882b880 --- /dev/null +++ b/Lang/Langur/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Langur \ No newline at end of file diff --git a/Lang/Lua/Combinations-and-permutations b/Lang/Lua/Combinations-and-permutations new file mode 120000 index 0000000000..c0a533db08 --- /dev/null +++ b/Lang/Lua/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Lua \ No newline at end of file diff --git a/Lang/Lua/Handle-a-signal b/Lang/Lua/Handle-a-signal new file mode 120000 index 0000000000..f16f994877 --- /dev/null +++ b/Lang/Lua/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Lua \ No newline at end of file diff --git a/Lang/Lua/Padovan-sequence b/Lang/Lua/Padovan-sequence new file mode 120000 index 0000000000..242b563fd5 --- /dev/null +++ b/Lang/Lua/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/Lua \ No newline at end of file diff --git a/Lang/Lua/Palindrome-dates b/Lang/Lua/Palindrome-dates new file mode 120000 index 0000000000..c839a0552f --- /dev/null +++ b/Lang/Lua/Palindrome-dates @@ -0,0 +1 @@ +../../Task/Palindrome-dates/Lua \ No newline at end of file diff --git a/Lang/Lua/Pisano-period b/Lang/Lua/Pisano-period new file mode 120000 index 0000000000..4b34e1a22a --- /dev/null +++ b/Lang/Lua/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Lua \ No newline at end of file diff --git a/Lang/MAD/Narcissistic-decimal-number b/Lang/MAD/Narcissistic-decimal-number new file mode 120000 index 0000000000..e10c6cbbcd --- /dev/null +++ b/Lang/MAD/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/MAD \ No newline at end of file diff --git a/Lang/MAD/Primality-by-Wilsons-theorem b/Lang/MAD/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..2fd2beea20 --- /dev/null +++ b/Lang/MAD/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/MAD \ No newline at end of file diff --git a/Lang/MATLAB/Arithmetic-geometric-mean-Calculate-Pi b/Lang/MATLAB/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..455d4f72bb --- /dev/null +++ b/Lang/MATLAB/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Babbage-problem b/Lang/MATLAB/Babbage-problem new file mode 120000 index 0000000000..995ca19944 --- /dev/null +++ b/Lang/MATLAB/Babbage-problem @@ -0,0 +1 @@ +../../Task/Babbage-problem/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Babylonian-spiral b/Lang/MATLAB/Babylonian-spiral new file mode 120000 index 0000000000..ecf91872cf --- /dev/null +++ b/Lang/MATLAB/Babylonian-spiral @@ -0,0 +1 @@ +../../Task/Babylonian-spiral/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Benfords-law b/Lang/MATLAB/Benfords-law new file mode 120000 index 0000000000..24ad64ca80 --- /dev/null +++ b/Lang/MATLAB/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Brazilian-numbers b/Lang/MATLAB/Brazilian-numbers new file mode 120000 index 0000000000..31d88350b2 --- /dev/null +++ b/Lang/MATLAB/Brazilian-numbers @@ -0,0 +1 @@ +../../Task/Brazilian-numbers/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Canonicalize-CIDR b/Lang/MATLAB/Canonicalize-CIDR new file mode 120000 index 0000000000..eb15cedc52 --- /dev/null +++ b/Lang/MATLAB/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Damm-algorithm b/Lang/MATLAB/Damm-algorithm new file mode 120000 index 0000000000..8c3c3b12e0 --- /dev/null +++ b/Lang/MATLAB/Damm-algorithm @@ -0,0 +1 @@ +../../Task/Damm-algorithm/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Department-numbers b/Lang/MATLAB/Department-numbers new file mode 120000 index 0000000000..a4bfc52d36 --- /dev/null +++ b/Lang/MATLAB/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/EKG-sequence-convergence b/Lang/MATLAB/EKG-sequence-convergence new file mode 120000 index 0000000000..d84b387d6c --- /dev/null +++ b/Lang/MATLAB/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Euler-method b/Lang/MATLAB/Euler-method new file mode 120000 index 0000000000..210be62097 --- /dev/null +++ b/Lang/MATLAB/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Farey-sequence b/Lang/MATLAB/Farey-sequence new file mode 120000 index 0000000000..8248da8507 --- /dev/null +++ b/Lang/MATLAB/Farey-sequence @@ -0,0 +1 @@ +../../Task/Farey-sequence/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Padovan-sequence b/Lang/MATLAB/Padovan-sequence new file mode 120000 index 0000000000..3df1773261 --- /dev/null +++ b/Lang/MATLAB/Padovan-sequence @@ -0,0 +1 @@ +../../Task/Padovan-sequence/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Pascal-matrix-generation b/Lang/MATLAB/Pascal-matrix-generation new file mode 120000 index 0000000000..52b2a75e65 --- /dev/null +++ b/Lang/MATLAB/Pascal-matrix-generation @@ -0,0 +1 @@ +../../Task/Pascal-matrix-generation/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Steffensens-method b/Lang/MATLAB/Steffensens-method new file mode 120000 index 0000000000..ee8fd5a1aa --- /dev/null +++ b/Lang/MATLAB/Steffensens-method @@ -0,0 +1 @@ +../../Task/Steffensens-method/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Strassens-algorithm b/Lang/MATLAB/Strassens-algorithm new file mode 120000 index 0000000000..74ee0ab355 --- /dev/null +++ b/Lang/MATLAB/Strassens-algorithm @@ -0,0 +1 @@ +../../Task/Strassens-algorithm/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/MATLAB/Sum-of-elements-below-main-diagonal-of-matrix new file mode 120000 index 0000000000..7c6a28e865 --- /dev/null +++ b/Lang/MATLAB/Sum-of-elements-below-main-diagonal-of-matrix @@ -0,0 +1 @@ +../../Task/Sum-of-elements-below-main-diagonal-of-matrix/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Thue-Morse b/Lang/MATLAB/Thue-Morse new file mode 120000 index 0000000000..c795b03216 --- /dev/null +++ b/Lang/MATLAB/Thue-Morse @@ -0,0 +1 @@ +../../Task/Thue-Morse/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Trabb-Pardo-Knuth-algorithm b/Lang/MATLAB/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..2c35ef2ed2 --- /dev/null +++ b/Lang/MATLAB/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Xiaolin-Wus-line-algorithm b/Lang/MATLAB/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..455a774f2c --- /dev/null +++ b/Lang/MATLAB/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Zeckendorf-number-representation b/Lang/MATLAB/Zeckendorf-number-representation new file mode 120000 index 0000000000..29c82374e5 --- /dev/null +++ b/Lang/MATLAB/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/MATLAB \ No newline at end of file diff --git a/Lang/Mathematica/Factorial-primes b/Lang/Mathematica/Factorial-primes new file mode 120000 index 0000000000..1c87586f1f --- /dev/null +++ b/Lang/Mathematica/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Giuga-numbers b/Lang/Mathematica/Giuga-numbers new file mode 120000 index 0000000000..66ff38fc64 --- /dev/null +++ b/Lang/Mathematica/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Pisano-period b/Lang/Mathematica/Pisano-period new file mode 120000 index 0000000000..e114173423 --- /dev/null +++ b/Lang/Mathematica/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Pseudo-random-numbers-PCG32 b/Lang/Mathematica/Pseudo-random-numbers-PCG32 new file mode 120000 index 0000000000..9d682a5443 --- /dev/null +++ b/Lang/Mathematica/Pseudo-random-numbers-PCG32 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-PCG32/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Ruth-Aaron-numbers b/Lang/Mathematica/Ruth-Aaron-numbers new file mode 120000 index 0000000000..9753b08d5c --- /dev/null +++ b/Lang/Mathematica/Ruth-Aaron-numbers @@ -0,0 +1 @@ +../../Task/Ruth-Aaron-numbers/Mathematica \ No newline at end of file diff --git a/Lang/MiniScript/00-LANG.txt b/Lang/MiniScript/00-LANG.txt index f8f2143953..5ef9c2bb3f 100644 --- a/Lang/MiniScript/00-LANG.txt +++ b/Lang/MiniScript/00-LANG.txt @@ -2,4 +2,7 @@ MiniScript is a high-level scripting language designed originally for embedding in other software (especially games). The first implementation was in C#. In 2019, a C++ implementation was added, and both versions were open-sourced on [https://github.com/JoeStrout/miniscript GitHub]. -More information can be found at [https://miniscript.org/ miniscript.org]. \ No newline at end of file +More information can be found at [https://miniscript.org/ miniscript.org]. + +==Todo== +* [[Tasks not implemented in MiniScript]] \ No newline at end of file diff --git a/Lang/MiniScript/CUSIP b/Lang/MiniScript/CUSIP new file mode 120000 index 0000000000..23ab881a7b --- /dev/null +++ b/Lang/MiniScript/CUSIP @@ -0,0 +1 @@ +../../Task/CUSIP/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Character-codes b/Lang/MiniScript/Character-codes new file mode 120000 index 0000000000..02f30676f2 --- /dev/null +++ b/Lang/MiniScript/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Comments b/Lang/MiniScript/Comments new file mode 120000 index 0000000000..6c2e69e82f --- /dev/null +++ b/Lang/MiniScript/Comments @@ -0,0 +1 @@ +../../Task/Comments/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Currying b/Lang/MiniScript/Currying new file mode 120000 index 0000000000..5bfc81e5a2 --- /dev/null +++ b/Lang/MiniScript/Currying @@ -0,0 +1 @@ +../../Task/Currying/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Date-format b/Lang/MiniScript/Date-format new file mode 120000 index 0000000000..691dbe1508 --- /dev/null +++ b/Lang/MiniScript/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Date-manipulation b/Lang/MiniScript/Date-manipulation new file mode 120000 index 0000000000..53293214b7 --- /dev/null +++ b/Lang/MiniScript/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Day-of-the-week b/Lang/MiniScript/Day-of-the-week new file mode 120000 index 0000000000..1b556db413 --- /dev/null +++ b/Lang/MiniScript/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Department-numbers b/Lang/MiniScript/Department-numbers new file mode 120000 index 0000000000..6daa070f52 --- /dev/null +++ b/Lang/MiniScript/Department-numbers @@ -0,0 +1 @@ +../../Task/Department-numbers/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Detect-division-by-zero b/Lang/MiniScript/Detect-division-by-zero new file mode 120000 index 0000000000..29baa515c8 --- /dev/null +++ b/Lang/MiniScript/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Empty-string b/Lang/MiniScript/Empty-string new file mode 120000 index 0000000000..bbda7e56b2 --- /dev/null +++ b/Lang/MiniScript/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Exponentiation-operator b/Lang/MiniScript/Exponentiation-operator new file mode 120000 index 0000000000..25dcaee73f --- /dev/null +++ b/Lang/MiniScript/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/MiniScript \ No newline at end of file diff --git a/Lang/MiniScript/Extreme-floating-point-values b/Lang/MiniScript/Extreme-floating-point-values new file mode 120000 index 0000000000..108b4683db --- /dev/null +++ b/Lang/MiniScript/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/MiniScript \ No newline at end of file diff --git a/Lang/Modula-2/Primality-by-Wilsons-theorem b/Lang/Modula-2/Primality-by-Wilsons-theorem new file mode 120000 index 0000000000..4d1359d549 --- /dev/null +++ b/Lang/Modula-2/Primality-by-Wilsons-theorem @@ -0,0 +1 @@ +../../Task/Primality-by-Wilsons-theorem/Modula-2 \ No newline at end of file diff --git a/Lang/Mojo/Hamming-numbers b/Lang/Mojo/Hamming-numbers new file mode 120000 index 0000000000..a401baa2d8 --- /dev/null +++ b/Lang/Mojo/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Mojo \ No newline at end of file diff --git a/Lang/Mojo/Legendre-prime-counting-function b/Lang/Mojo/Legendre-prime-counting-function new file mode 120000 index 0000000000..c7d7f4e32f --- /dev/null +++ b/Lang/Mojo/Legendre-prime-counting-function @@ -0,0 +1 @@ +../../Task/Legendre-prime-counting-function/Mojo \ No newline at end of file diff --git a/Lang/Mojo/Sieve-of-Eratosthenes b/Lang/Mojo/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..c8eb3cd500 --- /dev/null +++ b/Lang/Mojo/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Mojo \ No newline at end of file diff --git a/Lang/Oberon/FASTA-format b/Lang/Oberon/FASTA-format new file mode 120000 index 0000000000..cf4d667f1b --- /dev/null +++ b/Lang/Oberon/FASTA-format @@ -0,0 +1 @@ +../../Task/FASTA-format/Oberon \ No newline at end of file diff --git a/Lang/Odin/Disarium-numbers b/Lang/Odin/Disarium-numbers new file mode 120000 index 0000000000..994b840f85 --- /dev/null +++ b/Lang/Odin/Disarium-numbers @@ -0,0 +1 @@ +../../Task/Disarium-numbers/Odin \ No newline at end of file diff --git a/Lang/OoRexx/Ramer-Douglas-Peucker-line-simplification b/Lang/OoRexx/Ramer-Douglas-Peucker-line-simplification new file mode 120000 index 0000000000..b97748aa44 --- /dev/null +++ b/Lang/OoRexx/Ramer-Douglas-Peucker-line-simplification @@ -0,0 +1 @@ +../../Task/Ramer-Douglas-Peucker-line-simplification/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Temperature-conversion b/Lang/OoRexx/Temperature-conversion new file mode 120000 index 0000000000..dc621ac534 --- /dev/null +++ b/Lang/OoRexx/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/OoRexx \ No newline at end of file diff --git a/Lang/PARI-GP/Calkin-Wilf-sequence b/Lang/PARI-GP/Calkin-Wilf-sequence new file mode 120000 index 0000000000..5260a08bc6 --- /dev/null +++ b/Lang/PARI-GP/Calkin-Wilf-sequence @@ -0,0 +1 @@ +../../Task/Calkin-Wilf-sequence/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Chowla-numbers b/Lang/PARI-GP/Chowla-numbers new file mode 120000 index 0000000000..2787fa8eac --- /dev/null +++ b/Lang/PARI-GP/Chowla-numbers @@ -0,0 +1 @@ +../../Task/Chowla-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/PARI-GP/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..ce686eae22 --- /dev/null +++ b/Lang/PARI-GP/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k @@ -0,0 +1 @@ +../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Cuban-primes b/Lang/PARI-GP/Cuban-primes new file mode 120000 index 0000000000..9fcb6d862c --- /dev/null +++ b/Lang/PARI-GP/Cuban-primes @@ -0,0 +1 @@ +../../Task/Cuban-primes/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Cullen-and-Woodall-numbers b/Lang/PARI-GP/Cullen-and-Woodall-numbers new file mode 120000 index 0000000000..b88f4c7aa7 --- /dev/null +++ b/Lang/PARI-GP/Cullen-and-Woodall-numbers @@ -0,0 +1 @@ +../../Task/Cullen-and-Woodall-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Curzon-numbers b/Lang/PARI-GP/Curzon-numbers new file mode 120000 index 0000000000..f077d65bb8 --- /dev/null +++ b/Lang/PARI-GP/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Duffinian-numbers b/Lang/PARI-GP/Duffinian-numbers new file mode 120000 index 0000000000..2058b3fcc8 --- /dev/null +++ b/Lang/PARI-GP/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Egyptian-division b/Lang/PARI-GP/Egyptian-division new file mode 120000 index 0000000000..a72d5a169a --- /dev/null +++ b/Lang/PARI-GP/Egyptian-division @@ -0,0 +1 @@ +../../Task/Egyptian-division/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Fermat-numbers b/Lang/PARI-GP/Fermat-numbers new file mode 120000 index 0000000000..79fb20086b --- /dev/null +++ b/Lang/PARI-GP/Fermat-numbers @@ -0,0 +1 @@ +../../Task/Fermat-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Giuga-numbers b/Lang/PARI-GP/Giuga-numbers new file mode 120000 index 0000000000..0de2f922cb --- /dev/null +++ b/Lang/PARI-GP/Giuga-numbers @@ -0,0 +1 @@ +../../Task/Giuga-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Home-primes b/Lang/PARI-GP/Home-primes new file mode 120000 index 0000000000..e40e4d05cb --- /dev/null +++ b/Lang/PARI-GP/Home-primes @@ -0,0 +1 @@ +../../Task/Home-primes/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Jacobsthal-numbers b/Lang/PARI-GP/Jacobsthal-numbers new file mode 120000 index 0000000000..f9a4f5ef3a --- /dev/null +++ b/Lang/PARI-GP/Jacobsthal-numbers @@ -0,0 +1 @@ +../../Task/Jacobsthal-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/M-bius-function b/Lang/PARI-GP/M-bius-function new file mode 120000 index 0000000000..00d7d87a25 --- /dev/null +++ b/Lang/PARI-GP/M-bius-function @@ -0,0 +1 @@ +../../Task/M-bius-function/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Pisano-period b/Lang/PARI-GP/Pisano-period new file mode 120000 index 0000000000..983f75fe6c --- /dev/null +++ b/Lang/PARI-GP/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Repunit-primes b/Lang/PARI-GP/Repunit-primes new file mode 120000 index 0000000000..a51827e876 --- /dev/null +++ b/Lang/PARI-GP/Repunit-primes @@ -0,0 +1 @@ +../../Task/Repunit-primes/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Rhonda-numbers b/Lang/PARI-GP/Rhonda-numbers new file mode 120000 index 0000000000..d7d56fca21 --- /dev/null +++ b/Lang/PARI-GP/Rhonda-numbers @@ -0,0 +1 @@ +../../Task/Rhonda-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Tau-number b/Lang/PARI-GP/Tau-number new file mode 120000 index 0000000000..5b5ff3f6d3 --- /dev/null +++ b/Lang/PARI-GP/Tau-number @@ -0,0 +1 @@ +../../Task/Tau-number/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Yellowstone-sequence b/Lang/PARI-GP/Yellowstone-sequence new file mode 120000 index 0000000000..a7645262be --- /dev/null +++ b/Lang/PARI-GP/Yellowstone-sequence @@ -0,0 +1 @@ +../../Task/Yellowstone-sequence/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Zumkeller-numbers b/Lang/PARI-GP/Zumkeller-numbers new file mode 120000 index 0000000000..8e9fc8c2bd --- /dev/null +++ b/Lang/PARI-GP/Zumkeller-numbers @@ -0,0 +1 @@ +../../Task/Zumkeller-numbers/PARI-GP \ No newline at end of file diff --git a/Lang/PL-M/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/PL-M/Minimum-multiple-of-m-where-digital-sum-equals-m new file mode 120000 index 0000000000..ef707e8c5a --- /dev/null +++ b/Lang/PL-M/Minimum-multiple-of-m-where-digital-sum-equals-m @@ -0,0 +1 @@ +../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Narcissistic-decimal-number b/Lang/PL-M/Narcissistic-decimal-number new file mode 120000 index 0000000000..5a762f85d9 --- /dev/null +++ b/Lang/PL-M/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/PL-M \ No newline at end of file diff --git a/Lang/ParaCL/00-LANG.txt b/Lang/ParaCL/00-LANG.txt new file mode 100644 index 0000000000..0711f454ed --- /dev/null +++ b/Lang/ParaCL/00-LANG.txt @@ -0,0 +1 @@ +{{stub}}{{language|ParaCL}} \ No newline at end of file diff --git a/Lang/ParaCL/00-META.yaml b/Lang/ParaCL/00-META.yaml new file mode 100644 index 0000000000..ff70e57502 --- /dev/null +++ b/Lang/ParaCL/00-META.yaml @@ -0,0 +1,2 @@ +--- +from: http://rosettacode.org/wiki/Category:ParaCL diff --git a/Lang/ParaCL/Fibonacci-sequence b/Lang/ParaCL/Fibonacci-sequence new file mode 120000 index 0000000000..89eadc9ef4 --- /dev/null +++ b/Lang/ParaCL/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/ParaCL \ No newline at end of file diff --git a/Lang/Phix/00-LANG.txt b/Lang/Phix/00-LANG.txt index 18c8f9c2a5..cbc88ce28e 100644 --- a/Lang/Phix/00-LANG.txt +++ b/Lang/Phix/00-LANG.txt @@ -14,12 +14,12 @@ Phix is a self-hosted hybrid interpreter/compiler, developed by Pete Lomax. It is very easy to use, and similar to [https://rosettacode.org/wiki/Category:Euphoria Euphoria]. -On [https://rosettacode.org/w/index.php?title=Rosetta_Code%2FRank_languages_by_popularity%2FFull_list&type=revision&diff=282496&oldid=282495 26th December 2021, Phix became the first programming language on this site to have submissions for 100% of all tasks].
-(On 20th June 2022 [[Wren]] became the second, albeit with [https://www.rosettacode.org/wiki/Category:WrenGo 13]+[https://www.rosettacode.org/mw/index.php?title=Special%3ASearch&search=wren.h&go=Go 63] of those embedded that I, for one, have been unable to run.) +On [https://rosettacode.org/wiki/Rosetta_Code/Rank_languages_by_popularity/Full_list?oldid=294533 26th December 2021, Phix became the first programming language on this site to have submissions for 100% of all tasks].
+(On 20th June 2022 [[Wren]] became the second, albeit with [https://www.rosettacode.org/wiki/Category:WrenGo 13]+[https://rosettacode.org/wiki/Special:Search?search=wren.h&wprov=acrw1_-1 66] of those embedded that I, for one, have been unable to run.) [http://phix.x10.mx/download.php A simple 30MB download] contains a pre-compiled executable, all the sources, and'' '''everything''' ''needed to recompile them, in under 20 seconds. The download also contains a full-featured programmer's editor and about 1000 demo programs. -You can also [https://replit.com/@PeteLomax1/PhixInterpreter#main.sh run Phix on replit here], and several manually transpiled and uploaded entries [https://rosettacode.org/wiki/Category:Phix/online here] +You can also [https://replit.com/@PeteLomax1/PhixInterpreter#main.sh run Phix on replit here] (1.0.3 Lnx 64 bit), and several manually transpiled and uploaded entries [https://rosettacode.org/wiki/Category:Phix/online here] Perhaps the most striking feature of Phix is that it has just five builtin data types:
@@ -39,7 +39,7 @@ Technically Phix does not have a garbage collector, instead it is reference coun
 
 The fundamental goal of Phix is to make debugging easier, a whole subject area that does not seem to get the attention it deserves, despite several studies finding that most programmers actually spend between 70 and 90% of their time debugging. Most of us tend to think that getting just-written code to work is somehow not debugging, but that clipboard-toting researcher stood behind you would disagree.
 
-Since 1.0.0 you can also run (many/most) Phix programs in a browser, by using pwa/p2js (as included in the distro) to transpile the program to JavaScript (plus a bit of standard HTML and CSS). If you see "'''with javascript_semantics'''" it means the program has been tested and works fine, both on the (Windows/Linux) desktop/Phix and in a browser via pwa/p2js, and in fact unix_dict() has been added to avoid reading unixdict.txt. Conversely, "without js" being present on a rosettacode entry means that (for instance) it uses the local file system, and is therefore desktop/Phix only. It is worth pointing out that "with js" and deep_copy() have proved ''staggeringly'' effective and nowhere near as painful as first feared. In just a few months (1.0.0 was released in July 2021) I have tested, fixed where necessary, and marked as javascript compatible (Sorry, both links borken since move to WikiTide) ''[https://rosettacode.org/w/index.php?search=phixonline&title=Special%3ASearch&wprov=acrw1 over 1,200 rosettacode entries]'' for Phix, and only ''[https://rosettacode.org/w/index.php?search=notonline&title=Special%3ASearch&wprov=acrw1 one seventh]'' of that have as yet been marked incompatible, despite things like file i/o being prohibited within a web browser. The [https://rosettacode.org/wiki/Category:Phix/online Phix/online] subcategory currently lists 99 entries deemed interesting enough to bother (manually) uploading to the Phix website (ping me should any stop working), and the next goal is to get pwa/p2js itself runnning online, but obviously without using file i/o directly. Another long term goal is to get Phix running on ARM, and since that would be utterly pointless without a viable GUI, I am currently elbow deep in writing a new cross-platform GUI, as a stepping stone (for both ARM and p2js/online).
+Since 1.0.0 you can also run (many/most) Phix programs in a browser, by using pwa/p2js (as included in the distro) to transpile the program to JavaScript (plus a bit of standard HTML and CSS). If you see "'''with javascript_semantics'''" it means the program has been tested and works fine, both on the (Windows/Linux) desktop/Phix and in a browser via pwa/p2js, and in fact unix_dict() has been added to avoid reading unixdict.txt. Conversely, "without js" being present on a rosettacode entry means that (for instance) it uses the local file system, and is therefore desktop/Phix only. It is worth pointing out that "with js" and deep_copy() have proved ''staggeringly'' effective and nowhere near as painful as first feared. In just a few months (1.0.0 was released in July 2021) I have tested, fixed where necessary, and marked as javascript compatible ''[https://rosettacode.org/w/index.php?search=phixonline&title=Special%3ASearch&wprov=acrw1 over 1,200 rosettacode entries]'' for Phix, and only ''[https://rosettacode.org/w/index.php?search=notonline&title=Special%3ASearch&wprov=acrw1 one seventh]'' of that have as yet been marked incompatible, despite things like file i/o being prohibited within a web browser. The [https://rosettacode.org/wiki/Category:Phix/online Phix/online] subcategory currently lists 99 entries deemed interesting enough to bother (manually) uploading to the Phix website (ping me should any stop working), and the next goal is to get pwa/p2js itself runnning online, but obviously without using file i/o directly. Another long term goal is to get Phix running on ARM, and since that would be utterly pointless without a viable GUI, I am currently elbow deep in writing a new cross-platform GUI, as a stepping stone (for both ARM and p2js/online).
 
 ==See also==
 * [http://phix.x10.mx Phix site]
diff --git a/Lang/PowerPC-Assembly/Greatest-common-divisor b/Lang/PowerPC-Assembly/Greatest-common-divisor
new file mode 120000
index 0000000000..630e6db921
--- /dev/null
+++ b/Lang/PowerPC-Assembly/Greatest-common-divisor
@@ -0,0 +1 @@
+../../Task/Greatest-common-divisor/PowerPC-Assembly
\ No newline at end of file
diff --git a/Lang/Prog8/00-LANG.txt b/Lang/Prog8/00-LANG.txt
new file mode 100644
index 0000000000..1d713f3af5
--- /dev/null
+++ b/Lang/Prog8/00-LANG.txt
@@ -0,0 +1,11 @@
+{{language
+|exec=compiled
+|tags=prog8
+}}
+'''Prog8''' is a modern compiled programming language targeting computers based on the MOS 6502 family of CPUs. The compiler and standard library have support for the Atari 8-bit family (6502), Commodore 64 (6510) and 128 (8502), and the Commander X-16 (65c02). It's a relatively low-level language in the same niche as C, but specifically designed for the 8-bit architecture of its target systems. 
+
+==Links==
+* [https://prog8.readthedocs.io Documentation]
+* [https://github.com/irmen/prog8 Github source] 
+
+{{language programming paradigm|Procedural}}
\ No newline at end of file
diff --git a/Lang/Prog8/00-META.yaml b/Lang/Prog8/00-META.yaml
new file mode 100644
index 0000000000..288f396ee5
--- /dev/null
+++ b/Lang/Prog8/00-META.yaml
@@ -0,0 +1,2 @@
+---
+from: http://rosettacode.org/wiki/Category:Prog8
diff --git a/Lang/Prog8/The-Twelve-Days-of-Christmas b/Lang/Prog8/The-Twelve-Days-of-Christmas
new file mode 120000
index 0000000000..358b85327a
--- /dev/null
+++ b/Lang/Prog8/The-Twelve-Days-of-Christmas
@@ -0,0 +1 @@
+../../Task/The-Twelve-Days-of-Christmas/Prog8
\ No newline at end of file
diff --git a/Lang/Prolog/Generate-Chess960-starting-position b/Lang/Prolog/Generate-Chess960-starting-position
new file mode 120000
index 0000000000..7c664672ab
--- /dev/null
+++ b/Lang/Prolog/Generate-Chess960-starting-position
@@ -0,0 +1 @@
+../../Task/Generate-Chess960-starting-position/Prolog
\ No newline at end of file
diff --git a/Lang/PureBasic/Sphenic-numbers b/Lang/PureBasic/Sphenic-numbers
new file mode 120000
index 0000000000..5ff07480cd
--- /dev/null
+++ b/Lang/PureBasic/Sphenic-numbers
@@ -0,0 +1 @@
+../../Task/Sphenic-numbers/PureBasic
\ No newline at end of file
diff --git a/Lang/Python/Equal-prime-and-composite-sums b/Lang/Python/Equal-prime-and-composite-sums
new file mode 120000
index 0000000000..85cb0d4944
--- /dev/null
+++ b/Lang/Python/Equal-prime-and-composite-sums
@@ -0,0 +1 @@
+../../Task/Equal-prime-and-composite-sums/Python
\ No newline at end of file
diff --git a/Lang/Python/Erd-s-Nicolas-numbers b/Lang/Python/Erd-s-Nicolas-numbers
new file mode 120000
index 0000000000..c04d09ae0e
--- /dev/null
+++ b/Lang/Python/Erd-s-Nicolas-numbers
@@ -0,0 +1 @@
+../../Task/Erd-s-Nicolas-numbers/Python
\ No newline at end of file
diff --git a/Lang/Python/Jordan-P-lya-numbers b/Lang/Python/Jordan-P-lya-numbers
new file mode 120000
index 0000000000..72646172bd
--- /dev/null
+++ b/Lang/Python/Jordan-P-lya-numbers
@@ -0,0 +1 @@
+../../Task/Jordan-P-lya-numbers/Python
\ No newline at end of file
diff --git a/Lang/Python/Pell-numbers b/Lang/Python/Pell-numbers
new file mode 120000
index 0000000000..445be304a8
--- /dev/null
+++ b/Lang/Python/Pell-numbers
@@ -0,0 +1 @@
+../../Task/Pell-numbers/Python
\ No newline at end of file
diff --git a/Lang/Python/Transliterate-English-text-using-the-Greek-alphabet b/Lang/Python/Transliterate-English-text-using-the-Greek-alphabet
new file mode 120000
index 0000000000..ca70885140
--- /dev/null
+++ b/Lang/Python/Transliterate-English-text-using-the-Greek-alphabet
@@ -0,0 +1 @@
+../../Task/Transliterate-English-text-using-the-Greek-alphabet/Python
\ No newline at end of file
diff --git a/Lang/QuickBASIC/Reverse-a-string b/Lang/QuickBASIC/Reverse-a-string
new file mode 120000
index 0000000000..69b812ff8f
--- /dev/null
+++ b/Lang/QuickBASIC/Reverse-a-string
@@ -0,0 +1 @@
+../../Task/Reverse-a-string/QuickBASIC
\ No newline at end of file
diff --git a/Lang/R/9-billion-names-of-God-the-integer b/Lang/R/9-billion-names-of-God-the-integer
new file mode 120000
index 0000000000..5514828236
--- /dev/null
+++ b/Lang/R/9-billion-names-of-God-the-integer
@@ -0,0 +1 @@
+../../Task/9-billion-names-of-God-the-integer/R
\ No newline at end of file
diff --git a/Lang/R/Padovan-sequence b/Lang/R/Padovan-sequence
new file mode 120000
index 0000000000..cd4a17c5b4
--- /dev/null
+++ b/Lang/R/Padovan-sequence
@@ -0,0 +1 @@
+../../Task/Padovan-sequence/R
\ No newline at end of file
diff --git a/Lang/RATFOR/Fibonacci-sequence b/Lang/RATFOR/Fibonacci-sequence
new file mode 120000
index 0000000000..5d5e412db3
--- /dev/null
+++ b/Lang/RATFOR/Fibonacci-sequence
@@ -0,0 +1 @@
+../../Task/Fibonacci-sequence/RATFOR
\ No newline at end of file
diff --git a/Lang/RPL/Averages-Arithmetic-mean b/Lang/RPL/Averages-Arithmetic-mean
deleted file mode 120000
index 44479b0504..0000000000
--- a/Lang/RPL/Averages-Arithmetic-mean
+++ /dev/null
@@ -1 +0,0 @@
-../../Task/Averages-Arithmetic-mean/RPL
\ No newline at end of file
diff --git a/Lang/Refal/100-doors b/Lang/Refal/100-doors
new file mode 120000
index 0000000000..b42ae17bb5
--- /dev/null
+++ b/Lang/Refal/100-doors
@@ -0,0 +1 @@
+../../Task/100-doors/Refal
\ No newline at end of file
diff --git a/Lang/Refal/99-bottles-of-beer b/Lang/Refal/99-bottles-of-beer
new file mode 120000
index 0000000000..2ee58c482a
--- /dev/null
+++ b/Lang/Refal/99-bottles-of-beer
@@ -0,0 +1 @@
+../../Task/99-bottles-of-beer/Refal
\ No newline at end of file
diff --git a/Lang/Refal/ABC-problem b/Lang/Refal/ABC-problem
new file mode 120000
index 0000000000..147e0c9c08
--- /dev/null
+++ b/Lang/Refal/ABC-problem
@@ -0,0 +1 @@
+../../Task/ABC-problem/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Ackermann-function b/Lang/Refal/Ackermann-function
new file mode 120000
index 0000000000..b15c3eabf7
--- /dev/null
+++ b/Lang/Refal/Ackermann-function
@@ -0,0 +1 @@
+../../Task/Ackermann-function/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Binary-digits b/Lang/Refal/Binary-digits
new file mode 120000
index 0000000000..671ac48fe5
--- /dev/null
+++ b/Lang/Refal/Binary-digits
@@ -0,0 +1 @@
+../../Task/Binary-digits/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Catamorphism b/Lang/Refal/Catamorphism
new file mode 120000
index 0000000000..dd93ebc37a
--- /dev/null
+++ b/Lang/Refal/Catamorphism
@@ -0,0 +1 @@
+../../Task/Catamorphism/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Comma-quibbling b/Lang/Refal/Comma-quibbling
new file mode 120000
index 0000000000..e0a180f35a
--- /dev/null
+++ b/Lang/Refal/Comma-quibbling
@@ -0,0 +1 @@
+../../Task/Comma-quibbling/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Count-in-factors b/Lang/Refal/Count-in-factors
new file mode 120000
index 0000000000..8f09f07e9c
--- /dev/null
+++ b/Lang/Refal/Count-in-factors
@@ -0,0 +1 @@
+../../Task/Count-in-factors/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Count-occurrences-of-a-substring b/Lang/Refal/Count-occurrences-of-a-substring
new file mode 120000
index 0000000000..3ee1567368
--- /dev/null
+++ b/Lang/Refal/Count-occurrences-of-a-substring
@@ -0,0 +1 @@
+../../Task/Count-occurrences-of-a-substring/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Determine-if-a-string-is-collapsible b/Lang/Refal/Determine-if-a-string-is-collapsible
new file mode 120000
index 0000000000..93d8d21f97
--- /dev/null
+++ b/Lang/Refal/Determine-if-a-string-is-collapsible
@@ -0,0 +1 @@
+../../Task/Determine-if-a-string-is-collapsible/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Execute-Brain- b/Lang/Refal/Execute-Brain-
new file mode 120000
index 0000000000..b2a669e873
--- /dev/null
+++ b/Lang/Refal/Execute-Brain-
@@ -0,0 +1 @@
+../../Task/Execute-Brain-/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Execute-a-Markov-algorithm b/Lang/Refal/Execute-a-Markov-algorithm
new file mode 120000
index 0000000000..1c5c0f5111
--- /dev/null
+++ b/Lang/Refal/Execute-a-Markov-algorithm
@@ -0,0 +1 @@
+../../Task/Execute-a-Markov-algorithm/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Factorial b/Lang/Refal/Factorial
new file mode 120000
index 0000000000..0fea43897c
--- /dev/null
+++ b/Lang/Refal/Factorial
@@ -0,0 +1 @@
+../../Task/Factorial/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Fibonacci-sequence b/Lang/Refal/Fibonacci-sequence
new file mode 120000
index 0000000000..ef7f1ccdd3
--- /dev/null
+++ b/Lang/Refal/Fibonacci-sequence
@@ -0,0 +1 @@
+../../Task/Fibonacci-sequence/Refal
\ No newline at end of file
diff --git a/Lang/Refal/FizzBuzz b/Lang/Refal/FizzBuzz
new file mode 120000
index 0000000000..dc9c8c4e2c
--- /dev/null
+++ b/Lang/Refal/FizzBuzz
@@ -0,0 +1 @@
+../../Task/FizzBuzz/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Greatest-common-divisor b/Lang/Refal/Greatest-common-divisor
new file mode 120000
index 0000000000..4c2254b5ab
--- /dev/null
+++ b/Lang/Refal/Greatest-common-divisor
@@ -0,0 +1 @@
+../../Task/Greatest-common-divisor/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Hailstone-sequence b/Lang/Refal/Hailstone-sequence
new file mode 120000
index 0000000000..3262ce3df7
--- /dev/null
+++ b/Lang/Refal/Hailstone-sequence
@@ -0,0 +1 @@
+../../Task/Hailstone-sequence/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Happy-numbers b/Lang/Refal/Happy-numbers
new file mode 120000
index 0000000000..16f1b20516
--- /dev/null
+++ b/Lang/Refal/Happy-numbers
@@ -0,0 +1 @@
+../../Task/Happy-numbers/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Harshad-or-Niven-series b/Lang/Refal/Harshad-or-Niven-series
new file mode 120000
index 0000000000..da848d997c
--- /dev/null
+++ b/Lang/Refal/Harshad-or-Niven-series
@@ -0,0 +1 @@
+../../Task/Harshad-or-Niven-series/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Hello-world-Text b/Lang/Refal/Hello-world-Text
new file mode 120000
index 0000000000..3c67e6fb12
--- /dev/null
+++ b/Lang/Refal/Hello-world-Text
@@ -0,0 +1 @@
+../../Task/Hello-world-Text/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Jewels-and-stones b/Lang/Refal/Jewels-and-stones
new file mode 120000
index 0000000000..d8c63e5bb3
--- /dev/null
+++ b/Lang/Refal/Jewels-and-stones
@@ -0,0 +1 @@
+../../Task/Jewels-and-stones/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Levenshtein-distance b/Lang/Refal/Levenshtein-distance
new file mode 120000
index 0000000000..dffc24ebd3
--- /dev/null
+++ b/Lang/Refal/Levenshtein-distance
@@ -0,0 +1 @@
+../../Task/Levenshtein-distance/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Longest-common-substring b/Lang/Refal/Longest-common-substring
new file mode 120000
index 0000000000..2c12f47190
--- /dev/null
+++ b/Lang/Refal/Longest-common-substring
@@ -0,0 +1 @@
+../../Task/Longest-common-substring/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Look-and-say-sequence b/Lang/Refal/Look-and-say-sequence
new file mode 120000
index 0000000000..31bd518515
--- /dev/null
+++ b/Lang/Refal/Look-and-say-sequence
@@ -0,0 +1 @@
+../../Task/Look-and-say-sequence/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Luhn-test-of-credit-card-numbers b/Lang/Refal/Luhn-test-of-credit-card-numbers
new file mode 120000
index 0000000000..4caee7398b
--- /dev/null
+++ b/Lang/Refal/Luhn-test-of-credit-card-numbers
@@ -0,0 +1 @@
+../../Task/Luhn-test-of-credit-card-numbers/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Minimum-multiple-of-m-where-digital-sum-equals-m b/Lang/Refal/Minimum-multiple-of-m-where-digital-sum-equals-m
new file mode 120000
index 0000000000..8eb3682d6d
--- /dev/null
+++ b/Lang/Refal/Minimum-multiple-of-m-where-digital-sum-equals-m
@@ -0,0 +1 @@
+../../Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Mutual-recursion b/Lang/Refal/Mutual-recursion
new file mode 120000
index 0000000000..6f6c869fc0
--- /dev/null
+++ b/Lang/Refal/Mutual-recursion
@@ -0,0 +1 @@
+../../Task/Mutual-recursion/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Phrase-reversals b/Lang/Refal/Phrase-reversals
new file mode 120000
index 0000000000..1ba657880f
--- /dev/null
+++ b/Lang/Refal/Phrase-reversals
@@ -0,0 +1 @@
+../../Task/Phrase-reversals/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Primality-by-Wilsons-theorem b/Lang/Refal/Primality-by-Wilsons-theorem
new file mode 120000
index 0000000000..c38ba6debb
--- /dev/null
+++ b/Lang/Refal/Primality-by-Wilsons-theorem
@@ -0,0 +1 @@
+../../Task/Primality-by-Wilsons-theorem/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Rep-string b/Lang/Refal/Rep-string
new file mode 120000
index 0000000000..07bd8a4a37
--- /dev/null
+++ b/Lang/Refal/Rep-string
@@ -0,0 +1 @@
+../../Task/Rep-string/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Reverse-a-string b/Lang/Refal/Reverse-a-string
new file mode 120000
index 0000000000..32d7c21312
--- /dev/null
+++ b/Lang/Refal/Reverse-a-string
@@ -0,0 +1 @@
+../../Task/Reverse-a-string/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Roman-numerals-Decode b/Lang/Refal/Roman-numerals-Decode
new file mode 120000
index 0000000000..a0cf44e107
--- /dev/null
+++ b/Lang/Refal/Roman-numerals-Decode
@@ -0,0 +1 @@
+../../Task/Roman-numerals-Decode/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Sieve-of-Eratosthenes b/Lang/Refal/Sieve-of-Eratosthenes
new file mode 120000
index 0000000000..c82f28137f
--- /dev/null
+++ b/Lang/Refal/Sieve-of-Eratosthenes
@@ -0,0 +1 @@
+../../Task/Sieve-of-Eratosthenes/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Sorting-algorithms-Insertion-sort b/Lang/Refal/Sorting-algorithms-Insertion-sort
new file mode 120000
index 0000000000..55abe9cc64
--- /dev/null
+++ b/Lang/Refal/Sorting-algorithms-Insertion-sort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Insertion-sort/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Sorting-algorithms-Merge-sort b/Lang/Refal/Sorting-algorithms-Merge-sort
new file mode 120000
index 0000000000..9375e30960
--- /dev/null
+++ b/Lang/Refal/Sorting-algorithms-Merge-sort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Merge-sort/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Sorting-algorithms-Quicksort b/Lang/Refal/Sorting-algorithms-Quicksort
new file mode 120000
index 0000000000..9251c355c6
--- /dev/null
+++ b/Lang/Refal/Sorting-algorithms-Quicksort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Quicksort/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Stern-Brocot-sequence b/Lang/Refal/Stern-Brocot-sequence
new file mode 120000
index 0000000000..0b56a77639
--- /dev/null
+++ b/Lang/Refal/Stern-Brocot-sequence
@@ -0,0 +1 @@
+../../Task/Stern-Brocot-sequence/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Sum-of-squares b/Lang/Refal/Sum-of-squares
new file mode 120000
index 0000000000..171c9074d7
--- /dev/null
+++ b/Lang/Refal/Sum-of-squares
@@ -0,0 +1 @@
+../../Task/Sum-of-squares/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Symmetric-difference b/Lang/Refal/Symmetric-difference
new file mode 120000
index 0000000000..e1a4a3e3a0
--- /dev/null
+++ b/Lang/Refal/Symmetric-difference
@@ -0,0 +1 @@
+../../Task/Symmetric-difference/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Thue-Morse b/Lang/Refal/Thue-Morse
new file mode 120000
index 0000000000..f4e3ddd3b0
--- /dev/null
+++ b/Lang/Refal/Thue-Morse
@@ -0,0 +1 @@
+../../Task/Thue-Morse/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Towers-of-Hanoi b/Lang/Refal/Towers-of-Hanoi
new file mode 120000
index 0000000000..8fe4b6b370
--- /dev/null
+++ b/Lang/Refal/Towers-of-Hanoi
@@ -0,0 +1 @@
+../../Task/Towers-of-Hanoi/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Tree-traversal b/Lang/Refal/Tree-traversal
new file mode 120000
index 0000000000..9d83db52d1
--- /dev/null
+++ b/Lang/Refal/Tree-traversal
@@ -0,0 +1 @@
+../../Task/Tree-traversal/Refal
\ No newline at end of file
diff --git a/Lang/Refal/Van-Eck-sequence b/Lang/Refal/Van-Eck-sequence
new file mode 120000
index 0000000000..e8b3b8d52a
--- /dev/null
+++ b/Lang/Refal/Van-Eck-sequence
@@ -0,0 +1 @@
+../../Task/Van-Eck-sequence/Refal
\ No newline at end of file
diff --git a/Lang/Roc/00-LANG.txt b/Lang/Roc/00-LANG.txt
new file mode 100644
index 0000000000..ffdb69b5dd
--- /dev/null
+++ b/Lang/Roc/00-LANG.txt
@@ -0,0 +1,9 @@
+{{stub}}
+{{language|Roc|site=https://www.roc-lang.org|tags=roc}}
+{{Language programming paradigm|Functional}}
+
+Roc code is designed to build fast and run fast. It compiles to machine code or WebAssembly.
+
+Roc's syntax, semantics, and included toolset all prioritize user-friendliness.
+
+Roc has a small number of simple language primitives. It's a single-paradigm functional language.
\ No newline at end of file
diff --git a/Lang/Roc/00-META.yaml b/Lang/Roc/00-META.yaml
new file mode 100644
index 0000000000..53c6cdad21
--- /dev/null
+++ b/Lang/Roc/00-META.yaml
@@ -0,0 +1,2 @@
+---
+from: http://rosettacode.org/wiki/Category:Roc
diff --git a/Lang/Roc/Binary-digits b/Lang/Roc/Binary-digits
new file mode 120000
index 0000000000..da521e90f1
--- /dev/null
+++ b/Lang/Roc/Binary-digits
@@ -0,0 +1 @@
+../../Task/Binary-digits/Roc
\ No newline at end of file
diff --git a/Lang/Roc/Hello-world-Text b/Lang/Roc/Hello-world-Text
new file mode 120000
index 0000000000..40fe742e73
--- /dev/null
+++ b/Lang/Roc/Hello-world-Text
@@ -0,0 +1 @@
+../../Task/Hello-world-Text/Roc
\ No newline at end of file
diff --git a/Lang/Rust/Chowla-numbers b/Lang/Rust/Chowla-numbers
new file mode 120000
index 0000000000..73e1040f4e
--- /dev/null
+++ b/Lang/Rust/Chowla-numbers
@@ -0,0 +1 @@
+../../Task/Chowla-numbers/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Eertree b/Lang/Rust/Eertree
new file mode 120000
index 0000000000..80293e575c
--- /dev/null
+++ b/Lang/Rust/Eertree
@@ -0,0 +1 @@
+../../Task/Eertree/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Gamma-function b/Lang/Rust/Gamma-function
new file mode 120000
index 0000000000..f400cc415c
--- /dev/null
+++ b/Lang/Rust/Gamma-function
@@ -0,0 +1 @@
+../../Task/Gamma-function/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Introspection b/Lang/Rust/Introspection
new file mode 120000
index 0000000000..31d728e58c
--- /dev/null
+++ b/Lang/Rust/Introspection
@@ -0,0 +1 @@
+../../Task/Introspection/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Jordan-P-lya-numbers b/Lang/Rust/Jordan-P-lya-numbers
new file mode 120000
index 0000000000..498a0c552f
--- /dev/null
+++ b/Lang/Rust/Jordan-P-lya-numbers
@@ -0,0 +1 @@
+../../Task/Jordan-P-lya-numbers/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Pancake-numbers b/Lang/Rust/Pancake-numbers
new file mode 120000
index 0000000000..ef65209521
--- /dev/null
+++ b/Lang/Rust/Pancake-numbers
@@ -0,0 +1 @@
+../../Task/Pancake-numbers/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Pseudo-random-numbers-PCG32 b/Lang/Rust/Pseudo-random-numbers-PCG32
new file mode 120000
index 0000000000..ea0c68c73c
--- /dev/null
+++ b/Lang/Rust/Pseudo-random-numbers-PCG32
@@ -0,0 +1 @@
+../../Task/Pseudo-random-numbers-PCG32/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Pseudo-random-numbers-Xorshift-star b/Lang/Rust/Pseudo-random-numbers-Xorshift-star
new file mode 120000
index 0000000000..02667e7c55
--- /dev/null
+++ b/Lang/Rust/Pseudo-random-numbers-Xorshift-star
@@ -0,0 +1 @@
+../../Task/Pseudo-random-numbers-Xorshift-star/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Zeckendorf-arithmetic b/Lang/Rust/Zeckendorf-arithmetic
new file mode 120000
index 0000000000..fa9675f521
--- /dev/null
+++ b/Lang/Rust/Zeckendorf-arithmetic
@@ -0,0 +1 @@
+../../Task/Zeckendorf-arithmetic/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Zeckendorf-number-representation b/Lang/Rust/Zeckendorf-number-representation
new file mode 120000
index 0000000000..d6de4a899a
--- /dev/null
+++ b/Lang/Rust/Zeckendorf-number-representation
@@ -0,0 +1 @@
+../../Task/Zeckendorf-number-representation/Rust
\ No newline at end of file
diff --git a/Lang/S-BASIC/Bitwise-operations b/Lang/S-BASIC/Bitwise-operations
new file mode 120000
index 0000000000..08dd8f5cef
--- /dev/null
+++ b/Lang/S-BASIC/Bitwise-operations
@@ -0,0 +1 @@
+../../Task/Bitwise-operations/S-BASIC
\ No newline at end of file
diff --git a/Lang/S-BASIC/Strip-a-set-of-characters-from-a-string b/Lang/S-BASIC/Strip-a-set-of-characters-from-a-string
new file mode 120000
index 0000000000..3f36145b0a
--- /dev/null
+++ b/Lang/S-BASIC/Strip-a-set-of-characters-from-a-string
@@ -0,0 +1 @@
+../../Task/Strip-a-set-of-characters-from-a-string/S-BASIC
\ No newline at end of file
diff --git a/Lang/SETL/ABC-problem b/Lang/SETL/ABC-problem
new file mode 120000
index 0000000000..c18b2914bb
--- /dev/null
+++ b/Lang/SETL/ABC-problem
@@ -0,0 +1 @@
+../../Task/ABC-problem/SETL
\ No newline at end of file
diff --git a/Lang/SETL/Narcissistic-decimal-number b/Lang/SETL/Narcissistic-decimal-number
new file mode 120000
index 0000000000..d2b692567b
--- /dev/null
+++ b/Lang/SETL/Narcissistic-decimal-number
@@ -0,0 +1 @@
+../../Task/Narcissistic-decimal-number/SETL
\ No newline at end of file
diff --git a/Lang/SETL/Primality-by-Wilsons-theorem b/Lang/SETL/Primality-by-Wilsons-theorem
new file mode 120000
index 0000000000..0c948a95c3
--- /dev/null
+++ b/Lang/SETL/Primality-by-Wilsons-theorem
@@ -0,0 +1 @@
+../../Task/Primality-by-Wilsons-theorem/SETL
\ No newline at end of file
diff --git a/Lang/SETL/Stern-Brocot-sequence b/Lang/SETL/Stern-Brocot-sequence
new file mode 120000
index 0000000000..ed3c987e48
--- /dev/null
+++ b/Lang/SETL/Stern-Brocot-sequence
@@ -0,0 +1 @@
+../../Task/Stern-Brocot-sequence/SETL
\ No newline at end of file
diff --git a/Lang/SETL/Sum-of-a-series b/Lang/SETL/Sum-of-a-series
new file mode 120000
index 0000000000..7a9118efe1
--- /dev/null
+++ b/Lang/SETL/Sum-of-a-series
@@ -0,0 +1 @@
+../../Task/Sum-of-a-series/SETL
\ No newline at end of file
diff --git a/Lang/Sage/Amicable-pairs b/Lang/Sage/Amicable-pairs
new file mode 120000
index 0000000000..c06c543646
--- /dev/null
+++ b/Lang/Sage/Amicable-pairs
@@ -0,0 +1 @@
+../../Task/Amicable-pairs/Sage
\ No newline at end of file
diff --git a/Lang/Scala/Almkvist-Giullera-formula-for-pi b/Lang/Scala/Almkvist-Giullera-formula-for-pi
new file mode 120000
index 0000000000..4d4df47135
--- /dev/null
+++ b/Lang/Scala/Almkvist-Giullera-formula-for-pi
@@ -0,0 +1 @@
+../../Task/Almkvist-Giullera-formula-for-pi/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Arithmetic-derivative b/Lang/Scala/Arithmetic-derivative
new file mode 120000
index 0000000000..f28c4f2425
--- /dev/null
+++ b/Lang/Scala/Arithmetic-derivative
@@ -0,0 +1 @@
+../../Task/Arithmetic-derivative/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Arithmetic-numbers b/Lang/Scala/Arithmetic-numbers
new file mode 120000
index 0000000000..3d59c01a8c
--- /dev/null
+++ b/Lang/Scala/Arithmetic-numbers
@@ -0,0 +1 @@
+../../Task/Arithmetic-numbers/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Bin-given-limits b/Lang/Scala/Bin-given-limits
new file mode 120000
index 0000000000..9debe0aa7f
--- /dev/null
+++ b/Lang/Scala/Bin-given-limits
@@ -0,0 +1 @@
+../../Task/Bin-given-limits/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Biorhythms b/Lang/Scala/Biorhythms
new file mode 120000
index 0000000000..e60407361c
--- /dev/null
+++ b/Lang/Scala/Biorhythms
@@ -0,0 +1 @@
+../../Task/Biorhythms/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Blum-integer b/Lang/Scala/Blum-integer
new file mode 120000
index 0000000000..5a481a686a
--- /dev/null
+++ b/Lang/Scala/Blum-integer
@@ -0,0 +1 @@
+../../Task/Blum-integer/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Camel-case-and-snake-case b/Lang/Scala/Camel-case-and-snake-case
new file mode 120000
index 0000000000..ce7d2434b0
--- /dev/null
+++ b/Lang/Scala/Camel-case-and-snake-case
@@ -0,0 +1 @@
+../../Task/Camel-case-and-snake-case/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Canonicalize-CIDR b/Lang/Scala/Canonicalize-CIDR
new file mode 120000
index 0000000000..f594c73e4d
--- /dev/null
+++ b/Lang/Scala/Canonicalize-CIDR
@@ -0,0 +1 @@
+../../Task/Canonicalize-CIDR/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Church-numerals b/Lang/Scala/Church-numerals
new file mode 120000
index 0000000000..b2182324c0
--- /dev/null
+++ b/Lang/Scala/Church-numerals
@@ -0,0 +1 @@
+../../Task/Church-numerals/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Compare-length-of-two-strings b/Lang/Scala/Compare-length-of-two-strings
new file mode 120000
index 0000000000..dac82e206f
--- /dev/null
+++ b/Lang/Scala/Compare-length-of-two-strings
@@ -0,0 +1 @@
+../../Task/Compare-length-of-two-strings/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Cullen-and-Woodall-numbers b/Lang/Scala/Cullen-and-Woodall-numbers
new file mode 120000
index 0000000000..f8b8f7d073
--- /dev/null
+++ b/Lang/Scala/Cullen-and-Woodall-numbers
@@ -0,0 +1 @@
+../../Task/Cullen-and-Woodall-numbers/Scala
\ No newline at end of file
diff --git a/Lang/Scala/De-Bruijn-sequences b/Lang/Scala/De-Bruijn-sequences
new file mode 120000
index 0000000000..c833bc5131
--- /dev/null
+++ b/Lang/Scala/De-Bruijn-sequences
@@ -0,0 +1 @@
+../../Task/De-Bruijn-sequences/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Demings-funnel b/Lang/Scala/Demings-funnel
new file mode 120000
index 0000000000..64936fefc5
--- /dev/null
+++ b/Lang/Scala/Demings-funnel
@@ -0,0 +1 @@
+../../Task/Demings-funnel/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Doomsday-rule b/Lang/Scala/Doomsday-rule
new file mode 120000
index 0000000000..2d0de21fa5
--- /dev/null
+++ b/Lang/Scala/Doomsday-rule
@@ -0,0 +1 @@
+../../Task/Doomsday-rule/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Eulers-constant-0.5772... b/Lang/Scala/Eulers-constant-0.5772...
new file mode 120000
index 0000000000..0fe8049cca
--- /dev/null
+++ b/Lang/Scala/Eulers-constant-0.5772...
@@ -0,0 +1 @@
+../../Task/Eulers-constant-0.5772.../Scala
\ No newline at end of file
diff --git a/Lang/Scala/Floyd-Warshall-algorithm b/Lang/Scala/Floyd-Warshall-algorithm
new file mode 120000
index 0000000000..ef9de392a8
--- /dev/null
+++ b/Lang/Scala/Floyd-Warshall-algorithm
@@ -0,0 +1 @@
+../../Task/Floyd-Warshall-algorithm/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Gaussian-elimination b/Lang/Scala/Gaussian-elimination
new file mode 120000
index 0000000000..ececfb8068
--- /dev/null
+++ b/Lang/Scala/Gaussian-elimination
@@ -0,0 +1 @@
+../../Task/Gaussian-elimination/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Giuga-numbers b/Lang/Scala/Giuga-numbers
new file mode 120000
index 0000000000..69d4a1842f
--- /dev/null
+++ b/Lang/Scala/Giuga-numbers
@@ -0,0 +1 @@
+../../Task/Giuga-numbers/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Jordan-P-lya-numbers b/Lang/Scala/Jordan-P-lya-numbers
new file mode 120000
index 0000000000..ea8b9ff9a2
--- /dev/null
+++ b/Lang/Scala/Jordan-P-lya-numbers
@@ -0,0 +1 @@
+../../Task/Jordan-P-lya-numbers/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Padovan-sequence b/Lang/Scala/Padovan-sequence
new file mode 120000
index 0000000000..685b3e0f0a
--- /dev/null
+++ b/Lang/Scala/Padovan-sequence
@@ -0,0 +1 @@
+../../Task/Padovan-sequence/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Pancake-numbers b/Lang/Scala/Pancake-numbers
new file mode 120000
index 0000000000..65ed4c5503
--- /dev/null
+++ b/Lang/Scala/Pancake-numbers
@@ -0,0 +1 @@
+../../Task/Pancake-numbers/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Parsing-Shunting-yard-algorithm b/Lang/Scala/Parsing-Shunting-yard-algorithm
new file mode 120000
index 0000000000..84c22e4a24
--- /dev/null
+++ b/Lang/Scala/Parsing-Shunting-yard-algorithm
@@ -0,0 +1 @@
+../../Task/Parsing-Shunting-yard-algorithm/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Primality-by-Wilsons-theorem b/Lang/Scala/Primality-by-Wilsons-theorem
new file mode 120000
index 0000000000..ed0f8a0a73
--- /dev/null
+++ b/Lang/Scala/Primality-by-Wilsons-theorem
@@ -0,0 +1 @@
+../../Task/Primality-by-Wilsons-theorem/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Pseudo-random-numbers-PCG32 b/Lang/Scala/Pseudo-random-numbers-PCG32
new file mode 120000
index 0000000000..ebdb3ee5a4
--- /dev/null
+++ b/Lang/Scala/Pseudo-random-numbers-PCG32
@@ -0,0 +1 @@
+../../Task/Pseudo-random-numbers-PCG32/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Ramanujan-primes-twins b/Lang/Scala/Ramanujan-primes-twins
new file mode 120000
index 0000000000..9565fe8fd6
--- /dev/null
+++ b/Lang/Scala/Ramanujan-primes-twins
@@ -0,0 +1 @@
+../../Task/Ramanujan-primes-twins/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Ramer-Douglas-Peucker-line-simplification b/Lang/Scala/Ramer-Douglas-Peucker-line-simplification
new file mode 120000
index 0000000000..a357270663
--- /dev/null
+++ b/Lang/Scala/Ramer-Douglas-Peucker-line-simplification
@@ -0,0 +1 @@
+../../Task/Ramer-Douglas-Peucker-line-simplification/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Steffensens-method b/Lang/Scala/Steffensens-method
new file mode 120000
index 0000000000..8bb21e2851
--- /dev/null
+++ b/Lang/Scala/Steffensens-method
@@ -0,0 +1 @@
+../../Task/Steffensens-method/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Strassens-algorithm b/Lang/Scala/Strassens-algorithm
new file mode 120000
index 0000000000..075bfeb837
--- /dev/null
+++ b/Lang/Scala/Strassens-algorithm
@@ -0,0 +1 @@
+../../Task/Strassens-algorithm/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Sum-of-elements-below-main-diagonal-of-matrix b/Lang/Scala/Sum-of-elements-below-main-diagonal-of-matrix
new file mode 120000
index 0000000000..b5a437f612
--- /dev/null
+++ b/Lang/Scala/Sum-of-elements-below-main-diagonal-of-matrix
@@ -0,0 +1 @@
+../../Task/Sum-of-elements-below-main-diagonal-of-matrix/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Tau-function b/Lang/Scala/Tau-function
new file mode 120000
index 0000000000..15084d09c1
--- /dev/null
+++ b/Lang/Scala/Tau-function
@@ -0,0 +1 @@
+../../Task/Tau-function/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Yellowstone-sequence b/Lang/Scala/Yellowstone-sequence
new file mode 120000
index 0000000000..2a1f4217a6
--- /dev/null
+++ b/Lang/Scala/Yellowstone-sequence
@@ -0,0 +1 @@
+../../Task/Yellowstone-sequence/Scala
\ No newline at end of file
diff --git a/Lang/Smalltalk/FASTA-format b/Lang/Smalltalk/FASTA-format
new file mode 120000
index 0000000000..083740df9e
--- /dev/null
+++ b/Lang/Smalltalk/FASTA-format
@@ -0,0 +1 @@
+../../Task/FASTA-format/Smalltalk
\ No newline at end of file
diff --git a/Lang/Standard-ML/Evaluate-binomial-coefficients b/Lang/Standard-ML/Evaluate-binomial-coefficients
new file mode 120000
index 0000000000..c57e6c6558
--- /dev/null
+++ b/Lang/Standard-ML/Evaluate-binomial-coefficients
@@ -0,0 +1 @@
+../../Task/Evaluate-binomial-coefficients/Standard-ML
\ No newline at end of file
diff --git a/Lang/Standard-ML/Extreme-floating-point-values b/Lang/Standard-ML/Extreme-floating-point-values
new file mode 120000
index 0000000000..9f4669042a
--- /dev/null
+++ b/Lang/Standard-ML/Extreme-floating-point-values
@@ -0,0 +1 @@
+../../Task/Extreme-floating-point-values/Standard-ML
\ No newline at end of file
diff --git a/Lang/Swift/Abstract-type b/Lang/Swift/Abstract-type
new file mode 120000
index 0000000000..06a9f03e30
--- /dev/null
+++ b/Lang/Swift/Abstract-type
@@ -0,0 +1 @@
+../../Task/Abstract-type/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Append-a-record-to-the-end-of-a-text-file b/Lang/Swift/Append-a-record-to-the-end-of-a-text-file
new file mode 120000
index 0000000000..fd0f9e7cef
--- /dev/null
+++ b/Lang/Swift/Append-a-record-to-the-end-of-a-text-file
@@ -0,0 +1 @@
+../../Task/Append-a-record-to-the-end-of-a-text-file/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Averages-Median b/Lang/Swift/Averages-Median
new file mode 120000
index 0000000000..697fb8b0a6
--- /dev/null
+++ b/Lang/Swift/Averages-Median
@@ -0,0 +1 @@
+../../Task/Averages-Median/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Averages-Pythagorean-means b/Lang/Swift/Averages-Pythagorean-means
new file mode 120000
index 0000000000..028a483c28
--- /dev/null
+++ b/Lang/Swift/Averages-Pythagorean-means
@@ -0,0 +1 @@
+../../Task/Averages-Pythagorean-means/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Base64-decode-data b/Lang/Swift/Base64-decode-data
new file mode 120000
index 0000000000..6d50fcf1a1
--- /dev/null
+++ b/Lang/Swift/Base64-decode-data
@@ -0,0 +1 @@
+../../Task/Base64-decode-data/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Box-the-compass b/Lang/Swift/Box-the-compass
new file mode 120000
index 0000000000..76167bcbd0
--- /dev/null
+++ b/Lang/Swift/Box-the-compass
@@ -0,0 +1 @@
+../../Task/Box-the-compass/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Canonicalize-CIDR b/Lang/Swift/Canonicalize-CIDR
new file mode 120000
index 0000000000..a1566af70e
--- /dev/null
+++ b/Lang/Swift/Canonicalize-CIDR
@@ -0,0 +1 @@
+../../Task/Canonicalize-CIDR/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Check-output-device-is-a-terminal b/Lang/Swift/Check-output-device-is-a-terminal
new file mode 120000
index 0000000000..cd3cd93d22
--- /dev/null
+++ b/Lang/Swift/Check-output-device-is-a-terminal
@@ -0,0 +1 @@
+../../Task/Check-output-device-is-a-terminal/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Jordan-P-lya-numbers b/Lang/Swift/Jordan-P-lya-numbers
new file mode 120000
index 0000000000..df024964bb
--- /dev/null
+++ b/Lang/Swift/Jordan-P-lya-numbers
@@ -0,0 +1 @@
+../../Task/Jordan-P-lya-numbers/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Soloways-recurring-rainfall b/Lang/Swift/Soloways-recurring-rainfall
new file mode 120000
index 0000000000..992f203897
--- /dev/null
+++ b/Lang/Swift/Soloways-recurring-rainfall
@@ -0,0 +1 @@
+../../Task/Soloways-recurring-rainfall/Swift
\ No newline at end of file
diff --git a/Lang/Swift/XML-Input b/Lang/Swift/XML-Input
new file mode 120000
index 0000000000..d7c748b445
--- /dev/null
+++ b/Lang/Swift/XML-Input
@@ -0,0 +1 @@
+../../Task/XML-Input/Swift
\ No newline at end of file
diff --git a/Lang/Tcl/Canonicalize-CIDR b/Lang/Tcl/Canonicalize-CIDR
new file mode 120000
index 0000000000..a6d154c647
--- /dev/null
+++ b/Lang/Tcl/Canonicalize-CIDR
@@ -0,0 +1 @@
+../../Task/Canonicalize-CIDR/Tcl
\ No newline at end of file
diff --git a/Lang/Tcl/Damm-algorithm b/Lang/Tcl/Damm-algorithm
new file mode 120000
index 0000000000..cbcece145d
--- /dev/null
+++ b/Lang/Tcl/Damm-algorithm
@@ -0,0 +1 @@
+../../Task/Damm-algorithm/Tcl
\ No newline at end of file
diff --git a/Lang/Tcl/Padovan-sequence b/Lang/Tcl/Padovan-sequence
new file mode 120000
index 0000000000..554876550e
--- /dev/null
+++ b/Lang/Tcl/Padovan-sequence
@@ -0,0 +1 @@
+../../Task/Padovan-sequence/Tcl
\ No newline at end of file
diff --git a/Lang/Tcl/Pseudo-random-numbers-PCG32 b/Lang/Tcl/Pseudo-random-numbers-PCG32
new file mode 120000
index 0000000000..32494389fe
--- /dev/null
+++ b/Lang/Tcl/Pseudo-random-numbers-PCG32
@@ -0,0 +1 @@
+../../Task/Pseudo-random-numbers-PCG32/Tcl
\ No newline at end of file
diff --git a/Lang/UNIX-Shell/Modified-random-distribution b/Lang/UNIX-Shell/Modified-random-distribution
new file mode 120000
index 0000000000..0682164dd7
--- /dev/null
+++ b/Lang/UNIX-Shell/Modified-random-distribution
@@ -0,0 +1 @@
+../../Task/Modified-random-distribution/UNIX-Shell
\ No newline at end of file
diff --git a/Lang/Uiua/00-LANG.txt b/Lang/Uiua/00-LANG.txt
new file mode 100644
index 0000000000..f1b5a27727
--- /dev/null
+++ b/Lang/Uiua/00-LANG.txt
@@ -0,0 +1 @@
+{{stub}}{{language|Uiua}}
\ No newline at end of file
diff --git a/Lang/Uiua/00-META.yaml b/Lang/Uiua/00-META.yaml
new file mode 100644
index 0000000000..beb4610974
--- /dev/null
+++ b/Lang/Uiua/00-META.yaml
@@ -0,0 +1,2 @@
+---
+from: http://rosettacode.org/wiki/Category:Uiua
diff --git a/Lang/Uiua/Euler-method b/Lang/Uiua/Euler-method
new file mode 120000
index 0000000000..7b2e3712d9
--- /dev/null
+++ b/Lang/Uiua/Euler-method
@@ -0,0 +1 @@
+../../Task/Euler-method/Uiua
\ No newline at end of file
diff --git a/Lang/Uiua/Stack b/Lang/Uiua/Stack
new file mode 120000
index 0000000000..0f1554438f
--- /dev/null
+++ b/Lang/Uiua/Stack
@@ -0,0 +1 @@
+../../Task/Stack/Uiua
\ No newline at end of file
diff --git a/Lang/Uxntal/00-LANG.txt b/Lang/Uxntal/00-LANG.txt
index 362eb3d215..d0204e9b73 100644
--- a/Lang/Uxntal/00-LANG.txt
+++ b/Lang/Uxntal/00-LANG.txt
@@ -8,13 +8,13 @@ The Uxn VM relies on stacks for managing data and control flow. There are two st
 
 For I/O, Uxn features two instructions DEO and DEI, which are used to access a separate block of 256 8-bit registers, split into 16 devices of 16 ports each. The Varvara specification defines a standard set of computing devices, including keyboard, mouse, and controller input, and video + audio outputs.
 
-The 256 opcodes are divided into 8 special instructions, and 31 regular instructions with 3 flags each. The special instructions, which do not accept flags are: BRK (break), JCI, JMI, JSI, (immediate jumps), LIT, LIT2, LITr, LIT2r (integer literals). The flags on the regular instructions are: 2 (short mode), r (use return stack), and k (keep operands). The main instructions include general stack operations, load and store operations, arithmetic operations, and jumps, as well as the two I/O instructions mentioned above.
+The 256 opcodes are divided into 8 special instructions, and 31 regular instructions with 3 flags each. The special instructions, which can't take additional flags are: BRK (break), JCI, JMI, JSI, (immediate jumps), LIT, LIT2, LITr, LIT2r (integer literals). The flags on the regular instructions are: 2 (short mode), r (use return stack), and k (keep operands). The main instructions include general stack operations, load and store operations, arithmetic operations, and jumps, as well as the two I/O instructions mentioned above.
 
 == Syntax ==
 
-Instructions are written in uppercase, followed by any combination of the flags 2kr. Hex values are written with lowercase a-f.
+Instructions are written in uppercase, followed by any combination of the three flags 2kr. Hex values are written with lowercase a-f.
 
-Code can be placed at specific addresses with the | rune, which is especially important for assembling the reset vector at address 0x100 (|0100). Padding can be inserted with the $ rune.
+Code can be placed at specific addresses with the | rune, which is especially important for assembling the reset vector at address 0x100 (|0100) and for defining devices and zero-page variables. Padding can be inserted with the $ rune.
 
 Labels are created with @ and &. The difference is that @ creates a label with the given name, while & creates a sub-label by prefixing the most recent @label and a slash.
 
diff --git a/Lang/Uxntal/99-bottles-of-beer b/Lang/Uxntal/99-bottles-of-beer
new file mode 120000
index 0000000000..89fe8eecd6
--- /dev/null
+++ b/Lang/Uxntal/99-bottles-of-beer
@@ -0,0 +1 @@
+../../Task/99-bottles-of-beer/Uxntal
\ No newline at end of file
diff --git a/Lang/Uxntal/Bitwise-operations b/Lang/Uxntal/Bitwise-operations
new file mode 120000
index 0000000000..41621bed6f
--- /dev/null
+++ b/Lang/Uxntal/Bitwise-operations
@@ -0,0 +1 @@
+../../Task/Bitwise-operations/Uxntal
\ No newline at end of file
diff --git a/Lang/Uxntal/Loops-Infinite b/Lang/Uxntal/Loops-Infinite
new file mode 120000
index 0000000000..d61da1ed4f
--- /dev/null
+++ b/Lang/Uxntal/Loops-Infinite
@@ -0,0 +1 @@
+../../Task/Loops-Infinite/Uxntal
\ No newline at end of file
diff --git a/Lang/Uxntal/Sierpinski-triangle b/Lang/Uxntal/Sierpinski-triangle
new file mode 120000
index 0000000000..0c0c7f90eb
--- /dev/null
+++ b/Lang/Uxntal/Sierpinski-triangle
@@ -0,0 +1 @@
+../../Task/Sierpinski-triangle/Uxntal
\ No newline at end of file
diff --git a/Lang/Uxntal/Towers-of-Hanoi b/Lang/Uxntal/Towers-of-Hanoi
new file mode 120000
index 0000000000..8aab4983ec
--- /dev/null
+++ b/Lang/Uxntal/Towers-of-Hanoi
@@ -0,0 +1 @@
+../../Task/Towers-of-Hanoi/Uxntal
\ No newline at end of file
diff --git a/Lang/Wren/00-LANG.txt b/Lang/Wren/00-LANG.txt
index bea562a4e3..1dbc2e611b 100644
--- a/Lang/Wren/00-LANG.txt
+++ b/Lang/Wren/00-LANG.txt
@@ -15,8 +15,6 @@ It is under development on [https://github.com/wren-lang/wren GitHub] and is ful
 The CLI tool (Wren CLI) has its own repository and is the main focus of examples written for RC.
 The latest version 0.4.0 is available as a pre-built standalone executable for 64-bit Linux, MacOS and Windows and can be downloaded from [https://github.com/wren-lang/wren-cli/releases here].
 
-Following the migration to Miraheze and then WikiTide, RC now uses Pygments (rather than GeSHi) for syntax highlighting and I have written a lexer for Wren which can now be specified instead of 'ecmascipt' which was used previously. The latter was only supported by virtue of a GeSHi mapping to the 'javascript' lexer but it appears that this mapping no longer works and so all tasks/modules will need to be updated to use the 'wren' lexer in due course.
-
 As a language mainly designed for embedding, Wren's standard library is (of necessity) quite small and I have therefore decided to create some additional modules to assist with writing Rosetta Code tasks so the same code does not have to be written or copy/pasted time and time again thereby bloating a task's script code unnecessarily. The ones written so far are listed below:
 
 {| class="wikitable"
@@ -71,7 +69,7 @@ As a language mainly designed for embedding, Wren's standard library is (of nece
 
To use a class or classes from a module (say ''fmt''), you need to import them into your script with Wren code such as the following. To use more than one class separate their names with commas: -import "./fmt" for Conv, Fmt +import "./fmt" for Conv, Fmt These modules are subject to the same license as any other code submitted to Rosetta Code though contributors' user pages should be checked to see whether more permissive terms are available. If anyone wishes to add further modules, please do so using a similar model and append them to the list. diff --git a/Lang/XPL0/24-game b/Lang/XPL0/24-game new file mode 120000 index 0000000000..90030b857d --- /dev/null +++ b/Lang/XPL0/24-game @@ -0,0 +1 @@ +../../Task/24-game/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Arithmetic-derivative b/Lang/XPL0/Arithmetic-derivative new file mode 120000 index 0000000000..5115ecc5f7 --- /dev/null +++ b/Lang/XPL0/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Get-system-command-output b/Lang/XPL0/Get-system-command-output new file mode 120000 index 0000000000..260a4a7590 --- /dev/null +++ b/Lang/XPL0/Get-system-command-output @@ -0,0 +1 @@ +../../Task/Get-system-command-output/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Hash-from-two-arrays b/Lang/XPL0/Hash-from-two-arrays new file mode 120000 index 0000000000..13d72870ed --- /dev/null +++ b/Lang/XPL0/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Hofstadter-Conway-$10-000-sequence b/Lang/XPL0/Hofstadter-Conway-$10-000-sequence new file mode 120000 index 0000000000..c4c0f0e659 --- /dev/null +++ b/Lang/XPL0/Hofstadter-Conway-$10-000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10-000-sequence/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Particle-fountain b/Lang/XPL0/Particle-fountain new file mode 120000 index 0000000000..d512597b55 --- /dev/null +++ b/Lang/XPL0/Particle-fountain @@ -0,0 +1 @@ +../../Task/Particle-fountain/XPL0 \ No newline at end of file diff --git a/Lang/YAMLScript/00-LANG.txt b/Lang/YAMLScript/00-LANG.txt index 53857113ac..2b465e9da2 100644 --- a/Lang/YAMLScript/00-LANG.txt +++ b/Lang/YAMLScript/00-LANG.txt @@ -4,19 +4,33 @@ {{language programming paradigm|hosted}} {{implementation|Lisp}} -'''YAMLScript''' a hosted '''Lisp''' like '''Clojure''' (Java/JVM) and '''ClojureScript''' (JavaScript). -Actually it is simply an alternate syntax reader for Clojure and Lingy. -'''Lingy''' is a port of Clojure to various programming languages including Perl. +'''YAMLScript''' is a new programming language that uses [https://yaml.org/ YAML] as its syntax. It is a complete, functional, general purpose language, but can also be easily embedded in YAML files to make them dynamic at load time. Most existing YAML files and all JSON files are already valid YAMLScript programs. YAMLScript has a compiler/interpreter CLI program called ys and is also available in several programming languages as a binding module to the libyamlscript.so shared library: -YAMLScript offers all the power of Lisp but with a various syntax features that strive to make it more readable than encoding everything as nested s-expression forms. +* [https://metacpan.org/pod/YAMLScript Perl] +* [https://pypi.org/project/yamlscript/ Python] +* [https://raku.land/zef:ingy/YAMLScript Raku] +* [https://rubygems.org/gems/yamlscript Ruby] +* [https://crates.io/crates/yamlscript Rust] ==Installing YAMLScript== -Run this command to install the 'yamlscript' command line runner program. +Run this command to install the ys command line YAMLScript runner/loader/compiler program. - cpanm YAML + curl -s https://yamlscript.org/install | PREFIX=$HOME BIN=1 bash -==See Also== +That will install $HOME/bin/ys. If $HOME/bin is not in your PATH, run: -* [https://metacpan.org/pod/YAMLScript YAMLScript Doc] -* [https://metacpan.org/pod/Lingy Lingy Doc] \ No newline at end of file + export PATH=$HOME/bin:$PATH + +Test the new installation: + $ ys --help + ys - The YAMLScript (YS) Command Line Tool + + Usage: ys [options] [file] + + Options: + -r, --run Compile and evaluate a YAMLScript file (default) + -l, --load Output the evaluated YAMLScript value + -e, --eval YSEXPR Evaluate a YAMLScript expression + ... +See https://yamlscript.org for more information. \ No newline at end of file diff --git a/Lang/YAMLScript/Leap-year b/Lang/YAMLScript/Leap-year new file mode 120000 index 0000000000..47e901f838 --- /dev/null +++ b/Lang/YAMLScript/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/YAMLScript \ No newline at end of file diff --git a/Lang/Yabasic/Sphenic-numbers b/Lang/Yabasic/Sphenic-numbers new file mode 120000 index 0000000000..ea34dc4862 --- /dev/null +++ b/Lang/Yabasic/Sphenic-numbers @@ -0,0 +1 @@ +../../Task/Sphenic-numbers/Yabasic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Zero-to-the-zero-power b/Lang/ZX-Spectrum-Basic/Zero-to-the-zero-power new file mode 120000 index 0000000000..8f0b2baaa1 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Task/100-doors/BabyCobol/100-doors.cobol b/Task/100-doors/BabyCobol/100-doors.cobol new file mode 100644 index 0000000000..feccf1cab2 --- /dev/null +++ b/Task/100-doors/BabyCobol/100-doors.cobol @@ -0,0 +1,29 @@ + * NB: the implementation is rather vanilla + * besides using the idiomatic buffer overrun. + * LOOP is what PERFORM in COBOL is, with defaults. + * MOVE in this language acts like OVE CORRESPONDING, + * which is actually good here. + IDENTIFICATION DIVISION. + PROGRAM-ID. ONE HUNDRED DOORS. + DATA DIVISION. + 01 I PICTURE IS 9(3). + 01 J LIKE I. + 01 DOOR PICTURE IS 9 OCCURS 100 TIMES. + 01 STOP LIKE DOOR. + PROCEDURE DIVISION. + * Initialise the data + MOVE HIGH-VALUES TO STOP + MOVE SPACES TO DOOR. + * Do the main algorithm + LOOP VARYING I UNTIL DOOR(I) = 9 + LOOP VARYING J FROM I TO 100 BY I + SUBTRACT DOOR (J) FROM 1 GIVING DOOR (J) + END + END. + * Print the results + LOOP VARYING I UNTIL DOOR(I) = 9 + DISPLAY "Door" I "is" WITH NO ADVANCING + IF DOOR (I) = 1 + THEN DISPLAY "open" + ELSE DISPLAY "closed". + END. diff --git a/Task/100-doors/Elena/100-doors.elena b/Task/100-doors/Elena/100-doors.elena index cbfc05a44f..6e1a619ede 100644 --- a/Task/100-doors/Elena/100-doors.elena +++ b/Task/100-doors/Elena/100-doors.elena @@ -4,15 +4,15 @@ import extensions; public program() { var Doors := Array.allocate(100).populate::(n=>false); - for(int i := 0, i < 100, i := i + 1) + for(int i := 0; i < 100; i++) { - for(int j := i, j < 100, j := j + i + 1) + for(int j := i; j < 100; j := j + i + 1) { Doors[j] := Doors[j].Inverted } }; - for(int i := 0, i < 100, i := i + 1) + for(int i := 0; i < 100; i++) { console.printLine("Door #",i + 1," :",Doors[i].iif("Open","Closed")) }; diff --git a/Task/100-doors/Langur/100-doors-1.langur b/Task/100-doors/Langur/100-doors-1.langur index 545cca3a47..2ec8f19359 100644 --- a/Task/100-doors/Langur/100-doors-1.langur +++ b/Task/100-doors/Langur/100-doors-1.langur @@ -1,4 +1,4 @@ -var .doors = arr 100, false +var .doors = [false] x 100 for .i of .doors { for .j = .i; .j <= len(.doors); .j += .i { diff --git a/Task/100-doors/Refal/100-doors.refal b/Task/100-doors/Refal/100-doors.refal new file mode 100644 index 0000000000..027ee823a1 --- /dev/null +++ b/Task/100-doors/Refal/100-doors.refal @@ -0,0 +1,38 @@ +$ENTRY Go { + = >>; +}; + +NDoors { = 100; }; +Doors { = Closed>; }; + +Repeat { + 0 s.val = ; + s.N s.val = s.val s.val> ; +}; + +Toggle { + 1 Closed e.rest = Open e.rest; + 1 Open e.rest = Closed e.rest; + s.N s.door e.rest = s.door e.rest>; +}; + +Pass { + s.pass s.door e.doors, >: '+' + = e.doors; + s.pass s.door e.doors + = >; +}; + +Walk { + s.pass e.doors, >: '+' + = e.doors; + s.pass e.doors + = >; +}; + +Show { + s.N Open e.rest = + e.rest>; + s.N Closed e.rest = e.rest>; + s.N = ; +}; diff --git a/Task/100-doors/Swift/100-doors-3.swift b/Task/100-doors/Swift/100-doors-3.swift new file mode 100644 index 0000000000..05cf5c8d51 --- /dev/null +++ b/Task/100-doors/Swift/100-doors-3.swift @@ -0,0 +1 @@ +var arr: [Bool] = Array(1...100).map{ remquo(exp(log(Float($0))/2.0),1).0 == 0 } diff --git a/Task/100-doors/YAMLScript/100-doors.ys b/Task/100-doors/YAMLScript/100-doors.ys index 6a5a4400bd..d5248aee43 100644 --- a/Task/100-doors/YAMLScript/100-doors.ys +++ b/Task/100-doors/YAMLScript/100-doors.ys @@ -1,15 +1,16 @@ !yamlscript/v0 defn main(): - say: - "Open doors after 100 passes: - $(apply str interpose(\", \" open-doors()))" + say: |- + Open doors after 100 passes: + $(apply str interpose(', ' open-doors())) defn open-doors(): - for: .[[d n] map(vector doors() iterate(inc 1)) :when d] n + for [[d n] map(vector doors() iterate(inc 1)) :when d]: + n defn doors(): reduce: - fn [doors idx]: assoc(doors idx true) + fn(doors idx): assoc(doors idx true) into []: repeat(100 false) - map \(dec (% * %)): (1 .. 10) + map \(dec (%1 * %1)): 1 .. 10 diff --git a/Task/100-prisoners/EasyLang/100-prisoners.easy b/Task/100-prisoners/EasyLang/100-prisoners.easy index 3435445f04..6bdc815b68 100644 --- a/Task/100-prisoners/EasyLang/100-prisoners.easy +++ b/Task/100-prisoners/EasyLang/100-prisoners.easy @@ -4,7 +4,7 @@ for i = 1 to 100 . subr shuffle_drawer for i = len drawer[] downto 2 - r = random i + r = randint i swap drawer[r] drawer[i] . . @@ -13,7 +13,7 @@ subr play_random for prisoner = 1 to 100 found = 0 for i = 1 to 50 - r = random (100 - i) + r = randint (100 - i) card = drawer[sampler[r]] swap sampler[r] sampler[100 - i - 1] if card = prisoner diff --git a/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy b/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy index 56d3e27935..e10e23f2a7 100644 --- a/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy +++ b/Task/15-puzzle-game/EasyLang/15-puzzle-game.easy @@ -44,7 +44,7 @@ proc init . . . # shuffle for i = 15 downto 2 - r = random i + r = randint i swap f[r] f[i] . # make it solvable diff --git a/Task/15-puzzle-game/Ring/15-puzzle-game.ring b/Task/15-puzzle-game/Ring/15-puzzle-game-1.ring similarity index 100% rename from Task/15-puzzle-game/Ring/15-puzzle-game.ring rename to Task/15-puzzle-game/Ring/15-puzzle-game-1.ring diff --git a/Task/15-puzzle-game/Ring/15-puzzle-game-2.ring b/Task/15-puzzle-game/Ring/15-puzzle-game-2.ring new file mode 100644 index 0000000000..7db11feee3 --- /dev/null +++ b/Task/15-puzzle-game/Ring/15-puzzle-game-2.ring @@ -0,0 +1,452 @@ +/* +** +** Game : CalmoSoft Fifteen Puzzle Game 3D +** Date : 2017/09/01 +** Author : CalmoSoft , Mahmoud Fayed +** +*/ + +# Load Libraries +load "gamelib.ring" # RingAllegro Library +load "opengl21lib.ring" # RingOpenGL Library + +butSize = 3 +texture = list(9) +cube = list(9) +rnd = list(9) +rndok = 0 + +for n=1 to 9 + rnd[n] = 0 +next + +for n=1 to 9 + while true + rndok = 0 + ran = random(8) + 1 + for nr=1 to 9 + if rnd[nr] = ran + rndok = 1 + ok + next + if rndok = 0 + rnd[n] = ran + exit + ok + end +next + +for n=1 to 9 + if rnd[n] = 9 + empty = n + ok +next + +#============================================================== +# To Support MacOS X + al_run_main() + func al_game_start # Called by al_run_main() + main() # Now we call our main function +#============================================================== + +func main + new TicTacToe3D { + start() + } + +class TicTacToe3D from GameLogic + + FPS = 60 + TITLE = "CalmoSoft Fifteen Puzzle Game 3D" + + oBackground = new GameBackground + oGameSound = new GameSound + oGameCube = new GameCube + oGameInterface = new GameInterface + + func loadresources + oGameSound.loadresources() + oBackGround.loadresources() + oGameCube.loadresources() + + func drawScene + oBackground.update() + oGameInterface.update(self) + + func MouseClickEvent + oGameInterface.MouseClickEvent(self) + +class GameInterface + + func Update oGame + prepare() + cubes(oGame) + + func Prepare + w = 1024 h = 768 + ratio = w / h + glViewport(0, 0, w, h) + glMatrixMode(GL_PROJECTION) + glLoadIdentity() + gluPerspective(-120,ratio,1,120) + glMatrixMode(GL_MODELVIEW) + glLoadIdentity() + glEnable(GL_TEXTURE_2D) + glShadeModel(GL_SMOOTH) + glClearColor(0.0, 0.0, 0.0, 0.5) + glClearDepth(1.0) + glEnable(GL_DEPTH_TEST) + glEnable(GL_CULL_FACE) + glDepthFunc(GL_LEQUAL) + glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) + + func Cubes oGame + oGame.oGameCube { + aGameMap = oGame.aGameMap + cube[1] = cube( 5 , -3 , -5 , texture[rnd[1]] ) + cube[2] = cube( 0 , -3 , -5 , texture[rnd[2]] ) + cube[3] = cube( -5 , -3 , -5 , texture[rnd[3]] ) + cube[4] = cube( 5 , 1 , -5 , texture[rnd[4]] ) + cube[5] = cube( 0 , 1 , -5 , texture[rnd[5]] ) + cube[6] = cube( -5 , 1 , -5 , texture[rnd[6]] ) + cube[7] = cube( 5 , 5 , -5 , texture[rnd[7]] ) + cube[8] = cube( 0 , 5 , -5 , texture[rnd[8]] ) + cube[9] = cube( -5 , 5 , -5 , texture[rnd[9]] ) + rotate() + } + + func MouseClickEvent oGame + oGame { + aBtn = Point2Button(Mouse_X,Mouse_Y) + move = 0 + nRow = aBtn[1] + nCol = aBtn[2] + tile = (nRow-1)*3 + nCol + up = (empty = (tile - butSize)) + down = (empty = (tile + butSize)) + left = ((empty = (tile- 1)) and ((tile % butSize) != 1)) + right = ((empty = (tile + 1)) and ((tile % butSize) != 0)) + move = up or down or left or right + if move = 1 + temp = rnd[empty] + rnd[empty] = rnd[tile] + rnd[tile] = temp + empty = tile + oGame.oGameCube { + aGameMap = oGame.aGameMap + cube[1] = cube( 5 , -3 , -5 , texture[rnd[1]] ) + cube[2] = cube( 0 , -3 , -5 , texture[rnd[2]] ) + cube[3] = cube( -5 , -3 , -5 , texture[rnd[3]] ) + cube[4] = cube( 5 , 1 , -5 , texture[rnd[4]] ) + cube[5] = cube( 0 , 1 , -5 , texture[rnd[5]] ) + cube[6] = cube( -5 , 1 , -5 , texture[rnd[6]] ) + cube[7] = cube( 5 , 5 , -5 , texture[rnd[7]] ) + cube[8] = cube( 0 , 5 , -5 , texture[rnd[8]] ) + cube[9] = cube( -5 , 5 , -5 , texture[rnd[9]] ) + rotate() + } + ok + } + +Class GameLogic from GraphicsAppBase + + aGameMap = [ + [ :n , :n , :n ] , + [ :n , :n , :n ] , + [ :n , :n , :n ] + ] + + aGameButtons = [ # x1,y1,x2,y2 + [176,88,375,261], # [1,1] + [423,88,591,261], # [1,2] + [645,88,876,261], # [1,3] + [176,282,375,428], # [2,1] + [423,282,591,428], # [2,2] + [645,282,876,428], # [2,3] + [176,454,375,678], # [3,1] + [423,454,591,678], # [3,2] + [645,454,876,678] # [3,3] + ] + + cActivePlayer = :x + + func point2button x,y + nRow = 0 + nCol = 0 + for t = 1 to len(aGameButtons) + rect = aGameButtons[t] + if x >= rect[1] and x <= rect[3] and + y >= rect[2] and y <= rect[4] + switch t + on 1 nRow = 1 nCol = 1 + on 2 nRow = 1 nCol = 2 + on 3 nRow = 1 nCol = 3 + on 4 nRow = 2 nCol = 1 + on 5 nRow = 2 nCol = 2 + on 6 nRow = 2 nCol = 3 + on 7 nRow = 3 nCol = 1 + on 8 nRow = 3 nCol = 2 + on 9 nRow = 3 nCol = 3 + off + exit + ok + next + return [nRow,nCol] + +class GameCube + + bitmap bitmap2 bitmap3 + textureX textureO textureN + + xrot = 0.0 + yrot = 0.0 + zrot = 0.0 + + func loadresources + bitmp1 = al_load_bitmap("image/n1.jpg") + texture[1] = al_get_opengl_texture(bitmp1) + bitmp2 = al_load_bitmap("image/n2.jpg") + texture[2] = al_get_opengl_texture(bitmp2) + bitmp3 = al_load_bitmap("image/n3.jpg") + texture[3] = al_get_opengl_texture(bitmp3) + bitmp4 = al_load_bitmap("image/n4.jpg") + texture[4] = al_get_opengl_texture(bitmp4) + bitmp5 = al_load_bitmap("image/n5.jpg") + texture[5] = al_get_opengl_texture(bitmp5) + bitmp6 = al_load_bitmap("image/n6.jpg") + texture[6] = al_get_opengl_texture(bitmp6) + bitmp7 = al_load_bitmap("image/n7.jpg") + texture[7] = al_get_opengl_texture(bitmp7) + bitmp8 = al_load_bitmap("image/n8.jpg") + texture[8] = al_get_opengl_texture(bitmp8) + bitmp9 = al_load_bitmap("image/empty.png") + texture[9] = al_get_opengl_texture(bitmp9) + + func cube(x,y,z,nTexture) + glLoadIdentity() + glTranslatef(x,y,z) + glRotatef(xrot,1.0,0.0,0.0) + glRotatef(yrot,0.0,1.0,0.0) + glRotatef(zrot,0.0,0.0,1.0) + setCubeTexture(nTexture) + drawCube() + + func setCubeTexture cTexture + glBindTexture(GL_TEXTURE_2D, cTexture) + + func Rotate + xrot += 0.3 * 5 + yrot += 0.2 * 5 + zrot += 0.4 * 5 + + func drawcube + glBegin(GL_QUADS) + // Front Face + glTexCoord2f(0.0, 0.0) glVertex3f(-1.0, -1.0, 1.0) + glTexCoord2f(1.0, 0.0) glVertex3f( 1.0, -1.0, 1.0) + glTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) + glTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, 1.0) + // Back Face + glTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, -1.0) + glTexCoord2f(1.0, 1.0) glVertex3f(-1.0, 1.0, -1.0) + glTexCoord2f(0.0, 1.0) glVertex3f( 1.0, 1.0, -1.0) + glTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, -1.0) + // Top Face + glTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, -1.0) + glTexCoord2f(0.0, 0.0) glVertex3f(-1.0, 1.0, 1.0) + glTexCoord2f(1.0, 0.0) glVertex3f( 1.0, 1.0, 1.0) + glTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, -1.0) + // Bottom Face + glTexCoord2f(1.0, 1.0) glVertex3f(-1.0, -1.0, -1.0) + glTexCoord2f(0.0, 1.0) glVertex3f( 1.0, -1.0, -1.0) + glTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, 1.0) + glTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, 1.0) + + // Right face + glTexCoord2f(1.0, 0.0) glVertex3f( 1.0, -1.0, -1.0) + glTexCoord2f(1.0, 1.0) glVertex3f( 1.0, 1.0, -1.0) + glTexCoord2f(0.0, 1.0) glVertex3f( 1.0, 1.0, 1.0) + glTexCoord2f(0.0, 0.0) glVertex3f( 1.0, -1.0, 1.0) + + // Left Face + glTexCoord2f(0.0, 0.0) glVertex3f(-1.0, -1.0, -1.0) + glTexCoord2f(1.0, 0.0) glVertex3f(-1.0, -1.0, 1.0) + glTexCoord2f(1.0, 1.0) glVertex3f(-1.0, 1.0, 1.0) + glTexCoord2f(0.0, 1.0) glVertex3f(-1.0, 1.0, -1.0) + glEnd() + + +class GameBackground + + nBackX = 0 + nBackY = 0 + nBackDiffx = -1 + nBackDiffy = -1 + nBackMotion = 1 + aBackMotionList = [ + [ -1, -1 ] , # Down - Right + [ 0 , 1 ] , # Up + [ -1, -1 ] , # Down - Right + [ 0 , 1 ] , # Up + [ 1 , -1 ] , # Down - Left + [ 0 , 1 ] , # Up + [ 1 , -1 ] , # Down - Left + [ 0 , 1 ] # Up + ] + + bitmap + + func Update + draw() + motion() + + func draw + al_draw_bitmap(bitmap,nBackX,nBackY,1) + + func motion + nBackX += nBackDiffx + nBackY += nBackDiffy + if (nBackY = -350) or (nBackY = 0) + nBackMotion++ + if nBackMotion > len(aBackMotionList) + nBackMotion = 1 + ok + nBackDiffx = aBackMotionList[nBackMotion][1] + nBackDiffy = aBackMotionList[nBackMotion][2] + ok + + func loadResources + bitmap = al_load_bitmap("image/back.jpg") + +class GameSound + + sample sampleid + + func loadresources + sample = al_load_sample( "sound/music1.wav" ) + sampleid = al_new_allegro_sample_id() + al_play_sample(sample, 1.0, 0.0,1.0,ALLEGRO_PLAYMODE_LOOP,sampleid) + +class GraphicsAppBase + + display event_queue ev timeout + timer + redraw = true + FPS = 60 + SCREEN_W = 1024 + SCREEN_H = 700 + KEY_UP = 1 + KEY_DOWN = 2 + KEY_LEFT = 3 + KEY_RIGHT = 4 + Key = [false,false,false,false] + Mouse_X = 0 + Mouse_Y = 0 + TITLE = "Graphics Application" + PRINT_MOUSE_XY = False + + func start + SetUp() + loadResources() + eventsLoop() + destroy() + + func setup + al_init() + al_init_font_addon() + al_init_ttf_addon() + al_init_image_addon() + al_install_audio() + al_init_acodec_addon() + al_reserve_samples(1) + al_set_new_display_flags(ALLEGRO_OPENGL) + display = al_create_display(SCREEN_W,SCREEN_H) + al_set_window_title(display,TITLE) + al_clear_to_color(al_map_rgb(0,0,0)) + event_queue = al_create_event_queue() + al_register_event_source(event_queue, + al_get_display_event_source(display)) + ev = al_new_allegro_event() + timeout = al_new_allegro_timeout() + al_init_timeout(timeout, 0.06) + timer = al_create_timer(1.0 / FPS) + al_register_event_source(event_queue, + al_get_timer_event_source(timer)) + al_start_timer(timer) + al_install_mouse() + al_register_event_source(event_queue, + al_get_mouse_event_source()) + al_install_keyboard() + al_register_event_source(event_queue, + al_get_keyboard_event_source()) + + func eventsLoop + while true + al_wait_for_event_until(event_queue, ev, timeout) + switch al_get_allegro_event_type(ev) + on ALLEGRO_EVENT_DISPLAY_CLOSE + CloseEvent() + on ALLEGRO_EVENT_TIMER + redraw = true + on ALLEGRO_EVENT_MOUSE_AXES + mouse_x = al_get_allegro_event_mouse_x(ev) + mouse_y = al_get_allegro_event_mouse_y(ev) + if PRINT_MOUSE_XY + see "x = " + mouse_x + nl + see "y = " + mouse_y + nl + ok + on ALLEGRO_EVENT_MOUSE_ENTER_DISPLAY + mouse_x = al_get_allegro_event_mouse_x(ev) + mouse_y = al_get_allegro_event_mouse_y(ev) + on ALLEGRO_EVENT_MOUSE_BUTTON_UP + MouseClickEvent() + on ALLEGRO_EVENT_KEY_DOWN + switch al_get_allegro_event_keyboard_keycode(ev) + on ALLEGRO_KEY_UP + key[KEY_UP] = true + on ALLEGRO_KEY_DOWN + key[KEY_DOWN] = true + on ALLEGRO_KEY_LEFT + key[KEY_LEFT] = true + on ALLEGRO_KEY_RIGHT + key[KEY_RIGHT] = true + off + on ALLEGRO_EVENT_KEY_UP + switch al_get_allegro_event_keyboard_keycode(ev) + on ALLEGRO_KEY_UP + key[KEY_UP] = false + on ALLEGRO_KEY_DOWN + key[KEY_DOWN] = false + on ALLEGRO_KEY_LEFT + key[KEY_LEFT] = false + on ALLEGRO_KEY_RIGHT + key[KEY_RIGHT] = false + on ALLEGRO_KEY_ESCAPE + exit + off + off + if redraw and al_is_event_queue_empty(event_queue) + redraw = false + drawScene() + al_flip_display() + ok + callgc() + end + + func destroy + al_destroy_timer(timer) + al_destroy_allegro_event(ev) + al_destroy_allegro_timeout(timeout) + al_destroy_event_queue(event_queue) + al_destroy_display(display) + al_exit() + + func loadresources + + func drawScene + + func MouseClickEvent + exit # Exit from the Events Loop + + func CloseEvent + exit # Exit from the Events Loop diff --git a/Task/21-game/EasyLang/21-game.easy b/Task/21-game/EasyLang/21-game.easy index bcbd765121..1ed700b063 100644 --- a/Task/21-game/EasyLang/21-game.easy +++ b/Task/21-game/EasyLang/21-game.easy @@ -17,7 +17,7 @@ repeat else sleep 1 if sum mod 4 = 1 - n = random 3 + n = randint 3 else n = 4 - (sum + 3) mod 4 . diff --git a/Task/21-game/Forth/21-game.fth b/Task/21-game/Forth/21-game.fth new file mode 100644 index 0000000000..3090fa4563 --- /dev/null +++ b/Task/21-game/Forth/21-game.fth @@ -0,0 +1,32 @@ +: READKEY + 1+ BEGIN + KEY DUP 27 = ABORT" Bye!" + 48 - 2DUP > OVER 0 > AND IF + DUP 48 + EMIT CR SWAP DROP EXIT + THEN DROP + REPEAT +; +: 21GAME CLS + 0 2 RND 1- + ." 21 is a two player game." CR + ." The game is played by choosing a number (1, 2 or 3) to be added to the running total. " + ." The game is won by the player whose chosen number causes the running total to reach exactly 21." + ." The running total starts at zero. One player will be the computer." + BEGIN + NOT + CR ." The sum is " OVER . CR + SWAP OVER IF + ." How many would you like add?" + ." (1-3) " 3 READKEY + ELSE + ." It is the computer's turn." + 4 OVER 1- 4 MOD - + DUP 4 = IF 3 RND 1+ MIN THEN + DUP CR ." Computer adds " . CR + THEN + SWAP + OVER 21 < NOT UNTIL + CR + IF ." Congratulations. You win." + ELSE ." Bad Luck. Computer wins." + THEN CR DROP +; diff --git a/Task/21-game/IS-BASIC/21-game.basic b/Task/21-game/IS-BASIC/21-game.basic index d61a3efeb8..edb55d5d3c 100644 --- a/Task/21-game/IS-BASIC/21-game.basic +++ b/Task/21-game/IS-BASIC/21-game.basic @@ -1,25 +1,25 @@ 100 PROGRAM "21Game.bas" 110 RANDOMIZE 120 LET SUM,ADD=0 -130 LET TURN=RND(2) +130 LET TURN=RND(2)-1 140 CLEAR SCREEN 150 PRINT "21 is a two player game, the game is played by choosing a number (1, 2, or 3) to be added to the running total. The game is won by the player whose chosen number causes the running total to reach exactly 21." 160 PRINT "The running total starts at zero. One player will be the computer.":PRINT 170 DO -180 LET TURN=1-TURN +180 LET TURN=NOT TURN 190 SET #102:INK 3:PRINT "The sum is";SUM:SET #102:INK 1 -200 IF TURN=1 THEN +200 IF TURN THEN 210 PRINT "It is your turn.":PRINT "How many would you like to add? (1-3): "; 220 LET ADD=READKEY 230 IF ADD>21-SUM THEN PRINT "You can only add";21-SUM 240 ELSE -250 LET ADD=4-MOD((SUM-1),4) -260 IF ADD=4 THEN LET ADD=MIN(RND(3)+1,SUM) +250 LET ADD=4-MOD(SUM-1,4) +260 IF ADD=4 THEN LET ADD=RND(3)+1 270 PRINT "It is the computer's turn.":PRINT "The computer adds";ADD 280 END IF 290 PRINT :LET SUM=SUM+ADD 300 LOOP WHILE SUM<21 -310 IF TURN=1 THEN +310 IF TURN THEN 320 PRINT "Congratulations. You win." 330 ELSE 340 PRINT "Bad luck. The computer wins." diff --git a/Task/24-game/XPL0/24-game.xpl0 b/Task/24-game/XPL0/24-game.xpl0 new file mode 100644 index 0000000000..f2a6bae263 --- /dev/null +++ b/Task/24-game/XPL0/24-game.xpl0 @@ -0,0 +1,42 @@ +real Stack(10), A, B; +int SP, I, Char, Digit, Digits(10); + +proc Push(X); +real X; +[Stack(SP):= X; SP:= SP+1]; + +func real Pop; +[SP:= SP-1; return Stack(SP)]; + +[SP:= 0; +for I:= 0 to 9 do Digits(I):= 0; +Text(0, "Enter an RPN expression that equals 24 using all these digits:"); +for I:= 0 to 3 do + [Digit:= Ran(9)+1; + ChOut(0, ^ ); ChOut(0, Digit+^0); + Digits(Digit):= Digits(Digit)+1; + ]; +Text(0, "^m^j> "); +loop [Char:= ChIn(1); + ChOut(0, Char); + if Char >= ^1 and Char <=^9 then + [Digit:= Char - ^0; + Push(float(Digit)); + Digits(Digit):= Digits(Digit) - 1; + ] + else [if SP >= 2 then [A:= Pop; B:= Pop] else quit; + case Char of + ^+: Push(B+A); + ^-: Push(B-A); + ^*: Push(B*A); + ^/: Push(B/A) + other quit; + ]; + ]; +CrLf(0); +for I:= 0 to 9 do + if Digits(I) # 0 then + [Text(0, "Must use each of the given digits.^m^j"); exit]; +Text(0, if abs(Pop-24.0) < 0.001 then "Correct!" else "Wrong."); +CrLf(0); +] diff --git a/Task/9-billion-names-of-God-the-integer/R/9-billion-names-of-god-the-integer.r b/Task/9-billion-names-of-God-the-integer/R/9-billion-names-of-god-the-integer.r new file mode 100644 index 0000000000..70d49d803a --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/R/9-billion-names-of-god-the-integer.r @@ -0,0 +1,10 @@ +library(partitions) +library(stringi) + +get_row <- function(x) unname(table(parts(x)[1,])) + +center_string <- function(s,pad_len=80) stri_pad_both(s,(pad_len - length(s))," ") + +for (i in 1:25) cat(center_string(stri_c(get_row(i),collapse = " "),80),"\n") + +cat("The sum of G(25) is:", sum(get_row(25)),"\n") diff --git a/Task/99-bottles-of-beer/BabyCobol/99-bottles-of-beer.cobol b/Task/99-bottles-of-beer/BabyCobol/99-bottles-of-beer.cobol new file mode 100644 index 0000000000..08569d309c --- /dev/null +++ b/Task/99-bottles-of-beer/BabyCobol/99-bottles-of-beer.cobol @@ -0,0 +1,38 @@ + * Pointing out some interesting things: + * - BY 0 subclause of VARYING (illegal in some COBOL dialects) + * - PERFORM THROUGH with internal/external GO TOs + * - using non-reserved keywords (END, DATA) + * - ALTER (works the same way in COBOL) + * - fall-through from MANY-BOTTLES + * - the last NEXT SENTENCE does nothing (plays the role of EXIT) + IDENTIFICATION DIVISION. + PROGRAM-ID. 99 BOTTLES. + DATA DIVISION. + 01 DATA PICTURE IS 999. + PROCEDURE DIVISION. + LOOP VARYING DATA FROM 99 BY 0 + PERFORM COUNT-BOTTLES THROUGH END + DISPLAY DATA "bottles of beer" + DISPLAY "Take one down, pass it around" + SUBTRACT 1 FROM DATA + IF DATA = 1 + THEN ALTER COUNT-BOTTLES TO PROCEED TO SINGLE-BOTTLE + END + PERFORM COUNT-BOTTLES THROUGH END + DISPLAY "" + END. + NO-BOTTLES-LEFT. + DISPLAY "No bottles of beer on the wall" + DISPLAY "" + DISPLAY "Go to the store and buy some more" + DISPLAY "99 bottles of beer on the wall". + STOP. + COUNT-BOTTLES. + GO TO MANY-BOTTLES. + SINGLE-BOTTLE. + DISPLAY DATA "bottle of beer on the wall". + GO TO NO-BOTTLES-LEFT. + MANY-BOTTLES. + DISPLAY DATA "bottles of beer on the wall". + END. + NEXT SENTENCE. diff --git a/Task/99-bottles-of-beer/Bruijn/99-bottles-of-beer.bruijn b/Task/99-bottles-of-beer/Bruijn/99-bottles-of-beer.bruijn new file mode 100644 index 0000000000..afaffdd63f --- /dev/null +++ b/Task/99-bottles-of-beer/Bruijn/99-bottles-of-beer.bruijn @@ -0,0 +1,11 @@ +:import std/Combinator . +:import std/Number . +:import std/String . + +main [y [[=?0 case-end case-rec]] (+99)] + case-rec n ++ t1 ++ n ++ t2 ++ t3 ++ n ++ t1 ++ "\n" ++ (1 --0) + n number→string 0 + t1 " bottles of beer on the wall\n" + t2 " bottles of beer\n" + t3 "Take one down, pass it around\n" + case-end empty diff --git a/Task/99-bottles-of-beer/Refal/99-bottles-of-beer.refal b/Task/99-bottles-of-beer/Refal/99-bottles-of-beer.refal new file mode 100644 index 0000000000..2d53758e21 --- /dev/null +++ b/Task/99-bottles-of-beer/Refal/99-bottles-of-beer.refal @@ -0,0 +1,29 @@ +$ENTRY Go { + = >; +}; + +Verses { + '-'1 = ; + s.1 = + >; +}; + +Verse { + s.1 = ' of beer on the wall,\n' + ' of beer,\n' + '\n' + > ' of beer on the wall!\n\n'; +}; + +Bottles { + '-'1 = '99 bottles'; + 0 = 'No more bottles'; + 1 = '1 bottle'; + s.1 = s.1 'bottles'; +}; + +ThirdLine { + 0 = 'Go to the store and buy some more,'; + 1 = 'Take it down and pass it around,'; + s.1 = 'Take one down and pass it around,'; +}; diff --git a/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl b/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl new file mode 100644 index 0000000000..2d10b5487c --- /dev/null +++ b/Task/99-bottles-of-beer/Uxntal/99-bottles-of-beer.uxnatl @@ -0,0 +1,63 @@ +( uxncli 99bottles.rom ) + +|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 + +|0100 ( -> ) + #63 &loop + DUP + [ LIT2 0a -Console/write ] DEO + #01 EQUk ?&done + POP #01 SUB + !&loop + &done BRK + +@ ( num -- ) + DUP ;dict/wall + DUP [ LIT2 0a -Console/write ] DEO + ;dict/take + #01 SUB ;dict/wall ! + +@ ( num -- ) + DUP #00 EQU ?&zero + DUP #01 EQU ?&one + ;dict/bottle + [ LIT2 "s -Console/write ] DEO + !&end + + &one ( num -- ) + ;dict/bottle + !&end + &zero ( num -- ) + POP ;dict/no-more + ;dict/bottle + [ LIT2 "s -Console/write ] DEO + ( >> ) + &end + ;dict/of-beer + ( >> ) + +@ ( str -- ) + &loop + LDAk .Console/write DEO + INC2 LDAk ?&loop + POP2 JMP2r + +@ ( byte -- ) + DUP #64 DIV /try + DUP #0a DIV /try + ( >> ) + +@ ( num -- ) + #0a DIVk MUL SUB + [ LIT "0 ] ADD .Console/write DEO + JMP2r + + &try ( num -- ) + DUP ? + POP JMP2r + +@dict &no-more "No 20 "more $1 + &bottle 20 "bottle $1 + &of-beer 20 "of 20 "beer 20 $1 + &wall "on 20 "the 20 "wall 0a $1 + &take "Take 20 "one 20 "down, 20 "pass 20 "it 20 "around 0a $1 diff --git a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer.ys b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer.ys index 477c6f980a..4aa8dbc7b3 100644 --- a/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer.ys +++ b/Task/99-bottles-of-beer/YAMLScript/99-bottles-of-beer.ys @@ -5,19 +5,18 @@ # usage: # ys 99-bottles.ys [] -defn main(&[number]): - each [n ((number || 99) .. 1)]: - say: - paragraph: n +defn main(number=99): + each [n (number .. 1)]: + say: paragraph(n) defn paragraph(num): | - $(bottles num) of beer on the wall, - $(bottles num) of beer. + $bottles(num) of beer on the wall, + $bottles(num) of beer. Take one down, pass it around. - $(bottles (num - 1)) of beer on the wall. + $bottles(num - 1) of beer on the wall. defn bottles(n): cond: - (n == 0) "No more bottles" - (n == 1) "1 bottle" - :else str(n " bottles") + n == 0 : 'No more bottles' + n == 1 : '1 bottle' + => : "$n bottles" diff --git a/Task/A+B/BabyCobol/a+b.cobol b/Task/A+B/BabyCobol/a+b.cobol new file mode 100644 index 0000000000..aa35ab1873 --- /dev/null +++ b/Task/A+B/BabyCobol/a+b.cobol @@ -0,0 +1,11 @@ + * NB: COBOL's ACCEPT does not work with multiple identifiers + IDENTIFICATION DIVISION. + PROGRAM-ID. PLUS. + DATA DIVISION. + 01 A PICTURE IS S9999. + 01 B LIKE A. + PROCEDURE DIVISION. + DISPLAY "Enter two numbers: " WITH NO ADVANCING. + ACCEPT A B. + ADD A TO B. + DISPLAY "A+B =" B. diff --git a/Task/A+B/Bruijn/a+b.bruijn b/Task/A+B/Bruijn/a+b.bruijn new file mode 100644 index 0000000000..e6be6608b7 --- /dev/null +++ b/Task/A+B/Bruijn/a+b.bruijn @@ -0,0 +1,6 @@ +:import std/Combinator . +:import std/String . +:import std/Number . +:import std/Char C + +main (split-by (C.eq? ' ')) → &(add ⋔ string→number) diff --git a/Task/A+B/EasyLang/a+b.easy b/Task/A+B/EasyLang/a+b.easy index bec95e696d..b110fbde15 100644 --- a/Task/A+B/EasyLang/a+b.easy +++ b/Task/A+B/EasyLang/a+b.easy @@ -1,8 +1,8 @@ a$ = input -i = 1 -while i < len a$ and substr a$ i 1 <> " " - i += 1 +repeat + i += 1 + until i > len a$ or substr a$ i 1 = " " . a = number substr a$ 1 i -b = number substr a$ i -1 +b = number substr a$ i 99 print a + b diff --git a/Task/ABC-problem/Refal/abc-problem.refal b/Task/ABC-problem/Refal/abc-problem.refal new file mode 100644 index 0000000000..7e9c5f8af3 --- /dev/null +++ b/Task/ABC-problem/Refal/abc-problem.refal @@ -0,0 +1,35 @@ +$ENTRY Go { + = ) >; +}; + +Each { + s.F (e.Arg) = ; + s.F (e.Arg) t.I e.R = ; +}; + +Show { + (e.Word) e.Blocks = >; +}; + +Blocks { + = ('BO') ('XK') ('DQ') ('CP') ('NA') + ('GT') ('RE') ('TG') ('QD') ('FS') + ('JW') ('HU') ('VI') ('AN') ('OB') + ('ER') ('FS') ('LY') ('PC') ('ZM'); +}; + +Words { + = ('A') ('BARK') ('BOOK') ('TREAT') + ('common') ('squad') ('CoNfUsE'); +}; + +CanMakeWord { + (e.Word) e.Blocks = ) e.Blocks>; +} + +CanMakeWord1 { + () e.Blocks = T; + (s.Ltr e.Word) e.Blocks1 (e.X s.Ltr e.Y) e.Blocks2 + = ; + (e.Word) e.Blocks = F; +}; diff --git a/Task/ABC-problem/SETL/abc-problem.setl b/Task/ABC-problem/SETL/abc-problem.setl new file mode 100644 index 0000000000..1665c27216 --- /dev/null +++ b/Task/ABC-problem/SETL/abc-problem.setl @@ -0,0 +1,21 @@ +program ABC_problem; + blocks := ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS", + "JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"]; + + words := ["A","BARK","BOOK","treat","common","Squad","CoNfUsE"]; + + loop for word in words do + print(rpad(word, 8), can_make_word(word, blocks)); + end loop; + + proc can_make_word(word, blocks); + loop for letter in word do + if exists block = blocks(i) | to_upper(letter) in block then + blocks(i) := ""; + else + return false; + end if; + end loop; + return true; + end proc; +end program; diff --git a/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena b/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena index 42169edf1f..d1ab382bf3 100644 --- a/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena +++ b/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena @@ -12,9 +12,9 @@ singleton AksTest if ((n < 0) || (n > 63)) { AbortException.raise() }; // gracefully deal with range issue c[i] := 1l; - for (int i := 0, i < n, i += 1) { + for (int i := 0; i < n; i += 1) { c[1 + i] := 1l; - for (int j := i, j > 0, j -= 1) { + for (int j := i; j > 0; j -= 1) { c[j] := c[j - 1] - c[j] }; c[0] := c[0].Negative @@ -52,7 +52,7 @@ singleton AksTest public program() { - for (int n := 0, n < 10, n += 1) { + for (int n := 0; n < 10; n += 1) { AksTest.coef(n); console.print("(x-1)^",n," = "); @@ -61,7 +61,7 @@ public program() }; console.print("Primes:"); - for (int n := 1, n <= 63, n += 1) { + for (int n := 1; n <= 63; n += 1) { if (AksTest.is_prime(n)) { console.print(n," ") diff --git a/Task/Abstract-type/Swift/abstract-type.swift b/Task/Abstract-type/Swift/abstract-type.swift new file mode 100644 index 0000000000..8d13e16ebf --- /dev/null +++ b/Task/Abstract-type/Swift/abstract-type.swift @@ -0,0 +1,33 @@ +protocol Pet { + var name: String { get set } + var favouriteToy: String { get set } + + func feed() -> Bool + + func stroke() -> Void + +} + +extension Pet { + // Default implementation must be in an extension, not in the declaration above + + func stroke() { + print("default purr") + } +} + +struct Dog: Pet { + var name: String + var favouriteToy: String + + // Required implementation + func feed() -> Bool { + print("more please") + return false + } + // If this were not implemented, the default from the extension above + // would be called. + func stroke() { + print("roll over") + } +} diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Elena/abundant-deficient-and-perfect-number-classifications.elena b/Task/Abundant-deficient-and-perfect-number-classifications/Elena/abundant-deficient-and-perfect-number-classifications.elena index f3cc8f8e2e..90f65ae3e7 100644 --- a/Task/Abundant-deficient-and-perfect-number-classifications/Elena/abundant-deficient-and-perfect-number-classifications.elena +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Elena/abundant-deficient-and-perfect-number-classifications.elena @@ -7,15 +7,15 @@ classifyNumbers(int bound, ref int abundant, ref int deficient, ref int perfect) int p := 0; int[] sum := new int[](bound + 1); - for(int divisor := 1, divisor <= bound / 2, divisor += 1) + for(int divisor := 1; divisor <= bound / 2; divisor += 1) { - for(int i := divisor + divisor, i <= bound, i += divisor) + for(int i := divisor + divisor; i <= bound; i += divisor) { sum[i] := sum[i] + divisor } }; - for(int i := 1, i <= bound, i += 1) + for(int i := 1; i <= bound; i += 1) { int t := sum[i]; diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/JavaScript/abundant-deficient-and-perfect-number-classifications-5.js b/Task/Abundant-deficient-and-perfect-number-classifications/JavaScript/abundant-deficient-and-perfect-number-classifications-5.js new file mode 100644 index 0000000000..e5e8da98b0 --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/JavaScript/abundant-deficient-and-perfect-number-classifications-5.js @@ -0,0 +1,33 @@ +// classify the numbers 1 : 20 000 as abudant, deficient or perfect +"use strict" +let abundantCount = 0 +let deficientCount = 0 +let perfectCount = 0 +const maxNumber = 20000 +// construct a table of the proper divisor sums +let pds = [] +pds[ 1 ] = 0 +for( let i = 2; i <= maxNumber; i ++ ){ pds[ i ] = 1 } +for( let i = 2; i <= maxNumber; i ++ ) +{ + for( let j = i + i; j <= maxNumber; j += i ){ pds[ j ] += i } +} +// classify the numbers +for( let n = 1; n <= maxNumber; n ++ ) +{ + if( pds[ n ] < n ) + { + deficientCount ++ + } + else if( pds[ n ] == n ) + { + perfectCount ++ + } + else // pds[ n ] > n + { + abundantCount ++ + } +} +console.log( "abundant " + abundantCount.toString() ) +console.log( "deficient " + deficientCount.toString() ) +console.log( "perfect " + perfectCount.toString() ) diff --git a/Task/Achilles-numbers/EasyLang/achilles-numbers.easy b/Task/Achilles-numbers/EasyLang/achilles-numbers.easy new file mode 100644 index 0000000000..ec0935dde9 --- /dev/null +++ b/Task/Achilles-numbers/EasyLang/achilles-numbers.easy @@ -0,0 +1,101 @@ +func gcd n d . + if d = 0 + return n + . + return gcd d (n mod d) +. +func totient n . + for m = 1 to n + if gcd m n = 1 + tot += 1 + . + . + return tot +. +func isPowerful m . + n = m + f = 2 + l = sqrt m + if m <= 1 + return 0 + . + while 1 = 1 + q = n div f + if n mod f = 0 + if m mod (f * f) <> 0 + return 0 + . + n = q + if f > n + return 1 + . + else + f += 1 + if f > l + if m mod (n * n) <> 0 + return 0 + . + return 1 + . + . + . +. +func isAchilles n . + if isPowerful n = 0 + return 0 + . + m = 2 + a = m * m + repeat + repeat + if a = n + return 0 + . + a *= m + until a > n + . + m += 1 + a = m * m + until a > n + . + return 1 +. +print "First 50 Achilles numbers:" +n = 1 +repeat + if isAchilles n = 1 + write n & " " + num += 1 + . + n += 1 + until num >= 50 +. +print "" +print "" +print "First 20 strong Achilles numbers:" +num = 0 +n = 1 +repeat + if isAchilles n = 1 and isAchilles totient n = 1 + write n & " " + num += 1 + . + n += 1 + until num >= 20 +. +print "" +print "" +print "Number of Achilles numbers with 2 to 5 digits:" +a = 10 +b = 100 +for i = 2 to 5 + num = 0 + for n = a to b - 1 + if isAchilles n = 1 + num += 1 + . + . + write num & " " + a = b + b *= 10 +. diff --git a/Task/Achilles-numbers/Java/achilles-numbers.java b/Task/Achilles-numbers/Java/achilles-numbers.java index 5c4489b4a8..8feaddc1fe 100644 --- a/Task/Achilles-numbers/Java/achilles-numbers.java +++ b/Task/Achilles-numbers/Java/achilles-numbers.java @@ -1,78 +1,108 @@ import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.List; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; -import java.util.stream.IntStream; +import java.util.Map; -public final class AchlllesNumbers { +public class AchillesNumbers { - public static void main(String[] aArgs) { - Set perfectPowers = perfectPowers(500_000); - List achilles = achilles(1, 250_000, perfectPowers); - List totients = totients(250_000); + private Map pps = new HashMap<>(); - System.out.println("First 50 Achilles numbers:"); - for ( int i = 0; i < 50; i++ ) { - System.out.print(String.format("%4d%s", achilles.get(i), ( ( i + 1 ) % 10 == 0 ) ? "\n" : " ")); - } - System.out.println(); - - System.out.println("First 50 strong Achilles numbers:"); - for ( int i = 0, count = 0; count < 50; i++ ) { - if ( achilles.contains(totients.get(achilles.get(i))) ) { - System.out.print(String.format("%6d%s", achilles.get(i), ( ++count % 10 == 0 ) ? "\n" : " ")); - } - } - System.out.println(); - - System.out.println("Number of Achilles numbers with:"); - for ( int i = 100; i < 1_000_000; i *= 10 ) { - final int digits = String.valueOf(i).length() - 1; - System.out.println(" " + digits + " digits: " + achilles(i / 10, i - 1, perfectPowers).size()); - } - } - - private static List achilles(int aFrom, int aTo, Set aPerfectPowers) { - Set result = new TreeSet(); - final int cubeRoot = (int) Math.cbrt(aTo / 4); - final int squareRoot = (int) Math.sqrt(aTo / 8); - for ( int b = 2; b <= cubeRoot; b++ ) { - final int bCubed = b * b * b; - for ( int a = 2; a <= squareRoot; a++ ) { - int achilles = bCubed * a * a; - if ( achilles >= aTo ) { - break; - } - if ( achilles >= aFrom && ! aPerfectPowers.contains(achilles) ) { - result.add(achilles); - } - } - } - return new ArrayList(result); - } - - private static Set perfectPowers(int aN) { - Set result = new TreeSet(); - for ( int i = 2, root = (int) Math.sqrt(aN); i <= root; i++ ) { - for ( int perfect = i * i; perfect < aN; perfect *= i ) { - result.add(perfect); - } - } - return result; - } - - private static List totients(int aN) { - List result = IntStream.rangeClosed(0, aN).boxed().collect(Collectors.toList());; - for ( int i = 2; i <= aN; i++ ) { - if ( result.get(i) == i ) { - result.set(i, i - 1); - for ( int j = i * 2; j <= aN; j = j + i ) { - result.set(j, ( result.get(j) / i ) * ( i - 1 )); - } - } - } - return result; - } + public int totient(int n) { + int tot = n; + int i = 2; + while (i * i <= n) { + if (n % i == 0) { + while (n % i == 0) { + n /= i; + } + tot -= tot / i; + } + if (i == 2) { + i = 1; + } + i += 2; + } + if (n > 1) { + tot -= tot / n; + } + return tot; + } + public void getPerfectPowers(int maxExp) { + double upper = Math.pow(10, maxExp); + for (int i = 2; i <= Math.sqrt(upper); i++) { + double fi = i; + double p = fi; + while (true) { + p *= fi; + if (p >= upper) { + break; + } + pps.put((int) p, true); + } + } + } + + public Map getAchilles(int minExp, int maxExp) { + double lower = Math.pow(10, minExp); + double upper = Math.pow(10, maxExp); + Map achilles = new HashMap<>(); + for (int b = 1; b <= (int) Math.cbrt(upper); b++) { + int b3 = b * b * b; + for (int a = 1; a <= (int) Math.sqrt(upper); a++) { + int p = b3 * a * a; + if (p >= (int) upper) { + break; + } + if (p >= (int) lower) { + if (!pps.containsKey(p)) { + achilles.put(p, true); + } + } + } + } + return achilles; + } + + public static void main(String[] args) { + AchillesNumbers an = new AchillesNumbers(); + + int maxDigits = 8; + an.getPerfectPowers(maxDigits); + Map achillesSet = an.getAchilles(1, 5); + List achilles = new ArrayList<>(achillesSet.keySet()); + Collections.sort(achilles); + + System.out.println("First 50 Achilles numbers:"); + for (int i = 0; i < 50; i++) { + System.out.printf("%4d ", achilles.get(i)); + if ((i + 1) % 10 == 0) { + System.out.println(); + } + } + + System.out.println("\nFirst 30 strong Achilles numbers:"); + List strongAchilles = new ArrayList<>(); + int count = 0; + for (int n = 0; count < 30; n++) { + int tot = an.totient(achilles.get(n)); + if (achillesSet.containsKey(tot)) { + strongAchilles.add(achilles.get(n)); + count++; + } + } + for (int i = 0; i < 30; i++) { + System.out.printf("%5d ", strongAchilles.get(i)); + if ((i + 1) % 10 == 0) { + System.out.println(); + } + } + + System.out.println("\nNumber of Achilles numbers with:"); + for (int d = 2; d <= maxDigits; d++) { + int ac = an.getAchilles(d - 1, d).size(); + System.out.printf("%2d digits: %d\n", d, ac); + } + } } diff --git a/Task/Ackermann-function/Bruijn/ackermann-function.bruijn b/Task/Ackermann-function/Bruijn/ackermann-function.bruijn new file mode 100644 index 0000000000..87c110fc1a --- /dev/null +++ b/Task/Ackermann-function/Bruijn/ackermann-function.bruijn @@ -0,0 +1,15 @@ +:import std/Combinator . +:import std/Number/Unary U +:import std/Math . + +# unary ackermann +ackermann-unary [0 [[U.inc 0 1 (+1u)]] U.inc] + +:test (ackermann-unary (+0u) (+0u)) ((+1u)) +:test (ackermann-unary (+3u) (+4u)) ((+125u)) + +# ternary ackermann (lower space complexity) +ackermann-ternary y [[[=?1 ++0 (=?0 (2 --1 (+1)) (2 --1 (2 1 --0)))]]] + +:test ((ackermann-ternary (+0) (+0)) =? (+1)) ([[1]]) +:test ((ackermann-ternary (+3) (+4)) =? (+125)) ([[1]]) diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index 8c2541a05d..fc46c62750 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -18,9 +18,9 @@ ackermann(m,n) public program() { - for(int i:=0, i <= 3, i += 1) + for(int i:=0; i <= 3; i += 1) { - for(int j := 0, j <= 5, j += 1) + for(int j := 0; j <= 5; j += 1) { console.printLine("A(",i,",",j,")=",ackermann(i,j)) } diff --git a/Task/Ackermann-function/Refal/ackermann-function.refal b/Task/Ackermann-function/Refal/ackermann-function.refal new file mode 100644 index 0000000000..211834abf3 --- /dev/null +++ b/Task/Ackermann-function/Refal/ackermann-function.refal @@ -0,0 +1,9 @@ +$ENTRY Go { + = 2)} +end isArithmetic + +on task() + set output to {linefeed & "The first 100 arithmetic numbers are:"} + set {n, hitCount, compositeCount, pad} to {0, 0, 0, " "} + repeat 10 times + set row to {} + set targetCount to hitCount + 10 + repeat until (hitCount = targetCount) + set n to n + 1 + tell isArithmetic(n) to if (its arithmetic) then + set hitCount to hitCount + 1 + if (its composite) then set compositeCount to compositeCount + 1 + set row's end to text -4 thru -1 of (pad & n) + end if + end repeat + set output's end to join(row, "") + end repeat + repeat with targetCount in {1000, 10000, 100000, 1000000} + repeat while (hitCount < targetCount) + set n to n + 1 + tell isArithmetic(n) to if (its arithmetic) then + set hitCount to hitCount + 1 + if (its composite) then set compositeCount to compositeCount + 1 + end if + end repeat + set output's end to (linefeed & "The " & targetCount & "th arithmetic number is " & n) & ¬ + (linefeed & "(" & compositeCount & " composite numbers up to here)") + end repeat + + return join(output, linefeed) +end task + +on join(lst, delim) + set astid to AppleScript's text item delimiters + set AppleScript's text item delimiters to delim + set txt to lst as text + set AppleScript's text item delimiters to astid + return txt +end join + +task() diff --git a/Task/Arithmetic-numbers/AppleScript/arithmetic-numbers-2.applescript b/Task/Arithmetic-numbers/AppleScript/arithmetic-numbers-2.applescript new file mode 100644 index 0000000000..58eb79803e --- /dev/null +++ b/Task/Arithmetic-numbers/AppleScript/arithmetic-numbers-2.applescript @@ -0,0 +1,24 @@ +" +The first 100 arithmetic numbers are: + 1 3 5 6 7 11 13 14 15 17 + 19 20 21 22 23 27 29 30 31 33 + 35 37 38 39 41 42 43 44 45 46 + 47 49 51 53 54 55 56 57 59 60 + 61 62 65 66 67 68 69 70 71 73 + 77 78 79 83 85 86 87 89 91 92 + 93 94 95 96 97 99 101 102 103 105 + 107 109 110 111 113 114 115 116 118 119 + 123 125 126 127 129 131 132 133 134 135 + 137 138 139 140 141 142 143 145 147 149 + +The 1000th arithmetic number is 1361 +(782 composite numbers up to here) + +The 10000th arithmetic number is 12953 +(8458 composite numbers up to here) + +The 100000th arithmetic number is 125587 +(88219 composite numbers up to here) + +The 1000000th arithmetic number is 1228663 +(905043 composite numbers up to here)" diff --git a/Task/Arithmetic-numbers/C-sharp/arithmetic-numbers.cs b/Task/Arithmetic-numbers/C-sharp/arithmetic-numbers.cs new file mode 100644 index 0000000000..62a285d4e1 --- /dev/null +++ b/Task/Arithmetic-numbers/C-sharp/arithmetic-numbers.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class ArithmeticNumbers +{ + public static void Main(string[] args) + { + int arithmeticCount = 0; + int compositeCount = 0; + int n = 1; + + while (arithmeticCount <= 1_000_000) + { + var factors = Factors(n); + int sum = factors.Sum(); + if (sum % factors.Count == 0) + { + arithmeticCount++; + if (factors.Count > 2) + { + compositeCount++; + } + if (arithmeticCount <= 100) + { + Console.Write($"{n,3}{(arithmeticCount % 10 == 0 ? "\n" : " ")}"); + } + if (new[] { 1_000, 10_000, 100_000, 1_000_000 }.Contains(arithmeticCount)) + { + Console.WriteLine(); + Console.WriteLine($"{arithmeticCount}th arithmetic number is {n}"); + Console.WriteLine($"Number of composite arithmetic numbers <= {n}: {compositeCount}"); + } + } + n++; + } + } + + private static HashSet Factors(int number) + { + var result = new HashSet { 1, number }; + int i = 2; + int j; + while ((j = number / i) >= i) + { + if (i * j == number) + { + result.Add(i); + result.Add(j); + } + i++; + } + return result; + } +} diff --git a/Task/Arithmetic-numbers/Scala/arithmetic-numbers.scala b/Task/Arithmetic-numbers/Scala/arithmetic-numbers.scala new file mode 100644 index 0000000000..935ecafb6b --- /dev/null +++ b/Task/Arithmetic-numbers/Scala/arithmetic-numbers.scala @@ -0,0 +1,27 @@ +object ArithmeticNumbers extends App { + var arithmeticCount = 0 + var compositeCount = 0 + var n = 1 + + while (arithmeticCount <= 1_000_000) { + val factors = findFactors(n) + val sum = factors.sum + if (sum % factors.size == 0) { + arithmeticCount += 1 + if (factors.size > 2) compositeCount += 1 + if (arithmeticCount <= 100) { + print(f"$n%3d" + (if (arithmeticCount % 10 == 0) "\n" else " ")) + } + if (List(1_000, 10_000, 100_000, 1_000_000).contains(arithmeticCount)) { + println() + println(s"${arithmeticCount}th arithmetic number is $n") + println(s"Number of composite arithmetic numbers <= $n: $compositeCount") + } + } + n += 1 + } + + def findFactors(number: Int): Set[Int] = { + (1 to number).filter(number % _ == 0).toSet + } +} diff --git a/Task/Array-concatenation/Free-Pascal-Lazarus/array-concatenation-3.pas b/Task/Array-concatenation/Free-Pascal-Lazarus/array-concatenation-3.pas new file mode 100644 index 0000000000..1f7026a11f --- /dev/null +++ b/Task/Array-concatenation/Free-Pascal-Lazarus/array-concatenation-3.pas @@ -0,0 +1,21 @@ +Program arrayConcat; + +{$mode delphi} + +type + TDynArr = array of integer; + +var + i: integer; + arr1, arr2, arrSum : TDynArr; + +begin + arr1 := [1, 2, 3]; + arr2 := [4, 5, 6]; + + arrSum := arr1 + arr2; + + for i in arrSum do + write(i, ' '); + writeln; +end. diff --git a/Task/Array-length/K/array-length.k b/Task/Array-length/K/array-length.k new file mode 100644 index 0000000000..03a2f69162 --- /dev/null +++ b/Task/Array-length/K/array-length.k @@ -0,0 +1 @@ +#("apple";"orange") diff --git a/Task/Arrays/Elena/arrays-2.elena b/Task/Arrays/Elena/arrays-2.elena index 04e4f5031f..e857d71772 100644 --- a/Task/Arrays/Elena/arrays-2.elena +++ b/Task/Arrays/Elena/arrays-2.elena @@ -1,4 +1,4 @@ - var array := system'Array.allocate:3; + var array := system'Array.allocate(3); array[0] := 1; array[1] := 2; array[2] := 3; diff --git a/Task/Arrays/Elena/arrays-4.elena b/Task/Arrays/Elena/arrays-4.elena index 8e9883dd42..a47b18d5b5 100644 --- a/Task/Arrays/Elena/arrays-4.elena +++ b/Task/Arrays/Elena/arrays-4.elena @@ -1,6 +1,6 @@ var dynamicArray := new system'collections'ArrayList(); - dynamicArray.append:1; - dynamicArray.append:2; - dynamicArray.append:4; + dynamicArray.append(1); + dynamicArray.append(2); + dynamicArray.append(4); dynamicArray[2] := 3; diff --git a/Task/Associative-array-Iteration/Kotlin/associative-array-iteration.kotlin b/Task/Associative-array-Iteration/Kotlin/associative-array-iteration.kotlin index 94173d64a3..7b58f2a325 100644 --- a/Task/Associative-array-Iteration/Kotlin/associative-array-iteration.kotlin +++ b/Task/Associative-array-Iteration/Kotlin/associative-array-iteration.kotlin @@ -1,8 +1,8 @@ -fun main(a: Array) { +fun main() { val map = mapOf("hello" to 1, "world" to 2, "!" to 3) with(map) { - entries.forEach { println("key = ${it.key}, value = ${it.value}") } + forEach { println("key = ${it.key}, value = ${it.value}") } keys.forEach { println("key = $it") } values.forEach { println("value = $it") } } diff --git a/Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean.apl b/Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean-1.apl similarity index 100% rename from Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean.apl rename to Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean-1.apl diff --git a/Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean-2.apl b/Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean-2.apl new file mode 100644 index 0000000000..ba7d632d12 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean-2.apl @@ -0,0 +1,3 @@ + Avg←{(+⌿⍵)÷≢⍵} + Avg 1 2 3 4 5 6 +3.5 diff --git a/Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean-3.apl b/Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean-3.apl new file mode 100644 index 0000000000..07c2a8b173 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/APL/averages-arithmetic-mean-3.apl @@ -0,0 +1,3 @@ + Avg← +⌿÷≢ + Avg 1 2 3 4 5 6 +3.5 diff --git a/Task/Averages-Arithmetic-mean/RPL/averages-arithmetic-mean.rpl b/Task/Averages-Arithmetic-mean/RPL/averages-arithmetic-mean.rpl deleted file mode 100644 index f47f99470a..0000000000 --- a/Task/Averages-Arithmetic-mean/RPL/averages-arithmetic-mean.rpl +++ /dev/null @@ -1,4 +0,0 @@ -1 2 3 5 7 -AMEAN - << CLEAR DEPTH DUP 'N' STO →LIST ΣLIST N / >> -3.6 diff --git a/Task/Averages-Mean-time-of-day/ALGOL-68/averages-mean-time-of-day.alg b/Task/Averages-Mean-time-of-day/ALGOL-68/averages-mean-time-of-day.alg new file mode 100644 index 0000000000..82c7d87400 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/ALGOL-68/averages-mean-time-of-day.alg @@ -0,0 +1,46 @@ +BEGIN # Mean time of day mapping time to angles # + + # code from the Averages/Mean angle task - angles are in degrees # + PROC mean angle = ([]REAL angles)REAL: + ( + INT size = UPB angles - LWB angles + 1; + REAL y part := 0, x part := 0; + FOR i FROM LWB angles TO UPB angles DO + x part +:= cos (angles[i] * pi / 180); + y part +:= sin (angles[i] * pi / 180) + OD; + + arc tan2 (y part / size, x part / size) * 180 / pi + ); + # end code from the Averages/Mean angle task # + + MODE TIME = STRUCT( INT hh, mm, ss ); + + OP TOANGLE = ( TIME t )REAL: ( ( ( ( ( ss OF t / 60 ) + mm OF t ) / 60 ) + hh OF t ) * 360 ) / 24; + OP TOTIME = ( REAL a )TIME: + BEGIN + REAL t := ( a * 24 ) / 360; + WHILE t < 0 DO t +:= 24 OD; + WHILE t > 24 DO t -:= 24 OD; + INT hh = ENTIER t; + t -:= hh *:= 60; + INT mm = ENTIER t; + INT ss = ENTIER ( ( t - mm ) * 60 ); + ( hh, mm, ss ) + END # TOTIME # ; + + PROC mean time = ( []TIME times )TIME: + BEGIN + [ LWB times : UPB times ]REAL angles; + FOR i FROM LWB times TO UPB times DO angles[ i ] := TOANGLE times[ i ] OD; + TOTIME mean angle( angles ) + END # mean time # ; + + OP SHOW = ( TIME t )VOID: + BEGIN + PROC d2 = ( INT n )STRING: IF n < 10 THEN "0" ELSE "" FI + whole( n, 0 ); + print( ( d2( hh OF t ), ":", d2( mm OF t ), ":", d2( ss OF t ) ) ) + END # show time # ; + + SHOW mean time( ( ( 23,00,17 ), ( 23,40,20 ), ( 00,12,45 ), ( 00,17,19 ) ) ) +END diff --git a/Task/Averages-Median/Elena/averages-median.elena b/Task/Averages-Median/Elena/averages-median.elena index 12548a8e13..8dd0572594 100644 --- a/Task/Averages-Median/Elena/averages-median.elena +++ b/Task/Averages-Median/Elena/averages-median.elena @@ -16,7 +16,7 @@ extension op else { var middleIndex := len / 2; - if (len.mod:2 == 0) + if (len.mod(2) == 0) { ^ (sorted[middleIndex - 1] + sorted[middleIndex]) / 2 } diff --git a/Task/Averages-Median/Swift/averages-median-1.swift b/Task/Averages-Median/Swift/averages-median-1.swift new file mode 100644 index 0000000000..bc352bebf2 --- /dev/null +++ b/Task/Averages-Median/Swift/averages-median-1.swift @@ -0,0 +1,47 @@ + // Utility to aid easy type conversion +extension Double { + init(withNum v: any Numeric) { + switch v { + case let ii as any BinaryInteger: self.init(ii) + case let ff as any BinaryFloatingPoint: self.init(ff) + default: self.init() + } + } +} + +extension Array where Element: Numeric & Comparable { + // Helper func for random element in range + func randomElement(within: Range) -> Element { + return self[.random(in: within)] + } + + mutating func median() -> Double? { + switch self.count { + case 0: return nil + case 1: return Double(withNum: self[0]) + case 2: return self.reduce(0, {sum,this in sum + Double(withNum: this)/2.0}) + default: break + } + let pTarget: Int = self.count / 2 + 1 + let resultSetLen: Int = self.count.isMultiple(of: 2) ? 2 : 1 + func divideAndConquer(bottom: Int, top: Int, goal: Int) -> Int { + var (lower,upper) = (bottom,top) + while true { + let splitVal = self.randomElement(within: lower.. splitVal}) + switch partitionIndex { + case goal: return partitionIndex + case .. p > n); + countMap := countMap.Values.sort::(p,n => p > n); var max := countMap.FirstMember; ^ countMap - .filterBy:(kv => max.equal(kv.Value)) - .selectBy:(kv => kv.Key) + .filterBy::(kv => max.equal(kv.Value)) + .selectBy::(kv => kv.Key) .toArray() } } public program() { - var array1 := new int[]{1, 1, 2, 4, 4}; - var array2 := new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17}; - var array3 := new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"}; + var array1 := new int[]{1, 1, 2, 4, 4}; + var array2 := new int[]{1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17}; + var array3 := new object[]{1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"}; - console - .printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")") - .printLine("mode of (",array2.asEnumerable(),") is (",array2.Mode,")") - .printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")") - .readChar() + console + .printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")") + .printLine("mode of (",array2.asEnumerable(),") is (",array2.Mode,")") + .printLine("mode of (",array3.asEnumerable(),") is (",array3.Mode,")") + .readChar() } diff --git a/Task/Averages-Pythagorean-means/FutureBasic/averages-pythagorean-means.basic b/Task/Averages-Pythagorean-means/FutureBasic/averages-pythagorean-means.basic new file mode 100644 index 0000000000..8949b2b5c9 --- /dev/null +++ b/Task/Averages-Pythagorean-means/FutureBasic/averages-pythagorean-means.basic @@ -0,0 +1,14 @@ +Double ari = 1, geo = 0, har = 0 +Short i, n = 10 + +for i = 1 to n + ari += i + geo *= i + har += 1 \ i +next + +print "ari:", ari \ n +print "geo:", geo^( 1 \ n ) +print "har:", n \ har + +handleevents diff --git a/Task/Averages-Pythagorean-means/Swift/averages-pythagorean-means.swift b/Task/Averages-Pythagorean-means/Swift/averages-pythagorean-means.swift new file mode 100644 index 0000000000..0c7cc0a752 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Swift/averages-pythagorean-means.swift @@ -0,0 +1,33 @@ + // Utility for easy creation of Double from any Numeric +extension Double { + init(withNum v: any Numeric) { + switch v { + case let ii as any BinaryInteger: self.init(ii) + case let ff as any BinaryFloatingPoint: self.init(ff) + default: self.init() + } + } +} + // Extension for numeric collections +extension Collection where Element: Numeric { + var arithmeticMean: Double { + self.reduce(0.0, {$0 + Double(withNum: $1)})/Double(self.count) + } + var geometricMean: Double { + pow(self.reduce(1.0, {$0 * Double(withNum: $1)}), 1.0/Double(self.count)) + } + var harmonicMean: Double { + Double(self.count) / self.reduce(0.0, {$0 + 1.0/Double(withNum:$1)}) + } +} +//Usage: +var c: [Int] = (1...10).map {$0} + +print(c.arithmeticMean) +print(c.geometricMean) +print(c.harmonicMean) + +// output: +// 5.5 +// 4.528728688116765 +// 3.414171521474055 diff --git a/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena b/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena index c39c562aed..66c1f5e9b3 100644 --- a/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena +++ b/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena @@ -5,7 +5,7 @@ import system'math; extension op { get RootMeanSquare() - = (self.selectBy:(x => x * x).summarize(Real.new()) / self.Length).sqrt(); + = (self.selectBy::(x => x * x).summarize(Real.new()) / self.Length).sqrt(); } public program() diff --git a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena index c3776445db..c1663edc5a 100644 --- a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena +++ b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena @@ -20,10 +20,10 @@ class SMA var count := theList.Length; count => 0 { ^0.0r } - : { + ! { if (count > thePeriod) { - theList.removeAt:0; + theList.removeAt(0); count := thePeriod }; @@ -35,19 +35,21 @@ class SMA } } +// --- Program --- + public program() { - var SMA3 := SMA.new:3; - var SMA5 := SMA.new:5; + var SMA3 := SMA.new(3); + var SMA5 := SMA.new(5); - for (int i := 1, i <= 5, i += 1) { - console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:i); - console.printLine("sma5 + ", i, " = ", SMA5.append:i) + for (int i := 1; i <= 5; i += 1) { + console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append(i)); + console.printLine("sma5 + ", i, " = ", SMA5.append(i)) }; - for (int i := 5, i >= 1, i -= 1) { - console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:i); - console.printLine("sma5 + ", i, " = ", SMA5.append:i) + for (int i := 5; i >= 1; i -= 1) { + console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append(i)); + console.printLine("sma5 + ", i, " = ", SMA5.append(i)) }; console.readChar() diff --git a/Task/B-zier-curves-Intersections/C-sharp/b-zier-curves-intersections.cs b/Task/B-zier-curves-Intersections/C-sharp/b-zier-curves-intersections.cs new file mode 100644 index 0000000000..ab344ade1e --- /dev/null +++ b/Task/B-zier-curves-Intersections/C-sharp/b-zier-curves-intersections.cs @@ -0,0 +1,180 @@ +using System; +using System.Collections.Generic; + +public class BezierCurveIntersection +{ + public static void Main(string[] args) + { + QuadCurve vertical = new QuadCurve(new QuadSpline(-1.0, 0.0, 1.0), new QuadSpline(0.0, 10.0, 0.0)); + // QuadCurve vertical represents the Bezier curve having control points (-1, 0), (0, 10) and (1, 0) + QuadCurve horizontal = new QuadCurve(new QuadSpline(2.0, -8.0, 2.0), new QuadSpline(1.0, 2.0, 3.0)); + // QuadCurve horizontal represents the Bezier curve having control points (2, 1), (-8, 2) and (2, 3) + + Console.WriteLine("The points of intersection are:"); + List intersects = FindIntersects(vertical, horizontal); + foreach (Point intersect in intersects) + { + Console.WriteLine($"( {intersect.X,9:0.000000}, {intersect.Y,9:0.000000} )"); + } + } + + private static List FindIntersects(QuadCurve p, QuadCurve q) + { + List result = new List(); + Stack stack = new Stack(); + stack.Push(p); + stack.Push(q); + + while (stack.Count > 0) + { + QuadCurve pp = stack.Pop(); + QuadCurve qq = stack.Pop(); + List objects = TestIntersection(pp, qq); + bool accepted = (bool)objects[0]; + bool excluded = (bool)objects[1]; + Point intersect = (Point)objects[2]; + + if (accepted) + { + if (!SeemsToBeDuplicate(result, intersect)) + { + result.Add(intersect); + } + } + else if (!excluded) + { + QuadCurve p0 = new QuadCurve(); + QuadCurve q0 = new QuadCurve(); + QuadCurve p1 = new QuadCurve(); + QuadCurve q1 = new QuadCurve(); + SubdivideQuadCurve(pp, 0.5, p0, p1); + SubdivideQuadCurve(qq, 0.5, q0, q1); + stack.Push(p0); + stack.Push(q0); + stack.Push(p0); + stack.Push(q1); + stack.Push(p1); + stack.Push(q0); + stack.Push(p1); + stack.Push(q1); + } + } + return result; + } + + private static bool SeemsToBeDuplicate(List intersects, Point point) + { + foreach (Point intersect in intersects) + { + if (Math.Abs(intersect.X - point.X) < Spacing && Math.Abs(intersect.Y - point.Y) < Spacing) + { + return true; + } + } + return false; + } + + private static List TestIntersection(QuadCurve p, QuadCurve q) + { + double pxMin = Math.Min(Math.Min(p.X.C0, p.X.C1), p.X.C2); + double pyMin = Math.Min(Math.Min(p.Y.C0, p.Y.C1), p.Y.C2); + double pxMax = Math.Max(Math.Max(p.X.C0, p.X.C1), p.X.C2); + double pyMax = Math.Max(Math.Max(p.Y.C0, p.Y.C1), p.Y.C2); + + double qxMin = Math.Min(Math.Min(q.X.C0, q.X.C1), q.X.C2); + double qyMin = Math.Min(Math.Min(q.Y.C0, q.Y.C1), q.Y.C2); + double qxMax = Math.Max(Math.Max(q.X.C0, q.X.C1), q.X.C2); + double qyMax = Math.Max(Math.Max(q.Y.C0, q.Y.C1), q.Y.C2); + + bool accepted = false; + bool excluded = true; + Point intersect = new Point(0.0, 0.0); + + if (RectanglesOverlap(pxMin, pyMin, pxMax, pyMax, qxMin, qyMin, qxMax, qyMax)) + { + excluded = false; + double xMin = Math.Max(pxMin, qxMin); + double xMax = Math.Min(pxMax, pxMax); + if (xMax - xMin <= Tolerance) + { + double yMin = Math.Max(pyMin, qyMin); + double yMax = Math.Min(pyMax, qyMax); + if (yMax - yMin <= Tolerance) + { + accepted = true; + intersect = new Point(0.5 * (xMin + xMax), 0.5 * (yMin + yMax)); + } + } + } + return new List { accepted, excluded, intersect }; + } + + private static bool RectanglesOverlap(double xa0, double ya0, double xa1, double ya1, + double xb0, double yb0, double xb1, double yb1) + { + return xb0 <= xa1 && xa0 <= xb1 && yb0 <= ya1 && ya0 <= yb1; + } + + private static void SubdivideQuadCurve(QuadCurve q, double t, QuadCurve u, QuadCurve v) + { + SubdivideQuadSpline(q.X, t, u.X, v.X); + SubdivideQuadSpline(q.Y, t, u.Y, v.Y); + } + + // de Casteljau's algorithm + private static void SubdivideQuadSpline(QuadSpline q, double t, QuadSpline u, QuadSpline v) + { + double s = 1.0 - t; + u.C0 = q.C0; + v.C2 = q.C2; + u.C1 = s * q.C0 + t * q.C1; + v.C1 = s * q.C1 + t * q.C2; + u.C2 = s * u.C1 + t * v.C1; + v.C0 = u.C2; + } + + public struct Point + { + public double X { get; } + public double Y { get; } + + public Point(double x, double y) + { + X = x; + Y = y; + } + } + + public class QuadSpline + { + public double C0 { get; set; } + public double C1 { get; set; } + public double C2 { get; set; } + + public QuadSpline(double c0, double c1, double c2) + { + C0 = c0; + C1 = c1; + C2 = c2; + } + + public QuadSpline() : this(0.0, 0.0, 0.0) { } + } + + public class QuadCurve + { + public QuadSpline X { get; set; } + public QuadSpline Y { get; set; } + + public QuadCurve(QuadSpline x, QuadSpline y) + { + X = x; + Y = y; + } + + public QuadCurve() : this(new QuadSpline(), new QuadSpline()) { } + } + + private const double Tolerance = 0.000_000_1; + private const double Spacing = 10 * Tolerance; +} diff --git a/Task/Babbage-problem/Elena/babbage-problem.elena b/Task/Babbage-problem/Elena/babbage-problem.elena index 4c3a3e0f36..c7c4a77da2 100644 --- a/Task/Babbage-problem/Elena/babbage-problem.elena +++ b/Task/Babbage-problem/Elena/babbage-problem.elena @@ -5,7 +5,7 @@ public program() { var n := 1; - until(n.sqr().mod:1000000 == 269696) + until(n.sqr().mod(1000000) == 269696) { n += 1 }; diff --git a/Task/Babbage-problem/MATLAB/babbage-problem.m b/Task/Babbage-problem/MATLAB/babbage-problem.m new file mode 100644 index 0000000000..5f3d143653 --- /dev/null +++ b/Task/Babbage-problem/MATLAB/babbage-problem.m @@ -0,0 +1,21 @@ +clear all;close all;clc; +BabbageProblem(); + +function BabbageProblem + % Initialize x to 524, as the square root of 269696 is approximately 519.something + x = 524; + + % Loop until the square of x modulo 1000000 equals 269696 + while mod(x^2, 1000000) ~= 269696 + % If the last digit of x is 4, increment x by 2 + % Otherwise, increment x by 8 + if mod(x, 10) == 4 + x = x + 2; + else + x = x + 8; + end + end + + % Display the result + fprintf('The smallest positive integer whose square ends in 269696 = %d\n', x); +end diff --git a/Task/Babylonian-spiral/00-TASK.txt b/Task/Babylonian-spiral/00-TASK.txt index de43fc4687..cc4ed06584 100644 --- a/Task/Babylonian-spiral/00-TASK.txt +++ b/Task/Babylonian-spiral/00-TASK.txt @@ -1,3 +1,4 @@ +f The '''Babylonian spiral''' is a sequence of points in the plane that are created so as to continuously minimally increase in vector length and minimally bend in vector direction, while always moving from point to point on strictly integral coordinates. Of the two criteria diff --git a/Task/Babylonian-spiral/MATLAB/babylonian-spiral.m b/Task/Babylonian-spiral/MATLAB/babylonian-spiral.m new file mode 100644 index 0000000000..53626c7c2c --- /dev/null +++ b/Task/Babylonian-spiral/MATLAB/babylonian-spiral.m @@ -0,0 +1,65 @@ +% Rosetta Code task rosettacode.org/wiki/Babylonian_spiral + +clear all;close all;clc; +% Example usage +fprintf("The first 40 Babylonian spiral points are:\n"); +spiral_points = babylonianspiral(40); +for i = 1:size(spiral_points, 1) + fprintf('(%d, %d) ', spiral_points(i, 1), spiral_points(i, 2)); + if mod(i, 10) == 0 + fprintf('\n'); + end +end + +% For plotting the spiral (requires MATLAB plotting functions) +spiral_points = babylonianspiral(10000); +plot(spiral_points(:, 1), spiral_points(:, 2), 'LineWidth', 1); + + +function points = babylonianspiral(nsteps) +% Get the points for a Babylonian spiral of `nsteps` steps. Origin is at (0, 0) +% with first step one unit in the positive direction along the vertical (y) axis. +% See also: oeis.org/A256111, oeis.org/A297346, oeis.org/A297347 + + persistent squarecache; + if isempty(squarecache) + squarecache = []; + end + + if length(squarecache) <= nsteps + squarecache = [squarecache, arrayfun(@(x) x^2, length(squarecache):nsteps)]; + end + + xydeltas = [0, 0; 0, 1]; + deltaSq = 1; + for i = 1:nsteps-2 + x = xydeltas(end, 1); + y = xydeltas(end, 2); + theta = atan2(y, x); + candidates = []; + while isempty(candidates) + deltaSq = deltaSq + 1; + for k = 1:length(squarecache) + a = squarecache(k); + if a > deltaSq / 2 + break; + end + for j = floor(sqrt(deltaSq)):-1:1 + b = squarecache(j+1); + if a + b < deltaSq + break; + end + if a + b == deltaSq + i = k - 1; + candidates = [candidates; i, j; -i, j; i, -j; -i, -j; ... + j, i; -j, i; j, -i; -j, -i]; + end + end + end + end + [~, idx] = min(arrayfun(@(n) mod(theta - atan2(candidates(n, 2), candidates(n, 1)), 2*pi), 1:size(candidates, 1))); + xydeltas = [xydeltas; candidates(idx, :)]; + end + + points = cumsum(xydeltas); +end diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index 01382c5493..4636698372 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -1,46 +1,50 @@ +// Generate a string with N opening brackets ("[") and N closing brackets ("]"), in some arbitrary order. +// Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), +// none of which mis-nest. + import system'routines; import extensions; import extensions'text; randomBrackets(len) { - if (0 == len) - { - ^emptyString - } - else - { - var brackets := - Array.allocate(len).populate:(i => $91) - + - Array.allocate(len).populate:(i => $93); + if (0 == len) + { + ^emptyString + } + else + { + var brackets := + Array.allocate(len).populate::(i => $91) + + + Array.allocate(len).populate::(i => $93); - brackets := brackets.randomize(len * 2); + brackets := brackets.randomize(len * 2); - ^ brackets.summarize(new StringWriter()).toString() - } + ^ brackets.summarize(new StringWriter()).toString() + } } extension op { - get isBalanced() - { - var counter := new Integer(0); + get isBalanced() + { + var counter := new Integer(0); - self.seekEach:(ch => counter.append((ch==$91).iif(1,-1)) < 0); + self.seekEach::(ch => counter.append((ch==$91).iif(1,-1)) < 0); - ^ (0 == counter) - } + ^ (0 == counter) + } } public program() { - for(int len := 0, len < 9, len += 1) - { - var str := randomBrackets(len); + for(int len := 0; len < 9; len += 1) + { + var str := randomBrackets(len); - console.printLine("""",str,"""",str.isBalanced ? " is balanced" : " is not balanced") - }; + console.printLine("""",str,"""",str.isBalanced ? " is balanced" : " is not balanced") + }; - console.readChar() + console.readChar() } diff --git a/Task/Balanced-ternary/Bruijn/balanced-ternary.bruijn b/Task/Balanced-ternary/Bruijn/balanced-ternary.bruijn new file mode 100644 index 0000000000..5f7aa99ad9 --- /dev/null +++ b/Task/Balanced-ternary/Bruijn/balanced-ternary.bruijn @@ -0,0 +1,100 @@ +:import std/Combinator . +:import std/Logic . +:import std/Pair . + +# negative trit indicating coefficient of (-1) +t⁻ [[[2]]] + +# positive trit indicating coefficient of (+1) +t⁺ [[[1]]] + +# zero trit indicating coefficient of 0 +t⁰ [[[0]]] + +# shifts a negative trit into a balanced ternary number +↑⁻‣ [[[[[2 (4 3 2 1 0)]]]]] + +# shifts a positive trit into a balanced ternary number +↑⁺‣ [[[[[1 (4 3 2 1 0)]]]]] + +# shifts a zero trit into a balanced ternary number +↑⁰‣ [[[[[0 (4 3 2 1 0)]]]]] + +# shifts a specified trit into a balanced ternary number +…↑… [[[[[[5 2 1 0 (4 3 2 1 0)]]]]]] + +# negates a balanced ternary number +-‣ [[[[[4 3 1 2 0]]]]] + +# increments a balanced ternary number (can introduce leading 0s) +++‣ [~(0 z a⁻ a⁺ a⁰)] + z (+0) : (+1) + a⁻ &[[↑⁻1 : ↑⁰1]] + a⁺ &[[↑⁺1 : ↑⁻0]] + a⁰ &[[↑⁰1 : ↑⁺1]] + +# decrements a balanced ternary number (can introduce leading 0s) +--‣ [~(0 z a⁻ a⁺ a⁰)] + z (+0) : (-1) + a⁻ &[[↑⁻1 : ↑⁺0]] + a⁺ &[[↑⁺1 : ↑⁰1]] + a⁰ &[[↑⁰1 : ↑⁻1]] + +# converts the normal balanced ternary representation into abstract form +→^‣ [0 z a⁻ a⁺ a⁰] + z (+0) + a⁻ [[[[[2 4]]]]] + a⁺ [[[[[1 4]]]]] + a⁰ [[[[[0 4]]]]] + +# converts the abstracted balanced ternary representation back to normal +→_‣ y [[0 z a⁻ a⁺ a⁰]] + z (+0) + a⁻ [↑⁻(2 0)] + a⁺ [↑⁺(2 0)] + a⁰ [↑⁰(2 0)] + +# adds two balanced ternary numbers (can introduce leading 0s) +…+… [[[c (0 z a⁻ a⁺ a⁰)] 1 →^0]] + b⁻ [1 ↑⁺(3 0 t⁻) ↑⁰(3 0 t⁰) ↑⁻(3 0 t⁰)] + b⁰ [1 ↑ (3 0 t⁰)] + b⁺ [1 ↑⁰(3 0 t⁰) ↑⁻(3 0 t⁺) ↑⁺(3 0 t⁰)] + a⁻ [[[1 (b⁻ 1) b⁻' b⁰ b⁻]]] + b⁻' [1 ↑⁰(3 0 t⁻) ↑⁻(3 0 t⁰) ↑⁺(3 0 t⁻)] + a⁺ [[[1 (b⁺ 1) b⁰ b⁺' b⁺]]] + b⁺' [1 ↑⁺(3 0 t⁰) ↑⁰(3 0 t⁺) ↑⁻(3 0 t⁺)] + a⁰ [[[1 (b⁰ 1) b⁻ b⁺ b⁰]]] + z [[0 --(→_1) ++(→_1) →_1]] + c [[1 0 t⁰]] + +# subtracts two balanced ternary numbers (can introduce leading 0s) +…-… [[1 + -0]] + +# multiplicates two balanced ternary numbers (can introduce leading 0s) +…⋅… [[1 z a⁻ a⁺ a⁰]] + z (+0) + a⁻ [↑⁰0 - 1] + a⁺ [↑⁰0 + 1] + a⁰ [↑⁰0] + +# true if balanced ternary number is zero +=?‣ [0 true [false] [false] i] + +# true if two balanced ternary numbers are equal +# → ignores leading 0s! +…=?… [[[0 z a⁻ a⁺ a⁰] 1 →^0]] + z [=?(→_0)] + a⁻ [[0 false [2 0] [false] [false]]] + a⁺ [[0 false [false] [2 0] [false]]] + a⁰ [[0 (1 0) [false] [false] [2 0]]] + +main [[0]] + +# --- tests/examples --- + +:test ((-42) + (-1) =? (-43)) (true) +:test ((+1) + (+2) =? (+3)) (true) +:test ((-42) - (-1) =? (-41)) (true) +:test ((+1) - (+2) =? (-1)) (true) +:test ((-1) ⋅ (+42) =? (-42)) (true) +:test ((+3) ⋅ (+11) =? (+33)) (true) diff --git a/Task/Base64-decode-data/Swift/base64-decode-data.swift b/Task/Base64-decode-data/Swift/base64-decode-data.swift new file mode 100644 index 0000000000..88b8b847f8 --- /dev/null +++ b/Task/Base64-decode-data/Swift/base64-decode-data.swift @@ -0,0 +1,10 @@ +import Foundation + +let input = """ +VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g= +""" + +if let decoded = Data(base64Encoded: input), +let str = String(data: decoded, encoding: .utf8) { + print( str ) +} diff --git a/Task/Benfords-law/MATLAB/benfords-law.m b/Task/Benfords-law/MATLAB/benfords-law.m new file mode 100644 index 0000000000..290a42ccc1 --- /dev/null +++ b/Task/Benfords-law/MATLAB/benfords-law.m @@ -0,0 +1,57 @@ +benfords_law(); + +function benfords_law + % Benford's Law + P = @(d) log10(1 + 1./d); + + % Benford function + function counts = benford(numbers) + firstdigit = @(n) floor(mod(n / 10^floor(log10(n)), 10)); + counts = zeros(1, 9); + for i = 1:length(numbers) + digit = firstdigit(numbers(i)); + if digit ~= 0 + counts(digit) = counts(digit) + 1; + end + end + counts = counts ./ sum(counts); + end + + % Generate Fibonacci numbers + function fibNums = fibonacci(n) + fibNums = zeros(1, n); + a = 0; + b = 1; + for i = 1:n + c = b; + b = a + b; + a = c; + fibNums(i) = b; + end + end + + % Sample + sample = fibonacci(1000); + + % Observed and expected frequencies + observed = benford(sample) * 100; + expected = arrayfun(P, 1:9) * 100; + + % Table + mytable = [1:9; observed; expected]'; + + % Plotting + bar(1:9, observed); + hold on; + plot(1:9, expected, 'LineWidth', 2); + hold off; + title("Benford's Law"); + xlabel("First Digit"); + ylabel("Frequency %"); + legend("1000 Fibonacci Numbers", "P(d) = log10(1 + 1/d)"); + xticks(1:9); + + % Displaying the results + fprintf("Benford's Law\nFrequency of first digit\nin 1000 Fibonacci numbers\n"); + disp(table(mytable(:,1),mytable(:,2),mytable(:,3),'VariableNames',{'digit', 'observed(%)', 'expected(%)'})) +end diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index e06155442f..99e99cba05 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -4,45 +4,45 @@ import extensions'text; extension op { - get Shuffled() - { - var original := self.toArray(); - var shuffled := self.toArray(); + get Shuffled() + { + var original := self.toArray(); + var shuffled := self.toArray(); - for (int i := 0, i < original.Length, i += 1) { - for (int j := 0, j < original.Length, j += 1) { - if (i != j && original[i] != shuffled[j] && original[j] != shuffled[i]) - { - shuffled.exchange(i,j) - } + for (int i := 0; i < original.Length; i += 1) { + for (int j := 0; j < original.Length; j += 1) { + if (i != j && original[i] != shuffled[j] && original[j] != shuffled[i]) + { + shuffled.exchange(i,j) } - }; + } + }; - ^ shuffled.summarize(new StringWriter()).toString() - } + ^ shuffled.summarize(new StringWriter()).toString() + } - score(originalText) - { - var shuffled := self.toArray(); - var original := originalText.toArray(); - int score := 0; + score(originalText) + { + var shuffled := self.toArray(); + var original := originalText.toArray(); + int score := 0; - for (int i := 0, i < original.Length, i += 1) { - if (original[i] == shuffled[i]) { score += 1 } - }; + for (int i := 0; i < original.Length; i += 1) { + if (original[i] == shuffled[i]) { score += 1 } + }; - ^ score - } + ^ score + } } public program() { - new string[]{"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}.forEach:(s) - { - var shuffled_s := s.Shuffled; + new string[]{"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}.forEach::(s) + { + var shuffled_s := s.Shuffled; - console.printLine("The best shuffle of ",s," is ",shuffled_s,"(",shuffled_s.score(s),")") - }; + console.printLine("The best shuffle of ",s," is ",shuffled_s,"(",shuffled_s.score(s),")") + }; - console.readChar() + console.readChar() } diff --git a/Task/Bifid-cipher/C-sharp/bifid-cipher.cs b/Task/Bifid-cipher/C-sharp/bifid-cipher.cs new file mode 100644 index 0000000000..c00f4074d4 --- /dev/null +++ b/Task/Bifid-cipher/C-sharp/bifid-cipher.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Drawing; + +public class BifidCipher +{ + public static void Main(string[] args) + { + string message1 = "ATTACKATDAWN"; + string message2 = "FLEEATONCE"; + string message3 = "The invasion will start on the first of January".ToUpper().Replace(" ", ""); + + Bifid bifid1 = new Bifid(5, "ABCDEFGHIKLMNOPQRSTUVWXYZ"); + Bifid bifid2 = new Bifid(5, "BGWKZQPNDSIOAXEFCLUMTHYVR"); + + RunTest(bifid1, message1); + RunTest(bifid2, message2); + RunTest(bifid2, message1); + RunTest(bifid1, message2); + + Bifid bifid3 = new Bifid(6, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"); + RunTest(bifid3, message3); + } + + private static void RunTest(Bifid bifid, string message) + { + Console.WriteLine("Using Polybius square:"); + bifid.Display(); + Console.WriteLine("Message: " + message); + string encrypted = bifid.Encrypt(message); + Console.WriteLine("Encrypted: " + encrypted); + string decrypted = bifid.Decrypt(encrypted); + Console.WriteLine("Decrypted: " + decrypted); + Console.WriteLine(); + } +} + +public class Bifid +{ + private char[,] grid; + private Dictionary coordinates = new Dictionary(); + + public Bifid(int n, string text) + { + if (text.Length != n * n) + { + throw new ArgumentException("Incorrect length of text"); + } + + grid = new char[n, n]; + int row = 0; + int col = 0; + + foreach (char ch in text) + { + grid[row, col] = ch; + coordinates[ch] = new Point(row, col); + col += 1; + if (col == n) + { + col = 0; + row += 1; + } + } + + if (n == 5) + { + coordinates['J'] = coordinates['I']; + } + } + + public string Encrypt(string text) + { + List rowOne = new List(); + List rowTwo = new List(); + + foreach (char ch in text) + { + Point coordinate = coordinates[ch]; + rowOne.Add(coordinate.X); + rowTwo.Add(coordinate.Y); + } + + rowOne.AddRange(rowTwo); + var result = new System.Text.StringBuilder(); + + for (int i = 0; i < rowOne.Count - 1; i += 2) + { + result.Append(grid[rowOne[i], rowOne[i + 1]]); + } + + return result.ToString(); + } + + public string Decrypt(string text) + { + List row = new List(); + + foreach (char ch in text) + { + Point coordinate = coordinates[ch]; + row.Add(coordinate.X); + row.Add(coordinate.Y); + } + + int middle = row.Count / 2; + List rowOne = row.GetRange(0, middle); + List rowTwo = row.GetRange(middle, row.Count - middle); + var result = new System.Text.StringBuilder(); + + for (int i = 0; i < middle; i++) + { + result.Append(grid[rowOne[i], rowTwo[i]]); + } + + return result.ToString(); + } + + public void Display() + { + for (int i = 0; i < grid.GetLength(0); i++) + { + for (int j = 0; j < grid.GetLength(1); j++) + { + Console.Write(grid[i, j] + " "); + } + Console.WriteLine(); + } + } +} diff --git a/Task/Bifid-cipher/FutureBasic/bifid-cipher.basic b/Task/Bifid-cipher/FutureBasic/bifid-cipher.basic new file mode 100644 index 0000000000..e6b2e686af --- /dev/null +++ b/Task/Bifid-cipher/FutureBasic/bifid-cipher.basic @@ -0,0 +1,62 @@ +clear local fn recode( t as CFStringRef, code as CFStringRef ) as CFStringRef + CFStringRef s = @"" + Short i, k, w = sqr( len( code ) ) + + for i = 0 to len( t ) - 1 step 2 + k = intval( mid( t, i, 2 ) ) // Get ‘coordinates’ of char in code string + k = w * ( k / 10 ) + k mod 10 + s = fn StringByAppendingString( s, mid( code, k, 1 ) ) + next + +end fn = s + +// + +clear local fn encode( s as CFStringRef, code as CFStringRef ) as CFStringRef + CFStringRef a = @"", b = @"", c + Short i, k, w = sqr( len( code ) ) + if w == 5 then s = fn StringByReplacingOccurrencesOfString( s, @"J", @"I" ) + print s + + for i = 0 to len( s ) - 1 + c = mid( s, i, 1 ) + k = instr( 0, code, c ) // Put row in one string, column in the other + a = fn StringByAppendingString( a, fn StringWithFormat( @"%d", k / w ) ) + b = fn StringByAppendingString( b, fn StringWithFormat( @"%d", k mod w ) ) + next + + a = fn StringByAppendingString( a, b ) // Combine the two strings, and recode + +end fn = fn recode( a, code ) + +// + +clear local fn decode( s as CFStringRef, code as CFStringRef ) as CFStringRef + CFStringRef a = @"", b = @"", c + Short i, k, w = sqr( len( code ) ) + + for i = 0 to ( len( s ) - 1 ) + c = mid( s, i, 1 ) + k = instr( 0, code, c ) // Put row and columm in one long string + a = fn StringByAppendingString( a, fn StringWithFormat( @"%d%d", k / w, k mod w ) ) + next + + for i = 0 to len( a ) / 2 - 1 // Take row from first half of string, column from second + c = fn StringByAppendingString( mid( a, i, 1 ), mid( a, i + len( a ) / 2 , 1 ) ) + b = fn StringByAppendingString( b , c ) // Combine, and recode + next + +end fn = fn recode( b, code ) + +// + +print fn encode( @"ATTACKATDAWN", @"ABCDEFGHIKLMNOPQRSTUVWXYZ" ) +print fn decode( @"DQBDAXDQPDQH", @"ABCDEFGHIKLMNOPQRSTUVWXYZ" ) +print +print fn encode( @"FLEEATONCE", @"BGWKZQPDNSIOAXEFCLUMTHYVR" ) +print fn decode( @"UAEOLWRINS", @"BGWKZQPDNSIOAXEFCLUMTHYVR" ) +print +print fn encode( @"HAPPY40THDAD", @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ) +print fn decode( @"GO31GAGVANJD", @"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ) + +handleevents diff --git a/Task/Bin-given-limits/Scala/bin-given-limits.scala b/Task/Bin-given-limits/Scala/bin-given-limits.scala new file mode 100644 index 0000000000..6f4614aab1 --- /dev/null +++ b/Task/Bin-given-limits/Scala/bin-given-limits.scala @@ -0,0 +1,40 @@ +object Bins extends App { + + def bins[T](limits: List[T], data: Iterable[T])(implicit ord: Ordering[T]): Array[Int] = { + val result = new Array[Int](limits.size + 1) + for (n <- data) { + val i = limits.search(n)(ord) match { + case scala.collection.Searching.Found(i) => i + 1 + case scala.collection.Searching.InsertionPoint(i) => i + } + result(i) += 1 + } + result + } + + def printBins(limits: List[_], bins: Array[Int]): Unit = { + val n = limits.size + if (n == 0) return + + assert(n + 1 == bins.length) + + println(f" < ${limits.head}%3s: ${bins(0)}%2d") + for (i <- 1 until n) { + println(f">= ${limits(i - 1)}%3s and < ${limits(i)}%3s: ${bins(i)}%2d") + } + println(f">= ${limits.last}%3s : ${bins(n)}%2d") + } + + val limits1 = List(23, 37, 43, 53, 67, 83) + val data1 = List(95, 21, 94, 12, 99, 4, 70, 75, 83, 93, 52, 80, 57, 5, 53, 86, 65, 17, 92, 83, 71, 61, 54, 58, 47, 16, 8, 9, 32, 84, 7, 87, 46, 19, 30, 37, 96, 6, 98, 40, 79, 97, 45, 64, 60, 29, 49, 36, 43, 55) + + println("Example 1:") + printBins(limits1, bins(limits1, data1)) + + val limits2 = List(14, 18, 249, 312, 389, 392, 513, 591, 634, 720) + val data2 = List(445, 814, 519, 697, 700, 130, 255, 889, 481, 122, 932, 77, 323, 525, 570, 219, 367, 523, 442, 933, 416, 589, 930, 373, 202, 253, 775, 47, 731, 685, 293, 126, 133, 450, 545, 100, 741, 583, 763, 306, 655, 267, 248, 477, 549, 238, 62, 678, 98, 534, 622, 907, 406, 714, 184, 391, 913, 42, 560, 247, 346, 860, 56, 138, 546, 38, 985, 948, 58, 213, 799, 319, 390, 634, 458, 945, 733, 507, 916, 123, 345, 110, 720, 917, 313, 845, 426, 9, 457, 628, 410, 723, 354, 895, 881, 953, 677, 137, 397, 97, 854, 740, 83, 216, 421, 94, 517, 479, 292, 963, 376, 981, 480, 39, 257, 272, 157, 5, 316, 395, 787, 942, 456, 242, 759, 898, 576, 67, 298, 425, 894, 435, 831, 241, 989, 614, 987, 770, 384, 692, 698, 765, 331, 487, 251, 600, 879, 342, 982, 527, 736, 795, 585, 40, 54, 901, 408, 359, 577, 237, 605, 847, 353, 968, 832, 205, 838, 427, 876, 959, 686, 646, 835, 127, 621, 892, 443, 198, 988, 791, 466, 23, 707, 467, 33, 670, 921, 180, 991, 396, 160, 436, 717, 918, 8, 374, 101, 684, 727, 749) + + println() + println("Example 2:") + printBins(limits2, bins(limits2, data2)) +} diff --git a/Task/Binary-digits/EasyLang/binary-digits.easy b/Task/Binary-digits/EasyLang/binary-digits.easy index f8bc72d15f..ce46bb43af 100644 --- a/Task/Binary-digits/EasyLang/binary-digits.easy +++ b/Task/Binary-digits/EasyLang/binary-digits.easy @@ -1,14 +1,11 @@ func$ bin num . b$ = "" - if num = 0 - b$ = "0" - . - while num > 0 + while num > 1 b$ = num mod 2 & b$ num = num div 2 . - return b$ + return num & b$ . -print bin 2 +print bin 5 print bin 50 print bin 9000 diff --git a/Task/Binary-digits/Elena/binary-digits.elena b/Task/Binary-digits/Elena/binary-digits.elena index 8fdf161ca2..dbab2c5f2b 100644 --- a/Task/Binary-digits/Elena/binary-digits.elena +++ b/Task/Binary-digits/Elena/binary-digits.elena @@ -3,7 +3,7 @@ import extensions; public program() { - new int[]{5,50,9000}.forEach:(n) + new int[]{5,50,9000}.forEach::(n) { console.printLine(n.toString(2)) } diff --git a/Task/Binary-digits/Refal/binary-digits.refal b/Task/Binary-digits/Refal/binary-digits.refal new file mode 100644 index 0000000000..da17d999cb --- /dev/null +++ b/Task/Binary-digits/Refal/binary-digits.refal @@ -0,0 +1,15 @@ +$ENTRY Go { + = + + >; +}; + +Binary { + 0 = '0\n'; + s.N = '\n'; +}; + +Binary1 { + 0 = ; + s.N, : (s.R) s.D = ; +}; diff --git a/Task/Binary-digits/Roc/binary-digits.roc b/Task/Binary-digits/Roc/binary-digits.roc new file mode 100644 index 0000000000..db133b0da5 --- /dev/null +++ b/Task/Binary-digits/Roc/binary-digits.roc @@ -0,0 +1,6 @@ +binstr : Int * -> Str +binstr = \n -> + if n < 2 then + Num.toStr n + else + Str.concat (binstr (Num.shiftRightZfBy n 1)) (Num.toStr (Num.bitwiseAnd n 1)) diff --git a/Task/Binary-search/Bruijn/binary-search.bruijn b/Task/Binary-search/Bruijn/binary-search.bruijn new file mode 100644 index 0000000000..e8493367bf --- /dev/null +++ b/Task/Binary-search/Bruijn/binary-search.bruijn @@ -0,0 +1,18 @@ +:import std/Combinator . +:import std/Math . +:import std/List . +:import std/Option . + +binary-search [y [[[[[2 (iterate ++‣ (-50))) + +:test (find (+100)) ("not found") +:test ((head (find (+125))) =? (+55)) ([[1]]) +:test ((head (find (+117649))) =? (+99)) ([[1]]) diff --git a/Task/Biorhythms/Kotlin/biorhythms.kotlin b/Task/Biorhythms/Kotlin/biorhythms.kotlin new file mode 100644 index 0000000000..8cc7529557 --- /dev/null +++ b/Task/Biorhythms/Kotlin/biorhythms.kotlin @@ -0,0 +1,64 @@ +import java.time.LocalDate +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit +import kotlin.math.roundToInt +import kotlin.math.sin + +fun main() { + val datePairs = listOf( + listOf("1943-03-09", "1972-07-11"), + listOf("1809-01-12", "1863-11-19"), + listOf("1809-02-12", "1863-11-19") + ) + + for (datePair in datePairs) { + calculateBiorhythms(datePair) + } +} + +fun calculateBiorhythms(datePair: List) { + val formatter = DateTimeFormatter.ISO_LOCAL_DATE + val birthDate = LocalDate.parse(datePair[0], formatter) + val targetDate = LocalDate.parse(datePair[1], formatter) + val daysBetween = ChronoUnit.DAYS.between(birthDate, targetDate).toInt() + println("Birth date $birthDate, Target date $targetDate") + println("Days between: $daysBetween") + + for (cycle in Cycle.values()) { + val cycleLength = cycle.getLength() + val positionInCycle = daysBetween % cycleLength + val quadrantIndex = 4 * positionInCycle / cycleLength + val percentage = (100 * sin(2 * Math.PI * positionInCycle / cycleLength)).roundToInt() + + val description = when { + percentage > 95 -> "peak" + percentage < -95 -> "valley" + Math.abs(percentage) < 5 -> "critical transition" + else -> { + val daysToTransition = (cycleLength * (quadrantIndex + 1) / 4) - positionInCycle + val transitionDate = targetDate.plusDays(daysToTransition.toLong()) + val (trend, nextTransition) = cycle.descriptions(quadrantIndex) + "$percentage% ($trend, next $nextTransition $transitionDate)" + } + } + + println("${cycle.name} day $positionInCycle: $description") + } + println() +} + +enum class Cycle(private val length: Int) { + PHYSICAL(23), EMOTIONAL(28), MENTAL(33); + + fun getLength() = length + + fun descriptions(index: Int): Pair { + val descriptions = listOf( + listOf("up and rising", "peak"), + listOf("up but falling", "transition"), + listOf("down and falling", "valley"), + listOf("down but rising", "transition") + ) + return descriptions[index][0] to descriptions[index][1] + } +} diff --git a/Task/Biorhythms/Scala/biorhythms.scala b/Task/Biorhythms/Scala/biorhythms.scala new file mode 100644 index 0000000000..633e72666f --- /dev/null +++ b/Task/Biorhythms/Scala/biorhythms.scala @@ -0,0 +1,67 @@ +import java.time.LocalDate +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit +import scala.collection.JavaConverters._ + +object Biorythms extends App { + + val datePairs = List( + List("1943-03-09", "1972-07-11"), + List("1809-01-12", "1863-11-19"), + List("1809-02-12", "1863-11-19") + ) + + datePairs.foreach(biorhythms) + + def biorhythms(aDatePair: List[String]): Unit = { + val formatter = DateTimeFormatter.ISO_LOCAL_DATE + val birthDate = LocalDate.parse(aDatePair.head, formatter) + val targetDate = LocalDate.parse(aDatePair(1), formatter) + val daysBetween = ChronoUnit.DAYS.between(birthDate, targetDate).toInt + println(s"Birth date $birthDate, Target date $targetDate") + println(s"Days between: $daysBetween") + + for (cycle <- Cycle.values) { + val cycleLength = cycle.length + val positionInCycle = daysBetween % cycleLength + val quadrantIndex = 4 * positionInCycle / cycleLength + val percentage = Math.round(100 * Math.sin(2 * Math.PI * positionInCycle / cycleLength)).toInt + + val description = if (percentage > 95) { + "peak" + } else if (percentage < -95) { + "valley" + } else if (Math.abs(percentage) < 5) { + "critical transition" + } else { + val daysToTransition = (cycleLength * (quadrantIndex + 1) / 4) - positionInCycle + val transitionDate = targetDate.plusDays(daysToTransition) + val descriptions = cycle.descriptions(quadrantIndex).asScala + val trend = descriptions.head + val nextTransition = descriptions(1) + s"$percentage% ($trend, next $nextTransition $transitionDate)" + } + + println(s"${cycle} day $positionInCycle: $description") + } + println() + } + + enum Cycle(val length: Int) { + case PHYSICAL extends Cycle(23) + case EMOTIONAL extends Cycle(28) + case MENTAL extends Cycle(33) + + def descriptions(number: Int): java.util.List[String] = Cycle.DESCRIPTIONS.get(number) + } + + object Cycle { + private val DESCRIPTIONS = java.util.List.of( + java.util.List.of("up and rising", "peak"), + java.util.List.of("up but falling", "transition"), + java.util.List.of("down and falling", "valley"), + java.util.List.of("down but rising", "transition") + ) + } + +} diff --git a/Task/Bitmap-Read-a-PPM-file/FreeBASIC/bitmap-read-a-ppm-file.basic b/Task/Bitmap-Read-a-PPM-file/FreeBASIC/bitmap-read-a-ppm-file.basic new file mode 100644 index 0000000000..578d40b501 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/FreeBASIC/bitmap-read-a-ppm-file.basic @@ -0,0 +1,33 @@ +Dim As String imagen = "Lena.ppm" + +Sub readPPM (fs As String) + Dim As Integer x, y, ancho, alto + Dim As String t, kolor + Dim As Ubyte r, g, b + + If Len(fs) = 0 Then Print "No PPM file name indicated.": Exit Sub + + Dim As Long ff = Freefile + Open fs For Binary As #ff + If Err Then Print "File "; fs; " not found.": Exit Sub + + Input #ff, t, ancho, alto, kolor + + If t = "P6" Then + Screenres ancho, alto, 32 + For y = 0 To alto - 1 + For x = 0 To ancho - 1 + Get #ff, , r + Get #ff, , g + Get #ff, , b + Pset (x, y), Rgb(r, g, b) + Next x + Next y + Close #ff + Else + Print "File is NOT PPM P6 type." + End If +End Sub + +readPPM(imagen) +Sleep diff --git a/Task/Bitwise-operations/11l/bitwise-operations.11l b/Task/Bitwise-operations/11l/bitwise-operations.11l index 824918ca04..cd2aa30c15 100644 --- a/Task/Bitwise-operations/11l/bitwise-operations.11l +++ b/Task/Bitwise-operations/11l/bitwise-operations.11l @@ -2,7 +2,7 @@ V x = 10 V y = 2 print(‘x = ’x) print(‘y = ’y) -print(‘NOT x = ’(-)x) +print(‘NOT x = ’(~x)) print(‘x AND y = ’(x [&] y)) print(‘x OR y = ’(x [|] y)) print(‘x XOR y = ’(x (+) y)) diff --git a/Task/Bitwise-operations/S-BASIC/bitwise-operations.basic b/Task/Bitwise-operations/S-BASIC/bitwise-operations.basic new file mode 100644 index 0000000000..7fc07c1d66 --- /dev/null +++ b/Task/Bitwise-operations/S-BASIC/bitwise-operations.basic @@ -0,0 +1,11 @@ +var a, b = integer +a = 10 +b = 2 +print "a ="; a; tab(16); hex$(a) +print "b ="; b; tab(16); hex$(b) +print "a and b ="; a and b; tab(16); hex$(a and b) +print "a or b ="; a or b; tab(16); hex$(a or b) +print "a xor b ="; a xor b; tab(16); hex$(a xor b) +print "not a ="; not a; tab(16); hex$(not a) + +end diff --git a/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl b/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl new file mode 100644 index 0000000000..9e4335844f --- /dev/null +++ b/Task/Bitwise-operations/Uxntal/bitwise-operations.uxnatl @@ -0,0 +1,67 @@ +|00 @System [ &vector $2 &wst $1 &rst $1 &eaddr $2 &ecode $1 &pad $1 &r $2 &g $2 &b $2 &debug $1 &halt $1 ] +|10 @Console [ &vector $2 &read $1 &pad $5 &write $1 &error $1 ] + +( program ) +|0100 @on-reset ( -> ) + #0a02 + DUP2 SWP ;Labels/a ;Labels/b + bitwise + halt +BRK + +@bitwise ( a b -- ) + ;Labels/not ;Labels/a ;Labels/equ DUP2 [ POP #ff EOR ] + ;Labels/and DUP2 [ AND ] + ;Labels/or DUP2 [ ORA ] + ;Labels/xor DUP2 [ EOR ] + ;Labels/shl DUP2 [ #40 SFT SFT ] + ;Labels/shr DUP2 [ SFT ] + ;Labels/rol DUP2 [ #40 SFT #00 ROT ROT SFT2 ORA ] + ;Labels/ror [ SWP #00 ROT SFT2 ORA ] + JMP2r + +@halt ( -- ) + #01 .System/halt DEO + BRK + +@ ( a name* -- ) + ;Labels/equ + JMP2r + +@ ( a -- ) + ;Labels/newline + JMP2r + +@ ( label* -- ) + ;Labels/a + + ;Labels/b + ;Labels/equ + JMP2r + +@ ( byte -- ) + [ LIT "$ ] .Console/write DEO + DUP #04 SFT /l + &l ( -- ) + #0f AND DUP #09 GTH #27 MUL ADD [ LIT "0 ] ADD .Console/write DEO + JMP2r + +@ ( str* -- ) + &while ( -- ) + LDAk .Console/write DEO + INC2 LDAk ?&while + POP2 JMP2r + +@Labels + &a "a 20 $1 + &b "b 20 $1 + &equ "= 20 $1 + &newline 0a $1 + ¬ "NOT 20 $1 + &and "AND 20 $1 + &or "OR 20 $1 + &xor "XOR 20 $1 + &shl "SHL 20 $1 + &shr "SHR 20 $1 + &rol "ROL 20 $1 + &ror "ROR 20 $1 diff --git a/Task/Blum-integer/C-sharp/blum-integer.cs b/Task/Blum-integer/C-sharp/blum-integer.cs new file mode 100644 index 0000000000..a242084856 --- /dev/null +++ b/Task/Blum-integer/C-sharp/blum-integer.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections.Generic; + +public class BlumInteger +{ + public static void Main(string[] args) + { + int[] blums = new int[50]; + int blumCount = 0; + Dictionary lastDigitCounts = new Dictionary(); + int number = 1; + + while (blumCount < 400000) + { + int prime = LeastPrimeFactor(number); + if (prime % 4 == 3) + { + int quotient = number / prime; + if (quotient != prime && IsPrimeType3(quotient)) + { + if (blumCount < 50) + { + blums[blumCount] = number; + } + + if (!lastDigitCounts.ContainsKey(number % 10)) + { + lastDigitCounts[number % 10] = 0; + } + lastDigitCounts[number % 10]++; + + blumCount++; + if (blumCount == 50) + { + Console.WriteLine("The first 50 Blum integers:"); + for (int i = 0; i < 50; i++) + { + Console.Write($"{blums[i],3}"); + Console.Write((i % 10 == 9) ? Environment.NewLine : " "); + } + Console.WriteLine(); + } + else if (blumCount == 26828 || blumCount % 100000 == 0) + { + Console.WriteLine($"The {blumCount}th Blum integer is: {number}"); + if (blumCount == 400000) + { + Console.WriteLine(); + Console.WriteLine("Percent distribution of the first 400000 Blum integers:"); + foreach (var key in lastDigitCounts.Keys) + { + Console.WriteLine($" {((double)lastDigitCounts[key] / 4000):0.000}% end in {key}"); + } + } + } + } + } + number += (number % 5 == 3) ? 4 : 2; + } + } + + private static bool IsPrimeType3(int number) + { + if (number < 2) return false; + if (number % 2 == 0) return number == 2; + if (number % 3 == 0) return number == 3; + + for (int divisor = 5; divisor * divisor <= number; divisor += 2) + { + if (number % divisor == 0) return false; + } + return number % 4 == 3; + } + + private static int LeastPrimeFactor(int number) + { + if (number == 1) return 1; + if (number % 2 == 0) return 2; + if (number % 3 == 0) return 3; + if (number % 5 == 0) return 5; + + for (int divisor = 7; divisor * divisor <= number; divisor += 2) + { + if (number % divisor == 0) return divisor; + } + return number; + } +} diff --git a/Task/Blum-integer/Scala/blum-integer.scala b/Task/Blum-integer/Scala/blum-integer.scala new file mode 100644 index 0000000000..6130087f2b --- /dev/null +++ b/Task/Blum-integer/Scala/blum-integer.scala @@ -0,0 +1,62 @@ +import scala.collection.mutable + +object BlumInteger extends App { + var blums = new Array[Int](50) + var blumCount = 0 + val lastDigitCounts = mutable.Map[Int, Int]() + var number = 1 + + while (blumCount < 400_000) { + val prime = leastPrimeFactor(number) + if (prime % 4 == 3) { + val quotient = number / prime + if (quotient != prime && isPrimeType3(quotient)) { + if (blumCount < 50) { + blums(blumCount) = number + } + lastDigitCounts(number % 10) = lastDigitCounts.getOrElse(number % 10, 0) + 1 + blumCount += 1 + if (blumCount == 50) { + println("The first 50 Blum integers:") + blums.grouped(10).foreach(group => println(group.map(i => f"$i%3d").mkString(" "))) + println("") + } else if (blumCount == 26828 || blumCount % 100_000 == 0) { + println(f"The ${blumCount}th Blum integer is: $number%7d") + if (blumCount == 400_000) { + println("\nPercent distribution of the first 400000 Blum integers:") + lastDigitCounts.foreach { case (key, count) => + println(f" ${count.toDouble / 4000}%6.3f%% end in $key") + } + } + } + } + } + number += (if (number % 5 == 3) 4 else 2) + } + + def isPrimeType3(aNumber: Int): Boolean = { + if (aNumber < 2) return false + if (aNumber % 2 == 0) return aNumber == 2 + if (aNumber % 3 == 0) return aNumber == 3 + + var divisor = 5 + while (divisor * divisor <= aNumber) { + if (aNumber % divisor == 0) return false + divisor += 2 + } + aNumber % 4 == 3 + } + + def leastPrimeFactor(aNumber: Int): Int = { + if (aNumber == 1) return 1 + if (aNumber % 2 == 0) return 2 + if (aNumber % 3 == 0) return 3 + + var divisor = 5 + while (divisor * divisor <= aNumber) { + if (aNumber % divisor == 0) return divisor + divisor += 2 + } + aNumber + } +} diff --git a/Task/Box-the-compass/EasyLang/box-the-compass.easy b/Task/Box-the-compass/EasyLang/box-the-compass.easy new file mode 100644 index 0000000000..03c6aa33d7 --- /dev/null +++ b/Task/Box-the-compass/EasyLang/box-the-compass.easy @@ -0,0 +1,35 @@ +func$ expand cp$ . + for c$ in strchars cp$ + if c$ = "N" + r$ &= "north" + elif c$ = "E" + r$ &= "east" + elif c$ = "S" + r$ &= "south" + elif c$ = "W" + r$ &= "west" + elif c$ = "b" + r$ &= "by" + else + r$ &= "-" + . + . + h$ = strchar (strcode substr r$ 1 1 - 32) + return h$ & substr r$ 2 999 +. +proc main . . + cp$[] = [ "N" "NbE" "N-NE" "NEbN" "NE" "NEbE" "E-NE" "EbN" "E" "EbS" "E-SE" "SEbE" "SE" "SEbS" "S-SE" "SbE" "S" "SbW" "S-SW" "SWbS" "SW" "SWbW" "W-SW" "WbS" "W" "WbN" "W-NW" "NWbW" "NW" "NWbN" "N-NW" "NbW" ] + print "Index Degrees Compass point" + print "----- ------- -------------" + for i = 0 to 32 + ind = (i + 1) mod1 32 + heading = i * 11.25 + if i mod 3 = 1 + heading += 5.62 + elif i mod 3 = 2 + heading -= 5.62 + . + print ind & "\t" & heading & "\t" & expand cp$[ind] + . +. +main diff --git a/Task/Box-the-compass/Langur/box-the-compass.langur b/Task/Box-the-compass/Langur/box-the-compass.langur index 17635c933e..bb8171042a 100644 --- a/Task/Box-the-compass/Langur/box-the-compass.langur +++ b/Task/Box-the-compass/Langur/box-the-compass.langur @@ -17,6 +17,6 @@ writeln "index degrees compass point" writeln "----- ------- -------------" for .phi in .angles { - val .i = truncate(.phi x 32 / 360 + 0.5) rem 32 + 1 - writeln $"\.i:5; \.phi:r2:6; \.box[.i];" + val .i = trunc(.phi x 32 / 360 + 0.5) rem 32 + 1 + writeln $"\{.i:5} \{.phi:r2:6} \{.box[.i]}" } diff --git a/Task/Box-the-compass/Swift/box-the-compass-1.swift b/Task/Box-the-compass/Swift/box-the-compass-1.swift new file mode 100644 index 0000000000..f15d8f095c --- /dev/null +++ b/Task/Box-the-compass/Swift/box-the-compass-1.swift @@ -0,0 +1,59 @@ +import Foundation + +extension Double { + var nearestQr: Double {(self * 4.0).rounded(.toNearestOrAwayFromZero) / 4.0} +} + +extension Measurement/*: ExpressibleByFloatLiteral*/ { + var cos: Double { Darwin.cos(self.converted(to: .radians).value) } + var sin: Double { Darwin.sin(self.converted(to: .radians).value) } +} + +struct Compass { + var bearing: Measurement + var style: Style = .RN + init(_ deg: Double, _ min: Double = 0, _ sec: Double = 0, style: Style = .RN + ) { + self.bearing = .init(value: deg + min/60.0 + sec/360.0, unit: .degrees) + self.style = style + } + static func degreesToPoints(_ deg: Double) -> Double { + (deg/360 * 32).nearestQr + } + var point: Double { + Self.degreesToPoints(self.bearing.value) + } + var quad: (String,String) { + (bearing.cos < 0 ? "S" : "N", bearing.sin < 0 ? "W" : "E") + } + var step: (Int,Double) { + let temp = 8 - abs(abs(self.point - 16) - 8) + return (Int(temp),temp.truncatingRemainder(dividingBy: 1)) + } + enum Style {case RN, USN, noBy} + var formats = ["N", "NxE", "NNE", "NExN", "NE", "NExE", "ENE", "ExN", "E"] + let fractions = ["¼","½","¾"] + var invertedPoints: [Int] { + switch self.style { + case .RN: [3,6,7] + case .USN: [3,7] + case .noBy: [1,5,7] + } + } + + func named() -> String { + var (pt,frac) = self.step + var fracStr: String = "" + if frac != 0.0 { + if invertedPoints.contains(pt) { + pt += 1 + fracStr = fractions.reversed()[Int(frac * 4) - 1] + "N" + } else { + fracStr = fractions[Int(frac * 4) - 1] + "E" + } + } + return (self.formats[pt] + fracStr) + .replacing(/(N|E)/) { $0.output.0 == "N" ? self.quad.0 : self.quad.1 } + .replacing(/x/) {_ in "by"} + } +} diff --git a/Task/Box-the-compass/Swift/box-the-compass-2.swift b/Task/Box-the-compass/Swift/box-the-compass-2.swift new file mode 100644 index 0000000000..fd83ef3542 --- /dev/null +++ b/Task/Box-the-compass/Swift/box-the-compass-2.swift @@ -0,0 +1,17 @@ +let arr = [ + 000.00, 016.87, 016.88, 033.75, 050.62, 050.63, 067.50, 084.37, 084.38, + 090.00, 101.25, 118.12, 118.13, 135.00, 151.87, 151.88, 168.75, 185.62, + 185.63, 202.50, 219.37, 219.38, 236.25, 253.12, 253.13, 270.00, 286.87, + 286.88, 303.75, 320.62, 320.63, 337.50, 354.37, 354.38 +] + +let arr2 = stride(from: 0, through: 360, by: 22.5/8.0) + +let pointFormatter = NumberFormatter() +pointFormatter.minimumIntegerDigits = 2 +pointFormatter.minimumFractionDigits = 2 + +for d in arr { + let c = Compass(d, style: .RN) + print(pointFormatter.string(from: c.point as NSNumber)!, c.dms , c.named()) +} diff --git a/Task/Brazilian-numbers/MATLAB/brazilian-numbers.m b/Task/Brazilian-numbers/MATLAB/brazilian-numbers.m new file mode 100644 index 0000000000..cb62ca177a --- /dev/null +++ b/Task/Brazilian-numbers/MATLAB/brazilian-numbers.m @@ -0,0 +1,75 @@ +clear all;close all;clc; + +% Find the first 20 Brazilian numbers in the range 7 to 100. +brazilian_numbers = []; +for num = 7:100 + if brazilianQ(num) + brazilian_numbers = [brazilian_numbers, num]; + if length(brazilian_numbers) == 20 + break; + end + end +end +% For Brazilian numbers +fprintf('% 8d', brazilian_numbers); +fprintf("\n"); + + +% Find the first 20 odd Brazilian numbers in the range 7 to 100. +odd_brazilian_numbers = []; +for num = 7:100 + if brazilianQ(num) && mod(num, 2) ~= 0 + odd_brazilian_numbers = [odd_brazilian_numbers, num]; + if length(odd_brazilian_numbers) == 20 + break; + end + end +end +% For odd Brazilian numbers +fprintf('% 8d', odd_brazilian_numbers); +fprintf("\n"); + + +% Find the first 20 Brazilian prime numbers in the range 7 to 10000. +brazilian_prime_numbers = []; +for num = 7:10000 + if brazilianQ(num) && isprime(num) + brazilian_prime_numbers = [brazilian_prime_numbers, num]; + if length(brazilian_prime_numbers) == 20 + break; + end + end +end +% For Brazilian prime numbers +fprintf('% 8d', brazilian_prime_numbers); +fprintf("\n"); + + + +function isBrazilian = brazilianQ(n) + % Function to check if a number is a Brazilian number. + if n <= 6 + error('Input must be greater than 6.'); + end + isBrazilian = false; + for b = 2:(n-2) + base_b_digits = custom_dec2base(n, b) - '0'; % Convert number to base b and then to digits + if all(base_b_digits == base_b_digits(1)) + isBrazilian = true; + break; + end + end +end + +function digits = custom_dec2base(num, base) + % Custom function to convert number to any base representation + if base < 2 || base > num + error('Base must be at least 2 and less than the number itself.'); + end + digits = []; + while num > 0 + remainder = mod(num, base); + digits = [remainder, digits]; + num = floor(num / base); + end +end diff --git a/Task/Brownian-tree/EasyLang/brownian-tree.easy b/Task/Brownian-tree/EasyLang/brownian-tree.easy index 670ef5fdf6..49a2e7677b 100644 --- a/Task/Brownian-tree/EasyLang/brownian-tree.easy +++ b/Task/Brownian-tree/EasyLang/brownian-tree.easy @@ -6,15 +6,15 @@ f[100 * 200 + 100] = 1 n = 9000 while i < n repeat - x = random 200 - 1 - y = random 200 - 1 + x = randint 200 - 1 + y = randint 200 - 1 until f[y * 200 + x + 1] <> 1 . while 1 = 1 xo = x yo = y - x += random 3 - 2 - y += random 3 - 2 + x += randint 3 - 2 + y += randint 3 - 2 if x < 0 or y < 0 or x >= 200 or y >= 200 break 1 . diff --git a/Task/Bulls-and-cows/EasyLang/bulls-and-cows.easy b/Task/Bulls-and-cows/EasyLang/bulls-and-cows.easy index b692c49a54..94ee5244fd 100644 --- a/Task/Bulls-and-cows/EasyLang/bulls-and-cows.easy +++ b/Task/Bulls-and-cows/EasyLang/bulls-and-cows.easy @@ -1,42 +1,42 @@ dig[] = [ 1 2 3 4 5 6 7 8 9 ] for i = 1 to 4 - h = i - 1 + random (10 - i) - swap dig[i] dig[h] + h = i - 1 + randint (10 - i) + swap dig[i] dig[h] . # print dig[] len g[] 4 attempts = 0 repeat - repeat - ok = 0 - s$[] = strchars input - if len s$[] = 4 - ok = 1 - for i = 1 to 4 - g[i] = number s$[i] - if g[i] = 0 - ok = 0 - . + repeat + ok = 0 + s$[] = strchars input + if len s$[] = 4 + ok = 1 + for i = 1 to 4 + g[i] = number s$[i] + if g[i] = 0 + ok = 0 + . + . . - . - until ok = 1 - . - print g[] - attempts += 1 - bulls = 0 - cows = 0 - for i = 1 to 4 - if g[i] = dig[i] - bulls += 1 - else - for j = 1 to 4 - if dig[j] = g[i] - cows += 1 - . + until ok = 1 + . + print g[] + attempts += 1 + bulls = 0 + cows = 0 + for i = 1 to 4 + if g[i] = dig[i] + bulls += 1 + else + for j = 1 to 4 + if dig[j] = g[i] + cows += 1 + . + . . - . - . - print "bulls:" & bulls & " cows:" & cows - until bulls = 4 + . + print "bulls:" & bulls & " cows:" & cows + until bulls = 4 . print "Well done! " & attempts & " attempts needed." diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index 09afc896c0..c21e80a79d 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -35,7 +35,7 @@ class GameMaster { try { - for (int i := 0, i < 4, i+=1) { + for (int i := 0; i < 4; i+=1) { var ch := guess[i]; var number := ch.toString().toInt(); @@ -44,7 +44,7 @@ class GameMaster { InvalidArgumentException.raise() }; // check duplicates - var duplicate := guess.seekEach:(x => (x == ch)&&(x.equalReference(ch).Inverted)); + var duplicate := guess.seekEach::(x => (x == ch)&&(x.equalReference(ch).Inverted)); if (nil != duplicate) { InvalidArgumentException.raise() @@ -68,9 +68,9 @@ class GameMaster }; bulls => - -1 { console.printLine:"Not a valid guess."; ^ true } - 4 { console.printLine:"Congratulations! You have won!"; ^ false } - : { + -1 { console.printLine("Not a valid guess."); ^ true } + 4 { console.printLine("Congratulations! You have won!"); ^ false } + ! { _attempt.append(1); console.printLine("Your Score is ",bulls," bulls and ",cows," cows"); diff --git a/Task/Burrows-Wheeler-transform/Dart/burrows-wheeler-transform.dart b/Task/Burrows-Wheeler-transform/Dart/burrows-wheeler-transform.dart new file mode 100644 index 0000000000..4da16a962d --- /dev/null +++ b/Task/Burrows-Wheeler-transform/Dart/burrows-wheeler-transform.dart @@ -0,0 +1,67 @@ +import "dart:io"; + +void main() { + List tests = [ + "banana", + "appellee", + "dogwood", + "TO BE OR NOT TO BE OR WANT TO BE OR NOT?", + "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES", + "\u0002ABC\u0003" + ]; + for (String test in tests) { + print(makePrintable(test)); + stdout.write(" --> "); + String t = ""; + try { + t = bwt(test); + print(makePrintable(t)); + } catch (e) { + print("ERROR: ${e.toString()}"); + } + String r = ibwt(t); + print(" --> $r\n"); + } +} + +const String STX = "\u0002"; +const String ETX = "\u0003"; + +String bwt(String s) { + if (s.contains(STX) || s.contains(ETX)) { + throw FormatException("String cannot contain STX or ETX"); + } + + String ss = STX + s + ETX; + List table = []; + for (int i = 0; i < ss.length; i++) { + String before = ss.substring(i); + String after = ss.substring(0, i); + table.add(before + after); + } + table.sort(); + + return table.map((str) => str[str.length - 1]).join(); +} + +String ibwt(String r) { + int len = r.length; + List table = List.filled(len, ""); + for (int j = 0; j < len; ++j) { + for (int i = 0; i < len; ++i) { + table[i] = r[i] + table[i]; + } + table.sort(); + } + for (String row in table) { + if (row.endsWith(ETX)) { + return row.substring(1, len - 1); + } + } + return ""; +} + +String makePrintable(String s) { + // substitute ^ for STX and | for ETX to print results + return s.replaceAll(STX, "^").replaceAll(ETX, "|"); +} diff --git a/Task/Burrows-Wheeler-transform/Sidef/burrows-wheeler-transform-2.sidef b/Task/Burrows-Wheeler-transform/Sidef/burrows-wheeler-transform-2.sidef index 1da2b5b145..e5772e985e 100644 --- a/Task/Burrows-Wheeler-transform/Sidef/burrows-wheeler-transform-2.sidef +++ b/Task/Burrows-Wheeler-transform/Sidef/burrows-wheeler-transform-2.sidef @@ -16,28 +16,9 @@ func bwt_sort (String s) { # O(n * LOOKAHEAD_LEN) space (fast) func bwt_encode(String s) { - var bwt = bwt_sort(s) - var ret = bwt.map {|i| s.slice(i-1, 1) }.join - var prefix = s.slice(0, LOOKAHEAD_LEN) - var len = prefix.len - - var idx = 0; - for i in (bwt) { - - var lookahead = s.slice(i, len) - - if (lookahead.len < len) { - lookahead += s.slice(0, len - lookahead.len) - } - - if (lookahead == prefix) { - var row = s.rotate(i) - if (row == s) { - break - } - } - ++idx - } + var bwt = bwt_sort(s) + var ret = bwt.map {|i| s.slice(i-1, 1) }.join + var idx = bwt.first_index_by { .is_zero } return (ret, idx) } diff --git a/Task/CRC-32/Bait/crc-32.bait b/Task/CRC-32/Bait/crc-32.bait new file mode 100644 index 0000000000..5371a32855 --- /dev/null +++ b/Task/CRC-32/Bait/crc-32.bait @@ -0,0 +1,7 @@ +import hash.crc32 + +fun main() { + text := 'The quick brown fox jumps over the lazy dog' + sum := crc32.checksum(text.bytes()) + println(sum.hex()) +} diff --git a/Task/CUSIP/Langur/cusip-2.langur b/Task/CUSIP/Langur/cusip-2.langur index e855068536..d0648968ab 100644 --- a/Task/CUSIP/Langur/cusip-2.langur +++ b/Task/CUSIP/Langur/cusip-2.langur @@ -7,9 +7,7 @@ val .isCusip = f(.s) { val .c = .s[.i] var .v = 0 - given .c { - # for given, default op between conditions is "and" - # for switch, default op between conditions is "or" + switch[and] .c { case >= '0', <= '9': .v = .c-'0' diff --git a/Task/CUSIP/MiniScript/cusip.mini b/Task/CUSIP/MiniScript/cusip.mini new file mode 100644 index 0000000000..332bcb24f8 --- /dev/null +++ b/Task/CUSIP/MiniScript/cusip.mini @@ -0,0 +1,34 @@ +isCusip = function(s) + if s.len != 9 then return false + sum = 0 + for i in range(0, 7) + c = s[i] + v = 0 + if c >= "0" and c <= "9" then + v = code(c) - 48 + else if c >= "A" and c <= "Z" then + v = code(c) - 55 + else if c == "*" then + v = 36 + else if c == "@" then + v = 37 + else if c == "#" then + v = 38 + else + return false + end if + if i%2 == 1 then v *= 2 // check if odd as using 0-based indexing + sum += floor(v/10) + v%10 + end for + return code(s[8]) - 48 == (10 - (sum%10)) % 10 +end function + +candidates = [ + "037833100", "17275R102", "38259P508", + "594918104", "68389X106", "68389X105", +] +for candidate in candidates + s = "valid" + if not isCusip(candidate) then s = "invalid" + print candidate + " -> " + s +end for diff --git a/Task/Caesar-cipher/Clojure/caesar-cipher-3.clj b/Task/Caesar-cipher/Clojure/caesar-cipher-3.clj new file mode 100644 index 0000000000..d6436b49b6 --- /dev/null +++ b/Task/Caesar-cipher/Clojure/caesar-cipher-3.clj @@ -0,0 +1,7 @@ +(defn fast-caesar [n s] + (let [m (mod n 26) + upper (map char (range 65 91)) + upper->new (zipmap upper (drop m (cycle upper))) + lower (map char (range 97 123)) + lower->new (zipmap lower (drop m (cycle lower)))] + (clojure.string/escape s (merge upper->new lower->new)))) diff --git a/Task/Caesar-cipher/Elena/caesar-cipher.elena b/Task/Caesar-cipher/Elena/caesar-cipher.elena index 4a89a12e15..6120e1217c 100644 --- a/Task/Caesar-cipher/Elena/caesar-cipher.elena +++ b/Task/Caesar-cipher/Elena/caesar-cipher.elena @@ -33,14 +33,14 @@ class Encrypting : Enumerator if (-1 < index) { - ^ Letters[(_key+index).mod:26] + ^ Letters[(_key+index).mod(26)] } else { index := BigLetters.indexOf(0, ch); if (-1 < index) { - ^ BigLetters[(_key+index).mod:26] + ^ BigLetters[(_key+index).mod(26)] } else { @@ -63,11 +63,11 @@ public program() { console.printLine("Original text :",TestText); - var encryptedText := TestText.encrypt:Key; + var encryptedText := TestText.encrypt(Key); console.printLine("Encrypted text:",encryptedText); - var decryptedText := encryptedText.decrypt:Key; + var decryptedText := encryptedText.decrypt(Key); console.printLine("Decrypted text:",decryptedText); diff --git a/Task/Calculating-the-value-of-e/UNIX-Shell/calculating-the-value-of-e.sh b/Task/Calculating-the-value-of-e/UNIX-Shell/calculating-the-value-of-e.sh index 0bccb64654..c8d94684da 100644 --- a/Task/Calculating-the-value-of-e/UNIX-Shell/calculating-the-value-of-e.sh +++ b/Task/Calculating-the-value-of-e/UNIX-Shell/calculating-the-value-of-e.sh @@ -1,12 +1,11 @@ # POSIX requires "signed long" for shell arithmetic, so assume to have at # least 31 bits available, which is sufficient to store (e - 1) * 10^9 -one=1000000000 +declare -ir one=10**9 +declare -i e n rfct=one -e=0 n=0 rfct=$one -while [ $((rfct /= (n += 1))) -ne 0 ] -do - e=$((e + rfct)) +while (( (rfct /= ++n) != 0 )) +do e+=rfct done echo "$((e / one + 1)).$((e % one))" diff --git a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena index 83b29c7efe..02e0ac506f 100644 --- a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena +++ b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena @@ -28,7 +28,7 @@ class CalendarMonthPrinter _row.Value := 0; _date := Date.new(_year, _month, 1); - DayNames.forEach:(name) + DayNames.forEach::(name) { _line.print(" ",name) } } @@ -46,7 +46,7 @@ class CalendarMonthPrinter { _line.writePaddingLeft(_date.Day.toPrintable(), $32, 3); - _date := _date.addDays:1 + _date := _date.addDays(1) } until(_date.Month != _month || _date.DayOfWeek == 1) }; @@ -118,31 +118,31 @@ class Calendar output.writeLine().writeLine(); var rowCount := 12 / _rowLength; - var months := Array.allocate(rowCount).populate:(i => + var months := Array.allocate(rowCount).populate::(i => Array.allocate(_rowLength) - .populate:(j => + .populate::(j => new CalendarMonthPrinter(_year, i * _rowLength + j + 1))); - months.forEach:(row) + months.forEach::(row) { var r := row; - row.forEach:(month) + row.forEach::(month) { - month.printTitleTo:output; + month.printTitleTo(output); - output.write:" " + output.write(" ") }; output.writeLine(); - ParallelEnumerator.new(row).forEach:(line) + ParallelEnumerator.new(row).forEach::(line) { - line.forEach:(printer) + line.forEach::(printer) { - printer.printTo:output; + printer.printTo(output); - output.write:" " + output.write(" ") }; output.writeLine() @@ -153,9 +153,9 @@ class Calendar public program() { - var calender := Calendar.new(console.write:"ENTER THE YEAR:".readLine().toInt()); + var calender := Calendar.new(console.write("ENTER THE YEAR:").readLine().toInt()); - calender.printTo:console; + calender.printTo(console); console.readChar() } diff --git a/Task/Calendar---for-REAL-programmers/Forth/calendar---for-real-programmers.fth b/Task/Calendar---for-REAL-programmers/Forth/calendar---for-real-programmers.fth new file mode 100644 index 0000000000..23fea763b8 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/Forth/calendar---for-real-programmers.fth @@ -0,0 +1,32 @@ +: WEEKDAY ( D M Y -- U ) + OVER 3 < IF SWAP 12 + SWAP 1- THEN + DUP 4 / OVER 100 / - OVER 400 / + + SWAP 1+ 13 * 5 / + + 2 - 7 MOD ; + +: MDAYS ( M Y -- MSIZE MDAY ) + OVER 12 = IF 31 1 2SWAP WEEKDAY NEGATE EXIT THEN + 2>R 1 2R@ WEEKDAY 1 2R> SWAP 1+ SWAP WEEKDAY OVER - + 7 + 7 MOD 28 + SWAP NEGATE ; + +: .WEEK ( MSIZE MDAY -- MSIZE MDAY' ) + 7 0 DO DUP 0< IF 1+ 3 SPACES ELSE + 2DUP > IF 1+ DUP 2 .R SPACE ELSE 3 SPACES THEN THEN LOOP ; + +: .3MONTHS ( Y M -- ) + 3 0 DO ." MO TU WE TH FR SA SU " LOOP CR + 3 OVER + SWAP DO I OVER MDAYS ROT LOOP DROP + 6 0 DO 2ROT .WEEK 2 SPACES 2ROT .WEEK 2 SPACES 2ROT .WEEK CR LOOP + 2DROP 2DROP 2DROP ; + +: CAL ( Y -- ) + 30 SPACES ." [SNOOPY]" CR + 32 SPACES DUP . CR + ." JANUARY FEBRUARY MARCH" CR + DUP 1 .3MONTHS + ." APRIL MAY JUNE" CR + DUP 4 .3MONTHS + ." JULY AUGUST SEPTEMBER" CR + DUP 7 .3MONTHS + ." OCTOBER NOVEMBER DECEMBER" CR + 10 .3MONTHS ; + +1969 CAL diff --git a/Task/Calendar---for-REAL-programmers/Phix/calendar---for-real-programmers-1.phix b/Task/Calendar---for-REAL-programmers/Phix/calendar---for-real-programmers-1.phix index 3d48182395..e58e7e681a 100644 --- a/Task/Calendar---for-REAL-programmers/Phix/calendar---for-real-programmers-1.phix +++ b/Task/Calendar---for-REAL-programmers/Phix/calendar---for-real-programmers-1.phix @@ -1,3 +1,2 @@ -(phixonline)--> - return repeat(' ',left)&s&repeat(' ',right) - - return repeat(' ',left)&upper(s)&repeat(' ',right) - - initialSymEntry("integer", S_Type,"TI",opInt, E_none) -- #01 / 0b0001 integer - - Alias("INTEGER",symlimit) - - procedure tt_stringA(sequence text, integer alias) - tt_string(text,-2) - tt[pcurr] = alias - end procedure - - global constant T_include = 596 tt_stringF("include",T_include) - - tt_stringA("INCLUDE",T_include) - - Ch = find(Ch,escchar) - - Ch = find(lower(Ch),escchar) - - with javascript_semantics - constant year = 1969 +with javascript_semantics +constant year = 1969 - include builtins\timedate.e +include builtins\timedate.e - function centre(string s, integer width) - integer gap = width-length(s), - left = floor(gap/2), - right = gap-left - return repeat(' ',left) & s & repeat(' ',right) - end function +function centre(string s, integer width) + integer gap = width-length(s), + left = floor(gap/2), + right = gap-left + return repeat(' ',left) & s & repeat(' ',right) +end function - function one_month(integer year, integer month, bool sun_to_sat) - string weekdays = iff(sun_to_sat?"Su Mo Tu We Th Fr Sa" - :"Mo Tu We Th Fr Sa Su"), - line = repeat(' ',20) - sequence ldm = adjust_timedate(iff(month=12?{year+1,1,1,0,0,0,0,0} - :{year,month+1,1,0,0,0,0,0}), - timedelta(days:=-1)), - res = {centre(format_timedate(ldm,"Mmmm"),20),weekdays} - integer dow = day_of_week(year,month,1) - if sun_to_sat then dow = remainder(dow,7)+1 end if - integer lastday = ldm[DT_DAY], - p = dow*3-2 - for d=1 to lastday do - line[p..p+1] = sprintf("%2d",d) - p += 3 - if dow=7 or d=lastday then - res = append(res,line) - line = repeat(' ',20) - dow = 1 - p = 1 - else - dow += 1 - end if - end for - return res - end function +function one_month(integer year, integer month, bool sun_to_sat) + string weekdays = iff(sun_to_sat?"Su Mo Tu We Th Fr Sa" + :"Mo Tu We Th Fr Sa Su"), + line = repeat(' ',20) + sequence ldm = adjust_timedate(iff(month=12?{year+1,1,1,0,0,0,0,0} + :{year,month+1,1,0,0,0,0,0}), + timedelta(days:=-1)), + res = {centre(format_timedate(ldm,"Mmmm"),20),weekdays} + integer dow = day_of_week(year,month,1) + if sun_to_sat then dow = remainder(dow,7)+1 end if + integer lastday = ldm[DT_DAY], + p = dow*3-2 + for d=1 to lastday do + line[p..p+1] = sprintf("%2d",d) + p += 3 + if dow=7 or d=lastday then + res = append(res,line) + line = repeat(' ',20) + dow = 1 + p = 1 + else + dow += 1 + end if + end for + return res +end function - procedure print_calendar(integer year, width, bool sun_to_sat=false) - sequence months = repeat(0,12) - integer wide = floor((width+2)/22) - printf(1,centre("[Spot Reserved For Snoopy]",width)&"\n") - printf(1,centre(sprintf("%d",year),width)&"\n") - for month=1 to 12 do - months[month] = one_month(year,month,sun_to_sat) - end for - for month=1 to 12 by wide do - for k=1 to 9 do -- (more than enough) - integer any = 0 - string line = "" - for j=0 to wide-1 do - if length(line) then - line &= " " - end if - if k>length(months[month+j]) then - line &= repeat(' ',20) - else - line &= months[month+j][k] - any = 1 - end if - end for - if any=0 then exit end if - printf(1,centre(line,width)&"\n") - end for - end for - end procedure +procedure print_calendar(integer year, width, bool sun_to_sat=false) + sequence months = repeat(0,12) + integer wide = floor((width+2)/22) + printf(1,centre("[Spot Reserved For Snoopy]",width)&"\n") + printf(1,centre(sprintf("%d",year),width)&"\n") + for month=1 to 12 do + months[month] = one_month(year,month,sun_to_sat) + end for + for month=1 to 12 by wide do + for k=1 to 9 do -- (more than enough) + integer any = 0 + string line = "" + for j=0 to wide-1 do + if length(line) then + line &= " " + end if + if k>length(months[month+j]) then + line &= repeat(' ',20) + else + line &= months[month+j][k] + any = 1 + end if + end for + if any=0 then exit end if + printf(1,centre(line,width)&"\n") + end for + end for +end procedure - print_calendar(year,80) - printf(1,join(repeat("1234567890",8),"")&"\n") - print_calendar(year,132,true) - printf(1,join(repeat("1234567890",13),"")&"12\n") - ${toSnakeCase(text)}") + } + + println("\n" + " ".repeat(26) + "=== To camelCase ===") + variableNames.forEach { text -> + println("${text.padStart(34)} --> ${toCamelCase(text)}") + } +} + +fun toSnakeCase(camel: String): String { + val snake = StringBuilder() + camel.trim().replace(" ", "_").replace("-", "_").forEach { ch -> + if (snake.isEmpty() || snake.last() != '_' || ch != '_') { + if (ch.isUpperCase() && snake.isNotEmpty() && snake.last() != '_') snake.append('_') + snake.append(ch.toLowerCase()) + } + } + return snake.toString() +} + +fun toCamelCase(snake: String): String { + val camel = StringBuilder() + var underscore = false + snake.trim().replace(" ", "_").replace("-", "_").forEach { ch -> + if (ch == '_') { + underscore = true + } else if (underscore) { + camel.append(ch.toUpperCase()) + underscore = false + } else { + camel.append(ch) + } + } + return camel.toString() +} diff --git a/Task/Camel-case-and-snake-case/Scala/camel-case-and-snake-case.scala b/Task/Camel-case-and-snake-case/Scala/camel-case-and-snake-case.scala new file mode 100644 index 0000000000..209ba2986b --- /dev/null +++ b/Task/Camel-case-and-snake-case/Scala/camel-case-and-snake-case.scala @@ -0,0 +1,39 @@ +object CamelCaseAndSnakeCase extends App { + + val variableNames = List("snakeCase", "snake_case", "variable_10_case", "variable10Case", + "ergo rE tHis", "hurry-up-joe!", "c://my-docs/happy_Flag-Day/12.doc", " spaces ") + + println(" " * 26 + "=== To snake_case ===") + variableNames.foreach { text => + println(f"$text%34s --> ${toSnakeCase(text)}") + } + + println("\n" + " " * 26 + "=== To camelCase ===") + variableNames.foreach { text => + println(f"$text%34s --> ${toCamelCase(text)}") + } + + def toSnakeCase(camel: String): String = { + val snake = new StringBuilder + camel.trim.replace(" ", "_").replace("-", "_").foreach { ch => + if (snake.isEmpty || snake.last != '_' || ch != '_') { + if (ch.isUpper && snake.nonEmpty && snake.last != '_') snake.append('_') + snake.append(ch.toLower) + } + } + snake.toString + } + + def toCamelCase(snake: String): String = { + val camel = new StringBuilder + var underscore = false + snake.trim.replace(" ", "_").replace("-", "_").foreach { ch => + if (ch == '_') underscore = true + else if (underscore) { + camel.append(ch.toUpper) + underscore = false + } else camel.append(ch) + } + camel.toString + } +} diff --git a/Task/Canonicalize-CIDR/11l/canonicalize-cidr.11l b/Task/Canonicalize-CIDR/11l/canonicalize-cidr.11l index dcb2faf15e..b6ddd2a1f7 100644 --- a/Task/Canonicalize-CIDR/11l/canonicalize-cidr.11l +++ b/Task/Canonicalize-CIDR/11l/canonicalize-cidr.11l @@ -8,7 +8,7 @@ F cidr_parse(str) | c < 0 | c > 255 | d < 0 | d > 255 R (0, 0) - V mask = (-)((1 << (32 - m)) - 1) + V mask = ~((1 << (32 - m)) - 1) V address = (a << 24) + (b << 16) + (c << 8) + d address [&]= mask R (address, m) diff --git a/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy b/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy new file mode 100644 index 0000000000..64d7aae038 --- /dev/null +++ b/Task/Canonicalize-CIDR/EasyLang/canonicalize-cidr.easy @@ -0,0 +1,38 @@ +func$ can_cidr s$ . + n[] = number strsplit s$ "./" + if len n[] <> 5 + return "" + . + for i to 4 + if n[i] < 0 or n[i] > 255 + return "" + . + ad = ad * 256 + n[i] + . + if n[5] > 31 or n[5] < 1 + return "" + . + mask = bitnot (bitshift 1 (32 - n[5]) - 1) + ad = bitand ad mask + for i to 4 + if r$ <> "" + r$ = "." & r$ + . + r$ = ad mod 256 & r$ + ad = ad div 256 + . + return r$ & "/" & n[5] +. +repeat + s$ = input + until s$ = "" + print s$ & " -> " & can_cidr s$ +. +# +input_data +87.70.141.1/22 +36.18.154.103/12 +62.62.197.11/29 +67.137.119.181/4 +161.214.74.21/24 +184.232.176.184/18 diff --git a/Task/Canonicalize-CIDR/MATLAB/canonicalize-cidr.m b/Task/Canonicalize-CIDR/MATLAB/canonicalize-cidr.m new file mode 100644 index 0000000000..debc175a80 --- /dev/null +++ b/Task/Canonicalize-CIDR/MATLAB/canonicalize-cidr.m @@ -0,0 +1,49 @@ +clear all;close all;clc; +cidrCanonicalizer(); + +function cidrCanonicalizer + % Main function to test CIDR canonicalization + + % Define test cases + testCases = { + '36.18.154.103/12', '36.16.0.0/12'; + '62.62.197.11/29', '62.62.197.8/29'; + '67.137.119.181/4', '64.0.0.0/4'; + '161.214.74.21/24', '161.214.74.0/24'; + '184.232.176.184/18', '184.232.128.0/18' + }; + + % Run test cases + for i = 1:size(testCases, 1) + ip = testCases{i, 1}; + expected = testCases{i, 2}; + result = canonicalize(ip); + fprintf('%s -> %s\n', ip, result); + assert(strcmp(result, expected)); + end +end + +function result = dottedToInt(dotted) + % Convert dotted IP to integer representation + parts = str2double(strsplit(dotted, '.')); + result = sum(parts .* (256 .^ (3:-1:0))); +end + +function result = intToDotted(ip) + % Convert integer IP to dotted representation + result = strjoin(arrayfun(@(x) num2str(bitshift(bitand(ip, bitshift(255, x)), -x)), [24 16 8 0], 'UniformOutput', false), '.'); +end + +function result = networkMask(numberOfBits) + % Create a network mask for the given number of bits + result = bitshift((bitshift(1, numberOfBits) - 1), (32 - numberOfBits)); +end + +function result = canonicalize(ip) + % Canonicalize the given CIDR IP + [dotted, networkBits] = strtok(ip, '/'); + networkBits = str2double(strrep(networkBits, '/', '')); + i = dottedToInt(dotted); + mask = networkMask(networkBits); + result = strcat(intToDotted(bitand(i, mask)), '/', num2str(networkBits)); +end diff --git a/Task/Canonicalize-CIDR/Scala/canonicalize-cidr.scala b/Task/Canonicalize-CIDR/Scala/canonicalize-cidr.scala new file mode 100644 index 0000000000..584342d637 --- /dev/null +++ b/Task/Canonicalize-CIDR/Scala/canonicalize-cidr.scala @@ -0,0 +1,48 @@ +import java.text.MessageFormat + +object CanonicalizeCIDR extends App { + case class CIDR(address: Int, maskLength: Int) { + override def toString: String = { + val a = (address >> 24) & 0xFF + val b = (address >> 16) & 0xFF + val c = (address >> 8) & 0xFF + val d = address & 0xFF + MessageFormat.format(CIDR.format, a.asInstanceOf[AnyRef], b.asInstanceOf[AnyRef], c.asInstanceOf[AnyRef], d.asInstanceOf[AnyRef], maskLength.asInstanceOf[AnyRef]) + } + } + + object CIDR { + private val format = "{0,number,integer}.{1,number,integer}.{2,number,integer}.{3,number,integer}/{4,number,integer}" + + def apply(str: String): CIDR = { + val args = new MessageFormat(format).parse(str) + val address = args.take(4).foldLeft(0) { (acc, arg) => + val a = arg.asInstanceOf[Number].intValue() + require(a >= 0 && a <= 255, "Invalid IP address") + (acc << 8) + a + } + val maskLength = args(4).asInstanceOf[Number].intValue() + require(maskLength >= 1 && maskLength <= 32, "Invalid mask length") + val mask = ~((1 << (32 - maskLength)) - 1) + new CIDR(address & mask, maskLength) + } + } + + val tests = Array( + "87.70.141.1/22", + "36.18.154.103/12", + "62.62.197.11/29", + "67.137.119.181/4", + "161.214.74.21/24", + "184.232.176.184/18" + ) + + tests.foreach { test => + try { + val cidr = CIDR(test) + println(f"$test%-18s -> $cidr") + } catch { + case ex: Exception => println(s"Error parsing '$test': ${ex.getLocalizedMessage}") + } + } +} diff --git a/Task/Canonicalize-CIDR/Swift/canonicalize-cidr.swift b/Task/Canonicalize-CIDR/Swift/canonicalize-cidr.swift new file mode 100644 index 0000000000..a505e3a21a --- /dev/null +++ b/Task/Canonicalize-CIDR/Swift/canonicalize-cidr.swift @@ -0,0 +1,41 @@ +import Foundation + +func dottedToInt(_ dotted: String) -> UInt32 { + let digits = dotted.split(separator: ".").map { UInt32($0)! } + return digits.enumerated().reduce(0) { $0 + ($1.element << (24 - $1.offset * 8)) } +} + +func intToDotted(_ ip: UInt32) -> String { + let digits = [24, 16, 8, 0].map { (ip & (255 << $0)) >> $0 } + return digits.map { String($0) }.joined(separator: ".") +} + +func networkMask(_ numberOfBits: Int) -> UInt32 { + // Explicitly use UInt32 for bitwise operations + return UInt32((1 << numberOfBits) - 1) << (32 - numberOfBits) +} + +func canonicalize(_ ip: String) -> String { + let parts = ip.split(separator: "/") + let dotted = String(parts[0]) + let networkBits = Int(parts[1])! + + let i = dottedToInt(dotted) + let mask = networkMask(networkBits) + return "\(intToDotted(i & mask))/\(networkBits)" +} + +let testCases = [ + ("36.18.154.103/12", "36.16.0.0/12"), + ("62.62.197.11/29", "62.62.197.8/29"), + ("67.137.119.181/4", "64.0.0.0/4"), + ("161.214.74.21/24", "161.214.74.0/24"), + ("184.232.176.184/18", "184.232.128.0/18"), +] + +for testCase in testCases { + let (ip, expect) = testCase + let result = canonicalize(ip) + print("\(ip) -> \(result)") + assert(result == expect, "Test failed for \(ip)") +} diff --git a/Task/Canonicalize-CIDR/Tcl/canonicalize-cidr.tcl b/Task/Canonicalize-CIDR/Tcl/canonicalize-cidr.tcl new file mode 100644 index 0000000000..c77f6e308f --- /dev/null +++ b/Task/Canonicalize-CIDR/Tcl/canonicalize-cidr.tcl @@ -0,0 +1,52 @@ +# Canonicalize CIDR in Tcl + +# Convert dotted IP address to integer +proc dotted_to_int {dotted} { + set digits [split $dotted .] + set result 0 + foreach digit $digits { + set result [expr {$result * 256 + $digit}] + } + return $result +} + +# Convert integer IP address to dotted format +proc int_to_dotted {ip} { + set result {} + for {set i 3} {$i >= 0} {incr i -1} { + lappend result [expr {($ip >> ($i * 8)) & 0xFF}] + } + return [join $result .] +} + +# Calculate network mask +proc network_mask {number_of_bits} { + return [expr {(1 << $number_of_bits) - 1 << (32 - $number_of_bits)}] +} + +# Canonicalize IP address +proc canonicalize {ip} { + regexp {^(.*)/(.*)$} $ip -> dotted network_bits + set i [dotted_to_int $dotted] + set mask [network_mask $network_bits] + return [int_to_dotted [expr {$i & $mask}]]/$network_bits +} + +# Test cases +set test_cases { + {"36.18.154.103/12" "36.16.0.0/12"} + {"62.62.197.11/29" "62.62.197.8/29"} + {"67.137.119.181/4" "64.0.0.0/4"} + {"161.214.74.21/24" "161.214.74.0/24"} + {"184.232.176.184/18" "184.232.128.0/18"} +} + +# Main execution +foreach test $test_cases { + foreach {ip expect} $test {} + set rv [canonicalize $ip] + puts "$ip -> $rv" + if {$rv ne $expect} { + error "Test failed: $rv != $expect" + } +} diff --git a/Task/Cartesian-product-of-two-or-more-lists/EasyLang/cartesian-product-of-two-or-more-lists.easy b/Task/Cartesian-product-of-two-or-more-lists/EasyLang/cartesian-product-of-two-or-more-lists.easy new file mode 100644 index 0000000000..011a8d1706 --- /dev/null +++ b/Task/Cartesian-product-of-two-or-more-lists/EasyLang/cartesian-product-of-two-or-more-lists.easy @@ -0,0 +1,16 @@ +proc cart2 a[] b[] . p[][] . + p[][] = [ ] + for a in a[] + for b in b[] + p[][] &= [ a b ] + . + . +. +cart2 [ 1 2 ] [ 3 4 ] r[][] +print r[][] +cart2 [ 3 4 ] [ 1 2 ] r[][] +print r[][] +cart2 [ 1 2 ] [ ] r[][] +print r[][] +cart2 [ ] [ 1 2 ] r[][] +print r[][] diff --git a/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur b/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur index 26285ec8d2..14dcab9752 100644 --- a/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur +++ b/Task/Cartesian-product-of-two-or-more-lists/Langur/cartesian-product-of-two-or-more-lists.langur @@ -1,14 +1,16 @@ -writeln X([1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]] -writeln X([3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]] -writeln X([1, 2], []) == [] -writeln X([], [1, 2]) == [] +val .X = f(... .x) .x + +writeln mapX(.X, [1, 2], [3, 4]) == [[1, 3], [1, 4], [2, 3], [2, 4]] +writeln mapX(.X, [3, 4], [1, 2]) == [[3, 1], [3, 2], [4, 1], [4, 2]] +writeln mapX(.X, [1, 2], []) == [] +writeln mapX(.X, [], [1, 2]) == [] writeln() -writeln X [1776, 1789], [7, 12], [4, 14, 23], [0, 1] +writeln mapX .X, [1776, 1789], [7, 12], [4, 14, 23], [0, 1] writeln() -writeln X [1, 2, 3], [30], [500, 100] +writeln mapX .X, [1, 2, 3], [30], [500, 100] writeln() -writeln X [1, 2, 3], [], [500, 100] +writeln mapX .X, [1, 2, 3], [], [500, 100] writeln() diff --git a/Task/Catamorphism/Refal/catamorphism.refal b/Task/Catamorphism/Refal/catamorphism.refal new file mode 100644 index 0000000000..07ae72f561 --- /dev/null +++ b/Task/Catamorphism/Refal/catamorphism.refal @@ -0,0 +1,10 @@ +$ENTRY Go { + , 1 2 3 4 5 6 7: e.List + = > + >; +}; + +Reduce { + s.F t.I = t.I; + s.F t.I t.J e.X = e.X>; +}; diff --git a/Task/Chaos-game/EasyLang/chaos-game.easy b/Task/Chaos-game/EasyLang/chaos-game.easy index b0a7b03aae..1981fc43a7 100644 --- a/Task/Chaos-game/EasyLang/chaos-game.easy +++ b/Task/Chaos-game/EasyLang/chaos-game.easy @@ -4,9 +4,9 @@ y[] = [ 7 7 93 ] x = randomf * 100 y = randomf * 100 for i = 1 to 100000 - move x y - rect 0.3 0.3 - h = random 3 - x = (x + x[h]) / 2 - y = (y + y[h]) / 2 + move x y + rect 0.3 0.3 + h = randint 3 + x = (x + x[h]) / 2 + y = (y + y[h]) / 2 . diff --git a/Task/Character-codes/Elena/character-codes.elena b/Task/Character-codes/Elena/character-codes.elena index 966b890ae0..6dbbbee50c 100644 --- a/Task/Character-codes/Elena/character-codes.elena +++ b/Task/Character-codes/Elena/character-codes.elena @@ -4,6 +4,6 @@ public program() { var ch := $97; - console.printLine:ch; + console.printLine(ch); console.printLine(ch.toInt()) } diff --git a/Task/Character-codes/Langur/character-codes.langur b/Task/Character-codes/Langur/character-codes.langur index 25f711852a..14eaab6abe 100644 --- a/Task/Character-codes/Langur/character-codes.langur +++ b/Task/Character-codes/Langur/character-codes.langur @@ -8,4 +8,4 @@ writeln .a1 == .a2 writeln .a2 == .a3 writeln .a3 == .a4 writeln "numbers: ", join ", ", [.a1, .a2, .a3, .a4, .a5] -writeln "letters: ", join ", ", [cp2s(.a1), cp2s(.a2), cp2s(.a3), cp2s(.a4), cp2s(.a5)] +writeln "letters: ", join ", ", map cp2s, [.a1, .a2, .a3, .a4, .a5] diff --git a/Task/Character-codes/MiniScript/character-codes.mini b/Task/Character-codes/MiniScript/character-codes.mini new file mode 100644 index 0000000000..d204f9122c --- /dev/null +++ b/Task/Character-codes/MiniScript/character-codes.mini @@ -0,0 +1,10 @@ +cps = [] +for c in ["a", "π", "字", "🐘"] + cp = c.code + cps.push cp + print c + " = " + cp +end for +print +for i in cps + print i + " = " + char(i) +end for diff --git a/Task/Character-codes/Uxntal/character-codes.uxnatl b/Task/Character-codes/Uxntal/character-codes.uxnatl index 3c8894c079..0429ace25f 100644 --- a/Task/Character-codes/Uxntal/character-codes.uxnatl +++ b/Task/Character-codes/Uxntal/character-codes.uxnatl @@ -1,3 +1,5 @@ +( uxnasm char-codes.tal char-codes.rom && uxncli char-codes.rom ) + |00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 |10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 @@ -7,6 +9,7 @@ #61 .Console/write DEO newline + ( exit ) #80 .System/state DEO BRK diff --git a/Task/Check-output-device-is-a-terminal/Swift/check-output-device-is-a-terminal.swift b/Task/Check-output-device-is-a-terminal/Swift/check-output-device-is-a-terminal.swift new file mode 100644 index 0000000000..e2869aed95 --- /dev/null +++ b/Task/Check-output-device-is-a-terminal/Swift/check-output-device-is-a-terminal.swift @@ -0,0 +1 @@ +print(isatty(STDOUT_FILENO) != 0 ? "TTY" : "Not TTY" ) diff --git a/Task/Check-that-file-exists/Langur/check-that-file-exists.langur b/Task/Check-that-file-exists/Langur/check-that-file-exists.langur new file mode 100644 index 0000000000..2c3a109cb6 --- /dev/null +++ b/Task/Check-that-file-exists/Langur/check-that-file-exists.langur @@ -0,0 +1,17 @@ +val .printresult = f(.file) { + write .file, ": " + if val .p = prop(.file) { + if .p'isdir { + writeln "is directory" + } else { + writeln "is file" + } + } else { + writeln "not found or not accessible" + } +} + +.printresult("input.txt") +.printresult("/input.txt") +.printresult("docs") +.printresult("/docs") diff --git a/Task/Cheryls-birthday/ALGOL-68/cheryls-birthday.alg b/Task/Cheryls-birthday/ALGOL-68/cheryls-birthday.alg new file mode 100644 index 0000000000..253ab73fc8 --- /dev/null +++ b/Task/Cheryls-birthday/ALGOL-68/cheryls-birthday.alg @@ -0,0 +1,71 @@ +BEGIN # Cheryl's birthday puzzle # + + [ 1 : 4, 1 : 6 ]INT dates # non-zero indicates a possible date # + := ( ( 0, 15, 16, 0, 0, 19 ) # may # + , ( 0, 0, 0, 17, 18, 0 ) # june # + , ( 14, 0, 16, 0, 0, 0 ) # july # + , ( 14, 15, 0, 17, 0, 0 ) # august # + ); + []STRING month name = ( "May", "June", "July", "August" ); + print( ( "Cheryl tells Albert the month and Bernard the day", newline ) ); + print( ( "Albert doesn't know the date and knows Bernard doesn't either", newline ) ); + FOR d TO 2 UPB dates DO # elimiate the months with unique days # + INT day count := 0; + INT day := 0; + INT month := 0; + FOR m TO 1 UPB dates DO + IF dates[ m, d ] /= 0 THEN + day count +:= 1; + day := dates[ m, d ]; + month := m + FI + OD; + IF day count = 1 THEN + print( ( " Eliminating ", month name[ month ], ", ", whole( day, 0 ), "th is unique", newline ) ); + FOR p TO 2 UPB dates DO dates[ month, p ] := 0 OD + FI + OD; + print( ( "Bernard now knows the date", newline ) ); + FOR d TO 2 UPB dates DO # eliminate the days that aren't unique # + INT day count := 0; + INT day := 0; + INT month := 0; + FOR m TO 1 UPB dates DO + IF dates[ m, d ] /= 0 THEN + day count +:= 1; + day := dates[ m, d ]; + month := m + FI + OD; + IF day count > 1 THEN + print( ( " Eliminating ", whole( day, 0 ), "th, it is non-unique", newline ) ); + FOR p TO 1 UPB dates DO dates[ p, d ] := 0 OD + FI + OD; + print( ( "Albert now knows the date", newline ) ); + FOR m TO 1 UPB dates DO # eliminate months with non-unique days # + INT day count := 0; + INT day := 0; + INT month := 0; + FOR d TO 2 UPB dates DO + IF dates[ m, d ] /= 0 THEN + day count +:= 1; + day := dates[ m, d ]; + month := m + FI + OD; + IF day count > 1 THEN + print( ( " Eliminating ", month name[ m ], ", it has multiple days", newline ) ); + FOR p TO 2 UPB dates DO dates[ m, p ] := 0 OD + FI + OD; + print( ( "Cheryl's birthday: " ) ); # show the solution(s) # + FOR m TO 1 UPB dates DO + FOR d TO 2 UPB dates DO + IF dates[ m, d ] /= 0 THEN + print( ( " ", month name[ m ], " ", whole( dates[ m, d ], 0 ), "th" ) ) + FI + OD + OD; + print( ( newline ) ) +END diff --git a/Task/Cheryls-birthday/Fortran/cheryls-birthday.f b/Task/Cheryls-birthday/Fortran/cheryls-birthday.f new file mode 100644 index 0000000000..b7246542ce --- /dev/null +++ b/Task/Cheryls-birthday/Fortran/cheryls-birthday.f @@ -0,0 +1,131 @@ +program code_translation + implicit none + character(len=3), dimension(13) :: months = ["ERR", "Jan", "Feb", "Mar", "Apr", "May",& + "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + type :: Date + integer :: month, day + logical :: active + end type Date + type(Date), dimension(10) :: dates = [Date(5,15,.true.), Date(5,16,.true.), Date(5,19,.true.), & + Date(6,17,.true.), Date(6,18,.true.), & + Date(7,14,.true.), Date(7,16,.true.), & + Date(8,14,.true.), Date(8,15,.true.), Date(8,17,.true.)] + integer, parameter :: UPPER_BOUND = size(dates) +write(*,*) 'possible dates: [[May 15] [May 16] [May 19] [June 17] [June 18] [July 14] [July 16] [August 14] [August 15] [August & + 17]]' +write(*,*) +write(*,*) '(1) Albert: I don''t know when Cheryl''s birthday is, but I know that Bernard does not know too.' +write(*,*) ' -> meaning: the month cannot have a unique day' +write(*,*) ' -> remaining: [[July 14] [July 16] [August 14] [August 15] [August 17]] ' +write(*,*) +write(*,*) "(2) Bernard: At first I don't know when Cheryl's birthday is, but I know now." +write(*,*) ' -> meaning: the day must be unique' +write(*,*) ' -> remaining: [[July 16] [August 15] [August 17]] ' +write(*,*) +write(*,*) '(3) Albert: Then I also know when Cheryl''s birthday is.' +write(*,*) ' -> meaning: the month must be unique' +write(*,*) ' -> remaining: [[July 16]] ' + + call printRemaining() + ! the month cannot have a unique day + call firstPass() + call printRemaining() + ! the day must now be unique + call secondPass() + call printRemaining() + ! the month must now be unique + call thirdPass() + call printAnswer() + +contains + + subroutine printRemaining() + integer :: i, c + do i = 1, UPPER_BOUND + if (dates(i)%active) then + write(*,'(a,1x,i0,1x)',advance="no") months(dates(i)%month+1),dates(i)%day + c = c + 1 + end if + end do +! + write(*,*) + end subroutine printRemaining + + subroutine printAnswer() + integer :: i + write(*,'(a)',advance ='no') 'Cheryl''s birtday is on ' + do i = 1, UPPER_BOUND + if (dates(i)%active) then + write(*,'(a,1a1,i0)') trim(months(dates(i)%month+1)), ",", dates(i)%day + end if + end do + end subroutine printAnswer + + subroutine firstPass() + ! the month cannot have a unique day + integer :: i, j, c + do i = 1, UPPER_BOUND + c = 0 + do j = 1, UPPER_BOUND + if (dates(j)%day == dates(i)%day) then + c = c + 1 + end if + end do + if (c == 1) then + do j = 1, UPPER_BOUND + if (.not. dates(j)%active) cycle + if (dates(j)%month == dates(i)%month) then + dates(j)%active = .false. + end if + end do + end if + end do + end subroutine firstPass + + subroutine secondPass() + ! the day must now be unique + integer :: i, j, c + do i = 1, UPPER_BOUND + if (.not. dates(i)%active) cycle + c = 0 + do j = 1, UPPER_BOUND + if (.not. dates(j)%active) cycle + if (dates(j)%day == dates(i)%day) then + c = c + 1 + end if + end do + if (c > 1) then + do j = 1, UPPER_BOUND + if (.not. dates(j)%active) cycle + if (dates(j)%day == dates(i)%day) then + dates(j)%active = .false. + end if + end do + end if + end do + end subroutine secondPass + + subroutine thirdPass() + ! the month must now be unique + integer :: i, j, c + do i = 1, UPPER_BOUND + if (.not. dates(i)%active) cycle + c = 0 + do j = 1, UPPER_BOUND + if (.not. dates(j)%active) cycle + if (dates(j)%month == dates(i)%month) then + c = c + 1 + end if + end do + if (c > 1) then + do j = 1, UPPER_BOUND + if (.not. dates(j)%active) cycle + if (dates(j)%month == dates(i)%month) then + dates(j)%active = .false. + end if + end do + end if + end do + end subroutine thirdPass + +end program code_translation diff --git a/Task/Cheryls-birthday/FreeBASIC/cheryls-birthday.basic b/Task/Cheryls-birthday/FreeBASIC/cheryls-birthday.basic new file mode 100644 index 0000000000..15e3d2f8bb --- /dev/null +++ b/Task/Cheryls-birthday/FreeBASIC/cheryls-birthday.basic @@ -0,0 +1,81 @@ +Dim As Integer i, j, contarDias, dia, mes +Dim fechas(1 To 4, 1 To 6) As Integer => {{0, 15, 16, 0, 0, 19}, {0, 0, 0, 17, 18, 0}, {14, 0, 16, 0, 0, 0}, {14, 15, 0, 17, 0, 0}} +Dim nombreMes(1 To 4) As String => {"May", "June", "July", "August"} + +Print "Cheryl tells Albert the month and Bernard the day" +Print "Albert doesn't know the date and knows Bernard doesn't either" + +' elimiate the months with unique days +For i = 1 To 6 + contarDias = 0 + dia = 0 + mes = 0 + For j = 1 To 4 + If fechas(j, i) <> 0 Then + contarDias += 1 + dia = fechas(j, i) + mes = j + End If + Next j + If contarDias = 1 Then + Print " Eliminating "; nombreMes(mes); ", "; Str(dia); "th is unique" + For j = 1 To 6 + fechas(mes, j) = 0 + Next j + End If +Next i + +Print "Bernard now knows the date" + +' eliminate the days that aren't unique +For i = 1 To 6 + contarDias = 0 + dia = 0 + mes = 0 + For j = 1 To 4 + If fechas(j, i) <> 0 Then + contarDias += 1 + dia = fechas(j, i) + mes = j + End If + Next j + If contarDias > 1 Then + Print " Eliminating "; Str(dia); "th, it is non-unique" + For j = 1 To 4 + fechas(j, i) = 0 + Next j + End If +Next i + +Print "Albert now knows the date" + +' eliminate months with non-unique days +For i = 1 To 4 + contarDias = 0 + dia = 0 + mes = 0 + For j = 1 To 6 + If fechas(i, j) <> 0 Then + contarDias += 1 + dia = fechas(i, j) + mes = i + End If + Next j + If contarDias > 1 Then + Print " Eliminating "; nombreMes(i); ", it has multiple days" + For j = 1 To 6 + fechas(i, j) = 0 + Next j + End If +Next i + +Print "Cheryl's birthday: "; +For i = 1 To 4 + For j = 1 To 6 + If fechas(i, j) <> 0 Then + Print " "; nombreMes(i); " "; Str(fechas(i, j)); "th" + End If + Next j +Next i + +Sleep diff --git a/Task/Chinese-remainder-theorem/ALGOL-68/chinese-remainder-theorem.alg b/Task/Chinese-remainder-theorem/ALGOL-68/chinese-remainder-theorem.alg new file mode 100644 index 0000000000..e28552e935 --- /dev/null +++ b/Task/Chinese-remainder-theorem/ALGOL-68/chinese-remainder-theorem.alg @@ -0,0 +1,39 @@ +BEGIN # Chinese remainder theorewm - translated from the C sample # + + PROC mul inv = ( INT a in, b in )INT: + IF b in = 1 + THEN 1 + ELSE + INT b0 = b in; + INT a := a in, b := b in, x0 := 0, x1 := 1; + WHILE a > 1 DO + IF b = 0 THEN + print( ( "Numbers not pairwise coprime", newline ) ); stop + FI; + INT q = a OVER b; + INT t; + t := b; b := a MOD b; a := t; + t := x0; x0 := x1 - q * x0; x1 := t + OD; + IF x1 < 0 THEN x1 + b0 ELSE x1 FI + FI # mul inv # ; + + PROC chinese remainder = ( []INT n, a )INT: + IF LWB n /= LWB a OR UPB n /= UPB a OR ( UPB a - LWB a ) + 1 < 1 + THEN print( ( "Array bounds mismatch or empty arrays", newline ) ); stop + ELSE + INT prod := 1, sum := 0; + FOR i FROM LWB n TO UPB n DO prod *:= n[ i ] OD; + IF prod = 0 THEN + print( ( "Numbers not pairwise coprime", newline ) ); stop + FI; + FOR i FROM LWB n TO UPB n DO + INT p = prod OVER n[ i ]; + sum +:= a[ i ] * mul inv( p, n[ i ] ) * p + OD; + sum MOD prod + FI # chinese remainder # ; + + print( ( whole( chinese remainder( ( 3, 5, 7 ), ( 2, 3, 2 ) ), 0 ), newline ) ) + +END diff --git a/Task/Chowla-numbers/Fortran/chowla-numbers.f b/Task/Chowla-numbers/Fortran/chowla-numbers.f new file mode 100644 index 0000000000..9da7c28d01 --- /dev/null +++ b/Task/Chowla-numbers/Fortran/chowla-numbers.f @@ -0,0 +1,114 @@ + PROGRAM CHOWLA + + CALL PUT_1ST_37 + CALL PUT_PRIME + CALL PUT_PERFECT + + END + + INTEGER*4 FUNCTION CHOWLA1(N) + +C The Chowla number of N is the sum of the divisors of N +C excluding unity and N where N is a positive integer + + IMPLICIT INTEGER*4 (A-Z) + + IF (N .LE. 0) STOP 'Argument to Chowla function must be > 0' + + SUM = 0 + I = 2 + + 100 CONTINUE + IF (I * I .GT. N) GOTO 200 + + IF (MOD(N, I) .NE. 0) GOTO 110 + J = N / I + SUM = SUM + I + IF ( I .NE. J) SUM = SUM + J + 110 CONTINUE + + I = I + 1 + GOTO 100 + + 200 CONTINUE + + CHOWLA1 = SUM + + RETURN + + END + + SUBROUTINE PUT_1ST_37 + IMPLICIT INTEGER*4 (A-Z) + + DO 100 I = 1, 37 + PRINT 900, I, CHOWLA1(I) + 100 CONTINUE + + RETURN + + 900 FORMAT(1H , 'CHOWLA(', I2, ') = ', I2) + + END + + SUBROUTINE PUT_PRIME + IMPLICIT INTEGER*4 (A-Z) + PARAMETER LIMIT = 10000000 + + COUNT = 0 + POWER = 100 + + DO 200 N = 2, LIMIT + + IF (CHOWLA1(N) .EQ. 0) COUNT = COUNT + 1 + + IF (MOD(N, POWER) .NE. 0) GOTO 100 + + PRINT 900, COUNT, POWER + POWER = POWER * 10 + + 100 CONTINUE + + 200 CONTINUE + + RETURN + + 900 FORMAT(1H ,'There are ', I12, ' primes < ', I12) + + END + + SUBROUTINE PUT_PERFECT + IMPLICIT INTEGER*4 (A-Z) + PARAMETER LIMIT = 35000000 + + COUNT = 0 + K = 2 + KK = 3 + + 100 CONTINUE + + P = K * KK + + IF (P .GT. LIMIT) GOTO 300 + + IF (CHOWLA1(P) .NE. P - 1) GOTO 200 + PRINT 900, P + COUNT = COUNT + 1 + + 200 CONTINUE + + K = KK + 1 + KK = KK + K + + GOTO 100 + + 300 CONTINUE + + PRINT 910, COUNT, LIMIT + + RETURN + + 900 FORMAT(1H , I10, ' is a perfect number') + 910 FORMAT(1H , 'There are ', I10, ' perfect numbers < ', I10) + + END diff --git a/Task/Chowla-numbers/PARI-GP/chowla-numbers.parigp b/Task/Chowla-numbers/PARI-GP/chowla-numbers.parigp new file mode 100644 index 0000000000..a3b5237301 --- /dev/null +++ b/Task/Chowla-numbers/PARI-GP/chowla-numbers.parigp @@ -0,0 +1,28 @@ +chowla(n) = { + if (n < 1, error("Chowla function argument must be positive")); + if (n < 4, return(0)); + my(divs = divisors(n)); + sum(i=1, #divs, divs[i]) - n - 1; +} + +\\ Function to count Chowla numbers +countchowlas(n, asperfect = 1, verbose = 1) = { + my(count = 0, chow, i); + for (i = 2, n, + chow = chowla(i); + if ( (asperfect && (chow == i - 1)) || ((!asperfect) && (chow == 0)), + count++; + if (verbose, print("The number " i " is " if (asperfect, "perfect.", "prime."))); + ); + ); + count; +} + +\\ Main execution block +{ + print("The first 37 chowla numbers are:"); + for (i = 1, 37, printf("Chowla(%s) is %s\n", Str(i), Str(chowla(i)) ) ); + m=100; + while(m<=10000000, print("The count of the primes up to " m " is " countchowlas(m, 0, 0)); m=m*10); + print("The count of perfect numbers up to 35,000,000 is " countchowlas(35000000, 1, 1)); +} diff --git a/Task/Chowla-numbers/Rust/chowla-numbers.rust b/Task/Chowla-numbers/Rust/chowla-numbers.rust new file mode 100644 index 0000000000..bb9e557d57 --- /dev/null +++ b/Task/Chowla-numbers/Rust/chowla-numbers.rust @@ -0,0 +1,69 @@ +fn chowla(n: usize) -> usize { + let mut sum = 0; + let mut i = 2; + while i * i <= n { + if n % i == 0 { + sum += i; + let j = n / i; + if i != j { + sum += j; + } + } + i += 1; + } + sum +} + +fn sieve(limit: usize) -> Vec { + let mut c = vec![false; limit]; + let mut i = 3; + while i * i < limit { + if !c[i] && chowla(i) == 0 { + let mut j = 3 * i; + while j < limit { + c[j] = true; + j += 2 * i; + } + } + i += 2; + } + c +} + +fn main() { + for i in 1..=37 { + println!("chowla({}) = {}", i, chowla(i)); + } + + let mut count = 1; + let limit = 1e7 as usize; + let mut power = 100; + let c = sieve(limit); + for i in (3..limit).step_by(2) { + if !c[i] { + count += 1; + } + if i == power - 1 { + println!("Count of primes up to {} = {}", power, count); + power *= 10; + } + } + + count = 0; + let limit = 35000000; + let mut k = 2; + let mut kk = 3; + loop { + let p = k * kk; + if p > limit { + break; + } + if chowla(p) == p - 1 { + println!("{} is a number that is perfect", p); + count += 1; + } + k = kk + 1; + kk += k; + } + println!("There are {} perfect numbers <= 35,000,000", count); +} diff --git a/Task/Church-numerals/FreeBASIC/church-numerals.basic b/Task/Church-numerals/FreeBASIC/church-numerals.basic new file mode 100644 index 0000000000..a53eccda1c --- /dev/null +++ b/Task/Church-numerals/FreeBASIC/church-numerals.basic @@ -0,0 +1,93 @@ +Type church + ' eg {r_add,1,{a,b}} + op As Integer + n As Integer + x(1 To 2) As Integer +End Type + +Dim Shared As church zero = Type(1, 0, {0, 1}) + +Function succ(c As church) As church + ' eg {r_add,1,{a,b}} => {r_add,2,{a,b}} aka a+b -> a+b+b + c.n += 1 + Return c +End Function + +' three normal integer-handling routines... +Function sum(n As Integer, a As Integer, b As Integer) As Integer + For i As Integer = 1 To n + a += b + Next i + Return a +End Function + +Function mul(n As Integer, a As Integer, b As Integer) As Integer + For i As Integer = 1 To n + a *= b + Next i + Return a +End Function + +Function pow(n As Integer, a As Integer, b As Integer) As Integer + For i As Integer = 1 To n + a = a ^ b + Next i + Return a +End Function + +' ...and three church constructors to match +' (no maths here, just pure static data) +Function churchSum(c As church, d As church) As church + Dim res As church + res.op = 1 ' 1 for add + res.n = 1 + res.x(1) = c.n + res.x(2) = d.n + Return res +End Function + +Function churchMul(c As church, d As church) As church + Dim res As church + res.op = 2 ' 2 for mul + res.n = 1 + res.x(1) = c.n + res.x(2) = d.n + Return res +End Function + +Function churchPow(c As church, d As church) As church + Dim res As church + res.op = 3 ' 3 for pow + res.n = 1 + res.x(1) = c.n + res.x(2) = d.n + Return res +End Function + +Function churchToNum(c As church) As Integer + ' note this is where the bulk of any processing happens + Select Case c.op + Case 1 + Return sum(c.n, c.x(1), c.x(2)) + Case 2 + Return mul(c.n, c.x(1), c.x(2)) + Case 3 + Return pow(c.n, c.x(1), c.x(2)) + End Select +End Function + +Function numToChurch(i As Integer) As church + Return Iif(i = 0, zero, succ(numToChurch(i - 1))) +End Function + +Dim As church three = succ(succ(succ(zero))) +Dim As church four = succ(three) +Print "three -> "; churchToNum(three) +Print "four -> "; churchToNum(four) +Print "three + four -> "; churchToNum(churchSum(three, four)) +Print "three * four -> "; churchToNum(churchMul(three, four)) +Print "three ^ four -> "; churchToNum(churchPow(three, four)) +Print "four ^ three -> "; churchToNum(churchPow(four, three)) +Print "5 -> five -> "; churchToNum(numToChurch(5)) + +Sleep diff --git a/Task/Church-numerals/Scala/church-numerals.scala b/Task/Church-numerals/Scala/church-numerals.scala new file mode 100644 index 0000000000..a1050876cb --- /dev/null +++ b/Task/Church-numerals/Scala/church-numerals.scala @@ -0,0 +1,41 @@ +object Church { + + trait ChurchNum extends (ChurchNum => ChurchNum) + + def zero: ChurchNum = f => x => x + + def next(n: ChurchNum): ChurchNum = f => x => f(n(f)(x)) + + def plus(a: ChurchNum)(b: ChurchNum): ChurchNum = f => x => b(f)(a(f)(x)) + + def mult(a: ChurchNum)(b: ChurchNum): ChurchNum = f => x => b(a(f))(x) + + def pow(m: ChurchNum)(n: ChurchNum): ChurchNum = n(m) + + def toChurchNum(n: Int): ChurchNum = if (n <= 0) zero else next(toChurchNum(n - 1)) + + def toInt(c: ChurchNum): Int = { + var counter = 0 + val funCounter: ChurchNum = f => { counter += 1; f } + plus(zero)(c)(funCounter)(x => x) + counter + } + + def main(args: Array[String]): Unit = { + val zero = Church.zero + val three = next(next(next(zero))) + val four = next(next(next(next(zero)))) + + println(s"3+4=${toInt(plus(three)(four))}") // prints 7 + println(s"4+3=${toInt(plus(four)(three))}") // prints 7 + + println(s"3*4=${toInt(mult(three)(four))}") // prints 12 + println(s"4*3=${toInt(mult(four)(three))}") // prints 12 + + // exponentiation. note the reversed order! + println(s"3^4=${toInt(pow(four)(three))}") // prints 81 + println(s"4^3=${toInt(pow(three)(four))}") // prints 64 + + println(s" 8=${toInt(toChurchNum(8))}") // prints 8 + } +} diff --git a/Task/Closures-Value-capture/Elena/closures-value-capture.elena b/Task/Closures-Value-capture/Elena/closures-value-capture.elena index 374171bdfd..b943a12d2c 100644 --- a/Task/Closures-Value-capture/Elena/closures-value-capture.elena +++ b/Task/Closures-Value-capture/Elena/closures-value-capture.elena @@ -3,7 +3,7 @@ import extensions; public program() { - var functions := Array.allocate(10).populate:(int i => { ^ i * i} ); + var functions := Array.allocate(10).populate::(int i => { ^ i * i} ); - functions.forEach:(func) { console.printLine(func()) } + functions.forEach::(func) { console.printLine(func()) } } diff --git a/Task/Closures-Value-capture/J/closures-value-capture-6.j b/Task/Closures-Value-capture/J/closures-value-capture-6.j index 2c09797edb..87722562c0 100644 --- a/Task/Closures-Value-capture/J/closures-value-capture-6.j +++ b/Task/Closures-Value-capture/J/closures-value-capture-6.j @@ -1,9 +1,6 @@ - ( VL=. (<@:((<'"')(0:`)(,^:)&_))"0@:(^&2)@:i. 10 ) NB. Producing a list of boxed anonymous verbs (functions) -┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐ -│0"_│1"_│4"_│9"_│16"_│25"_│36"_│49"_│64"_│81"_│ -└───┴───┴───┴───┴────┴────┴────┴────┴────┴────┘ - - {::&VL 5 NB. Evoking the 6th verb (function) -25"_ - {::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('') -25 +geni=: {{ + N=. cocreate'' + i__N=. y + N +}} +task=: {{ u {{ u {{ u i__n [ y }} (geni y)`'' }}"0 i. y }} diff --git a/Task/Closures-Value-capture/J/closures-value-capture-7.j b/Task/Closures-Value-capture/J/closures-value-capture-7.j new file mode 100644 index 0000000000..8b774bd854 --- /dev/null +++ b/Task/Closures-Value-capture/J/closures-value-capture-7.j @@ -0,0 +1,7 @@ + fns=: *: task 10 + fns@.3 '' +9 + fns@.5 '' +25 + fns@.7 '' +49 diff --git a/Task/Closures-Value-capture/J/closures-value-capture-8.j b/Task/Closures-Value-capture/J/closures-value-capture-8.j new file mode 100644 index 0000000000..2c09797edb --- /dev/null +++ b/Task/Closures-Value-capture/J/closures-value-capture-8.j @@ -0,0 +1,9 @@ + ( VL=. (<@:((<'"')(0:`)(,^:)&_))"0@:(^&2)@:i. 10 ) NB. Producing a list of boxed anonymous verbs (functions) +┌───┬───┬───┬───┬────┬────┬────┬────┬────┬────┐ +│0"_│1"_│4"_│9"_│16"_│25"_│36"_│49"_│64"_│81"_│ +└───┴───┴───┴───┴────┴────┴────┴────┴────┴────┘ + + {::&VL 5 NB. Evoking the 6th verb (function) +25"_ + {::&VL 5 '' NB. Invoking the 6th verb with a dummy argument ('') +25 diff --git a/Task/Collections/Elena/collections-2.elena b/Task/Collections/Elena/collections-2.elena index eb1fcf2c6f..e62a8c5aa6 100644 --- a/Task/Collections/Elena/collections-2.elena +++ b/Task/Collections/Elena/collections-2.elena @@ -1,5 +1,5 @@ //Create and initialize ArrayList -var myAl := new system'collections'ArrayList().append:"Hello".append:"World".append:"!"; +var myAl := new system'collections'ArrayList().append("Hello").append("World").append("!"); //Create and initialize List -var myList := new system'collections'List().append:"Hello".append:"World".append:"!"; +var myList := new system'collections'List().append("Hello").append("World").append("!"); diff --git a/Task/Colour-bars-Display/Uxntal/colour-bars-display.uxnatl b/Task/Colour-bars-Display/Uxntal/colour-bars-display.uxnatl index ee4eb639ec..ae82d8a7db 100644 --- a/Task/Colour-bars-Display/Uxntal/colour-bars-display.uxnatl +++ b/Task/Colour-bars-Display/Uxntal/colour-bars-display.uxnatl @@ -1,15 +1,25 @@ +( uxnasm color-bars.tal color-bars.rom && uxnemu color-bars.rom ) + |00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 |20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1 |0100 + ( set 4 color theme + rgb + color0: 000 - black + color1: f00 - red + color2: 0f0 - green + color3: 00f - blue ) #0f00 .System/r DEO2 #00f0 .System/g DEO2 #000f .System/b DEO2 + ( store bars width ) .Screen/width DEI2 #0004 DIV2 ,&quarter STR2 - + ( set starting position ) #0000 .Screen/y DEO2 + ( draw bars ) #00 &loop #00 OVR [ LIT2 &quarter $2 ] MUL2 diff --git a/Task/Colour-pinstripe-Display/Uxntal/colour-pinstripe-display.uxnatl b/Task/Colour-pinstripe-Display/Uxntal/colour-pinstripe-display.uxnatl index cd1647b7ce..8f499e336d 100644 --- a/Task/Colour-pinstripe-Display/Uxntal/colour-pinstripe-display.uxnatl +++ b/Task/Colour-pinstripe-Display/Uxntal/colour-pinstripe-display.uxnatl @@ -1,18 +1,38 @@ +( uxnasm color-pinstripe.tal color-pinstripe.rom && uxnemu color-pinstripe.rom ) + |00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 |20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1 -|0100 @reset +|0100 + ( set theme ) #0f00 .System/r DEO2 #00f0 .System/g DEO2 #000f .System/b DEO2 - .Screen/width DEI2 ,&width STR2 + ( store screen width ) + .Screen/width DEI2 ,draw-layer/width STR2 + ( store a quarter of the screen height ) + .Screen/height DEI2 #02 SFT2 ,&quarter-height STR2 - #0000 .Screen/y DEO2 + ( draw the four stripe layers ) + #00 + &loop ( -- ) + ( update y coordinate ) + #00 OVR [ LIT2 &quarter-height $2 ] MUL2 .Screen/y DEO2 + ( draw a layer ) + INCk draw-layer + ( do it four times ) + INC DUP #04 LTH ?&loop + POP BRK - #0000 - &loop - DUP2 .Screen/x DEO2 +@draw-layer ( step -: ) + ( extend step to short, create counter ) + #00 SWP #0000 + &loop ( -- ) + ( update x coordinate ) + MUL2k .Screen/x DEO2 + ( fill a region ) DUP #03 AND #80 ORA .Screen/pixel DEO - INC2 DUP2 [ LIT2 &width $2 ] NEQ2 ?&loop -BRK + ( loop until the end of the screen ) + INC2 MUL2k [ LIT2 &width $2 ] LTH2 ?&loop + POP2 POP2 JMP2r diff --git a/Task/Combinations-and-permutations/C-sharp/combinations-and-permutations.cs b/Task/Combinations-and-permutations/C-sharp/combinations-and-permutations.cs new file mode 100644 index 0000000000..ed026016a0 --- /dev/null +++ b/Task/Combinations-and-permutations/C-sharp/combinations-and-permutations.cs @@ -0,0 +1,94 @@ +using System; +using System.Numerics; + +class CombinationsAndPermutations +{ + public static void Main(string[] args) + { + Console.WriteLine(double.MaxValue); + Console.WriteLine("A sample of permutations from 1 to 12 with exact Integer arithmetic:"); + for (int n = 1; n <= 12; n++) + { + int k = n / 2; + Console.WriteLine($"{n} P {k} = {Permutation(n, k)}"); + } + + Console.WriteLine(); + Console.WriteLine("A sample of combinations from 10 to 60 with exact Integer arithmetic:"); + for (int n = 10; n <= 60; n += 5) + { + int k = n / 2; + Console.WriteLine($"{n} C {k} = {Combination(n, k)}"); + } + + Console.WriteLine(); + Console.WriteLine("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:"); + Console.WriteLine($"{5} P {2} = {Display(Permutation(5, 2), 50)}"); + for (int n = 1000; n <= 15000; n += 1000) + { + int k = n / 2; + Console.WriteLine($"{n} P {k} = {Display(Permutation(n, k), 50)}"); + } + + Console.WriteLine(); + Console.WriteLine("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:"); + for (int n = 100; n <= 1000; n += 100) + { + int k = n / 2; + Console.WriteLine($"{n} C {k} = {Display(Combination(n, k), 50)}"); + } + } + + private static string Display(BigInteger val, int precision) + { + string s = val.ToString(); + // Ensure that we don't try to take a substring longer than what's available. + int actualPrecision = Math.Min(precision, s.Length - 1); // Adjusted to ensure it doesn't exceed string length + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + if (s.Length > 1) // Check if the string has more than one character + { + sb.Append(s.Substring(0, 1)); + sb.Append("."); + sb.Append(s.Substring(1, actualPrecision-1)); + } + else + { + // If the string is only one digit, no need to insert a decimal point. + sb.Append(s); + } + + sb.Append(" * 10^"); + sb.Append(s.Length - 1); + return sb.ToString(); + } + + public static BigInteger Combination(int n, int k) + { + // Select value with smallest intermediate results + // combination(n, k) = combination(n, n-k) + if (n - k < k) + { + k = n - k; + } + + BigInteger result = Permutation(n, k); + while (k > 0) + { + result = result / k; + k--; + } + + return result; + } + + public static BigInteger Permutation(int n, int k) + { + BigInteger result = BigInteger.One; + for (int i = n; i >= n - k + 1; i--) + { + result = result * i; + } + + return result; + } +} diff --git a/Task/Combinations-and-permutations/Lua/combinations-and-permutations.lua b/Task/Combinations-and-permutations/Lua/combinations-and-permutations.lua new file mode 100644 index 0000000000..5445a2a1fe --- /dev/null +++ b/Task/Combinations-and-permutations/Lua/combinations-and-permutations.lua @@ -0,0 +1,61 @@ +-- Helper function to display results in scientific notation corrected +function eshow(x) + local e = math.floor(x / math.log(10)) + local exponentiated = math.exp(x - e * math.log(10)) + -- Corrected format specifier from %.8Fe%+d to %.8e, and manually constructing the scientific notation if needed + return string.format("%.8e", exponentiated) .. "e" .. tostring(e) +end + +-- The rest of the functions remain the same + +-- Define the factorial function for permutations +function P(n, k) + local x = 1 + for i = n - k + 1, n do + x = x * i + end + return x +end + +-- Define the function for big permutations using logarithms +function P_big(n, k) + local x = 0 + for i = n - k + 1, n do + x = x + math.log(i) + end + return eshow(x) +end + +-- Define the combinations function +function C(n, k) + local x = 1 + for i = 1, k do + x = x * (n - i + 1) / i + end + return x +end + +-- Define the function for big combinations using logarithms +function C_big(n, k) + local x = 0 + for i = 1, k do + x = x + math.log(n - i + 1) - math.log(i) + end + return math.exp(x) +end + +-- Function to showcase the calculations +function showoff(text, code, fname, ...) + local n = {...} + print("\nA sample of " .. text .. " from " .. n[1] .. " to " .. n[#n] .. "") + for _, v in ipairs(n) do + local k = math.floor(v / 3) + print(v, fname .. " " .. k .. " = ", code(v, k)) + end +end + +-- Examples of usage +showoff("Permutations", P, "P", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) +showoff("Combinations", C, "C", 10, 20, 30, 40, 50, 60) +showoff("Permutations", P_big, "P", 5, 50, 500, 1000, 5000, 15000) +showoff("Combinations", C_big, "C", 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000) diff --git a/Task/Combinations/Elena/combinations.elena b/Task/Combinations/Elena/combinations.elena index 8493fde0ba..c4903032f5 100644 --- a/Task/Combinations/Elena/combinations.elena +++ b/Task/Combinations/Elena/combinations.elena @@ -7,13 +7,13 @@ const int N = 5; Numbers(n) { - ^ Array.allocate(n).populate:(int n => n) + ^ Array.allocate(n).populate::(int n => n) } public program() { var numbers := Numbers(N); - Combinator.new(M, numbers).forEach:(row) + Combinator.new(M, numbers).forEach::(row) { console.printLine(row.toString()) }; diff --git a/Task/Comma-quibbling/Refal/comma-quibbling.refal b/Task/Comma-quibbling/Refal/comma-quibbling.refal new file mode 100644 index 0000000000..5c52faa392 --- /dev/null +++ b/Task/Comma-quibbling/Refal/comma-quibbling.refal @@ -0,0 +1,17 @@ +$ENTRY Go { + = > + > + > + >; +}; + +Quibble { + e.X = '{' '}'; +}; + +Quibble1 { + = ; + (e.Word) = e.Word; + (e.Word1) (e.Word2) = e.Word1 ' and ' e.Word2; + (e.Word) e.Words = e.Word ', ' ; +}; diff --git a/Task/Command-line-arguments/Elena/command-line-arguments.elena b/Task/Command-line-arguments/Elena/command-line-arguments.elena index f2b40e0a6f..538889e4e8 100644 --- a/Task/Command-line-arguments/Elena/command-line-arguments.elena +++ b/Task/Command-line-arguments/Elena/command-line-arguments.elena @@ -3,6 +3,6 @@ import extensions; public program() { - program_arguments.forEvery:(int i) + program_arguments.forEvery::(int i) { console.printLine("Argument ",i," is ",program_arguments[i]) } } diff --git a/Task/Comments/Bruijn/comments.bruijn b/Task/Comments/Bruijn/comments.bruijn new file mode 100644 index 0000000000..7dd15c1854 --- /dev/null +++ b/Task/Comments/Bruijn/comments.bruijn @@ -0,0 +1 @@ +# This is a comment diff --git a/Task/Comments/MiniScript/comments.mini b/Task/Comments/MiniScript/comments.mini new file mode 100644 index 0000000000..225d3cd667 --- /dev/null +++ b/Task/Comments/MiniScript/comments.mini @@ -0,0 +1,2 @@ +// How many roads must a man walk down? +x = 6 * 7 // forty-two diff --git a/Task/Compare-a-list-of-strings/Elena/compare-a-list-of-strings.elena b/Task/Compare-a-list-of-strings/Elena/compare-a-list-of-strings.elena index a126c3d586..b6c8ab0d12 100644 --- a/Task/Compare-a-list-of-strings/Elena/compare-a-list-of-strings.elena +++ b/Task/Compare-a-list-of-strings/Elena/compare-a-list-of-strings.elena @@ -5,7 +5,7 @@ import extensions; extension helper { isEqual() - = nil == self.seekEach(self.FirstMember, (n,m => m.equal:n.Inverted )); + = nil == self.seekEach(self.FirstMember, (n,m => m != n)); isAscending() { @@ -14,7 +14,7 @@ extension helper later.next(); - ^ nil == former.zipBy(later, (prev,next => next <= prev )).seekEach:(b => b) + ^ nil == former.zipBy(later, (prev,next => next <= prev )).seekEach::(b => b) } } @@ -28,7 +28,7 @@ testCases public program() { - testCases.forEach:(list) + testCases.forEach::(list) { console.printLine(list.asEnumerable()," all equal - ",list.isEqual()); console.printLine(list.asEnumerable()," ascending - ",list.isAscending()) diff --git a/Task/Compare-length-of-two-strings/Scala/compare-length-of-two-strings.scala b/Task/Compare-length-of-two-strings/Scala/compare-length-of-two-strings.scala new file mode 100644 index 0000000000..3f6dd7a1e6 --- /dev/null +++ b/Task/Compare-length-of-two-strings/Scala/compare-length-of-two-strings.scala @@ -0,0 +1,28 @@ +object Example extends App { + val strings = Array("abcd", "123456789", "abcdef", "1234567") + compareAndReportStringsLength(strings) + + def compareAndReportStringsLength(strings: Array[String]): Unit = { + if (strings.nonEmpty) { + val Q = '"' + val hasLength = " has length " + val predicateMax = " and is the longest string" + val predicateMin = " and is the shortest string" + val predicateAve = " and is neither the longest nor the shortest string" + + val sortedStrings = strings.sortBy(-_.length) + val maxLength = sortedStrings.head.length + val minLength = sortedStrings.last.length + + sortedStrings.foreach { str => + val length = str.length + val predicate = length match { + case `maxLength` => predicateMax + case `minLength` => predicateMin + case _ => predicateAve + } + println(s"$Q$str$Q$hasLength$length$predicate") + } + } + } +} diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/FreeBASIC/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.basic b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/FreeBASIC/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.basic new file mode 100644 index 0000000000..eb9f94848b --- /dev/null +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/FreeBASIC/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.basic @@ -0,0 +1,46 @@ +Function isSubstring(kStr As String, f As Integer) As Integer + Dim As String fStr = Str(f) + Dim As Integer fLen = Len(fStr) + Dim As Integer result = 0 + Dim As Integer fEnd = Len(kStr) - fLen + 1 + For fPos As Integer = 1 To Len(kStr) - fLen + 1 + If Mid(kStr, fPos, fLen) = fStr Then + result = -1 + Exit For + End If + Next fPos + Return result +End Function + +Dim As Integer requiredNumbers = 20 +Dim As Integer kCount = 0 +For k As Integer = 11 To 99999999 Step 2 + If k Mod 3 <> 0 And k Mod 5 <> 0 And k Mod 7 <> 0 Then + Dim As Integer isCandidate = -1 + Dim As String kStr = Str(k) + Dim As Integer v = k + Dim As Integer fCount = 0 + For f As Integer = 11 To Sqr(k) + 1 + If v Mod f = 0 Then + isCandidate = isSubstring(kStr, f) + If isCandidate Then + While v Mod f = 0 + fCount += 1 + v \= f + Wend + Else + Exit For + End If + End If + Next f + If isCandidate And (fCount > 1 Or (v <> k And v > 1)) Then + If v > 1 Then isCandidate = isSubstring(kStr, v) + If isCandidate Then + Print Using "#######,###"; k; + kCount += 1 + If kCount Mod 10 = 0 Then Print + End If + End If + End If + If kCount >= requiredNumbers Then Exit For +Next k diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/PARI-GP/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.parigp b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/PARI-GP/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.parigp new file mode 100644 index 0000000000..c7337192e5 --- /dev/null +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/PARI-GP/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.parigp @@ -0,0 +1,45 @@ +/* Returns a substring of str starting at s with length n */ +ssubstr(str, s = 1, n = 0) = { + my(vt = Vecsmall(str), ve, vr, vtn = #str, n1); + if (vtn == 0, return("")); + if (s < 1 || s > vtn, return(str)); + n1 = vtn - s + 1; if (n == 0, n = n1); if (n > n1, n = n1); + ve = vector(n, z, z - 1 + s); vr = vecextract(vt, ve); return(Strchr(vr)); +} + +/* Checks if subStr is a substring of mainStr */ +isSubstring(mainStr, subStr) = { + mainLen = #Vecsmall(mainStr); + subLen = #Vecsmall(subStr); + for (startPos = 1, mainLen - subLen + 1, + if (ssubstr(mainStr, startPos, subLen) == subStr, + return(1); /* True: subStr found in mainStr */ + ) + ); + return(0); /* False: subStr not found */ +} + +/* Determines if a number's factors, all > 9, are substrings of its decimal representation */ +contains_its_prime_factors_all_over_9(n) = { + if (n < 10 || isprime(n), return(0)); /* Skip if n < 10 or n is prime */ + strn = Str(n); /* Convert n to string */ + pfacs = factor(n)[, 1]; /* Get unique prime factors of n */ + for (i = 1, #pfacs, + if (pfacs[i] <= 9, return(0)); /* Skip factors ≤ 9 */ + if (!isSubstring(strn, Str(pfacs[i])), return(0)); /* Check if factor is a substring */ + ); + return(1); /* All checks passed */ +} + +/* Main loop to find and print numbers meeting the criteria */ +{ + found = 0; /* Counter for numbers found */ + for (n = 0, 30 * 10^6, /* Iterate from 0 to 30 million */ + if (contains_its_prime_factors_all_over_9(n), + found += 1; /* Increment counter if n meets criteria */ + print1(n, " "); /* Print n followed by a space */ + if (found % 10 == 0, print("")); /* Newline every 10 numbers */ + if (found == 20, break); /* Stop after finding 20 numbers */ + ); + ); +} diff --git a/Task/Conditional-structures/EasyLang/conditional-structures.easy b/Task/Conditional-structures/EasyLang/conditional-structures.easy index e460ff3243..6833cc19e7 100644 --- a/Task/Conditional-structures/EasyLang/conditional-structures.easy +++ b/Task/Conditional-structures/EasyLang/conditional-structures.easy @@ -1,8 +1,8 @@ -i = random 10 +i = randint 10 if i mod 2 = 0 - print i & " is divisible by 2" + print i & " is divisible by 2" elif i mod 3 = 0 - print i & " is divisible by 3" + print i & " is divisible by 3" else - print i & " is not divisible by 2 or 3" + print i & " is not divisible by 2 or 3" . diff --git a/Task/Conditional-structures/Langur/conditional-structures-4.langur b/Task/Conditional-structures/Langur/conditional-structures-4.langur index 1599f7718e..8be040d87e 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-4.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-4.langur @@ -15,7 +15,7 @@ switch 0 { ... } -given .x, .y, .z { +switch[and] .x, .y, .z { case true: ... # all are true case false, _: ... diff --git a/Task/Conditional-structures/Langur/conditional-structures-5.langur b/Task/Conditional-structures/Langur/conditional-structures-5.langur index d3958bf2c9..8ee9423979 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-5.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-5.langur @@ -1,4 +1,4 @@ -given .x { +switch .x { case true: # implicit fallthrough case null: 0 diff --git a/Task/Conditional-structures/Langur/conditional-structures-6.langur b/Task/Conditional-structures/Langur/conditional-structures-6.langur index 5ffadd03ef..90ba731409 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-6.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-6.langur @@ -1,4 +1,4 @@ -given .x { +switch .x { case true: if .y > 100 { fallthrough diff --git a/Task/Conditional-structures/Langur/conditional-structures-7.langur b/Task/Conditional-structures/Langur/conditional-structures-7.langur index 225dcde3cf..7a0f665429 100644 --- a/Task/Conditional-structures/Langur/conditional-structures-7.langur +++ b/Task/Conditional-structures/Langur/conditional-structures-7.langur @@ -1,4 +1,4 @@ -given(.x, .y, .z; - true: ... ; # all are equal to true +switch(.x, .y, .z; + true: ... ; # any are equal to true _, >= .z: ...; # .y >= .z ... ) # default diff --git a/Task/Conditional-structures/UNIX-Shell/conditional-structures-2.sh b/Task/Conditional-structures/UNIX-Shell/conditional-structures-2.sh index ad1158aacc..9f137fa089 100644 --- a/Task/Conditional-structures/UNIX-Shell/conditional-structures-2.sh +++ b/Task/Conditional-structures/UNIX-Shell/conditional-structures-2.sh @@ -1,7 +1,6 @@ -if test 4 -ge 6; then - echo '4 is greater than or equal to 6' -elif test 4 -lt 6; then - echo '4 is less than 6' -else - echo '4 compares not to 6' +if test 4 -ge 6 +then echo '4 is greater than or equal to 6' +elif test 4 -lt 6 +then echo '4 is less than 6' +else echo '4 compares not to 6' fi diff --git a/Task/Constrained-random-points-on-a-circle/EasyLang/constrained-random-points-on-a-circle.easy b/Task/Constrained-random-points-on-a-circle/EasyLang/constrained-random-points-on-a-circle.easy index 3f4f491b57..70dc2970d0 100644 --- a/Task/Constrained-random-points-on-a-circle/EasyLang/constrained-random-points-on-a-circle.easy +++ b/Task/Constrained-random-points-on-a-circle/EasyLang/constrained-random-points-on-a-circle.easy @@ -1,6 +1,6 @@ while cnt < 100 - x = random 31 - 16 - y = random 31 - 16 + x = randint 31 - 16 + y = randint 31 - 16 r = sqrt (x * x + y * y) if 10 <= r and r <= 15 cnt += 1 diff --git a/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur b/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur new file mode 100644 index 0000000000..7930d09cf7 --- /dev/null +++ b/Task/Convert-seconds-to-compound-duration/Langur/convert-seconds-to-compound-duration.langur @@ -0,0 +1,17 @@ +val .duration = f(var .sec) { + [ + w/wk d hr min sec/, + for[=[]] .dm in [7 x 24 x 60 x 60, 24 x 60 x 60, 60 x 60, 60] { + _for ~= [.sec \ .dm] + .sec = .sec rem .dm + } ~ [.sec], + ] +} + +for .seconds in [7259, 86400, 6000000] { + val .dur = .duration(.seconds) + write $"\.seconds:7; sec = " + writeln join ", ", for[=[]] .k of .dur[1] { + if .dur[2][.k] != 0: _for ~= [$"\.dur[2][.k]; \.dur[1][.k];"] + } +} diff --git a/Task/Conways-Game-of-Life/APL/conways-game-of-life-1.apl b/Task/Conways-Game-of-Life/APL/conways-game-of-life-1.apl new file mode 100644 index 0000000000..67d1ff54c2 --- /dev/null +++ b/Task/Conways-Game-of-Life/APL/conways-game-of-life-1.apl @@ -0,0 +1,20 @@ + Life←{↑↑1 ⍵∨.∧3 4=+/,¯1 0 1∘.⊖¯1 0 1∘.⌽⊂⍵} + m ← 5 5⍴(0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0) + m +0 0 0 0 0 +0 0 0 0 0 +0 1 1 1 0 +0 0 0 0 0 +0 0 0 0 0 + Life m +0 0 0 0 0 +0 0 1 0 0 +0 0 1 0 0 +0 0 1 0 0 +0 0 0 0 0 + Life Life m +0 0 0 0 0 +0 0 0 0 0 +0 1 1 1 0 +0 0 0 0 0 +0 0 0 0 0 diff --git a/Task/Conways-Game-of-Life/APL/conways-game-of-life.apl b/Task/Conways-Game-of-Life/APL/conways-game-of-life-2.apl similarity index 100% rename from Task/Conways-Game-of-Life/APL/conways-game-of-life.apl rename to Task/Conways-Game-of-Life/APL/conways-game-of-life-2.apl diff --git a/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena b/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena index 5a01c0b0ac..946164b595 100644 --- a/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena +++ b/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena @@ -77,10 +77,10 @@ public extension presenterOp : Space int rows := self.Rows; auto line := new TextBuilder(); - for(int i := 0, i < rows, i += 1) + for(int i := 0; i < rows; i += 1) { line.clear(); - for(int j := 0, j < columns, j += 1) + for(int j := 0; j < columns; j += 1) { int cell := self.at(i, j); @@ -103,7 +103,7 @@ public program() { model.run(); - threadControl.sleep:DELAY + threadControl.sleep(DELAY) }; console.readChar() diff --git a/Task/Conways-Game-of-Life/FutureBasic/conways-game-of-life.basic b/Task/Conways-Game-of-Life/FutureBasic/conways-game-of-life.basic new file mode 100644 index 0000000000..583850b9f4 --- /dev/null +++ b/Task/Conways-Game-of-Life/FutureBasic/conways-game-of-life.basic @@ -0,0 +1,34 @@ +Short a(4, 4), c(4, 4) // Initialize arrays of cells and a working copy + +void local fn seed + Short x, y + // Blinker + a(1, 2) = 1 : a(2, 2) = 1 : a(3, 2) = 1 + for y = 1 to 3 : for x = 1 to 3 + print a(x, y); // Draw array + next : print : next : print +end fn + +void local fn nextGen + Short x, y, dx, dy, n + // Calculate next generation on temporary board + for y = 1 to 3 : for x = 1 to 3 + c(x, y) = 0 // Initialize + n = -a(x, y) // Don't count center cell + for dy = -1 to 1 : for dx = -1 to 1 + n += a(x + dx, y + dy) // Count the neighbours + next : next + c(x, y) = ( n == 3 ) or ( n == 2 and a(x, y) ) // Conway’s rule + next : next + // Copy temp array to actual array and draw + for y = 1 to 3 : for x = 1 to 3 + a(x, y) = c(x, y) // Copy + print a(x, y); // Draw + next : print : next : print +end fn + +fn seed +fn nextGen +fn nextGen + +handleevents // Go into Mac event loop diff --git a/Task/Copy-a-string/Pascal/copy-a-string.pas b/Task/Copy-a-string/Pascal/copy-a-string.pas index 90fe98f704..6fc5be060c 100644 --- a/Task/Copy-a-string/Pascal/copy-a-string.pas +++ b/Task/Copy-a-string/Pascal/copy-a-string.pas @@ -1,28 +1,16 @@ -program in,out; - -type - - pString = ^string; - -var - - s1,s2 : string ; - pStr : pString ; - -begin - - /* direct copy */ - s1 := 'Now is the time for all good men to come to the aid of their party.' - s2 := s1 ; - - writeln(s1); - writeln(s2); - - /* By Reference */ - pStr := @s1 ; - writeln(pStr^); - - pStr := @s2 ; - writeln(pStr^); - -end; +program copyAString; + var + { The Extended Pascal `string` schema data type + is essentially a `packed array[1..capacity] of char`. } + source, destination: string(80); + begin + source := 'Hello world!'; + { In Pascal _whole_ array data type values can be copied by assignment. } + destination := source; + { Provided `source` is a _non-empty_ string value + you can copy in Extended Pascal sub-ranges _of_ _string_ types, too. + Note, the sub-range notation is not permitted for a `bindable` data type. } + destination := source[1..length(source)]; + { You can also employ Extended Pascal’s `writeStr` routine: } + writeStr(destination, source); + end. diff --git a/Task/Count-in-factors/Refal/count-in-factors.refal b/Task/Count-in-factors/Refal/count-in-factors.refal new file mode 100644 index 0000000000..c34a578763 --- /dev/null +++ b/Task/Count-in-factors/Refal/count-in-factors.refal @@ -0,0 +1,33 @@ +$ENTRY Go { + = 2144>; +}; + +Factorize { + 1 = 1; + s.N = ; + s.D s.N, : '-' = ; + s.D s.N, : { + (s.R) 0 = s.D ; + e.X = s.N>; + }; +}; + +Join { + (e.J) = ; + (e.J) s.N = ; + (e.J) s.N e.X = e.J ; +}; + +Iota { + s.End s.End = s.End; + s.Start s.End = s.Start s.End>; +}; + +Each { + s.F = ; + s.F t.I e.X = ; +}; + +Show { + e.N = ' = ' >>; +}; diff --git a/Task/Count-in-octal/Langur/count-in-octal.langur b/Task/Count-in-octal/Langur/count-in-octal.langur index 79b1544672..75aba01e45 100644 --- a/Task/Count-in-octal/Langur/count-in-octal.langur +++ b/Task/Count-in-octal/Langur/count-in-octal.langur @@ -1,5 +1,5 @@ val .limit = 70000 -for .i = 0; .i <= .limit; .i += 1 { +for .i of .limit { writeln $"10x\.i; == 8x\.i:8x;" } diff --git a/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur b/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur index aeae29af77..2af267a23c 100644 --- a/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur +++ b/Task/Count-occurrences-of-a-substring/Langur/count-occurrences-of-a-substring.langur @@ -1,2 +1,2 @@ -writeln len indices q(th), q(the three truths) -writeln len indices q(abab), q(ababababab) +writeln len indices "th", "the three truths" +writeln len indices "abab", "ababababab" diff --git a/Task/Count-occurrences-of-a-substring/Refal/count-occurrences-of-a-substring.refal b/Task/Count-occurrences-of-a-substring/Refal/count-occurrences-of-a-substring.refal new file mode 100644 index 0000000000..80a74f5713 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Refal/count-occurrences-of-a-substring.refal @@ -0,0 +1,10 @@ +$ENTRY Go { + = > + >; +}; + +Count { + (e.item) e.item e.rest = <+ 1 >; + (e.item) s.x e.rest = ; + (e.item) = 0; +}; diff --git a/Task/Create-a-two-dimensional-array-at-runtime/EasyLang/create-a-two-dimensional-array-at-runtime.easy b/Task/Create-a-two-dimensional-array-at-runtime/EasyLang/create-a-two-dimensional-array-at-runtime.easy new file mode 100644 index 0000000000..acdab8f2fc --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/EasyLang/create-a-two-dimensional-array-at-runtime.easy @@ -0,0 +1,14 @@ +write "Number of rows: " +nrows = number input +print nrows +write "Number of columns: " +ncols = number input +print ncols +# +len a[][] nrows +for i to nrows + len a[i][] ncols +. +a[1][1] = 11 +print a[1][1] +len a[][] 0 diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-1.elena b/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-1.elena index aa7f03b717..72d7c9c5ee 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-1.elena +++ b/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-1.elena @@ -5,7 +5,7 @@ public program() var n := new Integer(); var m := new Integer(); - console.write:"Enter two space delimited integers:"; + console.write("Enter two space delimited integers:"); console.loadLine(n,m); var myArray := class Matrix.allocate(n,m); diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-2.elena b/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-2.elena index 4cd151dc9d..e2a4e361ec 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-2.elena +++ b/Task/Create-a-two-dimensional-array-at-runtime/Elena/create-a-two-dimensional-array-at-runtime-2.elena @@ -6,10 +6,10 @@ public program() auto n := new Integer(); auto m := new Integer(); - console.write:"Enter two space delimited integers:"; + console.write("Enter two space delimited integers:"); console.loadLine(n,m); - auto myArray2 := new object[][](n.Value).populate:(int i => (new object[](m.Value)) ); + auto myArray2 := new object[][](n.Value).populate::(int i => (new object[](m.Value)) ); myArray2[0][0] := 2; myArray2[1][0] := "Hello"; diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Objeck/create-a-two-dimensional-array-at-runtime.objeck b/Task/Create-a-two-dimensional-array-at-runtime/Objeck/create-a-two-dimensional-array-at-runtime.objeck index 699f99fad9..8702029533 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Objeck/create-a-two-dimensional-array-at-runtime.objeck +++ b/Task/Create-a-two-dimensional-array-at-runtime/Objeck/create-a-two-dimensional-array-at-runtime.objeck @@ -1,23 +1,12 @@ -use IO; +class TwoDimArray { + function : Main(args : String[]) ~ Nil { + rows := Standard->ReadLine()->ToInt(); + cols := Standard->ReadLine()->ToInt(); -bundle Default { - class TwoDee { - function : Main(args : System.String[]) ~ Nil { - DoIt(); - } - - function : native : DoIt() ~ Nil { - Console->GetInstance()->Print("Enter x: "); - x := Console->GetInstance()->ReadString()->ToInt(); - - Console->GetInstance()->Print("Enter y: "); - y := Console->GetInstance()->ReadString()->ToInt(); - - if(x > 0 & y > 0) { - array : Int[,] := Int->New[x, y]; - array[0, 0] := 2; - array[0, 0]->PrintLine(); - }; + if(rows > 0 & cols > 0) { + array := Float->New[rows, cols]; + array[0,0] := 42.0; + Standard->Print("The number at place [0,] is: ")->PrintLine(array[0,0]); } } } diff --git a/Task/Cuban-primes/EasyLang/cuban-primes.easy b/Task/Cuban-primes/EasyLang/cuban-primes.easy new file mode 100644 index 0000000000..015d45cd7d --- /dev/null +++ b/Task/Cuban-primes/EasyLang/cuban-primes.easy @@ -0,0 +1,27 @@ +fastfunc isprim_odd num . + i = 3 + while i <= sqrt num + if num mod i = 0 + return 0 + . + i += 2 + . + return 1 +. +numfmt 0 7 +i = 1 +while cnt < 100000 + di = 3 * i * (i + 1) + 1 + if isprim_odd di = 1 + cnt += 1 + if cnt <= 200 + write di & " " + if cnt mod 8 = 0 + print "" + . + . + . + i += 1 +. +print "" +print di diff --git a/Task/Cuban-primes/PARI-GP/cuban-primes.parigp b/Task/Cuban-primes/PARI-GP/cuban-primes.parigp new file mode 100644 index 0000000000..8a6da33165 --- /dev/null +++ b/Task/Cuban-primes/PARI-GP/cuban-primes.parigp @@ -0,0 +1,25 @@ +cubanprimes(N) = +{ + cubans = vector(N); + cube1 = 1; count = 1; cube100k = 0; + for (i=1, +oo, + cube2 = (i + 1)^3; + diff = cube2 - cube1; + if (isprime(diff), + if (count <= N, cubans[count] = diff); + if (count == 100000, cube100k = diff; break); + count++; + ); + cube1 = cube2; + ); + print("The first " N " Cuban primes are: "); + for (i=1, N, + if (cubans[i] != 0, + print1(cubans[i], " "); + if (i % 8 == 0, print); + ); + ); + print("\nThe 100,000th Cuban prime is " cube100k); +} + +cubanprimes(200); diff --git a/Task/Cullen-and-Woodall-numbers/PARI-GP/cullen-and-woodall-numbers.parigp b/Task/Cullen-and-Woodall-numbers/PARI-GP/cullen-and-woodall-numbers.parigp new file mode 100644 index 0000000000..1127cb9452 --- /dev/null +++ b/Task/Cullen-and-Woodall-numbers/PARI-GP/cullen-and-woodall-numbers.parigp @@ -0,0 +1,29 @@ +/* Define the Cullen and Woodall number functions */ +cullen(n) = n * 2^n + 1; +woodall(n) = n * 2^n - 1; + +{ +/* Generate the first 20 Cullen and Woodall numbers */ +print(vector(20, n, cullen(n))); +print(vector(20, n, woodall(n))); + +/* Find the first 5 Cullen prime numbers */ +cps = []; +for(i = 1, +oo, + if(isprime(cullen(i)), + cps = concat(cps, i); + if(#cps >= 5, break); + ); +); +print(cps); + +/* Find the first 12 Woodall prime numbers */ +wps = []; +for(i = 1, +oo, + if(isprime(woodall(i)), + wps = concat(wps, i); + if(#wps >= 12, break); + ); +); +print(wps); +} diff --git a/Task/Cullen-and-Woodall-numbers/Scala/cullen-and-woodall-numbers.scala b/Task/Cullen-and-Woodall-numbers/Scala/cullen-and-woodall-numbers.scala new file mode 100644 index 0000000000..4563d3910b --- /dev/null +++ b/Task/Cullen-and-Woodall-numbers/Scala/cullen-and-woodall-numbers.scala @@ -0,0 +1,70 @@ +import java.math.BigInteger +import scala.annotation.tailrec + +object CullenAndWoodhall extends App { + + val Certainty = 20 + var number: BigInteger = _ + var power: BigInteger = _ + var count: Int = _ + var primeIndex: Int = _ + + sealed trait NumberType + case object Cullen extends NumberType + case object Woodhall extends NumberType + + numberSequence(20, Cullen) + numberSequence(20, Woodhall) + primeSequence(5, Cullen) + primeSequence(12, Woodhall) + + def numberSequence(aCount: Int, aNumberType: NumberType): Unit = { + println(s"\nThe first $aCount $aNumberType numbers are:") + numberInitialise() + (1 to aCount).foreach { _ => + print(nextNumber(aNumberType).toString + " ") + } + println() +} + + + def primeSequence(aCount: Int, aNumberType: NumberType): Unit = { + println(s"\nThe indexes of the first $aCount $aNumberType primes are:") + primeInitialise() + + @tailrec + def findPrimes(): Unit = { + if (count < aCount) { + if (nextNumber(aNumberType).isProbablePrime(Certainty)) { + print(primeIndex + " ") + count += 1 + } + primeIndex += 1 + findPrimes() + } + } + + findPrimes() + println() + } + + def nextNumber(aNumberType: NumberType): BigInteger = { + number = number.add(BigInteger.ONE) + power = power.shiftLeft(1) + aNumberType match { + case Cullen => number.multiply(power).add(BigInteger.ONE) + case Woodhall => number.multiply(power).subtract(BigInteger.ONE) + } + } + + def numberInitialise(): Unit = { + number = BigInteger.ZERO + power = BigInteger.ONE + } + + def primeInitialise(): Unit = { + count = 0 + primeIndex = 1 + numberInitialise() + } +} diff --git a/Task/Currying/MiniScript/currying.mini b/Task/Currying/MiniScript/currying.mini new file mode 100644 index 0000000000..b832d049f5 --- /dev/null +++ b/Task/Currying/MiniScript/currying.mini @@ -0,0 +1,9 @@ +addN = function(n) + f = function(x) + return n + x + end function + return @f +end function + +adder = addN(40) +print "The answer to life is " + adder(2) + "." diff --git a/Task/Curzon-numbers/PARI-GP/curzon-numbers.parigp b/Task/Curzon-numbers/PARI-GP/curzon-numbers.parigp new file mode 100644 index 0000000000..a797abc6a7 --- /dev/null +++ b/Task/Curzon-numbers/PARI-GP/curzon-numbers.parigp @@ -0,0 +1,39 @@ +/* Define the CurzonNumberQ function for base b */ +powermod(a,k,n)=lift(Mod(a,n)^k) +CurzonNumberQ(b, n) = (powermod(b,n,b*n+1)== b*n); + +/* Define a function to find Curzon numbers within a range for base b */ +FindCurzonNumbers(b, maxrange) = { + local(val, res, i); + val = vector(maxrange); + res = []; + for(i = 1, maxrange, + if(CurzonNumberQ(b, i), res = concat(res, i)); + ); + return(Vec(res)); +} + +/* Select and display the first 50 Curzon numbers and the 1000th for base 2 */ +val = FindCurzonNumbers(2, 100000); +print(vector(50, i, val[i])); /* First 50 */ +print(val[1000]); /* 1000th Curzon number */ + +/* Select and display for base 4 */ +val = FindCurzonNumbers(4, 100000); +print(vector(50, i, val[i])); /* First 50 */ +print(val[1000]); /* 1000th Curzon number */ + +/* Select and display for base 6 */ +val = FindCurzonNumbers(6, 100000); +print(vector(50, i, val[i])); /* First 50 */ +print(val[1000]); /* 1000th Curzon number */ + +/* Select and display for base 8 */ +val = FindCurzonNumbers(8, 100000); +print(vector(50, i, val[i])); /* First 50 */ +print(val[1000]); /* 1000th Curzon number */ + +/* Select and display for base 10 */ +val = FindCurzonNumbers(10, 100000); +print(vector(50, i, val[i])); /* First 50 */ +print(val[1000]); /* 1000th Curzon number */ diff --git a/Task/Cut-a-rectangle/C-sharp/cut-a-rectangle.cs b/Task/Cut-a-rectangle/C-sharp/cut-a-rectangle.cs new file mode 100644 index 0000000000..7f89267214 --- /dev/null +++ b/Task/Cut-a-rectangle/C-sharp/cut-a-rectangle.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; + +public class CutRectangle +{ + private static int[][] dirs = new int[][] { new int[] { 0, -1 }, new int[] { -1, 0 }, new int[] { 0, 1 }, new int[] { 1, 0 } }; + + public static void Main(string[] args) + { + CutRectangleMethod(2, 2); + CutRectangleMethod(4, 3); + } + + static void CutRectangleMethod(int w, int h) + { + if (w % 2 == 1 && h % 2 == 1) + return; + + int[,] grid = new int[h, w]; + Stack stack = new Stack(); + + int half = (w * h) / 2; + long bits = (long)Math.Pow(2, half) - 1; + + for (; bits > 0; bits -= 2) + { + for (int i = 0; i < half; i++) + { + int r = i / w; + int c = i % w; + grid[r, c] = (bits & (1L << i)) != 0 ? 1 : 0; + grid[h - r - 1, w - c - 1] = 1 - grid[r, c]; + } + + stack.Push(0); + grid[0, 0] = 2; + int count = 1; + while (stack.Count > 0) + { + int pos = stack.Pop(); + int r = pos / w; + int c = pos % w; + + foreach (var dir in dirs) + { + int nextR = r + dir[0]; + int nextC = c + dir[1]; + + if (nextR >= 0 && nextR < h && nextC >= 0 && nextC < w) + { + if (grid[nextR, nextC] == 1) + { + stack.Push(nextR * w + nextC); + grid[nextR, nextC] = 2; + count++; + } + } + } + } + if (count == half) + { + PrintResult(grid, h, w); + } + } + } + + static void PrintResult(int[,] arr, int height, int width) + { + for (int i = 0; i < height; i++) + { + for (int j = 0; j < width; j++) + { + Console.Write(arr[i, j] + (j == width - 1 ? "" : ", ")); + } + Console.WriteLine(); + } + Console.WriteLine(); + } +} diff --git a/Task/Cyclops-numbers/FreeBASIC/cyclops-numbers.basic b/Task/Cyclops-numbers/FreeBASIC/cyclops-numbers.basic new file mode 100644 index 0000000000..6b496ea702 --- /dev/null +++ b/Task/Cyclops-numbers/FreeBASIC/cyclops-numbers.basic @@ -0,0 +1,124 @@ +Dim Shared As Double t +Dim Shared As Uinteger n(16), clops(52), primes(52), blinds(52), pals(52) +Dim Shared As Uinteger num, iClop, iPrime, iBlind, iPal +Dim Shared As Uinteger first1, last1, midPt +midPt = 8 + +Function convertToNumber As Uinteger + Dim As Uinteger p10 = 1, nr = 0, c2 = last1 + Do + nr += n(c2) * p10 + If c2 = midPt Then p10 *= 100 Else p10 *= 10 'Add 0 if at midPoint + c2 -= 1 + Loop Until c2 < first1 + Return nr +End Function + +Sub increment(dgt As Uinteger) + If n(dgt) < 9 Then n(dgt) += 1 : Exit Sub + n(dgt) = 1 + If dgt > first1 Then increment(dgt - 1) : Exit Sub 'Carry + first1 -= 1 : last1 += 1 + For dgt = first1 To last1 'New width: set all digits to 1 + n(dgt) = 1 + Next dgt +End Sub + +Function isPrime(v As Uinteger) As Boolean + 'Skip check for 2 and 3 because we're starting at 101 + If v Mod 2 = 0 Then Return False + If v Mod 3 = 0 Then Return False + Dim As Uinteger f = 5 + While f*f <= v + If v Mod f = 0 Then Return False + f += 2 + If v Mod f = 0 Then Return False + f += 4 + Wend + Return True +End Function + +Function isBlind As Boolean + Dim As Uinteger temp = 0 + Swap temp, midPt 'Keep fn convertToNumber from adding 0 at midPt + Dim As Boolean rslt = isPrime(convertToNumber()) + Swap temp, midPt + Return rslt +End Function + +Function isPalindrome As Boolean + Dim As Uinteger a = first1, b = last1 + While b > a + If n(a) <> n(b) Then Return False + a += 1 : b -= 1 + Wend + Return True +End Function + +Sub print50(title As String, addr() As Uinteger) + Dim As Uinteger r = 0 + Print : Print title + While r < 50 + Print Using "#########"; addr(r); + r += 1 : If r Mod 10 = 0 Then Print + Wend +End Sub + +Sub display + print50(" First 50 Cyclopean numbers:", clops()) + print50(" First 50 Cyclopean primes:", primes()) + print50(" First 50 blind Cyclopean primes:", blinds()) + print50(" First 50 palindromic Cyclopean primes:", pals()) + Print + Print Using " First Cyclopean number above 10,000,000 is ######### at index ######"; clops(50); clops(51) + Print Using " First Cyclopean prime above 10,000,000 is ######### at index ######"; primes(50); primes(51) + Print Using " First blind Cyclopean prime above 10,000,000 is ######### at index ######"; blinds(50); blinds(51) + Print Using " First palindromic Cyclopean prime above 10,000,000 is ######### at index ######"; pals(50); pals(51) + Print + Print Using " Compute time: ###.### sec"; t +End Sub + +Sub cyclops + clops(0) = 0 : iClop = 1 : iPrime = 0 : iBlind = 0 : iPal = 0 + first1 = midPt-1 : last1 = midPt : n(first1) = 1 : n(last1) = 1 + + ' Record first 50 numbers in each category + While iPal < 50 + num = convertToNumber() + If iClop < 50 Then clops(iClop) = num + iClop += 1 + If isPrime(num) Then + If iPrime < 50 Then primes(iPrime) = num : iPrime += 1 + If iBlind < 50 Andalso isBlind() Then blinds(iBlind) = num : iBlind += 1 + If iPal < 50 Andalso isPalindrome() Then pals(iPal) = num : iPal += 1 + End If + num += 1 + increment(last1) + Wend + + ' Keep counting Cyclops numbers until 10,000,000 + While convertToNumber() < 1e7 + increment(last1) : iClop += 1 + Wend + + ' Find next number in each category + clops(50) = convertToNumber() : clops(51) = iClop + iPrime = 1 : iBlind = 1 : iPal = 1 + While (iPrime Or iBlind Or iPal) + num = convertToNumber() + iClop += 1 + If isPrime(num) Then + If iPrime = 1 Then primes(50) = num : primes(51) = iClop : iPrime = 0 + If iBlind = 1 Andalso isBlind() Then blinds(50) = num : blinds(51) = iClop : iBlind = 0 + If iPal = 1 Andalso isPalindrome() Then pals(50) = num : pals(51) = iClop : iPal = 0 + End If + increment(last1) + Wend +End Sub + +t = Timer +cyclops() +t = Timer - t +display() + +Sleep diff --git a/Task/Cyclotomic-polynomial/Java/cyclotomic-polynomial.java b/Task/Cyclotomic-polynomial/Java/cyclotomic-polynomial-1.java similarity index 100% rename from Task/Cyclotomic-polynomial/Java/cyclotomic-polynomial.java rename to Task/Cyclotomic-polynomial/Java/cyclotomic-polynomial-1.java diff --git a/Task/Cyclotomic-polynomial/Java/cyclotomic-polynomial-2.java b/Task/Cyclotomic-polynomial/Java/cyclotomic-polynomial-2.java new file mode 100644 index 0000000000..0ff8665b72 --- /dev/null +++ b/Task/Cyclotomic-polynomial/Java/cyclotomic-polynomial-2.java @@ -0,0 +1,132 @@ +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CyclotomicPolynomials { + + public static void main(String[] args) { + System.out.println("Task 1: Cyclotomic polynomials for n <= 30:"); + for ( int cpIndex = 1; cpIndex <= 30; cpIndex++ ) { + System.out.println("CP[" + cpIndex + "] = " + toString(cyclotomicPolynomial(cpIndex))); + } + + System.out.println(); + System.out.println("Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:"); + System.out.println("CP[1] has a coefficient with magnitude 1"); + int cpIndex = 2; + for ( int coefficient = 2; coefficient <= 10; coefficient++ ) { + while ( BigInteger.valueOf(cpIndex).isProbablePrime(PRIME_CERTAINTY) + || ! hasHeight(cyclotomicPolynomial(cpIndex), coefficient) ) { + cpIndex += 1; + } + System.out.println("CP[" + cpIndex + "] has a coefficient with magnitude " + coefficient); + } + } + + // Return the Cyclotomic Polynomial of order 'cpIndex' as an array of coefficients, + // where, for example, the polynomial 3x^2 - 1 is represented by the array [3, 0, -1]. + private static int[] cyclotomicPolynomial(int cpIndex) { + int[] polynomial = new int[] { 1, -1 }; + if ( cpIndex == 1 ) { + return polynomial; + } + + if ( BigInteger.valueOf(cpIndex).isProbablePrime(PRIME_CERTAINTY) ) { + int[] result = new int[cpIndex]; + Arrays.fill(result, 1); + return result; + } + + List primes = distinctPrimeFactors(cpIndex); + int product = 1; + for ( int prime : primes ) { + int[] numerator = substituteExponent(polynomial, prime); + polynomial = exactDivision(numerator, polynomial); + product *= prime; + } + + polynomial = substituteExponent(polynomial, cpIndex / product); + return polynomial; + } + + // Return the Cyclotomic Polynomial obtained from 'polynomial' by replacing x with x^'exponent'. + private static int[] substituteExponent(int[] polynomial, int exponent) { + int[] result = new int[exponent * ( polynomial.length - 1 ) + 1]; + for ( int i = polynomial.length - 1; i >= 0; i-- ) { + result[i * exponent] = polynomial[i]; + } + + return result; + } + + // Return the Cyclotomic Polynomial equal to 'dividend' / 'divisor'. The division is always exact. + private static int[] exactDivision(int[] dividend, int[] divisor) { + int[] result = Arrays.copyOf(dividend, dividend.length); + for ( int i = 0; i < dividend.length - divisor.length + 1; i++ ) { + if ( result[i] != 0 ) { + for ( int j = 1; j < divisor.length; j ++ ) { + result[i + j] += -divisor[j] * result[i]; + } + } + } + + result = Arrays.copyOf(result, result.length - divisor.length + 1); + return result; + } + + // Return whether 'polynomial' has a coefficient of equal magnitude to 'coefficient'. + private static boolean hasHeight(int[] polynomial, int coefficient) { + for ( int i = 0; i <= ( polynomial.length + 1 ) / 2; i++ ) { + if ( Math.abs(polynomial[i]) == coefficient ) { + return true; + } + } + + return false; + } + + // Return a string representation of 'polynomial'. + private static String toString(int[] polynomial) { + StringBuilder text = new StringBuilder(); + for ( int i = 0; i < polynomial.length; i++ ) { + if ( polynomial[i] == 0 ) { + continue; + } + + text.append(( polynomial[i] < 0 ) ? ( ( i == 0 ) ? "-" : " - " ) : ( ( i == 0 ) ? "" : " + " )); + + final int exponent = polynomial.length - 1 - i; + if ( exponent > 0 && Math.abs(polynomial[i]) > 1 ) { + text.append(Math.abs(polynomial[i])); + } + + text.append(( exponent > 1 ) ? + ( "x^" + String.valueOf(exponent) ) : ( ( exponent == 1 ) ? "x" : Math.abs(polynomial[i]) )); + } + + return text.toString(); + } + + // Return a list of the distinct prime factors of 'number'. + private static List distinctPrimeFactors(int number) { + List primeFactors = new ArrayList(); + for ( int divisor = 2; divisor * divisor <= number; divisor++ ) { + if ( number % divisor == 0 ) { + primeFactors.add(divisor); + } + while ( number % divisor == 0 ) { + number = number / divisor; + } + } + + if ( number > 1 ) { + primeFactors.add(number); + } + + return primeFactors; + } + + private static final int PRIME_CERTAINTY = 15; + +} diff --git a/Task/Cyclotomic-polynomial/Wren/cyclotomic-polynomial.wren b/Task/Cyclotomic-polynomial/Wren/cyclotomic-polynomial-1.wren similarity index 100% rename from Task/Cyclotomic-polynomial/Wren/cyclotomic-polynomial.wren rename to Task/Cyclotomic-polynomial/Wren/cyclotomic-polynomial-1.wren diff --git a/Task/Cyclotomic-polynomial/Wren/cyclotomic-polynomial-2.wren b/Task/Cyclotomic-polynomial/Wren/cyclotomic-polynomial-2.wren new file mode 100644 index 0000000000..066a1c51c6 --- /dev/null +++ b/Task/Cyclotomic-polynomial/Wren/cyclotomic-polynomial-2.wren @@ -0,0 +1,67 @@ +import "./math" for Int +import "./fmt" for Fmt + +class CP { + // Return the Cyclotomic Polynomial of order 'cpIndex' as a list of coefficients, + // where, for example, the polynomial 3x^2 - 1 is represented by the list [3, 0, -1]. + static cycloPoly(cpIndex) { + var polynomial = [1, -1] + if (cpIndex == 1) return polynomial + if (Int.isPrime(cpIndex)) return List.filled(cpIndex, 1) + var primes = Int.distinctPrimeFactors(cpIndex) + var product = 1 + for (prime in primes) { + var numerator = substituteExponent(polynomial, prime) + polynomial = exactDivision(numerator, polynomial) + product = product * prime + } + return substituteExponent(polynomial, Int.quo(cpIndex, product)) + } + + // Return the Cyclotomic Polynomial obtained from 'polynomial' + // by replacing x with x^'exponent'. + static substituteExponent(polynomial, exponent) { + var result = List.filled(exponent * (polynomial.count - 1) + 1, 0) + for (i in polynomial.count-1..0) result[i*exponent] = polynomial[i] + return result + } + + // Return the Cyclotomic Polynomial equal to 'dividend' / 'divisor'. + // The division is always exact. + static exactDivision(dividend, divisor) { + var result = dividend.toList + for (i in 0..dividend.count - divisor.count) { + if (result[i] != 0) { + for (j in 1...divisor.count) { + result[i+j] = result[i+j] - divisor[j] * result[i] + } + } + } + return result[0..result.count - divisor.count] + } + + // Return whether 'polynomial' has a coefficient of equal magnitude + // to 'coefficient'. + static hasHeight(polynomial, coefficient) { + for (i in 0..Int.quo(polynomial.count + 1, 2)) { + if (polynomial[i].abs == coefficient) return true + } + return false + } +} + +System.print("Task 1: Cyclotomic polynomials for n <= 30:") +for (cpIndex in 1..30) { + Fmt.write("CP[$2d] = ", cpIndex) + Fmt.pprint("$d", CP.cycloPoly(cpIndex), "", "x") +} + +System.print("\nTask 2: Smallest cyclotomic polynomial with n or -n as a coefficient:") +System.print("CP[ 1] has a coefficient with magnitude 1") +var cpIndex = 2 +for (coeff in 2..10) { + while (Int.isPrime(cpIndex) || !CP.hasHeight(CP.cycloPoly(cpIndex), coeff)) { + cpIndex = cpIndex + 1 + } + Fmt.print("CP[$5d] has a coefficient with magnitude $d", cpIndex, coeff) +} diff --git a/Task/Damm-algorithm/EasyLang/damm-algorithm.easy b/Task/Damm-algorithm/EasyLang/damm-algorithm.easy new file mode 100644 index 0000000000..ab2892e5b4 --- /dev/null +++ b/Task/Damm-algorithm/EasyLang/damm-algorithm.easy @@ -0,0 +1,17 @@ +func damm inp$ . + table[][] = [ [ 0 3 1 7 5 9 8 6 4 2 ] [ 7 0 9 2 1 5 4 8 6 3 ] [ 4 2 0 6 8 7 1 3 5 9 ] [ 1 7 5 0 9 8 3 4 2 6 ] [ 6 1 2 3 0 4 5 9 7 8 ] [ 3 6 7 4 2 0 9 5 8 1 ] [ 5 8 6 9 7 2 0 1 3 4 ] [ 8 9 4 5 3 6 2 0 1 7 ] [ 9 4 3 8 6 1 7 2 0 5 ] [ 2 5 8 1 4 3 6 7 9 0 ] ] + inp[] = number strchars inp$ + for v in inp[] + inter = table[inter + 1][v + 1] + . + return if inter = 0 +. +nums[] = [ 5724 5727 112946 112949 ] +for v in nums[] + write v & " is " + if damm v = 1 + print "valid" + else + print "invalid" + . +. diff --git a/Task/Damm-algorithm/MATLAB/damm-algorithm.m b/Task/Damm-algorithm/MATLAB/damm-algorithm.m new file mode 100644 index 0000000000..8835fef6a1 --- /dev/null +++ b/Task/Damm-algorithm/MATLAB/damm-algorithm.m @@ -0,0 +1,34 @@ +clear all;close all;clc; + +% Test the function with the provided numbers +numbers = [5724, 5727, 112946]; +for i = 1:length(numbers) + if checkdigit(numbers(i)) + fprintf('%d validates as: true\n', numbers(i)); + else + fprintf('%d validates as: false\n', numbers(i)); + end +end + +function isValid = checkdigit(n) + matrix = [ + 0, 3, 1, 7, 5, 9, 8, 6, 4, 2; + 7, 0, 9, 2, 1, 5, 4, 8, 6, 3; + 4, 2, 0, 6, 8, 7, 1, 3, 5, 9; + 1, 7, 5, 0, 9, 8, 3, 4, 2, 6; + 6, 1, 2, 3, 0, 4, 5, 9, 7, 8; + 3, 6, 7, 4, 2, 0, 9, 5, 8, 1; + 5, 8, 6, 9, 7, 2, 0, 1, 3, 4; + 8, 9, 4, 5, 3, 6, 2, 0, 1, 7; + 9, 4, 3, 8, 6, 1, 7, 2, 0, 5; + 2, 5, 8, 1, 4, 3, 6, 7, 9, 0 + ]; + + row = 0; + nString = num2str(n); + for i = 1:length(nString) + d = str2double(nString(i)); + row = matrix(row+1, d + 1); + end + isValid = (row == 0); +end diff --git a/Task/Damm-algorithm/REXX/damm-algorithm-2.rexx b/Task/Damm-algorithm/REXX/damm-algorithm-2.rexx index 9d5732664a..1613a51c5f 100644 --- a/Task/Damm-algorithm/REXX/damm-algorithm-2.rexx +++ b/Task/Damm-algorithm/REXX/damm-algorithm-2.rexx @@ -1,12 +1,25 @@ -/*REXX pgm uses H. Michael Damm's algorithm to validate numbers with suffixed check sum.*/ - @.0= 0317598642; @.1= 7092154863; @.2= 4206871359; @.3= 1750983426; @.4= 6123045978 - @.5= 3674209581; @.6= 5869720134; @.7= 8945362017; @.8= 9438617205; @.9= 2581436790 -call Damm 5724, 5727, 112946, 112940 /*invoke Damm's algorithm for some #'s.*/ -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Damm: do j=1 for arg(); x= arg(j); $= 0; z= right(x, 1) - do p=1 for length(x); g=$; $= substr(@.$, 1 + substr(x, p, 1), 1) - end /*p*/ - if $==0 then say ' valid checksum digit ' z " for " x - else say ' invalid checksum digit ' z " for " x ' (should be' g")" - end /*j*/; return +/*REXX pgm uses H. Michael Damm's algorithm to validate numbers with suffixed check sum. digit*/ + a.0= 0317598642; a.1= 7092154863; a.2= 4206871359; a.3= 1750983426; a.4= 6123045978 + a.5= 3674209581; a.6= 5869720134; a.7= 8945362017; a.8= 9438617205; a.9= 2581436790 +Call Damm 5724, 5727, 112946, 112940 /*invoke Damm's algorithm To some #'s.*/ +Exit /*stick a Tok in it, we're all Done. */ +/*---------------------------------------------------------------------------------*/ +Damm: + Do j=1 To arg() /* loop over numbers */ + x=arg(j) + d=0 + Do p=1 To length(x)-1 /* compute the checksum digit */ + d=substr(a.d,substr(x,p,1)+1,1) + end /*p*/ + z=right(x,1) /* the given digit */ + If z=d Then Say ' valid checksum digit ' z " for " x + Else Say ' invalid checksum digit ' z " for " x ' (should be' d")" + End /*j*/ + Return /syntaxhighlight> +{{out|output|text=  when using the (internal) default inputs:}} +
+   valid checksum digit  4  for  5724
+ invalid checksum digit  7  for  5727    (should be 4)
+   valid checksum digit  6  for  112946
+ invalid checksum digit  0  for  112940    (should be 6)
+
diff --git a/Task/Damm-algorithm/Tcl/damm-algorithm.tcl b/Task/Damm-algorithm/Tcl/damm-algorithm.tcl new file mode 100644 index 0000000000..17e54e7f8c --- /dev/null +++ b/Task/Damm-algorithm/Tcl/damm-algorithm.tcl @@ -0,0 +1,26 @@ +proc damm {number} { + set digits [split $number ""] + set tbl { + {0 3 1 7 5 9 8 6 4 2} + {7 0 9 2 1 5 4 8 6 3} + {4 2 0 6 8 7 1 3 5 9} + {1 7 5 0 9 8 3 4 2 6} + {6 1 2 3 0 4 5 9 7 8} + {3 6 7 4 2 0 9 5 8 1} + {5 8 6 9 7 2 0 1 3 4} + {8 9 4 5 3 6 2 0 1 7} + {9 4 3 8 6 1 7 2 0 5} + {2 5 8 1 4 3 6 7 9 0} + } + + set row 0 + foreach col $digits { + set row [lindex $tbl $row $col] + } + return [expr {$row == 0 ? 1 : 0}] +} + +foreach number {5724 5727 112946} { + set correct [damm $number] + puts "$number:\tChecksum digit [expr {$correct ? "" : "in"}]correct." +} diff --git a/Task/Date-format/MiniScript/date-format.mini b/Task/Date-format/MiniScript/date-format.mini new file mode 100644 index 0000000000..f674cbca74 --- /dev/null +++ b/Task/Date-format/MiniScript/date-format.mini @@ -0,0 +1,4 @@ +import "dateTime" + +print dateTime.now("yyyy-MM-dd") +print dateTime.now("dddd, MMMM d, yyyy") diff --git a/Task/Date-manipulation/MiniScript/date-manipulation.mini b/Task/Date-manipulation/MiniScript/date-manipulation.mini new file mode 100644 index 0000000000..666ec85b51 --- /dev/null +++ b/Task/Date-manipulation/MiniScript/date-manipulation.mini @@ -0,0 +1,34 @@ +import "dateTime" +import "stringUtil" + +months = [ + "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December", +] + +date = "March 7 2009 7:30pm EST" +print "Original date/time : " + date + +// change the date to standard format +items = date.split +month = months.indexOf(items[0]) + 1 +day = items[1] +year = items[2] +time = items[3] +hour = time.split(":")[0].val +minute = time.split(":")[1][0:2] +pm = time.endsWith("pm") +if pm then hour = hour + 12 +time = hour + ":" + minute +zone = items[4] +date = year + "-" + month + "-" + day + " " + time + +// add 12 hours and display in original format +dval = dateTime.val(date) + 12*60*60 +dfmt = "MMMM d yyyy h:mmtt" +date2 = dateTime.str(dval, dfmt) + " " + zone +print "12 hours later : " + date2 + +// change from EST to MST (2 hours earlier) +date3 = dateTime.str(dval - 2*60*60, dfmt) + " MST" +print "Adjusted to MST : " + date3 diff --git a/Task/Day-of-the-week/MiniScript/day-of-the-week.mini b/Task/Day-of-the-week/MiniScript/day-of-the-week.mini new file mode 100644 index 0000000000..63cb0a0dab --- /dev/null +++ b/Task/Day-of-the-week/MiniScript/day-of-the-week.mini @@ -0,0 +1,9 @@ +import "dateTime" + +print "Years between 2008 and 2121 when 25th December falls on Sunday:" +years = [] +for year in range(2008, 2121) + date = year + "-12-25" + if dateTime.weekday(date) == 0 then years.push year +end for +print years.join(", ") diff --git a/Task/De-Bruijn-sequences/EasyLang/de-bruijn-sequences.easy b/Task/De-Bruijn-sequences/EasyLang/de-bruijn-sequences.easy new file mode 100644 index 0000000000..bd9029b38e --- /dev/null +++ b/Task/De-Bruijn-sequences/EasyLang/de-bruijn-sequences.easy @@ -0,0 +1,89 @@ +global a[] seq[] k n . +proc db t p . . + if t > n + if n mod p = 0 + for i = 1 to p + seq[] &= a[i + 1] + . + . + else + a[t + 1] = a[t - p + 1] + db t + 1 p + j = a[t - p + 1] + 1 + while j < k + a[t + 1] = j mod 256 + db t + 1 t + j += 1 + . + . +. +func$ debruijn k0 n0 . + k = k0 + n = n0 + a[] = [ ] + len a[] k * n + seq[] = [ ] + db 1 1 + for v in seq[] + buf$ &= v + . + buf$ &= substr buf$ 1 (n - 1) + return buf$ +. +func alldigits s$ . + for c$ in strchars s$ + if strcode c$ < 48 or strcode c$ > 57 + return 0 + . + . + return 1 +. +proc validate db$ . . + len found[] 10000 + for i = 1 to len db$ - 3 + s$ = substr db$ i 4 + if alldigits s$ = 1 + n = number s$ + found[n + 1] += 1 + . + . + for i = 1 to 10000 + if found[i] = 0 + errs$[] &= " PIN number " & i - 1 & " missing" + elif found[i] > 1 + errs$[] &= " PIN number " & i - 1 & " occurs " & found[i] & " times" + . + . + if len errs$[] = 0 + print " No errors found" + else + for s$ in errs$[] + print s$ + . + . +. +proc main . . + db$ = debruijn 10 4 + print "The length of the de Bruijn sequence is " & len db$ + print "" + write "The first 130 digits of the de Bruijn sequence are: " + print substr db$ 1 130 + print "" + write "The last 130 digits of the de Bruijn sequence are: " + print substr db$ -130 130 + print "" + print "Validating the de Bruijn sequence:" + validate db$ + print "" + print "Validating the reversed de Bruijn sequence:" + for i = len db$ downto 1 + dbr$ &= substr db$ i 1 + . + validate dbr$ + print "" + db$ = substr db$ 1 4443 & "." & substr db$ 4445 (1 / 0) + print "Validating the overlaid de Bruijn sequence:" + validate db$ + print "" +. +main diff --git a/Task/De-Bruijn-sequences/Scala/de-bruijn-sequences.scala b/Task/De-Bruijn-sequences/Scala/de-bruijn-sequences.scala new file mode 100644 index 0000000000..0de0703279 --- /dev/null +++ b/Task/De-Bruijn-sequences/Scala/de-bruijn-sequences.scala @@ -0,0 +1,77 @@ +import scala.collection.mutable.ListBuffer + +object DeBruijn { + + def deBruijn(k: Int, n: Int): String = { + val a = Array.fill[Byte](k * n)(0) + val seq = new ListBuffer[Byte]() + + def db(t: Int, p: Int): Unit = { + if (t > n) { + if (n % p == 0) { + seq ++= a.slice(1, p + 1) + } + } else { + a(t) = a(t - p) + db(t + 1, p) + for (j <- (a(t - p) + 1).until(k)) { + a(t) = j.toByte + db(t + 1, t) + } + } + } + + db(1, 1) + + val sb = new StringBuilder + seq.foreach(i => sb.append("0123456789".charAt(i))) + sb.append(sb.subSequence(0, n - 1)).toString + } + + private def allDigits(s: String): Boolean = s.forall(_.isDigit) + + private def validate(db: String): Unit = { + val found = Array.fill(10000)(0) + val errs = ListBuffer[String]() + + for (i <- 0 until db.length - 3) { + val s = db.substring(i, i + 4) + if (allDigits(s)) { + val n = s.toInt + found(n) += 1 + } + } + + for (i <- found.indices) { + if (found(i) == 0) errs += s" PIN number $i is missing" + else if (found(i) > 1) errs += s" PIN number $i occurs ${found(i)} times" + } + + if (errs.isEmpty) println(" No errors found") + else { + val pl = if (errs.size == 1) "" else "s" + println(s" ${errs.size} error$pl found:") + errs.foreach(println) + } + } + + def main(args: Array[String]): Unit = { + val db = deBruijn(10, 4) + + println(s"The length of the de Bruijn sequence is ${db.length}\n") + println(s"The first 130 digits of the de Bruijn sequence are: ${db.take(130)}\n") + println(s"The last 130 digits of the de Bruijn sequence are: ${db.takeRight(130)}\n") + + println("Validating the de Bruijn sequence:") + validate(db) + + println() + println("Validating the reversed de Bruijn sequence:") + validate(db.reverse) + + val overlaidDb = db.updated(4443, '.') + println() + println("Validating the overlaid de Bruijn sequence:") + validate(overlaidDb) + } +} diff --git a/Task/Death-Star/ALGOL-68/death-star.alg b/Task/Death-Star/ALGOL-68/death-star.alg new file mode 100644 index 0000000000..a7b6af136b --- /dev/null +++ b/Task/Death-Star/ALGOL-68/death-star.alg @@ -0,0 +1,86 @@ +BEGIN # draw a "Death Star" - translated from the C and 11l samples # + STRING shades = ".:!*oe&#%@"; + + PROC normalize = ( []REAL v )[]REAL: + BEGIN + REAL len = sqrt( v[ 1 ] * v[ 1 ] + v[ 2 ] * v[ 2 ] + v[ 3 ] * v[ 3 ] ); + ( v[ 1 ] / len, v[ 2 ] / len, v[ 3 ] / len ) + END # normalize # ; + + PROC dot = ( []REAL x, y )REAL: + BEGIN + REAL d = x[ 1 ] * y[ 1 ] + x[ 2 ] * y[ 2 ] + x[ 3 ] * y[ 3 ]; + IF d < 0 THEN - d ELSE 0 FI + END # dot # ; + + MODE SPHERE = STRUCT( REAL cx, cy, cz, r ); + + # positive shpere and negative sphere # + SPHERE pos = ( 20, 20, 0, 20 ), neg = ( 1, 1, -6, 20 ); + + # check if a ray (x,y, -inf)->(x, y, inf) hits a sphere; if so, return # + # the intersecting z values. z1 is closer to the eye # + PROC hit_sphere = ( SPHERE sph, REAL x in, y in, REF REAL z1, z2 )BOOL: + IF REAL x = x in - cx OF sph; + REAL y = y in - cy OF sph; + REAL zsq := r OF sph * r OF sph - ( x * x + y * y ); + zsq < 0 + THEN FALSE + ELSE zsq := sqrt( zsq ); + z1 := cz OF sph - zsq; + z2 := cz OF sph + zsq; + TRUE + FI # hit_sphere # ; + + PROC draw_sphere = ( REAL k, ambient, []REAL light )VOID: + FOR i FROM ENTIER ( cy OF pos - r OF pos ) TO ENTIER ( cy OF pos + r OF pos ) + 1 DO + REAL y := i + 0.5; + FOR j FROM ENTIER ( cx OF pos - 2 * r OF pos ) TO ENTIER (cx OF pos + 2 * r OF pos ) + 1 DO + REAL x := ( j - cx OF pos ) / 2.0 + 0.5 + cx OF pos; + REAL zb1 := 0, zb2 := 0, zs1 := 0, zs2 := 0; + INT hit_result + = IF NOT hit_sphere( pos, x, y, zb1, zb2 ) THEN + 0 # ray lands in blank space, draw bg # + ELIF NOT hit_sphere( neg, x, y, zs1, zs2 ) THEN + 1 # ray hits pos sphere but not neg, draw pos sphere surface # + ELIF zs1 > zb1 THEN + 1 # ray hits both, but pos front surface is closer # + ELIF zs2 > zb2 THEN + 0 # pos sphere surface is inside neg sphere, show bg # + ELIF zs2 > zb1 THEN + 2 # back surface on neg sphere is inside pos sphere, # + # the only place where neg sphere surface will be shown # + ELSE + 1 # show the pos sphere # + FI; + IF hit_result = 0 THEN + print( ( " " ) ) + ELSE + []REAL vec = + normalize( IF hit_result = 1 + THEN []REAL( x - cx OF pos + , y - cy OF pos + , zb1 - cz OF pos + ) + ELSE []REAL( cx OF neg - x + , cy OF neg - y + , cz OF neg - zs2 + ) + FI + ); + REAL b = ( dot( light, vec ) ^ k ) + ambient; + INT intensity := ENTIER ( ( 1 - b ) * ( ( UPB shades - LWB shades ) + 1 ) ) + 1; + IF intensity < LWB shades THEN intensity := LWB shades + ELIF intensity > UPB shades THEN intensity := UPB shades + FI; + print( ( shades[ intensity ] ) ) + FI + OD; + print( ( newline ) ) + OD # draw_sphere # ; + + BEGIN + []REAL light = ( -50, 30, 50 ); + draw_sphere( 2, 0.5, normalize( light ) ) + END +END diff --git a/Task/Death-Star/Zig/death-star-5.zig b/Task/Death-Star/Zig/death-star-5.zig index af3ddd2aec..97e28f0ac7 100644 --- a/Task/Death-Star/Zig/death-star-5.zig +++ b/Task/Death-Star/Zig/death-star-5.zig @@ -14,9 +14,9 @@ fn Sphere(comptime T: type) type { pub fn hit(self: *const Self, xx: T, yy: T) ?SphereHit(T) { const x = xx - self.cx; const y = yy - self.cy; - var zsq = self.r * self.r - x * x - y * y; + const zsq = self.r * self.r - x * x - y * y; if (zsq >= 0) { - var zsqrt = std.math.sqrt(zsq); + const zsqrt = std.math.sqrt(zsq); return .{ .z1 = self.cz - zsqrt, .z2 = self.cz + zsqrt }; } return null; diff --git a/Task/Death-Star/Zig/death-star-6.zig b/Task/Death-Star/Zig/death-star-6.zig index 4ffc6b3a12..0d5fe2337a 100644 --- a/Task/Death-Star/Zig/death-star-6.zig +++ b/Task/Death-Star/Zig/death-star-6.zig @@ -18,8 +18,8 @@ fn DeathStar(comptime T: type) type { const k: T = 1.5; const amb: T = 0.2; - var w: usize = @intFromFloat(pos.r * 4); - var h: usize = @intFromFloat(pos.r * 3); + const w: usize = @intFromFloat(pos.r * 4); + const h: usize = @intFromFloat(pos.r * 3); var img = try ImageData().init(allocator, "deathStar", w, h); var vec = Vector(T).zero(); diff --git a/Task/Deceptive-numbers/EasyLang/deceptive-numbers.easy b/Task/Deceptive-numbers/EasyLang/deceptive-numbers.easy new file mode 100644 index 0000000000..6cbd386682 --- /dev/null +++ b/Task/Deceptive-numbers/EasyLang/deceptive-numbers.easy @@ -0,0 +1,31 @@ +func modpow b e m . + r = 1 + while e > 0 + if e mod 2 = 1 + r = r * b mod m + . + b = b * b mod m + e = e div 2 + . + return r +. +func is_deceptive n . + if n mod 2 = 1 and n mod 3 <> 0 and n mod 5 <> 0 + if modpow 10 (n - 1) n = 1 + x = 7 + while x * x <= n + if n mod x = 0 or n mod (x + 4) = 0 + return 1 + . + x += 6 + . + . + . +. +while cnt < 10 + n += 1 + if is_deceptive n = 1 + write n & " " + cnt += 1 + . +. diff --git a/Task/Deceptive-numbers/FreeBASIC/deceptive-numbers.basic b/Task/Deceptive-numbers/FreeBASIC/deceptive-numbers.basic new file mode 100644 index 0000000000..c94a8eb4bc --- /dev/null +++ b/Task/Deceptive-numbers/FreeBASIC/deceptive-numbers.basic @@ -0,0 +1,33 @@ +Function ModPow(b As Uinteger, e As Uinteger, m As Uinteger) As Uinteger + Dim As Uinteger p = 1 + While e <> 0 + If (e And 1) Then p = (p*b) Mod m + b = (b*b) Mod m + e Shr= 1 + Wend + Return p +End Function + +Function isDeceptive(n As Uinteger) As Uinteger + Dim As Uinteger x + If (n And 1) <> 0 Andalso (n Mod 3) <> 0 Andalso (n Mod 5) <> 0 Then + x = 7 + While x*x <= n + If (n Mod x) = 0 Orelse (n Mod (x+4)) = 0 Then Return (ModPow(10, n-1, n) = 1) + x += 6 + Wend + End If + Return 0 +End Function + +Dim As Uinteger c = 0, i = 49 +While c <> 41 ' limit for signed 32-bit integers + If isDeceptive(i) Then + Print Using "#######"; Csng(i); + c += 1 + If (c Mod 10) = 0 Then Print + End If + i += 1 +Wend + +Sleep diff --git a/Task/Deceptive-numbers/Langur/deceptive-numbers.langur b/Task/Deceptive-numbers/Langur/deceptive-numbers.langur index 370672e433..991a1a816e 100644 --- a/Task/Deceptive-numbers/Langur/deceptive-numbers.langur +++ b/Task/Deceptive-numbers/Langur/deceptive-numbers.langur @@ -1,4 +1,5 @@ -val .isPrime = f .i == 2 or .i > 2 and not any f(.x) .i div .x, pseries 2 .. .i ^/ 2 +val .isPrime = f .i == 2 or .i > 2 and + not any f(.x) .i div .x, pseries 2 .. .i ^/ 2 var .nums = [] var .repunit = 111_111 diff --git a/Task/Delegates/Elena/delegates-1.elena b/Task/Delegates/Elena/delegates-1.elena index 9a199cacc3..cc9cc7e4fb 100644 --- a/Task/Delegates/Elena/delegates-1.elena +++ b/Task/Delegates/Elena/delegates-1.elena @@ -37,7 +37,7 @@ public program() { var delegator := new Delegator(); - new object[]{nil, new Object(), new Operable()}.forEach:(o) + new object[]{nil, new Object(), new Operable()}.forEach::(o) { delegator.Delegate := o; diff --git a/Task/Delegates/Elena/delegates-2.elena b/Task/Delegates/Elena/delegates-2.elena index e0d8d55955..bc014bde4e 100644 --- a/Task/Delegates/Elena/delegates-2.elena +++ b/Task/Delegates/Elena/delegates-2.elena @@ -21,7 +21,7 @@ class Delegator operate() { // if the object does not support "Operable" message - returns nil - var operable := Delegate.Operable \ back:nil; + var operable := Delegate.Operable \ back(nil); if (nil == operable) { @@ -38,7 +38,7 @@ public program() { var delegator := new Delegator(); - new object[]{nil, new Object(), new Operable()}.forEach:(o) + new object[]{nil, new Object(), new Operable()}.forEach::(o) { delegator.Delegate := o; diff --git a/Task/Demings-funnel/C-sharp/demings-funnel.cs b/Task/Demings-funnel/C-sharp/demings-funnel.cs new file mode 100644 index 0000000000..4221d07f55 --- /dev/null +++ b/Task/Demings-funnel/C-sharp/demings-funnel.cs @@ -0,0 +1,78 @@ +using System; +using System.Linq; + +public class DemingsFunnel +{ + public static void Main(string[] args) + { + double[] dxs = { + -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, + 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, + -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, + 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, + -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, + -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, + 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, + -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, + 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, + -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, + 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, + 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, + 0.443, -0.521, -0.799, 0.087}; + + double[] dys = { + 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, + 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, + 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, + 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, + -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, + 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, + 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, + 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, + -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, + 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, + -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, + 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, + -0.947, -1.424, -0.542, -1.032}; + + Experiment("Rule 1:", dxs, dys, (z, dz) => 0.0); + Experiment("Rule 2:", dxs, dys, (z, dz) => -dz); + Experiment("Rule 3:", dxs, dys, (z, dz) => -(z + dz)); + Experiment("Rule 4:", dxs, dys, (z, dz) => z + dz); + } + + static void Experiment(string label, double[] dxs, double[] dys, Func rule) + { + double[] resx = Funnel(dxs, rule); + double[] resy = Funnel(dys, rule); + Console.WriteLine(label); + Console.WriteLine($"Mean x, y: {Mean(resx):F4}, {Mean(resy):F4}"); + Console.WriteLine($"Std dev x, y: {StdDev(resx):F4}, {StdDev(resy):F4}"); + Console.WriteLine(); + } + + static double[] Funnel(double[] input, Func rule) + { + double x = 0; + double[] result = new double[input.Length]; + + for (int i = 0; i < input.Length; i++) + { + double rx = x + input[i]; + x = rule(x, input[i]); + result[i] = rx; + } + return result; + } + + static double Mean(double[] xs) + { + return xs.Average(); + } + + static double StdDev(double[] xs) + { + double m = Mean(xs); + return Math.Sqrt(xs.Select(x => Math.Pow((x - m), 2)).Sum() / xs.Length); + } +} diff --git a/Task/Demings-funnel/EasyLang/demings-funnel.easy b/Task/Demings-funnel/EasyLang/demings-funnel.easy new file mode 100644 index 0000000000..7e7b7aed7a --- /dev/null +++ b/Task/Demings-funnel/EasyLang/demings-funnel.easy @@ -0,0 +1,50 @@ +dxs[] = [ -0.533 0.27 0.859 -0.043 -0.205 -0.127 -0.071 0.275 1.251 -0.231 -0.401 0.269 0.491 0.951 1.15 0.001 -0.382 0.161 0.915 2.08 -2.337 0.034 -0.126 0.014 0.709 0.129 -1.093 -0.483 -1.193 0.02 -0.051 0.047 -0.095 0.695 0.34 -0.182 0.287 0.213 -0.423 -0.021 -0.134 1.798 0.021 -1.099 -0.361 1.636 -1.134 1.315 0.201 0.034 0.097 -0.17 0.054 -0.553 -0.024 -0.181 -0.7 -0.361 -0.789 0.279 -0.174 -0.009 -0.323 -0.658 0.348 -0.528 0.881 0.021 -0.853 0.157 0.648 1.774 -1.043 0.051 0.021 0.247 -0.31 0.171 0.0 0.106 0.024 -0.386 0.962 0.765 -0.125 -0.289 0.521 0.017 0.281 -0.749 -0.149 -2.436 -0.909 0.394 -0.113 -0.598 0.443 -0.521 -0.799 0.087 ] +# +dys[] = [ 0.136 0.717 0.459 -0.225 1.392 0.385 0.121 -0.395 0.49 -0.682 -0.065 0.242 -0.288 0.658 0.459 0.0 0.426 0.205 -0.765 -2.188 -0.742 -0.01 0.089 0.208 0.585 0.633 -0.444 -0.351 -1.087 0.199 0.701 0.096 -0.025 -0.868 1.051 0.157 0.216 0.162 0.249 -0.007 0.009 0.508 -0.79 0.723 0.881 -0.508 0.393 -0.226 0.71 0.038 -0.217 0.831 0.48 0.407 0.447 -0.295 1.126 0.38 0.549 -0.445 -0.046 0.428 -0.074 0.217 -0.822 0.491 1.347 -0.141 1.23 -0.044 0.079 0.219 0.698 0.275 0.056 0.031 0.421 0.064 0.721 0.104 -0.729 0.65 -1.103 0.154 -1.72 0.051 -0.385 0.477 1.537 -0.901 0.939 -0.411 0.341 -0.411 0.106 0.224 -0.947 -1.424 -0.542 -1.032 ] +# +proc funnel rule . dxs[] rxs[] . + rxs[] = [ ] + for dx in dxs[] + rxs[] &= x + dx + if rule = 1 + x = 0 + elif rule = 2 + x = -dx + elif rule = 3 + x = -(x + dx) + else + x = x + dx + . + . +. +proc mean . xs[] r . + r = 0 + for x in xs[] + r += x + . + r /= len xs[] +. +proc stddev . xs[] r . + mean xs[] m + for x in xs[] + s += (x - m) * (x - m) + . + r = sqrt (s / len xs[]) +. +proc experiment rule . . + funnel rule dxs[] rxs[] + funnel rule dys[] rys[] + print "Rule " & rule + mean rxs[] mx + mean rys[] my + print "Mean x, y : " & mx & " " & my + stddev rxs[] dx + stddev rys[] dy + print "Std dev x, y : " & dx & " " & dy + print "" +. +numfmt 4 0 +experiment 1 +experiment 2 +experiment 3 +experiment 4 diff --git a/Task/Demings-funnel/Scala/demings-funnel.scala b/Task/Demings-funnel/Scala/demings-funnel.scala new file mode 100644 index 0000000000..040c1621ad --- /dev/null +++ b/Task/Demings-funnel/Scala/demings-funnel.scala @@ -0,0 +1,69 @@ +object DemingsFunnel { + + def main(args: Array[String]): Unit = { + val dxs = Array( + -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275, + 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, + -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014, + 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, + -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021, + -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, + 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, + -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658, + 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, + -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, + 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017, + 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, + 0.443, -0.521, -0.799, 0.087 + ) + + val dys = Array( + 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, + 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, + 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208, + 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, + -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007, + 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, + 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, + 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217, + -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, + 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104, + -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, + 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224, + -0.947, -1.424, -0.542, -1.032 + ) + + experiment("Rule 1:", dxs, dys, (z, dz) => 0.0) + experiment("Rule 2:", dxs, dys, (z, dz) => -dz) + experiment("Rule 3:", dxs, dys, (z, dz) => -(z + dz)) + experiment("Rule 4:", dxs, dys, (z, dz) => z + dz) + } + + def experiment(label: String, dxs: Array[Double], dys: Array[Double], rule: (Double, Double) => Double): Unit = { + val resx = funnel(dxs, rule) + val resy = funnel(dys, rule) + println(label) + printf("Mean x, y: %.4f, %.4f%n", mean(resx), mean(resy)) + printf("Std dev x, y: %.4f, %.4f%n", stdDev(resx), stdDev(resy)) + println() + } + + def funnel(input: Array[Double], rule: (Double, Double) => Double): Array[Double] = { + var x = 0.0 + val result = new Array[Double](input.length) + + for (i <- input.indices) { + val rx = x + input(i) + x = rule(x, input(i)) + result(i) = rx + } + result + } + + def mean(xs: Array[Double]): Double = xs.sum / xs.length + + def stdDev(xs: Array[Double]): Double = { + val m = mean(xs) + math.sqrt(xs.map(x => math.pow((x - m), 2)).sum / xs.length) + } +} diff --git a/Task/Department-numbers/MATLAB/department-numbers.m b/Task/Department-numbers/MATLAB/department-numbers.m new file mode 100644 index 0000000000..c27b0069e7 --- /dev/null +++ b/Task/Department-numbers/MATLAB/department-numbers.m @@ -0,0 +1,18 @@ +% Execute the functions +clear all;close all;clc; +sol = findsolution(); +disp(table(sol(:, 1), sol(:, 2), sol(:, 3), 'VariableNames',{'Pol.','Fire','San.'})) + +function sol = findsolution() + rng = 1:7; + sol = []; + for p = rng + for f = rng + for s = rng + if p ~= s && s ~= f && f ~= p && p + s + f == 12 && mod(p, 2) == 0 + sol = [sol; p s f]; + end + end + end + end +end diff --git a/Task/Department-numbers/MiniScript/department-numbers.mini b/Task/Department-numbers/MiniScript/department-numbers.mini new file mode 100644 index 0000000000..b26bd9a2c1 --- /dev/null +++ b/Task/Department-numbers/MiniScript/department-numbers.mini @@ -0,0 +1,17 @@ +print "Police Sanitation Fire" +print "------ ---------- ----" +count = 0 +for h in range(1, 3) + i = h * 2 + for j in range(1, 7) + if j != i then + for k in range(1, 7) + if k != i and k != j and i + j + k == 12 then + print " " + i + " " + j + " " + k + count += 1 + end if + end for + end if + end for +end for +print char(10) + count + " valid combinations" diff --git a/Task/Detect-division-by-zero/MiniScript/detect-division-by-zero.mini b/Task/Detect-division-by-zero/MiniScript/detect-division-by-zero.mini new file mode 100644 index 0000000000..880af1c420 --- /dev/null +++ b/Task/Detect-division-by-zero/MiniScript/detect-division-by-zero.mini @@ -0,0 +1,25 @@ +number.isInfinite = function + return abs(self) == 1/0 +end function + +number.isNaN = function + return self != self +end function + +number.toBoolStr = function + if self == 0 then return "false" + return "true" +end function + +checkDivByZero = function(a, b) + c = a / b + if c.isInfinite or c.isNaN then return true + return false +end function + +print "Division by zero?" +print " 0 / 0 -> " + checkDivByZero( 0, 0).toBoolStr +print " 1 / 0 -> " + checkDivByZero( 1, 0).toBoolStr +print " 1 / 1 -> " + checkDivByZero( 1, 1).toBoolStr +print " -5 / 0 -> " + checkDivByZero(-5, 0).toBoolStr +print " -5 / 2 -> " + checkDivByZero(-5, 2).toBoolStr diff --git a/Task/Determinant-and-permanent/C-sharp/determinant-and-permanent.cs b/Task/Determinant-and-permanent/C-sharp/determinant-and-permanent.cs new file mode 100644 index 0000000000..4aed405499 --- /dev/null +++ b/Task/Determinant-and-permanent/C-sharp/determinant-and-permanent.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; // This is required for LINQ extension methods + +class Program +{ + static IEnumerable> GetPermutations(IEnumerable list, int length) + { + if (length == 1) return list.Select(t => new int[] { t }); + + return GetPermutations(list, length - 1) + .SelectMany(t => list.Where(e => !t.Contains(e)), + (t1, t2) => t1.Concat(new int[] { t2 })); + } + + static double Determinant(double[][] m) + { + double d = 0; + var p = new List(); + for (int i = 0; i < m.Length; i++) + { + p.Add(i); + } + + var permutations = GetPermutations(p, p.Count); + foreach (var perm in permutations) + { + double pr = 1; + int sign = Math.Sign(GetPermutationSign(perm.ToList())); + for (int i = 0; i < perm.Count(); i++) + { + pr *= m[i][perm.ElementAt(i)]; + } + d += sign * pr; + } + + return d; + } + + static int GetPermutationSign(IList perm) + { + int inversions = 0; + for (int i = 0; i < perm.Count; i++) + for (int j = i + 1; j < perm.Count; j++) + if (perm[i] > perm[j]) + inversions++; + return inversions % 2 == 0 ? 1 : -1; + } + + static double Permanent(double[][] m) + { + double d = 0; + var p = new List(); + for (int i = 0; i < m.Length; i++) + { + p.Add(i); + } + + var permutations = GetPermutations(p, p.Count); + foreach (var perm in permutations) + { + double pr = 1; + for (int i = 0; i < perm.Count(); i++) + { + pr *= m[i][perm.ElementAt(i)]; + } + d += pr; + } + + return d; + } + + static void Main(string[] args) + { + double[][] m2 = new double[][] { + new double[] { 1, 2 }, + new double[] { 3, 4 } + }; + + double[][] m3 = new double[][] { + new double[] { 2, 9, 4 }, + new double[] { 7, 5, 3 }, + new double[] { 6, 1, 8 } + }; + + Console.WriteLine($"{Determinant(m2)}, {Permanent(m2)}"); + Console.WriteLine($"{Determinant(m3)}, {Permanent(m3)}"); + } +} diff --git a/Task/Determine-if-a-string-has-all-the-same-characters/Forth/determine-if-a-string-has-all-the-same-characters.fth b/Task/Determine-if-a-string-has-all-the-same-characters/Forth/determine-if-a-string-has-all-the-same-characters.fth new file mode 100644 index 0000000000..3738cdf6ed --- /dev/null +++ b/Task/Determine-if-a-string-has-all-the-same-characters/Forth/determine-if-a-string-has-all-the-same-characters.fth @@ -0,0 +1,18 @@ +: samechars? ( str-addr str-len -- ) + [char] " emit 2dup type [char] " emit ." length: " dup . ." -> " + dup 1 > if + over c@ swap 1 do + over i + c@ over <> if + ." different character '" drop i + c@ dup emit + ." ' ($" hex 1 .r ." ) at " decimal i . cr unloop exit + then + loop + then 2drop ." all characters are the same" cr ; + +s" " samechars? +s" " samechars? +s" 2" samechars? +s" 333" samechars? +s" .55" samechars? +s" tttTTT" samechars? +s" 4444 444k" samechars? diff --git a/Task/Determine-if-a-string-is-collapsible/Refal/determine-if-a-string-is-collapsible.refal b/Task/Determine-if-a-string-is-collapsible/Refal/determine-if-a-string-is-collapsible.refal new file mode 100644 index 0000000000..ae63874d38 --- /dev/null +++ b/Task/Determine-if-a-string-is-collapsible/Refal/determine-if-a-string-is-collapsible.refal @@ -0,0 +1,34 @@ +$ENTRY Go { + , ('') + ('"If I were two-faced, would I be wearing this ' + 'one?" --- Abraham Lincoln ') + ('..11111111111111111111111111111111111111111111' + '11111111111111111117777888') + ('I never give \'em hell, I just tell the truth, ' + 'and they think it\'s hell. ') + (' ' + ' --- Harry S Truman '): e.Strings + = ; +}; + +Each { + s.F = ; + s.F t.I e.X = ; +}; + +Brackets { + e.X, : s.L e.X = + ': <<<' e.X '>>>'>; +}; + +Show { + (e.X) = + > + ; +}; + +Collapse { + = ; + s.C s.C e.S = ; + s.C e.S = s.C ; +}; diff --git a/Task/Dice-game-probabilities/C-sharp/dice-game-probabilities.cs b/Task/Dice-game-probabilities/C-sharp/dice-game-probabilities.cs new file mode 100644 index 0000000000..cb703b9093 --- /dev/null +++ b/Task/Dice-game-probabilities/C-sharp/dice-game-probabilities.cs @@ -0,0 +1,50 @@ +using System; + +class Program +{ + static uint MinOf(uint x, uint y) + { + return x < y ? x : y; + } + + static void ThrowDie(uint nSides, uint nDice, uint s, uint[] counts) + { + if (nDice == 0) + { + counts[s]++; + return; + } + for (uint i = 1; i <= nSides; i++) + { + ThrowDie(nSides, nDice - 1, s + i, counts); + } + } + + static double BeatingProbability(uint nSides1, uint nDice1, uint nSides2, uint nDice2) + { + uint len1 = (nSides1 + 1) * nDice1; + uint[] c1 = new uint[len1]; // initialized to zero by default + ThrowDie(nSides1, nDice1, 0, c1); + + uint len2 = (nSides2 + 1) * nDice2; + uint[] c2 = new uint[len2]; + ThrowDie(nSides2, nDice2, 0, c2); + double p12 = Math.Pow(nSides1, nDice1) * Math.Pow(nSides2, nDice2); + + double tot = 0.0; + for (uint i = 0; i < len1; i++) + { + for (uint j = 0; j < MinOf(i, len2); j++) + { + tot += (double)(c1[i] * c2[j]) / p12; + } + } + return tot; + } + + static void Main(string[] args) + { + Console.WriteLine(BeatingProbability(4, 9, 6, 6)); + Console.WriteLine(BeatingProbability(10, 5, 7, 6)); + } +} diff --git a/Task/Digital-root/Elena/digital-root.elena b/Task/Digital-root/Elena/digital-root.elena index 9e11e87757..60a2b16baf 100644 --- a/Task/Digital-root/Elena/digital-root.elena +++ b/Task/Digital-root/Elena/digital-root.elena @@ -11,7 +11,7 @@ extension op while (num > 9) { - num := num.toPrintable().toArray().selectBy:(ch => ch.toInt() - 48).summarize(new LongInteger()); + num := num.toPrintable().toArray().selectBy::(ch => ch.toInt() - 48).summarize(new LongInteger()); additivepersistence += 1 }; @@ -22,7 +22,7 @@ extension op public program() { - new long[]{627615l, 39390l, 588225l, 393900588225l}.forEach:(num) + new long[]{627615l, 39390l, 588225l, 393900588225l}.forEach::(num) { var t := num.DigitalRoot; diff --git a/Task/Digital-root/Janet/digital-root.janet b/Task/Digital-root/Janet/digital-root.janet new file mode 100644 index 0000000000..befc9037d9 --- /dev/null +++ b/Task/Digital-root/Janet/digital-root.janet @@ -0,0 +1,13 @@ +(defn numbers [s] (filter (fn [y] (and (<= y 9) (>= y 0))) (map (fn [z] (- z 48)) (string/bytes s)))) +(defn summa [s] (reduce (fn [x y] (+ x y)) 0 (numbers s))) +(defn minsumma [x p] + (if (<= x 9) + [x p] + (minsumma (summa (string/format "%d" x)) (+ 1 p)))) +(defn test [t] (printf "%j" (minsumma (summa t) 1))) +(test "627615") +(test "39390") +(test "588225") +(test "393900588225") +(test "19999999999999999999999999999999999999999999999999999999999999999999999999999999999999") +(test "192348-0347203478-20483298402-39482-04720348-20394823-058720375204820-394823842-049802-93482-034892-3") diff --git a/Task/Dijkstras-algorithm/EasyLang/dijkstras-algorithm.easy b/Task/Dijkstras-algorithm/EasyLang/dijkstras-algorithm.easy new file mode 100644 index 0000000000..3b7c6c90d6 --- /dev/null +++ b/Task/Dijkstras-algorithm/EasyLang/dijkstras-algorithm.easy @@ -0,0 +1,73 @@ +global con[][] n . +proc read . . + repeat + s$ = input + until s$ = "" + a = (strcode substr s$ 1 1) - 96 + b = (strcode substr s$ 3 1) - 96 + d = number substr s$ 5 9 + if a > len con[][] + len con[][] a + . + con[a][] &= b + con[a][] &= d + . + con[][] &= [ ] + n = len con[][] +. +read +# +len cost[] n +len prev[] n +# +proc dijkstra . . + for i = 2 to len cost[] + cost[i] = 1 / 0 + . + len todo[] n + todo[1] = 1 + repeat + min = 1 / 0 + a = 0 + for i to len todo[] + if todo[i] = 1 and cost[i] < min + min = cost[i] + a = i + . + . + until a = 0 + todo[a] = 0 + for i = 1 step 2 to len con[a][] - 1 + b = con[a][i] + c = con[a][i + 1] + if cost[a] + c < cost[b] + cost[b] = cost[a] + c + prev[b] = a + todo[b] = 1 + . + . + . +. +dijkstra +# +func$ gpath nd$ . + nd = strcode nd$ - 96 + while nd <> 1 + s$ = " -> " & strchar (nd + 96) & s$ + nd = prev[nd] + . + return "a" & s$ +. +print gpath "e" +print gpath "f" +# +input_data +a b 7 +a c 9 +a f 14 +b c 10 +b d 15 +c d 11 +c f 2 +d e 6 +e f 9 diff --git a/Task/Dijkstras-algorithm/Forth/dijkstras-algorithm.fth b/Task/Dijkstras-algorithm/Forth/dijkstras-algorithm.fth new file mode 100644 index 0000000000..4cff0f448e --- /dev/null +++ b/Task/Dijkstras-algorithm/Forth/dijkstras-algorithm.fth @@ -0,0 +1,158 @@ +\ utility routine to increment a variable +: 1+! 1 swap +! ; + +\ edge data +variable edge-count +0 edge-count ! +create edges + 'a , 'b , 7 , edge-count 1+! + 'a , 'c , 9 , edge-count 1+! + 'a , 'f , 14 , edge-count 1+! + 'b , 'c , 10 , edge-count 1+! + 'b , 'd , 15 , edge-count 1+! + 'c , 'd , 11 , edge-count 1+! + 'c , 'f , 2 , edge-count 1+! + 'd , 'e , 6 , edge-count 1+! + 'e , 'f , 9 , edge-count 1+! + +\ with accessors +: edge 3 * cells edges + ; +: edge-from edge ; +: edge-to edge 1 cells + ; +: edge-weight edge 2 cells + ; + +\ vertex data and acccessor +create vertex-names edge-count @ 2 * cells allot +: vertex-name cells vertex-names + ; + +variable vertex-count +0 vertex-count ! + +\ routine to look up a vertex by name +: find-vertex + -1 swap + vertex-count @ 0 ?do + dup i vertex-name @ = if swap drop i swap leave then + loop + drop +; + +\ routine to add a new vertex name if not found +: add-vertex + dup find-vertex dup -1 = if + swap vertex-count @ vertex-name ! + vertex-count dup @ swap 1+! + swap drop + else + swap + drop + then +; + +\ routine to add vertices to name table and replace names with indices in edges +: get-vertices + edge-count @ 0 ?do + i edge-from @ add-vertex i edge-from ! + i edge-to @ add-vertex i edge-to ! + loop +; + +\ call it +get-vertices + +\ variables to hold state during algorithm run +create been-visited +vertex-count @ cells allot +: visited cells been-visited + ; + +create prior-vertices +vertex-count @ cells allot +: prior-vertex cells prior-vertices + ; + +create distances +vertex-count @ cells allot +: distance cells distances + ; + +variable origin +variable current-vertex +variable neighbor +variable current-distance +variable tentative +variable closest-vertex +variable minimum-distance +variable vertex + +\ call with origin vertex name on stack +: dijkstra ( origin -- ) + + find-vertex origin ! + + been-visited vertex-count @ cells 0 fill + prior-vertices vertex-count @ cells -1 fill + distances vertex-count @ cells -1 fill + + 0 origin @ distance ! \ distance to origin is 0 + + origin @ current-vertex ! \ current vertex is the origin + + begin + + edge-count @ 0 ?do + i edge-from @ current-vertex @ = if \ if edge is from current + i edge-to @ neighbor ! \ neighbor vertex + neighbor @ distance @ current-distance ! + current-vertex @ distance @ i edge-weight @ + tentative ! + current-distance @ -1 = tentative @ current-distance @ < or if + tentative @ neighbor @ distance ! + current-vertex @ neighbor @ prior-vertex ! + then + else + then + loop + + 1 current-vertex @ visited ! \ current vertex has now been visited + -1 closest-vertex ! + + vertex-count @ 0 ?do + i visited @ 0= if + -1 minimum-distance ! + closest-vertex @ dup -1 <> if + distance @ minimum-distance ! + else + drop + then + i distance @ -1 <> + minimum-distance @ -1 = i distance @ minimum-distance @ < or + and if + i closest-vertex ! + then + then + loop + + closest-vertex @ current-vertex ! + current-vertex @ -1 = until + + cr + ." Shortest path to each vertex from " origin @ vertex-name @ emit ': emit cr + vertex-count @ 0 ?do + i origin @ <> if + i vertex-name @ emit ." : " i distance @ dup + -1 = if + drop + ." ∞ (unreachable)" + else + . + '( emit + i vertex ! + begin + vertex @ vertex-name @ emit + vertex @ origin @ <> while + ." ←" + vertex @ prior-vertex @ vertex ! + repeat + ') emit + then + cr + then + loop +; diff --git a/Task/Dinesmans-multiple-dwelling-problem/EasyLang/dinesmans-multiple-dwelling-problem.easy b/Task/Dinesmans-multiple-dwelling-problem/EasyLang/dinesmans-multiple-dwelling-problem.easy new file mode 100644 index 0000000000..8ca2c881b2 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/EasyLang/dinesmans-multiple-dwelling-problem.easy @@ -0,0 +1,44 @@ +proc nextperm . a[] . + n = len a[] + k = n - 1 + while k >= 1 and a[k + 1] <= a[k] + k -= 1 + . + if k = 0 + a[] = [ ] + return + . + l = n + while a[l] <= a[k] + l -= 1 + . + swap a[l] a[k] + k += 1 + while k < n + swap a[k] a[n] + k += 1 + n -= 1 + . +. +for i = 1 to 5 + floors[] &= i +. +BAKER = 1 +COOPER = 2 +FLETCHER = 3 +MILLER = 4 +SMITH = 5 +names$[] = [ "Baker" "Cooper" "Fletcher" "Miller" "Smith" ] +# +repeat + if floors[BAKER] <> 5 and floors[COOPER] <> 1 and floors[FLETCHER] <> 1 and floors[FLETCHER] <> 5 + if floors[MILLER] > floors[COOPER] and abs (floors[SMITH] - floors[FLETCHER]) <> 1 and abs (floors[FLETCHER] - floors[COOPER]) <> 1 + for i to 5 + print names$[i] & " lives on floor " & floors[i] + . + break 1 + . + . + nextperm floors[] + until len floors[] = 0 +. diff --git a/Task/Disarium-numbers/C-sharp/disarium-numbers.cs b/Task/Disarium-numbers/C-sharp/disarium-numbers.cs new file mode 100644 index 0000000000..311c7d21b4 --- /dev/null +++ b/Task/Disarium-numbers/C-sharp/disarium-numbers.cs @@ -0,0 +1,32 @@ +using System; + +class DisariumNumbers { + // Method to check if a number is a Disarium number + public static bool IsDisarium(int num) { + int n = num; + int len = num.ToString().Length; + int sum = 0; + int i = 1; + while (n > 0) { + // C# does not support implicit conversion from double to int, so we explicitly convert the result of Math.Pow to int + sum += (int)Math.Pow(n % 10, len - i + 1); + n /= 10; + i++; + } + return sum == num; + } + + static void Main(string[] args) { + int i = 0; + int count = 0; + // Find and print the first 19 Disarium numbers + while (count <= 18) { + if (IsDisarium(i)) { + Console.Write($"{i} "); + count++; + } + i++; + } + Console.WriteLine(); + } +} diff --git a/Task/Disarium-numbers/Odin/disarium-numbers.odin b/Task/Disarium-numbers/Odin/disarium-numbers.odin new file mode 100644 index 0000000000..c6ece460c6 --- /dev/null +++ b/Task/Disarium-numbers/Odin/disarium-numbers.odin @@ -0,0 +1,38 @@ +package disarium +import "core:fmt" +import "core:math" + +/* main block start */ +main :: proc() { + fmt.print("\nThe first 18 Disarium numbers are:") + count, i: int + for count < 19 { + if is_disarium(i) { + fmt.print(" ", i) + count += 1 + } + i += 1 + } + fmt.println("") +} /* main block end */ + +/* proc definitions */ +power :: proc(base, exponent: int) -> int { + result := 1 + for _ in 1 ..= exponent { + result *= base + } + return result +} + +is_disarium :: proc(num: int) -> bool { + n := num + sum := 0 + len := n <= 9 ? 1 : cast(int)math.floor_f64(math.log10_f64(auto_cast n) + 1) + for n > 0 { + sum += power(n % 10, len) + n /= 10 + len -= 1 + } + return num == sum +} diff --git a/Task/Distance-and-Bearing/Fortran/distance-and-bearing.f b/Task/Distance-and-Bearing/Fortran/distance-and-bearing.f new file mode 100644 index 0000000000..7d052d698e --- /dev/null +++ b/Task/Distance-and-Bearing/Fortran/distance-and-bearing.f @@ -0,0 +1,219 @@ + program code_translation + use iso_fortran_env , only:real64 , real32 + use helpers + implicit none + integer :: i + character(len = 300) :: input_string + character(len = *) , parameter :: filnam = "airports.csv" + character(len = *) , parameter :: delimiter = "," + character(len = 100) :: tokens(20) + integer :: num_tokens + integer :: iostat , counter + type(airport) , allocatable :: airports(:) + type(whereme) :: location + integer :: ii , jj + real(real64) :: dist + location%latitude = (51.514669D0)!Rosetta co-ords + location%longitude = (2.19858D0) + !Nearest to latitude 51.51467,longitude 2.19858 degrees + ! + !Open the file for reading + open(unit = 10 , file = 'airports.csv' , status = 'OLD' , & + &action = 'READ' , iostat = iostat , encoding = 'UTF-8') + if( iostat/=0 )stop 'Could not open file' + counter = 0 + do + read(10 , '(a)' , end = 100)input_string + counter = counter + 1 + end do + 100 continue ! Now we know how many elements there are + rewind(unit = 10) + write(*, '(a,1x,i0,1x,a)') 'Scanning',counter,'lines' + allocate(airports(counter)) + call system_clock(count = ii) + do i = 1 , counter + read(10 , '(a)' , end = 200)input_string + call tokenizes(input_string , tokens , num_tokens , ',') + read(tokens(1) , *)airports(i)%airportid + airports(i)%name = trim(adjustl(tokens(2))) + airports(i)%city = trim(adjustl(tokens(3))) + airports(i)%country = trim(adjustl(tokens(4))) + airports(i)%iata = trim(adjustl(tokens(5))) + airports(i)%icao = trim(adjustl(tokens(6))) + read(tokens(7) , '(f20.16)')airports(i)%latitude + read(tokens(8) , '(F20.16)')airports(i)%longitude + read(tokens(9) , *)airports(i)%altitude + read(tokens(10) , '(F5.2)' )airports(i)%timezone + airports(i)%dst = trim(adjustl(tokens(11))) + airports(i)%tzolson = trim(adjustl(tokens(12))) + airports(i)%typez = trim(adjustl(tokens(13))) + airports(i)%source = trim(adjustl(tokens(14))) + ! Calculate the distance and bearing straight away + airports(i)%distance = haversine(location%latitude , & + & location%longitude , airports(i)%latitude ,& + & airports(i)%longitude) + airports(i)%bearing = bearing(location%latitude , & + & location%longitude , airports(i)%latitude , & + & airports(i)%longitude) + end do + 200 continue + call system_clock(count = jj) + write(* , *) 'Read complete, time taken = ' , (jj - ii) , & + & 'milliseconds' // char(10) // char(13) + call sortem(airports) ! Sort the airports out + write(*, '(/,2x,a,t14,a,t75,a,t95,a,t108,a,t117,a)') 'Num' , 'Name' , & + &'Country' , 'ICAO' , 'Dist.' , 'Bearing' + write(*, '(a)') repeat('=' , 130) + do jj = 1 , 20!First 20 only + write(*, '(i5,t8,a,t75,a,t95,a,t105,f8.1,t117,i0)') airports(jj) & + & %airportid , airports(jj)%name , airports(jj)%country , & + & airports(jj)%icao , airports(jj)%distance , & + & nint(airports(jj)%bearing) + end do + stop 'Normal completion' // char(10) // char(13) + end program code_translation + module helpers + use iso_fortran_env , only:real32,real64 + implicit none + real(real64) , parameter :: radius_in_km = 6372.8D0 + real(real64) , parameter :: kilos_to_nautical = 0.5399568D0 + type whereme + real(real64) :: latitude , longitude + end type whereme + type airport + integer :: airportid + character(len = 100) :: name + character(len = 50) :: city , country + character(len = 10) :: iata , icao + real(real64) :: latitude , longitude + integer :: altitude + real(real32) :: timezone + character(len = 10) :: dst + character(len = 100) :: tzolson + character(len = 20) :: typez , source + real(real64) :: distance , bearing + end type airport + contains ! We'll calculate them and store in each airport + ! + ! The given angles are in radians, and the result is in degrees in the range [0, 360). + function bearing(lat1 , lon1 , lat2 , lon2) + real(real64) , parameter :: toradians = acos( - 1.0D0)/180.0D0 + real(real64) :: bearing + real(real64) , intent(in) :: lat1 + real(real64) , intent(in) :: lon1 + real(real64) , intent(in) :: lat2 + real(real64) , intent(in) :: lon2 + real(real64) :: dlat + real(real64) :: dlon + real(real64) :: rlat1 + real(real64) :: rlat2 + real(real64) :: x + real(real64) :: y + ! + dlat = (lat2 - lat1)*toradians + dlon = toradians*(lon2 - lon1) + rlat1 = toradians*(lat1) + rlat2 = toradians*(lat2) + ! + x = cos(rlat2)*sin(dlon) + y = cos(rlat1)*sin(rlat2) - sin(rlat1)*cos(rlat2)*cos(dlon) + bearing = atan2(x , y) + bearing = to_degrees(bearing) + bearing = mod(bearing + 360.0D0 , 360.0D0) + end function bearing + ! + ! + function to_radian(degree) result(rad) + real(real64) , parameter :: deg_to_rad = atan(1.0D0)/45.0D0 ! exploit intrinsic atan to generate pi/180 runtime constant + ! + real(real64) :: rad + real(real64) , intent(in) :: degree + ! degrees to radians + rad = degree*deg_to_rad + end function to_radian + ! + function to_degrees(radians) result(deg) + real(real64) , parameter :: radian_to_degree = 180.0D0/acos( - 1.0D0) + ! + real(real64) :: deg + real(real64) , intent(in) :: radians + deg = radians*radian_to_degree + end function to_degrees + ! + function haversine(deglat1 , deglon1 , deglat2 , deglon2) result(dist) + real(real64) :: dist + real(real64) , intent(in) :: deglat1 + real(real64) , intent(in) :: deglon1 + real(real64) , intent(in) :: deglat2 + real(real64) , intent(in) :: deglon2 + real(real64) :: a + real(real64) :: c + real(real64) :: dlat + real(real64) :: dlon + real(real64) :: lat1 + real(real64) :: lat2 + ! great circle distance + dlat = to_radian(deglat2 - deglat1) + dlon = to_radian(deglon2 - deglon1) + lat1 = to_radian(deglat1) + lat2 = to_radian(deglat2) + a = (sin(dlat/2.0D0)**2) + cos(lat1)*cos(lat2) & + & *((sin(dlon/2.0D0))**2) + c = 2.0D0*asin(sqrt(a)) + dist = radius_in_km*c*kilos_to_nautical + end function haversine + subroutine sortem(airports)!Bubble sort them, nice and easy + type(airport) , intent(inout) , dimension(:) :: airports + integer :: i + integer :: k + logical :: swapped + type(airport) :: temp + swapped = .true. + k = size(airports%distance) + do while ( swapped ) + swapped = .false. + do i = 1 , k - 1 + if( airports(i)%distance>airports(i + 1)%distance )then + temp = airports(i) + airports(i) = airports(i + 1) + airports(i + 1) = temp + swapped = .true. + end if + end do + end do + return + end subroutine sortem + ! + subroutine tokenizes(input_string , tokens , num_tokens , delimiter) + character(*) , intent(in) :: input_string + character(*) , intent(out) , dimension(:) :: tokens + integer , intent(out) :: num_tokens + character(1) , intent(in) :: delimiter + integer :: end_idx + integer :: i + integer :: start_idx + character(100) :: temp_string + num_tokens = 0 + temp_string = trim(input_string) + start_idx = 1 + do i = 1 , len_trim(temp_string) + if( (temp_string(i:i)==delimiter) )then + end_idx = i - 1 + if( end_idx>=start_idx )then + num_tokens = num_tokens + 1 + tokens(num_tokens) = '' + tokens(num_tokens) = temp_string(start_idx:end_idx) + end if + start_idx = i + 1 + end if + end do + ! Handle the last token + if( start_idx<=len_trim(temp_string) )then + num_tokens = num_tokens + 1 + tokens(num_tokens) = temp_string(start_idx:len_trim( & + & temp_string)) + end if + end subroutine tokenizes + ! + end module helpers + ! diff --git a/Task/Distribution-of-0-digits-in-factorial-series/C-sharp/distribution-of-0-digits-in-factorial-series.cs b/Task/Distribution-of-0-digits-in-factorial-series/C-sharp/distribution-of-0-digits-in-factorial-series.cs new file mode 100644 index 0000000000..849d169bfa --- /dev/null +++ b/Task/Distribution-of-0-digits-in-factorial-series/C-sharp/distribution-of-0-digits-in-factorial-series.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +public class DistributionInFactorials +{ + public static void Main(string[] args) + { + List limits = new List { 100, 1_000, 10_000 }; + foreach (int limit in limits) + { + MeanFactorialDigits(limit); + } + } + + private static void MeanFactorialDigits(int limit) + { + BigInteger factorial = BigInteger.One; + double proportionSum = 0.0; + double proportionMean = 0.0; + + for (int n = 1; n <= limit; n++) + { + factorial = factorial * n; + string factorialString = factorial.ToString(); + int digitCount = factorialString.Length; + long zeroCount = factorialString.Split('0').Length - 1; + proportionSum += (double)zeroCount / digitCount; + proportionMean = proportionSum / n; + } + + string result = string.Format("{0:F8}", proportionMean); + Console.WriteLine("Mean proportion of zero digits in factorials from 1 to " + limit + " is " + result); + } +} diff --git a/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy b/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy new file mode 100644 index 0000000000..5ebd3731b8 --- /dev/null +++ b/Task/Diversity-prediction-theorem/EasyLang/diversity-prediction-theorem.easy @@ -0,0 +1,18 @@ +proc calc TrueVal test[] . . + for test in test[] + h = (test - TrueVal) + Vari += h * h + Sum += test + c += 1 + . + AvgErr = Vari / c + RefAvg = Sum / c + h = (TrueVal - RefAvg) + CrowdErr = h * h + print "Average error : " & AvgErr + print " Crowd error : " & CrowdErr + print " Diversity : " & AvgErr - CrowdErr + print "" +. +calc 49 [ 48 47 51 ] +calc 49 [ 48 47 51 42 ] diff --git a/Task/Doomsday-rule/C-sharp/doomsday-rule.cs b/Task/Doomsday-rule/C-sharp/doomsday-rule.cs new file mode 100644 index 0000000000..da701dde47 --- /dev/null +++ b/Task/Doomsday-rule/C-sharp/doomsday-rule.cs @@ -0,0 +1,57 @@ +using System; + +class Doom { + public static void Main(string[] args) { + Date[] dates = { + new Date(1800,1,6), + new Date(1875,3,29), + new Date(1915,12,7), + new Date(1970,12,23), + new Date(2043,5,14), + new Date(2077,2,12), + new Date(2101,4,2) + }; + + foreach (Date d in dates) + Console.WriteLine($"{d.Format()}: {d.Weekday()}"); + } +} + +class Date { + private int year, month, day; + + private static readonly int[] leapDoom = {4,1,7,4,2,6,4,1,5,3,7,5}; + private static readonly int[] normDoom = {3,7,7,4,2,6,4,1,5,3,7,5}; + public static readonly string[] weekdays = { + "Sunday", "Monday", "Tuesday", "Wednesday", + "Thursday", "Friday", "Saturday" + }; + + public Date(int year, int month, int day) { + this.year = year; + this.month = month; + this.day = day; + } + + public bool IsLeapYear() { + return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + } + + public string Format() { + return $"{month:00}/{day:00}/{year:0000}"; + } + + public string Weekday() { + int c = year / 100; + int r = year % 100; + int s = r / 12; + int t = r % 12; + + int cAnchor = (5 * (c % 4) + 2) % 7; + int doom = (s + t + t / 4 + cAnchor) % 7; + int anchor = + IsLeapYear() ? leapDoom[month - 1] : normDoom[month - 1]; + + return weekdays[(doom + day - anchor + 7) % 7]; + } +} diff --git a/Task/Doomsday-rule/Fortran/doomsday-rule.f b/Task/Doomsday-rule/Fortran/doomsday-rule.f new file mode 100644 index 0000000000..7bfd36bf72 --- /dev/null +++ b/Task/Doomsday-rule/Fortran/doomsday-rule.f @@ -0,0 +1,208 @@ + program someday ! Calculates the day that a week falls on + use datestuff + implicit none +! +! PARAMETER definitions +! + integer , parameter :: numdates = 7 +! +! Local variable declarations +! + character(30) , dimension(numdates) , save :: date_string + integer , dimension(numdates) , save :: day + character(9) , dimension(numdates) , save :: days + integer :: j + integer :: k + integer , dimension(numdates) , save :: month + integer , dimension(numdates) , save :: year +! + data days/'Monday ' , 'Tuesday ' , 'Wednesday' , 'Thursday ' , & + &'Friday ' , 'Saturday ' , 'Sunday '/ + data month/01 , 03 , 12 , 12 , 05 , 02 , 04/ + data day/06 , 29 , 07 , 23 , 14 , 12 , 02/ + data year/1800 , 1875 , 1915 , 1970 , 2043 , 2077 , 2101/ + data date_string/'1800-01-06 (January 6, 1800)' , & + &'1875-03-29 (March 29, 1875)' , '1915-12-07 (December 7, 1915)' ,& + &'1970-12-23 (December 23, 1970)' , '2043-05-14 (May 14, 2043)' , & + &'2077-02-12 (February 12, 2077)' , '2101-04-02 (April 2, 2101)'/ ! +!*Code + + print * + do j = 1 , numdates + k = get_the_day(day(j) , month(j) , year(j)) + print '(a, t31,1a1,1x,a)' , date_string(j) , ':' , days(k) + end do + end program someday + module datestuff + implicit none + public :: get_the_day + private :: get_anchor_day , gregorian_leap_year +! + enum , bind(c) ! Use enums to get greater clarity in the code + enumerator :: january = 1 , february , march , april , may , & + & june , july , august , september , october , november ,& + & december + end enum + enum , bind(c) + enumerator :: sunday = 0 , monday , tuesday , wednesday , & + & thursday , friday , saturday + end enum + contains +! + pure function gregorian_leap_year(year) result(answer) ! Tests if the year is a leap year +! +! Function and Dummy argument declarations +! + logical :: answer + integer , intent(in) :: year +! + answer = .false. ! Set default to not a leap year + if( mod(year , 4)==0 )answer = .true. ! Year divisible by 4 = leap year + if( mod(year , 100)==0 )then + if( mod(year , 400)==0 )then ! Year divisible by 400 = century year that is leap year + answer = .true. + else + answer = .false. ! Century years are not leap years + end if + end if + end function gregorian_leap_year +! + pure function get_anchor_day(year) result(answer) ! Returns Anchor Days in doomsday calculation +!Note: The days start as Monday = 1, Tuesday =2, etc until Sunday = 7 +!The Doomsday rule, Doomsday algorithm or Doomsday method is an algorithm of determination of the day of the week for a given date. +!It provides a perpetual calendar because the Gregorian calendar moves in cycles of 400 years. +!It takes advantage of each year having a certain day of the week upon which certain easy-to-remember dates, +!called the doomsdays, fall; for example, the last day of February, 4/4, 6/6, 8/8, 10/10, and 12/12 all occur +! on the same day of the week in any year. Applying the Doomsday algorithm involves three steps: Determination of the anchor day +! for the century, calculation of the anchor day for the year from the one for the century, and selection of the closest date +! out of those that always fall on the doomsday, e.g., 4/4 and 6/6, and count of the number of days (modulo 7) between that +! date and the date in question to arrive at the day of the week. The technique applies to both the Gregorian calendar and the +! Julian calendar, although their doomsdays are usually different days of the week. +! +! Function and Dummy argument declarations +! + integer :: answer + integer , intent(in) :: year +! +! Local variable declarations +! + integer :: diffyear + integer :: div12 + integer :: numyears + integer :: temp1 +! +! End of declarations +!*Code + numyears = mod(year , 100) ! Get number of years greater than century + + temp1 = year - numyears ! Turn into a century year + temp1 = mod(temp1 , 400) ! Now mod 400 to get base year for anchor day + select case(temp1) ! Select the base day + case(0) + answer = tuesday + case(100) + answer = sunday + case(200) + answer = friday + case(300) + answer = wednesday + case default ! Anything else is an error + ERROR Stop 'Bad Anchor Day' ! Finish with error + end select + ! + !Calculate the doomsday of any given year + ! + div12 = int(numyears/12) ! Get number of times 12 goes into year + temp1 = mod(numyears , 12) ! Get the remainer + diffyear = int(temp1/4) ! Div 4 (magic algorithm) + answer = diffyear + div12 + answer + temp1 + answer = mod(answer , 7) + end function get_anchor_day ! Note: The days start as Sunday = 0, Monday = 1, Tuesday =2, etc until Saturda +! + pure function get_the_day(day , month , year) result(answer) +! Note: The days start as Sunday = 0, Monday = 1, Tuesday =2, etc until Saturday = 6 +! +! Function and Dummy argument declarations + integer :: answer + integer , intent(in) :: day + integer , intent(in) :: month + integer , intent(in) :: year +! +! Local variable declarations + integer :: closest + integer :: doomsday + integer :: temp1 + integer :: temp2 + integer :: up_or_down +! +! End of declarations +! + ! There are doomsdays in every month, so we know what month it is ... + ! We need to find the doomsday in the relevant month + select case(month) ! Scratch Variables + case(january) + closest = merge(4,3,gregorian_leap_year(year)) ! Use merge as a ternary + case(february) + closest = merge(29,28,gregorian_leap_year(year)) ! Use merge as a ternary + case(march) + closest = 7 + case(april) + closest = 4 + case(may) + closest = 9 + case(june) + closest = 6 + case(july) + temp1 = abs(4 - day) + temp2 = abs(11 - day) + closest = merge(4,11,temp1day )then + up_or_down = -7 + else if( closest0 )then + do while ( temp1<=day ) + temp2 = temp1 + temp1 = temp1 + up_or_down ! Count in sevens to the final + end do + temp1 = day - temp2 + temp1 = (doomsday + 7) + temp1 + else if( up_or_down<0 )then + do while ( temp1>=day ) + temp2 = temp1 + temp1 = temp1 + up_or_down ! Count in sevens to the final + end do + temp1 = temp2 - day ! See how far away I am from this day + temp1 = (doomsday + 7) - temp1 ! Subtract the difference in days from the known doomsday + else + temp1 = doomsday ! It fell on the doomsday + end if + answer = mod(temp1 , 7) ! Turn Sundays into Zeros + end function get_the_day +! + end module datestuff + ! diff --git a/Task/Doomsday-rule/Scala/doomsday-rule.scala b/Task/Doomsday-rule/Scala/doomsday-rule.scala new file mode 100644 index 0000000000..b2d3a46d05 --- /dev/null +++ b/Task/Doomsday-rule/Scala/doomsday-rule.scala @@ -0,0 +1,40 @@ +object Doom extends App { + val dates = Array( + new Date(1800, 1, 6), + new Date(1875, 3, 29), + new Date(1915, 12, 7), + new Date(1970, 12, 23), + new Date(2043, 5, 14), + new Date(2077, 2, 12), + new Date(2101, 4, 2) + ) + + dates.foreach(d => println(s"${d.format}: ${d.weekday}")) +} + +class Date(val year: Int, val month: Int, val day: Int) { + import Date._ + + def isLeapYear: Boolean = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) + + def format: String = f"$month%02d/$day%02d/$year%04d" + + def weekday: String = { + val c = year / 100 + val r = year % 100 + val s = r / 12 + val t = r % 12 + + val cAnchor = (5 * (c % 4) + 2) % 7 + val doom = (s + t + t / 4 + cAnchor) % 7 + val anchor = if (isLeapYear) leapdoom(month - 1) else normdoom(month - 1) + + weekdays((doom + day - anchor + 7) % 7) + } +} + +object Date { + private val leapdoom = Array(4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5) + private val normdoom = Array(3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5) + val weekdays = Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") +} diff --git a/Task/Draw-a-pixel/Applesoft-BASIC/draw-a-pixel.basic b/Task/Draw-a-pixel/Applesoft-BASIC/draw-a-pixel.basic new file mode 100644 index 0000000000..370428862e --- /dev/null +++ b/Task/Draw-a-pixel/Applesoft-BASIC/draw-a-pixel.basic @@ -0,0 +1,29 @@ + 100 WIDTH = 320 + 110 HEIGHT = 240 + 120 C = 1: REM RED + 130 X = 100 + 140 Y = 100 + 150 DEF FN X(X) = INT ((X - 1) / 14) + 160 DEF FN Y(Y) = INT ((Y - 1) / 8) + 170 W = FN X(WIDTH) + 180 H = FN Y(HEIGHT) + 190 WX = INT ( RND (1) * (40 - W)) + 200 WY = INT ( RND (1) * (48 - H)) + 210 C$ = "0123456789:;<=>?" + 220 C$ = MID$ (C$,C,I) + MID$ (C$,C + 2, LEN (C$) - C - 1) + 230 I = INT ( RND (1) * LEN (C$)) + 240 COLOR= ASC ( MID$ (C$,I + 1)) - 48 + 250 C$ = MID$ (C$,1,I) + MID$ (C$,I + 2, LEN (C$) - I - 1) + 260 A = PEEK (49234) + PEEK (49240) + PEEK (49232) + 270 FOR I = 0 TO 39 + 280 VLIN 0,47 AT I + 290 NEXT + 300 COLOR= ASC ( MID$ (C$, INT ( RND (1) * LEN (C$)) + 1)) - 48 + 310 FOR I = WX TO WX + W + 320 VLIN WY,WY + H AT I + 330 NEXT + 340 COLOR= C + 350 PLOT WX + FN X(X),WY + FN Y(Y) + 360 WAIT 49152,128 + 370 TEXT + 380 HOME diff --git a/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl b/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl index cbf44eb805..26c8170b96 100644 --- a/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl +++ b/Task/Draw-a-pixel/Uxntal/draw-a-pixel.uxnatl @@ -1,16 +1,22 @@ +( $ uxnasm draw-pixel.tal draw-pixel.rom && uxnemu draw-pixel.rom ) + |00 @System &vector $2 &expansion $2 &wst $1 &rst $1 &metadata $2 &r $2 &g $2 &b $2 &debug $1 &state $1 |20 @Screen &vector $2 &width $2 &height $2 &auto $1 &pad $1 &x $2 &y $2 &addr $2 &pixel $1 &sprite $1 |0100 + ( set theme ) #0f00 .System/r DEO2 #0000 .System/g DEO2 #0000 .System/b DEO2 + ( set screen size ) #0140 .Screen/width DEO2 #00f0 .Screen/height DEO2 + ( set position ) #0064 .Screen/x DEO2 #0064 .Screen/y DEO2 + ( draw pixel ) #01 .Screen/pixel DEO BRK diff --git a/Task/Draw-a-rotating-cube/Zig/draw-a-rotating-cube.zig b/Task/Draw-a-rotating-cube/Zig/draw-a-rotating-cube.zig index cde1f8bf6c..71e488cbe7 100644 --- a/Task/Draw-a-rotating-cube/Zig/draw-a-rotating-cube.zig +++ b/Task/Draw-a-rotating-cube/Zig/draw-a-rotating-cube.zig @@ -15,8 +15,8 @@ pub fn main() !void { const size = c.Vector3{ .x = cube_side, .y = cube_side, .z = cube_side }; const position = c.Vector3{ .x = 0, .y = 0, .z = 0 }; const x_rot = 45; - const y_center = std.math.sqrt(@as(f32, 3)) * cube_side / 2; - const z_rot = std.math.atan(@as(f32, std.math.sqrt1_2)) * 180 / std.math.pi; + const y_center: f32 = std.math.sqrt(3.0) * cube_side / 2.0; + const z_rot = std.math.radiansToDegrees(f32, std.math.atan(@as(f32, std.math.sqrt1_2))); c.SetConfigFlags(c.FLAG_WINDOW_RESIZABLE | c.FLAG_VSYNC_HINT); c.InitWindow(screen_width, screen_height, "Draw a Rotating Cube"); diff --git a/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy b/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy new file mode 100644 index 0000000000..6cc97d01fb --- /dev/null +++ b/Task/Duffinian-numbers/EasyLang/duffinian-numbers.easy @@ -0,0 +1,63 @@ +fastfunc isprim num . + i = 2 + while i <= sqrt num + if num mod i = 0 + return 0 + . + i += 1 + . + return 1 +. +func gcd a b . + while b <> 0 + h = b + b = a mod b + a = h + . + return a +. +func sumdiv num . + d = 2 + repeat + quot = num div d + until d > quot + if num mod d = 0 + sum += d + if d <> quot + sum += quot + . + . + d += 1 + . + return sum + 1 +. +func isduff n . + if isprim n = 0 and gcd sumdiv n n = 1 + return 1 + . + return 0 +. +proc duffs . . + print "First 50 Duffinian numbers:" + n = 4 + repeat + if isduff n = 1 + write n & " " + cnt += 1 + . + until cnt = 50 + n += 1 + . + cnt = 0 + n = 4 + print "\n\nFirst 15 Duffinian triplets:" + repeat + if isduff n = 1 and isduff (n + 1) = 1 and isduff (n + 2) = 1 + print n & " - " & n + 2 + cnt += 1 + . + until cnt = 15 + n += 1 + . +. +duffs diff --git a/Task/Duffinian-numbers/PARI-GP/duffinian-numbers.parigp b/Task/Duffinian-numbers/PARI-GP/duffinian-numbers.parigp new file mode 100644 index 0000000000..dfdeaaa0d6 --- /dev/null +++ b/Task/Duffinian-numbers/PARI-GP/duffinian-numbers.parigp @@ -0,0 +1,26 @@ +isDuffinian(n) = (!isprime(n)) && (gcd(n, sigma(n)) == 1); + +testDuffinians()= +{ + print("First 50 Duffinian numbers:"); + count = 0; n = 2; + while(count < 50, + if (isDuffinian(n), + print1(n, " "); + count++; + ); + n++; + ); + + print("\n\nFifteen Duffinian triplets:"); + count = 0; n = 2; + while (count < 15, + if (isDuffinian(n) && isDuffinian(n + 1) && isDuffinian(n + 2), + print(n, " ", n + 1, " ", n + 2); + count++; + ); + n++; + ); +} + +testDuffinians(); diff --git a/Task/Dutch-national-flag-problem/EasyLang/dutch-national-flag-problem.easy b/Task/Dutch-national-flag-problem/EasyLang/dutch-national-flag-problem.easy index 1c086c7fa7..97bf8d02eb 100644 --- a/Task/Dutch-national-flag-problem/EasyLang/dutch-national-flag-problem.easy +++ b/Task/Dutch-national-flag-problem/EasyLang/dutch-national-flag-problem.easy @@ -1,6 +1,6 @@ col$[] = [ "red" "white" "blue" ] for i to 8 - b[] &= random 3 + b[] &= randint 3 . for b in b[] write col$[b] & " " diff --git a/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena b/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena index 64232afd2c..f8ca8fa17c 100644 --- a/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena +++ b/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena @@ -12,7 +12,7 @@ class TestClass function() { - auto prop := new MessageName(console.write:"Enter the variable name:".readLine()); + auto prop := new MessageName(console.write("Enter the variable name:").readLine()); (prop.setPropertyMessage())(variables,42); console.printLine(prop.toPrintable(),"=",(prop.getPropertyMessage())(variables)).readChar() diff --git a/Task/EKG-sequence-convergence/MATLAB/ekg-sequence-convergence.m b/Task/EKG-sequence-convergence/MATLAB/ekg-sequence-convergence.m new file mode 100644 index 0000000000..2363b9b1e0 --- /dev/null +++ b/Task/EKG-sequence-convergence/MATLAB/ekg-sequence-convergence.m @@ -0,0 +1,43 @@ +% Displaying EKG sequences and the convergence point +for i = [2, 5, 7, 9, 10] + ekg = ekgsequence(i, 30); + fprintf('EKG(%d): %s\n', i, num2str(ekg)); +end + +convergencePoint = convergeat(5, 7); +fprintf('EKGs of 5 & 7 converge at term %d\n', convergencePoint); + + + +function ekg = ekgsequence(n, limit) + ekg = [1, n]; + while length(ekg) < limit + for i = 2:2^18 + if all(ekg ~= i) && gcd(ekg(end), i) > 1 + ekg = [ekg, i]; + break; + end + end + end +end + +function point = convergeat(n, m, max) + if nargin < 3 + max = 100; + end + + ekgn = ekgsequence(n, max); + ekgm = ekgsequence(m, max); + + point = 0; + for i = 3:max + if ekgn(i) == ekgm(i) && sum(ekgn(1:i+1)) == sum(ekgm(1:i+1)) + point = i; + return; + end + end + + if point == 0 + warning('No convergence in %d terms', max); + end +end diff --git a/Task/Earliest-difference-between-prime-gaps/FreeBASIC/earliest-difference-between-prime-gaps.basic b/Task/Earliest-difference-between-prime-gaps/FreeBASIC/earliest-difference-between-prime-gaps.basic new file mode 100644 index 0000000000..0b2a1db241 --- /dev/null +++ b/Task/Earliest-difference-between-prime-gaps/FreeBASIC/earliest-difference-between-prime-gaps.basic @@ -0,0 +1,49 @@ +Type PrimeGaps + As Ulong lastPrime + As Ulongint gapStarts(1 To 1e7) +End Type + +Function NextPrime(n As Ulong) As Ulong + Dim As Ulong j, i = n + 1 + Do + For j = 2 To Sqr(i) + If i Mod j = 0 Then Exit For + Next j + If j > Sqr(i) Then Return i + i += 1 + Loop +End Function + +Function findGapStart(Byref pg As PrimeGaps, gap As Ulongint) As Ulongint + Dim As Ulongint prev, diff + If pg.gapStarts(gap) <> 0 Then Return pg.gapStarts(gap) + Do + prev = pg.lastPrime + pg.lastPrime = NextPrime(pg.lastPrime) + diff = pg.lastPrime - prev + pg.gapStarts(diff) = prev + If gap = diff Then Return prev + Loop +End Function + +Dim Shared As PrimeGaps pg +pg.lastPrime = NextPrime(2) +Dim As Ulongint limit = 1e7 +Dim As Integer pm = 10 +Dim As Ulongint start1, start2, gap1 = 2, gap2, diff +Do + start1 = findGapStart(pg, gap1) + gap2 = gap1 + 2 + start2 = findGapStart(pg, gap2) + diff = Abs(start2 - start1) + If diff > pm Then + Print "Earliest difference >"; pm; " between adjacent prime gap starting primes:" + Print "Gap "; gap1; " starts at "; start1; ", gap "; gap2; " starts at "; start2; ", difference is "; diff; !".\n" + If pm = limit Then Exit Do + pm *= 10 + Else + gap1 = gap2 + End If +Loop + +Sleep diff --git a/Task/Eban-numbers/ALGOL-68/eban-numbers.alg b/Task/Eban-numbers/ALGOL-68/eban-numbers.alg new file mode 100644 index 0000000000..9cd640f69f --- /dev/null +++ b/Task/Eban-numbers/ALGOL-68/eban-numbers.alg @@ -0,0 +1,66 @@ +BEGIN # Eban numbers - translated from the Lua and Phix samples # + + MODE INTERVAL = STRUCT( INT start, end, BOOL print ); + + []INTERVAL intervals = ( ( 2, 1000, TRUE ) + , ( 1000, 4000, TRUE ) + , ( 2, 10000, FALSE ) + , ( 2, 1000000, FALSE ) + , ( 2, 10000000, FALSE ) + , ( 2, 100000000, FALSE ) + , ( 2, 1000000000, FALSE ) + ); + FOR intp FROM LWB intervals TO UPB intervals DO + INTERVAL intv = intervals[ intp ]; + IF start OF intv = 2 THEN + print( ( "eban numbers up to and including ", whole( end OF intv, 0 ), ":" ) ) + ELSE + print( ( "eban numbers between ", whole( start OF intv, 0 ) + , " and ", whole( end OF intv, 0 ), " (inclusive)" + ) + ) + FI; + print( ( newline ) ); + + IF NOT print OF intv THEN + # calculate the count, as in the Phix sample # + # end OF intv must be a power of 10 # + INT p10 := 0; + INT v := end OF intv; + WHILE v > p10 DO + p10 +:= 1; + v OVERAB 10 + OD; + INT n = p10 - ( p10 OVER 3 ); + INT p5 = n OVER 2; + INT p4 = ( n + 1 ) OVER 2; + print( ( "count = ", whole( ( ( 5 ^ p5 ) * ( 4 ^ p4 ) ) - 1, 0 ), newline ) ) + ELSE + # enumerate the eban numbers, as in the Lua and other samples # + INT count := 0; + FOR i FROM start OF intv BY 2 TO end OF intv DO + INT b = i OVER 1 000 000 000; + INT r := i MOD 1 000 000 000; + INT m := r OVER 1 000 000; + r := i MOD 1 000 000; + INT t := r OVER 1 000; + r := r MOD 1 000; + IF m >= 30 AND m <= 66 THEN m MODAB 10 FI; + IF t >= 30 AND t <= 66 THEN t MODAB 10 FI; + IF r >= 30 AND r <= 66 THEN r MODAB 10 FI; + IF b = 0 OR b = 2 OR b = 4 OR b = 6 THEN + IF m = 0 OR m = 2 OR m = 4 OR m = 6 THEN + IF t = 0 OR t = 2 OR t = 4 OR t = 6 THEN + IF r = 0 OR r = 2 OR r = 4 OR r = 6 THEN + print( ( whole( i, 0 ), " " ) ); + count +:= 1 + FI + FI + FI + FI + OD; + print( ( newline, "count = ", whole( count, 0 ), newline ) ) + FI; + print( ( newline ) ) + OD +END diff --git a/Task/Eertree/00-TASK.txt b/Task/Eertree/00-TASK.txt index 49f450de1d..c5d6507662 100644 --- a/Task/Eertree/00-TASK.txt +++ b/Task/Eertree/00-TASK.txt @@ -12,5 +12,6 @@ Construct an eertree for the string "eertree", then output all sub-palindromes b *   Wikipedia entry:   [https://en.wikipedia.org/wiki/Trie trie]. *   Wikipedia entry:   [https://en.wikipedia.org/wiki/Suffix_tree suffix tree] *   [https://arxiv.org/abs/1506.04862 Cornell University Library, Computer Science, Data Structures and Algorithms ───► EERTREE: An Efficient Data Structure for Processing Palindromes in Strings]. +*EERTREE: An efficient data structure for processing palindromes in strings[https://www.sciencedirect.com/science/article/pii/S0195669817301294]

diff --git a/Task/Eertree/JavaScript/eertree.js b/Task/Eertree/JavaScript/eertree.js new file mode 100644 index 0000000000..64cabf94a7 --- /dev/null +++ b/Task/Eertree/JavaScript/eertree.js @@ -0,0 +1,108 @@ +class Node { + constructor(len, suffix, id, level) { + this.edges = new Map(); // edges + this.link = suffix; // Suffix link points to another node + this.length = len; // Length of the palindrome represented by this node + this.palindrome = ""; + this.parent = null; + } +} + +class Eertree { + constructor() { + this.imaginary = new Node(-1, null, this.count++, 1); // also called odd length root node + this.empty = new Node(0, this.imaginary, this.count++, 2); // also called even length root node + this.maxSuffixOfT = this.empty; // this is the current node we are on also the maximum Suffix of tree T + this.s = ""; // String processed by the Eertree + } + + + /** + * Add will only add at most 1 node to the tree. + * We get the max suffix palindrome with the same character before it + * so we can get cQc which will be the new palindrome, c otherwise + * If the node is already in the tree then we return 0 and create no new nodes + * @param {Character} c + * @returns int 1 if it created a new node an 0 otherwise + */ + add(c){ + /** + * Traverse the suffix palindromes of T in the order of decreasing length + * Keep traversing until we get to imaginary node or until T[len - k] = a + * @param {Node} startNode + * @param {Character} a + * @returns {Node} u + */ + const getMaxSuffixPalindrome = (startNode, a) =>{ + let u = startNode; + let n = this.s.length; + let k = u.length; + while(u !== this.imaginary && this.s[n - k - 1] !== a){ + if(u === u.link){ + throw new Error('Infinite Loop'); + } + u = u.link; + k = u.length; + } + return u; + }; + + + let Q = getMaxSuffixPalindrome(this.maxSuffixOfT, c); + let createNewNode = !(Q.edges.has(c)); + if(createNewNode){ + let P = new Node(); + P.length = Q.length + 2; + // this is because Q is a palindrome and the suffix and prefix == c so cQc = P + //P.length == 1 if Q is the imaginary node + if(P.length === 1){ + P.link = this.empty; + P.palindrome = c; + } + else{ + /** + * Now we need to find the node to suffix link to + * Continue traversing suffix palindromes of T starting with the suffix + * we found earlier 's link + */ + P.link = getMaxSuffixPalindrome(Q.link, c).edges.get(c); + P.palindrome = c + Q.palindrome + c; + } + P.parent = Q; + Q.edges.set(c, P); + } + + this.maxSuffixOfT = Q.edges.get(c); + this.s += c; + + return createNewNode === true ? 1 : 0; + } + + traverse(){ + let subpalindromes = []; + + const dfs = (node) => { + if(node !== this.imaginary && node !== this.empty){ + subpalindromes.push(node.palindrome); + } + + for(let [_, childNode] of node.edges){ + dfs(childNode); + } + } + + dfs(this.imaginary); + dfs(this.empty); + return subpalindromes; + } +} + +var getSubpalindromes = function(s) { + let eertree = new Eertree(); + for(let c of s){ + eertree.add(c); + } + return eertree.traverse(); +} + +console.log(getSubpalindromes('eertree')); diff --git a/Task/Eertree/Rust/eertree.rust b/Task/Eertree/Rust/eertree.rust new file mode 100644 index 0000000000..36b93b82f5 --- /dev/null +++ b/Task/Eertree/Rust/eertree.rust @@ -0,0 +1,105 @@ +use std::collections::HashMap; +use std::convert::TryInto; + +struct Node { + length: isize, + edges: HashMap, + suffix: usize, +} + +impl Node { + fn new(length: isize, suffix: usize) -> Self { + Node { + length, + suffix, + edges: HashMap::new(), + } + } +} + +const EVEN_ROOT: usize = 0; +const ODD_ROOT: usize = 1; + +fn eertree(s: &[u8]) -> Vec { + let mut tree = vec![ + Node::new(0, ODD_ROOT), // even root + Node::new(-1, ODD_ROOT), // odd root + ]; + + let mut suffix = ODD_ROOT; + + for (i, &c) in s.iter().enumerate() { + let mut n = suffix; + let mut k; + + loop { + k = tree[n].length; + let k_plus_one: usize = (k + 1).try_into().unwrap_or(0); + if let Some(b) = i.checked_sub(k_plus_one) { + if b < s.len() && s[b] == c { + break; + } + } + n = tree[n].suffix; + } + + if tree[n].edges.contains_key(&c) { + suffix = tree[n].edges[&c]; + continue; + } + + suffix = tree.len(); + tree.push(Node::new(k + 2, 0)); + tree[n].edges.insert(c, suffix); + + if tree[suffix].length == 1 { + tree[suffix].suffix = EVEN_ROOT; + continue; + } + + loop { + n = tree[n].suffix; + let tree_n_length_plus_one: usize = (tree[n].length + 1).try_into().unwrap_or(0); + if let Some(b) = i.checked_sub(tree_n_length_plus_one) { + if b < s.len() && s[b] == c { + break; + } + } + } + + tree[suffix].suffix = tree[n].edges[&c]; + } + + tree +} + +fn sub_palindromes(tree: &[Node]) -> Vec { + let mut result = Vec::new(); + fn children(node: usize, p: String, tree: &[Node], result: &mut Vec) { + for (&c, &n) in &tree[node].edges { + let c = c as char; + let p_new = format!("{}{}{}", c, p, c); + result.push(p_new.clone()); + children(n, p_new, tree, result); + } + } + + children(EVEN_ROOT, String::new(), tree, &mut result); + + for (&c, &n) in &tree[ODD_ROOT].edges { + let c = c as char; + let p = c.to_string(); + result.push(p.clone()); + children(n, p, tree, &mut result); + } + + result +} + +fn main() { + let tree = eertree(b"eertree"); + let palindromes = sub_palindromes(&tree); + for palindrome in palindromes { + println!("{}", palindrome); + } +} diff --git a/Task/Egyptian-division/PARI-GP/egyptian-division.parigp b/Task/Egyptian-division/PARI-GP/egyptian-division.parigp new file mode 100644 index 0000000000..acf22d294b --- /dev/null +++ b/Task/Egyptian-division/PARI-GP/egyptian-division.parigp @@ -0,0 +1,23 @@ +myrow(powers_of2, doublings) = + { + if (dividend > doublings, + myrow(2 * powers_of2, 2 * doublings); + if (accumulator + doublings <= dividend, + answer += powers_of2; + accumulator += doublings; + ); + ); + }; + +egyptian_divrem(dividend, divisor) = +{ + local(answer, accumulator, row); + answer = 0; + accumulator = 0; + myrow(1, divisor); + [answer, dividend - accumulator]; +} + +divisor=34; +dividend=580; +print1(egyptian_divrem(dividend, divisor)); diff --git a/Task/Empty-program/Bruijn/empty-program.bruijn b/Task/Empty-program/Bruijn/empty-program.bruijn new file mode 100644 index 0000000000..42e2f47300 --- /dev/null +++ b/Task/Empty-program/Bruijn/empty-program.bruijn @@ -0,0 +1 @@ +main [0] diff --git a/Task/Empty-string/Emacs-Lisp/empty-string.l b/Task/Empty-string/Emacs-Lisp/empty-string-1.l similarity index 100% rename from Task/Empty-string/Emacs-Lisp/empty-string.l rename to Task/Empty-string/Emacs-Lisp/empty-string-1.l diff --git a/Task/Empty-string/Emacs-Lisp/empty-string-2.l b/Task/Empty-string/Emacs-Lisp/empty-string-2.l new file mode 100644 index 0000000000..909c54e808 --- /dev/null +++ b/Task/Empty-string/Emacs-Lisp/empty-string-2.l @@ -0,0 +1,5 @@ +(defvar str "" "An empty string") + +(if (length= str 0) + (message "string is empty") + (message "string is not empty")) diff --git a/Task/Empty-string/MiniScript/empty-string.mini b/Task/Empty-string/MiniScript/empty-string.mini new file mode 100644 index 0000000000..513d02ecdf --- /dev/null +++ b/Task/Empty-string/MiniScript/empty-string.mini @@ -0,0 +1,13 @@ +string.isEmpty = function + return self == "" +end function + +number.toBoolStr = function + if self == 0 then return "false" + return "true" +end function + +s = "" +t = "0" +print "'s' is empty? " + s.isEmpty.toBoolStr +print "'t' is empty? " + t.isEmpty.toBoolStr diff --git a/Task/Entropy/Elena/entropy.elena b/Task/Entropy/Elena/entropy.elena index 08426dc79f..7d16828ab0 100644 --- a/Task/Entropy/Elena/entropy.elena +++ b/Task/Entropy/Elena/entropy.elena @@ -15,7 +15,7 @@ public program() var infoC := 0.0r; var table := Dictionary.new(); - input.forEach:(ch) + input.forEach::(ch) { var n := table[ch]; if (nil == n) @@ -29,7 +29,7 @@ public program() }; var freq := 0; - table.forEach:(letter) + table.forEach::(letter) { freq := letter.toInt().realDiv(input.Length); diff --git a/Task/Entropy/Excel/entropy-1.excel b/Task/Entropy/Excel/entropy-1.excel new file mode 100644 index 0000000000..d01d139128 --- /dev/null +++ b/Task/Entropy/Excel/entropy-1.excel @@ -0,0 +1,9 @@ +=LET( +_MainS,A1, +_N,LEN(_MainS), +_Chars,UNIQUE(MID(_MainS,SEQUENCE(LEN(_MainS),1,1,1),1)), +calcH,LAMBDA(_c,(_c/_N)*LOG(_c/_N,2)), +getCount,LAMBDA(_i,LEN(_MainS)-LEN(SUBSTITUTE(_MainS,_i,""))), +_CharMap,MAP(_Chars,LAMBDA(a, calcH(getCount(a)))), +-SUM(_CharMap) +) diff --git a/Task/Entropy/Excel/entropy-2.excel b/Task/Entropy/Excel/entropy-2.excel new file mode 100644 index 0000000000..5df315aaa4 --- /dev/null +++ b/Task/Entropy/Excel/entropy-2.excel @@ -0,0 +1 @@ +ShannonEntropyH2=LAMBDA(String,LET(_MainS,String,_N,LEN(_MainS),_Chars,UNIQUE(MID(_MainS,SEQUENCE(LEN(_MainS),1,1,1),1)),calcH,LAMBDA(_c,(_c/_N)*LOG(_c/_N,2)),getCount,LAMBDA(_i,LEN(_MainS)-LEN(SUBSTITUTE(_MainS,_i,""))),_CharMap,MAP(_Chars,LAMBDA(a, calcH(getCount(a)))),-SUM(_CharMap))) diff --git a/Task/Entropy/Excel/entropy-3.excel b/Task/Entropy/Excel/entropy-3.excel new file mode 100644 index 0000000000..1e80e4e4dd --- /dev/null +++ b/Task/Entropy/Excel/entropy-3.excel @@ -0,0 +1 @@ +=ShannonEntropyH2(A1) diff --git a/Task/Entropy/K/entropy.k b/Task/Entropy/K/entropy.k new file mode 100644 index 0000000000..4d48d72d18 --- /dev/null +++ b/Task/Entropy/K/entropy.k @@ -0,0 +1,3 @@ +entropy: {(`ln[#x]-(+/{x*`ln@x}@+/{x=\:?x}x)%#x)%`ln@2} + +entropy "1223334444" diff --git a/Task/Equal-prime-and-composite-sums/EasyLang/equal-prime-and-composite-sums.easy b/Task/Equal-prime-and-composite-sums/EasyLang/equal-prime-and-composite-sums.easy new file mode 100644 index 0000000000..cd34636414 --- /dev/null +++ b/Task/Equal-prime-and-composite-sums/EasyLang/equal-prime-and-composite-sums.easy @@ -0,0 +1,50 @@ +fastfunc isprim num . + if num mod 2 = 0 and num > 2 + return 0 + . + i = 3 + while i <= sqrt num + if num mod i = 0 + return 0 + . + i += 2 + . + return 1 +. +indN = 1 ; indM = 2 +numP = 2 ; numC = 4 +sumP = 2 ; sumC = 4 +# +numfmt 0 11 +print " sum primes composites" +repeat + if sumC > sumP + repeat + numP += 1 + until isprim numP = 1 + . + sumP += numP + indN += 1 + . + if sumP > sumC + repeat + numC += 1 + until isprim numC = 0 + . + sumC += numC + indM += 1 + . + if sumP = sumC + print sumP & indN & indM + cnt += 1 + if cnt < 8 + repeat + numC += 1 + until isprim numC = 0 + . + sumC += numC + indM += 1 + . + . + until cnt >= 8 +. diff --git a/Task/Equal-prime-and-composite-sums/Python/equal-prime-and-composite-sums.py b/Task/Equal-prime-and-composite-sums/Python/equal-prime-and-composite-sums.py new file mode 100644 index 0000000000..3db02af590 --- /dev/null +++ b/Task/Equal-prime-and-composite-sums/Python/equal-prime-and-composite-sums.py @@ -0,0 +1,22 @@ +# equal_prime_comp_sums.py by Xing216 +import math +import numpy +def prime_composites(upto=50000): + nums = numpy.arange(2,upto+1) + primes=numpy.arange(3,upto+1,2) + isprime=numpy.ones((upto-1)//2,dtype=bool) + for factor in primes[:int(math.sqrt(upto))//2]: + if isprime[(factor-2)//2]: isprime[(factor*3-2)//2::factor]=0 + primes = numpy.insert(primes[isprime],0,2) + intersect = nums[numpy.in1d(nums, primes)] + mask1 = numpy.searchsorted(nums,intersect) + composites = numpy.delete(nums,mask1) + return primes, composites +primes, composites = prime_composites() +cum_primes = numpy.cumsum(primes) +cum_composites = numpy.cumsum(composites) +print("Sum | Prime Index | Composite Index") +print("------------------------------------------") +for idx, num in enumerate(cum_primes): + if num in cum_composites: + print(f"{num:10,} | {idx+1:11,} | {numpy.where(cum_composites == num)[0][0]+1:15,}") diff --git a/Task/Equilibrium-index/EasyLang/equilibrium-index.easy b/Task/Equilibrium-index/EasyLang/equilibrium-index.easy new file mode 100644 index 0000000000..22db6aad1d --- /dev/null +++ b/Task/Equilibrium-index/EasyLang/equilibrium-index.easy @@ -0,0 +1,14 @@ +func[] equind a[] . + for v in a[] + sumr += v + . + for i to len a[] + sumr -= a[i] + if suml = sumr + r[] &= i + . + suml += a[i] + . + return r[] +. +print equind [ -7 1 5 2 -4 3 0 ] diff --git a/Task/Equilibrium-index/Elena/equilibrium-index.elena b/Task/Equilibrium-index/Elena/equilibrium-index.elena index 1e97922ac9..0a3a257e70 100644 --- a/Task/Equilibrium-index/Elena/equilibrium-index.elena +++ b/Task/Equilibrium-index/Elena/equilibrium-index.elena @@ -64,5 +64,5 @@ class EquilibriumEnumerator : Enumerator public program() { EquilibriumEnumerator.new(new int[]{ -7, 1, 5, 2, -4, 3, 0 }) - .forEach:printingLn + .forEach(printingLn) } diff --git a/Task/Erd-s-Nicolas-numbers/C-sharp/erd-s-nicolas-numbers.cs b/Task/Erd-s-Nicolas-numbers/C-sharp/erd-s-nicolas-numbers.cs new file mode 100644 index 0000000000..0d9278fc1d --- /dev/null +++ b/Task/Erd-s-Nicolas-numbers/C-sharp/erd-s-nicolas-numbers.cs @@ -0,0 +1,31 @@ +using System; + +class ErdosNicolasNumbers +{ + static void Main(string[] args) + { + const int limit = 100_000_000; + + int[] divisorSum = new int[limit + 1]; + int[] divisorCount = new int[limit + 1]; + for (int i = 0; i <= limit; i++) + { + divisorSum[i] = 1; + divisorCount[i] = 1; + } + + for (int index = 2; index <= limit / 2; index++) + { + for (int number = 2 * index; number <= limit; number += index) + { + if (divisorSum[number] == number) + { + Console.WriteLine($"{number,8} equals the sum of its first {divisorCount[number],3} divisors"); + } + + divisorSum[number] += index; + divisorCount[number]++; + } + } + } +} diff --git a/Task/Erd-s-Nicolas-numbers/Python/erd-s-nicolas-numbers.py b/Task/Erd-s-Nicolas-numbers/Python/erd-s-nicolas-numbers.py new file mode 100644 index 0000000000..92ec1ca2d1 --- /dev/null +++ b/Task/Erd-s-Nicolas-numbers/Python/erd-s-nicolas-numbers.py @@ -0,0 +1,23 @@ +# erdos-nicolas.py by Xing216 +from time import perf_counter +start = perf_counter() +def get_div_cnt(n: int) -> None: + divcnt,divsum = 1,1 + lmt = n/2 + f = 2 + while True: + if f > lmt: break + if not (n % f): + divsum += f + divcnt += 1 + if divsum == n: break + f+=1 + print(f"{n:>8} equals the sum of its first {divcnt} divisors") +max_number = 91963649 +dsum = [1 for _ in range(max_number+1)] +for i in range(2, max_number + 1): + for j in range(i + i, max_number + 1, i): + if (dsum[j] == j): get_div_cnt(j) + dsum[j] += i +done = perf_counter() - start +print(f"Done in: {done:.3f}s") diff --git a/Task/Euler-method/Dart/euler-method.dart b/Task/Euler-method/Dart/euler-method.dart new file mode 100644 index 0000000000..7a812bbd9a --- /dev/null +++ b/Task/Euler-method/Dart/euler-method.dart @@ -0,0 +1,44 @@ +import 'dart:math'; +import "dart:io"; + +const double k = 0.07; +const double initialTemp = 100.0; +const double finalTemp = 20.0; +const int startTime = 0; +const int endTime = 100; + +void ivpEuler(double Function(double, double) function, double initialValue, int step) { + stdout.write(' Step ${step.toString().padLeft(2)}: '); + var y = initialValue; + for (int t = startTime; t <= endTime; t += step) { + if (t % 10 == 0) { + stdout.write(y.toStringAsFixed(3).padLeft(7)); + } + y += step * function(t.toDouble(), y); + } + print(''); +} + +void analytic() { + stdout.write(' Time: '); + for (int t = startTime; t <= endTime; t += 10) { + stdout.write(t.toString().padLeft(7)); + } + stdout.write('\nAnalytic: '); + for (int t = startTime; t <= endTime; t += 10) { + var temp = finalTemp + (initialTemp - finalTemp) * exp(-k * t); + stdout.write(temp.toStringAsFixed(3).padLeft(7)); + } + print(''); +} + +double cooling(double t, double temp) { + return -k * (temp - finalTemp); +} + +void main() { + analytic(); + ivpEuler(cooling, initialTemp, 2); + ivpEuler(cooling, initialTemp, 5); + ivpEuler(cooling, initialTemp, 10); +} diff --git a/Task/Euler-method/MATLAB/euler-method.m b/Task/Euler-method/MATLAB/euler-method.m new file mode 100644 index 0000000000..14e8b6882a --- /dev/null +++ b/Task/Euler-method/MATLAB/euler-method.m @@ -0,0 +1,40 @@ +clear all;close all;clc; +format longG; + +% Main Script +for h = [5, 10] + fprintf('Step %d:\n\n', h); + tabular(15, 'Time', 'Euler', 'Analytic'); + T0 = 100.0; + t0 = 0; + t1 = 100; + T = euler(@(T) -0.07 * (T - 20.0), T0, t0, t1, h); + for i = 1:length(T) + t = (i-1) * h; + analytic = 20.0 + 80.0 * exp(-0.07 * t); + tabular(15, t, round(T(i), 6), round(analytic, 6)); + end + fprintf('\n'); +end + +function T = euler(f, T0, t0, t1, h) + % EULER A simple implementation of Euler's method for solving ODEs + % f - function handle for the derivative + % T0 - initial temperature + % t0, t1 - start and end times + % h - step size + T = T0; + for t = t0:h:t1 + T(end+1) = T(end) + h * f(T(end)); + end +end + +function tabular(width, varargin) + % TABULAR Prints a series of values in a tabular form + % width - cell width + % varargin - variable number of arguments representing cells + for i = 1:length(varargin) + fprintf('%-*s', width, num2str(varargin{i})); + end + fprintf('\n'); +end diff --git a/Task/Euler-method/Uiua/euler-method.uiua b/Task/Euler-method/Uiua/euler-method.uiua new file mode 100644 index 0000000000..0d577690a3 --- /dev/null +++ b/Task/Euler-method/Uiua/euler-method.uiua @@ -0,0 +1,22 @@ +"Euler Solution" +T ← 100 # initial starting temp +TR ← 20 # room temp +TMINUSTR ← - TR T +h ← 10 # step size +k ← 0.07 # coefficent +TEND ← 100 # end time +n ← ÷ h 100 # steps +# inital starting point +T +. +# .. clone the top of stack and take if for next step +# repeat the steps n times with ⍥ +Solution ← [⍥(.. - × h × k - TR)]+ n 1 +⇌ ⊂ Solution T + +# analytical solution +"Analytical Solution" +# apply function to LIST +List ← × k × h ⇡n +# Analytical solution applied ++ TR × TMINUSTR ⁿ ¯List e diff --git a/Task/Eulers-constant-0.5772.../EasyLang/eulers-constant-0.5772....easy b/Task/Eulers-constant-0.5772.../EasyLang/eulers-constant-0.5772....easy new file mode 100644 index 0000000000..343c268ced --- /dev/null +++ b/Task/Eulers-constant-0.5772.../EasyLang/eulers-constant-0.5772....easy @@ -0,0 +1,12 @@ +fastfunc gethn n . + i = 1 + while i <= n + hn += 1 / i + i += 1 + . + return hn +. +e = 2.718281828459045235 +n = 10e8 +numfmt 9 0 +print gethn n - log10 n / log10 e diff --git a/Task/Eulers-constant-0.5772.../Scala/eulers-constant-0.5772....scala b/Task/Eulers-constant-0.5772.../Scala/eulers-constant-0.5772....scala new file mode 100644 index 0000000000..b2abef6885 --- /dev/null +++ b/Task/Eulers-constant-0.5772.../Scala/eulers-constant-0.5772....scala @@ -0,0 +1,16 @@ +/** + * Using a simple formula derived from Hurwitz zeta function, + * as described on https://en.wikipedia.org/wiki/Euler%27s_constant, + * gives a result accurate to 11 decimal places: 0.57721566490... + */ + +object EulerConstant extends App { + + println(gamma(1_000_000)) + + private def gamma(N: Int): Double = { + val sumOverN = (1 to N).map(1.0 / _).sum + sumOverN - Math.log(N) - 1.0 / (2 * N) + } + +} diff --git a/Task/Eulers-sum-of-powers-conjecture/C++/eulers-sum-of-powers-conjecture-6.cpp b/Task/Eulers-sum-of-powers-conjecture/C++/eulers-sum-of-powers-conjecture-6.cpp new file mode 100644 index 0000000000..9f6e3ff81c --- /dev/null +++ b/Task/Eulers-sum-of-powers-conjecture/C++/eulers-sum-of-powers-conjecture-6.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include +#include + +template static constexpr T power(T base) { + if constexpr (n == 0) + return 1; + else if constexpr (n == 1) + return base; + else if constexpr (n & 1) + return power(base * base) * base; + else + return power(base * base); +} + +static constexpr int count = 1024; +static constexpr uint64_t count_diff = []() { + // finds something that looks kinda sorta prime. + const uint64_t coprime_to_this = 2llu * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41 * 43 * 59; + // we make this oversized to reduce collisions and just hope it fits in cache. + uint64_t guess = 7 * count * count; + for (; std::gcd(guess, coprime_to_this) > 1; ++guess) + ; + return guess; +}(); + +static constexpr int fast_integer_root5(const double x) { + constexpr uint64_t magic = 3685583637919522816llu; + uint64_t x_i = std::bit_cast(x); + x_i /= 5; + x_i += magic; + const double x_f = std::bit_cast(x_i); + const double x5 = power<5>(x_f); + return x_f * ((x - x5) / (3 * x5 + 2 * x)) + (x_f + .5); +} + +static constexpr uint64_t hash(uint64_t h) { return h % count_diff; } + +void euler() { + std::array pow5; + for (int64_t i = 0; i < count; i++) + pow5[i] = power<5>(i); + + // build hash table + constexpr int oversize_fudge = 8; + std::unique_ptr differences = std::make_unique(count_diff + oversize_fudge); + std::fill(differences.get(), differences.get() + count_diff + oversize_fudge, 0); + for (int64_t n = 4; n < count; n++) + for (int64_t d = 3; d < n; d++) { + uint64_t h = hash(pow5[n] - pow5[d]); + for (; differences[h]; ++h) + if (h >= count_diff + oversize_fudge - 2) { + std::cerr << "too many collisions; increase fudge factor or hash table size\n"; + return; + } + differences[h] = d; + if (h >= count_diff) + differences[h - count_diff] = d; + } + + // brute force a,b,c + const int a_max = fast_integer_root5(.25 * pow5.back()); + for (int a = 0; a <= a_max; a++) { + const int b_max = fast_integer_root5((1.0 / 3.0) * (pow5.back() - pow5[a])); + for (int b = a; b <= b_max; b++) { + const int64_t a5_p_b5 = pow5[a] + pow5[b]; + const int c_max = fast_integer_root5(.5 * (pow5.back() - a5_p_b5)); + for (int c = b; c <= c_max; c++) { + // lookup d in hash table + const int64_t n5_minus_d5 = a5_p_b5 + pow5[c]; + //this loop is O(1) + for (uint64_t h = hash(n5_minus_d5); differences[h]; ++h) { + if (const int d = differences[h]; d >= c) + // calculate n from d + if (const int n = fast_integer_root5(n5_minus_d5 + pow5[d]); + // check whether this is a solution + n < count && n5_minus_d5 == pow5[n] - pow5[d] && d != n) + std::cout << a << "^5 + " << b << "^5 + " << c << "^5 + " << d << "^5 = " << n << "^5\t" + << pow5[a] + pow5[b] + pow5[c] + pow5[d] << " = " << pow5[n] << '\n'; + } + } + } + } +} + +int main() { + std::ios::sync_with_stdio(false); + euler(); + return 0; +} diff --git a/Task/Evaluate-binomial-coefficients/Standard-ML/evaluate-binomial-coefficients.ml b/Task/Evaluate-binomial-coefficients/Standard-ML/evaluate-binomial-coefficients.ml new file mode 100644 index 0000000000..5c7ded2667 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Standard-ML/evaluate-binomial-coefficients.ml @@ -0,0 +1,5 @@ +fun binomial n k = + if k > n then 0 else + let fun f (_, 0) = 1 + | f (i, d) = f (i + 1, d - 1) * i div d + in f (n - k + 1, k) end diff --git a/Task/Even-or-odd/Swift/even-or-odd.swift b/Task/Even-or-odd/Swift/even-or-odd.swift index a697ee6e29..d1923eb659 100644 --- a/Task/Even-or-odd/Swift/even-or-odd.swift +++ b/Task/Even-or-odd/Swift/even-or-odd.swift @@ -1,13 +1,3 @@ -func isEven(n:Int) -> Bool { +// Swift has Int.isMultiple(of:Int) -> Bool - // Bitwise check - if (n & 1 != 0) { - return false - } - - // Mod check - if (n % 2 != 0) { - return false - } - return true -} +var isEven: (_:Int) -> Bool = {$0.isMultiple(of: 2)} diff --git a/Task/Evolutionary-algorithm/Dart/evolutionary-algorithm.dart b/Task/Evolutionary-algorithm/Dart/evolutionary-algorithm.dart new file mode 100644 index 0000000000..34a176b6c5 --- /dev/null +++ b/Task/Evolutionary-algorithm/Dart/evolutionary-algorithm.dart @@ -0,0 +1,63 @@ +import 'dart:math'; + +class EvoAlgo { + static final String target = "METHINKS IT IS LIKE A WEASEL"; + static final List possibilities = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".split(''); + static int c = 100; // Number of spawn per generation + static double minMutateRate = 0.09; + static int perfectFitness = target.length; + static String parent = ''; + static Random rand = Random(); + + static int fitness(String trial) { + int retVal = 0; + for (int i = 0; i < trial.length; i++) { + if (trial[i] == target[i]) retVal++; + } + return retVal; + } + + static double newMutateRate() { + return (((perfectFitness - fitness(parent)) / perfectFitness) * (1 - minMutateRate)); + } + + static String mutate(String parent, double rate) { + String retVal = ''; + for (int i = 0; i < parent.length; i++) { + retVal += (rand.nextDouble() <= rate) + ? possibilities[rand.nextInt(possibilities.length)] + : parent[i]; + } + return retVal; + } + + static void main() { + parent = mutate(target, 1); + int iter = 0; + while (parent != target) { + double rate = newMutateRate(); + iter++; + if (iter % 100 == 0) { + print('$iter: $parent, fitness: ${fitness(parent)}, rate: $rate'); + } + String bestSpawn; + int bestFit = 0; + for (int i = 0; i < c; i++) { + String spawn = mutate(parent, rate); + int fit = fitness(spawn); + if (fit > bestFit) { + bestSpawn = spawn; + bestFit = fit; + } + } + if (bestFit > fitness(parent)) { + parent = bestSpawn; + } + } + print('$parent, $iter'); + } +} + +void main() { + EvoAlgo.main(); +} diff --git a/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena b/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena index 18675d0166..39a52319eb 100644 --- a/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena +++ b/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena @@ -16,13 +16,13 @@ randomChar extension evoHelper { randomString() - = 0.repeatTill(self).selectBy:(x => randomChar).summarize(new StringWriter()); + = 0.repeatTill(self).selectBy::(x => randomChar).summarize(new StringWriter()); fitnessOf(s) = self.zipBy(s, (a,b => a==b ? 1 : 0)).summarize(new Integer()).toInt(); mutate(p) - = self.selectBy:(ch => rnd.nextReal() <= p ? randomChar : ch).summarize(new StringWriter()); + = self.selectBy::(ch => rnd.nextReal() <= p ? randomChar : ch).summarize(new StringWriter()); } class EvoAlgorithm : Enumerator @@ -47,9 +47,9 @@ class EvoAlgorithm : Enumerator if (_target == _current) { ^ false }; - auto variants := Array.allocate(_variantCount).populate:(x => _current.mutate:P ); + auto variants := Array.allocate(_variantCount).populate::(x => _current.mutate(P) ); - _current := variants.sort:(a,b => a.fitnessOf:Target > b.fitnessOf:Target ).at:0; + _current := variants.sort::(a,b => a.fitnessOf(Target) > b.fitnessOf(Target) ).at(0); ^ true } @@ -65,7 +65,7 @@ class EvoAlgorithm : Enumerator public program() { var attempt := new Integer(); - EvoAlgorithm.new(Target,C).forEach:(current) + EvoAlgorithm.new(Target,C).forEach::(current) { console .printPaddingLeft(10,"#",attempt.append(1)) diff --git a/Task/Evolutionary-algorithm/Jq/evolutionary-algorithm.jq b/Task/Evolutionary-algorithm/Jq/evolutionary-algorithm.jq new file mode 100644 index 0000000000..5800f10a0f --- /dev/null +++ b/Task/Evolutionary-algorithm/Jq/evolutionary-algorithm.jq @@ -0,0 +1,64 @@ +# Assumption: input consists of random three-digit numbers i.e. 000 to 999 +def rand: input; + +def set: "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; + +def abs: + if . < 0 then -. else . end; + +def ichar: + if type == "number" then . else explode[0] end; + +# Output: a pseudo-random character from set. +# $n should be a random number drawn from range(0; N) inclusive where N > set|length +# Input: an admissible character from `set` (ignored in this implementation) +def shift($n): + ($n % (set|length)) as $i + | set[$i:$i+1]; + +# fitness: 0 indicates a perfect fit; greater numbers indicate worse fit. +def fitness($gold): + def diff($c; $d): ($c|ichar) - ($d|ichar) | abs; + . as $in + | reduce range(0;length) as $i (0; . + diff($in[$i:$i+1]; $gold[$i:$i+1])); + +# Input: a string +# Output: a mutation of . such that each character is mutated with probability $r +def mutate($r): + # Output: a pseudo-random character from set + # $n should be a random number drawn from range(0; N) inclusive where N > set|length + def letter($n): + ($n % (set|length)) as $i + | set[$i:$i+1]; + + . as $p + | reduce range(0;length) as $i (""; + rand as $rand + | if ($rand/1000) < $r then . + letter($rand) + else . + $p[$i:$i+1] + end ); + +# An array of $n children of the parent provided as input; $r is the mutation probability +def children($n; $r): + [range(0;$n) as $i | mutate($r)]; + +# Input: a "parent" +# Output: a single string +def next_generation($gold; $r): + ([.] + children(100; $r)) + | min_by( fitness($gold) ); + +# Evolve towards the target string provided as input, using $r as the mutation rate; +# `recurse` is used in order to show progress conveniently. +def evolve($r): + . as $gold + | (set|length) as $s + | (reduce range(0; $n) as $i (""; (rand % $s) as $j | . + set[$j:$j+1])) as $string + | {count: 0, $string } + | recurse ( + if .string | fitness($gold) == 0 then empty + else .string |= next_generation($gold; $r) + | .count += 1 + end); + +"METHINKS IT IS LIKE A WEASEL" | evolve(0.05) diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena index 06f339514f..aed2491fc4 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena @@ -33,7 +33,7 @@ singleton Exceptions foo() { - for(i := 0, i < 2, i := i + 1) + for(i := 0; i < 2; i := i + 1) { try { diff --git a/Task/Execute-Brain-/Refal/execute-brain-.refal b/Task/Execute-Brain-/Refal/execute-brain-.refal new file mode 100644 index 0000000000..8fcac88e4c --- /dev/null +++ b/Task/Execute-Brain-/Refal/execute-brain-.refal @@ -0,0 +1,115 @@ +$ENTRY Go { + , : e.File + , : e.Source + , : { + F e.Error = ; + T e.Prog = ; + }; +}; + +ReadFile { + s.Chan e.File = + ; + (s.Chan), : { + 0 = ; + e.Line = + }; +} + +SanitizeBF { + = ; + s.C e.X, '+-<>.,[]': e.L s.C e.R = s.C ; + s.C e.X = ; +}; + +ParseBF { + e.X, : { + T = T ; + e.Err = e.Err; + }; +}; + +CheckLoops { + (0) = T; + (s.N) = F 'Mismatched ['; + (0) ']' e.X = F 'Mismatched ]'; + (s.N) '[' e.X = ) e.X>; + (s.N) ']' e.X = ) e.X>; + (s.N) s.I e.X = ; + e.X = ; +}; + +ParseLoops { + (e.X) (e.C) = e.X e.C; + (e.R) (e.Cur) '[' e.Prog = ; + (e.R (e.Last)) (e.Cur) ']' e.Prog = ; + (e.R) (e.Cur) s.Instr e.Prog = ; +} + +RunProgram { + e.Prog, (() 0 ()): t.Tape, + (() ()): t.IObuf, + (t.Tape t.IObuf): t.State, + : (t.TapeOut t.IObufOut), + t.IObufOut: ((e.In) (e.Out)), + e.Out: { + = ; + e.X = ; + }; +}; + +RunBF { + t.State = t.State; + t.State t.Step e.Prog = e.Prog>; +}; + +StepBF { + (t.Tape t.IObuf) '+' = ( t.IObuf); + (t.Tape t.IObuf) '-' = ( t.IObuf); + (t.Tape t.IObuf) '<' = ( t.IObuf); + (t.Tape t.IObuf) '>' = ( t.IObuf); + t.State ',' = ; + t.State '.' = ; + t.State (e.Loop), t.State: ((t.L 0 t.R) t.IObuf) = t.State; + t.State (e.Loop), : t.Newstate = ; +}; + +TapeLeft { + ((e.L s.N) s.C (e.R)) = ((e.L) s.N (s.C e.R)); + (() s.C (e.R)) = (() 0 (s.C e.R)); +}; + +TapeRight { + ((e.L) s.C (s.N e.R)) = ((e.L s.C) s.N (e.R)); + ((e.L) s.C ()) = ((e.L s.C) 0 ()); +}; + +TapeF { + s.F ((e.L) s.C (e.R)) = ((e.L) (e.R)); +}; + +BFIn { + (t.Tape t.IObuf), t.Tape: (t.L s.C t.R), + t.IObuf: (t.In t.Out), + t.In: { + (s.Char e.Rest), (t.L s.Char t.R): t.Newtape, + ((e.Rest) t.Out): t.NewIO + = (t.Newtape t.NewIO); + (), : { + 0 = ((t.L 0 t.R) t.IObuf); + e.Line = 10) t.Out))>; + }; + }; +}; + +BFOut { + (t.Tape t.IObuf), t.Tape: (t.L s.C t.R), + t.IObuf: (t.In t.Out), + s.C: { + 10, t.Out: (e.Line) = > (t.Tape (t.In ())); + s.C, t.Out: (e.Line) = (t.Tape (t.In (e.Line s.C))); + }; +}; + +Inc { s.X = 256>; }; +Dec { s.X = 256>; }; diff --git a/Task/Execute-SNUSP/11l/execute-snusp.11l b/Task/Execute-SNUSP/11l/execute-snusp.11l index 5bf2bdb258..3180c22226 100644 --- a/Task/Execute-SNUSP/11l/execute-snusp.11l +++ b/Task/Execute-SNUSP/11l/execute-snusp.11l @@ -40,7 +40,7 @@ F snusp(store, code) ‘,’ ds[dp] = Byte(:stdin.read(1).code) ‘/’ - id = (-)id + id = ~id ‘\’ id (+)= 1 ‘!’ diff --git a/Task/Execute-SNUSP/EasyLang/execute-snusp.easy b/Task/Execute-SNUSP/EasyLang/execute-snusp.easy index 0a6abce0cd..dde98b1d48 100644 --- a/Task/Execute-SNUSP/EasyLang/execute-snusp.easy +++ b/Task/Execute-SNUSP/EasyLang/execute-snusp.easy @@ -60,4 +60,4 @@ input_data /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ - \==-<<<<+>+++/ /=.>.+>.--------.-/` + \==-<<<<+>+++/ /=.>.+>.--------.-/ diff --git a/Task/Execute-a-Markov-algorithm/Refal/execute-a-markov-algorithm.refal b/Task/Execute-a-Markov-algorithm/Refal/execute-a-markov-algorithm.refal new file mode 100644 index 0000000000..482e4b3e3a --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Refal/execute-a-markov-algorithm.refal @@ -0,0 +1,57 @@ +$ENTRY Go { + , : e.File + , : e.Input + , : e.Lines + , : e.Rules + , : e.Result + = ; +}; + +Each { + s.F = ; + s.F (e.I) e.R = ; +}; + +ReadLines { + s.Chan e.File = + ; + (s.Chan), : { + 0 = ; + e.Line = (e.Line) ; + }; +}; + +ParseRule { + = (Empty); + '#' e.X = (Empty); + e.Pat ' -> ' e.Rep, + : e.TrPat, + : e.TrRep, + e.TrRep: { + '.' e.R = (Term (e.Pat) (e.R)); + e.R = (Nonterm (e.Pat) (e.R)); + }; +}; + +ApplyRule { + (s.Type (e.Pat) (e.Rep)) e.Subj, + e.Subj: e.X e.Pat e.Y = s.Type e.X e.Rep e.Y; + t.Rule e.Subj = NoMatch e.Subj; +}; + +Apply { + (e.Rules) () e.Subj = e.Subj; + (e.Rules) (t.Rule e.Rest) e.Subj, + : { + NoMatch e.Subj = ; + Term e.Res = e.Res; + Nonterm e.Res = ; + }; + (e.Rules) e.Subj = ; +}; + +Trim { + ' ' e.X = ; + e.X ' ' = ; + e.X = e.X; +}; diff --git a/Task/Exponentiation-operator/MiniScript/exponentiation-operator.mini b/Task/Exponentiation-operator/MiniScript/exponentiation-operator.mini new file mode 100644 index 0000000000..e082de1366 --- /dev/null +++ b/Task/Exponentiation-operator/MiniScript/exponentiation-operator.mini @@ -0,0 +1,58 @@ +import "qa" + +number.isInteger = function + return self == floor(self) +end function + +ipow = function(base, exp) + if not base.isInteger then qa.abort("ipow must have an integer base") + if not exp.isInteger then qa.abort("ipow must have an integer exponent") + if base == 1 or exp == 0 then return 1 + if base == -1 then + if exp%2 == 0 then return 1 + return -1 + end if + if exp < 0 then qa.abort("ipow cannot have a negative exponent") + ans = 1 + e = exp + while e > 1 + if e%2 == 1 then ans *= base + e = floor(e/2) + base *= base + end while + return ans * base +end function + +fpow = function(base, exp) + if not exp.isInteger then qa.abort("fpow must have an integer exponent") + ans = 1.0 + e = exp + if e < 0 then + base = 1 / base + e = -e + end if + while e > 0 + if e%2 == 1 then ans *= base + e = floor(e/2) + base *= base + end while + return ans +end function + +print "Using the reimplemented functions:" +print " 2 ^ 3 = " + ipow(2, 3) +print " 1 ^ -10 = " + ipow(1, -10) +print " -1 ^ -3 = " + ipow(-1, -3) +print +print " 2.0 ^ -3 = " + fpow(2.0, -3) +print " 1.5 ^ 0 = " + fpow(1.5, 0) +print " 4.5 ^ 2 = " + fpow(4.5, 2) +print +print "Using the ^ operator:" +print " 2 ^ 3 = " + 2 ^ 3 +print " 1 ^ -10 = " + 1 ^ (-10) +print " -1 ^ -3 = " + (-1) ^ (-3) +print +print " 2.0 ^ -3 = " + 2.0 ^ (-3) +print " 1.5 ^ 0 = " + 1.5 ^ 0 +print " 4.5 ^ 2 = " + 4.5 ^ 2 diff --git a/Task/Extend-your-language/Langur/extend-your-language-1.langur b/Task/Extend-your-language/Langur/extend-your-language-1.langur index f48ac0759d..45647137b3 100644 --- a/Task/Extend-your-language/Langur/extend-your-language-1.langur +++ b/Task/Extend-your-language/Langur/extend-your-language-1.langur @@ -1,4 +1,4 @@ -given .x nxor, .y nxor { +switch[and] .x nxor, .y nxor { case true: ... # both true case true, false: ... # first true, second false case false, true: ... # first false, second true diff --git a/Task/Extend-your-language/Langur/extend-your-language-2.langur b/Task/Extend-your-language/Langur/extend-your-language-2.langur index 89e7a714d9..e5ec4f35b7 100644 --- a/Task/Extend-your-language/Langur/extend-your-language-2.langur +++ b/Task/Extend-your-language/Langur/extend-your-language-2.langur @@ -1,4 +1,4 @@ -given .x, .y { +switch[and] .x, .y { case true: ... # both true case true, false: ... # first true, second false case false, true: ... # first false, second true diff --git a/Task/Extreme-floating-point-values/MiniScript/extreme-floating-point-values.mini b/Task/Extreme-floating-point-values/MiniScript/extreme-floating-point-values.mini new file mode 100644 index 0000000000..6ddd323057 --- /dev/null +++ b/Task/Extreme-floating-point-values/MiniScript/extreme-floating-point-values.mini @@ -0,0 +1,22 @@ +import "listUtil" + +toBoolStr = function(n) + if n == 0 then return "false" + return "true" +end function + +// create 'extreme' values from 'normal' values +negZero = -0 +inf = 1 / 0 +negInf = -1 / 0 +nan = 0 / 0 + +// print them and do some arithmetic on them +print [inf, negInf, nan, negZero] +print [inf + inf, negInf + inf, inf * nan, nan * nan] +print [inf/inf, negInf/2, nan + inf, negZero/0] + +// show some comparisons +comps = [negZero == 0, inf == -inf, inf == nan, nan == nan] +comps.apply @toBoolStr +print comps diff --git a/Task/Extreme-floating-point-values/Standard-ML/extreme-floating-point-values-1.ml b/Task/Extreme-floating-point-values/Standard-ML/extreme-floating-point-values-1.ml new file mode 100644 index 0000000000..a8273663f8 --- /dev/null +++ b/Task/Extreme-floating-point-values/Standard-ML/extreme-floating-point-values-1.ml @@ -0,0 +1,20 @@ +let val inf = 1.0/0.0 + val ninf = ~1.0/0.0 + val nzero = ~0.0 + val nan = 0.0/0.0 + fun f (s, x) = print (s ^ " \t= " ^ Real.toString x ^ "\n") + fun g (s, x) = print (s ^ " \t= " ^ Bool.toString x ^ "\n") +in app f [("positive infinity", inf), + ("negative infinity", ninf), + ("negative zero", nzero), + ("not a number", nan), + ("+inf + 2.0", inf + 2.0), + ("+inf - 10.1", inf - 10.1), + ("+inf + -inf", inf + ninf), + ("0.0 * +inf", 0.0 * inf), + ("1.0/-0.0", 1.0 / nzero), + ("NaN + 1.0", nan + 1.0), + ("NaN + NaN", nan + nan)]; + app g [("NaN == NaN", Real.==(nan, nan)), + ("0.0 == -0.0", Real.==(0.0, nzero))] +end diff --git a/Task/Extreme-floating-point-values/Standard-ML/extreme-floating-point-values-2.ml b/Task/Extreme-floating-point-values/Standard-ML/extreme-floating-point-values-2.ml new file mode 100644 index 0000000000..49ce9643af --- /dev/null +++ b/Task/Extreme-floating-point-values/Standard-ML/extreme-floating-point-values-2.ml @@ -0,0 +1,13 @@ +positive infinity = inf +negative infinity = ~inf +negative zero = ~0.0 +not a number = nan ++inf + 2.0 = inf ++inf - 10.1 = inf ++inf + -inf = nan +0.0 * +inf = nan +1.0/-0.0 = ~inf +NaN + 1.0 = nan +NaN + NaN = nan +NaN == NaN = false +0.0 == -0.0 = true diff --git a/Task/FASTA-format/EasyLang/fasta-format.easy b/Task/FASTA-format/EasyLang/fasta-format.easy new file mode 100644 index 0000000000..664cc26fe4 --- /dev/null +++ b/Task/FASTA-format/EasyLang/fasta-format.easy @@ -0,0 +1,20 @@ +repeat + s$ = input + until s$ = "" + if substr s$ 1 1 = ">" + if stat = 1 + print "" + . + stat = 1 + print s$ + else + write s$ + . +. +input_data +>Rosetta_Example_1 +THERECANBENOSPACE +>Rosetta_Example_2 +THERECANBESEVERAL +LINESBUTTHEYALLMUST +BECONCATENATED diff --git a/Task/FASTA-format/Oberon/fasta-format.oberon b/Task/FASTA-format/Oberon/fasta-format.oberon new file mode 100644 index 0000000000..460d12be0f --- /dev/null +++ b/Task/FASTA-format/Oberon/fasta-format.oberon @@ -0,0 +1,39 @@ +MODULE Fasta; + +IMPORT Files, Streams, Strings, Commands; + +PROCEDURE PrintOn*(filename: ARRAY OF CHAR; wr: Streams.Writer); +VAR + rd: Files.Reader; + f: Files.File; + line: ARRAY 1024 OF CHAR; + res: BOOLEAN; +BEGIN + f := Files.Old(filename); + ASSERT(f # NIL); + NEW(rd,f,0); + res := rd.GetString(line); + WHILE rd.res # Streams.EOF DO + IF line[0] = '>' THEN + wr.Ln; + wr.String(Strings.Substring2(1,line)^); + wr.String(": ") + ELSE + wr.String(line) + END; + res := rd.GetString(line) + END +END PrintOn; + +PROCEDURE Do*; +VAR + ctx: Commands.Context; + filename: ARRAY 256 OF CHAR; + res: BOOLEAN +BEGIN + ctx := Commands.GetContext(); + res := ctx.arg.GetString(filename); + PrintOn(filename,ctx.out) +END Do; + +END Fasta. diff --git a/Task/FASTA-format/REXX/fasta-format-1.rexx b/Task/FASTA-format/REXX/fasta-format-1.rexx index 710c26e65d..a16452ac31 100644 --- a/Task/FASTA-format/REXX/fasta-format-1.rexx +++ b/Task/FASTA-format/REXX/fasta-format-1.rexx @@ -1,16 +1,24 @@ -/*REXX program reads a (bio-informational) FASTA file and displays the contents. */ -parse arg iFID . /*iFID: the input file to be read. */ -if iFID=='' then iFID='FASTA.IN' /*Not specified? Then use the default.*/ -name= /*the name of an output file (so far). */ -$= /*the value of the output file's stuff.*/ - do while lines(iFID)\==0 /*process the FASTA file contents. */ - x=strip( linein(iFID), 'T') /*read a line (a record) from the file,*/ - /*───────── and strip trailing blanks. */ - if left(x, 1)=='>' then do - if $\=='' then say name':' $ - name=substr(x, 2) - $= - end - else $=$ || x - end /*j*/ /* [↓] show output of last file used. */ -if $\=='' then say name':' $ /*stick a fork in it, we're all done. */ +/*REXX program reads a (bio-informational) FASTA file and displays the contents. */ +Parse Arg ifid . /* iFID: the input file to be read */ +If ifid=='' Then + ifid='FASTA.IN' /* Not specified? Then use the default */ +name='' /* the name of an output file (so far) */ +d='' /* the value of the output file's */ +Do While lines(ifid)\==0 /* process the FASTA file contents */ + x=strip(linein(ifid),'T') /* read a line (a record) from the input */ + /* and strip trailing blanks */ + If left(x,1)=='>' Then Do /* a new file id */ + Call out /* show output name and data */ + name=substr(x,2) /* and get the new (or first) output name */ + d='' /* start with empty contents */ + End + Else /* a line with data */ + d=d||x /* append it to output */ + End +Call out /* show output of last file used. */ +Exit + +out: +If d\=='' Then /* if there ara data */ + Say name':' d /* show output name and data */ +Return diff --git a/Task/FASTA-format/REXX/fasta-format-2.rexx b/Task/FASTA-format/REXX/fasta-format-2.rexx index 7f9821b0ab..bd0396040b 100644 --- a/Task/FASTA-format/REXX/fasta-format-2.rexx +++ b/Task/FASTA-format/REXX/fasta-format-2.rexx @@ -1,22 +1,28 @@ -/*REXX program reads a (bio-informational) FASTA file and displays the contents. */ -parse arg iFID . /*iFID: the input file to be read. */ -if iFID=='' then iFID='FASTA2.IN' /*Not specified? Then use the default.*/ -name= /*the name of an output file (so far). */ -$= /*the value of the output file's stuff.*/ - do while lines(iFID)\==0 /*process the FASTA file contents. */ - x=strip( linein(iFID), 'T') /*read a line (a record) from the file,*/ - /*───────── and strip trailing blanks. */ - if x=='' then iterate /*If the line is all blank, ignore it. */ - if left(x, 1)==';' then do - if name=='' then name=substr(x,2) - say x - iterate - end - if left(x, 1)=='>' then do - if $\=='' then say name':' $ - name=substr(x, 2) - $= - end - else $=space($ || translate(x, , '*'), 0) - end /*j*/ /* [↓] show output of last file used. */ -if $\=='' then say name':' $ /*stick a fork in it, we're all done. */ +/*REXX program reads a (bio-informational) FASTA file and displays the contents. */ +Parse Arg iFID . /*iFID: the input file to be read. */ +If iFID=='' Then iFID='FASTA2.IN' /*Not specified? Then use the default.*/ +name='' /*the name of an output file (so far). */ +data='' + /*the value of the output file's stuff.*/ +Do While lines(iFID)\==0 /*process the FASTA file contents. */ + x=strip(linein(iFID),'T') /*read a line (a record) from the file,*/ + /*--------- and strip trailing blanks. */ + Select + When x=='' Then /* If the line is all blank, */ + Nop /* ignore it. */ + When left(x,1)==';' Then Do + If name=='' Then name=substr(x,2) + Say x + End + When left(x,1)=='>' Then Do + If data\=='' Then + Say name':' data + name=substr(x,2) + data='' + End + Otherwise + data=space(data||translate(x, ,'*'),0) + End + End +If data\=='' Then + Say name':' data /* [?] show output of last file used. */ diff --git a/Task/FASTA-format/Smalltalk/fasta-format.st b/Task/FASTA-format/Smalltalk/fasta-format.st new file mode 100644 index 0000000000..584ee9a978 --- /dev/null +++ b/Task/FASTA-format/Smalltalk/fasta-format.st @@ -0,0 +1,10 @@ +FileLocator home / aFilename readStreamDo: [ :stream | + [ stream atEnd ] whileFalse: [ + | line | + ((line := stream nextLine) beginsWith: '>') + ifTrue: [ + Transcript + cr; + show: (line copyFrom: 2 to: line size); + show: ': ' ] + ifFalse: [ Transcript show: line ] ] ] diff --git a/Task/Factorial-primes/Mathematica/factorial-primes.math b/Task/Factorial-primes/Mathematica/factorial-primes.math new file mode 100644 index 0000000000..75ebdcc718 --- /dev/null +++ b/Task/Factorial-primes/Mathematica/factorial-primes.math @@ -0,0 +1,15 @@ +LimitedPrint[n_] := Module[{s = IntegerString[n], len}, + len = StringLength[s]; + If[len <= 40, s, StringJoin[StringTake[s, 20], "...", StringTake[s, -20], " (", ToString[len], " digits)"]] +] + +ShowFactorialPrimes[N_] := Module[{f}, + Do[ + f = Factorial[i]; + If[PrimeQ[f - 1], Print[IntegerString[i, 10, 3], "! - 1 -> ", LimitedPrint[f - 1]]]; + If[PrimeQ[f + 1], Print[IntegerString[i, 10, 3], "! + 1 -> ", LimitedPrint[f + 1]]], + {i, 1, N} + ] +] + +ShowFactorialPrimes[1000] diff --git a/Task/Factorial/APL/factorial-4.apl b/Task/Factorial/APL/factorial-4.apl new file mode 100644 index 0000000000..97b8778c57 --- /dev/null +++ b/Task/Factorial/APL/factorial-4.apl @@ -0,0 +1,3 @@ + fac←{⍵>1 : ⍵×fac ⍵-1 ⋄ 1} + fac 5 +120 diff --git a/Task/Factorial/Bruijn/factorial.bruijn b/Task/Factorial/Bruijn/factorial.bruijn new file mode 100644 index 0000000000..5fe7e558e6 --- /dev/null +++ b/Task/Factorial/Bruijn/factorial.bruijn @@ -0,0 +1,5 @@ +:import std/Math . + +factorial [∏ (+1) → 0 | [0]] + +:test ((factorial (+10)) =? (+3628800)) ([[1]]) diff --git a/Task/Factorial/Langur/factorial-1.langur b/Task/Factorial/Langur/factorial-1.langur index bc9dffcb32..9c2085a654 100644 --- a/Task/Factorial/Langur/factorial-1.langur +++ b/Task/Factorial/Langur/factorial-1.langur @@ -1,2 +1,2 @@ -val .factorial = f fold(f .x x .y, pseries .n) +val .factorial = f fold(f{x}, 2 .. .n) writeln .factorial(7) diff --git a/Task/Factorial/Langur/factorial-2.langur b/Task/Factorial/Langur/factorial-2.langur index 9c2085a654..eb03b40830 100644 --- a/Task/Factorial/Langur/factorial-2.langur +++ b/Task/Factorial/Langur/factorial-2.langur @@ -1,2 +1,2 @@ -val .factorial = f fold(f{x}, 2 .. .n) +val .factorial = f if(.x < 2: 1; .x x self(.x - 1)) writeln .factorial(7) diff --git a/Task/Factorial/Langur/factorial-3.langur b/Task/Factorial/Langur/factorial-3.langur index eb03b40830..584fd8692a 100644 --- a/Task/Factorial/Langur/factorial-3.langur +++ b/Task/Factorial/Langur/factorial-3.langur @@ -1,2 +1,8 @@ -val .factorial = f if(.x < 2: 1; .x x self(.x - 1)) +val .factorial = f(.i) { + var .answer = 1 + for .x in 2 .. .i { + .answer x= .x + } + .answer +} writeln .factorial(7) diff --git a/Task/Factorial/Langur/factorial-4.langur b/Task/Factorial/Langur/factorial-4.langur index 584fd8692a..18af40dfb3 100644 --- a/Task/Factorial/Langur/factorial-4.langur +++ b/Task/Factorial/Langur/factorial-4.langur @@ -1,8 +1,2 @@ -val .factorial = f(.i) { - var .answer = 1 - for .x in 2 .. .i { - .answer x= .x - } - .answer -} +val .factorial = f(.n) for[=1] .x in .n { _for x= .x } writeln .factorial(7) diff --git a/Task/Factorial/Langur/factorial-5.langur b/Task/Factorial/Langur/factorial-5.langur deleted file mode 100644 index 18af40dfb3..0000000000 --- a/Task/Factorial/Langur/factorial-5.langur +++ /dev/null @@ -1,2 +0,0 @@ -val .factorial = f(.n) for[=1] .x in .n { _for x= .x } -writeln .factorial(7) diff --git a/Task/Factorial/Refal/factorial.refal b/Task/Factorial/Refal/factorial.refal new file mode 100644 index 0000000000..ab25f846e3 --- /dev/null +++ b/Task/Factorial/Refal/factorial.refal @@ -0,0 +1,14 @@ +$ENTRY Go { + = ; +} + +Facts { + s.N s.Max, : '+' = ; + s.N s.Max = '! = ' > + s.Max>; +}; + +Fact { + 0 = 1; + s.N = <* s.N >>; +}; diff --git a/Task/Factorial/Soda/factorial-2.soda b/Task/Factorial/Soda/factorial-2.soda index 65bca7ad00..91cb1f27fb 100644 --- a/Task/Factorial/Soda/factorial-2.soda +++ b/Task/Factorial/Soda/factorial-2.soda @@ -1,4 +1,3 @@ -@tailrec _tailrec_fact (n : Int) (accum : Int) : Int = if n < 2 then accum diff --git a/Task/Factorial/YAMLScript/factorial.ys b/Task/Factorial/YAMLScript/factorial.ys index d8cd3215ed..8cd4d4397a 100644 --- a/Task/Factorial/YAMLScript/factorial.ys +++ b/Task/Factorial/YAMLScript/factorial.ys @@ -1,6 +1,7 @@ -!yamlscript/v0 +#!/usr/bin/env ys-0 + +defn main(n): + say: "$n! = $factorial(n)" defn factorial(x): - apply *: 2..x - -say: factorial(20) + apply *: 2 .. x diff --git a/Task/Factorial/Zig/factorial.zig b/Task/Factorial/Zig/factorial.zig index c0a83517ca..8b39b0719a 100644 --- a/Task/Factorial/Zig/factorial.zig +++ b/Task/Factorial/Zig/factorial.zig @@ -1,25 +1,27 @@ -const stdout = @import("std").io.getStdOut().outStream(); - pub fn factorial(comptime Num: type, n: i8) ?Num { return if (@typeInfo(Num) != .Int) - @compileError("factorial called with num-integral type: " ++ @typeName(Num)) + @compileError("factorial called with non-integral type: " ++ @typeName(Num)) else if (n < 0) null else calc: { var i: i8 = 1; var fac: Num = 1; while (i <= n) : (i += 1) { - if (@mulWithOverflow(Num, fac, i, &fac)) - break :calc null; + const tmp = @mulWithOverflow(fac, i); + if (tmp[1] != 0) + break :calc null; // overflow + fac = tmp[0]; } else break :calc fac; }; } pub fn main() !void { - try stdout.print("-1! = {}\n", .{factorial(i32, -1)}); - try stdout.print("0! = {}\n", .{factorial(i32, 0)}); - try stdout.print("5! = {}\n", .{factorial(i32, 5)}); - try stdout.print("33!(64 bit) = {}\n", .{factorial(i64, 33)}); // not vailid i64 factorial - try stdout.print("33! = {}\n", .{factorial(i128, 33)}); // biggest facorial possible - try stdout.print("34! = {}\n", .{factorial(i128, 34)}); // will overflow + const stdout = @import("std").io.getStdOut().writer(); + + try stdout.print("-1! = {?}\n", .{factorial(i32, -1)}); + try stdout.print("0! = {?}\n", .{factorial(i32, 0)}); + try stdout.print("5! = {?}\n", .{factorial(i32, 5)}); + try stdout.print("33!(64 bit) = {?}\n", .{factorial(i64, 33)}); // not valid i64 factorial + try stdout.print("33! = {?}\n", .{factorial(i128, 33)}); // biggest i128 factorial possible + try stdout.print("34! = {?}\n", .{factorial(i128, 34)}); // will overflow } diff --git a/Task/Fairshare-between-two-and-more/C-sharp/fairshare-between-two-and-more.cs b/Task/Fairshare-between-two-and-more/C-sharp/fairshare-between-two-and-more.cs new file mode 100644 index 0000000000..faaea48c58 --- /dev/null +++ b/Task/Fairshare-between-two-and-more/C-sharp/fairshare-between-two-and-more.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; + +class FairshareBetweenTwoAndMore +{ + static void Main(string[] args) + { + foreach (int baseValue in new List { 2, 3, 5, 11 }) + { + Console.WriteLine($"Base {baseValue} = {string.Join(", ", ThueMorseSequence(25, baseValue))}"); + } + } + + private static List ThueMorseSequence(int terms, int baseValue) + { + List sequence = new List(); + for (int i = 0; i < terms; i++) + { + int sum = 0; + int n = i; + while (n > 0) + { + // Compute the digit sum + sum += n % baseValue; + n /= baseValue; + } + // Compute the digit sum modulo baseValue. + sequence.Add(sum % baseValue); + } + return sequence; + } +} diff --git a/Task/Farey-sequence/Langur/farey-sequence.langur b/Task/Farey-sequence/Langur/farey-sequence.langur index eba7a535fe..c24fac50a8 100644 --- a/Task/Farey-sequence/Langur/farey-sequence.langur +++ b/Task/Farey-sequence/Langur/farey-sequence.langur @@ -7,7 +7,7 @@ val .farey = f(.n) { } } -val .testFarey = f() { +val .testFarey = impure f() { writeln "Farey sequence for orders 1 through 11" for .i of 11 { writeln $"\.i:2;: ", join " ", map(f $"\.f[1];/\.f[2];", .farey(.i)) diff --git a/Task/Farey-sequence/MATLAB/farey-sequence.m b/Task/Farey-sequence/MATLAB/farey-sequence.m new file mode 100644 index 0000000000..d136a7c1f3 --- /dev/null +++ b/Task/Farey-sequence/MATLAB/farey-sequence.m @@ -0,0 +1,32 @@ +clear all;close all;clc; + +% Print Farey sequences for 1 to 11 + for i = 1:11 + farey_sequence = farey(i); + fprintf('%2d: %s\n', i, strjoin(farey_sequence, ' ')); + end + fprintf('\n'); + + % Print the number of fractions in Farey sequences for 100 to 1000 step 100 + for i = 100:100:1000 + farey_sequence = farey(i); + fprintf('%4d: %6d fractions\n', i, length(farey_sequence)); + end + +function farey_sequence = farey(n) + a = 0; + b = 1; + c = 1; + d = n; + farey_sequence = {[num2str(a) '/' num2str(b)]}; % Initialize the sequence with "0/1" + while c <= n + k = fix((n + b) / d); + aa = a; + bb = b; + a = c; + b = d; + c = k * c - aa; + d = k * d - bb; + farey_sequence{end+1} = [num2str(a) '/' num2str(b)]; % Append the fraction to the sequence + end +end diff --git a/Task/Fast-Fourier-transform/Pascal/fast-fourier-transform.pas b/Task/Fast-Fourier-transform/Pascal/fast-fourier-transform.pas index 9b77684bfc..aa31e5b4b7 100644 --- a/Task/Fast-Fourier-transform/Pascal/fast-fourier-transform.pas +++ b/Task/Fast-Fourier-transform/Pascal/fast-fourier-transform.pas @@ -21,6 +21,8 @@ USES sysutils, ucomplex; + {$WARN 6058 off : Call to subroutine "$1" marked as inline is not inlined} + (*) Use for variants and ucomplex (*) TYPE diff --git a/Task/Fermat-numbers/Langur/fermat-numbers.langur b/Task/Fermat-numbers/Langur/fermat-numbers.langur index 06db90b3ff..16c1a3da8a 100644 --- a/Task/Fermat-numbers/Langur/fermat-numbers.langur +++ b/Task/Fermat-numbers/Langur/fermat-numbers.langur @@ -1,11 +1,11 @@ -val .fermat = f 2 ^ 2 ^ .n + 1 +val .fermat = f 2 ^ 2 ^ .i + 1 val .factors = f(var .x) { - for[.f=[]] .i, .s = 2, truncate .x ^/ 2; .i < .s; .i += 1 { + for[.f=[]] .i, .s = 2, trunc .x ^/ 2; .i < .s; .i += 1 { if .x div .i { .f ~= [.i] .x \= .i - .s = truncate .x ^/ 2 + .s = trunc .x ^/ 2 } } ~ [.x] } diff --git a/Task/Fermat-numbers/PARI-GP/fermat-numbers.parigp b/Task/Fermat-numbers/PARI-GP/fermat-numbers.parigp new file mode 100644 index 0000000000..46c80682ff --- /dev/null +++ b/Task/Fermat-numbers/PARI-GP/fermat-numbers.parigp @@ -0,0 +1,30 @@ +\\ Define a function to calculate Fermat numbers +fermat(n) = 2^(2^n) + 1; + + +\\ Define a function to factor Fermat numbers up to a given maximum +\\ and optionally just print them without factoring +factorfermats(mymax, nofactor=0) = +{ + local(fm, factors, n); + for (n = 0, mymax, + fm = fermat(n); + if (nofactor, + print("Fermat number F(", n, ") is ", fm, "."); + next; + ); + factors = factorint(fm); + if (matsize(factors)[1] == 1 && factors[1,2] == 1, \\ Check if it has only one factor with exponent 1 (i.e., prime) + print("Fermat number F(", n, "), ", fm, ", is prime."); + , + print("Fermat number F(", n, "), ", fm, ", factors to ", (factors), "."); + ); + ); +} + +{ +\\ Example usage +factorfermats(9, 1); \\ Print Fermat numbers without factoring +print(""); \\ Just to add a visual separator in the output +factorfermats(10); \\ Factor Fermat numbers +} diff --git a/Task/Fibonacci-sequence/Bruijn/fibonacci-sequence-1.bruijn b/Task/Fibonacci-sequence/Bruijn/fibonacci-sequence-1.bruijn new file mode 100644 index 0000000000..d2e4752aa5 --- /dev/null +++ b/Task/Fibonacci-sequence/Bruijn/fibonacci-sequence-1.bruijn @@ -0,0 +1,20 @@ +:import std/Combinator . +:import std/Math . +:import std/List . + +# unary/Church fibonacci (moderately fast but very high space complexity) +fib-unary [0 [[[2 0 [2 (1 0)]]]] k i] + +:test (fib-unary (+6u)) ((+8u)) + +# ternary fibonacci using infinite list iteration (very fast) +fib-list \index fibs + fibs head <$> (iterate &[[0 : (1 + 0)]] ((+0) : (+1))) + +:test (fib-list (+6)) ((+8)) + +# recursive fib (very slow) +fib-rec y [[0 :time fib-list (+1000) +0.9 seconds +> :time fib-unary (+50u) +1.7 seconds +> :time fib-rec (+25) +5.1 seconds +> :time fib-list (+50) +0.0006 seconds diff --git a/Task/Fibonacci-sequence/DIBOL-11/fibonacci-sequence.dibol-11 b/Task/Fibonacci-sequence/DIBOL-11/fibonacci-sequence.dibol-11 index 3ac39c2363..c1be25b5f6 100644 --- a/Task/Fibonacci-sequence/DIBOL-11/fibonacci-sequence.dibol-11 +++ b/Task/Fibonacci-sequence/DIBOL-11/fibonacci-sequence.dibol-11 @@ -1,14 +1,17 @@ - START ;First 10 Fibonacci NUmbers + ; Redone to include the first two values that + ; are noot computed. + + START ;First 15 Fibonacci NUmbers RECORD FIB1, D10, 0 FIB2, D10, 1 FIBNEW, D10 - LOOPCNT, D2, 1 + LOOPCNT, D2, 3 RECORD HEADER -, A32, "First 10 Fibonacci Numbers." +, A32, "First 15 Fibonacci Numbers." RECORD OUTPUT LOOPOUT, A2 @@ -21,6 +24,17 @@ WRITES(8,HEADER) +; The First Two are given. + + FIBOUT = 0 + LOOPOUT = 1 + WRITES(8,OUTPUT) + FIBOUT = 1 + LOOPOUT = 2 + WRITES(8,OUTPUT) + +; The Rest are Computed. + LOOP, FIBNEW = FIB1 + FIB2 LOOPOUT = LOOPCNT, 'ZX' @@ -32,7 +46,7 @@ FIB2 = FIBNEW LOOPCNT = LOOPCNT + 1 - IF LOOPCNT .LE. 10 GOTO LOOP + IF LOOPCNT .LE. 15 GOTO LOOP CLOSE 8 END diff --git a/Task/Fibonacci-sequence/Elena/fibonacci-sequence-1.elena b/Task/Fibonacci-sequence/Elena/fibonacci-sequence-1.elena index 9c4a4a1c20..2b0d6a74b4 100644 --- a/Task/Fibonacci-sequence/Elena/fibonacci-sequence-1.elena +++ b/Task/Fibonacci-sequence/Elena/fibonacci-sequence-1.elena @@ -9,7 +9,7 @@ fibu(n) } else { - for(int i := 2, i <= n, i+=1) + for(int i := 2; i <= n; i+=1) { int t := ac[1]; ac[1] := ac[0] + ac[1]; @@ -22,7 +22,7 @@ fibu(n) public program() { - for(int i := 0, i <= 10, i+=1) + for(int i := 0; i <= 10; i+=1) { console.printLine(fibu(i)) } diff --git a/Task/Fibonacci-sequence/Elena/fibonacci-sequence-2.elena b/Task/Fibonacci-sequence/Elena/fibonacci-sequence-2.elena index 93b2a68afd..0416651c30 100644 --- a/Task/Fibonacci-sequence/Elena/fibonacci-sequence-2.elena +++ b/Task/Fibonacci-sequence/Elena/fibonacci-sequence-2.elena @@ -26,7 +26,7 @@ public program() { auto e := new FibonacciGenerator(); - for(int i := 0, i < 10, i += 1) { + for(int i := 0; i < 10; i += 1) { console.printLine(e.next()) }; diff --git a/Task/Fibonacci-sequence/Elm/fibonacci-sequence.elm b/Task/Fibonacci-sequence/Elm/fibonacci-sequence-1.elm similarity index 100% rename from Task/Fibonacci-sequence/Elm/fibonacci-sequence.elm rename to Task/Fibonacci-sequence/Elm/fibonacci-sequence-1.elm diff --git a/Task/Fibonacci-sequence/Elm/fibonacci-sequence-2.elm b/Task/Fibonacci-sequence/Elm/fibonacci-sequence-2.elm new file mode 100644 index 0000000000..6315168f62 --- /dev/null +++ b/Task/Fibonacci-sequence/Elm/fibonacci-sequence-2.elm @@ -0,0 +1,6 @@ +fib : Int -> number +fib n = + case n of + 0 -> 0 + 1 -> 1 + _ -> fib (n-1) + fib (n-2) diff --git a/Task/Fibonacci-sequence/Logo/fibonacci-sequence.logo b/Task/Fibonacci-sequence/Logo/fibonacci-sequence.logo index 2eee939db8..9aac081880 100644 --- a/Task/Fibonacci-sequence/Logo/fibonacci-sequence.logo +++ b/Task/Fibonacci-sequence/Logo/fibonacci-sequence.logo @@ -1,4 +1,17 @@ -to fib :n [:a 0] [:b 1] - if :n < 1 [output :a] - output (fib :n-1 :b :a+:b) +to fib "loop +make "fib1 0 +make "fib2 1 + +type [You requested\ ] +type :loop +print [\ Fibonacci Numbers] + type :fib1 + type [\ ] + type :fib2 + type [\ ] + +make "loop :loop - 2 +repeat :loop [ make "fibnew :fib1 + :fib2 type :fibnew type [\ ] make "fib1 :fib2 make "fib2 :fibnew ] + print [\ ] + end diff --git a/Task/Fibonacci-sequence/ParaCL/fibonacci-sequence.paracl b/Task/Fibonacci-sequence/ParaCL/fibonacci-sequence.paracl new file mode 100644 index 0000000000..dcf7637ea5 --- /dev/null +++ b/Task/Fibonacci-sequence/ParaCL/fibonacci-sequence.paracl @@ -0,0 +1,7 @@ +fibbonachi = func(x) : fibb +{ + res = 1; + if (x > 1) + res = fibb(x - 1) + fibb(x - 2); + res; +} diff --git a/Task/Fibonacci-sequence/RATFOR/fibonacci-sequence.ratfor b/Task/Fibonacci-sequence/RATFOR/fibonacci-sequence.ratfor new file mode 100644 index 0000000000..2c3fa0a08e --- /dev/null +++ b/Task/Fibonacci-sequence/RATFOR/fibonacci-sequence.ratfor @@ -0,0 +1,26 @@ +program Fibonacci +# +integer*4 count, loop +integer*4 num1, num2, fib + +1 format(A) +2 format(I4) +3 format(I6,' ') +4 format(' ') +write(6,1,advance='no')'How Many: ' +read(5,2)count + +num1 = 0 +num2 = 1 +write(6,3,advance='no')num1 +write(6,3,advance='no')num2 + +for (loop = 3; loop<=count; loop=loop+1) + { + fib = num1 + num2 + write(6,3,advance='no')fib + num1 = num2 + num2 = fib + } +write(6,4) +end diff --git a/Task/Fibonacci-sequence/Refal/fibonacci-sequence.refal b/Task/Fibonacci-sequence/Refal/fibonacci-sequence.refal new file mode 100644 index 0000000000..b97375a6f8 --- /dev/null +++ b/Task/Fibonacci-sequence/Refal/fibonacci-sequence.refal @@ -0,0 +1,12 @@ +$ENTRY Go { + = > +} ; + +Repeat { + 0 s.F e.X = e.X; + s.N s.F e.X = s.F >; +}; + +Fibonacci { + e.X s.A s.B = e.X s.A s.B <+ s.A s.B>; +}; diff --git a/Task/Fibonacci-sequence/YAMLScript/fibonacci-sequence.ys b/Task/Fibonacci-sequence/YAMLScript/fibonacci-sequence.ys index 7580949924..3727f77a8e 100644 --- a/Task/Fibonacci-sequence/YAMLScript/fibonacci-sequence.ys +++ b/Task/Fibonacci-sequence/YAMLScript/fibonacci-sequence.ys @@ -1,4 +1,7 @@ -loop [a 0, b 1, i 1 ]: - say: a - (i < 10) ?: - ^^^: b, (a + b), (i + 1) +!yamlscript/v0 + +defn main(n=10): + loop [a 0, b 1, i 1]: + say: a + if (i < n): + recur: b, (a + b), (i + 1) diff --git a/Task/Fibonacci-word/Dart/fibonacci-word.dart b/Task/Fibonacci-word/Dart/fibonacci-word.dart new file mode 100644 index 0000000000..0259cd67ef --- /dev/null +++ b/Task/Fibonacci-word/Dart/fibonacci-word.dart @@ -0,0 +1,59 @@ +import 'dart:math'; + +class FWord { + String fWord0 = ""; + String fWord1 = ""; + + String nextFWord() { + String result; + + if (fWord1 == "") { + result = "1"; + } else if (fWord0 == "") { + result = "0"; + } else { + result = fWord1 + fWord0; + } + + fWord0 = fWord1; + fWord1 = result; + + return result; + } + + static double entropy(String source) { + int length = source.length; + var counts = {}; + double result = 0.0; + + for (int i = 0; i < length; i++) { + String c = source[i]; + + if (counts.containsKey(c)) { + counts[c] = counts[c] + 1; + } else { + counts[c] = 1; + } + } + + counts.values.forEach((count) { + double proportion = count / length; + result -= proportion * (log(proportion) / log(2)); + }); + + return result; + } + + static void main() { + FWord fWord = FWord(); + + for (int i = 0; i < 37;) { + String word = fWord.nextFWord(); + print("${++i} ${word.length} ${entropy(word)}"); + } + } +} + +void main() { + FWord.main(); +} diff --git a/Task/Filter/Elena/filter-1.elena b/Task/Filter/Elena/filter-1.elena index 0d72130bc1..1bb77db11f 100644 --- a/Task/Filter/Elena/filter-1.elena +++ b/Task/Filter/Elena/filter-1.elena @@ -7,7 +7,7 @@ public program() { auto array := new int[]{1,2,3,4,5}; - var evens := array.filterBy:(n => n.mod:2 == 0).toArray(); + var evens := array.filterBy::(n => n.mod(2) == 0).toArray(); - evens.forEach:printingLn + evens.forEach(printingLn) } diff --git a/Task/Filter/Elena/filter-2.elena b/Task/Filter/Elena/filter-2.elena index 2c3fdf4087..ffd14b6e6c 100644 --- a/Task/Filter/Elena/filter-2.elena +++ b/Task/Filter/Elena/filter-2.elena @@ -8,6 +8,6 @@ public program() int[] array := new int[]{1,2,3,4,5}; array - .filterBy:(int n => n.mod:2 == 0) - .forEach:(int i){ console.printLine(i) } + .filterBy::(int n => n.mod(2) == 0) + .forEach::(int i){ console.printLine(i) } } diff --git a/Task/Filter/Langur/filter.langur b/Task/Filter/Langur/filter.langur index 8a12534dd9..0952f2cfbc 100644 --- a/Task/Filter/Langur/filter.langur +++ b/Task/Filter/Langur/filter.langur @@ -1,4 +1,4 @@ -val .arr = series 7 +val .list = series 7 -writeln " array: ", .arr -writeln "filtered: ", filter f{div 2}, .arr +writeln " list: ", .list +writeln "filtered: ", filter f{div 2}, .list diff --git a/Task/Find-common-directory-path/Swift/find-common-directory-path.swift b/Task/Find-common-directory-path/Swift/find-common-directory-path-1.swift similarity index 100% rename from Task/Find-common-directory-path/Swift/find-common-directory-path.swift rename to Task/Find-common-directory-path/Swift/find-common-directory-path-1.swift diff --git a/Task/Find-common-directory-path/Swift/find-common-directory-path-2.swift b/Task/Find-common-directory-path/Swift/find-common-directory-path-2.swift new file mode 100644 index 0000000000..2d515d4e1b --- /dev/null +++ b/Task/Find-common-directory-path/Swift/find-common-directory-path-2.swift @@ -0,0 +1,28 @@ +import Foundation + +func commonPrefix(_ lhs: [T], _ rhs: [T]) -> [T] { + for tryLen in (0...min(lhs.count,rhs.count)).reversed() { + if lhs.starts(with: rhs.prefix(tryLen)) { + return Array(rhs.prefix(tryLen)) + } + } + return [] +} + +var test = ["/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members"] + +let lcp: String = test.reduce("") { lhs, rhs in + if !lhs.isEmpty { + var commonSoFar = commonPrefix( + lhs.components(separatedBy: "/"), + rhs.components(separatedBy: "/") + ) + return commonSoFar.joined(separator: "/") + } + return rhs +} +print("Longest common path: \(lcp)") + +// Longest common path: /home/user1/tmp diff --git a/Task/Find-the-intersection-of-two-lines/EasyLang/find-the-intersection-of-two-lines.easy b/Task/Find-the-intersection-of-two-lines/EasyLang/find-the-intersection-of-two-lines.easy new file mode 100644 index 0000000000..167f357dd3 --- /dev/null +++ b/Task/Find-the-intersection-of-two-lines/EasyLang/find-the-intersection-of-two-lines.easy @@ -0,0 +1,21 @@ +proc intersect ax1 ay1 ax2 ay2 bx1 by1 bx2 by2 . rx ry . + rx = 1 / 0 + ry = 1 / 0 + d = (by2 - by1) * (ax2 - ax1) - (bx2 - bx1) * (ay2 - ay1) + if d = 0 + return + . + ua = ((bx2 - bx1) * (ay1 - by1) - (by2 - by1) * (ax1 - bx1)) / d + ub = ((ax2 - ax1) * (ay1 - by1) - (by2 - by1) * (ax1 - bx1)) / d + if abs ua > 1 or abs ub > 1 + return + . + rx = ax1 + ua * (ax2 - ax1) + ry = ay1 + ua * (ay2 - ay1) +. +intersect 4 0 6 10 0 3 10 7 rx ry +print rx & " " & ry +intersect 4 0 6 10 0 3 10 7.1 rx ry +print rx & " " & ry +intersect 0 0 1 1 1 2 4 5 rx ry +print rx & " " & ry diff --git a/Task/Find-the-missing-permutation/EasyLang/find-the-missing-permutation.easy b/Task/Find-the-missing-permutation/EasyLang/find-the-missing-permutation.easy new file mode 100644 index 0000000000..86a7c5c24e --- /dev/null +++ b/Task/Find-the-missing-permutation/EasyLang/find-the-missing-permutation.easy @@ -0,0 +1,24 @@ +perms$[] = [ "ABCD" "CABD" "ACDB" "DACB" "BCDA" "ACBD" "ADCB" "CDAB" "DABC" "BCAD" "CADB" "CDBA" "CBAD" "ABDC" "ADBC" "BDCA" "DCBA" "BACD" "BADC" "BDAC" "CBDA" "DBCA" "DCAB" ] +n = len perms$[1] +len cnt[] n +# +nn = 1 +for i to n - 1 + nn *= i +. +for i to 4 + for j to n + cnt[j] = 0 + . + for s$ in perms$[] + cod = strcode substr s$ i 1 - 64 + cnt[cod] += 1 + . + for j to n + if cnt[j] <> nn + miss$ &= strchar (j + 64) + break 1 + . + . +. +print miss$ diff --git a/Task/First-class-functions-Use-numbers-analogously/Elena/first-class-functions-use-numbers-analogously.elena b/Task/First-class-functions-Use-numbers-analogously/Elena/first-class-functions-use-numbers-analogously.elena index 38782326bc..412018008a 100644 --- a/Task/First-class-functions-Use-numbers-analogously/Elena/first-class-functions-use-numbers-analogously.elena +++ b/Task/First-class-functions-Use-numbers-analogously/Elena/first-class-functions-use-numbers-analogously.elena @@ -15,5 +15,5 @@ public program() var multiplied := numlist.zipBy(numlisti, (n1,n2 => (m => n1 * n2 * m) )).toArray(); - multiplied.forEach:(multiplier){ console.printLine(multiplier(0.5r)) } + multiplied.forEach::(multiplier){ console.printLine(multiplier(0.5r)) } } diff --git a/Task/First-class-functions-Use-numbers-analogously/FreeBASIC/first-class-functions-use-numbers-analogously.basic b/Task/First-class-functions-Use-numbers-analogously/FreeBASIC/first-class-functions-use-numbers-analogously.basic new file mode 100644 index 0000000000..8c377cb95f --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/FreeBASIC/first-class-functions-use-numbers-analogously.basic @@ -0,0 +1,18 @@ +Dim As Double x = 2.0, xi = 0.5 +Dim As Double y = 4.0, yi = 0.25 +Dim As Double z = x + y, zi = 1.0 / (x + y) +Dim As Double values(2) = {x, y, z} +Dim As Double inverses(2) = {xi, yi, zi} + +Dim Shared As Double m = 0.5 + +Function multiplier(a As Double, d As Double) As Double + Return a * d * m +End Function + +For i As Byte = 0 To Ubound(values) + Dim As Double new_function = multiplier(values(i), inverses(i)) + Print values(i); " *"; inverses(i); " *"; m; " ="; new_function +Next i + +Sleep diff --git a/Task/First-class-functions/Elena/first-class-functions.elena b/Task/First-class-functions/Elena/first-class-functions.elena index 72cd37e51b..baa145697e 100644 --- a/Task/First-class-functions/Elena/first-class-functions.elena +++ b/Task/First-class-functions/Elena/first-class-functions.elena @@ -15,5 +15,5 @@ public program() var gs := new object[]{ mssgconst arcsin[1], mssgconst arccos[1], (x => power(x, 1.0r / 3)) }; fs.zipBy(gs, (f,g => 0.5r.compose(f,g))) - .forEach:printingLn + .forEach(printingLn) } diff --git a/Task/First-perfect-square-in-base-n-with-n-unique-digits/FreeBASIC/first-perfect-square-in-base-n-with-n-unique-digits.basic b/Task/First-perfect-square-in-base-n-with-n-unique-digits/FreeBASIC/first-perfect-square-in-base-n-with-n-unique-digits.basic new file mode 100644 index 0000000000..91eb36ff0c --- /dev/null +++ b/Task/First-perfect-square-in-base-n-with-n-unique-digits/FreeBASIC/first-perfect-square-in-base-n-with-n-unique-digits.basic @@ -0,0 +1,39 @@ +#define floor(x) ((x*2.0-0.5) Shr 1) + +Dim Shared As Double n, base_ = 2. ' Base is a reserved word on FB + +Sub NumOut(n As Double) 'Display n in the specified base + Dim As Integer remainder = Fix(n Mod base_) + n = floor(n / base_) + If n <> 0. Then NumOut(n) + Print Chr(remainder + Iif(remainder <= 9, Asc("0"), Asc("A")-10)); +End Sub + +Function isPandigital(n As Double) As Boolean + Dim As Integer used, remainder + used = 0 + While n <> 0. + remainder = Fix(n Mod base_) + n = floor(n / base_) + used Or= 1 Shl remainder + Wend + Return used = (1 Shl Fix(base_)) - 1 +End Function + +Do + n = floor(Sqr(base_ ^ (base_-1.))) + Do + If isPandigital(n*n) Then + Print Using "Base ##: "; base_; + NumOut(n) + Print "^2 = "; + NumOut(n*n) + Print + Exit Do + End If + n += 1. + Loop + base_ += 1. +Loop Until base_ > 14. + +Sleep diff --git a/Task/FizzBuzz/BabyCobol/fizzbuzz.cobol b/Task/FizzBuzz/BabyCobol/fizzbuzz.cobol new file mode 100644 index 0000000000..4ad1e730cd --- /dev/null +++ b/Task/FizzBuzz/BabyCobol/fizzbuzz.cobol @@ -0,0 +1,22 @@ + * NB: ANY does not exist in BabyCobol so the elegant + * EVALUATE-based COBOL-style solution is impossible here. + * Note the subtly unbalanced IF/ENDs yet valid END at the end. + IDENTIFICATION DIVISION. + PROGRAM-ID. FIZZBUZZ. + DATA DIVISION. + 01 INT PICTURE IS 9(3). + 01 REM LIKE INT. + 01 TMP LIKE INT. + PROCEDURE DIVISION. + LOOP VARYING INT TO 100 + DIVIDE 3 INTO INT GIVING TMP REMAINDER REM + IF REM = 0 + THEN DISPLAY "Fizz" WITH NO ADVANCING + DIVIDE 5 INTO INT GIVING TMP REMAINDER REM + IF REM = 0 + THEN DISPLAY "Buzz" WITH NO ADVANCING + DIVIDE 15 INTO INT GIVING TMP REMAINDER REM + IF REM = 0 + THEN DISPLAY "" + ELSE DISPLAY INT + END. diff --git a/Task/FizzBuzz/Bruijn/fizzbuzz.bruijn b/Task/FizzBuzz/Bruijn/fizzbuzz.bruijn new file mode 100644 index 0000000000..7f61704168 --- /dev/null +++ b/Task/FizzBuzz/Bruijn/fizzbuzz.bruijn @@ -0,0 +1,11 @@ +:import std/Combinator . +:import std/String . +:import std/Number . + +main [y [[0 =? (+101) case-end case-rec]] (+1)] + case-rec str ++ "\n" ++ (1 ++0) + str fizzbuzz "FizzBuzz" (fizz "Fizz" (buzz "Buzz" (number→string 0))) + fizz =?(0 % (+3)) + buzz =?(0 % (+5)) + fizzbuzz fizz buzz fizz + case-end empty diff --git a/Task/FizzBuzz/Langur/fizzbuzz-1.langur b/Task/FizzBuzz/Langur/fizzbuzz-1.langur index e2f50b4bcd..d5e5445c4f 100644 --- a/Task/FizzBuzz/Langur/fizzbuzz-1.langur +++ b/Task/FizzBuzz/Langur/fizzbuzz-1.langur @@ -1,3 +1,3 @@ for .i of 100 { - writeln given(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i) + writeln switch(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i) } diff --git a/Task/FizzBuzz/Refal/fizzbuzz.refal b/Task/FizzBuzz/Refal/fizzbuzz.refal new file mode 100644 index 0000000000..4dc835261a --- /dev/null +++ b/Task/FizzBuzz/Refal/fizzbuzz.refal @@ -0,0 +1,16 @@ +$ENTRY Go { + = ; +}; + +FizzBuzz { + 101 = ; + s.N = > + >; +}; + +Item { + s.N, : 0 = FizzBuzz; + s.N, : 0 = Buzz; + s.N, : 0 = Fizz; + s.N = s.N; +}; diff --git a/Task/FizzBuzz/YAMLScript/fizzbuzz.ys b/Task/FizzBuzz/YAMLScript/fizzbuzz.ys index 19dfaa2cbe..51f177ae81 100644 --- a/Task/FizzBuzz/YAMLScript/fizzbuzz.ys +++ b/Task/FizzBuzz/YAMLScript/fizzbuzz.ys @@ -2,21 +2,18 @@ # This program has multiple implementations of "fizzbuzz". -# usage: ys fizzbuzz.ys [] [] +# usage: yamlscript fizzbuzz.ys [] [] # The main function runs a certain requested fizzbuzz implementation function # for a certain requested number (default is 100). -defn main(&[count impl]): - count =: count || 100 - impl =: - str: impl || "1" +defn main(count=100 impl=1): fizzbuzz =: "fizzbuzz-$impl" - when-not ENV."YS_TEST": + when-not ENV.'YS_TEST': say: "Running function '$fizzbuzz' with count=$count" - function =: resolve(symbol(fizzbuzz)) + function =: resolve(fizzbuzz.symbol()) result =: function(count) mapv say: result @@ -27,33 +24,32 @@ defn main(&[count impl]): defn fizzbuzz-1(n): map: - fn [x]: + fn(x): cond: - zero?(mod(x 15)) "FizzBuzz" - zero?(mod(x 5)) "Buzz" - zero?(mod(x 3)) "Fizz" - :else x - =>: (1 .. n) + zero?(x % 15): 'FizzBuzz' + zero?(x % 5): 'Buzz' + zero?(x % 3): 'Fizz' + =>: x + =>: 1 .. n defn fizzbuzz-2(n): loop [i 1, l []]: if (i > n): =>: l - recur: - inc: i + recur inc(i): conj l: cond: - zero?(mod(i 15)) "FizzBuzz" - zero?(mod(i 5)) "Buzz" - zero?(mod(i 3)) "Fizz" - :else i + zero?(i % 15): 'FizzBuzz' + zero?(i % 5): 'Buzz' + zero?(i % 3): 'Fizz' + =>: i defn fizzbuzz-3(n): map: - fn [x]: + fn(x): s =: str: - when zero?(mod(x 3)): "Fizz" - when zero?(mod(x 5)): "Buzz" + when zero?(x % 3): 'Fizz' + =>: (zero?(x % 5) && 'Buzz') || nil if empty?(s): x s - rng: 1, n + rng: 1 n diff --git a/Task/Flipping-bits-game/Forth/flipping-bits-game-1.fth b/Task/Flipping-bits-game/Forth/flipping-bits-game-1.fth new file mode 100644 index 0000000000..7f21179011 --- /dev/null +++ b/Task/Flipping-bits-game/Forth/flipping-bits-game-1.fth @@ -0,0 +1,80 @@ +require random.fs + +0 value board-size +variable target +variable board +variable moves + +: moves-reset 0 moves ! ; +: moves+ 1 moves +! ; +: .moves ." You have made " moves @ . ." moves." ; + +: target-gen ( -- ) rnd target ! ; + +: row-flip ( n -- ) + 8 * 255 swap lshift + board @ xor board ! ; + +: column-flip ( n -- ) + 1 swap lshift + 8 0 do dup 8 lshift or loop + board @ xor board ! ; + +: target>board ( -- ) target @ board ! ; + +: board-shuffle ( -- ) + board-size dup * 0 do + board-size random 2 random if row-flip else column-flip then + loop ; + +: ask-move ( -- char ) + cr ." choose row [0-" board-size [char] 0 + 1- emit + ." ] or column [a-" board-size [char] a + 1- emit + ." ]: " + key ; + +: do-move ( char -- ) + dup emit + dup [char] a dup board-size + within + if dup [char] a - column-flip + else + dup [char] 0 dup board-size + within + if dup [char] 0 - row-flip + else ." - this move is not permitted!" + then then + cr drop +; + +: .header ( -- ) cr ." Target: " board-size 2 * spaces ." Board:" ; +: .column-header ( -- ) board-size 0 do i [char] a + emit space loop ; +: .row-header ( n -- ) . ." - " ; +: .row ( board@ n -- ) dup .row-header 8 * rshift board-size 0 do dup 1 and . 2/ loop drop ; +: .boards + .header cr + 4 spaces .column-header 8 spaces .column-header cr + board-size 0 do + target @ i .row 4 spaces board @ i .row cr + loop +; + +: ?win ( -- f ) + 0 board-size 0 do 2* 1+ loop + board-size 1 do dup 8 lshift or loop + dup target @ and + swap board @ and = +; + +: game-loop + begin + .boards .moves + ask-move do-move moves+ + ?win until + ." You win after " moves @ . ." moves!" +; + +: flip-bit-game ( n -- ) + to board-size + target-gen target>board board-shuffle + moves-reset + game-loop +; diff --git a/Task/Flipping-bits-game/Forth/flipping-bits-game-2.fth b/Task/Flipping-bits-game/Forth/flipping-bits-game-2.fth new file mode 100644 index 0000000000..b5664c72ac --- /dev/null +++ b/Task/Flipping-bits-game/Forth/flipping-bits-game-2.fth @@ -0,0 +1,101 @@ +require random.fs + +0 value board-size +0 value target +0 value board +variable moves + +: moves-reset 0 moves ! ; +: moves+ 1 moves +! ; +: .moves ." You have made " moves @ . ." moves." ; + +: allot-board ( -- addr ) here board-size dup * cells allot ; + +: target-gen ( -- ) + board-size dup * 0 do + 2 random [char] 0 + target i cells + ! + loop +; + +: row-flip ( board n -- ) + board-size * cells + + dup board-size cells + swap do + i dup @ 1 xor swap ! + cell +loop +; + +: column-flip ( board n -- ) + cells + + dup board-size dup * cells + swap do + i dup @ 1 xor swap ! + board-size cells +loop +; + +: target>board ( -- ) + board-size dup * cells 0 do + target i + @ board i + ! + cell +loop +; + +: board-shuffle ( -- ) + board-size dup * 0 do + board board-size random 2 random if row-flip else column-flip then + loop +; + +: ask-move ( -- char ) + cr ." choose row [0-" board-size [char] 0 + 1- emit + ." ] or column [a-" board-size [char] a + 1- emit + ." ]: " + key ; + +: do-move ( char -- ) + dup emit + dup [char] a dup board-size + within + if dup board swap [char] a - column-flip + else + dup [char] 0 dup board-size + within + if dup board swap [char] 0 - row-flip + else ." - this move is not permitted!" + then then + cr drop +; + +: .header ( -- ) cr ." Target: " board-size 2 * spaces ." Board:" ; +: .column-header ( -- ) board-size 0 do i [char] a + emit space loop ; +: .row-header ( n -- ) . ." - " ; +: .bit ( board row col -- ) board-size * + cells + @ emit space ; +: .row ( board n -- ) dup .row-header board-size 0 do 2dup i swap .bit loop 2drop ; +: .boards + .header cr + 4 spaces .column-header 8 spaces .column-header cr + board-size 0 do + target i .row 4 spaces board i .row cr + loop +; + +: ?win ( -- f ) + board-size dup * 0 do + target i cells + @ board i cells + @ + <> if false unloop exit then + loop true +; + +: game-loop + begin + .boards .moves + ask-move do-move moves+ + ?win until + ." You win after " moves @ . ." moves!" +; + +: flip-bit-game ( n -- ) + to board-size + allot-board to target + allot-board to board + target-gen + target>board + board-shuffle + moves-reset + game-loop +; diff --git a/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg b/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg new file mode 100644 index 0000000000..1b23cfac2f --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/ALGOL-68/floyd-warshall-algorithm.alg @@ -0,0 +1,84 @@ +BEGIN # Floyd-Warshall algorithm - translated from the Lua sample # + + OP FMT = ( REAL v )STRING: + BEGIN + STRING result := fixed( ABS v, 0, 15 ); + IF result[ LWB result ] = "." THEN "0" +=: result FI; + WHILE result[ UPB result ] = "0" DO result := result[ : UPB result - 1 ] OD; + IF result[ UPB result ] = "." THEN result := result[ : UPB result - 1 ] FI; + IF v < 0 THEN "-" ELSE " " FI + result + END # FMT # ; + + PROC print result = ( [,]REAL dist, [,]INT nxt )VOID: + BEGIN + print( ( "pair dist path", newline ) ); + FOR i FROM 1 LWB nxt TO 1 UPB nxt DO + FOR j FROM 2 LWB nxt TO 2 UPB nxt DO + IF i /= j THEN + INT u := i + 1; + INT v = j + 1; + print( ( whole( u, 0 ), " -> ", whole( v, 0 ), " " + , FMT dist[ i, j ], " ", whole( u, 0 ) + ) + ); + WHILE u := nxt[ u - 1, v - 1 ]; + print( ( " -> " +whole( u, 0 ) ) ); + u /= v + DO SKIP OD; + print( ( newline ) ) + FI + OD + OD + END # print result # ; + + PROC floyd warshall = ( [,]INT weights, INT num vertices )VOID: + BEGIN + + REAL infinity = max real; + + [ 0 : num vertices - 1, 0 : num vertices - 1 ]REAL dist; + FOR i FROM LWB dist TO 1 UPB dist DO + FOR j FROM 2 LWB dist TO 2 UPB dist DO + dist[ i, j ] := infinity + OD + OD; + + FOR i FROM 1 LWB weights TO 1 UPB weights DO + # the weights array is one based # + []INT w = weights[ i, : ]; + dist[ w[ 1 ] - 1, w[ 2 ] - 1 ] := w[ 3 ] + OD; + + [ 0 : num vertices - 1, 0 : num vertices - 1 ]INT nxt; + FOR i FROM LWB nxt TO 1 UPB nxt DO + FOR j FROM 2 LWB nxt TO 2 UPB nxt DO + nxt[ i, j ] := IF i /= j THEN j + 1 ELSE 0 FI + OD + OD; + + FOR k FROM 2 LWB dist TO 2 UPB dist DO + FOR i FROM 1 LWB dist TO 1 UPB dist DO + FOR j FROM 2 LWB dist TO 2 UPB dist DO + IF dist[ i, k ] /= infinity AND dist[ k, j ] /= infinity THEN + IF dist[ i, k ] + dist[ k, j ] < dist[ i, j ] THEN + dist[ i, j ] := dist[ i, k ] + dist[ k, j ]; + nxt[ i, j ] := nxt[ i, k ] + FI + FI + OD + OD + OD; + + print result( dist, nxt ) + END # floyd warshall # ; + + [,]INT weights = ( ( 1, 3, -2 ) + , ( 2, 1, 4 ) + , ( 2, 3, 3 ) + , ( 3, 4, 2 ) + , ( 4, 2, -1 ) + ); + INT num vertices = 4; + floyd warshall( weights, num vertices ) + +END diff --git a/Task/Floyd-Warshall-algorithm/JavaScript/floyd-warshall-algorithm.js b/Task/Floyd-Warshall-algorithm/JavaScript/floyd-warshall-algorithm.js index 5509d0c1a8..e6c040e093 100644 --- a/Task/Floyd-Warshall-algorithm/JavaScript/floyd-warshall-algorithm.js +++ b/Task/Floyd-Warshall-algorithm/JavaScript/floyd-warshall-algorithm.js @@ -1,21 +1,49 @@ -var graph = []; -for (i = 0; i < 10; ++i) { +'use strict' +let numVertices = 4; +let weights = [ [ 1, 3, -2 ], [ 2, 1, 4 ], [ 2, 3, 3 ], [ 3, 4, 2 ], [ 4, 2, -1 ] ]; + +let graph = []; +for (let i = 0; i < numVertices; ++i) { graph.push([]); - for (j = 0; j < 10; ++j) + for (let j = 0; j < numVertices; ++j) graph[i].push(i == j ? 0 : 9999999); } -for (i = 1; i < 10; ++i) { - graph[0][i] = graph[i][0] = parseInt(Math.random() * 9 + 1); +for (let i = 0; i < weights.length; ++i) { + let w = weights[i]; + graph[w[0] - 1][w[1] - 1] = w[2]; } -for (k = 0; k < 10; ++k) { - for (i = 0; i < 10; ++i) { - for (j = 0; j < 10; ++j) { - if (graph[i][j] > graph[i][k] + graph[k][j]) - graph[i][j] = graph[i][k] + graph[k][j] +let nxt = []; +for (let i = 0; i < numVertices; ++i) { + nxt.push([]); + for (let j = 0; j < numVertices; ++j) + nxt[i].push(i == j ? 0 : j + 1); +} + +for (let k = 0; k < numVertices; ++k) { + for (let i = 0; i < numVertices; ++i) { + for (let j = 0; j < numVertices; ++j) { + if (graph[i][j] > graph[i][k] + graph[k][j]) { + graph[i][j] = graph[i][k] + graph[k][j]; + nxt[i][j] = nxt[i][k]; + } } } } -console.log(graph); +console.log("pair dist path"); +for (let i = 0; i < numVertices; ++i) { + for (let j = 0; j < numVertices; ++j) { + if (i != j) { + let u = i + 1; + let v = j + 1; + let path = u + " -> " + v + " " + graph[i][j].toString().padStart(2) + " " + u; + do { + u = nxt[u - 1][v - 1]; + path = path + " -> " + u; + } while (u != v); + console.log(path) + } + } +} diff --git a/Task/Floyd-Warshall-algorithm/Scala/floyd-warshall-algorithm.scala b/Task/Floyd-Warshall-algorithm/Scala/floyd-warshall-algorithm.scala new file mode 100644 index 0000000000..250ce4faaa --- /dev/null +++ b/Task/Floyd-Warshall-algorithm/Scala/floyd-warshall-algorithm.scala @@ -0,0 +1,50 @@ +import java.lang.String.format; + +object FloydWarshall extends App { + + val weights = Array(Array(1, 3, -2), Array(2, 1, 4), Array(2, 3, 3), Array(3, 4, 2), Array(4, 2, -1)) + val numVertices = 4 + + floydWarshall(weights, numVertices) + + def floydWarshall(weights: Array[Array[Int]], numVertices: Int): Unit = { + + val dist = Array.fill(numVertices, numVertices)(Double.PositiveInfinity) + for (w <- weights) + dist(w(0) - 1)(w(1) - 1) = w(2) + + val next = Array.ofDim[Int](numVertices, numVertices) + for (i <- 0 until numVertices; j <- 0 until numVertices if i != j) + next(i)(j) = j + 1 + + for { + k <- 0 until numVertices + i <- 0 until numVertices + j <- 0 until numVertices + if dist(i)(k) + dist(k)(j) < dist(i)(j) + } { + dist(i)(j) = dist(i)(k) + dist(k)(j) + next(i)(j) = next(i)(k) + } + + printResult(dist, next) + } + + def printResult(dist: Array[Array[Double]], next: Array[Array[Int]]): Unit = { + println("pair dist path") + for { + i <- 0 until next.length + j <- 0 until next.length if i != j + } { + var u = i + 1 + val v = j + 1 + var path = format("%d -> %d %2d %s", u, v, + (dist(i)(j)).toInt, u); + while (u != v) { + u = next(u - 1)(v - 1) + path += s" -> $u" + } + println(path) + } + } +} diff --git a/Task/Forest-fire/Applesoft-BASIC/forest-fire.basic b/Task/Forest-fire/Applesoft-BASIC/forest-fire.basic index e6867458b4..6dc94fff63 100644 --- a/Task/Forest-fire/Applesoft-BASIC/forest-fire.basic +++ b/Task/Forest-fire/Applesoft-BASIC/forest-fire.basic @@ -1,18 +1,19 @@ 100 FOR I = 17239 TO 17493 110 READ B - 120 NEXT - 130 CALL 17239 - 140 END - 150 DATA 162,23,138,32,71,248,165,38,157,60,3,165,39,157,84,3,202,16,239,162,96 - 160 DATA 134,249,134,1,160,0,132,0,152,145,0,200,208,251,232,134,1,224,128,208 - 170 DATA 244,44,86,192,44,82,192,44,84,192,44,80,192,32,50,248,162,0,134,0,169 - 180 DATA 41,133,2,133,254,169,83,133,4,165,249,133,1,133,3,133,5,73,16,133,255 - 190 DATA 133,249,138,134,45,74,168,169,15,144,2,105,224,133,46,185,60,3,133,38 - 200 DATA 185,84,3,133,39,160,1,132,44,177,2,145,254,240,79,16,93,169,0,164,44 - 210 DATA 145,254,136,81,38,37,46,81,38,145,38,164,44,200,192,41,208,224,165,2 - 220 DATA 133,0,165,3,133,1,165,4,133,2,133,254,24,105,42,133,4,165,5,73,16 - 230 DATA 133,255,73,16,133,3,105,0,133,5,166,45,232,224,48,208,159,44,0,192 - 240 DATA 48,3,76,144,67,44,16,192,44,81,192,96,198,8,208,190,169,101,133,8,169 - 250 DATA 68,208,169,169,153,208,165,198,6,208,14,198,7,208,10,169,23,133,6,169 - 260 DATA 39,133,7,208,234,177,0,17,4,136,17,0,17,2,17,4,200,200,17,0,17,2,17,4 - 270 DATA 48,213,16,137,41 + 120 POKE I,B + 130 NEXT + 140 CALL 17239 + 150 END + 160 DATA162,23,138,32,71,248,165,38,157,60,3,165,39,157,84,3,202,16,239,162,96 + 170 DATA134,249,134,1,160,0,132,0,152,145,0,200,208,251,232,134,1,224,128,208 + 180 DATA244,44,86,192,44,82,192,44,84,192,44,80,192,32,50,248,162,0,134,0,169 + 190 DATA41,133,2,133,254,169,83,133,4,165,249,133,1,133,3,133,5,73,16,133,255 + 200 DATA133,249,138,134,45,74,168,169,15,144,2,105,224,133,46,185,60,3,133,38 + 210 DATA185,84,3,133,39,160,1,132,44,177,2,145,254,240,79,16,93,169,0,164,44 + 220 DATA145,254,136,81,38,37,46,81,38,145,38,164,44,200,192,41,208,224,165,2 + 230 DATA133,0,165,3,133,1,165,4,133,2,133,254,24,105,42,133,4,165,5,73,16 + 240 DATA133,255,73,16,133,3,105,0,133,5,166,45,232,224,48,208,159,44,0,192 + 250 DATA48,3,76,144,67,44,16,192,44,81,192,96,198,8,208,190,169,101,133,8,169 + 260 DATA68,208,169,169,153,208,165,198,6,208,14,198,7,208,10,169,23,133,6,169 + 270 DATA39,133,7,208,234,177,0,17,4,136,17,0,17,2,17,4,200,200,17,0,17,2,17,4 + 280 DATA48,213,16,137,41 diff --git a/Task/Forest-fire/Commodore-BASIC/forest-fire.basic b/Task/Forest-fire/Commodore-BASIC/forest-fire.basic new file mode 100644 index 0000000000..df106267ed --- /dev/null +++ b/Task/Forest-fire/Commodore-BASIC/forest-fire.basic @@ -0,0 +1,19 @@ + 100 FOR I = 17239 TO 17493 + 110 READ B + 120 POKE I,B + 130 NEXT + 140 SYS 17239 + 150 END + 160 DATA162,23,138,32,71,248,165,38,157,60,3,165,39,157,84,3,202,16,239,162,96 + 170 DATA134,249,134,1,160,0,132,0,152,145,0,200,208,251,232,134,1,224,128,208 + 180 DATA244,44,86,192,44,82,192,44,84,192,44,80,192,32,50,248,162,0,134,0,169 + 190 DATA41,133,2,133,254,169,83,133,4,165,249,133,1,133,3,133,5,73,16,133,255 + 200 DATA133,249,138,134,45,74,168,169,15,144,2,105,224,133,46,185,60,3,133,38 + 210 DATA185,84,3,133,39,160,1,132,44,177,2,145,254,240,79,16,93,169,0,164,44 + 220 DATA145,254,136,81,38,37,46,81,38,145,38,164,44,200,192,41,208,224,165,2 + 230 DATA133,0,165,3,133,1,165,4,133,2,133,254,24,105,42,133,4,165,5,73,16 + 240 DATA133,255,73,16,133,3,105,0,133,5,166,45,232,224,48,208,159,44,0,192 + 250 DATA48,3,76,144,67,44,16,192,44,81,192,96,198,8,208,190,169,101,133,8,169 + 260 DATA68,208,169,169,153,208,165,198,6,208,14,198,7,208,10,169,23,133,6,169 + 270 DATA39,133,7,208,234,177,0,17,4,136,17,0,17,2,17,4,200,200,17,0,17,2,17,4 + 280 DATA48,213,16,137,41 diff --git a/Task/Fortunate-numbers/ALGOL-68/fortunate-numbers.alg b/Task/Fortunate-numbers/ALGOL-68/fortunate-numbers.alg new file mode 100644 index 0000000000..fb7e629305 --- /dev/null +++ b/Task/Fortunate-numbers/ALGOL-68/fortunate-numbers.alg @@ -0,0 +1,40 @@ +BEGIN # find some Fortunate numbers m, m is smallest positive integer > 1 # + # where primorial(n) + m is prime for some n # + # as all primorials are even, m must be odd # + + PR precision 2000 PR # set the number of digits for LONG LONG INT # + PR read "primes.incl.a68" PR # include prime utilities # + INT max fortunate = 500; # largeest fortunate number we will consider # + []BOOL is prime = PRIMESIEVE 5 000; + [ 1 : max fortunate ]INT fortunate; FOR i TO max fortunate DO fortunate[ i ] := 0 OD; + INT primorial pos := 0; + LONG LONG INT primorial := 1; + INT prime pos := 0; + WHILE primorial pos < 100 DO + WHILE NOT is prime[ prime pos +:= 1 ] DO SKIP OD; + primorial pos +:= 1; + primorial *:= prime pos; + INT m := 3; + WHILE NOT is probably prime( primorial + m ) AND m <= max fortunate DO m +:= 2 OD; + IF m <= max fortunate THEN + IF fortunate[ m ] = 0 THEN fortunate[ m ] := primorial pos FI + FI + OD; + print( ( "The first 50 Fortunate numbers:", newline ) ); + INT f count := 0; + FOR f TO max fortunate WHILE f count < 50 DO + IF fortunate[ f ] /= 0 THEN + print( ( whole( f, -5 ) ) ); + IF ( f count +:= 1 ) MOD 10 = 0 THEN print( ( newline ) ) FI + FI + OD; + print( ( "The primorial associated with the first 50 Fortunate numbers:", newline ) ); + f count := 0; + FOR f TO max fortunate WHILE f count < 50 DO + IF fortunate[ f ] /= 0 THEN + print( ( whole( fortunate[ f ], -5 ) ) ); + IF ( f count +:= 1 ) MOD 10 = 0 THEN print( ( newline ) ) FI + FI + OD + +END diff --git a/Task/Fortunate-numbers/C-sharp/fortunate-numbers.cs b/Task/Fortunate-numbers/C-sharp/fortunate-numbers.cs new file mode 100644 index 0000000000..22f95c2071 --- /dev/null +++ b/Task/Fortunate-numbers/C-sharp/fortunate-numbers.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +public class FortunateNumbers +{ + private const int CERTAINTY_LEVEL = 10; + + public static void Main(string[] args) + { + var primes = PrimeSieve(400); + SortedSet fortunates = new SortedSet(); + BigInteger primorial = BigInteger.One; + + foreach (var prime in primes) + { + primorial *= prime; + int candidate = 3; + while (!BigInteger.Add(primorial, candidate).IsProbablyPrime(CERTAINTY_LEVEL)) + { + candidate += 2; + } + fortunates.Add(candidate); + } + + Console.WriteLine("The first 50 distinct fortunate numbers are:"); + int count = 0; + foreach (var fortunate in fortunates) + { + if (count >= 50) break; + Console.Write($"{fortunate,4}{(count % 10 == 9 ? "\n" : "")}"); + count++; + } + } + + private static List PrimeSieve(int aNumber) + { + var sieve = new bool[aNumber + 1]; + var primes = new List(); + + for (int i = 2; i <= aNumber; i++) + { + if (!sieve[i]) + { + primes.Add(i); + for (int j = i * i; j <= aNumber && j > 0; j += i) + { + sieve[j] = true; + } + } + } + return primes; + } +} + +public static class BigIntegerExtensions +{ + private static Random random = new Random(); + + public static bool IsProbablyPrime(this BigInteger source, int certainty) + { + if (source == 2 || source == 3) + return true; + if (source < 2 || source % 2 == 0) + return false; + + BigInteger d = source - 1; + int s = 0; + + while (d % 2 == 0) + { + d /= 2; + s += 1; + } + + for (int i = 0; i < certainty; i++) + { + BigInteger a = RandomBigInteger(2, source - 2); + BigInteger x = BigInteger.ModPow(a, d, source); + if (x == 1 || x == source - 1) + continue; + + for (int r = 1; r < s; r++) + { + x = BigInteger.ModPow(x, 2, source); + if (x == 1) + return false; + if (x == source - 1) + break; + } + + if (x != source - 1) + return false; + } + + return true; + } + + private static BigInteger RandomBigInteger(BigInteger minValue, BigInteger maxValue) + { + if (minValue > maxValue) + throw new ArgumentException("minValue must be less than or equal to maxValue"); + + BigInteger range = maxValue - minValue + 1; + int length = range.ToByteArray().Length; + byte[] buffer = new byte[length]; + + BigInteger result; + do + { + random.NextBytes(buffer); + buffer[buffer.Length - 1] &= 0x7F; // Ensure non-negative + result = new BigInteger(buffer); + } while (result < minValue || result >= maxValue); + + return result; + } +} diff --git a/Task/Fractal-tree/C++/fractal-tree.cpp b/Task/Fractal-tree/C++/fractal-tree.cpp index fd8e053394..42dece4c09 100644 --- a/Task/Fractal-tree/C++/fractal-tree.cpp +++ b/Task/Fractal-tree/C++/fractal-tree.cpp @@ -6,7 +6,9 @@ using namespace std; //-------------------------------------------------------------------------------------------------- -const float PI = 3.1415926536f; +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif //-------------------------------------------------------------------------------------------------- class myBitmap @@ -128,7 +130,7 @@ class fractalTree { public: fractalTree() { _ang = DegToRadian( 24.0f ); } - float DegToRadian( float degree ) { return degree * ( PI / 180.0f ); } + float DegToRadian( float degree ) { return degree * ( M_PI / 180.0f ); } void create( myBitmap* bmp ) { diff --git a/Task/Fractal-tree/C/fractal-tree.c b/Task/Fractal-tree/C/fractal-tree.c index 738c6b6886..3a820f1cb7 100644 --- a/Task/Fractal-tree/C/fractal-tree.c +++ b/Task/Fractal-tree/C/fractal-tree.c @@ -9,8 +9,8 @@ #include #include -#ifdef WITH_CAIRO -#define PI 3.1415926535 +#ifndef M_PI +#define M_PI 3.14159265358979323846 #endif #define SIZE 800 // determines size of window @@ -74,7 +74,7 @@ void render(SDL_Surface * surface){ surface->h - 10.0, 0.0, -1.0, INITIAL_LENGTH, - PI / 8, + M_PI / 8, BRANCHES); SDL_UpdateRect(surface, 0, 0, 0, 0); } diff --git a/Task/Fractran/C-sharp/fractran-1.cs b/Task/Fractran/C-sharp/fractran-1.cs new file mode 100644 index 0000000000..a1b546059d --- /dev/null +++ b/Task/Fractran/C-sharp/fractran-1.cs @@ -0,0 +1,92 @@ +namespace System.Numerics +{ + using Fractype = (BigInteger numerator, BigInteger denominator); + struct Quotient + { + private Fractype _frac; + public Fractype Fraction + { + get => _frac; + set => _frac = Reduce(value); + } + + public bool IsIntegral => _frac.denominator == 1; + + public Quotient(BigInteger num, BigInteger den) + { + Fraction = (num, den); + } + + public static BigInteger GCD(BigInteger a, BigInteger b) + { + return (b == 0) ? a : GCD(b, a % b); + } + + private static Fractype Reduce(Fractype f) + { + if (f.denominator == 0) + throw new DivideByZeroException(); + + BigInteger gcd = Quotient.GCD(f.numerator, f.denominator); + return (f.numerator / gcd, f.denominator / gcd); + } + + public static Quotient operator *(Quotient a, Quotient b) + => new Quotient(a._frac.numerator * b._frac.numerator, a._frac.denominator * b._frac.denominator); + + public static Quotient operator *(Quotient a, BigInteger n) + => new Quotient(a._frac.numerator * n, a._frac.denominator); + + public static explicit operator Quotient(Fractype t) => new Quotient(t.numerator, t.denominator); + } + + class FRACTRAN + { + private Quotient[] code; + public FRACTRAN(Fractype[] _code) + { + code = _code.Select(x => (Quotient) x).ToArray(); + } + + public (BigInteger value, bool success) Compute(BigInteger n) + { + for (int i = 0; i < code.Length; i++) + if ((code[i] * n).IsIntegral) + return ((code[i] * n).Fraction.numerator, true); + return (0, false); + } + } + + class Program + { + public static void Main(string[] args) + { + Fractype[] frac_code = args[0].Split(" ") + .Select(x => ((BigInteger)Int32.Parse(x.Split("/")[0]), (BigInteger)Int32.Parse(x.Split("/")[1].Trim(',')))).ToArray(); + BigInteger init = new BigInteger(Int32.Parse(args[1].Trim(','))); + int steps = Int32.Parse(args[2].Trim(',')); + + FRACTRAN FRACGAME = new FRACTRAN(frac_code); + + List sequence = new List(); + sequence.Add(init); + bool halt = false; + for (int i = 0; i < steps - 1; i++) + { + var k = FRACGAME.Compute(sequence[sequence.Count - 1]); + if (k.success) + sequence.Add(k.value); + else + { + halt = true; + break; + } + } + + for (int i = 0; i < sequence.Count; i++) + Console.WriteLine((i + 1).ToString() + ": " + sequence[i]); + if (halt) + Console.WriteLine("HALT"); + } + } +} diff --git a/Task/Fractran/C-sharp/fractran-2.cs b/Task/Fractran/C-sharp/fractran-2.cs new file mode 100644 index 0000000000..14d41b2e3e --- /dev/null +++ b/Task/Fractran/C-sharp/fractran-2.cs @@ -0,0 +1,54 @@ + class Program + { + private static bool PowerOfTwo(BigInteger b) + { + while (b % 2 == 0) + b /= 2; + return b == 1; + } + + private static BigInteger BigLog2(BigInteger b) + { + BigInteger r = 0; + while (b > 1) + { + r++; + b /= 2; + } + return r; + } + + public static void Main(string[] args) + { + Fractype[] frac_code = args[0].Split(" ") + .Select(x => ((BigInteger)Int32.Parse(x.Split("/")[0]), (BigInteger)Int32.Parse(x.Split("/")[1].Trim(',')))).ToArray(); + BigInteger init = new BigInteger(Int32.Parse(args[1].Trim(','))); + int steps = Int32.Parse(args[2].Trim(',')); + + FRACTRAN FRACGAME = new FRACTRAN(frac_code); + + List sequence = new List(); + List primes = new List(); + sequence.Add(init); + bool halt = false; + while (primes.Count() < 20) + { + var k = FRACGAME.Compute(sequence[sequence.Count - 1]); + if (k.success) + sequence.Add(k.value); + else + { + halt = true; + break; + } + + if (PowerOfTwo(k.value)) + primes.Add(BigLog2(k.value)); + } + + for (int i = 0; i < primes.Count; i++) + Console.WriteLine((i + 1).ToString() + ": " + primes[i]); + if (halt) + Console.WriteLine("HALT"); + } + } diff --git a/Task/Function-composition/Bruijn/function-composition.bruijn b/Task/Function-composition/Bruijn/function-composition.bruijn new file mode 100644 index 0000000000..c6603e8e02 --- /dev/null +++ b/Task/Function-composition/Bruijn/function-composition.bruijn @@ -0,0 +1,21 @@ +:import std/Number . + +# 1x composition, bluebird combinator +…∘… [[[2 (1 0)]]] + +:test (((inc ∘ (mul (+2))) (+3)) =? (+7)) ([[1]]) + +# 2x composition, blackbird combinator +…∘∘… [[[[3 (2 1 0)]]]] + +:test (((inc ∘∘ mul) (+2) (+3)) =? (+7)) ([[1]]) + +# 3x composition, bunting combinator +…∘∘∘… [[[[[4 (3 2 1 0)]]]]] + +:test (((inc ∘∘∘ (add ∘∘ mul)) (+1) (+2) (+4)) =? (+7)) ([[1]]) + +# reverse composition, queer bird combinator +…→… [[[1 (2 0)]]] + +:test ((((mul (+2)) → inc) (+3)) =? (+7)) ([[1]]) diff --git a/Task/Function-composition/Elena/function-composition.elena b/Task/Function-composition/Elena/function-composition.elena index 54a79583c3..2361868faf 100644 --- a/Task/Function-composition/Elena/function-composition.elena +++ b/Task/Function-composition/Elena/function-composition.elena @@ -8,7 +8,7 @@ extension op : Func1 public program() { - var fg := (x => x + 1).compose:(x => x * x); + var fg := (x => x + 1).compose::(x => x * x); console.printLine(fg(3)) } diff --git a/Task/Function-definition/Langur/function-definition-5.langur b/Task/Function-definition/Langur/function-definition-5.langur new file mode 100644 index 0000000000..3c3475afe5 --- /dev/null +++ b/Task/Function-definition/Langur/function-definition-5.langur @@ -0,0 +1 @@ +val .writeit = impure f(.x) { writeln .x } diff --git a/Task/GUI-component-interaction/Elena/gui-component-interaction-2.elena b/Task/GUI-component-interaction/Elena/gui-component-interaction-2.elena deleted file mode 100644 index 60705accbe..0000000000 --- a/Task/GUI-component-interaction/Elena/gui-component-interaction-2.elena +++ /dev/null @@ -1,8 +0,0 @@ -
- - - - -
diff --git a/Task/GUI-component-interaction/Elena/gui-component-interaction-3.elena b/Task/GUI-component-interaction/Elena/gui-component-interaction-3.elena deleted file mode 100644 index baba22a101..0000000000 --- a/Task/GUI-component-interaction/Elena/gui-component-interaction-3.elena +++ /dev/null @@ -1,44 +0,0 @@ -import xforms; -import forms; -import extensions; - -public class MainWindow -{ - SDIForm form; - - Button btmIncrement; - Button btmRandom; - Edit txtNumber; - - constructor new() - { - form := xforms.executePath("main.xs", self); - - btmIncrement := form.Controls.btmIncrement; - btmRandom := form.Controls.btmRandom; - txtNumber := form.Controls.txtNumber; - } - - onButtonIncrementClick(sender) - { - var number := txtNumber.Value.toInt(); - - number := number + 1; - self.changeTextBoxValue(number) - } - - onButtonRandomClick(sender) - { - if(messageDialog.showQuestion("Inf", "Really reset to random value?")) - { - self.changeTextBoxValue(randomGenerator.eval(99999999)) - } - } - - private changeTextBoxValue(number) - { - txtNumber.Caption := number.toString() - } - - dispatch() => form; -} diff --git a/Task/GUI-component-interaction/Elena/gui-component-interaction-1.elena b/Task/GUI-component-interaction/Elena/gui-component-interaction.elena similarity index 91% rename from Task/GUI-component-interaction/Elena/gui-component-interaction-1.elena rename to Task/GUI-component-interaction/Elena/gui-component-interaction.elena index 963127c707..774cd067de 100644 --- a/Task/GUI-component-interaction/Elena/gui-component-interaction-1.elena +++ b/Task/GUI-component-interaction/Elena/gui-component-interaction.elena @@ -15,9 +15,9 @@ public class MainWindow : SDIDialog txtNumber := Edit.new(); self - .appendControl:btmIncrement - .appendControl:btmRandom - .appendControl:txtNumber; + .appendControl(btmIncrement) + .appendControl(btmRandom) + .appendControl(txtNumber); self.Caption := "Rosseta Code"; self.setRegion(100, 100, 180, 140); diff --git a/Task/Gamma-function/Rust/gamma-function.rust b/Task/Gamma-function/Rust/gamma-function.rust new file mode 100644 index 0000000000..4916428977 --- /dev/null +++ b/Task/Gamma-function/Rust/gamma-function.rust @@ -0,0 +1,9 @@ +use std::f64::consts; + +fn main() { + let gamma = |x: f64| { assert_ne!(x, 0.0); (2.0*consts::PI/x).sqrt() * (x * (x/consts::E).ln()).exp()}; + (1..=20).for_each(|x| { + let x = f64::from(x) / 10.0; + println!("{:.02} => {:.10}", x, gamma(x)); + }); +} diff --git a/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy b/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy new file mode 100644 index 0000000000..dac0cbf67d --- /dev/null +++ b/Task/Gauss-Jordan-matrix-inversion/EasyLang/gauss-jordan-matrix-inversion.easy @@ -0,0 +1,61 @@ +proc rref . m[][] . + nrow = len m[][] + ncol = len m[1][] + lead = 1 + for r to nrow + if lead > ncol + return + . + i = r + while m[i][lead] = 0 + i += 1 + if i > nrow + i = r + lead += 1 + if lead > ncol + return + . + . + . + swap m[i][] m[r][] + m = m[r][lead] + for k to ncol + m[r][k] /= m + . + for i to nrow + if i <> r + m = m[i][lead] + for k to ncol + m[i][k] -= m * m[r][k] + . + . + . + lead += 1 + . +. +proc inverse . mat[][] inv[][] . + inv[][] = [ ] + ln = len mat[][] + for i to ln + if len mat[i][] <> ln + # not a square matrix + return + . + aug[][] &= [ ] + len aug[i][] 2 * ln + for j to ln + aug[i][j] = mat[i][j] + . + aug[i][ln + i] = 1 + . + rref aug[][] + for i to ln + inv[][] &= [ ] + for j = ln + 1 to 2 * ln + inv[i][] &= aug[i][j] + . + . +. +test[][] = [ [ 1 2 3 ] [ 4 1 6 ] [ 7 8 9 ] ] +inverse test[][] inv[][] +print inv[][] diff --git a/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy b/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy new file mode 100644 index 0000000000..12bd0ba26f --- /dev/null +++ b/Task/Gaussian-elimination/EasyLang/gaussian-elimination.easy @@ -0,0 +1,37 @@ +proc gauss_elim . a[][] b[] x[] . + n = len a[][] + for i to n + maxr = i + maxv = abs a[i][i] + for j = i + 1 to n + if abs a[j][i] > maxv + maxr = j + maxv = abs a[j][i] + . + . + if maxr <> i + swap a[maxr][] a[i][] + swap b[maxr] b[i] + . + for j = i + 1 to n + f = a[j][i] / a[i][i] + for k = i to n + a[j][k] -= f * a[i][k] + . + b[j] -= f * b[i] + . + . + x[] = [ ] + len x[] n + for i = n downto 1 + rhs = b[i] + for j = i + 1 to n + rhs -= a[i][j] * x[j] + . + x[i] = rhs / a[i][i] + . +. +a[][] = [ [ 1.00 0.00 0.00 0.00 0.00 0.00 ] [ 1.00 0.63 0.39 0.25 0.16 0.10 ] [ 1.00 1.26 1.58 1.98 2.49 3.13 ] [ 1.00 1.88 3.55 6.70 12.62 23.80 ] [ 1.00 2.51 6.32 15.88 39.90 100.28 ] [ 1.00 3.14 9.87 31.01 97.41 306.02 ] ] +b[] = [ -0.01 0.61 0.91 0.99 0.60 0.02 ] +gauss_elim a[][] b[] x[] +print x[] diff --git a/Task/Gaussian-elimination/Scala/gaussian-elimination.scala b/Task/Gaussian-elimination/Scala/gaussian-elimination.scala new file mode 100644 index 0000000000..ed99dd1688 --- /dev/null +++ b/Task/Gaussian-elimination/Scala/gaussian-elimination.scala @@ -0,0 +1,99 @@ +object GaussianElimination { + def solve(a: Array[Array[Double]], b: Array[Array[Double]]): Double = { + if (a == null || b == null || a.length == 0 || b.length == 0) { + throw new IllegalArgumentException("Invalid dimensions") + } + + val n = b.length + val p = b(0).length + + if (a.length != n || a(0).length != n) { + throw new IllegalArgumentException("Invalid dimensions") + } + + var det = 1.0 + + for (i <- 0 until n - 1) { + var k = i + + for (j <- i + 1 until n) { + if (Math.abs(a(j)(i)) > Math.abs(a(k)(i))) { + k = j + } + } + + if (k != i) { + det = -det + + for (j <- i until n) { + val s = a(i)(j) + a(i)(j) = a(k)(j) + a(k)(j) = s + } + + for (j <- 0 until p) { + val s = b(i)(j) + b(i)(j) = b(k)(j) + b(k)(j) = s + } + } + + for (j <- i + 1 until n) { + val s = a(j)(i) / a(i)(i) + + for (k <- i + 1 until n) { + a(j)(k) -= s * a(i)(k) + } + + for (k <- 0 until p) { + b(j)(k) -= s * b(i)(k) + } + } + } + + for (i <- n - 1 to 0 by -1) { + for (j <- i + 1 until n) { + val s = a(i)(j) + + for (k <- 0 until p) { + b(i)(k) -= s * b(j)(k) + } + } + + val s = a(i)(i) + det *= s + + for (k <- 0 until p) { + b(i)(k) /= s + } + } + + det + } + + def main(args: Array[String]): Unit = { + val a = Array( + Array(4.0, 1.0, 0.0, 0.0, 0.0), + Array(1.0, 4.0, 1.0, 0.0, 0.0), + Array(0.0, 1.0, 4.0, 1.0, 0.0), + Array(0.0, 0.0, 1.0, 4.0, 1.0), + Array(0.0, 0.0, 0.0, 1.0, 4.0) + ) + + val b = Array( + Array(1.0 / 2.0), + Array(2.0 / 3.0), + Array(3.0 / 4.0), + Array(4.0 / 5.0), + Array(5.0 / 6.0) + ) + + val x = Array(39.0 / 400.0, 11.0 / 100.0, 31.0 / 240.0, 37.0 / 300.0, 71.0 / 400.0) + + println("det: " + solve(a, b)) + + for (i <- 0 until 5) { + printf("%12.8f %12.4e\n", b(i)(0), b(i)(0) - x(i)) + } + } +} diff --git a/Task/Generate-Chess960-starting-position/C-sharp/generate-chess960-starting-position.cs b/Task/Generate-Chess960-starting-position/C-sharp/generate-chess960-starting-position.cs new file mode 100644 index 0000000000..3925cf8ea6 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/C-sharp/generate-chess960-starting-position.cs @@ -0,0 +1,80 @@ +using System; + +class Program +{ + struct Symbols + { + public char K, Q, R, B, N; + + public Symbols(char k, char q, char r, char b, char n) + { + K = k; Q = q; R = r; B = b; N = n; + } + } + + private static Symbols A = new Symbols('K', 'Q', 'R', 'B', 'N'); + private static Symbols W = new Symbols('♔', '♕', '♖', '♗', '♘'); + private static Symbols B = new Symbols('♚', '♛', '♜', '♝', '♞'); + + private static string[] krn = new string[] + { + "nnrkr", "nrnkr", "nrknr", "nrkrn", + "rnnkr", "rnknr", "rnkrn", + "rknnr", "rknrn", + "rkrnn" + }; + + private static string Chess960(Symbols sym, int id) + { + char[] pos = new char[8]; + int q = id / 4, r = id % 4; + pos[r * 2 + 1] = sym.B; + r = q % 4; q /= 4; + pos[r * 2] = sym.B; + r = q % 6; q /= 6; + int placementIndex = 0; // Adjusted variable name to prevent conflict + for (int i = 0; ; i++) + { + if (pos[i] != '\0') continue; + if (r == 0) + { + pos[i] = sym.Q; + break; + } + r--; + } + while (pos[placementIndex] != '\0') placementIndex++; // Adjusted loop to prevent conflict + foreach (char f in krn[q]) + { + while (pos[placementIndex] != '\0') placementIndex++; + switch (f) + { + case 'k': + pos[placementIndex] = sym.K; + break; + case 'r': + pos[placementIndex] = sym.R; + break; + case 'n': + pos[placementIndex] = sym.N; + break; + } + } + return new string(pos); + } + + static void Main(string[] args) + { + Console.WriteLine(" ID Start position"); + foreach (int id in new int[] { 0, 518, 959 }) + { + Console.WriteLine($"{id,3} {Chess960(A, id)}"); + } + Console.WriteLine("\nRandom"); + Random rand = new Random(); + for (int i = 0; i < 5; i++) + { + Console.WriteLine(Chess960(W, rand.Next(960))); + } + } +} diff --git a/Task/Generate-Chess960-starting-position/Prolog/generate-chess960-starting-position-1.pro b/Task/Generate-Chess960-starting-position/Prolog/generate-chess960-starting-position-1.pro new file mode 100644 index 0000000000..abfe908b60 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Prolog/generate-chess960-starting-position-1.pro @@ -0,0 +1,12 @@ +check(Row) :- + nth1(King, Row, ♔), + nth1(Rook1, Row, ♖), + nth1(Rook2, Row, ♖), + nth1(Bishop1, Row, ♗), + nth1(Bishop2, Row, ♗), + Rook1 < King, King < Rook2, + (Bishop1 + Bishop2) mod 2 =:= 1. + +generate(Row) :- + random_permutation([♖,♘,♗,♕,♔,♗,♘,♖], Row), + check(Row) ; generate(Row). diff --git a/Task/Generate-Chess960-starting-position/Prolog/generate-chess960-starting-position-2.pro b/Task/Generate-Chess960-starting-position/Prolog/generate-chess960-starting-position-2.pro new file mode 100644 index 0000000000..c89dce15f8 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Prolog/generate-chess960-starting-position-2.pro @@ -0,0 +1,5 @@ +?- generate(X). +X = [♘, ♗, ♖, ♕, ♘, ♔, ♗, ♖] ; +X = [♘, ♗, ♖, ♕, ♘, ♔, ♗, ♖] ; +X = [♘, ♖, ♘, ♕, ♔, ♖, ♗, ♗] ; +X = [♘, ♖, ♘, ♕, ♔, ♖, ♗, ♗] diff --git a/Task/Generic-swap/Langur/generic-swap-2.langur b/Task/Generic-swap/Langur/generic-swap-2.langur deleted file mode 100644 index bd298362ab..0000000000 --- a/Task/Generic-swap/Langur/generic-swap-2.langur +++ /dev/null @@ -1 +0,0 @@ -(.abc[3], .def[3]) = (.def[3], .abc[3]) diff --git a/Task/Generic-swap/Langur/generic-swap-1.langur b/Task/Generic-swap/Langur/generic-swap.langur similarity index 100% rename from Task/Generic-swap/Langur/generic-swap-1.langur rename to Task/Generic-swap/Langur/generic-swap.langur diff --git a/Task/Get-system-command-output/XPL0/get-system-command-output.xpl0 b/Task/Get-system-command-output/XPL0/get-system-command-output.xpl0 new file mode 100644 index 0000000000..b2f413624f --- /dev/null +++ b/Task/Get-system-command-output/XPL0/get-system-command-output.xpl0 @@ -0,0 +1,6 @@ +int C; +repeat C:= ChIn(1); + if C>=^a & C<=^z then \lowercase letters to uppercase + C:= C & ~$20; + ChOut(0, C); +until C = $1A diff --git a/Task/Giuga-numbers/Mathematica/giuga-numbers.math b/Task/Giuga-numbers/Mathematica/giuga-numbers.math new file mode 100644 index 0000000000..324f756348 --- /dev/null +++ b/Task/Giuga-numbers/Mathematica/giuga-numbers.math @@ -0,0 +1,15 @@ +IsGiuga[n_Integer] := Module[{factors}, + factors = FactorInteger[n]; + AllTrue[factors, Function[{f}, + Mod[Quotient[n, f[[1]]] - 1, f[[1]]] == 0 && f[[1]] != n]] +] + +GetGiuga[N_Integer] := Module[{giugaNumbers = {}, i = 4}, + While[Length[giugaNumbers] < N, + If[IsGiuga[i], AppendTo[giugaNumbers, i]]; + i++ + ]; + giugaNumbers +] + +Print[GetGiuga[4]] diff --git a/Task/Giuga-numbers/PARI-GP/giuga-numbers.parigp b/Task/Giuga-numbers/PARI-GP/giuga-numbers.parigp new file mode 100644 index 0000000000..7b4dd0aea2 --- /dev/null +++ b/Task/Giuga-numbers/PARI-GP/giuga-numbers.parigp @@ -0,0 +1,19 @@ +is_giuga(n) = { + my(factors = factor(n)); + for (i = 1, #factors[,1], + if (factors[i,1] == n, return(0)); + if (Mod(n \ factors[i,1] - 1, factors[i,1]) != 0, return(0)); + ); + return(1); +} + +get_giuga(N) = { + my(giugaNumbers = [], i = 4); + while(#giugaNumbers < N, + if (is_giuga(i), giugaNumbers = concat(giugaNumbers, i)); + i++; + ); + giugaNumbers +} + +print(get_giuga(4)) diff --git a/Task/Giuga-numbers/Scala/giuga-numbers.scala b/Task/Giuga-numbers/Scala/giuga-numbers.scala new file mode 100644 index 0000000000..7ed7c4dc11 --- /dev/null +++ b/Task/Giuga-numbers/Scala/giuga-numbers.scala @@ -0,0 +1,39 @@ +object GiugaNumbers { + + private var results: List[Int] = List() + def main(args: Array[String]): Unit = { + val primes: List[Int] = List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59) + + val primeCounts: List[Int] = List(3, 4, 5) + for (primeCount <- primeCounts) { + var primeFactors: List[Int] = List.fill(primeCount)(0) + combinations(primes, primeCount, 0, 0, primeFactors) + } + + val sortedResults = results.sorted + println(s"Found Giuga numbers: $sortedResults") + } + + private def checkIfGiugaNumber(primeFactors: List[Int]): Unit = { + val product: Int = primeFactors.reduce(Math.multiplyExact) + for (factor <- primeFactors) { + val divisor: Int = factor * factor + if ((product - factor) % divisor != 0) { + return + } + } + results :+= product + } + + private def combinations(primes: List[Int], primeCount: Int, index: Int, level: Int, primeFactors: List[Int]): Unit = { + if (level == primeCount) { + checkIfGiugaNumber(primeFactors) + return + } + + for (i <- index until primes.length) { + val updatedPrimeFactors = primeFactors.updated(level, primes(i)) + combinations(primes, primeCount, i + 1, level + 1, updatedPrimeFactors) + } + } +} diff --git a/Task/Golden-ratio-Convergence/C-sharp/golden-ratio-convergence.cs b/Task/Golden-ratio-Convergence/C-sharp/golden-ratio-convergence.cs new file mode 100644 index 0000000000..b3bfccf9c2 --- /dev/null +++ b/Task/Golden-ratio-Convergence/C-sharp/golden-ratio-convergence.cs @@ -0,0 +1,22 @@ +using System; + +public class GoldenRatio { + static void Iterate() { + double oldPhi = 1.0, phi = 1.0, limit = 1e-5; + int iters = 0; + while (true) { + phi = 1.0 + 1.0 / oldPhi; + iters++; + if (Math.Abs(phi - oldPhi) <= limit) break; + oldPhi = phi; + } + Console.WriteLine($"Final value of phi : {phi:0.00000000000000}"); + double actualPhi = (1.0 + Math.Sqrt(5.0)) / 2.0; + Console.WriteLine($"Number of iterations : {iters}"); + Console.WriteLine($"Error (approx) : {phi - actualPhi:0.00000000000000}"); + } + + public static void Main(string[] args) { + Iterate(); + } +} diff --git a/Task/Graph-colouring/C-sharp/graph-colouring.cs b/Task/Graph-colouring/C-sharp/graph-colouring.cs new file mode 100644 index 0000000000..b772807705 --- /dev/null +++ b/Task/Graph-colouring/C-sharp/graph-colouring.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public static class GraphColoring +{ + public static void Main(string[] args) + { + Colorize("0-1 1-2 2-0 3"); + Colorize("1-6 1-7 1-8 2-5 2-7 2-8 3-5 3-6 3-8 4-5 4-6 4-7"); + Colorize("1-4 1-6 1-8 3-2 3-6 3-8 5-2 5-4 5-8 7-2 7-4 7-6"); + Colorize("1-6 7-1 8-1 5-2 2-7 2-8 3-5 6-3 3-8 4-5 4-6 4-7"); + } + + private static void Colorize(string graphRepresentation) + { + List graph = InitializeGraph(graphRepresentation); + List nodes = new List(graph); + while (nodes.Any()) + { + Node maxNode = nodes.OrderByDescending(n => n.Saturation).First(); + maxNode.Color = MinColor(maxNode); + UpdateSaturation(maxNode, nodes); + nodes.Remove(maxNode); + } + + Console.WriteLine("Graph: " + graphRepresentation); + Display(graph); + } + + private static Color MinColor(Node node) + { + HashSet colorsUsed = ColorsUsed(node); + foreach (Color color in Enum.GetValues(typeof(Color))) + { + if (!colorsUsed.Contains(color)) + { + return color; + } + } + return Color.NoColor; + } + + private static HashSet ColorsUsed(Node node) + { + return new HashSet(node.Neighbours.Select(n => n.Color)); + } + + private static void UpdateSaturation(Node node, List nodes) + { + foreach (Node neighbour in node.Neighbours) + { + if (neighbour.Color == Color.NoColor) + { + neighbour.Saturation = ColorsUsed(neighbour).Count; + } + } + } + + private static void Display(List nodes) + { + HashSet graphColors = new HashSet(nodes.Select(n => n.Color)); + foreach (Node node in nodes) + { + Console.Write($"Node {node.Index}: color = {node.Color}"); + if (node.Neighbours.Any()) + { + var indexes = node.Neighbours.Select(n => n.Index).ToList(); + Console.Write(new string(' ', 8 - node.Color.ToString().Length) + "neighbours = " + string.Join(", ", indexes)); + } + Console.WriteLine(); + } + + Console.WriteLine("Number of colours used: " + graphColors.Count); + Console.WriteLine(); + } + + private static List InitializeGraph(string graphRepresentation) + { + SortedDictionary map = new SortedDictionary(); + foreach (string element in graphRepresentation.Split(' ')) + { + if (element.Contains("-")) + { + string[] parts = element.Split('-'); + int index1 = int.Parse(parts[0]); + int index2 = int.Parse(parts[1]); + Node node1 = map.GetOrAdd(index1, () => new Node(index1)); + Node node2 = map.GetOrAdd(index2, () => new Node(index2)); + node1.Neighbours.Add(node2); + node2.Neighbours.Add(node1); + } + else + { + int index = int.Parse(element); + map.GetOrAdd(index, () => new Node(index)); + } + } + + return new List(map.Values); + } + + public enum Color { Blue, Green, Red, Yellow, Cyan, Orange, NoColor } + + public class Node + { + public Node(int index) + { + Index = index; + Color = Color.NoColor; + Neighbours = new HashSet(); + } + + public int Index { get; } + public int Saturation { get; set; } + public Color Color { get; set; } + public HashSet Neighbours { get; } + } + + private static TValue GetOrAdd(this IDictionary dictionary, TKey key, Func valueFactory) + { + if (!dictionary.TryGetValue(key, out TValue value)) + { + value = valueFactory(); + dictionary[key] = value; + } + return value; + } +} diff --git a/Task/Gray-code/Jq/gray-code.jq b/Task/Gray-code/Jq/gray-code.jq new file mode 100644 index 0000000000..cb4f7ad97c --- /dev/null +++ b/Task/Gray-code/Jq/gray-code.jq @@ -0,0 +1,38 @@ +def encode: + def flip: if . == 1 then 0 else 1 end; + . as $b + | reduce range(1; length) as $i ($b; + if $b[$i-1] == 1 then .[$i] |= flip + else . + end ) ; + +def decode: + def xor($a;$b): ($a + $b) % 2; + . as $g + | reduce range(1; length) as $i (.[:1]; + .[$i] = xor($g[$i]; .[$i-1]) ) ; + + +# input: a non-negative integer +# output: a binary array, least-significant bit first +def to_binary: + if . == 0 then [0] + else [recurse( if . == 0 then empty else ./2 | floor end ) % 2] + | .[:-1] # remove the uninteresting 0 + end ; + +def lpad($len; $fill): + tostring + | ($len - length) as $l + | if $l <= 0 then . + else ($fill * $l)[:$l] + . + end; + +def pp: map(tostring) | join("") | lpad(5; "0"); + +### The task +"decimal binary gray roundtrip", +(range(0; 32) as $i + | ($i | to_binary | reverse) as $b + | ($b|encode) as $g + | " \($i|lpad(2;" ")) \($b|pp) \($g|pp) \($g|decode == $b)" ) diff --git a/Task/Greatest-common-divisor/EasyLang/greatest-common-divisor.easy b/Task/Greatest-common-divisor/EasyLang/greatest-common-divisor.easy index 92078d6b8b..b66fa24d09 100644 --- a/Task/Greatest-common-divisor/EasyLang/greatest-common-divisor.easy +++ b/Task/Greatest-common-divisor/EasyLang/greatest-common-divisor.easy @@ -1,8 +1,7 @@ func gcd a b . while b <> 0 - h = b - b = a mod b - a = h + swap a b + b = b mod a . return a . diff --git a/Task/Greatest-common-divisor/Elm/greatest-common-divisor.elm b/Task/Greatest-common-divisor/Elm/greatest-common-divisor.elm new file mode 100644 index 0000000000..600d41fbf4 --- /dev/null +++ b/Task/Greatest-common-divisor/Elm/greatest-common-divisor.elm @@ -0,0 +1,37 @@ +import Html exposing (Html, div, h1, p, text) +import Html.Attributes exposing (style) + + +-- Test cases + +nr1 : Int +nr1 = + 2 * 3 * 5 * 7 * 11 + + +nr2 : Int +nr2 = + 7 * 11 * 13 * 17 * 23 + + +main : Html msg +main = + div [ style "margin" "5%", style "font-size" "1.5em", style "color" "blue" ] + [ h1 [ style "font-size" "1.5em" ] [ text "GCD Calculator" ] + , text + ("number a = " + ++ String.fromInt nr1 + ++ ", number b = " + ++ String.fromInt nr2 + ) + , p [] [ text ("GCD = " ++ String.fromInt (gcd nr1 nr2)) ] + ] + + +gcd : Int -> Int -> Int +gcd anr bnr = + if bnr /= 0 then + gcd bnr (modBy bnr anr) + + else + abs anr diff --git a/Task/Greatest-common-divisor/PowerPC-Assembly/greatest-common-divisor.ppc b/Task/Greatest-common-divisor/PowerPC-Assembly/greatest-common-divisor.ppc new file mode 100644 index 0000000000..536b6851ed --- /dev/null +++ b/Task/Greatest-common-divisor/PowerPC-Assembly/greatest-common-divisor.ppc @@ -0,0 +1,123 @@ +#include +_gcd_string: + .ascii "gcd(" + _gcd_string_len = . - _gcd_string +_gcd_close_string: + .ascii ") = " + _gcd_close_string_len = . - _gcd_close_string + + .equiv STDIN, 0 + .equiv STDOUT, 1 + + .align 4 + .section ".text" + .global _start + .section ".opd","aw" + .align 3 +_start: + .quad ._start,.TOC.@tocbase,0 + .previous + .global ._start +._start: + li r30, 1071 + li r31, 1029 + # move the loaded values into the argument registers + mr r3, r30 + mr r4, r31 + bl gcd + # save the result for printing later + mr r29, r3 + addis r4, r2, _gcd_string@toc@ha + addi r4, r4, _gcd_string@toc@l + li r5, _gcd_string_len + bl print_string + mr r3, r30 + bl print_integer + li r3, ',' + bl print_char + mr r3, r31 + bl print_integer + addis r4, r2, _gcd_close_string@toc@ha + addi r4, r4, _gcd_close_string@toc@l + li r5, _gcd_close_string_len + bl print_string + mr r3, r29 + bl print_integer + li r3, '\n' + bl print_char + li r0,SYS_exit # syscall number (sys_exit) + li r3,0 # first argument: exit code + sc # call kernel + +gcd: + cmpd r3, r4 + bge _gcd + mr r5, r3 + mr r3, r4 + mr r4, r5 +_gcd: + cmpdi r4, 0 + beqlr + mr r5, r3 + mr r3, r4 + modud r4, r5, r4 + b _gcd + +# r4 is the address of the string +# r5 is the length of the string +print_string: + li r0, SYS_write + li r3, STDOUT + sc + blr + +print_char: + mr r4, r3 + li r0, SYS_write + li r3, STDOUT + stb r4, -1(sp) + addi r4, sp, -1 + li r5, 1 + sc + blr + +print_integer: + # r3 is the integer to print + # r4 is the working register + # r5 holds the current address to write to the string + # r6 is 10 for division operations + # r7 is working storage + mr r5, sp + li r6, 10 + neg r4, r3 + cmpdi r3, 0 + bne 1f + li r7, '0' + stbu r7, -1(r5) + b 3f +1: + isellt r4, r4, r3 # r4 = abs(r3) +1: + modsd r7, r4, r6 + divd r4, r4, r6 + addi r7, r7, '0' + stbu r7, -1(r5) + cmpdi r4, 0 + beq 1f + b 1b + +1: + cmpdi r3, 0 + blt 2f +3: + mr r4, r5 + subf r5, r5, sp + mflr r14 + bl print_string + mtlr r14 + blr + +2: + li r7, '-' + stbu r7, -1(r5) + b 3b diff --git a/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor-1.basic b/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor-1.basic deleted file mode 100644 index 5c5743f69d..0000000000 --- a/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor-1.basic +++ /dev/null @@ -1,9 +0,0 @@ -Procedure GCD(x, y) - Protected r - While y <> 0 - r = x % y - x = y - y = r - Wend - ProcedureReturn y -EndProcedure diff --git a/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor-2.basic b/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor-2.basic deleted file mode 100644 index 053fe34a33..0000000000 --- a/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor-2.basic +++ /dev/null @@ -1,8 +0,0 @@ -Procedure GCD(x, y) - Protected r - r = x % y - If (r > 0) - y = GCD(y, r) - EndIf - ProcedureReturn y -EndProcedure diff --git a/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor.basic b/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor.basic new file mode 100644 index 0000000000..b29a94857f --- /dev/null +++ b/Task/Greatest-common-divisor/PureBasic/greatest-common-divisor.basic @@ -0,0 +1,16 @@ +Import "" ;msvcrt.lib + AbsI(Quad.q) As "_abs64" + AbsL(Long.l) As "labs" +EndImport +Procedure.i GCD(u.i, v.i) + Protected.i t + While v <> 0 + t = v + v = u % v + u = t + Wend + ProcedureReturn AbsI(u) ; Avoid float conversion with Abs(u). +EndProcedure +Debug GCD(18, 12) ; 6 +Debug GCD(1071, 1029) ; 21 +Debug GCD(3528, -3780) ; 252 diff --git a/Task/Greatest-common-divisor/Raku/greatest-common-divisor-3.raku b/Task/Greatest-common-divisor/Raku/greatest-common-divisor-3.raku index f46e0769f4..e3ead41f57 100644 --- a/Task/Greatest-common-divisor/Raku/greatest-common-divisor-3.raku +++ b/Task/Greatest-common-divisor/Raku/greatest-common-divisor-3.raku @@ -1 +1 @@ -my &gcd = { ($^a.abs, $^b.abs, * % * ... 0)[*-2] } +{ $^b ?? &?BLOCK( $^b, $^a % $^b ) !! $^a } diff --git a/Task/Greatest-common-divisor/Raku/greatest-common-divisor-4.raku b/Task/Greatest-common-divisor/Raku/greatest-common-divisor-4.raku index 7d7fe222da..f46e0769f4 100644 --- a/Task/Greatest-common-divisor/Raku/greatest-common-divisor-4.raku +++ b/Task/Greatest-common-divisor/Raku/greatest-common-divisor-4.raku @@ -1 +1 @@ -my $gcd = $a gcd $b; +my &gcd = { ($^a.abs, $^b.abs, * % * ... 0)[*-2] } diff --git a/Task/Greatest-common-divisor/Raku/greatest-common-divisor-5.raku b/Task/Greatest-common-divisor/Raku/greatest-common-divisor-5.raku index cd9880fbea..7d7fe222da 100644 --- a/Task/Greatest-common-divisor/Raku/greatest-common-divisor-5.raku +++ b/Task/Greatest-common-divisor/Raku/greatest-common-divisor-5.raku @@ -1,4 +1 @@ -[gcd] @list; # reduce with gcd -@alist Zgcd @blist; # lazy zip with gcd -@alist Xgcd @blist; # lazy cross with gcd -@alist »gcd« @blist; # parallel gcd +my $gcd = $a gcd $b; diff --git a/Task/Greatest-common-divisor/Raku/greatest-common-divisor-6.raku b/Task/Greatest-common-divisor/Raku/greatest-common-divisor-6.raku new file mode 100644 index 0000000000..cd9880fbea --- /dev/null +++ b/Task/Greatest-common-divisor/Raku/greatest-common-divisor-6.raku @@ -0,0 +1,4 @@ +[gcd] @list; # reduce with gcd +@alist Zgcd @blist; # lazy zip with gcd +@alist Xgcd @blist; # lazy cross with gcd +@alist »gcd« @blist; # parallel gcd diff --git a/Task/Greatest-common-divisor/Refal/greatest-common-divisor.refal b/Task/Greatest-common-divisor/Refal/greatest-common-divisor.refal new file mode 100644 index 0000000000..91066da551 --- /dev/null +++ b/Task/Greatest-common-divisor/Refal/greatest-common-divisor.refal @@ -0,0 +1,8 @@ +$ENTRY Go { + = >; +}; + +Gcd { + s.M 0 = s.M; + s.M s.N = >; +}; diff --git a/Task/Greatest-common-divisor/TypeScript/greatest-common-divisor-3.ts b/Task/Greatest-common-divisor/TypeScript/greatest-common-divisor-3.ts new file mode 100644 index 0000000000..5069a3e212 --- /dev/null +++ b/Task/Greatest-common-divisor/TypeScript/greatest-common-divisor-3.ts @@ -0,0 +1 @@ +⊙◌⍢(⊃∘◿:)(±,) diff --git a/Task/Guess-the-number-With-feedback/C/guess-the-number-with-feedback.c b/Task/Guess-the-number-With-feedback/C/guess-the-number-with-feedback.c index c98b27e337..da09923f74 100644 --- a/Task/Guess-the-number-With-feedback/C/guess-the-number-with-feedback.c +++ b/Task/Guess-the-number-With-feedback/C/guess-the-number-with-feedback.c @@ -12,6 +12,7 @@ int main(){ number = lower_limit + rand() % (upper_limit - lower_limit + 1); printf( "Guess the number between %d and %d: ", lower_limit, upper_limit ); + fflush(stdout); // Flush the output buffer while( scanf( "%d", &guess ) == 1 ){ if( number == guess ){ 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 32a353df16..9acac39036 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,5 +1,5 @@ print "Guess a number between 1 and 100!" -n = random 100 +n = randint 100 repeat g = number input write g diff --git a/Task/Guess-the-number/EasyLang/guess-the-number.easy b/Task/Guess-the-number/EasyLang/guess-the-number.easy index 07a430d78b..9bdaaac98d 100644 --- a/Task/Guess-the-number/EasyLang/guess-the-number.easy +++ b/Task/Guess-the-number/EasyLang/guess-the-number.easy @@ -1,4 +1,4 @@ -n = random 10 +n = randint 10 write "Guess a number between 1 and 10: " repeat g = number input diff --git a/Task/Hailstone-sequence/Bruijn/hailstone-sequence.bruijn b/Task/Hailstone-sequence/Bruijn/hailstone-sequence.bruijn new file mode 100644 index 0000000000..cd759cb715 --- /dev/null +++ b/Task/Hailstone-sequence/Bruijn/hailstone-sequence.bruijn @@ -0,0 +1,21 @@ +:import std/Combinator . +:import std/List . +:import std/Math M +:import std/Number/Binary . + +# hailstone sequence using binary shifts +hailstone y [[(0 =? (+1b)) {}0 go]] + go 0 : (=²?0 (1 /²0) (1 (↑¹0 + 0))) + +# --- tests --- + +seq-27 hailstone (+27b) + +:test (∀seq-27) ((+112)) +:test (take (+4) seq-27) ((+27b) : ((+82b) : ((+41b) : {}(+124b)))) +:test (take (+4) <~>seq-27) ((+1b) : ((+2b) : ((+4b) : {}(+8b)))) + +below-100000 [0 : ∀(hailstone 0)] <$> seq + seq take (+99999) (iterate ++‣ (+1b)) + +main [head (max-by (M.compare ⋔ tail) below-100000)] diff --git a/Task/Hailstone-sequence/Elena/hailstone-sequence.elena b/Task/Hailstone-sequence/Elena/hailstone-sequence.elena index f7a6b6523d..65dd556d5d 100644 --- a/Task/Hailstone-sequence/Elena/hailstone-sequence.elena +++ b/Task/Hailstone-sequence/Elena/hailstone-sequence.elena @@ -36,7 +36,7 @@ public program() int longestNumber := 0; auto recursiveLengths := new Map(4096,4096); - for(int i := 1, i < maxNumber, i+=1) + for(int i := 1; i < maxNumber; i+=1) { var chainLength := Hailstone(i, recursiveLengths); if (longestChain < chainLength) diff --git a/Task/Hailstone-sequence/Refal/hailstone-sequence.refal b/Task/Hailstone-sequence/Refal/hailstone-sequence.refal new file mode 100644 index 0000000000..b8c16a96d3 --- /dev/null +++ b/Task/Hailstone-sequence/Refal/hailstone-sequence.refal @@ -0,0 +1,42 @@ +$ENTRY Go { + = + ; +} + +Hailstone { + 1 = 1; + s.N, : { + 0 = s.N >; + 1 = s.N >>; + }; +}; + +ShowHailstone { + s.N, : e.Seq, + : s.Len s.1 s.2 s.3 s.4 e.X s.D4 s.D3 s.D2 s.D1 + = ' has ' ' elements,\n' + 'starting with ' s.1 s.2 s.3 s.4 + 'and ending with ' s.D4 s.D3 s.D2 '.'>; +} + +FindLongest { + s.Max = ; + s.Max s.Max s.Long s.Len = s.Long s.Len; + s.Max s.Cur s.Long s.Len, + : e.CurSeq, + : s.CurLen e.X, + <+ s.Cur 1>: s.Next, + : { + '+' = ; + s.X = ; + }; +}; + +ShowLongest { + s.Max, : s.Long s.Len + = ' which has the longest' + ' hailstone sequence is ' '.\n' + 'The length of its Hailstone sequence is ' + '.'>; +}; diff --git a/Task/Halt-and-catch-fire/Bruijn/halt-and-catch-fire.bruijn b/Task/Halt-and-catch-fire/Bruijn/halt-and-catch-fire.bruijn new file mode 100644 index 0000000000..e053451775 --- /dev/null +++ b/Task/Halt-and-catch-fire/Bruijn/halt-and-catch-fire.bruijn @@ -0,0 +1,3 @@ +:test ([[0]]) ([[1]]) + +main [[0 0] [0 0]] diff --git a/Task/Hamming-numbers/Bruijn/hamming-numbers.bruijn b/Task/Hamming-numbers/Bruijn/hamming-numbers.bruijn new file mode 100644 index 0000000000..426223d327 --- /dev/null +++ b/Task/Hamming-numbers/Bruijn/hamming-numbers.bruijn @@ -0,0 +1,28 @@ +:import std/Combinator . +:import std/Number . +:import std/List . + +merge y [[[∅?1 0 (1 [[2 [[go]]]])]]] + go 3 ((+1) : 0))]]] + +:test ((hammings-classic !! (+42)) =? (+162)) ([[1]]) + +# enumeration by a chain of folded merges (faster) +hammings-folded ([(0 ∘ a) ∘ (0 ∘ b)] (foldr merge1 empty)) $ c + merge1 [[1 [[1 : (merge 0 2)]]]] + a iterate (map (mul (+5))) + b iterate (map (mul (+3))) + c iterate (mul (+2)) (+1) + +:test ((hammings-folded !! (+42)) =? (+162)) ([[1]]) + +# --- output --- + +main [first-twenty : (n1691 : {}n1000000)] + first-twenty take (+20) hammings-folded + n1691 hammings-folded !! (+1690) + n1000000 hammings-folded !! (+999999) diff --git a/Task/Hamming-numbers/Mojo/hamming-numbers.mojo b/Task/Hamming-numbers/Mojo/hamming-numbers.mojo new file mode 100644 index 0000000000..6defc7b7e9 --- /dev/null +++ b/Task/Hamming-numbers/Mojo/hamming-numbers.mojo @@ -0,0 +1,156 @@ +from collections.vector import (DynamicVector, CollectionElement) +from math import (log2, trunc, pow) +from memory import memset_zero #, memcpy) +from time import now + +alias cCOUNT: Int = 1_000_000 + +struct BigNat(Stringable): # enough just to support conversion and printing + ''' Enough "infinite" precision to support as required here - multiply and + divide by 10 conversion to string... + ''' + var contents: DynamicVector[UInt32] + fn __init__(inout self): + self.contents = DynamicVector[UInt32]() + fn __init__(inout self, val: UInt32): + self.contents = DynamicVector[UInt32](4) + self.contents.resize(1, val) + fn __copyinit__(inout self, existing: Self): + self.contents = existing.contents + fn __moveinit__(inout self, owned existing: Self): + self.contents = existing.contents^ + fn __str__(self) -> String: + var rslt: String = "" + var v = self.contents + while len(v) > 0: + var t: UInt64 = 0 + for i in range(len(v) - 1, -1, -1): + t = ((t << 32) + v[i].to_int()) + v[i] = (t // 10).to_int(); t -= v[i].to_int() * 10 + var sz = len(v) - 1 + while sz >= 0 and v[sz] == 0: sz -= 1 + v.resize(sz + 1, 0) + rslt = str(t) + rslt + return rslt + fn mult(inout self, mltplr: Self): + var rslt = DynamicVector[UInt32]() + rslt.resize(len(self.contents) + len(mltplr.contents), 0) + for i in range(len(mltplr.contents)): + var t: UInt64 = 0 + for j in range(len(self.contents)): + t += self.contents[j].to_int() * mltplr.contents[i].to_int() + rslt[i + j].to_int() + rslt[i + j] = (t & 0xFFFFFFFF).to_int(); t >>= 32 + rslt[i + len(self.contents)] += t.to_int() + var sz = len(rslt) - 1 + while sz >= 0 and rslt[sz] == 0: sz -= 1 + rslt.resize(sz + 1, 0); self.contents = rslt + +alias lb2: Float64 = 1.0 +alias lb3: Float64 = log2[DType.float64, 1](3.0) +alias lb5: Float64 = log2[DType.float64, 1](5.0) + +@value +struct LogRep(CollectionElement, Stringable): + var logrep: Float64 + var x2: UInt32 + var x3: UInt32 + var x5: UInt32 + fn __del__(owned self): return + @always_inline + fn mul2(self) -> Self: + return LogRep(self.logrep + lb2, self.x2 + 1, self.x3, self.x5) + @always_inline + fn mul3(self) -> Self: + return LogRep(self.logrep + lb3, self.x2, self.x3 + 1, self.x5) + @always_inline + fn mul5(self) -> Self: + return LogRep(self.logrep + lb5, self.x2, self.x3, self.x5 + 1) + fn __str__(self) -> String: + var rslt = BigNat(1) + fn expnd(inout rslt: BigNat, bs: UInt32, n: UInt32): + var bsm = BigNat(bs); var nm = n + while nm > 0: + if (nm & 1) != 0: rslt.mult(bsm) + bsm.mult(bsm); nm >>= 1 + expnd(rslt, 2, self.x2); expnd(rslt, 3, self.x3); expnd(rslt, 5, self.x5) + return str(rslt) + +alias oneLR: LogRep = LogRep(0.0, 0, 0, 0) + +alias LogRepThunk = fn() escaping -> LogRep + +fn hammingsLogImp() -> LogRepThunk: + var s2 = DynamicVector[LogRep](); var s3 = DynamicVector[LogRep](); var s5 = oneLR; var mrg = oneLR + s2.resize(512, oneLR); s2[0] = oneLR.mul2(); s3.resize(1, oneLR); s3[0] = oneLR.mul3() +# var s2p = s2.steal_data(); var s3p = s3.steal_data() + var s2hdi = 0; var s2tli = -1; var s3hdi = 0; var s3tli = -1 + @always_inline + fn next() escaping -> LogRep: + var rslt = s2[s2hdi] + var s2len = len(s2) + s2tli += 1; + if s2tli >= s2len: + s2tli = 0 + if s2hdi == s2tli: + if s2len < 1024: + s2.resize(1024, oneLR) + else: + s2.resize(s2len + s2len, oneLR) # ; s2p = s2.steal_data() + for i in range(s2hdi): + s2[s2len + i] = s2[i] +# memcpy[UInt8, 0](s2p + s2len, s2p, sizeof[LogRep]() * s2hdi) + s2tli += s2len; s2len += s2len + if rslt.logrep < mrg.logrep: + s2hdi += 1 + if s2hdi >= s2len: + s2hdi = 0 + else: + rslt = mrg + var s3len = len(s3) + s3tli += 1; + if s3tli >= s3len: + s3tli = 0 + if s3hdi == s3tli: + if s3len < 1024: + s3.resize(1024, oneLR) + else: + s3.resize(s3len + s3len, oneLR) # ; s3p = s3.steal_data() + for i in range(s3hdi): + s3[s3len + i] = s3[i] +# memcpy[UInt8, 0](s3p + s3len, s3p, sizeof[LogRep]() * s3hdi) + s3tli += s3len; s3len += s3len + if mrg.logrep < s5.logrep: + s3hdi += 1 + if s3hdi >= s3len: + s3hdi = 0 + else: + s5 = s5.mul5() + s3[s3tli] = rslt.mul3(); let t = s3[s3hdi]; + mrg = t if t.logrep < s5.logrep else s5 + s2[s2tli] = rslt.mul2(); return rslt + return next + +fn main(): + print("The first 20 Hamming numbers are:") + var f = hammingsLogImp(); + for i in range(20): print_no_newline(f(), " ") + print() + f = hammingsLogImp(); var h: LogRep = oneLR + for i in range(1691): h = f() + print("The 1691st Hamming number is", h) + let strt: Int = now() + f = hammingsLogImp() + for i in range(cCOUNT): h = f() + let elpsd = (now() - strt) / 1000 + + print("The " + str(cCOUNT) + "th Hamming number is:") + print("2**" + str(h.x2) + " * 3**" + str(h.x3) + " * 5**" + str(h.x5)) + let lg2 = lb2 * Float64(h.x2.to_int()) + lb3 * Float64(h.x3.to_int()) + lb5 * Float64(h.x5.to_int()) + let lg10 = lg2 / log2(Float64(10)) + let expnt = trunc(lg10); let num = pow(Float64(10.0), lg10 - expnt) + let apprxstr = str(num) + "E+" + str(expnt.to_int()) + print("Approximately: ", apprxstr) + let answrstr = str(h) + print("The result has", len(answrstr), "digits.") + print(answrstr) + print("This took " + str(elpsd) + " microseconds.") diff --git a/Task/Handle-a-signal/Lua/handle-a-signal.lua b/Task/Handle-a-signal/Lua/handle-a-signal.lua new file mode 100644 index 0000000000..8b97e083d7 --- /dev/null +++ b/Task/Handle-a-signal/Lua/handle-a-signal.lua @@ -0,0 +1,20 @@ +local start_date = os.time() + +local loop = true +local Exit = function () + print() + loop = false +end + +local posix = require"posix" +posix.signal(posix.SIGINT, Exit) +posix.signal(posix.SIGQUIT, Exit) + +local int = 0 +while loop do + int = int+1 + print(int) + posix.time.nanosleep{tv_sec=0,tv_nsec=500*1000*1000} +end + +print(os.time() - start_date) diff --git a/Task/Happy-numbers/EasyLang/happy-numbers.easy b/Task/Happy-numbers/EasyLang/happy-numbers.easy new file mode 100644 index 0000000000..922506ed62 --- /dev/null +++ b/Task/Happy-numbers/EasyLang/happy-numbers.easy @@ -0,0 +1,27 @@ +func dsum n . + while n > 0 + d = n mod 10 + s += d * d + n = n div 10 + . + return s +. +func happy n . + while n > 999 + n = dsum n + . + len seen[] 999 + repeat + n = dsum n + until seen[n] = 1 + seen[n] = 1 + . + return if n = 1 +. +while cnt < 8 + n += 1 + if happy n = 1 + cnt += 1 + write n & " " + . +. diff --git a/Task/Happy-numbers/Elena/happy-numbers.elena b/Task/Happy-numbers/Elena/happy-numbers.elena index ce34920d51..5b4b0322fa 100644 --- a/Task/Happy-numbers/Elena/happy-numbers.elena +++ b/Task/Happy-numbers/Elena/happy-numbers.elena @@ -9,14 +9,14 @@ isHappy(int n) int num := n; while (num != 1) { - if (cache.indexOfElement:num != -1) + if (cache.indexOfElement(num) != -1) { ^ false }; cache.append(num); while (num != 0) { - int digit := num.mod:10; + int digit := num.mod(10); sum += (digit*digit); num /= 10 }; diff --git a/Task/Happy-numbers/Julia/happy-numbers-1.julia b/Task/Happy-numbers/Julia/happy-numbers-1.julia index f4fc223f7c..d9d5a0d343 100644 --- a/Task/Happy-numbers/Julia/happy-numbers-1.julia +++ b/Task/Happy-numbers/Julia/happy-numbers-1.julia @@ -1,13 +1,14 @@ function happy(x) - happy_ints = ref(Int) + happy_ints = Int[] int_try = 1 while length(happy_ints) < x n = int_try - past = ref(Int) + past = Int[] while n != 1 - n = sum([y^2 for y in digits(n)]) - contains(past,n) ? break : push!(past,n) - end + n = sum(y^2 for y in digits(n)) + n in past && break + push!(past, n) + end n == 1 && push!(happy_ints,int_try) int_try += 1 end diff --git a/Task/Happy-numbers/Julia/happy-numbers-2.julia b/Task/Happy-numbers/Julia/happy-numbers-2.julia index 82b71edb0c..3d6947b562 100644 --- a/Task/Happy-numbers/Julia/happy-numbers-2.julia +++ b/Task/Happy-numbers/Julia/happy-numbers-2.julia @@ -1,11 +1,10 @@ sumhappy(n) = sum(x->x^2, digits(n)) -function ishappy(x, mem = []) - x == 1? true : - x in mem? false : - ishappy(sumhappy(x),[mem ; x]) +function ishappy(x, mem = Int[]) + x == 1 ? true : + x in mem ? false : + ishappy(sumhappy(x), [mem ; x]) end -nexthappy (x) = ishappy(x+1) ? x+1 : nexthappy(x+1) - -happy(n) = [z = 1 ; [z = nexthappy(z) for i = 1:n-1]] +nexthappy(x) = ishappy(x+1) ? x+1 : nexthappy(x+1) +happy(n) = accumulate((a, b) -> nexthappy(a), 1:n) diff --git a/Task/Happy-numbers/Julia/happy-numbers-3.julia b/Task/Happy-numbers/Julia/happy-numbers-3.julia index 6fbebd76e6..9a2d149a42 100644 --- a/Task/Happy-numbers/Julia/happy-numbers-3.julia +++ b/Task/Happy-numbers/Julia/happy-numbers-3.julia @@ -1,30 +1,30 @@ const CACHE = 256 -buf = zeros(Int,CACHE) -buf[1] = 1 -#happy(n) returns 1 if happy, 0 if not +buf = zeros(Int, CACHE) +buf[begin] = 1 + function happy(n) if n < CACHE buf[n] > 0 && return 2-buf[n] buf[n] = 2 end - sum = 0 + sqsum = 0 nn = n while nn != 0 - x = nn%10 - sum += x*x - nn = int8(nn/10) + nn, x = divrem(nn, 10) + sqsum += x * x end - x = happy(sum) - n < CACHE && (buf[n] = 2-x) + x = happy(sqsum) + n < CACHE && (buf[n] = 2 - x) return x end + function main() - i = 1; counter = 1000000 + i, counter = 1, 1000000 while counter > 0 - if happy(i) == 1 + if happy(i) != 0 counter -= 1 end i += 1 end - return i-1 + return i - 1 end diff --git a/Task/Happy-numbers/REXX/happy-numbers-1.rexx b/Task/Happy-numbers/REXX/happy-numbers-1.rexx deleted file mode 100644 index 8fb8f111be..0000000000 --- a/Task/Happy-numbers/REXX/happy-numbers-1.rexx +++ /dev/null @@ -1,19 +0,0 @@ -/*REXX program computes and displays a specified amount of happy numbers. */ -parse arg limit . /*obtain optional argument from the CL.*/ -if limit=='' | limit=="," then limit=8 /*Not specified? Then use the default.*/ -haps=0 /*count of the happy numbers (so far).*/ - - do n=1 while hapssw then do /*if the list is too long, then split */ - say strip($) /* ··· and display what we've got. */ - $=n /*Set the next line to overflow. */ - end /* [↑] new line now contains overflow.*/ - end /*n*/ -if $\='' then say strip($) /*display any residual happy numbers. */ - /*stick a fork in it, we're all done. */ diff --git a/Task/Happy-numbers/REXX/happy-numbers.rexx b/Task/Happy-numbers/REXX/happy-numbers.rexx new file mode 100644 index 0000000000..ff5e99ee46 --- /dev/null +++ b/Task/Happy-numbers/REXX/happy-numbers.rexx @@ -0,0 +1,78 @@ +/*REXX program computes and displays a specified range of happy numbers. */ +Call time 'R' +linesize=80 +Parse Arg low high /* obtain range of happy numbers */ +If low='?' Then Call help +If low='' Then low=10 +If high='' Then + Parse Value 1 low With low high +Do i=0 To 9 /*build a squared decimal digit table. */ + square.i=i*i + End +happy.=0 /* happy.m=1 - m is a happy number */ +unhappy.=0 /* unhappy.n=1 - n is an unhappy number*/ +hapn=0 /* count of the happy numbers */ +ol='' +Do n=1 While hapn0 Then Do /* or was already encountered */ + -- If wordpos(sum,suml)>0 Then say 'Loop' n':' suml sum + -- If n<7 Then say n':' suml sum + unhappy.n=1 /* n is unhappy */ + Call set suml /* amd so are all sums so far */ + Iterate n + End + When sum=1 Then Do /* we reached sum=1 */ + hapn+=1 /* increment number of happy numbers */ + happy.n=1 /* n is happy */ + If hapn>=low Then /* if it is in specified range */ + Call out n /* output it */ + If hapn=high Then /* end of range reached */ + Leave n /* we are done */ + Iterate n /* otherwise proceed */ + End + Otherwise Do /* otherwise */ + suml=suml sum /* add sum to list of sums */ + work=sum /* proceed with the new sum */ + End + End + End + End +If ol>'' Then /* more output data */ + Say strip(ol) /* write to console */ +-- Say time('E') +Exit + +set: /* all intermediate sums are unhappy */ +Parse Arg list +Do While list<>'' + Parse Var list s list + unhappy.s=1 + End +Return + +out: /* output management */ + Parse Arg hn /* the happy number */ + If length(ol hn)>linesize Then Do /* if it does not fit */ + Say strip(ol) /* output the line */ + ol=hn /* and start a new line */ + End + Else /* otherwise */ + ol=ol hn /* append is to the output line */ + Return + +help: + Say 'rexx hno n compute and show the first n happy numbers' + Say 'rexx hno low high show happy numbers from index low to high' + Exit diff --git a/Task/Happy-numbers/Refal/happy-numbers.refal b/Task/Happy-numbers/Refal/happy-numbers.refal new file mode 100644 index 0000000000..68c1b6b4e1 --- /dev/null +++ b/Task/Happy-numbers/Refal/happy-numbers.refal @@ -0,0 +1,26 @@ +$ENTRY Go { + = ; +}; + +ShowFirst { + 0 s.F s.I = ; + s.N s.F s.I, : T = + + s.F <+ s.I 1>>; + s.N s.F s.I = + >; +}; + +Happy { + 1 e.X = T; + s.N e.X s.N e.Y = F; + s.N e.X = s.N e.X>; +}; + +SqDigSum { + 0 = 0; + s.N, : s.Ds e.Rs, + : s.D, + : s.R = + <+ <* s.D s.D> >; +}; diff --git a/Task/Harmonic-series/C-sharp/harmonic-series.cs b/Task/Harmonic-series/C-sharp/harmonic-series.cs new file mode 100644 index 0000000000..2fc08009b4 --- /dev/null +++ b/Task/Harmonic-series/C-sharp/harmonic-series.cs @@ -0,0 +1,79 @@ +using System; +using System.Numerics; + +public class BigRational +{ + public BigInteger Numerator { get; private set; } + public BigInteger Denominator { get; private set; } + + public BigRational(BigInteger numerator, BigInteger denominator) + { + if (denominator == 0) + throw new ArgumentException("Denominator cannot be zero.", nameof(denominator)); + + BigInteger gcd = BigInteger.GreatestCommonDivisor(numerator, denominator); + Numerator = numerator / gcd; + Denominator = denominator / gcd; + + if (Denominator < 0) + { + Numerator = -Numerator; + Denominator = -Denominator; + } + } + + public static BigRational operator +(BigRational a, BigRational b) + { + return new BigRational(a.Numerator * b.Denominator + b.Numerator * a.Denominator, a.Denominator * b.Denominator); + } + + public override string ToString() + { + return $"{Numerator}/{Denominator}"; + } +} + +class Program +{ + static BigRational Harmonic(int n) + { + BigRational sum = new BigRational(0, 1); + for (int i = 1; i <= n; i++) + { + BigRational r = new BigRational(1, i); + sum += r; + } + return sum; + } + + static void Main(string[] args) + { + Console.WriteLine("The first 20 harmonic numbers and the 100th, expressed in rational form, are:"); + int[] numbers = new int[21]; + for (int i = 1; i <= 20; i++) + { + numbers[i - 1] = i; + } + numbers[20] = 100; + foreach (int i in numbers) + { + Console.WriteLine($"{i,3} : {Harmonic(i)}"); + } + + Console.WriteLine("\nThe first harmonic number to exceed the following integers is:"); + const int limit = 10; + for (int i = 1, n = 1; i <= limit; n++) + { + double h = 0; + for (int j = 1; j <= n; j++) + { + h += 1.0 / j; + } + if (h > i) + { + Console.WriteLine($"integer = {i,2} -> n = {n,6} -> harmonic number = {h,9:F6} (to 6dp)"); + i++; + } + } + } +} diff --git a/Task/Harshad-or-Niven-series/Refal/harshad-or-niven-series.refal b/Task/Harshad-or-Niven-series/Refal/harshad-or-niven-series.refal new file mode 100644 index 0000000000..6b6039bb2b --- /dev/null +++ b/Task/Harshad-or-Niven-series/Refal/harshad-or-niven-series.refal @@ -0,0 +1,28 @@ +$ENTRY Go { + = > + 1000: ' >; +}; + +GetFirst { + s.N s.F = ; + 0 s.F s.Cur = ; + s.N s.F s.Cur, : s.Next + = s.Next s.F s.Next>; +}; + +Next { + s.F s.N, <+ 1 s.N>: s.Next, : { + T = s.Next; + F = ; + }; +}; + +Harshad { + s.N, : s.Dsum, : 0 = T; + s.N = F; +}; + +DigSum { + 0 = 0; + s.N, : (s.Rest) s.Dgt = <+ s.Dgt >; +}; diff --git a/Task/Hash-from-two-arrays/XPL0/hash-from-two-arrays.xpl0 b/Task/Hash-from-two-arrays/XPL0/hash-from-two-arrays.xpl0 new file mode 100644 index 0000000000..0ff8043b63 --- /dev/null +++ b/Task/Hash-from-two-arrays/XPL0/hash-from-two-arrays.xpl0 @@ -0,0 +1,12 @@ +func Code(Str); \Return a simple, perfect hash code for the Keys used here +char Str; +return Str(2) & 7; + +int Keys, Values, I, Hash(8); +[Keys:= ["first", "second", "third", "fourth", "fifth", "sixth"]; +Values:= [1, 2, 3, 4, 5, 6]; +for I:= 0 to 6-1 do + Hash(Code(Keys(I))):= Values(I); +IntOut(0, Hash(Code("second"))); CrLf(0); +IntOut(0, Hash(Code("sixth"))); CrLf(0); +] diff --git a/Task/Hello-world-Graphical/Crystal/hello-world-graphical.crystal b/Task/Hello-world-Graphical/Crystal/hello-world-graphical.crystal new file mode 100644 index 0000000000..f45d693ae9 --- /dev/null +++ b/Task/Hello-world-Graphical/Crystal/hello-world-graphical.crystal @@ -0,0 +1,29 @@ +require "crsfml" + +window = SF::RenderWindow.new(SF::VideoMode.new(800, 600), "Hello world/Graphical") + +# A font file(s) MUST be in the directory of the Crystal file itself. +# CrSFML does NOT load font files from the filesystem root! +font = SF::Font.from_file("DejaVuSerif-Bold.ttf") + +text = SF::Text.new +text.font = font + +text.string = "Goodbye, world!" +text.character_size = 24 + +text.color = SF::Color::Black + +while window.open? + while event = window.poll_event + if event.is_a? SF::Event::Closed + window.close + end + end + + window.clear(SF::Color::White) + + window.draw(text) + + window.display +end diff --git a/Task/Hello-world-Newbie/Binary-Lambda-Calculus/hello-world-newbie.blc b/Task/Hello-world-Newbie/Binary-Lambda-Calculus/hello-world-newbie.blc new file mode 100644 index 0000000000..fa09305cd7 --- /dev/null +++ b/Task/Hello-world-Newbie/Binary-Lambda-Calculus/hello-world-newbie.blc @@ -0,0 +1,2 @@ +wget https://github.com/tromp/AIT/uni.pl +echo " Hello, world" | ./uni.pl diff --git a/Task/Hello-world-Newbie/Elena/hello-world-newbie-2.elena b/Task/Hello-world-Newbie/Elena/hello-world-newbie-2.elena index f4362b1167..b61d878d3e 100644 --- a/Task/Hello-world-Newbie/Elena/hello-world-newbie-2.elena +++ b/Task/Hello-world-Newbie/Elena/hello-world-newbie-2.elena @@ -1 +1 @@ -elc program1.l +elena-cli.exe program1.l diff --git a/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom b/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom index 30f70c3d8d..83bc364ef3 100644 --- a/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom +++ b/Task/Hello-world-Newline-omission/Fantom/hello-world-newline-omission.fantom @@ -16,5 +16,14 @@ class Main { // or method chain out.print("Goodbye, world!").flush() + // Also we can an implement a user-defined method + print("Hello, world! I'm back!"); + } + + // User-defined 'print' method + private Void print(Str s) { + Env.cur.out.print(s) + } + } diff --git a/Task/Hello-world-Newline-omission/FreeBASIC/hello-world-newline-omission.basic b/Task/Hello-world-Newline-omission/FreeBASIC/hello-world-newline-omission.basic index 7c2c782e21..b14090ea31 100644 --- a/Task/Hello-world-Newline-omission/FreeBASIC/hello-world-newline-omission.basic +++ b/Task/Hello-world-Newline-omission/FreeBASIC/hello-world-newline-omission.basic @@ -1,4 +1,4 @@ -' FB 1.05.0 Win64 +' FB 1.10.1 Win64 -Print "Goodbye, World!"; '' the trailing semi-colon suppresses the new line +Print "Goodbye, World!"; ' the trailing semi-colon suppresses the new line Sleep diff --git a/Task/Hello-world-Standard-error/Julia/hello-world-standard-error-1.julia b/Task/Hello-world-Standard-error/Julia/hello-world-standard-error-1.julia new file mode 100644 index 0000000000..c94f57365c --- /dev/null +++ b/Task/Hello-world-Standard-error/Julia/hello-world-standard-error-1.julia @@ -0,0 +1 @@ +println(stderr, "Goodbye, World!") diff --git a/Task/Hello-world-Standard-error/Julia/hello-world-standard-error.julia b/Task/Hello-world-Standard-error/Julia/hello-world-standard-error-2.julia similarity index 100% rename from Task/Hello-world-Standard-error/Julia/hello-world-standard-error.julia rename to Task/Hello-world-Standard-error/Julia/hello-world-standard-error-2.julia diff --git a/Task/Hello-world-Standard-error/Langur/hello-world-standard-error.langur b/Task/Hello-world-Standard-error/Langur/hello-world-standard-error.langur index 7b9149bb7a..3e78e993c5 100644 --- a/Task/Hello-world-Standard-error/Langur/hello-world-standard-error.langur +++ b/Task/Hello-world-Standard-error/Langur/hello-world-standard-error.langur @@ -1 +1 @@ -writelnErr "goodbye, people" +writelnErr "Goodbye, world." diff --git a/Task/Hello-world-Text/BabyCobol/hello-world-text.cobol b/Task/Hello-world-Text/BabyCobol/hello-world-text.cobol new file mode 100644 index 0000000000..5dbf9df8ec --- /dev/null +++ b/Task/Hello-world-Text/BabyCobol/hello-world-text.cobol @@ -0,0 +1,6 @@ + * Since no quotes are used, two undeclared fields (variables) are printed. + * Their default values are their own names in uppercase. + IDENTIFICATION DIVISION. + PROGRAM-ID. USER OUTPUT. + PROCEDURE DIVISION. + DISPLAY HELLO WORLD. diff --git a/Task/Hello-world-Text/Binary-Lambda-Calculus/hello-world-text.blc b/Task/Hello-world-Text/Binary-Lambda-Calculus/hello-world-text.blc deleted file mode 100644 index 00be4437c0..0000000000 --- a/Task/Hello-world-Text/Binary-Lambda-Calculus/hello-world-text.blc +++ /dev/null @@ -1 +0,0 @@ - Hello world! diff --git a/Task/Hello-world-Text/Bruijn/hello-world-text.bruijn b/Task/Hello-world-Text/Bruijn/hello-world-text.bruijn new file mode 100644 index 0000000000..caa75ec18e --- /dev/null +++ b/Task/Hello-world-Text/Bruijn/hello-world-text.bruijn @@ -0,0 +1 @@ +main ["Hello world!"] diff --git a/Task/Hello-world-Text/Elena/hello-world-text.elena b/Task/Hello-world-Text/Elena/hello-world-text.elena index 43198adb7d..a48885e3b8 100644 --- a/Task/Hello-world-Text/Elena/hello-world-text.elena +++ b/Task/Hello-world-Text/Elena/hello-world-text.elena @@ -1,4 +1,4 @@ public program() { - console.writeLine:"Hello world!" + console.writeLine("Hello world!") } diff --git a/Task/Hello-world-Text/Hopper/hello-world-text.hopper b/Task/Hello-world-Text/Hopper/hello-world-text.hopper new file mode 100644 index 0000000000..77622a8e7c --- /dev/null +++ b/Task/Hello-world-Text/Hopper/hello-world-text.hopper @@ -0,0 +1,14 @@ +program Hello +{ + uses "/Source/Library/Boards/PiPico" + + Hopper() + { + WriteLn("Hello world!"); + loop + { + LED = !LED; + Delay(500); + } + } +} diff --git a/Task/Hello-world-Text/Langur/hello-world-text.langur b/Task/Hello-world-Text/Langur/hello-world-text.langur index 493eb23dea..185de76e9a 100644 --- a/Task/Hello-world-Text/Langur/hello-world-text.langur +++ b/Task/Hello-world-Text/Langur/hello-world-text.langur @@ -1 +1 @@ -writeln "yo, peeps" +writeln "Hello" diff --git a/Task/Hello-world-Text/Refal/hello-world-text.refal b/Task/Hello-world-Text/Refal/hello-world-text.refal new file mode 100644 index 0000000000..6f40723ccc --- /dev/null +++ b/Task/Hello-world-Text/Refal/hello-world-text.refal @@ -0,0 +1,3 @@ +$ENTRY Go { + = ; +}; diff --git a/Task/Hello-world-Text/Roc/hello-world-text.roc b/Task/Hello-world-Text/Roc/hello-world-text.roc new file mode 100644 index 0000000000..8e641f0695 --- /dev/null +++ b/Task/Hello-world-Text/Roc/hello-world-text.roc @@ -0,0 +1,7 @@ +app "hello" + packages { pf: "https://github.com/roc-lang/basic-cli/releases/download/0.1.1/zAoiC9xtQPHywYk350_b7ust04BmWLW00sjb9ZPtSQk.tar.br" } + imports [pf.Stdout] + provides [main] to pf + +main = + Stdout.line "I'm a Roc application!" diff --git a/Task/Hello-world-Text/Uxntal/hello-world-text.uxnatl b/Task/Hello-world-Text/Uxntal/hello-world-text.uxnatl index abedc7f43c..7cef15e4e0 100644 --- a/Task/Hello-world-Text/Uxntal/hello-world-text.uxnatl +++ b/Task/Hello-world-Text/Uxntal/hello-world-text.uxnatl @@ -10,7 +10,7 @@ BRK @print-str ( str* -- ) &while - LDAk #18 DEO + LDAk .Console/write DEO INC2 LDAk ?&while POP2 JMP2r diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-1.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-1.ys deleted file mode 100644 index fe1102b873..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-1.ys +++ /dev/null @@ -1 +0,0 @@ -(println "Hello world!") diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-10.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-10.ys deleted file mode 100644 index 7181553e88..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-10.ys +++ /dev/null @@ -1,3 +0,0 @@ -# The . at the start of a value is way to indicate that the value is a scalar (string). -# Without the . this would be invalid YAML(Script). -say: ."Hello", "world!" diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-2.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-2.ys deleted file mode 100644 index 67b2867299..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-2.ys +++ /dev/null @@ -1 +0,0 @@ -(say "Hello world!") diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-3.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-3.ys deleted file mode 100644 index 532f5d13b8..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-3.ys +++ /dev/null @@ -1 +0,0 @@ -say("Hello world!") diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-4.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-4.ys deleted file mode 100644 index 1693143626..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-4.ys +++ /dev/null @@ -1 +0,0 @@ -say("Hello world!"): diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-5.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-5.ys deleted file mode 100644 index 342f3cc53e..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-5.ys +++ /dev/null @@ -1,2 +0,0 @@ -say: -- "Hello world!" diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-6.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-6.ys deleted file mode 100644 index e428ab45ef..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-6.ys +++ /dev/null @@ -1 +0,0 @@ -say: ["Hello world!"] diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-7.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-7.ys deleted file mode 100644 index 5e826d472b..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-7.ys +++ /dev/null @@ -1 +0,0 @@ -say: "Hello world!" diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-8.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-8.ys deleted file mode 100644 index 62b8d10309..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-8.ys +++ /dev/null @@ -1 +0,0 @@ -say("Hello"): "world!" diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text-9.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text-9.ys deleted file mode 100644 index ad0788f756..0000000000 --- a/Task/Hello-world-Text/YAMLScript/hello-world-text-9.ys +++ /dev/null @@ -1 +0,0 @@ -say: ["Hello", "world!"] diff --git a/Task/Hello-world-Text/YAMLScript/hello-world-text.ys b/Task/Hello-world-Text/YAMLScript/hello-world-text.ys new file mode 100644 index 0000000000..0432ff6961 --- /dev/null +++ b/Task/Hello-world-Text/YAMLScript/hello-world-text.ys @@ -0,0 +1,18 @@ +!yamlscript/v0 + +say: "Hello, world!" + +=>: (say "Hello, world!") + +=>: say("Hello, world!") + +say: + =>: "Hello, world!" + +say: ("Hello, " + "world!") + +say: ."Hello," "world!" + +say "Hello,": "world!" + +say "Hello," "world!": diff --git a/Task/Hickerson-series-of-almost-integers/C-sharp/hickerson-series-of-almost-integers.cs b/Task/Hickerson-series-of-almost-integers/C-sharp/hickerson-series-of-almost-integers.cs new file mode 100644 index 0000000000..927eebf380 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/C-sharp/hickerson-series-of-almost-integers.cs @@ -0,0 +1,24 @@ +using System; +using System.Numerics; + +public class Program +{ + public static void Main(string[] args) + { + decimal ln2 = 0.6931471805599453094172m; + decimal h = 0.5m / ln2; + BigInteger w = new BigInteger(); + decimal f = 0; + + for (long i = 1; i <= 17; i++) + { + h = h * i / ln2; + w = (BigInteger)h; + f = h - (decimal)w; + double y = (double)f; + string d = y.ToString("0.000"); + + Console.WriteLine($"n: {i,2} h: {w}{d.Substring(1)} Nearly integer: {d[2] == '0' || d[2] == '9'}"); + } + } +} diff --git a/Task/Higher-order-functions/Bruijn/higher-order-functions-1.bruijn b/Task/Higher-order-functions/Bruijn/higher-order-functions-1.bruijn new file mode 100644 index 0000000000..42e2f47300 --- /dev/null +++ b/Task/Higher-order-functions/Bruijn/higher-order-functions-1.bruijn @@ -0,0 +1 @@ +main [0] diff --git a/Task/Higher-order-functions/Bruijn/higher-order-functions-2.bruijn b/Task/Higher-order-functions/Bruijn/higher-order-functions-2.bruijn new file mode 100644 index 0000000000..f259ef31cb --- /dev/null +++ b/Task/Higher-order-functions/Bruijn/higher-order-functions-2.bruijn @@ -0,0 +1,5 @@ +first [0 [[0]]] + +second [first [[1]]] + +:test (second) ([[[[0]]]]) diff --git a/Task/History-variables/Elena/history-variables.elena b/Task/History-variables/Elena/history-variables.elena index 96f171d09b..437f6ba705 100644 --- a/Task/History-variables/Elena/history-variables.elena +++ b/Task/History-variables/Elena/history-variables.elena @@ -49,7 +49,7 @@ public program() console.printLine(o); - o.forEach:printingLn; + o.forEach(printingLn); o.undo().undo().undo(); diff --git a/Task/Hofstadter-Conway-$10-000-sequence/EasyLang/hofstadter-conway-$10-000-sequence.easy b/Task/Hofstadter-Conway-$10-000-sequence/EasyLang/hofstadter-conway-$10-000-sequence.easy new file mode 100644 index 0000000000..4a4c98272d --- /dev/null +++ b/Task/Hofstadter-Conway-$10-000-sequence/EasyLang/hofstadter-conway-$10-000-sequence.easy @@ -0,0 +1,21 @@ +numfmt 4 0 +a[] = [ 1 1 ] +x = 1 +n = 2 +mallow = 0 +for p = 1 to 19 + max = 0 + nextPot = n * 2 + while n < nextPot + n = len a[] + 1 + x = a[x] + a[n - x] + a[] &= x + f = x / n + max = higher max f + if f >= 0.55 + mallow = n + . + . + print "max between 2^" & p & " and 2^" & p + 1 & " was " & max +. +print "winning number " & mallow diff --git a/Task/Hofstadter-Conway-$10-000-sequence/XPL0/hofstadter-conway-$10-000-sequence.xpl0 b/Task/Hofstadter-Conway-$10-000-sequence/XPL0/hofstadter-conway-$10-000-sequence.xpl0 new file mode 100644 index 0000000000..e7513d5880 --- /dev/null +++ b/Task/Hofstadter-Conway-$10-000-sequence/XPL0/hofstadter-conway-$10-000-sequence.xpl0 @@ -0,0 +1,24 @@ +int A(1 + 1<<20), N, Power2, WinningN; +real Max, Member; +[A(1):= 1; A(2):= 1; +N:= 3; Power2:= 2; Max:= 0.; +Text(0, " Range Maximum^m^j"); +Format(1, 6); +repeat A(N):= A(A(N-1)) + A(N-A(N-1)); + Member:= float(A(N)) / float(N); + if Member >= Max then Max:= Member; + if Member >= 0.55 then WinningN:= N; + if N & 1< 1<<20; +IntOut(0, WinningN); +Text(0, " is the winning position.^m^j"); +] diff --git a/Task/Home-primes/PARI-GP/home-primes.parigp b/Task/Home-primes/PARI-GP/home-primes.parigp new file mode 100644 index 0000000000..dd584f6a2d --- /dev/null +++ b/Task/Home-primes/PARI-GP/home-primes.parigp @@ -0,0 +1,30 @@ +homeprimechain(n) = { + my(chain = [], concat_result, factors, factor_str); + while (!isprime(n), + chain = concat(chain, n); /* Append n to the chain */ + factors = factor(n); + /* Correctly build the concatenated string of factors */ + factor_str = Str(concat(Vec(vector(#factors~, i, + concat(Vec(concat(vector(factors[i, 2], j, Str(factors[i, 1]))))))))); + concat_result = factor_str; + \\print("concat_result=" concat_result); + n = eval(concat_result); /* Convert string back to number */ + ); + concat(chain, n); /* Append the final prime to the chain */ +} + +printHPiter(n, numperline = 4) = { + my(chain = homeprimechain(n), len = #chain, i); + for (i = 1, len, + if (i < len, + print1("HP" , chain[i] , " (" , len - i , ") = " , if(i % numperline == 0, "\n", "")), + print(chain[i], " is prime.\n\n"); + ); + ); +} + +{ +/* Iterate over a set of numbers */ +forstep(i = 2, 20, 1, print("Home Prime chain for ", i, ": "); printHPiter(i);); +printHPiter(65); +} diff --git a/Task/ISBN13-check-digit/11l/isbn13-check-digit.11l b/Task/ISBN13-check-digit/11l/isbn13-check-digit.11l index 7a14d6a82b..49b7b340b8 100644 --- a/Task/ISBN13-check-digit/11l/isbn13-check-digit.11l +++ b/Task/ISBN13-check-digit/11l/isbn13-check-digit.11l @@ -6,8 +6,8 @@ F is_isbn13(=n) + sum(n[(1..).step(2)].map(ch -> Int(ch) * 3)) R product % 10 == 0 -V tests = |‘978-1734314502 - 978-1734314509 +V tests = |‘978-0596528126 + 978-0596528120 978-1788399081 978-1788399083’.split("\n") diff --git a/Task/ISBN13-check-digit/ALGOL-68/isbn13-check-digit.alg b/Task/ISBN13-check-digit/ALGOL-68/isbn13-check-digit.alg index f88a34b77d..4022b47614 100644 --- a/Task/ISBN13-check-digit/ALGOL-68/isbn13-check-digit.alg +++ b/Task/ISBN13-check-digit/ALGOL-68/isbn13-check-digit.alg @@ -20,7 +20,7 @@ BEGIN # Check some IsBN13 check digits # digits = 13 AND sum MOD 10 = 0 END; # check isbn13 # # task test cases # - []STRING tests = ( "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" ); + []STRING tests = ( "978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083" ); []BOOL expected = ( TRUE, FALSE, TRUE, FALSE ); FOR pos FROM LWB tests TO UPB tests DO BOOL result = check isbn13( tests[ pos ] ); diff --git a/Task/ISBN13-check-digit/AWK/isbn13-check-digit.awk b/Task/ISBN13-check-digit/AWK/isbn13-check-digit.awk index 1e36f0a7b3..f4d2359d5e 100644 --- a/Task/ISBN13-check-digit/AWK/isbn13-check-digit.awk +++ b/Task/ISBN13-check-digit/AWK/isbn13-check-digit.awk @@ -1,7 +1,7 @@ # syntax: GAWK -f ISBN13_CHECK_DIGIT.AWK BEGIN { - arr[++n] = "978-1734314502" - arr[++n] = "978-1734314509" + arr[++n] = "978-0596528126" + arr[++n] = "978-0596528120" arr[++n] = "978-1788399081" arr[++n] = "978-1788399083" arr[++n] = "9780820424521" diff --git a/Task/ISBN13-check-digit/Action-/isbn13-check-digit.action b/Task/ISBN13-check-digit/Action-/isbn13-check-digit.action index bf40fbe6ad..02f9830166 100644 --- a/Task/ISBN13-check-digit/Action-/isbn13-check-digit.action +++ b/Task/ISBN13-check-digit/Action-/isbn13-check-digit.action @@ -38,8 +38,8 @@ RETURN PROC Main() Put(125) PutE() ;clear screen - Test("978-1734314502") - Test("978-1734314509") + Test("978-0596528126") + Test("978-0596528120") Test("978-1788399081") Test("978-1788399083") RETURN diff --git a/Task/ISBN13-check-digit/Ada/isbn13-check-digit.ada b/Task/ISBN13-check-digit/Ada/isbn13-check-digit.ada index 080c43e508..462f647f79 100644 --- a/Task/ISBN13-check-digit/Ada/isbn13-check-digit.ada +++ b/Task/ISBN13-check-digit/Ada/isbn13-check-digit.ada @@ -30,8 +30,8 @@ procedure ISBN_Check is New_Line; end Show; begin - Show ("978-1734314502"); - Show ("978-1734314509"); + Show ("978-0596528126"); + Show ("978-0596528120"); Show ("978-1788399081"); Show ("978-1788399083"); end ISBN_Check; diff --git a/Task/ISBN13-check-digit/AppleScript/isbn13-check-digit-1.applescript b/Task/ISBN13-check-digit/AppleScript/isbn13-check-digit-1.applescript index 112b6d9ea2..fa573cd714 100644 --- a/Task/ISBN13-check-digit/AppleScript/isbn13-check-digit-1.applescript +++ b/Task/ISBN13-check-digit/AppleScript/isbn13-check-digit-1.applescript @@ -27,7 +27,7 @@ on run end |λ| end script - map(test, {"978-1734314502", "978-1734314509", ¬ + map(test, {"978-0596528126", "978-0596528120", ¬ "978-1788399081", "978-1788399083"}) end run diff --git a/Task/ISBN13-check-digit/AppleScript/isbn13-check-digit-2.applescript b/Task/ISBN13-check-digit/AppleScript/isbn13-check-digit-2.applescript index 4ee26cf8b1..4b1c6abbc6 100644 --- a/Task/ISBN13-check-digit/AppleScript/isbn13-check-digit-2.applescript +++ b/Task/ISBN13-check-digit/AppleScript/isbn13-check-digit-2.applescript @@ -26,7 +26,7 @@ end validateISBN13 -- Test: set output to {} set verdicts to {"bad", "good"} -repeat with thisISBN13 in {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"} +repeat with thisISBN13 in {"978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"} set isValid to validateISBN13(thisISBN13) set end of output to thisISBN13 & ": " & item ((isValid as integer) + 1) of verdicts end repeat diff --git a/Task/ISBN13-check-digit/Arturo/isbn13-check-digit.arturo b/Task/ISBN13-check-digit/Arturo/isbn13-check-digit.arturo index 557101111c..ebabc6d242 100644 --- a/Task/ISBN13-check-digit/Arturo/isbn13-check-digit.arturo +++ b/Task/ISBN13-check-digit/Arturo/isbn13-check-digit.arturo @@ -12,7 +12,7 @@ validISBN?: function [isbn][ ] tests: [ - "978-1734314502" "978-1734314509" + "978-0596528126" "978-0596528120" "978-1788399081" "978-1788399083" ] diff --git a/Task/ISBN13-check-digit/AutoHotkey/isbn13-check-digit-2.ahk b/Task/ISBN13-check-digit/AutoHotkey/isbn13-check-digit-2.ahk index 344dd81b87..c5add79ab7 100644 --- a/Task/ISBN13-check-digit/AutoHotkey/isbn13-check-digit-2.ahk +++ b/Task/ISBN13-check-digit/AutoHotkey/isbn13-check-digit-2.ahk @@ -1,5 +1,5 @@ output := "" -nums := ["978-1734314502","978-1734314509","978-1788399081","978-1788399083"] +nums := ["978-0596528126","978-0596528120","978-1788399081","978-1788399083"] for i, n in nums output .= ISBN13_check_digit(n) "`n" MsgBox % output diff --git a/Task/ISBN13-check-digit/BASIC256/isbn13-check-digit.basic b/Task/ISBN13-check-digit/BASIC256/isbn13-check-digit.basic index 55041dded4..85d4ea1c90 100644 --- a/Task/ISBN13-check-digit/BASIC256/isbn13-check-digit.basic +++ b/Task/ISBN13-check-digit/BASIC256/isbn13-check-digit.basic @@ -1,5 +1,5 @@ arraybase 1 -dim isbn = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"} +dim isbn = {"978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"} for n = 1 to isbn[?] sum = 0 diff --git a/Task/ISBN13-check-digit/BCPL/isbn13-check-digit.bcpl b/Task/ISBN13-check-digit/BCPL/isbn13-check-digit.bcpl index d3f6cff2a7..d67ddb5247 100644 --- a/Task/ISBN13-check-digit/BCPL/isbn13-check-digit.bcpl +++ b/Task/ISBN13-check-digit/BCPL/isbn13-check-digit.bcpl @@ -26,8 +26,8 @@ let show(s) be writef("%S: %S*N", s, checkISBN(s) -> "good", "bad") let start() be -$( show("978-1734314502") - show("978-1734314509") +$( show("978-0596528126") + show("978-0596528120") show("978-1788399081") show("978-1788399083") $) diff --git a/Task/ISBN13-check-digit/C++/isbn13-check-digit.cpp b/Task/ISBN13-check-digit/C++/isbn13-check-digit.cpp index 682b7d87ae..c3b88d4e3d 100644 --- a/Task/ISBN13-check-digit/C++/isbn13-check-digit.cpp +++ b/Task/ISBN13-check-digit/C++/isbn13-check-digit.cpp @@ -27,7 +27,7 @@ bool check_isbn13(std::string isbn) { } int main() { - auto isbns = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" }; + auto isbns = { "978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083" }; for (auto isbn : isbns) { std::cout << isbn << ": " << (check_isbn13(isbn) ? "good" : "bad") << '\n'; } diff --git a/Task/ISBN13-check-digit/C-sharp/isbn13-check-digit.cs b/Task/ISBN13-check-digit/C-sharp/isbn13-check-digit.cs index 31400bce6a..e1e8fd4f9d 100644 --- a/Task/ISBN13-check-digit/C-sharp/isbn13-check-digit.cs +++ b/Task/ISBN13-check-digit/C-sharp/isbn13-check-digit.cs @@ -4,8 +4,8 @@ using System.Linq; public class Program { public static void Main() { - Console.WriteLine(CheckISBN13("978-1734314502")); - Console.WriteLine(CheckISBN13("978-1734314509")); + Console.WriteLine(CheckISBN13("978-0596528126")); + Console.WriteLine(CheckISBN13("978-0596528120")); Console.WriteLine(CheckISBN13("978-1788399081")); Console.WriteLine(CheckISBN13("978-1788399083")); diff --git a/Task/ISBN13-check-digit/C/isbn13-check-digit.c b/Task/ISBN13-check-digit/C/isbn13-check-digit.c index 0ca8023752..d99fcef1eb 100644 --- a/Task/ISBN13-check-digit/C/isbn13-check-digit.c +++ b/Task/ISBN13-check-digit/C/isbn13-check-digit.c @@ -24,7 +24,7 @@ int check_isbn13(const char *isbn) { int main() { int i; - const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}; + const char* isbns[] = {"978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"}; for (i = 0; i < 4; ++i) { printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad"); } diff --git a/Task/ISBN13-check-digit/CLU/isbn13-check-digit.clu b/Task/ISBN13-check-digit/CLU/isbn13-check-digit.clu index 9748799d2d..d1a19caddc 100644 --- a/Task/ISBN13-check-digit/CLU/isbn13-check-digit.clu +++ b/Task/ISBN13-check-digit/CLU/isbn13-check-digit.clu @@ -18,8 +18,8 @@ end isbn13_check start_up = proc () po: stream := stream$primary_output() tests: array[string] := array[string]$ - ["978-1734314502", - "978-1734314509", + ["978-0596528126", + "978-0596528120", "978-1788399081", "978-1788399083"] diff --git a/Task/ISBN13-check-digit/COBOL/isbn13-check-digit.cobol b/Task/ISBN13-check-digit/COBOL/isbn13-check-digit.cobol index 6f22cf56b9..5e0d564628 100644 --- a/Task/ISBN13-check-digit/COBOL/isbn13-check-digit.cobol +++ b/Task/ISBN13-check-digit/COBOL/isbn13-check-digit.cobol @@ -25,8 +25,8 @@ 01 IX PIC S9(4) COMP. 01 TEST-ISBNS. - 02 FILLER PIC X(14) VALUE '978-1734314502'. - 02 FILLER PIC X(14) VALUE '978-1734314509'. + 02 FILLER PIC X(14) VALUE '978-0596528126'. + 02 FILLER PIC X(14) VALUE '978-0596528120'. 02 FILLER PIC X(14) VALUE '978-1788399081'. 02 FILLER PIC X(14) VALUE '978-1788399083'. 01 TEST-ISBN REDEFINES TEST-ISBNS diff --git a/Task/ISBN13-check-digit/Cowgol/isbn13-check-digit.cowgol b/Task/ISBN13-check-digit/Cowgol/isbn13-check-digit.cowgol index a30c05c833..319babf744 100644 --- a/Task/ISBN13-check-digit/Cowgol/isbn13-check-digit.cowgol +++ b/Task/ISBN13-check-digit/Cowgol/isbn13-check-digit.cowgol @@ -24,7 +24,7 @@ sub check_isbn13(isbn: [uint8]): (r: uint8) is end sub; var isbns: [uint8][] := { - "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" + "978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083" }; var result: [uint8][] := {": bad\n", ": good\n"}; diff --git a/Task/ISBN13-check-digit/D/isbn13-check-digit.d b/Task/ISBN13-check-digit/D/isbn13-check-digit.d index a7a0ca6d55..947680cbbc 100644 --- a/Task/ISBN13-check-digit/D/isbn13-check-digit.d +++ b/Task/ISBN13-check-digit/D/isbn13-check-digit.d @@ -18,8 +18,8 @@ bool isValidISBN13(string text) { } unittest { - assert(isValidISBN13("978-1734314502")); - assert(!isValidISBN13("978-1734314509")); + assert(isValidISBN13("978-0596528126")); + assert(!isValidISBN13("978-0596528120")); assert(isValidISBN13("978-1788399081")); assert(!isValidISBN13("978-1788399083")); } diff --git a/Task/ISBN13-check-digit/Draco/isbn13-check-digit.draco b/Task/ISBN13-check-digit/Draco/isbn13-check-digit.draco index 126d1a413d..3b75eddd06 100644 --- a/Task/ISBN13-check-digit/Draco/isbn13-check-digit.draco +++ b/Task/ISBN13-check-digit/Draco/isbn13-check-digit.draco @@ -32,8 +32,8 @@ proc nonrec test(*char isbn) void: corp proc nonrec main() void: - test("978-1734314502"); - test("978-1734314509"); + test("978-0596528126"); + test("978-0596528120"); test("978-1788399081"); test("978-1788399083") corp diff --git a/Task/ISBN13-check-digit/Factor/isbn13-check-digit.factor b/Task/ISBN13-check-digit/Factor/isbn13-check-digit.factor index 34a7ba49f8..a84cdada97 100644 --- a/Task/ISBN13-check-digit/Factor/isbn13-check-digit.factor +++ b/Task/ISBN13-check-digit/Factor/isbn13-check-digit.factor @@ -10,5 +10,5 @@ sequences.extras sets unicode ; "- " without { [ length 13 = ] [ [ digit? ] all? ] [ (isbn13?) ] } 1&& ; -qw{ 978-1734314502 978-1734314509 978-1788399081 978-1788399083 } +qw{ 978-0596528126 978-0596528120 978-1788399081 978-1788399083 } [ dup isbn13? "good" "bad" ? "%s: %s\n" printf ] each diff --git a/Task/ISBN13-check-digit/Fortran/isbn13-check-digit.f b/Task/ISBN13-check-digit/Fortran/isbn13-check-digit.f index 12d7e68000..b32c2af037 100644 --- a/Task/ISBN13-check-digit/Fortran/isbn13-check-digit.f +++ b/Task/ISBN13-check-digit/Fortran/isbn13-check-digit.f @@ -1,7 +1,7 @@ program isbn13 implicit none - character(len=14), dimension(4), parameter :: isbns=["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"] + character(len=14), dimension(4), parameter :: isbns=["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"] integer :: i do i = 1, ubound(isbns, 1) diff --git a/Task/ISBN13-check-digit/FreeBASIC/isbn13-check-digit.basic b/Task/ISBN13-check-digit/FreeBASIC/isbn13-check-digit.basic index 5b844b3543..7a1281d01d 100644 --- a/Task/ISBN13-check-digit/FreeBASIC/isbn13-check-digit.basic +++ b/Task/ISBN13-check-digit/FreeBASIC/isbn13-check-digit.basic @@ -26,7 +26,7 @@ function is_good_isbn( isbn as string ) as boolean end if end function -dim as string isbns(0 to 3) = { "978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083" } +dim as string isbns(0 to 3) = { "978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083" } dim as uinteger i for i = 0 to 3 if is_good_isbn( isbns(i) ) then diff --git a/Task/ISBN13-check-digit/Gambas/isbn13-check-digit.gambas b/Task/ISBN13-check-digit/Gambas/isbn13-check-digit.gambas index 4b764de77c..634d0ed7aa 100644 --- a/Task/ISBN13-check-digit/Gambas/isbn13-check-digit.gambas +++ b/Task/ISBN13-check-digit/Gambas/isbn13-check-digit.gambas @@ -1,6 +1,6 @@ Public Sub Main() - Dim isbn As String[] = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"] + Dim isbn As String[] = ["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083", "978-2-74839-908-0", "978-2-74839-908-5", "978 1 86197 876 9"] For n As Integer = 1 To isbn.Count Dim sum As Integer = 0, num As Integer diff --git a/Task/ISBN13-check-digit/Go/isbn13-check-digit.go b/Task/ISBN13-check-digit/Go/isbn13-check-digit.go index 192e2b7c47..2c1d871cfe 100644 --- a/Task/ISBN13-check-digit/Go/isbn13-check-digit.go +++ b/Task/ISBN13-check-digit/Go/isbn13-check-digit.go @@ -30,7 +30,7 @@ func checkIsbn13(isbn string) bool { } func main() { - isbns := []string{"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"} + isbns := []string{"978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"} for _, isbn := range isbns { res := "bad" if checkIsbn13(isbn) { diff --git a/Task/ISBN13-check-digit/Haskell/isbn13-check-digit-1.hs b/Task/ISBN13-check-digit/Haskell/isbn13-check-digit-1.hs index c53341178d..64855019b6 100644 --- a/Task/ISBN13-check-digit/Haskell/isbn13-check-digit-1.hs +++ b/Task/ISBN13-check-digit/Haskell/isbn13-check-digit-1.hs @@ -21,8 +21,8 @@ main :: IO () main = mapM_ (printf "%s: Valid: %s\n" <*> (show . validIsbn13)) - [ "978-1734314502", - "978-1734314509", + [ "978-0596528126", + "978-0596528120", "978-1788399081", "978-1788399083" ] diff --git a/Task/ISBN13-check-digit/Haskell/isbn13-check-digit-2.hs b/Task/ISBN13-check-digit/Haskell/isbn13-check-digit-2.hs index f2b6bc3241..0c477b4856 100644 --- a/Task/ISBN13-check-digit/Haskell/isbn13-check-digit-2.hs +++ b/Task/ISBN13-check-digit/Haskell/isbn13-check-digit-2.hs @@ -13,8 +13,8 @@ main :: IO () main = mapM_ (print . ((,) <*> isISBN13)) - [ "978-1734314502", - "978-1734314509", + [ "978-0596528126", + "978-0596528120", "978-1788399081", "978-1788399083" ] diff --git a/Task/ISBN13-check-digit/J/isbn13-check-digit-2.j b/Task/ISBN13-check-digit/J/isbn13-check-digit-2.j index fbe28e101a..d17b4033f1 100644 --- a/Task/ISBN13-check-digit/J/isbn13-check-digit-2.j +++ b/Task/ISBN13-check-digit/J/isbn13-check-digit-2.j @@ -1,2 +1,2 @@ - isbn13c;._1 ' 978-1734314502 978-1734314509 978-1788399081 978-1788399083' + isbn13c;._1 ' 978-0596528126 978-0596528120 978-1788399081 978-1788399083' 1 0 1 0 diff --git a/Task/ISBN13-check-digit/Java/isbn13-check-digit-2.java b/Task/ISBN13-check-digit/Java/isbn13-check-digit-2.java index 5e2a85f211..70e0302fd0 100644 --- a/Task/ISBN13-check-digit/Java/isbn13-check-digit-2.java +++ b/Task/ISBN13-check-digit/Java/isbn13-check-digit-2.java @@ -1,6 +1,6 @@ public static void main(){ - System.out.println(isISBN13("978-1734314502")); - System.out.println(isISBN13("978-1734314509")); + System.out.println(isISBN13("978-0596528126")); + System.out.println(isISBN13("978-0596528120")); System.out.println(isISBN13("978-1788399081")); System.out.println(isISBN13("978-1788399083")); } diff --git a/Task/ISBN13-check-digit/Jq/isbn13-check-digit.jq b/Task/ISBN13-check-digit/Jq/isbn13-check-digit.jq index 77ae92356d..f26f0d89d6 100644 --- a/Task/ISBN13-check-digit/Jq/isbn13-check-digit.jq +++ b/Task/ISBN13-check-digit/Jq/isbn13-check-digit.jq @@ -8,7 +8,7 @@ def isbn_check: | (($one+$two) % 10) == 0; def testingcodes: - ["978-1734314502", "978-1734314509", + ["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"]; testingcodes[] diff --git a/Task/ISBN13-check-digit/Julia/isbn13-check-digit.julia b/Task/ISBN13-check-digit/Julia/isbn13-check-digit.julia index 5f4bc1498c..31cb75bcb6 100644 --- a/Task/ISBN13-check-digit/Julia/isbn13-check-digit.julia +++ b/Task/ISBN13-check-digit/Julia/isbn13-check-digit.julia @@ -3,7 +3,7 @@ function isbncheck(str) for (i, ch) in enumerate(replace(str, r"\D" => ""))) % 10 == 0 end -const testingcodes = ["978-1734314502", "978-1734314509", +const testingcodes = ["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"] for code in testingcodes diff --git a/Task/ISBN13-check-digit/Kotlin/isbn13-check-digit-2.kotlin b/Task/ISBN13-check-digit/Kotlin/isbn13-check-digit-2.kotlin index 127f3bfa86..e609262941 100644 --- a/Task/ISBN13-check-digit/Kotlin/isbn13-check-digit-2.kotlin +++ b/Task/ISBN13-check-digit/Kotlin/isbn13-check-digit-2.kotlin @@ -1,7 +1,7 @@ describe("ISBN Utilities") { mapOf( - "978-1734314502" to true, - "978-1734314509" to false, + "978-0596528126" to true, + "978-0596528120" to false, "978-1788399081" to true, "978-1788399083" to false ).forEach { (input, expected) -> diff --git a/Task/ISBN13-check-digit/Lua/isbn13-check-digit.lua b/Task/ISBN13-check-digit/Lua/isbn13-check-digit.lua index 540339953c..989dfcebda 100644 --- a/Task/ISBN13-check-digit/Lua/isbn13-check-digit.lua +++ b/Task/ISBN13-check-digit/Lua/isbn13-check-digit.lua @@ -32,8 +32,8 @@ function test(isbn) end function main() - test("978-1734314502") - test("978-1734314509") + test("978-0596528126") + test("978-0596528120") test("978-1788399081") test("978-1788399083") end diff --git a/Task/ISBN13-check-digit/Mathematica/isbn13-check-digit.math b/Task/ISBN13-check-digit/Mathematica/isbn13-check-digit.math index 489404ac14..12f3a00939 100644 --- a/Task/ISBN13-check-digit/Mathematica/isbn13-check-digit.math +++ b/Task/ISBN13-check-digit/Mathematica/isbn13-check-digit.math @@ -9,7 +9,7 @@ ValidISBNQ[iban_String] := Module[{i}, False ] ] -ValidISBNQ["978-1734314502"] -ValidISBNQ["978-1734314509"] +ValidISBNQ["978-0596528126"] +ValidISBNQ["978-0596528120"] ValidISBNQ["978-1788399081"] ValidISBNQ["978-1788399083"] diff --git a/Task/ISBN13-check-digit/Modula-2/isbn13-check-digit.mod2 b/Task/ISBN13-check-digit/Modula-2/isbn13-check-digit.mod2 index f713239a1a..47d5c6c250 100644 --- a/Task/ISBN13-check-digit/Modula-2/isbn13-check-digit.mod2 +++ b/Task/ISBN13-check-digit/Modula-2/isbn13-check-digit.mod2 @@ -37,8 +37,8 @@ BEGIN END check; BEGIN - check('978-1734314502'); - check('978-1734314509'); + check('978-0596528126'); + check('978-0596528120'); check('978-1788399081'); check('978-1788399083'); END ISBN. diff --git a/Task/ISBN13-check-digit/Nanoquery/isbn13-check-digit.nanoquery b/Task/ISBN13-check-digit/Nanoquery/isbn13-check-digit.nanoquery index 19bf8cf9f3..e592ebc549 100644 --- a/Task/ISBN13-check-digit/Nanoquery/isbn13-check-digit.nanoquery +++ b/Task/ISBN13-check-digit/Nanoquery/isbn13-check-digit.nanoquery @@ -25,7 +25,7 @@ def checkIsbn13(isbn) return (sum % 10) = 0 end -isbns = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"} +isbns = {"978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"} for isbn in isbns res = "bad" if checkIsbn13(isbn) diff --git a/Task/ISBN13-check-digit/Nim/isbn13-check-digit.nim b/Task/ISBN13-check-digit/Nim/isbn13-check-digit.nim index dba54619b0..3d0db84e0f 100644 --- a/Task/ISBN13-check-digit/Nim/isbn13-check-digit.nim +++ b/Task/ISBN13-check-digit/Nim/isbn13-check-digit.nim @@ -11,7 +11,7 @@ func is_isbn*(s: string): bool = return (len == 13) and (sum mod 10 == 0) when is_main_module: - let isbns = [ "978-1734314502", "978-1734314509", + let isbns = [ "978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083" ] for isbn in isbns: var quality: string = if is_isbn(isbn): "good" else: "bad" diff --git a/Task/ISBN13-check-digit/PL-M/isbn13-check-digit.plm b/Task/ISBN13-check-digit/PL-M/isbn13-check-digit.plm index 991b89d266..7bd84538e5 100644 --- a/Task/ISBN13-check-digit/PL-M/isbn13-check-digit.plm +++ b/Task/ISBN13-check-digit/PL-M/isbn13-check-digit.plm @@ -33,8 +33,8 @@ END PRINT; /* TESTS */ DECLARE TEST (4) ADDRESS; -TEST(0) = .'978-1734314502$'; -TEST(1) = .'978-1734314509$'; +TEST(0) = .'978-0596528126$'; +TEST(1) = .'978-0596528120$'; TEST(2) = .'978-1788399081$'; TEST(3) = .'978-1788399083$'; diff --git a/Task/ISBN13-check-digit/Pascal/isbn13-check-digit.pas b/Task/ISBN13-check-digit/Pascal/isbn13-check-digit.pas index 381d53bd31..06ce06d05d 100644 --- a/Task/ISBN13-check-digit/Pascal/isbn13-check-digit.pas +++ b/Task/ISBN13-check-digit/Pascal/isbn13-check-digit.pas @@ -78,8 +78,8 @@ end; { === MAIN ============================================================= } begin - writeLn(isValidISBNString('978-1734314502')); - writeLn(isValidISBNString('978-1734314509')); + writeLn(isValidISBNString('978-0596528126')); + writeLn(isValidISBNString('978-0596528120')); writeLn(isValidISBNString('978-1788399081')); writeLn(isValidISBNString('978-1788399083')) end. diff --git a/Task/ISBN13-check-digit/Perl/isbn13-check-digit.pl b/Task/ISBN13-check-digit/Perl/isbn13-check-digit.pl index be559a48a4..8e94b26803 100644 --- a/Task/ISBN13-check-digit/Perl/isbn13-check-digit.pl +++ b/Task/ISBN13-check-digit/Perl/isbn13-check-digit.pl @@ -8,7 +8,7 @@ sub check_digit { (10 - $sum % 10) % 10; } -for (<978-1734314502 978-1734314509 978-1788399081 978-1788399083 978-2-74839-908-0 978-2-74839-908-5>) { +for (<978-0596528126 978-0596528120 978-1788399081 978-1788399083 978-2-74839-908-0 978-2-74839-908-5>) { my($isbn,$check) = /(.*)(.)/; my $check_d = check_digit($isbn); say "$_ : " . ($check == $check_d ? 'Good' : "Bad check-digit $check; should be $check_d") diff --git a/Task/ISBN13-check-digit/Phix/isbn13-check-digit.phix b/Task/ISBN13-check-digit/Phix/isbn13-check-digit.phix index 4592d63d1c..d25e5b82da 100644 --- a/Task/ISBN13-check-digit/Phix/isbn13-check-digit.phix +++ b/Task/ISBN13-check-digit/Phix/isbn13-check-digit.phix @@ -17,7 +17,7 @@ printf(1,"%s: %s\n",{isbn,gb}) end procedure - constant isbns = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083", + constant isbns = {"978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083", "978-2-74839-908-0","978-2-74839-908-5","978 1 86197 876 9"} for i=1 to length(isbns) do check_isbn13(isbns[i]) end for ) -$ '978-1734314502' isbn-test -$ '978-1734314509' isbn-test +$ '978-0596528126' isbn-test +$ '978-0596528120' isbn-test $ '978-1788399081' isbn-test $ '978-1788399083' isbn-test diff --git a/Task/ISBN13-check-digit/REXX/isbn13-check-digit.rexx b/Task/ISBN13-check-digit/REXX/isbn13-check-digit.rexx index ac2bb1acc9..cfb6e8d470 100644 --- a/Task/ISBN13-check-digit/REXX/isbn13-check-digit.rexx +++ b/Task/ISBN13-check-digit/REXX/isbn13-check-digit.rexx @@ -1,6 +1,6 @@ /*REXX pgm validates the check digit of an ISBN─13 code (it may have embedded minuses).*/ parse arg $ /*obtain optional arguments from the CL*/ -if $='' | if $="," then $= '978-1734314502 978-1734314509 978-1788399081 978-1788399083' +if $='' | if $="," then $= '978-0596528126 978-0596528120 978-1788399081 978-1788399083' @ISBN= "ISBN─13 code isn't" /*a literal used when displaying msgs. */ /* [↓] remove all minuses from X code.*/ do j=1 for words($); y= word($,j) /*obtain an ISBN─13 code from $ list.*/ diff --git a/Task/ISBN13-check-digit/Racket/isbn13-check-digit.rkt b/Task/ISBN13-check-digit/Racket/isbn13-check-digit.rkt index 3c0cadc63c..3b0f0f3f63 100644 --- a/Task/ISBN13-check-digit/Racket/isbn13-check-digit.rkt +++ b/Task/ISBN13-check-digit/Racket/isbn13-check-digit.rkt @@ -9,7 +9,7 @@ (module+ test (require rackunit) - (check-true (isbn13-check-digit-valid? "978-1734314502")) - (check-false (isbn13-check-digit-valid? "978-1734314509")) + (check-true (isbn13-check-digit-valid? "978-0596528126")) + (check-false (isbn13-check-digit-valid? "978-0596528120")) (check-true (isbn13-check-digit-valid? "978-1788399081")) (check-false (isbn13-check-digit-valid? "978-1788399083"))) diff --git a/Task/ISBN13-check-digit/Raku/isbn13-check-digit.raku b/Task/ISBN13-check-digit/Raku/isbn13-check-digit.raku index 88e9fdc77d..a5a76b6df9 100644 --- a/Task/ISBN13-check-digit/Raku/isbn13-check-digit.raku +++ b/Task/ISBN13-check-digit/Raku/isbn13-check-digit.raku @@ -9,8 +9,8 @@ sub check-digit ($isbn) { 'Good' !! "Bad check-digit $check; should be $check-digit" } for words < - 978-1734314502 - 978-1734314509 + 978-0596528126 + 978-0596528120 978-1788399081 978-1788399083 978-2-74839-908-0 diff --git a/Task/ISBN13-check-digit/Red/isbn13-check-digit.red b/Task/ISBN13-check-digit/Red/isbn13-check-digit.red index 405e8b0f3b..ac16d0ea46 100644 --- a/Task/ISBN13-check-digit/Red/isbn13-check-digit.red +++ b/Task/ISBN13-check-digit/Red/isbn13-check-digit.red @@ -16,7 +16,7 @@ check_valid_isbn13: function [str] [ ] ; check given examples -foreach [str] ["978-1734314502" "978-1734314509" "978-1788399081" "978-1788399083"] [ +foreach [str] ["978-0596528126" "978-0596528120" "978-1788399081" "978-1788399083"] [ prin str prin " - " print check_valid_isbn13 str diff --git a/Task/ISBN13-check-digit/Ring/isbn13-check-digit.ring b/Task/ISBN13-check-digit/Ring/isbn13-check-digit.ring index d6c5e41207..98958ab94a 100644 --- a/Task/ISBN13-check-digit/Ring/isbn13-check-digit.ring +++ b/Task/ISBN13-check-digit/Ring/isbn13-check-digit.ring @@ -1,6 +1,6 @@ load "stdlib.ring" -isbn = ["978-1734314502","978-1734314509", "978-1788399081", "978-1788399083","978-2-74839-908-0","978-2-74839-908-5","978 1 86197 876 9"] +isbn = ["978-0596528126","978-0596528120", "978-1788399081", "978-1788399083","978-2-74839-908-0","978-2-74839-908-5","978 1 86197 876 9"] for n = 1 to len(isbn) sum = 0 diff --git a/Task/ISBN13-check-digit/Ruby/isbn13-check-digit.rb b/Task/ISBN13-check-digit/Ruby/isbn13-check-digit.rb index f734cdfdf6..d46e18462d 100644 --- a/Task/ISBN13-check-digit/Ruby/isbn13-check-digit.rb +++ b/Task/ISBN13-check-digit/Ruby/isbn13-check-digit.rb @@ -4,5 +4,5 @@ def validISBN13?(str) cleaned.each_slice(2).sum{|d1, d2| d1.to_i + 3*d2.to_i }.remainder(10) == 0 end -isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"] +isbns = ["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"] isbns.each{|isbn| puts "#{isbn}: #{validISBN13?(isbn)}" } diff --git a/Task/ISBN13-check-digit/Rust/isbn13-check-digit.rust b/Task/ISBN13-check-digit/Rust/isbn13-check-digit.rust index 76efbed13f..081a5323e7 100644 --- a/Task/ISBN13-check-digit/Rust/isbn13-check-digit.rust +++ b/Task/ISBN13-check-digit/Rust/isbn13-check-digit.rust @@ -1,5 +1,5 @@ fn main() { - let isbns = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]; + let isbns = ["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"]; isbns.iter().for_each(|isbn| println!("{}: {}", isbn, check_isbn(isbn))); } diff --git a/Task/ISBN13-check-digit/Seed7/isbn13-check-digit.seed7 b/Task/ISBN13-check-digit/Seed7/isbn13-check-digit.seed7 index f9553006ec..9d29803ea3 100644 --- a/Task/ISBN13-check-digit/Seed7/isbn13-check-digit.seed7 +++ b/Task/ISBN13-check-digit/Seed7/isbn13-check-digit.seed7 @@ -28,7 +28,7 @@ const proc: main is func local var string: str is ""; begin - for str range [] ("978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083") do + for str range [] ("978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083") do writeln(str <& ": " <& isISBN13(str)); end for; end func; diff --git a/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml index 3ea0737bff..14abd4e5fc 100644 --- a/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml +++ b/Task/ISBN13-check-digit/Standard-ML/isbn13-check-digit.ml @@ -9,7 +9,7 @@ in Int.rem (#2 (CharVector.foldl check (false, 0) s), 10) = 0 end -val test = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"] +val test = ["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"] val () = (print o concat o map (fn s => s ^ (if checkISBN s then ": good\n" else ": bad\n"))) test diff --git a/Task/ISBN13-check-digit/Swift/isbn13-check-digit.swift b/Task/ISBN13-check-digit/Swift/isbn13-check-digit.swift index cefe08f9fb..b5c70229ac 100644 --- a/Task/ISBN13-check-digit/Swift/isbn13-check-digit.swift +++ b/Task/ISBN13-check-digit/Swift/isbn13-check-digit.swift @@ -13,8 +13,8 @@ func checkISBN(isbn: String) -> Bool { } let cases = [ - "978-1734314502", - "978-1734314509", + "978-0596528126", + "978-0596528120", "978-1788399081", "978-1788399083" ] diff --git a/Task/ISBN13-check-digit/Tcl/isbn13-check-digit-1.tcl b/Task/ISBN13-check-digit/Tcl/isbn13-check-digit-1.tcl index 6dfa79dbbb..9a8d8f0d03 100644 --- a/Task/ISBN13-check-digit/Tcl/isbn13-check-digit-1.tcl +++ b/Task/ISBN13-check-digit/Tcl/isbn13-check-digit-1.tcl @@ -12,8 +12,8 @@ proc validISBN13 code { return false } foreach test { - 978-1734314502 - 978-1734314509 + 978-0596528126 + 978-0596528120 978-1788399081 978-1788399083 } {puts $test:[validISBN13 $test]} diff --git a/Task/ISBN13-check-digit/UNIX-Shell/isbn13-check-digit.sh b/Task/ISBN13-check-digit/UNIX-Shell/isbn13-check-digit.sh index c0de8e51b3..301b5984c7 100644 --- a/Task/ISBN13-check-digit/UNIX-Shell/isbn13-check-digit.sh +++ b/Task/ISBN13-check-digit/UNIX-Shell/isbn13-check-digit.sh @@ -8,7 +8,7 @@ check_isbn13 () { (( 0 == t % 10 )) } -for isbn in 978-1734314502 978-1734314509 978-1788399081 978-1788399083; do +for isbn in 978-0596528126 978-0596528120 978-1788399081 978-1788399083; do printf '%s: ' "$isbn" if check_isbn13 "$isbn"; then printf '%s\n' OK diff --git a/Task/ISBN13-check-digit/V-(Vlang)/isbn13-check-digit.v b/Task/ISBN13-check-digit/V-(Vlang)/isbn13-check-digit.v index fdaef1252b..da68e4c3de 100644 --- a/Task/ISBN13-check-digit/V-(Vlang)/isbn13-check-digit.v +++ b/Task/ISBN13-check-digit/V-(Vlang)/isbn13-check-digit.v @@ -22,7 +22,7 @@ fn check_isbn13(isbn13 string) bool { } fn main() { - isbns := ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"] + isbns := ["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"] for isbn in isbns { mut res := "bad" if check_isbn13(isbn) { diff --git a/Task/ISBN13-check-digit/Visual-Basic-.NET/isbn13-check-digit.vb b/Task/ISBN13-check-digit/Visual-Basic-.NET/isbn13-check-digit.vb index bdacc7a702..be6ff129a9 100644 --- a/Task/ISBN13-check-digit/Visual-Basic-.NET/isbn13-check-digit.vb +++ b/Task/ISBN13-check-digit/Visual-Basic-.NET/isbn13-check-digit.vb @@ -19,8 +19,8 @@ Module Module1 End Function Sub Main() - Console.WriteLine(CheckISBN13("978-1734314502")) - Console.WriteLine(CheckISBN13("978-1734314509")) + Console.WriteLine(CheckISBN13("978-0596528126")) + Console.WriteLine(CheckISBN13("978-0596528120")) Console.WriteLine(CheckISBN13("978-1788399081")) Console.WriteLine(CheckISBN13("978-1788399083")) End Sub diff --git a/Task/ISBN13-check-digit/Wren/isbn13-check-digit.wren b/Task/ISBN13-check-digit/Wren/isbn13-check-digit.wren index af45d2f2a2..bca6ca7452 100644 --- a/Task/ISBN13-check-digit/Wren/isbn13-check-digit.wren +++ b/Task/ISBN13-check-digit/Wren/isbn13-check-digit.wren @@ -15,7 +15,7 @@ var isbn13 = Fn.new { |s| return sum % 10 == 0 } -var tests = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"] +var tests = ["978-0596528126", "978-0596528120", "978-1788399081", "978-1788399083"] for (test in tests) { System.print("%(test) -> %(isbn13.call(test) ? "good" : "bad")") } diff --git a/Task/ISBN13-check-digit/XPL0/isbn13-check-digit.xpl0 b/Task/ISBN13-check-digit/XPL0/isbn13-check-digit.xpl0 index e045aab504..c2eaf4e120 100644 --- a/Task/ISBN13-check-digit/XPL0/isbn13-check-digit.xpl0 +++ b/Task/ISBN13-check-digit/XPL0/isbn13-check-digit.xpl0 @@ -18,8 +18,8 @@ Text(0, if rem(Sum/10)=0 & Cnt=13 then ": good" else ": bad"); CrLf(0); ]; -[ISBN13("978-1734314502"); - ISBN13("978-1734314509"); +[ISBN13("978-0596528126"); + ISBN13("978-0596528120"); ISBN13("978-1788399081"); ISBN13("978-1788399083"); ISBN13("978-1-59327-220-3"); diff --git a/Task/ISBN13-check-digit/Zkl/isbn13-check-digit-1.zkl b/Task/ISBN13-check-digit/Zkl/isbn13-check-digit-1.zkl index c4be69768b..4f8dc9bcbd 100644 --- a/Task/ISBN13-check-digit/Zkl/isbn13-check-digit-1.zkl +++ b/Task/ISBN13-check-digit/Zkl/isbn13-check-digit-1.zkl @@ -1,4 +1,4 @@ -fcn ISBN13_check(isbn){ // "978-1734314502", throws on invalid digits +fcn ISBN13_check(isbn){ // "978-0596528126", throws on invalid digits var [const] one3=("13"*6 + 1).split("").apply("toInt"); // examine 13 digits // one3=("13"*6) if you want to calculate what the check digit should be one3.zipWith('*,isbn - " -").sum(0) % 10 == 0 diff --git a/Task/ISBN13-check-digit/Zkl/isbn13-check-digit-2.zkl b/Task/ISBN13-check-digit/Zkl/isbn13-check-digit-2.zkl index c96ff21fd2..ea42f0f25a 100644 --- a/Task/ISBN13-check-digit/Zkl/isbn13-check-digit-2.zkl +++ b/Task/ISBN13-check-digit/Zkl/isbn13-check-digit-2.zkl @@ -1,7 +1,7 @@ isbns:= #<<<" - 978-1734314502 - 978-1734314509 + 978-0596528126 + 978-0596528120 978-1788399081 978-1788399083 978-2-74839-908-0 diff --git a/Task/Identity-matrix/Elena/identity-matrix.elena b/Task/Identity-matrix/Elena/identity-matrix.elena index 661d1ef051..079b48e360 100644 --- a/Task/Identity-matrix/Elena/identity-matrix.elena +++ b/Task/Identity-matrix/Elena/identity-matrix.elena @@ -4,11 +4,11 @@ import system'collections; public program() { - var n := console.write:"Enter the matrix size:".readLine().toInt(); + var n := console.write("Enter the matrix size:").readLine().toInt(); - var identity := new Range(0, n).selectBy:(i => new Range(0,n).selectBy:(j => (i == j).iif(1,0) ).summarize(new ArrayList())) + var identity := new Range(0, n).selectBy::(i => new Range(0,n).selectBy::(j => (i == j).iif(1,0) ).summarize(new ArrayList())) .summarize(new ArrayList()); - identity.forEach: + identity.forEach:: (row) { console.printLine(row.asEnumerable()) } } diff --git a/Task/Image-noise/EasyLang/image-noise.easy b/Task/Image-noise/EasyLang/image-noise.easy index 002181b964..caf8d4663e 100644 --- a/Task/Image-noise/EasyLang/image-noise.easy +++ b/Task/Image-noise/EasyLang/image-noise.easy @@ -18,7 +18,7 @@ on animate col[] = [ 000 999 ] for x = 0 to 319 for y = 0 to 199 - pset x y col[random 2] + pset x y col[randint 2] . . . diff --git a/Task/Index-finite-lists-of-positive-integers/Jq/index-finite-lists-of-positive-integers-1.jq b/Task/Index-finite-lists-of-positive-integers/Jq/index-finite-lists-of-positive-integers-1.jq new file mode 100644 index 0000000000..bbe77de937 --- /dev/null +++ b/Task/Index-finite-lists-of-positive-integers/Jq/index-finite-lists-of-positive-integers-1.jq @@ -0,0 +1,43 @@ +include "fibonacci" {search: "./"}; # see https://rosettacode.org/wiki/Category:Jq/fibonacci.jq + +# Input: an array of integers +# Output: an integer-valued binary string, being the reverse of the concatenated Fibonacci-encoded values +def rank: + map(fibencode | map(tostring) | join("")) + | "1" + join(""); + +# Input a bitstring or 0-1 integer interpreted as a bitstring +# Output: an array of integers +def unrank: + tostring + | .[1:] + | split("11") + | .[:-1] + | map(. + "11" | fibdecode) ; + +# Output: a PRN in range(0;$n) where $n is . +def prn: + if . == 1 then 0 + else . as $n + | (($n-1)|tostring|length) as $w + | [limit($w; inputs) | tostring] | join("") | sub("^0+";"") | tonumber + | if . < $n then . else $n | prn end + end; + +### The task +# Encode and decode a random number of distinct positive numbers chosen at random. +# Produce a JSON object showing the set of numbers, their encoding, and +# the result of comparing the original set with the reconstructed set. +def task: + (11 | prn) + 1 + | . as $numbers + | [range(0;$numbers) | 100000 | prn + 1] + | . as $numbers + | rank + | . as $encoded + # now decode: + | unrank + | {$numbers, encoded: ($encoded|tonumber), check: ($numbers == .)} +; + +task diff --git a/Task/Index-finite-lists-of-positive-integers/Jq/index-finite-lists-of-positive-integers-2.jq b/Task/Index-finite-lists-of-positive-integers/Jq/index-finite-lists-of-positive-integers-2.jq new file mode 100644 index 0000000000..adee679e13 --- /dev/null +++ b/Task/Index-finite-lists-of-positive-integers/Jq/index-finite-lists-of-positive-integers-2.jq @@ -0,0 +1,49 @@ +### Infrastructure + +# Input: a string in base $b (2 to 35 inclusive) +# Output: the decimal value +def frombase($b): + def decimalValue: + if 48 <= . and . <= 57 then . - 48 + elif 65 <= . and . <= 90 then . - 55 # (10+.-65) + elif 97 <= . and . <= 122 then . - 87 # (10+.-97) + else "decimalValue" | error + end; + reduce (explode|reverse[]|decimalValue) as $x ({p:1}; + .value += (.p * $x) + | .p *= $b) + | .value ; + +def binary_digits: + if . == 0 then 0 + else [recurse( if . == 0 then empty else ./2 | floor end ) % 2 | tostring] + | reverse + | .[1:] # remove the leading 0 + | join("") + end ; + + +### rank and unrank +# Each integer n in the list is mapped to '1' plus n '0's. +# The empty list is mapped to '0' +def rank: + if length == 0 then 0 + else reduce .[] as $i (""; + . += "1" + ("0" * $i)) + | frombase(2) + end ; + +def unrank: + if . == 0 then [] + else binary_digits + | split("1") + | .[1:] + | map(length) + end ; + +### Illustration +range(1;11) +| . as $i +| unrank +| . as $unrank +| [$i, $unrank, rank] diff --git a/Task/Infinity/Jq/infinity-2.jq b/Task/Infinity/Jq/infinity-2.jq deleted file mode 100644 index 5117e0f8ee..0000000000 --- a/Task/Infinity/Jq/infinity-2.jq +++ /dev/null @@ -1 +0,0 @@ -def isinfinite: . == infinite; diff --git a/Task/Infinity/Jq/infinity-1.jq b/Task/Infinity/Jq/infinity.jq similarity index 100% rename from Task/Infinity/Jq/infinity-1.jq rename to Task/Infinity/Jq/infinity.jq diff --git a/Task/Input-loop/Elena/input-loop-1.elena b/Task/Input-loop/Elena/input-loop-1.elena index 1123b2b487..a5dcad0def 100644 --- a/Task/Input-loop/Elena/input-loop-1.elena +++ b/Task/Input-loop/Elena/input-loop-1.elena @@ -4,5 +4,5 @@ import extensions'routines; public program() { - ReaderEnumerator.new(File.assign:"file.txt").forEach(printingLn) + ReaderEnumerator.new(File.assign("file.txt")).forEach(printingLn) } diff --git a/Task/Input-loop/Elena/input-loop-2.elena b/Task/Input-loop/Elena/input-loop-2.elena index 87355876e5..166e56ec74 100644 --- a/Task/Input-loop/Elena/input-loop-2.elena +++ b/Task/Input-loop/Elena/input-loop-2.elena @@ -2,7 +2,7 @@ import system'io; public program() { - using(var reader := File.assign:"file.txt".textreader()) + using(var reader := File.assign("file.txt").textreader()) { while (reader.Available) { diff --git a/Task/Integer-sequence/Jq/integer-sequence-1.jq b/Task/Integer-sequence/Jq/integer-sequence-1.jq index 66b3bcd40c..02faf0b0e5 100644 --- a/Task/Integer-sequence/Jq/integer-sequence-1.jq +++ b/Task/Integer-sequence/Jq/integer-sequence-1.jq @@ -1,2 +1 @@ -def iota: ., (. + 1 | iota); -0 | iota +0 | recurse(. + 1) diff --git a/Task/Integer-sequence/Jq/integer-sequence-2.jq b/Task/Integer-sequence/Jq/integer-sequence-2.jq index 75004d0a70..66b3bcd40c 100644 --- a/Task/Integer-sequence/Jq/integer-sequence-2.jq +++ b/Task/Integer-sequence/Jq/integer-sequence-2.jq @@ -1 +1,2 @@ -0 | while(true;. + 1) +def iota: ., (. + 1 | iota); +0 | iota diff --git a/Task/Integer-sequence/Jq/integer-sequence-3.jq b/Task/Integer-sequence/Jq/integer-sequence-3.jq index 02faf0b0e5..ed60432096 100644 --- a/Task/Integer-sequence/Jq/integer-sequence-3.jq +++ b/Task/Integer-sequence/Jq/integer-sequence-3.jq @@ -1 +1 @@ -0 | recurse(. + 1) +0 | while(true; . + 1) diff --git a/Task/Intersecting-number-wheels/Jq/intersecting-number-wheels-1.jq b/Task/Intersecting-number-wheels/Jq/intersecting-number-wheels-1.jq new file mode 100644 index 0000000000..127c9787d8 --- /dev/null +++ b/Task/Intersecting-number-wheels/Jq/intersecting-number-wheels-1.jq @@ -0,0 +1,18 @@ +def wheels: [ + { + "A": [1, 2, 3] + }, + { + "A": [1, "B", 2], + "B": [3, 4] + }, + { + "A": [1, "D", "D"], + "D": [6, 7, 8] + }, + { + "A": [1, "B", "C"], + "B": [3, 4], + "C": [5, "B"] + } +]; diff --git a/Task/Intersecting-number-wheels/Jq/intersecting-number-wheels-2.jq b/Task/Intersecting-number-wheels/Jq/intersecting-number-wheels-2.jq new file mode 100644 index 0000000000..a0e8f8931a --- /dev/null +++ b/Task/Intersecting-number-wheels/Jq/intersecting-number-wheels-2.jq @@ -0,0 +1,39 @@ +# read($wheel) +# where $wheel is the wheel to be read (a string) +# Input: a set of wheels +# Output: an object such that .value is the next value, +# and .state is the updated state of the set of wheels +def read($wheel): + + # Input: an array + # Output: the rotated array + def rotate: .[1:] + [.[0]]; + + .[$wheel][0] as $value + | (.[$wheel] |= rotate) as $state + | if ($value | type) == "number" + then {$value, $state} + else $state | read($value) + end; + +# Read wheel $wheel $n times +def multiread($wheel; $n): + if $n <= 0 then empty + else read($wheel) + | .value, (.state | multiread($wheel; $n - 1)) + end; + +def printWheels: + keys[] as $k + | "\($k): \(.[$k])"; + +# Spin each group $n times +def spin($n): + wheels[] + | "The number wheel group:", + printWheels, + "generates", + ([ multiread("A"; $n) ] | join(" ") + " ..."), + ""; + +spin(20) diff --git a/Task/Introspection/Rust/introspection-1.rust b/Task/Introspection/Rust/introspection-1.rust new file mode 100644 index 0000000000..eea9ec7720 --- /dev/null +++ b/Task/Introspection/Rust/introspection-1.rust @@ -0,0 +1,2 @@ +[dependencies] +rustc_version = "0.4" diff --git a/Task/Introspection/Rust/introspection-2.rust b/Task/Introspection/Rust/introspection-2.rust new file mode 100644 index 0000000000..49447f3c29 --- /dev/null +++ b/Task/Introspection/Rust/introspection-2.rust @@ -0,0 +1,30 @@ +use rustc_version::{version_meta, Channel, version, Version}; + +fn main() { + // We can check the Rust channel currently being used: stable, nightly, etc. + match version_meta().unwrap().channel { + Channel::Stable => { + println!("Rust Stable"); + } + Channel::Beta => { + println!("Rust Beta"); + } + Channel::Nightly => { + println!("Rust Nightly"); + } + Channel::Dev => { + println!("Rust Dev"); + } + } + + // We can print the Rust compiler version + println!("{}",version().unwrap()); + + // We can check for a minimum Rust compiler version + if version().unwrap() >= Version::parse("1.50.0").unwrap() { + println!("Rust compiler version is ok."); + } else { + eprintln!("Rust compiler version is too old. Please update to a more recent version."); + std::process::exit(1); + } +} diff --git a/Task/Jacobsthal-numbers/C-sharp/jacobsthal-numbers.cs b/Task/Jacobsthal-numbers/C-sharp/jacobsthal-numbers.cs new file mode 100644 index 0000000000..1611e23918 --- /dev/null +++ b/Task/Jacobsthal-numbers/C-sharp/jacobsthal-numbers.cs @@ -0,0 +1,155 @@ +using System; +using System.Numerics; +using System.Threading; + +public class JacobsthalNumbers +{ + private static BigInteger currentJacobsthal = 0; + private static int latestIndex = 0; + private static readonly BigInteger Three = new BigInteger(3); + private const int Certainty = 20; + public static void Main(string[] args) + { + Console.WriteLine("The first 30 Jacobsthal Numbers:"); + for (int i = 0; i < 6; i++) + { + for (int k = 0; k < 5; k++) + { + Console.Write($"{JacobsthalNumber(i * 5 + k), 15}"); + } + + Console.WriteLine(); + } + + Console.WriteLine(); + Console.WriteLine("The first 30 Jacobsthal-Lucas Numbers:"); + for (int i = 0; i < 6; i++) + { + for (int k = 0; k < 5; k++) + { + Console.Write($"{JacobsthalLucasNumber(i * 5 + k), 15}"); + } + + Console.WriteLine(); + } + + Console.WriteLine(); + Console.WriteLine("The first 20 Jacobsthal oblong Numbers:"); + for (int i = 0; i < 4; i++) + { + for (int k = 0; k < 5; k++) + { + Console.Write($"{JacobsthalOblongNumber(i * 5 + k), 15}"); + } + + Console.WriteLine(); + } + + Console.WriteLine(); + Console.WriteLine("The first 10 Jacobsthal Primes:"); + for (int i = 0; i < 10; i++) + { + Console.WriteLine(JacobsthalPrimeNumber()); + } + } + + private static BigInteger JacobsthalNumber(int index) + { + BigInteger value = new BigInteger(ParityValue(index)); + return ((BigInteger.Parse("1") << index) - value) / Three; + } + + private static long JacobsthalLucasNumber(int index) + { + return (1L << index) + ParityValue(index); + } + + private static long JacobsthalOblongNumber(int index) + { + BigInteger nextJacobsthal = JacobsthalNumber(index + 1); + long result = (long)(currentJacobsthal * nextJacobsthal); + currentJacobsthal = nextJacobsthal; + return result; + } + + private static long JacobsthalPrimeNumber() + { + BigInteger candidate = JacobsthalNumber(latestIndex++); + while (!candidate.IsProbablyPrime(Certainty)) + { + candidate = JacobsthalNumber(latestIndex++); + } + + return (long)candidate; + } + + private static int ParityValue(int index) + { + return (index & 1) == 0 ? +1 : -1; + } +} + + +public static class BigIntegerExtensions +{ + private static Random random = new Random(); + + public static bool IsProbablyPrime(this BigInteger source, int certainty) + { + if (source == 2 || source == 3) + return true; + if (source < 2 || source % 2 == 0) + return false; + + BigInteger d = source - 1; + int s = 0; + + while (d % 2 == 0) + { + d /= 2; + s += 1; + } + + for (int i = 0; i < certainty; i++) + { + BigInteger a = RandomBigInteger(2, source - 2); + BigInteger x = BigInteger.ModPow(a, d, source); + if (x == 1 || x == source - 1) + continue; + + for (int r = 1; r < s; r++) + { + x = BigInteger.ModPow(x, 2, source); + if (x == 1) + return false; + if (x == source - 1) + break; + } + + if (x != source - 1) + return false; + } + + return true; + } + + private static BigInteger RandomBigInteger(BigInteger minValue, BigInteger maxValue) + { + if (minValue > maxValue) + throw new ArgumentException("minValue must be less than or equal to maxValue"); + + BigInteger range = maxValue - minValue + 1; + int length = range.ToByteArray().Length; + byte[] buffer = new byte[length]; + + BigInteger result; + do + { + random.NextBytes(buffer); + buffer[buffer.Length - 1] &= 0x7F; // Ensure non-negative + result = new BigInteger(buffer); + } while (result < minValue || result >= maxValue); + + return result; + } +} diff --git a/Task/Jacobsthal-numbers/PARI-GP/jacobsthal-numbers.parigp b/Task/Jacobsthal-numbers/PARI-GP/jacobsthal-numbers.parigp new file mode 100644 index 0000000000..18903e27de --- /dev/null +++ b/Task/Jacobsthal-numbers/PARI-GP/jacobsthal-numbers.parigp @@ -0,0 +1,30 @@ +\\ Define the Jacobsthal function +Jacobsthal(n) = (2^n - (-1)^n) / 3; + +\\ Define the JacobsthalLucas function +JacobsthalLucas(n) = 2^n + (-1)^n; + +\\ Define the JacobsthalOblong function +JacobsthalOblong(n) = Jacobsthal(n) * Jacobsthal(n + 1); + + +{ +\\ Generate and print Jacobsthal numbers for 0 through 29 +print(vector(30, n, Jacobsthal(n-1))); + +\\ Generate and print JacobsthalLucas numbers for 0 through 29 +print(vector(30, n, JacobsthalLucas(n-1))); + +\\ Generate and print JacobsthalOblong numbers for 0 through 19 +print(vector(20, n, JacobsthalOblong(n-1))); + +\\ Find the first 20 prime numbers in the Jacobsthal sequence +myprimes = []; +i = 0; +while(#myprimes < 40, + if(isprime(Jacobsthal(i)), myprimes = concat(myprimes, [i, Jacobsthal(i)])); + i++; +); + +for (i = 1, #myprimes\2, print(myprimes[2*i-1] " " myprimes[2*i]); ); +} diff --git a/Task/Jaro-Winkler-distance/00-TASK.txt b/Task/Jaro-Winkler-distance/00-TASK.txt index 5d1b63c0e2..c04991a0e9 100644 --- a/Task/Jaro-Winkler-distance/00-TASK.txt +++ b/Task/Jaro-Winkler-distance/00-TASK.txt @@ -1,5 +1,5 @@ The Jaro-Winkler distance is a metric for measuring the edit distance between words. -It is similar to the more basic Levenstein distance but the Jaro distance also accounts +It is similar to the more basic Levenshtein distance but the Jaro distance also accounts for transpositions between letters in the words. With the Winkler modification to the Jaro metric, the Jaro-Winkler distance also adds an increase in similarity for words which start with the same letters (prefix). diff --git a/Task/Jaro-similarity/C-sharp/jaro-similarity.cs b/Task/Jaro-similarity/C-sharp/jaro-similarity.cs new file mode 100644 index 0000000000..c93cc8693e --- /dev/null +++ b/Task/Jaro-similarity/C-sharp/jaro-similarity.cs @@ -0,0 +1,52 @@ +using System; + +public class JaroDistance { + public static double Jaro(string s, string t) { + int s_len = s.Length; + int t_len = t.Length; + + if (s_len == 0 && t_len == 0) return 1; + + int match_distance = Math.Max(s_len, t_len) / 2 - 1; + + bool[] s_matches = new bool[s_len]; + bool[] t_matches = new bool[t_len]; + + int matches = 0; + int transpositions = 0; + + for (int i = 0; i < s_len; i++) { + int start = Math.Max(0, i - match_distance); + int end = Math.Min(i + match_distance + 1, t_len); + + for (int j = start; j < end; j++) { + if (t_matches[j]) continue; + if (s[i] != t[j]) continue; + s_matches[i] = true; + t_matches[j] = true; + matches++; + break; + } + } + + if (matches == 0) return 0; + + int k = 0; + for (int i = 0; i < s_len; i++) { + if (!s_matches[i]) continue; + while (!t_matches[k]) k++; + if (s[i] != t[k]) transpositions++; + k++; + } + + return (((double)matches / s_len) + + ((double)matches / t_len) + + (((double)matches - transpositions / 2.0) / matches)) / 3.0; + } + + public static void Main(string[] args) { + Console.WriteLine(Jaro("MARTHA", "MARHTA")); + Console.WriteLine(Jaro("DIXON", "DICKSONX")); + Console.WriteLine(Jaro("JELLYFISH", "SMELLYFISH")); + } +} diff --git a/Task/Jewels-and-stones/K/jewels-and-stones.k b/Task/Jewels-and-stones/K/jewels-and-stones.k new file mode 100644 index 0000000000..48760f8c8f --- /dev/null +++ b/Task/Jewels-and-stones/K/jewels-and-stones.k @@ -0,0 +1,3 @@ +jewels: +/~^? + +jewels["aA";"aAAbbbb"] diff --git a/Task/Jewels-and-stones/REXX/jewels-and-stones.rexx b/Task/Jewels-and-stones/REXX/jewels-and-stones.rexx index ea64a3c016..938cd09f2d 100644 --- a/Task/Jewels-and-stones/REXX/jewels-and-stones.rexx +++ b/Task/Jewels-and-stones/REXX/jewels-and-stones.rexx @@ -1,12 +1,13 @@ /*REXX pgm counts how many letters (in the 1st string) are in common with the 2nd string*/ say count('aAAbbbb', "aA") say count('ZZ' , "z" ) -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -count: procedure; parse arg stones,jewels /*obtain the two strings specified. */ - #= 0 /*initialize the variable # to zero.*/ - do j=1 for length(stones) /*scan STONES for matching JEWELS chars*/ - x= substr(stones, j, 1) /*obtain a character of the STONES var.*/ - if datatype(x, 'M') then if pos(x, jewels)\==0 then #= # + 1 - end /*j*/ /* [↑] if a letter and a match, bump #*/ - return # /*return the number of common letters. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────*/ +count: procedure +parse arg stones,jewels /*obtain the two strings specified. */ +number= 0 /*initialize number to zero.*/ +do j=1 for length(stones) /*scan STONES for matching JEWELS chars*/ + x= substr(stones, j, 1) /*obtain a character of the STONES var.*/ + if datatype(x, 'M') then if pos(x, jewels)\==0 then number=number + 1 +end /*j*/ /* [↑] if a letter and a match, bump number */ +return number /*return the number of common letters. */ diff --git a/Task/Jewels-and-stones/Refal/jewels-and-stones.refal b/Task/Jewels-and-stones/Refal/jewels-and-stones.refal new file mode 100644 index 0000000000..ce70a21d05 --- /dev/null +++ b/Task/Jewels-and-stones/Refal/jewels-and-stones.refal @@ -0,0 +1,13 @@ +$ENTRY Go { + = > + >; +}; + +Jewels { + () (e.Jewels) + = 0; + (s.Stone e.Stones) (e.Jewels), e.Jewels: e.X s.Stone e.Y + = <+ 1 >; + (s.Stone e.Stones) (e.Jewels) + = ; +}; diff --git a/Task/Jordan-P-lya-numbers/C-sharp/jordan-p-lya-numbers.cs b/Task/Jordan-P-lya-numbers/C-sharp/jordan-p-lya-numbers.cs new file mode 100644 index 0000000000..4aadf27b1f --- /dev/null +++ b/Task/Jordan-P-lya-numbers/C-sharp/jordan-p-lya-numbers.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class JordanPolyaNumbers +{ + private static SortedSet jordanPolyaSet = new SortedSet(); + private static Dictionary> decompositions = new Dictionary>(); + + public static void Main(string[] args) + { + CreateJordanPolya(); + + long belowHundredMillion = jordanPolyaSet.LastOrDefault(x => x < 100_000_000L); + List jordanPolya = new List(jordanPolyaSet); + + Console.WriteLine("The first 50 Jordan-Polya numbers:"); + for (int i = 0; i < 50; i++) + { + Console.Write($"{jordanPolya[i],5}{(i % 10 == 9 ? "\n" : "")}"); + } + Console.WriteLine(); + + Console.WriteLine("The largest Jordan-Polya number less than 100 million: " + belowHundredMillion); + Console.WriteLine(); + + foreach (int i in new List { 800, 1050, 1800, 2800, 3800 }) + { + Console.WriteLine($"The {i}th Jordan-Polya number is: {jordanPolya[i - 1]} = {ToString(decompositions[jordanPolya[i - 1]])}"); + } + } + + private static void CreateJordanPolya() + { + jordanPolyaSet.Add(1L); + SortedSet nextSet = new SortedSet(); + decompositions[1L] = new SortedDictionary(); + long factorial = 1; + + for (int multiplier = 2; multiplier <= 20; multiplier++) + { + factorial *= multiplier; + foreach (long number in new SortedSet(jordanPolyaSet)) + { + long newNumber = number; + while (newNumber <= long.MaxValue / factorial) + { + long original = newNumber; + newNumber *= factorial; + nextSet.Add(newNumber); + + decompositions[newNumber] = new SortedDictionary(decompositions[original]); + if (decompositions[newNumber].ContainsKey(multiplier)) + { + decompositions[newNumber][multiplier]++; + } + else + { + decompositions[newNumber][multiplier] = 1; + } + } + } + jordanPolyaSet.UnionWith(nextSet); + nextSet.Clear(); + } + } + + private static string ToString(SortedDictionary map) + { + string result = ""; + foreach (int key in map.Keys) + { + result = key + "!" + (map[key] == 1 ? "" : "^" + map[key]) + " * " + result; + } + return result.TrimEnd(' ', '*'); + } +} diff --git a/Task/Jordan-P-lya-numbers/Dart/jordan-p-lya-numbers.dart b/Task/Jordan-P-lya-numbers/Dart/jordan-p-lya-numbers.dart new file mode 100644 index 0000000000..330ab3b48f --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Dart/jordan-p-lya-numbers.dart @@ -0,0 +1,66 @@ +import "dart:collection"; +import "dart:io"; + +void main() { + createJordanPolya(); + + final belowHundredMillion = jordanPolyaSet.lastWhere((element) => element <= 100000000, orElse: () => null); + List jordanPolya = jordanPolyaSet.toList(); + + print("The first 50 Jordan-Polya numbers:"); + for (int i = 0; i < 50; i++) { + // Right-align each number in a 5-character wide space + stdout.write(jordanPolya[i].toString().padLeft(5)); + if (i % 10 == 9) { + print(""); // Newline every 10 numbers + } + } + print(""); + + print("The largest Jordan-Polya number less than 100 million: ${belowHundredMillion ?? 'Not found'}"); + print(""); + + for (int i in [800, 1050, 1800, 2800, 3800]) { + var decomposition = decompositions[jordanPolya[i - 1]]; + if (decomposition != null) { + print("The ${i}th Jordan-Polya number is: ${jordanPolya[i - 1]} = ${mapToString(decomposition)}"); + } + } +} + +SplayTreeSet jordanPolyaSet = SplayTreeSet(); +Map> decompositions = {}; + +void createJordanPolya() { + jordanPolyaSet.add(1); + Set nextSet = SplayTreeSet(); + decompositions[1] = {}; + int factorial = 1; + + for (int multiplier = 2; multiplier <= 20; multiplier++) { + factorial *= multiplier; + for (int number in jordanPolyaSet) { + int tempNumber = number; + while (tempNumber <= 9223372036854775807 ~/ factorial) { + int original = tempNumber; + tempNumber *= factorial; + nextSet.add(tempNumber); + var originalDecomposition = decompositions[original]; + if (originalDecomposition != null) { + decompositions[tempNumber] = Map.from(originalDecomposition) + ..update(multiplier, (value) => value + 1, ifAbsent: () => 1); + } + } + } + jordanPolyaSet.addAll(nextSet); + nextSet.clear(); + } +} + +String mapToString(Map map) { + String result = ""; + map.forEach((key, value) { + result = "$key!${value == 1 ? '' : '^$value'} * $result"; + }); + return result.isEmpty ? result : result.substring(0, result.length - 3); +} diff --git a/Task/Jordan-P-lya-numbers/Kotlin/jordan-p-lya-numbers.kotlin b/Task/Jordan-P-lya-numbers/Kotlin/jordan-p-lya-numbers.kotlin new file mode 100644 index 0000000000..e361b3b195 --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Kotlin/jordan-p-lya-numbers.kotlin @@ -0,0 +1,61 @@ +import java.util.* + +object JordanPolyaNumbers { + private val jordanPolyaSet = TreeSet() + private val decompositions = HashMap>() + + @JvmStatic + fun main(aArgs: Array) { + createJordanPolya() + + val belowHundredMillion = jordanPolyaSet.floor(100_000_000L) + val jordanPolya = ArrayList(jordanPolyaSet) + + println("The first 50 Jordan-Polya numbers:") + for (i in 0 until 50) { + print(String.format("%5s%s", jordanPolya[i], if (i % 10 == 9) "\n" else "")) + } + println() + + println("The largest Jordan-Polya number less than 100 million: $belowHundredMillion") + println() + + for (i in listOf(800, 1050, 1800, 2800, 3800)) { + println("The $i th Jordan-Polya number is: ${jordanPolya[i - 1]} = ${toString(decompositions[jordanPolya[i - 1]]!!)}") + } + } + + private fun createJordanPolya() { + jordanPolyaSet.add(1L) + val nextSet = TreeSet() + decompositions[1L] = TreeMap() + var factorial = 1L + + for (multiplier in 2..20) { + factorial *= multiplier + val iterator = jordanPolyaSet.iterator() + while (iterator.hasNext()) { + var number = iterator.next() + while (number <= Long.MAX_VALUE / factorial) { + val original = number + number *= factorial + nextSet.add(number) + decompositions[number] = TreeMap(decompositions[original]!!) + decompositions[number]?.merge(multiplier, 1) { a, b -> a + b } + } + } + jordanPolyaSet.addAll(nextSet) + nextSet.clear() + } + } + + private fun toString(aMap: Map): String { + return aMap.entries.joinToString(separator = " * ") { (key, value) -> + "$key!${if (value == 1) "" else "^$value"}" + } + } +} + +fun main(args: Array) { + JordanPolyaNumbers.main(arrayOf()) +} diff --git a/Task/Jordan-P-lya-numbers/Python/jordan-p-lya-numbers.py b/Task/Jordan-P-lya-numbers/Python/jordan-p-lya-numbers.py new file mode 100644 index 0000000000..11744b6d55 --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Python/jordan-p-lya-numbers.py @@ -0,0 +1,56 @@ +from collections import defaultdict +from itertools import product + +class JordanPolyaNumbers: + def __init__(self): + self.jordan_polya_set = set() + self.decompositions = defaultdict(dict) + + def create_jordan_polya(self): + self.jordan_polya_set.add(1) + next_set = set() + self.decompositions[1] = {} + factorial = 1 + + for multiplier in range(2, 21): + factorial *= multiplier + for number in list(self.jordan_polya_set): + while number <= 2**63 - 1 // factorial: + original = number + number *= factorial + next_set.add(number) + self.decompositions[number] = self.decompositions[original].copy() + self.decompositions[number][multiplier] = self.decompositions[number].get(multiplier, 0) + 1 + + self.jordan_polya_set.update(next_set) + next_set.clear() + + def to_string(self, a_map): + result = "" + for key in sorted(a_map.keys(), reverse=True): + exponent = a_map[key] + result += f"{key}!" + ("" if exponent == 1 else f"^{exponent}") + " * " + return result[:-3] + + def display_results(self): + below_hundred_million = max(n for n in self.jordan_polya_set if n < 100_000_000) + jordan_polya = sorted(list(self.jordan_polya_set)) + + print("The first 50 Jordan-Polya numbers:") + for i in range(50): + end = "\n" if (i % 10 == 9) else "" + print(f"{jordan_polya[i]:5}", end=end) + print() + + print(f"The largest Jordan-Polya number less than 100 million: {below_hundred_million}") + print() + + for i in [800, 1050, 1800, 2800, 3800]: + print(f"The {i}th Jordan-Polya number is: {jordan_polya[i-1]}" + f" = {self.to_string(self.decompositions[jordan_polya[i-1]])}") + + +if __name__ == "__main__": + jpn = JordanPolyaNumbers() + jpn.create_jordan_polya() + jpn.display_results() diff --git a/Task/Jordan-P-lya-numbers/Rust/jordan-p-lya-numbers.rust b/Task/Jordan-P-lya-numbers/Rust/jordan-p-lya-numbers.rust new file mode 100644 index 0000000000..a69ccc42c2 --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Rust/jordan-p-lya-numbers.rust @@ -0,0 +1,83 @@ +use std::collections::{HashMap, HashSet}; + +const LIMIT: u64 = 1 << 53; + +fn to_string(map: &HashMap) -> String { + let mut result = String::new(); + for (&key, &value) in map { + // println!("key={} value={}", key, value); + let part = if value == 1 { + format!("{}!", key) + } else { + format!("{}!^{}", key, value) + }; + result = part + " * " + &result; + } + result.trim_end_matches(" * ").to_string() +} + +fn insert_or_update(map: &mut HashMap, entry: u64) { + let count = map.entry(entry).or_insert(0); + *count += 1; +} + +fn create_jordan_polya() -> (HashSet, HashMap>) { + let mut jordan_polya_set = HashSet::new(); + let mut decompositions = HashMap::new(); + + jordan_polya_set.insert(1); + decompositions.insert(1, HashMap::new()); + let mut factorial = 1u64; + + for multiplier in 2..=20 { + factorial *= multiplier; // Using u64 for multiplier + let mut to_update = Vec::new(); + + for &number in &jordan_polya_set { + let mut current = number; + while current <= LIMIT / factorial { + to_update.push((current, current * factorial)); // Store original and new number + current *= factorial; + } + } + + for (original, new_number) in to_update { + jordan_polya_set.insert(new_number); + let mut new_decomposition = decompositions[&original].clone(); + insert_or_update(&mut new_decomposition, multiplier); + decompositions.insert(new_number, new_decomposition); + } + } + + (jordan_polya_set, decompositions) +} + + +fn main() { + let (jordan_polya_set, decompositions) = create_jordan_polya(); + let mut jordan_polya: Vec<_> = jordan_polya_set.into_iter().collect(); + jordan_polya.sort(); + + println!("The first 50 Jordan-Polya numbers:"); + for i in 0..50 { + print!("{:5}", jordan_polya[i]); + if i % 10 == 9 { + println!(); + } + } + + let hundred_million = jordan_polya.iter().position(|&x| x >= 100_000_000).unwrap(); + println!( + "\nThe largest Jordan-Polya number less than 100 million: {}\n", + jordan_polya[hundred_million - 1] + ); + + for &i in &[800, 1050, 1800, 2800, 3800] { + println!( + "The {}th Jordan-Polya number is: {} = {}", + i, + jordan_polya[i - 1], + to_string(&decompositions[&jordan_polya[i - 1]]) + ); + } +} diff --git a/Task/Jordan-P-lya-numbers/Scala/jordan-p-lya-numbers.scala b/Task/Jordan-P-lya-numbers/Scala/jordan-p-lya-numbers.scala new file mode 100644 index 0000000000..22478be416 --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Scala/jordan-p-lya-numbers.scala @@ -0,0 +1,59 @@ +import java.util.{ArrayList, HashMap, TreeMap, TreeSet} +import scala.jdk.CollectionConverters._ + +object JordanPolyaNumbers { + + private val jordanPolyaSet = new TreeSet[Long]() + private val decompositions = new HashMap[Long, TreeMap[Integer, Integer]]() + + def main(args: Array[String]): Unit = { + createJordanPolya() + + val belowHundredMillion = jordanPolyaSet.floor(100_000_000L) + val jordanPolya = new ArrayList[Long](jordanPolyaSet) + + println("The first 50 Jordan-Polya numbers:") + jordanPolya.asScala.take(50).zipWithIndex.foreach { case (number, index) => + print(f"$number%5s${if(index % 10 == 9) "\n" else ""}") + } + println() + + println(s"The largest Jordan-Polya number less than 100 million: $belowHundredMillion") + println() + + List(800, 1050, 1800, 2800, 3800).foreach { i => + println(s"The ${i}th Jordan-Polya number is: ${jordanPolya.get(i - 1)} = ${toString(decompositions.get(jordanPolya.get(i - 1)))}") + } + } + + private def createJordanPolya(): Unit = { + jordanPolyaSet.add(1L) + val nextSet = new TreeSet[Long]() + decompositions.put(1L, new TreeMap[Integer, Integer]()) + var factorial = 1L + + for (multiplier <- 2 to 20) { + factorial *= multiplier + val it = jordanPolyaSet.iterator() + while (it.hasNext) { + var number = it.next() + while (number <= Long.MaxValue / factorial) { + val original = number + number *= factorial + nextSet.add(number) + decompositions.put(number, new TreeMap[Integer, Integer](decompositions.get(original))) + val currentMap = decompositions.get(number) + currentMap.merge(multiplier, 1, (a: Integer, b: Integer) => Integer.sum(a, b)) + } + } + jordanPolyaSet.addAll(nextSet) + nextSet.clear() + } + } + + private def toString(aMap: TreeMap[Integer, Integer]): String = { + aMap.descendingMap().asScala.map { case (key, value) => + s"$key!${if (value == 1) "" else "^" + value}" + }.mkString(" * ") + } +} diff --git a/Task/Jordan-P-lya-numbers/Swift/jordan-p-lya-numbers.swift b/Task/Jordan-P-lya-numbers/Swift/jordan-p-lya-numbers.swift new file mode 100644 index 0000000000..fd45705bd4 --- /dev/null +++ b/Task/Jordan-P-lya-numbers/Swift/jordan-p-lya-numbers.swift @@ -0,0 +1,61 @@ +import Foundation + +class JordanPolyaNumbers { + + static var jordanPolyaSet = Set() + static var decompositions = [Int64: [Int: Int]]() + + static func main() { + createJordanPolya() + + let belowHundredMillion = jordanPolyaSet.filter { $0 <= 100_000_000 }.max() ?? 0 + let jordanPolya = Array(jordanPolyaSet).sorted() + + print("The first 50 Jordan-Polya numbers:") + for i in 0..<50 { + if i % 10 == 9 { + print("\(jordanPolya[i])\n", terminator: "") + } else { + print(String(format: "%5d ", jordanPolya[i]), terminator: "") + } + } + print("\nThe largest Jordan-Polya number less than 100 million: \(belowHundredMillion)\n") + + for i in [800, 1050, 1800, 2800, 3800] { + print("The \(i)th Jordan-Polya number is: \(jordanPolya[i - 1]) = \(toString(decompositions[jordanPolya[i - 1]] ?? [:]))") + } + } + + static func createJordanPolya() { + jordanPolyaSet.insert(1) + var nextSet = Set() + decompositions[1] = [:] + var factorial: Int64 = 1 + + for multiplier in 2...20 { + factorial *= Int64(multiplier) + for number in jordanPolyaSet { + var current = number + while current <= Int64.max / factorial { + let original = current + current *= factorial + nextSet.insert(current) + decompositions[current] = decompositions[original]?.merging([multiplier: 1], uniquingKeysWith: +) ?? [:] + } + } + jordanPolyaSet.formUnion(nextSet) + nextSet.removeAll() + } + } + + static func toString(_ aMap: [Int: Int]) -> String { + var result = "" + for key in aMap.keys.sorted().reversed() { + let value = aMap[key] ?? 0 + result += "\(key)!" + (value == 1 ? "" : "^\(value)") + " * " + } + return String(result.dropLast(3)) + } +} + +JordanPolyaNumbers.main() diff --git a/Task/Juggler-sequence/C-sharp/juggler-sequence.cs b/Task/Juggler-sequence/C-sharp/juggler-sequence.cs new file mode 100644 index 0000000000..f16c653d9d --- /dev/null +++ b/Task/Juggler-sequence/C-sharp/juggler-sequence.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Numerics; + +public class JugglerSequence +{ + public static void Main(string[] args) + { + Console.WriteLine(" n l[n] i[n] h[n]"); + Console.WriteLine("---------------------------------"); + for (int number = 20; number <= 39; number++) + { + JugglerData result = Juggler(number); + Console.WriteLine($"{number,2}{result.Count,7}{result.MaxCount,6}{result.MaxNumber,17}"); + } + Console.WriteLine(); + + List values = new List { 113, 173, 193, 2183, 11229, 15065, 15845, 30817 }; + Console.WriteLine(" n l[n] i[n] d[n]"); + Console.WriteLine("----------------------------"); + foreach (int value in values) + { + JugglerData result = Juggler(value); + Console.WriteLine($"{value,5}{result.Count,8}{result.MaxCount,7}{result.DigitCount,7}"); + } + } + + private static JugglerData Juggler(int number) + { + if (number < 1) + { + throw new ArgumentException("Starting value must be >= 1: " + number); + } + BigInteger bigNumber = new BigInteger(number); + int count = 0; + int maxCount = 0; + BigInteger maxNumber = bigNumber; + while (!bigNumber.Equals(BigInteger.One)) +{ + if (bigNumber.IsEven) + { + bigNumber = bigNumber.Sqrt(); + } + else + { + BigInteger cubed = BigInteger.Pow(bigNumber, 3); + bigNumber = cubed.Sqrt(); // Approximating the cube root by taking the square root of the cubed value. + } + count++; + if (bigNumber.CompareTo(maxNumber) > 0) + { + maxNumber = bigNumber; + maxCount = count; + } +} + + return new JugglerData(count, maxCount, maxNumber, maxNumber.ToString().Length); + } + + private class JugglerData + { + public int Count { get; } + public int MaxCount { get; } + public BigInteger MaxNumber { get; } + public int DigitCount { get; } + + public JugglerData(int count, int maxCount, BigInteger maxNumber, int digitCount) + { + Count = count; + MaxCount = maxCount; + MaxNumber = maxNumber; + DigitCount = digitCount; + } + } +} + +public static class BigIntegerExtensions +{ + public static BigInteger Sqrt(this BigInteger n) + { + if (n == 0) return 0; + if (n > 0) + { + int bitLength = Convert.ToInt32(Math.Ceiling(BigInteger.Log(n, 2))); + BigInteger root = BigInteger.One << (bitLength / 2); + + while (!IsSqrt(n, root)) + { + root += n / root; + root /= 2; + } + + return root; + } + throw new ArithmeticException("NaN"); + } + + private static bool IsSqrt(BigInteger n, BigInteger root) + { + BigInteger lowerBound = root * root; + BigInteger upperBound = (root + 1) * (root + 1); + return n >= lowerBound && n < upperBound; + } +} diff --git a/Task/Kaprekar-numbers/EasyLang/kaprekar-numbers.easy b/Task/Kaprekar-numbers/EasyLang/kaprekar-numbers.easy new file mode 100644 index 0000000000..fd28cb57c5 --- /dev/null +++ b/Task/Kaprekar-numbers/EasyLang/kaprekar-numbers.easy @@ -0,0 +1,17 @@ +func karp n . + h = n * n + e = 1 + while h > 0 + t += h mod 10 * e + e = e * 10 + h = h div 10 + if t > 0 and h + t = n + return 1 + . + . +. +for i to 9999 + if karp i = 1 + write i & " " + . +. diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/Forth/keyboard-input-flush-the-keyboard-buffer.fth b/Task/Keyboard-input-Flush-the-keyboard-buffer/Forth/keyboard-input-flush-the-keyboard-buffer.fth new file mode 100644 index 0000000000..784431937d --- /dev/null +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/Forth/keyboard-input-flush-the-keyboard-buffer.fth @@ -0,0 +1 @@ +: flush-keys begin key? while key drop repeat ; diff --git a/Task/Knapsack-problem-0-1/Fortran/knapsack-problem-0-1-1.f b/Task/Knapsack-problem-0-1/Fortran/knapsack-problem-0-1-1.f new file mode 100644 index 0000000000..9f6ca7b7be --- /dev/null +++ b/Task/Knapsack-problem-0-1/Fortran/knapsack-problem-0-1-1.f @@ -0,0 +1,65 @@ +Program Knapsack01 +! Translation of Pascal version on Rosetta Code. + implicit none + integer, parameter :: NUM_ITEMS = 22 + integer, parameter :: MAX_WEIGHT = 400 + type :: TItem + character(len=20) :: Name + integer :: Weight, Value + end type TItem + type(TItem), dimension(0:NUM_ITEMS-1) :: ITEMS + integer, dimension(0:NUM_ITEMS, 0:MAX_WEIGHT) :: D + integer :: I, W, V, MaxWeight + ! Init Arrays + d = 0 + ITEMS = [ TItem('compass', 13, 35), & + TItem('water', 153, 200), & + TItem('sandwich', 50, 160), & + TItem('glucose', 15, 60), & + TItem('tin', 68, 45), & + TItem('banana', 27, 60), & + TItem('apple', 39, 40), & + TItem('cheese', 23, 30), & + TItem('beer', 52, 10), & + TItem('suntan cream', 11, 70), & + TItem('camera', 32, 30), & + TItem('T-shirt', 24, 15), & + TItem('trousers', 48, 10), & + TItem('umbrella', 73, 40), & + TItem('waterproof trousers', 43, 70), & + TItem('waterproof overclothes', 42, 75), & + TItem('note-case', 22, 80), & + TItem('sunglasses', 7, 20), & + TItem('towel', 18, 12), & + TItem('map', 9, 150), & + TItem('socks', 4, 50), & + TItem('book', 30, 10) ] + ! + do I = 0, NUM_ITEMS-1 + do W = 0, MAX_WEIGHT + if (ITEMS(I)%Weight > W) then + D(I+1, W) = D(I, W) + else + D(I+1, W) = max(D(I, W), D(I, W - ITEMS(I)%Weight) + ITEMS(I)%Value) + end if + end do + end do + W = MAX_WEIGHT + V = D(NUM_ITEMS, W) + MaxWeight = 0 + ! + write(*, "(/,'bagged:')") + do I = NUM_ITEMS-1, 0, -1 !Pete + if (D(I+1, W) == V) then + if((D(I, (W - ITEMS(I)%Weight)) == V - ITEMS(I)%Value)) then + write(*, "(' ', A,t25,i0,t35,i0)", advance='yes') ITEMS(I)%Name,ITEMS(I)%weight,ITEMS(I)%value + MaxWeight = MaxWeight + ITEMS(I)%Weight + W = W - ITEMS(I)%Weight + V = V - ITEMS(I)%Value + end if + end if + end do + ! + write(*, "('value = ', I0)") D(NUM_ITEMS, MAX_WEIGHT) + write(*, "('weight = ', I0)") MaxWeight +end program Knapsack01 diff --git a/Task/Knapsack-problem-0-1/Fortran/knapsack-problem-0-1-2.f b/Task/Knapsack-problem-0-1/Fortran/knapsack-problem-0-1-2.f new file mode 100644 index 0000000000..13188deb21 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Fortran/knapsack-problem-0-1-2.f @@ -0,0 +1,507 @@ + module ksack2 +! +! THIS SUBROUTINE SOLVES THE 0-1 SINGLE KNAPSACK PROBLEM +! +! MAXIMIZE Z = P(1)*X(1) + ... + P(N)*X(N) +! +! SUBJECT TO: W(1)*X(1) + ... + W(N)*X(N) .LE. C , +! X(J) = 0 OR 1 FOR J=1,...,N. +! +! THE PROGRAM IS INCLUDED IN THE VOLUME +! S. MARTELLO, P. TOTH, "KNAPSACK PROBLEMS: ALGORITHMS +! AND COMPUTER IMPLEMENTATIONS", JOHN WILEY, 1990 +! (https://dl.acm.org/doi/book/10.5555/98124) +! AND IMPLEMENTS THE BRANCH-AND-BOUND ALGORITHM DESCRIBED IN +! SECTION 2.5.2 . +! THE PROGRAM DERIVES FROM AN EARLIER CODE PRESENTED IN +! S. MARTELLO, P. TOTH, "ALGORITHM FOR THE SOLUTION OF THE 0-1 SINGLE +! KNAPSACK PROBLEM", COMPUTING, 1978. + +! The orignal program was written in Fortran 77 and was an amazing tangle of GOTO statements. +! I have reworked the code in such a manner as to eliminate the GOTO statements and bring it +! to Fortran 2018 LANGUAGE compliance though the code logic remains somewhat untractable. +! +! The routine requires a large parameter string which includes 4 dummy arrays for it's calculations. +! As well, it offers an option to check the input data for correctness. +! Rather than modify the original algorithm, I wrote a simple wrapper called "start_knapsack" that +! allocates those arrays as well as defaulting the input parameter check to "on", hiding them from the user. +! Having said that, the algorithm works very well and is very fast. I've included it in this +! Rosetta Code listing because it scales well and can be used with a large dataset. +! Which a potential user may desire. +! Peter.kelly@acm.org (28-December-2023) +! +! THE INPUT PROBLEM MUST SATISFY THE CONDITIONS +! +! 1) 2 .LE. N .LE. JDIM - 1 ; +! 2) P(J), W(J), C POSITIVE INTEGERS; +! 3) MAX (W(J)) .LE. C ; +! 4) W(1) + ... + W(N) .GT. C ; +! 5) P(J)/W(J) .GE. P(J+1)/W(J+1) FOR J=1,...,N-1. <-- Note well. They need to be sorted in the greatest ratio of (p(j)/w(j)) down to the smallest one +! +! MT1 CALLS 1 PROCEDURE: CHMT1. +! +! MT1 NEEDS 8 ARRAYS ( P , W , X , XX , MIN , PSIGN , WSIGN +! AND ZSIGN ) OF LENGTH AT LEAST N + 1 . +! +! MEANING OF THE INPUT PARAMETERS: +! N = NUMBER OF ITEMS; +! P(J) = PROFIT OF ITEM J (J=1,...,N); +! W(J) = WEIGHT OF ITEM J (J=1,...,N); +! C = CAPACITY OF THE KNAPSACK; +! JDIM = DIMENSION OF THE 8 ARRAYS; +! JCK = 1 IF CHECK ON THE INPUT DATA IS DESIRED, +! = 0 OTHERWISE. +! +! MEANING OF THE OUTPUT PARAMETERS: +! Z = VALUE OF THE OPTIMAL SOLUTION IF Z .GT. 0 , +! = ERROR IN THE INPUT DATA (WHEN JCK=1) IF Z .LT. 0 : CONDI- +! TION - Z IS VIOLATED; +! X(J) = 1 IF ITEM J IS IN THE OPTIMAL SOLUTION, +! = 0 OTHERWISE. +! +! ARRAYS XX, MIN, PSIGN, WSIGN AND ZSIGN ARE DUMMY. +! +! ALL THE PARAMETERS ARE INTEGER. ON RETURN OF MT1 ALL THE INPUT +! PARAMETERS ARE UNCHANGED. +! + implicit none + contains + subroutine mt1(n , p , w , c , z , x , jdim , jck , xx , min , psign , wsign , zsign) + implicit none + integer :: jdim + integer :: n + integer , intent(inout) , dimension(jdim) :: p + integer , intent(inout) , dimension(jdim) :: w + integer :: c + integer , intent(inout) :: z + integer , intent(out) , dimension(jdim) :: x + integer , intent(in) :: jck + integer , intent(inout) , dimension(jdim) :: xx + integer , intent(inout) , dimension(jdim) :: min + integer , intent(inout) , dimension(jdim) :: psign + integer , intent(inout) , dimension(jdim) :: wsign + integer , intent(inout) , dimension(jdim) :: zsign +! + real :: a + real :: b + integer :: ch + integer :: chs + integer :: diff + integer :: ii + integer :: ii1 + integer :: in + integer :: ip + integer :: iu + integer :: j + integer :: j1 + integer :: jj + integer :: jtemp + integer :: kk + integer :: lim + integer :: lim1 + integer :: ll + integer :: lold + integer :: mink + integer :: n1 + integer :: nn + integer :: profit + integer :: r + integer :: t + integer :: next_code_block +!*Code + next_code_block = 1 +dispatch_loop: do + select case(next_code_block) + case(1) + z = 0 + if( jck==1 )call chmt1(n , p , w , c , z , jdim) + if( z<0 )return +! INITIALIZE. + ch = c + ip = 0 + chs = ch + first_loop: do ll = 1 , n + if( w(ll)>chs )exit first_loop + ip = ip + p(ll) + chs = chs - w(ll) + end do first_loop + ll = ll - 1 + if( chs==0 )then + z = ip + x(1:ll) = 1 + nn = ll + 1 + x(nn:n) = 0 + return + else + p(n + 1) = 0 + w(n + 1) = ch + 1 + lim = ip + chs*p(ll + 2)/w(ll + 2) + a = w(ll + 1) - chs + b = ip + p(ll + 1) + lim1 = b - a*float(p(ll))/float(w(ll)) + if( lim1>lim )lim = lim1 + mink = ch + 1 + min(n) = mink + do j = 2 , n + kk = n + 2 - j + if( w(kk)ch ) + ii1 = ii + 1 + if( z>=ch*p(ii1)/w(ii1) + profit )then + next_code_block = 5 + cycle dispatch_loop + end if + ii = ii1 + end do +! BUILD A NEW CURRENT SOLUTION. + ip = psign(ii) + chs = ch - wsign(ii) + in = zsign(ii) + ll = in + do while ( ll<=n ) + if( w(ll)>chs )then + iu = chs*p(ll)/w(ll) + ll = ll - 1 + if( iu==0 )then + next_code_block = 3 + cycle dispatch_loop + end if + if( z>=profit + ip + iu )then + next_code_block = 5 + cycle dispatch_loop + end if + next_code_block = 4 + cycle dispatch_loop + else + ip = ip + p(ll) + chs = chs - w(ll) + end if + end do + ll = n + next_code_block = 3 + case(3) + if( z>=ip + profit )then + next_code_block = 5 + cycle dispatch_loop + end if + z = ip + profit + nn = ii - 1 + x(1:nn) = xx(1:nn) + x(ii:ll) = 1 + if( ll/=n )then + nn = ll + 1 + x(nn:n) = 0 + end if + if( z/=lim )then + next_code_block = 5 + cycle dispatch_loop + end if + return + case(4) +! SAVE THE CURRENT SOLUTION. + wsign(ii) = ch - chs + psign(ii) = ip + zsign(ii) = ll + 1 + xx(ii) = 1 + nn = ll - 1 + if( nn>=ii )then + do j = ii , nn + wsign(j + 1) = wsign(j) - w(j) + psign(j + 1) = psign(j) - p(j) + zsign(j + 1) = ll + 1 + xx(j + 1) = 1 + end do + end if + j1 = ll + 1 + wsign(j1:lold) = 0 + psign(j) = 0 + zsign(j1:lold) = [(jtemp, jtemp = j1,lold)] + lold = ll + ch = chs + profit = profit + ip + if( ll<(n - 2) )then + ii = ll + 2 + if( ch>=min(ii - 1) )then + next_code_block = 2 + cycle dispatch_loop + end if + else if( ll==(n - 2) )then + if( ch>=w(n) )then + ch = ch - w(n) + profit = profit + p(n) + xx(n) = 1 + end if + ii = n - 1 + else + ii = n + end if +! SAVE THE CURRENT OPTIMAL SOLUTION. + if( z=min(nn) )then + if( z>=profit + p(nn) + t*p(nn + 1)/w(nn + 1) )exit inner_loop + ch = ch - w(nn) + profit = profit + p(nn) + xx(nn) = 1 + ii = nn + 1 + wsign(nn) = w(nn) + psign(nn) = p(nn) + zsign(nn) = ii + n1 = nn + 1 + wsign(n1:lold) = 0 + psign(n1:lold) = 0 + zsign(n1:lold) = [(jtemp, jtemp = n1,lold)] + lold = nn + next_code_block = 2 + cycle dispatch_loop + end if + else if( diff/=0 )then + if( diff<=r )then + if( zjdim - 1) )then + z = -1 + return + else if( c>0 )then + jsw = 0 + rr = float(p(1))/float(w(1)) + do j = 1 , n + r = rr + if(( p(j)<=0 ).or.( w(j)<=0 ))then + z = -2 + return + end if + jsw = jsw + w(j) + if( w(j)<=c )then + rr = float(p(j))/float(w(j)) + if( rr>r )then + z = -5 + return + end if + else + z = -3 + return + end if + end do + if( jsw>c )return + z = -4 + return + end if + z = -2 + return + end subroutine chmt1 + + subroutine start_knapsack(n , profit , weight , capacity , result_val , members) +! +! Dummy argument declarations +! + integer , intent(in) :: n + integer , intent(inout) , dimension(n) :: profit + integer , intent(inout) , dimension(n) :: weight + integer , intent(in) :: capacity + integer , intent(inout) :: result_val + integer , intent(inout) , dimension(n) :: members +! +! Local variable declarations + integer :: bigger + integer :: jck + integer , allocatable , dimension(:) :: mini + integer , allocatable , dimension(:) :: psign + integer , allocatable , dimension(:) :: wsign + integer , allocatable , dimension(:) :: xx + integer , allocatable , dimension(:) :: zsign +! +!Designed to invoke MT1 +!MT1 NEEDS 8 ARRAYS ( P , W , X , XX , MIN , PSIGN , WSIGN +! AND ZSIGN ) OF LENGTH AT LEAST N + 1 . + +! MEANING OF THE INPUT PARAMETERS: +! N = NUMBER OF ITEMS; +! P(J) = PROFIT OF ITEM J (J=1,...,N); +! W(J) = WEIGHT OF ITEM J (J=1,...,N); +! C = CAPACITY OF THE KNAPSACK; +! JDIM = DIMENSION OF THE 8 ARRAYS; +! JCK = 1 IF CHECK ON THE INPUT DATA IS DESIRED, +! = 0 OTHERWISE. +! +! MEANING OF THE OUTPUT PARAMETERS: +! Z = VALUE OF THE OPTIMAL SOLUTION IF Z .GT. 0 , +! = ERROR IN THE INPUT DATA (WHEN JCK=1) IF Z .LT. 0 : CONDI- +! TION - Z IS VIOLATED; +! X(J) = 1 IF ITEM J IS IN THE OPTIMAL SOLUTION, +! = 0 OTHERWISE. +! +! ARRAYS XX, MIN, PSIGN, WSIGN AND ZSIGN ARE DUMMY. +! +! ALL THE PARAMETERS ARE INTEGER. ON RETURN OF MT1 ALL THE INPUT +! PARAMETERS ARE UNCHANGED. +! + jck = 1 !Set parameter checking on + bigger = n + 100 +! +! Allocate the dummy arrays + allocate(xx(bigger)) + allocate(mini(bigger)) + allocate(psign(bigger)) + allocate(wsign(bigger)) + allocate(zsign(bigger)) + call mt1(n , profit , weight , capacity , result_val , members , bigger , jck , xx , mini , psign , wsign , zsign) + deallocate(xx) + deallocate(mini) + deallocate(psign) + deallocate(wsign) + deallocate(zsign) + + end subroutine start_knapsack + end module ksack2 +! +program serious_knapsack + use ksack2 + integer, parameter :: list_size=22 + integer:: p(list_size) ! The weights + integer::n,profit(list_size),capacity,result_val,members(size(p)),valuez,t1,t2,j + character(len=25) :: names(list_size),tempnam + real :: ratio(list_size),rats + logical :: swapped + capacity =400 + members = 0 + result_val = 0 + n = list_size + p(1:list_size) = (/13,153, 50,15,68,27,39,23,52,11,32,24,48,73,43,42,22,07,18,009,04,30/) + profit(1:list_size) =(/35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,150,50,10/) + + names(1:22) =[character(len=25) ::'compass','water','sandwich','glucose','tin','banana','apple', 'cheese', & + 'beer','suntan cream','camera','T-shirt','trousers','umbrella','waterproof trousers', 'waterproof overclothes', & + 'note-case','sunglasses','towel','map','socks', 'book'] + ratio(1:22) = float(profit(1:22))/float(p(1:22)) + ! The mt1 algorithm wants the data sorted downwards(large-->small) by the ration of profit/weight + ! So, I implemented a quick bubble sort to order the lists + swapped = .true. + do while (swapped) + swapped = .false. + do j = 1,21 + if(ratio(j).lt.ratio(j+1))then ! Swaps everywhere + swapped = .true. + t1 = p(j+1) ! Swap the weights + p(j+1) = p(j) + p(j) = t1 + t2 = profit(j+1) !Swap the profits + profit(j+1) = profit(j) + profit(j) = t2 + tempnam = names(j+1) ! Swap the names around + names(j+1) = names(j) + names(j) = tempnam + rats = ratio(j+1) ! Swap the ratios + ratio(j+1) = ratio(j) + ratio(j) = rats + endif + end do + end do + ! + call system_clock(count=xx) + call startup(n,profit(1:22),p(1:22),capacity,result_val,members) + call system_clock(count=yy) + print*,'Total of the sack = ',result_val + capacity = 0 + valuez = 0 + n = 0 + do i = 1,size(members) + if(members(i) /=0)then + capacity = capacity +p(i) + valuez = profit(i) + valuez + n = n+1 + print*, names(i),p(i),profit(i) + endif + + end do + print*,'Filled capacity = ',capacity,'Value = ',valuez!,'No items = ',n,sum(profit(1:22)),sum(p(1:22)) + print* + print*,'First knapsack time = ',(yy-xx),'Milliseconds' + stop 'All done' +end program serious_knapsack diff --git a/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy b/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy index ea070c7fe5..8870151216 100644 --- a/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy +++ b/Task/Knuth-shuffle/EasyLang/knuth-shuffle.easy @@ -1,6 +1,6 @@ proc shuffle . a[] . for i = len a[] downto 2 - r = random i + r = randint i swap a[r] a[i] . . diff --git a/Task/Knuth-shuffle/Elena/knuth-shuffle.elena b/Task/Knuth-shuffle/Elena/knuth-shuffle.elena index 7ab6fcba87..3a9c16b54a 100644 --- a/Task/Knuth-shuffle/Elena/knuth-shuffle.elena +++ b/Task/Knuth-shuffle/Elena/knuth-shuffle.elena @@ -9,7 +9,7 @@ extension randomOp { var max := self.Length; - for(int i := 0, i < max, i += 1) + for(int i := 0; i < max; i += 1) { var j := randomGenerator.nextInt(i,max); @@ -22,7 +22,7 @@ extension randomOp public program() { - var a := Array.allocate:MAX.populate:(i => i ); + var a := Array.allocate(MAX).populate::(i => i ); console.printLine(a.randomize()) } diff --git a/Task/Knuths-algorithm-S/Elena/knuths-algorithm-s.elena b/Task/Knuths-algorithm-S/Elena/knuths-algorithm-s.elena index f2da8ba5ef..b5a8254c97 100644 --- a/Task/Knuths-algorithm-S/Elena/knuths-algorithm-s.elena +++ b/Task/Knuths-algorithm-S/Elena/knuths-algorithm-s.elena @@ -14,16 +14,16 @@ extension algorithmOp { eval(i) { - counter.append:1; + counter.append(1); if (weak self.Length < n) { - weak self.append:i + weak self.append(i) } else { - if(randomGenerator.nextInt:counter < n) - { weak self[randomGenerator.nextInt:n] := i } + if(randomGenerator.nextInt(counter) < n) + { weak self[randomGenerator.nextInt(n)] := i } }; ^ weak self.Value @@ -34,19 +34,19 @@ extension algorithmOp public program() { - var bin := Array.allocate(10).populate:(n => new Integer()); - for(int trial := 0, trial < 10000, trial += 1) + var bin := Array.allocate(10).populate::(n => new Integer()); + for(int trial := 0; trial < 10000; trial += 1) { var s_of_n := 3.s_of_n(); - for(int n := 0, n < 10, n += 1) + for(int n := 0; n < 10; n += 1) { - var sample := s_of_n.eval:n; + var sample := s_of_n.eval(n); if (n == 9) - { sample.forEach:(i){ bin[i].append:1 } } + { sample.forEach::(i){ bin[i].append(1) } } } }; - console.printLine:bin.readChar() + console.printLine(bin).readChar() } diff --git a/Task/LU-decomposition/Wren/lu-decomposition.wren b/Task/LU-decomposition/Wren/lu-decomposition.wren index a0e9ff87ca..a96113a990 100644 --- a/Task/LU-decomposition/Wren/lu-decomposition.wren +++ b/Task/LU-decomposition/Wren/lu-decomposition.wren @@ -1,5 +1,5 @@ -import "/matrix" for Matrix -import "/fmt" for Fmt +import "./matrix" for Matrix +import "./fmt" for Fmt var arrays = [ [ [1, 3, 5], diff --git a/Task/Latin-Squares-in-reduced-form/Wren/latin-squares-in-reduced-form.wren b/Task/Latin-Squares-in-reduced-form/Wren/latin-squares-in-reduced-form.wren index e945091a95..930e1213d7 100644 --- a/Task/Latin-Squares-in-reduced-form/Wren/latin-squares-in-reduced-form.wren +++ b/Task/Latin-Squares-in-reduced-form/Wren/latin-squares-in-reduced-form.wren @@ -1,6 +1,6 @@ -import "/sort" for Sort -import "/math" for Int -import "/fmt" for Fmt +import "./sort" for Sort +import "./math" for Int +import "./fmt" for Fmt // generate derangements of first n numbers, with 'start' in first place. var dList = Fn.new { |n, start| diff --git a/Task/Leap-year/Koka/leap-year-1.koka b/Task/Leap-year/Koka/leap-year-1.koka new file mode 100644 index 0000000000..d2661c5cf0 --- /dev/null +++ b/Task/Leap-year/Koka/leap-year-1.koka @@ -0,0 +1,2 @@ + pub fun is-leap-year(year: int) + year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) diff --git a/Task/Leap-year/Koka/leap-year-2.koka b/Task/Leap-year/Koka/leap-year-2.koka new file mode 100644 index 0000000000..78132993f9 --- /dev/null +++ b/Task/Leap-year/Koka/leap-year-2.koka @@ -0,0 +1,2 @@ + pub fun is-leap-year'(year: int) + year % (if year % 100 == 0 then 400 else 4) == 0 diff --git a/Task/Leap-year/Koka/leap-year-3.koka b/Task/Leap-year/Koka/leap-year-3.koka new file mode 100644 index 0000000000..130a5dc829 --- /dev/null +++ b/Task/Leap-year/Koka/leap-year-3.koka @@ -0,0 +1,6 @@ + import std/time + import std/time/date + import std/time/time + + pub fun is-leap-year''(year: int) + Date(year, 2, 28).time.add-days(1).day == 29 diff --git a/Task/Leap-year/UNIX-Shell/leap-year-4.sh b/Task/Leap-year/UNIX-Shell/leap-year-4.sh index a11c9bf86b..ad717956c3 100644 --- a/Task/Leap-year/UNIX-Shell/leap-year-4.sh +++ b/Task/Leap-year/UNIX-Shell/leap-year-4.sh @@ -1,5 +1 @@ -is_leap() { - local year=$(( 10#${1:?'Missing year'} )) - (( year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ) )) && return 0 - return 1 -} +is_leap() (( year=${1-0}, year % 4 == 0 && ( year % 100 != 0 || year % 400 == 0 ))) diff --git a/Task/Leap-year/YAMLScript/leap-year.ys b/Task/Leap-year/YAMLScript/leap-year.ys new file mode 100644 index 0000000000..fec87e9556 --- /dev/null +++ b/Task/Leap-year/YAMLScript/leap-year.ys @@ -0,0 +1,16 @@ +!yamlscript/v0 + +defn main(year): + say: "$year is $when-not(leap-year(year) 'not ')a leap year." + +# Either one works: + +defn leap-year(year): + ((year % 4) == 0) && (((year % 100) > 0) || ((year % 100) == 0)) + +defn leap-year(year): + and: + zero?: (year % 4) + or: + pos?: (year % 100) + zero?: (year % 400) diff --git a/Task/Leap-year/Zig/leap-year.zig b/Task/Leap-year/Zig/leap-year-1.zig similarity index 100% rename from Task/Leap-year/Zig/leap-year.zig rename to Task/Leap-year/Zig/leap-year-1.zig diff --git a/Task/Leap-year/Zig/leap-year-2.zig b/Task/Leap-year/Zig/leap-year-2.zig new file mode 100644 index 0000000000..bb1c805c50 --- /dev/null +++ b/Task/Leap-year/Zig/leap-year-2.zig @@ -0,0 +1,35 @@ +/// The type that holds the current year, i.e. 2016 +pub const Year = u16; + +/// Returns true for years with 366 days +/// and false for years with 365 days. +pub fn isLeapYear(year: Year) bool { + // In the western Gregorian Calendar leap a year is + // a multiple of 4, excluding multiples of 100, and + // adding multiples of 400. In code: + // + // if (@mod(year, 4) != 0) + // return false; + // if (@mod(year, 100) != 0) + // return true; + // return (0 == @mod(year, 400)); + + // The following is equivalent to the above + // but uses bitwise operations when testing + // for divisibility, masking with 3 as test + // for multiples of 4 and with 15 as a test + // for multiples of 16. Multiples of 16 and + // 100 are, conveniently, multiples of 400. + const mask: Year = switch (year % 100) { + 0 => 0b1111, + else => 0b11, + }; + return 0 == year & mask; +} + +test "isLeapYear" { + try testing.expectEqual(false, isLeapYear(2095)); + try testing.expectEqual(true, isLeapYear(2096)); + try testing.expectEqual(false, isLeapYear(2100)); + try testing.expectEqual(true, isLeapYear(2400)); +} diff --git a/Task/Least-common-multiple/EasyLang/least-common-multiple.easy b/Task/Least-common-multiple/EasyLang/least-common-multiple.easy new file mode 100644 index 0000000000..7faa349ace --- /dev/null +++ b/Task/Least-common-multiple/EasyLang/least-common-multiple.easy @@ -0,0 +1,12 @@ +func gcd a b . + while b <> 0 + h = b + b = a mod b + a = h + . + return a +. +func lcm a b . + return a / gcd a b * b +. +print lcm 12 18 diff --git a/Task/Least-common-multiple/Elena/least-common-multiple.elena b/Task/Least-common-multiple/Elena/least-common-multiple.elena index 1e29b0d070..3aa18022db 100644 --- a/Task/Least-common-multiple/Elena/least-common-multiple.elena +++ b/Task/Least-common-multiple/Elena/least-common-multiple.elena @@ -1,7 +1,7 @@ import extensions; import system'math; -gcd = (m,n => (n == 0) ? (m.Absolute) : (gcd(n,n.mod:m))); +gcd = (m,n => (n == 0) ? (m.Absolute) : (gcd(n,n.mod(m)))); lcm = (m,n => (m * n).Absolute / gcd(m,n)); diff --git a/Task/Left-factorials/Wren/left-factorials.wren b/Task/Left-factorials/Wren/left-factorials.wren index 214883a7c1..157440e018 100644 --- a/Task/Left-factorials/Wren/left-factorials.wren +++ b/Task/Left-factorials/Wren/left-factorials.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/big" for BigInt +import "./fmt" for Fmt +import "./big" for BigInt var lfacts = List.filled(12, BigInt.zero) var lfact = BigInt.one diff --git a/Task/Legendre-prime-counting-function/FreeBASIC/legendre-prime-counting-function.basic b/Task/Legendre-prime-counting-function/FreeBASIC/legendre-prime-counting-function.basic new file mode 100644 index 0000000000..7156c2c534 --- /dev/null +++ b/Task/Legendre-prime-counting-function/FreeBASIC/legendre-prime-counting-function.basic @@ -0,0 +1,24 @@ +Function isPrime(n As Uinteger) As Boolean + Dim As Uinteger i + For i = 2 To Sqr(n) + If n Mod i = 0 Then Return False + Next i + Return True +End Function + +Dim As Uinteger n, i, j, count +Dim Shared As Ulongint primes(1e8) +n = 1 +For i = 0 To 9 + count = 0 + For j = 2 To n + If isPrime(j) Then + count += 1 + primes(count) = j + End If + Next j + Print "10^"; i; " "; count + n *= 10 +Next i + +Sleep diff --git a/Task/Legendre-prime-counting-function/Mojo/legendre-prime-counting-function.mojo b/Task/Legendre-prime-counting-function/Mojo/legendre-prime-counting-function.mojo new file mode 100644 index 0000000000..eb3ebfe5ac --- /dev/null +++ b/Task/Legendre-prime-counting-function/Mojo/legendre-prime-counting-function.mojo @@ -0,0 +1,151 @@ +from time import (now) + +alias cLIMIT: UInt64 = 100_000_000_000 + +@always_inline +fn mkMasks() -> DTypePointer[DType.uint8]: + let rslt = DTypePointer[DType.uint8].alloc(8) + for i in range(8): rslt.offset(i).store(1 << i) + return rslt + +let masksp = mkMasks() + +fn intsqrt(n: UInt64) -> UInt64: + if n < 4: + if n < 1: return 0 else: return 1 + var x: UInt64 = n; var qn: UInt64 = 0; var r: UInt64 = 0 + while qn < 64 and (1 << qn) <= n: + qn += 2 + var q: UInt64 = 1 << qn + while q > 1: + if qn >= 64: + q = 1 << (qn - 2); qn = 0 + else: + q >>= 2 + let t: UInt64 = r + q + r >>= 1 + if x >= t: + x -= t; r += q + return r + +fn countPrimes(n: UInt64) -> Int64: + if n < 3: + if n < 2: return 0 + else: return 1 + let rtlmt: Int = intsqrt(n).to_int() # precision limits range to maybe 1e16! + let mxndx = (rtlmt - 1) >> 1 + @always_inline + fn half(n: Int64) -> Int64 : return ((n - 1) // 2) + @always_inline + fn divide(nm: UInt64, d: UInt64) -> Int64: return ((nm * 1.0) / (d * 1.0)).to_int() + let smalls = # current accumulated counts of odd primes 1 to sqrt range + DTypePointer[DType.uint32].alloc(mxndx + 1) + # initialized for no sieving whatsoever other than odds-only - partial sieved by 2: + # 0 odd primes to 1; 1 odd prime to 3, etc.... + for i in range(mxndx + 1): smalls.offset(i).store(i) + let roughs = # current odd k-rough numbers up to sqrt of range; k = 2 + DTypePointer[DType.uint32].alloc(mxndx + 1) + # initialized to all odd positive numbers 1, 3, 5, ... sqrt range... + for i in range(mxndx + 1): roughs.offset(i).store(i + i + 1) + # array of current phi counts for above roughs... + # these are not strictly `phi`'s since they also include the + # count of base primes in order to match the above `smalls` definition! + let larges = # starts as size of counts just as `roughs` so they align! + DTypePointer[DType.uint64].alloc(mxndx + 1) + # initialized for current roughs after accounting for even prime of two... + for i in range(mxndx + 1): larges.offset(i).store((n // (i + i + 1) - 1) // 2) + # cmpsts is a bit-packed boolean array representing + # odd composite numbers from 1 up to rtlmt used for sieving... + # initialized as "zeros" meaning all odd positives are potentially prime + # note that this array starts at (and keeps) 1 to match the algorithm even + # though 1 is not a prime, as 1 is important in computation of phi... + let cmpsts = DTypePointer[DType.uint8].alloc((mxndx + 8) // 8) + memset_zero(cmpsts, (mxndx + 8) // 8) + + # number of found base primes and current highest used rough index... + var npc: Int = 0; var mxri: Int = mxndx + for i in range(1, mxndx + 1): # start at index for 3; i will never reach mxndx... + let sqri = (i + i) * (i + 1) # computation of square index! + if sqri > mxndx: break # stop partial sieving due to square index limit! + if (cmpsts.offset(i >> 3).load() & masksp.offset(i & 7).load()) != 0: continue # if not prime + # culling the base prime from cmpsts means it will never be found again + let cp = cmpsts.offset(i >> 3) + cp.store(cp.load() | masksp.offset(i & 7).load()) # cull base prime + let bp = i + i + 1 # base prime from index! + for c in range(sqri, mxndx + 1, bp): # SoE culling of all bp multiples... + let cp = cmpsts.offset(c >> 3); cp.store(cp.load() | masksp.offset(c & 7).load()) + # partial sieving to current base prime is now completed! + + var ri: Int = 0 # to keep track of current used roughs index! + for k in range(mxri + 1): # processing over current roughs size... + # q is not necessarily a prime but may be a + # product of primes not yet culled by partial sieving; + # this is what saves operations compared to recursive Legendre: + let q: UInt64 = roughs.offset(k).load().to_int(); let qi = q >> 1 # index of always odd q! + # skip over values of `q` already culled in the last partial sieve: + if (cmpsts.offset(qi >> 3).load() & masksp.offset(qi & 7).load()) != 0: continue + # since `q` cannot be equal to bp due to cull of bp and above skip; + let d: UInt64 = bp * q # `d` is odd product of some combination of odd primes! + # the following computation is essential to the algorithm's speed: + # see above description in the text for how this works: + larges.offset(ri).store(larges.offset(k).load() - + (larges.offset(smalls.offset(d >> 1).load().to_int() - npc).load() if d <= rtlmt + else smalls.offset(half(divide(n, d))).load().to_int()) + npc) + # eliminate rough values that have been culled in partial sieve: + # note that `larges` and `roughs` indices relate to each other! + roughs.offset(ri).store(q.to_int()); ri += 1 # update rough value; advance rough index + + var m = mxndx # adjust `smalls` counts for the newly culled odds... + # this is faster than recounting over the `cmpsts` array for each loop... + for k in range(((rtlmt // bp) - 1) | 1, bp - 1, -2): # k always odd! + # `c` is correction from current count to desired count... + # `e` is end limit index no correction is necessary for current cull... + let c = smalls.offset(k >> 1).load() - npc; let e = (k * bp) >> 1 + while m >= e: + let cp = smalls.offset(m) + cp.store(cp.load() - c); m -= 1 # correct over range down to `e` + mxri = ri - 1; npc += 1 # set next loop max roughs index; count base prime + # now `smalls` is a LUT of odd prime accumulated counts for all odd primes; + # `roughs` is exactly the "k-roughs" up to the sqrt of range with `k` the + # index of the next prime above the quad root of the range; + # `larges` is the partial prime counts for each of the `roughs` values... + # note that `larges` values include the count of the odd base primes!!! + # `cmpsts` are never used again! + + # the following does the top most "phi tree" calculation: + var result: Int64 = larges.load().to_int() # the answer to here is all valid `phis` + for i in range(1, mxri + 1): result -= larges.offset(i).load().to_int() # combined here by subtraction + # compensate for the included odd base prime counts over subracted above: + result += ((mxri + 1 + 2 * (npc - 1)) * mxri // 2) + + # This loop adds the counts due to the products of the `roughs` primes, + # of which we only use two different ones at a time, as all the + # combinations with lower primes than the cube root of the range have + # already been computed and included with the previous major loop... + # see text description above for how this works... + for j in range(1, mxri + 1): # for all `roughs` (now prime) not including one: + let p: UInt64 = roughs.offset(j).load().to_int() + let m: UInt64 = (n // p) # `m` is the `p` quotient + # so that the end limit `e` can be calculated based on `n`/(`p`^2) + let e: Int = smalls.offset(half((m // p).to_int())).load().to_int() - npc + # following break test equivalent to non-memoization/non-splitting optmization: + if e <= j: break # stop at about `p` of cube root of range! + for k in range(j + 1, e + 1): # for all `roughs` greater than `p` to end limit: + result += smalls.offset(half(divide(m, roughs.offset(k).load().to_int()))).load().to_int() + # compensate for all the extra base prime counts just added! + result -= ((e - j) * (npc + j - 1)) + + result += 1 # include the count for the only even prime of two + smalls.free(); roughs.free(); larges.free(); cmpsts.free() + + return result + +fn main(): + var pow: Int = 1 + for i in range(10): + print('10^', i, '=', countPrimes(pow)) + pow *= 10 + let start = now() + let answr = countPrimes(cLIMIT) + let elpsd = (now() - start) / 1000000 + print("Found", answr, "primes up to", cLIMIT, "in", elpsd, "milliseconds.") diff --git a/Task/Letter-frequency/Wren/letter-frequency.wren b/Task/Letter-frequency/Wren/letter-frequency.wren index 98669e4e57..c36209da3e 100644 --- a/Task/Letter-frequency/Wren/letter-frequency.wren +++ b/Task/Letter-frequency/Wren/letter-frequency.wren @@ -1,5 +1,5 @@ import "io" for File -import "/fmt" for Fmt +import "./fmt" for Fmt var text = File.read("mit10000.txt") var freqs = List.filled(26, 0) diff --git a/Task/Levenshtein-distance-Alignment/C-sharp/levenshtein-distance-alignment.cs b/Task/Levenshtein-distance-Alignment/C-sharp/levenshtein-distance-alignment.cs new file mode 100644 index 0000000000..2296a37992 --- /dev/null +++ b/Task/Levenshtein-distance-Alignment/C-sharp/levenshtein-distance-alignment.cs @@ -0,0 +1,64 @@ +using System; +using System.Text; + +public class LevenshteinAlignment +{ + public static string[] Alignment(string a, string b) + { + a = a.ToLower(); + b = b.ToLower(); + + int[,] costs = new int[a.Length + 1, b.Length + 1]; + + for (int j = 0; j <= b.Length; j++) + costs[0, j] = j; + + for (int i = 1; i <= a.Length; i++) + { + costs[i, 0] = i; + for (int j = 1; j <= b.Length; j++) + { + costs[i, j] = Math.Min(1 + Math.Min(costs[i - 1, j], costs[i, j - 1]), + a[i - 1] == b[j - 1] ? costs[i - 1, j - 1] : costs[i - 1, j - 1] + 1); + } + } + + StringBuilder aPathRev = new StringBuilder(); + StringBuilder bPathRev = new StringBuilder(); + + for (int i = a.Length, j = b.Length; i != 0 && j != 0;) + { + if (costs[i, j] == (a[i - 1] == b[j - 1] ? costs[i - 1, j - 1] : costs[i - 1, j - 1] + 1)) + { + aPathRev.Append(a[--i]); + bPathRev.Append(b[--j]); + } + else if (costs[i, j] == 1 + costs[i - 1, j]) + { + aPathRev.Append(a[--i]); + bPathRev.Append('-'); + } + else if (costs[i, j] == 1 + costs[i, j - 1]) + { + aPathRev.Append('-'); + bPathRev.Append(b[--j]); + } + } + + return new string[] { Reverse(aPathRev.ToString()), Reverse(bPathRev.ToString()) }; + } + + private static string Reverse(string s) + { + char[] charArray = s.ToCharArray(); + Array.Reverse(charArray); + return new string(charArray); + } + + public static void Main(string[] args) + { + string[] result = Alignment("rosettacode", "raisethysword"); + Console.WriteLine(result[0]); + Console.WriteLine(result[1]); + } +} diff --git a/Task/Levenshtein-distance-Alignment/Wren/levenshtein-distance-alignment.wren b/Task/Levenshtein-distance-Alignment/Wren/levenshtein-distance-alignment.wren index 96948bcc11..156688753c 100644 --- a/Task/Levenshtein-distance-Alignment/Wren/levenshtein-distance-alignment.wren +++ b/Task/Levenshtein-distance-Alignment/Wren/levenshtein-distance-alignment.wren @@ -1,4 +1,4 @@ -import "/str" for Str +import "./str" for Str var levenshteinAlign = Fn.new { |a, b| a = Str.lower(a) diff --git a/Task/Levenshtein-distance/Bruijn/levenshtein-distance.bruijn b/Task/Levenshtein-distance/Bruijn/levenshtein-distance.bruijn new file mode 100644 index 0000000000..2111ade5dd --- /dev/null +++ b/Task/Levenshtein-distance/Bruijn/levenshtein-distance.bruijn @@ -0,0 +1,10 @@ +:import std/Combinator . +:import std/Char C +:import std/List . +:import std/Math . + +levenshtein y [[[∅?1 ∀0 (∅?0 ∀1 (0 (1 [[[[go]]]])))]]] + go (C.eq? 3 1) (6 2 0) ++(lmin ((6 2 0) : ((6 5 0) : {}(6 2 4)))) + +:test ((levenshtein "rosettacode" "raisethysword") =? (+8)) ([[1]]) +:test ((levenshtein "kitten" "sitting") =? (+3)) ([[1]]) diff --git a/Task/Levenshtein-distance/Refal/levenshtein-distance.refal b/Task/Levenshtein-distance/Refal/levenshtein-distance.refal new file mode 100644 index 0000000000..98faef17fa --- /dev/null +++ b/Task/Levenshtein-distance/Refal/levenshtein-distance.refal @@ -0,0 +1,26 @@ +$ENTRY Go { + = + ; +}; + +Show { + (e.A) (e.B) = ' e.B ': ' >; +}; + +Lev { + (e.A) (), : s.L e.A = s.L; + () (e.B), : s.L e.B = s.L; + (s.C e.A) (s.C e.B) = ; + (e.A) (e.B), e.A: s.HA e.LA, e.B: s.HB e.LB = + <+ 1 + + >>; +} + +Min { + s.N = s.N; + s.M s.N e.X, : { + '-' = ; + s.X = ; + }; +}; diff --git a/Task/Linear-congruential-generator/EasyLang/linear-congruential-generator.easy b/Task/Linear-congruential-generator/EasyLang/linear-congruential-generator.easy new file mode 100644 index 0000000000..e41f880e8e --- /dev/null +++ b/Task/Linear-congruential-generator/EasyLang/linear-congruential-generator.easy @@ -0,0 +1,24 @@ +func mul32 a b . + # to avoid overflow with 53bit integer precision with double + ah = a div 0x10000 + al = a mod 0x10000 + bh = b div 0x10000 + bl = b mod 0x10000 + return al * bl + al * bh * 0x10000 + bl * ah * 0x10000 +. +global state_bsd state_ms . +func rand_bsd . + state_bsd = (mul32 1103515245 state_bsd + 12345) mod 0x80000000 + return state_bsd +. +func rand_ms . + state_ms = (214013 * state_ms + 2531011) mod 0x80000000 + return state_ms div 0x10000 +. +for i = 1 to 5 + print rand_bsd +. +print "" +for i = 1 to 5 + print rand_ms +. diff --git a/Task/Linear-congruential-generator/Wren/linear-congruential-generator.wren b/Task/Linear-congruential-generator/Wren/linear-congruential-generator.wren index 2c1f84f98a..7249535d22 100644 --- a/Task/Linear-congruential-generator/Wren/linear-congruential-generator.wren +++ b/Task/Linear-congruential-generator/Wren/linear-congruential-generator.wren @@ -1,5 +1,5 @@ -import "/big" for BigInt -import "/fmt" for Fmt +import "./big" for BigInt +import "./fmt" for Fmt // basic linear congruential generator var lcg = Fn.new { |a, c, m, seed| diff --git a/Task/List-rooted-trees/Wren/list-rooted-trees.wren b/Task/List-rooted-trees/Wren/list-rooted-trees.wren index 4e09444d6c..0347936260 100644 --- a/Task/List-rooted-trees/Wren/list-rooted-trees.wren +++ b/Task/List-rooted-trees/Wren/list-rooted-trees.wren @@ -1,4 +1,4 @@ -import "/long" for ULong +import "./long" for ULong import "os" for Process var treeList = [] diff --git a/Task/Long-literals-with-continuations/Wren/long-literals-with-continuations.wren b/Task/Long-literals-with-continuations/Wren/long-literals-with-continuations.wren index 018094a674..dd085d346b 100644 --- a/Task/Long-literals-with-continuations/Wren/long-literals-with-continuations.wren +++ b/Task/Long-literals-with-continuations/Wren/long-literals-with-continuations.wren @@ -1,31 +1,31 @@ -import "/pattern" for Pattern +import "./pattern" for Pattern var elementStr = - "hydrogen helium lithium beryllium boron carbon " + - "nitrogen oxygen fluorine neon sodium magnesium " + - "aluminum silicon phosphorous sulfur chlorine argon " + - "potassium calcium scandium titanium vanadium chromium " + - "manganese iron cobalt nickel copper zinc " + - "gallium germanium arsenic selenium bromine krypton " + - "rubidium strontium yttrium zirconium niobium molybdenum " + - "technetium ruthenium rhodium palladium silver cadmium " + - "indium tin antimony tellurium iodine xenon " + - "cesium barium lanthanum cerium praseodymium neodymium " + - "promethium samarium europium gadolinium terbium dysprosium " + - "holmium erbium thulium ytterbium lutetium hafnium " + - "tantalum tungsten rhenium osmium iridium platinum " + - "gold mercury thallium lead bismuth polonium " + - "astatine radon francium radium actinium thorium " + - "protactinium uranium neptunium plutonium americium curium " + - "berkelium californium einsteinium fermium mendelevium nobelium " + - "lawrencium rutherfordium dubnium seaborgium bohrium hassium " + - "meitnerium darmstadtium roentgenium copernicium nihonium flerovium " + - "moscovium livermorium tennessine oganesson" +"""hydrogen helium lithium beryllium boron carbon + nitrogen oxygen fluorine neon sodium magnesium + aluminum silicon phosphorous sulfur chlorine argon + potassium calcium scandium titanium vanadium chromium + manganese iron cobalt nickel copper zinc + gallium germanium arsenic selenium bromine krypton + rubidium strontium yttrium zirconium niobium molybdenum + technetium ruthenium rhodium palladium silver cadmium + indium tin antimony tellurium iodine xenon + cesium barium lanthanum cerium praseodymium neodymium + promethium samarium europium gadolinium terbium dysprosium + holmium erbium thulium ytterbium lutetium hafnium + tantalum tungsten rhenium osmium iridium platinum + gold mercury thallium lead bismuth polonium + astatine radon francium radium actinium thorium + protactinium uranium neptunium plutonium americium curium + berkelium californium einsteinium fermium mendelevium nobelium + lawrencium rutherfordium dubnium seaborgium bohrium hassium + meitnerium darmstadtium roentgenium copernicium nihonium flerovium + moscovium livermorium tennessine oganesson""" var p = Pattern.new("+1/s") // matches 1 or more whitespace characters var elements = p.splitAll(elementStr) // get a list of elements elementStr = elements.join(" ") // recombine using a single space as separator -var lastUpdate = "2020-08-03" +var lastUpdate = "2023-12-17" System.print("Last updated : %(lastUpdate)") System.print("Number of elements : %(elements.count)") System.print("Last element : %(elements[-1])") diff --git a/Task/Long-multiplication/Wren/long-multiplication.wren b/Task/Long-multiplication/Wren/long-multiplication.wren index 0aef8a5b57..1ab8d9ef27 100644 --- a/Task/Long-multiplication/Wren/long-multiplication.wren +++ b/Task/Long-multiplication/Wren/long-multiplication.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt // argument validation var d = Fn.new { |b| diff --git a/Task/Long-primes/ALGOL-68/long-primes.alg b/Task/Long-primes/ALGOL-68/long-primes.alg new file mode 100644 index 0000000000..5a56ad4552 --- /dev/null +++ b/Task/Long-primes/ALGOL-68/long-primes.alg @@ -0,0 +1,52 @@ +BEGIN # find some long primes - primes whose reciprocol have a period of p-1 # + INT max number = 64 000; + # sieve the primes to max number # + [ 1 : max number ]BOOL is prime; FOR i TO UPB is prime DO is prime[ i ] := ODD i OD; + is prime[ 1 ] := FALSE; + is prime[ 2 ] := TRUE; + FOR s FROM 3 BY 2 TO ENTIER sqrt( max number ) DO + IF is prime[ s ] THEN + FOR p FROM s * s BY s TO UPB is prime DO is prime[ p ] := FALSE OD + FI + OD; + + OP PERIOD = ( INT n )INT: # returns the period of the reciprocal of n # + BEGIN + INT r := 1; + FOR i TO n + 1 DO + r *:= 10 MODAB n + OD; + INT rr = r; + INT period := 0; + WHILE r *:= 10 MODAB n; + period +:= 1; + r /= rr + DO SKIP OD; + period + END # PERIOD # ; + + print( ( "Long primes upto 500:", newline, " " ) ); + INT lp count := 0; + FOR p FROM 3 TO 500 DO + IF is prime[ p ] THEN + IF PERIOD p = p - 1 THEN + print( ( " ", whole( p, 0 ) ) ); + lp count +:= 1 + FI + FI + OD; + print( ( newline ) ); + INT limit := 500; + FOR p FROM 500 WHILE limit <= 64 000 DO + IF p = limit THEN + print( ( "Long primes up to: ", whole( p, -5 ), ": ", whole( lp count, 0 ), newline ) ); + limit *:= 2 + FI; + IF is prime[ p ] THEN + IF PERIOD p = p - 1 THEN + lp count +:= 1 + FI + FI + OD + +END diff --git a/Task/Long-primes/EasyLang/long-primes.easy b/Task/Long-primes/EasyLang/long-primes.easy new file mode 100644 index 0000000000..c6faa26dc8 --- /dev/null +++ b/Task/Long-primes/EasyLang/long-primes.easy @@ -0,0 +1,54 @@ +fastfunc isprim num . + if num mod 2 = 0 and num > 2 + return 0 + . + i = 3 + while i <= sqrt num + if num mod i = 0 + return 0 + . + i += 2 + . + return 1 +. +prim = 2 +proc nextprim . . + repeat + prim += 1 + until isprim prim = 1 + . +. +func period n . + r = 1 + repeat + r = (r * 10) mod n + p += 1 + until r <= 1 + . + return p +. +# +print "Long primes up to 500 are:" +repeat + nextprim + until prim > 500 + if period prim = prim - 1 + write prim & " " + cnt += 1 + . +. +print "" +print "" +print "The number of long primes up to:" +limit = 500 +repeat + if prim > limit + print limit & " is " & cnt + limit *= 2 + . + until limit > 32000 + if period prim = prim - 1 + cnt += 1 + . + nextprim +. diff --git a/Task/Long-primes/Wren/long-primes.wren b/Task/Long-primes/Wren/long-primes.wren index 00844fb381..fa1dfd9bf1 100644 --- a/Task/Long-primes/Wren/long-primes.wren +++ b/Task/Long-primes/Wren/long-primes.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/math" for Int +import "./fmt" for Fmt +import "./math" for Int // finds the period of the reciprocal of n var findPeriod = Fn.new { |n| @@ -39,6 +39,6 @@ System.print(longPrimes[0...totals[0]].join(" ")) System.print("\nThe number of long primes up to: ") var i = 0 for (total in totals) { - System.print(" %(Fmt.d(5, numbers[i])) is %(total)") + Fmt.print(" $5d is $d", numbers[i], total) i = i + 1 } diff --git a/Task/Long-year/Amazing-Hopper/long-year.hopper b/Task/Long-year/Amazing-Hopper/long-year.hopper new file mode 100644 index 0000000000..be791aa6bf --- /dev/null +++ b/Task/Long-year/Amazing-Hopper/long-year.hopper @@ -0,0 +1,20 @@ +#include + +#proto esañolargo(_X_) + +algoritmo + + año=1800, c=5 + + imprimir ("Long (53 week) years between 1800 and 2100:\n\n" ) + + iterar grupo ( ++año, #( año<=2100 ), \ + cuando ( #( es año largo( año )==4 || es año largo( año-1 )==3 ) ){ \ + imprimir ( año, " ", solo si( #( c==0 ) , NL; c=6 ), --c ) } ) + +terminar + +subrutinas + +es año largo (y) +retornar ' #( (y + floor(y / 4) - floor(y / 100) + floor(y / 400)) % 7 ) ' diff --git a/Task/Long-year/EasyLang/long-year.easy b/Task/Long-year/EasyLang/long-year.easy new file mode 100644 index 0000000000..ee8e4208ce --- /dev/null +++ b/Task/Long-year/EasyLang/long-year.easy @@ -0,0 +1,11 @@ +func p y . + return (y + y div 4 - y div 100 + y div 400) mod 7 +. +func longyear y . + return if p y = 4 or p (y - 1) = 3 +. +for y = 2000 to 2100 + if longyear y = 1 + write y & " " + . +. diff --git a/Task/Long-year/Wren/long-year.wren b/Task/Long-year/Wren/long-year.wren index 69480bcb2e..01a940b7e8 100644 --- a/Task/Long-year/Wren/long-year.wren +++ b/Task/Long-year/Wren/long-year.wren @@ -1,4 +1,4 @@ -import "/date" for Date +import "./date" for Date var centuries = ["20th", "21st", "22nd"] var starts = [1900, 2000, 2100] diff --git a/Task/Longest-common-subsequence/EasyLang/longest-common-subsequence.easy b/Task/Longest-common-subsequence/EasyLang/longest-common-subsequence.easy new file mode 100644 index 0000000000..91136e30d9 --- /dev/null +++ b/Task/Longest-common-subsequence/EasyLang/longest-common-subsequence.easy @@ -0,0 +1,26 @@ +func$ right a$ n . + return substr a$ -n n +. +func$ left a$ n . + if n < 0 + n = len a$ + n + . + return substr a$ 1 n +. +func$ lcs a$ b$ . + if len a$ = 0 or len b$ = 0 + return "" + . + if right a$ 1 = right b$ 1 + return lcs left a$ -1 left b$ -1 & right a$ 1 + . + x$ = lcs a$ left b$ -1 + y$ = lcs left a$ -1 b$ + if len x$ > len y$ + return x$ + else + return y$ + . +. +print lcs "1234" "1224533324" +print lcs "thisisatest" "testing123testing" diff --git a/Task/Longest-common-substring/EasyLang/longest-common-substring.easy b/Task/Longest-common-substring/EasyLang/longest-common-substring.easy index 6a31753188..f832b582ad 100644 --- a/Task/Longest-common-substring/EasyLang/longest-common-substring.easy +++ b/Task/Longest-common-substring/EasyLang/longest-common-substring.easy @@ -14,7 +14,7 @@ func$ lcs a$ b$ . . . . - b$ = substr b$ 2 -1 + b$ = substr b$ 2 9999 . return max$ . diff --git a/Task/Longest-common-substring/Pascal/longest-common-substring.pas b/Task/Longest-common-substring/Pascal/longest-common-substring.pas index bc1b673cf6..f54ac3cf64 100644 --- a/Task/Longest-common-substring/Pascal/longest-common-substring.pas +++ b/Task/Longest-common-substring/Pascal/longest-common-substring.pas @@ -70,7 +70,7 @@ VAR S1: string = 'thisisatest' ; - S2: string = 'testing123isatesting' ; + S2: string = 'testing123testing' ; BEGIN diff --git a/Task/Longest-common-substring/Refal/longest-common-substring.refal b/Task/Longest-common-substring/Refal/longest-common-substring.refal new file mode 100644 index 0000000000..3f671f837f --- /dev/null +++ b/Task/Longest-common-substring/Refal/longest-common-substring.refal @@ -0,0 +1,18 @@ +$ENTRY Go { + = >; +}; + +LCS { + (e.X) e.L e.X e.R = e.X; + () e.Y = ; + e.X e.Y, e.X: (s.L e.XL), + e.X: (e.XR s.R) + = ) >; +}; + +Longest { + (e.X) e.Y, : s.LX e.X2, + : s.LY e.Y2, + : '+' = e.X; + (e.X) e.Y = e.Y; +}; diff --git a/Task/Look-and-say-sequence/Refal/look-and-say-sequence.refal b/Task/Look-and-say-sequence/Refal/look-and-say-sequence.refal new file mode 100644 index 0000000000..ea6e34584b --- /dev/null +++ b/Task/Look-and-say-sequence/Refal/look-and-say-sequence.refal @@ -0,0 +1,22 @@ +$ENTRY Go { + = >; +}; + +Sequence { + 0 e.seq = ; + s.N e.seq = + >; +} + +LookSay { + = ; + e.1, + e.1>: (e.group) e.rest, + : s.num s.item e.discard = + s.num s.item ; +} + +Group { + s.1 s.1 e.rest = <+ 1 >; + s.1 e.rest = 1; +}; diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Elena/loop-over-multiple-arrays-simultaneously-1.elena b/Task/Loop-over-multiple-arrays-simultaneously/Elena/loop-over-multiple-arrays-simultaneously-1.elena index 56a6ec1495..b300c3aaeb 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Elena/loop-over-multiple-arrays-simultaneously-1.elena +++ b/Task/Loop-over-multiple-arrays-simultaneously/Elena/loop-over-multiple-arrays-simultaneously-1.elena @@ -7,7 +7,7 @@ public program() var a2 := new string[]{"A","B","C"}; var a3 := new int[]{1,2,3}; - for(int i := 0, i < a1.Length, i += 1) + for(int i := 0; i < a1.Length; i += 1) { console.printLine(a1[i], a2[i], a3[i]) }; diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Elena/loop-over-multiple-arrays-simultaneously-2.elena b/Task/Loop-over-multiple-arrays-simultaneously/Elena/loop-over-multiple-arrays-simultaneously-2.elena index 66fe0bcdc1..4f93256236 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Elena/loop-over-multiple-arrays-simultaneously-2.elena +++ b/Task/Loop-over-multiple-arrays-simultaneously/Elena/loop-over-multiple-arrays-simultaneously-2.elena @@ -9,7 +9,7 @@ public program var zipped := a1.zipBy(a2,(first,second => first + second.toString() )) .zipBy(a3, (first,second => first + second.toString() )); - zipped.forEach:(e) + zipped.forEach::(e) { console.writeLine:e }; console.readChar(); diff --git a/Task/Loops-Break/EasyLang/loops-break.easy b/Task/Loops-Break/EasyLang/loops-break.easy index 860d4e1bcd..a0454750ba 100644 --- a/Task/Loops-Break/EasyLang/loops-break.easy +++ b/Task/Loops-Break/EasyLang/loops-break.easy @@ -1,6 +1,6 @@ repeat - a = random 20 - print a - until a = 10 - print random 20 + a = randint 20 + print a + until a = 10 + print randint 20 . diff --git a/Task/Loops-Break/Langur/loops-break.langur b/Task/Loops-Break/Langur/loops-break.langur index d346ac5846..ec8897cb73 100644 --- a/Task/Loops-Break/Langur/loops-break.langur +++ b/Task/Loops-Break/Langur/loops-break.langur @@ -2,5 +2,4 @@ for { val .i = random 0..19 write .i, " " if .i == 10 { writeln(); break } - write random(0..19), " " } diff --git a/Task/Loops-Downward-for/Bait/loops-downward-for.bait b/Task/Loops-Downward-for/Bait/loops-downward-for.bait new file mode 100644 index 0000000000..0914410570 --- /dev/null +++ b/Task/Loops-Downward-for/Bait/loops-downward-for.bait @@ -0,0 +1,5 @@ +fun main() { + for i := 10; i >= 0; i -= 1 { + println(i) + } +} diff --git a/Task/Loops-For-with-a-specified-step/Bait/loops-for-with-a-specified-step.bait b/Task/Loops-For-with-a-specified-step/Bait/loops-for-with-a-specified-step.bait new file mode 100644 index 0000000000..387295c3f3 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Bait/loops-for-with-a-specified-step.bait @@ -0,0 +1,6 @@ +fun main() { + // Print all single digit odd numbers + for i := 1; i < 10; i += 2 { + println(i) + } +} diff --git a/Task/Loops-For-with-a-specified-step/Elena/loops-for-with-a-specified-step.elena b/Task/Loops-For-with-a-specified-step/Elena/loops-for-with-a-specified-step.elena index f21aeff7c6..ba3cc3cd5e 100644 --- a/Task/Loops-For-with-a-specified-step/Elena/loops-for-with-a-specified-step.elena +++ b/Task/Loops-For-with-a-specified-step/Elena/loops-for-with-a-specified-step.elena @@ -1,7 +1,7 @@ public program() { - for(int i := 2, i <= 8, i += 2 ) + for(int i := 2; i <= 8; i += 2 ) { - console.writeLine:i + console.writeLine(i) } } diff --git a/Task/Loops-For-with-a-specified-step/Wren/loops-for-with-a-specified-step-2.wren b/Task/Loops-For-with-a-specified-step/Wren/loops-for-with-a-specified-step-2.wren index 94b101f031..d2c3ce9645 100644 --- a/Task/Loops-For-with-a-specified-step/Wren/loops-for-with-a-specified-step-2.wren +++ b/Task/Loops-For-with-a-specified-step/Wren/loops-for-with-a-specified-step-2.wren @@ -1,4 +1,4 @@ -import "/iterate" for Stepped +import "./iterate" for Stepped // Print odd numbers under 20. for (i in Stepped.new(1..20, 2)) System.write("%(i) ") diff --git a/Task/Loops-For/Bait/loops-for.bait b/Task/Loops-For/Bait/loops-for.bait new file mode 100644 index 0000000000..ffa8c6badc --- /dev/null +++ b/Task/Loops-For/Bait/loops-for.bait @@ -0,0 +1,10 @@ +const ROWS := 5 + +fun main() { + for i := 1; i <= ROWS; i += 1 { + for j := 1; j <= i; j += 1 { + print('*') + } + println('') + } +} diff --git a/Task/Loops-For/Elena/loops-for.elena b/Task/Loops-For/Elena/loops-for.elena index 5ca515de60..96efd36a5e 100644 --- a/Task/Loops-For/Elena/loops-for.elena +++ b/Task/Loops-For/Elena/loops-for.elena @@ -2,10 +2,10 @@ import extensions; public program() { - for(int i := 0, i < 5, i += 1) + for(int i := 0; i < 5; i += 1) { - for(int j := 0, j <= i, j += 1) - { console.write:"*" }; + for(int j := 0; j <= i; j += 1) + { console.write("*") }; console.writeLine() } diff --git a/Task/Loops-Foreach/Bait/loops-foreach.bait b/Task/Loops-Foreach/Bait/loops-foreach.bait new file mode 100644 index 0000000000..78f9dee773 --- /dev/null +++ b/Task/Loops-Foreach/Bait/loops-foreach.bait @@ -0,0 +1,40 @@ +fun for_in_array() { + arr := ['1st', '2nd', '3rd'] + + // Iterate over array indices and elements + for i, val in arr { + println('${i}: ${val}') + } + + // Using only one variable will iterate over the elements + for val in arr { + println(val) + } + + // To only iterate over the indices, use `_` as the second variable name. + // `_` is a special variable that will ignore any assigned value + for i, _ in arr { + println(i) + } +} + +fun for_in_map() { + nato_abc := map{ + 'a': 'Alpha' + 'b': 'Bravo' + 'c': 'Charlie' + 'd': 'Delta' + } + + // Iterate over map keys and values. + // Note that, unlike arrays, only the two-variable variant is allowed + for key, val in nato_abc { + println('${key}: ${val}') + } +} + +fun main() { + for_in_array() + println('') + for_in_map() +} diff --git a/Task/Loops-Foreach/Elena/loops-foreach.elena b/Task/Loops-Foreach/Elena/loops-foreach-1.elena similarity index 69% rename from Task/Loops-Foreach/Elena/loops-foreach.elena rename to Task/Loops-Foreach/Elena/loops-foreach-1.elena index b19726d60f..73b056adb4 100644 --- a/Task/Loops-Foreach/Elena/loops-foreach.elena +++ b/Task/Loops-Foreach/Elena/loops-foreach-1.elena @@ -5,8 +5,8 @@ public program() { var things := new string[]{"Apple", "Banana", "Coconut"}; - things.forEach:(thing) + things.forEach::(thing) { - console.printLine:thing + console.printLine(thing) } } diff --git a/Task/Loops-Foreach/Elena/loops-foreach-2.elena b/Task/Loops-Foreach/Elena/loops-foreach-2.elena new file mode 100644 index 0000000000..e7fb0ace04 --- /dev/null +++ b/Task/Loops-Foreach/Elena/loops-foreach-2.elena @@ -0,0 +1,11 @@ +import extensions; + +public program() +{ + var things := new string[]{"Apple", "Banana", "Coconut"}; + + foreach(var thing; in things) + { + console.printLine(thing) + } +} diff --git a/Task/Loops-Increment-loop-index-within-loop-body/Wren/loops-increment-loop-index-within-loop-body.wren b/Task/Loops-Increment-loop-index-within-loop-body/Wren/loops-increment-loop-index-within-loop-body.wren index 02d3ee36cf..7700146bb8 100644 --- a/Task/Loops-Increment-loop-index-within-loop-body/Wren/loops-increment-loop-index-within-loop-body.wren +++ b/Task/Loops-Increment-loop-index-within-loop-body/Wren/loops-increment-loop-index-within-loop-body.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var isPrime = Fn.new { |n| if (n < 2 || !n.isInteger) return false diff --git a/Task/Loops-Infinite/Bruijn/loops-infinite.bruijn b/Task/Loops-Infinite/Bruijn/loops-infinite.bruijn new file mode 100644 index 0000000000..badcec1a5b --- /dev/null +++ b/Task/Loops-Infinite/Bruijn/loops-infinite.bruijn @@ -0,0 +1,4 @@ +:import std/String . + +main [spam spam] + spam ["SPAM\n" ++ (0 0)] diff --git a/Task/Loops-Infinite/Elena/loops-infinite.elena b/Task/Loops-Infinite/Elena/loops-infinite.elena index 3d75e60918..8525f08ae6 100644 --- a/Task/Loops-Infinite/Elena/loops-infinite.elena +++ b/Task/Loops-Infinite/Elena/loops-infinite.elena @@ -2,6 +2,6 @@ public program() { while (true) { - console.writeLine:"spam" + console.writeLine("spam") } } diff --git a/Task/Loops-Infinite/Uxntal/loops-infinite.uxnatl b/Task/Loops-Infinite/Uxntal/loops-infinite.uxnatl new file mode 100644 index 0000000000..407bc40473 --- /dev/null +++ b/Task/Loops-Infinite/Uxntal/loops-infinite.uxnatl @@ -0,0 +1,11 @@ +|0100 + &l ;SPAM !&l + +@ ( str* -- ) + &while ( -- ) + LDAk #18 DEO + INC2 LDAk ?&while + POP2 JMP2r + +@SPAM + "SPAM 0a $1 diff --git a/Task/Loops-Nested/Wren/loops-nested.wren b/Task/Loops-Nested/Wren/loops-nested.wren index 517ff840f9..22041cefe9 100644 --- a/Task/Loops-Nested/Wren/loops-nested.wren +++ b/Task/Loops-Nested/Wren/loops-nested.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/fmt" for Fmt +import "./fmt" for Fmt var rand = Random.new() @@ -12,7 +12,7 @@ for (i in 0..19) { var found = false for (i in 0..19) { for (j in 0..19) { - System.write(Fmt.d(4, a[i][j])) + Fmt.write("$4d", a[i][j]) if (a[i][j] == 20) { found = true break diff --git a/Task/Loops-While/Elena/loops-while.elena b/Task/Loops-While/Elena/loops-while.elena index 58b7e7161c..d32fc98ef3 100644 --- a/Task/Loops-While/Elena/loops-while.elena +++ b/Task/Loops-While/Elena/loops-while.elena @@ -3,7 +3,7 @@ public program() int i := 1024; while (i > 0) { - console.writeLine:i; + console.writeLine(i); i /= 2 } diff --git a/Task/Loops-While/Langur/loops-while-2.langur b/Task/Loops-While/Langur/loops-while-2.langur deleted file mode 100644 index 0351d2b680..0000000000 --- a/Task/Loops-While/Langur/loops-while-2.langur +++ /dev/null @@ -1,5 +0,0 @@ -var .i = 1024 -for .i > 0 { - writeln .i - .i \= 2 -} diff --git a/Task/Loops-While/Langur/loops-while-1.langur b/Task/Loops-While/Langur/loops-while.langur similarity index 100% rename from Task/Loops-While/Langur/loops-while-1.langur rename to Task/Loops-While/Langur/loops-while.langur diff --git a/Task/Loops-With-multiple-ranges/Wren/loops-with-multiple-ranges.wren b/Task/Loops-With-multiple-ranges/Wren/loops-with-multiple-ranges.wren index 8612d7cb91..459c1e4493 100644 --- a/Task/Loops-With-multiple-ranges/Wren/loops-with-multiple-ranges.wren +++ b/Task/Loops-With-multiple-ranges/Wren/loops-with-multiple-ranges.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var prod = 1 var sum = 0 @@ -58,5 +58,5 @@ while (j <= p + one) { j = j + 1 } -System.print("sum = %(Fmt.dc(sum))") -System.print("prod = %(Fmt.dc(prod))") +Fmt.print("sum = $,d", sum) +Fmt.print("prod = $,d", prod) diff --git a/Task/Loops-Wrong-ranges/Wren/loops-wrong-ranges.wren b/Task/Loops-Wrong-ranges/Wren/loops-wrong-ranges.wren index 789d4807b6..678d762fab 100644 --- a/Task/Loops-Wrong-ranges/Wren/loops-wrong-ranges.wren +++ b/Task/Loops-Wrong-ranges/Wren/loops-wrong-ranges.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var loop = Fn.new { |start, stop, inc| System.write("%(Fmt.v("dm", 3, [start, stop, inc], 0, " ", "[]")) -> ") diff --git a/Task/Lucas-Lehmer-test/EasyLang/lucas-lehmer-test.easy b/Task/Lucas-Lehmer-test/EasyLang/lucas-lehmer-test.easy new file mode 100644 index 0000000000..bda8269c34 --- /dev/null +++ b/Task/Lucas-Lehmer-test/EasyLang/lucas-lehmer-test.easy @@ -0,0 +1,15 @@ +write "Mersenne Primes: " +func lulehm p . + mp = bitshift 1 p - 1 + sn = 4 + for i = 2 to p - 1 + sn = sn * sn - 2 + sn = sn - (mp * (sn div mp)) + . + return if sn = 0 +. +for p = 2 to 23 + if lulehm p = 1 + write "M" & p & " " + . +. diff --git a/Task/Lucas-Lehmer-test/Wren/lucas-lehmer-test-1.wren b/Task/Lucas-Lehmer-test/Wren/lucas-lehmer-test-1.wren index 1522512e86..7499cc17f6 100644 --- a/Task/Lucas-Lehmer-test/Wren/lucas-lehmer-test-1.wren +++ b/Task/Lucas-Lehmer-test/Wren/lucas-lehmer-test-1.wren @@ -1,5 +1,5 @@ -import "/big" for BigInt -import "/math" for Int +import "./big" for BigInt +import "./math" for Int import "io" for Stdout var start = System.clock diff --git a/Task/Lucky-and-even-lucky-numbers/Wren/lucky-and-even-lucky-numbers.wren b/Task/Lucky-and-even-lucky-numbers/Wren/lucky-and-even-lucky-numbers.wren index 19ef8992d5..f7acfbd420 100644 --- a/Task/Lucky-and-even-lucky-numbers/Wren/lucky-and-even-lucky-numbers.wren +++ b/Task/Lucky-and-even-lucky-numbers/Wren/lucky-and-even-lucky-numbers.wren @@ -1,6 +1,6 @@ import "os" for Process -import "/iterate" for Stepped -import "/str" for Str +import "./iterate" for Stepped +import "./str" for Str var luckyOdd = List.filled(1e5, 0) var luckyEven = List.filled(1e5, 0) diff --git a/Task/Ludic-numbers/Wren/ludic-numbers.wren b/Task/Ludic-numbers/Wren/ludic-numbers.wren index 10da4894a1..2a23a3d010 100644 --- a/Task/Ludic-numbers/Wren/ludic-numbers.wren +++ b/Task/Ludic-numbers/Wren/ludic-numbers.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var ludic = Fn.new { |n, max| var maxInt32 = 2.pow(31) - 1 diff --git a/Task/Luhn-test-of-credit-card-numbers/EasyLang/luhn-test-of-credit-card-numbers.easy b/Task/Luhn-test-of-credit-card-numbers/EasyLang/luhn-test-of-credit-card-numbers.easy new file mode 100644 index 0000000000..b2c6b6e536 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/EasyLang/luhn-test-of-credit-card-numbers.easy @@ -0,0 +1,23 @@ +func luhn cc$ . + for i = len cc$ downto 1 + odd = 1 - odd + dig = number substr cc$ i 1 + if odd = 0 + dig = 2 * dig + if dig >= 10 + dig -= 9 + . + . + sum += dig + . + return if sum mod 10 = 0 +. +cc$[] = [ "49927398716" "49927398717" "1234567812345678" "1234567812345670" ] +for cc$ in cc$[] + write cc$ & " " + if luhn cc$ = 1 + print "is valid" + else + print "is not valid" + . +. diff --git a/Task/Luhn-test-of-credit-card-numbers/Refal/luhn-test-of-credit-card-numbers.refal b/Task/Luhn-test-of-credit-card-numbers/Refal/luhn-test-of-credit-card-numbers.refal new file mode 100644 index 0000000000..c232ae435f --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Refal/luhn-test-of-credit-card-numbers.refal @@ -0,0 +1,26 @@ +$ENTRY Go { + = + + + ; +}; + +Test { + e.Digits = >; +}; + +Luhn { + (s.Sum) e.Digits s.Even s.Odd, + >: s.Even2, + : (s.EvenD1) s.EvenD2, + <+ s.EvenD1 s.EvenD2>: s.EvenV, + <+ s.EvenV>: s.Step + = ) e.Digits>; + (s.Sum) s.Odd = >)>; + (s.Sum), : (s.Rest) s.Last, + s.Last: { + 0 = Valid; + s.X = Invalid; + }; + e.Digits = ; +}; diff --git a/Task/Luhn-test-of-credit-card-numbers/Wren/luhn-test-of-credit-card-numbers.wren b/Task/Luhn-test-of-credit-card-numbers/Wren/luhn-test-of-credit-card-numbers.wren index cc1ee619ea..e7e0e4e528 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Wren/luhn-test-of-credit-card-numbers.wren +++ b/Task/Luhn-test-of-credit-card-numbers/Wren/luhn-test-of-credit-card-numbers.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/iterate" for Stepped +import "./fmt" for Fmt +import "./iterate" for Stepped var luhn = Fn.new { |s| // reverse digits @@ -18,5 +18,5 @@ var luhn = Fn.new { |s| var tests = [ "49927398716", "49927398717", "1234567812345678", "1234567812345670"] for (test in tests) { var ans = (luhn.call(test)) ? "pass" : "fail" - System.print("%(Fmt.s(-16, test)) -> %(ans)") + Fmt.print("$-16s -> $s", test, ans) } diff --git a/Task/Lychrel-numbers/Wren/lychrel-numbers.wren b/Task/Lychrel-numbers/Wren/lychrel-numbers.wren index e3475af2a7..c3a10d72e0 100644 --- a/Task/Lychrel-numbers/Wren/lychrel-numbers.wren +++ b/Task/Lychrel-numbers/Wren/lychrel-numbers.wren @@ -1,5 +1,5 @@ -import "/big" for BigInt -import "/set" for Set +import "./big" for BigInt +import "./set" for Set var iterations = 500 var limit = 10000 diff --git a/Task/M-bius-function/PARI-GP/m-bius-function.parigp b/Task/M-bius-function/PARI-GP/m-bius-function.parigp new file mode 100644 index 0000000000..fb6639b8fb --- /dev/null +++ b/Task/M-bius-function/PARI-GP/m-bius-function.parigp @@ -0,0 +1,6 @@ +{ + for(i = 1, 99, + print1(moebius(i) " "); + if(i % 10 == 0, print("\n");); + ); +} diff --git a/Task/M-bius-function/Wren/m-bius-function.wren b/Task/M-bius-function/Wren/m-bius-function.wren index b7355b0331..e51dca962e 100644 --- a/Task/M-bius-function/Wren/m-bius-function.wren +++ b/Task/M-bius-function/Wren/m-bius-function.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/math" for Int +import "./fmt" for Fmt +import "./math" for Int var isSquareFree = Fn.new { |n| var i = 2 @@ -26,7 +26,7 @@ for (i in 0..9) { if (i == 0 && j == 0) { System.write(" ") } else { - System.write("%(Fmt.dm(3, mu.call(i*20 + j))) ") + Fmt.write("$ 3d ", mu.call(i*20 + j)) } } System.print() diff --git a/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-1.wren b/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-1.wren index 6c514ff02d..b0b7b61e76 100644 --- a/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-1.wren +++ b/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-1.wren @@ -1,4 +1,4 @@ -/* mac_vendor_lookup.wren */ +/* MAC_vendor_lookup.wren */ class MAC { foreign static lookup(address) } diff --git a/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-2.wren b/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-2.wren index 5b9faf37cb..cdd00e14b6 100644 --- a/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-2.wren +++ b/Task/MAC-vendor-lookup/Wren/mac-vendor-lookup-2.wren @@ -1,4 +1,4 @@ -/* mac_vendor_lookup.go */ +/* MAC_vendor_lookup.go */ package main import ( @@ -28,7 +28,7 @@ func macLookup(vm *wren.VM, parameters []any) (any, error) { func main() { vm := wren.NewVM() - fileName := "mac_vendor_lookup.wren" + fileName := "MAC_vendor_lookup.wren" methodMap := wren.MethodMap{"static lookup(_)": macLookup} classMap := wren.ClassMap{"MAC": wren.NewClass(nil, nil, methodMap)} module := wren.NewModule(classMap) diff --git a/Task/MD4/Raku/md4.raku b/Task/MD4/Raku/md4.raku index 72a13698e9..e917bfb756 100644 --- a/Task/MD4/Raku/md4.raku +++ b/Task/MD4/Raku/md4.raku @@ -3,7 +3,8 @@ sub md4($str) { my $buf-length = $buf.elems; $buf.push: 0x80; $buf.push: 0 until ($buf - (448 div 8)) %% (512 div 8); - $buf.write-uint64: $buf.elems, $buf-length*8, LittleEndian; + # raku serializes in little endian by default + $buf.write-uint64: $buf.elems, $buf-length*8; my (&f, &g, &h, &r) = { $^x +& $^y +| +^$x +& $^z }, @@ -14,37 +15,34 @@ sub md4($str) { my uint32 ($a, $b, $c, $d) = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476; - for @$buf.rotor(64) { - my uint32 @x = .rotor(4).map: {:256[.reverse]} - + loop (my $pos = 0; $pos < $buf.elems; $pos+=64) { my ($aa, $bb, $cc, $dd) = $a, $b, $c, $d; for 0, 4, 8, 12 -> $i { - $a = r($a + f($b, $c, $d) + @x[ $i+0 ], 3); - $d = r($d + f($a, $b, $c) + @x[ $i+1 ], 7); - $c = r($c + f($d, $a, $b) + @x[ $i+2 ], 11); - $b = r($b + f($c, $d, $a) + @x[ $i+3 ], 19); + $a = r($a + f($b, $c, $d) + $buf.read-uint32($pos+($i+0)*4), 3); + $d = r($d + f($a, $b, $c) + $buf.read-uint32($pos+($i+1)*4), 7); + $c = r($c + f($d, $a, $b) + $buf.read-uint32($pos+($i+2)*4), 11); + $b = r($b + f($c, $d, $a) + $buf.read-uint32($pos+($i+3)*4), 19); } for 0, 1, 2, 3 -> $i { - $a = r($a + g($b, $c, $d) + @x[ $i+0 ] + 0x5a827999, 3); - $d = r($d + g($a, $b, $c) + @x[ $i+4 ] + 0x5a827999, 5); - $c = r($c + g($d, $a, $b) + @x[ $i+8 ] + 0x5a827999, 9); - $b = r($b + g($c, $d, $a) + @x[ $i+12] + 0x5a827999, 13); + $a = r($a + g($b, $c, $d) + $buf.read-uint32($pos+($i+0 )*4) + 0x5a827999, 3); + $d = r($d + g($a, $b, $c) + $buf.read-uint32($pos+($i+4 )*4) + 0x5a827999, 5); + $c = r($c + g($d, $a, $b) + $buf.read-uint32($pos+($i+8 )*4) + 0x5a827999, 9); + $b = r($b + g($c, $d, $a) + $buf.read-uint32($pos+($i+12)*4) + 0x5a827999, 13); } for 0, 2, 1, 3 -> $i { - $a = r($a + h($b, $c, $d) + @x[ $i+0 ] + 0x6ed9eba1, 3); - $d = r($d + h($a, $b, $c) + @x[ $i+8 ] + 0x6ed9eba1, 9); - $c = r($c + h($d, $a, $b) + @x[ $i+4 ] + 0x6ed9eba1, 11); - $b = r($b + h($c, $d, $a) + @x[ $i+12] + 0x6ed9eba1, 15); + $a = r($a + h($b, $c, $d) + $buf.read-uint32($pos+($i+0 )*4) + 0x6ed9eba1, 3); + $d = r($d + h($a, $b, $c) + $buf.read-uint32($pos+($i+4 )*4) + 0x6ed9eba1, 9); + $c = r($c + h($d, $a, $b) + $buf.read-uint32($pos+($i+8 )*4) + 0x6ed9eba1, 11); + $b = r($b + h($c, $d, $a) + $buf.read-uint32($pos+($i+12)*4) + 0x6ed9eba1, 15); } ($a,$b,$c,$d) Z[+=] ($aa,$bb,$cc,$dd); } - my buf8 $abcd .= new; - for $a, $b, $c, $d { $abcd.write-uint32: 4*$++, $_, LittleEndian } - blob8.new: $abcd; + reduce { $^buf.write-uint32: $buf.elems, $^x; $buf }, buf8.new, $a, $b, $c, $d; } -sub MAIN { - my $str = 'Rosetta Code'; - say md4($str); +CHECK { + use Test; + plan 1; + is md4('Rosetta Code').list.fmt('%02X'), 'A5 2B CF C6 A0 D0 D3 00 CD C5 DD BF BE FE 47 8B'; } diff --git a/Task/MD4/Wren/md4.wren b/Task/MD4/Wren/md4.wren index b7af0d2862..087f14c2b6 100644 --- a/Task/MD4/Wren/md4.wren +++ b/Task/MD4/Wren/md4.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var toBytes = Fn.new { |val| var bytes = List.filled(4, 0) diff --git a/Task/MD5-Implementation/11l/md5-implementation.11l b/Task/MD5-Implementation/11l/md5-implementation.11l index a65e489d98..61942b1b16 100644 --- a/Task/MD5-Implementation/11l/md5-implementation.11l +++ b/Task/MD5-Implementation/11l/md5-implementation.11l @@ -9,10 +9,10 @@ init_values = (UInt32(6745'2301), UInt32(EFCD'AB89), UInt32(98BA'DCFE), UInt32(1032'5476)) [((UInt32, UInt32, UInt32) -> UInt32)] functions -functions [+]= (b, c, d) -> (b [&] c) [|] ((-)b [&] d) -functions [+]= (b, c, d) -> (d [&] b) [|] ((-)d [&] c) +functions [+]= (b, c, d) -> (b [&] c) [|] (~b [&] d) +functions [+]= (b, c, d) -> (d [&] b) [|] (~d [&] c) functions [+]= (b, c, d) -> b (+) c (+) d -functions [+]= (b, c, d) -> c (+) (b [|] (-)d) +functions [+]= (b, c, d) -> c (+) (b [|] ~d) [(Int -> Int)] index_functions index_functions [+]= i -> i diff --git a/Task/MD5-Implementation/Raku/md5-implementation.raku b/Task/MD5-Implementation/Raku/md5-implementation.raku index e22359b0d0..7d3d56b8c0 100644 --- a/Task/MD5-Implementation/Raku/md5-implementation.raku +++ b/Task/MD5-Implementation/Raku/md5-implementation.raku @@ -1,24 +1,25 @@ proto md5($msg) returns Blob is export {*} multi md5(Str $msg) { md5 $msg.encode } multi md5(Blob $msg) { - sub rotl(uint32 \x, \n) returns uint32 { (x +< n) +| (x +> (32-n)) } - sub little-endian($w, $n, *@v) { (@v X+> flat ($w X* ^$n)) X% (2 ** $w) } my \bits = 8 * $msg.elems; - Blob.new: little-endian 8, 4, - |reduce -> Blob $blob, blob32 $X { + my buf8 $buf .= new; + $buf.write-uint32: $buf.elems, $_, LittleEndian for + reduce -> Blob $blob, blob32 $X { blob32.new: $blob Z+ reduce -> $b, $i { blob32.new: $b[3], - $b[1] + rotl( - $b[0] + (BEGIN Array.new: + $b[1] + + -> uint32 \x, \n { (x +< n) +| (x +> (32-n)) }( + ($b[0] + (BEGIN Array.new: { ($^x +& $^y) +| (+^$x +& $^z) }, { ($^x +& $^z) +| ($^y +& +^$z) }, { $^x +^ $^y +^ $^z }, { $^y +^ ($^x +| +^$^z) } )[$i div 16](|$b[1..3]) + (BEGIN blob32.new: map &floor ∘ * * 2**32 ∘ &abs ∘ &sin ∘ * + 1, ^64)[$i] + - $X[(BEGIN Blob.new: 16 X[R%] flat ($++, 5*$++ + 1, 3*$++ + 5, 7*$++) Xxx 16)[$i]], + $X[(BEGIN Blob.new: 16 X[R%] flat ($++, 5*$++ + 1, 3*$++ + 5, 7*$++) Xxx 16)[$i]] + ) mod 2**32, (BEGIN flat < 7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21 >.rotor(4) Xxx 4)[$i] ), $b[1], @@ -27,10 +28,14 @@ multi md5(Blob $msg) { }, (BEGIN blob32.new: 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476), |map { blob32.new: @$_ }, - blob32.new(flat(@$msg, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64)) - .rotor(4).map({ :256[@^a.reverse] }), little-endian(32, 2, bits) - ) + { + $^b.push(blob8.new(@$_).read-uint32(0)) for (@$msg, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64)) + .flat.rotor(4); + $b.write-uint64: $b.elems, bits, LittleEndian; + $b; + }(buf32.new) .rotor(16); + $buf; } CHECK { diff --git a/Task/MD5-Implementation/Scala/md5-implementation.scala b/Task/MD5-Implementation/Scala/md5-implementation.scala index 6fb43f4de3..f1d7a14e4b 100644 --- a/Task/MD5-Implementation/Scala/md5-implementation.scala +++ b/Task/MD5-Implementation/Scala/md5-implementation.scala @@ -1,20 +1,103 @@ -object MD5 extends App { +import java.lang.Math - def hash(s: String) = { - def b = s.getBytes("UTF-8") +object MD5 { + private val INIT_A = 0x67452301 + private val INIT_B = 0xEFCDAB89 + private val INIT_C = 0x98BADCFE + private val INIT_D = 0x10325476 - def m = java.security.MessageDigest.getInstance("MD5").digest(b) + private val SHIFT_AMTS = Array( + 7, 12, 17, 22, + 5, 9, 14, 20, + 4, 11, 16, 23, + 6, 10, 15, 21 + ) - BigInt(1, m).toString(16).reverse.padTo(32, "0").reverse.mkString + private val TABLE_T = Array.tabulate(64)(i => (Math.abs(Math.sin(i + 1)) * (1L << 32)).toLong.toInt) + + def computeMD5(message: Array[Byte]): Array[Byte] = { + val messageLenBytes = message.length + val numBlocks = ((messageLenBytes + 8) >>> 6) + 1 + val totalLen = numBlocks << 6 + val paddingBytes = Array.fill[Byte](totalLen - messageLenBytes)(0) + paddingBytes(0) = 0x80.toByte + + var messageLenBits = messageLenBytes.toLong << 3 + for (i <- 0 until 8) { + paddingBytes(paddingBytes.length - 8 + i) = messageLenBits.toByte + messageLenBits >>>= 8 + } + + var a = INIT_A + var b = INIT_B + var c = INIT_C + var d = INIT_D + val buffer = new Array[Int](16) + + for (i <- 0 until numBlocks) { + var index = i << 6 + for (j <- 0 until 64) { + buffer(j >>> 2) = (((if (index < messageLenBytes) message(index) else paddingBytes(index - messageLenBytes)) << 24) | (buffer(j >>> 2) >>> 8)).toInt + index += 1 + } + val originalA = a + val originalB = b + val originalC = c + val originalD = d + + for (j <- 0 until 64) { + val div16 = j >>> 4 + val bufferIndex = j match { + case j if j < 16 => j + case j if j < 32 => (j * 5 + 1) & 0x0F + case j if j < 48 => (j * 3 + 5) & 0x0F + case j => (j * 7) & 0x0F + } + + val f = div16 match { + case 0 => (b & c) | (~b & d) + case 1 => (b & d) | (c & ~d) + case 2 => b ^ c ^ d + case 3 => c ^ (b | ~d) + } + + val temp = b + Integer.rotateLeft(a + f + buffer(bufferIndex) + TABLE_T(j), SHIFT_AMTS((div16 << 2) | (j & 3))) + a = d + d = c + c = b + b = temp + } + + a += originalA + b += originalB + c += originalC + d += originalD + } + + val md5 = new Array[Byte](16) + var count = 0 + for (i <- 0 until 4) { + var n = i match { + case 0 => a + case 1 => b + case 2 => c + case 3 => d + } + for (j <- 0 until 4) { + md5(count) = n.toByte + n >>>= 8 + count += 1 + } + } + md5 } - assert("d41d8cd98f00b204e9800998ecf8427e" == hash("")) - assert("0000045c5e2b3911eb937d9d8c574f09" == hash("iwrupvqb346386")) - assert("0cc175b9c0f1b6a831c399e269772661" == hash("a")) - assert("900150983cd24fb0d6963f7d28e17f72" == hash("abc")) - assert("f96b697d7cb7938d525a2f31aaf161d0" == hash("message digest")) - assert("c3fcd3d76192e4007dfb496cca67e13b" == hash("abcdefghijklmnopqrstuvwxyz")) - assert("d174ab98d277d9f5a5611c2c9f419d9f" == hash("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")) - assert("57edf4a22be3c955ac49da2e2107b67a" == hash("12345678901234567890123456789012345678901234567890123456789012345678901234567890")) + def toHexString(b: Array[Byte]): String = b.map(byte => f"$byte%02X").mkString + def main(args: Array[String]): Unit = { + val testStrings = Array("", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890") + testStrings.foreach { s => + println(s"0x${toHexString(computeMD5(s.getBytes))} <== \"$s\"") + } + } } diff --git a/Task/MD5-Implementation/Wren/md5-implementation.wren b/Task/MD5-Implementation/Wren/md5-implementation.wren index c590f39693..27ade1c0cc 100644 --- a/Task/MD5-Implementation/Wren/md5-implementation.wren +++ b/Task/MD5-Implementation/Wren/md5-implementation.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var k = [ 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee , diff --git a/Task/MD5/EasyLang/md5.easy b/Task/MD5/EasyLang/md5.easy new file mode 100644 index 0000000000..727b788834 --- /dev/null +++ b/Task/MD5/EasyLang/md5.easy @@ -0,0 +1,93 @@ +len md5k[] 64 +proc md5init . . + for i = 1 to 64 + md5k[i] = floor (0x100000000 * abs sin (i * 180 / pi)) + . +. +md5init +# +func$ md5 inp$ . + subr addinp + if inp4 = 1 + inp[] &= 0 + . + inp[len inp[]] += b * inp4 + inp4 *= 0x100 + if inp4 = 0x100000000 + inp4 = 1 + . + . + s[] = [ 7 12 17 22 7 12 17 22 7 12 17 22 7 12 17 22 5 9 14 20 5 9 14 20 5 9 14 20 5 9 14 20 4 11 16 23 4 11 16 23 4 11 16 23 4 11 16 23 6 10 15 21 6 10 15 21 6 10 15 21 6 10 15 21 ] + inp[] = [ ] + inp4 = 1 + for i = 1 to len inp$ + b = strcode substr inp$ i 1 + addinp + . + b = 0x80 + addinp + while len inp[] mod 16 <> 14 or inp4 <> 1 + b = 0 + addinp + . + h = len inp$ * 8 + for i = 1 to 4 + b = h mod 0x100 + addinp + h = h div 0x100 + . + inp[] &= 0 + # + a0 = 0x67452301 + b0 = 0xefcdab89 + c0 = 0x98badcfe + d0 = 0x10325476 + for chunk = 1 step 16 to len inp[] - 15 + a = a0 ; b = b0 ; c = c0 ; d = d0 + for i = 1 to 64 + if i <= 16 + h1 = bitand b c + h2 = bitand bitnot b d + f = bitor h1 h2 + g = i - 1 + elif i <= 32 + h1 = bitand d b + h2 = bitand bitnot d c + f = bitor h1 h2 + g = (5 * i - 4) mod 16 + elif i <= 48 + h1 = bitxor b c + f = bitxor h1 d + g = (3 * i + 2) mod 16 + else + h1 = bitor b bitnot d + f = bitxor c h1 + g = (7 * i - 7) mod 16 + . + f = (f + a + md5k[i] + inp[chunk + g]) + a = d + d = c + c = b + h1 = bitshift f s[i] + h2 = bitshift f (s[i] - 32) + b = (b + h1 + h2) + . + a0 += a ; b0 += b ; c0 += c ; d0 += d + . + for a in [ a0 b0 c0 d0 ] + for i = 1 to 4 + b = a mod 256 + a = a div 256 + for h in [ b div 16 b mod 16 ] + h += 48 + if h > 57 + h += 39 + . + s$ &= strchar h + . + . + . + return s$ +. +# +print md5 "The quick brown fox jumped over the lazy dog's back" diff --git a/Task/MD5/Wren/md5.wren b/Task/MD5/Wren/md5.wren index edd40a4665..7b848d62c2 100644 --- a/Task/MD5/Wren/md5.wren +++ b/Task/MD5/Wren/md5.wren @@ -1,5 +1,5 @@ -import "/crypto" for Md5 -import "/fmt" for Fmt +import "./crypto" for Md5 +import "./fmt" for Fmt var strings = [ "The quick brown fox jumps over the lazy dog", diff --git a/Task/Machine-code/Wren/machine-code-1.wren b/Task/Machine-code/Wren/machine-code-1.wren index 4192fb8a02..7d867f30c5 100644 --- a/Task/Machine-code/Wren/machine-code-1.wren +++ b/Task/Machine-code/Wren/machine-code-1.wren @@ -1,4 +1,4 @@ -/* machine_code.wren */ +/* Machine_code.wren */ class C { // pass the machine code in string form to the host diff --git a/Task/Machine-code/Wren/machine-code-2.wren b/Task/Machine-code/Wren/machine-code-2.wren index 6e95df44a7..22d6a1fc45 100644 --- a/Task/Machine-code/Wren/machine-code-2.wren +++ b/Task/Machine-code/Wren/machine-code-2.wren @@ -1,3 +1,5 @@ +/* gcc Machine_code.c -o Machine_code -lwren -lm */ + #include #include #include @@ -24,13 +26,13 @@ unsigned char rmc_helper(const char *code, unsigned char a, unsigned char b, int void C_runMachineCode(WrenVM* vm) { /* unpack arguments passed from Wren */ - int *len; - const char *code = wrenGetSlotBytes(vm, 1, len); + int len; + const char *code = wrenGetSlotBytes(vm, 1, &len); unsigned char a = (unsigned char)wrenGetSlotDouble(vm, 2); unsigned char b = (unsigned char)wrenGetSlotDouble(vm, 3); /* obtain result */ - unsigned char c = rmc_helper(code, a, b, *len); + unsigned char c = rmc_helper(code, a, b, len); /* return result to Wren */ wrenSetSlotDouble(vm, 0, (double)c); @@ -90,7 +92,7 @@ int main() { config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "machine_code.wren"; + const char* fileName = "Machine_code.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Mad-Libs/Wren/mad-libs.wren b/Task/Mad-Libs/Wren/mad-libs.wren index 5de76e12e0..7e73d4d6e4 100644 --- a/Task/Mad-Libs/Wren/mad-libs.wren +++ b/Task/Mad-Libs/Wren/mad-libs.wren @@ -1,6 +1,6 @@ import "io" for Stdin, Stdout -import "/pattern" for Pattern -import "/seq" for Lst +import "./pattern" for Pattern +import "./seq" for Lst System.print("Please enter a multi-line story template terminated by a blank line:\n") Stdout.flush() diff --git a/Task/Magic-8-ball/EasyLang/magic-8-ball.easy b/Task/Magic-8-ball/EasyLang/magic-8-ball.easy new file mode 100644 index 0000000000..7f793ae08f --- /dev/null +++ b/Task/Magic-8-ball/EasyLang/magic-8-ball.easy @@ -0,0 +1,8 @@ +answers$[] = [ "It is certain" "It is decidedly so" "Without a doubt" "Yes, definitely" "You may rely on it" "As I see it, yes" "Most likely" "Outlook good" "Signs point to yes" "Yes" "Reply hazy, try again" "Ask again later" "Better not tell you now" "Cannot predict now" "Concentrate and ask again" "Don't bet on it" "My reply is no" "My sources say no" "Outlook not so good" "Very doubtful" ] +print "q to quit." +repeat + print "What would you like to know? " + q$ = input + until q$ = "q" + print answers$[randint len answers$[]] +. diff --git a/Task/Magic-8-ball/UNIX-Shell/magic-8-ball.sh b/Task/Magic-8-ball/UNIX-Shell/magic-8-ball.sh index 1d575f5a42..ec32205a81 100644 --- a/Task/Magic-8-ball/UNIX-Shell/magic-8-ball.sh +++ b/Task/Magic-8-ball/UNIX-Shell/magic-8-ball.sh @@ -1,6 +1,6 @@ #!/bin/bash -RESPONSES=("It is certain" "It is decidedly so" "Without a doubt" +declare -ra RESPONSES=("It is certain" "It is decidedly so" "Without a doubt" "Yes definitely" "You may rely on it" "As I see it yes" "Most likely" "Outlook good" "Signs point to yes" "Yes" "Reply hazy try again" "Ask again later" @@ -12,13 +12,8 @@ RESPONSES=("It is certain" "It is decidedly so" "Without a doubt" printf "Welcome to 8 ball! Enter your questions using the prompt below to find the answers you seek. Type 'quit' to exit.\n\n" -while true; do - read -p 'Enter Question: ' question - if [ "$question" == "quit" ]; then - exit 0 - fi - - response_index=$(($RANDOM % 20)) - - printf "Response: ${RESPONSES[response_index]}\n\n" +until + read -p 'Enter Question: ' + [[ "$REPLY" == quit ]] +do printf "Response: %s\n\n" "${RESPONSES[RANDOM % ${#RESPONSES[@]}]}" done diff --git a/Task/Magic-constant/C-sharp/magic-constant.cs b/Task/Magic-constant/C-sharp/magic-constant.cs new file mode 100644 index 0000000000..7b25365c5c --- /dev/null +++ b/Task/Magic-constant/C-sharp/magic-constant.cs @@ -0,0 +1,37 @@ +using System; + +public class MagicConstant { + + private const int OrderFirstMagicSquare = 3; + + public static void Main(string[] args) { + Console.WriteLine("The first 20 magic constants:"); + for (int i = 1; i <= 20; i++) { + Console.Write(" " + MagicConstantValue(Order(i))); + } + Console.WriteLine("\n"); + + Console.WriteLine("The 1,000th magic constant: " + MagicConstantValue(Order(1_000)) + "\n"); + + Console.WriteLine("Order of the smallest magic square whose constant is greater than:"); + for (int i = 1; i <= 20; i++) { + string powerOf10 = "10^" + i + ":"; + Console.WriteLine($"{powerOf10,6}{MinimumOrder(i),8}"); + } + } + + // Return the magic constant for a magic square of the given order + private static int MagicConstantValue(int n) { + return n * (n * n + 1) / 2; + } + + // Return the smallest order of a magic square such that its magic constant is greater than 10 to the given power + private static int MinimumOrder(int n) { + return (int)Math.Exp((Math.Log(2.0)+ n * Math.Log(10.0)) / 3) + 1; + } + + // Return the order of the magic square at the given index + private static int Order(int index) { + return OrderFirstMagicSquare + index - 1; + } +} diff --git a/Task/Magic-constant/EasyLang/magic-constant.easy b/Task/Magic-constant/EasyLang/magic-constant.easy new file mode 100644 index 0000000000..e2e585dfa2 --- /dev/null +++ b/Task/Magic-constant/EasyLang/magic-constant.easy @@ -0,0 +1,22 @@ +func a n . + n += 2 + return n * (n * n + 1) / 2 +. +func inva x . + while k * (k * k + 1) / 2 + 2 < x + k += 1 + . + return k +. +write "The first 20 magic constants: " +for n to 20 + write a n & " " +. +print "" +print "" +print "The 1,000th magic constant: " & a 1000 +print "" +print "Smallest magic square with constant greater than:" +for e to 10 + print "10^" & e & ": " & inva pow 10 e +. diff --git a/Task/Magic-squares-of-doubly-even-order/Elena/magic-squares-of-doubly-even-order.elena b/Task/Magic-squares-of-doubly-even-order/Elena/magic-squares-of-doubly-even-order.elena index d00164a30a..8240376b5f 100644 --- a/Task/Magic-squares-of-doubly-even-order/Elena/magic-squares-of-doubly-even-order.elena +++ b/Task/Magic-squares-of-doubly-even-order/Elena/magic-squares-of-doubly-even-order.elena @@ -5,7 +5,7 @@ import extensions'routines; MagicSquareDoublyEven(int n) { if(n < 4 || n.mod(4) != 0) - { InvalidArgumentException.new:"base must be a positive multiple of 4".raise() }; + { InvalidArgumentException.new("base must be a positive multiple of 4").raise() }; int bits := 09669h; int size := n * n; @@ -13,9 +13,9 @@ MagicSquareDoublyEven(int n) var result := IntMatrix.allocate(n,n); int i := 0; - for (int r := 0, r < n, r += 1) + for (int r := 0; r < n; r += 1) { - for(int c := 0, c < n, c += 1, i += 1) + for(int c := 0; c < n; c += 1; i += 1) { int bitPos := c / mult + (r / mult) * 4; diff --git a/Task/Magic-squares-of-doubly-even-order/Wren/magic-squares-of-doubly-even-order.wren b/Task/Magic-squares-of-doubly-even-order/Wren/magic-squares-of-doubly-even-order.wren index c3661305e7..d4e287be73 100644 --- a/Task/Magic-squares-of-doubly-even-order/Wren/magic-squares-of-doubly-even-order.wren +++ b/Task/Magic-squares-of-doubly-even-order/Wren/magic-squares-of-doubly-even-order.wren @@ -1,4 +1,4 @@ -import "/fmt" for Conv, Fmt +import "./fmt" for Conv, Fmt var magicSquareDoublyEven = Fn.new { |n| if (n < 4 || n%4 != 0) Fiber.abort("Base must be a positive multiple of 4") diff --git a/Task/Magic-squares-of-odd-order/EasyLang/magic-squares-of-odd-order.easy b/Task/Magic-squares-of-odd-order/EasyLang/magic-squares-of-odd-order.easy new file mode 100644 index 0000000000..2a148fff4f --- /dev/null +++ b/Task/Magic-squares-of-odd-order/EasyLang/magic-squares-of-odd-order.easy @@ -0,0 +1,13 @@ +func f n x y . + return (x + y * 2 + 1) mod n +. +numfmt 0 3 +proc msqr n . . + for i = 0 to n - 1 + for j = 0 to n - 1 + write f n (n - j - 1) i * n + f n j i + 1 + . + print "" + . +. +msqr 5 diff --git a/Task/Magic-squares-of-odd-order/Wren/magic-squares-of-odd-order.wren b/Task/Magic-squares-of-odd-order/Wren/magic-squares-of-odd-order.wren index 8bee508b1d..d7456b7347 100644 --- a/Task/Magic-squares-of-odd-order/Wren/magic-squares-of-odd-order.wren +++ b/Task/Magic-squares-of-odd-order/Wren/magic-squares-of-odd-order.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var ms = Fn.new { |n| var M = Fn.new { |x| (x + n - 1) % n } @@ -25,7 +25,7 @@ var res = ms.call(5) var n = res[0] var m = res[1] for (i in 0...n) { - for (j in 0...n) System.write(Fmt.d(4, m[i*n+j])) + for (j in 0...n) Fmt.write("$4d", m[i*n+j]) System.print() } System.print("\nMagic number : %(((n*n + 1)/2).floor * n)") diff --git a/Task/Magic-squares-of-singly-even-order/ALGOL-68/magic-squares-of-singly-even-order.alg b/Task/Magic-squares-of-singly-even-order/ALGOL-68/magic-squares-of-singly-even-order.alg new file mode 100644 index 0000000000..2a51083b48 --- /dev/null +++ b/Task/Magic-squares-of-singly-even-order/ALGOL-68/magic-squares-of-singly-even-order.alg @@ -0,0 +1,112 @@ +BEGIN # construct a magic square of singly even order # + # the singly even magic square procedure is translated from the Java # + # sample # + + CO begin code from the magic squares of odd order task CO + + # construct a magic square of odd order # + PROC odd magic square = ( INT order ) [,]INT: + IF NOT ODD order OR order < 1 THEN + # can't make a magic square of the specified order # + LOC[ 1 : 0, 1 : 0 ]INT + ELSE + # order is OK - construct the square using de la Loubère's # + # algorithm as in the wikipedia page # + + [ 1 : order, 1 : order ]INT square; + FOR i TO order DO FOR j TO order DO square[ i, j ] := 0 OD OD; + + # operator to advance "up" the square # + OP PREV = ( INT pos )INT: IF pos = 1 THEN order ELSE pos - 1 FI; + # operator to advance "across right" or "down" the square # + OP NEXT = ( INT pos )INT: ( pos MOD order ) + 1; + + # fill in the square, starting from the middle of the top row # + INT col := ( order + 1 ) OVER 2; + INT row := 1; + FOR i TO order * order DO + square[ row, col ] := i; + IF square[ PREV row, NEXT col ] /= 0 THEN + # the up/right position is already taken, move down # + row := NEXT row + ELSE + # can move up and right # + row := PREV row; + col := NEXT col + FI + OD; + + square + FI # odd magic square # ; + + PROC print square = ( [,]INT square )VOID: # prints the magic square # + BEGIN + + INT order = 1 UPB square; + + # calculate print width: negative so leading "+"s aren't printed # + INT width := -1; + INT mag := order * order; + WHILE mag >= 10 DO mag OVERAB 10; width -:= 1 OD; + + # calculate the "magic sum" # + INT sum := 0; + FOR i TO order DO sum +:= square[ 1, i ] OD; + + # print the square # + print( ( "maqic square of order ", whole( order, 0 ) ) ); + print( ( ": sum: ", whole( sum, 0 ), newline ) ); + FOR i TO order DO + FOR j TO order DO write( ( " ", whole( square[ i, j ], width ) ) ) OD; + print( ( newline ) ) + OD + + END # print square # ; + + CO end code from the magic squares of odd order task CO + + # returns a magic square of singly even order n # + PROC singly even magic square = ( INT n )[,]INT: + IF n < 6 OR ( n - 2 ) MOD 4 /= 0 THEN + LOC[ 1 : 0, 1 : 0 ]INT # n is not 2 + a multiple of 4 >= 6 # + ELSE + # order is OK # + INT size = n * n; + INT half n = n OVER 2; + INT sub square size = size OVER 4; + + [,]INT sub square = odd magic square( half n )[ AT 0, AT 0 ]; + []INT quadrant factors = []INT( 0, 2, 3, 1 )[ AT 0 ]; + [ 0 : n - 1, 0 : n - 1 ]INT result; + + FOR r FROM 1 LWB result TO 1 UPB result DO + FOR c FROM 2 LWB result TO 2 UPB result DO + INT quadrant = ( r OVER half n ) * 2 + ( c OVER half n ); + result[ r, c ] := sub square[ r MOD half n, c MOD half n ] + + quadrant factors[ quadrant ] * sub square size + OD + OD; + + INT n cols left = half n OVER 2; + INT n cols right = n cols left - 1; + + FOR r FROM 1 LWB result TO half n - 1 DO + FOR c FROM 1 LWB result TO 1 UPB result DO + IF c < n cols left OR c >= n - n cols right + OR ( c = n cols left AND r = n cols left ) + THEN + IF c /= 0 OR r /= n cols left THEN + INT tmp = result[ r, c ]; + result[ r, c ] := result[ r + half n, c ]; + result[ r + half n, c ] := tmp + FI + FI + OD + OD; + + result[ AT 1, AT 1 ] + FI # singly even magic square # ; + + print square( singly even magic square( 6 ) ) + +END diff --git a/Task/Magic-squares-of-singly-even-order/C-sharp/magic-squares-of-singly-even-order.cs b/Task/Magic-squares-of-singly-even-order/C-sharp/magic-squares-of-singly-even-order.cs new file mode 100644 index 0000000000..c7b8326999 --- /dev/null +++ b/Task/Magic-squares-of-singly-even-order/C-sharp/magic-squares-of-singly-even-order.cs @@ -0,0 +1,81 @@ +using System; + +class MagicSquare { + public static int[,] MagicSquareOdd(int n) { + if (n < 3 || n % 2 == 0) { + throw new ArgumentException("Base must be odd and > 2"); + } + int value = 1; + int gridSize = n * n; + int c = n / 2, r = 0; + int[,] result = new int[n, n]; + + while (value <= gridSize) { + result[r, c] = value; + int newR = r == 0 ? n - 1 : r - 1; + int newC = c == n - 1 ? 0 : c + 1; + if (result[newR, newC] != 0) { + r++; + } else { + r = newR; + c = newC; + } + value++; + } + + return result; + } + + public static int[,] MagicSquareSinglyEven(int n) { + if (n < 6 || (n - 2) % 4 != 0) { + throw new ArgumentException("Base must be a positive multiple of 4 plus 2"); + } + + int size = n * n; + int halfN = n / 2; + int subSquareSize = size / 4; + int[,] subSquare = MagicSquareOdd(halfN); + int[] quadrantFactors = new int[] {0, 2, 3, 1}; + int[,] result = new int[n, n]; + + for (int r = 0; r < n; r++) { + for (int c = 0; c < n; c++) { + int quadrant = (r / halfN) * 2 + (c / halfN); + result[r, c] = subSquare[r % halfN, c % halfN] + quadrantFactors[quadrant] * subSquareSize; + } + } + + int nColsLeft = halfN / 2; + int nColsRight = nColsLeft - 1; + + for (int r = 0; r < halfN; r++) { + for (int c = 0; c < n; c++) { + if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { + if (!(c == 0 && r == nColsLeft)) { + int tmp = result[r, c]; + result[r, c] = result[r + halfN, c]; + result[r + halfN, c] = tmp; + } + } + } + } + + return result; + } + + static void Main(string[] args) { + const int n = 6; + try { + var msse = MagicSquareSinglyEven(n); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + Console.Write($"{msse[i, j],2} "); + } + Console.WriteLine(); + } + Console.WriteLine($"\nMagic constant: {(n * n + 1) * n / 2}"); + } catch (Exception ex) { + Console.WriteLine(ex.Message); + } + } +} diff --git a/Task/Magic-squares-of-singly-even-order/Wren/magic-squares-of-singly-even-order.wren b/Task/Magic-squares-of-singly-even-order/Wren/magic-squares-of-singly-even-order.wren index 4749ead386..f59d86a4d9 100644 --- a/Task/Magic-squares-of-singly-even-order/Wren/magic-squares-of-singly-even-order.wren +++ b/Task/Magic-squares-of-singly-even-order/Wren/magic-squares-of-singly-even-order.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var magicSquareOdd = Fn.new { |n| if (n < 3 || n%2 == 0) Fiber.abort("Base must be odd and > 2") diff --git a/Task/Magnanimous-numbers/Wren/magnanimous-numbers.wren b/Task/Magnanimous-numbers/Wren/magnanimous-numbers.wren index d07951aa97..d2f08a815f 100644 --- a/Task/Magnanimous-numbers/Wren/magnanimous-numbers.wren +++ b/Task/Magnanimous-numbers/Wren/magnanimous-numbers.wren @@ -1,5 +1,5 @@ -import "/fmt" for Conv, Fmt -import "/math" for Int +import "./fmt" for Conv, Fmt +import "./math" for Int var isMagnanimous = Fn.new { |n| if (n < 10) return true diff --git a/Task/Main-step-of-GOST-28147-89/C-sharp/main-step-of-gost-28147-89.cs b/Task/Main-step-of-GOST-28147-89/C-sharp/main-step-of-gost-28147-89.cs new file mode 100644 index 0000000000..6963291be8 --- /dev/null +++ b/Task/Main-step-of-GOST-28147-89/C-sharp/main-step-of-gost-28147-89.cs @@ -0,0 +1,96 @@ +using System; + +class Gost +{ + private byte[,] sBox = new byte[8, 16]; + private byte[] k87 = new byte[256]; + private byte[] k65 = new byte[256]; + private byte[] k43 = new byte[256]; + private byte[] k21 = new byte[256]; + private byte[] enc = new byte[8]; + + public Gost(byte[,] s) + { + sBox = s; + for (int i = 0; i < 256; i++) + { + k87[i] = (byte)((sBox[7, i >> 4] << 4) | sBox[6, i & 15]); + k65[i] = (byte)((sBox[5, i >> 4] << 4) | sBox[4, i & 15]); + k43[i] = (byte)((sBox[3, i >> 4] << 4) | sBox[2, i & 15]); + k21[i] = (byte)((sBox[1, i >> 4] << 4) | sBox[0, i & 15]); + } + } + + private uint F(uint x) + { + x = (uint)(k87[x >> 24 & 255] << 24) | (uint)(k65[x >> 16 & 255] << 16) | + (uint)(k43[x >> 8 & 255] << 8) | (uint)(k21[x & 255]); + return x << 11 | x >> (32 - 11); + } + + private static uint U32(byte[] b) + { + return (uint)(b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24); + } + + private static void B4(uint u, byte[] b) + { + b[0] = (byte)u; + b[1] = (byte)(u >> 8); + b[2] = (byte)(u >> 16); + b[3] = (byte)(u >> 24); + } + + public void MainStep(byte[] input, byte[] key) + { + uint key32 = U32(key); + uint input1 = U32(input, 0); + uint input2 = U32(input, 4); + B4(F(key32 + input1) ^ input2, enc, 0); + Array.Copy(input, 0, enc, 4, 4); + } + + public byte[] Enc => enc; + + private static uint U32(byte[] b, int index) + { + return (uint)(b[index] | b[index + 1] << 8 | b[index + 2] << 16 | b[index + 3] << 24); + } + + private static void B4(uint u, byte[] b, int index) + { + b[index] = (byte)u; + b[index + 1] = (byte)(u >> 8); + b[index + 2] = (byte)(u >> 16); + b[index + 3] = (byte)(u >> 24); + } +} + +class Program +{ + static void Main(string[] args) + { + byte[,] cbrf = { + {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3}, + {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9}, + {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11}, + {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3}, + {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2}, + {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14}, + {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12}, + {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12}, + }; + + byte[] input = { 0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04 }; + byte[] key = { 0xF9, 0x04, 0xC1, 0xE2 }; + + Gost g = new Gost(cbrf); + g.MainStep(input, key); + + foreach (var b in g.Enc) + { + Console.Write("[{0:x2}]", b); + } + Console.WriteLine(); + } +} diff --git a/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia b/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia index 7afa767444..4816bf33d9 100644 --- a/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia +++ b/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia @@ -25,8 +25,8 @@ function f(x) (y << 11) | (y >> (32-11)) end -bytes2int(arr) = arr[1] + (UInt32(arr[2]) << 8) + (UInt32(arr[3]) << 16) + (UInt32(arr[4])) << 24 -int2bytes(x) = [UInt8(x&0xff), UInt8((x&0xff00)>>8), UInt8((x&0xff0000)>>16), UInt8(x>>24)] +bytes2int(arr) = reinterpret(UInt32, arr)[begin] +int2bytes(x) = reinterpret(UInt8, [x]) function mainstep(inputbytes, keybytes) intkey = bytes2int(keybytes) diff --git a/Task/Main-step-of-GOST-28147-89/Wren/main-step-of-gost-28147-89.wren b/Task/Main-step-of-GOST-28147-89/Wren/main-step-of-gost-28147-89.wren index f1f77e758d..2a168570e1 100644 --- a/Task/Main-step-of-GOST-28147-89/Wren/main-step-of-gost-28147-89.wren +++ b/Task/Main-step-of-GOST-28147-89/Wren/main-step-of-gost-28147-89.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt class GOST { // assumes 's' is an 8 x 16 integer array @@ -56,5 +56,5 @@ var input = [0x21, 0x04, 0x3b, 0x04, 0x30, 0x04, 0x32, 0x04] var key = [0xf9, 0x04, 0xc1, 0xe2] var g = GOST.new(cbrf) g.mainStep(input, key) -for (b in g.enc) System.write("[%(Fmt.xz(2, b))]") +for (b in g.enc) Fmt.write("[$02x]", b) System.print() diff --git a/Task/Man-or-boy-test/Elena/man-or-boy-test.elena b/Task/Man-or-boy-test/Elena/man-or-boy-test.elena index 470d3aca88..772b8361f1 100644 --- a/Task/Man-or-boy-test/Elena/man-or-boy-test.elena +++ b/Task/Man-or-boy-test/Elena/man-or-boy-test.elena @@ -18,7 +18,7 @@ A(k,x1,x2,x3,x4,x5) public program() { - for(int n := 0, n <= 14, n += 1) + for(int n := 0; n <= 14; n += 1) { console.printLine(A(n,{^1},{^-1},{^-1},{^1},{^0})) } diff --git a/Task/Man-or-boy-test/F-Sharp/man-or-boy-test-3.fs b/Task/Man-or-boy-test/F-Sharp/man-or-boy-test-3.fs new file mode 100644 index 0000000000..c60920bd77 --- /dev/null +++ b/Task/Man-or-boy-test/F-Sharp/man-or-boy-test-3.fs @@ -0,0 +1,19 @@ +[] +let main (args : string[]) = + let k = int(args.[0]) + + let l x cont = cont x + + let rec a k x1 x2 x3 x4 x5 cont = + if k <= 0 then + x4 (fun n4 -> x5 (fun n5 -> cont (n4+n5))) + else + let mutable k = k + let rec b cont = + k <- k - 1 + a k b x1 x2 x3 x4 cont + b cont + + a k (l 1) (l -1) (l -1) (l 1) (l 0) (printfn "%d") + + 0 diff --git a/Task/Man-or-boy-test/Wren/man-or-boy-test-1.wren b/Task/Man-or-boy-test/Wren/man-or-boy-test-1.wren index 1d96569f88..d3b219cea2 100644 --- a/Task/Man-or-boy-test/Wren/man-or-boy-test-1.wren +++ b/Task/Man-or-boy-test/Wren/man-or-boy-test-1.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var a a = Fn.new { |k, x1, x2, x3, x4, x5| diff --git a/Task/Man-or-boy-test/Wren/man-or-boy-test-2.wren b/Task/Man-or-boy-test/Wren/man-or-boy-test-2.wren index b1511641bc..47be849b68 100644 --- a/Task/Man-or-boy-test/Wren/man-or-boy-test-2.wren +++ b/Task/Man-or-boy-test/Wren/man-or-boy-test-2.wren @@ -1,4 +1,4 @@ -/* man_or_boy_test_gmp.wren */ +/* Man_or_boy_test_2.wren */ import "./gmp" for Mpz import "./fmt" for Fmt diff --git a/Task/Map-range/Wren/map-range.wren b/Task/Map-range/Wren/map-range.wren index c924b1c6e5..f54937e6f6 100644 --- a/Task/Map-range/Wren/map-range.wren +++ b/Task/Map-range/Wren/map-range.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var mapRange = Fn.new { |a, b, s| b.from + (s - a.from) * (b.to - b.from) / (a.to - a.from) } @@ -6,6 +6,5 @@ var a = 0..10 var b = -1..0 for (s in a) { var t = mapRange.call(a, b, s) - var f = (t >= 0) ? " " : "" - System.print("%(Fmt.d(2, s)) maps to %(f)%(t)") + Fmt.print("$2d maps to $ h", s, t) } diff --git a/Task/Mastermind/EasyLang/mastermind.easy b/Task/Mastermind/EasyLang/mastermind.easy index 0ad14ab4a5..c7155969ca 100644 --- a/Task/Mastermind/EasyLang/mastermind.easy +++ b/Task/Mastermind/EasyLang/mastermind.easy @@ -1,5 +1,3 @@ -# Mastermind:w90 -# col[] = [ 802 990 171 229 950 808 ] len code[] 4 len guess[] 4 @@ -102,7 +100,7 @@ on timer proc new . . init_vars for i to 4 - code[i] = random 6 + code[i] = randint 6 . color 531 move 10 10 diff --git a/Task/Mastermind/Wren/mastermind.wren b/Task/Mastermind/Wren/mastermind.wren index a6b6829b86..10ef54efcc 100644 --- a/Task/Mastermind/Wren/mastermind.wren +++ b/Task/Mastermind/Wren/mastermind.wren @@ -1,6 +1,6 @@ import "random" for Random -import "/ioutil" for Input -import "/str" for Str +import "./ioutil" for Input +import "./str" for Str var Rand = Random.new() diff --git a/Task/Matrix-chain-multiplication/00-META.yaml b/Task/Matrix-chain-multiplication/00-META.yaml index db6539cf92..9ec1289b25 100644 --- a/Task/Matrix-chain-multiplication/00-META.yaml +++ b/Task/Matrix-chain-multiplication/00-META.yaml @@ -1,3 +1,5 @@ --- +category: +- Matrices from: http://rosettacode.org/wiki/Matrix_chain_multiplication note: Discrete math diff --git a/Task/Matrix-chain-multiplication/00-TASK.txt b/Task/Matrix-chain-multiplication/00-TASK.txt index 5ab316a198..507b4e8dac 100644 --- a/Task/Matrix-chain-multiplication/00-TASK.txt +++ b/Task/Matrix-chain-multiplication/00-TASK.txt @@ -1,5 +1,5 @@ ;Problem -Using the most straightfoward algorithm (which we assume here), computing the [[Matrix multiplication|product of two matrices]] of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 [[wp:Multiply–accumulate_operation|FMA]] operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved. +Using the most straightforward algorithm (which we assume here), computing the [[Matrix multiplication|product of two matrices]] of dimensions (n1,n2) and (n2,n3) requires n1*n2*n3 [[wp:Multiply–accumulate_operation|FMA]] operations. The number of operations required to compute the product of matrices A1, A2... An depends on the order of matrix multiplications, hence on where parens are put. Remember that the matrix product is associative, but not commutative, hence only the parens can be moved. For instance, with four matrices, one can compute A(B(CD)), A((BC)D), (AB)(CD), (A(BC))D, (AB)C)D. The number of different ways to put the parens is a [[Catalan numbers|Catalan number]], and grows exponentially with the number of factors. diff --git a/Task/Matrix-digital-rain/J/matrix-digital-rain.j b/Task/Matrix-digital-rain/J/matrix-digital-rain.j index 844558a430..ef86e2f6d1 100644 --- a/Task/Matrix-digital-rain/J/matrix-digital-rain.j +++ b/Task/Matrix-digital-rain/J/matrix-digital-rain.j @@ -1,4 +1,4 @@ -require'ide/qt/gl2' +require'gl2' coinsert'jgl2' junk=: 7 u:;48 65 16b30a1(+i.)&.>10 26 90 @@ -9,36 +9,42 @@ heat=: (224 255 255),~(<.0.5+255*(%>./)(-<./)^>:(% >./)i.len)*/0 1 0 cols=: i.0 rows=: i.0 scale=: 24 -live=: (#heat)#._3++/?2 2 2 2 4 - cols=: cols,upd{.(?~{.sz)-.(-<.0.3*{:sz){.cols - rows=: (#cols){.rows - live=: }.live,<(scale*cols,.rows),.?(#cols)##junk - for_p. live do. - gltextcolor glrgb p_index{heat - if.p_index=<:#live do. - glfont font,' bold' +rain_timer=: {{ + try. + wd 'psel rain' + glsel 'green' + glfill 0 0 0 255 + glfont font=.'courier ',":0.8*scale + upd=. 0>._3++/?2 2 2 2 4 + cols=: cols,upd{.(?~{.sz)-.(-<.0.3*{:sz){.cols + rows=: (#cols){.rows + live=: }.live,<(scale*cols,.rows),.?(#cols)##junk + for_p. live do. + gltextcolor glrgb p_index{heat + if.p_index=<:#live do. + glfont font,' bold' + end. + for_xyj.;p do. + gltextxy 2{.xyj + gltext 8 u:junk{~{:xyj + end. end. - for_xyj.;p do. - gltextxy 2{.xyj - gltext 8 u:junk{~{:xyj - end. - end. glpaint'' - keep=: rows<{:sz-1 - cols=: keep#cols - rows=: keep#rows+1 - EMPTY + glpaintx'' + keep=: rows<{:sz-1 + cols=: keep#cols + rows=: keep#rows+1 + EMPTY + catch. + wd'ptimer 0' + end. }} -sys_timer_z_=: update_base_ wd rplc&('DIMS';":scale*sz) {{)n pc rain closeok; setp wh DIMS; cc green isidraw flush; pshow; - timer 100 + ptimer 100 }} diff --git a/Task/Matrix-exponentiation-operator/Wren/matrix-exponentiation-operator.wren b/Task/Matrix-exponentiation-operator/Wren/matrix-exponentiation-operator.wren index d7a46a2586..47e62e7a30 100644 --- a/Task/Matrix-exponentiation-operator/Wren/matrix-exponentiation-operator.wren +++ b/Task/Matrix-exponentiation-operator/Wren/matrix-exponentiation-operator.wren @@ -1,5 +1,5 @@ -import "/matrix" for Matrix -import "/fmt" for Fmt +import "./matrix" for Matrix +import "./fmt" for Fmt var m = Matrix.new([[0, 1], [1, 1]]) System.print("Original:\n") diff --git a/Task/Matrix-multiplication/EasyLang/matrix-multiplication.easy b/Task/Matrix-multiplication/EasyLang/matrix-multiplication.easy new file mode 100644 index 0000000000..72b50c1d7c --- /dev/null +++ b/Task/Matrix-multiplication/EasyLang/matrix-multiplication.easy @@ -0,0 +1,16 @@ +proc matmul . m1[][] m2[][] r[][] . + r[][] = [ ] + for i to len m1[][] + r[][] &= [ ] + for j = 1 to len m2[1][] + r[i][] &= 0 + for k to len m2[][] + r[i][j] += m1[i][k] * m2[k][j] + . + . + . +. +mat1[][] = [ [ 1 2 3 ] [ 4 5 6 ] ] +mat2[][] = [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ] +matmul mat1[][] mat2[][] erg[][] +print erg[][] diff --git a/Task/Matrix-multiplication/Raku/matrix-multiplication-4.raku b/Task/Matrix-multiplication/Raku/matrix-multiplication-4.raku index 2a7bbfa0cb..4d3a015f87 100644 --- a/Task/Matrix-multiplication/Raku/matrix-multiplication-4.raku +++ b/Task/Matrix-multiplication/Raku/matrix-multiplication-4.raku @@ -1,4 +1,2 @@ -sub infix:<×>(@A, @B) { - cross(@A, ([Z] @B), with => { [+] @^a Z* @^b }) - .rotor(@B); -} +sub infix:<·> { [+] @^a Z* @^b } +sub infix:<×>(@A, @B) { (@A X· [Z] @B).rotor(@B) } diff --git a/Task/Matrix-multiplication/Wren/matrix-multiplication.wren b/Task/Matrix-multiplication/Wren/matrix-multiplication.wren index 18e95a5157..f5b7c99673 100644 --- a/Task/Matrix-multiplication/Wren/matrix-multiplication.wren +++ b/Task/Matrix-multiplication/Wren/matrix-multiplication.wren @@ -1,5 +1,5 @@ -import "/matrix" for Matrix -import "/fmt" for Fmt +import "./matrix" for Matrix +import "./fmt" for Fmt var a = Matrix.new([ [1, 2], diff --git a/Task/Matrix-transposition/Wren/matrix-transposition.wren b/Task/Matrix-transposition/Wren/matrix-transposition.wren index c7e8e5b6cc..1ce0760175 100644 --- a/Task/Matrix-transposition/Wren/matrix-transposition.wren +++ b/Task/Matrix-transposition/Wren/matrix-transposition.wren @@ -1,5 +1,5 @@ -import "/matrix" for Matrix -import "/fmt" for Fmt +import "./matrix" for Matrix +import "./fmt" for Fmt var m = Matrix.new([ [ 1, 2, 3], diff --git a/Task/Maximum-triangle-path-sum/EasyLang/maximum-triangle-path-sum.easy b/Task/Maximum-triangle-path-sum/EasyLang/maximum-triangle-path-sum.easy index 7ff134def3..9bb9ad8c2a 100644 --- a/Task/Maximum-triangle-path-sum/EasyLang/maximum-triangle-path-sum.easy +++ b/Task/Maximum-triangle-path-sum/EasyLang/maximum-triangle-path-sum.easy @@ -6,7 +6,7 @@ repeat while substr s$ i 1 = " " i += 1 . - s$ = "0 " & substr s$ i -1 & " 0" + s$ = "0 " & substr s$ i 999 & " 0" b[] = number strsplit s$ " " for i = 2 to len b[] - 1 b[i] = higher (b[i] + a[i - 1]) (b[i] + a[i]) diff --git a/Task/Maximum-triangle-path-sum/Elena/maximum-triangle-path-sum.elena b/Task/Maximum-triangle-path-sum/Elena/maximum-triangle-path-sum.elena index e57a0dc472..af21f5cb9b 100644 --- a/Task/Maximum-triangle-path-sum/Elena/maximum-triangle-path-sum.elena +++ b/Task/Maximum-triangle-path-sum/Elena/maximum-triangle-path-sum.elena @@ -27,10 +27,10 @@ public program() int i := 0; int j := 0; - input.splitBy(newLineConstant).forEach:(string line) + input.splitBy(newLineConstant).forEach::(string line) { j := 0; - line.trim().splitBy(" ").forEach:(string num) + line.trim().splitBy(" ").forEach::(string num) { list[i][j] := num.toInt(); @@ -40,9 +40,9 @@ public program() i += 1 }; - for(int i := 16, i >= 0, i-=1) + for(int i := 16; i >= 0; i-=1) { - for(int j := 0, j < 18, j += 1) + for(int j := 0; j < 18; j += 1) { list[i][j] := max(list[i][j] + list[i+1][j], list[i][j] + list[i+1][j+1]) } diff --git a/Task/Mayan-calendar/Wren/mayan-calendar.wren b/Task/Mayan-calendar/Wren/mayan-calendar.wren index bccb903784..131abe6249 100644 --- a/Task/Mayan-calendar/Wren/mayan-calendar.wren +++ b/Task/Mayan-calendar/Wren/mayan-calendar.wren @@ -1,5 +1,5 @@ -import "/date" for Date -import "/fmt" for Fmt +import "./date" for Date +import "./fmt" for Fmt var sacred = "Imix’ Ik’ Ak’bal K’an Chikchan Kimi Manik’ Lamat Muluk Ok Chuwen Eb Ben Hix Men K’ib’ Kaban Etz’nab’ Kawak Ajaw".split(" ") diff --git a/Task/Mayan-numerals/FreeBASIC/mayan-numerals.basic b/Task/Mayan-numerals/FreeBASIC/mayan-numerals.basic new file mode 100644 index 0000000000..24b058b797 --- /dev/null +++ b/Task/Mayan-numerals/FreeBASIC/mayan-numerals.basic @@ -0,0 +1,58 @@ +Dim As Integer i, j, m, n, s, v +Dim As String maya(5), num +For i = 0 To 5 + Read maya(i) +Next i +Const ul = Chr(201), uc = Chr(203), ur = Chr(187), ll = Chr(200) +Const lc = Chr(202), lr = Chr(188), hb = Chr(205), vb = Chr(186) + +Dim As Longint numbers(0 To ...) = {4005, 8017, 326205, 886205, 1081439556, 18380658207197784} +For v = 0 To Ubound(numbers) + num = Str(numbers(v)) + Print "Converting"; numbers(v); " to Mayan:" + + m = Len(num) + Redim As Integer D(m) + For i = 1 To m + D(i) = Val(Mid(num,i,1)) + Next i + + For j = m-1 To 1 Step -1 + For i = 1 To j + D(i+1) += 10*(D(i) And 1) + D(i) \= 2 + Next i + Next j + + s = 1 + Do While D(s) = 0 And s < m + s += 1 + Loop + + For i = s To m + Print Iif(i < m-1, ul+hb+hb+hb+hb, uc+hb+hb+hb+hb); + Next i + Print ur + For j = 3 To 0 Step -1 + For i = s To m + If (D(i) Or j) = 0 Then + Print vb + " @ "; + Else + n = D(i)-5*j + If n > 5 Then + n = 5 + Elseif n < 0 Then + n = 0 + End If + Print vb; maya(n); + End If + Next i + Print vb + Next j + For i = s To m + Print Iif(i < m-1, ll+hb+hb+hb+hb, lc+hb+hb+hb+hb); + Next i + Print lr + Chr(10) '"+" +Next v +Sleep +Data " "," . "," .. ","... ","....","----" diff --git a/Task/Mayan-numerals/Wren/mayan-numerals.wren b/Task/Mayan-numerals/Wren/mayan-numerals.wren index a65cbe7cb6..09c4293f18 100644 --- a/Task/Mayan-numerals/Wren/mayan-numerals.wren +++ b/Task/Mayan-numerals/Wren/mayan-numerals.wren @@ -1,4 +1,4 @@ -import "/fmt" for Conv +import "./fmt" for Conv var ul = "╔" var uc = "╦" diff --git a/Task/Maze-generation/EasyLang/maze-generation.easy b/Task/Maze-generation/EasyLang/maze-generation.easy index cc5c352028..043b229e65 100644 --- a/Task/Maze-generation/EasyLang/maze-generation.easy +++ b/Task/Maze-generation/EasyLang/maze-generation.easy @@ -24,7 +24,7 @@ proc m_maze pos . . show_maze d[] = [ 1 2 3 4 ] for i = 4 downto 1 - d = random i + d = randint i dir = offs[d[d]] d[d] = d[i] if m[pos + dir] = 1 and m[pos + 2 * dir] = 1 @@ -44,7 +44,7 @@ proc make_maze . . m[n * i - n + 1] = 2 m[n * n - n + i] = 2 . - h = 2 * random 15 - n + n * 2 * random 15 + h = 2 * randint 15 - n + n * 2 * randint 15 m_maze h m[endpos] = 0 endpos += n diff --git a/Task/Maze-solving/C-sharp/maze-solving.cs b/Task/Maze-solving/C-sharp/maze-solving.cs new file mode 100644 index 0000000000..d6333a55e1 --- /dev/null +++ b/Task/Maze-solving/C-sharp/maze-solving.cs @@ -0,0 +1,182 @@ +using System; +using System.Text; + +public class Maze +{ + private char[,] cells; + private char[,] hWalls; // Horizontal walls + private char[,] vWalls; // Vertical walls + private Random rand = new Random(); + + public Maze(int rows, int cols) + { + cells = new char[rows, cols]; + hWalls = new char[rows + 1, cols]; // Include walls for the bottom + vWalls = new char[rows, cols + 1]; // Include walls for the right side + + // Initialize walls + for (int i = 0; i < rows; i++) + { + for (int j = 0; j < cols; j++) + { + hWalls[i, j] = '-'; + vWalls[i, j] = '|'; + } + } + + // Set the outer walls for the bottom and right + for (int i = 0; i < cols; i++) + { + hWalls[rows, i] = '-'; + } + for (int i = 0; i < rows; i++) + { + vWalls[i, cols] = '|'; + } + } + + public override string ToString() + { + var builder = new StringBuilder(); + + for (int i = 0; i < cells.GetLength(0); i++) + { + // Top walls + for (int j = 0; j < cells.GetLength(1); j++) + { + builder.Append("+"); + builder.Append(hWalls[i, j] == '-' ? "---" : " "); + } + builder.AppendLine("+"); + + // Side walls and cells + for (int j = 0; j < cells.GetLength(1); j++) + { + builder.Append(vWalls[i, j] == '|' ? "| " : " "); + char cell = cells[i, j] == '\0' ? ' ' : cells[i, j]; + builder.Append(cell + " "); + } + builder.AppendLine("|"); + } + + // Bottom walls + for (int j = 0; j < cells.GetLength(1); j++) + { + builder.Append("+---"); + } + builder.AppendLine("+"); + + return builder.ToString(); + } + + public void Generate() + { + Generate(rand.Next(cells.GetLength(0)), rand.Next(cells.GetLength(1))); + } + + private void Generate(int r, int c) + { + cells[r, c] = ' '; + int[] dirs = { 0, 1, 2, 3 }; + Shuffle(dirs); + + foreach (int dir in dirs) + { + switch (dir) + { + case 0: // Up + if (r > 0 && cells[r - 1, c] == '\0') + { + hWalls[r, c] = ' '; + Generate(r - 1, c); + } + break; + case 1: // Down + if (r < cells.GetLength(0) - 1 && cells[r + 1, c] == '\0') + { + hWalls[r + 1, c] = ' '; + Generate(r + 1, c); + } + break; + case 2: // Right + if (c < cells.GetLength(1) - 1 && cells[r, c + 1] == '\0') + { + vWalls[r, c + 1] = ' '; + Generate(r, c + 1); + } + break; + case 3: // Left + if (c > 0 && cells[r, c - 1] == '\0') + { + vWalls[r, c] = ' '; + Generate(r, c - 1); + } + break; + } + } + } + + private void Shuffle(int[] array) + { + for (int i = array.Length - 1; i > 0; i--) + { + int j = rand.Next(i + 1); + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + } + + public void Solve(int startRow, int startCol, int endRow, int endCol) + { + if (Solve(startRow, startCol, endRow, endCol, -1)) + { + cells[startRow, startCol] = 'S'; + cells[endRow, endCol] = 'F'; + } + } + + private bool Solve(int r, int c, int endRow, int endCol, int dir) + { + if (r == endRow && c == endCol) return true; + + // Up + if (dir != 1 && r > 0 && hWalls[r, c] == ' ' && Solve(r - 1, c, endRow, endCol, 0)) + { + cells[r, c] = '^'; + return true; + } + // Down + if (dir != 0 && r < cells.GetLength(0) - 1 && hWalls[r + 1, c] == ' ' && Solve(r + 1, c, endRow, endCol, 1)) + { + cells[r, c] = 'v'; + return true; + } + // Right + if (dir != 3 && c < cells.GetLength(1) - 1 && vWalls[r, c + 1] == ' ' && Solve(r, c + 1, endRow, endCol, 2)) + { + cells[r, c] = '>'; + return true; + } + // Left + if (dir != 2 && c > 0 && vWalls[r, c] == ' ' && Solve(r, c - 1, endRow, endCol, 3)) + { + cells[r, c] = '<'; + return true; + } + + return false; + } +} + +class Program +{ + static void Main(string[] args) + { + var maze = new Maze(4, 7); + maze.Generate(); + Random rand = new Random(); + maze.Solve(rand.Next(4), rand.Next(7), rand.Next(4), rand.Next(7)); + Console.WriteLine(maze); + } +} diff --git a/Task/Maze-solving/EasyLang/maze-solving.easy b/Task/Maze-solving/EasyLang/maze-solving.easy index 52f27f223c..29daa66062 100644 --- a/Task/Maze-solving/EasyLang/maze-solving.easy +++ b/Task/Maze-solving/EasyLang/maze-solving.easy @@ -23,7 +23,7 @@ proc m_maze pos . . show_maze d[] = [ 1 2 3 4 ] for i = 4 downto 1 - d = random i + d = randint i dir = offs[d[d]] d[d] = d[i] if m[pos + dir] = 1 and m[pos + 2 * dir] = 1 @@ -43,7 +43,7 @@ proc make_maze . . m[n * i - n + 1] = 2 m[n * n - n + i] = 2 . - h = 2 * random 15 - n + n * 2 * random 15 + h = 2 * randint 15 - n + n * 2 * randint 15 m_maze h m[endpos] = 0 . @@ -68,7 +68,7 @@ proc solve dir0 pos . . found = 1 return . - of = random 4 - 1 + of = randint 4 - 1 for h = 1 to 4 dir = (h + of) mod1 4 posn = pos + offs[dir] diff --git a/Task/Maze-solving/Wren/maze-solving.wren b/Task/Maze-solving/Wren/maze-solving.wren index 0653c5d4f2..a209b41e4a 100644 --- a/Task/Maze-solving/Wren/maze-solving.wren +++ b/Task/Maze-solving/Wren/maze-solving.wren @@ -1,5 +1,5 @@ import "os" for Process -import "/ioutil" for File, FileUtil +import "./ioutil" for File, FileUtil /* * Makes the maze half as wide (i. e. "+---+" becomes "+-+"), so that diff --git a/Task/Meissel-Mertens-constant/EasyLang/meissel-mertens-constant.easy b/Task/Meissel-Mertens-constant/EasyLang/meissel-mertens-constant.easy new file mode 100644 index 0000000000..8fdd64cc93 --- /dev/null +++ b/Task/Meissel-Mertens-constant/EasyLang/meissel-mertens-constant.easy @@ -0,0 +1,27 @@ +fastfunc isprim num . + if num mod 2 = 0 + if num = 2 + return 1 + . + return 0 + . + i = 3 + while i <= sqrt num + if num mod i = 0 + return 0 + . + i += 2 + . + return 1 +. +func log x . + return log10 x / log10 2.7182818284590452354 +. +euler = 0.5772156649 +for x = 2 to 1e6 + if isprim x = 1 + m += log (1 - (1 / x)) + (1 / x) + . +. +numfmt 11 0 +print "mm = " & euler + m diff --git a/Task/Memory-layout-of-a-data-structure/Wren/memory-layout-of-a-data-structure.wren b/Task/Memory-layout-of-a-data-structure/Wren/memory-layout-of-a-data-structure.wren index 0712981379..57ce894edf 100644 --- a/Task/Memory-layout-of-a-data-structure/Wren/memory-layout-of-a-data-structure.wren +++ b/Task/Memory-layout-of-a-data-structure/Wren/memory-layout-of-a-data-structure.wren @@ -1,5 +1,5 @@ -import "/seq" for Lst -import "/fmt" for Fmt +import "./seq" for Lst +import "./fmt" for Fmt var ON = true var OFF = false diff --git a/Task/Menu/Langur/menu.langur b/Task/Menu/Langur/menu.langur index 3c86399462..e8c6c3e499 100644 --- a/Task/Menu/Langur/menu.langur +++ b/Task/Menu/Langur/menu.langur @@ -1,5 +1,5 @@ val .select = f(.entries) { - if not isArray(.entries): throw "invalid args" + if not isList(.entries): throw "invalid args" if len(.entries) == 0: return "" # print the menu diff --git a/Task/Menu/Wren/menu.wren b/Task/Menu/Wren/menu.wren index 4248915bef..e11b0c5831 100644 --- a/Task/Menu/Wren/menu.wren +++ b/Task/Menu/Wren/menu.wren @@ -1,4 +1,4 @@ -import "/ioutil" for Input +import "./ioutil" for Input var menu = Fn.new { |list| var n = list.count diff --git a/Task/Merge-and-aggregate-datasets/Wren/merge-and-aggregate-datasets.wren b/Task/Merge-and-aggregate-datasets/Wren/merge-and-aggregate-datasets.wren index f8a374138a..b26755b176 100644 --- a/Task/Merge-and-aggregate-datasets/Wren/merge-and-aggregate-datasets.wren +++ b/Task/Merge-and-aggregate-datasets/Wren/merge-and-aggregate-datasets.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/sort" for Sort +import "./fmt" for Fmt +import "./sort" for Sort class Patient { construct new(id, lastName) { diff --git a/Task/Mertens-function/EasyLang/mertens-function.easy b/Task/Mertens-function/EasyLang/mertens-function.easy new file mode 100644 index 0000000000..bacf516727 --- /dev/null +++ b/Task/Mertens-function/EasyLang/mertens-function.easy @@ -0,0 +1,29 @@ +len mertens[] 1000 +mertens[1] = 1 +for n = 2 to 1000 + mertens[n] = 1 + for k = 2 to n + mertens[n] -= mertens[n div k] + . +. +print "First 99 Mertens numbers:" +write " " +numfmt 0 2 +for n = 1 to 99 + write mertens[n] & " " + if n mod 10 = 9 + print "" + . +. +for n = 1 to 1000 + if mertens[n] = 0 + zeros += 1 + if mertens[n - 1] <> 0 + crosses += 1 + . + . +. +print "" +print "In the first 1000 terms of the Mertens sequence there are:" +print zeros & " zeros" +print crosses & " zero crosses" diff --git a/Task/Mertens-function/Wren/mertens-function.wren b/Task/Mertens-function/Wren/mertens-function.wren index f85bcc03a5..9dc301af2c 100644 --- a/Task/Mertens-function/Wren/mertens-function.wren +++ b/Task/Mertens-function/Wren/mertens-function.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/math" for Int +import "./fmt" for Fmt +import "./math" for Int var isSquareFree = Fn.new { |n| var i = 2 diff --git a/Task/Metallic-ratios/Wren/metallic-ratios.wren b/Task/Metallic-ratios/Wren/metallic-ratios.wren index cd13adaaf3..e752d18f38 100644 --- a/Task/Metallic-ratios/Wren/metallic-ratios.wren +++ b/Task/Metallic-ratios/Wren/metallic-ratios.wren @@ -1,5 +1,5 @@ -import "/big" for BigInt, BigRat -import "/fmt" for Fmt +import "./big" for BigInt, BigRat +import "./fmt" for Fmt var names = ["Platinum", "Golden", "Silver", "Bronze", "Copper","Nickel", "Aluminium", "Iron", "Tin", "Lead"] diff --git a/Task/Metered-concurrency/Wren/metered-concurrency.wren b/Task/Metered-concurrency/Wren/metered-concurrency.wren index d07b450065..6c3cd6c389 100644 --- a/Task/Metered-concurrency/Wren/metered-concurrency.wren +++ b/Task/Metered-concurrency/Wren/metered-concurrency.wren @@ -1,6 +1,6 @@ import "scheduler" for Scheduler import "timer" for Timer -import "/queue" for Queue +import "./queue" for Queue class CountingSemaphore { construct new(numRes) { diff --git a/Task/Metronome/C-sharp/metronome.cs b/Task/Metronome/C-sharp/metronome.cs new file mode 100644 index 0000000000..e3f00c8016 --- /dev/null +++ b/Task/Metronome/C-sharp/metronome.cs @@ -0,0 +1,53 @@ +using System; +using System.Threading; + +public class Program +{ + public static void Main(string[] args) + { + Metronome metronome1 = new Metronome(120, 4); + metronome1.Start(); + } +} + +public class Metronome +{ + private double bpm; + private int measure; + private int counter; + + public Metronome(double bpm, int measure) + { + this.bpm = bpm; + this.measure = measure; + } + + public void Start() + { + Thread thread = new Thread(() => + { + while (true) + { + try + { + Thread.Sleep((int)(1000 * (60.0 / bpm))); + } + catch (ThreadInterruptedException e) + { + Console.WriteLine(e.StackTrace); + } + counter++; + if (counter % measure == 0) + { + Console.WriteLine("TICK"); + } + else + { + Console.WriteLine("TOCK"); + } + } + }); + + thread.Start(); + } +} diff --git a/Task/Middle-three-digits/Elena/middle-three-digits.elena b/Task/Middle-three-digits/Elena/middle-three-digits.elena index 1a5cbb174f..6386c6f2df 100644 --- a/Task/Middle-three-digits/Elena/middle-three-digits.elena +++ b/Task/Middle-three-digits/Elena/middle-three-digits.elena @@ -7,11 +7,11 @@ middleThreeDigits(int n) int len := s.Length; if(len<3) { - InvalidArgumentException.new:"n must have 3 digits or more".raise() + InvalidArgumentException.new("n must have 3 digits or more").raise() } else if(len.isEven()) { - InvalidArgumentException.new:"n must have an odd number of digits".raise() + InvalidArgumentException.new("n must have an odd number of digits").raise() }; int mid := len / 2; @@ -22,8 +22,8 @@ middleThreeDigits(int n) public program() { new int[]{123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0} - .forEach:(n) + .forEach::(n) { - console.printLine("middleThreeDigits(",n,"):",middleThreeDigits(n) \\ on:(e => e.Message)) + console.printLine("middleThreeDigits(",n,"):",middleThreeDigits(n) \\ on::(e => e.Message)) } } diff --git a/Task/Middle-three-digits/Wren/middle-three-digits.wren b/Task/Middle-three-digits/Wren/middle-three-digits.wren index ff06b5573b..861ae05616 100644 --- a/Task/Middle-three-digits/Wren/middle-three-digits.wren +++ b/Task/Middle-three-digits/Wren/middle-three-digits.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var middle3 = Fn.new { |n| if (n < 0) n = -n @@ -15,5 +15,5 @@ var a = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0] for (e in a) { - System.print("%(Fmt.s(9, e)) -> %(middle3.call(e))") + Fmt.print("$9d -> $n", e, middle3.call(e)) } diff --git a/Task/Miller-Rabin-primality-test/Wren/miller-rabin-primality-test.wren b/Task/Miller-Rabin-primality-test/Wren/miller-rabin-primality-test.wren index 1a54b27e63..0190c9111c 100644 --- a/Task/Miller-Rabin-primality-test/Wren/miller-rabin-primality-test.wren +++ b/Task/Miller-Rabin-primality-test/Wren/miller-rabin-primality-test.wren @@ -1,4 +1,4 @@ -import "/big" for BigInt +import "./big" for BigInt var iters = 10 // find all primes < 100 diff --git a/Task/Mind-boggling-card-trick/C-sharp/mind-boggling-card-trick.cs b/Task/Mind-boggling-card-trick/C-sharp/mind-boggling-card-trick.cs new file mode 100644 index 0000000000..e9c0b46677 --- /dev/null +++ b/Task/Mind-boggling-card-trick/C-sharp/mind-boggling-card-trick.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class MindBogglingCardTrick +{ + public static void Main(string[] args) + { + List cards = new List(); + cards.AddRange(Enumerable.Repeat('R', 26)); + cards.AddRange(Enumerable.Repeat('B', 26)); + Shuffle(cards); + + List redPile = new List(); + List blackPile = new List(); + List discardPile = new List(); + + for (int i = 0; i < 52; i += 2) + { + if (cards[i] == 'R') + { + redPile.Add(cards[i + 1]); + } + else + { + blackPile.Add(cards[i + 1]); + } + discardPile.Add(cards[i]); + } + + Console.WriteLine("A sample run.\n"); + Console.WriteLine("After dealing the cards the state of the piles is:"); + Console.WriteLine($" Red : {redPile.Count} cards -> {string.Join(",", redPile)}"); + Console.WriteLine($" Black : {blackPile.Count} cards -> {string.Join(",", blackPile)}"); + Console.WriteLine($" Discard: {discardPile.Count} cards -> {string.Join(",", discardPile)}"); + + Random random = new Random(); + int minimumSize = Math.Min(redPile.Count, blackPile.Count); + int choice = random.Next(1, minimumSize + 1); + + List redIndexes = Enumerable.Range(0, redPile.Count).ToList(); + List blackIndexes = Enumerable.Range(0, blackPile.Count).ToList(); + Shuffle(redIndexes); + Shuffle(blackIndexes); + List redChosenIndexes = redIndexes.Take(choice).ToList(); + List blackChosenIndexes = blackIndexes.Take(choice).ToList(); + + Console.WriteLine($"\nNumber of cards are to be swapped: {choice}"); + Console.WriteLine("The respective zero-based indices of the cards to be swapped are:"); + Console.WriteLine($" Red : {string.Join(", ", redChosenIndexes)}"); + Console.WriteLine($" Black: {string.Join(", ", blackChosenIndexes)}"); + + for (int i = 0; i < choice; i++) + { + char temp = redPile[redChosenIndexes[i]]; + redPile[redChosenIndexes[i]] = blackPile[blackChosenIndexes[i]]; + blackPile[blackChosenIndexes[i]] = temp; + } + + Console.WriteLine($"\nAfter swapping cards the state of the red and black piles is:"); + Console.WriteLine($" Red : {string.Join(", ", redPile)}"); + Console.WriteLine($" Black: {string.Join(", ", blackPile)}"); + + int redCount = redPile.Count(ch => ch == 'R'); + int blackCount = blackPile.Count(ch => ch == 'B'); + + Console.WriteLine($"\nThe number of red cards in the red pile: {redCount}"); + Console.WriteLine($"The number of black cards in the black pile: {blackCount}"); + if (redCount == blackCount) + { + Console.WriteLine("So the assertion is correct."); + } + else + { + Console.WriteLine("So the assertion is incorrect."); + } + } + + private static void Shuffle(List list) + { + Random rng = new Random(); + int n = list.Count; + while (n > 1) + { + n--; + int k = rng.Next(n + 1); + T value = list[k]; + list[k] = list[n]; + list[n] = value; + } + } +} diff --git a/Task/Mind-boggling-card-trick/Wren/mind-boggling-card-trick.wren b/Task/Mind-boggling-card-trick/Wren/mind-boggling-card-trick.wren index 92c33173a1..1242c61408 100644 --- a/Task/Mind-boggling-card-trick/Wren/mind-boggling-card-trick.wren +++ b/Task/Mind-boggling-card-trick/Wren/mind-boggling-card-trick.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/fmt" for Fmt +import "./fmt" for Fmt var R = 82 // ASCII 'R' var B = 66 // ASCII 'B' diff --git a/Task/Minesweeper-game/EasyLang/minesweeper-game.easy b/Task/Minesweeper-game/EasyLang/minesweeper-game.easy index 96d2a19eb8..8d1fc663b8 100644 --- a/Task/Minesweeper-game/EasyLang/minesweeper-game.easy +++ b/Task/Minesweeper-game/EasyLang/minesweeper-game.easy @@ -130,8 +130,8 @@ proc start . . . n = 8 while n > 0 - c = random 8 - 1 - r = random 7 - 1 + c = randint 8 - 1 + r = randint 7 - 1 ind = r * 8 + c + 1 if cell[ind] = 0 n -= 1 diff --git a/Task/Minesweeper-game/Wren/minesweeper-game.wren b/Task/Minesweeper-game/Wren/minesweeper-game.wren index 32f08181dd..ad36107ca3 100644 --- a/Task/Minesweeper-game/Wren/minesweeper-game.wren +++ b/Task/Minesweeper-game/Wren/minesweeper-game.wren @@ -1,8 +1,8 @@ -import "/dynamic" for Struct -import "/fmt" for Fmt +import "./dynamic" for Struct +import "./fmt" for Fmt import "random" for Random -import "/ioutil" for Input -import "/str" for Str +import "./ioutil" for Input +import "./str" for Str var Cell = Struct.create("Cell", ["isMine", "display"]) diff --git a/Task/Minimal-steps-down-to-1/Kotlin/minimal-steps-down-to-1.kotlin b/Task/Minimal-steps-down-to-1/Kotlin/minimal-steps-down-to-1.kotlin new file mode 100644 index 0000000000..9eab0e825d --- /dev/null +++ b/Task/Minimal-steps-down-to-1/Kotlin/minimal-steps-down-to-1.kotlin @@ -0,0 +1,145 @@ +fun main() { + runTasks(getFunctions1()) + runTasks(getFunctions2()) + runTasks(getFunctions3()) +} + +fun runTasks(functions: List) { + val minPath = getInitialMap(functions, 5) + + // Task 1 + val max = 10 + populateMap(minPath, functions, max) + println("\nWith functions: $functions") + println(" Minimum steps to 1:") + for (n in 2..max) { + val steps = minPath[n]?.size ?: 0 + println(" %2d: %d step%s: %s".format(n, steps, if (steps == 1) "" else "s", minPath[n])) + } + + // Task 2 + displayMaxMin(minPath, functions, 2000) + + // Task 2a + displayMaxMin(minPath, functions, 20000) + + // Task 2a + + displayMaxMin(minPath, functions, 100000) +} + +fun displayMaxMin(minPath: MutableMap>, functions: List, max: Int) { + populateMap(minPath, functions, max) + val maxIntegers = getMaxMin(minPath, max) + val maxSteps = maxIntegers.removeAt(0) + val numCount = maxIntegers.size + println(" There ${if (numCount == 1) "is" else "are"} $numCount number${if (numCount == 1) "" else "s"} in the range 1-$max that have maximum 'minimal steps' of $maxSteps:\n $maxIntegers") +} + +fun getMaxMin(minPath: Map>, max: Int): MutableList { + var maxSteps = Int.MIN_VALUE + val maxIntegers = mutableListOf() + for (n in 2..max) { + val len = minPath[n]?.size ?: 0 + if (len > maxSteps) { + maxSteps = len + maxIntegers.clear() + maxIntegers.add(n) + } else if (len == maxSteps) { + maxIntegers.add(n) + } + } + maxIntegers.add(0, maxSteps) + return maxIntegers +} + +fun populateMap(minPath: MutableMap>, functions: List, max: Int) { + for (n in 2..max) { + if (n in minPath) continue + var minFunction: Function? = null + var minSteps = Int.MAX_VALUE + for (f in functions) { + if (f.actionOk(n)) { + val result = f.action(n) + val steps = 1 + (minPath[result]?.size ?: 0) + if (steps < minSteps) { + minFunction = f + minSteps = steps + } + } + } + minFunction?.let { + val result = it.action(n) + val path = mutableListOf(it.toString(n)) + path.addAll(minPath[result] ?: emptyList()) + minPath[n] = path + } + } +} + +fun getInitialMap(functions: List, max: Int): MutableMap> { + val minPath = mutableMapOf>() + for (i in 2..max) { + for (f in functions) { + if (f.actionOk(i)) { + val result = f.action(i) + if (result == 1) { + minPath[i] = listOf(f.toString(i)) + } + } + } + } + return minPath +} + +fun getFunctions1(): List = listOf( + Divide3Function(), + Divide2Function(), + Subtract1Function() +) + +fun getFunctions2(): List = listOf( + Divide3Function(), + Divide2Function(), + Subtract2Function() +) + +fun getFunctions3(): List = listOf( + Divide2Function(), + Divide3Function(), + Subtract2Function(), + Subtract1Function() +) + +abstract class Function { + abstract fun action(n: Int): Int + abstract fun actionOk(n: Int): Boolean + abstract fun toString(n: Int): String +} + +class Divide2Function : Function() { + override fun action(n: Int) = n / 2 + override fun actionOk(n: Int) = n % 2 == 0 + override fun toString(n: Int) = "/2 -> ${n / 2}" + override fun toString() = "Divisor 2" +} + +class Divide3Function : Function() { + override fun action(n: Int) = n / 3 + override fun actionOk(n: Int) = n % 3 == 0 + override fun toString(n: Int) = "/3 -> ${n / 3}" + override fun toString() = "Divisor 3" +} + +class Subtract1Function : Function() { + override fun action(n: Int) = n - 1 + override fun actionOk(n: Int) = true + override fun toString(n: Int) = "-1 -> ${n - 1}" + override fun toString() = "Subtractor 1" +} + +class Subtract2Function : Function() { + override fun action(n: Int) = n - 2 + override fun actionOk(n: Int) = n > 2 + override fun toString(n: Int) = "-2 -> ${n - 2}" + override fun toString() = "Subtractor 2" +} diff --git a/Task/Minimal-steps-down-to-1/Wren/minimal-steps-down-to-1.wren b/Task/Minimal-steps-down-to-1/Wren/minimal-steps-down-to-1.wren index 81d4ca4b99..dc262d1a2a 100644 --- a/Task/Minimal-steps-down-to-1/Wren/minimal-steps-down-to-1.wren +++ b/Task/Minimal-steps-down-to-1/Wren/minimal-steps-down-to-1.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var limit = 50000 var divs = [] diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/BBC-BASIC/minimum-multiple-of-m-where-digital-sum-equals-m.basic b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/BBC-BASIC/minimum-multiple-of-m-where-digital-sum-equals-m.basic new file mode 100644 index 0000000000..983fc36db1 --- /dev/null +++ b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/BBC-BASIC/minimum-multiple-of-m-where-digital-sum-equals-m.basic @@ -0,0 +1,19 @@ + FOR N%=1 TO 70 + PRINT FNa131382(N%); + IF N% MOD 10 == 0 PRINT + NEXT + END + + DEF FNa131382(n%) LOCAL m% + m%=1 + WHILE n% <> FNdigit_sum(m% * n%) + m%+=1 + ENDWHILE + =m% + + DEF FNdigit_sum(n%) LOCAL sum% + WHILE n% + sum%+=n% MOD 10 + n%/=10 + ENDWHILE + =sum% diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/PL-M/minimum-multiple-of-m-where-digital-sum-equals-m.plm b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/PL-M/minimum-multiple-of-m-where-digital-sum-equals-m.plm new file mode 100644 index 0000000000..d9eab6fbe3 --- /dev/null +++ b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/PL-M/minimum-multiple-of-m-where-digital-sum-equals-m.plm @@ -0,0 +1,66 @@ +100H: /* FIND THE SMALLEST M WHERE M*N = DIGIT SUM OF N, N IN 1 .. 70 */ + + /* CP/M BDOS SYSTEM CALL AND I/O ROUTINES */ + BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; + PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END; + PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; + PR$NL: PROCEDURE; CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END; + PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH */ + DECLARE N ADDRESS; + DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE; + V = N; + W = LAST( N$STR ); + N$STR( W ) = '$'; + N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); + DO WHILE( ( V := V / 10 ) > 0 ); + N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); + END; + CALL PR$STRING( .N$STR( W ) ); + END PR$NUMBER; + + /* TASK */ + + DECLARE TRUE LITERALLY '0FFH', FALSE LITERALLY '0'; + DIGIT$SUM: PROCEDURE( N )ADDRESS; /* RETURNS THE DIGIT SUM OF N */ + DECLARE N ADDRESS; + IF N < 10 THEN RETURN N; + ELSE DO; + DECLARE ( RESULT, V ) ADDRESS; + RESULT = N MOD 10; + V = N / 10; + DO WHILE V > 0; + RESULT = RESULT + ( V MOD 10 ); + V = V / 10; + END; + RETURN RESULT; + END; + END DIGIT$SUM ; + + /* SHOW THE MINIMUM MULTIPLE OF N WHERE THE DIGIT SUM OF THE MULTIPLE IS N */ + DECLARE ( M, N ) ADDRESS; + DECLARE FOUND$MULTIPLE BYTE; + DO N = 1 TO 39; + FOUND$MULTIPLE = FALSE; + M = 0; + DO WHILE NOT FOUND$MULTIPLE; + M = M + 1; + IF DIGIT$SUM( M * N ) = N THEN DO; + FOUND$MULTIPLE = TRUE; + CALL PR$CHAR( ' ' ); + IF M < 10000 THEN DO; + CALL PR$CHAR( ' ' ); + IF M < 1000 THEN DO; + CALL PR$CHAR( ' ' ); + IF M < 100 THEN DO; + CALL PR$CHAR( ' ' ); + IF M < 10 THEN CALL PR$CHAR( ' ' ); + END; + END; + END; + CALL PR$NUMBER( M ); + IF N MOD 8 = 0 THEN CALL PR$NL; + END; + END; + END; + +EOF diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Refal/minimum-multiple-of-m-where-digital-sum-equals-m.refal b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Refal/minimum-multiple-of-m-where-digital-sum-equals-m.refal new file mode 100644 index 0000000000..53f90ebd84 --- /dev/null +++ b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Refal/minimum-multiple-of-m-where-digital-sum-equals-m.refal @@ -0,0 +1,33 @@ +$ENTRY Go { + = ; +}; + +MinMult { + s.N = ; + s.N s.M, >: s.N = s.M; + s.N s.M = >; +}; + +DigSum { + 0 = 0; + s.N, : s.D e.R = <+ >>; +}; + +Cell { + s.Size e.X, : s.Cur e.Y, + : '-' = ; + s.Size e.X = e.X; +}; + +Table { + s.F s.N s.Max s.Width s.CW = +
; + s.F s.N s.Max s.Width s.CW 0 (e.Line) = + +
; + s.F s.N s.Max s.Width s.CW s.Col (e.Line), : '+' = + ; + s.F s.N s.Max s.Width s.CW s.Col (e.Line) = +
s.Max s.Width s.CW <- s.Col 1> + (e.Line >>)>; +}; diff --git a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Wren/minimum-multiple-of-m-where-digital-sum-equals-m.wren b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Wren/minimum-multiple-of-m-where-digital-sum-equals-m.wren index 7e0975930f..2602ee7e96 100644 --- a/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Wren/minimum-multiple-of-m-where-digital-sum-equals-m.wren +++ b/Task/Minimum-multiple-of-m-where-digital-sum-equals-m/Wren/minimum-multiple-of-m-where-digital-sum-equals-m.wren @@ -8,4 +8,4 @@ for (n in 1..70) { while (Int.digitSum(m * n) != n) m = m + 1 res.add(m) } -for (chunk in Lst.chunks(res, 10)) Fmt.print("$,10d", chunk) +Fmt.tprint("$,10d", res, 10) diff --git a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Wren/minimum-positive-multiple-in-base-10-using-only-0-and-1.wren b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Wren/minimum-positive-multiple-in-base-10-using-only-0-and-1.wren index 0ae9241558..94296d2288 100644 --- a/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Wren/minimum-positive-multiple-in-base-10-using-only-0-and-1.wren +++ b/Task/Minimum-positive-multiple-in-base-10-using-only-0-and-1/Wren/minimum-positive-multiple-in-base-10-using-only-0-and-1.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/big" for BigInt +import "./fmt" for Fmt +import "./big" for BigInt var b10 = Fn.new { |n| if (n == 1) { diff --git a/Task/Minkowski-question-mark-function/C-sharp/minkowski-question-mark-function.cs b/Task/Minkowski-question-mark-function/C-sharp/minkowski-question-mark-function.cs new file mode 100644 index 0000000000..984ceefc7e --- /dev/null +++ b/Task/Minkowski-question-mark-function/C-sharp/minkowski-question-mark-function.cs @@ -0,0 +1,125 @@ +using System; + +class Program +{ + const int MAXITER = 151; + + static double Minkowski(double x) + { + if (x > 1 || x < 0) + { + return Math.Floor(x) + Minkowski(x - Math.Floor(x)); + } + ulong p = (ulong)x; + ulong q = 1; + ulong r = p + 1; + ulong s = 1; + double d = 1.0; + double y = (double)p; + while (true) + { + d = d / 2; + if (y + d == y) + { + break; + } + ulong m = p + r; + if (m < 0 || p < 0) + { + break; + } + ulong n = q + s; + if (n < 0) + { + break; + } + if (x < (double)m / (double)n) + { + r = m; + s = n; + } + else + { + y = y + d; + p = m; + q = n; + } + } + return y + d; + } + + static double MinkowskiInv(double x) + { + if (x > 1 || x < 0) + { + return Math.Floor(x) + MinkowskiInv(x - Math.Floor(x)); + } + if (x == 1 || x == 0) + { + return x; + } + uint[] contFrac = new uint[] { 0 }; + uint curr = 0; + uint count = 1; + int i = 0; + while (true) + { + x *= 2; + if (curr == 0) + { + if (x < 1) + { + count++; + } + else + { + i++; + Array.Resize(ref contFrac, i + 1); + contFrac[i - 1] = count; + count = 1; + curr = 1; + x--; + } + } + else + { + if (x > 1) + { + count++; + x--; + } + else + { + i++; + Array.Resize(ref contFrac, i + 1); + contFrac[i - 1] = count; + count = 1; + curr = 0; + } + } + if (x == Math.Floor(x)) + { + contFrac[i] = count; + break; + } + if (i == MAXITER) + { + break; + } + } + double ret = 1.0 / contFrac[i]; + for (int j = i - 1; j >= 0; j--) + { + ret = contFrac[j] + 1.0 / ret; + } + return 1.0 / ret; + } + + static void Main(string[] args) + { + Console.WriteLine("{0,19:0.0000000000000000} {1,19:0.0000000000000000}", Minkowski(0.5 * (1 + Math.Sqrt(5))), 5.0 / 3.0); + Console.WriteLine("{0,19:0.0000000000000000} {1,19:0.0000000000000000}", MinkowskiInv(-5.0 / 9.0), (Math.Sqrt(13) - 7) / 6); + Console.WriteLine("{0,19:0.0000000000000000} {1,19:0.0000000000000000}", Minkowski(MinkowskiInv(0.718281828)), + MinkowskiInv(Minkowski(0.1213141516171819))); + } +} diff --git a/Task/Minkowski-question-mark-function/Wren/minkowski-question-mark-function.wren b/Task/Minkowski-question-mark-function/Wren/minkowski-question-mark-function.wren index a0cd6857f7..247ef22741 100644 --- a/Task/Minkowski-question-mark-function/Wren/minkowski-question-mark-function.wren +++ b/Task/Minkowski-question-mark-function/Wren/minkowski-question-mark-function.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var MAXITER = 151 diff --git a/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg b/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg new file mode 100644 index 0000000000..f87bdbb776 --- /dev/null +++ b/Task/Modified-random-distribution/ALGOL-68/modified-random-distribution.alg @@ -0,0 +1,44 @@ +BEGIN # Modified random distribution - translation of the Wren sample # + + next random; # initialise the random number generator # + + PROC rng = ( PROC(REAL)REAL modifier )REAL: + BEGIN + REAL r1, r2; + WHILE + r1 := random; + r2 := random; + r2 >= modifier( r1 ) + DO SKIP OD; + r1 + END # rng # ; + + PROC modifier = ( REAL x )REAL: 2 * ABS ( 0.5 - x ); + + INT n = 100 000; + INT num bins = 21; + REAL bin size = 1 / num bins; + CHAR hist char = "#"; + INT hist char size = 125; + [ 0 : num bins - 1 ]INT bins ; FOR i FROM LWB bins TO UPB bins DO bins[ i ] := 0 OD; + FOR i FROM 0 TO n DO + bins[ ENTIER ( rng( modifier ) / bin size ) ] +:= 1 + OD; + + PROC f2 = ( REAL v )STRING: # formatting routine # + BEGIN + STRING result := fixed( ABS v, 0, 2 ); + IF result[ LWB result ] = "." THEN "0" +=: result FI; + IF v < 0 THEN "-" +=: result FI; + result + END # FMT # ; + + print( ( "Modified random distribution with ", whole( n, 0 ), " samples in range [0, 1):", newline ) ); + print( ( " Range Number of samples within that range", newline ) ); + FOR i FROM LWB bins TO UPB bins DO + STRING hist = hist char * ROUND ( bins[ i ] / hist char size ); + print( ( f2( bin size * i ), " ..< " ) ); + print( ( f2( bin size * ( i + 1 ) ), " ", whole( bins[ i ], -5 ), " ", hist, newline ) ) + OD + +END diff --git a/Task/Modified-random-distribution/JavaScript/modified-random-distribution.js b/Task/Modified-random-distribution/JavaScript/modified-random-distribution.js new file mode 100644 index 0000000000..a4b56eea58 --- /dev/null +++ b/Task/Modified-random-distribution/JavaScript/modified-random-distribution.js @@ -0,0 +1,36 @@ +function modifier(x) { return (x < .5 ? -1 : +1)*(2*(x-.5)) } + +function random(m) { + let random1, random2; + while (true) { + random1 = Math.random(); + random2 = Math.random(); + if (random2 < m(random1)) { + return random1; + } + } +} + +const N = 10000; +const bins = 20; +var numbers = []; +for (i=0;i13 as the congruence modulus and you will compute f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. In other words, the function is an algebraic expression that could be used with any ring, not just integers.

- +;Related tasks: +[[Modular exponentiation]] +

diff --git a/Task/Modular-arithmetic/FreeBASIC/modular-arithmetic.basic b/Task/Modular-arithmetic/FreeBASIC/modular-arithmetic.basic new file mode 100644 index 0000000000..41ba7f43a4 --- /dev/null +++ b/Task/Modular-arithmetic/FreeBASIC/modular-arithmetic.basic @@ -0,0 +1,50 @@ +Type ModInt + As Ulongint Value + As Ulongint Modulo +End Type + +Function Add_(lhs As ModInt, rhs As ModInt) As ModInt + If lhs.Modulo <> rhs.Modulo Then Print "Cannot add rings with different modulus": End + Dim res As ModInt + res.Value = (lhs.Value + rhs.Value) Mod lhs.Modulo + res.Modulo = lhs.Modulo + Return res +End Function + +Function Multiply(lhs As ModInt, rhs As ModInt) As ModInt + If lhs.Modulo <> rhs.Modulo Then Print "Cannot multiply rings with different modulus": End + Dim res As ModInt + res.Value = (lhs.Value * rhs.Value) Mod lhs.Modulo + res.Modulo = lhs.Modulo + Return res +End Function + +Function One(self As ModInt) As ModInt + Dim res As ModInt + res.Value = 1 + res.Modulo = self.Modulo + Return res +End Function + +Function Power(self As ModInt, p As Ulongint) As ModInt + If p < 0 Then Print "p must be zero or greater": End + Dim pp As Ulongint = p + Dim pwr As ModInt = One(self) + While pp > 0 + pp -= 1 + pwr = Multiply(pwr, self) + Wend + Return pwr +End Function + +Function F(x As ModInt) As ModInt + Return Add_(Power(x, 100), Add_(x, One(x))) +End Function + +Dim x As ModInt +x.Value = 10 +x.Modulo = 13 +Dim y As ModInt = F(x) +Print Using "x ^ 100 + x + 1 for x = ModInt(&, &) is ModInt(&, &)"; x.Value; x.Modulo; y.Value; y.Modulo + +Sleep diff --git a/Task/Modular-exponentiation/Wren/modular-exponentiation.wren b/Task/Modular-exponentiation/Wren/modular-exponentiation.wren index 85ed91ae8f..aa32afa7b0 100644 --- a/Task/Modular-exponentiation/Wren/modular-exponentiation.wren +++ b/Task/Modular-exponentiation/Wren/modular-exponentiation.wren @@ -1,4 +1,4 @@ -import "/big" for BigInt +import "./big" for BigInt var a = BigInt.new("2988348162058574136915891421498819466320163312926952423791023078876139") var b = BigInt.new("2351399303373464486466122544523690094744975233415544072992656881240319") diff --git a/Task/Modular-inverse/Wren/modular-inverse.wren b/Task/Modular-inverse/Wren/modular-inverse.wren index 8e586cc652..d93312b61e 100644 --- a/Task/Modular-inverse/Wren/modular-inverse.wren +++ b/Task/Modular-inverse/Wren/modular-inverse.wren @@ -1,4 +1,4 @@ -import "/big" for BigInt +import "./big" for BigInt var a = BigInt.new(42) var b = BigInt.new(2017) diff --git a/Task/Monads-List-monad/Python/monads-list-monad.py b/Task/Monads-List-monad/Python/monads-list-monad.py index 0296e0676b..e6a7470216 100644 --- a/Task/Monads-List-monad/Python/monads-list-monad.py +++ b/Task/Monads-List-monad/Python/monads-list-monad.py @@ -2,7 +2,6 @@ from __future__ import annotations from itertools import chain -from typing import Any from typing import Callable from typing import Iterable from typing import List @@ -10,6 +9,7 @@ from typing import TypeVar T = TypeVar("T") +U = TypeVar("U") class MList(List[T]): @@ -17,15 +17,15 @@ class MList(List[T]): def unit(cls, value: Iterable[T]) -> MList[T]: return cls(value) - def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]: + def bind(self, func: Callable[[T], MList[U]]) -> MList[U]: return MList(chain.from_iterable(map(func, self))) - def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]: + def __rshift__(self, func: Callable[[T], MList[U]]) -> MList[U]: return self.bind(func) if __name__ == "__main__": - # Chained int and string functions + # Chained int and string functions. print( MList([1, 99, 4]) .bind(lambda val: MList([val + 1])) @@ -39,14 +39,14 @@ if __name__ == "__main__": >> (lambda val: MList([f"${val}.00"])) ) - # Cartesian product of [1..5] and [6..10] + # Cartesian product of [1..5] and [6..10]. print( MList(range(1, 6)).bind( lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)])) ) ) - # Pythagorean triples with elements between 1 and 25 + # Pythagorean triples with elements between 1 and 25. print( MList(range(1, 26)).bind( lambda x: MList(range(x + 1, 26)).bind( diff --git a/Task/Monads-Maybe-monad/Python/monads-maybe-monad.py b/Task/Monads-Maybe-monad/Python/monads-maybe-monad.py index 6e31696414..4b3c8bd33f 100644 --- a/Task/Monads-Maybe-monad/Python/monads-maybe-monad.py +++ b/Task/Monads-Maybe-monad/Python/monads-maybe-monad.py @@ -1,7 +1,6 @@ -"""A Maybe Monad. Requires Python >= 3.7 for type hints.""" +"""A Maybe monad. Requires Python >= 3.7 for type hints.""" from __future__ import annotations -from typing import Any from typing import Callable from typing import Generic from typing import Optional @@ -10,6 +9,7 @@ from typing import Union T = TypeVar("T") +U = TypeVar("U") class Maybe(Generic[T]): @@ -19,10 +19,10 @@ class Maybe(Generic[T]): else: self.value = value - def __rshift__(self, func: Callable[[Optional[T]], Maybe[Any]]): + def __rshift__(self, func: Callable[[Optional[T]], Maybe[U]]) -> Maybe[U]: return self.bind(func) - def bind(self, func: Callable[[Optional[T]], Maybe[Any]]) -> Maybe[Any]: + def bind(self, func: Callable[[Optional[T]], Maybe[U]]) -> Maybe[U]: return func(self.value) def __str__(self): @@ -31,22 +31,23 @@ class Maybe(Generic[T]): def plus_one(value: Optional[int]) -> Maybe[int]: if value is not None: - return Maybe[int](value + 1) - return Maybe[int](None) + return Maybe(value + 1) + return Maybe(None) def currency(value: Optional[int]) -> Maybe[str]: if value is not None: - return Maybe[str](f"${value}.00") - return Maybe[str](None) + return Maybe(f"${value}.00") + return Maybe(None) if __name__ == "__main__": test_cases = [1, 99, None, 4] for case in test_cases: - m_int = Maybe[int](case) - result = m_int >> plus_one >> currency + result = Maybe(case) >> plus_one >> currency + # or.. - # result = m_int.bind(plus_one).bind(currency) + # result = Maybe(case).bind(plus_one).bind(currency) + print(f"{str(case):<4} -> {result}") diff --git a/Task/Monads-Maybe-monad/Wren/monads-maybe-monad.wren b/Task/Monads-Maybe-monad/Wren/monads-maybe-monad.wren index 5db69e4aa1..1ae1f166b4 100644 --- a/Task/Monads-Maybe-monad/Wren/monads-maybe-monad.wren +++ b/Task/Monads-Maybe-monad/Wren/monads-maybe-monad.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt class Maybe { construct new(value) { @@ -27,5 +27,5 @@ for (i in [3, 4, null, 5]) { var m2 = m1.bind(decrement).bind(triple) var s1 = (m1.value) ? "%(m1.value)" : "none" var s2 = (m2.value) ? "%(m2.value)" : "none" - System.print("%(Fmt.s(4, s1)) -> %(s2)") + Fmt.print("$4s -> $s", s1, s2) } diff --git a/Task/Monads-Writer-monad/Python/monads-writer-monad.py b/Task/Monads-Writer-monad/Python/monads-writer-monad.py index a48aaf9bdf..5cc493d3a8 100644 --- a/Task/Monads-Writer-monad/Python/monads-writer-monad.py +++ b/Task/Monads-Writer-monad/Python/monads-writer-monad.py @@ -5,7 +5,6 @@ import functools import math import os -from typing import Any from typing import Callable from typing import Generic from typing import List @@ -14,6 +13,7 @@ from typing import Union T = TypeVar("T") +U = TypeVar("U") class Writer(Generic[T]): @@ -25,11 +25,11 @@ class Writer(Generic[T]): self.value = value self.msgs = list(f"{msg}: {self.value}" for msg in msgs) - def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: + def bind(self, func: Callable[[T], Writer[U]]) -> Writer[U]: writer = func(self.value) return Writer(writer, *self.msgs) - def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]: + def __rshift__(self, func: Callable[[T], Writer[U]]) -> Writer[U]: return self.bind(func) def __str__(self): @@ -39,11 +39,11 @@ class Writer(Generic[T]): return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")" -def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]: +def lift(func: Callable[[T], U], msg: str) -> Callable[[T], Writer[U]]: """Return a writer monad version of the simple function `func`.""" @functools.wraps(func) - def wrapped(value): + def wrapped(value: T) -> Writer[U]: return Writer(func(value), msg) return wrapped @@ -51,7 +51,13 @@ def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]: if __name__ == "__main__": square_root = lift(math.sqrt, "square root") - add_one = lift(lambda x: x + 1, "add one") - half = lift(lambda x: x / 2, "div two") + + add_one: Callable[[Union[int, float]], Writer[Union[int, float]]] = lift( + lambda x: x + 1, "add one" + ) + + half: Callable[[Union[int, float]], Writer[float]] = lift( + lambda x: x / 2, "div two" + ) print(Writer(5, "initial") >> square_root >> add_one >> half) diff --git a/Task/Monads-Writer-monad/Wren/monads-writer-monad.wren b/Task/Monads-Writer-monad/Wren/monads-writer-monad.wren index 99eaec3424..2fe86e317f 100644 --- a/Task/Monads-Writer-monad/Wren/monads-writer-monad.wren +++ b/Task/Monads-Writer-monad/Wren/monads-writer-monad.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt class Mwriter { construct new(value, log) { diff --git a/Task/Monte-Carlo-methods/Wren/monte-carlo-methods.wren b/Task/Monte-Carlo-methods/Wren/monte-carlo-methods.wren index 20fb20edaa..b5b54a9246 100644 --- a/Task/Monte-Carlo-methods/Wren/monte-carlo-methods.wren +++ b/Task/Monte-Carlo-methods/Wren/monte-carlo-methods.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/fmt" for Fmt +import "./fmt" for Fmt var rand = Random.new() diff --git a/Task/Monty-Hall-problem/EasyLang/monty-hall-problem.easy b/Task/Monty-Hall-problem/EasyLang/monty-hall-problem.easy index 1ee159f97e..58f05bec08 100644 --- a/Task/Monty-Hall-problem/EasyLang/monty-hall-problem.easy +++ b/Task/Monty-Hall-problem/EasyLang/monty-hall-problem.easy @@ -1,12 +1,12 @@ max = 1000000 for i = 1 to max - car_door = random 3 - chosen_door = random 3 + car_door = randint 3 + chosen_door = randint 3 if car_door <> chosen_door montys_door = 6 - car_door - chosen_door else repeat - montys_door = random 3 + montys_door = randint 3 until montys_door <> car_door . . diff --git a/Task/Morse-code/Wren/morse-code-1.wren b/Task/Morse-code/Wren/morse-code-1.wren index ab4144f2c5..28fc71dfca 100644 --- a/Task/Morse-code/Wren/morse-code-1.wren +++ b/Task/Morse-code/Wren/morse-code-1.wren @@ -1,5 +1,5 @@ -import "/str" for Str -import "/sound" for Wav +import "./str" for Str +import "./sound" for Wav var charToMorse = { "!": "---.", "\"": ".-..-.", "$": "...-..-", "'": ".----.", diff --git a/Task/Motzkin-numbers/Wren/motzkin-numbers.wren b/Task/Motzkin-numbers/Wren/motzkin-numbers.wren index 46a5716b30..1bf9b98a87 100644 --- a/Task/Motzkin-numbers/Wren/motzkin-numbers.wren +++ b/Task/Motzkin-numbers/Wren/motzkin-numbers.wren @@ -1,5 +1,5 @@ -import "/long" for ULong -import "/fmt" for Fmt +import "./long" for ULong +import "./fmt" for Fmt var motzkin = Fn.new { |n| var m = List.filled(n+1, 0) diff --git a/Task/Move-to-front-algorithm/Wren/move-to-front-algorithm.wren b/Task/Move-to-front-algorithm/Wren/move-to-front-algorithm.wren index f67708be00..c69ff30dd0 100644 --- a/Task/Move-to-front-algorithm/Wren/move-to-front-algorithm.wren +++ b/Task/Move-to-front-algorithm/Wren/move-to-front-algorithm.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/seq" for Lst +import "./fmt" for Fmt +import "./seq" for Lst var encode = Fn.new { |s| if (s.isEmpty) return [] diff --git a/Task/Multi-base-primes/FreeBASIC/multi-base-primes.basic b/Task/Multi-base-primes/FreeBASIC/multi-base-primes.basic new file mode 100644 index 0000000000..a1c357dfbe --- /dev/null +++ b/Task/Multi-base-primes/FreeBASIC/multi-base-primes.basic @@ -0,0 +1,98 @@ +Const maxBase = 36 ' o 62 +Function isPrime(Byval ValorEval As Integer) As Boolean + If ValorEval < 2 Then Return False + If ValorEval Mod 2 = 0 Then Return ValorEval = 2 + If ValorEval Mod 3 = 0 Then Return ValorEval = 3 + Dim d As Integer = 5 + While d * d <= ValorEval + If ValorEval Mod d = 0 Then Return False Else d += 2 + Wend + Return True +End Function +Function maxval(arr() As Integer) As Integer + Dim As Integer max_value = arr(0) + For i As Integer = 1 To Ubound(arr) + If arr(i) > max_value Then max_value = arr(i) + Next + Return max_value +End Function +Function join(arr() As Integer, delimiter As String) As String + Dim As String result = "" + For i As Integer = 0 To Ubound(arr) + result &= Str(arr(i)) + If i < Ubound(arr) Then result &= delimiter + Next + Return result +End Function + +Function evalPoly(x As Integer, p() As Integer) As Integer + Dim result As Integer = 0 + For y As Integer = 0 To Ubound(p) + result = result * x + p(y) + Next + Return result +End Function + +Function stringify(digits() As Integer) As String + Dim res As String + For i As Integer = 0 To Ubound(digits) + Dim di As Integer = digits(i) + res &= Chr(Iif(di <= 9, di + Asc("0"), Iif(di < 36, di + Asc("A") - 10, di + Asc("a") - 36))) + Next + Return res +End Function + +Sub maxPrimeVases(ndig As Integer, maxVase As Integer) + Dim As Double t0 = Timer + Dim As String maxPrimeBases() + Dim As Integer digits(ndig - 1) + Dim As Integer maxlen = 0 + Dim As Integer limit = 10 ^ ndig + Dim As Integer maxDigit = maxBase + If ndig > 1 Then digits(0) = 1 + Do + For i As Integer = Ubound(digits) To 0 Step -1 + Dim As Integer di = digits(i) + 1 + If di < maxDigit Then + digits(i) = di + Exit For + Else + digits(i) = 0 + End If + Next + Dim As Integer minBase = maxval(digits()) + 1 + Dim As Integer maxPoss = maxBase - minBase + 1 + If minBase = 1 Then Exit Do + Dim As Integer bases() + For base_ As Integer = minBase To maxBase + If isPrime(evalPoly(base_, digits())) Then + Redim Preserve bases(Ubound(bases) + 1) + bases(Ubound(bases)) = base_ + Else + maxPoss -= 1 + If maxPoss < maxlen Then Exit For + End If + Next + Dim As Integer l = Ubound(bases) + 1 + If l > maxlen Then + maxlen = l + maxDigit = maxBase - maxlen + Redim maxPrimeBases(0) + End If + If l = maxlen Then + Redim Preserve maxPrimeBases(Ubound(maxPrimeBases) + 1) + maxPrimeBases(Ubound(maxPrimeBases)) = Chr(10) & stringify(digits()) & " => " & join(bases(), ", ") + End If + Loop + Print Using "# character strings which are prime in most bases: ## (#.##s):"; ndig; maxlen; Timer - t0; + For i As Integer = 0 To Ubound(maxPrimeBases) + Print maxPrimeBases(i); + Next + Print Chr(10) +End Sub + +For n As Integer = 1 To Iif(maxBase > 36, 4, 6) + maxPrimeVases(n, maxBase) +Next n + +Sleep diff --git a/Task/Multi-base-primes/Wren/multi-base-primes.wren b/Task/Multi-base-primes/Wren/multi-base-primes.wren index 426b98264b..1a4e24911d 100644 --- a/Task/Multi-base-primes/Wren/multi-base-primes.wren +++ b/Task/Multi-base-primes/Wren/multi-base-primes.wren @@ -1,4 +1,4 @@ -import "/math" for Int, Nums +import "./math" for Int, Nums var maxDepth = 5 var maxBase = 36 diff --git a/Task/Multi-dimensional-array/Wren/multi-dimensional-array.wren b/Task/Multi-dimensional-array/Wren/multi-dimensional-array.wren index c79084831f..9a3739f55d 100644 --- a/Task/Multi-dimensional-array/Wren/multi-dimensional-array.wren +++ b/Task/Multi-dimensional-array/Wren/multi-dimensional-array.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt // create a 4 dimensional list of the required size and initialize successive elements to the values 1 to 120 var m = 1 diff --git a/Task/Multifactorial/Wren/multifactorial.wren b/Task/Multifactorial/Wren/multifactorial.wren index 9738c2bd12..726ec89e1a 100644 --- a/Task/Multifactorial/Wren/multifactorial.wren +++ b/Task/Multifactorial/Wren/multifactorial.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var mf = Fn.new { |n, d| var prod = 1 diff --git a/Task/Multiple-distinct-objects/Elena/multiple-distinct-objects.elena b/Task/Multiple-distinct-objects/Elena/multiple-distinct-objects.elena index 36605ad6a5..0b072e17db 100644 --- a/Task/Multiple-distinct-objects/Elena/multiple-distinct-objects.elena +++ b/Task/Multiple-distinct-objects/Elena/multiple-distinct-objects.elena @@ -5,7 +5,7 @@ class Foo; // create a list of disting object fill(n) - = RangeEnumerator.new(1,n).selectBy:(x => new Foo()).toArray(); + = RangeEnumerator.new(1,n).selectBy::(x => new Foo()).toArray(); // testing public program() diff --git a/Task/Multiple-regression/Wren/multiple-regression.wren b/Task/Multiple-regression/Wren/multiple-regression.wren index ec641751ec..adaf9a1343 100644 --- a/Task/Multiple-regression/Wren/multiple-regression.wren +++ b/Task/Multiple-regression/Wren/multiple-regression.wren @@ -1,4 +1,4 @@ -import "/matrix" for Matrix +import "./matrix" for Matrix var multipleRegression = Fn.new { |y, x| var cy = y.transpose diff --git a/Task/Multiplication-tables/Wren/multiplication-tables.wren b/Task/Multiplication-tables/Wren/multiplication-tables.wren index 8a8cab2876..cebe8a260b 100644 --- a/Task/Multiplication-tables/Wren/multiplication-tables.wren +++ b/Task/Multiplication-tables/Wren/multiplication-tables.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] Fmt.print(" x | $4d", nums) diff --git a/Task/Multiplicative-order/Wren/multiplicative-order.wren b/Task/Multiplicative-order/Wren/multiplicative-order.wren index 7dcf476b77..0eba22c44e 100644 --- a/Task/Multiplicative-order/Wren/multiplicative-order.wren +++ b/Task/Multiplicative-order/Wren/multiplicative-order.wren @@ -1,4 +1,4 @@ -import "/big" for BigInt +import "./big" for BigInt class PExp { construct new(prime, exp) { diff --git a/Task/Multisplit/C++/multisplit-3.cpp b/Task/Multisplit/C++/multisplit-3.cpp new file mode 100644 index 0000000000..16384c1d1d --- /dev/null +++ b/Task/Multisplit/C++/multisplit-3.cpp @@ -0,0 +1,127 @@ +/* multisplit.cpp */ +#include +#include +#include +#include +#include + +/* C++23 example for Multisplit 6 Jan 2024 + email: + spikeysnack@gmail.com + + compile: + g++-13 -std=c++23 -Wall -o multisplit multisplit.cpp +*/ + +// extra info +#define _EXTRA + +// aliases +using std::string; +using std::vector; +using str_vec = vector; +using std::cout; + + +// constants +constexpr static const size_t npos = -1; + +// function signatures +string replace_all(string& str, string& remove, string& insert ); + +str_vec split_on_delim(string& str, const string& delims); + +str_vec Multisplit( string& input, const str_vec& seps); + +// functions + +// replace all substrings in string +// a = "dogs and cats and dogs and cats and birds" +// replace(a, "cats" , "fish"); +// ==> "dogs and fish and dogs and fish and birds" + +string replace_all(string& str, + const string& remove, + const string& insert ){ + string s{str}; + string::size_type pos = 0; + + #ifdef _EXTRA + const string rightarrow{"\u2B62"}; //unicode arrow + auto ex = std::format("match: {}\t{} ", remove, rightarrow); + std::cerr << ex; + #endif + + while ((pos = s.find(remove, pos)) != npos){ + s.replace(pos, remove.size(), insert); + pos++; + } + + return s; +} + + +// create a string vector from a string, +// split on a delimiter string +// x = "ab:cde:fgh:ijk" +// split_on_delim( x, ":"); +// ==> { "ab", "cde", "fgh", "ijk" } + +str_vec split_on_delim(string& str, const string& delims) { + string::size_type beg, pos = 0; + str_vec sv; + string tmp; + + while ( (beg = str.find_first_not_of(delims, pos)) != npos ){ + + pos = str.find_first_of(delims, beg + 1); + + tmp = { str.substr(beg, pos - beg) }; + + sv.push_back(tmp); + } + return sv; +} + + +str_vec Multisplit( string& input, const str_vec& seps) { + + string s1{input}; + str_vec sv; + + for( auto sep : seps){ + s1 = replace_all(s1, sep, "^"); // space sep + +#ifdef _EXTRA + std::cerr << s1 << "\n"; +#endif + sv = split_on_delim(s1, "^"); // split + } + return sv; +} + + +/* main program */ + +int main(){ + + string sample{"a!===b=!=c"}; + + const str_vec seps {"!=", "==", "="}; + + auto s = std::format("sample: \t{}\n", sample); + + cout << s; + + auto sv = Multisplit(sample, seps); + + for( auto s : sv){ + auto out = std::format( "{}\t" , s); + cout << out; + } + cout << "\n"; + + return 0; +} + +// end diff --git a/Task/Multisplit/Wren/multisplit.wren b/Task/Multisplit/Wren/multisplit.wren index 6b7d5b1843..a619d5e357 100644 --- a/Task/Multisplit/Wren/multisplit.wren +++ b/Task/Multisplit/Wren/multisplit.wren @@ -1,5 +1,5 @@ -import "/pattern" for Pattern -import "/fmt" for Fmt +import "./pattern" for Pattern +import "./fmt" for Fmt var input = "a!===b=!=c" var p = Pattern.new("[/=/=|!/=|/=]") diff --git a/Task/Munchausen-numbers/EasyLang/munchausen-numbers.easy b/Task/Munchausen-numbers/EasyLang/munchausen-numbers.easy new file mode 100644 index 0000000000..4e621dfb4e --- /dev/null +++ b/Task/Munchausen-numbers/EasyLang/munchausen-numbers.easy @@ -0,0 +1,12 @@ +for i = 1 to 5000 + sum = 0 + n = i + while n > 0 + dig = n mod 10 + sum += pow dig dig + n = n div 10 + . + if sum = i + print i + . +. diff --git a/Task/Munchausen-numbers/Langur/munchausen-numbers-1.langur b/Task/Munchausen-numbers/Langur/munchausen-numbers-1.langur deleted file mode 100644 index 6f1a749f89..0000000000 --- a/Task/Munchausen-numbers/Langur/munchausen-numbers-1.langur +++ /dev/null @@ -1,5 +0,0 @@ -# sum power of digits -val .spod = f(.n) fold f{+}, map(f (.x-'0') ^ (.x-'0'), s2cp toString .n) - -# Munchausen -writeln "Answers: ", filter f(.n) .n == .spod(.n), series 0..5000 diff --git a/Task/Munchausen-numbers/Langur/munchausen-numbers-2.langur b/Task/Munchausen-numbers/Langur/munchausen-numbers.langur similarity index 100% rename from Task/Munchausen-numbers/Langur/munchausen-numbers-2.langur rename to Task/Munchausen-numbers/Langur/munchausen-numbers.langur diff --git a/Task/Munchausen-numbers/Phix/munchausen-numbers-1.phix b/Task/Munchausen-numbers/Phix/munchausen-numbers-1.phix index 14fa63a591..0c62ca9448 100644 --- a/Task/Munchausen-numbers/Phix/munchausen-numbers-1.phix +++ b/Task/Munchausen-numbers/Phix/munchausen-numbers-1.phix @@ -1,18 +1,17 @@ -(phixonline)--> - with javascript_semantics - constant powers = sq_power(tagset(9,0),tagset(9,0)) +with javascript_semantics +constant powers = sq_power(tagset(9),tagset(9)) - function munchausen(integer n) - integer n0 = n - atom total = 0 - while n!=0 do - total += powers[remainder(n,10)+1] - n = floor(n/10) - end while - return (total==n0) - end function +function munchausen(integer n) + integer n0 = n + atom total = 0 + while n!=0 do + integer r = remainder(n,10) + if r then total += powers[r] end if + n = floor(n/10) + end while + return (total==n0) +end function - for i=1 to 5000 do - if munchausen(i) then ?i end if - end for - - with javascript_semantics - function munchausen(integer lo, hi) - integer maxlen = length(sprint(hi)) - string digits = sprint(lo) - sequence res = {} - while length(digits)<=maxlen do - atom tot = 0 - for j=1 to length(digits) do - integer d = digits[j]-'0' - if d then tot += power(d,d) end if - end for - if sort(sprint(tot))=digits then - res &= tot - end if - for j=length(digits) to 0 by -1 do - if j=0 then - digits = repeat('0',length(digits)+1) - exit - elsif digits[j]<'9' then - digits[j..$] = digits[j]+1 - exit - end if - end for - end while - return res - end function - atom t0 = time() - ?munchausen(1,5000) - ?munchausen(0,500_000_000) - ?elapsed(time()-t0) - - without js -- (file i/o) - puts(1,{"\n\ntrue\n\n","\n\nfalse\n\n"}[1+(gets(open(command_line()[2],"r"))!=gets(0))]) - - function is_perfect(integer n) - return sum(factors(n,-1))=n - end function +function is_perfect(integer n) + return sum(factors(n,-1))=n +end function - for i=2 to 100000 do - if is_perfect(i) then ?i end if - end for - - with javascript_semantics - -- demo\rosetta\Perfect_numbers.exw (includes native version above) - include mpfr.e - mpz n = mpz_init(), p = mpz_init() - for i=2 to 159 do - mpz_ui_pow_ui(n, 2, i) - mpz_sub_ui(n, n, 1) - if mpz_prime(n) then - mpz_ui_pow_ui(p,2,i-1) - mpz_mul(n,n,p) - printf(1, "%d %s\n",{i,mpz_get_str(n,comma_fill:=true)}) - end if - end for - n = mpz_free(n) -' f ' has a count of: ' right(frequency.d.f,w)||, + ', frequency of:' right(format(frequency.d.f/n*100,,4)'%.',10) + End + End +Say 'Frequency analysis:' time('E') 'seconds' +sum=0 +Say 'last digit Number of occurrences' +Do i=1 To 9 + If cnt.i>0 Then + Say ' 'i format(cnt.i,8) + sum+=cnt.i + End +Say ' 'format(sum,10) diff --git a/Task/Prime-conspiracy/Wren/prime-conspiracy.wren b/Task/Prime-conspiracy/Wren/prime-conspiracy.wren index 4b6246ce11..4fac1ee3ac 100644 --- a/Task/Prime-conspiracy/Wren/prime-conspiracy.wren +++ b/Task/Prime-conspiracy/Wren/prime-conspiracy.wren @@ -1,6 +1,6 @@ -import "/fmt" for Fmt -import "/math" for Int -import "/sort" for Sort +import "./fmt" for Fmt +import "./math" for Int +import "./sort" for Sort var reportTransitions = Fn.new { |transMap, num| var keys = transMap.keys.toList diff --git a/Task/Prime-decomposition/Elm/prime-decomposition.elm b/Task/Prime-decomposition/Elm/prime-decomposition.elm new file mode 100644 index 0000000000..f5c558e297 --- /dev/null +++ b/Task/Prime-decomposition/Elm/prime-decomposition.elm @@ -0,0 +1,67 @@ +module Main exposing (main) + +import Html exposing (Html, div, h1, text) +import Html.Attributes exposing (style) + +-- See live: +-- https://ellie-app.com/pMYxVPQ4fvca1 + +accumulator : List Int +accumulator = +    [] + +compositeNr = 84894624407 + +ts = +    showFactors compositeNr 2 accumulator + + +main = +        div +            [ style "margin" "5%" +            , style "font-size" "1.5em" +            , style "color" "blue" +            ] +            [ h1 [] [ text "Prime Factorizer" ] +            , text +                ("Prime factors: " +                    ++ listAsString ts +                    ++ " from number " +                    ++ String.fromInt (List.product ts) +                ) +            ] + + +showFactors : Int -> Int -> List Int -> List Int +showFactors number factor acc = +    if number < 2 then +        acc +        -- returns the final result if number < 2 +    else if +        modBy factor number == 0 +        -- modulo used to get prime factors + then let +            v2 : List Int +            v2 = +                factor :: acc +            number2 : Int +            number2 = +                number // factor +        in +        showFactors number2 factor v2 +        -- recursive call +        -- this modulus function is used +        -- in order to output factor !=2 +    else +        let +            factor2 : Int +            factor2 = +                factor + 1 +        in +        showFactors number factor2 acc + +listAsString : List Int -> String +listAsString myList = +    List.map String.fromInt myList +        |> List.map (\el -> " " ++ el) +        |> List.foldl (++) " " diff --git a/Task/Prime-decomposition/Wren/prime-decomposition.wren b/Task/Prime-decomposition/Wren/prime-decomposition.wren index 2b429cc462..19a4429c14 100644 --- a/Task/Prime-decomposition/Wren/prime-decomposition.wren +++ b/Task/Prime-decomposition/Wren/prime-decomposition.wren @@ -1,5 +1,5 @@ -import "/big" for BigInt -import "/fmt" for Fmt +import "./big" for BigInt +import "./fmt" for Fmt var vals = [1 << 31, 1234567, 333333, 987653, 2 * 3 * 5 * 7 * 11 * 13 * 17] for (val in vals) { diff --git a/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/C-sharp/prime-numbers-whose-neighboring-pairs-are-tetraprimes.cs b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/C-sharp/prime-numbers-whose-neighboring-pairs-are-tetraprimes.cs new file mode 100644 index 0000000000..fa8e1a61c6 --- /dev/null +++ b/Task/Prime-numbers-whose-neighboring-pairs-are-tetraprimes/C-sharp/prime-numbers-whose-neighboring-pairs-are-tetraprimes.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; + +public class PrimeNumbersNeighboringPairsTetraprimes +{ + private static List primes; + + public static void Main(string[] args) + { + ListPrimeNumbers(10_000_000); + + int largestPrime5 = LargestLessThan(100_000); + int largestPrime6 = LargestLessThan(1_000_000); + int largestPrime7 = primes[primes.Count - 1]; + var tetrasPreceding = new List(); + var tetrasFollowing = new List(); + int sevensPreceding = 0; + int sevensFollowing = 0; + int limit = 100_000; + + foreach (var prime in primes) + { + if (IsTetraPrime(prime - 1) && IsTetraPrime(prime - 2)) + { + tetrasPreceding.Add(prime); + if ((prime - 1) % 7 == 0 || (prime - 2) % 7 == 0) + { + sevensPreceding++; + } + } + + if (IsTetraPrime(prime + 1) && IsTetraPrime(prime + 2)) + { + tetrasFollowing.Add(prime); + if ((prime + 1) % 7 == 0 || (prime + 2) % 7 == 0) + { + sevensFollowing++; + } + } + + if (prime == largestPrime5 || prime == largestPrime6 || prime == largestPrime7) + { + for (int i = 0; i <= 1; i++) + { + List tetras = (i == 0) ? new List(tetrasPreceding) : new List(tetrasFollowing); + int size = tetras.Count; + int sevens = (i == 0) ? sevensPreceding : sevensFollowing; + string text = (i == 0) ? "preceding" : "following"; + + Console.Write("Found " + size + " primes under " + limit + " whose " + text + " neighboring pair are tetraprimes"); + if (prime == largestPrime5) + { + Console.WriteLine(":"); + for (int j = 0; j < size; j++) + { + Console.Write($"{tetras[j],7}{(j % 10 == 9 ? "\n" : "")}"); + } + Console.WriteLine(); + } + Console.WriteLine(); + Console.WriteLine("of which " + sevens + " have a neighboring pair one of whose factors is 7."); + Console.WriteLine(); + + var gaps = new List(); + for (int k = 0; k < size - 1; k++) + { + gaps.Add(tetras[k + 1] - tetras[k]); + } + gaps.Sort(); + int minimum = gaps[0]; + int maximum = gaps[gaps.Count - 1]; + int middle = Median(gaps); + Console.WriteLine("Minimum gap between those " + size + " primes: " + minimum); + Console.WriteLine("Median gap between those " + size + " primes: " + middle); + Console.WriteLine("Maximum gap between those " + size + " primes: " + maximum); + Console.WriteLine(); + } + limit *= 10; + } + } + } + + private static bool IsTetraPrime(int number) + { + int count = 0; + int previousFactor = 1; + foreach (var prime in primes) + { + int limit = prime * prime; + if (count == 0) + { + limit *= limit; + } + else if (count == 1) + { + limit *= prime; + } + if (limit <= number) + { + while (number % prime == 0) + { + if (count == 4 || prime == previousFactor) + { + return false; + } + count++; + number /= prime; + previousFactor = prime; + } + } + else + { + break; + } + } + + if (number > 1) + { + if (count == 4 || number == previousFactor) + { + return false; + } + count++; + } + return count == 4; + } + + private static int Median(List list) + { + int size = list.Count; + if (size % 2 == 0) + { + return (list[size / 2 - 1] + list[size / 2]) / 2; + } + return list[size / 2]; + } + + private static int LargestLessThan(int number) + { + int index = primes.BinarySearch(number); + if (index > 0) + { + return primes[index - 1]; + } + return primes[~index - 2]; + } + + private static void ListPrimeNumbers(int limit) + { + int halfLimit = (limit + 1) / 2; + var composite = new bool[halfLimit]; + for (int i = 1, p = 3; i < halfLimit; p += 2, i++) + { + if (!composite[i]) + { + for (int j = i + p; j < halfLimit; j += p) + { + composite[j] = true; + } + } + } + + primes = new List { 2 }; + for (int i = 1, p = 3; i < halfLimit; p += 2, i++) + { + if (!composite[i]) + { + primes.Add(p); + } + } + } +} diff --git a/Task/Prime-triangle/FreeBASIC/prime-triangle.basic b/Task/Prime-triangle/FreeBASIC/prime-triangle.basic new file mode 100644 index 0000000000..3c7b2543af --- /dev/null +++ b/Task/Prime-triangle/FreeBASIC/prime-triangle.basic @@ -0,0 +1,106 @@ +Dim Shared As Uinteger maxNumber = 20 ' Largest number we will consider. +Dim Shared As Uinteger prime(2 * maxNumber) ' prime sieve. + +Function countArrangements(Byval n As Uinteger) As Uinteger + Dim As Uinteger i + If n < 2 Then ' No solutions for n < 2. + Return 0 + Elseif n < 4 Then + ' For 2 and 3. there is only 1 solution: 1, 2 and 1, 2, 3. + For i = 1 To n + Print Using "###"; i; + Next i + Print + Return 1 + Else + ' 4 or more - must find the solutions. + Dim As Boolean printSolution = True + Dim As Boolean used(n) + Dim As Uinteger number(n) + ' The triangle row must have 1 in the leftmost and n in the rightmost elements. + ' The numbers must alternate between even and odd in order for the sums to be prime. + For i = 0 To n - 1 + number(i) = i Mod 2 + Next i + used(1) = True + number(n) = n + used(n) = True + ' Find the intervening numbers and count the solutions. + Dim As Uinteger count = 0 + Dim As Uinteger p = 2 + Do While p > 0 + Dim As Uinteger p1 = number(p - 1) + Dim As Uinteger current = number(p) + Dim As Uinteger sgte = current + 2 + Do While sgte < n Andalso (Not prime(p1 + sgte) Or used(sgte)) + sgte += 2 + Loop + If sgte >= n Then + sgte = 0 + End If + If p = n - 1 Then + ' We are at the final number before n. + ' It must be the final even/odd number preceded by the final odd/even number. + If sgte <> 0 Then + ' Possible solution. + If prime(sgte + n) Then + ' Found a solution. + count += 1 + If printSolution Then + For i = 1 To n - 2 + Print Using "###"; number(i); + Next i + Print Using "###"; sgte; n + printSolution = False + End If + End If + sgte = 0 + End If + ' Backtrack for more solutions. + p -= 1 + ' There will be a further backtrack as next is 0 ( there could only be one possible number at p - 1 ). + End If + If sgte <> 0 Then + ' have a/another number that can appear at p. + used(current) = False + used(sgte) = True + number(p) = sgte + ' Haven't found all the intervening digits yet. + p += 1 + Elseif p <= 2 Then + ' No more solutions. + p = 0 + Else + ' Can't find a number for this position, backtrack. + used(number(p)) = False + number(p) = p Mod 2 + p -= 1 + End If + Loop + Return count + End If +End Function + +Dim As Integer i, s, n +prime(2) = True +For i = 3 To Ubound(prime) Step 2 + prime(i) = True +Next i +For i = 3 To Cint(Sqr(Ubound(prime))) Step 2 + If prime(i) Then + For s = i * i To Ubound(prime) Step i + i + prime(s) = False + Next s + End If +Next i + +Dim As Integer arrangements(maxNumber) +For n = 2 To Ubound(arrangements) + arrangements(n) = countArrangements(n) +Next n +For n = 2 To Ubound(arrangements) + Print arrangements(n); +Next n +Print + +Sleep diff --git a/Task/Primes---allocate-descendants-to-their-ancestors/Wren/primes---allocate-descendants-to-their-ancestors.wren b/Task/Primes---allocate-descendants-to-their-ancestors/Wren/primes---allocate-descendants-to-their-ancestors.wren index cdbb8fc3d5..0d853aab2a 100644 --- a/Task/Primes---allocate-descendants-to-their-ancestors/Wren/primes---allocate-descendants-to-their-ancestors.wren +++ b/Task/Primes---allocate-descendants-to-their-ancestors/Wren/primes---allocate-descendants-to-their-ancestors.wren @@ -1,6 +1,6 @@ -import "/math" for Int -import "/sort" for Sort -import "/fmt" for Fmt +import "./math" for Int +import "./sort" for Sort +import "./fmt" for Fmt var maxSum = 99 diff --git a/Task/Primorial-numbers/JavaScript/primorial-numbers-1.js b/Task/Primorial-numbers/JavaScript/primorial-numbers-1.js new file mode 100644 index 0000000000..9355e44301 --- /dev/null +++ b/Task/Primorial-numbers/JavaScript/primorial-numbers-1.js @@ -0,0 +1,48 @@ +{ // calculate and show some primorial numbers + 'use strict' + + let primorial = 1n + let prime = 1n + let pn = [] + const maxNumber = 2000000 + let isPrime = [] + for( let i = 1; i <= maxNumber; i ++ ){ isPrime[ i ] = i % 2 != 0 } + isPrime[ 1 ] = false + isPrime[ 2 ] = true + const rootMaxNumber = Math.floor( Math.sqrt( maxNumber ) ) + for( let s = 3; s <= rootMaxNumber; s += 2 ){ + if( isPrime[ s ] ){ + for( let p = s * s; p <= maxNumber; p += s ){ isPrime[ p ] = false } + } + } + + const primeMax = 100000 + pn[ 0 ] = 1 + let nextToShow = 10 + for( let i = 1; i <= primeMax; i ++ ){ + // find the next prime + prime += 1n + while( ! isPrime[ prime ] ){ prime += 1n } + primorial *= prime + if( i < 10 ){ + pn[ i ] = primorial + } + else if( i == nextToShow ){ + if( nextToShow < 10000 ){ + nextToShow *= 10 + } + else{ + nextToShow += 10000 + } + if( i == 10 ){ console.log( "primorials 0-9: ", pn.toString() ) } + // show the number of digits in the primorial + let p = primorial + let length = 0 + while( p > 0 ){ + length += 1 + p /= 10n + } + console.log( "length of primorial " + i + " is "+ length ) + } + } +} diff --git a/Task/Primorial-numbers/JavaScript/primorial-numbers-2.js b/Task/Primorial-numbers/JavaScript/primorial-numbers-2.js new file mode 100644 index 0000000000..9c1691961a --- /dev/null +++ b/Task/Primorial-numbers/JavaScript/primorial-numbers-2.js @@ -0,0 +1,56 @@ +{ // calculate and show some primorial numbers + 'use strict' + + let primorial = 1n + let prime = 1n + let pn = [] + const maxNumber = 2000000 + let isPrime = [] + for( let i = 1; i <= maxNumber; i ++ ){ isPrime[ i ] = i % 2 != 0 } + isPrime[ 1 ] = false + isPrime[ 2 ] = true + const rootMaxNumber = Math.floor( Math.sqrt( maxNumber ) ) + for( let s = 3; s <= rootMaxNumber; s += 2 ){ + if( isPrime[ s ] ){ + for( let p = s * s; p <= maxNumber; p += s ){ isPrime[ p ] = false } + } + } + + const primeMax = 100000 + pn[ 0 ] = 1 + let nextToShow = 10 + let reducedDigits = 0 + const n500 = 10n**500n + const n1000 = 10n**1000n + for( let i = 1; i <= primeMax; i ++ ){ + // find the next prime + prime += 1n + while( ! isPrime[ prime ] ){ prime += 1n } + primorial *= prime + if( i < 10 ){ + pn[ i ] = primorial + } + else if( i == nextToShow ){ + if( nextToShow < 10000 ){ + nextToShow *= 10 + } + else{ + nextToShow += 10000 + } + if( i == 10 ){ console.log( "primorials 0-9: ", pn.toString() ) } + // show the number of digits in the primorial + let p = primorial + let length = 0 + while( p > 0 ){ + length += 1 + p /= 10n + } + console.log( "length of primorial " + i + " is "+ ( reducedDigits + length ) ) + } + if( primorial > n1000 ){ + // the number has more than 1000 digits - reduce it to 500-ish + primorial /= n500 + reducedDigits += 500 + } + } +} diff --git a/Task/Primorial-numbers/Wren/primorial-numbers-1.wren b/Task/Primorial-numbers/Wren/primorial-numbers-1.wren index 56d388f0db..2e6d13dc95 100644 --- a/Task/Primorial-numbers/Wren/primorial-numbers-1.wren +++ b/Task/Primorial-numbers/Wren/primorial-numbers-1.wren @@ -1,6 +1,6 @@ -import "/big" for BigInt -import "/math" for Int -import "/fmt" for Fmt +import "./big" for BigInt +import "./math" for Int +import "./fmt" for Fmt var vecprod = Fn.new { |primes| var le = primes.count diff --git a/Task/Priority-queue/COBOL/priority-queue.cobol b/Task/Priority-queue/COBOL/priority-queue.cobol new file mode 100644 index 0000000000..6ea881ea71 --- /dev/null +++ b/Task/Priority-queue/COBOL/priority-queue.cobol @@ -0,0 +1,286 @@ + PROCESS NOSEQ,DS(S),AR(E),TEST(SO),CP(1047) + IDENTIFICATION DIVISION. + PROGRAM-ID. PTYQTEST + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + * UNCOMMENT WITH DEBUGGING CLAUSE FOR DEBUG LINES TO EXECUTE. + SOURCE-COMPUTER. + Z-SYSTEM + * WITH DEBUGGING MODE + . + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 PTYQ-PGMNAMES. + 05 PTYQPUSH PIC X(8) VALUE "PTYQPUSH". + 05 PTYQPOP PIC X(8) VALUE "PTYQPOP". + + 01 TASK-PTR POINTER. + + 01 TOP-PTR POINTER. + + 01 LINK-KEY PIC S9(8) COMP-5. + + 01 HEAP-PTR POINTER VALUE NULL. + + 01 PUSHD-PTR POINTER VALUE NULL. + + 01 POPPD-PTR POINTER VALUE NULL. + + LINKAGE SECTION. + 01 TASK. + 05 TASK-NODE. + 10 TASK-KEY PIC S9(8) COMP-5. + 10 TASK-NEXT POINTER. + 10 TASK-DOWN POINTER. + 05 TASK-NAME PIC X(40). + + PROCEDURE DIVISION. + ALLOCATE TASK RETURNING TASK-PTR + MOVE "EAT SCONES." TO TASK-NAME + MOVE +6 TO LINK-KEY + CALL PTYQPUSH USING TASK-PTR, LINK-KEY, HEAP-PTR, PUSHD-PTR + SET HEAP-PTR TO PUSHD-PTR + + ALLOCATE TASK RETURNING TASK-PTR + MOVE "CLEAR DRAINS." TO TASK-NAME + MOVE +3 TO LINK-KEY + CALL PTYQPUSH USING TASK-PTR, LINK-KEY, HEAP-PTR, PUSHD-PTR + SET HEAP-PTR TO PUSHD-PTR + + ALLOCATE TASK RETURNING TASK-PTR + MOVE "FEED CAT." TO TASK-NAME + MOVE +4 TO LINK-KEY + CALL PTYQPUSH USING TASK-PTR, LINK-KEY, HEAP-PTR, PUSHD-PTR + SET HEAP-PTR TO PUSHD-PTR + + ALLOCATE TASK RETURNING TASK-PTR + MOVE "MAKE TEA." TO TASK-NAME + MOVE +5 TO LINK-KEY + CALL PTYQPUSH USING TASK-PTR, LINK-KEY, HEAP-PTR, PUSHD-PTR + SET HEAP-PTR TO PUSHD-PTR + + ALLOCATE TASK RETURNING TASK-PTR + MOVE "SOLVE RC TASKS." TO TASK-NAME + MOVE +1 TO LINK-KEY + CALL PTYQPUSH USING TASK-PTR, LINK-KEY, HEAP-PTR, PUSHD-PTR + SET HEAP-PTR TO PUSHD-PTR + + ALLOCATE TASK RETURNING TASK-PTR + MOVE "TAX RETURN." TO TASK-NAME + MOVE +2 TO LINK-KEY + CALL PTYQPUSH USING TASK-PTR, LINK-KEY, HEAP-PTR, PUSHD-PTR + SET HEAP-PTR TO PUSHD-PTR + + PERFORM WITH TEST BEFORE UNTIL HEAP-PTR = NULL + SET TOP-PTR TO HEAP-PTR + SET ADDRESS OF TASK TO TOP-PTR + DISPLAY TASK-KEY " " TASK-NAME + CALL PTYQPOP USING HEAP-PTR, POPPD-PTR + SET HEAP-PTR TO POPPD-PTR + FREE TOP-PTR + END-PERFORM + GOBACK. + END PROGRAM PTYQTEST. + PROCESS NOSEQ,DS(S),AR(E),TEST(SO),CP(1047) + IDENTIFICATION DIVISION. + PROGRAM-ID. PTYQMERG RECURSIVE. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + * UNCOMMENT WITH DEBUGGING CLAUSE FOR DEBUG LINES TO EXECUTE. + SOURCE-COMPUTER. + Z-SYSTEM + * WITH DEBUGGING MODE + . + + DATA DIVISION. + + LINKAGE SECTION. + 01 HEAP-PTRA POINTER. + + 01 HEAP-PTRB POINTER. + + 01 MERGD-PTR POINTER. + + 01 HEAPA. + 05 HEAPA-KEY PIC S9(8) COMP-5 VALUE +0. + 05 HEAPA-NEXT POINTER. + 05 HEAPA-DOWN POINTER. + + 01 HEAPB. + 05 HEAPB-KEY PIC S9(8) COMP-5 VALUE +0. + 05 HEAPB-NEXT POINTER. + 05 HEAPB-DOWN POINTER. + + PROCEDURE DIVISION USING HEAP-PTRA, HEAP-PTRB, MERGD-PTR. + EVALUATE TRUE + WHEN HEAP-PTRA = NULL + SET MERGD-PTR TO HEAP-PTRB + WHEN HEAP-PTRB = NULL + SET MERGD-PTR TO HEAP-PTRA + WHEN OTHER + SET ADDRESS OF HEAPA TO HEAP-PTRA + SET ADDRESS OF HEAPB TO HEAP-PTRB + IF HEAPA-KEY < HEAPB-KEY + IF HEAPA-DOWN NOT = NULL + SET HEAPB-NEXT TO HEAPA-DOWN + END-IF + SET HEAPA-DOWN TO HEAP-PTRB + SET MERGD-PTR TO HEAP-PTRA + ELSE + IF HEAPB-DOWN NOT = NULL + SET HEAPA-NEXT TO HEAPB-DOWN + END-IF + SET HEAPB-DOWN TO HEAP-PTRA + SET MERGD-PTR TO HEAP-PTRB + END-IF + END-EVALUATE + GOBACK. + END PROGRAM PTYQMERG. + PROCESS NOSEQ,DS(S),AR(E),TEST(SO),CP(1047) + IDENTIFICATION DIVISION. + PROGRAM-ID. PTYQ2PMG RECURSIVE. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + * UNCOMMENT WITH DEBUGGING CLAUSE FOR DEBUG LINES TO EXECUTE. + SOURCE-COMPUTER. + Z-SYSTEM + * WITH DEBUGGING MODE + . + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 PGMQMERG PIC X(8) VALUE "PTYQMERG". + 01 PGMQ2PMG PIC X(8) VALUE "PTYQ2PMG". + + LOCAL-STORAGE SECTION. + 01 HEAP-PTRA POINTER. + + 01 HEAP-PTRB POINTER. + + 01 HEAP-REST POINTER. + + 01 MERG1-PTR POINTER. + + 01 MERG2-PTR POINTER. + + LINKAGE SECTION. + 01 HEAP-PTR POINTER. + + 01 MERGD-PTR POINTER. + + 01 HEAP. + 05 HEAP-KEY PIC S9(8) COMP-5 VALUE +0. + 05 HEAP-NEXT POINTER. + 05 HEAP-DOWN POINTER. + + 01 HEAPA. + 05 HEAPA-KEY PIC S9(8) COMP-5 VALUE +0. + 05 HEAPA-NEXT POINTER. + 05 HEAPA-DOWN POINTER. + + 01 HEAPB. + 05 HEAPB-KEY PIC S9(8) COMP-5 VALUE +0. + 05 HEAPB-NEXT POINTER. + 05 HEAPB-DOWN POINTER. + + 01 REST. + 05 REST-KEY PIC S9(8) COMP-5 VALUE +0. + 05 REST-NEXT POINTER. + 05 REST-DOWN POINTER. + + PROCEDURE DIVISION USING HEAP-PTR, MERGD-PTR. + SET ADDRESS OF HEAP TO HEAP-PTR + EVALUATE TRUE + WHEN HEAP-PTR = NULL + SET MERGD-PTR TO HEAP-PTR + WHEN HEAP-NEXT = NULL + SET MERGD-PTR TO HEAP-PTR + WHEN OTHER + SET HEAP-PTRA TO HEAP-PTR + SET ADDRESS OF HEAPA TO HEAP-PTRA + SET HEAP-PTRB TO HEAP-NEXT + SET ADDRESS OF HEAPB TO HEAP-PTRB + SET HEAP-REST TO HEAPB-NEXT + SET ADDRESS OF REST TO HEAP-REST + SET HEAPA-NEXT TO NULL + SET HEAPB-NEXT TO NULL + CALL PGMQMERG USING HEAP-PTRA, HEAP-PTRB, MERG1-PTR + CALL PGMQ2PMG USING HEAP-REST, MERG2-PTR + CALL PGMQMERG USING MERG1-PTR, MERG2-PTR, MERGD-PTR + END-EVALUATE + GOBACK. + END PROGRAM PTYQ2PMG. + PROCESS NOSEQ,DS(S),AR(E),TEST(SO),CP(1047) + IDENTIFICATION DIVISION. + PROGRAM-ID. PTYQPUSH RECURSIVE. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + * UNCOMMENT WITH DEBUGGING CLAUSE FOR DEBUG LINES TO EXECUTE. + SOURCE-COMPUTER. + Z-SYSTEM + * WITH DEBUGGING MODE + . + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 PTYQMERG PIC X(8) VALUE "PTYQMERG". + + LINKAGE SECTION. + 01 NODE-PTR POINTER. + + 01 LINK-KEY PIC S9(8) COMP-5. + + 01 HEAP-PTR POINTER. + + 01 PUSHD-PTR POINTER. + + 01 HEAP. + 05 HEAP-KEY PIC S9(8) COMP-5. + 05 HEAP-NEXT POINTER. + 05 HEAP-DOWN POINTER. + + 01 NODE. + 05 NODE-KEY PIC S9(8) COMP-5. + 05 NODE-NEXT POINTER. + 05 NODE-DOWN POINTER. + + PROCEDURE DIVISION USING NODE-PTR, LINK-KEY, HEAP-PTR, PUSHD-PTR. + SET ADDRESS OF NODE TO NODE-PTR + SET ADDRESS OF HEAP TO HEAP-PTR + SET NODE-NEXT TO NULL + SET NODE-DOWN TO NULL + MOVE LINK-KEY TO NODE-KEY + CALL PTYQMERG USING NODE-PTR, HEAP-PTR, PUSHD-PTR + GOBACK. + END PROGRAM PTY2PUSH. + PROCESS NOSEQ,DS(S),AR(E),TEST(SO),CP(1047) + IDENTIFICATION DIVISION. + PROGRAM-ID. PTYQPOP RECURSIVE. + ENVIRONMENT DIVISION. + CONFIGURATION SECTION. + * UNCOMMENT WITH DEBUGGING CLAUSE FOR DEBUG LINES TO EXECUTE. + SOURCE-COMPUTER. + Z-SYSTEM + * WITH DEBUGGING MODE + . + + DATA DIVISION. + WORKING-STORAGE SECTION. + 01 PTYQ2PMG PIC X(8) VALUE "PTYQ2PMG". + + LINKAGE SECTION. + 01 HEAP-PTR POINTER. + + 01 POPPD-PTR POINTER. + + 01 HEAP. + 05 HEAP-KEY PIC S9(8) COMP-5 VALUE +0. + 05 HEAP-NEXT POINTER. + 05 HEAP-DOWN POINTER. + + PROCEDURE DIVISION USING HEAP-PTR, POPPD-PTR. + SET ADDRESS OF HEAP TO HEAP-PTR + CALL PTYQ2PMG USING HEAP-DOWN, POPPD-PTR + GOBACK. + END PROGRAM PTYQPOP. diff --git a/Task/Priority-queue/Wren/priority-queue.wren b/Task/Priority-queue/Wren/priority-queue.wren index c60f3c2c94..1fb6cd9321 100644 --- a/Task/Priority-queue/Wren/priority-queue.wren +++ b/Task/Priority-queue/Wren/priority-queue.wren @@ -1,4 +1,4 @@ -import "/queue" for PriorityQueue +import "./queue" for PriorityQueue var tasks = PriorityQueue.new() tasks.push("Clear drains", 3) diff --git a/Task/Probabilistic-choice/EasyLang/probabilistic-choice.easy b/Task/Probabilistic-choice/EasyLang/probabilistic-choice.easy new file mode 100644 index 0000000000..cae44439f9 --- /dev/null +++ b/Task/Probabilistic-choice/EasyLang/probabilistic-choice.easy @@ -0,0 +1,24 @@ +name$[] = [ "aleph " "beth " "gimel " "daleth" "he " "waw " "zayin " "heth " ] +probs[] = [ 1 / 5 1 / 6 1 / 7 1 / 8 1 / 9 1 / 10 1 / 11 0 ] +for i = 1 to 7 + cum += probs[i] + cum[] &= cum +. +cum[] &= 1 +probs[8] = 1 - cum[7] +len act[] 8 +n = 1000000 +for i to n + h = randomf + j = 1 + while h > cum[j] + j += 1 + . + act[j] += 1 +. +print "Name Ratio Expected" +print "---------------------" +numfmt 4 6 +for i to 8 + print name$[i] & " " & act[i] / n & " " & probs[i] +. diff --git a/Task/Probabilistic-choice/Wren/probabilistic-choice.wren b/Task/Probabilistic-choice/Wren/probabilistic-choice.wren index 0e0036d794..fb64a3c40c 100644 --- a/Task/Probabilistic-choice/Wren/probabilistic-choice.wren +++ b/Task/Probabilistic-choice/Wren/probabilistic-choice.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/fmt" for Fmt +import "./fmt" for Fmt var letters = ["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"] var actual = [0] * 8 diff --git a/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy b/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy new file mode 100644 index 0000000000..fbde02ed3e --- /dev/null +++ b/Task/Problem-of-Apollonius/EasyLang/problem-of-apollonius.easy @@ -0,0 +1,68 @@ +proc solve c1[] c2[] c3[] s1 s2 s3 . r[] . + len r[] 3 + x1 = c1[1] ; y1 = c1[2] ; r1 = c1[3] + x2 = c2[1] ; y2 = c2[2] ; r2 = c2[3] + x3 = c3[1] ; y3 = c3[2] ; r3 = c3[3] + # + v11 = 2 * x2 - 2 * x1 + v12 = 2 * y2 - 2 * y1 + v13 = x1 * x1 - x2 * x2 + y1 * y1 - y2 * y2 - r1 * r1 + r2 * r2 + v14 = 2 * s2 * r2 - 2 * s1 * r1 + v21 = 2 * x3 - 2 * x2 + v22 = 2 * y3 - 2 * y2 + v23 = x2 * x2 - x3 * x3 + y2 * y2 - y3 * y3 - r2 * r2 + r3 * r3 + v24 = 2 * s3 * r3 - 2 * s2 * r2 + w12 = v12 / v11 + w13 = v13 / v11 + w14 = v14 / v11 + w22 = v22 / v21 - w12 + w23 = v23 / v21 - w13 + w24 = v24 / v21 - w14 + P = -w23 / w22 + Q = w24 / w22 + M = -w12 * P - w13 + N = w14 - w12 * Q + a = N * N + Q * Q - 1 + b = 2 * M * N - 2 * N * x1 + 2 * P * Q - 2 * Q * y1 + 2 * s1 * r1 + c = x1 * x1 + M * M - 2 * M * x1 + P * P + y1 * y1 - 2 * P * y1 - r1 * r1 + # + D = b * b - 4 * a * c + rs = (-b - sqrt D) / (2 * a) + r[1] = M + N * rs + r[2] = P + Q * rs + r[3] = rs +. +c1[] = [ 0 0 1 ] +c2[] = [ 4 0 1 ] +c3[] = [ 2 4 2 ] +solve c1[] c2[] c3[] 1 1 1 r1[] +print r1[] +solve c1[] c2[] c3[] -1 -1 -1 r2[] +print r2[] +# +proc circ x y r . . + linewidth 0.5 + for a = 0 to 360 + line x + sin a * r y + cos a * r + . +. +proc draw col c[] . . + color col + circ c[1] * 10 + 30 c[2] * 10 + 30 c[3] * 10 +. +background 888 +clear +linewidth 0.5 +color 000 +drawgrid +move 30 0 +line 30 100 +move 0 30 +line 100 30 +draw 000 c1[] +draw 000 c2[] +draw 000 c3[] +sleep 0.5 +draw 070 r1[] +sleep 0.5 +draw 700 r2[] diff --git a/Task/Problem-of-Apollonius/Wren/problem-of-apollonius.wren b/Task/Problem-of-Apollonius/Wren/problem-of-apollonius.wren index e1d9fe3d81..36178f387f 100644 --- a/Task/Problem-of-Apollonius/Wren/problem-of-apollonius.wren +++ b/Task/Problem-of-Apollonius/Wren/problem-of-apollonius.wren @@ -1,4 +1,4 @@ -import "/dynamic" for Tuple +import "./dynamic" for Tuple var Circle = Tuple.create("Circle", ["x", "y", "r"]) diff --git a/Task/Proper-divisors/EasyLang/proper-divisors.easy b/Task/Proper-divisors/EasyLang/proper-divisors.easy new file mode 100644 index 0000000000..3e4ff18fbc --- /dev/null +++ b/Task/Proper-divisors/EasyLang/proper-divisors.easy @@ -0,0 +1,29 @@ +proc propdivs n . divs[] . + divs[] = [ ] + if n < 2 + return + . + divs[] &= 1 + sqr = sqrt n + for d = 2 to sqr + if n mod d = 0 + divs[] &= d + if d <> sqr + divs[] &= n / d + . + . + . +. +for i to 10 + propdivs i d[] + write i & ":" + print d[] +. +for i to 20000 + propdivs i d[] + if len d[] > max + max = len d[] + maxi = i + . +. +print maxi & " has " & max & " proper divisors." diff --git a/Task/Proper-divisors/Langur/proper-divisors.langur b/Task/Proper-divisors/Langur/proper-divisors.langur index 4b684afcfb..3c668cb44f 100644 --- a/Task/Proper-divisors/Langur/proper-divisors.langur +++ b/Task/Proper-divisors/Langur/proper-divisors.langur @@ -3,14 +3,13 @@ val .cntproper = f(.x) for[=0] .i of .x \ 2 { if .x div .i: _for += 1 } val .listproper = f(.x) { if .x < 1: return null - for .i of .x { - writeln $"\.i:2; -> ", .getproper(.i) + for[=""] .i of .x { + _for ~= $"\.i:2; -> \.getproper(.i);\n" } - writeln() } writeln "The proper divisors of the following numbers are :" -.listproper(10) +writeln .listproper(10) var .max = 0 var .most = [] diff --git a/Task/Proper-divisors/Wren/proper-divisors.wren b/Task/Proper-divisors/Wren/proper-divisors.wren index 2608a71bde..c920b24ef4 100644 --- a/Task/Proper-divisors/Wren/proper-divisors.wren +++ b/Task/Proper-divisors/Wren/proper-divisors.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/math" for Int +import "./fmt" for Fmt +import "./math" for Int for (i in 1..10) System.print("%(Fmt.d(2, i)) -> %(Int.properDivisors(i))") diff --git a/Task/Pseudo-random-numbers-PCG32/11l/pseudo-random-numbers-pcg32.11l b/Task/Pseudo-random-numbers-PCG32/11l/pseudo-random-numbers-pcg32.11l index 5ed6be86d7..06dc9b5eb3 100644 --- a/Task/Pseudo-random-numbers-PCG32/11l/pseudo-random-numbers-pcg32.11l +++ b/Task/Pseudo-random-numbers-PCG32/11l/pseudo-random-numbers-pcg32.11l @@ -6,7 +6,7 @@ T PCG32 .state = (old * 6364136223846793005) + .inc V shifted = UInt32(((old >> 18) (+) old) >> 27) V rot = UInt32(old >> 59) - R (shifted >> rot) [|] (shifted << (((-)rot + 1) [&] 31)) + R (shifted >> rot) [|] (shifted << ((~rot + 1) [&] 31)) F seed(UInt64 seed_state, seed_sequence) .state = 0 diff --git a/Task/Pseudo-random-numbers-PCG32/C++/pseudo-random-numbers-pcg32.cpp b/Task/Pseudo-random-numbers-PCG32/C++/pseudo-random-numbers-pcg32.cpp index 6b84e9aae1..06642fc389 100644 --- a/Task/Pseudo-random-numbers-PCG32/C++/pseudo-random-numbers-pcg32.cpp +++ b/Task/Pseudo-random-numbers-PCG32/C++/pseudo-random-numbers-pcg32.cpp @@ -1,5 +1,6 @@ #include #include +#include class PCG32 { private: diff --git a/Task/Pseudo-random-numbers-PCG32/C-sharp/pseudo-random-numbers-pcg32.cs b/Task/Pseudo-random-numbers-PCG32/C-sharp/pseudo-random-numbers-pcg32.cs new file mode 100644 index 0000000000..5d9ac59e95 --- /dev/null +++ b/Task/Pseudo-random-numbers-PCG32/C-sharp/pseudo-random-numbers-pcg32.cs @@ -0,0 +1,61 @@ +using System; + +class PCG32 +{ + private const ulong N = 6364136223846793005; + private ulong state = 0x853c49e6748fea9b; + private ulong inc = 0xda3e39cb94b95bdb; + + public uint NextInt() + { + ulong old = state; + state = old * N + inc; + uint shifted = (uint)(((old >> 18) ^ old) >> 27); + uint rot = (uint)(old >> 59); + return (shifted >> (int)rot) | (shifted << (int)((~rot + 1) & 31)); + } + + public double NextFloat() + { + return ((double)NextInt()) / (1UL << 32); + } + + public void Seed(ulong seedState, ulong seedSequence) + { + state = 0; + inc = (seedSequence << 1) | 1; + NextInt(); + state += seedState; + NextInt(); + } +} + +class Program +{ + static void Main(string[] args) + { + var r = new PCG32(); + + r.Seed(42, 54); + Console.WriteLine(r.NextInt()); + Console.WriteLine(r.NextInt()); + Console.WriteLine(r.NextInt()); + Console.WriteLine(r.NextInt()); + Console.WriteLine(r.NextInt()); + Console.WriteLine(); + + int[] counts = new int[5]; + r.Seed(987654321, 1); + for (int i = 0; i < 100000; i++) + { + int j = (int)Math.Floor(r.NextFloat() * 5.0); + counts[j]++; + } + + Console.WriteLine("The counts for 100,000 repetitions are:"); + for (int i = 0; i < counts.Length; i++) + { + Console.WriteLine($" {i} : {counts[i]}"); + } + } +} diff --git a/Task/Pseudo-random-numbers-PCG32/Dart/pseudo-random-numbers-pcg32.dart b/Task/Pseudo-random-numbers-PCG32/Dart/pseudo-random-numbers-pcg32.dart new file mode 100644 index 0000000000..25290e63d3 --- /dev/null +++ b/Task/Pseudo-random-numbers-PCG32/Dart/pseudo-random-numbers-pcg32.dart @@ -0,0 +1,69 @@ +import 'dart:math'; + +class PCG32 { + BigInt fState = BigInt.zero; + BigInt fInc = BigInt.zero; + final BigInt mask64 = (BigInt.one << 64) - BigInt.one; + final BigInt mask32 = (BigInt.one << 32) - BigInt.one; + final BigInt k = BigInt.parse('6364136223846793005'); + + PCG32(BigInt seedState, BigInt seedSequence) { + seed(seedState, seedSequence); + } + + PCG32.noSeed() { + fState = BigInt.zero; + fInc = BigInt.zero; + } + + void seed(BigInt seedState, BigInt seedSequence) { + fState = BigInt.zero; + fInc = ((seedSequence << 1) | BigInt.one) & mask64; + nextInt(); + fState += seedState; + nextInt(); + } + + BigInt nextInt() { + BigInt old = fState; + fState = ((old * k) + fInc) & mask64; + BigInt xorshifted = ( ((old >> 18) ^ old) >> 27) & mask32; + BigInt rot = (old >> 59) & mask32; + BigInt shifted = (xorshifted >> rot.toInt()) | (xorshifted << ((-rot) & BigInt.from(31)).toInt()); + return shifted & mask32; + } + + double nextFloat() { + return nextInt().toDouble() / (BigInt.one << 32).toDouble(); + } + + List nextIntRange(int size) { + List result = []; + for (int i = 0; i < size; i++) { + result.add(nextInt()); + } + return result; + } +} + +void main() { + var pcg32 = PCG32(BigInt.from(42), BigInt.from(54)); + + for (int i = 0; i < 5; i++) { + print(pcg32.nextInt().toString()); + } + + pcg32.seed(BigInt.from(987654321), BigInt.one); + + var count = {}; + + for (int i = 0; i < 100000; i++) { + int key = (pcg32.nextFloat() * 5).truncate(); + count[key] = (count[key] ?? 0) + 1; + } + + print('\nThe counts for 100,000 repetitions are:'); + count.forEach((key, value) { + print('$key : $value'); + }); +} diff --git a/Task/Pseudo-random-numbers-PCG32/Mathematica/pseudo-random-numbers-pcg32.math b/Task/Pseudo-random-numbers-PCG32/Mathematica/pseudo-random-numbers-pcg32.math new file mode 100644 index 0000000000..dbf05e2dea --- /dev/null +++ b/Task/Pseudo-random-numbers-PCG32/Mathematica/pseudo-random-numbers-pcg32.math @@ -0,0 +1,58 @@ +ClearAll["Global`*"]; + +(*Constants*) +mask32 = BitAnd[2^32 - 1]; +CONST = 6364136223846793005; + +(*Convert Hex String to Expression*) +Hex[x_?StringQ] := ToExpression["16^^" <> StringDrop[x, 2]]; + +(*Definition of PCG32 Structure*) +PCG32[state_: Hex["0x853c49e6748fea9b"], + inc_: Hex["0xda3e39cb94b95bdb"]] := <|"state" -> state, + "inc" -> inc|>; + +(*Function to generate next integer*) +nextInt[pcg_Association] := + Module[{old, xorshifted, rot, newState}, old = pcg["state"]; + newState = BitAnd[(old*CONST + pcg["inc"]), 2^64 - 1]; + xorshifted = + BitAnd[BitShiftRight[BitXor[BitShiftRight[old, 18], old], 27], + mask32]; + rot = BitAnd[BitShiftRight[old, 59], mask32]; + <|"state" -> newState, "inc" -> pcg["inc"], + "nextInt" -> + BitAnd[BitOr[BitShiftRight[xorshifted, rot], + BitShiftLeft[xorshifted, BitAnd[-rot, 31]]], mask32]|>]; + +(*Function to generate next float*) +nextFloat[pcg_Association] := nextInt[pcg]["nextInt"]/2^32; + +(*Function to seed the generator*) +seed[pcg_Association, st_, seq_] := + Module[{newPcg}, + newPcg = <|"state" -> 0, + "inc" -> BitOr[BitShiftLeft[seq, 1], 1]|>; + newPcg = nextInt[newPcg]; + <|"state" -> newPcg["state"] + st, "inc" -> newPcg["inc"]|>]; + +(*Test function*) +testPCG32[] := + Module[{randomGen, hist, n, nextGen}, randomGen = PCG32[]; + randomGen = seed[randomGen, 42, 54]; + Do[ + nextGen = nextInt[randomGen]; + randNumber = nextGen["nextInt"]; + If[randNumber != 0, Print[randNumber]]; + randomGen = nextGen + , {6}]; + randomGen = seed[randomGen, 987654321, 1]; + hist = ConstantArray[0, 5]; + Do[nextGen = nextInt[randomGen]; + hist[[Floor[nextFloat[nextGen]*5] + 1]] += 1; + randomGen = nextGen, {100000}]; + Print[hist]; + Do[Print[n - 1, ": ", hist[[n]], " "], {n, 1, 5}];]; + +(*Run the test*) +testPCG32[]; diff --git a/Task/Pseudo-random-numbers-PCG32/Rust/pseudo-random-numbers-pcg32.rust b/Task/Pseudo-random-numbers-PCG32/Rust/pseudo-random-numbers-pcg32.rust new file mode 100644 index 0000000000..c61d56c336 --- /dev/null +++ b/Task/Pseudo-random-numbers-PCG32/Rust/pseudo-random-numbers-pcg32.rust @@ -0,0 +1,58 @@ +struct PCG32 { + multiplier: u64, + state: u64, + inc: u64, +} + +impl PCG32 { + fn new() -> Self { + PCG32 { + multiplier: 6364136223846793005, + state: 0x853c49e6748fea9b, + inc: 0xda3e39cb94b95bdb, + } + } + + fn next_int(&mut self) -> u32 { + let old = self.state; + self.state = old.wrapping_mul(self.multiplier).wrapping_add(self.inc); + let xorshifted = (((old >> 18) ^ old) >> 27) as u32; + let rot = (old >> 59) as u32; + (xorshifted >> rot) | (xorshifted << ((!rot).wrapping_add(1) & 31)) + } + + fn next_float(&mut self) -> f64 { + (self.next_int() as f64) / ((1u64 << 32) as f64) + } + + fn seed(&mut self, seed_state: u64, seed_sequence: u64) { + self.state = 0; + self.inc = (seed_sequence << 1) | 1; + self.next_int(); + self.state = self.state.wrapping_add(seed_state); + self.next_int(); + } +} + +fn main() { + let mut rng = PCG32::new(); + + rng.seed(42, 54); + for _ in 0..5 { + println!("{}", rng.next_int()); + } + + println!(); + + let mut counts = [0; 5]; + rng.seed(987654321, 1); + for _ in 0..100000 { + let j = (rng.next_float() * 5.0).floor() as usize; + counts[j] += 1; + } + + println!("The counts for 100,000 repetitions are:"); + for (i, count) in counts.iter().enumerate() { + println!(" {} : {}", i, count); + } +} diff --git a/Task/Pseudo-random-numbers-PCG32/Scala/pseudo-random-numbers-pcg32.scala b/Task/Pseudo-random-numbers-PCG32/Scala/pseudo-random-numbers-pcg32.scala new file mode 100644 index 0000000000..66ceb7f952 --- /dev/null +++ b/Task/Pseudo-random-numbers-PCG32/Scala/pseudo-random-numbers-pcg32.scala @@ -0,0 +1,51 @@ +object PCG32 { + private val N = 6364136223846793005L + + private var state = 0x853c49e6748fea9bL + private var inc = 0xda3e39cb94b95bdbL + + def seed(seedState: Long, seedSequence: Long): Unit = { + state = 0 + inc = (seedSequence << 1) | 1 + nextInt() + state += seedState + nextInt() + } + + def nextInt(): Int = { + val old = state + state = old * N + inc + val shifted = (((old >>> 18) ^ old) >>> 27).toInt + val rot = (old >>> 59).toInt + (shifted >>> rot) | (shifted << ((~rot + 1) & 31)) + } + + def nextFloat(): Double = { + val u = nextInt() & 0xffffffffL + u.toDouble / (1L << 32) + } +} + +object Main extends App { + val r = PCG32 + + r.seed(42, 54) + println(Integer.toUnsignedString(r.nextInt())) + println(Integer.toUnsignedString(r.nextInt())) + println(Integer.toUnsignedString(r.nextInt())) + println(Integer.toUnsignedString(r.nextInt())) + println(Integer.toUnsignedString(r.nextInt())) + println() + + val counts = Array(0, 0, 0, 0, 0) + r.seed(987654321, 1) + for (_ <- 1 to 100000) { + val j = Math.floor(r.nextFloat() * 5.0).toInt + counts(j) += 1 + } + + println("The counts for 100,000 repetitions are:") + for (i <- counts.indices) { + println(s" $i : ${counts(i)}") + } +} diff --git a/Task/Pseudo-random-numbers-PCG32/Tcl/pseudo-random-numbers-pcg32.tcl b/Task/Pseudo-random-numbers-PCG32/Tcl/pseudo-random-numbers-pcg32.tcl new file mode 100644 index 0000000000..47abb3c9cd --- /dev/null +++ b/Task/Pseudo-random-numbers-PCG32/Tcl/pseudo-random-numbers-pcg32.tcl @@ -0,0 +1,55 @@ +proc uint32 {n} { + return [expr {$n & 0xffffffff}] +} + +proc uint64 {n} { + return [expr {$n & 0xffffffffffffffff}] +} + +set N 6364136223846793005 +set state 0x853c49e6748fea9b +set inc 0xda3e39cb94b95bdb + +proc pcg32_seed {seed_state seed_sequence} { + global state inc + set state 0 + set inc [expr {($seed_sequence << 1) | 1}] + pcg32_int + set state [expr {$state + $seed_state}] + pcg32_int +} + +proc pcg32_int {} { + global state N inc + set old $state + set state [uint64 [expr {$old * $N + $inc}]] + set shifted [uint32 [expr {(($old >> 18) ^ $old) >> 27}]] + set rot [uint32 [expr {$old >> 59}]] + return [uint32 [expr {($shifted >> $rot) | ($shifted << ((~$rot + 1) & 31))}]] +} + +proc pcg32_float {} { + return [expr {1.0 * [pcg32_int] / (1 << 32)}] +} + +# ------------------------------------------------------------------- + +pcg32_seed 42 54 +puts [pcg32_int] +puts [pcg32_int] +puts [pcg32_int] +puts [pcg32_int] +puts [pcg32_int] +puts "" + +set counts {0 0 0 0 0} +pcg32_seed 987654321 1 +for {set i 1} {$i <= 100000} {incr i} { + set j [expr {int([pcg32_float] * 5.0) + 1}] + lset counts [expr {$j - 1}] [expr {[lindex $counts [expr {$j - 1}]] + 1}] +} + +puts "The counts for 100,000 repetitions are:" +foreach idx {0 1 2 3 4} { + puts " $idx: [lindex $counts $idx]" +} diff --git a/Task/Pseudo-random-numbers-PCG32/Wren/pseudo-random-numbers-pcg32.wren b/Task/Pseudo-random-numbers-PCG32/Wren/pseudo-random-numbers-pcg32.wren index fbf63ab0bc..4768d83c79 100644 --- a/Task/Pseudo-random-numbers-PCG32/Wren/pseudo-random-numbers-pcg32.wren +++ b/Task/Pseudo-random-numbers-PCG32/Wren/pseudo-random-numbers-pcg32.wren @@ -1,4 +1,4 @@ -import "/big" for BigInt +import "./big" for BigInt var Const = BigInt.new("6364136223846793005") var Mask64 = (BigInt.one << 64) - BigInt.one diff --git a/Task/Pseudo-random-numbers-Splitmix64/Jq/pseudo-random-numbers-splitmix64-1.jq b/Task/Pseudo-random-numbers-Splitmix64/Jq/pseudo-random-numbers-splitmix64-1.jq new file mode 100644 index 0000000000..8b73efadd3 --- /dev/null +++ b/Task/Pseudo-random-numbers-Splitmix64/Jq/pseudo-random-numbers-splitmix64-1.jq @@ -0,0 +1,74 @@ +# Input: a string in base $b (2 to 35 inclusive) +# Output: a JSON number, being the decimal value corresponding to the input. +def frombase($b): + def decimalValue: + if 48 <= . and . <= 57 then . - 48 + elif 65 <= . and . <= 90 then . - 55 # (10+.-65) + elif 97 <= . and . <= 122 then . - 87 # (10+.-97) + else "decimalValue" | error + end; + reduce (explode|reverse[]|decimalValue) as $x ({p:1}; + .value += (.p * $x) + | .p *= $b) + | .value ; + +# To take advantage of gojq's arbitrary-precision integer arithmetic: +def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in); + +# If the input and $j are integers, then the result will be an integer. +def div($j): + (. - (. % j)) / $j; + +# Convert an integer to a bitarray, least significant bit first +def bitwise: + recurse( if . >= 2 then div(2) else empty end) | . % 2; + +# Essentially the inverse of bitwise, +# i.e. interpret an array of 0s and 1s (with least-significant-bit first ) as a decimal +def to_int: + . as $in + # state: [sum, power] + | reduce .[] as $i ([0, 1]; .[1] as $p | [.[0] + $p * $i, ($p * 2)]) + | .[0]; + +# $x and $y and output are bitarrays +def xor($x;$y): + def lxor(a;b): + if (a==1 or b==1) and ((a==1 and b==1)|not) then 1 + elif a == null then b + elif b == null then a + else 0 + end; + if $x == [0] then $y + elif $y == [0] then $x + else + [ range(0; [($x|length), ($y|length)] | max) as $i + | lxor($x[$i]; $y[$i]) ] + end ; + +# $x and $y and output are bitarrays +def xand($x;$y): + def lxand(a;b): + (a==1 and b==1) | 1 // 0; + if $x == [0] or $y == [0] then [0] + else + [range(0; [($x|length), ($y|length)] | min) as $i + | lxand($x[$i]; $y[$i]) ] + end ; + +# shift right +def right($n): .[$n:]; + +def mask64: .[:64]; + +# input and output: a bitarray +def mult($int): + ($int * to_int) | [bitwise]; + +def plus($int): + ($int + to_int) | [bitwise]; + +def tabulate(stream): + reduce stream as $i ([]; .[$i] += 1) + | range(0;length) as $i + | " \($i) : \(.[$i] // 0)" ; diff --git a/Task/Pseudo-random-numbers-Splitmix64/Jq/pseudo-random-numbers-splitmix64-2.jq b/Task/Pseudo-random-numbers-Splitmix64/Jq/pseudo-random-numbers-splitmix64-2.jq new file mode 100644 index 0000000000..9471072189 --- /dev/null +++ b/Task/Pseudo-random-numbers-Splitmix64/Jq/pseudo-random-numbers-splitmix64-2.jq @@ -0,0 +1,24 @@ +# input: a bitarray +def nextInt: + def Const1: "9e3779b97f4a7c15" | frombase(16) ; + def Const2: "bf58476d1ce4e5b9" | frombase(16) ; + def Const3: "94d049bb133111eb" | frombase(16) ; + + (plus(Const1) | mask64) + | . as $state + | xor(.; right(30)) | mult(Const2) | mask64 + | xor(.; right(27)) | mult(Const3) | mask64 + | xor(.; right(31)) | mask64 + | ., ($state|nextInt) ; + +def randomInt64: [bitwise] | nextInt | to_int; + +def randomReal: + pow(2;64) as $d + | [bitwise] | nextInt | to_int / $d; + +### The tasks +(limit(5; 1234567 | randomInt64)), + +"\nThe counts for 100,000 repetitions are:", +tabulate( limit(100; 987654321 | randomReal * 5 | floor) ) diff --git a/Task/Pseudo-random-numbers-Splitmix64/Wren/pseudo-random-numbers-splitmix64.wren b/Task/Pseudo-random-numbers-Splitmix64/Wren/pseudo-random-numbers-splitmix64.wren index e996e31a78..446e6c1295 100644 --- a/Task/Pseudo-random-numbers-Splitmix64/Wren/pseudo-random-numbers-splitmix64.wren +++ b/Task/Pseudo-random-numbers-Splitmix64/Wren/pseudo-random-numbers-splitmix64.wren @@ -1,4 +1,4 @@ -import "/big" for BigInt +import "./big" for BigInt var Const1 = BigInt.fromBaseString("9e3779b97f4a7c15", 16) var Const2 = BigInt.fromBaseString("bf58476d1ce4e5b9", 16) diff --git a/Task/Pseudo-random-numbers-Xorshift-star/Rust/pseudo-random-numbers-xorshift-star.rust b/Task/Pseudo-random-numbers-Xorshift-star/Rust/pseudo-random-numbers-xorshift-star.rust new file mode 100644 index 0000000000..583375b4a0 --- /dev/null +++ b/Task/Pseudo-random-numbers-Xorshift-star/Rust/pseudo-random-numbers-xorshift-star.rust @@ -0,0 +1,51 @@ +struct XorShiftStar { + magic: u64, + state: u64, +} + +impl XorShiftStar { + fn new() -> Self { + Self { + magic: 0x2545_F491_4F6C_DD1D, + state: 0, + } + } + + fn seed(&mut self, num: u64) { + self.state = num; + } + + fn next_int(&mut self) -> u32 { + let mut x = self.state; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.state = x; + ((x.wrapping_mul(self.magic)) >> 32) as u32 + } + + fn next_float(&mut self) -> f32 { + self.next_int() as f32 / (1u64 << 32) as f32 + } +} + +fn main() { + let mut rng = XorShiftStar::new(); + rng.seed(1234567); + println!("{}", rng.next_int()); + println!("{}", rng.next_int()); + println!("{}", rng.next_int()); + println!("{}", rng.next_int()); + println!("{}", rng.next_int()); + println!(); + + let mut counts = [0; 5]; + rng.seed(987654321); + for _ in 0..100000 { + let j = (rng.next_float() * 5.0).floor() as usize; + counts[j] += 1; + } + for (i, count) in counts.iter().enumerate() { + println!("{}: {}", i, count); + } +} diff --git a/Task/Pseudo-random-numbers-Xorshift-star/Wren/pseudo-random-numbers-xorshift-star.wren b/Task/Pseudo-random-numbers-Xorshift-star/Wren/pseudo-random-numbers-xorshift-star.wren index 5011b84526..c630c8717d 100644 --- a/Task/Pseudo-random-numbers-Xorshift-star/Wren/pseudo-random-numbers-xorshift-star.wren +++ b/Task/Pseudo-random-numbers-Xorshift-star/Wren/pseudo-random-numbers-xorshift-star.wren @@ -1,4 +1,4 @@ -import "/big" for BigInt +import "./big" for BigInt var Const = BigInt.fromBaseString("2545F4914F6CDD1D", 16) var Mask64 = (BigInt.one << 64) - BigInt.one diff --git a/Task/Pythagoras-tree/Dart/pythagoras-tree-2.dart b/Task/Pythagoras-tree/Dart/pythagoras-tree-2.dart index 3c939b914b..000038a2a1 100644 --- a/Task/Pythagoras-tree/Dart/pythagoras-tree-2.dart +++ b/Task/Pythagoras-tree/Dart/pythagoras-tree-2.dart @@ -1,14 +1,7 @@ import 'package:flutter/material.dart'; -void main() => runApp(const MainApp()); - -class MainApp extends StatelessWidget { - const MainApp({super.key}); - - @override - Widget build(BuildContext context) => FittedBox( - child: CustomPaint(painter: TreePainter(), size: const Size(2400, 1600))); -} +void main() => runApp(FittedBox( + child: CustomPaint(painter: TreePainter(), size: const Size(2400, 1600)))); class TreePainter extends CustomPainter { @override diff --git a/Task/Pythagorean-quadruples/EDSAC-order-code/pythagorean-quadruples.edsac b/Task/Pythagorean-quadruples/EDSAC-order-code/pythagorean-quadruples.edsac new file mode 100644 index 0000000000..e1c173673b --- /dev/null +++ b/Task/Pythagorean-quadruples/EDSAC-order-code/pythagorean-quadruples.edsac @@ -0,0 +1,75 @@ +[Pythagorean quadruples - Rosetta Code + EDSAC program, Initial Orders 2] + + [Arrange the storage] + T46K P56F [N parameter: modified library s/r P7 to print integer] + T47K P106F [M parameter: main routine] + +[Library subroutine M3, prints header at load time. + Here, header leaves teleprinter in figures mode.] + PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF + *NUMBERS!WHOSE!SQUARES!ARE!NOT!THE!SUM! + OF!THREE!NONZERO!SQUARES@&MAXIMUM#!V! + ..PK [after header, blank tape and PK (WWG, 1951, page 91)] + +[------------------------------------------------------------------------------] +[Main routine] + E25K TM GK [load at address specified by M parameter] +[Constants] + [0] P1100F [limit, right-justified, e.g. P1100F for 2200] + [1] !F [teleprinter space] + [2] @F [carriage return] + [3] &F [line feed] + [4] K4096F [teleprinter null] + [5] PD [17-bit constant 1] + [6] P2D [17-bit constant 5] +[Variables] + [7] PF [2^m, where m = 0, 1, 2, ...] + [8] PF [5*2^n, where n = 0, 1, 2, ...] +[Enter here, with acc = 0] + [Complete header by printing limit] + [9] A4@ T1F [print leading zeros as nulls] + A@ TF [pass limit to print subroutine in 0F] + [13] A13@ GN [call print subroutine; leaves acc clear] + O2@ O3@ [print new line] + [Initialize variables] + A5@ T7@ [2^m := 1] + A6@ T8@ [5*2^n := 5] + [Loop back to here after printing number] + [Print 2^m or 5*2^n, whichever is smaller] + [21] A7@ S8@ [compare values] + E28@ [jump if 5*2^n is smaller] + A8@ [else restore 2^m in acc] + LD U7@ [double value in memory] + E32@ [jump to common code] + [28] T4F [clear acc] + A8@ [acc := 5*2^n] + LD U8@ [double value in memory] + [32] RD [common code: undo doubling in acc] + TF [pass number to print subroutine in 0F] + A@ SF [test for number > limit] + G42@ [jump to exit if so] + O1@ [print space before number] + T4F [clear acc] + [39] A39@ GN [call print subroutine; leaves acc clear] + E21@ [loop back for next number] + [Here when done] + [42] O2@ O3@ [print new line] + O4@ [print null to flush teleprinter buffer] + ZF [halt the machine] + +[------------------------------------------------------------] +[Subroutine to print 17-bit non-negative integer + Parameters: 0F = integer to be printed (not preserved) + 1F = character for leading zero + (preserved; typically null, space or zero) + Workspace: 4F, 5F + Even address; 39 locations] + E25K TN [load at address specified by N parameter] + GKA3FT34@A1FT35@S37@T36@T4DAFT4FH38@V4FRDA4D + R1024FH30@E23@O35@A2FT36@T5FV4DYFL8FT4DA5F + L1024FUFA36@G16@OFTFT35@A36@G17@ZFPFPFP4FZ219D + + E25K TM GK [M parameter again] + E9Z [define entry point] + PF [acc = 0 on entry] diff --git a/Task/Pythagorean-triples/ALGOL-68/pythagorean-triples.alg b/Task/Pythagorean-triples/ALGOL-68/pythagorean-triples.alg new file mode 100644 index 0000000000..997c95e085 --- /dev/null +++ b/Task/Pythagorean-triples/ALGOL-68/pythagorean-triples.alg @@ -0,0 +1,41 @@ +BEGIN # find some Pythagorean triples ( a, b, c ) # + # where a < b < c and a^2 + b^2 = c^2 # + + INT max perimeter = 100; # maximum a + b + c we will consider # + INT max square = max perimeter * max perimeter; + # form a table of square roots of numbers to max perimeter ^ 2 # + [ 1 : max square ]INT sr; + FOR i TO UPB sr DO sr[ i ] := 0 OD; + FOR i TO max perimeter DO sr[ i * i ] := i OD; + + PROC gcd = ( INT x, y )INT: # iterative gcd # + BEGIN + INT a := ABS x, b := ABS y; + WHILE b /= 0 DO + INT next a = b; + b := a MOD b; + a := next a + OD; + a + END # gcd # ; + + # count the Pythagorean triples # + INT t count := 0, p count := 0; + FOR a TO max perimeter DO + INT a2 = a * a; + FOR b FROM a + 1 TO max perimeter - a + WHILE INT c = sr[ a2 + ( b * b ) ]; + a + b + c <= max perimeter + DO IF c > b THEN # have a triple # + t count +:= 1; + IF gcd( a, b ) = 1 THEN # have a primitive triple # + p count +:= 1 + FI + FI + OD + OD; + print( ( "Pythagorean triples with perimeters up to ", whole( max perimeter, 0 ), ":", newline ) ); + print( ( " Primitive: ", whole( p count, 0 ), newline ) ); + print( ( " Total: ", whole( t count, 0 ), newline ) ) + +END diff --git a/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy b/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy new file mode 100644 index 0000000000..1d8b36eaeb --- /dev/null +++ b/Task/Pythagorean-triples/EasyLang/pythagorean-triples.easy @@ -0,0 +1,17 @@ +global total prim maxperi . +proc newtri s0 s1 s2 . . + p = s0 + s1 + s2 + if p <= maxperi + prim += 1 + total += maxperi div p + newtri s0 - 2 * s1 + 2 * s2 2 * s0 - s1 + 2 * s2 2 * s0 - 2 * s1 + 3 * s2 + newtri s0 + 2 * s1 + 2 * s2 2 * s0 + s1 + 2 * s2 2 * s0 + 2 * s1 + 3 * s2 + newtri -s0 + 2 * s1 + 2 * s2 -2 * s0 + s1 + 2 * s2 -2 * s0 + 2 * s1 + 3 * s2 + . +. +for maxperi in [ 100 10000000 ] + prim = 0 + total = 0 + newtri 3 4 5 + print "Up to " & maxperi & ": " & total & " triples, " & prim & " primitives" +. diff --git a/Task/QR-decomposition/Wren/qr-decomposition.wren b/Task/QR-decomposition/Wren/qr-decomposition.wren index 552fb811fc..0373a92279 100644 --- a/Task/QR-decomposition/Wren/qr-decomposition.wren +++ b/Task/QR-decomposition/Wren/qr-decomposition.wren @@ -1,5 +1,5 @@ -import "/matrix" for Matrix -import "/fmt" for Fmt +import "./matrix" for Matrix +import "./fmt" for Fmt var minor = Fn.new { |x, d| var nr = x.numRows diff --git a/Task/Quaternion-type/Dart/quaternion-type.dart b/Task/Quaternion-type/Dart/quaternion-type.dart new file mode 100644 index 0000000000..7298b39474 --- /dev/null +++ b/Task/Quaternion-type/Dart/quaternion-type.dart @@ -0,0 +1,63 @@ +import 'dart:math' as math; + +class Quaternion { + final double a, b, c, d; + + Quaternion(this.a, this.b, this.c, this.d); + + Quaternion operator +(Object other) { + if (other is Quaternion) { + return Quaternion(a + other.a, b + other.b, c + other.c, d + other.d); + } else if (other is double) { + return Quaternion(a + other, b, c, d); + } + throw ArgumentError('Invalid type for addition: ${other.runtimeType}'); + } + + Quaternion operator *(Object other) { + if (other is Quaternion) { + return Quaternion( + a * other.a - b * other.b - c * other.c - d * other.d, + a * other.b + b * other.a + c * other.d - d * other.c, + a * other.c - b * other.d + c * other.a + d * other.b, + a * other.d + b * other.c - c * other.b + d * other.a, + ); + } else if (other is double) { + return Quaternion(a * other, b * other, c * other, d * other); + } + throw ArgumentError('Invalid type for multiplication: ${other.runtimeType}'); + } + + Quaternion operator -() => Quaternion(-a, -b, -c, -d); + + Quaternion conj() => Quaternion(a, -b, -c, -d); + + double norm() => math.sqrt(a * a + b * b + c * c + d * d); + + @override + String toString() => '($a, $b, $c, $d)'; +} + +void main() { + var q = Quaternion(1.0, 2.0, 3.0, 4.0); + var q1 = Quaternion(2.0, 3.0, 4.0, 5.0); + var q2 = Quaternion(3.0, 4.0, 5.0, 6.0); + var r = 7.0; + print("q = $q"); + print("q1 = $q1"); + print("q2 = $q2"); + print("r = $r\n"); + print("norm(q) = ${q.norm().toStringAsFixed(6)}"); + print("-q = ${-q}"); + print("conj(q) = ${q.conj()}\n"); + print("r + q = ${q + r}"); + print("q + r = ${q + r}"); + print("q1 + q2 = ${q1 + q2}\n"); + print("r * q = ${q * r}"); + print("q * r = ${q * r}"); + var q3 = q1 * q2; + var q4 = q2 * q1; + print("q1 * q2 = $q3"); + print("q2 * q1 = $q4\n"); + print("q1 * q2 != q2 * q1 = ${q3 != q4}"); +} diff --git a/Task/Quaternion-type/EasyLang/quaternion-type.easy b/Task/Quaternion-type/EasyLang/quaternion-type.easy new file mode 100644 index 0000000000..6ef652e5ed --- /dev/null +++ b/Task/Quaternion-type/EasyLang/quaternion-type.easy @@ -0,0 +1,61 @@ +func qnorm q[] . + for i to 4 + s += q[i] * q[i] + . + return sqrt s +. +func[] qneg q[] . + for i to 4 + q[i] = -q[i] + . + return q[] +. +func[] qconj q[] . + for i = 2 to 4 + q[i] = -q[i] + . + return q[] +. +func[] qaddreal q[] r . + q[1] += r + return q[] +. +func[] qadd q[] q2[] . + for i to 4 + q[i] += q2[i] + . + return q[] +. +func[] qmulreal q[] r . + for i to 4 + q[i] *= r + . + return q[] +. +func[] qmul q1[] q2[] . + res[] &= q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3] - q1[4] * q2[4] + res[] &= q1[1] * q2[2] + q1[2] * q2[1] + q1[3] * q2[4] - q1[4] * q2[3] + res[] &= q1[1] * q2[3] - q1[2] * q2[4] + q1[3] * q2[1] + q1[4] * q2[2] + res[] &= q1[1] * q2[4] + q1[2] * q2[3] - q1[3] * q2[2] + q1[4] * q2[1] + return res[] +. +q[] = [ 1 2 3 4 ] +q1[] = [ 2 3 4 5 ] +q2[] = [ 3 4 5 6 ] +r = 7 +# +print "q = " & q[] +print "q1 = " & q1[] +print "q2 = " & q2[] +print "r = " & r +print "norm(q) = " & qnorm q[] +print "neg(q) = " & qneg q[] +print "conjugate(q) = " & qconj q[] +print "q+r = " & qaddreal q[] r +print "q1+q2 = " & qadd q1[] q2[] +print "qr = " & qmulreal q[] r +print "q1q2 = " & qmul q1[] q2[] +print "q2q1 = " & qmul q2[] q1[] +if q1[] <> q2[] + print "q1 != q2" +. diff --git a/Task/Queue-Definition/EasyLang/queue-definition.easy b/Task/Queue-Definition/EasyLang/queue-definition.easy new file mode 100644 index 0000000000..7b5aa19e3a --- /dev/null +++ b/Task/Queue-Definition/EasyLang/queue-definition.easy @@ -0,0 +1,56 @@ +prefix qu_ +global q[] head tail . +# +proc enq n . . + if tail = 0 + head = 1 + else + q[tail + 2] = len q[] + 1 + . + q[] &= n + q[] &= tail + q[] &= 0 + tail = len q[] - 2 +. +func deq . + if head = 0 + return 0 / 0 + . + r = q[head] + old = head + head = q[head + 2] + prev = q[-2] + if prev <> 0 + q[prev + 2] = old + . + next = q[-1] + if next <> 0 + q[next + 1] = old + else + tail = old + . + q[old] = q[-3] + q[old + 1] = q[-2] + q[old + 2] = q[-1] + len q[] -3 + if head = len q[] + 1 + head = old + . + if head <> 0 + q[head + 1] = 0 + else + tail = 0 + . + return r +. +func empty . + return if head = 0 +. +prefix +# +qu_enq 2 +qu_enq 5 +qu_enq 7 +while qu_empty = 0 + print qu_deq +. diff --git a/Task/Queue-Definition/Elena/queue-definition.elena b/Task/Queue-Definition/Elena/queue-definition.elena index 5aebbdadc2..08c8db9a5b 100644 --- a/Task/Queue-Definition/Elena/queue-definition.elena +++ b/Task/Queue-Definition/Elena/queue-definition.elena @@ -31,7 +31,7 @@ class queue T pop() { if (theTale == theTop) - { InvalidOperationException.new:"Queue is empty".raise() }; + { InvalidOperationException.new("Queue is empty").raise() }; T item := theArray[theTop]; diff --git a/Task/Queue-Definition/Wren/queue-definition.wren b/Task/Queue-Definition/Wren/queue-definition.wren index 1291269231..eaa1665a21 100644 --- a/Task/Queue-Definition/Wren/queue-definition.wren +++ b/Task/Queue-Definition/Wren/queue-definition.wren @@ -1,4 +1,4 @@ -import "/queue" for Queue +import "./queue" for Queue var q = Queue.new() var item = q.pop() diff --git a/Task/Queue-Usage/EasyLang/queue-usage.easy b/Task/Queue-Usage/EasyLang/queue-usage.easy new file mode 100644 index 0000000000..1c34516183 --- /dev/null +++ b/Task/Queue-Usage/EasyLang/queue-usage.easy @@ -0,0 +1,9 @@ +## +# queue definition +# +qu_enq 2 +qu_enq 5 +qu_enq 7 +while qu_empty = 0 + print qu_deq +. diff --git a/Task/Queue-Usage/Elena/queue-usage.elena b/Task/Queue-Usage/Elena/queue-usage.elena index db27d31263..0f7a17383a 100644 --- a/Task/Queue-Usage/Elena/queue-usage.elena +++ b/Task/Queue-Usage/Elena/queue-usage.elena @@ -6,9 +6,9 @@ public program() // Create a queue and "push" items into it var queue := new Queue(); - queue.push:1; - queue.push:3; - queue.push:5; + queue.push(1); + queue.push(3); + queue.push(5); // "Pop" items from the queue in FIFO order console.printLine(queue.pop()); // 1 @@ -20,5 +20,5 @@ public program() // If we try to pop from an empty queue, an exception // is thrown. - queue.pop() \\ on:(e){ console.writeLine:"Queue empty." } + queue.pop() \\ on::(e){ console.writeLine("Queue empty.") } } diff --git a/Task/Queue-Usage/Wren/queue-usage.wren b/Task/Queue-Usage/Wren/queue-usage.wren index 9b2a106560..1b262135e3 100644 --- a/Task/Queue-Usage/Wren/queue-usage.wren +++ b/Task/Queue-Usage/Wren/queue-usage.wren @@ -1,4 +1,4 @@ -import "/queue" for Queue +import "./queue" for Queue var q = Queue.new() q.push(1) diff --git a/Task/Quickselect-algorithm/Wren/quickselect-algorithm.wren b/Task/Quickselect-algorithm/Wren/quickselect-algorithm.wren index eacffeea2e..01d929a2f0 100644 --- a/Task/Quickselect-algorithm/Wren/quickselect-algorithm.wren +++ b/Task/Quickselect-algorithm/Wren/quickselect-algorithm.wren @@ -1,4 +1,4 @@ -import "/sort" for Find +import "./sort" for Find var a = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] for (k in 0..9) { diff --git a/Task/Quine/Binary-Lambda-Calculus/quine.blc b/Task/Quine/Binary-Lambda-Calculus/quine.blc deleted file mode 100644 index bbd4fd4ea5..0000000000 --- a/Task/Quine/Binary-Lambda-Calculus/quine.blc +++ /dev/null @@ -1 +0,0 @@ -000101100100011010000000000001011011110010111100111111011111011010000101100100011010000000000001011011110010111100111111011111011010 diff --git a/Task/Quine/Wren/quine.wren b/Task/Quine/Wren/quine.wren index c685894c31..36afa90d69 100644 --- a/Task/Quine/Wren/quine.wren +++ b/Task/Quine/Wren/quine.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt -var a = "import $c/fmt$c for Fmt$c$cvar a = $q$cFmt.lprint(a, [34, 34, 10, 10, a, 10])" +var a = "import $c./fmt$c for Fmt$c$cvar a = $q$cFmt.lprint(a, [34, 34, 10, 10, a, 10])" Fmt.lprint(a, [34, 34, 10, 10, a, 10]) diff --git a/Task/Quoting-constructs/Wren/quoting-constructs.wren b/Task/Quoting-constructs/Wren/quoting-constructs.wren index 8cccf15e4a..a03a467ce8 100644 --- a/Task/Quoting-constructs/Wren/quoting-constructs.wren +++ b/Task/Quoting-constructs/Wren/quoting-constructs.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt // simple string literal System.print("Hello world!") diff --git a/Task/RIPEMD-160/Wren/ripemd-160.wren b/Task/RIPEMD-160/Wren/ripemd-160.wren index 96534ffdbd..2b900c9656 100644 --- a/Task/RIPEMD-160/Wren/ripemd-160.wren +++ b/Task/RIPEMD-160/Wren/ripemd-160.wren @@ -1,5 +1,5 @@ -import "/crypto" for Ripemd160 -import "/fmt" for Fmt +import "./crypto" for Ripemd160 +import "./fmt" for Fmt var strings = [ "", diff --git a/Task/RPG-attributes-generator/EasyLang/rpg-attributes-generator.easy b/Task/RPG-attributes-generator/EasyLang/rpg-attributes-generator.easy new file mode 100644 index 0000000000..11cd450552 --- /dev/null +++ b/Task/RPG-attributes-generator/EasyLang/rpg-attributes-generator.easy @@ -0,0 +1,27 @@ +func rollstat . + for i to 4 + h = randint 6 + s += h + min = lower min h + . + return s - min +. +state$[] = [ "STR" "CON" "DEX" "INT" "WIS" "CHA" ] +len stat[] 6 +repeat + sum = 0 + n15 = 0 + for i to 6 + stat[i] = rollstat + sum += stat[i] + if stat[i] >= 15 + n15 += 1 + . + . + until sum >= 75 and n15 >= 2 +. +for i to 6 + print state$[i] & ": " & stat[i] +. +print "-------" +print "TOT: " & sum diff --git a/Task/RPG-attributes-generator/Wren/rpg-attributes-generator.wren b/Task/RPG-attributes-generator/Wren/rpg-attributes-generator.wren index 5de5c19457..962baafc88 100644 --- a/Task/RPG-attributes-generator/Wren/rpg-attributes-generator.wren +++ b/Task/RPG-attributes-generator/Wren/rpg-attributes-generator.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/sort" for Sort +import "./sort" for Sort var rand = Random.new() var vals = List.filled(6, 0) diff --git a/Task/RSA-code/Wren/rsa-code.wren b/Task/RSA-code/Wren/rsa-code.wren index e130e2761e..c1d904d41f 100644 --- a/Task/RSA-code/Wren/rsa-code.wren +++ b/Task/RSA-code/Wren/rsa-code.wren @@ -1,4 +1,4 @@ -import "/big" for BigInt +import "./big" for BigInt var pt = "Rosetta Code" System.print("Plain text: : %(pt)") diff --git a/Task/Radical-of-an-integer/Lua/radical-of-an-integer.lua b/Task/Radical-of-an-integer/Lua/radical-of-an-integer.lua index b402e7bf47..f234df2515 100644 --- a/Task/Radical-of-an-integer/Lua/radical-of-an-integer.lua +++ b/Task/Radical-of-an-integer/Lua/radical-of-an-integer.lua @@ -32,7 +32,7 @@ do -- find the radicals of some integers - the radical of n is the product local dpfc = {} for i = 1, maxNumber do local count = dpfc[ upfc[ i ] ] - dpfc[ upfc[ i ] ] = ( count == null and 1 or count + 1 ) + dpfc[ upfc[ i ] ] = ( count == nil and 1 or count + 1 ) end io.write( "Distribution of radicals:\n" ) for i = 0, #dpfc do diff --git a/Task/Ramanujan-primes-twins/EasyLang/ramanujan-primes-twins.easy b/Task/Ramanujan-primes-twins/EasyLang/ramanujan-primes-twins.easy new file mode 100644 index 0000000000..fd1878b281 --- /dev/null +++ b/Task/Ramanujan-primes-twins/EasyLang/ramanujan-primes-twins.easy @@ -0,0 +1,48 @@ +global cnt[] . +proc primcnt limit . . + cnt[] = [ 0 1 1 ] + for i = 4 step 2 to limit + cnt[] &= 0 + cnt[] &= 1 + . + p = 3 + sq = 9 + while sq <= limit + if cnt[p] <> 0 + for q = sq step p * 2 to limit + cnt[q] = 0 + . + . + sq += (p + 1) * 4 + p += 2 + . + for i = 2 to limit + sum += cnt[i] + cnt[i] = sum + . +. +func log n . + e = 2.7182818284590452354 + return log10 n / log10 e +. +func ramamax n . + return floor (4 * n * log (4 * n)) +. +func ramaprim_twins n . + i = ramamax n + i -= i mod 2 + while i >= 2 + if cnt[i] - cnt[i / 2] < n + p1 = p + p = i + 1 + if p1 - p = 2 + cnt += 1 + . + n -= 1 + . + i -= 2 + . + return cnt +. +primcnt ramamax 1000000 +print ramaprim_twins 1000000 diff --git a/Task/Ramanujan-primes-twins/FreeBASIC/ramanujan-primes-twins.basic b/Task/Ramanujan-primes-twins/FreeBASIC/ramanujan-primes-twins.basic new file mode 100644 index 0000000000..094a7d5c13 --- /dev/null +++ b/Task/Ramanujan-primes-twins/FreeBASIC/ramanujan-primes-twins.basic @@ -0,0 +1,62 @@ +#define floor(x) ((x*2.0-0.5) Shr 1) + +Dim Shared pi() As Integer + +Sub primeCounter(limit As Integer) + Dim As Integer i, q, p, sq, total + Redim pi(limit) + pi(0) = 0 + pi(1) = 0 + For i = 2 To limit + pi(i) = 1 + Next + If limit > 2 Then + For i = 4 To limit Step 2 + pi(i) = 0 + Next i + p = 3 + sq = 9 + While sq <= limit + If pi(p) <> 0 Then + For q = sq To limit Step p*2 + pi(q) = 0 + Next q + End If + sq += (p + 1) * 4 + p += 2 + Wend + total = 0 + For i = 2 To limit + total += pi(i) + pi(i) = total + Next i + End If +End Sub + +Function ramanujanMax(n As Integer) As Integer + Return floor(4 * n * Log(4*n)) +End Function + +Function ramanujanPrimeTwins(n As Integer) As Integer + Dim As Integer maxposs, p1, p, cnt + maxposs = ramanujanMax(n) + maxposs -= maxposs Mod 2 + While maxposs >= 2 + If pi(maxposs) - pi(maxposs \ 2) < n Then + p1 = p + p = maxposs + 1 + If p1 - p = 2 Then cnt += 1 + n -= 1 + End If + maxposs -= 2 + Wend + Return cnt +End Function + +Dim As Integer limit = 1e6 +Dim As Double t0 = Timer +primeCounter ramanujanMax(limit) +Print Using "There are & twins in the first & Ramanujan primes"; ramanujanPrimeTwins(limit); limit +Print Using "##.##sec."; Timer - t0 + +Sleep diff --git a/Task/Ramanujan-primes-twins/Scala/ramanujan-primes-twins.scala b/Task/Ramanujan-primes-twins/Scala/ramanujan-primes-twins.scala new file mode 100644 index 0000000000..caa981316e --- /dev/null +++ b/Task/Ramanujan-primes-twins/Scala/ramanujan-primes-twins.scala @@ -0,0 +1,107 @@ +import java.util.{ArrayList, Arrays, List} + +object RamanujanPrimesTwins { + + def main(args: Array[String]): Unit = { + val limit = 1_000_000 + val primePi = initialisePrimePi(ramanujanMaximum(limit) + 1) + val millionthRamanujanPrime = ramanujanPrime(primePi, limit) + println(s"The 1_000_000th Ramanujan prime is $millionthRamanujanPrime") + + val primes = listPrimesLessThan(millionthRamanujanPrime) + val ramanujanPrimeIndexes = new Array[Int](primes.size) + for (i <- 0 until primes.size by 1) { + ramanujanPrimeIndexes(i) = primePi(primes.get(i)) - primePi(primes.get(i) / 2) + } + + var lowerLimit = ramanujanPrimeIndexes(ramanujanPrimeIndexes.length - 1) + for (i <- ramanujanPrimeIndexes.length - 2 to 0 by -1) { + if (ramanujanPrimeIndexes(i) < lowerLimit) { + lowerLimit = ramanujanPrimeIndexes(i) + } else { + ramanujanPrimeIndexes(i) = 0 + } + } + + val ramanujanPrimes = new ArrayList[Integer]() + for (i <- 0 until ramanujanPrimeIndexes.size by 1) { + if (ramanujanPrimeIndexes(i) != 0) { + ramanujanPrimes.add(primes.get(i)) + } + } + + var twinsCount = 0 + for (i <- 0 until ramanujanPrimes.size - 1) { + if (ramanujanPrimes.get(i) + 2 == ramanujanPrimes.get(i + 1)) { + twinsCount += 1 + } + } + println(s"There are $twinsCount twins in the first $limit Ramanujan primes.") + } + + private def listPrimesLessThan(limit: Int): List[Integer] = { + val composite = new Array[Boolean](limit + 1) + var n = 3 + var nSquared = 9 + while (nSquared <= limit) { + if (!composite(n)) { + for (k <- nSquared until limit by (2*n) ) { + composite(k) = true + } + } + nSquared += (n + 1) << 2 + n += 2 + } + + var result = new ArrayList[Integer]() + result.add(2) + for (i <- 3 until limit by 2) { + if (!composite(i)) { + result.add(i) + } + } + result + } + + private def ramanujanPrime(primePi: Array[Int], number: Int): Int = { + var maximum = ramanujanMaximum(number) + if ((maximum & 1) == 1) { + maximum -= 1 + } + + var index = maximum + while (primePi(index) - primePi(index / 2) >= number) { + index -= 1 + } + index + 1 + } + + private def initialisePrimePi(aLimit : Int): Array[Int] = { + val result = new Array[Int](aLimit ) + Arrays.fill(result, 1) + result(0) = 0 + result(1) = 0 + for (i <- 4 until aLimit by 2) { + result(i) = 0 + } + + var p = 3;var square = 9; + while(square < aLimit) { + if ( result(p) != 0 ) { + for ( q <- square until aLimit by (p << 1) ) { + result(q) = 0; + } + } + square += ( p + 1 ) << 2; + p += 2 + } + for (i <- 1 until result.length) { + result(i) += result(i - 1) + } + result + } + + private def ramanujanMaximum(number: Int): Int = { + Math.ceil(4 * number * Math.log(4 * number)).toInt + } +} diff --git a/Task/Ramanujan-primes-twins/Wren/ramanujan-primes-twins.wren b/Task/Ramanujan-primes-twins/Wren/ramanujan-primes-twins.wren index 24d8a6d223..6e8b2f3c28 100644 --- a/Task/Ramanujan-primes-twins/Wren/ramanujan-primes-twins.wren +++ b/Task/Ramanujan-primes-twins/Wren/ramanujan-primes-twins.wren @@ -1,6 +1,6 @@ -import "/iterate" for Stepped, Indexed -import "/math" for Int, Math -import "/fmt" for Fmt +import "./iterate" for Stepped, Indexed +import "./math" for Int, Math +import "./fmt" for Fmt var count @@ -65,5 +65,5 @@ for (limit in [1e5, 1e6]) { if (ir[i].value + 2 == ir[i+1].value) twins = twins + 1 } Fmt.print("There are $,d twins in the first $,d Ramanujan primes.", twins, limit) - System.print("Took %(Math.toPlaces(System.clock -start, 2, 0)) seconds.\n") + System.print("Took %(Math.toPlaces(System.clock - start, 2, 0)) seconds.\n") } diff --git a/Task/Ramanujans-constant/Wren/ramanujans-constant.wren b/Task/Ramanujans-constant/Wren/ramanujans-constant.wren index 06557ae5fd..6c56b2510a 100644 --- a/Task/Ramanujans-constant/Wren/ramanujans-constant.wren +++ b/Task/Ramanujans-constant/Wren/ramanujans-constant.wren @@ -1,5 +1,5 @@ -import "/big" for BigRat -import "/fmt" for Fmt +import "./big" for BigRat +import "./fmt" for Fmt var pi = "3.1415926535897932384626433832795028841971693993751058209749445923078164" var bigPi = BigRat.fromDecimal(pi) diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/OoRexx/ramer-douglas-peucker-line-simplification.rexx b/Task/Ramer-Douglas-Peucker-line-simplification/OoRexx/ramer-douglas-peucker-line-simplification.rexx new file mode 100644 index 0000000000..ea1aff135f --- /dev/null +++ b/Task/Ramer-Douglas-Peucker-line-simplification/OoRexx/ramer-douglas-peucker-line-simplification.rexx @@ -0,0 +1,98 @@ +/*REXX program uses the Ramer-Douglas-Peucker (RDP) line simplification algorithm for*/ +/*--------------------------- reducing the number of points used to define its shape. */ +Parse Arg epsilon pl /*obtain optional arguments from the CL*/ +If epsilon='' | epsilon=',' then epsilon= 1 /*Not specified? Then use the default.*/ +If pl='' Then pl= '(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)' +Say ' error threshold:' epsilon +Say ' points specified:' pl +Say 'points simplified:' dlp(pl) +Exit +dlp: Procedure Expose epsilon + Parse Arg pl + plc=pl + Do i=1 By 1 While plc<>'' + Parse Var plc '(' X ',' y ')' plc + p.i=.point~new(x,y) + End + end=i-1 + dmax=0 + index=0 + Do i=2 To end-1 + d=distpg(p.i,.line~new(p.1,p.end)) + If d>dmax Then Do + index=i + dmax=d + End + End + If dmax>epsilon Then Do + rla=dlp(subword(pl,1,index)) + rlb=dlp(subword(pl,index,end)) + rl=subword(rla,1,words(rla)-1) rlb + End + Else + rl=word(pl,1) word(pl,end) + Return rl + +::CLASS point public +::ATTRIBUTE X +::ATTRIBUTE Y +::METHOD init PUBLIC + Expose X Y + Use Arg X,Y + +::CLASS line public +::ATTRIBUTE A +::ATTRIBUTE B +::METHOD init PUBLIC + Expose A B + Use Arg A,B + If A~x=B~x & A~y=B~y Then Do + Say 'not a line' + Return .nil + End + +::METHOD k PUBLIC + Expose A B + ax=A~x; ay=A~y; bx=B~x; by=B~y + If ax=bx Then + res='infinite' + Else + res=(by-ay)/(bx-ax) + Return res + +::METHOD d PUBLIC + Expose A B + ax=A~x; ay=A~y + If self~k='infinite' Then + res='indeterminate' + Else + res=round(ay-ax*self~k) + Return res + +::ROUTINE distpg PUBLIC --Compute the distance from a point to a line +/*********************************************************************** +* Compute the distance from a point to a line +***********************************************************************/ + Use Arg A,g + ax=A~x; ay=A~y + k=g~k + If k='infinite' Then Do + Parse Value g~kxd With 'x='gx + res=gx-ax + End + Else + res=(ay-k*ax-g~d)/rxCalcsqrt(1+k**2) + Return abs(res) + +::ROUTINE round PUBLIC --Round a number to 3 decimal digits +/*********************************************************************** +* Round a nmber to 3 decimal digits +***********************************************************************/ + Use Arg z,d + Numeric Digits 30 + res=z+0 + If d>'' Then + res=format(res,9,6) + Return strip(res) + +::requires rxMath library diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/REXX/ramer-douglas-peucker-line-simplification.rexx b/Task/Ramer-Douglas-Peucker-line-simplification/REXX/ramer-douglas-peucker-line-simplification-1.rexx similarity index 100% rename from Task/Ramer-Douglas-Peucker-line-simplification/REXX/ramer-douglas-peucker-line-simplification.rexx rename to Task/Ramer-Douglas-Peucker-line-simplification/REXX/ramer-douglas-peucker-line-simplification-1.rexx diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/REXX/ramer-douglas-peucker-line-simplification-2.rexx b/Task/Ramer-Douglas-Peucker-line-simplification/REXX/ramer-douglas-peucker-line-simplification-2.rexx new file mode 100644 index 0000000000..aac2fd5ba7 --- /dev/null +++ b/Task/Ramer-Douglas-Peucker-line-simplification/REXX/ramer-douglas-peucker-line-simplification-2.rexx @@ -0,0 +1,72 @@ +/*REXX program uses the Ramer-Douglas-Peucker (RDP) line simplification algorithm for*/ +/*--------------------------- reducing the number of points used to define its shape. */ +Parse Arg epsilon pl /*obtain optional arguments from the CL*/ +If epsilon='' | epsilon=',' then epsilon= 1 /*Not specified? Then use the default.*/ +If pl='' Then pl= '(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)' +Say ' error threshold:' epsilon +Say ' points specified:' pl +Say 'points simplified:' dlp(pl) +Exit +dlp: Procedure Expose epsilon + Parse Arg pl + plc=pl + Do i=1 By 1 While plc<>'' + Parse Var plc '(' x ',' y ')' plc + p.i=x y + End + end=i-1 + dmax=0 + index=0 + Do i=2 To end-1 + d=distpg(p.i,p.1,p.end) + If d>dmax Then Do + index=i + dmax=d + End + End + If dmax>epsilon Then Do + rla=dlp(subword(pl,1,index)) + rlb=dlp(subword(pl,index,end)) + rl=subword(rla,1,words(rla)-1) rlb + End + Else + rl=word(pl,1) word(pl,end) + Return rl + +distpg: Procedure +/********************************************************************** +* compute the distance of point P from the line giveb by A and B +**********************************************************************/ + Parse Arg P,A,B + Parse Var P px py + Parse Var A ax ay + Parse Var B bx by + If ax=bx Then + res=px-ax + Else Do + k=(by-ay)/(bx-ax) + d=(ay-ax*k) + res=(py-k*px-d)/sqrt(1+k**2) + End + Return abs(res) +sqrt: Procedure +/* REXX *************************************************************** +* EXEC to calculate the square root of a = 2 with high precision +**********************************************************************/ + Parse Arg x,prec + If prec<9 Then prec=9 + prec1=2*prec + eps=10**(-prec1) + k = 1 + Numeric Digits 3 + r0= x + r = 1 + Do i=1 By 1 Until r=r0 | (abs(r*r-x) 0.0) { dx /= mag; dy /= mag } + val pvx = pt._1 - lineStart._1 + val pvy = pt._2 - lineStart._2 + + // Get dot product (project pv onto normalized direction) + val pvdot = dx * pvx + dy * pvy + + // Scale line direction vector and subtract it from pv + val ax = pvx - pvdot * dx + val ay = pvy - pvdot * dy + + math.hypot(ax, ay) + } + + def RamerDouglasPeucker( + pointList: List[Point], + epsilon: Double + ): List[Point] = { + if (pointList.length < 2) + throw new IllegalArgumentException("Not enough points to simplify") + + // Check if there are points to process + if (pointList.length > 2) { + // Find the point with the maximum distance from the line between the first and last + val (dmax, index) = pointList.zipWithIndex + .slice(1, pointList.length - 1) + .map { case (point, i) => + (perpendicularDistance(point, pointList.head, pointList.last), i) + } + .maxBy(_._1) + + // If max distance is greater than epsilon, recursively simplify + if (dmax > epsilon) { + val firstLine = pointList.take(index + 1) + val lastLine = pointList.drop(index) + val recResults1 = RamerDouglasPeucker(firstLine, epsilon) + val recResults2 = RamerDouglasPeucker(lastLine, epsilon) + + // Combine the results + (recResults1.init ++ recResults2).distinct + } else { + // If no point is further than epsilon, return the endpoints + List(pointList.head, pointList.last) + } + } else { + // If there are only two points, just return them + pointList + } + } + + val pointList = List( + (0.0, 0.0), + (1.0, 0.1), + (2.0, -0.1), + (3.0, 5.0), + (4.0, 6.0), + (5.0, 7.0), + (6.0, 8.1), + (7.0, 9.0), + (8.0, 9.0), + (9.0, 9.0) + ) + + val simplifiedPointList = RamerDouglasPeucker(pointList, 1.0) + println("Points remaining after simplification:") + simplifiedPointList.foreach(println) +} diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/Wren/ramer-douglas-peucker-line-simplification.wren b/Task/Ramer-Douglas-Peucker-line-simplification/Wren/ramer-douglas-peucker-line-simplification.wren index 91d8a28f0b..6c93af86fa 100644 --- a/Task/Ramer-Douglas-Peucker-line-simplification/Wren/ramer-douglas-peucker-line-simplification.wren +++ b/Task/Ramer-Douglas-Peucker-line-simplification/Wren/ramer-douglas-peucker-line-simplification.wren @@ -1,4 +1,4 @@ -import "/dynamic" for Tuple +import "./dynamic" for Tuple var Point = Tuple.create("Point", ["x", "y"]) diff --git a/Task/Random-Latin-squares/Wren/random-latin-squares-2.wren b/Task/Random-Latin-squares/Wren/random-latin-squares-2.wren index f79cc7c609..405424c685 100644 --- a/Task/Random-Latin-squares/Wren/random-latin-squares-2.wren +++ b/Task/Random-Latin-squares/Wren/random-latin-squares-2.wren @@ -1,7 +1,7 @@ import "random" for Random -import "/sort" for Sort -import "/fmt" for Fmt -import "/math" for Int +import "./sort" for Sort +import "./fmt" for Fmt +import "./math" for Int var rand = Random.new() var counts = List.filled(4, 0) diff --git a/Task/Random-numbers/Elena/random-numbers.elena b/Task/Random-numbers/Elena/random-numbers.elena index 20b17528cb..81a9b469cf 100644 --- a/Task/Random-numbers/Elena/random-numbers.elena +++ b/Task/Random-numbers/Elena/random-numbers.elena @@ -12,7 +12,7 @@ public program() real[] a := new real[](1000); real tAvg := 0; - for (int x := 0, x < a.Length, x += 1) + for (int x := 0; x < a.Length; x += 1) { a[x] := (randomNormal()) / 2 + 1; tAvg += a[x] @@ -22,7 +22,7 @@ public program() console.printLine("Average: ", tAvg); real s := 0; - for (int x := 0, x < a.Length, x += 1) + for (int x := 0; x < a.Length; x += 1) { s += power(a[x] - tAvg, 2) }; diff --git a/Task/Random-sentence-from-book/Wren/random-sentence-from-book.wren b/Task/Random-sentence-from-book/Wren/random-sentence-from-book.wren index b9318ce053..e55e9aa7ad 100644 --- a/Task/Random-sentence-from-book/Wren/random-sentence-from-book.wren +++ b/Task/Random-sentence-from-book/Wren/random-sentence-from-book.wren @@ -1,6 +1,6 @@ import "io" for File import "random" for Random -import "/seq" for Lst +import "./seq" for Lst // puctuation to keep (also keep hyphen and apostrophe but don't count as words) var ending = ".!?" diff --git a/Task/Range-consolidation/ALGOL-68/range-consolidation.alg b/Task/Range-consolidation/ALGOL-68/range-consolidation.alg new file mode 100644 index 0000000000..a8d0e4311a --- /dev/null +++ b/Task/Range-consolidation/ALGOL-68/range-consolidation.alg @@ -0,0 +1,115 @@ +BEGIN # range consolidation # + + MODE RANGE = STRUCT( REAL lb, ub ); + + # returns a with the bounds swapped if necessary, so lb OF a <= ub OF a # + OP NORMALISE = ( RANGE a )RANGE: + ( IF lb OF a < ub OF a THEN lb OF a ELSE ub OF a FI + , IF ub OF a > lb OF a THEN ub OF a ELSE lb OF a FI + ) # NORMALISE # ; + # returns a with each element normalised # + OP NORMALISE = ( []RANGE a )[]RANGE: + BEGIN + [ LWB a : UPB a ]RANGE result; + FOR a pos FROM LWB a TO UPB a DO result[ a pos ] := NORMALISE a[ a pos ] OD; + result + END # NORMALISE # ; + OP < = ( RANGE a, b )BOOL: lb OF a < lb OF b; + OP > = ( RANGE a, b )BOOL: lb OF a > lb OF b; + + # sorts a into order of each element's lb # + OP SORT = ( []RANGE a )[]RANGE: + BEGIN + # in-place quick sort an array of RANGEs from element lb # + # to element ub # + PROC quicksort = ( REF[]RANGE a, INT lb, ub )REF[]RANGE: + IF ub <= lb + THEN + # empty array or only 1 element # + a + ELSE + # more than one element, so must sort # + INT left := lb; + INT right := ub; + # choosing the middle element of the array as the pivot # + RANGE pivot := a[ left + ( ( right + 1 ) - left ) OVER 2 ]; + WHILE + WHILE IF left <= ub THEN a[ left ] < pivot ELSE FALSE FI DO left +:= 1 OD; + WHILE IF right >= lb THEN a[ right ] > pivot ELSE FALSE FI DO right -:= 1 OD; + left <= right + DO + RANGE t := a[ left ]; + a[ left ] := a[ right ]; + a[ right ] := t; + left +:= 1; + right -:= 1 + OD; + quicksort( a, lb, right ); + quicksort( a, left, ub ); + a + FI # quicksort # ; + quicksort( HEAP[ LWB a : UPB a ]RANGE := a, LWB a, UPB a ) + END # SORT # ; + + # returns the consolidation of the ranges in a in # + OP CONSOLIDATE = ( []RANGE a in )[]RANGE: + IF UPB a in <= LWB a in + THEN a in # 0 or 1 range # + ELSE # multiple ranges # + []RANGE a = SORT NORMALISE a in; + [ 1 : 2 * ( ( UPB a - LWB a ) + 1 ) ]RANGE result; + INT r max := 1; + result[ r max ] := a[ LWB a ]; + FOR a pos FROM LWB a + 1 TO UPB a DO + RANGE m = result[ r max ], n = a[ a pos ]; + IF ub OF m < lb OF n THEN + result[ r max +:= 1 ] := n # distinct ranges # + ELSE + result[ r max ] # overlapping ranges # + := ( IF lb OF m < lb OF n THEN lb OF m ELSE lb OF n FI + , IF ub OF m > ub OF n THEN ub OF m ELSE ub OF n FI + ) + FI + OD; + result[ : r max ] + FI # CONSOLIDATE # ; + + OP FMT = ( REAL v )STRING: # prints v with at most 3 decimal places # + BEGIN + STRING result := fixed( ABS v, 0, 3 ); + IF result[ LWB result ] = "." THEN "0" +=: result FI; + WHILE result[ UPB result ] = "0" DO result := result[ : UPB result - 1 ] OD; + IF result[ UPB result ] = "." THEN result := result[ : UPB result - 1 ] FI; + IF v < 0 THEN "-" ELSE "" FI + result + END # FMT # ; + + OP TOSTRING = ( RANGE a )STRING: "[ " + FMT lb OF a + ", " + FMT ub OF a + " ]"; + OP TOSTRING = ( []RANGE a )STRING: + BEGIN + STRING result := "["; + STRING prefix := " "; + FOR r pos FROM LWB a TO UPB a DO + result +:= prefix + TOSTRING a[ r pos ]; + prefix := ", " + OD; + result + " ]" + END # TOSTRING # ; + PRIO PAD = 8; # right pads s with blanks to w characters # + OP PAD = ( STRING s, INT w )STRING: + IF INT len = ( UPB s - LWB s ) + 1; + len >= w + THEN s + ELSE s + ( ( w - len ) * " " ) + FI # PAD # ; + + # task test cases # + + PROC test = ( []RANGE a )VOID: + BEGIN print( ( ( TOSTRING a PAD 60 ), " -> ", TOSTRING CONSOLIDATE a, newline ) ) END; + test( []RANGE( RANGE( 1.1, 2.2 ) ) ); + test( ( ( 6.1, 7.2 ), ( 7.2, 8.3 ) ) ); + test( ( ( 4, 3 ), ( 2, 1 ) ) ); + test( ( ( 4, 3 ), ( 2, 1 ), ( -1, -2 ), ( 3.9, 10 ) ) ); + test( ( ( 1, 3 ), ( -6, -1 ), ( -4, -5 ), ( 8, 2 ), ( -6, -6 ) ) ) + +END diff --git a/Task/Range-extraction/EasyLang/range-extraction.easy b/Task/Range-extraction/EasyLang/range-extraction.easy new file mode 100644 index 0000000000..34766517e6 --- /dev/null +++ b/Task/Range-extraction/EasyLang/range-extraction.easy @@ -0,0 +1,21 @@ +func$ mkrange arr[] . + idx = 1 + idx2 = 1 + while idx <= len arr[] + repeat + idx2 += 1 + until idx2 > len arr[] or arr[idx2] - arr[idx2 - 1] <> 1 + . + if idx2 - idx > 2 + r$ &= arr[idx] & "-" & arr[idx2 - 1] & "," + idx = idx2 + else + while idx < idx2 + r$ &= arr[idx] & "," + idx += 1 + . + . + . + return substr r$ 1 (len r$ - 1) +. +print mkrange [ 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 ] diff --git a/Task/Ranking-methods/Wren/ranking-methods.wren b/Task/Ranking-methods/Wren/ranking-methods.wren index 1dc610b8d3..c126b12255 100644 --- a/Task/Ranking-methods/Wren/ranking-methods.wren +++ b/Task/Ranking-methods/Wren/ranking-methods.wren @@ -1,5 +1,5 @@ -import "/math" for Nums -import "/fmt" for Fmt +import "./math" for Nums +import "./fmt" for Fmt /* all ranking functions assume the array of Pairs is non-empty and already sorted by decreasing order of scores and then, if the scores are equal, by reverse diff --git a/Task/Rare-numbers/Langur/rare-numbers-2.langur b/Task/Rare-numbers/Langur/rare-numbers-2.langur deleted file mode 100644 index f29707686e..0000000000 --- a/Task/Rare-numbers/Langur/rare-numbers-2.langur +++ /dev/null @@ -1 +0,0 @@ -val .reverse = f toNumber join reverse split .n diff --git a/Task/Rare-numbers/Langur/rare-numbers-1.langur b/Task/Rare-numbers/Langur/rare-numbers.langur similarity index 84% rename from Task/Rare-numbers/Langur/rare-numbers-1.langur rename to Task/Rare-numbers/Langur/rare-numbers.langur index e2558bf81a..57af78e1b2 100644 --- a/Task/Rare-numbers/Langur/rare-numbers-1.langur +++ b/Task/Rare-numbers/Langur/rare-numbers.langur @@ -9,10 +9,9 @@ val .israre = f(.n) { } val .findfirst = f(.max) { - for[=[]] .i = 0; ; .i += 1 { + for[=[]] .i = 0; len(_for) < .max; .i += 1 { if .israre(.i) { _for ~= [.i] - if len(_for) == .max: break } } } diff --git a/Task/Rare-numbers/Wren/rare-numbers-1.wren b/Task/Rare-numbers/Wren/rare-numbers-1.wren index 7cd6d5fd5c..4829e57fb9 100644 --- a/Task/Rare-numbers/Wren/rare-numbers-1.wren +++ b/Task/Rare-numbers/Wren/rare-numbers-1.wren @@ -1,5 +1,5 @@ -import "/sort" for Sort -import "/fmt" for Fmt +import "./sort" for Sort +import "./fmt" for Fmt class Term { construct new(coeff, ix1, ix2) { diff --git a/Task/Rare-numbers/Wren/rare-numbers-2.wren b/Task/Rare-numbers/Wren/rare-numbers-2.wren index 1ee858e107..09a238c9a8 100644 --- a/Task/Rare-numbers/Wren/rare-numbers-2.wren +++ b/Task/Rare-numbers/Wren/rare-numbers-2.wren @@ -1,6 +1,6 @@ -import "/sort" for Sort -import "/fmt" for Fmt -import "/date" for Date +import "./sort" for Sort +import "./fmt" for Fmt +import "./date" for Date class Z2 { construct new(value, hasValue) { diff --git a/Task/Rate-counter/EasyLang/rate-counter.easy b/Task/Rate-counter/EasyLang/rate-counter.easy new file mode 100644 index 0000000000..1526c935de --- /dev/null +++ b/Task/Rate-counter/EasyLang/rate-counter.easy @@ -0,0 +1,15 @@ +color 700 +on animate + clear + rad += 0.2 + move 50 50 + circle rad + if rad > 50 + rad = 0 + . + t = systime + if t0 > 0 + print 1000 * (t - t0) & " ms" + . + t0 = t +end diff --git a/Task/Ray-casting-algorithm/ALGOL-68/ray-casting-algorithm.alg b/Task/Ray-casting-algorithm/ALGOL-68/ray-casting-algorithm.alg new file mode 100644 index 0000000000..2703405022 --- /dev/null +++ b/Task/Ray-casting-algorithm/ALGOL-68/ray-casting-algorithm.alg @@ -0,0 +1,63 @@ +BEGIN + +MODE POINT = STRUCT( REAL x, y ); + +MODE POLYGON = STRUCT( STRING name, FLEX[ 1 : 0 ]POINT points ); +PROC contains = ( POLYGON self, POINT p )BOOL: + BEGIN + BOOL odd := FALSE, REAL eps = 1e-9; + PROC rayseg = ( POINT p in, a in, b in )BOOL: + BEGIN + PROC max = ( REAL m, n )REAL: IF m > n THEN m ELSE n FI; + PROC min = ( REAL m, n )REAL: IF m < n THEN m ELSE n FI; + POINT p := p in, a := a in, b := b in; + IF y OF a > y OF b THEN POINT t = a; a := b; b := t FI; + IF y OF p = y OF a OR y OF p = y OF b THEN y OF p+:= eps FI; + IF y OF p < y OF a OR y OF p > y OF b OR x OF p > max( x OF a, x OF b ) + THEN FALSE + ELIF x OF p < min( x OF a, x OF b ) + THEN TRUE + ELSE + REAL red = IF x OF a = x OF b THEN max real ELSE ( y OF b - y OF a ) / ( x OF b - x OF a ) FI; + REAL blu = IF x OF a = x OF p THEN max real ELSE ( y OF p - y OF a ) / ( x OF p - x OF a ) FI; + blu >= red + FI + END # rayseq # ; + + INT len points = ( UPB points OF self - LWB points OF self ) + 1; + FOR i FROM LWB points OF self TO UPB points OF self DO + POINT a = ( points OF self )[ i ]; + POINT b = ( points OF self )[ ( i MOD len points ) + 1 ]; + IF rayseg( p, a, b ) THEN odd := NOT odd FI + OD; + odd + END # contains # ; + +[]POLYGON polygons = + ( ( "square" + , ( ( 0, 0 ), ( 10, 0 ), ( 10, 10 ), ( 0, 10 ) ) + ) + , ( "squarehole" + , ( ( 0, 0 ), ( 10, 0 ), ( 10, 10 ), ( 0, 10 ), ( 2.5, 2.5 ), ( 7.5, 2.5 ), ( 7.5, 7.5 ), ( 2.5, 7.5 ) ) + ) + , ( "strange" + , ( ( 0, 0 ), ( 2.5, 2.5 ), ( 0, 10 ), ( 2.5, 7.5 ), ( 7.5, 7.5 ), ( 10, 10 ), ( 10, 0 ), ( 2.5, 2.5 ) ) + ) + , ( "hexagon" + , ( ( 3, 0 ), ( 7, 0 ), ( 10, 5 ), ( 7, 10 ), ( 3, 10 ), ( 0, 5 ) ) + ) + ); +[]POINT points = ( ( 5, 5 ), (5 , 8 ), ( -10, 5 ), ( 0, 5 ), ( 10, 5 ), ( 8, 5 ), ( 10, 10 ) ); + +FOR p FROM LWB polygons TO UPB polygons DO + POLYGON poly = polygons[ p ]; + print(( "Does '", name OF poly, "' contain the point..", newline ) ); + FOR i FROM LWB points TO UPB points DO + POINT pt = points[ i ]; + print( ( " ( ", fixed( x OF pt, -5, 1 ), ", ", fixed( y OF pt, -5, 1 ), " ) " ) ); + print( ( IF contains( poly, pt ) THEN " true" ELSE " false" FI, newline ) ) + OD; + print( ( newline ) ) +OD + +END diff --git a/Task/Ray-casting-algorithm/C-sharp/ray-casting-algorithm.cs b/Task/Ray-casting-algorithm/C-sharp/ray-casting-algorithm.cs new file mode 100644 index 0000000000..20336eddd3 --- /dev/null +++ b/Task/Ray-casting-algorithm/C-sharp/ray-casting-algorithm.cs @@ -0,0 +1,67 @@ +using System; + +class RayCasting { + + static bool Intersects(int[] A, int[] B, double[] P) { + if (A[1] > B[1]) + return Intersects(B, A, P); + + if (P[1] == A[1] || P[1] == B[1]) + P[1] += 0.0001; + + if (P[1] > B[1] || P[1] < A[1] || P[0] >= Math.Max(A[0], B[0])) + return false; + + if (P[0] < Math.Min(A[0], B[0])) + return true; + + double red = (P[1] - A[1]) / (P[0] - A[0]); + double blue = (B[1] - A[1]) / (B[0] - A[0]); + return red >= blue; + } + + static bool Contains(int[][] shape, double[] pnt) { + bool inside = false; + int len = shape.Length; + for (int i = 0; i < len; i++) { + if (Intersects(shape[i], shape[(i + 1) % len], pnt)) + inside = !inside; + } + return inside; + } + + public static void Main(string[] args) { + double[][] testPoints = new double[][] { + new double[] { 10, 10 }, new double[] { 10, 16 }, new double[] { -20, 10 }, + new double[] { 0, 10 }, new double[] { 20, 10 }, new double[] { 16, 10 }, + new double[] { 20, 20 } + }; + + foreach (int[][] shape in shapes) { + foreach (double[] pnt in testPoints) + Console.Write($"{Contains(shape, pnt),7} "); + Console.WriteLine(); + } + } + + readonly static int[][] square = new int[][] { + new int[] { 0, 0 }, new int[] { 20, 0 }, new int[] { 20, 20 }, new int[] { 0, 20 } + }; + + readonly static int[][] squareHole = new int[][] { + new int[] { 0, 0 }, new int[] { 20, 0 }, new int[] { 20, 20 }, new int[] { 0, 20 }, + new int[] { 5, 5 }, new int[] { 15, 5 }, new int[] { 15, 15 }, new int[] { 5, 15 } + }; + + readonly static int[][] strange = new int[][] { + new int[] { 0, 0 }, new int[] { 5, 5 }, new int[] { 0, 20 }, new int[] { 5, 15 }, + new int[] { 15, 15 }, new int[] { 20, 20 }, new int[] { 20, 0 } + }; + + readonly static int[][] hexagon = new int[][] { + new int[] { 6, 0 }, new int[] { 14, 0 }, new int[] { 20, 10 }, new int[] { 14, 20 }, + new int[] { 6, 20 }, new int[] { 0, 10 } + }; + + readonly static int[][][] shapes = new int[][][] { square, squareHole, strange, hexagon }; +} diff --git a/Task/Ray-casting-algorithm/Wren/ray-casting-algorithm.wren b/Task/Ray-casting-algorithm/Wren/ray-casting-algorithm.wren index 6a1f5a11d6..9a0650bd05 100644 --- a/Task/Ray-casting-algorithm/Wren/ray-casting-algorithm.wren +++ b/Task/Ray-casting-algorithm/Wren/ray-casting-algorithm.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt class RayCasting { static intersects(a, b, p) { diff --git a/Task/Read-a-configuration-file/Wren/read-a-configuration-file.wren b/Task/Read-a-configuration-file/Wren/read-a-configuration-file.wren index ea3558bd58..65b7a6619c 100644 --- a/Task/Read-a-configuration-file/Wren/read-a-configuration-file.wren +++ b/Task/Read-a-configuration-file/Wren/read-a-configuration-file.wren @@ -1,5 +1,5 @@ import "io" for File -import "/ioutil" for FileUtil +import "./ioutil" for FileUtil class Configuration { construct new(map) { diff --git a/Task/Read-a-file-line-by-line/Elena/read-a-file-line-by-line.elena b/Task/Read-a-file-line-by-line/Elena/read-a-file-line-by-line.elena index 9e45ecba78..54e25a1d64 100644 --- a/Task/Read-a-file-line-by-line/Elena/read-a-file-line-by-line.elena +++ b/Task/Read-a-file-line-by-line/Elena/read-a-file-line-by-line.elena @@ -4,5 +4,5 @@ import extensions'routines; public program() { - File.assign:"file.txt".forEachLine(printingLn) + File.assign("file.txt").forEachLine(printingLn) } diff --git a/Task/Read-entire-file/Java/read-entire-file-5.java b/Task/Read-entire-file/Java/read-entire-file-5.java new file mode 100644 index 0000000000..735800cf08 --- /dev/null +++ b/Task/Read-entire-file/Java/read-entire-file-5.java @@ -0,0 +1,8 @@ +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; + +public class ReadAll { + public static void main(String[] args) { + System.out.print(Files.readString(Path.of(args[0], StandardCharsets.UTF_8))); + } +} diff --git a/Task/Record-sound/Wren/record-sound-1.wren b/Task/Record-sound/Wren/record-sound-1.wren index 3d2b1caa0f..8922c706f5 100644 --- a/Task/Record-sound/Wren/record-sound-1.wren +++ b/Task/Record-sound/Wren/record-sound-1.wren @@ -1,4 +1,4 @@ -/* record_sound.wren */ +/* Record_sound.wren */ class C { foreign static getInput(maxSize) diff --git a/Task/Record-sound/Wren/record-sound-2.wren b/Task/Record-sound/Wren/record-sound-2.wren index ab947be46e..0ad3196c0d 100644 --- a/Task/Record-sound/Wren/record-sound-2.wren +++ b/Task/Record-sound/Wren/record-sound-2.wren @@ -83,7 +83,7 @@ int main(int argc, char **argv) { config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "record_sound.wren"; + const char* fileName = "Record_sound.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy b/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy new file mode 100644 index 0000000000..a3ff68820f --- /dev/null +++ b/Task/Reduced-row-echelon-form/EasyLang/reduced-row-echelon-form.easy @@ -0,0 +1,38 @@ +proc rref . m[][] . + nrow = len m[][] + ncol = len m[1][] + lead = 1 + for r to nrow + if lead > ncol + return + . + i = r + while m[i][lead] = 0 + i += 1 + if i > nrow + i = r + lead += 1 + if lead > ncol + return + . + . + . + swap m[i][] m[r][] + m = m[r][lead] + for k to ncol + m[r][k] /= m + . + for i to nrow + if i <> r + m = m[i][lead] + for k to ncol + m[i][k] -= m * m[r][k] + . + . + . + lead += 1 + . +. +test[][] = [ [ 1 2 -1 -4 ] [ 2 3 -1 -11 ] [ -2 0 -3 22 ] ] +rref test[][] +print test[][] diff --git a/Task/Reduced-row-echelon-form/Wren/reduced-row-echelon-form.wren b/Task/Reduced-row-echelon-form/Wren/reduced-row-echelon-form.wren index ad949ec072..d521698ac2 100644 --- a/Task/Reduced-row-echelon-form/Wren/reduced-row-echelon-form.wren +++ b/Task/Reduced-row-echelon-form/Wren/reduced-row-echelon-form.wren @@ -1,5 +1,5 @@ -import "/matrix" for Matrix -import "/fmt" for Fmt +import "./matrix" for Matrix +import "./fmt" for Fmt var m = Matrix.new([ [ 1, 2, -1, -4], diff --git a/Task/Reflection-Get-source/Wren/reflection-get-source.wren b/Task/Reflection-Get-source/Wren/reflection-get-source.wren index 7a4d0593e7..35d8e7d3d7 100644 --- a/Task/Reflection-Get-source/Wren/reflection-get-source.wren +++ b/Task/Reflection-Get-source/Wren/reflection-get-source.wren @@ -1,6 +1,6 @@ import "os" for Platform, Process import "io" for File -import "/pattern" for Pattern +import "/.pattern" for Pattern var getSourceLines = Fn.new { var fileName = Process.allArguments[1] diff --git a/Task/Reflection-List-methods/Elena/reflection-list-methods.elena b/Task/Reflection-List-methods/Elena/reflection-list-methods.elena index 4861789f88..54c0e7aece 100644 --- a/Task/Reflection-List-methods/Elena/reflection-list-methods.elena +++ b/Task/Reflection-List-methods/Elena/reflection-list-methods.elena @@ -13,7 +13,7 @@ public program() { var o := new MyClass(); - o.__getClass().__getMessages().forEach:(p) + o.__getClass().__getMessages().forEach::(p) { console.printLine("o.",p) } diff --git a/Task/Reflection-List-properties/Elena/reflection-list-properties.elena b/Task/Reflection-List-properties/Elena/reflection-list-properties.elena index fc08354750..0397b02201 100644 --- a/Task/Reflection-List-properties/Elena/reflection-list-properties.elena +++ b/Task/Reflection-List-properties/Elena/reflection-list-properties.elena @@ -17,7 +17,7 @@ public program() this Y := "String"; }; - MyClass.__getProperties().forEach:(p) + MyClass.__getProperties().forEach::(p) { console.printLine("o.",p,"=",p.getPropertyValue(o)) } diff --git a/Task/Regular-expressions/Langur/regular-expressions-3.langur b/Task/Regular-expressions/Langur/regular-expressions-3.langur index e4e2858ad2..11bbed2fdd 100644 --- a/Task/Regular-expressions/Langur/regular-expressions-3.langur +++ b/Task/Regular-expressions/Langur/regular-expressions-3.langur @@ -1 +1,4 @@ -if val (.x, .y) = submatch(re/(abc+).+?(def)/, "somestring") { ... } +switch "somestring" { + case re/abc/: ... + ... +} diff --git a/Task/Regular-expressions/Langur/regular-expressions-4.langur b/Task/Regular-expressions/Langur/regular-expressions-4.langur index 737a671db7..ea4b2722e1 100644 --- a/Task/Regular-expressions/Langur/regular-expressions-4.langur +++ b/Task/Regular-expressions/Langur/regular-expressions-4.langur @@ -1,4 +1,4 @@ -given "somestring" { - case re/abc/: ... +switch re/abc/ { + case "somestring": ... ... } diff --git a/Task/Regular-expressions/Langur/regular-expressions-5.langur b/Task/Regular-expressions/Langur/regular-expressions-5.langur index 949629bc2a..dd3a7ba9f8 100644 --- a/Task/Regular-expressions/Langur/regular-expressions-5.langur +++ b/Task/Regular-expressions/Langur/regular-expressions-5.langur @@ -1,4 +1,2 @@ -given re/abc/ { - case "somestring": ... - ... -} +replace("abcdef", re/abc/, "Y") +# result: "Ydef" diff --git a/Task/Regular-expressions/Langur/regular-expressions-6.langur b/Task/Regular-expressions/Langur/regular-expressions-6.langur deleted file mode 100644 index dd3a7ba9f8..0000000000 --- a/Task/Regular-expressions/Langur/regular-expressions-6.langur +++ /dev/null @@ -1,2 +0,0 @@ -replace("abcdef", re/abc/, "Y") -# result: "Ydef" diff --git a/Task/Regular-expressions/Wren/regular-expressions-1.wren b/Task/Regular-expressions/Wren/regular-expressions-1.wren index 0f40a54c79..8001e28e9a 100644 --- a/Task/Regular-expressions/Wren/regular-expressions-1.wren +++ b/Task/Regular-expressions/Wren/regular-expressions-1.wren @@ -1,4 +1,4 @@ -import "/pattern" for Pattern +import "./pattern" for Pattern var s = "This is a story about R2D2 and C3P0 who are best friends." var p = Pattern.new("/u/d/u/d") diff --git a/Task/Regular-expressions/Wren/regular-expressions-2.wren b/Task/Regular-expressions/Wren/regular-expressions-2.wren index 70740b2fd1..98a98a0be7 100644 --- a/Task/Regular-expressions/Wren/regular-expressions-2.wren +++ b/Task/Regular-expressions/Wren/regular-expressions-2.wren @@ -1,4 +1,4 @@ -/* regular_expressions.wren */ +/* Regular_expressions_2.wren */ import "./regex" for Regex var s = "This is a story about R2D2 and C3P0 who are best friends." diff --git a/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena b/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena index 17e27a8ade..80075ac1c9 100644 --- a/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena +++ b/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena @@ -7,7 +7,7 @@ public program() var nums := new int[]{1,1,2,3,4,4}; auto unique := new Map(); - nums.forEach:(n){ unique[n] := n }; + nums.forEach::(n){ unique[n] := n }; console.printLine(unique.MapValues.asEnumerable()) } diff --git a/Task/Remove-duplicate-elements/Wren/remove-duplicate-elements.wren b/Task/Remove-duplicate-elements/Wren/remove-duplicate-elements.wren index 67238fce18..bbaa436fc7 100644 --- a/Task/Remove-duplicate-elements/Wren/remove-duplicate-elements.wren +++ b/Task/Remove-duplicate-elements/Wren/remove-duplicate-elements.wren @@ -1,4 +1,4 @@ -import "/sort" for Sort +import "./sort" for Sort // Using a map - order of distinct items is undefined. var removeDuplicates1 = Fn.new { |a| diff --git a/Task/Rename-a-file/Wren/rename-a-file.wren b/Task/Rename-a-file/Wren/rename-a-file.wren index 7f04066b24..3557d15865 100644 --- a/Task/Rename-a-file/Wren/rename-a-file.wren +++ b/Task/Rename-a-file/Wren/rename-a-file.wren @@ -1,4 +1,4 @@ -import "/ioutil" for FileUtil +import "./ioutil" for FileUtil FileUtil.move("input.txt", "output.txt") FileUtil.move("/input.txt", "/output.txt") diff --git a/Task/Rep-string/C-sharp/rep-string.cs b/Task/Rep-string/C-sharp/rep-string.cs new file mode 100644 index 0000000000..7af4850801 --- /dev/null +++ b/Task/Rep-string/C-sharp/rep-string.cs @@ -0,0 +1,40 @@ +using System; + +public class RepString +{ + static readonly string[] input = {"1001110011", "1110111011", "0010010010", + "1010101010", "1111111111", "0100101101", "0100100", "101", "11", + "00", "1", "0100101"}; + + public static void Main(string[] args) + { + foreach (string s in input) + Console.WriteLine($"{s} : {repString(s)}"); + } + + static string repString(string s) + { + int len = s.Length; + for (int part = len / 2; part > 0; part--) + { + int tail = len % part; + if (tail > 0 && !s.Substring(0, tail).Equals(s.Substring(len - tail))) + continue; + bool isRepeated = true; + for (int j = 0; j < len / part - 1; j++) + { + int a = j * part; + int b = (j + 1) * part; + int c = (j + 2) * part; + if (!s.Substring(a, part).Equals(s.Substring(b, part))) + { + isRepeated = false; + break; + } + } + if (isRepeated) + return s.Substring(0, part); + } + return "none"; + } +} diff --git a/Task/Rep-string/EasyLang/rep-string.easy b/Task/Rep-string/EasyLang/rep-string.easy new file mode 100644 index 0000000000..b3558d67a5 --- /dev/null +++ b/Task/Rep-string/EasyLang/rep-string.easy @@ -0,0 +1,28 @@ +func$ repstr s$ . + sl = len s$ div 2 + 1 + while sl > 1 + r$ = substr s$ sl 999 + if r$ = substr s$ 1 len r$ + return substr r$ 1 (sl - 1) + . + sl -= 1 + . + return "" +. +repeat + s$ = input + until s$ = "" + print s$ & " -> " & repstr s$ +. +input_data +1001110011 +1110111011 +0010010010 +1010101010 +1111111111 +0100101101 +0100100 +101 +11 +00 +1 diff --git a/Task/Rep-string/Refal/rep-string.refal b/Task/Rep-string/Refal/rep-string.refal new file mode 100644 index 0000000000..df61f4bcf9 --- /dev/null +++ b/Task/Rep-string/Refal/rep-string.refal @@ -0,0 +1,34 @@ +$ENTRY Go { + , ('1001110011') ('1110111011') ('0010010010') + ('1010101010') ('1111111111') ('0100101101') + ('0100100') ('101') ('11') ('00') ('1'): e.Tests + = ; +}; + +Each { + s.F = ; + s.F t.I e.R = ; +}; + +Show { + (e.S), : e.R = ' e.R>; +}; + +RepString { + () e.S = ; + (e.R) e.S, : e.S e.X = e.R; + (e.R s.C) e.S = ; + e.S, : s.L e.S, + e.S>: (e.F) e.X + = ; +}; + +Lengthen { + (e.A) e.B, : s.LA e.A, + : s.LB e.B, + : '-' + = ; + (e.A) e.B, : s.LB e.B, + : (e.FA) e.RA + = e.FA; +}; diff --git a/Task/Rep-string/Wren/rep-string.wren b/Task/Rep-string/Wren/rep-string.wren index e8e48e67f3..1ea47cbc30 100644 --- a/Task/Rep-string/Wren/rep-string.wren +++ b/Task/Rep-string/Wren/rep-string.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var repString = Fn.new { |s| var reps = [] diff --git a/Task/Repeat-a-string/Elena/repeat-a-string.elena b/Task/Repeat-a-string/Elena/repeat-a-string.elena index aaa8a24fed..30a3efb13e 100644 --- a/Task/Repeat-a-string/Elena/repeat-a-string.elena +++ b/Task/Repeat-a-string/Elena/repeat-a-string.elena @@ -4,5 +4,5 @@ import extensions'text; public program() { - var s := new Range(0, 5).selectBy:(x => "ha").summarize(new StringWriter()) + var s := new Range(0, 5).selectBy::(x => "ha").summarize(new StringWriter()) } diff --git a/Task/Repunit-primes/PARI-GP/repunit-primes.parigp b/Task/Repunit-primes/PARI-GP/repunit-primes.parigp new file mode 100644 index 0000000000..baf91799cc --- /dev/null +++ b/Task/Repunit-primes/PARI-GP/repunit-primes.parigp @@ -0,0 +1,18 @@ +default(parisizemax, "128M") +default(parisize, "64M"); + + +repunitprimeinbase(n, base) = { + repunit = sum(i=0, n-1, base^i); /* Construct the repunit */ + return(isprime(repunit)); /* Check if it's prime */ +} + +{ +for(b=2, 40, + print("Base ", b, ": "); + for(n=1, 2700, + if(repunitprimeinbase(n, b), print1(n, " ")) + ); + print(""); /* Print a newline */ +) +} diff --git a/Task/Repunit-primes/Wren/repunit-primes.wren b/Task/Repunit-primes/Wren/repunit-primes.wren index 28909b32d0..afcb6ef4a8 100644 --- a/Task/Repunit-primes/Wren/repunit-primes.wren +++ b/Task/Repunit-primes/Wren/repunit-primes.wren @@ -1,4 +1,4 @@ -/* repunit_primes.wren */ +/* Repunit_primes.wren */ import "./gmp" for Mpz import "./math" for Int diff --git a/Task/Retrieve-and-search-chat-history/Wren/retrieve-and-search-chat-history-1.wren b/Task/Retrieve-and-search-chat-history/Wren/retrieve-and-search-chat-history-1.wren index a17f369a30..1c00c5416b 100644 --- a/Task/Retrieve-and-search-chat-history/Wren/retrieve-and-search-chat-history-1.wren +++ b/Task/Retrieve-and-search-chat-history/Wren/retrieve-and-search-chat-history-1.wren @@ -1,4 +1,4 @@ -/* retrieve_and_search_chat_history.wren */ +/* Retrieve_and_search_chat_history.wren */ import "./date" for Date diff --git a/Task/Retrieve-and-search-chat-history/Wren/retrieve-and-search-chat-history-2.wren b/Task/Retrieve-and-search-chat-history/Wren/retrieve-and-search-chat-history-2.wren index 5d0de6c128..ba4cd3c80e 100644 --- a/Task/Retrieve-and-search-chat-history/Wren/retrieve-and-search-chat-history-2.wren +++ b/Task/Retrieve-and-search-chat-history/Wren/retrieve-and-search-chat-history-2.wren @@ -1,4 +1,4 @@ -/* gcc retrieve_and_search_chat_history.c -o retrieve_and_search_chat_history -lcurl -lwren -lm */ +/* gcc Retrieve_and_search_chat_history.c -o Retrieve_and_search_chat_history -lcurl -lwren -lm */ #include #include @@ -195,7 +195,7 @@ int main(int argc, char **argv) { config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "retrieve_and_search_chat_history.wren"; + const char* fileName = "Retrieve_and_search_chat_history.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Return-multiple-values/Elena/return-multiple-values.elena b/Task/Return-multiple-values/Elena/return-multiple-values-1.elena similarity index 100% rename from Task/Return-multiple-values/Elena/return-multiple-values.elena rename to Task/Return-multiple-values/Elena/return-multiple-values-1.elena diff --git a/Task/Return-multiple-values/Elena/return-multiple-values-2.elena b/Task/Return-multiple-values/Elena/return-multiple-values-2.elena new file mode 100644 index 0000000000..ab3052cd1e --- /dev/null +++ b/Task/Return-multiple-values/Elena/return-multiple-values-2.elena @@ -0,0 +1,21 @@ +import system'routines; +import extensions; + +extension op +{ + ::(int, int) MinMax() + { + var ordered := self.ascendant(); + + ^ (ordered.FirstMember, ordered.LastMember); + } +} + +public program() +{ + var values := new int[]{4, 51, 1, -3, 3, 6, 8, 26, 2, 4}; + + (int min, int max) := values.MinMax(); + + console.printLine("Min: ",min," Max: ",max) +} diff --git a/Task/Reverse-a-string/Commodore-BASIC/reverse-a-string.basic b/Task/Reverse-a-string/Commodore-BASIC/reverse-a-string.basic new file mode 100644 index 0000000000..1ad2aa1988 --- /dev/null +++ b/Task/Reverse-a-string/Commodore-BASIC/reverse-a-string.basic @@ -0,0 +1,8 @@ +100 INPUT "STRING";S$ +110 FOR I=1 TO INT(LEN(S$)/2) +120 : J=LEN(S$)+1-I +130 : T$=MID$(S$,I,1) +140 : MID$(S$,I,1) = MID$(S$,J,1) +150 : MID$(S$,J,1) = T$ +160 NEXT I +170 PRINT S$ diff --git a/Task/Reverse-a-string/Elm/reverse-a-string.elm b/Task/Reverse-a-string/Elm/reverse-a-string.elm index d069d2a121..c5cdd6eab0 100644 --- a/Task/Reverse-a-string/Elm/reverse-a-string.elm +++ b/Task/Reverse-a-string/Elm/reverse-a-string.elm @@ -1,39 +1,17 @@ --- The import on the next line provides the reverse string --- functionality satisfying the rosettacode.org task description. -import String exposing (reverse) +module Main exposing (main) --- The rest is fairly boilerplate code demonstrating --- interactively that the reverse function works. -import Html exposing (Html, Attribute, text, div, input) -import Html.Attributes exposing (placeholder, value, style) -import Html.Events exposing (on, targetValue) -import Html.App exposing (beginnerProgram) +import Html exposing (Html, text, div, p) +import Html.Attributes exposing (style) -main = beginnerProgram { model = "", view = view, update = update } -update newStr oldStr = newStr +change myText = + text ("reverse " ++ myText + ++ " = " ++ String.reverse myText) -view : String -> Html String -view forward = - div [] - ([ input - [ placeholder "Enter a string to be reversed." - , value forward - , on "input" targetValue - , myStyle - ] - [] - ] ++ - [ let backward = reverse forward - in div [ myStyle] [text backward] - ]) -myStyle : Attribute msg -myStyle = - style - [ ("width", "100%") - , ("height", "20px") - , ("padding", "5px 0 0 5px") - , ("font-size", "1em") - , ("text-align", "left") +main = + div [style "margin" "5%", style "font-size" "1.5em"] + [change "as⃝da" + , p [] [change "a⃝su-as⃝u"] + , p [] [change "Hello!"] ] diff --git a/Task/Reverse-a-string/Langur/reverse-a-string.langur b/Task/Reverse-a-string/Langur/reverse-a-string.langur index 294e64c6bc..43a9ef1478 100644 --- a/Task/Reverse-a-string/Langur/reverse-a-string.langur +++ b/Task/Reverse-a-string/Langur/reverse-a-string.langur @@ -1 +1 @@ -writeln cp2s reverse s2cp q(don't you know) +writeln reverse "don't you know" diff --git a/Task/Reverse-a-string/BASIC/reverse-a-string.basic b/Task/Reverse-a-string/QuickBASIC/reverse-a-string.basic similarity index 100% rename from Task/Reverse-a-string/BASIC/reverse-a-string.basic rename to Task/Reverse-a-string/QuickBASIC/reverse-a-string.basic diff --git a/Task/Reverse-a-string/Refal/reverse-a-string.refal b/Task/Reverse-a-string/Refal/reverse-a-string.refal new file mode 100644 index 0000000000..a88bd77ac5 --- /dev/null +++ b/Task/Reverse-a-string/Refal/reverse-a-string.refal @@ -0,0 +1,9 @@ +$ENTRY Go { + = >; +}; + +Reverse { + (e.X) = e.X; + (e.X) s.C e.Y = ; + e.X = ; +}; diff --git a/Task/Reverse-a-string/Seed7/reverse-a-string.seed7 b/Task/Reverse-a-string/Seed7/reverse-a-string-1.seed7 similarity index 72% rename from Task/Reverse-a-string/Seed7/reverse-a-string.seed7 rename to Task/Reverse-a-string/Seed7/reverse-a-string-1.seed7 index 28eb7de6c8..869d1450b5 100644 --- a/Task/Reverse-a-string/Seed7/reverse-a-string.seed7 +++ b/Task/Reverse-a-string/Seed7/reverse-a-string-1.seed7 @@ -1,6 +1,6 @@ $ include "seed7_05.s7i"; -const func string: reverse (in string: stri) is func +const func string: reverso(in string: stri) is func result var string: result is ""; local @@ -13,5 +13,5 @@ const func string: reverse (in string: stri) is func const proc: main is func begin - writeln(reverse("Was it a cat I saw")); + writeln(reverso("Was it a cat I saw")); end func; diff --git a/Task/Reverse-a-string/Seed7/reverse-a-string-2.seed7 b/Task/Reverse-a-string/Seed7/reverse-a-string-2.seed7 new file mode 100644 index 0000000000..07db4ec8e3 --- /dev/null +++ b/Task/Reverse-a-string/Seed7/reverse-a-string-2.seed7 @@ -0,0 +1,6 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + begin + writeln(reverse("Was it a cat I saw?")); + end func; diff --git a/Task/Reverse-a-string/Wren/reverse-a-string.wren b/Task/Reverse-a-string/Wren/reverse-a-string.wren index 27d0a99227..e55802c5ba 100644 --- a/Task/Reverse-a-string/Wren/reverse-a-string.wren +++ b/Task/Reverse-a-string/Wren/reverse-a-string.wren @@ -1,5 +1,5 @@ -import "/str" for Str -import "/upc" for Graphemes +import "./str" for Str +import "./upc" for Graphemes for (word in ["asdf", "josé", "møøse", "was it a car or a cat I saw", "😀🚂🦊"]) { System.print(Str.reverse(word)) diff --git a/Task/Reverse-words-in-a-string/EasyLang/reverse-words-in-a-string.easy b/Task/Reverse-words-in-a-string/EasyLang/reverse-words-in-a-string.easy new file mode 100644 index 0000000000..64ca664c1e --- /dev/null +++ b/Task/Reverse-words-in-a-string/EasyLang/reverse-words-in-a-string.easy @@ -0,0 +1,20 @@ +repeat + s$ = input + until error = 1 + s$[] = strsplit s$ " " + for i = len s$[] downto 1 + write s$[i] & " " + . + print "" +. +input_data +--------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert ----------------------- diff --git a/Task/Reverse-words-in-a-string/Elena/reverse-words-in-a-string.elena b/Task/Reverse-words-in-a-string/Elena/reverse-words-in-a-string.elena index 66e5206139..0e0ba1284c 100644 --- a/Task/Reverse-words-in-a-string/Elena/reverse-words-in-a-string.elena +++ b/Task/Reverse-words-in-a-string/Elena/reverse-words-in-a-string.elena @@ -14,9 +14,9 @@ public program() "", "Frost Robert -----------------------"}; - text.forEach:(line) + text.forEach::(line) { - line.splitBy:" ".sequenceReverse().forEach:(word) + line.splitBy(" ").sequenceReverse().forEach::(word) { console.print(word," ") }; diff --git a/Task/Rhonda-numbers/FreeBASIC/rhonda-numbers.basic b/Task/Rhonda-numbers/FreeBASIC/rhonda-numbers.basic new file mode 100644 index 0000000000..a5c5aaea37 --- /dev/null +++ b/Task/Rhonda-numbers/FreeBASIC/rhonda-numbers.basic @@ -0,0 +1,77 @@ +'#include "isprime.bas" + +Function FactorSum(n As Uinteger) As Uinteger + Dim As Uinteger result = 0 + Dim As Uinteger v = Abs(n) + While v > 1 And v Mod 2 = 0 + result += 2 + v \= 2 + Wend + For f As Uinteger = 3 To v Step 2 + While v > 1 And v Mod f = 0 + result += f + v \= f + Wend + Next f + Return result +End Function + +Function DigitProduct(n As Uinteger, base_ As Uinteger) As Uinteger + If n = 0 Then Return 0 + Dim As Uinteger result = 1 + Dim As Uinteger v = Abs(n) + While v > 0 + result *= v Mod base_ + v \= base_ + Wend + Return result +End Function + +Function isRhonda(n As Uinteger, base_ As Uinteger) As Uinteger + Return base_ * FactorSum(n) = DigitProduct(n, base_) +End Function + +Function ToBaseString(n As Uinteger, base_ As Uinteger) As String + If n = 0 Then Return "0" + Dim As Uinteger under10 = Asc("0") + Dim As Uinteger over9 = Asc("a") - 10 + Dim As String result = "" + Dim As Uinteger v = Abs(n) + While v > 0 + Dim As Uinteger d = v Mod base_ + result = Chr(d + Iif(d < 10, under10, over9)) + result + v \= base_ + Wend + Return result +End Function + +Dim As Uinteger maxRhonda = 10, maxBase = 16 +For base_ As Uinteger = 2 To maxBase + If Not isPrime(base_) Then + Print "The first "; maxRhonda; " Rhonda numbers in base "; base_; ":" + Dim As Uinteger rCount = 0 + Dim As Uinteger rhonda(1 To maxRhonda) + Dim As Uinteger n = 1 + While rCount < maxRhonda + If isRhonda(n, base_) Then + rCount += 1 + rhonda(rCount) = n + End If + n += 1 + Wend + Print " in base 10: "; + For i As Uinteger = 1 To maxRhonda + Print " "; rhonda(i); + Next i + Print + If base_ <> 10 Then + Print Using " in base ##: "; base_; + For i As Uinteger = 1 To maxRhonda + Print " "; ToBaseString(rhonda(i), base_); + Next i + Print + End If + End If +Next base_ + +Sleep diff --git a/Task/Rhonda-numbers/PARI-GP/rhonda-numbers.parigp b/Task/Rhonda-numbers/PARI-GP/rhonda-numbers.parigp new file mode 100644 index 0000000000..d20cd94422 --- /dev/null +++ b/Task/Rhonda-numbers/PARI-GP/rhonda-numbers.parigp @@ -0,0 +1,38 @@ +isRhonda(n, b) = +{ + local(mydigits, product, mysum, factors, pairProduct); + + mydigits = digits(n, b); + product = vecprod(mydigits); + factors = factor(n); + mysum= 0; + for(i = 1, matsize(factors)[1], + pairProduct = factors[i, 1] * factors[i, 2]; + mysum += pairProduct; + ); + product == b * mysum; +} + +displayrhondas(low, high, nshow) = +{ + local(b, n, rhondas, count, basebRhondas); + for(b = low, high, + if(isprime(b), next); + n = 1; rhondas = []; + count = 0; + while(count < nshow, + if(isRhonda(n, b), + rhondas = concat(rhondas, n); + count++; + ); + n++; + ); + print("First " nshow " Rhondas in base " b ":"); + print("In base 10: " rhondas); + basebRhondas = vector(#rhondas, i, (digits(rhondas[i], b))); + print("In base " b ": " basebRhondas); + print("\n"); + ); +} + +displayrhondas(2, 16, 15); diff --git a/Task/Rock-paper-scissors/Wren/rock-paper-scissors.wren b/Task/Rock-paper-scissors/Wren/rock-paper-scissors.wren index 8ae3ff2c27..94d7188d9f 100644 --- a/Task/Rock-paper-scissors/Wren/rock-paper-scissors.wren +++ b/Task/Rock-paper-scissors/Wren/rock-paper-scissors.wren @@ -1,6 +1,6 @@ import "random" for Random -import "/str" for Str -import "/ioutil" for Input +import "./str" for Str +import "./ioutil" for Input var choices = "rpsq" var rand = Random.new() diff --git a/Task/Roman-numerals-Decode/Elena/roman-numerals-decode.elena b/Task/Roman-numerals-Decode/Elena/roman-numerals-decode.elena index 2f2748025e..3de6d82b6c 100644 --- a/Task/Roman-numerals-Decode/Elena/roman-numerals-decode.elena +++ b/Task/Roman-numerals-Decode/Elena/roman-numerals-decode.elena @@ -20,7 +20,7 @@ extension op : String var s := self.toUpper(); var total := 0; - for(int i := 0, i < s.Length, i += 1) + for(int i := 0; i < s.Length; i += 1) { var thisNumeral := RomanDictionary[s[i]] - minus; if (i >= s.Length - 1 || thisNumeral + minus >= RomanDictionary[s[i + 1]]) diff --git a/Task/Roman-numerals-Decode/Phix/roman-numerals-decode-1.phix b/Task/Roman-numerals-Decode/Phix/roman-numerals-decode-1.phix new file mode 100644 index 0000000000..23432d2cfb --- /dev/null +++ b/Task/Roman-numerals-Decode/Phix/roman-numerals-decode-1.phix @@ -0,0 +1,14 @@ +with javascript_semantics +function romanDec(string s) + integer res = 0, prev = 0 + for i=length(s) to 1 by -1 do + integer rdx = find(upper(s[i]),"IVXLCDM"), + rn = power(10,floor((rdx-1)/2)) + if even(rdx) then rn *= 5 end if + res += iff(rn - function romanDec(string s) - constant romans = "MDCLXVI", - decmls = {1000,500,100,50,10,5,1} - integer n, prev = 0, res = 0 - for i=length(s) to 1 by -1 do - n = decmls[find(s[i],romans)] - if n<prev then n = 0-n end if - res += n - prev = n - end for - -- return res - return {s,res} -- (for output) - end function - - ?apply({"MCMXC","MMVIII","MDCLXVI"},romanDec) - - function toRoman(integer v) - constant roman = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"}, - decml = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 } - string res = "" - integer val = v - for i=1 to length(roman) do - while val>=decml[i] do - res &= roman[i] - val -= decml[i] - end while - end for - -- return res - return {v,res} -- (for output) - end function - - ?apply({1990,2008,1666},toRoman) - - --(1) starting from n characters in and of m length; - --(2) starting from n characters in, up to the end of the string; - --(3) whole string minus last character; - --(4) starting from a known character within the string and of m length; - --(5) starting from a known substring within the string and of m length. +--(1) starting from n characters in and of m length; +--(2) starting from n characters in, up to the end of the string; +--(3) whole string minus last character; +--(4) starting from a known character within the string and of m length; +--(5) starting from a known substring within the string and of m length. - constant sentence = "the last thing the man said was the", - n = 10, m = 5 - integer k, l - l = n+m-1 - if l<=length(sentence) then - ?sentence[n..l] -- (1) - end if - if n<=length(sentence) then - ?sentence[n..-1] -- (2) or [n..$] - end if - if length(sentence)>0 then - ?sentence[1..-2] -- (3) or [1..$-1] - end if - k = find('m',sentence) - l = k+m-1 - if l<=length(sentence) then - ?sentence[k..l] -- (4) - end if - k = match("aid",sentence) - l = k+m-1 - if l<=length(sentence) then - ?sentence[k..l] -- (5) - end if - - ?sentence[n..n+m-1] - ?sentence[n..-1] - ?sentence[1..-2] - ?(sentence[find('m',sentence)..$])[1..m] - ?(sentence[match("aid",sentence)..$])[1..m] - temp. short name. */ + snU=translate(sn) /* uppercase version of temperature unit*/ + snU=translate(snU,'-eE',"_éÉ") /* translate some accented characters. */ + + If left(snU,7)=='DEGREES' Then /* is this a redundant "degrees" ? */ + snU=substr(snU,8) + If left(snU,6)=='DEGREE' Then /* " " " " "degree" ? */ + snU=substr(snU,7) + snU=strip(snU) /* elide all leading & trailing blanks */ + _= length(snU) /* obtain the length of the snU value */ + + If right(snU,1)=='S' & _>1 Then + snU=left(snU,_-1) /* remove any trailing plural(s) */ + + Select /* get scalename from abbrevuation */ + When abbrev('ALL' , snU, 3) Then sn= "ALL" + When abbrev('ABSOLUTE' , snU, 1) Then sn= "ABSOLUTE" + When abbrev('AMONTON' , snU) Then sn= "AMONTON" + When abbrev('BARNDORF' , snU,2) |, + abbrev('BARNSDORF' , snU,2) Then sn= "BARNSDORF" + When abbrev('BEAUMIUR' , snU,3) |, + abbrev('BEAUMUIR' , snU,3) Then sn= "BEAUMUIR" + When abbrev('BENERT' , snU,3) |, + abbrev('BENART' , snU,3) Then sn= "BENART" + When abbrev('BRISSEN' , snU,3) |, + abbrev('BRISSON' , snU,3) Then sn= "BRISSEN" + When abbrev('BURGEN' , snU,3) |, + abbrev('BURGAN' , snU,3) |, + abbrev('BERGAN' , snU,3) |, + abbrev('BERGEN' , snU,3) Then sn= "BERGEN" + When abbrev('CENTIGRADE' , snU) |, + abbrev('CENTRIGRADE' , snU) |, /* 50% misspelled.*/ + abbrev('CETIGRADE' , snU) |, /* 50% misspelled.*/ + abbrev('CENTINGRADE' , snU) |, + abbrev('CENTESIMAL' , snU) |, + abbrev('CELCIU' , snU) |, /* 82% misspelled.*/ + abbrev('CELCIOU' , snU) |, /* 4% misspelled.*/ + abbrev('CELCUI' , snU) |, /* 4% misspelled.*/ + abbrev('CELSUI' , snU) |, /* 2% misspelled.*/ + abbrev('CELCEU' , snU) |, /* 2% misspelled.*/ + abbrev('CELCU' , snU) |, /* 2% misspelled.*/ + abbrev('CELISU' , snU) |, /* 1% misspelled.*/ + abbrev('CELSU' , snU) |, /* 1% misspelled.*/ + abbrev('HECTOGRADE' , snU) |, + abbrev('CELSIU' , snU) Then sn= "CELSIUS" + When abbrev('CIMANTO' , snU,2) |, + abbrev('CIMENTO' , snU,2) Then sn= "CIMENTO" + When abbrev('CRUQUIOU' , snU,2) |, + abbrev('CRUQUIO' , snU,2) |, + abbrev('CRUQUIU' , snU,2) Then sn= "CRUQUIU" + When abbrev('DALANCE' , snU,4) |, + abbrev('DALENCE' , snU,4) Then sn= "DALENCE" + When abbrev('DANELLE' , snU,3) |, + abbrev('DANEAL' , snU,3) |, + abbrev('DANIAL' , snU,3) |, + abbrev('DANIELE' , snU,3) |, + abbrev('DANNEL' , snU,3) |, + abbrev('DANYAL' , snU,3) |, + abbrev('DANYEL' , snU,3) |, + abbrev('DANIELL' , snU,3) Then sn= "DANIELL" + When abbrev('DALTON' , snU,3) Then sn= "DALTON" + When abbrev('DELAHIRE' , snU,7) |, + abbrev('LAHIRE' , snU,4) |, + abbrev('HIRE' , snU,2) |, + abbrev('DE-LA-HIRE' , snU,7) Then sn= "DE LA HIRE" + When abbrev('DELAVILLE' , snU,7) |, + abbrev('LAVILLE' , snU,3) |, + abbrev('VILLE' , snU,1) |, + abbrev('VILLA' , snU,1) |, + abbrev('DE-LA-VILLE' , snU,7) Then sn= "DE LA VILLE" + When abbrev('DELISLE' , snU,3) Then sn= "DELISLE" + When abbrev('DELISLE-OLD' , snU,8) |, + abbrev('OLDDELISLE' , snU,6) |, + abbrev('DELISLEOLD' , snU,8) Then sn= "DELISLE OLD" + When abbrev('DELUC' , snU,4) |, + abbrev('LUC' , snU,2) |, + abbrev('DE-LUC' , snU,5) Then sn= "DE LUC" + When abbrev('DELYON' , snU,4) |, + abbrev('LYON' , snU,2) |, + abbrev('DE-LYON' , snU,5) Then sn= "DE LYON" + When abbrev('DEREVILLA' , snU,3) |, + abbrev('DEREVILA' , snU,3) |, + abbrev('REVILLA' , snU,3) |, + abbrev('DE-REVILLA' , snU,4) |, + abbrev('DE-REVILLA' , snU,5) Then sn= "DE REVILLAS" + When abbrev('DEVILLENEUVE' , snU,3) |, + abbrev('DE-VILLENEUVE' , snU,4) Then sn= "DE VILLENEUVE" + When abbrev('DURHAM' , snU,3) |, + abbrev('DERHAM' , snU,4) Then sn= "DERHAM" + When abbrev('OLDDURHAM' , snU,5) |, + abbrev('OLDDERHAM' , snU,6) |, + abbrev('DERHAM-OLD' , snU,4) |, + abbrev('DERHAMOLD' , snU,4) Then sn= "DERHAM OLD" + When abbrev('DE-SUEDE' , snU,4) |, + abbrev('DESUEDE' , snU,4) Then sn= "DE SUEDE" + When abbrev('DU-CREST' , snU,2) |, + abbrev('DUCREST' , snU,2) Then sn= "DU CREST" + When abbrev('EDENBURGH' , snU,2) |, + abbrev('EDINBURGH' , snU,2) Then sn= "EDINBURGH" + When abbrev('EVOLT' , snU,2) |, + abbrev('ELECTRONVOLT' , snU,2) Then sn= "ELECTRON VOLTS" + When abbrev('FARENHEIT' , snU) |, /* 39% misspelled.*/ + abbrev('FARENHEIGHT' , snU) |, /* 15% misspelled.*/ + abbrev('FARENHITE' , snU) |, /* 6% misspelled.*/ + abbrev('FARENHIET' , snU) |, /* 3% misspelled.*/ + abbrev('FARHENHEIT' , snU) |, /* 3% misspelled.*/ + abbrev('FARINHEIGHT' , snU) |, /* 2% misspelled.*/ + abbrev('FARENHIGHT' , snU) |, /* 2% misspelled.*/ + abbrev('FAHRENHIET' , snU) |, /* 2% misspelled.*/ + abbrev('FERENHEIGHT' , snU) |, /* 2% misspelled.*/ + abbrev('FEHRENHEIT' , snU) |, /* 2% misspelled.*/ + abbrev('FERENHEIT' , snU) |, /* 2% misspelled.*/ + abbrev('FERINHEIGHT' , snU) |, /* 1% misspelled.*/ + abbrev('FARIENHEIT' , snU) |, /* 1% misspelled.*/ + abbrev('FARINHEIT' , snU) |, /* 1% misspelled.*/ + abbrev('FARANHITE' , snU) |, /* 1% misspelled.*/ + abbrev('FAHRENHEIT' , snU) Then sn= "FAHRENHEIT" + When abbrev('OLDFAHRENHEIT' , snU,4) |, + abbrev('FAHRENHEIT-OLD' , snU,13) |, + abbrev('FAHRENHEITOLD' , snU,13) Then sn= "FARHENHEIT OLD" + When abbrev('FLORENTINE-LARGE' , snU,12) |, + abbrev('LARGE-FLORENTINE' , snU,7) |, + abbrev('LARGEFLORENTINE' , snU,6) |, + abbrev('FLORENTINELARGE' , snU,12) Then sn= "FLORENTINE LARGE" + When abbrev('FLORENTINE-MAGNUM' , snU,2) |, + abbrev('MAGNUM-FLORENTINE' , snU,3) |, + abbrev('MAGNUMFLORENTINE' , snU,3) |, + abbrev('FLORENTINEMAGNUM' , snU,2) Then sn= "FLORENTINE MAGNUM" + When abbrev('FLORENTINE-SMALL' , snU,13) |, + abbrev('SMALL-FLORENTINE' , snU,7) |, + abbrev('SMALLFLORENTINE' , snU,6) |, + abbrev('FLORENTINESMALL' , snU,13) Then sn= "FLORENTINE SMALL" + When abbrev('FOULER' , snU,2) |, + abbrev('FOWLOR' , snU,2) |, + abbrev('FOWLER' , snU,2) Then sn= "FOWLER" + When abbrev('FRICK' , snU,2) Then sn= "FRICK" + When abbrev('GAS-MARK' , snU,2) |, + abbrev('GASMARK' , snU,2) Then sn= "GAS MARK" + When abbrev('GOUBERT' , snU,2) Then sn= "GOUBERT" + When abbrev('HAIL' , snU,3) |, + abbrev('HALE' , snU,3) Then sn= "HALES" + When abbrev('HANOW' , snU,3) Then sn= "HANOW" + When abbrev('HUCKSBEE' , snU,3) |, + abbrev('HAWKSBEE' , snU,3) |, + abbrev('HAUKSBEE' , snU,3) Then sn= "HAUKSBEE" + When abbrev('JACOBSHOLBORN' , snU,2) |, + abbrev('JACOBS-HOLBORN' , snU,2) Then sn= "JACOBS-HOLBORN" + When abbrev('KALVIN' , snU) |, /* 27% misspelled.*/ + abbrev('KERLIN' , snU) |, /* 18% misspelled.*/ + abbrev('KEVEN' , snU) |, /* 9% misspelled.*/ + abbrev('KELVIN' , snU) Then sn= "KELVIN" + When abbrev('LAYDEN' , snU) |, + abbrev('LEIDEN' , snU) Then sn= "LEIDEN" + When abbrev('NEUTON' , snU) |, /*100% misspelled.*/ + abbrev('NEWTON' , snU) Then sn= "NEWTON" + When abbrev('ORTEL' , snU) |, + abbrev('OERTEL' , snU) Then sn= "OERTEL" + When abbrev('PLACK' , snU) |, /*100% misspelled.*/ + abbrev('PLANC' , snU) |, /* misspelled.*/ + abbrev('PLANK' , snU) |, /* misspelled.*/ + abbrev('PLANCK' , snU) Then sn= "PLANCK" + When abbrev('RANKINE' , snU, 1) Then sn= "RANKINE" + When abbrev('REAUMUR' , snU, 2) Then sn= "REAUMUR" + When abbrev('RICKTER' , snU, 3) |, + abbrev('RICHTER' , snU, 3) Then sn= "RICHTER" + When abbrev('RINALDINI' , snU, 3) Then sn= "RINALDINI" + When abbrev('ROEMER' , snU, 3) |, + abbrev('ROMER' , snU, 3) Then sn= "ROMER" + When abbrev('ROSANTHAL' , snU, 3) |, + abbrev('ROSENTHAL' , snU, 3) Then sn= "ROSENTHAL" + When abbrev('RSOL' , snU, 2) |, + abbrev('RSL' , snU, 2) |, + abbrev('ROYALSOCIETYOFLONDON' , snU, 3) |, + abbrev('ROYAL-SOCIETY-OF-LONDON' , snU, 3) Then sn= "ROYAL SOCIETY" + When abbrev('SAGREDO' , snU, 3) Then sn= "SAGREDO" + When abbrev('ST.-PATRICE' , snU, 3) |, + abbrev('ST.PATRICE' , snU, 3) |, + abbrev('SAINTPATRICE' , snU, 3) |, + abbrev('SAINT-PATRICE' , snU, 3) Then sn= "SAINT-PATRICE" + When abbrev('STUFFE' , snU, 3) |, + abbrev('STUFE' , snU, 3) Then sn= "STUFE" + When abbrev('SULTZER' , snU, 2) |, + abbrev('SULZER' , snU, 2) Then sn= "SULZER" + When abbrev('WEDGEWOOD' , snU) |, + abbrev('WEDGWOOD' , snU) Then sn= "WEDGWOOD" + Otherwise + sn='***' sn '***' + End /*Select*/ +Return sn + +convert2Fahrenheit: /*convert N --? ºF temperatures. */ +/* [?] fifty-eight temperature scales.*/ +Parse Arg n sn +Select + When sn=='ABSOLUTE' Then F= n * 9/5 - 459.67 + When sn=='AMONTON' Then F= n * 8.37209 - 399.163 + When sn=='BARNSDORF' Then F= n * 6.85714 + 6.85714 + When sn=='BEAUMUIR' Then F= n * 2.22951 + 32 + When sn=='BENART' Then F= n * 1.43391 + 31.2831 + When sn=='BERGEN' Then F=(n + 23.8667) * 15/14 + When sn=='BRISSEN' Then F= n * 32/15 + 32 + When sn=='CELSIUS' Then F= n * 9/5 + 32 /* C -> Celsius.*/ + When sn=='CIMENTO' Then F= n * 2.70677 - 4.54135 + When sn=='CRUQUIUS' Then F= n * 0.409266 - 405.992 + When sn=='DALENCE' Then F= n * 2.7 + 59 + When sn=='DALTON' Then F=rxCalcexp(rxCalclog(373.15/273.15)*n/100)*9*273.15/5-459.67 +--When sn=='DALTON' Then F=273.15*rxCalcexp(273.15/273.15,n/100)*1.8-459.67 + When sn=='DANIELL' Then F= n * 7.27194 + 55.9994 + When sn=='DE LA HIRE' Then F=(n - 3) / 0.549057 + When sn=='DE LA VILLE' Then F=(n + 6.48011) / 0.985568 + When sn=='DELISLE' Then F=212 - n * 6/5 + When sn=='DELISLE OLD' Then F=212 - n * 1.58590197 + When sn=='DE LUC' Then F=(n + 14) * 16/7 + When sn=='DE LYON' Then F=(n + 17.5) * 64/35 + When sn=='DE REVILLAS' Then F=212 - n * 97/80 + When sn=='DERHAM' Then F= n / 0.38444386 - 188.578 + When sn=='DERHAM OLD' Then F= n * 3 + 4.5 + When sn=='DE SUEDE' Then F=(n + 17.6666) * 150/83 + When sn=='DE VILLENEUVE' Then F=(n + 23.7037) / 0.740741 + When sn=='DU CREST' Then F=(n + 37.9202) / 0.650656 + When sn=='EDINBURGH' Then F= n * 4.6546 - 6.40048 + When sn=='ELECTRON VOLTS' Then F= n * 20888.1 - 459.67 + When sn=='FAHRENHEIT' Then F= n + When sn=='FAHRENHEIT OLD' Then F= n * 20/11 - 89.2727 + When sn=='FLORENTINE LARGE' Then F=(n + 7.42857) / 0.857143 + When sn=='FLORENTINE MAGNUM' Then F=(n + 73.9736 ) / 1.50659 + When sn=='FLORENTINE SMALL' Then F=(n - 1.38571) / 0.378571 + When sn=='FOWLER' Then F= n * 0.640321 + 53.7709 + When sn=='FRICK' Then F= n * 200/251 + 58.5339 + When sn=='GASMARK' Then F= n * 25 + 250 + When sn=='GOUBERT' Then F= n * 2 + 32 + When sn=='HALES' Then F= n * 1.2 + 32 + When sn=='HANOW' Then F= n * 1.06668 - 10.6672 + When sn=='HAUKSBEE' Then F= n * 18/25 + 88.16 + When sn=='JACOBS-HOLBORN' Then F= n * 18/71 - 53.4366 + When sn=='K' Then F= n * 9/5 - 459.67 + When sn=='KELVIN' Then F= n * 9/5 - 459.67 + When sn=='LEIDEN' Then F= n * 1.8 - 423.4 + When sn=='NEWTON' Then F= n * 60/11 + 32 + When sn=='OERTEL' Then F= n + n - 32 + When sn=='PLANCK' Then F= n * 1.416833e32* 9/5 - 459.67 + When sn=='RANKINE' Then F= n - 459.67 /* R -> Rankine.*/ + When sn=='REAUMUR' Then F= n * 9/4 + 32 + When sn=='RICHTER' Then F= n * 160/73 - 7.45205 + When sn=='RINALDINI' Then F= n * 15 + 32 + When sn=='ROMER' Then F=(n - 7.5) * 27/4+ 32 + When sn=='ROSENTHAL' Then F= n * 45/86 - 453.581 + When sn=='ROYAL SOCIETY' Then F=(n -122.82) * -50/69 + When sn=='SAGREDO' Then F= n * 0.3798 - 5.98 + When sn=='SAINT-PATRICE' Then F= n * 2.62123 + 115.879 + When sn=='STUFE' Then F= n * 45 + 257 + When sn=='SULZER' Then F= n * 1.14595 + 33.2334 + When sn=='THERMOSTAT' Then F= n * 54 + 32 + When sn=='WEDGWOOD' Then F= n * 44.7429295 + 516.2 + Otherwise Call serr 'invalid temperature scale: ' + End /*Select*/ +Return F + +convert2specific: /*convert ºF --? xxx temperatures.*/ + +K=(F+459.67)*5/9 /*compute temperature in kelvin scale. */ +a=(1e||(-digits()%2)-digits()%20) /*minimum number for Dalton temperature*/ +eV=(F+459.67)/20888.1 /*compute the number of electron volts.*/ + +If ?('ABSOLUTE') Then Call line fn(k) "Absolute" +If ?('AMONTON') Then Call line fn((F+399.163) / 8.37209 ) "Amonton" +If ?('BARNSDORF') Then Call line fn( ( F - 6.85715) / 6.85715 ) "Barnsdorf" +If ?('BEAUMUIR') Then Call line fn( ( F - 32 ) / 2.22951 ) "Beaumuir" +If ?('BENART') Then Call line fn( ( F - 31.2831 ) / 1.43391 ) "Benart" +If ?('BERGEN') Then Call line fn( ( F * 14/15 ) - 23.8667 ) "Bergen" +If ?('BRISSON') Then Call line fn( ( F - 32 ) * 15/32 ) "Brisson" +If ?('CELSIUS') Then Call line fn( ( F - 32 ) * 5/9 ) "Celsius" +If ?('CIMENTO') Then Call line fn( ( F + 4.54135) / 2.70677 ) "Cimento" +If ?('CRUQUIUS') Then Call line fn( ( F + 405.992 ) / 0.409266 ) "Cruquius" +If ?('DALENCE') Then Call line fn( ( F - 59 ) / 2.7 ) "Dalence" +If ?('DALTON') Then Do + If K>a Then Call line fn(100*rxCalclog(k/273.15)/rxCalclog(373.15/273.15) ) "Dalton" + Else Call line right("-infinity ", 60) "Dalton" + End +If ?('DANIELL') Then Call line fn( ( F - 55.9994 ) / 7.27194 ) "Daniell" +If ?('DE LA HIRE') Then Call line fn( F * 0.549057 + 3 ) "De la Hire" +If ?('DE LA VILLE') Then Call line fn( F * 0.985568 - 6.48011 ) "De la Ville" +If ?('DELISLE') Then Call line fn( ( 212 - F ) * 5/6 ) "Delisle" +If ?('DELISLE OLD') Then Call line fn( ( 212 - F ) / 1.58590197 ) "Delisle OLD" +If ?('DE LUC') Then Call line fn( F * 7/16 - 14 ) "De Luc" +If ?('DE LYON') Then Call line fn( F * 35/64 - 17.5 ) "De Lyon" +If ?('DE REVILLAS') Then Call line fn( ( 212 - F ) * 80/97 ) "De Revillas" +If ?('DERHAM') Then Call line fn( F * 0.38444386 + 72.4978 ) "Derham" +If ?('DERHAM OLD') Then Call line fn( ( F - 4.5 ) / 3 ) "Derham OLD" +If ?('DE VILLENEUVE') Then Call line fn( F * 0.740741 - 23.7037 ) "De Villeneuve" +If ?('DE SUEDE') Then Call line fn( F * 83/150 - 17.6666 ) "De Suede" +If ?('DU CREST') Then Call line fn( F * 0.650656 - 37.9202 ) "Du Crest" +If ?('EDINBURGH') Then Call line fn( ( F + 6.40048) / 4.6546 ) "Edinburgh" +If ?('ELECTRON VOLTS') Then Call line fn( eV ) "electron volt"s(eV) +If ?('FAHRENHEIT') Then Call line fn( F ) "Fahrenheit" +If ?('FAHRENHEIT OLD') Then Call line fn( F * 20/11 - 89.2727 ) "Fahrenheit OLD" +If ?('FLORENTINE LARGE') Then Call line fn( F * 0.857143 - 7.42857 ) "Florentine large" +If ?('FLORENTINE MAGNUM') Then Call line fn( F * 1.50659 - 73.9736 ) "Florentine Magnum" +If ?('FLORENTINE SMALL') Then Call line fn( F * 0.378571 + 1.38571 ) "Florentine small" +If ?('FOWLER') Then Call line fn( ( F - 53.7709 ) / 0.640321 ) "Fowler" +If ?('FRICK') Then Call line fn( ( F - 58.5338 ) * 251/200 ) "Frick" +If ?('GAS MARK') Then Call line fn( ( F - 250 ) * 0.04 ) "gas mark" +If ?('GOUBERT') Then Call line fn( ( F + 32 ) * 0.5 ) "Goubert" +If ?('HALES') Then Call line fn( ( F - 32 ) / 1.2 ) "Hales" +If ?('HANOW') Then Call line fn( ( F + 10.6672 ) / 1.06668 ) "Hanow" +If ?('HAUKSBEE') Then Call line fn( ( F - 88.16 ) * 25/18 ) "Hauksbee" +If ?('JACOBS-HOLBORN') Then Call line fn( ( F + 53.4366 ) * 71/18 ) "Jacobs-Holborn" +If ?('KELVIN') Then Call line fn( k ) 'KELVIN' +If ?('LEIDEN') Then Call line fn( F / 1.8 + 235.222 ) "Leiden" +If ?('NEWTON') Then Call line fn( ( F - 32 ) * 11/60 ) "Newton" +If ?('OERTEL') Then Call line fn( ( F + 32 ) * 0.5 ) "Oertel" +If ?('PLANCK') Then Call line fn( ( F + 459.67 ) * 5/9 / 1.416833e32 ) "Planck" +If ?('RANKINE') Then Call line fn( F + 459.67 ) "Rankine" +If ?('REAUMUR') Then Call line fn( ( F - 32 ) * 4/9 ) "Reaumur" +If ?('RICHTER') Then Call line fn( ( F + 7.45205) * 73/160 ) "Richter" +If ?('RINALDINI') Then Call line fn( ( F - 32 ) / 15 ) "Rinaldini" +If ?('ROMER') Then Call line fn( ( F - 32 ) * 4/27 + 7.5 ) "Romer" +If ?('ROSENTHAL') Then Call line fn( ( F + 453.581 ) * 86/45 ) "Rosenthal" +If ?('ROYAL SOCIETY') Then Call line fn( F * -69/50 + 122.82 ) "Royal Society of London" +If ?('SAGREDO') Then Call line fn( ( F + 5.98 ) / 0.3798 ) "Segredo" +If ?('SAINT-PATRICE') Then Call line fn( ( F - 115.879 ) / 2.62123 ) "Saint-Patrice" +If ?('STUFE') Then Call line fn( ( F - 257 ) / 45 ) "Stufe" +If ?('SULZER') Then Call line fn( ( F - 33.2334 ) / 1.14595 ) "Sulzer" +If ?('THERMOSTAT') Then Call line fn( ( F - 32 ) / 54 ) "Thermostat" +If ?('WEDGWOOD') Then Call line fn( ( F - 516.2 ) / 44.7429295 ) "Wedgwood" +Return + +line: + If how='FUNCTION' & all=0 Then + Exit space(arg(1)) + Else + Say arg(1) + Return + +?: + Return (arg(1)=toscale | all) + +fn: Procedure Expose how result + showDig=8 /* only show 8 decimal digs. */ + number=commas(format(arg(1),,showDig)/1) /* format# 8 digits past . and add commas */ + p=pos('.',number) /* find position of the decimal point. */ + /* [?] align integers with FP numbers. */ + If p==0 Then /* no decimal point .*/ + number=number||left('',5+showDig+1) + Else /* ddd.ddd */ + number=number||left('',5+showDig-length(number)+p) + Return right(number,max(25,length(number)))/* return the re-formatted argument (#).*/ + +commas: Procedure +Parse Arg u +a=pos('.',u'.') +e=1 +If left(u,1)='-' Then e=2 +Do j=a-4 To e by -3 + u=insert(',',u,j) + End +Return u + +s: + If arg(1)==1 Then Return arg(3) + Return word(arg(2)'s',1) /*pluralizer.*/ + +serr: + If how='FUNCTION' Then + Exit arg(1) + Else + Say arg(1) + Exit 13 + +help: + Say 'use as command:' + Say 'rexx tcw fromtemp [fromscale] [TO toscale | all],...' + Say 'or as function' + Say 'tcw(fromtemp [fromscale] [TO toscale])' + Exit +::Requires rxmath library diff --git a/Task/Temperature-conversion/REXX/temperature-conversion.rexx b/Task/Temperature-conversion/REXX/temperature-conversion.rexx index 6955769d37..ec2d96f93c 100644 --- a/Task/Temperature-conversion/REXX/temperature-conversion.rexx +++ b/Task/Temperature-conversion/REXX/temperature-conversion.rexx @@ -21,7 +21,7 @@ parse arg tList /*get the specified temperature if \datatype(n, 'N') then call serr 'illegal number:' n if \all then do /*is there is a TO ααα scale? */ call name ! /*process the TO abbreviation. */ - != s n /*assign the full name to ! */ + != sn /*assign the full name to ! */ end /*!: now contains temperature full name*/ call name u /*allow alternate scale (miss)spellings*/ diff --git a/Task/Temperature-conversion/Wren/temperature-conversion.wren b/Task/Temperature-conversion/Wren/temperature-conversion.wren index f0c9306f8b..47432346b5 100644 --- a/Task/Temperature-conversion/Wren/temperature-conversion.wren +++ b/Task/Temperature-conversion/Wren/temperature-conversion.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var tempConv = Fn.new { |k| var c = k - 273.15 diff --git a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-1.wren b/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-1.wren index e153cd8d7b..29e4020676 100644 --- a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-1.wren +++ b/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-1.wren @@ -1,4 +1,4 @@ -/* terminal_control_dimensions.wren */ +/* Terminal_control_Dimensions.wren */ class C { foreign static terminalWidth diff --git a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-2.wren b/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-2.wren index fc9915e230..39adb409c6 100644 --- a/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-2.wren +++ b/Task/Terminal-control-Dimensions/Wren/terminal-control-dimensions-2.wren @@ -1,3 +1,5 @@ +/* gcc Terminal_control_Dimensions.c -o Terminal_control_Dimensions -lwren -lm */ + #include #include #include @@ -73,7 +75,7 @@ int main() { config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "terminal_control_dimensions.wren"; + const char* fileName = "Terminal_control_Dimensions.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Terminal-control-Positional-read/Wren/terminal-control-positional-read-1.wren b/Task/Terminal-control-Positional-read/Wren/terminal-control-positional-read-1.wren index 2ec4ee37b9..509dcca5ab 100644 --- a/Task/Terminal-control-Positional-read/Wren/terminal-control-positional-read-1.wren +++ b/Task/Terminal-control-Positional-read/Wren/terminal-control-positional-read-1.wren @@ -1,4 +1,4 @@ -/* terminal_control_positional_read.wren */ +/* Terminal_control_Positional_read.wren */ import "random" for Random diff --git a/Task/Terminal-control-Positional-read/Wren/terminal-control-positional-read-2.wren b/Task/Terminal-control-Positional-read/Wren/terminal-control-positional-read-2.wren index d21fc7a522..f38a425045 100644 --- a/Task/Terminal-control-Positional-read/Wren/terminal-control-positional-read-2.wren +++ b/Task/Terminal-control-Positional-read/Wren/terminal-control-positional-read-2.wren @@ -1,3 +1,5 @@ +/* gcc Terminal_control_Positional_read.c -o Terminal_control_Positional_read -lncurses -lwren -lm */ + #include #include #include @@ -125,7 +127,7 @@ int main(int argc, char **argv) { config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "terminal_control_positional_read.wren"; + const char* fileName = "Terminal_control_Positional_read.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-1.wren b/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-1.wren index 54773fe082..7c4cd972c3 100644 --- a/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-1.wren +++ b/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-1.wren @@ -1,4 +1,4 @@ -/* terminal_control_unicode_output.wren */ +/* Terminal_control_Unicode_output.wren */ class C { foreign static isUnicodeSupported diff --git a/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-2.wren b/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-2.wren index c710a55c81..6f00e2acd0 100644 --- a/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-2.wren +++ b/Task/Terminal-control-Unicode-output/Wren/terminal-control-unicode-output-2.wren @@ -1,3 +1,5 @@ +/* gcc Terminal_control_Unicode_output.c -o Terminal_control_Unicode_output -lwren -lm */ + #include #include #include @@ -71,7 +73,7 @@ int main() { config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "terminal_control_unicode_output.wren"; + const char* fileName = "Terminal_control_Unicode_output.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Ternary-logic/Bruijn/ternary-logic.bruijn b/Task/Ternary-logic/Bruijn/ternary-logic.bruijn new file mode 100644 index 0000000000..9ecf058743 --- /dev/null +++ b/Task/Ternary-logic/Bruijn/ternary-logic.bruijn @@ -0,0 +1,27 @@ +true [[[0]]] + +maybe [[[1]]] + +false [[[2]]] + +¬‣ [0 true maybe false] + +…⋀… [[1 (0 1 1 1) (0 0 0 1) (0 0 0 0)]] + +…⋁… [[1 (0 0 0 0) (0 1 0 0) (0 1 1 1)]] + +…⊃… [[1 (0 true 0 1) (0 true 1 1) (0 1 1 1)]] + +…≡… [[1 (0 true 0 1) (0 1 1 1) (0 0 0 0)]] + +# --- result samples --- + +:import std/List . + +main [[inp <> "=" <> !res ++ "\n"] <++> (cross3 ops trits trits)] + !‣ [0 "false" "maybe" "true"] + …<>… [[1 ++ " " ++ 0]] + inp 0 [[~1 <> (0 [[!1 <> (0 [[!1]])]])]] + res ^(^0) ^(~0) ^(~(~0)) + ops (…⋀… : "and") : ((…⋁… : "or") : ((…⊃… : "if") : {}(…≡… : "equiv"))) + trits true : (maybe : {}false) diff --git a/Task/Ternary-logic/EasyLang/ternary-logic.easy b/Task/Ternary-logic/EasyLang/ternary-logic.easy new file mode 100644 index 0000000000..69266a8cbc --- /dev/null +++ b/Task/Ternary-logic/EasyLang/ternary-logic.easy @@ -0,0 +1,42 @@ +sym$[] = [ "F" "?" "T" ] +arrbase sym$[] -1 +# +func tnot x . + return -x +. +func tand x y . + if x > y + return tand y x + . + return x +. +func tor x y . + if x < y + return tor y x + . + return x +. +func teqv x y . + return x * y +. +func timp x y . + if -y > x + return -y + . + return x +. +print " (AND) ( OR) (EQV) (IMP) (NOT)" +print " F ? T F ? T F ? T F ? T " +print " -------------------------------------------------" +for i = -1 to 1 + o$ = " " & sym$[i] & " | " + o$ &= sym$[tand -1 i] & " " & sym$[tand 0 i] & " " & sym$[tand 1 i] + o$ &= " " + o$ &= sym$[tor -1 i] & " " & sym$[tor 0 i] & " " & sym$[tor 1 i] + o$ &= " " + o$ &= sym$[timp -1 i] & " " & sym$[timp 0 i] & " " & sym$[timp 1 i] + o$ &= " " + o$ &= sym$[timp -1 i] & " " & sym$[timp 0 i] & " " & sym$[timp 1 i] + o$ &= " " & sym$[tnot i] + print o$ +. diff --git a/Task/Ternary-logic/Elena/ternary-logic.elena b/Task/Ternary-logic/Elena/ternary-logic.elena index a309c1e58a..bb5f37e75f 100644 --- a/Task/Ternary-logic/Elena/ternary-logic.elena +++ b/Task/Ternary-logic/Elena/ternary-logic.elena @@ -18,7 +18,7 @@ sealed class Trit Trit equivalent(b) { - var val2 := cast bool(b) \ back:nil; + var val2 := cast bool(b) \ back(nil); if (val2 != nil && _value != nil) { @@ -29,17 +29,17 @@ sealed class Trit } Trit Inverted - = _value.Inverted \ back:nilValue; + = _value.Inverted \ back(nilValue); Trit and(b) { if (nil == _value) { - ^ b.and:nil \ back:nilValue + ^ b.and(nil) \ back(nilValue) } else { - ^ _value.and(/*$lazy cast bool(*/b/*)*/) \ back:nilValue + ^ _value.and(b) \ back(nilValue) } } @@ -47,32 +47,32 @@ sealed class Trit { if (nil == _value) { - ^ b.or:nilValue \ back:nilValue + ^ b.or(nilValue) \ back(nilValue) } else { - ^ _value.or(/*$lazy cast bool(*/b/*)*/) \ back:nilValue + ^ _value.or(b) \ back(nilValue) } } Trit implies(b) = self.Inverted.or(b); - string toPrintable() = _value.toPrintable() \ back:"maybe"; + string toPrintable() = _value.toPrintable() \ back("maybe"); } public program() { List values := new Trit[]{true, nilValue, false}; - values.forEach:(left) + values.forEach::(left) { console.printLine("¬",left," = ", left.Inverted); - values.forEach:(right) + values.forEach::(right) { console.printLine(left, " & ", right, " = ", left && right); console.printLine(left, " | ", right, " = ", left || right); - console.printLine(left, " → ", right, " = ", left.implies:right); - console.printLine(left, " ≡ ", right, " = ", left.equivalent:right) + console.printLine(left, " → ", right, " = ", left.implies(right)); + console.printLine(left, " ≡ ", right, " = ", left.equivalent(right)) } } } diff --git a/Task/Ternary-logic/Langur/ternary-logic.langur b/Task/Ternary-logic/Langur/ternary-logic.langur index a9265e3307..6147ac7870 100644 --- a/Task/Ternary-logic/Langur/ternary-logic.langur +++ b/Task/Ternary-logic/Langur/ternary-logic.langur @@ -1,14 +1,14 @@ # borrowing null for "maybe" val .trSet = [false, null, true] -val .and = f given .a, .b { +val .and = f switch[and] .a, .b { case true, null: case null, true: case null: null default: .a and .b } -val .or = f given .a, .b { +val .or = f switch[and] .a, .b { case false, null: case null, false: case null: null diff --git a/Task/Test-a-function/Bruijn/test-a-function.bruijn b/Task/Test-a-function/Bruijn/test-a-function.bruijn new file mode 100644 index 0000000000..dc76eeba22 --- /dev/null +++ b/Task/Test-a-function/Bruijn/test-a-function.bruijn @@ -0,0 +1,6 @@ +:import std/String . + +main [<~>0 =? 0] + +:test (main "tacocat") ([[1]]) +:test (main "bruijn") ([[1]]) diff --git a/Task/Test-a-function/Wren/test-a-function.wren b/Task/Test-a-function/Wren/test-a-function.wren index 9ffd43721e..a8830cfd2b 100644 --- a/Task/Test-a-function/Wren/test-a-function.wren +++ b/Task/Test-a-function/Wren/test-a-function.wren @@ -1,4 +1,4 @@ -import "/module" for Expect, Suite, ConsoleReporter +import "./module" for Expect, Suite, ConsoleReporter var isPal = Fn.new { |word| word == ((word.count > 0) ? word[-1..0] : "") } diff --git a/Task/Test-integerness/EasyLang/test-integerness.easy b/Task/Test-integerness/EasyLang/test-integerness.easy new file mode 100644 index 0000000000..9b53110ed6 --- /dev/null +++ b/Task/Test-integerness/EasyLang/test-integerness.easy @@ -0,0 +1,16 @@ +func isint x . + if x mod 1 = 0 + return 1 + . +. +num[] = [ 25.000000 24.999999 25.0001 -2.1e120 -5e-2 0 / 0 1 / 0 ] +# +numfmt 10 0 +for n in num[] + write n & " -> " + if isint n = 1 + print "integer" + else + print "no integer" + . +. diff --git a/Task/Test-integerness/Wren/test-integerness.wren b/Task/Test-integerness/Wren/test-integerness.wren index d2b198697a..55eb75c5b7 100644 --- a/Task/Test-integerness/Wren/test-integerness.wren +++ b/Task/Test-integerness/Wren/test-integerness.wren @@ -1,7 +1,7 @@ -import "/big" for BigRat -import "/complex" for Complex -import "/rat" for Rat -import "/fmt" for Fmt +import "./big" for BigRat +import "./complex" for Complex +import "./rat" for Rat +import "./fmt" for Fmt var tests1 = [25.000000, 24.999999, 25.000100] var tests2 = ["-2.1e120"] diff --git a/Task/Text-processing-1/Wren/text-processing-1.wren b/Task/Text-processing-1/Wren/text-processing-1.wren index 3698073df1..3490d4cf8e 100644 --- a/Task/Text-processing-1/Wren/text-processing-1.wren +++ b/Task/Text-processing-1/Wren/text-processing-1.wren @@ -1,6 +1,6 @@ import "io" for File -import "/pattern" for Pattern -import "/fmt" for Fmt +import "./pattern" for Pattern +import "./fmt" for Fmt var p = Pattern.new("+1/s") var fileName = "readings.txt" diff --git a/Task/Text-processing-2/Wren/text-processing-2.wren b/Task/Text-processing-2/Wren/text-processing-2.wren index 9a934c5660..d99d954e2d 100644 --- a/Task/Text-processing-2/Wren/text-processing-2.wren +++ b/Task/Text-processing-2/Wren/text-processing-2.wren @@ -1,7 +1,7 @@ import "io" for File -import "/pattern" for Pattern -import "/fmt" for Fmt -import "/sort" for Sort +import "./pattern" for Pattern +import "./fmt" for Fmt +import "./sort" for Sort var p = Pattern.new("+1/s") var fileName = "readings.txt" diff --git a/Task/Textonyms/AWK/textonyms.awk b/Task/Textonyms/AWK/textonyms.awk new file mode 100644 index 0000000000..d06a7770d4 --- /dev/null +++ b/Task/Textonyms/AWK/textonyms.awk @@ -0,0 +1,160 @@ +#!/usr/bin/env -S gawk -E + +BEGIN { # user's configuration area + + KEYMAP="2 abc 3 def 4 ghi 5 jkl 6 mno 7 pqrs 8 tuv 9 wxyz" + FNAME="/usr/share/dict/american-english" # 0.5 MB; 102775 words; + + #KEYMAP="2 αβγά 3 δεζέ 4 ηθιήίϊΐ 5 κλμ 6 νξοό 7 πρσς 8 τυφύϋΰ 9 χψωώ" + #FNAME="/usr/share/dict/greek" # 19.5MB; 828808 words; + + # where generated data will be written, + # or comment out a line if you don’t need it. + EXPORT_TXN="/tmp/textonyms" + EXPORT_ALL="/tmp/phonewords" + EXPORT_BAD="/tmp/invalidwords" #also the line ‘BUFF_ERRW = BUFF_...’ +} +BEGIN { # main + delete ARGV; ARGC=1 # do not accept command line arguments + delete XEK # reserve id for use only as a hash table + delete TXN # reserve id ... + AZ="" # generated Alphabet + EE=0 # invalid word Counter + KK=0 # valid word Counter + TT=0 # textonym groups in the table TXN + BUFF_ERRW="" # invalid word buffer + TOTAL=1 # enum + COUNT=2 # enum + + STDERR="/dev/stderr" + OLD_RS=RS + OLD_FS=FS + processFile() + generateReport() + userQuery() +} +function processFile( ii,jj,nn,errW,ss,aKey,aGroup,qqq){ + $0=KEYMAP + AZ=" " + for (ii=1; ii<=NF; ii=ii+2) { + aKey=$ii; aGroup=$(ii+1) + nn=split(aGroup, qqq, //) + for (jj=1; jj<=nn; jj++) {ss=qqq[jj]; XEK[ss]=aKey; AZ = AZ ss " " } + } + AZ = AZ " " + ###################### + RS="^$" # + FS="[\n\t ]+" # + ###################### + if ((getline STDERR + exit 1 + } else printf "total words in the file ‘%s’: %s\n", FNAME,NF + + for (ii=1; ii<=NF; ii++) { + errW=0 + ss=tolower($ii) + nn=split(ss, qqq, //) + nmb="" + for (jj=1; jj<=nn; jj++) { + lchr=qqq[jj] + if (index(AZ," "lchr" ")>0) { nmb = nmb XEK[lchr] } + else { + EE++ + errW=1 + BUFF_ERRW = BUFF_ERRW $ii "\n" + break + } + } + if (errW) { continue } + T9=TXN[nmb][TOTAL] + if (index(T9" "," "ss" ")==0) { + TXN[nmb][TOTAL] = T9 " " ss + TXN[nmb][COUNT]++ + } + KK++ + } +} +function generateReport( elm){ + for (elm in TXN) { if (TXN[elm][COUNT]>1) { TT++ } } + printf "valid words: %9s\n", KK + printf "invalid words: %9s\n", EE + printf "table indices for valid words: %9s\n", length(TXN) + printf "textonym groups in the table: %9s\n", TT + exportData() + close(EXPORT_BAD); close(EXPORT_TXN); close(EXPORT_ALL) +} +function exportData( elm){ + if (EXPORT_BAD != "") print BUFF_ERRW >EXPORT_BAD + + if (EXPORT_TXN != "" && EXPORT_ALL != "") { + printf "%s\n", + "number-of-textonyms\tword's-length\tkeys\tlist-of-textonyms" >EXPORT_ALL + printf "%s\n", + "number-of-textonyms\tword's-length\tkeys\tlist-of-textonyms" >EXPORT_TXN + for (elm in TXN) { + printf "%s\t%s\t%s\t%s\n", + TXN[elm][COUNT], length(elm), elm, TXN[elm][TOTAL] >EXPORT_ALL + if (TXN[elm][COUNT]>1) { + printf "%s\t%s\t%s\t%s\n", + TXN[elm][COUNT], length(elm), elm, TXN[elm][TOTAL] >EXPORT_TXN + } + } + return ## return ## return ## return ## + } else if (EXPORT_ALL != "") { + printf "%s\n", + "number-of-textonyms\tword's-length\tkeys\tlist-of-textonyms" >EXPORT_ALL + for (elm in TXN) { + printf "%s\t%s\t%s\t%s\n", + TXN[elm][COUNT], length(elm), elm, TXN[elm][TOTAL] >EXPORT_ALL + } + } + else if (EXPORT_TXN != "") { + printf "%s\n", + "number-of-textonyms\tword's-length\tkeys\tlist-of-textonyms" >EXPORT_TXN + for (elm in TXN) { + if (TXN[elm][COUNT]>1) { + printf "%s\t%s\t%s\t%s\n", + TXN[elm][COUNT], length(elm), elm, TXN[elm][TOTAL] >EXPORT_TXN + } + } + } +} +function userQuery( userasks,ss,ss1,nn,key,words){ + printf "txn>> " + RS=OLD_RS + FS=OLD_FS + while ((getline ) > 0) { + userasks=$1 + if (NF==0){ printf "txn>> ", ""; continue } + else if (userasks ~ /^-e|--ex|--exit$/) { exit } + else if (userasks ~ /^[0-9]+$/) { + nn=TXN[userasks][COUNT]+0 + words=TXN[userasks][TOTAL] + if (nn == 0) { printf "%s -> %s\n", userasks,"no matching words" } + else { printf "%s -> (%s) %s\n", userasks,nn,words } + } + else { + ss=tolower(userasks) + if ((key=keySeq_orElse_zero(ss))>0) { + ss1=(index((TXN[key][TOTAL]" ") , " "ss" ")>0) ? + ", and the word is in" : ", but the word is not in" + printf "%s -> %s; the key is%s in the table%s\n", ss,key, + ((key in TXN) ?"":" not"),ss1 + } + else { + printf "%s -> not a valid word for the alphabet:\n%s\n", userasks,AZ + } + } + printf "txn>> " + } + printf "\n" +} +function keySeq_orElse_zero(aWord, qqq,lchr,nn,jj,buf){ + nn=split(aWord, qqq, //) + for (jj=1; jj<=nn; jj++) { + lchr=qqq[jj] + if (index(AZ," "lchr" ")>0) { buf = buf XEK[lchr] } else { return 0 } + } + return buf +} diff --git a/Task/Textonyms/AppleScript/textonyms-1.applescript b/Task/Textonyms/AppleScript/textonyms-1.applescript new file mode 100644 index 0000000000..d42ebf3a8f --- /dev/null +++ b/Task/Textonyms/AppleScript/textonyms-1.applescript @@ -0,0 +1,124 @@ +use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later. +-- https://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Straightforward +use sorter : script "Quicksort" +use scripting additions + +on textonyms(posixPath, query) + set digits to "23456789" + set keys to {"", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"} + set {mv, LF} to {missing value, linefeed} + -- Check input. + try + set reporting to (query's class is not text) + if (not reporting) then + repeat with chr in query + if (chr is not in digits) then error "Invalid digit input" + end repeat + set digitCount to (count query) + end if + script o + property |words| : (do shell script ("cat " & posixPath))'s paragraphs + property combos : mv + end script + on error errMsg + display alert "Textonyms handler: parameter error" message ¬ + errMsg as critical buttons {"Stop"} default button 1 + error number -128 + end try + + ignoring case + -- Lose obvious no-hope words. + set alphabet to join(keys's rest, "") + repeat with i from 1 to (count o's |words|) + set wrd to o's |words|'s item i + if ((reporting) or (wrd's length = digitCount)) then + repeat with chr in wrd + if (chr is not in alphabet) then + set o's |words|'s item i to mv + exit repeat + end if + end repeat + else + set o's |words|'s item i to mv + end if + end repeat + set o's |words| to o's |words|'s every text + set wordCount to (count o's |words|) + + -- Derive digit combinations from the rest. + set txt to join(o's |words|, LF) + repeat with d in digits + set d to d's contents + repeat with letter in keys's item d + set txt to replaceText(txt, letter's contents, d) + end repeat + end repeat + set o's combos to txt's paragraphs + end ignoring + + -- Return the appropriate result + considering case -- Case insensitivity not needed with digits. + if (reporting) then + tell sorter to sort(o's combos, 1, wordCount) + set {previousCombo, comboCount, textonymCount, counting} to ¬ + {"", wordCount, 0, true} + repeat with i from 1 to wordCount + set thisCombo to o's combos's item i + if (thisCombo = previousCombo) then + set comboCount to comboCount - 1 + if (counting) then + set textonymCount to textonymCount + 1 + set counting to false + end if + else + set previousCombo to thisCombo + set counting to true + end if + end repeat + set output to (wordCount as text) & " words in '" & ¬ + (do shell script ("basename " & posixPath)) & ¬ + "' can be represented by the digit key mapping." & ¬ + (LF & comboCount & " digit combinations are required to represent them.") & ¬ + (LF & textonymCount & " of the digit combinations represent Textonyms.") + else + set output to {} + repeat with i from 1 to wordCount + if (o's combos's item i = query) then set output's end to o's |words|'s item i + end repeat + if ((count output) = 1) then set output to {} + end if + end considering + + return output +end textonyms + +on join(lst, delim) + set astid to AppleScript's text item delimiters + set AppleScript's text item delimiters to delim + set txt to lst as text + set AppleScript's text item delimiters to astid + return txt +end join + +on replaceText(mainText, searchText, replacementText) + set astid to AppleScript's text item delimiters + set AppleScript's text item delimiters to searchText + set textItems to mainText's text items + set AppleScript's text item delimiters to replacementText + set mainText to textItems as text + set AppleScript's text item delimiters to astid + return mainText +end replaceText + +on task() + set posixPath to "~/Desktop/www.rosettacode.org/unixdict.txt" + set report to textonyms(posixPath, missing value) + set output to {report, "", "Examples:"} + repeat with digitCombo in {"729", "723353", "25287876746242"} + set foundWords to textonyms(posixPath, digitCombo's contents) + set output's end to digitCombo & " --> {" & join(foundWords, ", ") & "}" + end repeat + return join(output, linefeed) +end task + +task() diff --git a/Task/Textonyms/AppleScript/textonyms-2.applescript b/Task/Textonyms/AppleScript/textonyms-2.applescript new file mode 100644 index 0000000000..f08314130d --- /dev/null +++ b/Task/Textonyms/AppleScript/textonyms-2.applescript @@ -0,0 +1,8 @@ +"24978 words in 'unixdict.txt' can be represented by the digit key mapping. +22903 digit combinations are required to represent them. +1473 of the digit combinations represent Textonyms. + +Examples: +729 --> {paw, pax, pay, paz, raw, ray, saw, sax, say} +723353 --> {paddle, raffle, saddle} +25287876746242 --> {claustrophobia, claustrophobic}" diff --git a/Task/Textonyms/AppleScript/textonyms-3.applescript b/Task/Textonyms/AppleScript/textonyms-3.applescript new file mode 100644 index 0000000000..4051d9fc8a --- /dev/null +++ b/Task/Textonyms/AppleScript/textonyms-3.applescript @@ -0,0 +1,99 @@ +use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later +use framework "Foundation" +use scripting additions + +on textonyms(posixPath, query) + set digits to "23456789" + set keys to {"", "[abc]", "[def]", "[ghi]", "[jkl]", "[mno]", "[pqrs]", "[tuv]", "[wxyz]"} + set {mv, LF} to {missing value, linefeed} + -- Check input. + try + set reporting to (query's class is not text) + if (not reporting) then + repeat with chr in query + if (chr is not in digits) then error "Invalid digit input" + end repeat + set digitCount to (count query) + end if + set || to current application + set pathStr to (||'s NSString's stringWithString:(posixPath))'s ¬ + stringByExpandingTildeInPath() + set {txt, err} to ||'s NSMutableString's stringWithContentsOfFile:(pathStr) ¬ + usedEncoding:(mv) |error|:(reference) + if (err ≠ mv) then error (err's localizedDescription() as text) + on error errMsg + display alert "Textonyms handler: parameter error" message ¬ + errMsg as critical buttons {"Stop"} default button 1 + error number -128 + end try + + -- Lose obvious no-hope words. + set regex to ||'s NSRegularExpressionSearch + txt's replaceOccurrencesOfString:("\\R") withString:(LF) ¬ + options:(regex) range:({0, txt's |length|()}) + set |words| to txt's componentsSeparatedByString:(LF) + if ((reporting) or (digitCount > 9)) then + set predFormat to "(self MATCHES '(?i)[a-z]++')" + else + set predFormat to "(self MATCHES '(?i)[a-z]{" & digitCount & "}+')" + end if + set predicate to ||'s NSPredicate's predicateWithFormat:(predFormat) + set |words| to |words|'s filteredArrayUsingPredicate:(predicate) + set wordCount to |words|'s |count|() + + -- Derive digit combinations from the rest. + set txt to (|words|'s componentsJoinedByString:(LF))'s mutableCopy() + set range to {0, txt's |length|()} + repeat with d in digits + (txt's replaceOccurrencesOfString:("(?i)" & keys's item d) withString:(d) ¬ + options:(regex) range:(range)) + end repeat + set combos to txt's componentsSeparatedByString:(LF) + + -- Return the appropriate result. + if (reporting) then + set comboSet to ||'s NSSet's setWithArray:(combos) + set comboCount to comboSet's |count|() + set textonymSet to ||'s NSCountedSet's alloc()'s initWithArray:(combos) + textonymSet's minusSet:(comboSet) + set textonymCount to textonymSet's |count|() + set output to (wordCount as text) & " words in '" & ¬ + (pathStr's lastPathComponent()) & ¬ + "' can be represented by the digit key mapping." & ¬ + (LF & comboCount & " digit combinations are required to represent them.") & ¬ + (LF & textonymCount & " of the digit combinations represent Textonyms.") + else + set output to {} + set range to {0, wordCount} + set i to combos's indexOfObject:(query) inRange:(range) + repeat until (i > wordCount) + set output's end to (|words|'s objectAtIndex:(i)) as text + set range to {i + 1, wordCount - (i + 1)} + set i to combos's indexOfObject:(query) inRange:(range) + end repeat + if ((count output) = 1) then set output to {} + end if + + return output +end textonyms + +on join(lst, delim) + set astid to AppleScript's text item delimiters + set AppleScript's text item delimiters to delim + set txt to lst as text + set AppleScript's text item delimiters to astid + return txt +end join + +on task() + set posixPath to "~/Desktop/www.rosettacode.org/unixdict.txt" + set report to textonyms(posixPath, missing value) + set output to {report, "", "Examples:"} + repeat with digitCombo in {"729", "723353", "25287876746242"} + set foundWords to textonyms(posixPath, digitCombo's contents) + set output's end to digitCombo & " --> {" & join(foundWords, ", ") & "}" + end repeat + return join(output, linefeed) +end task + +task() diff --git a/Task/Textonyms/Wren/textonyms.wren b/Task/Textonyms/Wren/textonyms.wren index 53eec21550..31190af632 100644 --- a/Task/Textonyms/Wren/textonyms.wren +++ b/Task/Textonyms/Wren/textonyms.wren @@ -1,7 +1,7 @@ import "io" for File -import "/str" for Char, Str -import "/sort" for Sort -import "/fmt" for Fmt +import "./str" for Char, Str +import "./sort" for Sort +import "./fmt" for Fmt var wordList = "unixdict.txt" var DIGITS = "22233344455566677778889999" diff --git a/Task/The-Name-Game/Wren/the-name-game.wren b/Task/The-Name-Game/Wren/the-name-game.wren index 56fbbd1ea9..223ff87e29 100644 --- a/Task/The-Name-Game/Wren/the-name-game.wren +++ b/Task/The-Name-Game/Wren/the-name-game.wren @@ -1,4 +1,4 @@ -import "/str" for Str +import "./str" for Str var printVerse = Fn.new { |name| var x = Str.capitalize(Str.lower(name)) diff --git a/Task/The-Twelve-Days-of-Christmas/APL/the-twelve-days-of-christmas.apl b/Task/The-Twelve-Days-of-Christmas/APL/the-twelve-days-of-christmas.apl new file mode 100644 index 0000000000..6143cd2ef8 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/APL/the-twelve-days-of-christmas.apl @@ -0,0 +1,7 @@ +ord ← { ⍵ ⌷ 'first' 'second' 'third' 'fourth' 'fifth' 'sixth' 'seventh' 'eighth' 'ninth' 'tenth' 'eleventh' 'twelfth' } + +gift ← { ⍵ ⌷ 'A partridge in a pear tree.' 'Two turtle doves, and' 'Three French hens,' 'Four calling birds,' 'Five gold rings,' 'Six geese a-laying,' 'Seven swans a-swimming,' 'Eight maids a-milking,' 'Nine ladies dancing,' 'Ten lords a-leaping,' 'Eleven pipers piping,' 'Twelve drummers drumming,' } + +day ← { ⎕ ← (⎕ucs 10),'On the',(ord ⍵),'day of Christmas, my true love sent to me:' ⋄ { ⎕ ← gift ⍵ } ¨ ⌽⍳⍵ } + +day ¨ ⍳12 diff --git a/Task/The-Twelve-Days-of-Christmas/Commodore-BASIC/the-twelve-days-of-christmas.basic b/Task/The-Twelve-Days-of-Christmas/Commodore-BASIC/the-twelve-days-of-christmas.basic new file mode 100644 index 0000000000..6f1294bb5c --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Commodore-BASIC/the-twelve-days-of-christmas.basic @@ -0,0 +1,38 @@ +1 rem rosetta code +2 rem twelve days of christmas +5 print chr$(14):poke 53280,13:poke 53281,1 +10 dim a$(12),ex$(12):a=1 +15 for i=1 to 12:read a$(i),ex$(i):next i +20 for c=1 to 12 +25 print chr$(147):print chr$(30);" The Twelve Days of Christmas":print +30 print chr$(28);" On the ";a$(c);" day of Christmas":gosub 200 +35 print " my true love gave to me: ":print:gosub 200 +40 for bc=c to 1 step -1 +45 print tab(4); +50 if c=1 then print "A "; +55 if c>1 and bc=1 then print "And a "; +60 print ex$(bc); +65 if bc=1 or bc=5 then print "!":gosub 200:gosub 200:goto 75 +70 print "," +75 gosub 200 +80 next bc +85 rem pause for verse change +90 print:for t=1 to 500:next t +95 next c +100 end + +200 for t=1 to 750:next t:return:rem generic delay + +1000 rem lyrics +1010 data "first","partridge in a pear tree" +1020 data "second","Two turtle doves" +1030 data "third","Three french hens" +1040 data "fourth","Four calling birds" +1050 data "fifth","Five golden rings" +1060 data "sixth","Six geese a-laying" +1070 data "seventh","Seven swans a-swimming" +1080 data "eighth","Eight maids a-milking" +1090 data "ninth","Nine ladies dancing" +1100 data "tenth","Ten lords a-leaping" +1110 data "eleventh","Eleven pipers piping" +1120 data "twelfth","Twelve drummers drumming" diff --git a/Task/The-Twelve-Days-of-Christmas/Elena/the-twelve-days-of-christmas.elena b/Task/The-Twelve-Days-of-Christmas/Elena/the-twelve-days-of-christmas.elena index 73fa4563e5..7f8fee3da3 100644 --- a/Task/The-Twelve-Days-of-Christmas/Elena/the-twelve-days-of-christmas.elena +++ b/Task/The-Twelve-Days-of-Christmas/Elena/the-twelve-days-of-christmas.elena @@ -22,7 +22,7 @@ public program() "Twelve drummers drumming" }; - for(int i := 0, i < 12, i += 1) + for(int i := 0; i < 12; i += 1) { console.printLine("On the ", days[i], " day of Christmas, my true love gave to me"); @@ -32,7 +32,7 @@ public program() } else { - for(int j := i, j >= 0, j -= 1) + for(int j := i; j >= 0; j -= 1) { console.printLine(gifts[j]) } diff --git a/Task/The-Twelve-Days-of-Christmas/Fish/the-twelve-days-of-christmas.fish b/Task/The-Twelve-Days-of-Christmas/Fish/the-twelve-days-of-christmas.fish new file mode 100644 index 0000000000..2206bc2eed --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Fish/the-twelve-days-of-christmas.fish @@ -0,0 +1,59 @@ +> 0 7 . (0,0): Vector. Jumps to main, then used for sub returns +> 0 f 5 + . (0,1): Print a NUL-terminated string +> 6 6 * 9 + f 8 + . (0,2): Pop N, push Nth (e.g. 1 -> "first") +> 0 f 8 + . (0,3): Pop N, push gift countdown starting from N. +> 0 f 1 + . (0,4): Jump to line in range 16-30 + +main: +> 1 \ +/ a "On the " 0 < +\ "a" 4 0 p 0 1 . +> "b" 4 0 p : 0 2 . +> "c" 4 0 p 0 1 . +> \ +/ " day of Christmas, my true love sent to me:" a 0 / +> "f" 4 0 p 0 1 . +> "1" 6 4 p "4" 4 0 p : 0 3 . +> "2" 6 4 p 0 1 . +> 1 + : c ) ?\ / + ; + +> : ?\ ~ 0 0 . +\ o / > 0 0 . + ^ "first" 0 ~ \ +> \ > 1 - : ?\ / +/ "A partridge in a pear tree." a 0 & < / / ^ "second" 0 ~ \ +\ & 1 - : ?\ ~ 0 0 . \ 1 - : ?\ / + \ \ / / ^ "third" 0 ~ \ +/ "Two turtle doves and" a & / \ 1 - : ?\ / +\ & 1 - : ?\ ~ 0 0 . / / ^ "fourth" 0 ~ \ + \ \ \ 1 - : ?\ / +/ "Three French hens," a & / / / ^ "fifth" 0 ~ \ +\ & 1 - : ?\ ~ 0 0 . \ 1 - : ?\ / + \ \ / / ^ "sixth" 0 ~ \ +/ "Four calling birds," a & / \ 1 - : ?\ / +\ & 1 - : ?\ ~ 0 0 . / / ^ "seventh" 0 ~ \ + \ \ \ 1 - : ?\ / +/ "Five gold rings," a & / / / ^ "eighth" 0 ~ \ +\ & 1 - : ?\ ~ 0 0 . \ 1 - : ?\ / + \ \ / / ^ "ninth" 0 ~ \ +/ "Six geese a-laying," a & / \ 1 - : ?\ / +\ & 1 - : ?\ ~ 0 0 . / / ^ "tenth" 0 ~ \ + \ \ \ 1 - : ?\ / +/ "Seven swans a-swimming," a & / / / ^ "eleventh" 0 ~ \ +\ & 1 - : ?\ ~ 0 0 . \ 1 - : ?\ / + \ \ \ \ +/ "Eight maids a-milking," a & / ^ "twelfth" 0 ~ / +\ & 1 - : ?\ ~ 0 0 . + \ \ +/ "Nine ladies dancing," a & / +\ & 1 - : ?\ ~ 0 0 . + \ \ +/ "Ten lords a-leaping," a & / +\ & 1 - : ?\ ~ 0 0 . + \ \ +/ "Eleven pipers piping," a & / +\ & 1 - : ?\ ~ 0 0 . + \ \ +/ "Twelve drummers drumming," a & / +\ & ~ 0 0 . diff --git a/Task/The-Twelve-Days-of-Christmas/LOLCODE/the-twelve-days-of-christmas.lol b/Task/The-Twelve-Days-of-Christmas/LOLCODE/the-twelve-days-of-christmas.lol index ecca81d40f..700545b074 100644 --- a/Task/The-Twelve-Days-of-Christmas/LOLCODE/the-twelve-days-of-christmas.lol +++ b/Task/The-Twelve-Days-of-Christmas/LOLCODE/the-twelve-days-of-christmas.lol @@ -1,5 +1,5 @@ -CAN HAS STDIO? HAI 1.2 +CAN HAS STDIO? I HAS A Dayz ITZ A BUKKIT Dayz HAS A SRS 1 ITZ "first" diff --git a/Task/The-Twelve-Days-of-Christmas/Prog8/the-twelve-days-of-christmas.prog8 b/Task/The-Twelve-Days-of-Christmas/Prog8/the-twelve-days-of-christmas.prog8 new file mode 100644 index 0000000000..09b83e3478 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Prog8/the-twelve-days-of-christmas.prog8 @@ -0,0 +1,43 @@ +%zeropage basicsafe +%import textio + +main { + str[12] ordinals = [ "first", "second", "third", "fourth", + "fifth", "sixth", "seventh", "eighth", + "ninth", "tenth", "eleventh", "twelfth" ] + + str[12] gifts = [ "A partridge in a pear tree.", + "Two turtle doves and", + "Three French hens,", + "Four calling birds,", + "Five gold rings,", + "Six geese a-laying,", + "Seven swans a-swimming,", + "Eight maids a-milking,", + "Nine ladies dancing,", + "Ten lords a-leaping,", + "Eleven pipers piping,", + "Twelve drummers drumming," ] + + sub print_gifts(ubyte day) { + ubyte i + txt.print("On the ") + txt.print(ordinals[day]) + txt.print(" day of Christmas, my true love sent to me:") + txt.nl() + for i in day to 0 step -1 { + txt.print(gifts[i]) + txt.nl() + } + } + + sub start() { + ubyte day + + txt.lowercase() + for day in 0 to 11 { + txt.nl() + print_gifts(day) + } + } +} diff --git a/Task/The-sieve-of-Sundaram/EasyLang/the-sieve-of-sundaram.easy b/Task/The-sieve-of-Sundaram/EasyLang/the-sieve-of-sundaram.easy new file mode 100644 index 0000000000..f4759333aa --- /dev/null +++ b/Task/The-sieve-of-Sundaram/EasyLang/the-sieve-of-sundaram.easy @@ -0,0 +1,28 @@ +func log n . + return log10 n / log10 2.71828182845904523 +. +proc sundaram np . primes[] . + nmax = floor (np * (log np + log log np) - 0.9385) + 1 + k = (nmax - 2) / 2 + len marked[] k + for i to k + h = 2 * i + 2 * i * i + while h <= k + marked[h] = 1 + h += 2 * i + 1 + . + . + i = 1 + primes[] = [ ] + while np > 0 + if marked[i] = 0 + np -= 1 + primes[] &= 2 * i + 1 + . + i += 1 + . +. +sundaram 100 primes[] +print primes[] +sundaram 1000000 primes[] +print primes[-1] diff --git a/Task/The-sieve-of-Sundaram/FreeBASIC/the-sieve-of-sundaram.basic b/Task/The-sieve-of-Sundaram/FreeBASIC/the-sieve-of-sundaram.basic new file mode 100644 index 0000000000..d1787777fc --- /dev/null +++ b/Task/The-sieve-of-Sundaram/FreeBASIC/the-sieve-of-sundaram.basic @@ -0,0 +1,36 @@ +Function sieve_of_Sundaram(n As Uinteger) As Uinteger Ptr + If n < 3 Then Return 0 + Dim As Uinteger r = Cint(Sqr(n)) + Dim As Uinteger k = Cint((n - 3) / 2) + 1 + Dim As Uinteger l = Cint((r - 3) / 2) + 1 + Dim As Uinteger Ptr primes = Callocate(k, Sizeof(Uinteger)) + Dim As Boolean Ptr marked = Callocate(k, Sizeof(Boolean)) + For i As Uinteger = 1 To l + Dim As Uinteger p = 2 * i + 1 + Dim As Uinteger s = Cint((p * p - 1) / 2) + For j As Uinteger = s To k Step p + marked[j] = True + Next j + Next i + Dim As Uinteger count = 0 + For i As Uinteger = 1 To k + If Not marked[i] Then + primes[count] = 2 * i + 1 + count += 1 + End If + Next i + Return primes +End Function + +Const limit As Uinteger = 16e6 +Dim As Uinteger Ptr s = sieve_of_Sundaram(limit) +Print "First 100 odd primes generated by the Sieve of Sundaram:" +For i As Uinteger = 0 To 99 + Print Using "#####"; s[i]; + If (i + 1) Mod 10 = 0 Then Print +Next i +Print !"\nSundaram primes start with 3." +Print !"\nThe 100th Sundaram prime is: "; s[99] +Print !"\nThe 1000000th Sundaram prime is: "; s[999999] + +Sleep diff --git a/Task/The-sieve-of-Sundaram/Wren/the-sieve-of-sundaram.wren b/Task/The-sieve-of-Sundaram/Wren/the-sieve-of-sundaram.wren index ca716ba292..6dfc857aa7 100644 --- a/Task/The-sieve-of-Sundaram/Wren/the-sieve-of-sundaram.wren +++ b/Task/The-sieve-of-Sundaram/Wren/the-sieve-of-sundaram.wren @@ -1,5 +1,4 @@ -import "/fmt" for Fmt -import "/seq" for Lst +import "./fmt" for Fmt var sos = Fn.new { |n| if (n < 3) return [] @@ -54,7 +53,7 @@ var primes = sos.call(limit) var elapsed = ((System.clock - start) * 1000).round Fmt.print("Using the Sieve of Sundaram generated primes up to $,d in $,d ms.\n", limit, elapsed) System.print("First 100 odd primes generated by the Sieve of Sundaram:") -for (chunk in Lst.chunks(primes[0..99], 10)) Fmt.print("$3d", chunk) +Fmt.tprint("$3d", primes[0..99], 10) Fmt.print("\nThe $,d Sundaram prime is $,d", 1e6, primes[1e6-1]) start = System.clock diff --git a/Task/Thieles-interpolation-formula/Wren/thieles-interpolation-formula.wren b/Task/Thieles-interpolation-formula/Wren/thieles-interpolation-formula.wren index e9f34bc1ff..702858befa 100644 --- a/Task/Thieles-interpolation-formula/Wren/thieles-interpolation-formula.wren +++ b/Task/Thieles-interpolation-formula/Wren/thieles-interpolation-formula.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var N = 32 var N2 = N * (N - 1) / 2 diff --git a/Task/Thue-Morse/EasyLang/thue-morse.easy b/Task/Thue-Morse/EasyLang/thue-morse.easy new file mode 100644 index 0000000000..03952a890a --- /dev/null +++ b/Task/Thue-Morse/EasyLang/thue-morse.easy @@ -0,0 +1,16 @@ +func$ tmorse s$ . + for i to len s$ + if substr s$ i 1 = "1" + k$ &= "0" + else + k$ &= "1" + . + . + return s$ & k$ +. +tm$ = "0" +print tm$ +for j to 7 + tm$ = tmorse tm$ + print tm$ +. diff --git a/Task/Thue-Morse/Elena/thue-morse.elena b/Task/Thue-Morse/Elena/thue-morse.elena index d640a5aa5d..2c27a7d6b7 100644 --- a/Task/Thue-Morse/Elena/thue-morse.elena +++ b/Task/Thue-Morse/Elena/thue-morse.elena @@ -5,7 +5,7 @@ sequence(int steps) { var sb1 := TextBuilder.load("0"); var sb2 := TextBuilder.load("1"); - for(int i := 0, i < steps, i += 1) + for(int i := 0; i < steps; i += 1) { var tmp := sb1.Value; sb1.write(sb2); diff --git a/Task/Thue-Morse/MATLAB/thue-morse.m b/Task/Thue-Morse/MATLAB/thue-morse.m new file mode 100644 index 0000000000..7d43395f0e --- /dev/null +++ b/Task/Thue-Morse/MATLAB/thue-morse.m @@ -0,0 +1,11 @@ +tmSequence = thue_morse_digits(20); +disp(tmSequence); + +function tmSequence = thue_morse_digits(n) + tmSequence = zeros(1, n); + for i = 0:(n-1) + binStr = dec2bin(i); + numOnes = sum(binStr == '1'); + tmSequence(i+1) = mod(numOnes, 2); + end +end diff --git a/Task/Thue-Morse/Refal/thue-morse.refal b/Task/Thue-Morse/Refal/thue-morse.refal new file mode 100644 index 0000000000..c9d7344c98 --- /dev/null +++ b/Task/Thue-Morse/Refal/thue-morse.refal @@ -0,0 +1,19 @@ +$ENTRY Go { + = > +}; + +ThueMorse { + 0 e.X = e.X; + s.N e.X = >; +}; + +ThueMorseStep { + = '0'; + e.X = e.X ; +}; + +Invert { + = ; + '0' e.X = '1' ; + '1' e.X = '0' ; +}; diff --git a/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy b/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy index fffa6c4109..222a3071a8 100644 --- a/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy +++ b/Task/Tic-tac-toe/EasyLang/tic-tac-toe.easy @@ -82,7 +82,7 @@ proc minmax player alpha beta . rval rmov . . else rval = alpha - start = random 9 + start = randint 9 mov = start repeat if f[mov] = 0 diff --git a/Task/Tic-tac-toe/Wren/tic-tac-toe.wren b/Task/Tic-tac-toe/Wren/tic-tac-toe.wren index 6721773a01..0fa39c9f87 100644 --- a/Task/Tic-tac-toe/Wren/tic-tac-toe.wren +++ b/Task/Tic-tac-toe/Wren/tic-tac-toe.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/ioutil" for Input +import "./ioutil" for Input var r = Random.new() var b = List.filled(3, null) diff --git a/Task/Time-a-function/Elena/time-a-function.elena b/Task/Time-a-function/Elena/time-a-function.elena index c1f8618815..f07ac6deb3 100644 --- a/Task/Time-a-function/Elena/time-a-function.elena +++ b/Task/Time-a-function/Elena/time-a-function.elena @@ -8,7 +8,7 @@ someProcess() { threadControl.sleep(1000); - new Range(0,10000).filterBy:(x => x.mod:2 == 0).summarize(); + new Range(0,10000).filterBy::(x => x.mod(2) == 0).summarize(); } public program() diff --git a/Task/Tokenize-a-string-with-escaping/Elena/tokenize-a-string-with-escaping.elena b/Task/Tokenize-a-string-with-escaping/Elena/tokenize-a-string-with-escaping.elena index a5c936370e..94d2914440 100644 --- a/Task/Tokenize-a-string-with-escaping/Elena/tokenize-a-string-with-escaping.elena +++ b/Task/Tokenize-a-string-with-escaping/Elena/tokenize-a-string-with-escaping.elena @@ -12,11 +12,11 @@ extension op : String auto list := new ArrayList(); bool escaping := false; - self.forEach:(ch) + self.forEach::(ch) { if (escaping) { - buffer.write:ch; + buffer.write(ch); escaping := false } else if (ch == escape) @@ -30,7 +30,7 @@ extension op : String } else { - buffer.write:ch + buffer.write(ch) } }; @@ -42,5 +42,5 @@ const string testcase = "one^|uno||three^^^^|four^^^|^cuatro|"; public program() { - testcase.tokenize("|", "^").forEach:printingLn + testcase.tokenize("|", "^").forEach(printingLn) } diff --git a/Task/Tokenize-a-string/Elena/tokenize-a-string.elena b/Task/Tokenize-a-string/Elena/tokenize-a-string.elena index 90144d3c5d..38a1ce5c50 100644 --- a/Task/Tokenize-a-string/Elena/tokenize-a-string.elena +++ b/Task/Tokenize-a-string/Elena/tokenize-a-string.elena @@ -3,9 +3,9 @@ import extensions; public program() { - var string := "Hello,How,Are,You,Today"; + auto string := "Hello,How,Are,You,Today"; - string.splitBy:",".forEach:(s) + string.splitBy(",").forEach::(s) { console.print(s,".") } diff --git a/Task/Tonelli-Shanks-algorithm/Wren/tonelli-shanks-algorithm.wren b/Task/Tonelli-Shanks-algorithm/Wren/tonelli-shanks-algorithm.wren index 69ccb1d3bf..4ae18a7c69 100644 --- a/Task/Tonelli-Shanks-algorithm/Wren/tonelli-shanks-algorithm.wren +++ b/Task/Tonelli-Shanks-algorithm/Wren/tonelli-shanks-algorithm.wren @@ -1,5 +1,5 @@ -import "/dynamic" for Tuple -import "/big" for BigInt +import "./dynamic" for Tuple +import "./big" for BigInt var Solution = Tuple.create("Solution", ["root1", "root2", "exists"]) diff --git a/Task/Top-rank-per-group/Elena/top-rank-per-group.elena b/Task/Top-rank-per-group/Elena/top-rank-per-group.elena index 197f080a9f..6ca23c9ef6 100644 --- a/Task/Top-rank-per-group/Elena/top-rank-per-group.elena +++ b/Task/Top-rank-per-group/Elena/top-rank-per-group.elena @@ -6,9 +6,9 @@ import extensions'text; class Employee { - string Name : prop; - string ID : prop; - int Salary : prop; + string Name : prop; + string ID : prop; + int Salary : prop; string Department : prop; string toPrintable() @@ -16,19 +16,19 @@ class Employee .writePaddingRight(Name, 25) .writePaddingRight(ID, 12) .writePaddingRight(Salary.toPrintable(), 12) - .write:Department; + .write(Department); } extension reportOp { topNPerDepartment(n) - = self.groupBy:(x => x.Department ).selectBy:(x) + = self.groupBy::(x => x.Department ).selectBy::(x) { ^ new { Department = x.Key; Employees - = x.orderBy:(f,l => f.Salary > l.Salary ).top(n).summarize(new ArrayList()); + = x.orderBy::(f,l => f.Salary > l.Salary ).top(n).summarize(new ArrayList()); } }; } @@ -52,13 +52,13 @@ public program() new Employee{ this Name := "Timothy Grove"; this ID := "E16398"; this Salary:=29900; this Department:="D190";} }; - employees.topNPerDepartment:2.forEach:(info) + employees.topNPerDepartment(2).forEach::(info) { console.printLine("Department: ",info.Department); - info.Employees.forEach:printingLn; + info.Employees.forEach(printingLn); - console.writeLine:"---------------------------------------------" + console.writeLine("---------------------------------------------") }; console.readChar() diff --git a/Task/Top-rank-per-group/Wren/top-rank-per-group.wren b/Task/Top-rank-per-group/Wren/top-rank-per-group.wren index 41a13157cb..cff900293b 100644 --- a/Task/Top-rank-per-group/Wren/top-rank-per-group.wren +++ b/Task/Top-rank-per-group/Wren/top-rank-per-group.wren @@ -1,7 +1,7 @@ -import "/dynamic" for Tuple -import "/sort" for Sort, Cmp -import "/seq" for Lst -import "/fmt" for Fmt +import "./dynamic" for Tuple +import "./sort" for Sort, Cmp +import "./seq" for Lst +import "./fmt" for Fmt var Employee = Tuple.create("Employee", ["name", "id", "salary", "dept"]) diff --git a/Task/Topswops/C-sharp/topswops.cs b/Task/Topswops/C-sharp/topswops.cs new file mode 100644 index 0000000000..a9866fcf40 --- /dev/null +++ b/Task/Topswops/C-sharp/topswops.cs @@ -0,0 +1,49 @@ +using System; + +public class Topswops { + static readonly int maxBest = 32; + static int[] best; + + private static void TrySwaps(int[] deck, int f, int d, int n) { + if (d > best[n]) + best[n] = d; + + for (int i = n - 1; i >= 0; i--) { + if (deck[i] == -1 || deck[i] == i) + break; + if (d + best[i] <= best[n]) + return; + } + + int[] deck2 = (int[])deck.Clone(); + for (int i = 1; i < n; i++) { + int k = 1 << i; + if (deck2[i] == -1) { + if ((f & k) != 0) + continue; + } else if (deck2[i] != i) + continue; + + deck2[0] = i; + for (int j = i - 1; j >= 0; j--) + deck2[i - j] = deck[j]; // Reverse copy. + TrySwaps(deck2, f | k, d + 1, n); + } + } + + static int topswops(int n) { + if(n <= 0 || n >= maxBest) throw new ArgumentOutOfRangeException(nameof(n), "n must be greater than 0 and less than maxBest."); + best[n] = 0; + int[] deck0 = new int[n + 1]; + for (int i = 1; i < n; i++) + deck0[i] = -1; + TrySwaps(deck0, 1, 0, n); + return best[n]; + } + + public static void Main(string[] args) { + best = new int[maxBest]; + for (int i = 1; i < 11; i++) + Console.WriteLine(i + ": " + topswops(i)); + } +} diff --git a/Task/Topswops/Wren/topswops.wren b/Task/Topswops/Wren/topswops.wren index 8d44ef7126..7ddff959a4 100644 --- a/Task/Topswops/Wren/topswops.wren +++ b/Task/Topswops/Wren/topswops.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var maxn = 10 var maxl = 50 diff --git a/Task/Total-circles-area/C-sharp/total-circles-area.cs b/Task/Total-circles-area/C-sharp/total-circles-area.cs new file mode 100644 index 0000000000..72a45748f2 --- /dev/null +++ b/Task/Total-circles-area/C-sharp/total-circles-area.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Program +{ + public static void Main(string[] args) + { + const double precision = 0.000001; + Console.WriteLine($"Approximate area = {AreaScan(precision):F8}"); + } + + private static double AreaScan(double precision) + { + List valuesY = new List(); + foreach (var circle in circles) + { + valuesY.Add(circle.CentreY + circle.Radius); + valuesY.Add(circle.CentreY - circle.Radius); + } + + double min = valuesY.Min(); + double max = valuesY.Max(); + long minY = (long)Math.Floor(min / precision); + long maxY = (long)Math.Ceiling(max / precision); + double totalArea = 0.0; + for (long i = minY; i <= maxY; i++) + { + double y = i * precision; + double right = double.NegativeInfinity; + List pairsX = new List(); + foreach (var circle in circles) + { + if (Math.Abs(y - circle.CentreY) < circle.Radius) + { + pairsX.Add(HorizontalSection(circle, y)); + } + } + + pairsX.Sort((one, two) => one.X1.CompareTo(two.X1)); + foreach (var pairX in pairsX) + { + if (pairX.X2 > right) + { + totalArea += pairX.X2 - Math.Max(pairX.X1, right); + right = pairX.X2; + } + } + } + + return totalArea * precision; + } + + private static PairX HorizontalSection(Circle circle, double y) + { + double value = Math.Pow(circle.Radius, 2) - Math.Pow(y - circle.CentreY, 2); + double deltaX = Math.Sqrt(value); + return new PairX(circle.CentreX - deltaX, circle.CentreX + deltaX); + } + + private record PairX(double X1, double X2); + private record Circle(double CentreX, double CentreY, double Radius); + private static readonly List circles = new List + { + new Circle(1.6417233788, 1.6121789534, 0.0848270516), + new Circle(-1.4944608174, 1.2077959613, 1.1039549836), + new Circle(0.6110294452, -0.6907087527, 0.9089162485), + new Circle(0.3844862411, 0.2923344616, 0.2375743054), + new Circle(-0.2495892950, -0.3832854473, 1.0845181219), + new Circle(1.7813504266, 1.6178237031, 0.8162655711), + new Circle(-0.1985249206, -0.8343333301, 0.0538864941), + new Circle(-1.7011985145, -0.1263820964, 0.4776976918), + new Circle(-0.4319462812, 1.4104420482, 0.7886291537), + new Circle(0.2178372997, -0.9499557344, 0.0357871187), + new Circle(-0.6294854565, -1.3078893852, 0.7653357688), + new Circle(1.7952608455, 0.6281269104, 0.2727652452), + new Circle(1.4168575317, 1.0683357171, 1.1016025378), + new Circle(1.4637371396, 0.9463877418, 1.1846214562), + new Circle(-0.5263668798, 1.7315156631, 1.4428514068), + new Circle(-1.2197352481, 0.9144146579, 1.0727263474), + new Circle(-0.1389358881, 0.1092805780, 0.7350208828), + new Circle(1.5293954595, 0.0030278255, 1.2472867347), + new Circle(-0.5258728625, 1.3782633069, 1.3495508831), + new Circle(-0.1403562064, 0.2437382535, 1.3804956588), + new Circle(0.8055826339, -0.0482092025, 0.3327165165), + new Circle(-0.6311979224, 0.7184578971, 0.2491045282), + new Circle(1.4685857879, -0.8347049536, 1.3670667538), + new Circle(-0.6855727502, 1.6465021616, 1.0593087096), + new Circle(0.0152957411, 0.0638919221, 0.9771215985) + }; +} diff --git a/Task/Total-circles-area/Wren/total-circles-area-1.wren b/Task/Total-circles-area/Wren/total-circles-area-1.wren index 929fae39c3..10d70cd45b 100644 --- a/Task/Total-circles-area/Wren/total-circles-area-1.wren +++ b/Task/Total-circles-area/Wren/total-circles-area-1.wren @@ -1,5 +1,5 @@ -import "/dynamic" for Tuple -import "/math" for Nums +import "./dynamic" for Tuple +import "./math" for Nums var Circle = Tuple.create("Circle", ["x", "y", "r"]) diff --git a/Task/Total-circles-area/Wren/total-circles-area-2.wren b/Task/Total-circles-area/Wren/total-circles-area-2.wren index 99f7a0c10c..c9bc6f7832 100644 --- a/Task/Total-circles-area/Wren/total-circles-area-2.wren +++ b/Task/Total-circles-area/Wren/total-circles-area-2.wren @@ -1,6 +1,6 @@ -import "/dynamic" for Tuple -import "/math" for Nums -import "/sort" for Sort +import "./dynamic" for Tuple +import "./math" for Nums +import "./sort" for Sort var Point = Tuple.create("Point", ["x", "y"]) var Circle = Tuple.create("Circle", ["x", "y", "r"]) diff --git a/Task/Totient-function/Wren/totient-function.wren b/Task/Totient-function/Wren/totient-function.wren index 54ade3af88..9671787aa8 100644 --- a/Task/Totient-function/Wren/totient-function.wren +++ b/Task/Totient-function/Wren/totient-function.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var totient = Fn.new { |n| var tot = n diff --git a/Task/Towers-of-Hanoi/Refal/towers-of-hanoi.refal b/Task/Towers-of-Hanoi/Refal/towers-of-hanoi.refal new file mode 100644 index 0000000000..e4c403dda1 --- /dev/null +++ b/Task/Towers-of-Hanoi/Refal/towers-of-hanoi.refal @@ -0,0 +1,11 @@ +$ENTRY Go { + = ; +}; + +Move { + 0 e.X = ; + s.N s.Src s.Via s.Dest, <- s.N 1>: s.Next = + + + ; +}; diff --git a/Task/Towers-of-Hanoi/Uxntal/towers-of-hanoi.uxnatl b/Task/Towers-of-Hanoi/Uxntal/towers-of-hanoi.uxnatl new file mode 100644 index 0000000000..4ea818bcc2 --- /dev/null +++ b/Task/Towers-of-Hanoi/Uxntal/towers-of-hanoi.uxnatl @@ -0,0 +1,43 @@ +|10 @Console &vector $2 &read $1 &pad $4 &type $1 &write $1 &error $1 + +|0100 ( -> ) + #0102 [ LIT2 03 &count 04 ] hanoi + POP2 POP2 BRK + +@hanoi ( from spare to count -: from spare to count ) + ( moving 0 disks is no-op ) + DUP ?{ JMP2r } + + ( move disks 1..count-1 to the spare peg ) + #01 SUB ROT SWP hanoi + ( from to spare count-1 ) + + ( print the current move ) + ;dict/move print-str + INCk #30 ORA .Console/write DEO + STH2 + ;dict/from print-str + OVR #30 ORA .Console/write DEO + ;dict/to print-str + DUP #30 ORA .Console/write DEO + [ LIT2 0a -Console/write ] DEO + STH2r + + ( move disks 1..count-1 from the spare peg to the goal peg ) + STH ROT ROT STHr hanoi + + ( restore original parameters for convenient recursion ) + STH2 SWP STH2r INC + + JMP2r + +@print-str + &loop + LDAk .Console/write DEO + INC2 LDAk ?&loop + POP2 JMP2r + +@dict + &move "Move 20 "disk 2000 + &from 20 "from 20 "pole 2000 + &to 20 "to 20 "pole 2000 diff --git a/Task/Trabb-Pardo-Knuth-algorithm/EasyLang/trabb-pardo-knuth-algorithm.easy b/Task/Trabb-Pardo-Knuth-algorithm/EasyLang/trabb-pardo-knuth-algorithm.easy new file mode 100644 index 0000000000..77fa3b475a --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/EasyLang/trabb-pardo-knuth-algorithm.easy @@ -0,0 +1,16 @@ +print "Please enter 11 numbers :" +n[] = number strsplit input " " +print "" +print "Evaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :" +for i = len n[] downto 1 + r = sqrt abs n[i] + 5 * pow n[i] 3 + write "f(" & n[i] & ") = " + if r > 400 + print "Overflow!" + else + print r + . +. +# without this section, the input is interactive +input_data +10 -1 1 2 3 4 4.3 4.31 4.32 4.32 4.29 diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Elena/trabb-pardo-knuth-algorithm.elena b/Task/Trabb-Pardo-Knuth-algorithm/Elena/trabb-pardo-knuth-algorithm.elena index 7de0b39414..9b2b3f8f60 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/Elena/trabb-pardo-knuth-algorithm.elena +++ b/Task/Trabb-Pardo-Knuth-algorithm/Elena/trabb-pardo-knuth-algorithm.elena @@ -5,13 +5,13 @@ public program() { real[] inputs := new real[](11); console.printLine("Please enter 11 numbers :"); - for(int i := 0, i < 11, i += 1) + for(int i := 0; i < 11; i += 1) { inputs[i] := console.readLine().toReal() }; console.printLine("Evaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"); - for(int i := 10, i >= 0, i -= 1) + for(int i := 10; i >= 0; i -= 1) { real result := sqrt(abs(inputs[i])) + 5 * power(inputs[i], 3); diff --git a/Task/Trabb-Pardo-Knuth-algorithm/MATLAB/trabb-pardo-knuth-algorithm.m b/Task/Trabb-Pardo-Knuth-algorithm/MATLAB/trabb-pardo-knuth-algorithm.m new file mode 100644 index 0000000000..84b1cb565b --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/MATLAB/trabb-pardo-knuth-algorithm.m @@ -0,0 +1,18 @@ +clear all;close all;clc; + +% Define the function f(x) +f = @(x) sqrt(abs(x)) + 5 * x^3; + +% Read a line of input, split it into elements, convert to numbers +inputLine = input('', 's'); +numbers = str2double(strsplit(inputLine)); + +% Process each number in reverse order +for i = length(numbers):-1:1 + value = f(numbers(i)); + if value > 400 + fprintf('%g: TOO LARGE\n', numbers(i)); + else + fprintf('%g: %g\n', numbers(i), value); + end +end diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Wren/trabb-pardo-knuth-algorithm.wren b/Task/Trabb-Pardo-Knuth-algorithm/Wren/trabb-pardo-knuth-algorithm.wren index 21808c0978..f4c5087722 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/Wren/trabb-pardo-knuth-algorithm.wren +++ b/Task/Trabb-Pardo-Knuth-algorithm/Wren/trabb-pardo-knuth-algorithm.wren @@ -1,5 +1,5 @@ import "io" for Stdin, Stdout -import "/fmt" for Fmt +import "./fmt" for Fmt var f = Fn.new { |x| x.abs.sqrt + 5*x*x*x } diff --git a/Task/Transliterate-English-text-using-the-Greek-alphabet/Python/transliterate-english-text-using-the-greek-alphabet.py b/Task/Transliterate-English-text-using-the-Greek-alphabet/Python/transliterate-english-text-using-the-greek-alphabet.py new file mode 100644 index 0000000000..d5e5f2e6ed --- /dev/null +++ b/Task/Transliterate-English-text-using-the-Greek-alphabet/Python/transliterate-english-text-using-the-greek-alphabet.py @@ -0,0 +1,40 @@ +import re + +# Input texts +texts = [ + "The quick brown fox jumped over the lazy dog.", + """I was looking at some rhododendrons in my back garden, +dressed in my khaki shorts, when the telephone rang. + +As I answered it, I cheerfully glimpsed that the July sun +caused a fragment of black pine wax to ooze on the velvet quilt +laying in my patio.""", + "sphinx of black quartz, judge my vow." +] + +# Mapping of replacements +replacements = [ + ("ch", "χ"), ("th", "θ"), ("ps", "ψ"), ("ph", "f"), (r"s(\W)", r"ς\1"), ("Ch", "Χ"), + ("Th", "Θ"), ("Ps", "Ψ"), ("Ph", "F"), ("ee", "h"), ("ck", "κ"), ("rh", "r"), ("kh", "χ"), + ("Kh", "Χ"), ("oo", "w"), ("a", "α"), ("b", "β"), ("c", "κ"), ("d", "δ"), ("e", "ε"), + ("f", "φ"), ("g", "γ"), ("h", "η"), ("i", "ι"), ("j", "ι"), ("k", "κ"), ("l", "λ"), + ("m", "μ"), ("n", "ν"), ("o", "ο"), ("p", "π"), ("q", "κ"), ("r", "ρ"), ("s", "σ"), + ("t", "τ"), ("u", "υ"), ("v", "β"), ("w", "ω"), ("x", "ξ"), ("y", "υ"), ("z", "ζ"), + ("D", "Δ"), ("F", "Φ"), ("G", "Γ"), ("J", "I"), ("L", "Λ"), ("P", "Π"), ("Q", "Κ"), + ("R", "Ρ"), ("S", "Σ"), ("Y", "U"), ("W", "Ω"), ("X", "Ξ") +] + +# Function to apply replacements +def replace_text(text, replacements): + for old, new in replacements: + if re.search(r"\W", old): # If the key contains special characters, treat it as a regex + text = re.sub(old, new, text) + else: + text = text.replace(old, new) + return text + +# Apply replacements and print the results +for txt in texts: + print(f"{txt}\n=>") + txt = replace_text(txt, replacements) + print(f"{txt}\n" + "="*65) diff --git a/Task/Tree-datastructures/Wren/tree-datastructures.wren b/Task/Tree-datastructures/Wren/tree-datastructures.wren index 72ffdd274a..b6a6b99dc4 100644 --- a/Task/Tree-datastructures/Wren/tree-datastructures.wren +++ b/Task/Tree-datastructures/Wren/tree-datastructures.wren @@ -1,5 +1,5 @@ -import "/dynamic" for Struct -import "/fmt" for Fmt +import "./dynamic" for Struct +import "./fmt" for Fmt var NNode = Struct.create("NNode", ["name", "children"]) var INode = Struct.create("INode", ["level", "name"]) diff --git a/Task/Tree-from-nesting-levels/Wren/tree-from-nesting-levels-1.wren b/Task/Tree-from-nesting-levels/Wren/tree-from-nesting-levels-1.wren index 2910d2dbcc..8b6175f990 100644 --- a/Task/Tree-from-nesting-levels/Wren/tree-from-nesting-levels-1.wren +++ b/Task/Tree-from-nesting-levels/Wren/tree-from-nesting-levels-1.wren @@ -1,5 +1,5 @@ -import "/seq" for Stack -import "/fmt" for Fmt +import "./seq" for Stack +import "./fmt" for Fmt var toTree = Fn.new { |list| var nested = [] diff --git a/Task/Tree-from-nesting-levels/Wren/tree-from-nesting-levels-2.wren b/Task/Tree-from-nesting-levels/Wren/tree-from-nesting-levels-2.wren index 1eed40b8f3..250bc2165d 100644 --- a/Task/Tree-from-nesting-levels/Wren/tree-from-nesting-levels-2.wren +++ b/Task/Tree-from-nesting-levels/Wren/tree-from-nesting-levels-2.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var toTree // recursive toTree = Fn.new { |list, index, depth| diff --git a/Task/Tree-traversal/Elena/tree-traversal.elena b/Task/Tree-traversal/Elena/tree-traversal.elena index ca89c84ab6..4cca79b45f 100644 --- a/Task/Tree-traversal/Elena/tree-traversal.elena +++ b/Task/Tree-traversal/Elena/tree-traversal.elena @@ -76,7 +76,7 @@ class Node LevelOrder = new Enumerable { - Queue queue := class Queue.allocate(4).push:self; + Queue queue := class Queue.allocate(4).push(self); Enumerator enumerator() = new Enumerator { diff --git a/Task/Tree-traversal/Refal/tree-traversal.refal b/Task/Tree-traversal/Refal/tree-traversal.refal new file mode 100644 index 0000000000..03c647d68c --- /dev/null +++ b/Task/Tree-traversal/Refal/tree-traversal.refal @@ -0,0 +1,35 @@ +$ENTRY Go { + = > + > + > + >; +}; + +Show { + s.F t.T = >; +}; + +Tree { + = (1 (2 (4 (7 () ()) ()) (5 () ())) (3 (6 (8 () ()) (9 () ())) ())); +}; + +Preorder { + () = ; + (s.V t.L t.R) = s.V ; +}; + +Inorder { + () = ; + (s.V t.L t.R) = s.V ; +}; + +Postorder { + () = ; + (s.V t.L t.R) = s.V; +}; + +Levelorder { + = ; + () e.Q = ; + (s.V t.L t.R) e.Q = s.V ; +}; diff --git a/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy b/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy new file mode 100644 index 0000000000..39f5395c7a --- /dev/null +++ b/Task/Trigonometric-functions/EasyLang/trigonometric-functions.easy @@ -0,0 +1,21 @@ +r = pi / 4 +d = 45 +# +func r2d r . + return r / pi * 180 +. +func d2r d . + return d * pi / 180 +. +# +numfmt 4 0 +print sin d & " " & sin r2d r +print cos d & " " & cos r2d r +print tan d & " " & tan r2d r +print "" +h = asin sin d +print h & " " & d2r h +h = acos cos d +print h & " " & d2r h +h = atan tan d +print h & " " & d2r h diff --git a/Task/Trigonometric-functions/Wren/trigonometric-functions.wren b/Task/Trigonometric-functions/Wren/trigonometric-functions.wren index e0d621c78f..9e09085a5d 100644 --- a/Task/Trigonometric-functions/Wren/trigonometric-functions.wren +++ b/Task/Trigonometric-functions/Wren/trigonometric-functions.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var d = 30 var r = d * Num.pi / 180 diff --git a/Task/Tropical-algebra-overloading/C-sharp/tropical-algebra-overloading.cs b/Task/Tropical-algebra-overloading/C-sharp/tropical-algebra-overloading.cs new file mode 100644 index 0000000000..c3a13cc2e8 --- /dev/null +++ b/Task/Tropical-algebra-overloading/C-sharp/tropical-algebra-overloading.cs @@ -0,0 +1,86 @@ +using System; + +public class Program +{ + public static void Main(string[] args) + { + var a = new Tropical(-2); + var b = new Tropical(-1); + var c = new Tropical(-0.5); + var d = new Tropical(-0.001); + var e = new Tropical(0); + var f = new Tropical(1.5); + var g = new Tropical(2); + var h = new Tropical(5); + var i = new Tropical(7); + var j = new Tropical(8); + var k = new Tropical(); // Represents -Inf + + Console.WriteLine("2 x -2 = " + g.Multiply(a)); + Console.WriteLine("-0.001 + -Inf = " + d.Add(k)); + Console.WriteLine("0 x -Inf = " + e.Multiply(k)); + Console.WriteLine("1.5 + -1 = " + f.Add(b)); + Console.WriteLine("-0.5 x 0 = " + c.Multiply(e)); + + Console.WriteLine(); + Console.WriteLine("5^7 = " + h.Power(7)); + + Console.WriteLine(); + Console.WriteLine("5 * ( 8 + 7 ) = " + h.Multiply(j.Add(i))); + Console.WriteLine("5 * 8 + 5 * 7 = " + h.Multiply(j).Add(h.Multiply(i))); + } +} + +public class Tropical +{ + private double? number; + + public Tropical(double number) + { + this.number = number; + } + + public Tropical() + { + this.number = null; // Represents -Inf + } + + public override string ToString() + { + return number.HasValue ? ((int)number.Value).ToString() : "-Inf"; + } + + public Tropical Add(Tropical other) + { + if (!number.HasValue) return other; + if (!other.number.HasValue) return this; + + return number > other.number ? this : other; + } + + public Tropical Multiply(Tropical other) + { + if (number.HasValue && other.number.HasValue) + { + return new Tropical(number.Value + other.number.Value); + } + + return new Tropical(); + } + + public Tropical Power(int exponent) + { + if (exponent <= 0) + { + throw new ArgumentException("Power must be positive", nameof(exponent)); + } + + Tropical result = this; + for (int i = 1; i < exponent; i++) + { + result = result.Multiply(this); + } + + return result; + } +} diff --git a/Task/Truncatable-primes/EasyLang/truncatable-primes.easy b/Task/Truncatable-primes/EasyLang/truncatable-primes.easy new file mode 100644 index 0000000000..bc201f07a4 --- /dev/null +++ b/Task/Truncatable-primes/EasyLang/truncatable-primes.easy @@ -0,0 +1,46 @@ +fastfunc isprim num . + if num < 2 + return 0 + . + i = 2 + while i <= sqrt num + if num mod i = 0 + return 0 + . + i += 1 + . + return 1 +. +func isright h . + while h > 0 + if isprim h = 0 + return 0 + . + h = h div 10 + . + return 1 +. +func isleft h . + d = pow 10 (floor log10 h) + while h > 0 + if isprim h = 0 + return 0 + . + if h div d = 0 + return 0 + . + h = h mod d + d /= 10 + . + return 1 +. +p = 999999 +while isleft p = 0 + p -= 2 +. +print p +p = 999999 +while isright p = 0 + p -= 2 +. +print p diff --git a/Task/Truncatable-primes/Elena/truncatable-primes.elena b/Task/Truncatable-primes/Elena/truncatable-primes.elena index 5c7680f747..5ae07350b7 100644 --- a/Task/Truncatable-primes/Elena/truncatable-primes.elena +++ b/Task/Truncatable-primes/Elena/truncatable-primes.elena @@ -10,9 +10,9 @@ extension mathOp if (n < 2) { ^ false }; if (n < 4) { ^ true }; - if (n.mod:2 == 0) { ^ false }; + if (n.mod(2) == 0) { ^ false }; if (n < 9) { ^ true }; - if (n.mod:3 == 0) { ^ false }; + if (n.mod(3) == 0) { ^ false }; int r := n.sqrt(); int f := 5; diff --git a/Task/Truncatable-primes/Wren/truncatable-primes.wren b/Task/Truncatable-primes/Wren/truncatable-primes.wren index 9e86bb8004..6faeda1615 100644 --- a/Task/Truncatable-primes/Wren/truncatable-primes.wren +++ b/Task/Truncatable-primes/Wren/truncatable-primes.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/math" for Int +import "./fmt" for Fmt +import "./math" for Int var limit = 999999 var c = Int.primeSieve(limit, false) diff --git a/Task/Truncate-a-file/Elena/truncate-a-file.elena b/Task/Truncate-a-file/Elena/truncate-a-file.elena index 964814b700..d59c38df47 100644 --- a/Task/Truncate-a-file/Elena/truncate-a-file.elena +++ b/Task/Truncate-a-file/Elena/truncate-a-file.elena @@ -16,7 +16,7 @@ extension fileOp : File public program() { if (program_arguments.Length != 3) - { console.printLine:"Please provide the path to the file and a new length"; AbortException.raise() }; + { console.printLine("Please provide the path to the file and a new length"); AbortException.raise() }; auto file := File.assign(program_arguments[1]); var length := program_arguments[2].toInt(); diff --git a/Task/Truncate-a-file/Wren/truncate-a-file.wren b/Task/Truncate-a-file/Wren/truncate-a-file.wren index 39af8d78f3..702faafaa2 100644 --- a/Task/Truncate-a-file/Wren/truncate-a-file.wren +++ b/Task/Truncate-a-file/Wren/truncate-a-file.wren @@ -1,4 +1,4 @@ -import "/ioutil" for FileUtil +import "./ioutil" for FileUtil var fileName = "temp.txt" diff --git a/Task/Truth-table/11l/truth-table.11l b/Task/Truth-table/11l/truth-table.11l index 0dabd3b3d2..669af240c8 100644 --- a/Task/Truth-table/11l/truth-table.11l +++ b/Task/Truth-table/11l/truth-table.11l @@ -38,7 +38,7 @@ T ASTNode ‘&’ R .first_child.eval() [&] .second_child.eval() ‘!’ - R (-).first_child.eval() [&] 1 + R ~.first_child.eval() [&] 1 ‘(’ R .first_child.eval() E diff --git a/Task/Truth-table/Wren/truth-table.wren b/Task/Truth-table/Wren/truth-table.wren index 3c945f038a..a206d7776f 100644 --- a/Task/Truth-table/Wren/truth-table.wren +++ b/Task/Truth-table/Wren/truth-table.wren @@ -1,7 +1,7 @@ -import "/dynamic" for Struct -import "/ioutil" for Input -import "/seq" for Stack -import "/str" for Str +import "./dynamic" for Struct +import "./ioutil" for Input +import "./seq" for Stack +import "./str" for Str var Variable = Struct.create("Variable", ["name", "value"]) diff --git a/Task/Twelve-statements/Elena/twelve-statements.elena b/Task/Twelve-statements/Elena/twelve-statements.elena index 28ef1edc0d..85fd6bdea9 100644 --- a/Task/Twelve-statements/Elena/twelve-statements.elena +++ b/Task/Twelve-statements/Elena/twelve-statements.elena @@ -6,7 +6,7 @@ extension op { printSolution(bits) = self.zipBy(bits, - (s,b => s.iif("T","F") + (s.xor:b).iif("* "," "))).summarize(new StringWriter()); + (s,b => s.iif("T","F") + (s.xor(b)).iif("* "," "))).summarize(new StringWriter()); toBit() = self.iif(1,0); @@ -16,46 +16,46 @@ puzzle = new Func1[] { (bits => bits.Length == 12), - (bits => bits.last(6).selectBy:(x => x.toBit()).summarize() == 3 ), + (bits => bits.last(6).selectBy::(x => x.toBit()).summarize() == 3 ), (bits => bits.zipBy(new Range(1, 12), - (x,i => (i.toInt().isEven()).and:x.toBit())).summarize() == 2 ), + (x,i => (i.toInt().isEven()).and(x).toBit())).summarize() == 2 ), (bits => bits[4].iif(bits[5] && bits[6],true) ), (bits => ((bits[1] || bits[2]) || bits[3]).Inverted ), (bits => bits.zipBy(new Range(1, 12), - (x,i => (i.toInt().isOdd()).and:x.toBit() )).summarize() == 4 ), + (x,i => (i.toInt().isOdd()).and(x).toBit() )).summarize() == 4 ), (bits => bits[1].xor(bits[2]) ), (bits => bits[6].iif(bits[5] && bits[4],true) ), - (bits => bits.top(6).selectBy:(x => x.toBit() ).summarize() == 3 ), + (bits => bits.top(6).selectBy::(x => x.toBit() ).summarize() == 3 ), (bits => bits[10] && bits[11] ), (bits => (bits[6].toBit() + bits[7].toBit() + bits[8].toBit())==1 ), - (bits => bits.top(11).selectBy:(x => x.toBit()).summarize() == 4 ) + (bits => bits.top(11).selectBy::(x => x.toBit()).summarize() == 4 ) }; public program() { console.writeLine(); - for(int n := 0, n < 2.power(12), n += 1) + for(int n := 0; n < 2.power(12); n += 1) { var bits := BitArray32.load(n).top(12).toArray(); - var results := puzzle.selectBy:(r => r(bits)).toArray(); + var results := puzzle.selectBy::(r => r(bits)).toArray(); - var counts := bits.zipBy(results, (b,r => b.xor:r.toBit() )).summarize(); + var counts := bits.zipBy(results, (b,r => b.xor(r).toBit() )).summarize(); counts => - 0 { console.printLine("Total hit :",results.printSolution:bits) } - 1 { console.printLine("Near miss :",results.printSolution:bits) } - 12 { console.printLine("Total miss:",results.printSolution:bits) }; + 0 { console.printLine("Total hit :",results.printSolution(bits)) } + 1 { console.printLine("Near miss :",results.printSolution(bits)) } + 12 { console.printLine("Total miss:",results.printSolution(bits)) }; }; console.readChar() diff --git a/Task/Twelve-statements/Wren/twelve-statements.wren b/Task/Twelve-statements/Wren/twelve-statements.wren index 66215e6f74..7349713244 100644 --- a/Task/Twelve-statements/Wren/twelve-statements.wren +++ b/Task/Twelve-statements/Wren/twelve-statements.wren @@ -1,4 +1,4 @@ -import "/fmt" for Conv, Fmt +import "./fmt" for Conv, Fmt var predicates = [ Fn.new { |s| s.count == 13 }, // indexing starts at 0 but first bit ignored diff --git a/Task/Twin-primes/Wren/twin-primes.wren b/Task/Twin-primes/Wren/twin-primes.wren index b53901513b..3c1ce1976a 100644 --- a/Task/Twin-primes/Wren/twin-primes.wren +++ b/Task/Twin-primes/Wren/twin-primes.wren @@ -1,5 +1,5 @@ -import "/math" for Int -import "/fmt" for Fmt +import "./math" for Int +import "./fmt" for Fmt var c = Int.primeSieve(1e8-1, false) var limit = 10 diff --git a/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy b/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy index 7a271b0f1e..7819a5d4b0 100644 --- a/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy +++ b/Task/Two-bullet-roulette/EasyLang/two-bullet-roulette.easy @@ -19,7 +19,7 @@ proc load . . rshift . proc spin . . - lim = random 6 + lim = randint 6 for i = 1 to lim - 1 rshift . diff --git a/Task/Two-bullet-roulette/FreeBASIC/two-bullet-roulette.basic b/Task/Two-bullet-roulette/FreeBASIC/two-bullet-roulette.basic new file mode 100644 index 0000000000..2f10d3ca7b --- /dev/null +++ b/Task/Two-bullet-roulette/FreeBASIC/two-bullet-roulette.basic @@ -0,0 +1,81 @@ +Type Revolver + cylinder(0 To 5) As Integer +End Type + +Sub rshift(r As Revolver) + Dim t As Integer = r.cylinder(5) + For i As Integer = 4 To 0 Step -1 + r.cylinder(i + 1) = r.cylinder(i) + Next i + r.cylinder(0) = t +End Sub + +Sub unload(r As Revolver) + For i As Integer = 0 To 5 + r.cylinder(i) = 0 + Next i +End Sub + +Sub load(r As Revolver) + While r.cylinder(0) <> 0 + rshift(r) + Wend + r.cylinder(0) = -1 + rshift(r) +End Sub + +Sub spin(r As Revolver) + For i As Integer = 1 To Int(Rnd * 6) + 1 + rshift(r) + Next i +End Sub + +Function fire(r As Revolver) As Integer + Dim As Integer shot = r.cylinder(0) + rshift(r) + Return shot +End Function + +Function method(r As Revolver, s As String) As Integer + unload(r) + For i As Integer = 1 To Len(s) + Dim c As String = Mid(s, i, 1) + If c = "L" Then + load(r) + Elseif c = "S" Then + spin(r) + Elseif c = "F" Then + If fire(r) <> 0 Then Return 1 + End If + Next i + Return 0 +End Function + +Function mstring(s As String) As String + Dim As String l = "" + For i As Integer = 1 To Len(s) + Dim As String c = Mid(s, i, 1) + If c = "L" Then + l &= "load, " + Elseif c = "S" Then + l &= "spin, " + Elseif c = "F" Then + l &= "fire, " + End If + Next i + Return Left(l, Len(l) - 2) +End Function + +Dim As Revolver rev +Dim As Integer tests = 100000 +Dim As String methods(0 To 3) = {"LSLSFSF", "LSLSFF", "LLSFSF", "LLSFF"} + +For m As Integer = 0 To 3 'In methods + Dim sum As Integer = 0 + For t As Integer = 1 To tests + sum += method(rev, methods(m)) + Next t + Print mstring(methods(m)), " produces "; sum * 100.0 / tests; "% deaths." +Next m + +Sleep diff --git a/Task/Two-bullet-roulette/Wren/two-bullet-roulette.wren b/Task/Two-bullet-roulette/Wren/two-bullet-roulette.wren index 42c61e0e42..9ef0f1fbaf 100644 --- a/Task/Two-bullet-roulette/Wren/two-bullet-roulette.wren +++ b/Task/Two-bullet-roulette/Wren/two-bullet-roulette.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/fmt" for Fmt +import "./fmt" for Fmt var Rand = Random.new() diff --git a/Task/UPC/Wren/upc.wren b/Task/UPC/Wren/upc.wren index 02fc69759d..114079f135 100644 --- a/Task/UPC/Wren/upc.wren +++ b/Task/UPC/Wren/upc.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var digitL = { " ## #": 0, diff --git a/Task/URL-decoding/Wren/url-decoding.wren b/Task/URL-decoding/Wren/url-decoding.wren index d293ef0aac..f2bcf9f19b 100644 --- a/Task/URL-decoding/Wren/url-decoding.wren +++ b/Task/URL-decoding/Wren/url-decoding.wren @@ -1,4 +1,4 @@ -import "/fmt" for Conv +import "./fmt" for Conv var urlDecode = Fn.new { |enc| var res = "" diff --git a/Task/URL-encoding/Wren/url-encoding.wren b/Task/URL-encoding/Wren/url-encoding.wren index fb4d107247..9c91223215 100644 --- a/Task/URL-encoding/Wren/url-encoding.wren +++ b/Task/URL-encoding/Wren/url-encoding.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var urlEncode = Fn.new { |url| var res = "" diff --git a/Task/UTF-8-encode-and-decode/Elena/utf-8-encode-and-decode.elena b/Task/UTF-8-encode-and-decode/Elena/utf-8-encode-and-decode.elena index e2909e8904..e1d9a8c2b4 100644 --- a/Task/UTF-8-encode-and-decode/Elena/utf-8-encode-and-decode.elena +++ b/Task/UTF-8-encode-and-decode/Elena/utf-8-encode-and-decode.elena @@ -10,12 +10,12 @@ extension op : String string printAsUTF8Array() { - self.toByteArray().forEach:(b){ console.print(b.toString(16)," ") } + self.toByteArray().forEach::(b){ console.print(b.toString(16)," ") } } string printAsUTF32() { - self.toArray().forEach:(c){ console.print("U+",c.toInt().toString(16)," ") } + self.toArray().forEach::(c){ console.print("U+",c.toInt().toString(16)," ") } } } diff --git a/Task/UTF-8-encode-and-decode/Wren/utf-8-encode-and-decode.wren b/Task/UTF-8-encode-and-decode/Wren/utf-8-encode-and-decode.wren index 5b5a8368c5..04a8d5c0bc 100644 --- a/Task/UTF-8-encode-and-decode/Wren/utf-8-encode-and-decode.wren +++ b/Task/UTF-8-encode-and-decode/Wren/utf-8-encode-and-decode.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var utf8_encode = Fn.new { |cp| String.fromCodePoint(cp).bytes.toList } diff --git a/Task/Ukkonen-s-suffix-tree-construction/Wren/ukkonen-s-suffix-tree-construction.wren b/Task/Ukkonen-s-suffix-tree-construction/Wren/ukkonen-s-suffix-tree-construction.wren index 2aecc534f8..317dd3edf7 100644 --- a/Task/Ukkonen-s-suffix-tree-construction/Wren/ukkonen-s-suffix-tree-construction.wren +++ b/Task/Ukkonen-s-suffix-tree-construction/Wren/ukkonen-s-suffix-tree-construction.wren @@ -1,6 +1,6 @@ -import "/big" for BigRat -import "/dynamic" for Struct -import "/trait" for ByRef +import "./big" for BigRat +import "./dynamic" for Struct +import "./trait" for ByRef import "io" for File var maxChar = 128 diff --git a/Task/Ulam-spiral-for-primes-/Wren/ulam-spiral-for-primes-.wren b/Task/Ulam-spiral-for-primes-/Wren/ulam-spiral-for-primes-.wren index b4a62dc8f3..e6c344d6a9 100644 --- a/Task/Ulam-spiral-for-primes-/Wren/ulam-spiral-for-primes-.wren +++ b/Task/Ulam-spiral-for-primes-/Wren/ulam-spiral-for-primes-.wren @@ -1,7 +1,7 @@ -import "/dynamic" for Enum -import "/math" for Int -import "/str" for Char -import "/fmt" for Fmt +import "./dynamic" for Enum +import "./math" for Int +import "./str" for Char +import "./fmt" for Fmt var Direction = Enum.create("Direction", ["right", "up", "left", "down"]) diff --git a/Task/Unbias-a-random-generator/EasyLang/unbias-a-random-generator.easy b/Task/Unbias-a-random-generator/EasyLang/unbias-a-random-generator.easy new file mode 100644 index 0000000000..a3bea2058b --- /dev/null +++ b/Task/Unbias-a-random-generator/EasyLang/unbias-a-random-generator.easy @@ -0,0 +1,21 @@ +func biased n . + return if randomf < 1 / n +. +func unbiased n . + repeat + a = biased n + b = biased n + until a <> b + . + return a +. +m = 50000 +for n = 3 to 6 + c1 = 0 + c2 = 0 + for i to m + c1 += biased n + c2 += unbiased n + . + print n & ": " & 100 * c1 / m & " " & 100 * c2 / m +. diff --git a/Task/Unbias-a-random-generator/Elena/unbias-a-random-generator.elena b/Task/Unbias-a-random-generator/Elena/unbias-a-random-generator.elena index 13a5b10fb3..1b8e8fe4d9 100644 --- a/Task/Unbias-a-random-generator/Elena/unbias-a-random-generator.elena +++ b/Task/Unbias-a-random-generator/Elena/unbias-a-random-generator.elena @@ -22,14 +22,14 @@ extension op : IntNumber public program() { - for(int n := 3, n <= 6, n += 1) + for(int n := 3; n <= 6; n += 1) { int biasedZero := 0; int biasedOne := 0; int unbiasedZero := 0; int unbiasedOne := 0; - for(int i := 0, i < 100000, i += 1) + for(int i := 0; i < 100000; i += 1) { if(n.randN()) { biasedOne += 1 } else { biasedZero += 1 }; if(n.Unbiased) { unbiasedOne += 1 } else { unbiasedZero += 1 } diff --git a/Task/Unbias-a-random-generator/Wren/unbias-a-random-generator.wren b/Task/Unbias-a-random-generator/Wren/unbias-a-random-generator.wren index 990f544959..c200d628a6 100644 --- a/Task/Unbias-a-random-generator/Wren/unbias-a-random-generator.wren +++ b/Task/Unbias-a-random-generator/Wren/unbias-a-random-generator.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/fmt" for Fmt +import "./fmt" for Fmt var rand = Random.new() diff --git a/Task/Undefined-values/Forth/undefined-values.fth b/Task/Undefined-values/Forth/undefined-values.fth new file mode 100644 index 0000000000..1f82873c5b --- /dev/null +++ b/Task/Undefined-values/Forth/undefined-values.fth @@ -0,0 +1,11 @@ +[undefined] var [if] .( var is undefined at first check) cr [then] + +marker forget-var + +variable var + +[defined] var [if] .( var is defined at second check) cr [then] + +forget-var + +[undefined] var [if] .( var is undefined at third check) cr [then] diff --git a/Task/Unicode-strings/Elena/unicode-strings.elena b/Task/Unicode-strings/Elena/unicode-strings.elena index 50133dd14f..7de9434d33 100644 --- a/Task/Unicode-strings/Elena/unicode-strings.elena +++ b/Task/Unicode-strings/Elena/unicode-strings.elena @@ -3,6 +3,6 @@ public program() var 四十二 := "♥♦♣♠"; // UTF8 string var строка := "Привет"w; // UTF16 string - console.writeLine:строка; - console.writeLine:四十二; + console.writeLine(строка); + console.writeLine(四十二); } diff --git a/Task/Unicode-variable-names/Elena/unicode-variable-names.elena b/Task/Unicode-variable-names/Elena/unicode-variable-names.elena index a418e4faba..eef0f6ba75 100644 --- a/Task/Unicode-variable-names/Elena/unicode-variable-names.elena +++ b/Task/Unicode-variable-names/Elena/unicode-variable-names.elena @@ -3,5 +3,5 @@ public program() var Δ := 1; Δ := Δ + 1; - console.writeLine:Δ + console.writeLine(Δ) } diff --git a/Task/Universal-Turing-machine/Wren/universal-turing-machine.wren b/Task/Universal-Turing-machine/Wren/universal-turing-machine.wren index 69576fac5b..deb373352f 100644 --- a/Task/Universal-Turing-machine/Wren/universal-turing-machine.wren +++ b/Task/Universal-Turing-machine/Wren/universal-turing-machine.wren @@ -1,5 +1,5 @@ -import "/dynamic" for Enum, Tuple, Struct -import "/fmt" for Fmt +import "./dynamic" for Enum, Tuple, Struct +import "./fmt" for Fmt var Dir = Enum.create("Dir", ["LEFT", "RIGHT", "STAY"]) diff --git a/Task/Unprimeable-numbers/Wren/unprimeable-numbers.wren b/Task/Unprimeable-numbers/Wren/unprimeable-numbers.wren index e34029c72a..12241fb5df 100644 --- a/Task/Unprimeable-numbers/Wren/unprimeable-numbers.wren +++ b/Task/Unprimeable-numbers/Wren/unprimeable-numbers.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/math" for Int +import "./fmt" for Fmt +import "./math" for Int System.print("The first 35 unprimeable numbers are:") var count = 0 // counts all unprimeable numbers diff --git a/Task/Untouchable-numbers/Wren/untouchable-numbers-1.wren b/Task/Untouchable-numbers/Wren/untouchable-numbers-1.wren index 283ac76a16..7c192fa99c 100644 --- a/Task/Untouchable-numbers/Wren/untouchable-numbers-1.wren +++ b/Task/Untouchable-numbers/Wren/untouchable-numbers-1.wren @@ -1,6 +1,5 @@ -import "/math" for Int, Nums -import "/seq" for Lst -import "/fmt" for Fmt +import "./math" for Int, Nums +import "./fmt" for Fmt var sieve = Fn.new { |n| n = n + 1 @@ -23,9 +22,7 @@ while (n <= limit) { } System.print("List of untouchable numbers <= 2,000:") -for (chunk in Lst.chunks(untouchable.where { |n| n <= 2000 }.toList, 10)) { - Fmt.print("$,6d", chunk) -} +Fmt.tprint("$,6d", untouchable.where { |n| n <= 2000 }, 10) System.print() Fmt.print("$,6d untouchable numbers were found <= 2,000", untouchable.count { |n| n <= 2000 }) var p = 10 diff --git a/Task/Untouchable-numbers/Wren/untouchable-numbers-2.wren b/Task/Untouchable-numbers/Wren/untouchable-numbers-2.wren index 9cde338484..4b18d7aafc 100644 --- a/Task/Untouchable-numbers/Wren/untouchable-numbers-2.wren +++ b/Task/Untouchable-numbers/Wren/untouchable-numbers-2.wren @@ -1,6 +1,5 @@ -import "/math" for Int, Nums -import "/seq" for Lst -import "/fmt" for Fmt +import "./math" for Int, Nums +import "./fmt" for Fmt var limit = 1e6 var m = 63 @@ -26,9 +25,7 @@ while (n <= limit) { n = n + 2 } System.print("List of untouchable numbers <= 2,000:") -for (chunk in Lst.chunks(untouchable.where { |n| n <= 2000 }.toList, 10)) { - Fmt.print("$,6d", chunk) -} +Fmt.tprint("$,6d", untouchable.where { |n| n <= 2000 }, 10) System.print() Fmt.print("$,7d untouchable numbers were found <= 2,000", untouchable.count { |n| n <= 2000 }) var p = 10 diff --git a/Task/Update-a-configuration-file/Wren/update-a-configuration-file.wren b/Task/Update-a-configuration-file/Wren/update-a-configuration-file.wren index bdf2a50b87..47dca5b469 100644 --- a/Task/Update-a-configuration-file/Wren/update-a-configuration-file.wren +++ b/Task/Update-a-configuration-file/Wren/update-a-configuration-file.wren @@ -1,7 +1,7 @@ import "io" for File -import "/ioutil" for FileUtil -import "/dynamic" for Tuple -import "/str" for Str +import "./ioutil" for FileUtil +import "./dynamic" for Tuple +import "./str" for Str var fields = ["favouriteFruit", "needsPeeling", "seedsRemoved", "numberOfBananas", "numberOfStrawberries"] var ConfigData = Tuple.create("ConfigData", fields) diff --git a/Task/Use-another-language-to-call-a-function/Wren/use-another-language-to-call-a-function-1.wren b/Task/Use-another-language-to-call-a-function/Wren/use-another-language-to-call-a-function-1.wren index 9004d9d356..45d880c1e6 100644 --- a/Task/Use-another-language-to-call-a-function/Wren/use-another-language-to-call-a-function-1.wren +++ b/Task/Use-another-language-to-call-a-function/Wren/use-another-language-to-call-a-function-1.wren @@ -1,4 +1,4 @@ -/* query.wren */ +/* Use_another_language_to_call_a_function.wren */ class RCQuery { // Both arguments are lists as we need pass by reference here diff --git a/Task/Use-another-language-to-call-a-function/Wren/use-another-language-to-call-a-function-2.wren b/Task/Use-another-language-to-call-a-function/Wren/use-another-language-to-call-a-function-2.wren index 45867d58d5..97be378664 100644 --- a/Task/Use-another-language-to-call-a-function/Wren/use-another-language-to-call-a-function-2.wren +++ b/Task/Use-another-language-to-call-a-function/Wren/use-another-language-to-call-a-function-2.wren @@ -1,3 +1,5 @@ +/* gcc Use_another_language_to_call_a_function.c -o Use_another_language_to_call_a_function -lwren -lm */ + #include #include "wren.h" @@ -51,7 +53,7 @@ int configWrenVM() { config.bindForeignMethodFn = &bindForeignMethod; vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "query.wren"; + const char* fileName = "Use_another_language_to_call_a_function.wren"; script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/User-input-Text/BabyCobol/user-input-text.cobol b/Task/User-input-Text/BabyCobol/user-input-text.cobol new file mode 100644 index 0000000000..0d0b6c0bcc --- /dev/null +++ b/Task/User-input-Text/BabyCobol/user-input-text.cobol @@ -0,0 +1,12 @@ + * NB: whitespace insignificance and case insensitivity + * are used in the field name. + IDENTIFICATION DIVISION. + PROGRAM-ID. USER INPUT. + DATA DIVISION. + 01 HUNDRED CHAR STRING PICTURE IS X(100). + 01 FIVE DIGIT NUMBER PICTURE IS 9(5). + PROCEDURE DIVISION. + DISPLAY "Enter a string of appropriate length: " WITH NO ADVANCING + ACCEPT HundredChar String. + DISPLAY "Enter a number (preferably 75000): " WITH NO ADVANCING + ACCEPT FiveDigit Number. diff --git a/Task/User-input-Text/Elena/user-input-text.elena b/Task/User-input-Text/Elena/user-input-text.elena index 432fecf07e..c53b775e8e 100644 --- a/Task/User-input-Text/Elena/user-input-text.elena +++ b/Task/User-input-Text/Elena/user-input-text.elena @@ -3,7 +3,7 @@ import extensions; public program() { var num := new Integer(); - console.write:"Enter an integer: ".loadLineTo:num; + console.write("Enter an integer: ").loadLineTo(num); - var word := console.write:"Enter a String: ".readLine() + var word := console.write("Enter a String: ").readLine() } diff --git a/Task/Validate-International-Securities-Identification-Number/BASIC256/validate-international-securities-identification-number.basic b/Task/Validate-International-Securities-Identification-Number/BASIC256/validate-international-securities-identification-number.basic new file mode 100644 index 0000000000..d3fdd3f879 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/BASIC256/validate-international-securities-identification-number.basic @@ -0,0 +1,54 @@ +array base 1 + +dim test_set$(7) +test_set$ = {"US0378331005", "US0373831005", "U50378331005", "US03378331005", "AU0000XVGZA3", "AU0000VXGZA3", "FR0000988040"} + +for i = 1 to test_set$[?] + test_str$ = "" + l = length(test_set$[i]) + if l <> 12 then + print test_set$[i]; " Invalid, length <> 12 char." + continue for + end if + if asc(mid(test_set$[i], 1, 1)) < asc("A") or asc(mid(test_set$[i], 2, 1)) < asc("A") then + print test_set$[i]; " Invalid, number needs to start with 2 characters" + continue for + end if + for n = 1 to l + x = asc(mid(test_set$[i], n, 1)) - asc("0") + if x > 9 then x -= 7 + if x < 10 then + test_str$ += string(x) + else # two digest number + test_str$ += string(x \ 10) + string(x mod 10) + end if + next + print test_set$[i]; " "; + if luhntest(test_str$) = 1 then + print "Invalid, checksum error" + else + print "Valid" + end if +next +end + +function luhntest(cardnr$) + cardnr$ = trim(cardnr$) # remove spaces + l = length(cardnr$) + s1 = 0 + s2 = 0 + + # sum odd numbers + for i = 1 to l step 2 + s1 += fromradix(asc(mid(cardnr$, i, 1)), 10) + next + # sum even numbers + for i = 2 to l step 2 + j = fromradix(asc(mid(cardnr$, i, 1)), 10) + j *= 2 + if j > 9 then j = (j mod 10) + 1 + s2 += j + next + + return (s1 + s2) mod 10 = 0 +end function diff --git a/Task/Validate-International-Securities-Identification-Number/Dart/validate-international-securities-identification-number.dart b/Task/Validate-International-Securities-Identification-Number/Dart/validate-international-securities-identification-number.dart new file mode 100644 index 0000000000..18c00b28f8 --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/Dart/validate-international-securities-identification-number.dart @@ -0,0 +1,48 @@ +bool checkISIN(String isin) { + int j = 0, v = 0; + List s = List.filled(24, 0); + + for (int i = 0; i < 12; i++) { + int k = isin.codeUnitAt(i); + if (k >= '0'.codeUnitAt(0) && k <= '9'.codeUnitAt(0)) { + if (i < 2) return false; + s[j++] = k - '0'.codeUnitAt(0); + } else if (k >= 'A'.codeUnitAt(0) && k <= 'Z'.codeUnitAt(0)) { + if (i == 11) return false; + k -= 'A'.codeUnitAt(0) - 10; + s[j++] = k ~/ 10; + s[j++] = k % 10; + } else { + return false; + } + } + + if (isin.length > 12) return false; + + for (int i = j - 2; i >= 0; i -= 2) { + int k = 2 * s[i]; + v += k > 9 ? k - 9 : k; + } + + for (int i = j - 1; i >= 0; i -= 2) { + v += s[i]; + } + + return v % 10 == 0; +} + +void main() { + List test = [ + "US0378331005", + "US0373831005", + "U50378331005", + "US03378331005", + "AU0000XVGZA3", + "AU0000VXGZA3", + "FR0000988040" + ]; + + for (String isin in test) { + print('$isin - ${checkISIN(isin)}'); + } +} diff --git a/Task/Validate-International-Securities-Identification-Number/EasyLang/validate-international-securities-identification-number.easy b/Task/Validate-International-Securities-Identification-Number/EasyLang/validate-international-securities-identification-number.easy new file mode 100644 index 0000000000..3df18636ea --- /dev/null +++ b/Task/Validate-International-Securities-Identification-Number/EasyLang/validate-international-securities-identification-number.easy @@ -0,0 +1,48 @@ +func isin t$ . + if len t$ <> 12 + return 0 + . + for i to 12 + k = strcode substr t$ i 1 + if k >= 48 and k <= 57 + if i <= 2 + return 0 + . + s[] &= k - 48 + elif k >= 65 and k <= 91 + if (i = 12) + return 0 + . + k -= 55 + s[] &= k div 10 + s[] &= k mod 10 + else + return 0 + . + . + i = len s[] - 1 + while i >= 1 + k = 2 * s[i] + if k > 9 + k -= 9 + . + v += k + i -= 2 + . + i = len s[] + while i >= 1 + v += s[i] + i -= 2 + . + if v mod 10 = 0 + return 1 + . +. +test$[] = [ "US0378331005" "US0373831005" "U50378331005" "US03378331005" "AU0000XVGZA3" "AU0000VXGZA3" "FR0000988040" ] +for t$ in test$[] + if isin t$ = 1 + print t$ & " is valid" + else + print t$ & " is invalid" + . +. diff --git a/Task/Validate-International-Securities-Identification-Number/Wren/validate-international-securities-identification-number.wren b/Task/Validate-International-Securities-Identification-Number/Wren/validate-international-securities-identification-number.wren index 79b0bbc3d9..8d631abc16 100644 --- a/Task/Validate-International-Securities-Identification-Number/Wren/validate-international-securities-identification-number.wren +++ b/Task/Validate-International-Securities-Identification-Number/Wren/validate-international-securities-identification-number.wren @@ -1,6 +1,6 @@ -import "/str" for Char -import "/iterate" for Stepped -import "/fmt" for Conv, Fmt +import "./str" for Char +import "./iterate" for Stepped +import "./fmt" for Conv, Fmt var luhn = Fn.new { |s| s = s[-1..0] diff --git a/Task/Vampire-number/Forth/vampire-number.fth b/Task/Vampire-number/Forth/vampire-number.fth new file mode 100644 index 0000000000..4b2a394d05 --- /dev/null +++ b/Task/Vampire-number/Forth/vampire-number.fth @@ -0,0 +1,55 @@ +: sqrt ( u -- sqrt ) ( Babylonian method ) + dup 2/ ( first square root guess is half ) + dup 0= if drop exit then ( sqrt[0]=0, sqrt[1]=1 ) + begin dup >r 2dup / r> + 2/ ( stack: square old-guess new-guess ) + 2dup > while ( as long as guess is decreasing ) + nip repeat ( forget old-guess and repeat ) + drop nip ; + +: ndigits ( n -- n ) 10 / dup 0<> if recurse then 1+ ; + +: dtally ( n -- n ) + 10 /mod + dup 0<> if recurse then + swap 6 * 1 swap lshift + ; + +: ?product ( x a b -- f ) * = ; +: ?dtally ( x a b -- f ) dtally rot dtally rot dtally rot + = ; +: ?ndigits ( a b -- f ) ndigits swap ndigits = ; +: ?0trail ( a b -- f ) 10 mod 0= swap 10 mod 0= and invert ; + +: ?fang ( x a -- f ) + 2dup / 2>r + dup 2r@ ?product + swap 2r@ ?dtally and + 2r@ ?ndigits and + 2r> ?0trail and ; + +: next-fang ( n a -- false | a true ) + over sqrt swap 1+ ?do + dup i ?fang if drop i true unloop exit then + loop drop false ; + +: ?vampire ( n -- false | a true ) 0 next-fang ; + +: next-vampire ( n -- n a ) begin 1+ dup ?vampire until ; + +: .product ( n a -- ) dup . ." x " / . ." = " ; + +: .vampire ( n a -- ) + cr + begin 2dup .product + over swap next-fang + while repeat + . ; + +: .fangs ( n -- ) dup ?vampire if .vampire else cr . ." is not vampiric." then ; + +: vampires ( n -- ) + 1 swap + 0 do next-vampire over swap .vampire loop drop ; + +25 vampires +16758243290880 .fangs +24959017348650 .fangs +14593825548650 .fangs diff --git a/Task/Vampire-number/Wren/vampire-number.wren b/Task/Vampire-number/Wren/vampire-number.wren index 169db02d19..1e50a96303 100644 --- a/Task/Vampire-number/Wren/vampire-number.wren +++ b/Task/Vampire-number/Wren/vampire-number.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var ndigits = Fn.new { |x| var n = 0 diff --git a/Task/Van-Eck-sequence/Refal/van-eck-sequence.refal b/Task/Van-Eck-sequence/Refal/van-eck-sequence.refal new file mode 100644 index 0000000000..d364c38139 --- /dev/null +++ b/Task/Van-Eck-sequence/Refal/van-eck-sequence.refal @@ -0,0 +1,28 @@ +$ENTRY Go { + , : e.Eck + , : (e.First10) e.Rest1 + , : (e.Rest2) e.Last10 + = + ; +}; + +Eck { + s.N = >; +}; + +Reverse { + = ; + e.X s.I = s.I ; +}; + +Repeat { + 0 s.F e.X = e.X; + s.N s.F e.X = s.F >; +}; + +EckStep { + = 0; + s.N e.X, e.X: e.F s.N e.R, + : s.M e.F = <+ s.M 1> s.N e.X; + s.N e.X = 0 s.N e.X; +}; diff --git a/Task/Variable-length-quantity/Wren/variable-length-quantity.wren b/Task/Variable-length-quantity/Wren/variable-length-quantity.wren index 8dc7c2fc6f..56b0497d73 100644 --- a/Task/Variable-length-quantity/Wren/variable-length-quantity.wren +++ b/Task/Variable-length-quantity/Wren/variable-length-quantity.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt, Conv -import "/str" for Str +import "./fmt" for Fmt, Conv +import "./str" for Str var toOctets = Fn.new { |n| var s = Conv.itoa(n, 2) diff --git a/Task/Variable-size-Set/Forth/variable-size-set.fth b/Task/Variable-size-Set/Forth/variable-size-set.fth new file mode 100644 index 0000000000..1546d14795 --- /dev/null +++ b/Task/Variable-size-Set/Forth/variable-size-set.fth @@ -0,0 +1,7 @@ +create cvar 0 c, \ char size variable + +variable var \ cell size variable + +2variable 2var \ 2 cells size variable + +fvariable fvar \ float size variable diff --git a/Task/Variadic-function/Elena/variadic-function.elena b/Task/Variadic-function/Elena/variadic-function.elena index b16eb7a99d..4152fbec0a 100644 --- a/Task/Variadic-function/Elena/variadic-function.elena +++ b/Task/Variadic-function/Elena/variadic-function.elena @@ -5,7 +5,7 @@ extension variadicOp { printAll(params object[] list) { - for(int i := 0, i < list.Length, i+=1) + for(int i := 0; i < list.Length; i++) { self.printLine(list[i]) } diff --git a/Task/Variadic-function/F-Sharp/variadic-function.fs b/Task/Variadic-function/F-Sharp/variadic-function.fs new file mode 100644 index 0000000000..a0f0642952 --- /dev/null +++ b/Task/Variadic-function/F-Sharp/variadic-function.fs @@ -0,0 +1,4 @@ +// Variadic function. Nigel Galloway: March 6th., 2024 +open System +type X()=static member F([] args: Object[]) = args|>Array.iter(printfn "%A") +X.F(23, 3.142, "Nigel", 1u, true) diff --git a/Task/Vector-products/EasyLang/vector-products.easy b/Task/Vector-products/EasyLang/vector-products.easy new file mode 100644 index 0000000000..9b15984e77 --- /dev/null +++ b/Task/Vector-products/EasyLang/vector-products.easy @@ -0,0 +1,20 @@ +func vdot a[] b[] . + for i to len a[] + r += a[i] * b[i] + . + return r +. +func[] vcross a[] b[] . + r[] &= a[2] * b[3] - a[3] * b[2] + r[] &= a[3] * b[1] - a[1] * b[3] + r[] &= a[1] * b[2] - a[2] * b[1] + return r[] +. +a[] = [ 3 4 5 ] +b[] = [ 4 3 5 ] +c[] = [ -5 -12 -13 ] +# +print vdot a[] b[] +print vcross a[] b[] +print vdot a[] vcross b[] c[] +print vcross a[] vcross b[] c[] diff --git a/Task/Vector/EasyLang/vector.easy b/Task/Vector/EasyLang/vector.easy new file mode 100644 index 0000000000..821535f3f9 --- /dev/null +++ b/Task/Vector/EasyLang/vector.easy @@ -0,0 +1,28 @@ +func[] vadd a[] b[] . + for i to len a[] + r[] &= a[i] + b[i] + . + return r[] +. +func[] vsub a[] b[] . + for i to len a[] + r[] &= a[i] - b[i] + . + return r[] +. +func[] vmul a[] b . + for i to len a[] + r[] &= a[i] * b + . + return r[] +. +func[] vdiv a[] b . + for i to len a[] + r[] &= a[i] / b + . + return r[] +. +print vadd [ 5 7 ] [ 2 3 ] +print vsub [ 5 7 ] [ 2 3 ] +print vmul [ 5 7 ] 11 +print vdiv [ 5 7 ] 2 diff --git a/Task/Verhoeff-algorithm/Wren/verhoeff-algorithm.wren b/Task/Verhoeff-algorithm/Wren/verhoeff-algorithm.wren index 904a1bd939..eb0cfdcca4 100644 --- a/Task/Verhoeff-algorithm/Wren/verhoeff-algorithm.wren +++ b/Task/Verhoeff-algorithm/Wren/verhoeff-algorithm.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var d = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/C-sharp/verify-distribution-uniformity-chi-squared-test.cs b/Task/Verify-distribution-uniformity-Chi-squared-test/C-sharp/verify-distribution-uniformity-chi-squared-test.cs new file mode 100644 index 0000000000..1793b69f07 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/C-sharp/verify-distribution-uniformity-chi-squared-test.cs @@ -0,0 +1,145 @@ +using System; + +class Program +{ + public delegate double Func(double x); + public static double Simpson38(Func f, double a, double b, int n) + { + double h = (b - a) / n; + double h1 = h / 3; + double sum = f(a) + f(b); + for (int j = 3 * n - 1; j > 0; j--) + { + if (j % 3 == 0) + { + sum += 2 * f(a + h1 * j); + } + else + { + sum += 3 * f(a + h1 * j); + } + } + + return h * sum / 8; + } + + // Lanczos Approximation for Gamma Function + private static double SpecialFunctionGamma(double z) + { + double[] p = + { + 676.5203681218851, + -1259.1392167224028, + 771.32342877765313, + -176.61502916214059, + 12.507343278686905, + -0.13857109526572012, + 9.9843695780195716e-6, + 1.5056327351493116e-7 + }; + if (z < 0.5) + return Math.PI / (Math.Sin(Math.PI * z) * SpecialFunctionGamma(1 - z)); + z -= 1; + double x = 0.99999999999980993; + for (int i = 0; i < p.Length; i++) + { + x += p[i] / (z + i + 1); + } + + double t = z + p.Length - 0.5; + return Math.Sqrt(2 * Math.PI) * Math.Pow(t, z + 0.5) * Math.Exp(-t) * x; + } + + public static double GammaIncQ(double a, double x) + { + double aa1 = a - 1; + Func f = t => Math.Pow(t, aa1) * Math.Exp(-t); + double y = aa1; + double h = 1.5e-2; + while (f(y) * (x - y) > 2e-8 && y < x) + { + y += .4; + } + + if (y > x) + { + y = x; + } + + return 1 - Simpson38(f, 0, y, (int)(y / h / SpecialFunctionGamma(a))); + } + + public static double Chi2Ud(int[] ds) + { + double sum = 0, expected = 0; + foreach (var d in ds) + { + expected += d; + } + + expected /= ds.Length; + foreach (var d in ds) + { + double x = d - expected; + sum += x * x; + } + + return sum / expected; + } + + public static double Chi2P(int dof, double distance) + { + return GammaIncQ(.5 * dof, .5 * distance); + } + + const double SigLevel = .05; + static void Main(string[] args) + { + int[][] datasets = new int[][] + { + new int[] + { + 199809, + 200665, + 199607, + 200270, + 199649 + }, + new int[] + { + 522573, + 244456, + 139979, + 71531, + 21461 + }, + }; + foreach (var dset in datasets) + { + UTest(dset); + } + } + + static void UTest(int[] dset) + { + Console.WriteLine("Uniform distribution test"); + int sum = 0; + foreach (var c in dset) + { + sum += c; + } + + Console.WriteLine($" dataset: {string.Join(", ", dset)}"); + Console.WriteLine($" samples: {sum}"); + Console.WriteLine($" categories: {dset.Length}"); + int dof = dset.Length - 1; + Console.WriteLine($" degrees of freedom: {dof}"); + double dist = Chi2Ud(dset); + Console.WriteLine($" chi square test statistic: {dist}"); + double p = Chi2P(dof, dist); + Console.WriteLine($" p-value of test statistic: {p}"); + bool sig = p < SigLevel; + Console.WriteLine($" significant at {SigLevel * 100}% level? {sig}"); + Console.WriteLine($" uniform? {!sig}\n"); + } +} diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Wren/verify-distribution-uniformity-chi-squared-test.wren b/Task/Verify-distribution-uniformity-Chi-squared-test/Wren/verify-distribution-uniformity-chi-squared-test.wren index 1cb82012e8..ee061a9aa8 100644 --- a/Task/Verify-distribution-uniformity-Chi-squared-test/Wren/verify-distribution-uniformity-chi-squared-test.wren +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Wren/verify-distribution-uniformity-chi-squared-test.wren @@ -1,5 +1,5 @@ -import "/math" for Math, Nums -import "/fmt" for Fmt +import "./math" for Math, Nums +import "./fmt" for Fmt var integrate = Fn.new { |a, b, n, f| var h = (b - a) / n diff --git a/Task/Verify-distribution-uniformity-Naive/C-sharp/verify-distribution-uniformity-naive.cs b/Task/Verify-distribution-uniformity-Naive/C-sharp/verify-distribution-uniformity-naive.cs new file mode 100644 index 0000000000..b8ceeebb4a --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/C-sharp/verify-distribution-uniformity-naive.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public class Test +{ + static void DistCheck(Func func, int nRepeats, double delta) + { + var counts = new Dictionary(); + + for (int i = 0; i < nRepeats; i++) + { + int result = func(); + if (counts.ContainsKey(result)) + counts[result]++; + else + counts[result] = 1; + } + + double target = nRepeats / (double)counts.Count; + int deltaCount = (int)(delta / 100.0 * target); + + foreach (var kvp in counts) + { + if (Math.Abs(target - kvp.Value) >= deltaCount) + Console.WriteLine("distribution potentially skewed for '{0}': '{1}'", kvp.Key, kvp.Value); + } + + foreach (var key in counts.Keys.OrderBy(k => k)) + { + Console.WriteLine("{0} {1}", key, counts[key]); + } + } + + public static void Main(string[] args) + { + DistCheck(() => new Random().Next(1, 6), 1_000_000, 1); + } +} diff --git a/Task/Verify-distribution-uniformity-Naive/Wren/verify-distribution-uniformity-naive.wren b/Task/Verify-distribution-uniformity-Naive/Wren/verify-distribution-uniformity-naive.wren index 9f97cdd509..9ba59a7f11 100644 --- a/Task/Verify-distribution-uniformity-Naive/Wren/verify-distribution-uniformity-naive.wren +++ b/Task/Verify-distribution-uniformity-Naive/Wren/verify-distribution-uniformity-naive.wren @@ -1,6 +1,6 @@ import "random" for Random -import "/fmt" for Fmt -import "/sort" for Sort +import "./fmt" for Fmt +import "./sort" for Sort var r = Random.new() diff --git a/Task/Video-display-modes/Wren/video-display-modes-1.wren b/Task/Video-display-modes/Wren/video-display-modes-1.wren index 2adf23f8a1..81433e1a32 100644 --- a/Task/Video-display-modes/Wren/video-display-modes-1.wren +++ b/Task/Video-display-modes/Wren/video-display-modes-1.wren @@ -1,4 +1,4 @@ -/* video_display_modes.wren */ +/* Video_display_modes.wren */ class C { foreign static xrandr(args) diff --git a/Task/Video-display-modes/Wren/video-display-modes-2.wren b/Task/Video-display-modes/Wren/video-display-modes-2.wren index 9e560c6ac0..d834210a12 100644 --- a/Task/Video-display-modes/Wren/video-display-modes-2.wren +++ b/Task/Video-display-modes/Wren/video-display-modes-2.wren @@ -1,3 +1,5 @@ +/* gcc Video_display_modes.c -o Video_display_modes -lwren -lm */ + #include #include #include @@ -55,7 +57,7 @@ int main(int argc, char **argv) { config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "video_display_modes.wren"; + const char* fileName = "Video_display_modes.wren"; char *script = readFile(fileName); wrenInterpret(vm, module, script); wrenFreeVM(vm); diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Wren/vigen-re-cipher-cryptanalysis.wren b/Task/Vigen-re-cipher-Cryptanalysis/Wren/vigen-re-cipher-cryptanalysis.wren index f35c4dab13..e87ef83420 100644 --- a/Task/Vigen-re-cipher-Cryptanalysis/Wren/vigen-re-cipher-cryptanalysis.wren +++ b/Task/Vigen-re-cipher-Cryptanalysis/Wren/vigen-re-cipher-cryptanalysis.wren @@ -1,7 +1,7 @@ -import "/math" for Nums -import "/iterate" for Stepped -import "/str" for Char, Str -import "/fmt" for Fmt +import "./math" for Nums +import "./iterate" for Stepped +import "./str" for Char, Str +import "./fmt" for Fmt var encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + diff --git a/Task/Vigen-re-cipher/Elena/vigen-re-cipher.elena b/Task/Vigen-re-cipher/Elena/vigen-re-cipher.elena index ba72a398f9..36658564cc 100644 --- a/Task/Vigen-re-cipher/Elena/vigen-re-cipher.elena +++ b/Task/Vigen-re-cipher/Elena/vigen-re-cipher.elena @@ -6,30 +6,27 @@ import extensions; class VCipher { - string encrypt(string txt, string pw, int d) - { - auto output := new TextBuilder(); - int pwi := 0; + string encrypt(string txt, string pw, int d) + { + auto output := new TextBuilder(); + int pwi := 0; - string PW := pw.toUpper(); + string PW := pw.toUpper(); + var TXT := txt.toUpper(); - txt.toUpper().forEach:(t) - { - if(t >= $65) - { - int tmp := t.toInt() - 65 + d * (PW[pwi].toInt() - 65); - if (tmp < 0) - { - tmp += 26 - }; - output.write((65 + tmp.mod:26).toChar()); - pwi += 1; - if (pwi == PW.Length) { pwi := 0 } - } - }; + foreach(char t; in TXT) + { + if (t < $65) $continue; - ^ output.Value - } + int tmp := t - 65 + d * (pw[pwi] - 65); + if (tmp < 0) tmp += 26; + output.write((65 + tmp.mod(26)).toChar()); + pwi++; + if (pwi == PW.Length) { pwi := 0 } + }; + + ^ output.Value + } } public program() diff --git a/Task/Vigen-re-cipher/Wren/vigen-re-cipher.wren b/Task/Vigen-re-cipher/Wren/vigen-re-cipher.wren index 4d909eaee8..a2d09271a5 100644 --- a/Task/Vigen-re-cipher/Wren/vigen-re-cipher.wren +++ b/Task/Vigen-re-cipher/Wren/vigen-re-cipher.wren @@ -1,4 +1,4 @@ -import "/str" for Char, Str +import "./str" for Char, Str var vigenere = Fn.new { |text, key, encrypt| var t = encrypt ? Str.upper(text) : text diff --git a/Task/Visualize-a-tree/Wren/visualize-a-tree.wren b/Task/Visualize-a-tree/Wren/visualize-a-tree.wren index aa8742a938..1b5456709a 100644 --- a/Task/Visualize-a-tree/Wren/visualize-a-tree.wren +++ b/Task/Visualize-a-tree/Wren/visualize-a-tree.wren @@ -1,4 +1,4 @@ -import "/dynamic" for Struct +import "./dynamic" for Struct import "random" for Random var Stem = Struct.create("Stem", ["str", "next"]) diff --git a/Task/Vogels-approximation-method/Wren/vogels-approximation-method.wren b/Task/Vogels-approximation-method/Wren/vogels-approximation-method.wren index 9c8b4809d0..685d2c41f5 100644 --- a/Task/Vogels-approximation-method/Wren/vogels-approximation-method.wren +++ b/Task/Vogels-approximation-method/Wren/vogels-approximation-method.wren @@ -1,5 +1,5 @@ -import "/math" for Int, Nums -import "/fmt" for Fmt +import "./math" for Nums +import "./fmt" for Fmt var supply = [50, 60, 50, 50] var demand = [30, 20, 70, 30, 60] @@ -20,7 +20,7 @@ var results = List.filled(nRows, null) for (i in 0...nRows) results[i] = List.filled(nCols, 0) var diff = Fn.new { |j, len, isRow| - var min1 = Int.maxSafe + var min1 = Num.maxSafeInteger var min2 = min1 var minP = -1 for (i in 0...len) { @@ -38,7 +38,7 @@ var diff = Fn.new { |j, len, isRow| } var maxPenalty = Fn.new { |len1, len2, isRow| - var md = -Int.maxSafe + var md = Num.minSafeInteger var pc = -1 var pm = -1 var mc = -1 diff --git a/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy b/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy new file mode 100644 index 0000000000..dc2b970759 --- /dev/null +++ b/Task/Voronoi-diagram/EasyLang/voronoi-diagram.easy @@ -0,0 +1,29 @@ +func hypo a b . + return sqrt (a * a + b * b) +. +nsites = 25 +for i to nsites + nx[] &= randint 1001 - 1 + ny[] &= randint 1001 - 1 + nc[] &= randint 1000 - 1 +. +for y = 0 to 1000 + for x = 0 to 1000 + dmin = 1 / 0 + for i to nsites + d = hypo (nx[i] - x) (ny[i] - y) + if d < dmin + dmin = d + imin = i + . + . + color nc[imin] + move x / 10 - 0.05 y / 10 - 0.05 + rect 0.11 0.11 + . +. +color 000 +for i to nsites + move nx[i] / 10 ny[i] / 10 + circle 0.5 +. diff --git a/Task/Walk-a-directory-Non-recursively/Elena/walk-a-directory-non-recursively.elena b/Task/Walk-a-directory-Non-recursively/Elena/walk-a-directory-non-recursively.elena index 97381716cb..ae29a527b1 100644 --- a/Task/Walk-a-directory-Non-recursively/Elena/walk-a-directory-non-recursively.elena +++ b/Task/Walk-a-directory-Non-recursively/Elena/walk-a-directory-non-recursively.elena @@ -6,5 +6,5 @@ public program() { var dir := Directory.assign("c:\MyDir"); - dir.getFiles("a.*").forEach:printingLn; + dir.getFiles("a.*").forEach(printingLn); } diff --git a/Task/Walk-a-directory-Non-recursively/Wren/walk-a-directory-non-recursively.wren b/Task/Walk-a-directory-Non-recursively/Wren/walk-a-directory-non-recursively.wren index 8c0298d730..c7f1060b3b 100644 --- a/Task/Walk-a-directory-Non-recursively/Wren/walk-a-directory-non-recursively.wren +++ b/Task/Walk-a-directory-Non-recursively/Wren/walk-a-directory-non-recursively.wren @@ -1,5 +1,5 @@ import "io" for Directory -import "/pattern" for Pattern +import "./pattern" for Pattern var walk = Fn.new { |dir, pattern| if (!Directory.exists(dir)) Fiber.abort("Directory does not exist.") diff --git a/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-3.txr b/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-3.txr new file mode 100644 index 0000000000..76cbf5f2ad --- /dev/null +++ b/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-3.txr @@ -0,0 +1 @@ +(glob* "**/*.c") diff --git a/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-4.txr b/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-4.txr new file mode 100644 index 0000000000..5917e53a77 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/TXR/walk-a-directory-recursively-4.txr @@ -0,0 +1,8 @@ +("args.c" "arith.c" "autoload.c" "buf.c" "cadr.c" "chksum.c" "chksums/crc32.c" + "chksums/md5.c" "chksums/sha1.c" "chksums/sha256.c" "combi.c" + "debug.c" "eval.c" "ffi.c" "filter.c" "ftw.c" "gc.c" "glob.c" + "gzio.c" "hash.c" "itypes.c" "lib.c" "linenoise/example.c" "linenoise/linenoise.c" + "match.c" "mpi/mpi.c" "mpi/mplogic.c" "parser.c" "protsym.c" + "psquare.c" "rand.c" "regex.c" "signal.c" "socket.c" "stream.c" + "struct.c" "strudel.c" "sysif.c" "syslog.c" "termios.c" "time.c" + "tree.c" "txr.c" "unwind.c" "utf8.c" "vm.c") diff --git a/Task/Walk-a-directory-Recursively/Wren/walk-a-directory-recursively.wren b/Task/Walk-a-directory-Recursively/Wren/walk-a-directory-recursively.wren index 59c632a58d..c935246549 100644 --- a/Task/Walk-a-directory-Recursively/Wren/walk-a-directory-recursively.wren +++ b/Task/Walk-a-directory-Recursively/Wren/walk-a-directory-recursively.wren @@ -1,6 +1,6 @@ import "io" for Directory, File -import "/pattern" for Pattern -import "/sort" for Sort +import "./pattern" for Pattern +import "./sort" for Sort var walk // recursive function walk = Fn.new { |dir, pattern, found| diff --git a/Task/War-card-game/FreeBASIC/war-card-game.basic b/Task/War-card-game/FreeBASIC/war-card-game.basic new file mode 100644 index 0000000000..cc6eac9676 --- /dev/null +++ b/Task/War-card-game/FreeBASIC/war-card-game.basic @@ -0,0 +1,74 @@ +Dim Shared As Integer stack(1, 51) ' each player's stack of cards (52 maximum) +Dim Shared As Integer inx(1) ' index to last card (+1) for each stack +Dim Shared As Integer carta + +Sub MoveCard(hacia As Integer, desde As Integer) ' Move top card desde stack to bottom of To stack + Dim As Integer i + carta = stack(desde, 0) ' take top carta from desde stack + For i = 0 To inx(desde) - 2 ' shift remaining cards over + stack(desde, i) = stack(desde, i + 1) + Next i + If inx(desde) > 0 Then inx(desde) -= 1 ' remove desde card from its stack + stack(hacia, inx(hacia)) = carta ' add carta to bottom of To stack + If inx(hacia) < 52 Then inx(hacia) += 1 ' remove desde card from its stack +End Sub + +Dim As String suit = "HDCS " +Dim As String rank = "23456789TJQKA " +Dim As Integer top ' index to compared cards, = stack top if not war +Dim As Integer deck(51) ' initial card deck (low 2 bits = suit) +For carta = 0 To 51 ' make a complete deck of cards + deck(carta) = carta +Next carta +Dim As Integer n, i, j, p, t + +Randomize Timer +For n = 0 To 10000 ' shuffle the deck by swapping random locations + i = Int(Rnd * 52): j = Int(Rnd * 52) + Swap deck(i), deck(j) +Next n +For n = 0 To 51 ' deal deck into two stacks + carta = deck(n) + i = n \ 2 + p = n Mod 2 + stack(p, i) = carta +Next n +inx(0) = 52 \ 2: inx(1) = 52 \ 2 ' set indexes to last card +1 + +Do + For p = 0 To 1 ' show both stacks of cards + For i = 0 To inx(p) - 1 + carta = stack(p, i) + Print Left(rank, carta Shr 2); + Next i + Print + For i = 0 To inx(p) - 1 + carta = stack(p, i) + Print Mid(suit, (carta And 3) + 1, 1); + Next i + Print + Next p + If inx(0) = 0 Or inx(1) = 0 Then Exit Do ' game over + + top = 0 ' compare card ranks (above 2-bit suits) + Do + If (stack(0, top) Shr 2) = (stack(1, top) Shr 2) Then + Color 3 : Print "War!" : Print : Color 7 + top += 2 ' play a card down and a card up + Elseif (stack(0, top) Shr 2) > (stack(1, top) Shr 2) Then + For i = 0 To top ' move cards to stack 0 + MoveCard(0, 0): MoveCard(0, 1) + Next i + Exit Do + Else + For i = 0 To top ' move cards to stack 1 + MoveCard(1, 1): MoveCard(1, 0) + Next i + Exit Do + End If + Loop + Sleep 1000, 1 + Print +Loop + +End diff --git a/Task/War-card-game/Wren/war-card-game.wren b/Task/War-card-game/Wren/war-card-game.wren index 46a749cb5e..da05091dce 100644 --- a/Task/War-card-game/Wren/war-card-game.wren +++ b/Task/War-card-game/Wren/war-card-game.wren @@ -1,5 +1,5 @@ import "random" for Random -import "/queue" for Deque +import "./queue" for Deque var rand = Random.new() var suits = ["♣", "♦", "♥", "♠"] diff --git a/Task/Water-collected-between-towers/Wren/water-collected-between-towers.wren b/Task/Water-collected-between-towers/Wren/water-collected-between-towers.wren index 21d8bb77df..b802187acf 100644 --- a/Task/Water-collected-between-towers/Wren/water-collected-between-towers.wren +++ b/Task/Water-collected-between-towers/Wren/water-collected-between-towers.wren @@ -1,5 +1,5 @@ -import "/math" for Math, Nums -import "/fmt" for Fmt +import "./math" for Math, Nums +import "./fmt" for Fmt var waterCollected = Fn.new { |tower| var n = tower.count diff --git a/Task/Web-scraping/Wren/web-scraping-1.wren b/Task/Web-scraping/Wren/web-scraping-1.wren index f2937b6b5c..60bded3b8e 100644 --- a/Task/Web-scraping/Wren/web-scraping-1.wren +++ b/Task/Web-scraping/Wren/web-scraping-1.wren @@ -1,4 +1,4 @@ -/* web_scraping.wren */ +/* Web_scraping.wren */ import "./pattern" for Pattern @@ -7,7 +7,7 @@ var CURLOPT_FOLLOWLOCATION = 52 var CURLOPT_WRITEFUNCTION = 20011 var CURLOPT_WRITEDATA = 10001 -var BUFSIZE = 16384 +var BUFSIZE = 16384 * 4 foreign class Buffer { construct new(size) {} @@ -38,6 +38,7 @@ curl.easyCleanup() var html = buffer.value var ix = html.indexOf("(UTC)") +ix = html.indexOf("(UTC)", ix + 1) // skip the site notice if (ix == -1) { System.print("UTC time not found.") return diff --git a/Task/Web-scraping/Wren/web-scraping-2.wren b/Task/Web-scraping/Wren/web-scraping-2.wren index fe1f69ce7c..67ab072199 100644 --- a/Task/Web-scraping/Wren/web-scraping-2.wren +++ b/Task/Web-scraping/Wren/web-scraping-2.wren @@ -1,4 +1,4 @@ -/* gcc web_scraping.c -o web_scraping -lcurl -lwren -lm */ +/* gcc Web_scraping.c -o Web_scraping -lcurl -lwren -lm */ #include #include @@ -154,7 +154,7 @@ int main(int argc, char **argv) { config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "web_scraping.wren"; + const char* fileName = "Web_scraping.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Weird-numbers/Wren/weird-numbers.wren b/Task/Weird-numbers/Wren/weird-numbers.wren index 78c539972c..086473d5f1 100644 --- a/Task/Weird-numbers/Wren/weird-numbers.wren +++ b/Task/Weird-numbers/Wren/weird-numbers.wren @@ -1,5 +1,5 @@ -import "/math" for Int, Nums -import "/iterate" for Stepped +import "./math" for Int, Nums +import "./iterate" for Stepped var semiperfect // recursive semiperfect = Fn.new { |n, divs| diff --git a/Task/Wieferich-primes/EasyLang/wieferich-primes.easy b/Task/Wieferich-primes/EasyLang/wieferich-primes.easy new file mode 100644 index 0000000000..6a9f6073d3 --- /dev/null +++ b/Task/Wieferich-primes/EasyLang/wieferich-primes.easy @@ -0,0 +1,30 @@ +fastfunc isprim num . + i = 2 + while i <= sqrt num + if num mod i = 0 + return 0 + . + i += 1 + . + return 1 +. +func weiferich p . + if isprim p = 0 + return 0 + . + q = 1 + p2 = p * p + while p > 1 + q = (2 * q) mod p2 + p -= 1 + . + if q = 1 + return 1 + . +. +print "Wieferich primes less than 5000: " +for i = 2 to 5000 + if weiferich i = 1 + print i + . +. diff --git a/Task/Wieferich-primes/Wren/wieferich-primes.wren b/Task/Wieferich-primes/Wren/wieferich-primes.wren index 7697394ff1..0dcc34c9d7 100644 --- a/Task/Wieferich-primes/Wren/wieferich-primes.wren +++ b/Task/Wieferich-primes/Wren/wieferich-primes.wren @@ -1,5 +1,5 @@ -import "/math" for Int -import "/big" for BigInt +import "./math" for Int +import "./big" for BigInt var primes = Int.primeSieve(5000) System.print("Wieferich primes < 5000:") diff --git a/Task/Wilson-primes-of-order-n/Wren/wilson-primes-of-order-n.wren b/Task/Wilson-primes-of-order-n/Wren/wilson-primes-of-order-n.wren index 6e8adbe3b1..027b7a3814 100644 --- a/Task/Wilson-primes-of-order-n/Wren/wilson-primes-of-order-n.wren +++ b/Task/Wilson-primes-of-order-n/Wren/wilson-primes-of-order-n.wren @@ -1,6 +1,6 @@ -import "/math" for Int -import "/big" for BigInt -import "/fmt" for Fmt +import "./math" for Int +import "./big" for BigInt +import "./fmt" for Fmt var limit = 11000 var primes = Int.primeSieve(limit) diff --git a/Task/Window-creation-X11/Wren/window-creation-x11-1.wren b/Task/Window-creation-X11/Wren/window-creation-x11-1.wren index 8ffd22e34e..b4a8fd6e93 100644 --- a/Task/Window-creation-X11/Wren/window-creation-x11-1.wren +++ b/Task/Window-creation-X11/Wren/window-creation-x11-1.wren @@ -1,4 +1,4 @@ -/* window_creation_x11.wren */ +/* Window_creation_X11.wren */ var KeyPressMask = 1 << 0 var ExposureMask = 1 << 15 diff --git a/Task/Window-creation-X11/Wren/window-creation-x11-2.wren b/Task/Window-creation-X11/Wren/window-creation-x11-2.wren index f49e002f75..f72ad0e150 100644 --- a/Task/Window-creation-X11/Wren/window-creation-x11-2.wren +++ b/Task/Window-creation-X11/Wren/window-creation-x11-2.wren @@ -1,3 +1,5 @@ +/* gcc Window_creation_X11.c -o Window_creation_X11 -lX11 -lwren -lm */ + #include #include #include @@ -199,7 +201,7 @@ int main(int argc, char **argv) { config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "window_creation_x11.wren"; + const char* fileName = "Window_creation_X11.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Window-management/Wren/window-management-1.wren b/Task/Window-management/Wren/window-management-1.wren index dbf86364e3..e975c12af1 100644 --- a/Task/Window-management/Wren/window-management-1.wren +++ b/Task/Window-management/Wren/window-management-1.wren @@ -1,4 +1,4 @@ -/* window_management.wren */ +/* Window_management.wren */ var GTK_WINDOW_TOPLEVEL = 0 var GTK_ORIENTATION_VERTICAL = 1 diff --git a/Task/Window-management/Wren/window-management-2.wren b/Task/Window-management/Wren/window-management-2.wren index 99c3ab7a7b..7bc13e1359 100644 --- a/Task/Window-management/Wren/window-management-2.wren +++ b/Task/Window-management/Wren/window-management-2.wren @@ -1,4 +1,4 @@ -/* gcc `pkg-config --cflags gtk+-3.0` -DGDK_VERSION_MIN_REQIRED=GDK_VERSION_3_2 window_management.c -o window_management `pkg-config --libs gtk+-3.0` -lwren -lm */ +/* gcc `pkg-config --cflags gtk+-3.0` -DGDK_VERSION_MIN_REQIRED=GDK_VERSION_3_2 Window_management.c -o Window_management `pkg-config --libs gtk+-3.0` -lwren -lm */ #include #include @@ -230,7 +230,7 @@ int main(int argc, char **argv) { config.bindForeignMethodFn = &bindForeignMethod; vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "window_management.wren"; + const char* fileName = "Window_management.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Wireworld/EasyLang/wireworld.easy b/Task/Wireworld/EasyLang/wireworld.easy new file mode 100644 index 0000000000..d40d68f310 --- /dev/null +++ b/Task/Wireworld/EasyLang/wireworld.easy @@ -0,0 +1,94 @@ +sys topleft +global m[] nc . +background 777 +# +proc show . . + clear + scale = 100 / nc + sz = scale * 0.95 + for i to len m[] + x = (i - 1) mod nc + y = (i - 1) div nc + move x * scale y * scale + if m[i] = 0 + color 000 + elif m[i] = 1 + color 980 + elif m[i] = 2 + color 338 + else + color 833 + . + rect sz sz + . +. +proc read . . + s$ = input + nc = len s$ + 2 + for i to nc + m[] &= 0 + . + repeat + m[] &= 0 + for c$ in strchars s$ + if c$ = "." + m[] &= 1 + elif c$ = "H" + m[] &= 2 + elif c$ = "t" + m[] &= 3 + else + m[] &= 0 + . + . + for i to nc - len s$ - 1 + m[] &= 0 + . + s$ = input + until s$ = "" + . + for i to nc + m[] &= 0 + . +. +read +# +len mn[] len m[] +# +proc update . . + for i to len m[] + if m[i] = 2 + mn[i] = 3 + elif m[i] = 3 + mn[i] = 1 + elif m[i] = 1 + s = 0 + for dx = -1 to 1 + for dy = -1 to 1 + ix = i + dy * nc + dx + s += if m[ix] = 2 + . + . + if s = 2 or s = 1 + mn[i] = 2 + else + mn[i] = 1 + . + . + . + swap mn[] m[] +. +on timer + update + show + timer 0.5 +. +show +timer 0.5 +# +input_data +tH......... +. . + ... +. . +Ht.. ...... diff --git a/Task/Wireworld/Elena/wireworld.elena b/Task/Wireworld/Elena/wireworld.elena index 5cc684ffbb..aa9380bcd2 100644 --- a/Task/Wireworld/Elena/wireworld.elena +++ b/Task/Wireworld/Elena/wireworld.elena @@ -50,7 +50,7 @@ wireWorldRuleSet = new RuleSet { ^ conductor } - :{ + !{ ^ cell } } @@ -62,7 +62,7 @@ sealed class Model constructor load(string stateString, int maxX, int maxY) { - var strings := stateString.splitBy(newLineConstant).selectBy:(s => s.toArray()).toArray(); + var strings := stateString.splitBy(newLineConstant).selectBy::(s => s.toArray()).toArray(); theSpace := IntMatrixSpace.allocate(maxX, maxY, RuleSet { @@ -135,7 +135,7 @@ sealed class Model public program() { Model model := Model.load(sample,10,30); - for(int i := 0, i < 10, i += 1) + for(int i := 0; i < 10; i += 1) { console.printLineFormatted("Iteration {0}",i); model.print().run() diff --git a/Task/Wireworld/F-Sharp/wireworld.fs b/Task/Wireworld/F-Sharp/wireworld.fs new file mode 100644 index 0000000000..956bb16d3f --- /dev/null +++ b/Task/Wireworld/F-Sharp/wireworld.fs @@ -0,0 +1,10 @@ +// Wireworld. Nigel Galloway: January 22nd., 2024 +type Cell= |E |T |H |C +let n=array2D [[T;H;C;C;C;C;C;C;C;C;C]; + [C;E;E;E;C;E;E;E;E;E;E]; + [E;E;E;C;C;C;E;E;E;E;E]; + [C;E;E;E;C;E;E;E;E;E;E]; + [H;T;C;C;E;C;C;C;C;C;C]] +let fG n g=match n|>Seq.sumBy(fun n->match Array2D.get g (fst n) (snd n) with H->1 |_->0) with 1 |2->H |_->C +let fX i=i|>Array2D.mapi(fun n g->function |E->E |H->T |T->C |C->fG (Seq.allPairs [max 0 (n-1)..min (n+1) (Array2D.length1 i-1)] [max 0 (g-1)..min (g+1) (Array2D.length2 i-1)]) i) +Seq.unfold(fun n->Some(n,fX n))n|>Seq.take 15|>Seq.iteri(fun n g->printfn "%d:\n%A\n" n g) diff --git a/Task/Wireworld/Wren/wireworld.wren b/Task/Wireworld/Wren/wireworld.wren index a2adc33dbd..c5166a40c0 100644 --- a/Task/Wireworld/Wren/wireworld.wren +++ b/Task/Wireworld/Wren/wireworld.wren @@ -1,5 +1,5 @@ -import "/fmt" for Fmt -import "/ioutil" for FileUtil, Stdin +import "./fmt" for Fmt +import "./ioutil" for FileUtil, Stdin var rows = 0 // extent of input configuration var cols = 0 // """ diff --git a/Task/Word-frequency/Wren/word-frequency.wren b/Task/Word-frequency/Wren/word-frequency.wren index 7c76858c9d..6d331b8340 100644 --- a/Task/Word-frequency/Wren/word-frequency.wren +++ b/Task/Word-frequency/Wren/word-frequency.wren @@ -1,8 +1,8 @@ import "io" for File -import "/str" for Str -import "/sort" for Sort -import "/fmt" for Fmt -import "/pattern" for Pattern +import "./str" for Str +import "./sort" for Sort +import "./fmt" for Fmt +import "./pattern" for Pattern var fileName = "135-0.txt" var text = File.read(fileName).trimEnd() diff --git a/Task/Word-ladder/Wren/word-ladder.wren b/Task/Word-ladder/Wren/word-ladder.wren index 018e1294eb..3e5910a2ac 100644 --- a/Task/Word-ladder/Wren/word-ladder.wren +++ b/Task/Word-ladder/Wren/word-ladder.wren @@ -1,5 +1,5 @@ import "io" for File -import "/sort" for Find +import "./sort" for Find var words = File.read("unixdict.txt").trim().split("\n") diff --git a/Task/Word-search/Wren/word-search.wren b/Task/Word-search/Wren/word-search.wren index a70be7ea07..f4029d5f4e 100644 --- a/Task/Word-search/Wren/word-search.wren +++ b/Task/Word-search/Wren/word-search.wren @@ -1,8 +1,8 @@ import "random" for Random -import "/ioutil" for FileUtil -import "/pattern" for Pattern -import "/str" for Str -import "/fmt" for Fmt +import "./ioutil" for FileUtil +import "./pattern" for Pattern +import "./str" for Str +import "./fmt" for Fmt var dirs = [ [1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1] ] var Rows = 10 diff --git a/Task/Word-wheel/Wren/word-wheel.wren b/Task/Word-wheel/Wren/word-wheel.wren index da0ea9cb97..a53e47fa10 100644 --- a/Task/Word-wheel/Wren/word-wheel.wren +++ b/Task/Word-wheel/Wren/word-wheel.wren @@ -1,6 +1,6 @@ import "io" for File -import "/sort" for Sort, Find -import "/seq" for Lst +import "./sort" for Sort, Find +import "./seq" for Lst var letters = ["d", "e", "e", "g", "k", "l", "n", "o","w"] diff --git a/Task/Word-wrap/Elena/word-wrap.elena b/Task/Word-wrap/Elena/word-wrap.elena index 0cb029e6a3..44f714e95d 100644 --- a/Task/Word-wrap/Elena/word-wrap.elena +++ b/Task/Word-wrap/Elena/word-wrap.elena @@ -21,7 +21,7 @@ extension wrapOp ^ TokenEnumerator .new(self) - .selectBy:(word) + .selectBy::(word) { currentWidth += word.Length; if (currentWidth > lineWidth) diff --git a/Task/Wordiff/Wren/wordiff.wren b/Task/Wordiff/Wren/wordiff.wren index b7f60ec52e..a7a9954805 100644 --- a/Task/Wordiff/Wren/wordiff.wren +++ b/Task/Wordiff/Wren/wordiff.wren @@ -1,7 +1,7 @@ import "random" for Random -import "/ioutil" for File, Input -import "/str" for Str -import "/sort" for Find +import "./ioutil" for File, Input +import "./str" for Str +import "./sort" for Find var rand = Random.new() var words = File.read("unixdict.txt").trim().split("\n") diff --git a/Task/World-Cup-group-stage/Elena/world-cup-group-stage.elena b/Task/World-Cup-group-stage/Elena/world-cup-group-stage.elena index 64dac2ec37..8c4e35dcca 100644 --- a/Task/World-Cup-group-stage/Elena/world-cup-group-stage.elena +++ b/Task/World-Cup-group-stage/Elena/world-cup-group-stage.elena @@ -27,7 +27,7 @@ public singleton program { var records := new int[]{0,0,0,0}; - for(int i := 0, i < 6, i += 1) + for(int i := 0; i < 6; i += 1) { var r := results[i]; r => @@ -41,7 +41,7 @@ public singleton program records := records.ascendant(); - for(int i := 0, i <= 3, i += 1) + for(int i := 0; i <= 3; i += 1) { points[i][records[i]] := points[i][records[i]] + 1 } diff --git a/Task/World-Cup-group-stage/Wren/world-cup-group-stage.wren b/Task/World-Cup-group-stage/Wren/world-cup-group-stage.wren index 0adaabbf76..746ceb198a 100644 --- a/Task/World-Cup-group-stage/Wren/world-cup-group-stage.wren +++ b/Task/World-Cup-group-stage/Wren/world-cup-group-stage.wren @@ -1,5 +1,5 @@ -import "/fmt" for Conv, Fmt -import "/sort" for Sort +import "./fmt" for Conv, Fmt +import "./sort" for Sort var games = ["12", "13", "14", "23", "24", "34"] var results = "000000" diff --git a/Task/Write-entire-file/Forth/write-entire-file.fth b/Task/Write-entire-file/Forth/write-entire-file.fth new file mode 100644 index 0000000000..a0a4e56f9e --- /dev/null +++ b/Task/Write-entire-file/Forth/write-entire-file.fth @@ -0,0 +1,4 @@ +: >file ( string len filename len -- ) + w/o create-file throw dup >r write-file throw r> close-file throw ; + +s" This is a string." s" file.txt" >file diff --git a/Task/Write-float-arrays-to-a-text-file/Wren/write-float-arrays-to-a-text-file.wren b/Task/Write-float-arrays-to-a-text-file/Wren/write-float-arrays-to-a-text-file.wren index c253ebcfc5..0a4cb86a2d 100644 --- a/Task/Write-float-arrays-to-a-text-file/Wren/write-float-arrays-to-a-text-file.wren +++ b/Task/Write-float-arrays-to-a-text-file/Wren/write-float-arrays-to-a-text-file.wren @@ -1,5 +1,5 @@ import "io" for File -import "/fmt" for Fmt +import "./fmt" for Fmt var x = [1, 2, 3, 1e11] var y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791] diff --git a/Task/Write-to-Windows-event-log/Wren/write-to-windows-event-log-1.wren b/Task/Write-to-Windows-event-log/Wren/write-to-windows-event-log-1.wren index 0968136204..6f1b130dc7 100644 --- a/Task/Write-to-Windows-event-log/Wren/write-to-windows-event-log-1.wren +++ b/Task/Write-to-Windows-event-log/Wren/write-to-windows-event-log-1.wren @@ -1,4 +1,4 @@ -/* write_to_windows_event_log.wren */ +/* Write_to_Windows_event_log.wren */ class Windows { foreign static eventCreate(args) diff --git a/Task/Write-to-Windows-event-log/Wren/write-to-windows-event-log-2.wren b/Task/Write-to-Windows-event-log/Wren/write-to-windows-event-log-2.wren index d83af50e67..04a4756273 100644 --- a/Task/Write-to-Windows-event-log/Wren/write-to-windows-event-log-2.wren +++ b/Task/Write-to-Windows-event-log/Wren/write-to-windows-event-log-2.wren @@ -1,3 +1,5 @@ +/* gcc Write_to_Windows_event_log.c -o Write_to_Windows_event_log -lwren -lm */ + #include #include #include @@ -65,7 +67,7 @@ int main(int argc, char **argv) { config.bindForeignMethodFn = &bindForeignMethod; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "write_to_windows_event_log.wren"; + const char* fileName = "Write_to_Windows_event_log.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/XML-Input/Swift/xml-input-1.swift b/Task/XML-Input/Swift/xml-input-1.swift new file mode 100644 index 0000000000..cf596f40a9 --- /dev/null +++ b/Task/XML-Input/Swift/xml-input-1.swift @@ -0,0 +1,32 @@ +import Foundation + +let xmlString = """ + + + + + + + + + +""" +if let xmlData = xmlString.data(using: .utf8) { + do { + let doc = try XMLDocument(data: xmlData) + print("Using XPath:") + for node in try doc.nodes(forXPath: "/Students/Student/@Name") { + guard let name = node.stringValue else { continue } + print(name) + } + print("Using node walk") + if let root = doc.rootElement() { + for child in root.elements(forName: "Student") { + guard let name = child.attribute(forName: "Name")?.stringValue else { continue } + print(name) + } + } + } catch { + debugPrint(error) + } +} diff --git a/Task/XML-Input/Swift/xml-input-2.swift b/Task/XML-Input/Swift/xml-input-2.swift new file mode 100644 index 0000000000..ed809e34c6 --- /dev/null +++ b/Task/XML-Input/Swift/xml-input-2.swift @@ -0,0 +1,13 @@ +~ % ./XMLInput +Using XPath: +April +Bob +Chad +Dave +Émily +Using node walk +April +Bob +Chad +Dave +Émily diff --git a/Task/XML-Input/Wren/xml-input-1.wren b/Task/XML-Input/Wren/xml-input-1.wren index fac11e8d92..0cc8c517a6 100644 --- a/Task/XML-Input/Wren/xml-input-1.wren +++ b/Task/XML-Input/Wren/xml-input-1.wren @@ -1,5 +1,5 @@ -import "/pattern" for Pattern -import "/fmt" for Conv +import "./pattern" for Pattern +import "./fmt" for Conv var xml = " diff --git a/Task/XML-XPath/Wren/xml-xpath-1.wren b/Task/XML-XPath/Wren/xml-xpath-1.wren index ae2571ce47..835ede2ac7 100644 --- a/Task/XML-XPath/Wren/xml-xpath-1.wren +++ b/Task/XML-XPath/Wren/xml-xpath-1.wren @@ -1,4 +1,4 @@ -import "/pattern" for Pattern +import "./pattern" for Pattern var doc = """ diff --git a/Task/Xiaolin-Wus-line-algorithm/MATLAB/xiaolin-wus-line-algorithm.m b/Task/Xiaolin-Wus-line-algorithm/MATLAB/xiaolin-wus-line-algorithm.m new file mode 100644 index 0000000000..0a0bc177a1 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/MATLAB/xiaolin-wus-line-algorithm.m @@ -0,0 +1,79 @@ +clear all;close all;clc; +% Example usage: +img = ones(250, 250); +img = drawline(img, 8, 8, 192, 154); +imshow(img); % Display the image + +function img = drawline(img, x0, y0, x1, y1) + function f = fpart(x) + f = mod(x, 1); + end + + function rf = rfpart(x) + rf = 1 - fpart(x); + end + + steep = abs(y1 - y0) > abs(x1 - x0); + + if steep + [x0, y0] = deal(y0, x0); + [x1, y1] = deal(y1, x1); + end + if x0 > x1 + [x0, x1] = deal(x1, x0); + [y0, y1] = deal(y1, y0); + end + + dx = x1 - x0; + dy = y1 - y0; + grad = dy / dx; + + if dx == 0 + grad = 1.0; + end + + % handle first endpoint + xend = round(x0); + yend = y0 + grad * (xend - x0); + xgap = rfpart(x0 + 0.5); + xpxl1 = xend; + ypxl1 = floor(yend); + + if steep + img(ypxl1, xpxl1) = rfpart(yend) * xgap; + img(ypxl1+1, xpxl1) = fpart(yend) * xgap; + else + img(xpxl1, ypxl1 ) = rfpart(yend) * xgap; + img(xpxl1, ypxl1+1) = fpart(yend) * xgap; + end + intery = yend + grad; % first y-intersection for the main loop + + % handle second endpoint + xend = round(x1); + yend = y1 + grad * (xend - x1); + xgap = fpart(x1 + 0.5); + xpxl2 = xend; + ypxl2 = floor(yend); + if steep + img(ypxl2, xpxl2) = rfpart(yend) * xgap; + img(ypxl2+1, xpxl2) = fpart(yend) * xgap; + else + img(xpxl2, ypxl2 ) = rfpart(yend) * xgap; + img(xpxl2, ypxl2+1) = fpart(yend) * xgap; + end + + % main loop + if steep + for x = (xpxl1+1):(xpxl2-1) + img(floor(intery), x) = rfpart(intery); + img(floor(intery)+1, x) = fpart(intery); + intery = intery + grad; + end + else + for x = (xpxl1+1):(xpxl2-1) + img(x, floor(intery) ) = rfpart(intery); + img(x, floor(intery)+1) = fpart(intery); + intery = intery + grad; + end + end +end diff --git a/Task/Y-combinator/ALGOL-68/y-combinator-2.alg b/Task/Y-combinator/ALGOL-68/y-combinator-2.alg index f305ee5b71..08b088eab3 100644 --- a/Task/Y-combinator/ALGOL-68/y-combinator-2.alg +++ b/Task/Y-combinator/ALGOL-68/y-combinator-2.alg @@ -8,69 +8,85 @@ MODE F = PROC( INT ) INT ; MODE X = PROC( X ) F ; -# Y_combinator = func_gen => ( x => x( x ) )( x => func_gen( arg => x( x )( arg ) ) ) ; # +# +Y_combinator = + func_gen => ( x => x( x ) )( x => func_gen( arg => x( x )( arg ) ) ) +# PROC y combinator = ( PROC( F ) F func gen ) F: - ( ( X x ) F: x( x ) ) +( ( X x ) F: x( x ) ) + ( ( - ( - ( PROC( F ) F func gen , X x ) F: - func gen( ( ( X x , INT arg ) INT: x( x )( arg ) )( x , ) ) - ) ( func gen , ) - ) + ( PROC( F ) F func gen , X x ) F: + func gen( ( ( X x , INT arg ) INT: x( x )( arg ) )( x , ) ) + )( func gen , ) + ) ; # - factorial = - Y_combinator( fac => ( n => ( ( n === 0 ) ? 1 : n * fac( n - 1 ) ) ) ) - ; +fac_gen = fac => (n => ( ( n === 0 ) ? 1 : n * fac( n - 1 ) ) ) # -F factorial = - y combinator( - ( F fac ) F: - ( ( F fac , INT n ) INT: IF n = 0 THEN 1 ELSE n * fac( n - 1 ) FI ) - ( fac , ) - ) +PROC fac gen = ( F fac ) F: +( ( F fac , INT n ) INT: IF n = 0 THEN 1 ELSE n * fac( n - 1 ) FI )( fac , ) ; # - fibonacci = - Y_combinator( - fib => ( n => ( ( n === 0 ) ? 0 : ( n === 1 ) ? 1 : fib( n - 2 ) + fib( n - 1 ) ) ) - ) - ; +factorial = Y_combinator( fac_gen ) # -F fibonacci = - y combinator( - ( F fib ) F: - ( ( F fib , INT n ) INT: CASE n IN 1 , 1 OUT fib( n - 2 ) + fib( n - 1 ) ESAC ) - ( fib , ) - ) +F factorial = y combinator( fac gen ) ; + + +# +fib_gen = + fib => + ( n => ( ( n === 0 ) ? 0 : ( n === 1 ) ? 1 : fib( n - 2 ) + fib( n - 1 ) ) ) +# + +PROC fib gen = ( F fib ) F: +( + ( F fib , INT n ) INT: + CASE n + 1 IN 0 , 1 OUT fib( n - 2 ) + fib( n - 1 ) ESAC +)( fib , ) ; -# for ( i = 1 ; i <= 12 ; i++) { console.log( " " + factorial( i ) ) ; } # +# +fibonacci = Y_combinator( fib_gen ) +# + +F fibonacci = y combinator( fib gen ) ; + + +# +for ( i = 1 ; i <= 12 ; i++) { process.stdout.write( " " + factorial( i ) ) } +# INT nofacs = 12 ; -print( ( "The first " , whole( nofacs , 0 ) , " factorials." , newline ) ) ; +printf( ( $ l , "Here are the first " , g( 0 ) , " factorials." , l $ , nofacs ) ) ; FOR i TO nofacs DO - print( whole( factorial( i ) , -11 ) ) + printf( ( $ " " , g( 0 ) $ , factorial( i ) ) ) OD ; +print( newline ) ; -print( ( newline , newline ) ) ; -# for ( i = 1 ; i <= 12 ; i++) { console.log( " " + fibonacci( i ) ) ; } # +# +for ( i = 1 ; i <= 12 ; i++) { process.stdout.write( " " + fibonacci( i ) ) } +# INT nofibs = 12 ; -print( ( "The first " , whole( nofibs , 0 ) , " fibonacci numbers." , newline ) ) ; +printf( ( + $ l , "Here are the first " , g( 0 ) , " fibonacci numbers." , l $ +, nofibs + ) ) +; FOR i TO nofibs DO - print( whole( fibonacci( i ) , -11 ) ) + printf( ( $ " " , g( 0 ) $ , fibonacci( i ) ) ) OD ; print( newline ) diff --git a/Task/Y-combinator/Bruijn/y-combinator.bruijn b/Task/Y-combinator/Bruijn/y-combinator.bruijn new file mode 100644 index 0000000000..95a985b3e9 --- /dev/null +++ b/Task/Y-combinator/Bruijn/y-combinator.bruijn @@ -0,0 +1,15 @@ +:import std/Number . + +# sage bird combinator +y [[1 (0 0)] [1 (0 0)]] + +# factorial using y +factorial y [[=?0 (+1) (0 ⋅ (1 --0))]] + +:test ((factorial (+6)) =? (+720)) ([[1]]) + +# (very slow) fibonacci using y +fibonacci y [[0 (i => (i <= 1) ? i : (f(i-1) + f(i-2)) )); - var fact := YCombinator.fix:(f => (i => (i == 0) ? 1 : (f(i-1) * i) )); + var fib := YCombinator.fix::(f => (i => (i <= 1) ? i : (f(i-1) + f(i-2)) )); + var fact := YCombinator.fix::(f => (i => (i == 0) ? 1 : (f(i-1) * i) )); console.printLine("fib(10)=",fib(10)); console.printLine("fact(10)=",fact(10)); diff --git a/Task/Y-combinator/F-Sharp/y-combinator-1.fs b/Task/Y-combinator/F-Sharp/y-combinator-1.fs index 570693a413..6b5376cb55 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-1.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-1.fs @@ -1,35 +1,6 @@ -type 'a mu = Roll of ('a mu -> 'a) // ' fixes ease syntax colouring confusion with - -let unroll (Roll x) = x -// val unroll : 'a mu -> ('a mu -> 'a) - -// As with most of the strict (non-deferred or non-lazy) languages, -// this is the Z-combinator with the additional 'a' parameter... -let fix f = let g = fun x a -> f (unroll x x) a in g (Roll g) -// val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = - -// Although true to the factorial definition, the -// recursive call is not in tail call position, so can't be optimized -// and will overflow the call stack for the recursive calls for large ranges... -//let fac = fix (fun f n -> if n < 2 then 1I else bigint n * f (n - 1)) -// val fac : (int -> BigInteger) = - -// much better progressive calculation in tail call position... -let fac = fix (fun f n i -> if i < 2 then n else f (bigint i * n) (i - 1)) <| 1I -// val fac : (int -> BigInteger) = - -// Although true to the definition of Fibonacci numbers, -// this can't be tail call optimized and recursively repeats calculations -// for a horrendously inefficient exponential performance fib function... -// let fib = fix (fun fnc n -> if n < 2 then n else fnc (n - 1) + fnc (n - 2)) -// val fib : (int -> BigInteger) = - -// much better progressive calculation in tail call position... -let fib = fix (fun fnc f s i -> if i < 2 then f else fnc s (f + s) (i - 1)) 1I 1I -// val fib : (int -> BigInteger) = - -[] -let main argv = - fac 10 |> printfn "%A" // prints 3628800 - fib 10 |> printfn "%A" // prints 55 - 0 // return an integer exit code +// Y combinator. Nigel Galloway: March 5th., 2024 +type Y<'T> = { eval: Y<'T> -> ('T -> 'T) } +let Y n g=let l = { eval = fun l -> fun x -> (n (l.eval l)) x } in (l.eval l) g +let fibonacci=function 0->1 |x->let fibonacci f= function 0->0 |1->1 |x->f(x - 1) + f(x - 2) in Y fibonacci x +let factorial n=let factorial f=function 0->1 |x->x*f(x-1) in Y factorial n +printfn "fibonacci 10=%d\nfactorial 5=%d" (fibonacci 10) (factorial 5) diff --git a/Task/Y-combinator/F-Sharp/y-combinator-2.fs b/Task/Y-combinator/F-Sharp/y-combinator-2.fs index c9fbe39fbc..570693a413 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-2.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-2.fs @@ -1,40 +1,35 @@ -// same as previous... type 'a mu = Roll of ('a mu -> 'a) // ' fixes ease syntax colouring confusion with -// same as previous... let unroll (Roll x) = x // val unroll : 'a mu -> ('a mu -> 'a) -// break race condition with some deferred execution - laziness... -let fix f = let g = fun x -> f <| fun() -> (unroll x x) in g (Roll g) -// val fix : ((unit -> 'a) -> 'a -> 'a) = +// As with most of the strict (non-deferred or non-lazy) languages, +// this is the Z-combinator with the additional 'a' parameter... +let fix f = let g = fun x a -> f (unroll x x) a in g (Roll g) +// val fix : (('a -> 'b) -> 'a -> 'b) -> 'a -> 'b = -// same efficient version of factorial functionb with added deferred execution... -let fac = fix (fun f n i -> if i < 2 then n else f () (bigint i * n) (i - 1)) <| 1I +// Although true to the factorial definition, the +// recursive call is not in tail call position, so can't be optimized +// and will overflow the call stack for the recursive calls for large ranges... +//let fac = fix (fun f n -> if n < 2 then 1I else bigint n * f (n - 1)) // val fac : (int -> BigInteger) = -// same efficient version of Fibonacci function with added deferred execution... -let fib = fix (fun fnc f s i -> if i < 2 then f else fnc () s (f + s) (i - 1)) 1I 1I +// much better progressive calculation in tail call position... +let fac = fix (fun f n i -> if i < 2 then n else f (bigint i * n) (i - 1)) <| 1I +// val fac : (int -> BigInteger) = + +// Although true to the definition of Fibonacci numbers, +// this can't be tail call optimized and recursively repeats calculations +// for a horrendously inefficient exponential performance fib function... +// let fib = fix (fun fnc n -> if n < 2 then n else fnc (n - 1) + fnc (n - 2)) // val fib : (int -> BigInteger) = -// given the following definition for an infinite Co-Inductive Stream (CIS)... -type CIS<'a> = CIS of 'a * (unit -> CIS<'a>) // ' fix formatting - -// Using a double Y-Combinator recursion... -// defines a continuous stream of Fibonacci numbers; there are other simpler ways, -// this way implements recursion by using the Y-combinator, although it is -// much slower than other ways due to the many additional function calls, -// it demonstrates something that can't be done with the Z-combinator... -let fibs() = - let fbsgen = fix (fun fnc (CIS((f, s), rest)) -> - CIS((s, f + s), fun() -> fnc () <| rest())) - Seq.unfold (fun (CIS((v, _), rest)) -> Some(v, rest())) - <| fix (fun cis -> fbsgen (CIS((1I, 0I), cis))) // cis is a lazy thunk! +// much better progressive calculation in tail call position... +let fib = fix (fun fnc f s i -> if i < 2 then f else fnc s (f + s) (i - 1)) 1I 1I +// val fib : (int -> BigInteger) = [] let main argv = fac 10 |> printfn "%A" // prints 3628800 fib 10 |> printfn "%A" // prints 55 - fibs() |> Seq.take 20 |> Seq.iter (printf "%A ") - printfn "" 0 // return an integer exit code diff --git a/Task/Y-combinator/F-Sharp/y-combinator-3.fs b/Task/Y-combinator/F-Sharp/y-combinator-3.fs index 67c1a271c4..c9fbe39fbc 100644 --- a/Task/Y-combinator/F-Sharp/y-combinator-3.fs +++ b/Task/Y-combinator/F-Sharp/y-combinator-3.fs @@ -1,4 +1,40 @@ -let rec fix f = f <| fun() -> fix f -// val fix : f:((unit -> 'a) -> 'a) -> 'a +// same as previous... +type 'a mu = Roll of ('a mu -> 'a) // ' fixes ease syntax colouring confusion with -// the application of this true Y-combinator is the same as for the above non function recursive version. +// same as previous... +let unroll (Roll x) = x +// val unroll : 'a mu -> ('a mu -> 'a) + +// break race condition with some deferred execution - laziness... +let fix f = let g = fun x -> f <| fun() -> (unroll x x) in g (Roll g) +// val fix : ((unit -> 'a) -> 'a -> 'a) = + +// same efficient version of factorial functionb with added deferred execution... +let fac = fix (fun f n i -> if i < 2 then n else f () (bigint i * n) (i - 1)) <| 1I +// val fac : (int -> BigInteger) = + +// same efficient version of Fibonacci function with added deferred execution... +let fib = fix (fun fnc f s i -> if i < 2 then f else fnc () s (f + s) (i - 1)) 1I 1I +// val fib : (int -> BigInteger) = + +// given the following definition for an infinite Co-Inductive Stream (CIS)... +type CIS<'a> = CIS of 'a * (unit -> CIS<'a>) // ' fix formatting + +// Using a double Y-Combinator recursion... +// defines a continuous stream of Fibonacci numbers; there are other simpler ways, +// this way implements recursion by using the Y-combinator, although it is +// much slower than other ways due to the many additional function calls, +// it demonstrates something that can't be done with the Z-combinator... +let fibs() = + let fbsgen = fix (fun fnc (CIS((f, s), rest)) -> + CIS((s, f + s), fun() -> fnc () <| rest())) + Seq.unfold (fun (CIS((v, _), rest)) -> Some(v, rest())) + <| fix (fun cis -> fbsgen (CIS((1I, 0I), cis))) // cis is a lazy thunk! + +[] +let main argv = + fac 10 |> printfn "%A" // prints 3628800 + fib 10 |> printfn "%A" // prints 55 + fibs() |> Seq.take 20 |> Seq.iter (printf "%A ") + printfn "" + 0 // return an integer exit code diff --git a/Task/Y-combinator/F-Sharp/y-combinator-4.fs b/Task/Y-combinator/F-Sharp/y-combinator-4.fs new file mode 100644 index 0000000000..67c1a271c4 --- /dev/null +++ b/Task/Y-combinator/F-Sharp/y-combinator-4.fs @@ -0,0 +1,4 @@ +let rec fix f = f <| fun() -> fix f +// val fix : f:((unit -> 'a) -> 'a) -> 'a + +// the application of this true Y-combinator is the same as for the above non function recursive version. diff --git a/Task/Y-combinator/Forth/y-combinator-1.fth b/Task/Y-combinator/Forth/y-combinator-1.fth index f6c5c3617b..8d360e2c43 100644 --- a/Task/Y-combinator/Forth/y-combinator-1.fth +++ b/Task/Y-combinator/Forth/y-combinator-1.fth @@ -1,12 +1,9 @@ -\ Address of an xt. -variable 'xt -\ Make room for an xt. -: xt, ( -- ) here 'xt ! 1 cells allot ; -\ Store xt. -: !xt ( xt -- ) 'xt @ ! ; -\ Compile fetching the xt. -: @xt, ( -- ) 'xt @ postpone literal postpone @ ; -\ Compile the Y combinator. -: y, ( xt1 -- xt2 ) >r :noname @xt, r> compile, postpone ; ; -\ Make a new instance of the Y combinator. -: y ( xt1 -- xt2 ) xt, y, dup !xt ; +\ Begin of approach. Depends on 'latestxt' word of GForth implementation. + +: self-parameter ( xt -- xt' ) + >r :noname latestxt postpone literal r> compile, postpone ; +; +: Y ( xt -- xt' ) + dup self-parameter 2>r + :noname 2r> postpone literal compile, postpone ; +; diff --git a/Task/Y-combinator/Forth/y-combinator-2.fth b/Task/Y-combinator/Forth/y-combinator-2.fth index 3b00047b30..5c7757e609 100644 --- a/Task/Y-combinator/Forth/y-combinator-2.fth +++ b/Task/Y-combinator/Forth/y-combinator-2.fth @@ -1,7 +1,6 @@ -\ Factorial -10 :noname ( u1 xt -- u2 ) over ?dup if 1- swap execute * else 2drop 1 then ; -y execute . 3628800 ok +\ Fibonnacci test +10 :noname ( u xt -- u' ) over 2 < if drop exit then >r 1- dup r@ execute swap 1- r> execute + ; Y execute . 55 ok +\ Factorial test +10 :noname ( u xt -- u' ) over 2 < if 2drop 1 exit then over 1- swap execute * ; Y execute . 3628800 ok -\ Fibonacci -10 :noname ( u1 xt -- u2 ) over 2 < if drop else >r 1- dup r@ execute swap 1- r> execute + then ; -y execute . 55 ok +\ End of approach. diff --git a/Task/Y-combinator/Forth/y-combinator-3.fth b/Task/Y-combinator/Forth/y-combinator-3.fth new file mode 100644 index 0000000000..f6c5c3617b --- /dev/null +++ b/Task/Y-combinator/Forth/y-combinator-3.fth @@ -0,0 +1,12 @@ +\ Address of an xt. +variable 'xt +\ Make room for an xt. +: xt, ( -- ) here 'xt ! 1 cells allot ; +\ Store xt. +: !xt ( xt -- ) 'xt @ ! ; +\ Compile fetching the xt. +: @xt, ( -- ) 'xt @ postpone literal postpone @ ; +\ Compile the Y combinator. +: y, ( xt1 -- xt2 ) >r :noname @xt, r> compile, postpone ; ; +\ Make a new instance of the Y combinator. +: y ( xt1 -- xt2 ) xt, y, dup !xt ; diff --git a/Task/Y-combinator/Forth/y-combinator-4.fth b/Task/Y-combinator/Forth/y-combinator-4.fth new file mode 100644 index 0000000000..3b00047b30 --- /dev/null +++ b/Task/Y-combinator/Forth/y-combinator-4.fth @@ -0,0 +1,7 @@ +\ Factorial +10 :noname ( u1 xt -- u2 ) over ?dup if 1- swap execute * else 2drop 1 then ; +y execute . 3628800 ok + +\ Fibonacci +10 :noname ( u1 xt -- u2 ) over 2 < if drop else >r 1- dup r@ execute swap 1- r> execute + then ; +y execute . 55 ok diff --git a/Task/Y-combinator/R/y-combinator-1.r b/Task/Y-combinator/R/y-combinator-1.r index d355b170fd..e6c6a42fd4 100644 --- a/Task/Y-combinator/R/y-combinator-1.r +++ b/Task/Y-combinator/R/y-combinator-1.r @@ -1,3 +1,6 @@ -Y <- function(f) { - (function(x) { (x)(x) })( function(y) { f( (function(a) {y(y)})(a) ) } ) -} +#' Y = λf.(λs.ss)(λx.f(xx)) +#' Z = λf.(λs.ss)(λx.f(λz.(xx)z)) +#' + +fixp.Y <- \ (f) (\ (x) (x) (x)) (\ (y) (f) ((y) (y))) # y-combinator +fixp.Z <- \ (f) (\ (x) (x) (x)) (\ (y) (f) (\ (...) (y) (y) (...))) # z-combinator diff --git a/Task/Y-combinator/R/y-combinator-2.r b/Task/Y-combinator/R/y-combinator-2.r index 875df436bb..aea36319b3 100644 --- a/Task/Y-combinator/R/y-combinator-2.r +++ b/Task/Y-combinator/R/y-combinator-2.r @@ -1,17 +1,5 @@ -fac <- function(f) { - function(n) { - if (n<2) - 1 - else - n*f(n-1) - } -} +fac.y <- fixp.Y (\ (f) \ (n) if (n<2) 1 else n*f(n-1)) +fac.y(9) # [1] 362880 -fib <- function(f) { - function(n) { - if (n <= 1) - n - else - f(n-1) + f(n-2) - } -} +fib.y <- fixp.Y (\ (f) \ (n) if (n <= 1) n else f(n-1) + f(n-2)) +fib.y(9) # [1] 34 diff --git a/Task/Y-combinator/R/y-combinator-3.r b/Task/Y-combinator/R/y-combinator-3.r index 5ea7ce779c..7cb4875133 100644 --- a/Task/Y-combinator/R/y-combinator-3.r +++ b/Task/Y-combinator/R/y-combinator-3.r @@ -1,2 +1,5 @@ -for(i in 1:9) print(Y(fac)(i)) -for(i in 1:9) print(Y(fib)(i)) +fac.z <- fixp.Z (\ (f) \ (n) if (n<2) 1 else n*f(n-1)) +fac.z(9) # [1] 362880 + +fib.z <- fixp.Z (\ (f) \ (n) if (n <= 1) n else f(n-1) + f(n-2)) +fib.z(9) # [1] 34 diff --git a/Task/Yahoo-search-interface/Wren/yahoo-search-interface-1.wren b/Task/Yahoo-search-interface/Wren/yahoo-search-interface-1.wren index 39c064989d..d85e59c19c 100644 --- a/Task/Yahoo-search-interface/Wren/yahoo-search-interface-1.wren +++ b/Task/Yahoo-search-interface/Wren/yahoo-search-interface-1.wren @@ -1,4 +1,4 @@ -/* yahoo_search_interface.wren */ +/* Yahoo_search_interface.wren */ import "./pattern" for Pattern diff --git a/Task/Yahoo-search-interface/Wren/yahoo-search-interface-2.wren b/Task/Yahoo-search-interface/Wren/yahoo-search-interface-2.wren index 453d2b0e5f..61a5a04cb4 100644 --- a/Task/Yahoo-search-interface/Wren/yahoo-search-interface-2.wren +++ b/Task/Yahoo-search-interface/Wren/yahoo-search-interface-2.wren @@ -1,4 +1,4 @@ -/* gcc yahoo_search_interface.c -o yahoo_search_interface -lcurl -lwren -lm */ +/* gcc Yahoo_search_interface.c -o Yahoo_search_interface -lcurl -lwren -lm */ #include #include @@ -172,7 +172,7 @@ int main(int argc, char **argv) { config.loadModuleFn = &loadModule; WrenVM* vm = wrenNewVM(&config); const char* module = "main"; - const char* fileName = "yahoo_search_interface.wren"; + const char* fileName = "Yahoo_search_interface.wren"; char *script = readFile(fileName); WrenInterpretResult result = wrenInterpret(vm, module, script); switch (result) { diff --git a/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy b/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy new file mode 100644 index 0000000000..00de4fa265 --- /dev/null +++ b/Task/Yellowstone-sequence/EasyLang/yellowstone-sequence.easy @@ -0,0 +1,38 @@ +func gcd a b . + if b = 0 + return a + . + return gcd b (a mod b) +. +proc remove_at i . a[] . + for j = i + 1 to len a[] + a[j - 1] = a[j] + . + len a[] -1 +. +proc yellowstone count . yellow[] . + yellow[] = [ 1 2 3 ] + num = 4 + while len yellow[] < count + for i to len notyellow[] + test = notyellow[i] + if gcd yellow[-2] test > 1 and gcd yellow[-1] test = 1 + break 1 + . + . + if i <= len notyellow[] + yellow[] &= notyellow[i] + remove_at i notyellow[] + else + while gcd yellow[-2] num <= 1 or gcd yellow[-1] num <> 1 + notyellow[] &= num + num += 1 + . + yellow[] &= num + num += 1 + . + . +. +print "First 30 values in the yellowstone sequence:" +yellowstone 30 yellow[] +print yellow[] diff --git a/Task/Yellowstone-sequence/PARI-GP/yellowstone-sequence.parigp b/Task/Yellowstone-sequence/PARI-GP/yellowstone-sequence.parigp new file mode 100644 index 0000000000..a46e477f94 --- /dev/null +++ b/Task/Yellowstone-sequence/PARI-GP/yellowstone-sequence.parigp @@ -0,0 +1,29 @@ +yellowstone(n) = { + my(a=3, o=2, u=[]); + if(n<3, return(n)); \\ Base case: return n if it is less than 3 + print1("1, 2"); \\ Print initial values + + for(i = 4, n, \\ Iterate from 4 to n + print1(", "a); \\ Print current value of a + u = setunion(u, Set(a)); \\ Add a to the set u + + \\ Remove consecutive elements from u + while(#u > 1 && u[2] == u[1] + 1, + u = vecextract(u, "^1") + ); + + \\ Find next value of a + for(k = u[1] + 1, 1e10, + if(gcd(k, o) <= 1, next); \\ Skip if gcd(k, o) is greater than 1 + if(setsearch(u, k), next); \\ Skip if k is in set u + if(gcd(k, a) != 1, next); \\ Skip if gcd(k, a) is not 1 + o = a; \\ Update o to current a + a = k; \\ Update a to k + break + ) + ); + + a \\ Return the final value of a +} + +yellowstone(20); \\ Call the function with n = 20 diff --git a/Task/Yellowstone-sequence/Scala/yellowstone-sequence.scala b/Task/Yellowstone-sequence/Scala/yellowstone-sequence.scala new file mode 100644 index 0000000000..c6c1a51819 --- /dev/null +++ b/Task/Yellowstone-sequence/Scala/yellowstone-sequence.scala @@ -0,0 +1,42 @@ +import scala.util.control.Breaks._ + + +object YellowstoneSequence extends App { + + println(s"First 30 values in the yellowstone sequence:\n${yellowstoneSequence(30)}") + + def yellowstoneSequence(sequenceCount: Int): List[Int] = { + var yellowstoneList = List(1, 2, 3) + var num = 4 + var notYellowstoneList = List[Int]() + + while (yellowstoneList.size < sequenceCount) { + val foundIndex = notYellowstoneList.indexWhere(test => + gcd(yellowstoneList(yellowstoneList.size - 2), test) > 1 && + gcd(yellowstoneList.last, test) == 1 + ) + + if (foundIndex >= 0) { + yellowstoneList = yellowstoneList :+ notYellowstoneList(foundIndex) + notYellowstoneList = notYellowstoneList.patch(foundIndex, Nil, 1) + } else { + breakable({ + while (true) { + if (gcd(yellowstoneList(yellowstoneList.size - 2), num) > 1 && + gcd(yellowstoneList.last, num) == 1) { + yellowstoneList = yellowstoneList :+ num + num += 1 + // break the inner while loop + break + } + notYellowstoneList = notYellowstoneList :+ num + num += 1 + } + }); + } + } + yellowstoneList + } + + def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b) +} diff --git a/Task/Yellowstone-sequence/Wren/yellowstone-sequence.wren b/Task/Yellowstone-sequence/Wren/yellowstone-sequence.wren index 49a41fa321..66510767ee 100644 --- a/Task/Yellowstone-sequence/Wren/yellowstone-sequence.wren +++ b/Task/Yellowstone-sequence/Wren/yellowstone-sequence.wren @@ -1,4 +1,4 @@ -import "/math" for Int +import "./math" for Int var yellowstone = Fn.new { |n| var m = {} diff --git a/Task/Yin-and-yang/Dart/yin-and-yang-2.dart b/Task/Yin-and-yang/Dart/yin-and-yang-2.dart index 59488f37dc..d28abd0b2a 100644 --- a/Task/Yin-and-yang/Dart/yin-and-yang-2.dart +++ b/Task/Yin-and-yang/Dart/yin-and-yang-2.dart @@ -1,4 +1,4 @@ -import 'dart:math'; +import 'dart:math' show pi; import 'package:flutter/material.dart'; Path yinYang(double r, double x, double y, [double th = 1.0]) { @@ -13,13 +13,7 @@ Path yinYang(double r, double x, double y, [double th = 1.0]) { ..addArc(cR(-r / 2, r / 2), pi / 2, -pi); } -void main() => runApp(const MainApp()); - -class MainApp extends StatelessWidget { - const MainApp({super.key}); - @override - Widget build(BuildContext context) => CustomPaint(painter: YinYangPainter()); -} +void main() => runApp(CustomPaint(painter: YinYangPainter())); class YinYangPainter extends CustomPainter { @override diff --git a/Task/Yin-and-yang/Dart/yin-and-yang-3.dart b/Task/Yin-and-yang/Dart/yin-and-yang-3.dart index 63a279e248..df220edeb7 100644 --- a/Task/Yin-and-yang/Dart/yin-and-yang-3.dart +++ b/Task/Yin-and-yang/Dart/yin-and-yang-3.dart @@ -1,30 +1,20 @@ import 'package:flutter/material.dart'; -const colors = [Colors.black, Colors.white]; +const color = [Colors.black, Colors.white]; -Container cR(int iClr, double r, {Widget? child, Clip clip = Clip.none}) => Container( - width: r * 2, - height: r * 2, - decoration: ShapeDecoration(color: colors[iClr], shape: const CircleBorder()), - clipBehavior: clip, - child: Center(child: child)); +Widget cR(int iColor, double r, {Widget? child}) => DecoratedBox( + decoration: BoxDecoration(color: color[iColor], shape: BoxShape.circle), + child: SizedBox.square(dimension: r * 2, child: Center(child: child))); -Container yinYang(double r, [double th = 1.0]) => cR(0, r + th, - clip: Clip.hardEdge, - child: cR(1, r, - child: Stack(alignment: Alignment.center, children: [ - Container(color: colors[0], margin: EdgeInsets.only(left: r)), - Column(children: List.generate(2, (i) => cR(1 - i, r / 2, child: cR(i, r / 6)))) - ]))); +Widget yinYang(double r, [double th = 1.0]) => Padding( + padding: const EdgeInsets.all(5), + child: ClipOval( + child: cR(0, r + th, + child: cR(1, r, + child: Stack(alignment: Alignment.center, children: [ + Container(color: color[0], margin: EdgeInsets.only(left: r)), + Column(children: List.generate(2, (i) => cR(1 - i, r / 2, child: cR(i, r / 6)))) + ]))))); -void main() => runApp(const MainApp()); - -class MainApp extends StatelessWidget { - const MainApp({super.key}); - @override - Widget build(BuildContext context) => MaterialApp( - home: Container( - color: colors[1], - padding: const EdgeInsets.all(10), - child: Wrap(children: [yinYang(50), yinYang(20)]))); -} +void main() => runApp(MaterialApp( + home: ColoredBox(color: color[1], child: Wrap(children: [yinYang(50), yinYang(20)])))); diff --git a/Task/Yin-and-yang/EasyLang/yin-and-yang.easy b/Task/Yin-and-yang/EasyLang/yin-and-yang.easy new file mode 100644 index 0000000000..38961146b9 --- /dev/null +++ b/Task/Yin-and-yang/EasyLang/yin-and-yang.easy @@ -0,0 +1,20 @@ +proc circ r c . . + color c + circle r +. +proc yinyang x y r . . + move x y + circ 2 * r 000 + color 999 + circseg 2 * r 90 -90 + move x y - r + circ r 000 + circ r / 3 999 + move x y + r + circ r 999 + circ r / 3 000 +. +background 555 +clear +yinyang 20 20 6 +yinyang 50 60 14 diff --git a/Task/Zebra-puzzle/00-TASK.txt b/Task/Zebra-puzzle/00-TASK.txt index e8c16f4a83..24e087e978 100644 --- a/Task/Zebra-puzzle/00-TASK.txt +++ b/Task/Zebra-puzzle/00-TASK.txt @@ -9,12 +9,12 @@ It has several variants, one of them this: :#   The Dane drinks tea. :#   The green house is immediately to the left of the white house. :#   They drink coffee in the green house. -:#   The man who smokes Pall Mall has birds. +:#   The man who smokes Pall Mall has a bird. :#   In the yellow house they smoke Dunhill. :#   In the middle house they drink milk. :#   The Norwegian lives in the first house. -:#   The man who smokes Blend lives in the house next to the house with cats. -:#   In a house next to the house where they have a horse, they smoke Dunhill. +:#   The Blend-smoker lives in the house next to the house with a cat. +:#   In a house next to the house with a horse, they smoke Dunhill. :#   The man who smokes Blue Master drinks beer. :#   The German smokes Prince. :#   The Norwegian lives next to the blue house. diff --git a/Task/Zebra-puzzle/Python/zebra-puzzle-4.py b/Task/Zebra-puzzle/Python/zebra-puzzle-4.py index 98ddaee90f..df437fd76b 100644 --- a/Task/Zebra-puzzle/Python/zebra-puzzle-4.py +++ b/Task/Zebra-puzzle/Python/zebra-puzzle-4.py @@ -1,61 +1,185 @@ +''' +Improved version: Instead of simple variables (a, b), +more intelligible and readable (?) variables are employed. +''' +def doc1(): + ''' + There are five houses. + The English man lives in the red house. + The Swede has a dog. + The Dane drinks tea. + The green house is immediately to the left of the white house. + They drink coffee in the green house. + The man who smokes Pall Mall has a bird. + In the yellow house they smoke Dunhill. + In the middle house they drink milk. + The Norwegian lives in the first house. + The man who smokes Blend lives in the house next to the house with a cat. + In a house next to the house where they have a horse, they smoke Dunhill. + The man who smokes Blue Master drinks beer. + The German smokes Prince. + The Norwegian lives next to the blue house. + They drink water in a house next to the house where they smoke Blend. + + The solution: + + Nation: Norwegian Dane Englishman German Swede + Color: Yellow Blue Red Green White + Smoke: Dunhill Blend PallMall Prince BlueMaster + Pet: Cat Horse Bird Zebra Dog + Drink: Water Tea Milk Coffee Beer + ''' + +import os +print(os.system('cls') if os.name == 'nt' else os.system('clear')) + +print(doc1.__doc__) +input('') + from constraint import * -problem = Problem() +p = Problem() -Nation = ["Englishman", "Spaniard", "Japanese", "Ukrainian", "Norwegian" ] -Color = ["Red", "Green", "White", "Yellow", "Blue" ] -Smoke = ["Oldgold", "Kools", "Chesterfield", "Luckystrike", "Parliament"] -Pet = ["Dog", "Snails", "Fox", "Horse", "Zebra" ] -Drink = ["Tea", "Coffee", "Milk", "Orangejuice", "Water" ] +Nation = ['Englishman', 'Dane', 'German', 'Norwegian', 'Swede'] +Color = [ 'Blue', 'Green', 'Red', 'White', 'Yellow'] +Smoke = [ 'Blend', 'BlueMaster', 'Dunhill', 'PallMall', 'Prince'] +Pet = [ 'Bird', 'Cat', 'Dog', 'Horse', 'Zebra'] +Drink = [ 'Beer', 'Coffee', 'Milk', 'Tea', 'Water'] # add variables: house numbers 1 to 5 -problem.addVariables(Nation, range(1,5+1)) -problem.addVariables(Color, range(1,5+1)) -problem.addVariables(Smoke, range(1,5+1)) -problem.addVariables(Pet, range(1,5+1)) -problem.addVariables(Drink, range(1,5+1)) +p.addVariables(Nation, range(1,6)) +p.addVariables(Color, range(1,6)) +p.addVariables(Smoke, range(1,6)) +p.addVariables(Pet, range(1,6)) +p.addVariables(Drink, range(1,6)) # add constraint: the values in each list are exclusive -problem.addConstraint(AllDifferentConstraint(), Nation) -problem.addConstraint(AllDifferentConstraint(), Color) -problem.addConstraint(AllDifferentConstraint(), Smoke) -problem.addConstraint(AllDifferentConstraint(), Pet) -problem.addConstraint(AllDifferentConstraint(), Drink) +p.addConstraint(AllDifferentConstraint(), Nation) +p.addConstraint(AllDifferentConstraint(), Color) +p.addConstraint(AllDifferentConstraint(), Smoke) +p.addConstraint(AllDifferentConstraint(), Pet) +p.addConstraint(AllDifferentConstraint(), Drink) # add constraint: actual constraints -problem.addConstraint(lambda a, b: a == b, ["Englishman", "Red" ]) -problem.addConstraint(lambda a, b: a == b, ["Spaniard", "Dog" ]) -problem.addConstraint(lambda a, b: a == b, ["Green", "Coffee" ]) -problem.addConstraint(lambda a, b: a == b, ["Ukrainian", "Tea" ]) -problem.addConstraint(lambda a, b: a == b + 1, ["Green", "White" ]) -problem.addConstraint(lambda a, b: a == b, ["Oldgold", "Snails" ]) -problem.addConstraint(lambda a, b: a == b, ["Yellow", "Kools" ]) -problem.addConstraint(lambda a: a == 3, ["Milk" ]) -problem.addConstraint(lambda a: a == 1, ["Norwegian" ]) -problem.addConstraint(lambda a, b: a == b - 1 or a == b + 1, ["Chesterfield", "Fox" ]) -problem.addConstraint(lambda a, b: a == b - 1 or a == b + 1, ["Kools", "Horse" ]) -problem.addConstraint(lambda a, b: a == b, ["Luckystrike", "Orangejuice"]) -problem.addConstraint(lambda a, b: a == b, ["Japanese", "Parliament" ]) -problem.addConstraint(lambda a, b: a == b - 1 or a == b + 1, ["Norwegian", "Blue" ]) +# The English man lives in the red house. +p.addConstraint( + lambda house_englishman, red: + house_englishman is red, + ['Englishman', 'Red']) + +# The Swede has a dog. +p.addConstraint( + lambda pet_swede, dog: + pet_swede is dog, + ['Swede', 'Dog']) + +# The Dane drinks tea. +p.addConstraint( + lambda drink_dane, tea: + drink_dane is tea, + ['Dane', 'Tea']) + +# The green house is immediately to the left of the white house. +p.addConstraint( + lambda green_house, white_house: + # Houses 1 .. 5 -> green house is 1 lower than white house + green_house is white_house - 1, + ['Green', 'White']) + +# They drink coffee in the green house. +p.addConstraint( + lambda drink_green_house, coffee: + drink_green_house is coffee, + ['Green', 'Coffee']) + +# The man who smokes Pall Mall has a bird. +p.addConstraint( + lambda pet_of_pallmall_smoker, a_bird: + pet_of_pallmall_smoker is a_bird, + ['PallMall', 'Bird']) + +# In the yellow house they smoke Dunhill. +p.addConstraint( + lambda owner_yellow_house, dunhill_smoker: + owner_yellow_house is dunhill_smoker, + ['Yellow', 'Dunhill']) + +# In the middle house they drink milk. +p.addConstraint( + lambda house_number_milk_drinker: + house_number_milk_drinker is 3, + ['Milk']) + +# The Norwegian lives in the first house. +p.addConstraint( + lambda house_number_norwegian: + house_number_norwegian is 1, + ['Norwegian']) + +# The man who smokes Blend lives in the house next to the house with a cat. +p.addConstraint( + lambda house_number_blend_smoker, number_of_house_with_cat: + # next -> housenumber +/- 1 + house_number_blend_smoker is number_of_house_with_cat + 1 or + house_number_blend_smoker is number_of_house_with_cat - 1, + ['Blend', 'Cat']) + +# In a house next to the house where they have a horse, they smoke Dunhill. +p.addConstraint( + lambda house_number_dunhill_smoker, number_of_house_with_horse: + # next -> housenumber +/- 1 + house_number_dunhill_smoker is number_of_house_with_horse + 1 or + house_number_dunhill_smoker is number_of_house_with_horse - 1, + ['Dunhill', 'Horse']) + +# The man who smokes Blue Master drinks beer. +p.addConstraint( + lambda drink_bluemaster_smoker, beer: + drink_bluemaster_smoker is beer, + ['BlueMaster', 'Beer']) + +# The German smokes Prince. +p.addConstraint( + lambda prince_smoker, german: + prince_smoker is german, + ['Prince', 'German']) + +# The Norwegian lives next to the blue house. +p.addConstraint( + lambda house_number_norwegian, house_number_blue_house: + house_number_norwegian is house_number_blue_house + 1 or + house_number_norwegian is house_number_blue_house - 1, + ['Norwegian', 'Blue']) + +# They drink water in a house next to the house where they smoke Blend. +p.addConstraint( + lambda house_number_water_drinker, house_number_blend_smoker: + house_number_water_drinker is house_number_blend_smoker + 1 or + house_number_water_drinker is house_number_blend_smoker - 1, +['Water', 'Blend']) # get solution -sol = problem.getSolution() +sol = p.getSolution() # print the answers -nation = ["Nation" if i == 0 else "" for i in range(6)] -color = ["Color" if i == 0 else "" for i in range(6)] -smoke = ["Smoke" if i == 0 else "" for i in range(6)] -pet = ["Pet" if i == 0 else "" for i in range(6)] -drink = ["Drink" if i == 0 else "" for i in range(6)] -for n in Nation: - nation[sol[n]] = n -for n in Color: - color[sol[n]] = n -for n in Smoke: - smoke[sol[n]] = n -for n in Pet: - pet[sol[n]] = n -for n in Drink: - drink[sol[n]] = n -for d in [nation, color, smoke, pet, drink]: - print("%6s: %14s%14s%14s%14s%14s" % (d[0], d[1], d[2], d[3], d[4], d[5])) +nation = ['Nation' if i == 0 else '' for i in range(6)] +color = ['Color' if i == 0 else '' for i in range(6)] +smoke = ['Smoke' if i == 0 else '' for i in range(6)] +pet = ['Pet' if i == 0 else '' for i in range(6)] +drink = ['Drink' if i == 0 else '' for i in range(6)] + +for n in Nation: nation[sol[n]] = n +for n in Color: color[sol[n]] = n +for n in Smoke: smoke[sol[n]] = n +for n in Pet: pet[sol[n]] = n +for n in Drink: drink[sol[n]] = n + +# put the answers in the correct order of solution +print('\n\n', 'The calculated solution:', '\n') + +for r in [nation, color, smoke, pet, drink]: + print(f'{r[0]:>13s}: ', end='') + for i in range(1, 6): + print(f'{r[i]:>14s}',end='') + print() +print() diff --git a/Task/Zebra-puzzle/Wren/zebra-puzzle.wren b/Task/Zebra-puzzle/Wren/zebra-puzzle.wren index a1fe453352..d250e6e26a 100644 --- a/Task/Zebra-puzzle/Wren/zebra-puzzle.wren +++ b/Task/Zebra-puzzle/Wren/zebra-puzzle.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var colors = ["Red", "Green", "White", "Yellow", "Blue"] var nations = ["English", "Swede", "Danish", "Norwegian", "German"] diff --git a/Task/Zeckendorf-arithmetic/Dart/zeckendorf-arithmetic.dart b/Task/Zeckendorf-arithmetic/Dart/zeckendorf-arithmetic.dart new file mode 100644 index 0000000000..4bda9b2668 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Dart/zeckendorf-arithmetic.dart @@ -0,0 +1,155 @@ +class Zeckendorf { + int dVal = 0; + int dLen = 0; + + Zeckendorf(String x) { + var q = 1; + var i = x.length - 1; + dLen = i ~/ 2; + while (i >= 0) { + dVal += (x[i].codeUnitAt(0) - '0'.codeUnitAt(0)) * q; + q *= 2; + i--; + } + } + + void a(int n) { + var i = n; + while (true) { + if (dLen < i) dLen = i; + var j = (dVal >> (i * 2)) & 3; + switch (j) { + case 0: + case 1: + return; + case 2: + if (((dVal >> ((i + 1) * 2)) & 1) != 1) return; + dVal += 1 << (i * 2 + 1); + return; + case 3: + dVal &= ~(3 << (i * 2)); + b((i + 1) * 2); + break; + } + i++; + } + } + + void b(int pos) { + if (pos == 0) { + this.increment(); + return; + } + if (((dVal >> pos) & 1) == 0) { + dVal += 1 << pos; + a(pos ~/ 2); + if (pos > 1) a(pos ~/ 2 - 1); + } else { + dVal &= ~(1 << pos); + b(pos + 1); + b(pos - (pos > 1 ? 2 : 1)); + } + } + + void c(int pos) { + if (((dVal >> pos) & 1) == 1) { + dVal &= ~(1 << pos); + return; + } + c(pos + 1); + if (pos > 0) + b(pos - 1); + else + this.increment(); + } + + Zeckendorf increment() { + dVal += 1; + a(0); + return this; + } + + void operator + (Zeckendorf other) { + for (var gn = 0; gn < (other.dLen + 1) * 2; gn++) { + if (((other.dVal >> gn) & 1) == 1) b(gn); + } + } + + void operator - (Zeckendorf other) { + for (var gn = 0; gn < (other.dLen + 1) * 2; gn++) { + if (((other.dVal >> gn) & 1) == 1) c(gn); + } + while (dLen > 0 && (((dVal >> dLen * 2) & 3) == 0)) dLen--; + } + + + void operator * (Zeckendorf other) { + var na = other.copy(); + var nb = other.copy(); + Zeckendorf nt; + var nr = Zeckendorf("0"); + for (var i = 0; i <= (dLen + 1) * 2; i++) { + if (((dVal >> i) & 1) > 0) nr + nb; + nt = nb.copy(); + nb + na; + na = nt.copy(); + } + dVal = nr.dVal; + dLen = nr.dLen; + } + + int compareTo(Zeckendorf other) { + return dVal.compareTo(other.dVal); + } + + @override + String toString() { + if (dVal == 0) return "0"; + var sb = StringBuffer(dig1[(dVal >> (dLen * 2)) & 3]); + for (var i = dLen - 1; i >= 0; i--) { + sb.write(dig[(dVal >> (i * 2)) & 3]); + } + return sb.toString(); + } + + Zeckendorf copy() { + var z = Zeckendorf("0"); + z.dVal = dVal; + z.dLen = dLen; + return z; + } + + static final List dig = ["00", "01", "10"]; + static final List dig1 = ["", "1", "10"]; +} + +void main() { + print("Addition:"); + var g = Zeckendorf("10"); + g + Zeckendorf("10"); + print(g); + g + Zeckendorf("10"); + print(g); + g + Zeckendorf("1001"); + print(g); + g + Zeckendorf("1000"); + print(g); + g + Zeckendorf("10101"); + print(g); + + print("\nSubtraction:"); + g = Zeckendorf("1000"); + g - Zeckendorf("101"); + print(g); + g = Zeckendorf("10101010"); + g - Zeckendorf("1010101"); + print(g); + + print("\nMultiplication:"); + g = Zeckendorf("1001"); + g * Zeckendorf("101"); + print(g); + g = Zeckendorf("101010"); + g + Zeckendorf("101"); + print(g); +} diff --git a/Task/Zeckendorf-arithmetic/Elena/zeckendorf-arithmetic.elena b/Task/Zeckendorf-arithmetic/Elena/zeckendorf-arithmetic.elena index 9d758e4d1b..d122dab5d6 100644 --- a/Task/Zeckendorf-arithmetic/Elena/zeckendorf-arithmetic.elena +++ b/Task/Zeckendorf-arithmetic/Elena/zeckendorf-arithmetic.elena @@ -50,7 +50,7 @@ sealed struct ZeckendorfNumber 0 { ^ self } 1 { ^ self } 2 { - ifnot ((dVal $shr ((i + 1) * 2)).allMask:1) + ifnot ((dVal $shr ((i + 1) * 2)).allMask(1)) { ^ self }; @@ -81,7 +81,7 @@ sealed struct ZeckendorfNumber { if (pos == 0) { ^ self.inc() }; - ifnot((dVal $shr pos).allMask:1) + ifnot((dVal $shr pos).allMask(1)) { dVal += (1 $shl pos); self.a(pos / 2); @@ -98,7 +98,7 @@ sealed struct ZeckendorfNumber private c(int pos) { - if ((dVal $shr pos).allMask:1) + if ((dVal $shr pos).allMask(1)) { int tmp := 1 $shl pos; tmp := tmp.bxor(-1); @@ -131,9 +131,9 @@ sealed struct ZeckendorfNumber dVal := v; dLen := l; - for(int GN := 0, GN < (mLen + 1) * 2, GN += 1) + for(int GN := 0; GN < (mLen + 1) * 2; GN += 1) { - if ((mVal $shr GN).allMask:1) + if ((mVal $shr GN).allMask(1)) { self.b(GN) } @@ -151,9 +151,9 @@ sealed struct ZeckendorfNumber dVal := v; dLen := l; - for(int GN := 0, GN < (mLen + 1) * 2, GN += 1) + for(int GN := 0; GN < (mLen + 1) * 2; GN += 1) { - if ((mVal $shr GN).allMask:1) + if ((mVal $shr GN).allMask(1)) { self.c(GN) } @@ -177,7 +177,7 @@ sealed struct ZeckendorfNumber ZeckendorfNumber Nr := 0n; ZeckendorfNumber Nt := 0n; - for(int i := 0, i < (dLen + 1) * 2, i += 1) + for(int i := 0; i < (dLen + 1) * 2; i += 1) { if (((dVal $shr i) & 1) > 0) { diff --git a/Task/Zeckendorf-arithmetic/Rust/zeckendorf-arithmetic.rust b/Task/Zeckendorf-arithmetic/Rust/zeckendorf-arithmetic.rust new file mode 100644 index 0000000000..cac41937a1 --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Rust/zeckendorf-arithmetic.rust @@ -0,0 +1,182 @@ +struct Zeckendorf { + d_val: i32, + d_len: i32, +} + +impl Zeckendorf { + fn new(x: &str) -> Zeckendorf { + let mut d_val = 0; + let mut q = 1; + let mut i = x.len() as i32 - 1; + let d_len = i / 2; + while i >= 0 { + d_val += (x.chars().nth(i as usize).unwrap() as i32 - '0' as i32) * q; + q *= 2; + i -= 1; + } + + Zeckendorf { d_val, d_len } + } + + fn a(&mut self, n: i32) { + let mut i = n; + loop { + if self.d_len < i { + self.d_len = i; + } + let j = (self.d_val >> (i * 2)) & 3; + match j { + 0 | 1 => return, + 2 => { + if ((self.d_val >> ((i + 1) * 2)) & 1) != 1 { + return; + } + self.d_val += 1 << (i * 2 + 1); + return; + } + 3 => { + let temp = 3 << (i * 2); + let temp = !temp; + self.d_val &= temp; + self.b((i + 1) * 2); + } + _ => (), + } + i += 1; + } + } + + fn b(&mut self, pos: i32) { + if pos == 0 { + self.inc(); + return; + } + if ((self.d_val >> pos) & 1) == 0 { + self.d_val += 1 << pos; + self.a(pos / 2); + if pos > 1 { + self.a(pos / 2 - 1); + } + } else { + let temp = 1 << pos; + let temp = !temp; + self.d_val &= temp; + self.b(pos + 1); + self.b(pos - if pos > 1 { 2 } else { 1 }); + } + } + + fn c(&mut self, pos: i32) { + if ((self.d_val >> pos) & 1) == 1 { + let temp = 1 << pos; + let temp = !temp; + self.d_val &= temp; + return; + } + self.c(pos + 1); + if pos > 0 { + self.b(pos - 1); + } else { + self.inc(); + } + } + + fn inc(&mut self) -> &mut Self { + self.d_val += 1; + self.a(0); + self + } + + fn copy(&self) -> Zeckendorf { + Zeckendorf { + d_val: self.d_val, + d_len: self.d_len, + } + } + + fn plus_assign(&mut self, other: &Zeckendorf) { + for gn in 0..(other.d_len + 1) * 2 { + if ((other.d_val >> gn) & 1) == 1 { + self.b(gn); + } + } + } + + fn minus_assign(&mut self, other: &Zeckendorf) { + for gn in 0..(other.d_len + 1) * 2 { + if ((other.d_val >> gn) & 1) == 1 { + self.c(gn); + } + } + while (((self.d_val >> self.d_len * 2) & 3) == 0) || (self.d_len == 0) { + self.d_len -= 1; + } + } + + fn times_assign(&mut self, other: &Zeckendorf) { + let mut na = other.copy(); + let mut nb = other.copy(); + let mut nt; + let mut nr = Zeckendorf::new("0"); + for i in 0..(self.d_len + 1) * 2 { + if ((self.d_val >> i) & 1) > 0 { + nr.plus_assign(&nb); + } + nt = nb.copy(); + nb.plus_assign(&na); + na = nt.copy(); // `na` is now mutable, so this reassignment is allowed + } + self.d_val = nr.d_val; + self.d_len = nr.d_len; + } + + fn to_string(&self) -> String { + if self.d_val == 0 { + return "0".to_string(); + } + + let dig = ["00", "01", "10"]; + let dig1 = ["", "1", "10"]; + + let idx = (self.d_val >> (self.d_len * 2)) & 3; + let mut sb = String::from(dig1[idx as usize]); + for i in (0..self.d_len).rev() { + let idx = (self.d_val >> (i * 2)) & 3; + sb.push_str(dig[idx as usize]); + } + sb + } +} + +fn main() { + println!("Addition:"); + let mut g = Zeckendorf::new("10"); + g.plus_assign(&Zeckendorf::new("10")); + println!("{}", g.to_string()); + g.plus_assign(&Zeckendorf::new("10")); + println!("{}", g.to_string()); + g.plus_assign(&Zeckendorf::new("1001")); + println!("{}", g.to_string()); + g.plus_assign(&Zeckendorf::new("1000")); + println!("{}", g.to_string()); + g.plus_assign(&Zeckendorf::new("10101")); + println!("{}", g.to_string()); + println!(); + + println!("Subtraction:"); + g = Zeckendorf::new("1000"); + g.minus_assign(&Zeckendorf::new("101")); + println!("{}", g.to_string()); + g = Zeckendorf::new("10101010"); + g.minus_assign(&Zeckendorf::new("1010101")); + println!("{}", g.to_string()); + println!(); + + println!("Multiplication:"); + g = Zeckendorf::new("1001"); + g.times_assign(&Zeckendorf::new("101")); + println!("{}", g.to_string()); + g = Zeckendorf::new("101010"); + g.plus_assign(&Zeckendorf::new("101")); + println!("{}", g.to_string()); +} diff --git a/Task/Zeckendorf-arithmetic/Wren/zeckendorf-arithmetic.wren b/Task/Zeckendorf-arithmetic/Wren/zeckendorf-arithmetic.wren index 6ba9ed1451..9880138768 100644 --- a/Task/Zeckendorf-arithmetic/Wren/zeckendorf-arithmetic.wren +++ b/Task/Zeckendorf-arithmetic/Wren/zeckendorf-arithmetic.wren @@ -1,4 +1,4 @@ -import "/trait" for Comparable +import "./trait" for Comparable class Zeckendorf is Comparable { static dig { ["00", "01", "10"] } diff --git a/Task/Zeckendorf-number-representation/Dart/zeckendorf-number-representation.dart b/Task/Zeckendorf-number-representation/Dart/zeckendorf-number-representation.dart new file mode 100644 index 0000000000..8869e20a84 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Dart/zeckendorf-number-representation.dart @@ -0,0 +1,32 @@ +class Zeckendorf { + static String getZeckendorf(int n) { + if (n == 0) { + return "0"; + } + List fibNumbers = [1]; + int nextFib = 2; + while (nextFib <= n) { + fibNumbers.add(nextFib); + nextFib += fibNumbers[fibNumbers.length - 2]; + } + StringBuffer sb = StringBuffer(); + for (int i = fibNumbers.length - 1; i >= 0; i--) { + int fibNumber = fibNumbers[i]; + sb.write((fibNumber <= n) ? "1" : "0"); + if (fibNumber <= n) { + n -= fibNumber; + } + } + return sb.toString(); + } + + static void main() { + for (int i = 0; i <= 20; i++) { + print("Z($i)=${getZeckendorf(i)}"); + } + } +} + +void main() { + Zeckendorf.main(); +} diff --git a/Task/Zeckendorf-number-representation/Elena/zeckendorf-number-representation.elena b/Task/Zeckendorf-number-representation/Elena/zeckendorf-number-representation.elena index 0fe80bd20c..c23dd8574c 100644 --- a/Task/Zeckendorf-number-representation/Elena/zeckendorf-number-representation.elena +++ b/Task/Zeckendorf-number-representation/Elena/zeckendorf-number-representation.elena @@ -26,7 +26,7 @@ extension op while (currentFibonaciNum <= num) { - fibonacciNumbers.append:currentFibonaciNum; + fibonacciNumbers.append(currentFibonaciNum); fibPosition := fibPosition + 1; currentFibonaciNum := fibPosition.fibonacci() @@ -35,7 +35,7 @@ extension op auto output := new TextBuilder(); int temp := num; - fibonacciNumbers.sequenceReverse().forEach:(item) + fibonacciNumbers.sequenceReverse().forEach::(item) { if (item <= temp) { @@ -54,7 +54,7 @@ extension op public program() { - for(int i := 1, i <= 20, i += 1) + for(int i := 1; i <= 20; i += 1) { console.printFormatted("{0} : {1}",i,i.zeckendorf()).writeLine() }; diff --git a/Task/Zeckendorf-number-representation/Erlang/zeckendorf-number-representation.erl b/Task/Zeckendorf-number-representation/Erlang/zeckendorf-number-representation.erl new file mode 100644 index 0000000000..92b07fc2c9 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Erlang/zeckendorf-number-representation.erl @@ -0,0 +1,33 @@ +% Function to generate a list of the first N Zeckendorf numbers +number(N) -> + number_helper(N, 0, 0, []). + +number_helper(0, _, _, Acc) -> + lists:reverse(Acc); +number_helper(N, Curr, Index, Acc) -> + case zn_loop(Curr) of + {Bin, Next} -> + number_helper(N - 1, Next, Index + 1, [{Bin, Index} | Acc]) + end. + +% Helper function to find the next Zeckendorf number +zn_loop(N) -> + Bin = my_integer_to_binary(N), + case re:run(Bin, "11", [{capture, none}]) of + match -> + zn_loop(N + 1); + nomatch -> + {Bin, N + 1} + end. + +% Convert an integer to its binary representation as a string +my_integer_to_binary(N) -> + lists:flatten(io_lib:format("~.2B", [N])). + +% Test function to output the first 21 Zeckendorf numbers +main([]) -> + ZnNumbers = number(21), + lists:foreach( + fun({Zn, I}) -> + io:format("~p: ~s~n", [I, Zn]) + end, ZnNumbers). diff --git a/Task/Zeckendorf-number-representation/MATLAB/zeckendorf-number-representation.m b/Task/Zeckendorf-number-representation/MATLAB/zeckendorf-number-representation.m new file mode 100644 index 0000000000..59f573d8da --- /dev/null +++ b/Task/Zeckendorf-number-representation/MATLAB/zeckendorf-number-representation.m @@ -0,0 +1,35 @@ +clear all; close all; clc; + +% Print the sequence for numbers from 0 to 20 +for x = 0:20 + zeckString = arrayfun(@num2str, zeck(x), 'UniformOutput', false); + zeckString = strjoin(zeckString, ''); + fprintf("%d : %s\n", x, zeckString); +end + +function dig = zeck(n) + if n <= 0 + dig = 0; + return; + end + + fib = [1, 2]; + while fib(end) < n + fib(end + 1) = sum(fib(end-1:end)); + end + fib = fliplr(fib); % Reverse the order of Fibonacci numbers + + dig = []; + for i = 1:length(fib) + if fib(i) <= n + dig(end + 1) = 1; + n = n - fib(i); + else + dig(end + 1) = 0; + end + end + + if dig(1) == 0 + dig = dig(2:end); + end +end diff --git a/Task/Zeckendorf-number-representation/Rust/zeckendorf-number-representation.rust b/Task/Zeckendorf-number-representation/Rust/zeckendorf-number-representation.rust new file mode 100644 index 0000000000..cfaf2d3399 --- /dev/null +++ b/Task/Zeckendorf-number-representation/Rust/zeckendorf-number-representation.rust @@ -0,0 +1,42 @@ +use std::collections::VecDeque; + +fn fibonacci(n: u32) -> u32 { + match n { + 0 => 0, + 1 => 1, + _ => fibonacci(n - 1) + fibonacci(n - 2), + } +} + +fn zeckendorf(num: u32) -> String { + let mut fibonacci_numbers = VecDeque::new(); + let mut fib_position = 2; + let mut current_fibonacci_num = fibonacci(fib_position); + + while current_fibonacci_num <= num { + fibonacci_numbers.push_front(current_fibonacci_num); + fib_position += 1; + current_fibonacci_num = fibonacci(fib_position); + } + + let mut temp = num; + let mut output = String::new(); + + for item in fibonacci_numbers { + if item <= temp { + output.push('1'); + temp -= item; + } else { + output.push('0'); + } + } + + output +} + +fn main() { + for i in 1..=20 { + let zeckendorf_representation = zeckendorf(i); + println!("{} : {}", i, zeckendorf_representation); + } +} diff --git a/Task/Zeckendorf-number-representation/Wren/zeckendorf-number-representation.wren b/Task/Zeckendorf-number-representation/Wren/zeckendorf-number-representation.wren index 17fa430644..48e433bb6c 100644 --- a/Task/Zeckendorf-number-representation/Wren/zeckendorf-number-representation.wren +++ b/Task/Zeckendorf-number-representation/Wren/zeckendorf-number-representation.wren @@ -1,4 +1,4 @@ -import "/fmt" for Fmt +import "./fmt" for Fmt var LIMIT = 46 // to stay within range of signed 32 bit integer diff --git a/Task/Zero-to-the-zero-power/Elena/zero-to-the-zero-power.elena b/Task/Zero-to-the-zero-power/Elena/zero-to-the-zero-power.elena index f25f4e82d3..cc2b4cc240 100644 --- a/Task/Zero-to-the-zero-power/Elena/zero-to-the-zero-power.elena +++ b/Task/Zero-to-the-zero-power/Elena/zero-to-the-zero-power.elena @@ -2,5 +2,5 @@ import extensions; public program() { - console.printLine("0^0 is ",0.power:0) + console.printLine("0^0 is ",0.power(0)) } diff --git a/Task/Zero-to-the-zero-power/ZX-Spectrum-Basic/zero-to-the-zero-power.basic b/Task/Zero-to-the-zero-power/ZX-Spectrum-Basic/zero-to-the-zero-power.basic new file mode 100644 index 0000000000..1d1d9027c1 --- /dev/null +++ b/Task/Zero-to-the-zero-power/ZX-Spectrum-Basic/zero-to-the-zero-power.basic @@ -0,0 +1 @@ +PRINT 0↑0 diff --git a/Task/Zhang-Suen-thinning-algorithm/Elena/zhang-suen-thinning-algorithm.elena b/Task/Zhang-Suen-thinning-algorithm/Elena/zhang-suen-thinning-algorithm.elena index 909e4f4c4d..e7466f425b 100644 --- a/Task/Zhang-Suen-thinning-algorithm/Elena/zhang-suen-thinning-algorithm.elena +++ b/Task/Zhang-Suen-thinning-algorithm/Elena/zhang-suen-thinning-algorithm.elena @@ -62,7 +62,7 @@ extension zhangsuenOp : Matrix { int count := 0; - for (int i := 0, i < nbrs.Length - 1, i += 1) + for (int i := 0; i < nbrs.Length - 1; i += 1) { if (self[r + nbrs[i][1]][c + nbrs[i + 1][0]] == $35) { count += 1 } @@ -75,7 +75,7 @@ extension zhangsuenOp : Matrix { int count := 0; - for (int i := 0, i < nbrs.Length - 1, i += 1) + for (int i := 0; i < nbrs.Length - 1; i += 1) { if (self[r + nbrs[i][1]][c + nbrs[i][0]] == $32) { @@ -93,9 +93,9 @@ extension zhangsuenOp : Matrix { int count := 0; var group := nbrGroups[step]; - for(int i := 0, i < 2, i += 1) + for(int i := 0; i < 2; i += 1) { - for(int j := 0, j < group[i].Length, j += 1) + for(int j := 0; j < group[i].Length; j += 1) { var nbr := nbrs[group[i][j]]; @@ -118,16 +118,16 @@ extension zhangsuenOp : Matrix hasChanged := false; firstStep := firstStep.Inverted; - for(int r := 1, r < self.Rows - 1, r += 1) + for(int r := 1; r < self.Rows - 1; r += 1) { - for(int c := 1, c < self.Columns - 1, c += 1) + for(int c := 1; c < self.Columns - 1; c += 1) { if(self.proceed(r,c,toWhite,firstStep)) { hasChanged := true } } }; - toWhite.forEach:(p){ self[p.y][p.x] := $32 }; + toWhite.forEach::(p){ self[p.y][p.x] := $32 }; toWhite.clear() } } @@ -136,12 +136,12 @@ extension zhangsuenOp : Matrix { var it := self.enumerator(); - it.forEach:(ch){ console.print(ch," ") }; + it.forEach::(ch){ console.print(ch," ") }; while (it.next()) { console.writeLine(); - it.forEach:(ch){ console.print(ch," ") } + it.forEach::(ch){ console.print(ch," ") } } } } diff --git a/Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg b/Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg index 96c4e91353..7dfe088913 100644 --- a/Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg +++ b/Task/Zig-zag-matrix/ALGOL-68/zig-zag-matrix.alg @@ -32,6 +32,10 @@ INT dim = 5; ELSE# [,]INT result = zig zag(dim); FOR i TO dim DO - print((result[i,], new line)) + print((IF i = 1 THEN "((" ELSE " (" FI)); + FOR j TO dim DO + print(( whole( result[i,j], -3 ), IF j /= dim THEN "," ELSE "" FI )) + OD; + print((IF i = dim THEN "))" ELSE ")," FI, new line)) OD #FI# diff --git a/Task/Zig-zag-matrix/Wren/zig-zag-matrix.wren b/Task/Zig-zag-matrix/Wren/zig-zag-matrix.wren index f3860035f5..92db15bcab 100644 --- a/Task/Zig-zag-matrix/Wren/zig-zag-matrix.wren +++ b/Task/Zig-zag-matrix/Wren/zig-zag-matrix.wren @@ -1,4 +1,4 @@ -import "/fmt" for Conv, Fmt +import "./fmt" for Conv, Fmt var zigzag = Fn.new { |n| var r = List.filled(n*n, 0) diff --git a/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy b/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy new file mode 100644 index 0000000000..4123cf2bd5 --- /dev/null +++ b/Task/Zumkeller-numbers/EasyLang/zumkeller-numbers.easy @@ -0,0 +1,65 @@ +proc divisors n . divs[] . + divs[] = [ 1 n ] + for i = 2 to sqrt n + if n mod i = 0 + j = n / i + divs[] &= i + if i <> j + divs[] &= j + . + . + . +. +func ispartsum divs[] sum . + if sum = 0 + return 1 + . + if len divs[] = 0 + return 0 + . + last = divs[-1] + len divs[] -1 + if last > sum + return ispartsum divs[] sum + . + if ispartsum divs[] sum = 1 + return 1 + . + return ispartsum divs[] (sum - last) +. +func iszumkeller n . + divisors n divs[] + for v in divs[] + sum += v + . + if sum mod 2 = 1 + return 0 + . + if n mod 2 = 1 + abund = sum - 2 * n + return if abund > 0 and abund mod 2 = 0 + . + return ispartsum divs[] (sum / 2) +. +# +print "The first 220 Zumkeller numbers are:" +i = 2 +repeat + if iszumkeller i = 1 + write i & " " + count += 1 + . + until count = 220 + i += 1 +. +print "\n\nThe first 40 odd Zumkeller numbers are:" +count = 0 +i = 3 +repeat + if iszumkeller i = 1 + write i & " " + count += 1 + . + until count = 40 + i += 2 +. diff --git a/Task/Zumkeller-numbers/PARI-GP/zumkeller-numbers.parigp b/Task/Zumkeller-numbers/PARI-GP/zumkeller-numbers.parigp new file mode 100644 index 0000000000..d652c285ad --- /dev/null +++ b/Task/Zumkeller-numbers/PARI-GP/zumkeller-numbers.parigp @@ -0,0 +1,38 @@ +\\ Define a function to check if a number is Zumkeller +isZumkeller(n) = { + my(d = divisors(n)); + my(ds = sum(i=1, #d, d[i])); \\ Total of divisors + if (ds % 2, return(0)); \\ If sum of divisors is odd, return false + my(coeffs = vector(ds+1, i, 0)); \\ Create a vector to store coefficients + coeffs[1] = 1; + for(i=1, #d, coeffs = Pol(coeffs) * (1 + x^d[i]); coeffs = Vecrev(coeffs); if(#coeffs > ds + 1, coeffs = coeffs[^1])); \\ Generate coefficients + coeffs[ds \ 2 + 1] > 0; \\ Check if the middle coefficient is positive +} + +\\ Generate a list of Zumkeller numbers +ZumkellerList(limit) = { + my(res = List(), i = 1); + while(#res < limit, + if(isZumkeller(i), listput(res, i)); + i++; + ); + Vec(res); \\ Convert list to vector +} + +\\ Generate a list of odd Zumkeller numbers +OddZumkellerList(limit) = { + my(res = List(), i = 1); + while(#res < limit, + if(isZumkeller(i), listput(res, i)); + i += 2; \\ Only check odd numbers + ); + Vec(res); \\ Convert list to vector +} + +\\ Call the functions to get the lists +zumkeller220 = ZumkellerList(220); +oddZumkeller40 = OddZumkellerList(40); + +\\ Print the results +print(zumkeller220); +print(oddZumkeller40); diff --git a/Task/Zumkeller-numbers/Phix/zumkeller-numbers.phix b/Task/Zumkeller-numbers/Phix/zumkeller-numbers.phix index 71a5d6e9a7..37cbff0186 100644 --- a/Task/Zumkeller-numbers/Phix/zumkeller-numbers.phix +++ b/Task/Zumkeller-numbers/Phix/zumkeller-numbers.phix @@ -1,45 +1,43 @@ -(phixonline)--"> - function isPartSum(sequence f, integer l, t) - if t=0 then return true end if - if l=0 then return false end if - integer last = f[l] - return (t>=last and isPartSum(f, l-1, t-last)) - or isPartSum(f, l-1, t) - end function +with javascript_semantics +function isPartSum(sequence f, integer l, t) + if t=0 then return true end if + if l=0 then return false end if + integer last = f[l] + return (t>=last and isPartSum(f, l-1, t-last)) + or isPartSum(f, l-1, t) +end function - function isZumkeller(integer n) - sequence f = factors(n,1) - integer t = sum(f) - -- an odd sum cannot be split into two equal sums - if remainder(t,2)=1 then return false end if - -- if n is odd use 'abundant odd number' optimization - if remainder(n,2)=1 then - integer abundance := t - 2*n - return abundance>0 and remainder(abundance,2)=0 - end if - -- if n and t both even check for any partition of t/2 - return isPartSum(f, length(f), t/2) - end function +function isZumkeller(integer n) + sequence f = factors(n,1) + integer t = sum(f) + -- an odd sum cannot be split into two equal sums + if odd(t) then return false end if + -- if n is odd use 'abundant odd number' optimization + if odd(n) then + integer abundance := t - 2*n + return abundance>0 and even(abundance) + end if + -- if n and t both even check for any partition of t/2 + return isPartSum(f, length(f), t/2) +end function - sequence tests = {{220,1,0,20,"%3d "}, - {40,2,0,10,"%5d "}, - {40,2,5,8,"%7d "}} - integer lim, step, rem, cr; string fmt - for t=1 to length(tests) do - {lim, step, rem, cr, fmt} = tests[t] - string odd = iff(step=1?"":"odd "), - wch = iff(rem=0?"":"which don't end in 5 ") - printf(1,"The first %d %sZumkeller numbers %sare:\n",{lim,odd,wch}) - integer i = step+1, count = 0 - while count<lim do - if (rem=0 or remainder(i,10)!=rem) - and isZumkeller(i) then - printf(1,fmt,i) - count += 1 - if remainder(count,cr)=0 then puts(1,"\n") end if - end if - i += step - end while - printf(1,"\n") - end for -